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(windows): wait for observed text settlement before Enter
enes97fa5c585f37
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 8bb7a4597..f954e3311 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -71,4 +71,4 @@ jobs:run: npm run host:build- name: Windows-relevant tests- run: npx vitest run src/core/fs-atomic.test.ts src/core/fs-atomic.guard.test.ts src/core/exec-path.test.ts src/core/claude-cli.test.ts src/core/codex-identity-caps.test.ts src/core/codex-cli.test.ts src/core/grok-cli.test.ts src/core/commit-message.test.ts src/core/context-link.windows.test.ts src/core/git-service.windows.test.ts src/core/usage/codex-usage.windows.test.ts src/session-host/ src/core/session-host-client.test.ts src/core/session-host-launch-ledger.test.ts src/core/session-host-client-startup-wait.test.ts src/core/agent-launch.test.ts src/core/pty-session-host.test.ts src/main/bootstrap-windows.test.ts src/main/media-protocol.test.ts src/main/remote-atomic-write.test.ts src/main/ssh-fs.test.ts src/main/remote-ssh/ssh-project.test.ts src/renderer/terminal/file-links.test.ts src/renderer/terminal/file-links.windows.test.ts src/renderer/terminal/file-link-dialect.test.ts src/renderer/terminal/host-platform.test.ts src/main/pairing-service.windows.test.ts src/main/windows-ssh-keys.test.ts src/shared/pairing-gate.test.ts src/renderer/components/settings/sections/PhoneSection.windows.test.tsx+ run: npx vitest run src/core/settled-text.test.ts src/core/native-windows-pane.test.ts src/core/fs-atomic.test.ts src/core/fs-atomic.guard.test.ts src/core/exec-path.test.ts src/core/claude-cli.test.ts src/core/codex-identity-caps.test.ts src/core/codex-cli.test.ts src/core/grok-cli.test.ts src/core/commit-message.test.ts src/core/context-link.windows.test.ts src/core/git-service.windows.test.ts src/core/usage/codex-usage.windows.test.ts src/session-host/ src/core/session-host-client.test.ts src/core/session-host-launch-ledger.test.ts src/core/session-host-client-startup-wait.test.ts src/core/agent-launch.test.ts src/core/pty-session-host.test.ts src/main/bootstrap-windows.test.ts src/main/media-protocol.test.ts src/main/remote-atomic-write.test.ts src/main/ssh-fs.test.ts src/main/remote-ssh/ssh-project.test.ts src/renderer/terminal/file-links.test.ts src/renderer/terminal/file-links.windows.test.ts src/renderer/terminal/file-link-dialect.test.ts src/renderer/terminal/host-platform.test.ts src/main/pairing-service.windows.test.ts src/main/windows-ssh-keys.test.ts src/shared/pairing-gate.test.ts src/renderer/components/settings/sections/PhoneSection.windows.test.tsxdiff --git a/CLAUDE.md b/CLAUDE.mdindex 0f26bc7fb..95981c5b7 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1084,13 +1084,19 @@ emulator: a `?2004h` it sees was written by the app itself, which is exactly the`paste-buffer -p` asks tmux for. `HostSession.bracketedPasteRequested()` reads it (behind`outputTail`, like `serialize` — xterm applies writes asynchronously, so an early read answers "no"for the turn that just enabled it) and `sendKeysWrites` (`session-host/send-keys-delivery.ts`)-mirrors the tmux plan: `sanitizePasteText` ALWAYS, the frame only when the app asked, and the Enter-as its own write AFTER the close marker — never inside the framed burst, which is the shape #453-measured as mangled. Unframed it stays one write, byte-identical to the pre-fix path. Before this-the host answered `sendKeys` with a single raw `text + '\r'`, so an injected prompt landed in a-paste-aware composer (Codex, Claude) and was never submitted. **NOT verified on a device**: whether-ConPTY re-emits an app's `?2004h` into the pty stream the host reads. If it does not, the mode is-always false and every write is the old one — no fix, never a regression.+sanitizes ALWAYS and frames only when the app asked. Separate writes alone can still be read+as one burst (#780). Both native Windows `sendText` and host `sendKeys` now execute through+`core/settled-text.ts`: capture a baseline, paste without Enter, then poll at 40 ms for at most+15 polls for a changed, stable screen containing the sanitized text. Only then write one Enter,+after rechecking liveness/generation and paste mode. Unknown capture, unchanged output or timeout+leaves the paste unsubmitted. True still means accepted text, so callers must not retry an+unconfirmed submit and duplicate the paste. Overlapping sendText operations on the same pane+are refused before input; insert-only, empty Enter and unframed input retain their contracts.+A collapsed/hidden/oversize paste may require manual Enter. This is an observed-screen heuristic,+not an application acknowledgement. Linux fake-PTY tests cover a 150 ms busy reader; real Windows+Codex/Claude, context-link/write, dictation and rename device checks remain required. Existing+hosts keep their old implementation until they retire; no automatic host restart is performed.+**The actual fix is older than the problem: `paste-buffer -p`.** From tmux's own man page — *"If`-p` is specified, paste bracket control codes are inserted around the buffer **if the applicationdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex c62e87a5d..29b242d42 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -705,3 +705,9 @@ Two files, two audiences:**If you change or discover something other contributors must know, update this file too.** Aninvariant that only lives in a commit message is one refactor away from being violated by someonewho never saw it.++**Windows text submission waits for the composer.** Use `core/settled-text.ts` for native PTY and+session-host `sendText`: adjacent paste/Enter writes can be consumed in one read. The bounded+screen check may leave text unsubmitted; a true result means text was accepted, not that a turn+started. Never retry the paste just because no submit was observed. Collapsed or hidden pastes+may need manual Enter; device testing remains necessary.diff --git a/src/core/native-windows-pane.ts b/src/core/native-windows-pane.tsindex f80ebdc77..3cc4cf89c 100644--- a/src/core/native-windows-pane.ts+++ b/src/core/native-windows-pane.ts@@ -1,7 +1,7 @@import { randomUUID } from 'crypto'import { TerminalEmulator } from '../session-host/terminal-emulator'import { readWindowsConsoleOwner, sameNativeProcess } from '../session-host/windows-pane-owner'-import { sendKeysWrites } from '../session-host/send-keys-delivery'+import { sendTextWhenSettled } from './settled-text'import type { PaneOwner } from '../shared/agents/pane-owner-predicate'import { sanitizePasteText } from './paste-injection'import { pasteThenSubmitWhenSettled, type SettleOptions } from './settled-submit'@@ -85,17 +85,12 @@ export class NativeWindowsPane {* session for a direct PTY, and failed every time.*/async sendText(text: string, enter: boolean): Promise<boolean> {- if (!this.alive) return false- // The write plan is the session host's `sendKeysWrites` — one rule for both Windows backends,- // so the direct PTY cannot drift from the host on where the Enter goes or what gets stripped.- const bracketed = sanitizePasteText(text) ? await this.pasteAware() : false- if (!this.alive) return false- try {- for (const chunk of sendKeysWrites(text, enter, bracketed)) this.proc.write(chunk)- return true- } catch {- return false- }+ return sendTextWhenSettled(this, text, enter, {+ current: () => this.alive,+ bracketed: () => this.pasteAware(),+ capture: () => this.capture(false),+ write: (chunk) => this.proc.write(chunk)+ }, this.settle)}dispose(): void {diff --git a/src/core/settled-text.test.ts b/src/core/settled-text.test.tsnew file mode 100644index 000000000..6a1ea1bec--- /dev/null+++ b/src/core/settled-text.test.ts@@ -0,0 +1,89 @@+import { describe, expect, it, vi } from 'vitest'+import { sendTextWhenSettled, type TextPane } from './settled-text'++function fixture() {+ let screen: string | null = 'prompt'+ let alive = true+ const write = vi.fn()+ const pane: TextPane = {+ current: () => alive, bracketed: async () => true,+ capture: async () => screen, write+ }+ return { pane, write, screen: (s: string | null) => { screen = s }, exit: () => { alive = false } }+}+describe('observed text settlement', () => {+ it('waits for a slow reader and a stable render, then submits exactly once', async () => {+ const f = fixture()+ let polls = 0+ const wait = async () => {+ expect(f.write.mock.calls).toHaveLength(1)+ if (++polls === 4) f.screen('prompt hello')+ }+ expect(await sendTextWhenSettled(f, 'hello', true, f.pane, { wait })).toBe(true)+ expect(polls).toBe(5)+ expect(f.write.mock.calls).toEqual([['\x1b[200~hello\x1b[201~'], ['\r']])+ })+ it.each(['unchanged', 'unrelated', 'unreadable', 'unstable'])('never submits %s output and bounds the wait', async (kind) => {+ const f = fixture()+ f.screen('hello') // old occurrence is not evidence of THIS paste+ let polls = 0+ const wait = async () => {+ polls+++ if (kind === 'unrelated') f.screen('spinner')+ if (kind === 'unreadable') f.screen(null)+ if (kind === 'unstable') f.screen('hello ' + polls)+ }+ expect(await sendTextWhenSettled(f, 'hello', true, f.pane, { wait })).toBe(true)+ expect(polls).toBe(15)+ expect(f.write).toHaveBeenCalledTimes(1)+ })+ it('does not send Enter after the generation exits/replaces', async () => {+ const f = fixture()+ expect(await sendTextWhenSettled(f, 'hello', true, f.pane, { wait: async () => f.exit() })).toBe(true)+ expect(f.write).toHaveBeenCalledTimes(1)+ })+ it('refuses overlapping text and bare Enter before they write', async () => {+ const f = fixture()+ let once = false+ const overlaps: boolean[] = []+ await sendTextWhenSettled(f, 'hello', true, f.pane, { wait: async () => {+ if (!once) {+ once = true+ overlaps.push(await sendTextWhenSettled(f, '', true, f.pane))+ overlaps.push(await sendTextWhenSettled(f, 'other', true, f.pane, { wait: async () => {} }))+ }+ f.screen('hello')+ } })+ expect(overlaps).toEqual([false, false])+ expect(f.write.mock.calls).toEqual([['\x1b[200~hello\x1b[201~'], ['\r']])+ })+ it('rechecks liveness after capture and paste mode before Enter', async () => {+ for (const change of ['exit', 'mode']) {+ const f = fixture()+ let captures = 0+ vi.spyOn(f.pane, 'capture').mockImplementation(async () => {+ if (++captures === 3 && change === 'exit') f.exit()+ return captures === 1 ? 'prompt' : 'hello'+ })+ vi.spyOn(f.pane, 'bracketed').mockImplementation(async () => !(change === 'mode' && captures >= 3))+ expect(await sendTextWhenSettled(f, 'hello', true, f.pane, { wait: async () => {} })).toBe(true)+ expect(f.write).toHaveBeenCalledTimes(1)+ }+ })+ it('preserves accepted-paste semantics when the final write throws', async () => {+ const f = fixture()+ f.write.mockImplementation((s) => { if (s === '\r') throw Error('exited') })+ expect(await sendTextWhenSettled(f, 'hello', true, f.pane, {+ wait: async () => f.screen('hello')+ })).toBe(true)+ expect(f.write).toHaveBeenCalledTimes(2)+ })+ it('keeps insert-only and empty text immediate', async () => {+ const f = fixture()+ const capture = vi.spyOn(f.pane, 'capture')+ expect(await sendTextWhenSettled(f, 'hello', false, f.pane)).toBe(true)+ expect(await sendTextWhenSettled(f, '', true, f.pane)).toBe(true)+ expect(capture).not.toHaveBeenCalled()+ expect(f.write.mock.calls).toEqual([['\x1b[200~hello\x1b[201~'], ['\r']])+ })+})diff --git a/src/core/settled-text.ts b/src/core/settled-text.tsnew file mode 100644index 000000000..f4173a7ac--- /dev/null+++ b/src/core/settled-text.ts@@ -0,0 +1,72 @@+import { sendKeysWrites } from '../session-host/send-keys-delivery'+import { sanitizePasteText } from './paste-injection'+import { ENVELOPE_SETTLE_POLLS, ENVELOPE_SETTLE_POLL_MS, type SettleOptions } from './settled-submit'++export interface TextPane {+ current(): boolean+ bracketed(): Promise<boolean>+ capture(): Promise<string | null>+ write(text: string): void+}++// Refuse overlapping calls before writing anything, including a second bare Enter. The host+// uses the session object as the key (across sockets); direct PTYs use their pane object.+const pending = new WeakSet<object>()+const visible = (text: string): string => text+ .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')+ .replace(/\s+/g, '')++/** True means text reached the PTY, NOT that the app accepted Enter. Never return false after+ * pasting: callers may retry false, duplicating the composer contents. No blind submit retry.+ * Generic text has no unique envelope footer, so require a changed, stable screen containing+ * the sanitized payload. Collapsed/hidden/oversize pastes may need the user's manual Enter. */+export async function sendTextWhenSettled(+ key: object, text: string, enter: boolean, pane: TextPane, options: SettleOptions = {}+): Promise<boolean> {+ if (pending.has(key) || !pane.current()) return false+ pending.add(key)+ let written = false+ try {+ const body = sanitizePasteText(text)+ const bracketed = body ? await pane.bracketed() : false+ if (!pane.current()) return false+ const capture = async (): Promise<string | null> => {+ if (!pane.current()) return null+ try {+ const value = await pane.capture()+ return pane.current() && value !== null ? visible(value) : null+ } catch { return null }+ }+ const settle = bracketed && enter && !!body+ const before = settle ? await capture() : null+ // The baseline await may have crossed an exit or a mode change.+ if (settle && !(await pane.bracketed())) return false+ if (!pane.current()) return false+ for (const chunk of sendKeysWrites(body, settle ? false : enter, bracketed)) {+ pane.write(chunk)+ written = true+ }+ if (!settle) return true+ const wait = options.wait ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))+ const polls = Math.min(ENVELOPE_SETTLE_POLLS, Math.max(1, options.polls ?? ENVELOPE_SETTLE_POLLS))+ const needle = visible(body)+ let previous: string | null = null+ for (let i = 0; i < polls; i++) {+ await wait(ENVELOPE_SETTLE_POLL_MS)+ if (!pane.current()) break+ const now = await capture()+ if (before !== null && needle && now !== null && now !== before && now.includes(needle)) {+ if (now === previous) {+ if (await pane.bracketed() && pane.current()) pane.write('\r')+ break+ }+ previous = now+ } else previous = null+ }+ return true+ } catch {+ return written+ } finally {+ pending.delete(key)+ }+}diff --git a/src/session-host/host.ts b/src/session-host/host.tsindex 78cb7b16c..57de7d5df 100644--- a/src/session-host/host.ts+++ b/src/session-host/host.ts@@ -31,7 +31,7 @@ import {type ListSessionsResult} from './protocol'import { HostSession } from './session'-import { sendKeysWrites } from './send-keys-delivery'+import { sendTextWhenSettled } from '../core/settled-text'import { paneCommand as readPaneCommand } from './process-tree'import { terminateWindowsProcessTree } from './windows-process-tree'import { publishSessionHostState } from './state-file'@@ -821,14 +821,13 @@ async function main(): Promise<void> {case 'sendKeys': {const s = sessions.get(req.name)if (!s || s.exited) return { ok: false, error: 'no such session' }- // Framed from the pane's REAL bracketed-paste state, with the Enter as its own write —- // the session host's equivalent of tmux's `paste-buffer -p` + `send-keys Enter`. See- // send-keys-delivery.ts; the mode read crosses the emulator tail, so re-check liveness- // after it rather than writing into a session that exited meanwhile.- const bracketed = await s.bracketedPasteRequested()- if (s.exited || sessions.get(req.name) !== s) return { ok: false, error: 'no such session' }- for (const chunk of sendKeysWrites(req.text, req.enter, bracketed)) s.proc.write(chunk)- return { ok: true }+ const ok = await sendTextWhenSettled(s, req.text, req.enter, {+ current: () => !s.exited && sessions.get(req.name) === s,+ bracketed: () => s.bracketedPasteRequested(),+ capture: () => s.serialize(200),+ write: (chunk) => s.proc.write(chunk)+ })+ return ok ? { ok: true } : { ok: false, error: 'session unavailable or delivery busy' }}case 'paneCommand': {const s = sessions.get(req.name)diff --git a/src/session-host/send-keys-delivery.ts b/src/session-host/send-keys-delivery.tsindex 63e5a58fe..4723ffc19 100644--- a/src/session-host/send-keys-delivery.ts+++ b/src/session-host/send-keys-delivery.ts@@ -17,11 +17,9 @@// hands an AGENT's text to this same path.// - The frame is written only when the app REQUESTED bracketed paste. Writing markers at an app// that never asked puts literal `[200~` in its input.-// - The Enter is its OWN write, after the close marker — not appended inside the framed burst.-// This is where the tmux leg moved after #453: a paste-aware composer cannot re-chunk a key-// event that arrives after a definitive close marker, while the "Enter inside the same write"-// shape the older comment described is the one that was mangled. Unframed, the Enter stays-// inside the single write, which is byte-identical to what this path did before.+// - The Enter is a separate write. This byte plan alone is NOT a timing guarantee: ConPTY+// can coalesce adjacent writes. `core/settled-text.ts` executes framed sendText with observed+// settlement before requesting the bare Enter. Unframed input retains its single write.// - An empty payload with `enter` is a bare Enter — `sendText('', { enter: true })` is a live// call meaning "submit whatever is composed" (`Canvas.tsx`'s write verb, `settled-envelope.ts`).//diff --git a/src/session-host/send-keys-host.test.ts b/src/session-host/send-keys-host.test.tsindex 983fe957d..169146a9f 100644--- a/src/session-host/send-keys-host.test.ts+++ b/src/session-host/send-keys-host.test.ts@@ -37,18 +37,28 @@ function fakePtyPlugin(): Plugin {contents: `const fs = require('fs')export function spawn() {- let onExit+ let onExit, output, draining = falseconst log = process.env.NT_TEST_WRITE_LOGconst announce = process.env.NT_TEST_PTY_OUTPUTreturn {pid: 4242,onData(cb) {+ output = cb// Repeated so the announcement cannot be lost to the host registering late; a// DECSET is idempotent, and every repeat crosses the same emulator tail.if (announce) for (let i = 1; i <= 5; i++) setTimeout(() => cb(announce), i * 20)},onExit(cb) { onExit = cb },- write(data) { fs.appendFileSync(log, JSON.stringify(data) + '\\n') },+ write(data) {+ fs.appendFileSync(log, JSON.stringify(draining && data === '\\r' ? 'SWALLOWED' : data) + '\\n')+ if (data.startsWith('\\x1b[200~') && process.env.NT_TEST_RENDER !== 'false') {+ draining = true+ setTimeout(() => {+ draining = false+ output?.(data.slice(6, -6))+ }, 150)+ }+ },resize() {},pause() {},resume() {},@@ -147,6 +157,7 @@ afterEach(() => {/** Boot the real bundled host against the fake pty and return the writes one sendKeys produced. */async function writesForSendKeys(opts: {announce?: string+ render?: booleantext: stringenter: boolean/** Poll `capture` until the serialized screen proves this mode reached the emulator. */@@ -175,7 +186,7 @@ async function writesForSendKeys(opts: {cwd: process.cwd(),stdio: 'ignore',windowsHide: true,- env: { ...process.env, NT_TEST_WRITE_LOG: writeLog, NT_TEST_PTY_OUTPUT: opts.announce ?? '' }+ env: { ...process.env, NT_TEST_WRITE_LOG: writeLog, NT_TEST_PTY_OUTPUT: opts.announce ?? '', NT_TEST_RENDER: String(opts.render ?? true) }})let socket: Socket | null = nulltry {@@ -230,6 +241,13 @@ describe('session-host sendKeys delivery', () => {expect(writes).toEqual([`${PASTE_START}summarise the linked context${PASTE_END}`, '\r'])}, 30_000)+ it('does not submit a paste that never renders', async () => {+ expect(await writesForSendKeys({+ announce: '\x1b[?2004h', awaitMode: '\x1b[?2004h',+ text: 'unseen', enter: true, render: false+ })).toEqual([`${PASTE_START}unseen${PASTE_END}`])+ }, 30_000)+it('leaves a pane that never asked byte-identical to the pre-fix single write', async () => {const writes = await writesForSendKeys({ text: 'npm test', enter: true })expect(writes).toEqual(['npm test\r'])