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(delivery): use Escape to clear line before delivery retries on Windows shells
abhirupone29fbbb74945e
diff --git a/src/core/session-host-launch-ledger.test.ts b/src/core/session-host-launch-ledger.test.tsindex aaeb66f74..bbb7f64f9 100644--- a/src/core/session-host-launch-ledger.test.ts+++ b/src/core/session-host-launch-ledger.test.ts@@ -28,7 +28,7 @@ class FakePty {write(data: string): void {this.writes.push(data)this.onWrite?.(data)- if (this.echoWrites && data !== '\r' && data !== '\x15') this.emitData(data)+ if (this.echoWrites && data !== '\r' && data !== '\x15' && data !== '\x1b') this.emitData(data)}emitData(data: string): void {diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 7211e4ca2..a4190dd1a 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -106,7 +106,13 @@ import {validCellSize,type Vec2} from '../lib/glyphGridNode'-import { cleanEcho, deliverCommand, KILL_LINE, type DeliveryIo } from '../terminal/command-delivery'+import {+ cleanEcho,+ deliverCommand,+ KILL_LINE,+ WINDOWS_KILL_LINE,+ type DeliveryIo+} from '../terminal/command-delivery'import {RESUME_MISS_WINDOW_MS,detectsResumeMiss,@@ -1558,6 +1564,12 @@ export function TerminalNode({!parentWtStale &&!remoteSession &&(data.cwd as string | undefined) !== parentWtPath+ const getTerminalKillLine = (): string => {+ const isWindows =+ (corePlatformRef.current === 'win32' || (isWindowsPlatform() && session.source === 'local')) &&+ !remoteSession+ return isWindows ? WINDOWS_KILL_LINE : KILL_LINE+ }const status = useAgentStatus((s) => s.byId[id])/*** Which Claude account this node is ACTUALLY on. `data.accountId` is what nodeterm launched@@ -3325,7 +3337,8 @@ export function TerminalNode({if (outcome === 'line-too-long') {setCo(termKey, { launchTooLongBytes: lineBytes(cmd) })}- }+ },+ { killLine: getTerminalKillLine() }))})@@ -3719,6 +3732,7 @@ export function TerminalNode({// An unusable session id leaves this undefined and performRestartResume refuses the// restart on its own `resumeCommand` gate — nothing is written either way.command,+ killLine: getTerminalKillLine(),// Session-scoped (`api`, not the global preload), like readScrollback above: a relay// tab's pane lives on the host, and only its own api can see it.paneCommand: () => api.pty.paneCommand(id),@@ -3860,12 +3874,14 @@ export function TerminalNode({// reason; the wake half owes the same. Deliberately HERE and not inside// `performResumePhase`: that function's output is pinned byte-for-byte by Task 8's tests,// and the restart path (which just cleared the line itself) must not clear it twice.- restartIo.write(KILL_LINE)+ const killLine = getTerminalKillLine()+ restartIo.write(killLine)return performResumePhase({agentId,sessionId: agentSessionId,io: restartIo,command,+ killLine,isLive: restartTarget,onDelivery: (cancel) => {if (life.dead) cancel()diff --git a/src/renderer/terminal/agent-restart.test.ts b/src/renderer/terminal/agent-restart.test.tsindex 952f0c75f..9338608fb 100644--- a/src/renderer/terminal/agent-restart.test.ts+++ b/src/renderer/terminal/agent-restart.test.ts@@ -683,6 +683,29 @@ describe('performResumePhase', () => {expect(written.join('')).toContain('claude --resume sid-1 --permission-mode plan')})+ it('forwards custom killLine to deliverCommand on verification retry', async () => {+ const written: string[] = []+ const io = {+ write(d: string) {+ written.push(d)+ },+ onData() {+ return () => {}+ }+ }+ const p = performResumePhase({+ agentId: 'claude',+ sessionId: 'sid-1',+ io,+ killLine: '\x1b'+ })+ await vi.advanceTimersByTimeAsync(2000)+ expect(written).toContain('\x1b')+ expect(written).not.toContain('\x15')+ await vi.advanceTimersByTimeAsync(10000)+ await p+ })+it('keeps the bare command as the gate even when the caller overrides it', async () => {const { written, io } = fakeIo()expect(diff --git a/src/renderer/terminal/agent-restart.ts b/src/renderer/terminal/agent-restart.tsindex e6666de20..8a5d5cb09 100644--- a/src/renderer/terminal/agent-restart.ts+++ b/src/renderer/terminal/agent-restart.ts@@ -273,6 +273,7 @@ export async function performResumePhase(d: {command?: string/** Backstop for the resume delivery; see RESTART_DELIVERY_TIMEOUT_MS. */deliveryTimeoutMs?: number+ killLine?: string/*** Handed `deliverCommand`'s cancel the moment a delivery starts — and only then. The delivery* outlives this promise (it runs on its own echo-verify timers), so its lifetime belongs to@@ -319,7 +320,12 @@ export async function performResumePhase(d: {// Two statements on purpose: `d.onDelivery?.(deliverCommand(…))` short-circuits the ARGUMENT// too when no callback was passed — nothing would be delivered and this promise would never// settle.- const cancelDelivery = deliverCommand(d.io, cmd, settle)+ const cancelDelivery = deliverCommand(+ d.io,+ cmd,+ settle,+ d.killLine !== undefined ? { killLine: d.killLine } : undefined+ )started = trued.onDelivery?.(cancelDelivery)} catch (e) {@@ -360,6 +366,7 @@ export async function performRestartResume(d: {pollMs?: number/** Backstop for the resume delivery; see RESTART_DELIVERY_TIMEOUT_MS. */deliveryTimeoutMs?: number+ killLine?: string/** Handed `deliverCommand`'s cancel as the delivery starts; see `performResumePhase`. */onDelivery?: (cancel: () => void) => void/**@@ -388,6 +395,7 @@ export async function performRestartResume(d: {io: d.io,command: d.command,deliveryTimeoutMs: d.deliveryTimeoutMs,+ killLine: d.killLine,onDelivery: d.onDelivery,isLive: d.isLive})diff --git a/src/renderer/terminal/command-delivery.test.ts b/src/renderer/terminal/command-delivery.test.tsindex cfc972336..34541840c 100644--- a/src/renderer/terminal/command-delivery.test.ts+++ b/src/renderer/terminal/command-delivery.test.ts@@ -3,6 +3,7 @@ import {DELIVERY_ATTEMPTS,KILL_LINE,VERIFY_TIMEOUT_MS,+ WINDOWS_KILL_LINE,cleanEcho,deliverCommand,echoedIntact@@ -124,6 +125,25 @@ describe('deliverCommand', () => {expect(f.writes[f.writes.length - 1]).toBe('\r')})+ it('uses custom killLine (WINDOWS_KILL_LINE) when provided in options', () => {+ const f = fakeIo()+ deliverCommand(f.io, CMD, undefined, { killLine: WINDOWS_KILL_LINE })+ f.emit(CMD.slice(0, 30))+ vi.advanceTimersByTime(VERIFY_TIMEOUT_MS)+ expect(f.writes).toEqual([CMD, WINDOWS_KILL_LINE, CMD])+ f.emit(CMD)+ expect(f.writes).toEqual([CMD, WINDOWS_KILL_LINE, CMD, '\r'])+ })++ it('fails open with WINDOWS_KILL_LINE between retries when echo never arrives', () => {+ const f = fakeIo()+ deliverCommand(f.io, CMD, undefined, { killLine: WINDOWS_KILL_LINE })+ for (let i = 0; i < DELIVERY_ATTEMPTS; i++) vi.advanceTimersByTime(VERIFY_TIMEOUT_MS)+ expect(f.writes.filter((w) => w === CMD)).toHaveLength(DELIVERY_ATTEMPTS)+ expect(f.writes.filter((w) => w === WINDOWS_KILL_LINE)).toHaveLength(DELIVERY_ATTEMPTS - 1)+ expect(f.writes[f.writes.length - 1]).toBe('\r')+ })+it('cancel stops timers and listeners cold', () => {const f = fakeIo()const cancel = deliverCommand(f.io, CMD)@@ -288,4 +308,17 @@ describe('a launch line longer than the tty can carry (issue #706)', () => {expect(outcome).toBe('submitted')expect(f.writes).toContain('\r')})++ it('clears line with WINDOWS_KILL_LINE on line-too-long when configured', () => {+ const f = fakeIo()+ let outcome: string | undefined+ deliverCommand(f.io, LONG, (o) => (outcome = o), { killLine: WINDOWS_KILL_LINE })+ 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(WINDOWS_KILL_LINE)+ })})diff --git a/src/renderer/terminal/command-delivery.ts b/src/renderer/terminal/command-delivery.tsindex fd40c63ef..11ee38ade 100644--- a/src/renderer/terminal/command-delivery.ts+++ b/src/renderer/terminal/command-delivery.ts@@ -18,9 +18,13 @@ import { fitsLaunchLine } from '@shared/canonical-line'export const VERIFY_TIMEOUT_MS = 2000export const DELIVERY_ATTEMPTS = 3-/** Ctrl-U — clear the pending input line before a rewrite. Exported because the in-place restart- * choreography clears the line the same way before typing its exit command (agent-restart.ts). */export const KILL_LINE = '\x15'+/** Escape — clear the pending input line in Windows shells (PowerShell, cmd.exe). */+export const WINDOWS_KILL_LINE = '\x1b'++export interface DeliverCommandOptions {+ killLine?: string+}// CSI (\x1b[...X), OSC (\x1b]...BEL|ST) and single-char ESC sequences.// eslint-disable-next-line no-control-regex@@ -94,8 +98,10 @@ export interface DeliveryIo {export function deliverCommand(io: DeliveryIo,cmd: string,- onSettled?: (outcome: DeliveryOutcome) => void+ onSettled?: (outcome: DeliveryOutcome) => void,+ options?: DeliverCommandOptions): () => void {+ const killLine = options?.killLine ?? KILL_LINElet done = falselet attempt = 0let echoed = ''@@ -156,14 +162,14 @@ export function deliverCommand(// 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)+ write(killLine)finish('line-too-long')return}submit() // fail-open: unverified submit beats a never-launched agentreturn}- if (!write(KILL_LINE)) return // transport gone — the delivery is over, not stuck+ if (!write(killLine)) return // transport gone — the delivery is over, not stucktryOnce()}, VERIFY_TIMEOUT_MS)write(cmd, attempt === 1)diff --git a/src/session-host/session.test.ts b/src/session-host/session.test.tsindex 58e75b1a3..cfde65e61 100644--- a/src/session-host/session.test.ts+++ b/src/session-host/session.test.ts@@ -3,8 +3,11 @@ import type { Socket } from 'net'import type { IPty } from 'node-pty'import {HostSession,+ KILL_LINE,SESSION_EMULATOR_OUTPUT_HIGH_WATER_BYTES,- SESSION_EMULATOR_OUTPUT_LOW_WATER_BYTES+ SESSION_EMULATOR_OUTPUT_LOW_WATER_BYTES,+ WINDOWS_KILL_LINE,+ shellKillLineSequence} from './session'import type { TerminalEmulator } from './terminal-emulator'import type { SessionHostSpawnOptions } from './protocol'@@ -612,4 +615,95 @@ describe('HostSession launch echo verification', () => {// submit() is synchronous inside the data handler, so its absence is observable now.expect(proc.written).not.toContain('\r')})++ it('clears line with \\x1b on Windows PowerShell during retry and refusal', async () => {+ vi.useFakeTimers()+ try {+ const proc = deliveryProc()+ const winSpawn: SessionHostSpawnOptions = {+ ...SPAWN,+ shell: 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe',+ launchDialect: 'windows-powershell'+ }+ const session = new HostSession('echo-win-retry', winSpawn, 100, {+ proc: proc.value,+ term: inertTerm()+ })+ const delivered = deliver(session, COMMAND)+ const failure = expect(delivered).rejects.toThrow(+ 'session-host could not verify launch command delivery'+ )+ await vi.advanceTimersByTimeAsync(2_000 * 3)+ await failure+ expect(proc.written).toEqual([+ COMMAND,+ WINDOWS_KILL_LINE,+ COMMAND,+ WINDOWS_KILL_LINE,+ COMMAND,+ WINDOWS_KILL_LINE+ ])+ } finally {+ vi.useRealTimers()+ }+ })++ it('clears line with \\x15 on POSIX shells during retry and refusal', async () => {+ vi.useFakeTimers()+ try {+ const proc = deliveryProc()+ const posixSpawn: SessionHostSpawnOptions = {+ ...SPAWN,+ shell: '/bin/zsh',+ launchDialect: 'posix'+ }+ const session = new HostSession('echo-posix-retry', posixSpawn, 100, {+ proc: proc.value,+ term: inertTerm()+ })+ const delivered = deliver(session, COMMAND)+ const failure = expect(delivered).rejects.toThrow(+ 'session-host could not verify launch command delivery'+ )+ await vi.advanceTimersByTimeAsync(2_000 * 3)+ await failure+ expect(proc.written).toEqual([+ COMMAND,+ KILL_LINE,+ COMMAND,+ KILL_LINE,+ COMMAND,+ KILL_LINE+ ])+ } finally {+ vi.useRealTimers()+ }+ })+})++describe('shellKillLineSequence', () => {+ it('returns \\x1b for Windows PowerShell, pwsh, and cmd dialects', () => {+ expect(shellKillLineSequence('windows-powershell')).toBe(WINDOWS_KILL_LINE)+ expect(shellKillLineSequence('pwsh')).toBe(WINDOWS_KILL_LINE)+ expect(shellKillLineSequence('cmd')).toBe(WINDOWS_KILL_LINE)+ })++ it('returns \\x15 for posix dialect', () => {+ expect(shellKillLineSequence('posix')).toBe(KILL_LINE)+ })++ it('infers sequence from shell executable name when dialect is omitted', () => {+ expect(shellKillLineSequence(undefined, 'powershell.exe')).toBe(WINDOWS_KILL_LINE)+ expect(shellKillLineSequence(undefined, 'powershell')).toBe(WINDOWS_KILL_LINE)+ expect(shellKillLineSequence(undefined, 'pwsh.exe')).toBe(WINDOWS_KILL_LINE)+ expect(shellKillLineSequence(undefined, 'cmd.exe')).toBe(WINDOWS_KILL_LINE)+ expect(shellKillLineSequence(undefined, 'bash.exe')).toBe(KILL_LINE)+ expect(shellKillLineSequence(undefined, 'zsh')).toBe(KILL_LINE)+ })++ it('falls back based on host platform when dialect and shell executable are unknown', () => {+ expect(shellKillLineSequence(undefined, undefined, 'win32')).toBe(WINDOWS_KILL_LINE)+ expect(shellKillLineSequence(undefined, undefined, 'darwin')).toBe(KILL_LINE)+ expect(shellKillLineSequence(undefined, undefined, 'linux')).toBe(KILL_LINE)+ })})diff --git a/src/session-host/session.ts b/src/session-host/session.tsindex f4a35d954..061ce2bf6 100644--- a/src/session-host/session.ts+++ b/src/session-host/session.ts@@ -16,7 +16,37 @@ const LAUNCH_READINESS_POLL_MS = 100const VERIFY_TIMEOUT_MS = 2_000const ECHO_EDGE_CHARS = 24const DELIVERY_ATTEMPTS = 3-const KILL_LINE = '\x15'+export const KILL_LINE = '\x15'+export const WINDOWS_KILL_LINE = '\x1b'++export function shellKillLineSequence(+ dialect?: SessionHostShellDialect,+ shellExecutableName?: string,+ platform: NodeJS.Platform = process.platform+): string {+ if (dialect === 'pwsh' || dialect === 'windows-powershell' || dialect === 'cmd') {+ return WINDOWS_KILL_LINE+ }+ if (dialect === 'posix') {+ return KILL_LINE+ }+ const exe = (shellExecutableName ?? '').toLowerCase()+ if (+ exe === 'powershell' ||+ exe === 'powershell.exe' ||+ exe === 'pwsh' ||+ exe === 'pwsh.exe' ||+ exe === 'cmd' ||+ exe === 'cmd.exe'+ ) {+ return WINDOWS_KILL_LINE+ }+ if (exe === 'bash' || exe === 'bash.exe' || exe === 'zsh' || exe === 'sh' || exe === 'fish') {+ return KILL_LINE+ }+ return platform === 'win32' ? WINDOWS_KILL_LINE : KILL_LINE+}+const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i// eslint-disable-next-line no-control-regexconst ESC_SEQ = /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]/g@@ -169,6 +199,10 @@ export class HostSession {return this.privateLaunchOutput}+ get killLineSequence(): string {+ return shellKillLineSequence(this.launchDialect, this.shellExecutableName)+ }+/** True once a successful explicit kill has claimed the name but before node-pty proves process* death with onExit. Same-name attach waits behind `ending` instead of joining this generation. */retiring = false@@ -576,11 +610,11 @@ export class HostSession {if (attempt >= DELIVERY_ATTEMPTS) {// Never submit an unverified/mangled command. Clear it so the terminal remains// recoverable, cache the fixed failure, and let explicit user action decide next.- write(KILL_LINE)+ write(this.killLineSequence)finish(new Error('session-host could not verify launch command delivery'))return}- if (!write(KILL_LINE)) return+ if (!write(this.killLineSequence)) returntryOnce()}, VERIFY_TIMEOUT_MS)timer.unref?.()