diff --git a/packages/agent-office/CHANGELOG.md b/packages/agent-office/CHANGELOG.md index 31601d5..b4cadd4 100644 --- a/packages/agent-office/CHANGELOG.md +++ b/packages/agent-office/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## 0.2.3 · 2026-11-01 + +### Added + +- Jump directly to the live macOS terminal tab, multiplexer pane or desktop app window running a session (`lib/jump.mjs`), with single-click panel buttons, multi-host selector when a multiplexer session (`herdr` / `tmux`) is attached in multiple terminals, and double-click on workers, name tags, list rows or side-rail rows (#552). + ## 0.2.2 · 2026-11-01 ### Fixed diff --git a/packages/agent-office/README.md b/packages/agent-office/README.md index 5ac9339..be8353b 100644 --- a/packages/agent-office/README.md +++ b/packages/agent-office/README.md @@ -45,6 +45,7 @@ bun bin/agent-office.mjs --json # 一次性快照,适合让 Agent 在聊天 ![Today usage and context](https://raw.githubusercontent.com/QingJ01/magpie-agent-office/main/docs/today.png) - **最近对话**:点击 Agent 查看任务、当前步骤、最近消息、模型、目录、上下文和续接命令。 +- **一键跳回终端**:在 macOS 上自动识别活跃会话所在的终端标签页、分屏或桌面窗口(Terminal.app、iTerm2、tmux、Herdr、Otty、Claude Desktop、Cursor、VS Code),支持面板点击(多宿主并排切换)或双击小人/名牌/列表行直接切回。 - **页内提醒**:新出现的「需要你」或错误会在页面右下角弹出提示;标题栏显示需要你的数量。magpie 的 iframe 没有系统通知权限,所以不调用浏览器通知。 - **9 种语言**:English、简体中文、繁體中文、日本語、한국어、Español、Français、Deutsch、Português。自动按最近提问的语言选择,也可手动指定。 - **画中画**:可拖动、可缩放的页内悬浮小窗,✕ 或 Esc 放回。 diff --git a/packages/agent-office/bin/agent-office.mjs b/packages/agent-office/bin/agent-office.mjs index b9befc3..6a6a6cd 100644 --- a/packages/agent-office/bin/agent-office.mjs +++ b/packages/agent-office/bin/agent-office.mjs @@ -79,7 +79,7 @@ process.env.MAGPIE_AGENT_OFFICE_PAGE = scratch const hook = await import("../office.hooks.mjs") const startOpts = { text: !o.private, scanner: { days, max: 200 } } -hook.start(startOpts) +hook.start({ ...startOpts, jumper: {} }) await new Promise((r) => setTimeout(r, 250)) const first = hook.snapshot() @@ -187,10 +187,10 @@ async function route(req) { } // UI preferences remain local to this bridge; never accept scanner paths or // other hook internals from a request body. - for (const key of ["text", "remote", "mode", "dim", "demo", "showDone", "hideAfter", "scene", "quality", "agents", "showSub", "showIdle", "side", "sideV", "cleared", "approvalAfterSec", "lang"]) { + for (const key of ["text", "remote", "mode", "dim", "demo", "showDone", "hideAfter", "scene", "quality", "agents", "showSub", "showIdle", "side", "sideV", "cleared", "approvalAfterSec", "lang", "preferredJumpHost"]) { if (Object.hasOwn(next, key)) options[key] = next[key] } - hook.start({ text: options.text !== false, remote: options.remote === true }) + hook.start({ text: options.text !== false, remote: options.remote === true, jumper: {}, jumpRequest: next.jumpRequest, preferredJumpHost: options.preferredJumpHost }) return json(options) } if (req.method !== "GET" && req.method !== "HEAD") return json({ error: "method not allowed" }, 405) diff --git a/packages/agent-office/cli.test.mjs b/packages/agent-office/cli.test.mjs index eb65b22..f32da35 100644 --- a/packages/agent-office/cli.test.mjs +++ b/packages/agent-office/cli.test.mjs @@ -97,6 +97,21 @@ test("--json prints the same snapshot and honours --private", () => { expect(priv.sessions[0].query).toBe("") expect(priv.sessions[0].messages).toEqual([]) expect(JSON.stringify(priv)).not.toContain(SECRET) + + // Even when agent-office is also installed in magpie's plugins.json with + // text:true, --private must stay private and never leak prompts. + const cfg = tmp() + mkdirSync(join(cfg, "magpie"), { recursive: true }) + writeFileSync(join(cfg, "magpie", "plugins.json"), JSON.stringify({ + plugins: [{ spec: "@magpie-community/page-agent-office", options: { text: true, jumpRequest: { key: "claude|s1", session: "s1", at: Date.now() } } }], + })) + const envWithMagpie = { ...envFor(h), XDG_CONFIG_HOME: cfg } + const r = Bun.spawnSync({ cmd: [process.execPath, script, "--json", "--hours", "1", "--private"], cwd: dir, env: envWithMagpie, stdout: "pipe", stderr: "pipe" }) + expect(r.exitCode).toBe(0) + const privWithMagpie = JSON.parse(new TextDecoder().decode(r.stdout)) + expect(privWithMagpie.text).toBe(false) + expect(privWithMagpie.sessions[0].query).toBe("") + expect(JSON.stringify(privWithMagpie)).not.toContain(SECRET) }) test("the authenticated standalone page, bridge, live data and JSON options work", async () => { @@ -104,7 +119,7 @@ test("the authenticated standalone page, bridge, live data and JSON options work try { const ping = await (await fetch(s.url + "api/ping")).json() expect(ping.name).toBe("agent-office") - expect(ping.version).toBe("0.2.2") + expect(ping.version).toBe("0.2.3") const page = await fetch(s.url) expect(page.status).toBe(200) expect(await page.text()).toContain('src="_magpie/bridge.js"') diff --git a/packages/agent-office/jump.test.mjs b/packages/agent-office/jump.test.mjs new file mode 100644 index 0000000..26bbd69 --- /dev/null +++ b/packages/agent-office/jump.test.mjs @@ -0,0 +1,359 @@ +import { expect, test } from "bun:test" +import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { pathToFileURL } from "node:url" +import { appleScriptQuote, buildJumpPlan, createJumper, parseHerdrPanes, parsePs, parseTmuxPanes, resolveTarget, validTty, walkAncestors } from "./lib/jump.mjs" + +const dir = import.meta.dir +const scope = {} +new Function("globalThis", readFileSync(join(dir, "page", "agents.js"), "utf8"))(scope) +new Function("globalThis", readFileSync(join(dir, "page", "model.js"), "utf8"))(scope) +const M = scope.AgentOfficeModel + +const SAMPLE_PS = [ + " 100 1 ?? /Applications/iTerm.app/Contents/MacOS/iTerm2 /Applications/iTerm.app/Contents/MacOS/iTerm2", + " 101 100 ttys004 -zsh -zsh", + " 102 101 ttys004 claude claude --resume s-iterm", + " 200 1 ?? /System/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal /System/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal", + " 201 200 ttys008 -zsh -zsh", + " 202 201 ttys008 tmux tmux new -s dev", + " 203 1 ?? tmux tmux -s dev", + " 204 203 ttys009 -zsh -zsh", + " 205 204 ttys009 claude claude", + " 300 1 ?? /Users/me/.local/bin/herdr /Users/me/.local/bin/herdr server", + " 301 300 ttys016 -zsh -zsh", + " 302 301 ttys016 claude claude", + " 400 1 ?? /Applications/Otty.app/Contents/MacOS/Otty /Applications/Otty.app/Contents/MacOS/Otty", + " 401 400 ttys001 -zsh -zsh", + " 402 401 ttys001 herdr herdr", + " 500 1 ?? /Users/me/.local/bin/herdr-core /Users/me/.local/bin/herdr-core hold --socket /tmp/h.sock", + " 501 500 ttys012 /bin/zsh /bin/zsh -l", + " 502 501 ttys012 herdr herdr", + " 600 1 ?? /Applications/Alacritty.app/Contents/MacOS/alacritty /Applications/Alacritty.app/Contents/MacOS/alacritty", + " 601 600 ttys020 -zsh -zsh", + " 602 601 ttys020 claude claude", + " 700 1 ?? /Applications/Cursor.app/Contents/MacOS/Cursor /Applications/Cursor.app/Contents/MacOS/Cursor", + " 701 700 ttys021 -zsh -zsh", + " 702 701 ttys021 claude claude", +].join("\n") + +const BINS = { + herdr: "/usr/local/bin/herdr", + herdrApp: "/usr/local/bin/herdr-app", + ottyCli: "/Applications/Otty.app/Contents/MacOS/otty-cli", + tmux: "/opt/homebrew/bin/tmux", + osascript: "/usr/bin/osascript", + open: "/usr/bin/open", +} + +test("parsePs and walkAncestors find the controlling tty and outer terminal app", () => { + const procs = parsePs(SAMPLE_PS) + expect(walkAncestors(102, procs)).toMatchObject({ + tty: "/dev/ttys004", + ttyShort: "ttys004", + inHerdr: false, + inTmux: false, + app: { id: "iterm2", kind: "iterm2", app: "iTerm2", bundleId: "com.googlecode.iterm2" }, + }) + expect(walkAncestors(302, procs)).toMatchObject({ + tty: "/dev/ttys016", + ttyShort: "ttys016", + inHerdr: true, + }) +}) + +test("resolveTarget and buildJumpPlan focus iTerm2, Terminal.app and tmux panes", () => { + const procs = parsePs(SAMPLE_PS) + const tmuxByTty = parseTmuxPanes("%3\t/dev/ttys009\tdev\t2\n", "/dev/ttys008\t202\tdev\n") + const liveFiles = new Map([ + ["s-iterm", { pid: 102, alive: true, sessionId: "s-iterm", entrypoint: "cli" }], + ["s-tmux", { pid: 205, alive: true, sessionId: "s-tmux", entrypoint: "cli" }], + ]) + const state = { platform: "darwin", liveFiles, procs, tmuxByTty } + + const itermTarget = resolveTarget({ session: "s-iterm" }, state) + expect(itermTarget).toMatchObject({ kind: "iterm2", badge: "iTerm2 · ttys004", tty: "/dev/ttys004" }) + const itermPlan = buildJumpPlan({ session: "s-iterm" }, state, BINS) + expect(itermPlan.ok).toBe(true) + expect(itermPlan.steps[0].cmd).toBe("/usr/bin/osascript") + expect(itermPlan.steps[0].args[1]).toContain('else if "/dev/ttys004" is not "" and (tty of aSess as text) is "/dev/ttys004" then') + + const tmuxTarget = resolveTarget({ session: "s-tmux" }, state) + expect(tmuxTarget).toMatchObject({ kind: "tmux", badge: "Terminal · %3", tmuxPane: "%3", tmuxWindow: "dev:2", clientTty: "/dev/ttys008", outerKind: "terminal" }) + const tmuxPlan = buildJumpPlan({ session: "s-tmux" }, state, BINS) + expect(tmuxPlan.steps.map((x) => x.desc)).toEqual([ + "tmux select-window -t dev:2", + "tmux select-pane -t %3", + "osascript Terminal select (/dev/ttys008)", + ]) + expect(tmuxPlan.steps[2].args[1]).toContain('if (tty of aTab as text) is "/dev/ttys008" then') +}) + +test("a request carrying its own target or cwd in options gets no steps from it", async () => { + const procs = parsePs(SAMPLE_PS) + const liveFiles = new Map([ + ["s-cursor", { pid: 702, alive: true, sessionId: "s-cursor", entrypoint: "cli" }], + ]) + const state = { platform: "darwin", liveFiles, procs } + const jumper = createJumper({ state }) + + // 1. Unknown session with an injected AppleScript tty payload in req.target + const injectedTtyReq = { + session: "non-existent", + target: { + kind: "iterm2", + tty: 'x" then\ndo shell script "touch ~/runs/pwned552"\nend if\nif "a" is "b', + }, + } + expect(buildJumpPlan(injectedTtyReq, state, BINS)).toEqual({ ok: false, reason: "no_target", target: null, steps: [] }) + expect(await jumper.jump(injectedTtyReq, true)).toEqual({ ok: false, reason: "no_target", target: null, steps: [] }) + + // 2. Unknown session with an injected IDE bundleId + cwd payload in req.target + const injectedIdeReq = { + session: "non-existent", + cwd: "/Users/me/Downloads/run.command", + target: { + kind: "ide", + bundleId: "com.apple.Terminal", + }, + } + expect(buildJumpPlan(injectedIdeReq, state, BINS)).toEqual({ ok: false, reason: "no_target", target: null, steps: [] }) + expect(await jumper.jump(injectedIdeReq, true)).toEqual({ ok: false, reason: "no_target", target: null, steps: [] }) + + // 3. Real IDE session ignores req.target and never passes req.cwd to `open -b` + const cursorPlan = buildJumpPlan({ + session: "s-cursor", + cwd: "/Users/me/Downloads/run.command", + target: { kind: "terminal", tty: 'x" then\ndo shell script "pwn"\n' }, + }, state, BINS) + expect(cursorPlan.ok).toBe(true) + expect(cursorPlan.steps).toEqual([ + { cmd: "/usr/bin/open", args: ["-b", "com.todesktop.230313mzl4w4u92"], desc: "open -b com.todesktop.230313mzl4w4u92" }, + ]) + + expect(validTty("/dev/ttys004")).toBe(true) + expect(validTty("/dev/pts/8")).toBe(false) + expect(validTty('x" then do shell script "y"')).toBe(false) + expect(appleScriptQuote('a"b\\c\nd')).toBe('a\\"b\\\\cd') +}) + +test("Linux and unrecognized macOS terminals resolve to null instead of Terminal.app", () => { + const procs = parsePs(SAMPLE_PS) + const liveFiles = new Map([ + ["s-iterm", { pid: 102, alive: true, sessionId: "s-iterm", entrypoint: "cli" }], + ["s-alacritty", { pid: 602, alive: true, sessionId: "s-alacritty", entrypoint: "cli" }], + ]) + expect(resolveTarget({ session: "s-iterm" }, { platform: "linux", liveFiles, procs })).toBeNull() + expect(resolveTarget({ session: "s-alacritty" }, { platform: "darwin", liveFiles, procs })).toBeNull() +}) + +test("Herdr sessions expose all attached hosts (Herdr.app, Otty) and switch between them", () => { + const procs = parsePs(SAMPLE_PS) + const herdrJson = JSON.stringify({ + result: { + panes: [ + { pane_id: "wM:p8C", tab_id: "wM:t73", workspace_id: "wM", cwd: "/Users/me/repo", agent_session: { value: "s-herdr" } }, + ], + }, + }) + const { bySession: herdrBySession, byCwd: herdrByCwd } = parseHerdrPanes(herdrJson) + const herdrHosts = [ + { id: "herdr-app", app: "Herdr.app", bundleId: "dev.herdr.app", herdrAppSpace: "sp1", herdrAppTab: "tb1" }, + { id: "otty", app: "Otty", bundleId: "io.appmakes.otty", ottyPane: "p_1" }, + ] + const liveFiles = new Map([["s-herdr", { pid: 302, alive: true, sessionId: "s-herdr", entrypoint: "cli" }]]) + const state = { platform: "darwin", liveFiles, procs, herdrBySession, herdrByCwd, herdrHosts } + const target = resolveTarget({ session: "s-herdr" }, state) + expect(target.kind).toBe("herdr") + expect(target.badge).toBe("Herdr.app · wM:p8C") + expect(target.hosts.map((h) => h.id)).toEqual(["herdr-app", "otty"]) + + const planHerdrApp = buildJumpPlan({ session: "s-herdr", preferredHostId: "herdr-app" }, state, BINS) + expect(planHerdrApp.steps.map((x) => x.desc)).toEqual([ + "herdr workspace focus wM", + "herdr tab focus wM:t73", + "herdr agent focus wM:p8C", + "open -b dev.herdr.app", + ]) + + const planOtty = buildJumpPlan({ session: "s-herdr", preferredHostId: "otty" }, state, BINS) + expect(planOtty.steps.map((x) => x.desc)).toEqual([ + "herdr workspace focus wM", + "herdr tab focus wM:t73", + "herdr agent focus wM:p8C", + "otty-cli pane focus p_1", + "open -b io.appmakes.otty", + ]) +}) + +test("Claude Desktop sessions jump via claude://resume deep link", () => { + const desktopIdx = new Map([["cli-1", "local_abc123"]]) + const state = { platform: "darwin", desktopIdx } + const target = resolveTarget({ session: "cli-1" }, state) + expect(target).toMatchObject({ kind: "claude-desktop", badge: "Claude Desktop", hostSessionId: "local_abc123" }) + const plan = buildJumpPlan({ session: "cli-1" }, state, BINS) + expect(plan.steps.map((x) => x.desc)).toEqual([ + "open claude://resume?session=local_abc123", + "open -b com.anthropic.claudefordesktop", + ]) +}) + +test("page/model.js preserves session target metadata and target fields match page/app.js", () => { + const now = 1_000_000 + const procs = parsePs(SAMPLE_PS) + const herdrJson = JSON.stringify({ + result: { panes: [{ pane_id: "wM:p8C", tab_id: "wM:t73", workspace_id: "wM", cwd: "/Users/me/repo", agent_session: { value: "s-herdr" } }] }, + }) + const { bySession: herdrBySession, byCwd: herdrByCwd } = parseHerdrPanes(herdrJson) + const herdrHosts = [ + { id: "herdr-app", app: "Herdr.app", bundleId: "dev.herdr.app" }, + { id: "otty", app: "Otty", bundleId: "io.appmakes.otty" }, + ] + const liveFiles = new Map([["s-herdr", { pid: 302, alive: true, sessionId: "s-herdr", entrypoint: "cli" }]]) + const target = resolveTarget({ session: "s-herdr" }, { platform: "darwin", liveFiles, procs, herdrBySession, herdrByCwd, herdrHosts }) + expect(target.label).toBe("Herdr.app · wM:p8C") + expect(target.badge).toBe("Herdr.app · wM:p8C") + expect(target.paneId).toBe("wM:p8C") + expect(target.hosts.map((h) => [h.id, h.label, h.app])).toEqual([ + ["herdr-app", "Herdr.app", "Herdr.app"], + ["otty", "Otty", "Otty"], + ]) + + const [a] = M.agents({ sessions: [{ key: "claude|s-herdr", source: "files", agent: "claude", session: "s-herdr", phase: "tool", touched: now - 1000, target }] }, now) + expect(a.target).toEqual(target) + + // Verify the exact button-text derivation used in page/app.js fillPanel() + const w = M.text("en") + const paneId = a.target.paneId || a.target.herdrPane || a.target.tmuxPane || "" + const buttons = a.target.hosts.map((h, idx) => { + const text = idx === 0 && paneId && !h.label.includes(paneId) ? `${h.label} · ${paneId}` : h.label + return M.fill(w.jumpTo, text) + }) + expect(buttons).toEqual(["↗ Herdr.app · wM:p8C", "↗ Otty"]) + expect(buttons.join(" ")).not.toContain("undefined") +}) + +test("office.hooks.mjs imported without MAGPIE_AGENT_OFFICE_PAGE writes page/live.js and never throws", () => { + const root = mkdtempSync(join(tmpdir(), "agent-office-host-probe-")) + try { + const home = join(root, "home") + const pkgDir = join(root, "pkg") + mkdirSync(join(pkgDir, "page"), { recursive: true }) + cpSync(join(dir, "lib"), join(pkgDir, "lib"), { recursive: true }) + cpSync(join(dir, "office.hooks.mjs"), join(pkgDir, "office.hooks.mjs")) + cpSync(join(dir, "package.json"), join(pkgDir, "package.json")) + + const project = join(home, ".claude", "projects", "-tmp-probe") + mkdirSync(project, { recursive: true }) + const ts = new Date().toISOString() + writeFileSync(join(project, "s1.jsonl"), [ + JSON.stringify({ type: "user", sessionId: "s1", cwd: "/tmp/probe", timestamp: ts, message: { role: "user", content: "hello" } }), + JSON.stringify({ type: "assistant", sessionId: "s1", cwd: "/tmp/probe", timestamp: ts, message: { role: "assistant", stop_reason: "end_turn", content: [{ type: "text", text: "ok" }] } }), + ].join("\n")) + + const env = { ...process.env, HOME: home, XDG_CONFIG_HOME: join(home, ".config") } + delete env.MAGPIE_AGENT_OFFICE_PAGE + const hookUrl = pathToFileURL(join(pkgDir, "office.hooks.mjs")).href + const code = ` + const h = await import(${JSON.stringify(hookUrl)}); + const snap = h.snapshot(); + h.write(); + h.stop(); + console.log(JSON.stringify({ count: snap.sessions.length, id: snap.sessions[0]?.session })); + ` + const r = Bun.spawnSync({ cmd: [process.execPath, "-e", code], cwd: pkgDir, env, stdout: "pipe", stderr: "pipe" }) + expect(r.exitCode).toBe(0) + const out = JSON.parse(new TextDecoder().decode(r.stdout).trim()) + expect(out).toEqual({ count: 1, id: "s1" }) + const livePath = join(pkgDir, "page", "live.js") + expect(existsSync(livePath)).toBe(true) + const live = readFileSync(livePath, "utf8") + expect(live.startsWith("globalThis.AgentOfficeLive = ")).toBe(true) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + +test("magpie host restart on options.set executes a fresh jumpRequest once and never touches plugins.json", () => { + if (process.platform !== "darwin") return + const root = mkdtempSync(join(tmpdir(), "agent-office-restart-probe-")) + try { + const home = join(root, "home") + const cfg = join(root, "cfg") + const cache = join(root, "cache") + const pkgDir = join(root, "pkg") + mkdirSync(join(pkgDir, "page"), { recursive: true }) + cpSync(join(dir, "lib"), join(pkgDir, "lib"), { recursive: true }) + cpSync(join(dir, "office.hooks.mjs"), join(pkgDir, "office.hooks.mjs")) + cpSync(join(dir, "package.json"), join(pkgDir, "package.json")) + + // Fake herdr in $HOME/.local/bin/herdr logging every invocation + const binDir = join(home, ".local", "bin") + const herdrLog = join(home, "herdr.log") + mkdirSync(binDir, { recursive: true }) + const fakeHerdr = join(binDir, "herdr") + writeFileSync(fakeHerdr, `#!/bin/sh +echo "$@" >> "${herdrLog}" +if [ "$1" = "pane" ] && [ "$2" = "list" ]; then + echo '{"result":{"panes":[{"pane_id":"wM:p8C","tab_id":"wM:t73","workspace_id":"wM","cwd":"/tmp/probe","agent_session":{"value":"11111111-2222-3333-4444-555555555555"}}]}}' +fi +`) + chmodSync(fakeHerdr, 0o755) + + // plugins.json written 0600 with another plugin's apiKey + fresh jumpRequest + const magpieCfg = join(cfg, "magpie") + mkdirSync(magpieCfg, { recursive: true }) + const pluginsFile = join(magpieCfg, "plugins.json") + const pluginsContent = JSON.stringify({ + plugins: [ + { spec: "other-plugin", options: { apiKey: "secret-api-key" } }, + { + spec: "@magpie-community/page-agent-office", + options: { + text: true, + jumpRequest: { + key: "claude|11111111-2222-3333-4444-555555555555", + session: "11111111-2222-3333-4444-555555555555", + preferredHostId: "herdr-cli", + at: Date.now(), + }, + }, + }, + ], + }, null, 2) + writeFileSync(pluginsFile, pluginsContent, { mode: 0o600 }) + chmodSync(pluginsFile, 0o600) + + const env = { ...process.env, HOME: home, XDG_CONFIG_HOME: cfg, XDG_CACHE_HOME: cache } + delete env.MAGPIE_AGENT_OFFICE_PAGE + const hookUrl = pathToFileURL(join(pkgDir, "office.hooks.mjs")).href + const code = ` + const h = await import(${JSON.stringify(hookUrl)}); + await h.waitForJump(); + h.stop(); + ` + // First host startup (right after magpie's SetOptions -> Restart) + const r1 = Bun.spawnSync({ cmd: [process.execPath, "-e", code], cwd: pkgDir, env, stdout: "pipe", stderr: "pipe" }) + expect(r1.exitCode).toBe(0) + const log1 = readFileSync(herdrLog, "utf8") + expect(log1).toContain("workspace focus wM") + expect(log1).toContain("tab focus wM:t73") + expect(log1).toContain("agent focus wM:p8C") + + // plugins.json mode (0600) and content must be untouched + expect(statSync(pluginsFile).mode & 0o777).toBe(0o600) + expect(readFileSync(pluginsFile, "utf8")).toBe(pluginsContent) + + // Second host startup with the same plugins.json must not replay the jump + writeFileSync(herdrLog, "") + const r2 = Bun.spawnSync({ cmd: [process.execPath, "-e", code], cwd: pkgDir, env, stdout: "pipe", stderr: "pipe" }) + expect(r2.exitCode).toBe(0) + const log2 = readFileSync(herdrLog, "utf8") + expect(log2).not.toContain("workspace focus wM") + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + + diff --git a/packages/agent-office/lib/jump.mjs b/packages/agent-office/lib/jump.mjs new file mode 100644 index 0000000..98e1929 --- /dev/null +++ b/packages/agent-office/lib/jump.mjs @@ -0,0 +1,620 @@ +// Finds the terminal tab, multiplexer pane or desktop window where a live +// session is open, and brings it to the front when the user clicks Jump. +// +// Pure functions (parsePs, walkAncestors, parseHerdrPanes, parseTmuxPanes, +// resolveTarget, buildJumpPlan) take the process table and session records +// as values so tests drive every branch without touching the system. +// createJumper wraps the host side: it refreshes the process snapshot +// asynchronously and never trusts a target or path supplied in options. +import { execFile } from "node:child_process" +import { existsSync, readFileSync, readdirSync } from "node:fs" +import { homedir } from "node:os" +import { join } from "node:path" + +const TTY_RE = /^\/dev\/ttys?\d+$/ +const GUID_RE = /^[A-Za-z0-9_:-]{1,64}$/ + +function homeDir() { + return process.env.HOME || homedir() +} + +function extraPath() { + return [ + join(homeDir(), ".local", "bin"), + "/opt/homebrew/bin", + "/usr/local/bin", + "/usr/bin", + "/bin", + "/usr/sbin", + "/sbin", + ].join(":") +} + +export function validTty(tty) { + return typeof tty === "string" && TTY_RE.test(tty) +} + +export function appleScriptQuote(s) { + return String(s || "").replace(/[\r\n\0]/g, "").replace(/\\/g, "\\\\").replace(/"/g, '\\"') +} + +function envWithPath() { + const ep = extraPath() + return { ...process.env, PATH: ep + (process.env.PATH ? ":" + process.env.PATH : "") } +} + +function findBin(name, candidates = []) { + for (const c of candidates) if (c && existsSync(c)) return c + for (const d of extraPath().split(":")) { + const p = join(d, name) + if (existsSync(p)) return p + } + return name +} + +function pidAlive(pid) { + if (!Number.isInteger(pid) || pid <= 0) return false + try { process.kill(pid, 0); return true } catch (e) { return e?.code !== "ESRCH" } +} + +function runAsync(bin, args = [], timeout = 1200) { + return new Promise((resolve) => { + execFile(bin, args, { env: envWithPath(), encoding: "utf8", timeout }, (err, stdout) => { + resolve(err ? "" : String(stdout || "")) + }) + }) +} + +// `ps -axo pid=,ppid=,tty=,comm=,args=` turned into Map(pid -> { pid, ppid, tty, ttyShort, comm, args }) +export function parsePs(text) { + const procs = new Map() + for (const line of String(text || "").split("\n")) { + const m = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(\S+)\s*(.*)$/.exec(line) + if (!m) continue + const pid = Number(m[1]) + const ppid = Number(m[2]) + const ttyRaw = m[3] + const comm = m[4] + const args = m[5] || comm + const tty = ttyRaw && ttyRaw !== "??" && ttyRaw !== "-" ? (ttyRaw.startsWith("/dev/") ? ttyRaw : "/dev/" + ttyRaw) : "" + procs.set(pid, { pid, ppid, tty, ttyShort: tty ? tty.replace("/dev/", "") : "", comm, args }) + } + return procs +} + +export function detectHostApp(p) { + if (!p) return null + const s = (p.comm + " " + p.args).toLowerCase() + if (s.includes("/applications/otty.app/")) return { id: "otty", kind: "otty", app: "Otty", label: "Otty", bundleId: "io.appmakes.otty" } + if (s.includes("herdr-core") || s.includes("herdr-app") || s.includes("/applications/herdr.app/")) return { id: "herdr-app", kind: "herdr-app", app: "Herdr.app", label: "Herdr.app", bundleId: "dev.herdr.app" } + if (s.includes("/applications/iterm.app/") || s.includes("iterm2")) return { id: "iterm2", kind: "iterm2", app: "iTerm2", label: "iTerm2", bundleId: "com.googlecode.iterm2" } + if (s.includes("/utilities/terminal.app/")) return { id: "terminal", kind: "terminal", app: "Terminal", label: "Terminal", bundleId: "com.apple.Terminal" } + if (s.includes("/applications/ghostty.app/")) return { id: "ghostty", kind: "ghostty", app: "Ghostty", label: "Ghostty", bundleId: "com.mitchellh.ghostty" } + if (s.includes("/applications/warp.app/")) return { id: "warp", kind: "warp", app: "Warp", label: "Warp", bundleId: "dev.warp.Warp-Stable" } + if (s.includes("wezterm")) return { id: "wezterm", kind: "wezterm", app: "WezTerm", label: "WezTerm", bundleId: "com.github.wez.wezterm" } + if (s.includes("/applications/cursor.app/")) return { id: "cursor", kind: "ide", app: "Cursor", label: "Cursor", bundleId: "com.todesktop.230313mzl4w4u92" } + if (s.includes("/applications/visual studio code.app/")) return { id: "vscode", kind: "ide", app: "VS Code", label: "VS Code", bundleId: "com.microsoft.VSCode" } + if (s.includes("/applications/antigravity.app/")) return { id: "antigravity", kind: "ide", app: "Antigravity", label: "Antigravity", bundleId: "com.google.antigravity" } + if (s.includes("/applications/claude.app/")) return { id: "claude-desktop", kind: "claude-desktop", app: "Claude Desktop", label: "Claude Desktop", bundleId: "com.anthropic.claudefordesktop" } + return null +} + +export function walkAncestors(pid, procs) { + const res = { tty: "", ttyShort: "", inHerdr: false, inTmux: false, app: null } + let cur = Number(pid) + const seen = new Set() + while (cur > 1 && !seen.has(cur) && seen.size < 32) { + seen.add(cur) + const p = procs.get(cur) + if (!p) break + if (!res.tty && p.tty) { res.tty = p.tty; res.ttyShort = p.ttyShort } + if (/\bherdr\s+server\b/.test(p.args)) res.inHerdr = true + if (/\btmux\b/.test(p.comm) || /\btmux\b/.test(p.args)) res.inTmux = true + const app = detectHostApp(p) + if (app && !res.app) res.app = app + cur = p.ppid + } + return res +} + +export function parseHerdrPanes(text) { + const bySession = new Map() + const byCwd = new Map() + try { + const i = String(text || "").indexOf("{") + if (i < 0) return { bySession, byCwd } + const j = JSON.parse(String(text).slice(i)) + for (const p of j?.result?.panes || j?.result?.agents || []) { + const info = { + paneId: p.pane_id || "", + tabId: p.tab_id || "", + workspaceId: p.workspace_id || "", + cwd: p.foreground_cwd || p.cwd || "", + title: p.terminal_title_stripped || p.terminal_title || "", + } + const sid = p.agent_session?.value || "" + if (sid) bySession.set(String(sid), info) + const m = /--resume\s+([0-9A-Za-z-]{8,})/.exec(info.title) + if (m && !bySession.has(m[1])) bySession.set(m[1], info) + if (info.cwd && !byCwd.has(info.cwd)) byCwd.set(info.cwd, info) + } + } catch {} + return { bySession, byCwd } +} + +export function parseTmuxPanes(panesText, clientsText = "") { + const byTty = new Map() + const clientsBySession = new Map() + for (const line of String(clientsText || "").split("\n")) { + const [clientTty, clientPid, sessionName] = line.trim().split("\t") + if (sessionName && clientTty) clientsBySession.set(sessionName, { clientTty, clientPid: Number(clientPid) || 0 }) + } + for (const line of String(panesText || "").split("\n")) { + const [paneId, paneTty, sessionName, windowIndex] = line.trim().split("\t") + if (!paneId || !paneTty) continue + const cl = clientsBySession.get(sessionName) || {} + byTty.set(paneTty, { paneId, paneTty, sessionName: sessionName || "", windowIndex: windowIndex || "", clientTty: cl.clientTty || "", clientPid: cl.clientPid || 0 }) + } + return byTty +} + +function normalizeHosts(herdrHosts) { + const list = Array.isArray(herdrHosts) && herdrHosts.length + ? herdrHosts + : [{ id: "herdr-app", app: "Herdr.app", label: "Herdr.app", bundleId: "dev.herdr.app" }] + return list.map((h) => ({ + ...h, + id: String(h?.id || "herdr-app"), + app: String(h?.app || h?.label || "Herdr.app"), + label: String(h?.label || h?.app || "Herdr.app"), + })) +} + +export function resolveTarget(s, state) { + const platform = state?.platform ?? process.platform + if (platform !== "darwin") return null + + const sid = String(s?.session || s?.id || "").replace(/^[^|]+\|/, "") + const cwd = String(s?.cwd || "") + const { + liveFiles = new Map(), + desktopIdx = new Map(), + procs = new Map(), + herdrBySession = new Map(), + herdrByCwd = new Map(), + herdrHosts = [], + tmuxByTty = new Map(), + } = state || {} + + const hp = sid ? herdrBySession.get(sid) : null + const lf = sid ? liveFiles.get(sid) : null + const walk = lf?.alive ? walkAncestors(lf.pid, procs) : null + const hosts = normalizeHosts(herdrHosts) + const primary = hosts[0] + + // 1. Session inside a Herdr pane + if (hp && hp.paneId) { + const label = `${primary.app} · ${hp.paneId}` + return { + kind: "herdr", + hostId: primary.id, + app: primary.app, + label, + badge: label, + paneId: hp.paneId, + detail: [hp.workspaceId, hp.tabId, hp.paneId].filter(Boolean).join(" / "), + herdrWorkspace: hp.workspaceId, + herdrTab: hp.tabId, + herdrPane: hp.paneId, + ottyPane: primary.ottyPane || "", + outerBundleId: primary.bundleId || "dev.herdr.app", + hosts, + tty: validTty(walk?.tty) ? walk.tty : "", + pid: lf?.pid || 0, + live: true, + } + } + + // 2. Claude Desktop session + const hostSid = lf?.hostSessionId || (sid ? desktopIdx.get(sid) : "") || "" + if (lf?.entrypoint === "claude-desktop-3p" || hostSid) { + return { + kind: "claude-desktop", + app: "Claude Desktop", + label: "Claude Desktop", + badge: "Claude Desktop", + paneId: "", + detail: hostSid || sid.slice(0, 8), + hostSessionId: hostSid, + bundleId: "com.anthropic.claudefordesktop", + pid: lf?.pid || 0, + live: !!lf?.alive || !!hostSid, + } + } + + // 3. Live process walked up the process tree (only known macOS apps or multiplexers) + if (walk) { + const safeTty = validTty(walk.tty) ? walk.tty : "" + if (walk.inHerdr) { + const cp = cwd ? herdrByCwd.get(cwd) : null + const paneId = cp?.paneId || "" + const label = paneId ? `${primary.app} · ${paneId}` : `${primary.app} · Herdr` + return { + kind: "herdr", + hostId: primary.id, + app: primary.app, + label, + badge: label, + paneId, + detail: [cp?.workspaceId, cp?.tabId, paneId].filter(Boolean).join(" / "), + herdrWorkspace: cp?.workspaceId || "", + herdrTab: cp?.tabId || "", + herdrPane: paneId, + ottyPane: primary.ottyPane || "", + outerBundleId: primary.bundleId || "dev.herdr.app", + hosts, + tty: safeTty, + pid: lf.pid, + live: true, + } + } + if (walk.inTmux && safeTty && tmuxByTty.has(safeTty)) { + const tm = tmuxByTty.get(safeTty) + const outer = tm.clientPid ? walkAncestors(tm.clientPid, procs).app : null + const clientTty = validTty(tm.clientTty) ? tm.clientTty : "" + const label = `${outer?.app || "tmux"} · ${tm.paneId}` + return { + kind: "tmux", + app: outer?.app || "tmux", + label, + badge: label, + paneId: tm.paneId, + detail: [tm.sessionName, tm.windowIndex, tm.paneId].filter(Boolean).join(":"), + tmuxPane: tm.paneId, + tmuxWindow: tm.windowIndex ? `${tm.sessionName}:${tm.windowIndex}` : "", + clientTty, + outerKind: outer?.kind || "", + bundleId: outer?.bundleId || "", + tty: safeTty, + pid: lf.pid, + live: true, + } + } + if (walk.app) { + const suffix = safeTty ? ` · ${walk.ttyShort}` : "" + const label = `${walk.app.app}${suffix}` + return { + kind: walk.app.kind, + app: walk.app.app, + label, + badge: label, + paneId: "", + detail: safeTty || cwd, + bundleId: walk.app.bundleId, + tty: safeTty, + pid: lf.pid, + live: true, + } + } + } + + return null +} + +function appleScriptIterm(tty, sessionGuid = "") { + const safeTty = validTty(tty) ? appleScriptQuote(tty) : "" + const rawGuid = sessionGuid ? String(sessionGuid).split(":").pop() : "" + const safeGuid = GUID_RE.test(rawGuid) ? appleScriptQuote(rawGuid) : "" + if (!safeTty && !safeGuid) return "" + return ` +if application "iTerm2" is not running then return "not_running" +tell application "iTerm2" + repeat with aWin in windows + repeat with aTab in tabs of aWin + repeat with aSess in sessions of aTab + set matched to false + if "${safeGuid}" is not "" and (id of aSess as text) contains "${safeGuid}" then + set matched to true + else if "${safeTty}" is not "" and (tty of aSess as text) is "${safeTty}" then + set matched to true + end if + if matched then + set miniaturized of aWin to false + select aWin + select aTab + tell aSess to select + activate + return "ok" + end if + end repeat + end repeat + end repeat + activate + return "activated_only" +end tell`.trim() +} + +function appleScriptTerminalApp(tty) { + const safeTty = validTty(tty) ? appleScriptQuote(tty) : "" + if (!safeTty) return "" + return ` +if application "Terminal" is not running then return "not_running" +tell application "Terminal" + repeat with aWin in windows + repeat with aTab in tabs of aWin + if (tty of aTab as text) is "${safeTty}" then + set selected tab of aWin to aTab + set miniaturized of aWin to false + set index of aWin to 1 + activate + return "ok" + end if + end repeat + end repeat + activate + return "activated_only" +end tell`.trim() +} + +// Builds the jump plan strictly from host-resolved state; any `target` or `cwd` +// supplied on `req` (for example from plugins.json options) is ignored. +export function buildJumpPlan(req, state, bins = {}) { + const home = homeDir() + const B = { + herdr: bins.herdr || findBin("herdr", [join(home, ".local", "bin", "herdr")]), + ottyCli: bins.ottyCli || findBin("otty-cli", ["/Applications/Otty.app/Contents/MacOS/otty-cli"]), + tmux: bins.tmux || findBin("tmux", ["/opt/homebrew/bin/tmux", "/usr/local/bin/tmux"]), + osascript: bins.osascript || "/usr/bin/osascript", + open: bins.open || "/usr/bin/open", + } + const sid = String(req?.session || req?.id || req?.key || "").replace(/^[^|]+\|/, "") + const target = sid && state ? resolveTarget({ session: sid }, state) : null + if (!target) return { ok: false, reason: "no_target", target: null, steps: [] } + + const steps = [] + switch (target.kind) { + case "herdr": { + const wantHostId = typeof req?.preferredHostId === "string" ? req.preferredHostId : (target.hostId || "") + const hosts = Array.isArray(target.hosts) ? target.hosts : [] + const chosen = wantHostId === "herdr-cli" + ? { id: "herdr-cli", app: "herdr", bundleId: "" } + : (hosts.find((h) => h.id === wantHostId) || { + id: target.hostId || (target.outerBundleId === "dev.herdr.app" ? "herdr-app" : "otty"), + app: target.app || "Herdr.app", + bundleId: target.outerBundleId || "dev.herdr.app", + ottyPane: target.ottyPane || "", + tty: target.tty || "", + }) + if (target.herdrWorkspace) steps.push({ cmd: B.herdr, args: ["workspace", "focus", target.herdrWorkspace], desc: `herdr workspace focus ${target.herdrWorkspace}` }) + if (target.herdrTab) steps.push({ cmd: B.herdr, args: ["tab", "focus", target.herdrTab], desc: `herdr tab focus ${target.herdrTab}` }) + if (target.herdrPane) steps.push({ cmd: B.herdr, args: ["agent", "focus", target.herdrPane], desc: `herdr agent focus ${target.herdrPane}` }) + if (chosen.id === "otty" && chosen.ottyPane) { + steps.push({ cmd: B.ottyCli, args: ["pane", "focus", chosen.ottyPane], desc: `otty-cli pane focus ${chosen.ottyPane}` }) + } else if (chosen.id === "iterm2" && validTty(chosen.tty)) { + const script = appleScriptIterm(chosen.tty) + if (script) steps.push({ cmd: B.osascript, args: ["-e", script], desc: `osascript iTerm2 select (${chosen.tty})` }) + } else if (chosen.id === "terminal" && validTty(chosen.tty)) { + const script = appleScriptTerminalApp(chosen.tty) + if (script) steps.push({ cmd: B.osascript, args: ["-e", script], desc: `osascript Terminal select (${chosen.tty})` }) + } + if (chosen.bundleId) steps.push({ cmd: B.open, args: ["-b", chosen.bundleId], desc: `open -b ${chosen.bundleId}` }) + break + } + case "claude-desktop": { + if (target.hostSessionId && GUID_RE.test(target.hostSessionId)) { + steps.push({ cmd: B.open, args: [`claude://resume?session=${target.hostSessionId}`], desc: `open claude://resume?session=${target.hostSessionId}` }) + } + steps.push({ cmd: B.open, args: ["-b", "com.anthropic.claudefordesktop"], desc: "open -b com.anthropic.claudefordesktop" }) + break + } + case "iterm2": { + const script = appleScriptIterm(target.tty, target.itermSessionId) + if (script) steps.push({ cmd: B.osascript, args: ["-e", script], desc: `osascript iTerm2 select (${target.tty})` }) + else steps.push({ cmd: B.open, args: ["-b", "com.googlecode.iterm2"], desc: "open -b com.googlecode.iterm2" }) + break + } + case "terminal": { + const script = appleScriptTerminalApp(target.tty) + if (script) steps.push({ cmd: B.osascript, args: ["-e", script], desc: `osascript Terminal select (${target.tty})` }) + else steps.push({ cmd: B.open, args: ["-b", "com.apple.Terminal"], desc: "open -b com.apple.Terminal" }) + break + } + case "tmux": { + if (target.tmuxWindow) steps.push({ cmd: B.tmux, args: ["select-window", "-t", target.tmuxWindow], desc: `tmux select-window -t ${target.tmuxWindow}` }) + if (target.tmuxPane) steps.push({ cmd: B.tmux, args: ["select-pane", "-t", target.tmuxPane], desc: `tmux select-pane -t ${target.tmuxPane}` }) + if (target.outerKind === "iterm2" && validTty(target.clientTty)) { + const script = appleScriptIterm(target.clientTty) + if (script) steps.push({ cmd: B.osascript, args: ["-e", script], desc: `osascript iTerm2 select (${target.clientTty})` }) + } else if (target.outerKind === "terminal" && validTty(target.clientTty)) { + const script = appleScriptTerminalApp(target.clientTty) + if (script) steps.push({ cmd: B.osascript, args: ["-e", script], desc: `osascript Terminal select (${target.clientTty})` }) + } else if (target.bundleId) { + steps.push({ cmd: B.open, args: ["-b", target.bundleId], desc: `open -b ${target.bundleId}` }) + } + break + } + case "otty": { + if (target.ottyPane) steps.push({ cmd: B.ottyCli, args: ["pane", "focus", target.ottyPane], desc: `otty-cli pane focus ${target.ottyPane}` }) + steps.push({ cmd: B.open, args: ["-b", "io.appmakes.otty"], desc: "open -b io.appmakes.otty" }) + break + } + default: { + if (target.bundleId) steps.push({ cmd: B.open, args: ["-b", target.bundleId], desc: `open -b ${target.bundleId}` }) + break + } + } + return { ok: steps.length > 0, target, steps } +} + +// ---- Host-side asynchronous collector & jumper ----------------------------- +export function createJumper(opts = {}) { + const ttl = opts.ttl ?? 10_000 + const onUpdate = typeof opts.onUpdate === "function" ? opts.onUpdate : null + let snap = { at: 0, state: opts.state || null, inflight: null } + let desktopCache = { at: 0, map: new Map() } + + function readLiveFiles() { + const home = homeDir() + const bySession = new Map() + for (const d of [".claude", ".qoder", ".qoder-cn", ".workbuddy", ".codebuddy"]) { + const dir = join(home, d, "sessions") + if (!existsSync(dir)) continue + let names = [] + try { names = readdirSync(dir) } catch { continue } + for (const n of names) { + if (!/^\d+\.json$/.test(n)) continue + try { + const j = JSON.parse(readFileSync(join(dir, n), "utf8")) + const pid = Number(j?.pid) + const sid = String(j?.sessionId || "") + if (!sid || !pid) continue + const alive = pidAlive(pid) + const prev = bySession.get(sid) + if (!prev || (alive && !prev.alive) || (j.updatedAt || 0) > (prev.updatedAt || 0)) { + bySession.set(sid, { pid, alive, sessionId: sid, cwd: j.cwd || "", entrypoint: j.entrypoint || "cli", hostSessionId: j.hostSessionId || "", updatedAt: j.updatedAt || 0 }) + } + } catch {} + } + } + return bySession + } + + function readDesktopIndex(now) { + if (now - desktopCache.at < 15_000 && desktopCache.map.size > 0) return desktopCache.map + const home = homeDir() + const map = new Map() + for (const appDir of ["Claude-3p", "Claude"]) { + const root = join(home, "Library", "Application Support", appDir, "claude-code-sessions") + if (!existsSync(root)) continue + let l1 = [] + try { l1 = readdirSync(root, { withFileTypes: true }) } catch { continue } + for (const d1 of l1) { + if (!d1.isDirectory()) continue + const p1 = join(root, d1.name) + let l2 = [] + try { l2 = readdirSync(p1, { withFileTypes: true }) } catch { continue } + for (const d2 of l2) { + if (!d2.isDirectory()) continue + const p2 = join(p1, d2.name) + let files = [] + try { files = readdirSync(p2) } catch { continue } + for (const f of files) { + if (!f.startsWith("local_") || !f.endsWith(".json")) continue + try { + const j = JSON.parse(readFileSync(join(p2, f), "utf8")) + if (j?.cliSessionId && j?.sessionId) map.set(String(j.cliSessionId), String(j.sessionId)) + } catch {} + } + } + } + } + desktopCache = { at: now, map } + return map + } + + async function refreshState(now = Date.now(), preferredHost = "herdr-app") { + if (opts.state) return opts.state + if (process.platform !== "darwin") { + const st = { platform: process.platform, liveFiles: new Map(), desktopIdx: new Map(), procs: new Map(), herdrBySession: new Map(), herdrByCwd: new Map(), herdrHosts: [], tmuxByTty: new Map() } + snap = { at: now, state: st, inflight: null } + return st + } + if (snap.inflight) return snap.inflight + snap.inflight = (async () => { + const home = homeDir() + const herdrBin = findBin("herdr", [join(home, ".local", "bin", "herdr")]) + const ottyBin = findBin("otty-cli", ["/Applications/Otty.app/Contents/MacOS/otty-cli"]) + const tmuxBin = findBin("tmux", ["/opt/homebrew/bin/tmux", "/usr/local/bin/tmux"]) + + const [psTxt, herdrTxt, ottyTxt] = await Promise.all([ + runAsync("/bin/ps", ["-axo", "pid=,ppid=,tty=,comm=,args="], 1200), + existsSync(herdrBin) ? runAsync(herdrBin, ["pane", "list"], 1200) : Promise.resolve(""), + existsSync(ottyBin) ? runAsync(ottyBin, ["pane", "list", "--json"], 1000) : Promise.resolve(""), + ]) + + const procs = parsePs(psTxt) + const { bySession: herdrBySession, byCwd: herdrByCwd } = herdrTxt ? parseHerdrPanes(herdrTxt) : { bySession: new Map(), byCwd: new Map() } + + let activeOttyPane = "" + if (ottyTxt) { + try { + const i = ottyTxt.indexOf("{") + if (i >= 0) { + const data = JSON.parse(ottyTxt.slice(i))?.data || [] + activeOttyPane = data.find((x) => x.active && x.process)?.id || data[0]?.id || "" + } + } catch {} + } + + let tmuxByTty = new Map() + const hasTmuxProc = [...procs.values()].some((p) => /\btmux\b/.test(p.comm) || /\btmux\b/.test(p.args)) + if (hasTmuxProc && existsSync(tmuxBin)) { + const [panesTxt, clientsTxt] = await Promise.all([ + runAsync(tmuxBin, ["list-panes", "-a", "-F", "#{pane_id}\t#{pane_tty}\t#{session_name}\t#{window_index}"], 1000), + runAsync(tmuxBin, ["list-clients", "-F", "#{client_tty}\t#{client_pid}\t#{session_name}"], 1000), + ]) + tmuxByTty = parseTmuxPanes(panesTxt, clientsTxt) + } + + const herdrHosts = [] + const seen = new Set() + for (const p of procs.values()) { + if ((p.comm === "herdr" || p.comm.endsWith("/herdr")) && !/\b(server|pane|agent|workspace|tab)\b/.test(p.args)) { + const w = walkAncestors(p.pid, procs) + if (w.app && !seen.has(w.app.id)) { + seen.add(w.app.id) + herdrHosts.push({ id: w.app.id, app: w.app.app, label: w.app.app, bundleId: w.app.bundleId, ottyPane: w.app.id === "otty" ? activeOttyPane : "", tty: w.tty }) + } + } + } + herdrHosts.sort((a, b) => (a.id === preferredHost ? -1 : b.id === preferredHost ? 1 : 0)) + + const st = { + platform: process.platform, + liveFiles: readLiveFiles(), + desktopIdx: readDesktopIndex(now), + procs, + herdrBySession, + herdrByCwd, + herdrHosts, + tmuxByTty, + } + snap = { at: Date.now(), state: st, inflight: null } + onUpdate?.() + return st + })() + return snap.inflight + } + + function resolve(s, now = Date.now(), preferredHost = "herdr-app") { + if (!s) return null + if (opts.state) return resolveTarget(s, opts.state) + if (!snap.state || now - snap.at >= ttl) void refreshState(now, preferredHost) + if (!snap.state) return null + const st = { ...snap.state, liveFiles: readLiveFiles(), desktopIdx: readDesktopIndex(now) } + return resolveTarget(s, st) + } + + function decorate(sessions, now = Date.now(), preferredHost = "herdr-app") { + if (!opts.state && (!snap.state || now - snap.at >= ttl)) void refreshState(now, preferredHost) + if (!Array.isArray(sessions) || !sessions.length) return sessions + const baseState = opts.state || snap.state + if (!baseState) return sessions + const st = opts.state ? baseState : { ...baseState, liveFiles: readLiveFiles(), desktopIdx: readDesktopIndex(now) } + for (const s of sessions) { + const t = resolveTarget(s, st) + if (t) s.target = t + } + return sessions + } + + async function jump(req, dryRun = false) { + const st = opts.state || (await refreshState(Date.now(), req?.preferredHostId || "herdr-app")) + const plan = buildJumpPlan(req, st) + if (!plan.ok || dryRun) return plan + for (const step of plan.steps) await runAsync(step.cmd, step.args, 2000) + return { ...plan, executed: true } + } + + return { resolve, decorate, jump, refreshState } +} diff --git a/packages/agent-office/office.hooks.mjs b/packages/agent-office/office.hooks.mjs index 3843bf8..77c73dc 100644 --- a/packages/agent-office/office.hooks.mjs +++ b/packages/agent-office/office.hooks.mjs @@ -20,6 +20,7 @@ import { dirname, join, resolve } from "node:path" import { fileURLToPath } from "node:url" import { createTracker } from "./lib/track.mjs" import { createScanner } from "./lib/scan.mjs" +import { createJumper } from "./lib/jump.mjs" const here = dirname(fileURLToPath(import.meta.url)) // the page's folder, where live.js goes; a test points this elsewhere so it @@ -43,9 +44,12 @@ const ownDir = (() => { try { return realpathSync(here) } catch { return here } let tracker = null let scanner = null +let jumper = null let timer = null let ticking = null let last = "" +let lastJumpAt = 0 +let lastJumpPromise = null // fail closed: until an install's options are read, or a request carries // them, no prompt, reply or command is written let options = { text: false } @@ -76,6 +80,7 @@ function fromFiles(s, text) { messages: text && Array.isArray(s.messages) ? s.messages.slice(-8) : [], tokensToday: Number(s.tokensToday) || 0, turnsToday: Number(s.turnsToday) || 0, context: Number(s.context) || 0, contextWindow: Number(s.contextWindow) || 0, + target: s.target || null, } } @@ -92,6 +97,7 @@ export function snapshot(now = Date.now()) { sessions.push(fromFiles(s, text)) } } + 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) { @@ -105,6 +111,7 @@ export function snapshot(now = Date.now()) { export function write(now = Date.now()) { timer = null + checkJumpOption() let body try { body = JSON.stringify(snapshot(now)) } catch { return } // only a change is written; the time alone is no change @@ -129,6 +136,11 @@ function soon() { export function start(opts = {}) { options = { ...options, ...opts } if (!scanner) scanner = createScanner({ days: 2, max: 40, ...(opts.scanner || {}) }) + if (!jumper && (opts.jumper || !process.env.MAGPIE_AGENT_OFFICE_PAGE)) { + jumper = createJumper({ onUpdate: soon, ...(opts.jumper || {}) }) + void jumper.refreshState(Date.now(), options.preferredJumpHost || "herdr-app") + } + if (opts.jumpRequest) checkJumpOption(opts.jumpRequest) if (!ticking) { write() ticking = setInterval(write, EVERY) @@ -136,6 +148,14 @@ export function start(opts = {}) { } } +export function jump(req) { + return jumper ? jumper.jump(req) : Promise.resolve({ ok: false, steps: [] }) +} + +export function waitForJump() { + return lastJumpPromise || Promise.resolve(null) +} + export function stop() { if (ticking) clearInterval(ticking) ticking = null @@ -195,8 +215,62 @@ function readOptions() { return null } +function jumpCacheFile() { + const cache = process.env.XDG_CACHE_HOME || join(process.env.HOME || "", ".cache") + return join(cache, "agent-office", "last-jump.json") +} + +function readLastJumpAt() { + try { + const j = JSON.parse(readFileSync(jumpCacheFile(), "utf8")) + return Number(j?.at) > 0 ? Number(j.at) : 0 + } catch { return 0 } +} + +function writeLastJumpAt(at) { + try { + const file = jumpCacheFile() + mkdirSync(dirname(file), { recursive: true }) + writeFileSync(file, JSON.stringify({ at }) + "\n", { mode: 0o600 }) + } catch {} +} + +function checkJumpOption(directReq) { + if (!jumper) return + const standalone = !!process.env.MAGPIE_AGENT_OFFICE_PAGE + // Standalone CLI and tests set MAGPIE_AGENT_OFFICE_PAGE and pass jumpRequest + // explicitly to start(); they must never read or act on magpie's plugins.json. + if (standalone && !directReq) return + const fresh = standalone ? null : readOptions() + if (fresh && typeof fresh.preferredJumpHost === "string") options.preferredJumpHost = fresh.preferredJumpHost + const req = directReq || fresh?.jumpRequest + if (!req || typeof req !== "object") return + const at = Number(req.at || 0) + // magpie restarts the plugin host when options.set writes jumpRequest to + // plugins.json. Keep the last handled timestamp in our own cache file (never + // touching plugins.json) so the freshly started host acts on a ≤15s request + // once and never replays it on later restarts. + if (!at || at <= lastJumpAt || Date.now() - at > 15000) { + if (at > lastJumpAt) { + lastJumpAt = at + if (!standalone) writeLastJumpAt(at) + } + return + } + lastJumpAt = at + if (!standalone) writeLastJumpAt(at) + lastJumpPromise = jumper.jump({ + key: String(req.key || ""), + session: String(req.session || ""), + preferredHostId: String(req.preferredHostId || options.preferredJumpHost || ""), + }) +} + // read what the plugin's options say about text, then start: a host that // loads this module starts watching at once, before any request const loaded = readOptions() if (loaded) options = { text: false, ...loaded } -if (!process.env.MAGPIE_AGENT_OFFICE_PAGE) start() +if (!process.env.MAGPIE_AGENT_OFFICE_PAGE) { + lastJumpAt = readLastJumpAt() + start() +} diff --git a/packages/agent-office/package.json b/packages/agent-office/package.json index d9e1169..95c5ffe 100644 --- a/packages/agent-office/package.json +++ b/packages/agent-office/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/page-agent-office", - "version": "0.2.2", + "version": "0.2.3", "description": "我的 Agent 在干嘛:读取本机 Claude Code、Codex、Copilot CLI、Kimi Code、DeepSeek Harness、Gemini CLI、Qwen Code、Pi、omp、Qoder、WorkBuddy、CodeBuddy、Grok Build 的会话文件,把每个会话画成真 3D / 等距 / 2D 办公室里的小人,或分组工作台。Live agent activity dashboard for magpie, with a real WebGL office and six scenes.", "type": "module", "files": [ diff --git a/packages/agent-office/page/app.js b/packages/agent-office/page/app.js index 1e048fd..64f6bfe 100644 --- a/packages/agent-office/page/app.js +++ b/packages/agent-office/page/app.js @@ -41,6 +41,7 @@ // ignored until this version saves the preference again side: opts.side === true && Number(opts.sideV) === 2, cleared: opts.cleared && typeof opts.cleared === "object" && !Array.isArray(opts.cleared) ? { ...opts.cleared } : {}, + preferredJumpHost: typeof opts.preferredJumpHost === "string" ? opts.preferredJumpHost : "", } let manualLang = opts.lang === "auto" || M.LANG_NAMES[opts.lang] ? opts.lang : "auto" const state = { @@ -183,6 +184,7 @@ e.type = "button" e.dataset.key = a.key e.addEventListener("click", (ev) => { ev.stopPropagation(); open(a.key) }) + e.addEventListener("dblclick", (ev) => { ev.stopPropagation(); const cur = state.list.find((x) => x.key === a.key); if (cur?.target) triggerJump(cur, view.preferredJumpHost, null) }) e.addEventListener("mouseenter", () => highlight(a.key)) e.addEventListener("mouseleave", () => highlight("")) $("tags").append(e) @@ -277,6 +279,12 @@ if (k) open(k) else close() }) + canvas.addEventListener("dblclick", (e) => { + const k = scene.hit(e.offsetX, e.offsetY) + if (!k) return + const a = state.list.find((x) => x.key === k) + if (a?.target) triggerJump(a, view.preferredJumpHost, null) + }) } bindCanvas(office2) bindCanvas(office3) @@ -324,13 +332,15 @@ P.msgs = el("div", "pmsgs") const foot = el("div", "pf") P.meta = el("span", "pm") + P.jumpWrap = el("span", "pjump-wrap") + P.jumpWrap.hidden = true P.copy = el("button", "pc") P.copy.type = "button" P.copy.addEventListener("click", (e) => { e.stopPropagation(); showCommand(P.copy.dataset.value, P.copy) }) P.clear = el("button", "pc") P.clear.type = "button" P.clear.addEventListener("click", (e) => { e.stopPropagation(); clearAgent(P.clear.dataset.key) }) - foot.append(P.meta, P.copy, P.clear) + foot.append(P.meta, P.jumpWrap, P.copy, P.clear) P.src = el("div", "psrc") panel.replaceChildren(head, P.title, P.status, P.query, P.step, P.err, P.reply, P.ctx, P.convoHead, P.msgs, foot, P.src) })() @@ -388,6 +398,37 @@ setText(P.convoHead, msgs.length ? w.recent : "") renderMessages(msgs) setText(P.meta, [a.model, a.project].filter(Boolean).join(" · ")) + const target = a.target + const targetLabel = target?.label || target?.badge || target?.app || "" + if (target && targetLabel) { + P.jumpWrap.hidden = false + const paneId = target.paneId || target.herdrPane || target.tmuxPane || "" + const rawHosts = Array.isArray(target.hosts) && target.hosts.length > 1 + ? target.hosts + : [{ id: target.hosts?.[0]?.id || target.hostId || "default", label: targetLabel }] + const hosts = rawHosts.map((h) => ({ id: String(h?.id || "default"), label: String(h?.label || h?.app || targetLabel) })) + const sig = `${a.key}|${lang}|${view.preferredJumpHost}|${paneId}|${hosts.map((h) => `${h.id}:${h.label}`).join(",")}` + if (P.jumpWrap.dataset.sig !== sig) { + P.jumpWrap.dataset.sig = sig + P.jumpWrap.replaceChildren(...hosts.map((h, idx) => { + const isPrimary = view.preferredJumpHost ? h.id === view.preferredJumpHost : idx === 0 + const text = idx === 0 && paneId && !h.label.includes(paneId) ? `${h.label} · ${paneId}` : h.label + const btn = el("button", isPrimary ? "pjump" : "pjump alt", M.fill(w.jumpTo, text)) + btn.type = "button" + btn.dataset.label = M.fill(w.jumpTo, text) + btn.title = w.jumpTip + btn.addEventListener("click", (e) => { + e.stopPropagation() + if (hosts.length > 1 && h.id) view.preferredJumpHost = h.id + triggerJump(a, h.id, btn) + }) + return btn + })) + } + } else { + P.jumpWrap.hidden = true + P.jumpWrap.dataset.sig = "" + } const copy = a.resume || a.session P.copy.hidden = !copy const box = P.copy.nextElementSibling @@ -401,7 +442,46 @@ P.clear.dataset.key = a.key setText(P.clear, w.clear) P.clear.title = w.clearTip - setText(P.src, a.source === "files" ? w.fromFiles : w.via) + const baseSrc = a.source === "files" ? w.fromFiles : w.via + setText(P.src, targetLabel ? `${baseSrc} · ${M.fill(w.host, targetLabel)}` : baseSrc) + } + + async function triggerJump(a, hostId, btn) { + const targetLabel = a?.target?.label || a?.target?.badge || a?.target?.app || "" + if (!targetLabel) return + const w = t() + const targetBtn = btn || (!P.jumpWrap.hidden ? P.jumpWrap.querySelector(".pjump") : null) + const orig = targetBtn ? (targetBtn.dataset.label || targetBtn.textContent) : "" + if (targetBtn) { + targetBtn.classList.remove("err") + targetBtn.textContent = M.fill(w.jumpingTo, targetLabel) + } + clearTimeout(saving) + saving = null + try { + const next = { + ...wanted(), + preferredJumpHost: hostId || view.preferredJumpHost || "", + jumpRequest: { + key: a.key, + session: a.session || "", + preferredHostId: hostId || view.preferredJumpHost || "", + at: Date.now(), + }, + } + opts = await magpie.options.set(next) + saved = JSON.stringify(wanted()) + if (targetBtn) setTimeout(() => { if (targetBtn.dataset.label) targetBtn.textContent = orig }, 900) + } catch { + if (targetBtn) { + targetBtn.classList.add("err") + targetBtn.textContent = w.jumpFail + setTimeout(() => { + targetBtn.classList.remove("err") + if (targetBtn.dataset.label) targetBtn.textContent = orig + }, 1600) + } + } } // out of the office until its session moves again; kept in options, only @@ -486,6 +566,7 @@ r.title = el("div", "lt"); r.sub = el("div", "ls"); r.task.append(r.title, r.sub) r.badge = el("span", "badge"); r.st.append(r.badge) tr.addEventListener("click", () => open(a.key)) + tr.addEventListener("dblclick", (e) => { e.stopPropagation(); const cur = state.list.find((x) => x.key === a.key); if (cur?.target) triggerJump(cur, view.preferredJumpHost, null) }) tr.addEventListener("keydown", (e) => { if (e.key === "Enter") open(a.key) }) rowsByKey.set(a.key, r) } @@ -581,6 +662,7 @@ row.append(st) row.title = `${a.brand.name} · ${label(a)}` row.addEventListener("click", (e) => { e.stopPropagation(); open(a.key) }) + row.addEventListener("dblclick", (e) => { e.stopPropagation(); if (a.target) triggerJump(a, view.preferredJumpHost, null) }) kids.push(row) } } @@ -798,11 +880,13 @@ let saved = JSON.stringify(opts) const textOn = () => $("optText").checked function wanted() { + const base = { ...opts } + delete base.jumpRequest return { - ...opts, 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, 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 }, + cleared: { ...view.cleared }, preferredJumpHost: view.preferredJumpHost || "", } } function save() { diff --git a/packages/agent-office/page/index.html b/packages/agent-office/page/index.html index b661798..ecad5ec 100644 --- a/packages/agent-office/page/index.html +++ b/packages/agent-office/page/index.html @@ -4,15 +4,15 @@ Agent Office - + - + - +
diff --git a/packages/agent-office/page/model.js b/packages/agent-office/page/model.js index a300ceb..e78485b 100644 --- a/packages/agent-office/page/model.js +++ b/packages/agent-office/page/model.js @@ -447,8 +447,20 @@ "ESTAÇÃO ORBITAL 7" ] } + const JUMP_TEXT = { + en: { jumpTo: "↗ {n}", jumpingTo: "↗ Opening {n}…", jumpFail: "Jump failed · try again", host: "Host: {n}", jumpTip: "Focus the terminal tab, pane or app window running this session (or double-click)" }, + "zh-CN": { jumpTo: "↗ {n}", jumpingTo: "↗ 正在切换到 {n}…", jumpFail: "跳转未成功 · 请重试", host: "宿主: {n}", jumpTip: "直接切回该会话所在的终端标签页、分屏或桌面窗口(也可双击直接跳转)" }, + "zh-TW": { jumpTo: "↗ {n}", jumpingTo: "↗ 正在切換到 {n}…", jumpFail: "跳轉未成功 · 請重試", host: "宿主: {n}", jumpTip: "直接切回該工作階段所在的終端分頁、分割畫面或桌面視窗(也可雙擊直接跳轉)" }, + ja: { jumpTo: "↗ {n}", jumpingTo: "↗ {n} を開いています…", jumpFail: "移動できませんでした · 再試行", host: "ホスト: {n}", jumpTip: "このセッションを実行中のターミナルタブ・ペイン・ウィンドウに切り替えます(ダブルクリックでも移動)" }, + ko: { jumpTo: "↗ {n}", jumpingTo: "↗ {n} 여는 중…", jumpFail: "이동 실패 · 다시 시도", host: "호스트: {n}", jumpTip: "이 세션이 실행 중인 터미널 탭·패널·창으로 바로 이동합니다 (더블클릭 가능)" }, + es: { jumpTo: "↗ {n}", jumpingTo: "↗ Abriendo {n}…", jumpFail: "No se pudo abrir · reintenta", host: "Host: {n}", jumpTip: "Ir a la pestaña, panel o ventana donde corre esta sesión (o doble clic)" }, + fr: { jumpTo: "↗ {n}", jumpingTo: "↗ Ouverture de {n}…", jumpFail: "Échec · réessayez", host: "Hôte : {n}", jumpTip: "Basculer vers l'onglet, le panneau ou la fenêtre de cette session (ou double-clic)" }, + de: { jumpTo: "↗ {n}", jumpingTo: "↗ Öffne {n}…", jumpFail: "Wechsel fehlgeschlagen · erneut", host: "Host: {n}", jumpTip: "Zum Terminal-Tab, Pane oder Fenster dieser Sitzung wechseln (oder Doppelklick)" }, + pt: { jumpTo: "↗ {n}", jumpingTo: "↗ Abrindo {n}…", jumpFail: "Falha ao abrir · tente novamente", host: "Host: {n}", jumpTip: "Alternar para a aba, painel ou janela onde esta sessão está rodando (ou clique duplo)" }, + } const EXTRA_KEYS = ["sceneOffice", "sceneStation", "sceneCafe", "sceneCastle", "scenePirate", "sceneGraveyard", "qLow", "qMedium", "qHigh", "webglFallback", "you", "venueReading", "venueArcade", "venueMeeting", "venuePingpong", "venueCoffee", "stationSign"] for (const [code, values] of Object.entries(EXTRA_TEXT)) EXTRA_KEYS.forEach((key, i) => { TEXT[code][key] = values[i] }) + for (const [code, map] of Object.entries(JUMP_TEXT)) Object.assign(TEXT[code], map) const LANGS = ["en", "zh-CN", "zh-TW", "ja", "ko", "es", "fr", "de", "pt"] const LANG_NAMES = { en: "English", "zh-CN": "简体中文", "zh-TW": "繁體中文", ja: "日本語", ko: "한국어", @@ -706,7 +718,7 @@ messages: Array.isArray(s.messages) ? s.messages : [], private: s.private === true, noProgress: sub === "noprog" || sub === "stuck", - resume: resume(s), seed: hash(s.key), + resume: resume(s), target: s.target || null, seed: hash(s.key), }) } return out diff --git a/packages/agent-office/page/style.css b/packages/agent-office/page/style.css index d369f4c..41ca2b5 100644 --- a/packages/agent-office/page/style.css +++ b/packages/agent-office/page/style.css @@ -108,6 +108,12 @@ canvas[hidden] { display: none; } .pm { font-family: var(--mono); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .pc { border: 0; background: none; color: #6b7280; cursor: pointer; padding: 0; white-space: nowrap; } .pc:hover { color: #1f2937; text-decoration: underline; } +.pjump-wrap { display: inline-flex; flex-direction: row; align-items: center; gap: 6px; flex-wrap: nowrap; } +.pjump { display: inline-flex; align-items: center; gap: 4px; border: 0; border-radius: 7px; padding: 4px 10px; background: var(--accent, #4f46e5); color: #fff; font: 600 12px/1.3 var(--font); cursor: pointer; white-space: nowrap; transition: opacity .12s; } +.pjump:hover { opacity: .9; } +.pjump.alt { background: rgba(79, 70, 229, .12); color: var(--accent, #4f46e5); font-weight: 600; padding: 4px 8px; } +.pjump.alt:hover { background: rgba(79, 70, 229, .2); } +.pjump.err { background: var(--err, #ef4444); color: #fff; } .pcopy { width: 100%; margin-top: 6px; font: 12px var(--mono); padding: 4px 6px; border: 1px solid #e5e7eb; border-radius: 6px; } .psrc { margin-top: 6px; color: #b0b5bd; font-size: 11.5px; }