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(launch): never submit a launch line the tty truncated

enesdbdbed7708fe
diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.ts
index 1828a5208..6548ce7c9 100644
--- a/src/core/canvas-control-core.ts
+++ b/src/core/canvas-control-core.ts
@@ -358,7 +358,10 @@ export function buildCanvasControlInstructions(shimPath: string): string {
' path>` instead: write the brief to a file, pass the absolute path, and the session starts',
' with the file\'s exact contents — newlines, numbered lists and headings preserved. The file',
' is read when the session LAUNCHES (later than the call for an `--after`-armed node), so',
- ' leave it in place until the station has started. Never begin a prompt with `/`: once',
+ ' leave it in place until the station has started. A long `--prompt` is SAFE on a local',
+ ' project (nodeterm spills it to a file itself), but on an SSH project pass `--prompt-file`:',
+ ' a terminal line caps at 1024 bytes on macOS, and a launch line that cannot be delivered is',
+ ' refused with a message on the node rather than half-run. Never begin a prompt with `/`: once',
' flattened, the agent reads the whole prompt as arguments to that slash command, your task',
' is never seen, and the node then sits idle looking healthy. To pick a model use `--model`,',
' not a leading `/model`.',
@@ -803,6 +806,13 @@ Verbs:
collapsed to a single space before the session starts, because the prompt is passed as an
argument on the agent CLI's launch command line and that line is typed into the pane. Two
consequences worth planning around:
+ - **A very long \`--prompt\` is safe on a local project and risky on an SSH one.** The launch
+ line is typed into the pane and a terminal line has a hard limit (1024 bytes on macOS), past
+ which the tail is silently discarded. On a local project nodeterm writes an over-long prompt
+ to a file for you and the session starts with the same flattened text; on an SSH project it
+ cannot (the file would land on the wrong machine), so pass a long brief with
+ \`--prompt-file\` there. A launch line that cannot be delivered is refused with a message on
+ the node, never half-run.
- **A structured brief goes through \`--prompt-file <abs path>\`.** Write the brief (numbered
acceptance criteria, file lists, guard clauses — anything multi-line) to a file, pass the
absolute path, and the session starts with the file's exact contents: the launch line stays
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 0c685b0ec..0291442f8 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -413,6 +413,11 @@ import {
} from '@shared/agents/config'
import { withPermissionMode } from '@shared/agents/approval-mode'
import { promptFilePathError } from '@shared/agents/launch'
+import {
+ encodeUtf8Base64,
+ shouldSpillPrompt,
+ spillPromptToFile
+} from '../lib/promptSpill'
import { parseTeamSpec } from '../lib/teamSpec'
import { relativeTime } from '../lib/relativeTime'
import { AgentIcon } from '../lib/agentIcons'
@@ -9758,6 +9763,21 @@ export function Canvas() {
})()
const ctlSsh = ctlProject?.ssh
const sshFor = (cwd?: string) => nodeSshFor(ctlSsh, cwd)
+ // A prompt too long for a typed line goes into a file the pane's own shell reads (#706).
+ // See lib/promptSpill.ts for the budget and for why an SSH project is excluded: the file
+ // would land on THIS machine while the pane runs on the host. Fails open in every
+ // direction — a spill we cannot perform returns the prompt inline, exactly as before, and
+ // the delivery layer refuses a truncated line rather than submitting half of it.
+ const spillLongPrompt = async (
+ prompt: string | undefined
+ ): Promise<{ prompt?: string; promptFile?: string }> => {
+ if (!shouldSpillPrompt(prompt, !ctlSsh)) return { prompt }
+ const path = await spillPromptToFile(prompt as string, {
+ saveUpload: (n, d) => api.files.saveUpload(n, d),
+ encodeBase64: encodeUtf8Base64
+ })
+ return path ? { promptFile: path } : { prompt }
+ }
// Place opened nodes BELOW the source and rope them to it (source flow-out → target
// flow-in), mirroring how subagent/loop nodes attach — so they read as "hanging off" the
// conversation instead of landing on top of unrelated nodes. `placeBelow` returns a node
@@ -10176,6 +10196,10 @@ export function Canvas() {
// See the same list in open-terminal: which of these nodes end up ARMED is
// `armAfter`'s per-node decision, recorded as it builds them.
const queuedIds: string[] = []
+ // A `--prompt` over the typed-line budget is spilled to a file and delivered through
+ // the same `"$(cat …)"` substitution `--prompt-file` uses (#706). An explicit
+ // `--prompt-file` already took that route and is passed through untouched.
+ const promptLaunch = await spillLongPrompt(promptFile ? undefined : args.prompt)
const make = (i: number): CanvasNode => {
const node = armAfter(
createAgentNode(
@@ -10183,7 +10207,7 @@ export function Canvas() {
nodesRef.current.length + i,
agentCwd,
placeBelow(i),
- args.prompt,
+ promptLaunch.prompt,
sshFor(agentCwd),
account,
activePermissionMode(agentId),
@@ -10194,7 +10218,7 @@ export function Canvas() {
// interpolation site and emits nothing for an agent outside MODEL_SWITCH_CAPABLE,
// so an unsupported agent's command line stays byte-identical.
args.model,
- promptFile
+ promptFile ?? promptLaunch.promptFile
),
after ?? [],
undefined,
@@ -10548,24 +10572,38 @@ export function Canvas() {
// Every node in the panel (reviewers + judge) runs `reviewAgent`, so one resolution
// serves them all — gated on that agent, not on the caller's.
const vMode = activePermissionMode(reviewAgent)
+ // A lens brief assembles to MORE than a typed line can carry — measured 1045 and 1044
+ // bytes for the `security` and `tests` defaults against a 1024-byte macOS MAX_CANON,
+ // with a nine-character node title and no `--focus` at all (#706). So every panel
+ // prompt goes through the spill before a node is built, and the awaits are done up
+ // front because the factories below are synchronous.
+ const lensLaunches = await Promise.all(
+ lenses.map((lens) =>
+ spillLongPrompt(
+ verifyLensPrompt({
+ lens,
+ targetTitle,
+ targetId,
+ agentId: reviewAgent,
+ shimPath: vShim,
+ focus: args.focus
+ })
+ )
+ )
+ )
const reviewers = lenses.map((lens, i) => {
const node = createAgentNode(
reviewAgent,
live.length + i,
targetCwd,
placeBelow(i),
- verifyLensPrompt({
- lens,
- targetTitle,
- targetId,
- agentId: reviewAgent,
- shimPath: vShim,
- focus: args.focus
- }),
+ lensLaunches[i].prompt,
sshFor(targetCwd),
vAccount,
vMode,
- vStore.activeProjectId
+ vStore.activeProjectId,
+ undefined,
+ lensLaunches[i].promptFile
)
return armAfter(
{ ...node, data: { ...node.data, title: `Verify: ${lens}`, titleAuto: false } },
@@ -10573,6 +10611,14 @@ export function Canvas() {
)
})
const reviewerIds = reviewers.map((r) => r.id)
+ const judgeLaunch = await spillLongPrompt(
+ verifySynthesisPrompt({
+ lenses,
+ targetTitle,
+ agentId: reviewAgent,
+ shimPath: vShim
+ })
+ )
const judge = wantJudge
? armAfter(
(() => {
@@ -10581,16 +10627,13 @@ export function Canvas() {
live.length + lenses.length,
targetCwd,
placeBelow(lenses.length),
- verifySynthesisPrompt({
- lenses,
- targetTitle,
- agentId: reviewAgent,
- shimPath: vShim
- }),
+ judgeLaunch.prompt,
sshFor(targetCwd),
vAccount,
vMode,
- vStore.activeProjectId
+ vStore.activeProjectId,
+ undefined,
+ judgeLaunch.promptFile
)
return { ...j, data: { ...j.data, title: 'Verify: verdict', titleAuto: false } }
})(),
@@ -10705,6 +10748,14 @@ export function Canvas() {
teamStore.getProject(teamStore.activeProjectId ?? ''),
useSettings.getState().settings.claudeAccounts
)
+ // Same typed-line budget as open-agent (#706): a role brief long enough to truncate
+ // the launch line is spilled to a file first. A role that named its own promptFile
+ // is passed through untouched. Awaited up front — the factory below is synchronous.
+ const roleLaunches = await Promise.all(
+ roles.map((r) =>
+ r.promptFile ? spillLongPrompt(undefined) : spillLongPrompt(r.prompt)
+ )
+ )
// Build members; fixed role titles pin the node name (titleAuto off).
const members = roles.map((r, i) => {
// Roles may name different agents, so the mode is resolved PER member: claude's
@@ -10716,7 +10767,7 @@ export function Canvas() {
live.length + i,
srcCwd,
placeBelow(i),
- r.prompt,
+ roleLaunches[i].prompt,
sshFor(srcCwd),
teamAccount,
activePermissionMode(memberAgent),
@@ -10726,7 +10777,7 @@ export function Canvas() {
r.model,
// Per-role promptFile (parser-validated + existence-checked above); wins over
// `prompt` in the assembler.
- r.promptFile
+ r.promptFile ?? roleLaunches[i].promptFile
)
return r.title ? { ...node, data: { ...node.data, title: r.title, titleAuto: false } } : node
})
diff --git a/src/renderer/lib/promptSpill.test.ts b/src/renderer/lib/promptSpill.test.ts
new file mode 100644
index 000000000..71d311766
--- /dev/null
+++ b/src/renderer/lib/promptSpill.test.ts
@@ -0,0 +1,158 @@
+import { describe, expect, it, vi } from 'vitest'
+import {
+ LAUNCH_PROMPT_BUDGET_BYTES,
+ encodeUtf8Base64,
+ flattenPrompt,
+ promptExceedsLineBudget,
+ shouldSpillPrompt,
+ spillPromptToFile
+} from './promptSpill'
+import { MAX_LAUNCH_LINE_BYTES, fitsLaunchLine, lineBytes } from '@shared/canonical-line'
+import { DEFAULT_LENSES, verifyLensPrompt, verifySynthesisPrompt } from './verifyPanel'
+import { assembleLaunchCommand } from '@shared/agents/launch'
+
+const io = (saveUpload: (n: string, d: string) => Promise<string | null>) => ({
+ saveUpload,
+ encodeBase64: encodeUtf8Base64
+})
+
+describe('the spill decision', () => {
+ it('leaves a short prompt alone — the command line stays byte-identical', () => {
+ expect(promptExceedsLineBudget('hello')).toBe(false)
+ expect(shouldSpillPrompt('hello', true)).toBe(false)
+ expect(promptExceedsLineBudget(undefined)).toBe(false)
+ })
+
+ it('spills a prompt over the budget on a local project', () => {
+ const long = 'x'.repeat(LAUNCH_PROMPT_BUDGET_BYTES + 1)
+ expect(promptExceedsLineBudget(long)).toBe(true)
+ expect(shouldSpillPrompt(long, true)).toBe(true)
+ })
+
+ it('NEVER spills for an SSH project — the file would land on the wrong machine', () => {
+ // `saveUpload` writes where this renderer's core runs; an SSH pane runs on the host, so the
+ // composed `"$(cat …)"` would read a path that does not exist there and start the agent with
+ // an EMPTY prompt. A prompt at risk of truncation must not become one that is certainly gone.
+ const long = 'x'.repeat(LAUNCH_PROMPT_BUDGET_BYTES + 1)
+ expect(shouldSpillPrompt(long, false)).toBe(false)
+ })
+
+ it('measures the FLATTENED prompt, which is what actually gets typed', () => {
+ // A prompt padded out with newlines collapses to one space per run before it reaches the
+ // pane, so judging the raw text would spill a line that was never going to be long.
+ const padded = 'a'.repeat(100) + '\n'.repeat(LAUNCH_PROMPT_BUDGET_BYTES)
+ expect(lineBytes(padded)).toBeGreaterThan(LAUNCH_PROMPT_BUDGET_BYTES)
+ expect(promptExceedsLineBudget(padded)).toBe(false)
+ })
+})
+
+describe('spillPromptToFile', () => {
+ it('writes the FLATTENED prompt, so a prompt does not change meaning with its length', () => {
+ // Under the budget `--prompt` arrives with every whitespace run collapsed (the assembler does
+ // it, and the agent-facing docs promise it). If the spilled file kept the newlines, the same
+ // flag would mean two different things either side of an invisible threshold.
+ const save = vi.fn(async (_n: string, _d: string) => '/tmp/p.txt' as string | null)
+ return spillPromptToFile('one\n\ntwo three', io(save)).then((path) => {
+ expect(path).toBe('/tmp/p.txt')
+ const written = Buffer.from(String(save.mock.calls[0][1]), 'base64').toString('utf8')
+ expect(written).toBe('one two three')
+ })
+ })
+
+ it('round-trips non-ASCII — a prompt is full of em dashes and ellipses', () => {
+ const save = vi.fn(async (_n: string, _d: string) => '/tmp/p.txt' as string | null)
+ const text = 'a — b … ç'
+ return spillPromptToFile(text, io(save)).then(() => {
+ expect(Buffer.from(String(save.mock.calls[0][1]), 'base64').toString('utf8')).toBe(text)
+ })
+ })
+
+ it('fails OPEN: a writer that returns null or throws yields null, never a bad path', async () => {
+ expect(await spillPromptToFile('x', io(async () => null))).toBeNull()
+ expect(
+ await spillPromptToFile(
+ 'x',
+ io(async () => {
+ throw new Error('E_UNSUPPORTED')
+ })
+ )
+ ).toBeNull()
+ })
+
+ it('never reuses a name — two spills in the same millisecond are separate files', async () => {
+ const names: string[] = []
+ const sink = io(async (n) => {
+ names.push(n)
+ return `/tmp/${n}`
+ })
+ await Promise.all([spillPromptToFile('a', sink), spillPromptToFile('b', sink)])
+ expect(new Set(names).size).toBe(2)
+ })
+})
+
+describe("verify's own prompts (the case that fires with no user input)", () => {
+ const shimPath = '/Users/x/Library/Application Support/node-terminal/context-link/context.sh'
+ const targetId = 'n'.repeat(22)
+
+ it('every default lens is over the budget, so the panel spills instead of truncating', () => {
+ // The reporter's table, reproduced from the shipped prompt builder: with a nine-character
+ // node title and NO `--focus`, the assembled `security` and `tests` commands are 1045 and
+ // 1044 bytes against a 1024-byte MAX_CANON. This asserts the whole panel takes the file
+ // route, which is what makes `verify` work on macOS at all.
+ for (const lens of DEFAULT_LENSES) {
+ const prompt = verifyLensPrompt({
+ lens,
+ targetTitle: 'short-one',
+ targetId,
+ agentId: 'claude',
+ shimPath
+ })
+ expect(shouldSpillPrompt(prompt, true)).toBe(true)
+ }
+ })
+
+ it('the JUDGE prompt fits and is left inline — the spill only fires where it is needed', () => {
+ // Measured: the synthesis prompt assembles to 749 bytes for the three default lenses, well
+ // inside the budget, so a `verify` panel writes one file per REVIEWER and none for the
+ // verdict node. Pinned so a future rewording that pushes it over is a visible change rather
+ // than a silent extra file — and so the "only when needed" property has a witness.
+ const judge = verifySynthesisPrompt({
+ lenses: DEFAULT_LENSES,
+ targetTitle: 'short-one',
+ agentId: 'claude',
+ shimPath
+ })
+ expect(shouldSpillPrompt(judge, true)).toBe(false)
+ })
+
+ it('the spilled command FITS a canonical-mode line, which the inline one does not', () => {
+ const prompt = verifyLensPrompt({
+ lens: 'security',
+ targetTitle: 'short-one',
+ targetId,
+ agentId: 'claude',
+ shimPath
+ })
+ const shape = {
+ agentId: 'claude',
+ permissionMode: 'auto' as const,
+ sessionId: '11111111-2222-3333-4444-555555555555',
+ sessionIdFlagSupported: true
+ }
+ const inline = assembleLaunchCommand({ ...shape, initialPrompt: prompt }, {}).command
+ expect(fitsLaunchLine(inline)).toBe(false)
+ expect(lineBytes(inline)).toBeGreaterThan(MAX_LAUNCH_LINE_BYTES)
+
+ const spilled = assembleLaunchCommand(
+ { ...shape, promptFile: '/Users/x/Library/Application Support/node-terminal/uploads/k/p.txt' },
+ {}
+ ).command
+ expect(fitsLaunchLine(spilled)).toBe(true)
+ })
+})
+
+describe('flattenPrompt', () => {
+ it('matches the assembler: every whitespace run becomes one space, ends trimmed', () => {
+ expect(flattenPrompt(' a\n\n b\t\tc ')).toBe('a b c')
+ })
+})
diff --git a/src/renderer/lib/promptSpill.ts b/src/renderer/lib/promptSpill.ts
new file mode 100644
index 000000000..a5a2b364f
--- /dev/null
+++ b/src/renderer/lib/promptSpill.ts
@@ -0,0 +1,119 @@
+// A LAUNCH PROMPT TOO BIG FOR A TYPED LINE GOES INTO A FILE INSTEAD (issue #706).
+//
+// `--prompt` becomes a quoted argument on a command line that is TYPED into the pane, and a
+// canonical-mode tty silently discards everything past its buffer (1024 bytes on macOS — see
+// @shared/canonical-line). The closing quote is what gets dropped, so the shell is left at
+// `quote>` and the agent never launches. `verify` reaches that length with no user input at all:
+// two of its three default lenses assemble to > 1024 bytes with a nine-character node title.
+//
+// The mechanism to avoid it already exists and is already the documented answer for a prompt with
+// structure: `--prompt-file` (issue #520), which the assembler composes as `"$(cat '<path>')"` —
+// the pane's own shell reads the file at execution, so the TYPED line stays short whatever the
+// prompt weighs. All this module adds is doing it automatically for a prompt we generated.
+//
+// Three properties, in order of importance:
+//
+// 1. **It never makes things worse.** A spill that fails for any reason (no writer on this
+// surface, a full disk, a relay tab) returns `null` and the caller passes the prompt inline
+// exactly as before. The delivery layer's own refusal (`deliverCommand`'s `line-too-long`)
+// is what stops a truncated line from being submitted in that case, so failing open here
+// costs a visible refusal, never a half-run command.
+// 2. **It only fires when needed.** Under the budget the caller's command line is byte-identical
+// to what it has always been — no file is written for `--prompt "hello"`.
+// 3. **It writes on the machine the terminals run on.** `files.saveUpload` is that seam by
+// definition (it is what a clipboard paste and a browser-side drop already use), which makes
+// this correct on the desktop and in the Server Edition without a branch. An SSH project's
+// pane runs on the HOST, where this cannot reach — so those callers must not spill, and
+// `shouldSpillPrompt` takes that as an explicit argument rather than guessing.
+
+import { MAX_LAUNCH_LINE_BYTES, lineBytes } from '@shared/canonical-line'
+
+/**
+ * How many bytes of PROMPT we will put on a typed line before spilling.
+ *
+ * The rest of the line is the program, its args, the permission-mode flag, a minted `--session-id`
+ * and an optional `--model`. Measured against `assembleLaunchCommand` (2026-09) the worst builtin
+ * is claude at **122 bytes** of overhead with every one of those present; grok is 90, copilot 74,
+ * codex 41, gemini 35, opencode 20. The reserve is set well above the worst measured value because
+ * two inputs are NOT bounded by anything here — a per-builtin launch-command override (a wrapper
+ * script the user names in Settings) and a custom agent's `args` — and being a little eager to
+ * spill costs one file, while being a little short costs a truncated launch.
+ *
+ * Deliberately a budget on the prompt rather than a check on the finished command: the command is
+ * assembled inside `createAgentNode`, which also MINTS a session id, so it cannot be dry-run to
+ * measure. The finished line is still checked at delivery, which is the backstop for the cases
+ * this reserve does not cover.
+ */
+export const LAUNCH_LINE_OVERHEAD_RESERVE = 200
+export const LAUNCH_PROMPT_BUDGET_BYTES = MAX_LAUNCH_LINE_BYTES - LAUNCH_LINE_OVERHEAD_RESERVE
+
+/**
+ * What actually reaches the pane for an inline `--prompt`: the assembler collapses every run of
+ * whitespace to one space (`assembleLaunchCommand`), and the agent-facing docs promise exactly
+ * that. **The spilled file must hold the SAME text**, or a prompt's meaning would change with its
+ * length — under the budget it arrives flattened, over the budget it would arrive with its
+ * newlines intact. `--prompt-file` remains the way to ask for structure, and it is untouched by
+ * this module. Kept here rather than imported so the invariant is stated where the file is
+ * written.
+ */
+export function flattenPrompt(prompt: string): string {
+ return prompt.replace(/\s+/g, ' ').trim()
+}
+
+/** Would this prompt, typed inline, risk a truncated launch line? Measured on what will actually
+ * be typed — the flattened form, which is never longer than the original. */
+export function promptExceedsLineBudget(prompt: string | undefined): boolean {
+ return !!prompt && lineBytes(flattenPrompt(prompt)) > LAUNCH_PROMPT_BUDGET_BYTES
+}
+
+/**
+ * Should this prompt be spilled to a file?
+ *
+ * `localFs` is the caller's answer to "will the pane read the filesystem `saveUpload` writes to?".
+ * It is FALSE for an SSH project, whose pane runs on the host — spilling there would compose a
+ * `cat` of a path that exists only on this machine, turning a prompt that is merely at risk of
+ * truncation into one that is guaranteed empty. Those callers pass the prompt inline and rely on
+ * the delivery refusal instead, which also means a host with a larger canonical buffer (Linux is
+ * 4096) keeps working exactly as it does today.
+ */
+export function shouldSpillPrompt(prompt: string | undefined, localFs: boolean): boolean {
+ return localFs && promptExceedsLineBudget(prompt)
+}
+
+export interface PromptSpillIo {
+ /** `window.nodeTerminal.files.saveUpload` — writes on the machine the terminals run on. */
+ saveUpload(name: string, dataBase64: string): Promise<string | null>
+ /** Injected so the module tests without a DOM. */
+ encodeBase64(text: string): string
+}
+
+let spillSeq = 0
+
+/** UTF-8 → base64, which is what `saveUpload` takes. `btoa` is Latin-1 only, so the text is
+ * encoded to bytes first — a prompt is full of `—` and `…` and would otherwise throw. */
+export function encodeUtf8Base64(text: string): string {
+ const bytes = new TextEncoder().encode(text)
+ let binary = ''
+ for (const b of bytes) binary += String.fromCharCode(b)
+ return btoa(binary)
+}
+
+/**
+ * Write `prompt` to a file on the machine the terminals run on and resolve its ABSOLUTE path, or
+ * `null` if it could not be written — in which case the caller keeps its inline prompt.
+ *
+ * Never throws: `saveUpload` is a `window.nodeTerminal` member, and a surface that stubs it
+ * (a relay tab) rejects rather than resolving null.
+ */
+export async function spillPromptToFile(
+ prompt: string,
+ io: PromptSpillIo
+): Promise<string | null> {
+ try {
+ const name = `nodeterm-prompt-${Date.now().toString(36)}-${(spillSeq++).toString(36)}.txt`
+ const path = await io.saveUpload(name, io.encodeBase64(flattenPrompt(prompt)))
+ return path || null
+ } catch {
+ return null
+ }
+}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 472693909..8a13adc39 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -107,6 +107,7 @@ import {
type Vec2
} from '../lib/glyphGridNode'
import { deliverCommand, KILL_LINE, type DeliveryIo } from '../terminal/command-delivery'
+import { MAX_LAUNCH_LINE_BYTES, lineBytes } from '@shared/canonical-line'
import {
agentHibernateFns,
exitSequence,
@@ -820,6 +821,16 @@ interface CoState {
* respawn clears it.
*/
staleCwd: boolean
+ /**
+ * A one-shot launch command was REFUSED at delivery because it is longer than a canonical-mode
+ * tty line (`deliverCommand`'s `line-too-long`, issue #706). Holds the command's byte length,
+ * for the banner; `null` = nothing refused.
+ *
+ * NOT an overlay like `spawnError`: the terminal is alive and the user can run the command
+ * themselves — covering it would take away the only surface that can still be used. Same slim
+ * top banner as `staleCwd`, and for the same reason.
+ */
+ launchTooLongBytes: number | null
}
const NO_CO: CoState = {
letterbox: false,
@@ -827,7 +838,8 @@ const NO_CO: CoState = {
ended: false,
offline: false,
spawnError: null,
- staleCwd: false
+ staleCwd: false,
+ launchTooLongBytes: null
}
const coStates = new Map<string, CoState>()
const coSubs = new Map<string, (s: CoState) => void>()
@@ -1035,7 +1047,8 @@ function setCo(key: string, patch: Partial<CoState>): void {
next.ended === prev.ended &&
next.offline === prev.offline &&
next.spawnError === prev.spawnError &&
- next.staleCwd === prev.staleCwd
+ next.staleCwd === prev.staleCwd &&
+ next.launchTooLongBytes === prev.launchTooLongBytes
)
return
coStates.set(key, next)
@@ -1859,6 +1872,7 @@ export function TerminalNode({
}))
}
const dismissStaleCwd = (): void => setCo(termKey, { staleCwd: false })
+ const dismissLaunchTooLong = (): void => setCo(termKey, { launchTooLongBytes: null })
// "Not connected" (CoState.offline): the host was unreachable, so this node has no session
// anywhere. Ask the coordinator to re-establish the project's master NOW — it flushes the
@@ -3277,7 +3291,15 @@ export function TerminalNode({
write: (d) => transport.write(sid, d),
onData: (cb) => transport.onData(sid, cb)
},
- cmd
+ cmd,
+ (outcome) => {
+ // The one outcome the caller must act on: the line was longer than the pane's
+ // tty could take, so nothing was submitted (#706). Say so — a refusal that is
+ // only visible as an idle pane is the failure this replaces.
+ if (outcome === 'line-too-long') {
+ setCo(termKey, { launchTooLongBytes: lineBytes(cmd) })
+ }
+ }
)
)
})
@@ -5394,6 +5416,27 @@ export function TerminalNode({
</button>
</div>
)}
+ {/* Launch line refused (#706): same slim TOP banner as staleCwd, for the same reason —
+ the terminal is alive and the command can still be run by hand, so nothing is
+ covered. It reports what was measured and names the flag that avoids it; it does not
+ offer a retry, because retyping the identical line would be truncated identically. */}
+ {!co.closed && !co.ended && !co.spawnError && !co.offline && co.launchTooLongBytes !== null && !offscreenDown && (
+ <div className="term-node__stalecwd nodrag">
+ <span className="term-node__stalecwd-text">
+ This session&apos;s launch command ({co.launchTooLongBytes} bytes) is longer than a
+ terminal line can carry ({MAX_LAUNCH_LINE_BYTES}), so it was not run. Shorten the
+ prompt, or pass it with --prompt-file.
+ </span>
+ <button
+ className="term-node__stalecwd-dismiss"
+ onClick={dismissLaunchTooLong}
+ title="Dismiss"
+ aria-label="Dismiss"
+ >
+ ×
+ </button>
+ </div>
+ )}
{armed && !mdMode && (
<div
className="term-hover-guard"
diff --git a/src/renderer/terminal/command-delivery.test.ts b/src/renderer/terminal/command-delivery.test.ts
index bd5feb7a2..cfc972336 100644
--- a/src/renderer/terminal/command-delivery.test.ts
+++ b/src/renderer/terminal/command-delivery.test.ts
@@ -7,6 +7,7 @@ import {
deliverCommand,
echoedIntact
} from './command-delivery'
+import { MAX_LAUNCH_LINE_BYTES } from '@shared/canonical-line'
const CMD = `claude --settings x 'implement the rerank feature for search results' --permission-mode auto`
@@ -240,3 +241,51 @@ describe('deliverCommand', () => {
expect(f.writes).toEqual([CMD, '\r'])
})
})
+
+describe('a launch line longer than the tty can carry (issue #706)', () => {
+ beforeEach(() => vi.useFakeTimers())
+ afterEach(() => vi.useRealTimers())
+
+ /** Over MAX_LAUNCH_LINE_BYTES, the length `verify`'s default lenses actually reach: measured
+ * 1045 bytes for `security` against a 1024-byte macOS MAX_CANON, with no `--focus` at all. */
+ const LONG = `claude '${'x'.repeat(1000)}' --permission-mode auto`
+
+ /** A pane in canonical mode echoes what the kernel accepted and silently discards the rest, so
+ * the head matches and the tail never does — exactly what `echoedIntact` is built to catch. */
+ const truncatedEcho = (cmd: string): string => cmd.slice(0, MAX_LAUNCH_LINE_BYTES)
+
+ it('is never SUBMITTED unverified — no Enter, and the half-line is cleared', () => {
+ const f = fakeIo()
+ let outcome: string | undefined
+ deliverCommand(f.io, LONG, (o) => (outcome = o))
+ for (let i = 0; i < DELIVERY_ATTEMPTS; i++) {
+ f.emit(truncatedEcho(LONG))
+ vi.advanceTimersByTime(VERIFY_TIMEOUT_MS)
+ }
+ expect(outcome).toBe('line-too-long')
+ expect(f.writes).not.toContain('\r')
+ expect(f.writes[f.writes.length - 1]).toBe(KILL_LINE)
+ })
+
+ it('still fails OPEN for a line that FITS but whose echo we could not recognise', () => {
+ // The historical contract, and why the refusal is narrowed to over-cap lines: an unverified
+ // echo is usually our own blindness, and blocking every launch on it is worse than the bug.
+ const f = fakeIo()
+ let outcome: string | undefined
+ deliverCommand(f.io, CMD, (o) => (outcome = o))
+ for (let i = 0; i < DELIVERY_ATTEMPTS; i++) vi.advanceTimersByTime(VERIFY_TIMEOUT_MS)
+ expect(outcome).toBe('submitted')
+ expect(f.writes).toContain('\r')
+ })
+
+ it('submits an over-cap line the pane DID echo whole — a raw-mode tty has no such limit', () => {
+ // The cap applies only while the tty is canonical; once the shell's line editor is up the
+ // same line arrives intact, and a verified echo is proof of exactly that.
+ const f = fakeIo()
+ let outcome: string | undefined
+ deliverCommand(f.io, LONG, (o) => (outcome = o))
+ f.emit(LONG)
+ expect(outcome).toBe('submitted')
+ expect(f.writes).toContain('\r')
+ })
+})
diff --git a/src/renderer/terminal/command-delivery.ts b/src/renderer/terminal/command-delivery.ts
index d8016de8e..fd40c63ef 100644
--- a/src/renderer/terminal/command-delivery.ts
+++ b/src/renderer/terminal/command-delivery.ts
@@ -7,6 +7,14 @@
// kills the pending line (Ctrl-U) and rewrites; the LAST attempt submits unverified —
// fail-open, a terminal whose echo we can't recognize must never block the launch (that
// worst case is exactly the pre-fix behavior).
+//
+// The ONE exception to failing open is a line the tty could not physically have taken: a
+// canonical-mode buffer silently drops everything past its cap (1024 bytes on macOS), so an
+// over-cap command is truncated mid-quote and Enter would strand the shell at `quote>` with the
+// agent never launched (#706). That case is refused, not submitted — see `DeliveryOutcome` and
+// @shared/canonical-line.
+
+import { fitsLaunchLine } from '@shared/canonical-line'
export const VERIFY_TIMEOUT_MS = 2000
export const DELIVERY_ATTEMPTS = 3
@@ -54,6 +62,22 @@ export function echoedIntact(cleanedSoFar: string, cmd: string): boolean {
)
}
+/**
+ * How a delivery ended, for the callers that must tell the difference.
+ *
+ * - `submitted` — Enter was written. Either the echo verified, or the last attempt failed OPEN
+ * (the historical behaviour: a terminal whose echo we cannot recognise must never block a
+ * launch). Every pre-existing caller treated a settle as exactly this.
+ * - `line-too-long` — the echo never verified AND the command is longer than a canonical-mode
+ * tty can carry (`MAX_LAUNCH_LINE_BYTES`), so the pane is holding a KNOWN-truncated line.
+ * Enter is NOT written; the pending line is killed instead. This is the one case where
+ * failing open is not a fail-open at all: submitting a line whose closing quote the kernel
+ * dropped strands the shell at `quote>` and the agent never starts (#706). A refusal the
+ * caller can show beats a pane that merely looks idle.
+ * - `cancelled` — the caller tore the delivery down (node unmount), or the transport threw.
+ */
+export type DeliveryOutcome = 'submitted' | 'line-too-long' | 'cancelled'
+
export interface DeliveryIo {
write(data: string): void
/** Subscribe to session output; returns unsubscribe. */
@@ -65,20 +89,25 @@ export interface DeliveryIo {
* (verified or fail-open) or cancelled — for callers that must know when the LINE has left the
* pane, not merely when it was started: the retries run for up to
* DELIVERY_ATTEMPTS × VERIFY_TIMEOUT_MS, and anything typed into the pane during that window
- * lands inside the un-submitted line. */
-export function deliverCommand(io: DeliveryIo, cmd: string, onSettled?: () => void): () => void {
+ * lands inside the un-submitted line. The outcome argument is optional to read: every caller
+ * that only needs "the line has left the pane" keeps working unchanged. */
+export function deliverCommand(
+ io: DeliveryIo,
+ cmd: string,
+ onSettled?: (outcome: DeliveryOutcome) => void
+): () => void {
let done = false
let attempt = 0
let echoed = ''
let timer: ReturnType<typeof setTimeout> | undefined
let unsub: (() => void) | undefined
- const finish = (): void => {
+ const finish = (outcome: DeliveryOutcome = 'cancelled'): void => {
if (done) return // a cancel after the submit must not re-announce the delivery
done = true
if (timer) clearTimeout(timer)
unsub?.()
- onSettled?.()
+ onSettled?.(outcome)
}
/**
* Every write goes through here. `io.write` is unguarded all the way down to the relay client's
@@ -109,7 +138,7 @@ export function deliverCommand(io: DeliveryIo, cmd: string, onSettled?: () => vo
// in-place restart choreography feeds one) would otherwise re-enter the listener below while
// the tail still matches, and submit forever.
const submit = (): void => {
- finish()
+ finish('submitted')
write('\r')
}
const tryOnce = (): void => {
@@ -121,6 +150,16 @@ export function deliverCommand(io: DeliveryIo, cmd: string, onSettled?: () => vo
timer = setTimeout(() => {
if (done) return
if (attempt >= DELIVERY_ATTEMPTS) {
+ // Fail-open — UNLESS the tty provably could not have taken the line. An unverified echo
+ // is usually our own blindness (an exotic prompt, a redraw we cannot parse) and submitting
+ // is then the right bet. An over-cap line is different in kind: the kernel discarded its
+ // tail while the pane was in canonical mode, so Enter would submit a command we KNOW is
+ // cut in half. Kill the pending line and report instead. See @shared/canonical-line.
+ if (!fitsLaunchLine(cmd)) {
+ write(KILL_LINE)
+ finish('line-too-long')
+ return
+ }
submit() // fail-open: unverified submit beats a never-launched agent
return
}
diff --git a/src/shared/canonical-line.test.ts b/src/shared/canonical-line.test.ts
new file mode 100644
index 000000000..d4a7b46c2
--- /dev/null
+++ b/src/shared/canonical-line.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest'
+import {
+ MAX_CANON_BYTES,
+ MAX_LAUNCH_LINE_BYTES,
+ fitsLaunchLine,
+ lineBytes
+} from './canonical-line'
+
+describe('the canonical-mode line budget', () => {
+ it('is macOS MAX_CANON, with a byte reserved for the submitting CR', () => {
+ // Measured on a real pty (see the module header): a 4000-byte payload plus its newline fit a
+ // 4096-byte Linux buffer, 5000 did not. macOS caps at 1024, and the renderer cannot know
+ // which machine the pane is on — so the smallest cap is the one that must hold.
+ expect(MAX_CANON_BYTES).toBe(1024)
+ expect(MAX_LAUNCH_LINE_BYTES).toBe(1023)
+ })
+
+ it('measures BYTES, not characters — a prompt is rarely pure ASCII', () => {
+ // '—' is 3 UTF-8 bytes. Counting characters would let a 400-em-dash line through a 1023-byte
+ // buffer that will truncate it.
+ expect(lineBytes('—')).toBe(3)
+ expect(lineBytes('a')).toBe(1)
+ const emDashes = '—'.repeat(400)
+ expect(emDashes.length).toBeLessThan(MAX_LAUNCH_LINE_BYTES)
+ expect(fitsLaunchLine(emDashes)).toBe(false)
+ })
+
+ it('fits a line at the budget and refuses one past it', () => {
+ expect(fitsLaunchLine('x'.repeat(MAX_LAUNCH_LINE_BYTES))).toBe(true)
+ expect(fitsLaunchLine('x'.repeat(MAX_LAUNCH_LINE_BYTES + 1))).toBe(false)
+ })
+})
diff --git a/src/shared/canonical-line.ts b/src/shared/canonical-line.ts
new file mode 100644
index 000000000..15447cd58
--- /dev/null
+++ b/src/shared/canonical-line.ts
@@ -0,0 +1,55 @@
+/**
+ * HOW LONG A LINE TYPED INTO A PANE MAY BE — the tty's limit, not ours.
+ *
+ * A launch command is delivered by typing it into the pane's tty and then pressing Enter. While
+ * that tty is in CANONICAL mode the kernel buffers the line itself, and a line longer than the
+ * driver's canonical buffer is **silently truncated**: the tail is dropped, no error is raised,
+ * and the Enter that follows submits whatever survived. For a launch line that ends in a quoted
+ * prompt the survivor is an unterminated quote, so the shell sits at `quote>` and the agent never
+ * starts — a pane that merely looks idle (issue #706).
+ *
+ * MEASURED, on a real pty whose slave was left in canonical mode:
+ * - Linux (N_TTY, `N_TTY_BUF_SIZE`): 4000 bytes + `\n` arrived whole; 5000 bytes came back as
+ * 4096 with the newline gone.
+ * - macOS (`MAX_CANON`, `<sys/syslimits.h>`): 1024. Reported and measured by #706 on 25.5.0.
+ *
+ * Two consequences the code depends on:
+ *
+ * 1. **Chunking the WRITE does not help.** The cap is on the assembled LINE, not on any single
+ * `write()`. Measured: 5000 bytes delivered as one write, as 512-byte writes and as 100-byte
+ * writes all arrived as the same truncated 4096. So "write it in pieces" is not a fix, and
+ * nothing here should be refactored into one.
+ * 2. **The budget must be the SMALLEST cap of any machine a pane can be on**, not this machine's.
+ * The renderer types into panes that live on an SSH host, a relay peer or the Server Edition's
+ * own box, and it cannot know their platform — a Linux desktop driving a macOS host would
+ * otherwise compute a 4096-byte budget for a 1024-byte tty. 1024 it is.
+ *
+ * The cap only bites while the tty is CANONICAL — an interactive shell's line editor (readline,
+ * ZLE) puts it in raw mode, where no such limit applies. That is why a long line usually works:
+ * delivery normally lands after the prompt is up. It is not something we may rely on. Measured on
+ * this box: `bash -i` leaves canonical mode within 50 ms, but `sh -i` (dash — no line editor)
+ * stays canonical for the whole life of the pane, so on an editor-less shell EVERY over-cap line
+ * truncates, always. Startup is the other window: an rc file that reads the same tty (oh-my-zsh's
+ * update prompt is the documented example — see `echoedIntact`) holds the pane canonical for as
+ * long as it waits.
+ */
+
+/** macOS `MAX_CANON`. The smallest canonical-mode line buffer across the platforms we ship to. */
+export const MAX_CANON_BYTES = 1024
+
+/**
+ * The longest command we will type into a pane, in bytes. One byte under `MAX_CANON_BYTES`
+ * because the CR that submits the line is buffered with it — measured above: a 4000-byte payload
+ * plus its newline fit a 4096-byte buffer, 5000 did not.
+ */
+export const MAX_LAUNCH_LINE_BYTES = MAX_CANON_BYTES - 1
+
+/** Byte length, not character length: the tty buffers bytes, and a prompt is rarely pure ASCII. */
+export function lineBytes(text: string): number {
+ return new TextEncoder().encode(text).length
+}
+
+/** Can this command be typed into a pane whole? */
+export function fitsLaunchLine(command: string): boolean {
+ return lineBytes(command) <= MAX_LAUNCH_LINE_BYTES
+}