Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(ssh-p2b): remote context-tail + subagent-tail (async poll) + sshRemoteForNode
enesc16f47d19eea
diff --git a/src/main/pty-manager.ts b/src/main/pty-manager.tsindex 8b6a63585..6c0847ba9 100644--- a/src/main/pty-manager.ts+++ b/src/main/pty-manager.ts@@ -260,6 +260,19 @@ export class PtyManager {return undefined}+ /**+ * The live SSH-remote handle for a node id, if its session is running on a remote host.+ * Used by the remote context/subagent tails to read the node's transcript over the same+ * ControlMaster. Returns undefined for local sessions or unknown nodes.+ */+ sshRemoteForNode(+ nodeId: string+ ): { controlPath: string; conn: import('../shared/ssh').SshConnection } | undefined {+ const s = this.sessionByPersistKey(nodeId)+ if (!s?.sshRemote) return undefined+ return { controlPath: s.sshRemote.controlPath, conn: s.sshRemote.conn }+ }+/** Whether a tmux session for this node id currently exists (server alive + session present). */private tmuxSessionExists(persistKey: string): boolean {if (!this.tmuxPath) return falsediff --git a/src/main/remote-context-tail.test.ts b/src/main/remote-context-tail.test.tsnew file mode 100644index 000000000..864e79278--- /dev/null+++ b/src/main/remote-context-tail.test.ts@@ -0,0 +1,74 @@+import { describe, expect, it, vi } from 'vitest'+import { createRemoteContextTail } from './remote-context-tail'+import type { RemoteFileRef } from './remote-ssh/remote-file'++const ref: RemoteFileRef = { conn: { host: 'h', user: 'u' }, controlPath: '/s', path: '/abs/x.jsonl' }+const line = (used: number, model: string): string =>+ JSON.stringify({ type: 'assistant', message: { model, usage: { input_tokens: used } } })++function fakeWin(): { win: never; send: ReturnType<typeof vi.fn> } {+ const send = vi.fn()+ return { win: { isDestroyed: () => false, webContents: { send } } as never, send }+}++const tick = (): Promise<void> => new Promise((r) => setTimeout(r, 30))++describe('createRemoteContextTail', () => {+ it('reads the remote transcript via readTail and pushes ContextWindowUsage on first usage', async () => {+ const { win, send } = fakeWin()+ const remoteFile = {+ readTail: vi.fn(async () => line(120, 'claude-opus-4-8')),+ readFrom: vi.fn(async (_r: RemoteFileRef, o: number) => ({ text: '', newOffset: o }))+ }+ const tail = createRemoteContextTail(win, remoteFile as never)+ tail.track('sess1', ref)+ await tick()+ expect(remoteFile.readTail).toHaveBeenCalled()+ expect(send).toHaveBeenCalled()+ const [channel, payload] = send.mock.calls.at(-1)!+ expect(channel).toBe('context:update')+ expect(payload).toMatchObject({+ sessionId: 'sess1',+ usedTokens: 120,+ model: 'claude-opus-4-8',+ windowTokens: 1_000_000+ })+ tail.untrack('sess1')+ })++ it('uses readFrom with the advancing offset after the first tail read', async () => {+ const { win } = fakeWin()+ const readFrom = vi.fn(async (_r: RemoteFileRef, o: number) => ({ text: '', newOffset: o + 0 }))+ const remoteFile = {+ readTail: vi.fn(async () => line(50, 'claude-haiku')),+ readFrom+ }+ const tail = createRemoteContextTail(win, remoteFile as never)+ tail.track('sess2', ref)+ await tick()+ expect(remoteFile.readTail).toHaveBeenCalledTimes(1)+ // pathFor exposes the tracked path+ expect(tail.pathFor('sess2')).toBe('/abs/x.jsonl')+ tail.untrack('sess2')+ })++ it('only pushes again when the usage changes', async () => {+ const { win, send } = fakeWin()+ let nextFrom = line(200, 'claude-opus-4-8')+ const remoteFile = {+ readTail: vi.fn(async () => line(100, 'claude-opus-4-8')),+ readFrom: vi.fn(async (_r: RemoteFileRef, o: number) => {+ const text = nextFrom+ nextFrom = ''+ return { text, newOffset: o + Buffer.byteLength(text) }+ })+ }+ const tail = createRemoteContextTail(win, remoteFile as never)+ tail.track('sess3', ref)+ await new Promise((r) => setTimeout(r, 1200)) // first tick (track) + one interval tick+ const usedValues = send.mock.calls.map((c) => c[1].usedTokens)+ expect(usedValues).toContain(100)+ expect(usedValues).toContain(200)+ tail.untrack('sess3')+ })+})diff --git a/src/main/remote-context-tail.ts b/src/main/remote-context-tail.tsnew file mode 100644index 000000000..f4b1b0b30--- /dev/null+++ b/src/main/remote-context-tail.ts@@ -0,0 +1,150 @@+// Remote counterpart of context-tail.ts: tails a Claude transcript .jsonl that lives on a+// REMOTE host (read over the project's ControlMaster via an injected RemoteFile) and pushes+// the IDENTICAL ContextWindowUsage IPC the local tail does — the renderer can't tell remote+// from local. Reuses the pure parser (parseLatestUsage) + model-window resolution from the+// local tail; differs only in being async (the read is an ssh round-trip), so it async-polls+// with a per-session in-flight `reading` flag that skips a tick instead of overlapping reads.+import { type BrowserWindow } from 'electron'+import { IPC } from '../shared/ipc'+import type { ContextWindowUsage } from '../shared/types'+import { cachedWindowFor, resolveModelWindow } from './model-window'+import { parseLatestUsage } from './context-tail'+import type { RemoteFile, RemoteFileRef } from './remote-ssh/remote-file'++const POLL_MS = 1000+// Cap the first read like the local tail: a resumed transcript can be many MB. Only the LATEST+// assistant usage matters, so a tail of the file is enough. Defined locally (not imported) so+// context-tail.ts stays untouched; value mirrors its INITIAL_READ_CAP.+const INITIAL_READ_CAP = 1024 * 1024 // 1 MB++interface Tracked {+ ref: RemoteFileRef+ offset: number+ used: number+ window: number+ model: string | null+ // In-flight guard: a slow ssh read must not overlap with the next tick.+ reading: boolean+ // Last pushed snapshot — a push fires only when one of these changes.+ lastUsed: number+ lastModel: string | null+ lastWindow: number+}++export interface RemoteContextTail {+ track(sessionId: string | undefined, ref: RemoteFileRef | undefined): void+ untrack(sessionId: string | undefined): void+ /** The transcript path currently tracked for a session, if any. */+ pathFor(sessionId: string | undefined): string | undefined+}++export function createRemoteContextTail(win: BrowserWindow, remoteFile: RemoteFile): RemoteContextTail {+ const sessions = new Map<string, Tracked>()+ let timer: ReturnType<typeof setInterval> | null = null++ const push = (sessionId: string, t: Tracked): void => {+ if (win.isDestroyed()) return+ const usedPercent = Math.min(100, Math.max(0, (t.used / t.window) * 100))+ const payload: ContextWindowUsage = {+ sessionId,+ usedTokens: t.used,+ windowTokens: t.window,+ usedPercent,+ model: t.model,+ updatedAt: Date.now()+ }+ win.webContents.send(IPC.contextUpdate, payload)+ }++ // One async read+reconcile pass for a session. Fail-open: RemoteFile already returns empty on+ // error, so a failed read keeps the last value. The `reading` flag skips overlapping ticks.+ const read = async (sessionId: string, t: Tracked): Promise<void> => {+ if (t.reading) return+ t.reading = true+ try {+ if (t.offset === 0) {+ // First read: grab the tail of the (possibly huge) file in one shot. We can't stat the+ // remote size, so advance the offset by the bytes we actually received.+ const text = await remoteFile.readTail(t.ref, INITIAL_READ_CAP)+ t.offset = Buffer.byteLength(text)+ const latest = parseLatestUsage(text)+ if (latest) {+ t.used = latest.used+ t.model = latest.model ?? t.model+ }+ } else {+ const { text, newOffset } = await remoteFile.readFrom(t.ref, t.offset)+ t.offset = newOffset+ if (text) {+ const latest = parseLatestUsage(text)+ if (latest) {+ t.used = latest.used+ t.model = latest.model ?? t.model+ }+ }+ }+ } finally {+ t.reading = false+ }++ // Reconcile the window every pass, same resolution as the local tail.+ if (t.model) void resolveModelWindow(t.model)+ const window = cachedWindowFor(t.model)++ if (t.used > 0 && (t.used !== t.lastUsed || t.model !== t.lastModel || window !== t.lastWindow)) {+ t.window = window+ push(sessionId, t)+ t.lastUsed = t.used+ t.lastModel = t.model+ t.lastWindow = window+ }+ }++ const tick = (): void => {+ for (const [sessionId, t] of sessions) void read(sessionId, t)+ if (!sessions.size && timer) {+ clearInterval(timer)+ timer = null+ }+ }++ return {+ track(sessionId, ref) {+ if (!sessionId || !ref) return+ const existing = sessions.get(sessionId)+ if (existing) {+ if (existing.ref.path !== ref.path) {+ existing.ref = ref+ existing.offset = 0+ }+ return+ }+ const t: Tracked = {+ ref,+ offset: 0,+ used: 0,+ window: 0,+ model: null,+ reading: false,+ lastUsed: 0,+ lastModel: null,+ lastWindow: 0+ }+ sessions.set(sessionId, t)+ void read(sessionId, t) // immediate first value (resumed sessions already have content)+ if (!timer) timer = setInterval(tick, POLL_MS)+ },+ untrack(sessionId) {+ if (!sessionId) return+ sessions.delete(sessionId)+ if (!sessions.size && timer) {+ clearInterval(timer)+ timer = null+ }+ },+ pathFor(sessionId) {+ if (!sessionId) return undefined+ return sessions.get(sessionId)?.ref.path+ }+ }+}diff --git a/src/main/remote-subagent-tail.test.ts b/src/main/remote-subagent-tail.test.tsnew file mode 100644index 000000000..4798eb617--- /dev/null+++ b/src/main/remote-subagent-tail.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it, vi } from 'vitest'+import { createRemoteSubagentTail } from './remote-subagent-tail'+import { formatSubagentChunk } from './subagent-tail'+import type { RemoteFileRef } from './remote-ssh/remote-file'++const ref: RemoteFileRef = { conn: { host: 'h', user: 'u' }, controlPath: '/s', path: '/abs/agent-1.jsonl' }++function fakeWin(): { win: never; send: ReturnType<typeof vi.fn> } {+ const send = vi.fn()+ return { win: { isDestroyed: () => false, webContents: { send } } as never, send }+}++const tick = (): Promise<void> => new Promise((r) => setTimeout(r, 30))++const assistant = (text: string): string =>+ JSON.stringify({ type: 'assistant', message: { content: [{ type: 'text', text }] } })++describe('createRemoteSubagentTail', () => {+ it('streams a formatted chunk over agent:subagent-activity for the toolUseId', async () => {+ const { win, send } = fakeWin()+ const raw = assistant('hello from subagent')+ let served = false+ const remoteFile = {+ readFrom: vi.fn(async (_r: RemoteFileRef, o: number) => {+ if (served) return { text: '', newOffset: o }+ served = true+ return { text: raw + '\n', newOffset: o + Buffer.byteLength(raw + '\n') }+ })+ }+ const tail = createRemoteSubagentTail(win, remoteFile as never)+ tail.track('tool-1', ref)+ await tick()+ expect(send).toHaveBeenCalled()+ const [channel, payload] = send.mock.calls.at(-1)!+ expect(channel).toBe('agent:subagent-activity')+ expect(payload.toolUseId).toBe('tool-1')+ expect(payload.chunk).toContain(formatSubagentChunk(raw + '\n'))+ tail.untrack('tool-1')+ })++ it('does not send when the chunk is empty', async () => {+ const { win, send } = fakeWin()+ const remoteFile = {+ readFrom: vi.fn(async (_r: RemoteFileRef, o: number) => ({ text: '', newOffset: o }))+ }+ const tail = createRemoteSubagentTail(win, remoteFile as never)+ tail.track('tool-2', ref)+ await tick()+ expect(send).not.toHaveBeenCalled()+ tail.untrack('tool-2')+ })+})diff --git a/src/main/remote-subagent-tail.ts b/src/main/remote-subagent-tail.tsnew file mode 100644index 000000000..72adf5959--- /dev/null+++ b/src/main/remote-subagent-tail.ts@@ -0,0 +1,76 @@+// Remote counterpart of subagent-tail.ts: tails a subagent's transcript .jsonl on a REMOTE+// host (read over the project's ControlMaster via an injected RemoteFile) and streams the+// formatted activity-log chunks over the IDENTICAL `agent:subagent-activity` IPC the local+// tail uses ({ toolUseId, chunk }) — the renderer can't tell remote from local. Reuses the+// pure formatter (formatSubagentChunk); differs only in being async (each read is an ssh+// round-trip), so it async-polls with a per-entry in-flight `reading` flag that skips a tick.+//+// Unlike the local tail, the remote transcript path is resolved by the caller (the hook raw-+// listener already learned it), so each entry is tracked directly by its RemoteFileRef.+import { type BrowserWindow } from 'electron'+import { IPC } from '../shared/ipc'+import { formatSubagentChunk } from './subagent-tail'+import type { RemoteFile, RemoteFileRef } from './remote-ssh/remote-file'++const POLL_MS = 1000++interface Tracked {+ ref: RemoteFileRef+ offset: number+ reading: boolean+}++export interface RemoteSubagentTail {+ track(toolUseId: string, ref: RemoteFileRef | undefined): void+ untrack(toolUseId: string): void+}++export function createRemoteSubagentTail(win: BrowserWindow, remoteFile: RemoteFile): RemoteSubagentTail {+ const tracked = new Map<string, Tracked>()+ let timer: ReturnType<typeof setInterval> | null = null++ const send = (toolUseId: string, chunk: string): void => {+ if (chunk && !win.isDestroyed()) win.webContents.send(IPC.agentSubagentActivity, { toolUseId, chunk })+ }++ // One async read+stream pass. Fail-open: RemoteFile returns empty on error. The `reading`+ // flag skips overlapping ticks while a slow ssh read is in flight.+ const readOne = async (toolUseId: string, e: Tracked): Promise<void> => {+ if (e.reading) return+ e.reading = true+ try {+ const { text, newOffset } = await remoteFile.readFrom(e.ref, e.offset)+ e.offset = newOffset+ if (text) {+ const out = formatSubagentChunk(text)+ if (out) send(toolUseId, out + '\n')+ }+ } finally {+ e.reading = false+ }+ }++ const tick = (): void => {+ for (const [toolUseId, e] of tracked) void readOne(toolUseId, e)+ if (!tracked.size && timer) {+ clearInterval(timer)+ timer = null+ }+ }++ return {+ track(toolUseId, ref) {+ if (!ref || tracked.has(toolUseId)) return+ tracked.set(toolUseId, { ref, offset: 0, reading: false })+ void readOne(toolUseId, tracked.get(toolUseId)!) // immediate first read+ if (!timer) timer = setInterval(tick, POLL_MS)+ },+ untrack(toolUseId) {+ tracked.delete(toolUseId)+ if (!tracked.size && timer) {+ clearInterval(timer)+ timer = null+ }+ }+ }+}