Skip to content

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.

Merge main and preserve subagent approval forwarding (W2)

review5a54f0c106b9
diff --cc CLAUDE.md
index 6880a2969,55aea8eb9..50e7af538
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@@ -4685,10 -4829,3 +4829,15 @@@ sessions is a hazard whatever kills it
follow-up note rather than same-PR work — but flag it so it isn't forgotten.
When a change is genuinely desktop-only (native menus, auto-update, Keychain), say so; the
point is to make the call consciously, not to leave the other surfaces to rot.
+
+An unanswered Claude `AskUserQuestion` is correlated by session and tool-use ID in the core
+mirror, independently of its short-lived display stash. Ordinary hooks, subagent activity and
+unrelated transcript results must not clear attention or archive its inbox card. Both shells
+use `recordQuestionResult` for transcript rescue (including Escape/decline), and broadcast the
+mirror's effective event. Keep result IDs through local and SSH tails; a boolean “some tool
+finished” is insufficient. Explicit new user turns, interrupts and session boundaries reset it.
++
++Claude child `PreToolUse`/`PostToolUse`/`PostToolUseFailure` hooks must not drive parent state.
++Child `PermissionRequest` and attention `Notification` hooks still reach needs-you and phone
++approvals, including the raw approval summary and deterministic reply ticket. Keep raw summary
++recording before the child transcript-association guard in both shells.
diff --cc CONTRIBUTING.md
index 069df50eb,ac203f4e4..0ad8f4618
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@@ -691,9 -759,6 +759,17 @@@ Two files, two audiences
invariant that only lives in a commit message is one refactor away from being violated by someone
who never saw it.
+An unanswered Claude `AskUserQuestion` is correlated by session and tool-use ID in the core
+mirror, independently of its short-lived display stash. Ordinary hooks, subagent activity and
+unrelated transcript results must not clear attention or archive its inbox card. Both shells
+use `recordQuestionResult` for transcript rescue (including Escape/decline), and broadcast the
+mirror's effective event. Keep result IDs through local and SSH tails; a boolean “some tool
+finished” is insufficient. Explicit new user turns, interrupts and session boundaries reset it.
+ Managed Codex login terminals are agent-less: core identifies their provider from the saved
+ account list. Before opening one, await `useSettings.getState().flush()` after adding the account.
+ The normal 300 ms coalesced save is too late: an unknown id can launch against the system home.
++
++Claude child `PreToolUse`/`PostToolUse`/`PostToolUseFailure` hooks must not drive parent state.
++Child `PermissionRequest` and attention `Notification` hooks still reach needs-you and phone
++approvals, including the raw approval summary and deterministic reply ticket. Keep raw summary
++recording before the child transcript-association guard in both shells.
diff --cc src/core/agent-status-mirror.ts
index f95cc162b,c052e9c38..b2e468925
--- a/src/core/agent-status-mirror.ts
+++ b/src/core/agent-status-mirror.ts
@@@ -1658,7 -1627,7 +1658,8 @@@ export function ignoreQuestionHook(node
* the line actually changes (raw POSTs are bursty).
*/
export function recordRawToolEvent(nodeId: string, payload: Record<string, unknown>): void {
- if (!nodeId || ignoreQuestionHook(nodeId, payload)) return
- if (!nodeId) return
++ // Approval summaries must reach the phone even when the child transcript is excluded.
++ if (!nodeId || (payload.hook_event_name !== 'PermissionRequest' && ignoreQuestionHook(nodeId, payload))) return
const hook = typeof payload.hook_event_name === 'string' ? payload.hook_event_name : ''
const now = Date.now()
if (hook === 'PreToolUse') {
diff --cc src/core/context-tail.test.ts
index d6d38afda,537ea73ce..7483f7f93
--- a/src/core/context-tail.test.ts
+++ b/src/core/context-tail.test.ts
@@@ -257,27 -257,34 +257,58 @@@ describe('createContextTail — `wholeF
}, 8000)
})
+it('delivers each tool result ID across a torn local transcript read', async () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-question-tail-'))
+ const file = path.join(dir, 'session.jsonl')
+ const onToolResult = vi.fn()
+ const tail = createContextTail(() => {}, { onToolResult })
+ try {
+ fs.writeFileSync(file, '')
+ tail.track('session', file)
+ await new Promise(resolve => setTimeout(resolve, 1200))
+ const line = JSON.stringify({ type: 'user', message: { content: [
+ { type: 'tool_result', tool_use_id: 'other', content: 'ok' },
+ { type: 'tool_result', tool_use_id: 'ask', content: 'User declined to answer questions' }
+ ] } })
+ fs.appendFileSync(file, line.slice(0, 40))
+ await new Promise(resolve => setTimeout(resolve, 1200))
+ expect(onToolResult).not.toHaveBeenCalled()
+ fs.appendFileSync(file, line.slice(40) + '\n')
+ await new Promise(resolve => setTimeout(resolve, 1200))
+ expect(onToolResult.mock.calls).toEqual([['session', 'other'], ['session', 'ask']])
+ } finally {
+ tail.untrack('session')
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
+}, 8000)
+ describe('session-scoped context configuration (#818)', () => {
+ it('overrides even a sonnet guess, isolates equal model ids, and invalidates changed/removed env', async () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'context-env-'))
+ const file = path.join(dir, 'session.jsonl')
+ fs.writeFileSync(file, JSON.stringify({ type: 'assistant', message: { model: 'vendor-sonnet', usage: { input_tokens: 16000 } } }) + '\n')
+ const send = vi.fn()
+ const tail = createContextTail(send)
+ try {
+ tail.track('small', file, 32000)
+ tail.track('large', file, 1048576)
+ await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(2))
+ expect(send.mock.calls.map(([p]) => p)).toEqual(expect.arrayContaining([
+ expect.objectContaining({ sessionId: 'small', windowTokens: 32000, usedPercent: 50, windowSource: 'session-env' }),
+ expect.objectContaining({ sessionId: 'large', windowTokens: 1048576, windowSource: 'session-env' })
+ ]))
+ send.mockClear()
+ tail.track('small', file, 32000)
+ tail.track('small', file) // legacy hook, no new observation
+ expect(send).not.toHaveBeenCalled()
+ tail.replay('small') // renderer reload: preserve observed env
+ expect(send).toHaveBeenCalledWith(expect.objectContaining({ windowTokens: 32000, windowSource: 'session-env' }))
+ tail.track('small', file, 64000)
+ await vi.waitFor(() => expect(send).toHaveBeenLastCalledWith(expect.objectContaining({ sessionId: 'small', windowTokens: 64000 })), { timeout: 1800 })
+ tail.track('small', file, null)
+ await vi.waitFor(() => expect(send).toHaveBeenLastCalledWith(expect.objectContaining({ sessionId: 'small', windowSource: 'estimate' })), { timeout: 1800 })
+ } finally {
+ tail.untrack('small'); tail.untrack('large')
+ fs.rmSync(dir, { recursive: true, force: true })
+ }
+ })
+ })
diff --cc src/core/pending-question.test.ts
index 4904720f7,000000000..e558ccdd3
mode 100644,000000..100644
--- a/src/core/pending-question.test.ts
+++ b/src/core/pending-question.test.ts
@@@ -1,75 -1,0 +1,99 @@@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { normalizeClaude } from '../shared/agents/normalize'
+import { parseToolResultIds } from './context-tail'
+import { _resetForTest, _snapshot, _inboxSnapshot, recordAgentEvent, recordRawToolEvent,
+ recordQuestionResult, ignoreQuestionHook, STASH_MAX_AGE_MS, sweepStaleWorking } from './agent-status-mirror'
+
+function hook(hook_event_name: string, extra: Record<string, unknown> = {}) {
+ const payload = { hook_event_name, session_id: 'parent', ...extra }
+ recordRawToolEvent('node', payload)
+ const event = normalizeClaude({ nodeId: 'node', agentId: 'claude', payload })
+ return event ? recordAgentEvent({ ...event, verified: true }) : null
+}
+function ask(id = 'ask-1') {
+ return hook('PreToolUse', { tool_name: 'AskUserQuestion', tool_use_id: id,
+ tool_input: { questions: [{ question: 'Which?', options: [{ label: 'A' }, { label: 'B' }] }] } })
+}
+beforeEach(() => { _resetForTest(); vi.useFakeTimers(); vi.setSystemTime(100000) })
+afterEach(() => { _resetForTest(); vi.useRealTimers() })
+
+describe('Claude pending question correlation (#821)', () => {
+ it('keeps attention and the inbox open through unrelated and child activity beyond stash freshness', () => {
+ ask()
+ vi.setSystemTime(Date.now() + STASH_MAX_AGE_MS + 1)
+ for (const extra of [{ tool_name: 'Bash' }, { tool_name: 'Read', session_id: 'child' }]) {
+ expect(hook('PreToolUse', extra)?.state).toBe('waiting')
+ }
+ expect(ignoreQuestionHook('node', { session_id: 'child' })).toBe(true)
+ expect(ignoreQuestionHook('node', { session_id: 'parent' })).toBe(false)
+ expect(hook('PreToolUse', { tool_name: 'Bash', agent_id: 'child' })).toBeNull()
+ expect(hook('Stop')?.state).toBe('waiting')
+ expect(hook('Notification', { notification_type: 'permission_prompt' })?.state).toBe('waiting')
+ expect(hook('UserPromptSubmit', { prompt: '<task-notification>done</task-notification>' })?.state).toBe('waiting')
+ sweepStaleWorking(Date.now() + 30 * 60000)
+ expect(_snapshot().node).toMatchObject({ state: 'waiting', sessionId: 'parent' })
+ expect(_inboxSnapshot().events).toHaveLength(1)
+ expect(_inboxSnapshot().events[0].resolved).not.toBe(true)
+ })
+
+ it('matches session and tool ID for hooks, including a delayed answer to an older question', () => {
+ ask()
+ expect(hook('PostToolUse', { tool_name: 'AskUserQuestion', tool_use_id: 'other' })?.state).toBe('waiting')
+ expect(hook('PostToolUse', { tool_name: 'AskUserQuestion', tool_use_id: 'ask-1', session_id: 'child' })?.state).toBe('waiting')
+ expect(hook('PostToolUse', { tool_name: 'AskUserQuestion', tool_use_id: 'ask-1' })?.state).toBe('working')
+ expect(_inboxSnapshot().events[0].resolved).toBe(true)
+ ask('ask-2')
+ expect(hook('PostToolUse', { tool_name: 'AskUserQuestion', tool_use_id: 'ask-1' })?.state).toBe('waiting')
+ })
+
+ it.each(['User declined to answer questions', 'A'])('rescues the matching transcript result: %s', content => {
+ ask()
+ const ids = parseToolResultIds(JSON.stringify({ type: 'user', message: { content: [
+ { type: 'tool_result', tool_use_id: 'unrelated', content: 'ok' },
+ { type: 'tool_result', tool_use_id: 'ask-1', content }
+ ] } }))
+ expect(ids).toEqual(['unrelated', 'ask-1'])
+ expect(recordQuestionResult('node', 'parent', ids[0])).toBeUndefined()
+ expect(recordQuestionResult('node', 'other-session', ids[1])).toBeUndefined()
+ expect(recordQuestionResult('node', 'parent', ids[1])?.state).toBe('working')
+ expect(recordQuestionResult('node', 'parent', ids[1])).toBeUndefined()
+ expect(_inboxSnapshot().events[0].resolved).toBe(true)
+ })
+
+ it.each(['UserPromptSubmit', 'SessionEnd', 'SessionStart', 'Stop'])('allows explicit reset: %s', event => {
+ ask()
+ hook(event, { is_interrupt: true, ...(event === 'SessionStart' ? { session_id: 'new' } : {}) })
+ expect(_snapshot().node.pendingQuestion).toBeUndefined()
+ expect(_inboxSnapshot().events[0].resolved).toBe(true)
+ })
+
+ it('does not let a transcript result dismiss an approval without a tracked question', () => {
+ hook('PermissionRequest', { tool_name: 'Bash' })
+ expect(recordQuestionResult('node', 'parent', 'tool')).toBeUndefined()
+ expect(_snapshot().node.state).toBe('blocked')
+ })
+})
++
++describe('subagent attention forwarding (W2)', () => {
++ it.each(['PreToolUse', 'PostToolUse', 'PostToolUseFailure'])('filters child %s without changing a blocked parent', event => {
++ hook('PermissionRequest', { tool_name: 'Bash' })
++ expect(hook(event, { agent_id: 'child', tool_name: 'Bash' })).toBeNull()
++ expect(_snapshot().node.state).toBe('blocked')
++ })
++
++ it.each(['allow', 'deny'])('forwards a child approval ticket, summary and %s reply', decision => {
++ const approval = { agent_id: 'child', tool_name: 'Bash', tool_input: { command: 'echo child' }, nodeterm_pending_id: 'node-1-1' }
++ expect(hook('PermissionRequest', approval)).toMatchObject({ state: 'blocked', pendingId: 'node-1-1', askKind: 'approval' })
++ expect(_inboxSnapshot().events[0]).toMatchObject({ kind: 'approval', pendingId: 'node-1-1' })
++ expect(_inboxSnapshot().events[0].resolved).not.toBe(true)
++ expect(JSON.stringify(_inboxSnapshot().events[0])).toContain('echo child')
++ expect(hook('PermissionRequest', { ...approval, nodeterm_answered: decision })).toMatchObject({ state: 'working', pendingId: 'node-1-1' })
++ expect(_inboxSnapshot().events[0].resolved).toBe(true)
++ })
++
++ it('forwards child permission notifications and ignores informational notifications', () => {
++ expect(hook('Notification', { agent_id: 'child', notification_type: 'permission_prompt' })?.state).toBe('blocked')
++ expect(hook('Notification', { agent_id: 'child', notification_type: 'auth_success' })).toBeNull()
++ expect(_snapshot().node.state).toBe('blocked')
++ })
++})
diff --cc src/main/index.ts
index 2955d12bf,d8f8d94cb..b1c9bfcb2
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@@ -3129,6 -3135,6 +3128,7 @@@ app.whenReady().then(async () =>
// Runs BEFORE the local/remote split so it covers remote (SSH) nodes too — it needs only
// tool_name/tool_input, never the transcript path the split routes on.
recordRawToolEvent(nodeId, payload)
++ if (ignoreQuestionHook(nodeId, payload)) return
const p = payload as {
hook_event_name?: string
session_id?: string
diff --cc src/main/remote-context-tail.test.ts
index 6fd05c2c1,7b0f88313..3e85ec9cc
--- a/src/main/remote-context-tail.test.ts
+++ b/src/main/remote-context-tail.test.ts
@@@ -1,127 -1,203 +1,220 @@@
- import { describe, expect, it, vi } from 'vitest'
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+ import { execFileSync } from 'node:child_process'
+ import { mkdtempSync, writeFileSync, appendFileSync, rmSync } from 'node:fs'
+ import { tmpdir } from 'node:os'
+ import { join } from 'node:path'
import { createRemoteContextTail } from './remote-context-tail'
- import type { RemoteFileRef } from './remote-ssh/remote-file'
+ import { RemoteFile, 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 cap = 1024 * 1024
+ const ref: RemoteFileRef = { conn: { host: 'fixture', user: 'fixture' }, controlPath: '/unused', path: '/fixture' }
+ const usage = (used: number): string => JSON.stringify({ type: 'assistant', message: { model: 'claude-opus-4-8', usage: { input_tokens: used } } }) + '\n'
+ const notification = (result: string): string => JSON.stringify({ type: 'queue-operation', operation: 'enqueue', content: `<task-notification><tool-use-id>tu</tool-use-id><status>completed</status><result>${result}</result></task-notification>` }) + '\n'
+ const tool = JSON.stringify({ type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: 'tu', content: 'done' }] } }) + '\n'
+ function harness(remote: Pick<RemoteFile, 'readContextWindow'>) {
+ const send = vi.fn(), onTaskNotification = vi.fn(), onToolResult = vi.fn()
+ const tail = createRemoteContextTail({ isDestroyed: () => false, webContents: { send } } as never, remote as RemoteFile, { onTaskNotification, onToolResult })
+ return { tail, send, onTaskNotification, onToolResult }
}
+ const flush = async (): Promise<void> => { await vi.advanceTimersByTimeAsync(0) }
- const tick = (): Promise<void> => new Promise((r) => setTimeout(r, 30))
+ beforeEach(() => vi.useFakeTimers())
+ afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks() })
- 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 }))
+ describe('remote context polling', () => {
+ it('backs off failures to 60s, logs no remote error content, and recovers at the same offset', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const readContextWindow = vi.fn().mockRejectedValue(new Error('SECRET transcript'))
+ const h = harness({ readContextWindow })
+ h.tail.track('s', ref)
+ await flush()
+ for (const delay of [2000, 4000, 8000, 16000, 32000, 60000, 60000]) {
+ const calls = readContextWindow.mock.calls.length
+ await vi.advanceTimersByTimeAsync(delay - 1000)
+ expect(readContextWindow).toHaveBeenCalledTimes(calls)
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(readContextWindow).toHaveBeenCalledTimes(calls + 1)
}
- 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')
+ expect(warn.mock.calls.flat().join()).not.toContain('SECRET')
+ readContextWindow.mockResolvedValue({ data: Buffer.from(usage(120)), start: 0, newOffset: 200, initial: true })
+ await vi.advanceTimersByTimeAsync(60000)
+ expect(h.send.mock.calls.at(-1)?.[1].usedTokens).toBe(120)
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(readContextWindow).toHaveBeenLastCalledWith(ref, 200, cap)
+ h.tail.untrack('s')
})
- 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('serializes reads and ignores detached or replaced in-flight snapshots', async () => {
+ let finish!: (value: unknown) => void
+ const readContextWindow = vi.fn(() => new Promise(resolve => { finish = resolve }))
+ const h = harness({ readContextWindow } as never)
+ h.tail.track('s', ref)
+ const oldFinish = finish
+ await vi.advanceTimersByTimeAsync(3000)
+ expect(readContextWindow).toHaveBeenCalledTimes(1)
+ h.tail.track('s', { ...ref, controlPath: '/new-owner' })
+ oldFinish({ data: Buffer.from(usage(100)), newOffset: 100, initial: true })
+ await flush()
+ expect(h.send).not.toHaveBeenCalled()
+ h.tail.untrack('s')
+ finish({ data: Buffer.from(usage(200)), newOffset: 200, initial: true })
+ await flush()
+ expect(h.send).not.toHaveBeenCalled()
})
+ })
- it('fires onTaskNotification for a <task-notification> line in the remote transcript', async () => {
- const { win } = fakeWin()
- const notif = JSON.stringify({
- type: 'queue-operation',
- operation: 'enqueue',
- content: '<task-notification>\n<tool-use-id>tu-remote</tool-use-id>\n<status>completed</status>\n<result>remote done</result>\n</task-notification>'
+ describe.skipIf(process.platform === 'win32')('real POSIX shell transcript fixture (no SSH/session access)', () => {
+ let dir: string
+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'nt-transcript-')) })
+ afterEach(() => rmSync(dir, { recursive: true, force: true }))
+ function fixture(initial: string | Buffer) {
+ const path = join(dir, "transcript ' fixture.jsonl")
+ writeFileSync(path, initial)
+ const transfers: number[] = []
+ const reader = new RemoteFile(async args => {
+ const stdout = execFileSync('/bin/sh', ['-c', args.at(-1)!], { encoding: 'utf8', maxBuffer: 2 * cap })
+ transfers.push(Buffer.byteLength(stdout))
+ return { code: 0, stdout }
})
- let served = false
- const remoteFile = {
- readTail: vi.fn(async () => line(10, 'claude-opus-4-8') + '\n'),
- readFrom: vi.fn(async (_r: RemoteFileRef, o: number) => {
- if (served) return { text: '', newOffset: o }
- served = true
- return { text: notif + '\n', newOffset: o + Buffer.byteLength(notif + '\n') }
- })
- }
- const onTaskNotification = vi.fn()
- const tail = createRemoteContextTail(win, remoteFile as never, { onTaskNotification })
- tail.track('sess4', ref)
- await new Promise((r) => setTimeout(r, 1200)) // first read + one poll tick
- expect(onTaskNotification).toHaveBeenCalledTimes(1)
- expect(onTaskNotification.mock.calls[0][0]).toBe('sess4')
- expect(onTaskNotification.mock.calls[0][1]).toMatchObject({ toolUseId: 'tu-remote', result: 'remote done' })
- tail.untrack('sess4')
- }, 5000)
+ const read = vi.spyOn(reader, 'readContextWindow')
+ const h = harness(reader)
+ h.tail.track('s', { ...ref, path })
+ return { ...h, path, transfers, read }
+ }
- it('only pushes again when the usage changes', async () => {
- const { win, send } = fakeWin()
- // Realistic JSONL: records are newline-terminated (the tail carries a torn trailing
- // line into the next read, so un-delimited records would garble on purpose).
- let nextFrom = line(200, 'claude-opus-4-8') + '\n'
- const remoteFile = {
- readTail: vi.fn(async () => line(100, 'claude-opus-4-8') + '\n'),
- 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')
+ it('bounds transfer for an idle >20 MiB file, starts at EOF, and never replays historical events', async () => {
+ const history = notification('historical') + tool + usage(100)
+ const content = Buffer.concat([Buffer.alloc(20 * cap, 10), Buffer.from(history)])
+ const h = fixture(content)
+ await flush()
+ await expect(h.read.mock.results[0].value).resolves.toHaveProperty('newOffset', content.length)
+ expect(h.send.mock.calls.at(-1)?.[1].usedTokens).toBe(100)
+ expect(h.transfers[0]).toBeLessThan(1.6 * cap)
+ await vi.advanceTimersByTimeAsync(5000)
+ expect(h.read.mock.calls.slice(1).every(c => c[1] === content.length)).toBe(true)
+ expect(h.transfers.slice(1).every(n => n < 100)).toBe(true)
+ expect(h.onTaskNotification).not.toHaveBeenCalled()
+ expect(h.onToolResult).not.toHaveBeenCalled()
+ expect(h.send).toHaveBeenCalledTimes(1)
+
+ // Position the cap in the middle of a UTF-8 character inside a new notification.
+ const event = Buffer.from(notification('yeni é 🐈'))
+ const split = event.indexOf(Buffer.from('é')) + 1
+ appendFileSync(h.path, Buffer.concat([Buffer.alloc(cap - split, 10), event, Buffer.from(tool + usage(200)), Buffer.alloc(18 * cap, 10)]))
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(h.onTaskNotification).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(h.onTaskNotification).toHaveBeenCalledExactlyOnceWith('s', expect.objectContaining({ result: 'yeni é 🐈' }))
- expect(h.onToolResult).toHaveBeenCalledExactlyOnceWith('s')
++ expect(h.onToolResult).toHaveBeenCalledExactlyOnceWith('s', 'tu')
+ expect(h.send.mock.calls.at(-1)?.[1].usedTokens).toBe(200)
+ expect(h.transfers.every(n => n < 1.6 * cap)).toBe(true)
+ await vi.advanceTimersByTimeAsync(2000)
+ expect(h.onTaskNotification).toHaveBeenCalledTimes(1)
+ h.tail.untrack('s')
+ })
+
+ it('suppresses historical torn lines, resets after truncation, and handles an initially empty file', async () => {
+ const h = fixture('')
+ await flush()
+ appendFileSync(h.path, notification('fresh') + usage(10))
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(h.onTaskNotification).toHaveBeenCalledTimes(1)
+ const torn = notification('old').trimEnd()
+ writeFileSync(h.path, torn.slice(0, -5))
+ await vi.advanceTimersByTimeAsync(1000)
+ appendFileSync(h.path, torn.slice(-5) + '\n' + notification('next'))
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(h.onTaskNotification.mock.calls.map(c => c[1].result)).toEqual(['fresh', 'next'])
+ h.tail.untrack('s')
})
})
- it('passes SSH transcript result IDs to the correlated answer consumer', async () => {
- const { win } = fakeWin()
- const onToolResult = vi.fn()
+ describe('session windows with bounded remote reads', () => {
+ it('updates and removes the override without new bytes, replaying only on request', async () => {
+ const readContextWindow = vi.fn()
+ .mockResolvedValue({ data: Buffer.alloc(0), newOffset: 200, initial: false })
+ .mockResolvedValueOnce({ data: Buffer.from(usage(16000)), newOffset: 200, initial: true })
+ const { tail, send } = harness({ readContextWindow })
+ try {
+ tail.track('env', ref, 32000)
+ await flush()
+ expect(send.mock.calls.at(-1)![1]).toMatchObject({ windowTokens: 32000, usedPercent: 50, windowSource: 'session-env' })
+ tail.track('env', { ...ref, conn: { ...ref.conn } }, 32000)
+ tail.track('env', ref)
+ await vi.advanceTimersByTimeAsync(1000)
+ expect(send).toHaveBeenCalledTimes(1)
+ tail.replay('env')
+ expect(send).toHaveBeenCalledTimes(2)
+ expect(send.mock.calls.at(-1)![1]).toMatchObject({ windowTokens: 32000, windowSource: 'session-env' })
+ tail.track('env', ref, 64000)
+ await flush()
+ expect(send.mock.calls.at(-1)![1]).toMatchObject({ windowTokens: 64000, usedPercent: 25, windowSource: 'session-env' })
+ tail.track('env', ref, null)
+ await flush()
+ const estimate = send.mock.calls.at(-1)![1].windowTokens
+ expect(send.mock.calls.at(-1)![1]).toMatchObject({ windowSource: 'estimate' })
+ // Even when the denominator is unchanged, the observation's provenance must update.
+ tail.track('env', ref, estimate)
+ await flush()
+ expect(send.mock.calls.at(-1)![1]).toMatchObject({ windowTokens: estimate, windowSource: 'session-env' })
+ expect(readContextWindow.mock.calls.slice(1).every(c => c[1] === 200)).toBe(true)
+ } finally { tail.untrack('env') }
+ })
+
+ it.each([
+ { ...ref, path: '/abs/new.jsonl' },
+ { ...ref, controlPath: '/new-owner' },
+ { ...ref, conn: { ...ref.conn, host: 'new-host' } }
+ ])('replaces the generation for changed reference %j, rejecting stale reads', async replacement => {
+ let finishOld!: (value: unknown) => void
+ const readContextWindow = vi.fn()
+ .mockImplementationOnce(() => new Promise(resolve => { finishOld = resolve }))
+ .mockResolvedValue({ data: Buffer.from(usage(16000)), newOffset: 200, initial: true })
+ const { tail, send } = harness({ readContextWindow })
+ try {
+ tail.track('replaced', ref, 32000)
+ tail.track('replaced', replacement)
+ await flush()
+ expect(readContextWindow).toHaveBeenLastCalledWith(replacement, null, cap)
+ expect(send).toHaveBeenCalledTimes(1)
+ expect(send.mock.calls[0][1]).toMatchObject({ usedTokens: 16000, windowSource: 'estimate' })
+ finishOld({ data: Buffer.from(usage(1)), newOffset: 100, initial: true })
+ await flush()
+ tail.replay('replaced')
+ expect(send).toHaveBeenCalledTimes(2)
+ expect(send.mock.calls.at(-1)![1]).toMatchObject({ usedTokens: 16000, windowSource: 'estimate' })
+ } finally { tail.untrack('replaced') }
+ })
+
+ it('applies the latest window when an existing read completes', async () => {
+ let finish!: (value: unknown) => void
+ const readContextWindow = vi.fn(() => new Promise(resolve => { finish = resolve }))
+ const { tail, send } = harness({ readContextWindow } as never)
+ try {
+ tail.track('s', ref, 32000)
+ tail.track('s', ref, 64000)
+ expect(readContextWindow).toHaveBeenCalledTimes(1)
+ finish({ data: Buffer.from(usage(16000)), newOffset: 200, initial: true })
+ await flush()
+ expect(send).toHaveBeenCalledTimes(1)
+ expect(send.mock.calls[0][1]).toMatchObject({ windowTokens: 64000, windowSource: 'session-env' })
+ } finally { tail.untrack('s') }
+ })
+ })
++
++it('passes only live SSH result IDs to the correlated answer consumer', async () => {
+ const result = (id: string) => JSON.stringify({ type: 'user', message: { content: [
+ { type: 'tool_result', tool_use_id: id, content: 'User declined to answer questions' }
- ] } })
- const remoteFile = {
- readTail: vi.fn(async () => line(50, 'claude-haiku') + '\n'),
- readFrom: vi.fn(async (_r: RemoteFileRef, o: number) => {
- const text = result('other') + '\n' + result('ask') + '\n'
- return { text, newOffset: o + Buffer.byteLength(text) }
- })
- }
- const tail = createRemoteContextTail(win, remoteFile as never, { onToolResult })
++ ] } }) + '\n'
++ const readContextWindow = vi.fn()
++ .mockResolvedValueOnce({ data: Buffer.from(result('historical')), start: 0, newOffset: 100, initial: true })
++ .mockResolvedValueOnce({ data: Buffer.from(result('other') + result('ask')), start: 100, newOffset: 300, initial: false })
++ const h = harness({ readContextWindow })
+ try {
- tail.track('session', ref)
- await tick()
- await vi.waitFor(() => expect(onToolResult.mock.calls).toEqual([
- ['session', 'other'], ['session', 'ask']
- ]), { timeout: 2500 })
- } finally {
- tail.untrack('session')
- }
++ h.tail.track('session', ref)
++ await flush()
++ expect(h.onToolResult).not.toHaveBeenCalled()
++ await vi.advanceTimersByTimeAsync(1000)
++ expect(h.onToolResult.mock.calls).toEqual([['session', 'other'], ['session', 'ask']])
++ } finally { h.tail.untrack('session') }
+})
diff --cc src/main/remote-context-tail.ts
index 4ba364b4d,0cca83f99..8a52c5666
--- a/src/main/remote-context-tail.ts
+++ b/src/main/remote-context-tail.ts
@@@ -71,10 -76,13 +76,14 @@@ export function createRemoteContextTail
t.used = latest.used
t.model = latest.model ?? t.model
}
+ // A historical partial line may finish on a later poll; it still must not emit events.
+ const eventLines = historical ? [] : completeLines.slice(t.suppressCarry ? 1 : 0)
+ if (historical) t.suppressCarry = !!t.carry
+ else if (completeLines.length) t.suppressCarry = false
- if (opts?.onToolResult && hasToolResult(eventLines)) opts.onToolResult(sessionId)
+ if (opts?.onToolResult)
- for (const id of parseToolResultIds(completeLines)) opts.onToolResult(sessionId, id)
++ for (const id of parseToolResultIds(eventLines)) opts.onToolResult(sessionId, id)
if (opts?.onTaskNotification) {
- for (const n of parseTaskNotifications(completeLines)) opts.onTaskNotification(sessionId, n)
+ for (const n of parseTaskNotifications(eventLines)) opts.onTaskNotification(sessionId, n)
}
}
diff --cc src/server/agent-status.test.ts
index 278565c0c,f77586e9d..86a9dc370
--- a/src/server/agent-status.test.ts
+++ b/src/server/agent-status.test.ts
@@@ -4,7 -4,7 +4,7 @@@ import os from 'os
import path from 'path'
import { ServerPlatform } from './platform-server'
import { wireAgentStatus } from './agent-status'
--import { _resetForTest } from '../core/agent-status-mirror'
++import { _resetForTest, _inboxSnapshot } from '../core/agent-status-mirror'
import { forgetGrokSession, grokSessionDirFor, readGrokSessionName } from '../core/grok-session'
import {
registerClaudeAccountsSource,
@@@ -135,6 -118,6 +136,20 @@@ describe('wireAgentStatus', () =>
expect('pendingId' in e).toBe(false)
})
++ it('forwards child approval details and ticket without tracking its transcript', () => {
++ const fh = fakeHooks()
++ const context = recTail()
++ wireAgentStatus(platform, { hooks: fh.hooks as never, contextTail: context.tail as never })
++ const payload = { hook_event_name: 'PermissionRequest', agent_id: 'child', session_id: 'parent',
++ transcript_path: '/tmp/child.jsonl', tool_name: 'Bash', tool_input: { command: 'echo child' },
++ nodeterm_pending_id: 'child-ticket' }
++ fh.fireRaw('claude', 'child-node', payload, true)
++ fh.fireNormalized({ ...normalizeClaude({ nodeId: 'child-node', agentId: 'claude', payload }), verified: true })
++ expect(lastAgentStatus()).toMatchObject({ state: 'blocked', pendingId: 'child-ticket', askKind: 'approval' })
++ expect(JSON.stringify(_inboxSnapshot().events)).toContain('echo child')
++ expect(context.calls).toEqual([])
++ })
++
it('broadcasts a genuine approval unchanged (keeps pendingId, askKind approval)', () => {
const fh = fakeHooks()
wireAgentStatus(platform, { hooks: fh.hooks as never })
diff --cc src/server/agent-status.ts
index 647aece10,fcc66008f..ec003f15f
--- a/src/server/agent-status.ts
+++ b/src/server/agent-status.ts
@@@ -348,6 -353,6 +344,7 @@@ export function wireAgentStatus
// Mirror the per-node "what it's doing now" activity line for the phone (mobile-usage-inbox).
// Independent of the transcript-tailing below (no path needed), so it runs first.
recordRawToolEvent(nodeId, payload)
++ if (ignoreQuestionHook(nodeId, payload)) return
const p = payload as {
hook_event_name?: string
session_id?: string
diff --cc src/shared/agents/normalize.ts
index bd36cff79,2d3374ee7..10c0ba06f
--- a/src/shared/agents/normalize.ts
+++ b/src/shared/agents/normalize.ts
@@@ -189,7 -185,6 +189,8 @@@ export function isAsyncSubagentLaunch(r
export function normalizeClaude(env: RawHookEnvelope): NormalizedAgentEvent | null {
const p = env.payload as ClaudePayload
- if (p.agent_id) return null
++ // Child tool activity cannot drive the parent, but permission requests still need a reply.
++ if (p.agent_id && ['PreToolUse', 'PostToolUse', 'PostToolUseFailure'].includes(p.hook_event_name ?? '')) return null
const base = { nodeId: env.nodeId, agentId: env.agentId, sessionId: p.session_id }
// Deterministic hook-reply "answered" signal (docs/hook-reply-approvals.md): the managed hook
// fires this the instant it reads a valid allow/deny answer file — the agent is about to proceed