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(handoff): context-budget the transfer file so the target agent survives reading it

enes515a57e4866a
diff --git a/src/main/handoff/budget.test.ts b/src/main/handoff/budget.test.ts
new file mode 100644
index 000000000..3742c9b2f
--- /dev/null
+++ b/src/main/handoff/budget.test.ts
@@ -0,0 +1,89 @@
+import { describe, it, expect } from 'vitest'
+import { budgetHandoff, digestHead, HANDOFF_BODY_BUDGET } from './budget'
+
+/** A rendered transcript in the shape the renderers emit: `## ` messages, `### ` tool blocks. */
+function transcript(messages: number, toolBlocksPer = 2, filler = 400): string {
+ const parts: string[] = []
+ for (let i = 0; i < messages; i++) {
+ const role = i % 2 === 0 ? 'User' : 'Assistant'
+ parts.push(`## ${role}\n\nmessage ${i} ${'x'.repeat(filler)}`)
+ for (let t = 0; t < toolBlocksPer; t++) {
+ parts.push(`### Tool call: Bash\n\n\`\`\`json\n{"cmd":"echo ${i}-${t}"}\n\`\`\``)
+ parts.push('### Tool result\n\n```\nout\n```')
+ }
+ }
+ return parts.join('\n\n')
+}
+
+describe('budgetHandoff', () => {
+ it('passes an under-budget body through untouched', () => {
+ const body = transcript(3)
+ expect(budgetHandoff(body)).toEqual({ body, truncated: false })
+ })
+
+ it('fits an over-budget body inside the budget', () => {
+ const body = transcript(600, 4, 800) // well over the default budget
+ const out = budgetHandoff(body)
+ expect(out.truncated).toBe(true)
+ expect(out.body.length).toBeLessThanOrEqual(HANDOFF_BODY_BUDGET)
+ })
+
+ it('keeps the tail verbatim from a message boundary — the end of the file is the live task', () => {
+ const body = transcript(200, 2, 600)
+ const out = budgetHandoff(body, 40_000)
+ // The final message must appear verbatim.
+ expect(out.body).toContain('message 199 ')
+ // The verbatim region starts at a `## ` message header, never inside a tool block.
+ // (lastIndexOf: the note ABOVE quotes the marker string when explaining the layout.)
+ const marker = out.body.lastIndexOf('VERBATIM FROM HERE')
+ expect(marker).toBeGreaterThan(-1)
+ const after = out.body.slice(marker + 'VERBATIM FROM HERE'.length).trimStart()
+ expect(after.startsWith('## ')).toBe(true)
+ })
+
+ it('digests omitted messages and collapses tool-block runs to counts', () => {
+ // Budget chosen so the digest fits whole: every omitted message keeps its line
+ // (message 0 included) alongside the collapsed tool-run counters.
+ const body = transcript(40, 3, 300)
+ const out = budgetHandoff(body, 20_000)
+ expect(out.truncated).toBe(true)
+ expect(out.body).toContain('## Digest of earlier conversation')
+ expect(out.body).toMatch(/- User: message 0 /)
+ expect(out.body).toMatch(/tool call\/result blocks omitted/)
+ })
+
+ it('references the full-copy path and warns against whole-file reads', () => {
+ const out = budgetHandoff(transcript(200, 2, 600), 40_000, '/tmp/h-full.md')
+ expect(out.body).toContain('/tmp/h-full.md')
+ expect(out.body).toContain('do NOT read it whole')
+ })
+
+ it('hard-cuts when a single trailing message alone exceeds the tail budget', () => {
+ const body = `## User\n\nsmall\n\n## Assistant\n\n${'y'.repeat(100_000)}`
+ const out = budgetHandoff(body, 20_000)
+ expect(out.truncated).toBe(true)
+ expect(out.body.length).toBeLessThanOrEqual(21_000)
+ expect(out.body).toContain('cut mid-message')
+ // The very end is still the end of the conversation.
+ expect(out.body.endsWith('y'.repeat(50))).toBe(true)
+ })
+
+ it('caps a huge digest by dropping the OLDEST lines', () => {
+ const body = transcript(3000, 0, 40)
+ const out = budgetHandoff(body, 30_000)
+ expect(out.body.length).toBeLessThanOrEqual(30_000)
+ expect(out.body).toContain('earliest messages omitted')
+ // Recent digest lines survive; the oldest are gone.
+ expect(out.body).not.toMatch(/- User: message 0 /)
+ })
+})
+
+describe('digestHead', () => {
+ it('is empty for a head with no message boundaries', () => {
+ expect(digestHead('no headers here')).toBe('')
+ })
+ it('one line per message with collapsed whitespace', () => {
+ const d = digestHead('## User\n\nline one\nline two\n\n## Assistant\n\nreply')
+ expect(d.split('\n')).toEqual(['- User: line one line two', '- Assistant: reply'])
+ })
+})
diff --git a/src/main/handoff/budget.ts b/src/main/handoff/budget.ts
new file mode 100644
index 000000000..9a10770e4
--- /dev/null
+++ b/src/main/handoff/budget.ts
@@ -0,0 +1,106 @@
+// Context budget for handoff bodies. The renderers deliberately never truncate, but a long
+// session renders to megabytes — and a target agent that obeys "read the entire file first"
+// walks straight into its own context ceiling, compacts, and forgets the handoff instruction
+// entirely (field report: codex read the file, then reset to "What would you like to work
+// on?"). So the PRIMARY handoff file is kept under a budget the target can actually afford:
+// the most recent conversation verbatim (the live task state is at the end), older messages
+// condensed to one-line digests, and the COMPLETE render preserved next to it for on-demand
+// grep/range reads. Pure string work — unit-testable, no fs.
+
+/** Primary handoff body budget, in characters (~40k tokens at 4 chars/token — well inside
+ * every target agent's window while leaving room for the session's own work). */
+export const HANDOFF_BODY_BUDGET = 150_000
+/** Of the budget, how much goes to the verbatim tail vs the digest of older messages. */
+const TAIL_SHARE = 0.8
+
+/** A `## User` / `## Assistant` message boundary (tool blocks are `###` and never match). */
+const MESSAGE_HEADER = /^## /gm
+
+export interface BudgetedHandoff {
+ body: string
+ truncated: boolean
+}
+
+/** One digest line for an omitted section; whitespace collapsed, hard-capped. */
+function digestLine(section: string): string {
+ const nl = section.indexOf('\n')
+ const header = (nl === -1 ? section : section.slice(0, nl)).trim()
+ const rest = (nl === -1 ? '' : section.slice(nl)).replace(/\s+/g, ' ').trim()
+ const text = rest.length > 120 ? `${rest.slice(0, 120)}…` : rest
+ return text ? `- ${header.replace(/^#+\s*/, '')}: ${text}` : `- ${header.replace(/^#+\s*/, '')}`
+}
+
+/** Digest the omitted head: one line per message, tool-block runs collapsed to a count. */
+export function digestHead(head: string): string {
+ const boundaries: number[] = []
+ for (const m of head.matchAll(MESSAGE_HEADER)) boundaries.push(m.index)
+ if (boundaries.length === 0) return ''
+ const lines: string[] = []
+ let toolRun = 0
+ const flushTools = (): void => {
+ if (toolRun > 0) lines.push(`- (${toolRun} tool call/result block${toolRun === 1 ? '' : 's'} omitted)`)
+ toolRun = 0
+ }
+ for (let i = 0; i < boundaries.length; i++) {
+ const section = head.slice(boundaries[i], boundaries[i + 1] ?? head.length)
+ // Within a message section, everything up to the first `### ` is the message; the rest
+ // are tool blocks — count them instead of digesting each (they dominate long sessions).
+ const toolAt = section.search(/^### /m)
+ const message = toolAt === -1 ? section : section.slice(0, toolAt)
+ flushTools()
+ lines.push(digestLine(message))
+ if (toolAt !== -1) {
+ toolRun = (section.slice(toolAt).match(/^### /gm) ?? []).length
+ flushTools()
+ }
+ }
+ flushTools()
+ return lines.join('\n')
+}
+
+/**
+ * Fit `body` into `budget` chars: verbatim tail from a message boundary + digested head.
+ * Under-budget bodies pass through untouched (`truncated: false`).
+ */
+export function budgetHandoff(body: string, budget = HANDOFF_BODY_BUDGET, fullPath?: string): BudgetedHandoff {
+ if (body.length <= budget) return { body, truncated: false }
+
+ const tailBudget = Math.floor(budget * TAIL_SHARE)
+ // Earliest message boundary whose suffix fits the tail budget.
+ let tailStart = -1
+ for (const m of body.matchAll(MESSAGE_HEADER)) {
+ if (body.length - m.index <= tailBudget) {
+ tailStart = m.index
+ break
+ }
+ }
+ // No boundary fits (one enormous trailing message): hard-cut mid-message rather than blow
+ // the budget — the note below says so.
+ const midMessage = tailStart === -1
+ const tail = midMessage ? body.slice(-tailBudget) : body.slice(tailStart)
+ const head = midMessage ? body.slice(0, body.length - tailBudget) : body.slice(0, tailStart)
+
+ let digest = digestHead(head)
+ const digestBudget = budget - tail.length - 1_500 // headroom for the note scaffolding
+ if (digest.length > digestBudget) {
+ // Keep the most recent digest lines; drop the oldest.
+ const lines = digest.split('\n')
+ while (lines.length > 1 && lines.join('\n').length > digestBudget) lines.shift()
+ digest = `- … (earliest messages omitted)\n${lines.join('\n')}`
+ }
+
+ const note =
+ `> **Note:** this handoff was condensed to fit your context. Older messages appear only ` +
+ `as the one-line digest below; everything after the "VERBATIM FROM HERE" marker is the ` +
+ `unmodified recent conversation${midMessage ? ' (cut mid-message to fit)' : ''} — the live ` +
+ `task state is at the END of this file.` +
+ (fullPath
+ ? ` The COMPLETE transcript is at \`${fullPath}\` — read specific ranges or grep it on ` +
+ `demand; do NOT read it whole.`
+ : '')
+
+ const parts = [note]
+ if (digest) parts.push(`## Digest of earlier conversation\n\n${digest}`)
+ parts.push(`---\n\nVERBATIM FROM HERE\n\n${tail}`)
+ return { body: parts.join('\n\n'), truncated: true }
+}
diff --git a/src/main/handoff/index.ts b/src/main/handoff/index.ts
index 1ccade80d..6ccb550ec 100644
--- a/src/main/handoff/index.ts
+++ b/src/main/handoff/index.ts
@@ -1,6 +1,11 @@
// Cross-agent conversation transfer (main process). Locates the source agent's native
// transcript by sessionId, renders it to full Markdown, and writes a portable handoff file
-// under <cwd>/.nodeterm/. No summarization; the entire transcript is dumped.
+// under <cwd>/.nodeterm/. The PRIMARY file is context-budgeted (budget.ts): a long session
+// used to dump megabytes, and a target agent obeying "read the entire file" hit its own
+// context ceiling, compacted, and forgot the task (field report — codex greeted with
+// "What would you like to work on?"). Over-budget sessions keep the recent conversation
+// verbatim + a digest of the rest, with the COMPLETE render written beside it as
+// `…-full.md` for on-demand range reads.
import fs from 'fs'
import os from 'os'
import path from 'path'
@@ -8,6 +13,7 @@ import { SESSION_ID_RE } from '../../core/transcript-reader'
import { renderClaudeTranscript } from './render-claude'
import { renderCodexTranscript } from './render-codex'
import { renderGeminiTranscript } from './render-gemini'
+import { budgetHandoff } from './budget'
import { locateClaude, locateCodex, locateGemini } from '../../core/handoff/locate'
export type HandoffResult = { filePath: string } | { error: string }
@@ -58,17 +64,25 @@ export async function buildHandoff(opts: {
return { error: 'Failed to read the source transcript.' }
}
- const body = render(raw)
+ const full = render(raw)
const ts = new Date().toISOString().replace(/[:.]/g, '-')
+
+ const dir = path.join(cwd && cwd.length ? cwd : os.homedir(), '.nodeterm')
+ const filePath = path.join(dir, handoffFilename(sourceNodeId, ts))
+ const fullPath = filePath.replace(/\.md$/, '-full.md')
+
+ const { body, truncated } = budgetHandoff(full, undefined, fullPath)
const header =
`# Conversation handoff\n\n` +
`Source agent: ${agentId}\nSource session: ${sessionId}\n\n` +
- `This is the COMPLETE prior conversation, including all tool calls and outputs.\n\n---\n\n`
+ (truncated
+ ? `This is the prior conversation, condensed to fit your context (see the note below).\n\n---\n\n`
+ : `This is the COMPLETE prior conversation, including all tool calls and outputs.\n\n---\n\n`)
- const dir = path.join(cwd && cwd.length ? cwd : os.homedir(), '.nodeterm')
- const filePath = path.join(dir, handoffFilename(sourceNodeId, ts))
try {
await fs.promises.mkdir(dir, { recursive: true })
+ // The complete render goes first: if it fails, the primary must not promise a full copy.
+ if (truncated) await fs.promises.writeFile(fullPath, full, 'utf8')
await fs.promises.writeFile(filePath, header + body, 'utf8')
} catch {
return { error: 'Failed to write the handoff file.' }
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 3a9ec678a..5f0a71442 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -3615,10 +3615,16 @@ export function Canvas() {
setConfirm({ message: res.error, onConfirm: () => setConfirm(null) })
return
}
+ // The file is context-budgeted by buildHandoff (long sessions: digest + verbatim tail,
+ // full copy beside it), so "read it" is always affordable. The wording pins the agent to
+ // resuming: an earlier phrasing let the reader finish the file, end its turn, and greet
+ // with "what would you like to work on?" — the task must be treated as already assigned.
const prompt =
- `The file ${res.filePath} contains the COMPLETE prior conversation from a ` +
- `${sourceAgentId} session, including every message and all tool calls and outputs. ` +
- `Read the entire file first, then continue the task from where it left off.`
+ `The file ${res.filePath} is a handoff of the prior conversation from a ` +
+ `${sourceAgentId} session; the live task state is at the END of the file. ` +
+ `Read the file, then resume that task immediately from where it left off. ` +
+ `Do not greet, do not summarize the file back, and do not ask what to work on — ` +
+ `the task in the file is already assigned to you.`
const node = createAgentNode(
targetAgentId,
nodesRef.current.length,