agent-office: a Settings switch for agents from other computers and gateway keys (#741)

agent-office: a Settings switch, "Include agents from other computers
and gateway keys", sets options.remote, so the gateway hook keeps
requests that are not local. It is off by default (package default
remote:false, the page reads opts.remote === true, the hook
opts?.remote === true). While it is off the hook counts the non-local
requests it drops (capped at 9999) into the snapshot, and an empty
office says they were ignored and where the switch is, in all nine
languages. Adapted by frederick-wang from QingJ01/magpie-agent-office#5.
Merged onto #740 with the page stamps taken again (a7a5bce6).

Run at the reviewed head a7a5bce6, on mote:
- HOME=<scratch> bun test packages/agent-office: 183 pass, 0 fail,
  34 more times (20 of them four at a time, load ~30). The first run
  of this head had 2 fails whose names were lost to tail; not seen
  again in the 34.
- stamp-page.mjs --check: 0 (every ?v= checked against sha256);
  bun scripts/check.mjs agent-office: 0.
- Broken by hand: dropping the dropped++ turns 2 tests red. Turning
  remote on by default in the hook's track() turned nothing red; a
  guard test follows in the version bump.
- Playwright 1.62.0, Chromium and WebKit, light and dark, stub bridge,
  live.js with dropped:2 and no sessions: the empty state gives the
  hint; ticking the switch hides it, options.set receives remote:true
  after the 2.5s save, and a reload with those options shows the box
  ticked and no hint.

Not tried: a real remote agent or gateway key through a real magpie.
This commit is contained in:
Zhaoji Wang
2026-11-05 09:42:49 +08:00
committed by GitHub
parent 845fcfea4e
commit 5150142eb2
8 changed files with 71 additions and 23 deletions
+1 -1
View File
@@ -136,7 +136,7 @@ bun bin/agent-office.mjs --json # 一次性快照,适合让 Agent 在聊天
| `side` | 显示分组侧栏 |
| `lang` | `auto` 或九种语言代码 |
| `cleared` | { 会话 key: 时间 }:被「清除」的会话,文件再动就回来 |
| `remote` | 网关部分也记录其他电脑的请求 |
| `remote` | 网关部分也记录其他电脑和网关密钥的请求(也可在页面右上角 **设置** 里直接勾选) |
| `approvalAfterSec` | 只有网关记录时,工具运行多久算等你批准(90) |
## 独立 CLI
@@ -331,6 +331,33 @@ test("the gateway part still reads replies in each API", () => {
expect(outcomeOf(replyOf({ output: [{ type: "function_call", name: "shell", arguments: "{}" }] }, "responses"))).toBe("tools")
const t = createTracker()
expect(t.request({ model: "m", tools: [1], messages: [{ role: "user", content: "x" }] }, { origin: "remote", agent: "a", session: "s" }, 1)).toBeNull()
expect(t.snapshot(1).dropped).toBe(1)
const remoteOn = createTracker({ remote: true })
expect(remoteOn.request({ model: "m", tools: [1], messages: [{ role: "user", content: "x" }] }, { origin: "gateway-key", agent: "a", session: "s" }, 1)).toBe("a|s")
expect(remoteOn.snapshot(1).dropped).toBe(0)
})
test("a gateway install counts dropped non-local requests until remote is enabled", async () => {
const out = tmp()
process.env.MAGPIE_AGENT_OFFICE_PAGE = out
const hook = await import("./office.hooks.mjs")
const body = { model: "m", tools: [{ name: "x" }], messages: [{ role: "user", content: "hi" }] }
await hook.onRequest(body, { origin: "gateway-key", protocol: "anthropic", agent: "cursor", session: "r1", cwd: "/srv", model: "m", query: "hi", options: { remote: false, text: true }, state: {}, report() {} })
expect(hook.snapshot().dropped).toBeGreaterThanOrEqual(1)
// toggling text while remote stays false preserves the dropped count
await hook.onRequest(body, { origin: "local", protocol: "anthropic", agent: "cursor", session: "l1", cwd: "/srv", model: "m", query: "hi", options: { remote: false, text: false }, state: {}, report() {} })
expect(hook.snapshot().dropped).toBeGreaterThanOrEqual(1)
// enabling remote resets dropped to 0 and records the remote agent
await hook.onRequest(body, { origin: "gateway-key", protocol: "anthropic", agent: "cursor", session: "r1", cwd: "/srv", model: "m", query: "hi", options: { remote: true, text: true }, state: {}, report() {} })
expect(hook.snapshot().dropped).toBe(0)
expect(hook.snapshot().sessions.some((s) => s.session === "r1")).toBe(true)
expect(read("index.html")).toContain('id="optRemote"')
expect(read("app.js")).toContain("remote: view.remote")
expect(read("app.js")).toContain("state.snap.dropped > 0")
for (const lang of M.LANGS) {
expect(M.TEXT[lang].remote).toBeTruthy()
expect(M.TEXT[lang].emptyRemote).toBeTruthy()
}
})
test("live.js is no file of the package's", () => {
+1 -1
View File
@@ -185,7 +185,7 @@ test("conversations are redacted with the rest of the text", () => {
test("the page carries the workbench hooks and still reaches no network", () => {
const html = read("index.html")
const app = read("app.js")
for (const id of ["toasts", "rail", "railGroups", "todayMenu", "todayTokens", "todayBtn", "sideBtn", "optAgents", "optLang", "optSub", "optIdle"]) {
for (const id of ["toasts", "rail", "railGroups", "todayMenu", "todayTokens", "todayBtn", "sideBtn", "optAgents", "optLang", "optRemote", "optSub", "optIdle"]) {
expect(html).toContain(`id="${id}"`)
}
for (const token of ["M.groups", "M.today", "M.detectLang", "M.redact", "showToast", "document.title"]) expect(app).toContain(token)
+6 -2
View File
@@ -143,6 +143,7 @@ export function keyOf(ctx) {
export function createTracker(opts = {}) {
const o = { text: true, remote: false, ...opts }
const sessions = new Map()
let dropped = o.remote ? 0 : Math.min(9999, Math.max(0, Math.trunc(Number(opts.dropped) || 0)))
function wanted(ctx) {
if (!ctx) return false
@@ -165,7 +166,10 @@ export function createTracker(opts = {}) {
// a request on its way: the session is at work
function request(body, ctx, now) {
if (!wanted(ctx)) return null
if (!wanted(ctx)) {
if (ctx && !o.remote) dropped = Math.min(9999, dropped + 1)
return null
}
const key = keyOf(ctx)
let s = sessions.get(key)
const tools = hasTools(body)
@@ -225,7 +229,7 @@ export function createTracker(opts = {}) {
function snapshot(now) {
prune(now)
return { v: 1, written: now, text: o.text, sessions: [...sessions.values()].sort((a, b) => a.started - b.started) }
return { v: 1, written: now, text: o.text, dropped, sessions: [...sessions.values()].sort((a, b) => a.started - b.started) }
}
// after a restart of the host: what was written last, nothing in flight
+9 -6
View File
@@ -58,7 +58,7 @@ function track(opts) {
const o = { text: opts?.text !== false, remote: opts?.remote === true }
if (tracker && tracker.options.text === o.text && tracker.options.remote === o.remote) return tracker
const was = tracker
tracker = createTracker(o)
tracker = createTracker({ text: o.text, remote: o.remote, dropped: !o.remote && was ? was.snapshot(0).dropped : 0 })
if (was) for (const [k, s] of was.sessions) tracker.sessions.set(k, s)
return tracker
}
@@ -99,14 +99,15 @@ export function snapshot(now = Date.now()) {
}
if (jumper) jumper.decorate(sessions, now, options.preferredJumpHost || "herdr-app")
// what only the gateway saw: an agent whose files aren't read here
if (tracker) {
for (const g of tracker.snapshot(now).sessions) {
const tracked = tracker ? track(options).snapshot(now) : null
if (tracked) {
for (const g of tracked.sessions) {
if (seen.has(g.key) || fileAgents.has(g.agent)) continue
seen.add(g.key)
sessions.push({ ...g, source: "gateway" })
}
}
return { v: 2, written: now, text, sessions }
return { v: 2, written: now, text, dropped: tracked ? tracked.dropped : 0, sessions }
}
export function write(now = Date.now()) {
@@ -166,9 +167,11 @@ export async function onRequest(body, ctx) {
// not turn back into text:true because a field was missing
options = { ...options, ...(ctx.options || {}) }
start()
const key = track(options).request(body, ctx, Date.now())
const t = track(options)
const dropped = t.snapshot(0).dropped
const key = t.request(body, ctx, Date.now())
ctx.state.office = key
if (key) soon()
if (key || t.snapshot(0).dropped !== dropped) soon()
ctx.report?.("skipped")
return undefined
}
+6 -2
View File
@@ -33,6 +33,7 @@
quality: ["low", "medium", "high"].includes(opts.quality) ? opts.quality : "medium",
demo: opts.demo === true,
showDone: opts.showDone !== false,
remote: opts.remote === true,
hideAfter: M.HIDE[opts.hideAfter] !== undefined ? opts.hideAfter : M.DEFAULTS.hideAfter,
text: opts.text !== false,
approvalAfterSec: Number(opts.approvalAfterSec) > 0 ? Number(opts.approvalAfterSec) : M.DEFAULTS.approvalAfterSec,
@@ -628,7 +629,8 @@
}
function emptyText() {
return state.loaded && state.snap ? t().empty : t().noFile
if (!state.loaded || !state.snap) return t().noFile
return !view.remote && state.snap.dropped > 0 ? t().empty + " " + t().emptyRemote : t().empty
}
// ---- the side rail ----------------------------------------------------
@@ -886,7 +888,7 @@
const base = { ...opts }
delete base.jumpRequest
return {
...base, mode: view.mode, dim: view.dim, demo: view.demo, showDone: view.showDone, hideAfter: view.hideAfter,
...base, mode: view.mode, dim: view.dim, demo: view.demo, showDone: view.showDone, remote: view.remote, hideAfter: view.hideAfter,
text: textOn(), agents: view.agents.slice(), showSub: view.showSub, showIdle: view.showIdle,
side: view.side, sideV: 2, lang: manualLang, scene: view.scene, quality: view.quality,
cleared: { ...view.cleared }, preferredJumpHost: view.preferredJumpHost || "",
@@ -970,12 +972,14 @@
})
$("optDemo").checked = view.demo
$("optDone").checked = view.showDone
$("optRemote").checked = view.remote
$("optText").checked = opts.text !== false
$("optSub").checked = view.showSub
$("optIdle").checked = view.showIdle
select("optHide", "hide", view.hideAfter)
$("optDemo").addEventListener("change", (e) => { view.demo = e.target.checked; state.demoSnap = null; refresh(); save() })
$("optDone").addEventListener("change", (e) => { view.showDone = e.target.checked; refresh(); save() })
$("optRemote").addEventListener("change", (e) => { view.remote = e.target.checked; refresh(); save() })
$("optText").addEventListener("change", (e) => { view.text = e.target.checked; refresh(); save() })
$("optSub").addEventListener("change", (e) => { view.showSub = e.target.checked; agentFilterSig = ""; refresh(); save() })
$("optIdle").addEventListener("change", (e) => { view.showIdle = e.target.checked; agentFilterSig = ""; refresh(); save() })
+3 -2
View File
@@ -7,12 +7,12 @@
<link rel="stylesheet" href="style.css?v=f600355d91db">
<script src="_magpie/bridge.js"></script>
<script src="agents.js?v=d958111cd669"></script>
<script src="model.js?v=ba46364dfbb1"></script>
<script src="model.js?v=b04e2020da2a"></script>
<script src="icons.js?v=e918b44d46c2"></script>
<script src="scene.js?v=097cc0a3eec6"></script>
<script src="three.min.js?v=5b5a0ae404b6"></script>
<script src="scene3d.js?v=b666062a087d"></script>
<script src="app.js?v=b681f2393c97" defer></script>
<script src="app.js?v=54035e24dbb8" defer></script>
</head>
<body>
<main class="card" id="card">
@@ -48,6 +48,7 @@
<div class="menu wide" id="settings" hidden>
<label class="row"><input type="checkbox" id="optDemo"> <span data-t="demo">Sample agents</span></label>
<label class="row"><input type="checkbox" id="optDone"> <span data-t="showDone">Show finished agents</span></label>
<label class="row"><input type="checkbox" id="optRemote"> <span data-t="remote">Include agents from other computers and gateway keys</span></label>
<label class="row"><input type="checkbox" id="optText"> <span data-t="showText">Show prompts and replies</span></label>
<label class="row"><input type="checkbox" id="optSub"> <span data-t="showSub">Show subagents</span></label>
<label class="row"><input type="checkbox" id="optIdle"> <span data-t="showIdle">Show idle agents</span></label>
+18 -9
View File
@@ -22,8 +22,9 @@
copyResume: "Copy resume command", copySession: "Copy session id", copied: "Copied",
justNow: "just now", sAgo: "{n}s ago", mAgo: "{n} min ago", hAgo: "{n} h ago", dAgo: "{n} d ago",
empty: "No agent has been at work in the last two days. Start Claude Code, Codex, DeepSeek Harness, Gemini CLI… and it walks in here.",
emptyRemote: "Requests through this gateway from other computers or gateway keys were ignored because that switch is off in Settings.",
noFile: "Starting… the plugin reads your agents' sessions in magpie's plugin host.",
demo: "Sample agents", showDone: "Show finished agents", showText: "Show prompts and replies",
demo: "Sample agents", showDone: "Show finished agents", remote: "Include agents from other computers and gateway keys", showText: "Show prompts and replies",
showSub: "Show subagents", showIdle: "Show idle agents", agents: "Agents", allAgents: "All agents",
language: "Language", auto: "Auto", scene: "Scene", quality: "Quality",
hideAfter: "Leave the office after", h1: "1 hour", h6: "6 hours", h24: "24 hours", never: "Never",
@@ -51,8 +52,9 @@
copyResume: "复制续接命令", copySession: "复制会话 ID", copied: "已复制",
justNow: "刚刚", sAgo: "{n}秒前", mAgo: "{n}分钟前", hAgo: "{n}小时前", dAgo: "{n}天前",
empty: "最近两天没有 Agent 在干活。打开 Claude Code、Codex、DeepSeek Harness、Gemini CLI……它就会走进这间办公室。",
emptyRemote: "已有经此网关发来的其他电脑或网关密钥请求,因右上角「设置」中未勾选该项而未显示。",
noFile: "正在启动……插件在 magpie 的插件宿主里读取各个 Agent 的会话。",
demo: "示例 Agent", showDone: "显示已完成的 Agent", showText: "显示提问和回复",
demo: "示例 Agent", showDone: "显示已完成的 Agent", remote: "包含其他电脑和网关密钥的 Agent", showText: "显示提问和回复",
showSub: "显示子 Agent", showIdle: "显示摸鱼 Agent", agents: "Agent", allAgents: "全部 Agent",
language: "语言", auto: "自动", scene: "场景", quality: "画质",
hideAfter: "多久后离开办公室", h1: "1 小时", h6: "6 小时", h24: "24 小时", never: "从不",
@@ -80,8 +82,9 @@
copyResume: "複製續接指令", copySession: "複製工作階段 ID", copied: "已複製",
justNow: "剛剛", sAgo: "{n}秒前", mAgo: "{n}分鐘前", hAgo: "{n}小時前", dAgo: "{n}天前",
empty: "最近兩天沒有 Agent 在幹活。打開 Claude Code、Codex、DeepSeek Harness、Gemini CLI……它就會走進這間辦公室。",
emptyRemote: "已有經此閘道發來的其他電腦或閘道金鑰請求,因右上角「設定」中未勾選該項而未顯示。",
noFile: "正在啟動……外掛在 magpie 的外掛宿主裡讀取各個 Agent 的工作階段。",
demo: "範例 Agent", showDone: "顯示已完成的 Agent", showText: "顯示提問和回覆",
demo: "範例 Agent", showDone: "顯示已完成的 Agent", remote: "包含其他電腦和閘道金鑰的 Agent", showText: "顯示提問和回覆",
showSub: "顯示子 Agent", showIdle: "顯示摸魚 Agent", agents: "Agent", allAgents: "全部 Agent",
language: "語言", auto: "自動", scene: "場景", quality: "畫質",
hideAfter: "多久後離開辦公室", h1: "1 小時", h6: "6 小時", h24: "24 小時", never: "從不",
@@ -109,8 +112,9 @@
copyResume: "再開コマンドをコピー", copySession: "セッション ID をコピー", copied: "コピーしました",
justNow: "たった今", sAgo: "{n}秒前", mAgo: "{n}分前", hAgo: "{n}時間前", dAgo: "{n}日前",
empty: "この2日間、エージェントは動いていません。Claude Code、Codex、DeepSeek Harness、Gemini CLI… を起動すると、ここに現れます。",
emptyRemote: "他のコンピュータやゲートウェイキーからのリクエストは、「設定」でこのスイッチがオフのため表示されていません。",
noFile: "起動中… プラグインが magpie のプラグインホストで各エージェントのセッションを読んでいます。",
demo: "サンプルエージェント", showDone: "終了したエージェントを表示", showText: "プロンプトと返信を表示",
demo: "サンプルエージェント", showDone: "終了したエージェントを表示", remote: "他のコンピュータやゲートウェイキーのエージェントを含める", showText: "プロンプトと返信を表示",
showSub: "サブエージェントを表示", showIdle: "待機中のエージェントを表示", agents: "エージェント", allAgents: "すべてのエージェント",
language: "言語", auto: "自動", scene: "シーン", quality: "画質",
hideAfter: "オフィスを離れるまで", h1: "1 時間", h6: "6 時間", h24: "24 時間", never: "なし",
@@ -138,8 +142,9 @@
copyResume: "이어하기 명령 복사", copySession: "세션 ID 복사", copied: "복사됨",
justNow: "방금", sAgo: "{n}초 전", mAgo: "{n}분 전", hAgo: "{n}시간 전", dAgo: "{n}일 전",
empty: "지난 이틀 동안 에이전트가 작업하지 않았습니다. Claude Code, Codex, DeepSeek Harness, Gemini CLI…를 실행하면 여기로 들어옵니다.",
emptyRemote: "다른 컴퓨터나 게이트웨이 키에서 보낸 요청은 '설정'에서 이 스위치가 꺼져 있어 표시되지 않았습니다.",
noFile: "시작 중… 플러그인이 magpie의 플러그인 호스트에서 에이전트 세션을 읽고 있습니다.",
demo: "샘플 에이전트", showDone: "완료된 에이전트 표시", showText: "프롬프트와 답변 표시",
demo: "샘플 에이전트", showDone: "완료된 에이전트 표시", remote: "다른 컴퓨터 및 게이트웨이 키의 에이전트 포함", showText: "프롬프트와 답변 표시",
showSub: "하위 에이전트 표시", showIdle: "대기 중인 에이전트 표시", agents: "에이전트", allAgents: "모든 에이전트",
language: "언어", auto: "자동", scene: "장면", quality: "품질",
hideAfter: "사무실을 떠나기까지", h1: "1시간", h6: "6시간", h24: "24시간", never: "안 함",
@@ -167,8 +172,9 @@
copyResume: "Copiar comando de reanudación", copySession: "Copiar id de sesión", copied: "Copiado",
justNow: "ahora mismo", sAgo: "hace {n} s", mAgo: "hace {n} min", hAgo: "hace {n} h", dAgo: "hace {n} d",
empty: "Ningún agente ha trabajado en los últimos dos días. Abre Claude Code, Codex, DeepSeek Harness, Gemini CLI… y entrará aquí.",
emptyRemote: "Las solicitudes de otros equipos o claves de pasarela se ignoraron porque esa opción está desactivada en Ajustes.",
noFile: "Iniciando… el plugin lee las sesiones de tus agentes en el host de plugins de magpie.",
demo: "Agentes de ejemplo", showDone: "Mostrar agentes terminados", showText: "Mostrar preguntas y respuestas",
demo: "Agentes de ejemplo", showDone: "Mostrar agentes terminados", remote: "Incluir agentes de otros equipos y claves de pasarela", showText: "Mostrar preguntas y respuestas",
showSub: "Mostrar subagentes", showIdle: "Mostrar agentes inactivos", agents: "Agentes", allAgents: "Todos los agentes",
language: "Idioma", auto: "Auto", scene: "Escena", quality: "Calidad",
hideAfter: "Salir de la oficina tras", h1: "1 hora", h6: "6 horas", h24: "24 horas", never: "Nunca",
@@ -196,8 +202,9 @@
copyResume: "Copier la commande de reprise", copySession: "Copier l'id de session", copied: "Copié",
justNow: "à l'instant", sAgo: "il y a {n} s", mAgo: "il y a {n} min", hAgo: "il y a {n} h", dAgo: "il y a {n} j",
empty: "Aucun agent n'a travaillé ces deux derniers jours. Lancez Claude Code, Codex, DeepSeek Harness, Gemini CLI… et il entrera ici.",
emptyRemote: "Les requêtes d'autres ordinateurs ou clés de passerelle ont été ignorées car cette option est désactivée dans les Réglages.",
noFile: "Démarrage… le plugin lit les sessions de vos agents dans l'hôte de plugins de magpie.",
demo: "Agents d'exemple", showDone: "Afficher les agents terminés", showText: "Afficher les questions et réponses",
demo: "Agents d'exemple", showDone: "Afficher les agents terminés", remote: "Inclure les agents d'autres ordinateurs et clés de passerelle", showText: "Afficher les questions et réponses",
showSub: "Afficher les sous-agents", showIdle: "Afficher les agents inactifs", agents: "Agents", allAgents: "Tous les agents",
language: "Langue", auto: "Auto", scene: "Scène", quality: "Qualité",
hideAfter: "Quitter le bureau après", h1: "1 heure", h6: "6 heures", h24: "24 heures", never: "Jamais",
@@ -225,8 +232,9 @@
copyResume: "Fortsetzen-Befehl kopieren", copySession: "Sitzungs-ID kopieren", copied: "Kopiert",
justNow: "gerade eben", sAgo: "vor {n} s", mAgo: "vor {n} min", hAgo: "vor {n} h", dAgo: "vor {n} T",
empty: "In den letzten zwei Tagen war kein Agent tätig. Starte Claude Code, Codex, DeepSeek Harness, Gemini CLI… und er kommt herein.",
emptyRemote: "Anfragen von anderen Computern oder Gateway-Schlüsseln wurden ignoriert, da dieser Schalter in den Einstellungen aus ist.",
noFile: "Startet… das Plugin liest die Sitzungen deiner Agenten im magpie-Plugin-Host.",
demo: "Beispiel-Agenten", showDone: "Beendete Agenten zeigen", showText: "Fragen und Antworten zeigen",
demo: "Beispiel-Agenten", showDone: "Beendete Agenten zeigen", remote: "Agenten anderer Computer und Gateway-Schlüssel einbeziehen", showText: "Fragen und Antworten zeigen",
showSub: "Subagenten zeigen", showIdle: "Inaktive Agenten zeigen", agents: "Agents", allAgents: "Alle Agents",
language: "Sprache", auto: "Auto", scene: "Szene", quality: "Qualität",
hideAfter: "Büro verlassen nach", h1: "1 Stunde", h6: "6 Stunden", h24: "24 Stunden", never: "Nie",
@@ -254,8 +262,9 @@
copyResume: "Copiar comando de retomar", copySession: "Copiar id da sessão", copied: "Copiado",
justNow: "agora mesmo", sAgo: "há {n} s", mAgo: "há {n} min", hAgo: "há {n} h", dAgo: "há {n} d",
empty: "Nenhum agente trabalhou nos últimos dois dias. Abra Claude Code, Codex, DeepSeek Harness, Gemini CLI… e ele entra aqui.",
emptyRemote: "As solicitações de outros computadores ou chaves de gateway foram ignoradas porque essa opção está desativada nas Configurações.",
noFile: "Iniciando… o plugin lê as sessões dos seus agentes no host de plugins do magpie.",
demo: "Agentes de exemplo", showDone: "Mostrar agentes finalizados", showText: "Mostrar perguntas e respostas",
demo: "Agentes de exemplo", showDone: "Mostrar agentes finalizados", remote: "Incluir agentes de outros computadores e chaves de gateway", showText: "Mostrar perguntas e respostas",
showSub: "Mostrar subagentes", showIdle: "Mostrar agentes ociosos", agents: "Agentes", allAgents: "Todos os agentes",
language: "Idioma", auto: "Auto", scene: "Cenário", quality: "Qualidade",
hideAfter: "Sair do escritório após", h1: "1 hora", h6: "6 horas", h24: "24 horas", never: "Nunca",