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
fix(context): integrate bounded SSH reads and explicit ensure replay
review6ccc75e9b470
diff --cc CLAUDE.mdindex a9dc753b7,1943badc1..cedb33f2d--- a/CLAUDE.md+++ b/CLAUDE.md@@@ -1616,21 -1616,19 +1616,36 @@@ else, and its context links must keep cbecause `/quit --delete` exits *and permanently deletes* the session history, i.e. exactly what therestart exists to resume (pinned by its own test).Full picture, measurements, gaps and a device checklist: **`docs/gemini-agent.md`**.+- **Claude session context capacity (#818)** — the managed hook reports only+ `CLAUDE_CODE_MAX_CONTEXT_TOKENS` from the effective Claude process environment (including+ `--settings` env), never the GUI/server process environment. HookServer validates decimal safe+ integers and verified node identity before passing optional `contextWindow` metadata to BOTH+ shells. Missing metadata means an older/unverified hook; explicit null means the current hook+ observed no valid override and clears the old observation. Local and SSH tails apply the exact+ per-session limit before the family estimate, including SMALLER limits; equal model ids do not+ share configuration. The renderer labels family fallbacks as estimates. Claude observations are+ not loaded from localStorage: `context.ensure` rehydrates usage, and until another verified hook+ observes the session env an idle Claude session has only an estimated window. No arbitrary+ endpoint fields, credentials, config-file reads or CLI commands are involved. A changed transcript- starts fresh tracked state; async reads from replaced/untracked entries cannot publish.++ starts fresh tracked state; unchanged hook observations never replay usage. Only `context.ensure`++ explicitly replays the live snapshot for a remounted consumer. Async reads from replaced/untracked++ entries cannot publish.+ Desktop and Server share validation; the SSH tail receives the remote hook's own env. Canvas and+ kanban share ContextMeter. Mobile's separate implementation needs the same provenance distinction.+ Gateway catalogue/accepted-launch work remains in #723/#725; this does not replace those PRs.+ - **SSH context polling is a bounded byte protocol** (issue #816). The initial snapshot reads+ only the last 1 MiB and records the absolute end offset; subsequent polls process at most+ 1 MiB. `core/remote-ssh/transcript-window.ts` measures size and uses block-aligned POSIX `dd`+ with base64, transferring less than 1.6 MiB including alignment/framing; idle replies contain+ only the size/range header. The encoded dd exit status must survive the shell pipeline:+ pipeline success alone can hide a failed read. Short/malformed replies and SSH failures throw,+ retain the cursor, and back off from 2s to 60s with payload-free diagnostics. Bootstrap and+ detected truncation restore usage without replaying historical task notifications/tool results,+ including a historical partial line completed later. A changed remote reference replaces its+ tracking generation so stale in-flight replies cannot publish. Server Edition uses the local+ core tail on its host (no SSH-project manager); mobile has its own direct-SSH implementation,+ so this desktop fix makes no claim about that separate path. Real `/bin/sh` fixtures cover+ >20 MiB idle files and a new notification split inside UTF-8; BSD/macOS SSH remains a device check.- **Context-meter rehydration (`context:ensure`)** — the meter is fed by hook events, and a tmuxsession outlives the app, so a continuing session that is idle after a restart emits nothing andits meter stays blank until the user's next prompt. The mount-time read that exists to close thatdiff --cc CONTRIBUTING.mdindex fb9359ff9,23976fcda..bab35faac--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@@ -611,12 -616,6 +616,15 @@@ examples). If the same effect also WRITmid-session applies stored state to whatever the user is doing right then, which is a differentfeature from the one they asked for.+**A context capacity needs session provenance.** Claude's effective `CLAUDE_CODE_MAX_CONTEXT_TOKENS`+is reported by its managed hook, accepted only with verified node identity, and validated as a+positive decimal safe integer. Never read the app's global env for another session or let a+model-family guess enlarge an observed limit. Unobserved Claude windows are labelled estimates.- The renderer rehydrates through `context.ensure`; it does not restore Claude denominators from storage. Other agents retain transcript-window persistence.++The renderer rehydrates through `context.ensure`; it does not restore Claude denominators from++storage. Other agents retain transcript-window persistence.++Only an explicit ensure replays an unchanged live snapshot; repeated hook observations must not++broadcast it again. Remote path, ControlMaster or connection changes replace the tracked generation.+## Testing`npm test` must pass, and `npm run typecheck` is the fastest gate.diff --cc src/core/context-ensure.test.tsindex d3db94977,d3db94977..dead66594--- a/src/core/context-ensure.test.ts+++ b/src/core/context-ensure.test.ts@@@ -25,6 -25,6 +25,7 @@@ function fakeTail(): ContextTail & { trconst tracked: [string | undefined, string | undefined][] = []return {tracked,++ replay: vi.fn(),track: (sessionId, transcriptPath) => void tracked.push([sessionId, transcriptPath]),untrack: () => {},pathFor: () => undefined@@@ -88,6 -88,6 +89,16 @@@ afterEach(() =>})describe('local rehydration, per agent', () => {++ it('replays a tracked session on each remount without resolving or tracking again', async () => {++ claude.pathFor = () => '/already-tracked.jsonl'++ registerContextEnsureIpc({ tailFor })++ await ensure({ agentId: 'claude' })++ await ensure({ agentId: 'claude' })++ expect(claude.replay).toHaveBeenCalledTimes(2)++ expect(claude.replay).toHaveBeenCalledWith(SID)++ expect(claude.tracked).toEqual([])++ })++it('tracks a claude session on claude’s tail from its own transcript', async () => {const p = writeClaudeTranscript()registerContextEnsureIpc({ tailFor })diff --cc src/core/context-ensure.tsindex 78e4243f1,78e4243f1..cbcbdc3ae--- a/src/core/context-ensure.ts+++ b/src/core/context-ensure.ts@@@ -142,7 -142,7 +142,10 @@@ export function registerContextEnsureIpif (!tail) return// The tail's own path is the authoritative hint for claude's resolver (hook-fed when// present) AND the early-out for everyone: a session already tracked needs no scan.-- if (tail.pathFor(sessionId)) return++ if (tail.pathFor(sessionId)) {++ tail.replay(sessionId)++ return++ }const p = await localTranscriptFor(q, (s) => tail.pathFor(s))if (p) tail.track(sessionId, p)} finally {diff --cc src/core/context-tail.test.tsindex c479ae3f4,2c298bfb7..537ea73ce--- a/src/core/context-tail.test.ts+++ b/src/core/context-tail.test.ts@@@ -256,32 -256,3 +256,35 @@@ describe('createContextTail — `wholeFexpect(JSON.stringify(pushes)).not.toContain('222222')}, 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) // renderer reload: replay while preserving observed env++ 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/context-tail.tsindex 79e7063f3,60990b42a..c6399aaea--- a/src/core/context-tail.ts+++ b/src/core/context-tail.ts@@@ -197,7 -196,7 +197,9 @@@ interface Tracked}export interface ContextTail {- track(sessionId: string | undefined, transcriptPath: string | undefined): void+ track(sessionId: string | undefined, transcriptPath: string | undefined, sessionWindow?: number | null): void++ /** Replay a live snapshot only when a consumer explicitly asks to rehydrate. */++ replay(sessionId: string): voiduntrack(sessionId: string | undefined): void/** The transcript path currently tracked for a session, if any. */pathFor(sessionId: string | undefined): string | undefined@@@ -324,17 -335,14 +326,14 @@@ export function createContextTail}return {- track(sessionId, transcriptPath) {+ track(sessionId, transcriptPath, sessionWindow) {if (!sessionId || !transcriptPath) returnconst existing = sessions.get(sessionId)- if (existing) {- if (existing.path !== transcriptPath) {- existing.path = transcriptPath- existing.offset = 0- existing.carry = null+ if (existing && existing.path === transcriptPath) {+ if (sessionWindow !== undefined && sessionWindow !== existing.sessionWindow) {+ existing.sessionWindow = sessionWindow+ existing.lastWindow = 0 // publish even if only provenance changed+ void read(sessionId, existing)- } else if (existing.used > 0 && existing.lastWindow > 0) {- // A remounted renderer has no persisted snapshot; context.ensure must replay it.- push(sessionId, existing)}return}@@@ -356,6 -363,6 +355,10 @@@void read(sessionId, t) // immediate first value (resumed sessions already have content)if (!timer) timer = setInterval(tick, POLL_MS)},++ replay(sessionId) {++ const t = sessions.get(sessionId)++ if (t && t.used > 0 && t.lastWindow > 0) push(sessionId, t)++ },untrack(sessionId) {if (!sessionId) returnsessions.delete(sessionId)diff --cc src/main/context-ensure-wiring.test.tsindex 75c29f91b,75c29f91b..d8cd88082--- a/src/main/context-ensure-wiring.test.ts+++ b/src/main/context-ensure-wiring.test.ts@@@ -41,6 -41,6 +41,10 @@@ describe('main wires the context-meter})describe('the remote leg keeps the jail and never falls through', () => {++ it('replays the live remote snapshot when a tracked session remounts', () => {++ expect(ensureRemoteBody()).toContain('remoteContextTail.replay(sessionId)')++ })++it('resolves through `remoteTranscriptRefFor`, the one jailed locator', () => {const body = ensureRemoteBody()expect(body).toContain('await remoteTranscriptRefFor(sessionId, cwd, accountId, nodeId)')diff --cc src/main/index.tsindex c76cd3400,6e451993a..d8f8d94cb--- a/src/main/index.ts+++ b/src/main/index.ts@@@ -2664,7 -2664,7 +2664,10 @@@ app.whenReady().then(async () =>// wrong-machine read, which is what falling through would produce.if (agentId && agentId !== 'claude') return 'unresolved'// Already tracked (a hook event landed, or an earlier mount resolved it) — nothing to ask.-- if (remoteContextTail.pathFor(sessionId)) return 'tracked'++ if (remoteContextTail.pathFor(sessionId)) {++ remoteContextTail.replay(sessionId)++ return 'tracked'++ }// Asks the HOST where the transcript is, jails the answer, and caches a HIT under the session// id (shared with the ⌘M read path, which is the locator's first consumer). A clean miss and// a failed ssh call both come back `undefined` and cache NOTHING — so a momentarily deaddiff --cc src/main/remote-context-tail.test.tsindex c70e4db7f,eded37867..7b0f88313--- a/src/main/remote-context-tail.test.ts+++ b/src/main/remote-context-tail.test.ts@@@ -1,139 -1,130 +1,203 @@@- 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.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('uses the remote session env and clears a removed override without new transcript bytes', async () => {- const { win, send } = fakeWin()- const remoteFile = {- readTail: vi.fn(async () => line(16000, 'vendor-sonnet')),- readFrom: vi.fn(async (_r: RemoteFileRef, o: number) => ({ text: '', newOffset: o }))- }- const tail = createRemoteContextTail(win, remoteFile as never)- try {- tail.track('env', ref, 32000)- await vi.waitFor(() => expect(send).toHaveBeenCalled())- expect(send.mock.calls.at(-1)![1]).toMatchObject({ windowTokens: 32000, usedPercent: 50, windowSource: 'session-env' })- tail.track('env', ref, null)- await vi.waitFor(() => expect(send.mock.calls.at(-1)![1]).toMatchObject({ windowSource: 'estimate' }), { timeout: 1800 })- } finally { tail.untrack('env') }+ 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('does not publish a stale async read after replacing the tracked transcript', async () => {- const { win, send } = fakeWin()- let finishOld!: (text: string) => void- const remoteFile = {- readTail: vi.fn((r: RemoteFileRef) => r.path === ref.path- ? new Promise<string>(resolve => { finishOld = resolve })- : Promise.resolve(line(16000, 'new-model'))),- readFrom: vi.fn(async (_r: RemoteFileRef, o: number) => ({ text: '', newOffset: o }))- }- const tail = createRemoteContextTail(win, remoteFile as never)- try {- tail.track('replaced', ref, 32000)- tail.track('replaced', { ...ref, path: '/abs/new.jsonl' })- await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1))- expect(send.mock.calls[0][1]).toMatchObject({ model: 'new-model', windowSource: 'estimate' })- finishOld(line(1, 'old-model'))- await tick()- expect(send).toHaveBeenCalledTimes(1)- } finally { tail.untrack('replaced') }++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') }++ })+})diff --cc src/main/remote-context-tail.tsindex c852431b9,d43cbfe84..0cca83f99--- a/src/main/remote-context-tail.ts+++ b/src/main/remote-context-tail.ts@@@ -41,7 -43,7 +44,9 @@@ interface Tracked}export interface RemoteContextTail {- track(sessionId: string | undefined, ref: RemoteFileRef | undefined): void+ track(sessionId: string | undefined, ref: RemoteFileRef | undefined, sessionWindow?: number | null): void++ /** Replay a live snapshot only when a consumer explicitly asks to rehydrate. */++ replay(sessionId: string): voiduntrack(sessionId: string | undefined): void/** The transcript path currently tracked for a session, if any. */pathFor(sessionId: string | undefined): string | undefined@@@ -136,23 -145,18 +149,25 @@@ export function createRemoteContextTail}return {- track(sessionId, ref) {+ track(sessionId, ref, sessionWindow) {if (!sessionId || !ref) returnconst existing = sessions.get(sessionId)- if (existing && existing.ref.path === ref.path && existing.ref.controlPath === ref.controlPath) {+ if (existing && existing.ref.path === ref.path &&+ existing.ref.controlPath === ref.controlPath &&- JSON.stringify(existing.ref.conn) === JSON.stringify(ref.conn)) return++ JSON.stringify(existing.ref.conn) === JSON.stringify(ref.conn)) {+ if (sessionWindow !== undefined && sessionWindow !== existing.sessionWindow) {+ existing.sessionWindow = sessionWindow+ existing.lastWindow = 0 // publish even if only provenance changed+ void read(sessionId, existing)- } else if (existing.used > 0 && existing.lastWindow > 0) {- // A remounted renderer has no persisted snapshot; context.ensure must replay it.- push(sessionId, existing)+ }+ return+ }const t: Tracked = {ref,- offset: 0,+ offset: null,+ failures: 0,+ retryAt: 0,+ suppressCarry: false,used: 0,window: 0,model: null,@@@ -167,6 -170,6 +182,10 @@@void read(sessionId, t) // immediate first value (resumed sessions already have content)if (!timer) timer = setInterval(tick, POLL_MS)},++ replay(sessionId) {++ const t = sessions.get(sessionId)++ if (t && t.used > 0 && t.lastWindow > 0) push(sessionId, t)++ },untrack(sessionId) {if (!sessionId) returnsessions.delete(sessionId)