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.

fix(context): honor verified Claude session window overrides

enes14ecb6bcb3d3
diff --git a/CLAUDE.md b/CLAUDE.md
index f108819c7..a9dc753b7 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1616,6 +1616,21 @@ else, and its context links must keep classifying across restarts).
because `/quit --delete` exits *and permanently deletes* the session history, i.e. exactly what the
restart 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.
+ 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.
- **Context-meter rehydration (`context:ensure`)** — the meter is fed by hook events, and a tmux
session outlives the app, so a continuing session that is idle after a restart emits nothing and
its meter stays blank until the user's next prompt. The mount-time read that exists to close that
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 0223794bd..fb9359ff9 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -611,6 +611,12 @@ examples). If the same effect also WRITES, latch its first run: otherwise switch
mid-session applies stored state to whatever the user is doing right then, which is a different
feature 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.
+
## Testing
`npm test` must pass, and `npm run typecheck` is the fastest gate.
diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.ts
index c23386d7e..e8528a9c0 100644
--- a/src/core/agents/hook-server.ts
+++ b/src/core/agents/hook-server.ts
@@ -1,3 +1,4 @@
+import { sessionContextWindow } from '../model-window'
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'http'
import { randomUUID, timingSafeEqual } from 'crypto'
import { writeFileSync, mkdirSync, chmodSync, unlinkSync } from 'fs'
@@ -190,6 +191,8 @@ function observedClaudeAccount(
* it. A later task makes the label useful; until then, false must cost a caller nothing.
*/
export interface HookEventMeta {
+ /** undefined: old/unverified client; null: observed env has no valid override. */
+ contextWindow?: number | null
verified: boolean
}
@@ -771,7 +774,12 @@ class HookServer {
if (form.nodeterm_answered) payload.nodeterm_answered = form.nodeterm_answered
// Raw listener first: it drives the transcript-tailing features (which need
// transcript_path). Inside the try so a throwing raw listener still ends 204.
- this.rawListener?.(agentId, nodeId, payload, { verified })
+ this.rawListener?.(agentId, nodeId, payload, {
+ verified,
+ ...(verified && agentId === 'claude' && form.nodeterm_context_window !== undefined
+ ? { contextWindow: sessionContextWindow(form.nodeterm_context_window) }
+ : {})
+ })
// WHICH CLAUDE ACCOUNT this session is on. A third LABEL alongside
// `verified`/`clientRevision`, computed HERE so ONE implementation serves both shells —
// the "both raw listeners change together" rule is sidestepped rather than violated,
diff --git a/src/core/agents/hook-verified-parity.test.ts b/src/core/agents/hook-verified-parity.test.ts
index d83b6a052..d646fa0a6 100644
--- a/src/core/agents/hook-verified-parity.test.ts
+++ b/src/core/agents/hook-verified-parity.test.ts
@@ -29,9 +29,9 @@ const NODE = 'node-verified-1'
let dir = ''
let events: NormalizedAgentEvent[] = []
-let raws: { agentId: string; nodeId: string; meta: { verified: boolean } | undefined }[] = []
+let raws: { agentId: string; nodeId: string; meta: { verified: boolean; contextWindow?: number | null } | undefined }[] = []
-function post(nodeId: string, token?: string): Promise<Response> {
+function post(nodeId: string, token?: string, contextWindow?: string): Promise<Response> {
const headers: Record<string, string> = {
'X-Nodeterm-Hook-Token': hookServer.getToken(),
'content-type': 'application/x-www-form-urlencoded'
@@ -42,7 +42,7 @@ function post(nodeId: string, token?: string): Promise<Response> {
return fetch(`http://127.0.0.1:${hookServer.getPort()}/hook/claude`, {
method: 'POST',
headers,
- body: `nodeId=${encodeURIComponent(nodeId)}&payload=${encodeURIComponent(payload)}`
+ body: `nodeId=${encodeURIComponent(nodeId)}&payload=${encodeURIComponent(payload)}${contextWindow === undefined ? "" : `&nodeterm_context_window=${encodeURIComponent(contextWindow)}`}`
})
}
@@ -239,3 +239,19 @@ describe('both shells register a 4-arg raw listener', () => {
})
}
})
+
+
+describe('session window metadata', () => {
+ it('accepts validated configuration only from this node identity', async () => {
+ await post(NODE, nodeAuthToken(SECRET, NODE), '1048576')
+ expect(raws[0].meta?.contextWindow).toBe(1048576)
+ await post('legacy', undefined, '32000')
+ expect(raws[1].meta?.contextWindow).toBeUndefined()
+ })
+ it('explicitly invalidates missing or malformed current configuration', async () => {
+ for (const value of ['', '0', '1e6', '32000oops']) {
+ await post(NODE, nodeAuthToken(SECRET, NODE), value)
+ expect(raws.at(-1)?.meta?.contextWindow).toBeNull()
+ }
+ })
+})
diff --git a/src/core/agents/hooks/managed-script.test.ts b/src/core/agents/hooks/managed-script.test.ts
index ddd8a1634..d07309fb3 100644
--- a/src/core/agents/hooks/managed-script.test.ts
+++ b/src/core/agents/hooks/managed-script.test.ts
@@ -1172,3 +1172,37 @@ describe('the managed script bail path (issues #186/#187), under /bin/sh', () =>
}
)
})
+
+describe('session context env on the executed hook wire', () => {
+ const shAvailable = spawnSync('sh', ['-c', 'exit 0']).status === 0
+ it.skipIf(!shAvailable)('reports only Claude decimal context env and sends empty to invalidate it', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'hook-context-'))
+ try {
+ const bin = join(dir, 'bin')
+ mkdirSync(bin)
+ const log = join(dir, 'curl.log')
+ writeFileSync(join(bin, 'curl'), fakeCurlScript(log), { mode: 0o755 })
+ const script = join(dir, 'hook.sh')
+ for (const [agent, value, expected] of [
+ ['claude', '1048576', '1048576'],
+ ['claude', '', ''],
+ ['claude', '32000oops', ''],
+ ['claude', '9'.repeat(17), ''],
+ ['codex', '1048576', '']
+ ]) {
+ writeFileSync(script, buildManagedScript(agent, null))
+ await new Promise<void>((resolve, reject) => {
+ const child = spawn('sh', [script], {
+ env: { PATH: `${bin}:${process.env.PATH}`, HOME: dir, NODETERM_NODE_ID: 'fixture', NODETERM_HOOK_PORT: '1', CLAUDE_CODE_MAX_CONTEXT_TOKENS: value },
+ stdio: ['pipe', 'pipe', 'pipe']
+ })
+ child.stdin.on('error', reject)
+ child.on('error', reject)
+ child.on('close', code => code === 0 ? resolve() : reject(new Error(`exit ${code}`)))
+ child.stdin.end('{"hook_event_name":"Stop"}')
+ })
+ expect(curlCalls(log).at(-1)?.argv).toContain(`--data-urlencode nodeterm_context_window=${expected} --data-urlencode`)
+ }
+ } finally { rmSync(dir, { recursive: true, force: true }) }
+ })
+})
diff --git a/src/core/agents/hooks/managed-script.ts b/src/core/agents/hooks/managed-script.ts
index 2917a7c08..43b4bfa9e 100644
--- a/src/core/agents/hooks/managed-script.ts
+++ b/src/core/agents/hooks/managed-script.ts
@@ -184,6 +184,15 @@ export function buildManagedScript(
NODE_TOKEN_READ_SH,
'nt_read_node_token',
HOOK_CURL_HEADERS_SH,
+ // Report the effective Claude process env, including env from --settings. Always send
+ // an empty value too: removing an override must invalidate a prior observation.
+ ...(agentId === 'claude'
+ ? [
+ 'nt_context_window="$CLAUDE_CODE_MAX_CONTEXT_TOKENS"',
+ 'case "$nt_context_window" in *[!0-9]*) nt_context_window="" ;; esac',
+ '[ "${#nt_context_window}" -le 16 ] || nt_context_window=""'
+ ]
+ : ['nt_context_window=""']),
'payload=$(cat)',
'if [ -z "$payload" ]; then',
' exit 0',
@@ -278,6 +287,7 @@ export function buildManagedScript(
' -H "Content-Type: application/x-www-form-urlencoded" \\',
' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',
' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',
+ ' --data-urlencode "nodeterm_context_window=${nt_context_window}" \\',
' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',
' --data-urlencode "payload@${nt_payload_arg}" >/dev/null 2>&1',
' elif [ -n "$NODETERM_HOOK_PORT" ]; then',
@@ -287,6 +297,7 @@ export function buildManagedScript(
' -H "Content-Type: application/x-www-form-urlencoded" \\',
' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',
' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',
+ ' --data-urlencode "nodeterm_context_window=${nt_context_window}" \\',
' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',
' --data-urlencode "payload@${nt_payload_arg}" >/dev/null 2>&1',
' else',
@@ -379,6 +390,7 @@ export function buildManagedScript(
' -H "Content-Type: application/x-www-form-urlencoded" \\',
' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',
' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',
+ ' --data-urlencode "nodeterm_context_window=${nt_context_window}" \\',
' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',
' --data-urlencode "nodeterm_answered=${nt_decision}" \\',
' --data-urlencode "payload@${nt_payload_arg}" >/dev/null 2>&1; rm -f "$nt_payload_file" 2>/dev/null || :; } &',
@@ -390,6 +402,7 @@ export function buildManagedScript(
' -H "Content-Type: application/x-www-form-urlencoded" \\',
' --data-urlencode "nodeId=${NODETERM_NODE_ID}" \\',
' --data-urlencode "version=${NODETERM_HOOK_VERSION}" \\',
+ ' --data-urlencode "nodeterm_context_window=${nt_context_window}" \\',
' --data-urlencode "nodeterm_pending_id=${nt_pending}" \\',
' --data-urlencode "nodeterm_answered=${nt_decision}" \\',
' --data-urlencode "payload@${nt_payload_arg}" >/dev/null 2>&1; rm -f "$nt_payload_file" 2>/dev/null || :; } &',
diff --git a/src/core/context-tail.test.ts b/src/core/context-tail.test.ts
index 2c298bfb7..c479ae3f4 100644
--- a/src/core/context-tail.test.ts
+++ b/src/core/context-tail.test.ts
@@ -256,3 +256,32 @@ describe('createContextTail — `wholeFile` (grok: a document rewritten, not app
expect(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
+ 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 --git a/src/core/context-tail.ts b/src/core/context-tail.ts
index 60990b42a..79e7063f3 100644
--- a/src/core/context-tail.ts
+++ b/src/core/context-tail.ts
@@ -4,7 +4,7 @@
// as ContextWindowUsage keyed by sessionId.
import fs from 'fs'
import type { ContextWindowUsage } from '../shared/types'
-import { cachedWindowFor, resolveModelWindow } from './model-window'
+import { cachedWindowFor } from './model-window'
import { splitCompleteLines } from './subagent-tail'
const POLL_MS = 1000
@@ -179,6 +179,7 @@ interface Tracked {
lastUsed: number
lastModel: string | null
lastWindow: number
+ sessionWindow: number | null
/** An async read is in flight — the next tick skips this session instead of double-reading. */
reading: boolean
/**
@@ -196,7 +197,7 @@ interface Tracked {
}
export interface ContextTail {
- track(sessionId: string | undefined, transcriptPath: string | undefined): void
+ track(sessionId: string | undefined, transcriptPath: string | undefined, sessionWindow?: number | null): void
untrack(sessionId: string | undefined): void
/** The transcript path currently tracked for a session, if any. */
pathFor(sessionId: string | undefined): string | undefined
@@ -223,6 +224,7 @@ export function createContextTail(
windowTokens: t.window,
usedPercent,
model: t.model,
+ windowSource: customParse ? 'transcript' : t.sessionWindow === null ? 'estimate' : 'session-env',
updatedAt: Date.now()
}
send(payload)
@@ -291,24 +293,11 @@ export function createContextTail(
}
}
- // Reconcile the window every tick: kick off async API resolution once per model
- // (self-gating), and use the best cached/static value now.
- if (t.model) void resolveModelWindow(t.model)
- // Whose number is the denominator: the transcript's own when the agent states one, else
- // claude's model-family inference.
- //
- // `cachedWindowFor` is CLAUDE's inference and is consulted only on claude's path (no custom
- // parser). It always answers a number — DEFAULT_WINDOW (200k) for anything it doesn't
- // recognize — so handing it "gpt-5.6-sol" or "gemini-3.5-flash" would not fail, it would
- // confidently return the wrong denominator. A custom parser that could not state a window
- // therefore yields `null`, and null pushes NOTHING (the guard below): a meter is a
- // percentage, and a used count over a guessed denominator is worse than no meter at all.
- //
- // Claude's path is unchanged by construction: no custom parser ⇒ `cachedWindowFor(t.model)`
- // exactly as before, always > 0, so the added guard can never fire for it.
- const win = customParse ? t.parsedWindow : cachedWindowFor(t.model)
+ // The observed session env outranks model-family estimates, even when it is smaller.
+ // Custom parsers own their denominator and never inherit Claude configuration.
+ const win = customParse ? t.parsedWindow : t.sessionWindow ?? cachedWindowFor(t.model)
- if (!sessions.has(sessionId)) return // untracked while this async read was in flight
+ if (sessions.get(sessionId) !== t) return // untracked while this async read was in flight
if (
t.used > 0 &&
win !== null &&
@@ -335,14 +324,17 @@ export function createContextTail(
}
return {
- track(sessionId, transcriptPath) {
+ track(sessionId, transcriptPath, sessionWindow) {
if (!sessionId || !transcriptPath) return
const 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
}
@@ -355,6 +347,7 @@ export function createContextTail(
lastUsed: 0,
lastModel: null,
lastWindow: 0,
+ sessionWindow: sessionWindow ?? null,
reading: false,
carry: null,
parsedWindow: null
diff --git a/src/core/model-window.test.ts b/src/core/model-window.test.ts
new file mode 100644
index 000000000..c80dd27d7
--- /dev/null
+++ b/src/core/model-window.test.ts
@@ -0,0 +1,12 @@
+import { describe, expect, it } from 'vitest'
+import { sessionContextWindow } from './model-window'
+
+describe('sessionContextWindow', () => {
+ it('accepts the session override without rounding to a model family window', () => {
+ expect(sessionContextWindow('1048576')).toBe(1_048_576)
+ expect(sessionContextWindow('32768')).toBe(32_768)
+ })
+ it.each(['', '0', '-1', '1.5', '1e6', '200000junk', 'Infinity', 'NaN', '9007199254740992', ' 32000', undefined, null, 32000])('rejects invalid value %s', value => {
+ expect(sessionContextWindow(value)).toBeNull()
+ })
+})
diff --git a/src/core/model-window.ts b/src/core/model-window.ts
index 7dab263d3..c63acb2de 100644
--- a/src/core/model-window.ts
+++ b/src/core/model-window.ts
@@ -1,4 +1,12 @@
-// Resolves a Claude model id → its context window (max input tokens).
+/** A hook reports only this session's effective env, never nodeterm's global environment.
+ * Decimal safe integers only: reject partial parses, exponents, infinities and zero. */
+export function sessionContextWindow(value: unknown): number | null {
+ if (typeof value !== 'string' || !/^[0-9]{1,16}$/.test(value)) return null
+ const window = Number(value)
+ return Number.isSafeInteger(window) && window > 0 ? window : null
+}
+
+// Legacy Claude model-family ESTIMATES only; session env takes precedence in both tails.
//
// Empirically (verified via `/context` on this machine) Claude Code runs opus/sonnet/fable
// sessions in a 1M window — the model id in the transcript stays bare ("claude-opus-4-8")
@@ -61,11 +69,3 @@ export function geminiWindowFor(model: string | null): number | null {
if (!model) return null
return GEMMA_4_MODELS.has(model) ? GEMINI_GEMMA_4_TOKEN_LIMIT : GEMINI_DEFAULT_TOKEN_LIMIT
}
-
-/**
- * Kept only for call-site compatibility with context-tail.ts. Window resolution is fully
- * synchronous via cachedWindowFor/staticWindowFor, so there is nothing to resolve — no-op.
- */
-export async function resolveModelWindow(_model: string | null): Promise<void> {
- // intentional no-op
-}
diff --git a/src/main/index.ts b/src/main/index.ts
index 6e451993a..c76cd3400 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -2969,11 +2969,7 @@ app.whenReady().then(async () => {
return isSafeRemoteTranscriptPath(abs, remoteHome) ? abs : undefined
}
const SUBAGENT_TOOLS = new Set(['Agent', 'Task'])
- // `meta` carries the per-node `verified` flag and is deliberately UNUSED here: A13 moved
- // enforcement into the hook server, which refuses before a listener is ever called. This shell
- // used to keep a `nodeVerified` map written on every event and read by nothing. The parameter
- // stays because the flag is part of the listener contract and both shells must take it
- // (invariant 4, pinned by hook-verified-parity.test.ts); a second copy of the answer is not.
+ // Hook server validates session-env capacity and caller identity once for both shells.
hookServer.setRawListener((agentId, nodeId, payload, _meta) => {
if (agentId === 'grok') {
// This branch records two associations, neither of which grok's envelope states outright.
@@ -3155,7 +3151,7 @@ app.whenReady().then(async () => {
const transcriptPath = safeRemoteTranscriptPath(p.transcript_path, remoteHome)
if (p.session_id && transcriptPath) {
const ref: RemoteFileRef = { conn: rt.conn, controlPath: rt.controlPath, path: transcriptPath }
- remoteContextTail.track(p.session_id, ref)
+ remoteContextTail.track(p.session_id, ref, _meta.contextWindow)
remoteTranscriptBySession.set(p.session_id, ref)
}
if (nodeId && p.session_id) nodeContextSession.set(nodeId, p.session_id)
@@ -3211,7 +3207,7 @@ app.whenReady().then(async () => {
}
const transcriptPath = safeTranscriptPath(p.transcript_path)
// Context-window meter: tail the session transcript (any event carrying both fields).
- if (p.session_id && transcriptPath) contextTail.track(p.session_id, transcriptPath)
+ if (p.session_id && transcriptPath) contextTail.track(p.session_id, transcriptPath, _meta.contextWindow)
if (nodeId && p.session_id) nodeContextSession.set(nodeId, p.session_id)
if (nodeId && p.session_id && transcriptPath) setNodeTranscript(nodeId, p.session_id, transcriptPath)
if (p.hook_event_name === 'SessionEnd' && p.session_id) contextTail.untrack(p.session_id)
diff --git a/src/main/remote-context-tail.test.ts b/src/main/remote-context-tail.test.ts
index 39a994a61..c70e4db7f 100644
--- a/src/main/remote-context-tail.test.ts
+++ b/src/main/remote-context-tail.test.ts
@@ -100,3 +100,40 @@ describe('createRemoteContextTail', () => {
tail.untrack('sess3')
})
})
+
+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('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') }
+})
diff --git a/src/main/remote-context-tail.ts b/src/main/remote-context-tail.ts
index fb094f8c8..c852431b9 100644
--- a/src/main/remote-context-tail.ts
+++ b/src/main/remote-context-tail.ts
@@ -7,7 +7,7 @@
import { type BrowserWindow } from 'electron'
import { IPC } from '../shared/ipc'
import type { ContextWindowUsage } from '../shared/types'
-import { cachedWindowFor, resolveModelWindow } from '../core/model-window'
+import { cachedWindowFor } from '../core/model-window'
import {
parseLatestUsage,
parseTaskNotifications,
@@ -35,12 +35,13 @@ interface Tracked {
lastUsed: number
lastModel: string | null
lastWindow: number
+ sessionWindow: number | null
/** Partial trailing line held back until the next read completes it (see subagent-tail.ts). */
carry: Buffer | null
}
export interface RemoteContextTail {
- track(sessionId: string | undefined, ref: RemoteFileRef | undefined): void
+ track(sessionId: string | undefined, ref: RemoteFileRef | undefined, sessionWindow?: number | null): void
untrack(sessionId: string | undefined): void
/** The transcript path currently tracked for a session, if any. */
pathFor(sessionId: string | undefined): string | undefined
@@ -86,6 +87,7 @@ export function createRemoteContextTail(
windowTokens: t.window,
usedPercent,
model: t.model,
+ windowSource: t.sessionWindow === null ? 'estimate' : 'session-env',
updatedAt: Date.now()
}
win.webContents.send(IPC.contextUpdate, payload)
@@ -113,9 +115,9 @@ export function createRemoteContextTail(
}
// Reconcile the window every pass, same resolution as the local tail.
- if (t.model) void resolveModelWindow(t.model)
- const window = cachedWindowFor(t.model)
+ const window = t.sessionWindow ?? cachedWindowFor(t.model)
+ if (sessions.get(sessionId) !== t) return
if (t.used > 0 && (t.used !== t.lastUsed || t.model !== t.lastModel || window !== t.lastWindow)) {
t.window = window
push(sessionId, t)
@@ -134,14 +136,17 @@ export function createRemoteContextTail(
}
return {
- track(sessionId, ref) {
+ track(sessionId, ref, sessionWindow) {
if (!sessionId || !ref) return
const existing = sessions.get(sessionId)
- if (existing) {
- if (existing.ref.path !== ref.path) {
- existing.ref = ref
- existing.offset = 0
- existing.carry = null
+ if (existing && existing.ref.path === ref.path && existing.ref.controlPath === ref.controlPath) {
+ 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
}
@@ -155,6 +160,7 @@ export function createRemoteContextTail(
lastUsed: 0,
lastModel: null,
lastWindow: 0,
+ sessionWindow: sessionWindow ?? null,
carry: null
}
sessions.set(sessionId, t)
diff --git a/src/renderer/components/ContextMeter.test.tsx b/src/renderer/components/ContextMeter.test.tsx
new file mode 100644
index 000000000..c53507d61
--- /dev/null
+++ b/src/renderer/components/ContextMeter.test.tsx
@@ -0,0 +1,19 @@
+// @vitest-environment jsdom
+import { expect, it } from 'vitest'
+import { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { ContextMeter } from './ContextMeter'
+import { useContextWindow } from '../state/contextWindow'
+
+it('qualifies model-name guesses but not observed session configuration', async () => {
+ const el = document.createElement('div')
+ const root = createRoot(el)
+ const usage = { sessionId: 's', usedTokens: 16000, windowTokens: 32000, usedPercent: 50, model: 'vendor-sonnet', updatedAt: Date.now() }
+ try {
+ useContextWindow.getState().set({ ...usage, windowSource: 'estimate' })
+ await act(async () => root.render(<ContextMeter sessionId="s" />))
+ expect(el.querySelector('button')?.title).toContain('Estimated context window')
+ await act(async () => { useContextWindow.getState().set({ ...usage, windowSource: 'session-env' }) })
+ expect(el.querySelector('button')?.title).toMatch(/^Context window/)
+ } finally { await act(async () => root.unmount()) }
+})
diff --git a/src/renderer/components/ContextMeter.tsx b/src/renderer/components/ContextMeter.tsx
index 3d10937dc..8ad21fedc 100644
--- a/src/renderer/components/ContextMeter.tsx
+++ b/src/renderer/components/ContextMeter.tsx
@@ -28,13 +28,14 @@ export function ContextMeter({ sessionId }: { sessionId: string | null }): JSX.E
// (issue #78).
const pillText = contextPillText(usage.usedTokens, usage.windowTokens, usage.usedPercent, percentMode)
const color = contextFillColor(usage.usedPercent)
+ const estimated = usage.windowSource === 'estimate'
const modelLabel = formatModelLabel(usage.model)
return (
<div className="ctx-meter nodrag" ref={ref}>
{open && (
<div className="ctx-popover">
- <div className="ctx-popover__title">Context</div>
+ <div className="ctx-popover__title">Context{estimated ? ' (estimated window)' : ''}</div>
<div className="ctx-bar">
<div className="ctx-bar__fill" style={{ width: `${barFillPercent(usage.usedPercent, percentMode)}%`, background: color }} />
</div>
@@ -51,7 +52,7 @@ export function ContextMeter({ sessionId }: { sessionId: string | null }): JSX.E
)}
<button
className="ctx-pill"
- title={`Context window — ${percentText(usage.usedPercent, percentMode)}`}
+ title={`${estimated ? 'Estimated context window' : 'Context window'} — ${percentText(usage.usedPercent, percentMode)}`}
onClick={(e) => {
e.stopPropagation()
setOpen((v) => !v)
@@ -61,7 +62,7 @@ export function ContextMeter({ sessionId }: { sessionId: string | null }): JSX.E
<span className="ctx-pill__bar">
<span className="ctx-pill__fill" style={{ width: `${barFillPercent(usage.usedPercent, percentMode)}%`, background: color }} />
</span>
- <span className="ctx-pill__num">{pillText}</span>
+ <span className="ctx-pill__num">{estimated ? '~' : ''}{pillText}</span>
</button>
</div>
)
diff --git a/src/renderer/components/SessionRow.tsx b/src/renderer/components/SessionRow.tsx
index 10ef19386..1884aa7cb 100644
--- a/src/renderer/components/SessionRow.tsx
+++ b/src/renderer/components/SessionRow.tsx
@@ -164,10 +164,10 @@ export function SessionRow({
{row.usesContext && usage && (
<span
className="ss-ctx"
- title={`Context window — ${percentText(usage.usedPercent, percentMode)}`}
+ title={`${usage.windowSource === 'estimate' ? 'Estimated context window' : 'Context window'} — ${percentText(usage.usedPercent, percentMode)}`}
style={{ background: contextFillColor(usage.usedPercent) }}
>
- {contextPillText(usage.usedTokens, usage.windowTokens, usage.usedPercent, percentMode)}
+ {usage.windowSource === 'estimate' ? '~' : ''}{contextPillText(usage.usedTokens, usage.windowTokens, usage.usedPercent, percentMode)}
</span>
)}
{/* Both buttons are invisible until the row is hovered, yet they used to hold 46px of a
diff --git a/src/renderer/state/contextWindow.test.ts b/src/renderer/state/contextWindow.test.ts
new file mode 100644
index 000000000..a5555eb35
--- /dev/null
+++ b/src/renderer/state/contextWindow.test.ts
@@ -0,0 +1,10 @@
+// @vitest-environment jsdom
+import { expect, it, vi } from 'vitest'
+
+it('does not restore an old denominator from persistent browser state', async () => {
+ localStorage.setItem('nodeterm.contextWindow', JSON.stringify({ old: { sessionId: 'old', windowTokens: 200000 }, claude: { sessionId: 'claude', windowSource: 'session-env', windowTokens: 32000 }, own: { sessionId: 'own', windowSource: 'transcript', windowTokens: 64000 } }))
+ vi.resetModules()
+ const { useContextWindow } = await import('./contextWindow')
+ expect(useContextWindow.getState().bySessionId).toEqual({ own: { sessionId: 'own', windowSource: 'transcript', windowTokens: 64000 } })
+ localStorage.clear()
+})
diff --git a/src/renderer/state/contextWindow.ts b/src/renderer/state/contextWindow.ts
index b4106b27d..54ed4f7a1 100644
--- a/src/renderer/state/contextWindow.ts
+++ b/src/renderer/state/contextWindow.ts
@@ -1,14 +1,9 @@
import { create } from 'zustand'
import type { ContextWindowUsage } from '@shared/types'
-// Per-session context-window fill, fed by context.onUpdate.
-//
-// Persisted to localStorage (like agentStatus' sessionId). Why: after an app restart the
-// node's sessionId is restored, but its tmux Claude session is now idle and emits no new
-// hook event — so the main-process tailer is never re-fed the transcript path and can't
-// re-push until the next prompt. Without persistence the meter would vanish on every restart
-// even though the session (and its fill) is unchanged. We restore the last-known value so the
-// meter survives the restart; the live tailer overwrites it on the next prompt.
+// Claude windows depend on session configuration: rehydrate them through context.ensure,
+// never restore a stale denominator. Agent-owned transcript windows may still be persisted
+// (notably Grok, which cannot locate its signals file until the next hook after restart).
const KEY = 'nodeterm.contextWindow'
// Hard cap on retained sessions. Every resume / `/clear` / restart mints a new sessionId, so
// without a bound the map would grow forever (and we'd re-stringify the whole thing on every
@@ -22,12 +17,17 @@ function load(): Record<string, ContextWindowUsage> {
const raw = localStorage.getItem(KEY)
if (!raw) return {}
const data = JSON.parse(raw) as Record<string, ContextWindowUsage>
- return data && typeof data === 'object' ? prune(data) : {}
+ return data && typeof data === 'object' ? prune(persistable(data)) : {}
} catch {
return {}
}
}
+function persistable(map: Record<string, ContextWindowUsage>): Record<string, ContextWindowUsage> {
+ // Older records have no provenance; invalidate them instead of guessing their agent.
+ return Object.fromEntries(Object.entries(map).filter(([, usage]) => usage?.windowSource === 'transcript'))
+}
+
/** Keep only the MAX_SESSIONS most-recently-updated entries (LRU by updatedAt). */
function prune(map: Record<string, ContextWindowUsage>): Record<string, ContextWindowUsage> {
const keys = Object.keys(map)
@@ -46,7 +46,7 @@ function scheduleSave(bySessionId: Record<string, ContextWindowUsage>): void {
saveTimer = setTimeout(() => {
saveTimer = null
try {
- localStorage.setItem(KEY, JSON.stringify(bySessionId))
+ localStorage.setItem(KEY, JSON.stringify(persistable(bySessionId)))
} catch {
// ignore quota / serialization errors
}
diff --git a/src/server/agent-status.test.ts b/src/server/agent-status.test.ts
index 5e1deb853..f77586e9d 100644
--- a/src/server/agent-status.test.ts
+++ b/src/server/agent-status.test.ts
@@ -22,7 +22,7 @@ function fakeHooks() {
agentId: string,
nodeId: string,
payload: Record<string, unknown>,
- meta: { verified: boolean }
+ meta: { verified: boolean; contextWindow?: number | null }
) => void)
| undefined
return {
@@ -41,8 +41,9 @@ function fakeHooks() {
agentId: string,
nodeId: string,
payload: Record<string, unknown>,
- verified = false
- ) => raw?.(agentId, nodeId, payload, { verified })
+ verified = false,
+ contextWindow?: number | null
+ ) => raw?.(agentId, nodeId, payload, { verified, contextWindow })
}
}
@@ -447,3 +448,18 @@ describe('wireAgentStatus — the grok raw-listener branch', () => {
expect(grokSessionDirFor('gs-5')).toBeUndefined()
})
})
+
+
+it('passes observed session capacity through the Server Edition transcript jail', () => {
+ const fh = fakeHooks()
+ const ctx = recTail()
+ wireAgentStatus(platform, { hooks: fh.hooks as never, contextTail: ctx.tail as never })
+ const transcriptPath = path.join(os.homedir(), '.claude', 'projects', 'capacity.jsonl')
+ fh.fireRaw('claude', 'capacity-node', { session_id: 'capacity', transcript_path: transcriptPath }, true, 32000)
+ expect(ctx.calls).toContainEqual({ m: 'track', args: ['capacity', transcriptPath, 32000] })
+ fh.fireRaw('claude', 'capacity-node', { session_id: 'capacity', transcript_path: transcriptPath }, true, null)
+ expect(ctx.calls).toContainEqual({ m: 'track', args: ['capacity', transcriptPath, null] })
+ const before = ctx.calls.length
+ fh.fireRaw('claude', 'capacity-node', { session_id: 'capacity', transcript_path: '/outside-jail/secret' }, true, 64000)
+ expect(ctx.calls).toHaveLength(before)
+})
diff --git a/src/server/agent-status.ts b/src/server/agent-status.ts
index 7f99e2647..fcc66008f 100644
--- a/src/server/agent-status.ts
+++ b/src/server/agent-status.ts
@@ -39,7 +39,7 @@ export interface HookLike {
agentId: string,
nodeId: string,
payload: Record<string, unknown>,
- meta: { verified: boolean }
+ meta: { verified: boolean; contextWindow?: number | null }
) => void
): void
}
@@ -197,11 +197,7 @@ export function wireAgentStatus(
}
const SUBAGENT_TOOLS = new Set(['Agent', 'Task'])
- // `meta` carries the per-node `verified` flag and is deliberately UNUSED here: A13 moved
- // enforcement into the hook server, which refuses before a listener is ever called. This shell
- // used to keep a `nodeVerified` map written on every event and read by nothing. The parameter
- // stays because the flag is part of the listener contract and both shells must take it
- // (invariant 4, pinned by hook-verified-parity.test.ts); a second copy of the answer is not.
+ // Hook server validates session-env capacity and caller identity once for both shells.
hooks.setRawListener((agentId, nodeId, payload, _meta) => {
if (agentId === 'grok') {
// This branch records two associations, neither of which grok's envelope states outright.
@@ -370,7 +366,7 @@ export function wireAgentStatus(
const asyncLaunch = p.hook_event_name === 'PostToolUse' && isAsyncSubagentLaunch(p.tool_response)
const transcriptPath = safeTranscriptPath(p.transcript_path)
// Context-window meter: tail the session transcript (any event carrying both fields).
- if (p.session_id && transcriptPath) contextTail.track(p.session_id, transcriptPath)
+ if (p.session_id && transcriptPath) contextTail.track(p.session_id, transcriptPath, _meta.contextWindow)
if (nodeId && p.session_id) nodeContextSession.set(nodeId, p.session_id)
if (nodeId && p.session_id && transcriptPath) setNodeTranscript(nodeId, p.session_id, transcriptPath)
if (p.hook_event_name === 'SessionEnd' && p.session_id) contextTail.untrack(p.session_id)
diff --git a/src/shared/types.ts b/src/shared/types.ts
index d05cad046..16d5ac512 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -2608,6 +2608,8 @@ export interface UsageApi {
/** A Claude session's context-window fill, pushed per sessionId from the transcript tailer. */
export interface ContextWindowUsage {
+ /** Missing on older hosts; only session-env is an observed Claude configuration. */
+ windowSource?: 'session-env' | 'transcript' | 'estimate'
sessionId: string
/** input + cache_read + cache_creation tokens of the latest assistant message. */
usedTokens: number