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.

feat(terminal): echo-verified command delivery module

enes00c3d226efc8
diff --git a/src/renderer/terminal/command-delivery.test.ts b/src/renderer/terminal/command-delivery.test.ts
new file mode 100644
index 000000000..f68cd3062
--- /dev/null
+++ b/src/renderer/terminal/command-delivery.test.ts
@@ -0,0 +1,96 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ DELIVERY_ATTEMPTS,
+ VERIFY_TIMEOUT_MS,
+ cleanEcho,
+ deliverCommand,
+ echoedIntact
+} from './command-delivery'
+
+const CMD = `claude --settings x 'implement the rerank feature for search results' --permission-mode auto`
+
+function fakeIo() {
+ const writes: string[] = []
+ let cb: ((chunk: string) => void) | undefined
+ return {
+ writes,
+ emit: (chunk: string) => cb?.(chunk),
+ io: {
+ write: (d: string) => writes.push(d),
+ onData: (fn: (chunk: string) => void) => {
+ cb = fn
+ return () => {
+ cb = undefined
+ }
+ }
+ }
+ }
+}
+
+describe('cleanEcho', () => {
+ it('strips CSI, OSC and other escape sequences plus line breaks', () => {
+ const noisy = '\x1b[1;32mprompt\x1b[0m \x1b]0;title\x07ec' + '\r\n' + 'ho text\x1b[K'
+ expect(cleanEcho(noisy)).toBe('prompt echo text')
+ })
+})
+
+describe('echoedIntact', () => {
+ it('matches on the command tail, tolerating junk before it', () => {
+ expect(echoedIntact(`% ${CMD}`, CMD)).toBe(true)
+ })
+ it('does not match a truncated echo (flush ate the tail)', () => {
+ expect(echoedIntact(CMD.slice(0, -6), CMD)).toBe(false)
+ })
+})
+
+describe('deliverCommand', () => {
+ beforeEach(() => vi.useFakeTimers())
+ afterEach(() => vi.useRealTimers())
+
+ it('writes the command without Enter, then submits once the echo confirms it', () => {
+ const f = fakeIo()
+ deliverCommand(f.io, CMD)
+ expect(f.writes).toEqual([CMD])
+ // Echo arrives in chunks, wrapped with \r\n and colored — still recognized.
+ f.emit('\x1b[32m% \x1b[0m' + CMD.slice(0, 40) + '\r\n')
+ f.emit(CMD.slice(40))
+ expect(f.writes).toEqual([CMD, '\r'])
+ })
+
+ it('kills the line and rewrites when the echo never completes, then succeeds', () => {
+ const f = fakeIo()
+ deliverCommand(f.io, CMD)
+ f.emit(CMD.slice(0, 30)) // the tty flush ate the rest
+ vi.advanceTimersByTime(VERIFY_TIMEOUT_MS)
+ expect(f.writes).toEqual([CMD, '\x15', CMD])
+ f.emit(CMD) // clean echo on attempt 2
+ expect(f.writes).toEqual([CMD, '\x15', CMD, '\r'])
+ })
+
+ it('fails open: after the last attempt times out it submits unverified', () => {
+ const f = fakeIo()
+ deliverCommand(f.io, CMD)
+ for (let i = 0; i < DELIVERY_ATTEMPTS; i++) vi.advanceTimersByTime(VERIFY_TIMEOUT_MS)
+ // attempt 1..N writes, N-1 kill-lines between them, final bare Enter.
+ expect(f.writes.filter((w) => w === CMD)).toHaveLength(DELIVERY_ATTEMPTS)
+ expect(f.writes.filter((w) => w === '\x15')).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)
+ cancel()
+ vi.advanceTimersByTime(VERIFY_TIMEOUT_MS * DELIVERY_ATTEMPTS)
+ f.emit(CMD)
+ expect(f.writes).toEqual([CMD])
+ })
+
+ it('ignores echo arriving after submit (no double Enter)', () => {
+ const f = fakeIo()
+ deliverCommand(f.io, CMD)
+ f.emit(CMD)
+ f.emit(CMD)
+ expect(f.writes).toEqual([CMD, '\r'])
+ })
+})
diff --git a/src/renderer/terminal/command-delivery.ts b/src/renderer/terminal/command-delivery.ts
new file mode 100644
index 000000000..0d39b05d7
--- /dev/null
+++ b/src/renderer/terminal/command-delivery.ts
@@ -0,0 +1,84 @@
+// Two-act delivery of a node's one-shot launch command (initialCommand / cold-restore
+// resume) into a freshly spawned shell. Writing line+Enter blind races shell init: zsh's
+// rc/ZLE setup resets the tty with a FLUSH that can eat part of the queued line, and a
+// mangled line submitted anyway strands the shell at `quote>` (field report: 3 spawned
+// team agents, none started, each needed a manual `'` + Enter). So: write WITHOUT Enter,
+// wait until the shell has echoed the tail of the line back, THEN submit. A verify timeout
+// 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).
+
+export const VERIFY_TIMEOUT_MS = 2000
+export const DELIVERY_ATTEMPTS = 3
+/** Long enough to be unambiguous in the echo stream, short enough that a ZLE wrap/redraw
+ * sequence interleaved mid-line rarely lands inside the matched window. */
+export const ECHO_TAIL_CHARS = 24
+const KILL_LINE = '\x15' // Ctrl-U — clear the pending input line before a rewrite
+
+// CSI (\x1b[...X), OSC (\x1b]...BEL|ST) and single-char ESC sequences.
+// eslint-disable-next-line no-control-regex
+const ESC_SEQ = /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]/g
+
+/** Echo stream → comparable text: drop escape sequences and line breaks (ZLE re-wraps a
+ * long line with explicit \r\n at the terminal width). */
+export function cleanEcho(chunk: string): string {
+ // eslint-disable-next-line no-control-regex
+ return chunk.replace(ESC_SEQ, '').replace(/[\r\n]/g, '')
+}
+
+/** Has the shell echoed the full line? Tail-match: the head is polluted by the prompt. */
+export function echoedIntact(cleanedSoFar: string, cmd: string): boolean {
+ return cleanedSoFar.includes(cmd.slice(-ECHO_TAIL_CHARS))
+}
+
+export interface DeliveryIo {
+ write(data: string): void
+ /** Subscribe to session output; returns unsubscribe. */
+ onData(cb: (chunk: string) => void): () => void
+}
+
+/** Deliver `cmd` + Enter, echo-verified with bounded retries. Returns a cancel function
+ * (call on node teardown). */
+export function deliverCommand(io: DeliveryIo, cmd: string): () => void {
+ let done = false
+ let attempt = 0
+ let echoed = ''
+ let timer: ReturnType<typeof setTimeout> | undefined
+ let unsub: (() => void) | undefined
+
+ const finish = (): void => {
+ done = true
+ if (timer) clearTimeout(timer)
+ unsub?.()
+ }
+ const submit = (): void => {
+ io.write('\r')
+ finish()
+ }
+ const tryOnce = (): void => {
+ if (done) return
+ attempt += 1
+ echoed = ''
+ io.write(cmd)
+ timer = setTimeout(() => {
+ if (done) return
+ if (attempt >= DELIVERY_ATTEMPTS) {
+ submit() // fail-open: unverified submit beats a never-launched agent
+ return
+ }
+ io.write(KILL_LINE)
+ tryOnce()
+ }, VERIFY_TIMEOUT_MS)
+ }
+
+ unsub = io.onData((chunk) => {
+ if (done) return
+ echoed += cleanEcho(chunk)
+ if (echoedIntact(echoed, cmd)) {
+ if (timer) clearTimeout(timer)
+ submit()
+ }
+ })
+ tryOnce()
+ return finish
+}