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(windows): surface pasted but unsubmitted text delivery

review17042848b170
diff --git a/CLAUDE.md b/CLAUDE.md
index 56e133734..1becefbc3 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1096,13 +1096,16 @@ as one burst (#780). Both native Windows `sendText` and host `sendKeys` now exec
`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
+leaves the paste unsubmitted and returns `pasted-not-submitted`, never `true`. The discriminant
+survives IPC/WS and `sendKeysV2`; canvas writes name the partial delivery, trigger runs record
+a terminal miss (including queue flush), and one-way UI writers raise a visible warning. Test
+success with `=== true`, never truthiness. Do 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.
+hosts refuse the additive `sendKeysV2` command until they retire; no raw-write fallback or
+automatic host restart is performed. Legacy clients still use the existing `sendKeys` command.
**The actual fix is older than the problem: `paste-buffer -p`.** From tmux's own man page — *"If
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index a2c731359..bd69f481d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -841,9 +841,11 @@ who 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.
+screen check may leave text unsubmitted; propagate `pasted-not-submitted` all the way to the
+caller and tell the user to inspect the terminal. Never treat that truthy string as success or
+automatically retry the paste. True means the requested writes completed, not that a turn began.
+The versioned `sendKeysV2` host request refuses old hosts without fallback or restart. Collapsed
+or hidden pastes may need manual Enter; device testing remains necessary.
An unanswered Claude `AskUserQuestion` is correlated by session and tool-use ID in the core
mirror, independently of its short-lived display stash. Ordinary hooks, subagent activity and
diff --git a/docs/windows-session-host.md b/docs/windows-session-host.md
index b5f5a1f5c..649343611 100644
--- a/docs/windows-session-host.md
+++ b/docs/windows-session-host.md
@@ -685,3 +685,14 @@ Windows named-pipe DACL hardening remain outside this profile pass as described
`spawnSession()`'s new branch automatically (they call it directly with no prior async
pre-check), so they work, but were not separately hand-verified end-to-end through the relay
feature itself in this pass — only the primary create/join/reconnect/capture/kill paths were.
+
+### Non-message delivery result (#780)
+
+New callers use additive `sendKeysV2`, returning `result.delivery`: `true` for completed
+requested writes, `false` before input, or `pasted-not-submitted` when paste landed but the
+settle/mode/generation checks withheld Enter. The last result is terminal for automatic
+delivery: inspect the terminal, do not resend or blindly press Enter. Canvas write, trigger
+run history, and one-way UI writers surface it. An older host refuses this command and keeps
+its sessions; there is no fallback to `sendKeys`, raw input, or automatic restart. Legacy
+clients retain their existing `sendKeys` wire contract. No real Windows TUI measurement is
+claimed by the fake-PTY regression fixtures.
diff --git a/src/core/native-windows-pane.test.ts b/src/core/native-windows-pane.test.ts
index f28dab45b..5da3c9e1a 100644
--- a/src/core/native-windows-pane.test.ts
+++ b/src/core/native-windows-pane.test.ts
@@ -69,6 +69,17 @@ describe('native Windows envelope delivery', () => {
})
describe('native Windows sendText (the write verb and the app’s own writers)', () => {
+ it('reports folded pasted text without submitting or retrying', async () => {
+ const write = vi.fn()
+ const pane = new NativeWindowsPane({ pid: 10, write },
+ { cols: 80, rows: 24, scrollback: 100 }, async () => expected, {
+ wait: async () => pane.recordOutput('\r> [Pasted text #1 +40 lines]')
+ })
+ panes.push(pane)
+ pane.recordOutput('\x1b[?2004h')
+ expect(await pane.sendText('a\nb\nc', true)).toBe('pasted-not-submitted')
+ expect(write.mock.calls).toEqual([['\x1b[200~a\nb\nc\x1b[201~']])
+ })
it('waits for a busy direct PTY composer before its single Enter', async () => {
const write = vi.fn()
let polls = 0
diff --git a/src/core/native-windows-pane.ts b/src/core/native-windows-pane.ts
index 3cc4cf89c..5dee821f2 100644
--- a/src/core/native-windows-pane.ts
+++ b/src/core/native-windows-pane.ts
@@ -1,3 +1,4 @@
+import type { TextDeliveryResult } from '../shared/text-delivery'
import { randomUUID } from 'crypto'
import { TerminalEmulator } from '../session-host/terminal-emulator'
import { readWindowsConsoleOwner, sameNativeProcess } from '../session-host/windows-pane-owner'
@@ -84,7 +85,7 @@ export class NativeWindowsPane {
* the pane. Without it those callers fell through to the session-host backend, which has no
* session for a direct PTY, and failed every time.
*/
- async sendText(text: string, enter: boolean): Promise<boolean> {
+ async sendText(text: string, enter: boolean): Promise<TextDeliveryResult> {
return sendTextWhenSettled(this, text, enter, {
current: () => this.alive,
bracketed: () => this.pasteAware(),
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index b454da0eb..145767307 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -1,3 +1,4 @@
+import type { TextDeliveryResult } from '../shared/text-delivery'
import os from 'os'
import fs from 'fs'
import path from 'path'
@@ -4194,7 +4195,7 @@ export class PtyManager {
* composition is exported, both callers use it, and the only thing left in this method is which
* transport runs it.
*/
- async sendText(persistKey: string, text: string, opts?: { enter?: boolean }): Promise<boolean> {
+ async sendText(persistKey: string, text: string, opts?: { enter?: boolean }): Promise<TextDeliveryResult> {
const enter = opts?.enter ?? true
const target = sessionName(persistKey)
const live = this.liveSessionForPersistKey(persistKey)
diff --git a/src/core/session-host-backend.ts b/src/core/session-host-backend.ts
index 4bf48ceec..aa80eedeb 100644
--- a/src/core/session-host-backend.ts
+++ b/src/core/session-host-backend.ts
@@ -1,3 +1,4 @@
+import type { TextDeliveryResult } from '../shared/text-delivery'
// The thin facade `pty-manager.ts` talks to — owns the ONE process-wide `SessionHostClient` (one
// long-lived connection per app process, matching how `PtyManager` itself keeps one `tmuxPath`
// for the whole process) and exposes exactly the operations pty-manager's existing tmux/ssh call
@@ -83,7 +84,7 @@ export function attachExistingSessionHostPty(name: string): SessionHostPty {
/** Background write — works whether or not this process currently has a live client for `name`,
* exactly like `sendText`'s tmux `send-keys -t <name>` needs no attached client. */
-export async function sessionHostSendKeys(name: string, text: string, enter: boolean): Promise<boolean> {
+export async function sessionHostSendKeys(name: string, text: string, enter: boolean): Promise<TextDeliveryResult> {
return getClient().sendKeys(name, text, enter)
}
diff --git a/src/core/session-host-client.test.ts b/src/core/session-host-client.test.ts
index f308b9818..71500c59e 100644
--- a/src/core/session-host-client.test.ts
+++ b/src/core/session-host-client.test.ts
@@ -217,6 +217,30 @@ describe('SessionHostClient handshake transition', () => {
// No fallback to sendKeys/write/executeLaunch, no kill, no replacement/attach request.
})
+ it.each([true, false, 'pasted-not-submitted', undefined] as const)('preserves sendKeysV2 outcome %s', async (delivery) => {
+ const { userDataDir, paths } = createUserData('text-delivery-result')
+ const commands: string[] = []
+ await serve(paths.endpoint, (request, socket) => {
+ commands.push(request.cmd)
+ if (request.cmd === 'hello') socket.write(acceptedHello(request.id))
+ else socket.write(encodeFrame({ id: request.id, ok: true, result: { delivery } }))
+ })
+ const client = new SessionHostClient({ userDataDir, repoRoot: userDataDir })
+ expect(await within(client.sendKeys('nt-existing', 'long text', true))).toBe(delivery ?? 'pasted-not-submitted')
+ expect(commands).toEqual(['hello', 'sendKeysV2'])
+ })
+ it('does not fall back or restart an older host that refuses sendKeysV2', async () => {
+ const { userDataDir, paths } = createUserData('old-text-host')
+ const commands: string[] = []
+ await serve(paths.endpoint, (request, socket) => {
+ commands.push(request.cmd)
+ socket.write(request.cmd === 'hello' ? acceptedHello(request.id) : encodeFrame({ id: request.id, ok: false, error: 'unknown command' }))
+ })
+ const client = new SessionHostClient({ userDataDir, repoRoot: userDataDir })
+ expect(await within(client.sendKeys('nt-existing', 'text', true))).toBe(false)
+ expect(commands).toEqual(['hello', 'sendKeysV2'])
+ })
+
it('hands the socket to the production listener before the first attach response and data', async () => {
const { userDataDir, paths, token } = createUserData('test-token-kept-off-argv')
diff --git a/src/core/session-host-client.ts b/src/core/session-host-client.ts
index fe5c6f956..cab697139 100644
--- a/src/core/session-host-client.ts
+++ b/src/core/session-host-client.ts
@@ -1,3 +1,4 @@
+import type { TextDeliveryResult } from '../shared/text-delivery'
// The Electron-main-side client for the session host: one long-lived connection per app process,
// auto-spawning the host on first use and restoring every live local attachment before allowing
// ordinary traffic through a replacement connection.
@@ -1408,10 +1409,11 @@ export class SessionHostClient {
}
}
- async sendKeys(name: string, text: string, enter: boolean): Promise<boolean> {
+ async sendKeys(name: string, text: string, enter: boolean): Promise<TextDeliveryResult> {
try {
- await this.request({ cmd: 'sendKeys', name, text, enter })
- return true
+ const result = await this.request<{ delivery?: TextDeliveryResult } | undefined>({ cmd: 'sendKeysV2', name, text, enter })
+ // A malformed success cannot prove submission; never retry a possibly accepted paste.
+ return result?.delivery === true || result?.delivery === false ? result.delivery : 'pasted-not-submitted'
} catch {
return false
}
diff --git a/src/core/settled-text.test.ts b/src/core/settled-text.test.ts
index 6a1ea1bec..09f343d10 100644
--- a/src/core/settled-text.test.ts
+++ b/src/core/settled-text.test.ts
@@ -33,19 +33,19 @@ describe('observed text settlement', () => {
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(await sendTextWhenSettled(f, 'hello', true, f.pane, { wait })).toBe('pasted-not-submitted')
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(await sendTextWhenSettled(f, 'hello', true, f.pane, { wait: async () => f.exit() })).toBe('pasted-not-submitted')
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[] = []
+ const overlaps: unknown[] = []
await sendTextWhenSettled(f, 'hello', true, f.pane, { wait: async () => {
if (!once) {
once = true
@@ -66,7 +66,7 @@ describe('observed text settlement', () => {
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(await sendTextWhenSettled(f, 'hello', true, f.pane, { wait: async () => {} })).toBe('pasted-not-submitted')
expect(f.write).toHaveBeenCalledTimes(1)
}
})
@@ -75,9 +75,17 @@ describe('observed text settlement', () => {
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)
+ })).toBe('pasted-not-submitted')
expect(f.write).toHaveBeenCalledTimes(2)
})
+ it('reports a folded multiline paste without submitting or duplicating it', async () => {
+ const f = fixture()
+ const text = Array.from({ length: 80 }, (_, i) => `line ${i}`).join('\n')
+ expect(await sendTextWhenSettled(f, text, true, f.pane, {
+ wait: async () => f.screen('> [Pasted text #1 +80 lines]')
+ })).toBe('pasted-not-submitted')
+ expect(f.write.mock.calls).toEqual([[`\x1b[200~${text}\x1b[201~`]])
+ })
it('keeps insert-only and empty text immediate', async () => {
const f = fixture()
const capture = vi.spyOn(f.pane, 'capture')
diff --git a/src/core/settled-text.ts b/src/core/settled-text.ts
index f4173a7ac..6f9f339bf 100644
--- a/src/core/settled-text.ts
+++ b/src/core/settled-text.ts
@@ -1,3 +1,4 @@
+import type { TextDeliveryResult } from '../shared/text-delivery'
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'
@@ -16,13 +17,13 @@ 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. */
+/** True means the requested writes completed (not application acknowledgement). A partial
+ * paste is explicit: callers must surface it and never automatically resend it. Generic text
+ * requires a changed, stable screen containing the payload before submitting; unknown/folded
+ * composers are left untouched rather than blindly pressing Enter. */
export async function sendTextWhenSettled(
key: object, text: string, enter: boolean, pane: TextPane, options: SettleOptions = {}
-): Promise<boolean> {
+): Promise<TextDeliveryResult> {
if (pending.has(key) || !pane.current()) return false
pending.add(key)
let written = false
@@ -57,15 +58,18 @@ export async function sendTextWhenSettled(
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')
+ if (await pane.bracketed() && pane.current()) {
+ pane.write('\r')
+ return true
+ }
break
}
previous = now
} else previous = null
}
- return true
+ return 'pasted-not-submitted'
} catch {
- return written
+ return written ? 'pasted-not-submitted' : false
} finally {
pending.delete(key)
}
diff --git a/src/core/trigger-delivery.test.ts b/src/core/trigger-delivery.test.ts
index 467104329..3ccbb4a7e 100644
--- a/src/core/trigger-delivery.test.ts
+++ b/src/core/trigger-delivery.test.ts
@@ -72,6 +72,14 @@ function world(overrides: Partial<TriggerDeliveryDeps> = {}): World {
}
describe('trigger delivery — immediate outcomes', () => {
+ it('records an unsubmitted paste as a terminal miss with no retry', async () => {
+ const sendText = vi.fn(async () => 'pasted-not-submitted' as const)
+ const w = world({ sendText })
+ const result = await w.delivery.fire(row())
+ expect(result.outcome).toBe('missed')
+ expect(result.detail).toContain('Do not resend')
+ expect(sendText).toHaveBeenCalledTimes(1)
+ })
it('delivers into an idle (done) agent target', async () => {
const w = world()
const r = await w.delivery.fire(row())
@@ -128,6 +136,17 @@ describe('trigger delivery — immediate outcomes', () => {
})
describe('trigger delivery — the deliver-on-idle queue', () => {
+ it('retains the partial-paste explanation after an idle queue flush and never retries', async () => {
+ const sendText = vi.fn(async () => 'pasted-not-submitted' as const)
+ const w = world({ sendText })
+ w.state = 'working'
+ expect((await w.delivery.fire(row())).outcome).toBe('queued')
+ w.state = 'done'
+ await w.delivery.onTargetIdle('term-tgt-1')
+ expect(w.runs[0].run).toMatchObject({ outcome: 'missed', detail: expect.stringContaining('Do not resend') })
+ await w.delivery.onTargetIdle('term-tgt-1')
+ expect(sendText).toHaveBeenCalledTimes(1)
+ })
it('flushes on the idle edge and reports delivered-late', async () => {
const w = world()
w.state = 'working'
diff --git a/src/core/trigger-delivery.ts b/src/core/trigger-delivery.ts
index 99c77c22f..048e145bc 100644
--- a/src/core/trigger-delivery.ts
+++ b/src/core/trigger-delivery.ts
@@ -1,3 +1,5 @@
+import { TEXT_NOT_SUBMITTED } from '../shared/text-delivery'
+import type { TextDeliveryResult } from '../shared/text-delivery'
/**
* Trigger DELIVERY (issue #493, phase 3) — the real implementation behind the scheduler's `fire`
* seam: put the armed payload into the target's pane, or say honestly why not.
@@ -37,7 +39,7 @@ import type { TriggerFireResult, TriggerRow, TriggerRun } from './trigger-schedu
export interface TriggerDeliveryDeps {
/** `PtyManager.sendText` — the paste path; false = tmux unavailable / session doesn't exist. */
- sendText(nodeId: string, text: string): Promise<boolean>
+ sendText(nodeId: string, text: string): Promise<TextDeliveryResult>
/** `PtyManager.paneCommand` — null = no live session / unreadable, never evidence of a command. */
paneCommand(nodeId: string): Promise<string | null>
/** The mirror's live view of the target (`mirrorEntry`) — state undefined = unknown. */
@@ -99,7 +101,7 @@ export function createTriggerDelivery(deps: TriggerDeliveryDeps): TriggerDeliver
return { act: 'missed', detail: `target pane is running '${pane}' — refusing to type into it` }
}
const sent = await deps.sendText(row.spec.target, row.spec.payload)
- return sent ? { act: 'fired' } : { act: 'missed', detail: 'target session is not running' }
+ return sent === true ? { act: 'fired' } : { act: 'missed', detail: sent === 'pasted-not-submitted' ? TEXT_NOT_SUBMITTED : 'target session is not running' }
}
/**
@@ -125,6 +127,7 @@ export function createTriggerDelivery(deps: TriggerDeliveryDeps): TriggerDeliver
// run recorded for the card comes from `onFlushed`, keyed on the kind alone.
return { kind: 'delivered', traceId: randomUUID(), traced: 'memory', receipt: 'observed', signal: 'newTurn' }
if (a.act === 'queue') return { kind: 'targetBusy', state: a.reason } // requeued, TTL keeps counting
+ if (a.detail === TEXT_NOT_SUBMITTED) return { kind: 'stalled', traceId: randomUUID(), traced: 'memory', waitedMs: 0 }
return { kind: 'targetGone' } // terminal miss — the target left while the payload waited
}
@@ -139,6 +142,8 @@ export function createTriggerDelivery(deps: TriggerDeliveryDeps): TriggerDeliver
const run: TriggerRun =
outcome.kind === 'delivered'
? { at: now(), outcome: 'delivered-late' }
+ : outcome.kind === 'stalled'
+ ? { at: now(), outcome: 'missed', detail: TEXT_NOT_SUBMITTED }
: outcome.kind === 'notPermitted'
? { at: now(), outcome: 'missed', detail: 'disarmed or edited while queued — dropped' }
: { at: now(), outcome: 'missed', detail: 'target went away while queued' }
diff --git a/src/core/trigger-service.ts b/src/core/trigger-service.ts
index 436887502..ea4d36734 100644
--- a/src/core/trigger-service.ts
+++ b/src/core/trigger-service.ts
@@ -1,3 +1,4 @@
+import type { TextDeliveryResult } from '../shared/text-delivery'
/**
* The trigger node's whole host-side machine, composed ONCE (issue #493, phase 3): the
* machine-local arm store + the scheduler + the delivery (with its deliver-on-idle queue) + the
@@ -39,7 +40,7 @@ export interface TriggerServiceDeps {
/** `WorkspaceStore.getNode` — target resolution + the flush-time current-spec re-read. */
getNode(nodeId: string): CanvasNodeState | undefined
/** `PtyManager.sendText` / `PtyManager.paneCommand`. */
- sendText(nodeId: string, text: string): Promise<boolean>
+ sendText(nodeId: string, text: string): Promise<TextDeliveryResult>
paneCommand(nodeId: string): Promise<string | null>
/**
* Register one request/response IPC handler — both shells pass `platform().handle`. REQUIRED
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index a57691de1..ecdef8e64 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -1,3 +1,5 @@
+import { reportTextDelivery } from '../lib/textDelivery'
+import { TEXT_NOT_SUBMITTED } from '@shared/text-delivery'
import { VisibleMiniMap } from './VisibleMiniMap'
import { LINK_ENDPOINT_NOT_FOUND } from '@shared/canvas-link'
import { createControlOpenBatch } from '../lib/controlOpenBatch'
@@ -3562,7 +3564,7 @@ export function Canvas() {
void api.pty.sendText(
selfId,
buildContextLinkNote(agentIdOf(selfId), titleOf(otherId), shimPath)
- )
+ ).then(reportTextDelivery)
}
void note(source, target)
void note(target, source)
@@ -3579,7 +3581,7 @@ export function Canvas() {
(sticky?.data.text as string) ?? '',
agentIdOf(target)
)
- if (msg) void api.pty.sendText(target, msg)
+ if (msg) void api.pty.sendText(target, msg).then(reportTextDelivery)
},
[linkEndpointOf, agentIdOf, setLinkEdges, markDirty, nodes]
)
@@ -6964,7 +6966,8 @@ export function Canvas() {
const known = useAgentStatus.getState().byId[nodeId]?.sessionId
let originalId = known
if (known) {
- await api.pty.sendText(nodeId, '/branch')
+ const delivery = await api.pty.sendText(nodeId, '/branch')
+ if (delivery !== true) return { ok: false, error: delivery === 'pasted-not-submitted' ? TEXT_NOT_SUBMITTED : 'Branch delivery failed.' }
} else {
const res = await branchClaudeSession(api, nodeId)
if (!res.ok || !res.originalId) {
@@ -12160,7 +12163,8 @@ export function Canvas() {
const outcome = await guardConcurrentRestart(args.node, async () => {
try {
const ok = await api.pty.sendText(args.node, args.text ?? '')
- return ok ? ('sent' as const) : ('failed' as const)
+ if (ok === 'pasted-not-submitted') thrown = TEXT_NOT_SUBMITTED
+ return ok === true ? ('sent' as const) : ('failed' as const)
} catch (e) {
thrown = String(e)
return 'failed' as const
diff --git a/src/renderer/lib/claudeBranch.test.ts b/src/renderer/lib/claudeBranch.test.ts
index 7eb959680..e88d6affa 100644
--- a/src/renderer/lib/claudeBranch.test.ts
+++ b/src/renderer/lib/claudeBranch.test.ts
@@ -6,6 +6,14 @@ const fakeApi = (over: { sendText?: unknown; capture?: unknown }): NodeTerminalA
({ pty: { sendText: over.sendText, capture: over.capture } }) as unknown as NodeTerminalApi
describe('branchClaudeSession', () => {
+ it('does not create a branch or poll after an unsubmitted paste', async () => {
+ const capture = vi.fn()
+ const sendText = vi.fn(async () => 'pasted-not-submitted')
+ const result = await branchClaudeSession(fakeApi({ sendText, capture }), 'node-1')
+ expect(result).toMatchObject({ ok: false, error: expect.stringContaining('Do not resend') })
+ expect(capture).not.toHaveBeenCalled()
+ expect(sendText).toHaveBeenCalledTimes(1)
+ })
it('sends /branch through the passed api, not the global', async () => {
const sendText = vi.fn(async () => true)
const capture = vi.fn(async () => 'run claude -r abcdef12-3456 in a new terminal')
diff --git a/src/renderer/lib/claudeBranch.ts b/src/renderer/lib/claudeBranch.ts
index accf1da9e..ddb66c18c 100644
--- a/src/renderer/lib/claudeBranch.ts
+++ b/src/renderer/lib/claudeBranch.ts
@@ -1,3 +1,4 @@
+import { TEXT_NOT_SUBMITTED } from '@shared/text-delivery'
// Drives Claude Code's own `/branch` slash command from a node action.
//
// Running `/branch` switches the CURRENT terminal onto a new branch and prints, e.g.:
@@ -25,6 +26,7 @@ export interface BranchResult {
export async function branchClaudeSession(api: NodeTerminalApi, nodeId: string): Promise<BranchResult> {
const sent = await api.pty.sendText(nodeId, '/branch')
+ if (sent === 'pasted-not-submitted') return { ok: false, error: TEXT_NOT_SUBMITTED }
if (!sent) return { ok: false, error: 'Branch requires a persistent (tmux) session.' }
// Poll the visible buffer until the branch output (with the original session id) appears.
diff --git a/src/renderer/lib/sessionRename.ts b/src/renderer/lib/sessionRename.ts
index 43babeab2..7041ff682 100644
--- a/src/renderer/lib/sessionRename.ts
+++ b/src/renderer/lib/sessionRename.ts
@@ -1,3 +1,5 @@
+import { reportTextDelivery } from './textDelivery'
+import type { TextDeliveryResult } from '@shared/text-delivery'
// Mirroring a node's title into its agent session as `/rename <name>`, safely.
//
// The io is injected so the gate below is unit-testable: it is the fix for a real data-loss bug,
@@ -46,7 +48,7 @@ export function sessionNameUnchanged(next: string, current: string): boolean {
export interface RenamePushIo {
paneCommand(persistKey: string): Promise<string | null>
- sendText(persistKey: string, text: string): Promise<boolean>
+ sendText(persistKey: string, text: string): Promise<TextDeliveryResult>
/** Injected so tests don't wait in real time. */
sleep?(ms: number): Promise<void>
}
@@ -88,8 +90,7 @@ export async function pushSessionRename(
if (i > 0) await sleep(RENAME_PUSH_RETRY_MS)
const pane = await io.paneCommand(nodeId).catch(() => null)
if (pane && !isShellCommand(pane)) {
- void io.sendText(nodeId, renameCommand(name))
- return true
+ return reportTextDelivery(await io.sendText(nodeId, renameCommand(name)))
}
}
return false
diff --git a/src/renderer/lib/textDelivery.test.ts b/src/renderer/lib/textDelivery.test.ts
new file mode 100644
index 000000000..55c63e352
--- /dev/null
+++ b/src/renderer/lib/textDelivery.test.ts
@@ -0,0 +1,20 @@
+// @vitest-environment jsdom
+import { describe, expect, it, vi } from 'vitest'
+import { reportTextDelivery } from './textDelivery'
+
+describe('partial text delivery notice', () => {
+ it('shows a no-resend warning for accepted but unsubmitted input', () => {
+ const notice = vi.fn()
+ window.addEventListener('nodeterm:toast', notice)
+ try {
+ expect(reportTextDelivery('pasted-not-submitted')).toBe(false)
+ expect(notice).toHaveBeenCalledTimes(1)
+ expect((notice.mock.calls[0][0] as CustomEvent).detail).toEqual({
+ kind: 'error', message: expect.stringContaining('Do not resend')
+ })
+ expect(reportTextDelivery(true)).toBe(true)
+ expect(reportTextDelivery(false)).toBe(false)
+ expect(notice).toHaveBeenCalledTimes(1)
+ } finally { window.removeEventListener('nodeterm:toast', notice) }
+ })
+})
diff --git a/src/renderer/lib/textDelivery.ts b/src/renderer/lib/textDelivery.ts
new file mode 100644
index 000000000..5ca006b92
--- /dev/null
+++ b/src/renderer/lib/textDelivery.ts
@@ -0,0 +1,10 @@
+import { TEXT_NOT_SUBMITTED, type TextDeliveryResult } from '@shared/text-delivery'
+
+export function reportTextDelivery(result: TextDeliveryResult): boolean {
+ if (result === 'pasted-not-submitted') {
+ window.dispatchEvent(new CustomEvent('nodeterm:toast', {
+ detail: { kind: 'error', message: TEXT_NOT_SUBMITTED }
+ }))
+ }
+ return result === true
+}
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index 2992cd152..07e970c3d 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -1,3 +1,4 @@
+import { TEXT_NOT_SUBMITTED } from '@shared/text-delivery'
import { memo, useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react'
import { renderMarkdown } from '../lib/markdown'
import { useAgentStatus } from '../state/agentStatus'
@@ -132,6 +133,11 @@ export function ChatPanel({
const text = input.trim()
if (!text || working) return
const ok = await api.pty.sendText(nodeId, text)
+ if (ok === 'pasted-not-submitted') {
+ window.dispatchEvent(new CustomEvent('nodeterm:toast', { detail: { kind: 'error', message: TEXT_NOT_SUBMITTED } }))
+ setInput('')
+ return
+ }
if (!ok) {
setReadonly(true)
return
diff --git a/src/renderer/nodes/LoopNode.tsx b/src/renderer/nodes/LoopNode.tsx
index 8f96e20fb..a6f5dcfc6 100644
--- a/src/renderer/nodes/LoopNode.tsx
+++ b/src/renderer/nodes/LoopNode.tsx
@@ -1,3 +1,4 @@
+import { reportTextDelivery } from '../lib/textDelivery'
import { useEffect, useRef } from 'react'
import { IconChevronDown, IconChevronRight, IconClose, IconPlay } from '../components/icons'
import { Handle, NodeResizer, Position, type NodeProps } from '@xyflow/react'
@@ -32,7 +33,7 @@ export function LoopNode({ id, data, selected }: NodeProps<CanvasNode>) {
const trigger = (e: React.MouseEvent) => {
e.stopPropagation()
- if (task) void api.pty.sendText(id.replace(/^loop-/, ''), task)
+ if (task) void api.pty.sendText(id.replace(/^loop-/, ''), task).then(reportTextDelivery)
}
// Manual dismiss: cron/schedule cards persist across turns/sessions/restarts, so a job
diff --git a/src/server/headless-node-factory.ts b/src/server/headless-node-factory.ts
index d9db2d28a..c9b16c9e3 100644
--- a/src/server/headless-node-factory.ts
+++ b/src/server/headless-node-factory.ts
@@ -1,3 +1,4 @@
+import type { TextDeliveryResult } from '../shared/text-delivery'
import { isLaunchShell } from '../shared/agents/pane'
import { randomBytes, randomUUID } from 'node:crypto'
import path from 'node:path'
@@ -59,7 +60,7 @@ export interface HeadlessPty {
/** Probe only. Boot reconciliation must never turn absence into a fresh session. */
paneCommand(persistKey: string): Promise<string | null>
sessionExists(persistKey: string): Promise<boolean>
- sendText(nodeId: string, text: string, opts?: { enter?: boolean }): Promise<boolean>
+ sendText(nodeId: string, text: string, opts?: { enter?: boolean }): Promise<TextDeliveryResult>
destroySession(
clientId: number | null,
persistKey: string,
@@ -1245,7 +1246,7 @@ export class HeadlessNodeFactory {
const command = commands.get(node.id)
if (command) {
if (isLaunchShell(await this.deps.ptyManager.paneCommand(node.id)) &&
- await this.deps.ptyManager.sendText(node.id, command)) node.pendingLaunch = undefined
+ (await this.deps.ptyManager.sendText(node.id, command)) === true) node.pendingLaunch = undefined
else failed.push(node.id)
}
} catch {
@@ -1423,7 +1424,7 @@ export class HeadlessNodeFactory {
await this.deps.workspaceStore.save(workspace)
markChanged()
if (!isLaunchShell(await this.deps.ptyManager.paneCommand(node.id).catch(() => null))) continue
- if (!(await this.deps.ptyManager.sendText(node.id, pending.command).catch(() => false))) continue
+ if ((await this.deps.ptyManager.sendText(node.id, pending.command).catch(() => false)) !== true) continue
node.pendingLaunch = undefined
markChanged()
}
diff --git a/src/server/settled-envelope.ts b/src/server/settled-envelope.ts
index 42074e2c4..2574a3d4a 100644
--- a/src/server/settled-envelope.ts
+++ b/src/server/settled-envelope.ts
@@ -1,3 +1,4 @@
+import type { TextDeliveryResult } from '../shared/text-delivery'
/**
* Server-only adapter: the tmux-backed pane is reached through PtyManager's capture + sendText.
* The sequencing itself (paste, observe the envelope settle, submit in a second write) lives in
@@ -9,7 +10,7 @@ export { ENVELOPE_SETTLE_POLL_MS, ENVELOPE_SETTLE_POLLS } from '../core/settled-
export interface SettledEnvelopePty {
captureSession(nodeId: string): Promise<string>
- sendText(nodeId: string, text: string, opts?: { enter?: boolean }): Promise<boolean>
+ sendText(nodeId: string, text: string, opts?: { enter?: boolean }): Promise<TextDeliveryResult>
}
export type SettledEnvelopeOptions = SettleOptions
@@ -33,7 +34,7 @@ export async function sendSettledEnvelope(
},
paste: async () => {
try {
- return await pty.sendText(nodeId, envelope, { enter: false })
+ return (await pty.sendText(nodeId, envelope, { enter: false })) === true
} catch {
return false
}
diff --git a/src/session-host/host.ts b/src/session-host/host.ts
index 57de7d5df..9e9e8678a 100644
--- a/src/session-host/host.ts
+++ b/src/session-host/host.ts
@@ -818,7 +818,8 @@ async function main(): Promise<void> {
s.resumeFor(socket)
return { ok: true }
}
- case 'sendKeys': {
+ case 'sendKeys':
+ case 'sendKeysV2': {
const s = sessions.get(req.name)
if (!s || s.exited) return { ok: false, error: 'no such session' }
const ok = await sendTextWhenSettled(s, req.text, req.enter, {
@@ -827,7 +828,7 @@ async function main(): Promise<void> {
capture: () => s.serialize(200),
write: (chunk) => s.proc.write(chunk)
})
- return ok ? { ok: true } : { ok: false, error: 'session unavailable or delivery busy' }
+ return ok !== false ? { ok: true, result: { delivery: ok } } : { ok: false, error: 'session unavailable or delivery busy' }
}
case 'paneCommand': {
const s = sessions.get(req.name)
diff --git a/src/session-host/protocol.ts b/src/session-host/protocol.ts
index 22da49fce..22fa713d1 100644
--- a/src/session-host/protocol.ts
+++ b/src/session-host/protocol.ts
@@ -83,7 +83,7 @@ export type SessionHostRequest =
| { id: number; cmd: 'resize'; name: string; cols: number; rows: number }
| { id: number; cmd: 'pause'; name: string }
| { id: number; cmd: 'resume'; name: string }
- | { id: number; cmd: 'sendKeys'; name: string; text: string; enter: boolean }
+ | { id: number; cmd: 'sendKeys' | 'sendKeysV2'; name: string; text: string; enter: boolean }
| { id: number; cmd: 'paneCommand'; name: string }
| { id: number; cmd: 'messageOwnerV1'; name: string }
| { id: number; cmd: 'messagePasteReadyV1'; name: string }
diff --git a/src/session-host/send-keys-host.test.ts b/src/session-host/send-keys-host.test.ts
index 169146a9f..b9b417ee6 100644
--- a/src/session-host/send-keys-host.test.ts
+++ b/src/session-host/send-keys-host.test.ts
@@ -55,7 +55,7 @@ function fakePtyPlugin(): Plugin {
draining = true
setTimeout(() => {
draining = false
- output?.(data.slice(6, -6))
+ output?.(process.env.NT_TEST_RENDER === 'folded' ? '[Pasted text #1 +40 lines]' : data.slice(6, -6))
}, 150)
}
},
@@ -157,7 +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?: boolean
+ render?: boolean | 'folded'
text: string
enter: boolean
/** Poll `capture` until the serialized screen proves this mode reached the emulator. */
@@ -214,9 +214,9 @@ async function writesForSendKeys(opts: {
}
socket.write(
- encodeFrame({ id: 900, cmd: 'sendKeys', name: 'keys', text: opts.text, enter: opts.enter })
+ encodeFrame({ id: 900, cmd: 'sendKeysV2', name: 'keys', text: opts.text, enter: opts.enter })
)
- await expect(connected.response(900)).resolves.toMatchObject({ id: 900, ok: true })
+ await expect(connected.response(900)).resolves.toMatchObject({ id: 900, ok: true, result: { delivery: opts.render === false || opts.render === 'folded' ? 'pasted-not-submitted' : true } })
return readFileSync(writeLog, 'utf8')
.split('\n')
.filter(Boolean)
@@ -241,6 +241,14 @@ describe('session-host sendKeys delivery', () => {
expect(writes).toEqual([`${PASTE_START}summarise the linked context${PASTE_END}`, '\r'])
}, 30_000)
+ it('returns partial delivery over the wire for a folded multiline paste', async () => {
+ const text = Array.from({ length: 40 }, (_, i) => `line ${i}`).join('\n')
+ expect(await writesForSendKeys({
+ announce: '\x1b[?2004h', awaitMode: '\x1b[?2004h',
+ text, enter: true, render: 'folded'
+ })).toEqual([`${PASTE_START}${text}${PASTE_END}`])
+ }, 30_000)
+
it('does not submit a paste that never renders', async () => {
expect(await writesForSendKeys({
announce: '\x1b[?2004h', awaitMode: '\x1b[?2004h',
diff --git a/src/shared/text-delivery.ts b/src/shared/text-delivery.ts
new file mode 100644
index 000000000..18f7de0ce
--- /dev/null
+++ b/src/shared/text-delivery.ts
@@ -0,0 +1,3 @@
+/** A partial paste must never be retried or represented as submitted. */
+export type TextDeliveryResult = boolean | 'pasted-not-submitted'
+export const TEXT_NOT_SUBMITTED = 'Text was pasted but not submitted. Do not resend it. Inspect the terminal and submit manually if appropriate.'
diff --git a/src/shared/types.ts b/src/shared/types.ts
index e23431008..77d4787ee 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1,3 +1,4 @@
+import type { TextDeliveryResult } from './text-delivery'
// Types shared across the main, preload, and renderer processes.
import { TABBAR_HEIGHT_PX } from './window-chrome-metrics'
@@ -1006,8 +1007,9 @@ export interface PtyApi {
readScrollback(persistKey: string): Promise<string>
/** Send literal text into a session, by default followed by Enter (e.g. a slash command).
* `opts.enter: false` writes the text without submitting it (dictation's Insert). Returns
- * false if unavailable. */
- sendText(persistKey: string, text: string, opts?: { enter?: boolean }): Promise<boolean>
+ * false if unavailable; `pasted-not-submitted` means input was accepted but Enter was not
+ * confirmed written. Surface it without automatically resending. True is not an app receipt. */
+ sendText(persistKey: string, text: string, opts?: { enter?: boolean }): Promise<TextDeliveryResult>
/** Is tmux available on this host (else the silent plain-shell fallback), plus a suggested
* install command for the "tmux not found" banner. */
tmuxStatus(): Promise<TmuxStatus>