Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Label control characters in agent terminal handoffs (PRD-9325) (#6223)

Andrew Mikofalvy45a1037c9f07
diff --git a/.changeset/terminal-handoff-control-labels.md b/.changeset/terminal-handoff-control-labels.md
new file mode 100644
index 000000000..ab6e4edbd
--- /dev/null
+++ b/.changeset/terminal-handoff-control-labels.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Text sent to a running or newly staged agent terminal now shows control characters as labels such as `<control-0003>`, so they can no longer end a Codex session or act as keystrokes. When the agent supports bracketed paste, the text arrives as one paste, which may display collapsed.
diff --git a/knip.config.ts b/knip.config.ts
index 69344114d..0004a763a 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -149,11 +149,15 @@ export default {
'packages/server': {
entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],
project: 'src/**',
- ignoreDependencies: ['@types/shell-quote'],
+ ignoreDependencies: [
+ '@types/shell-quote',
+ ],
},
'packages/cli': {
entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],
- ignoreDependencies: ['yjs'],
+ ignoreDependencies: [
+ 'yjs',
+ ],
},
'packages/desktop': {
entry: [
diff --git a/packages/app/src/components/SessionsHost.tsx b/packages/app/src/components/SessionsHost.tsx
index cf4a1be06..5902fae06 100644
--- a/packages/app/src/components/SessionsHost.tsx
+++ b/packages/app/src/components/SessionsHost.tsx
@@ -1,7 +1,11 @@
// oxlint-disable ok/no-physical-direction-utility -- pre-rule backlog — physical margin/padding/inset utilities predate the rule; drain by swapping ml/mr → ms/me, pl/pr → ps/pe, left/right → start/end, then deleting this line. See https://github.com/inkeep/open-knowledge/blob/main/lint-plugins/ok-rules/README.md#no-physical-direction-utility
import type { AttachmentPart, ThreadInfo } from '@inkeep/open-knowledge-core/acp/thread-protocol';
-import { TERMINAL_CLIS, type TerminalCli } from '@inkeep/open-knowledge-core/handoff';
+import {
+ buildTerminalInputBytes,
+ TERMINAL_CLIS,
+ type TerminalCli,
+} from '@inkeep/open-knowledge-core/handoff';
import type { TerminalPlacement } from '@inkeep/open-knowledge-core/terminal-layout';
import { useLingui } from '@lingui/react/macro';
import { SquareTerminalIcon } from 'lucide-react';
@@ -108,6 +112,7 @@ import {
subscribeToActiveTerminalInput,
} from './handoff/terminal-input-events';
import { requestTerminalLaunch } from './handoff/terminal-launch-events';
+import { isBracketedPasteEnabled } from './handoff/terminal-paste-mode';
import { TerminalGate } from './TerminalGate';
import { TerminalNewChatButton } from './TerminalNewChatButton';
import {
@@ -979,7 +984,10 @@ export function SessionsHost({
const livePtyId = ptyIdBySessionRef.current.get(active.id);
const terminal = bridge?.terminal;
if (livePtyId != null && terminal != null && active.launch?.cli != null) {
- terminal.input(livePtyId, text);
+ terminal.input(
+ livePtyId,
+ buildTerminalInputBytes(text, isBracketedPasteEnabled(livePtyId)),
+ );
revealForReuse();
queueMicrotask(() => focusTerminalSession(activeId));
return;
diff --git a/packages/app/src/components/TerminalDock.dom.test.tsx b/packages/app/src/components/TerminalDock.dom.test.tsx
index b621c3167..20066f929 100644
--- a/packages/app/src/components/TerminalDock.dom.test.tsx
+++ b/packages/app/src/components/TerminalDock.dom.test.tsx
@@ -11,9 +11,11 @@ import {
} from '@/lib/local-menu-action-bus';
import { writePreferBareTerminal } from '@/lib/terminal-new-tab-store';
import { saveStickyAgent, terminalCliId } from '@/lib/unified-agent-store';
+import { composeTerminalSelectionPaste } from './handoff/compose-terminal-selection';
import { requestPreferredSession } from './handoff/preferred-session-events';
import { requestActiveTerminalInput } from './handoff/terminal-input-events';
import { subscribeToTerminalLaunchRequests } from './handoff/terminal-launch-events';
+import { registerBracketedPasteProbe } from './handoff/terminal-paste-mode';
const TERMINAL_PANEL_ID = 'terminal-dock-panel';
@@ -897,21 +899,75 @@ describe('TerminalDock multi-session', () => {
expect(view.input).not.toHaveBeenCalled();
});
- test('the selection input reuses a live CLI tab — raw PTY write, no new tab', async () => {
+ test('the selection input reuses a live CLI tab — one bracketed-paste PTY write, no new tab', async () => {
const view = renderDock(true);
await waitFor(() => expect(emitTitle('pty-1', 'zsh')).toBe(true));
act(() => view.rerender(true, { prompt: null, cli: 'claude', nonce: 1 }));
await waitFor(() => expect(emitTitle('pty-2', 'claude')).toBe(true));
const runningId = activePanelId();
+ const unregister = registerBracketedPasteProbe('pty-2', () => true);
await act(async () => {
requestActiveTerminalInput('explain this');
});
+ unregister();
- await waitFor(() => expect(view.input).toHaveBeenCalledWith('pty-2', 'explain this'));
+ await waitFor(() =>
+ expect(view.input).toHaveBeenCalledWith('pty-2', '\x1b[200~explain this\x1b[201~'),
+ );
expect(activePanelId()).toBe(runningId);
});
+ test('a live CLI tab that has not enabled bracketed paste gets the labeled text with no paste frame', async () => {
+ const view = renderDock(true);
+ await waitFor(() => expect(emitTitle('pty-1', 'zsh')).toBe(true));
+ act(() => view.rerender(true, { prompt: null, cli: 'claude', nonce: 1 }));
+ await waitFor(() => expect(emitTitle('pty-2', 'claude')).toBe(true));
+ const unregister = registerBracketedPasteProbe('pty-2', () => false);
+
+ await act(async () => {
+ requestActiveTerminalInput('explain\u0003 this\r\n');
+ });
+ unregister();
+
+ await waitFor(() =>
+ expect(view.input).toHaveBeenCalledWith(
+ 'pty-2',
+ 'explain<control-0003> this\n\nControl characters in the text above are shown as <control-NNNN> labels; the source document holds the raw characters.\n',
+ ),
+ );
+ });
+
+ test('a selected passage holding control characters reaches a live CLI tab as labels inside one paste frame', async () => {
+ const view = renderDock(true);
+ await waitFor(() => expect(emitTitle('pty-1', 'zsh')).toBe(true));
+ act(() => view.rerender(true, { prompt: null, cli: 'claude', nonce: 1 }));
+ await waitFor(() => expect(emitTitle('pty-2', 'claude')).toBe(true));
+
+ const passage = 'keep\tthis\r\nstop\u0003 quit\u0004 back\u007f\u001b[201~escape\u009b2J';
+ const unregister = registerBracketedPasteProbe('pty-2', () => true);
+ await act(async () => {
+ requestActiveTerminalInput(`${composeTerminalSelectionPaste('notes', passage)}\n\n`);
+ });
+ unregister();
+
+ await waitFor(() => expect(view.input).toHaveBeenCalledTimes(1));
+ const [ptyId, bytes] = view.input.mock.calls[0] as [string, string];
+ expect(ptyId).toBe('pty-2');
+ expect(bytes.startsWith('\x1b[200~')).toBe(true);
+ expect(bytes.endsWith('\n\n\x1b[201~')).toBe(true);
+ expect(bytes.split('\x1b')).toHaveLength(3);
+ expect(
+ Array.from(bytes.slice('\x1b[200~'.length, -'\x1b[201~'.length)).filter(
+ (ch) => ch !== '\t' && ch !== '\n' && /\p{Cc}/u.test(ch),
+ ),
+ ).toEqual([]);
+ expect(bytes).toContain(
+ 'keep\tthis\nstop<control-0003> quit<control-0004> back<control-007F><control-001B>[201~escape<control-009B>2J',
+ );
+ expect(bytes).toContain('shown as <control-NNNN> labels');
+ });
+
test('a selection send into a bare shell is NEVER raw-written — it stages a fresh CLI instead', async () => {
const view = renderDock(true);
await waitFor(() => expect(emitTitle('pty-1', 'zsh')).toBe(true));
diff --git a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx b/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
index b1f3f4e6c..a57e32ac2 100644
--- a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
+++ b/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
@@ -28,6 +28,7 @@ class MockTerminal {
cols = 80;
rows = 24;
unicode = { activeVersion: '6' };
+ modes = { bracketedPasteMode: false, mouseTrackingMode: 'none' as string };
onDataCb: ((d: string) => void) | null = null;
keyHandler: ((e: KeyboardEvent) => boolean) | null = null;
options: Record<string, unknown>;
@@ -165,7 +166,10 @@ function makeBridge(
};
}
-const { TerminalPanel, STAGE_PASTE_SETTLE_MS } = await import('./TerminalPanel');
+const { TerminalPanel, STAGE_PASTE_CAP_MS, STAGE_PASTE_SETTLE_MS } = await import(
+ './TerminalPanel'
+);
+const { isBracketedPasteEnabled } = await import('./handoff/terminal-paste-mode');
function bakedLaunch(
createMock: ReturnType<typeof vi.fn>,
@@ -456,8 +460,8 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
await waitFor(() => expect(lastTerm?.paste).toHaveBeenCalledWith('launch clipboard paste'));
});
- test('a launch carrying stagePaste writes it into the CLI input after the TUI settles — no submit', async () => {
- const { bridge, terminal } = makeBridge(WIRED);
+ test('a launch carrying stagePaste writes it into the CLI input as one paste once the CLI enables bracketed paste — no submit', async () => {
+ const { bridge, terminal, pushData } = makeBridge(WIRED);
const staged = 'work on @notes.md — the selected passage\n\n';
render(
<TerminalPanel
@@ -468,12 +472,74 @@ describe('TerminalPanel "Open in terminal" launch (baked into the PTY spawn)', (
await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
expect(bakedLaunch(terminal.create)).toBe(`claude ${CLAUDE_PRE}`);
- await waitFor(() => expect(terminal.input).toHaveBeenCalledWith('pty-1', staged), {
- timeout: 2_000,
- });
+ await new Promise((r) => setTimeout(r, STAGE_PASTE_SETTLE_MS + 300));
+ expect(terminal.input).not.toHaveBeenCalled();
+ if (lastTerm !== null) lastTerm.modes.bracketedPasteMode = true;
+ pushData({ ptyId: 'pty-1', data: '\x1b[?2004h' });
+ await waitFor(
+ () => expect(terminal.input).toHaveBeenCalledWith('pty-1', `\x1b[200~${staged}\x1b[201~`),
+ { timeout: 2_000 },
+ );
expect(terminal.input.mock.calls.every((c) => !(c[1] as string).includes('\r'))).toBe(true);
});
+ test("publishes the PTY's live bracketed-paste mode for live-tab handoffs and withdraws it on unmount", async () => {
+ const { bridge, terminal } = makeBridge(WIRED);
+ const { unmount } = render(<TerminalPanel bridge={bridge} />);
+
+ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
+ if (lastTerm === null) throw new Error('no terminal mounted');
+ const term = lastTerm;
+ term.modes.bracketedPasteMode = true;
+ await waitFor(() => expect(isBracketedPasteEnabled('pty-1')).toBe(true));
+ term.modes.bracketedPasteMode = false;
+ expect(isBracketedPasteEnabled('pty-1')).toBe(false);
+ term.modes.bracketedPasteMode = true;
+ unmount();
+ expect(isBracketedPasteEnabled('pty-1')).toBe(false);
+ });
+
+ test('a stagePaste holding control characters is labeled, so no control reaches the CLI as a keystroke', async () => {
+ const { bridge, terminal, pushData } = makeBridge(WIRED);
+ const staged = 'passage\u0004 with\r\nbreaks\u001b[201~\n\n';
+ render(
+ <TerminalPanel
+ bridge={bridge}
+ launch={{ prompt: null, cli: 'claude', nonce: 1, stagePaste: staged }}
+ />,
+ );
+
+ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
+ if (lastTerm !== null) lastTerm.modes.bracketedPasteMode = true;
+ pushData({ ptyId: 'pty-1', data: '\x1b[?2004h' });
+ await waitFor(() => expect(terminal.input).toHaveBeenCalledTimes(1), { timeout: 2_000 });
+ const bytes = terminal.input.mock.calls[0]?.[1] as string;
+ expect(bytes).toBe(
+ '\x1b[200~passage<control-0004> with\nbreaks<control-001B>[201~\n\nControl characters in the text above are shown as <control-NNNN> labels; the source document holds the raw characters.\n\n\x1b[201~',
+ );
+ });
+
+ test('a stagePaste for a CLI that never enables bracketed paste lands unframed but labeled after the cap', async () => {
+ const { bridge, terminal } = makeBridge(WIRED);
+ const staged = 'passage\u0003 here\n\n';
+ render(
+ <TerminalPanel
+ bridge={bridge}
+ launch={{ prompt: null, cli: 'claude', nonce: 1, stagePaste: staged }}
+ />,
+ );
+
+ await waitFor(() => expect(terminal.create).toHaveBeenCalledTimes(1));
+ await new Promise((r) => setTimeout(r, STAGE_PASTE_SETTLE_MS + 100));
+ expect(terminal.input).not.toHaveBeenCalled();
+ await waitFor(() => expect(terminal.input).toHaveBeenCalledTimes(1), {
+ timeout: STAGE_PASTE_CAP_MS + 1_000,
+ });
+ expect(terminal.input.mock.calls[0]?.[1]).toBe(
+ 'passage<control-0003> here\n\nControl characters in the text above are shown as <control-NNNN> labels; the source document holds the raw characters.\n\n',
+ );
+ }, 10_000);
+
test('a Hermes launch bakes promptless `hermes chat` and injects the prompt only after the ready marker (ESC[?2004h)', async () => {
const { bridge, terminal, pushData } = makeBridge();
const prompt = 'summarize @notes.md\nthen link the people';
diff --git a/packages/app/src/components/TerminalPanel.tsx b/packages/app/src/components/TerminalPanel.tsx
index a5f7e7e8e..6fb9b3e48 100644
--- a/packages/app/src/components/TerminalPanel.tsx
+++ b/packages/app/src/components/TerminalPanel.tsx
@@ -6,8 +6,10 @@ import {
assetOpenRefusalRevealsInstead,
} from '@inkeep/open-knowledge-core/desktop-bridge';
import {
+ BRACKETED_PASTE_ENABLE_MARKER,
buildCliLaunchArgString,
buildStartupInjectionBytes,
+ buildTerminalInputBytes,
buildWindowsCliLaunch,
quoteWindowsShellPath,
shellSingleQuote,
@@ -36,6 +38,7 @@ import {
terminalCommandFor,
windowsTerminalCommandFor,
} from './handoff/terminal-command-events';
+import { registerBracketedPasteProbe } from './handoff/terminal-paste-mode';
import { TerminalAgentConnectionBanner } from './TerminalAgentConnectionBanner';
import { TerminalCliMissingBanner } from './TerminalCliMissingBanner';
import { TerminalCliUnverifiedBanner } from './TerminalCliUnverifiedBanner';
@@ -55,6 +58,7 @@ import { useLiveXtermTheme } from './use-live-xterm-theme';
const PTY_RESIZE_THROTTLE_MS = 100;
export const STAGE_PASTE_SETTLE_MS = 500;
+export const STAGE_PASTE_CAP_MS = 4000;
interface TerminalPanelProps {
readonly bridge: OkDesktopBridge;
@@ -197,6 +201,19 @@ function TerminalSession({
let pendingShellNotices: OkPtyNotice[] = [];
let launchCapabilityLimited = false;
let readinessScan: ((data: string) => void) | undefined;
+ const armReadinessScan = (marker: string, onReady: () => void): void => {
+ let acc = '';
+ readinessScan = (data) => {
+ acc += data;
+ if (acc.includes(marker)) {
+ readinessScan = undefined;
+ onReady();
+ return;
+ }
+ if (acc.length > marker.length + 256) acc = acc.slice(-(marker.length + 256));
+ };
+ };
+ let unregisterPasteProbe: () => void = () => undefined;
let injectCapTimer: ReturnType<typeof setTimeout> | undefined;
let titleDisposable: { dispose(): void } | undefined;
let linkProviderDisposable: { dispose(): void } | undefined;
@@ -503,6 +520,11 @@ function TerminalSession({
const attachSession = (livePtyId: string): void => {
ptyId = livePtyId;
ptyIdRef.current = livePtyId;
+ unregisterPasteProbe();
+ unregisterPasteProbe = registerBracketedPasteProbe(
+ livePtyId,
+ () => term.modes.bracketedPasteMode,
+ );
onPtyIdRef.current?.(livePtyId);
for (const notice of pendingShellNotices) {
if (notice.ptyId !== livePtyId) continue;
@@ -797,17 +819,10 @@ function TerminalSession({
};
injectCapTimer = setTimeout(inject, cfg?.capMs ?? settleMs);
if (marker != null) {
- let acc = '';
- readinessScan = (data) => {
+ armReadinessScan(marker, () => {
if (fired || stagePasteTimer !== undefined) return;
- acc += data;
- if (acc.includes(marker)) {
- readinessScan = undefined;
- stagePasteTimer = setTimeout(inject, settleMs);
- return;
- }
- if (acc.length > marker.length + 256) acc = acc.slice(-(marker.length + 256));
- };
+ stagePasteTimer = setTimeout(inject, settleMs);
+ });
} else {
stagePasteTimer = setTimeout(inject, settleMs);
}
@@ -816,11 +831,22 @@ function TerminalSession({
'[terminal] TerminalLaunchIntent carried both prompt and stagePaste; dropping stagePaste',
);
} else if (launchCommand !== undefined && staged != null && staged !== '') {
- stagePasteTimer = setTimeout(() => {
+ let stageFired = false;
+ const stage = (): void => {
+ if (stageFired) return;
+ stageFired = true;
+ readinessScan = undefined;
+ if (stagePasteTimer !== undefined) clearTimeout(stagePasteTimer);
+ if (injectCapTimer !== undefined) clearTimeout(injectCapTimer);
if (cancelled || !terminalInputEnabledRef.current || launchCapabilityLimited) return;
- sendInput(staged);
+ sendInput(buildTerminalInputBytes(staged, term.modes.bracketedPasteMode));
term.focus();
- }, STAGE_PASTE_SETTLE_MS);
+ };
+ injectCapTimer = setTimeout(stage, STAGE_PASTE_CAP_MS);
+ armReadinessScan(BRACKETED_PASTE_ENABLE_MARKER, () => {
+ if (stageFired || stagePasteTimer !== undefined) return;
+ stagePasteTimer = setTimeout(stage, STAGE_PASTE_SETTLE_MS);
+ });
}
})().catch((err) => {
console.error('[terminal] mount sequence failed:', err);
@@ -844,6 +870,7 @@ function TerminalSession({
if (stagePasteTimer !== undefined) clearTimeout(stagePasteTimer);
if (injectCapTimer !== undefined) clearTimeout(injectCapTimer);
readinessScan = undefined;
+ unregisterPasteProbe();
ptyIdRef.current = null;
onPtyIdRef.current?.(null);
termRef.current = null;
diff --git a/packages/app/src/components/handoff/terminal-paste-mode.ts b/packages/app/src/components/handoff/terminal-paste-mode.ts
new file mode 100644
index 000000000..aad35c3df
--- /dev/null
+++ b/packages/app/src/components/handoff/terminal-paste-mode.ts
@@ -0,0 +1,12 @@
+const bracketedPasteProbes = new Map<string, () => boolean>();
+
+export function registerBracketedPasteProbe(ptyId: string, probe: () => boolean): () => void {
+ bracketedPasteProbes.set(ptyId, probe);
+ return () => {
+ if (bracketedPasteProbes.get(ptyId) === probe) bracketedPasteProbes.delete(ptyId);
+ };
+}
+
+export function isBracketedPasteEnabled(ptyId: string): boolean {
+ return bracketedPasteProbes.get(ptyId)?.() === true;
+}
diff --git a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
index a50b00123..4549c74b3 100644
--- a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
+++ b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
@@ -1,3 +1,4 @@
+
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
index 6fcdc23f2..4fc2c11f9 100644
--- a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
+++ b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { normalizeBridge } from '@inkeep/open-knowledge-core';
import { updateYFragment } from '@tiptap/y-tiptap';
diff --git a/packages/app/tests/integration/interior-edit-freshness.test.ts b/packages/app/tests/integration/interior-edit-freshness.test.ts
index 40b5cdfd6..9f2f6feb6 100644
--- a/packages/app/tests/integration/interior-edit-freshness.test.ts
+++ b/packages/app/tests/integration/interior-edit-freshness.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
index 93666af70..2a085742b 100644
--- a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
+++ b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/producer-guard-wiring.test.ts b/packages/app/tests/integration/producer-guard-wiring.test.ts
index 867598d34..878d5196b 100644
--- a/packages/app/tests/integration/producer-guard-wiring.test.ts
+++ b/packages/app/tests/integration/producer-guard-wiring.test.ts
@@ -1,3 +1,4 @@
+
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
index 0970ac12f..4ada3cf26 100644
--- a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
+++ b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
@@ -1,3 +1,4 @@
+
import { randomUUID } from 'node:crypto';
import { afterEach, describe, expect, test } from 'vitest';
import { agentWriteMd, createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
index b632185e1..cbe2b705f 100644
--- a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
+++ b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
@@ -1,3 +1,4 @@
+
import { execFileSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { join } from 'node:path';
diff --git a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
index c530ce4ba..89bc9b4d9 100644
--- a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
+++ b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
@@ -1,3 +1,4 @@
+
import { randomUUID } from 'node:crypto';
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';
import type * as Y from 'yjs';
diff --git a/packages/app/tests/integration/undo-after-rollback.test.ts b/packages/app/tests/integration/undo-after-rollback.test.ts
index d3767adc9..a78aeb0e4 100644
--- a/packages/app/tests/integration/undo-after-rollback.test.ts
+++ b/packages/app/tests/integration/undo-after-rollback.test.ts
@@ -1,3 +1,4 @@
+
import { ROLLBACK_ORIGIN } from '@inkeep/open-knowledge-server';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
diff --git a/packages/app/tests/integration/undo-recycle-reset.test.ts b/packages/app/tests/integration/undo-recycle-reset.test.ts
index b076f955c..e7cc69c3f 100644
--- a/packages/app/tests/integration/undo-recycle-reset.test.ts
+++ b/packages/app/tests/integration/undo-recycle-reset.test.ts
@@ -1,3 +1,4 @@
+
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/tests/integration/undo-rederive-survival.test.ts b/packages/app/tests/integration/undo-rederive-survival.test.ts
index 7935e35f8..9ddcd0730 100644
--- a/packages/app/tests/integration/undo-rederive-survival.test.ts
+++ b/packages/app/tests/integration/undo-rederive-survival.test.ts
@@ -1,3 +1,4 @@
+
import { prependFrontmatter } from '@inkeep/open-knowledge-core';
import { Plugin, PluginKey } from '@tiptap/pm/state';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.ts
index f4cc8a286..2a597ec3d 100644
--- a/packages/core/src/bridge/compose.ts
+++ b/packages/core/src/bridge/compose.ts
@@ -1,3 +1,4 @@
+
import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';
export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index e7e63f43d..ffd8fce06 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,3 +1,4 @@
+
import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';
import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';
diff --git a/packages/core/src/handoff/index.ts b/packages/core/src/handoff/index.ts
index dbee2cf40..b3fd11a9d 100644
--- a/packages/core/src/handoff/index.ts
+++ b/packages/core/src/handoff/index.ts
@@ -27,10 +27,12 @@ export {
withSkillPointer,
} from './prompt-composer.ts';
export {
+ BRACKETED_PASTE_ENABLE_MARKER,
buildClaudeLaunchCommand,
buildCliLaunchArgString,
buildCliLaunchCommand,
buildStartupInjectionBytes,
+ buildTerminalInputBytes,
buildWindowsCliLaunch,
composeWindowsShellLaunchArgs,
isTerminalLaunchEnvName,
diff --git a/packages/core/src/handoff/prompt-composer.test.ts b/packages/core/src/handoff/prompt-composer.test.ts
index 07232d852..50b8713ba 100644
--- a/packages/core/src/handoff/prompt-composer.test.ts
+++ b/packages/core/src/handoff/prompt-composer.test.ts
@@ -20,7 +20,7 @@ import {
TERMINAL_INLINE_PROMPT_BUDGET,
withSkillPointer,
} from './prompt-composer.ts';
-import { shellSingleQuote } from './terminal-launch.ts';
+import { shellSingleQuote, toTerminalPromptText } from './terminal-launch.ts';
import type { HandoffPayload, HandoffTarget } from './types.ts';
test('composeFilePrompt with autoOpen=true emits the file directive + Open-the-OK-editor trailer', () => {
@@ -1288,6 +1288,28 @@ test('terminal transport measures shell-quoted BYTES — an apostrophe-dense ins
expect(quotedByteLength(out)).toBeLessThanOrEqual(TERMINAL_INLINE_PROMPT_BUDGET);
});
+test('terminal transport measures the labeled bytes — a control-dense instruction trims by its labeled length, not its raw length', () => {
+ const instruction = 'x\u0003'.repeat(20_000);
+ expect(quotedByteLength(instruction)).toBeLessThan(TERMINAL_INLINE_PROMPT_BUDGET);
+ expect(quotedByteLength(toTerminalPromptText(instruction))).toBeGreaterThan(
+ TERMINAL_INLINE_PROMPT_BUDGET,
+ );
+ const out = assembleHandoffPrompt({
+ scope: 'doc',
+ docRelativePath: 'plans/migration.md',
+ instruction,
+ mentions: [],
+ autoOpen: false,
+ target: 'claude-code',
+ transport: 'terminal',
+ });
+ expect(out).not.toContain(instruction);
+ expect(out).toContain(' …');
+ expect(quotedByteLength(toTerminalPromptText(out))).toBeLessThanOrEqual(
+ TERMINAL_INLINE_PROMPT_BUDGET,
+ );
+});
+
test('an inline selection between the URL and terminal budgets ships inline on terminal, degrades to locus on url', () => {
const passage = terminalProse(10_000);
const base = {
diff --git a/packages/core/src/handoff/prompt-composer.ts b/packages/core/src/handoff/prompt-composer.ts
index ecfe2fcd5..40e99131d 100644
--- a/packages/core/src/handoff/prompt-composer.ts
+++ b/packages/core/src/handoff/prompt-composer.ts
@@ -2,7 +2,7 @@
* They never carry file content, so the precedent #60 invariant ("agent grounds via OK MCP, not
* native attach") holds by virtue of the URL never carrying `file=` attach data.
*/
-import { shellSingleQuote } from './terminal-launch.ts';
+import { shellSingleQuote, toTerminalPromptText } from './terminal-launch.ts';
import type { HandoffTarget } from './types.ts';
const PATH_INJECTION_SANITIZE_RE = new RegExp(
@@ -224,7 +224,7 @@ function promptTransportLength(
transport: PromptTransport,
): number {
if (transport === 'terminal') {
- return UTF8_ENCODER.encode(shellSingleQuote(prompt)).length;
+ return UTF8_ENCODER.encode(shellSingleQuote(toTerminalPromptText(prompt))).length;
}
return encodedPromptLength(prompt, target);
}
diff --git a/packages/core/src/handoff/terminal-launch.test.ts b/packages/core/src/handoff/terminal-launch.test.ts
index dff93595b..92bbc31c9 100644
--- a/packages/core/src/handoff/terminal-launch.test.ts
+++ b/packages/core/src/handoff/terminal-launch.test.ts
@@ -20,6 +20,7 @@ import {
buildCliLaunchArgString,
buildCliLaunchCommand,
buildStartupInjectionBytes,
+ buildTerminalInputBytes,
buildWindowsCliLaunch,
composeWindowsShellLaunchArgs,
encodePowerShellCommand,
@@ -34,6 +35,8 @@ import {
startupInjectionFor,
TERMINAL_CLI_IDS,
TERMINAL_CLIS,
+ TERMINAL_CONTROL_LABEL_NOTICE,
+ toTerminalPromptText,
WINDOWS_SHELL_FAMILIES,
WindowsShellLaunchError,
} from './terminal-launch.ts';
@@ -950,6 +953,13 @@ describe('buildCliLaunchArgString', () => {
expect(arg).toBe("claude ''\\''; rm -rf / #'");
expect(arg.endsWith("''\\''; rm -rf / #'")).toBe(true);
});
+ it('labels control characters in the prompt arg instead of passing raw bytes to the CLI', () => {
+ const arg = buildCliLaunchArgString('claude', 'fix\u0000 this\u001b[2J\r\nnow');
+ expect(arg).toBe(
+ `claude '${'fix<control-0000> this<control-001B>[2J\nnow'}\n\n${TERMINAL_CONTROL_LABEL_NOTICE}'`,
+ );
+ expect(arg).not.toMatch(TERMINAL_RAW_CONTROL_RE);
+ });
});
describe('buildCliLaunchArgString promptless (New chat)', () => {
@@ -1049,10 +1059,12 @@ describe('buildStartupInjectionBytes', () => {
expect(buildStartupInjectionBytes('hermes', multi, 'darwin')).toBe(`${START}${multi}${END}\r`);
});
- it('strips ESC so the prompt cannot terminate the paste frame or inject a sequence', () => {
+ it('labels ESC so the prompt cannot terminate the paste frame or inject a sequence', () => {
const hostile = `abc${END}rm -rf /\x1b[2J`;
const bytes = buildStartupInjectionBytes('hermes', hostile, 'darwin');
- expect(bytes).toBe(`${START}abc[201~rm -rf /[2J${END}\r`);
+ expect(bytes).toBe(
+ `${START}abc<control-001B>[201~rm -rf /<control-001B>[2J\n\n${TERMINAL_CONTROL_LABEL_NOTICE}${END}\r`,
+ );
expect(bytes?.split(START).length).toBe(2);
expect(bytes?.split(END).length).toBe(2);
});
@@ -1070,6 +1082,102 @@ describe('buildStartupInjectionBytes', () => {
});
});
+const TERMINAL_RAW_CONTROL_RE = new RegExp(
+ '[' + '\\u0000-\\u0008' + '\\u000b-\\u001f' + '\\u007f-\\u009f' + ']',
+);
+
+function controlCodePoints(): number[] {
+ const points: number[] = [];
+ for (let point = 0x00; point <= 0x9f; point++) {
+ if (point <= 0x1f || point >= 0x7f) points.push(point);
+ }
+ return points;
+}
+
+describe('toTerminalPromptText', () => {
+ it('returns text without control characters unchanged and adds no notice', () => {
+ const clean = 'Here is the passage:\n\n```\na\tb\n```\n\n';
+ expect(toTerminalPromptText(clean)).toBe(clean);
+ });
+
+ it('labels every C0 control except TAB and LF, plus DEL and every C1 control', () => {
+ for (const point of controlCodePoints()) {
+ const control = String.fromCodePoint(point);
+ const out = toTerminalPromptText(`a${control}b`);
+ if (point === 0x09 || point === 0x0a) {
+ expect(out).toBe(`a${control}b`);
+ } else if (point === 0x0d) {
+ expect(out).toBe('a\nb');
+ } else {
+ const label = `<control-${point.toString(16).toUpperCase().padStart(4, '0')}>`;
+ expect(out).toBe(`a${label}b\n\n${TERMINAL_CONTROL_LABEL_NOTICE}`);
+ }
+ expect(out).not.toMatch(TERMINAL_RAW_CONTROL_RE);
+ }
+ });
+
+ it('passes printable ASCII, NBSP and non-Latin text through unchanged', () => {
+ let printableAscii = '';
+ for (let point = 0x20; point <= 0x7e; point++) printableAscii += String.fromCodePoint(point);
+ const passage = `${printableAscii}\u00a0é ü «» 日本語 🙂 \u2028`;
+ expect(toTerminalPromptText(passage)).toBe(passage);
+ });
+
+ it('turns CRLF and lone CR line breaks into LF so a CR never reaches the CLI as Enter', () => {
+ expect(toTerminalPromptText('one\r\ntwo\rthree\nfour')).toBe('one\ntwo\nthree\nfour');
+ });
+
+ it('places the notice before trailing line breaks so staged text keeps its blank-line tail', () => {
+ expect(toTerminalPromptText('passage \u0003 end\n\n')).toBe(
+ `passage <control-0003> end\n\n${TERMINAL_CONTROL_LABEL_NOTICE}\n\n`,
+ );
+ });
+
+ it('is idempotent, so a relayed handoff is not labeled twice', () => {
+ fc.assert(
+ fc.property(fc.string({ unit: 'binary' }), (text) => {
+ const once = toTerminalPromptText(text);
+ expect(toTerminalPromptText(once)).toBe(once);
+ expect(once).not.toMatch(TERMINAL_RAW_CONTROL_RE);
+ expect(once).not.toContain('\r');
+ }),
+ );
+ });
+});
+
+describe('buildTerminalInputBytes', () => {
+ const START = '\x1b[200~';
+ const END = '\x1b[201~';
+
+ it('frames the labeled text in exactly one bracketed paste whatever the text holds', () => {
+ fc.assert(
+ fc.property(fc.string({ unit: 'binary' }), (text) => {
+ const bytes = buildTerminalInputBytes(text, true);
+ expect(bytes.startsWith(START)).toBe(true);
+ expect(bytes.endsWith(END)).toBe(true);
+ expect(bytes.slice(START.length, -END.length)).toBe(toTerminalPromptText(text));
+ expect(bytes.split('\x1b').length).toBe(3);
+ }),
+ );
+ });
+
+ it('sends the labeled text unframed to a receiver that has not enabled bracketed paste', () => {
+ fc.assert(
+ fc.property(fc.string({ unit: 'binary' }), (text) => {
+ const bytes = buildTerminalInputBytes(text, false);
+ expect(bytes).toBe(toTerminalPromptText(text));
+ expect(bytes).not.toContain('\x1b');
+ }),
+ );
+ });
+
+ it('keeps TAB and LF raw inside the frame', () => {
+ expect(buildTerminalInputBytes('Columns:\tA\tB\n\tC', true)).toBe(
+ `${START}Columns:\tA\tB\n\tC${END}`,
+ );
+ });
+});
+
describe('claude MCP pre-approval', () => {
it('is OFF by default and only added for claude when opted in', () => {
expect(buildCliLaunchCommand('claude', 'hi')).not.toContain('--settings');
diff --git a/packages/core/src/handoff/terminal-launch.ts b/packages/core/src/handoff/terminal-launch.ts
index 4e6293f83..037d29f0b 100644
--- a/packages/core/src/handoff/terminal-launch.ts
+++ b/packages/core/src/handoff/terminal-launch.ts
@@ -313,7 +313,41 @@ const ESC = '\x1b';
const BRACKETED_PASTE_START = `${ESC}[200~`;
const BRACKETED_PASTE_END = `${ESC}[201~`;
-const BRACKETED_PASTE_ENABLE_MARKER = '\x1b[?2004h';
+const TERMINAL_LINE_BREAK_RE = /\r\n?/g;
+const TERMINAL_UNSAFE_CONTROL_RE = new RegExp(
+ '[' + '\\u0000-\\u0008' + '\\u000b-\\u001f' + '\\u007f-\\u009f' + ']',
+ 'g',
+);
+const TRAILING_LINE_BREAKS_RE = /\n*$/;
+
+export const TERMINAL_CONTROL_LABEL_NOTICE =
+ 'Control characters in the text above are shown as <control-NNNN> labels; the source document holds the raw characters.';
+
+function controlLabel(control: string): string {
+ const codePoint = control.codePointAt(0) ?? 0;
+ return `<control-${codePoint.toString(16).toUpperCase().padStart(4, '0')}>`;
+}
+
+export function toTerminalPromptText(text: string): string {
+ let labeled = false;
+ const printable = text
+ .replace(TERMINAL_LINE_BREAK_RE, '\n')
+ .replace(TERMINAL_UNSAFE_CONTROL_RE, (control) => {
+ labeled = true;
+ return controlLabel(control);
+ });
+ if (!labeled) return printable;
+ const trailing = TRAILING_LINE_BREAKS_RE.exec(printable)?.[0] ?? '';
+ const body = printable.slice(0, printable.length - trailing.length);
+ return `${body}\n\n${TERMINAL_CONTROL_LABEL_NOTICE}${trailing}`;
+}
+
+export function buildTerminalInputBytes(text: string, bracketedPaste: boolean): string {
+ const printable = toTerminalPromptText(text);
+ return bracketedPaste ? `${BRACKETED_PASTE_START}${printable}${BRACKETED_PASTE_END}` : printable;
+}
+
+export const BRACKETED_PASTE_ENABLE_MARKER = '\x1b[?2004h';
const HERMES_INJECT_DEBOUNCE_MS = 300;
const HERMES_INJECT_CAP_MS = 4000;
const WINDOWS_INJECT_SETTLE_MS = 800;
@@ -471,7 +505,7 @@ export function buildCliLaunchArgString(
return `${info.bin} ${sub}${fixedPrefix}`.trimEnd();
}
const promptFlag = info.promptFlag ? `${info.promptFlag} ` : '';
- return `${info.bin} ${sub}${fixedPrefix}${promptFlag}${shellSingleQuote(prompt)}`;
+ return `${info.bin} ${sub}${fixedPrefix}${promptFlag}${shellSingleQuote(toTerminalPromptText(prompt))}`;
}
export function buildCliLaunchCommand(
@@ -501,6 +535,5 @@ export function buildStartupInjectionBytes(
): string | null {
const injection = startupInjectionFor(cli, platform);
if (injection == null || prompt == null || prompt.length === 0) return null;
- const safe = prompt.replaceAll(ESC, '');
- return `${BRACKETED_PASTE_START}${safe}${BRACKETED_PASTE_END}${injection.submit}`;
+ return `${buildTerminalInputBytes(prompt, true)}${injection.submit}`;
}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index d2ed63871..08b9dc92b 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -777,6 +777,7 @@ export {
type AssembleHandoffPromptInput,
assembleHandoffPrompt,
assertNeverUrnIpcLookup,
+ BRACKETED_PASTE_ENABLE_MARKER,
buildClaudeLaunchCommand,
buildClaudeUrl,
buildCliLaunchArgString,
@@ -784,6 +785,7 @@ export {
buildCodexUrl,
buildCursorUrl,
buildStartupInjectionBytes,
+ buildTerminalInputBytes,
buildWindowsCliLaunch,
type ComposeSelection,
type CreateScenario,
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index fc267cbea..fb0ba5a7c 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index bfd7e3109..fa3cfcd86 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,3 +1,4 @@
+
import type { Nodes, Parent, Root } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 4d3250d3a..8be632ba4 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,3 +1,4 @@
+
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/packages/desktop/src/main/terminal-manager.ts b/packages/desktop/src/main/terminal-manager.ts
index 016e00085..a9d6bbe13 100644
--- a/packages/desktop/src/main/terminal-manager.ts
+++ b/packages/desktop/src/main/terminal-manager.ts
@@ -1,4 +1,5 @@
import {
+ BRACKETED_PASTE_ENABLE_MARKER,
isWindowsShellFamily,
isWindowsShellLaunchFailureReason,
type TerminalLaunchCommand,
@@ -82,6 +83,8 @@ interface SessionState {
pendingCreate: PtyCreateMessage | null;
outbound: string;
replay: string;
+ bracketedPaste: boolean;
+ modeScanTail: string;
flushToken: TimerToken | null;
staleToken: TimerToken | null;
pendingBytes: number;
@@ -134,6 +137,29 @@ export const DEFAULT_PTY_COLS = 80;
export const DEFAULT_PTY_ROWS = 24;
const MAX_PTY_DIMENSION = 1000;
+const ESC = '\u001b';
+const MODE_SCAN_CARRY_MAX_CHARS = 256;
+const PRIVATE_MODE_OR_RESET_RE = new RegExp(`${ESC}(?:\\[\\?([0-9;]*)([hl])|c)`, 'g');
+const UNTERMINATED_ESCAPE_RE = new RegExp(`^${ESC}(?:\\[[0-?]*[ -/]*)?$`);
+
+function trackBracketedPaste(session: SessionState, data: string): void {
+ const scanned = session.modeScanTail + data;
+ for (const match of scanned.matchAll(PRIVATE_MODE_OR_RESET_RE)) {
+ if (match[2] === undefined) {
+ session.bracketedPaste = false;
+ } else if ((match[1] ?? '').split(';').includes('2004')) {
+ session.bracketedPaste = match[2] === 'h';
+ }
+ }
+ const pending = scanned.slice(scanned.lastIndexOf(ESC));
+ session.modeScanTail =
+ scanned.includes(ESC) &&
+ pending.length <= MODE_SCAN_CARRY_MAX_CHARS &&
+ UNTERMINATED_ESCAPE_RE.test(pending)
+ ? pending
+ : '';
+}
+
export function clampPtyDimension(value: unknown, fallback: number): number {
return typeof value === 'number' &&
Number.isInteger(value) &&
@@ -351,6 +377,7 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
session.sawOutput = true;
session.outbound += message.data;
session.replay += message.data;
+ trackBracketedPaste(session, message.data);
if (session.replay.length > replayCap) {
session.replay = session.replay.slice(session.replay.length - replayCap);
}
@@ -552,6 +579,8 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
},
outbound: '',
replay: '',
+ bracketedPaste: false,
+ modeScanTail: '',
flushToken: null,
pendingBytes: 0,
paused: false,
@@ -738,7 +767,9 @@ export function createTerminalManager(deps: TerminalManagerDeps): TerminalManage
handle.webContents = req.webContents;
return {
ok: true,
- replay: session.replay,
+ replay: session.bracketedPaste
+ ? `${BRACKETED_PASTE_ENABLE_MARKER}${session.replay}`
+ : session.replay,
...(session.shellFamily === null ? {} : { shellFamily: session.shellFamily }),
...(session.shellNoticeReason === null
? {}
diff --git a/packages/desktop/tests/main/terminal-manager.test.ts b/packages/desktop/tests/main/terminal-manager.test.ts
index 896cb243a..5696ba19d 100644
--- a/packages/desktop/tests/main/terminal-manager.test.ts
+++ b/packages/desktop/tests/main/terminal-manager.test.ts
@@ -198,6 +198,57 @@ describe('terminal creation waits for the renderer to subscribe', () => {
expect(h.forked[0]?.posted.filter((m) => m.type === 'create')).toHaveLength(1);
});
+ test('an adopted replay keeps bracketed paste on after the enable sequence scrolled out of the cap', () => {
+ const h = reserve({ replayCapBytes: 16 });
+ h.start();
+ const emit = (data: string) => h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data });
+ emit('\u001b[?20');
+ emit('04h');
+ emit('x'.repeat(40));
+ h.runTimers();
+ expect(h.start()).toEqual({ ok: true, replay: `\u001b[?2004h${'x'.repeat(16)}` });
+ });
+
+ test('a long private-mode list split across chunks still sets bracketed paste', () => {
+ const h = reserve({ replayCapBytes: 16 });
+ h.start();
+ const emit = (data: string) => h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data });
+ emit(`${'p'.repeat(40)}\u001b[?1000;1002;1003;1004;1005;1006;1015;10`);
+ emit(`16;2004h${'q'.repeat(40)}`);
+ h.runTimers();
+ expect(h.start()).toEqual({ ok: true, replay: `\u001b[?2004h${'q'.repeat(16)}` });
+ });
+
+ test('a sequence split right after its ESC byte still sets bracketed paste', () => {
+ const h = reserve({ replayCapBytes: 16 });
+ h.start();
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: `${'p'.repeat(40)}\u001b` });
+ h.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: `[?2004h${'q'.repeat(40)}` });
+ h.runTimers();
+ expect(h.start()).toEqual({ ok: true, replay: `\u001b[?2004h${'q'.repeat(16)}` });
+ });
+
+ test('an adopted replay carries no enable sequence once the CLI turned bracketed paste off', () => {
+ const disabled = reserve({ replayCapBytes: 16 });
+ disabled.start();
+ disabled.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: '\u001b[?1049;2004h' });
+ disabled.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: '\u001b[?2004l' });
+ disabled.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: 'y'.repeat(40) });
+ disabled.runTimers();
+ expect(disabled.start()).toEqual({ ok: true, replay: 'y'.repeat(16) });
+
+ const reset = reserve({ replayCapBytes: 16 });
+ reset.start();
+ reset.forked[0]?.emitMessage({ type: 'data', ptyId: 'pty-1', data: '\u001b[?2004h' });
+ reset.forked[0]?.emitMessage({
+ type: 'data',
+ ptyId: 'pty-1',
+ data: `\u001bc${'z'.repeat(40)}`,
+ });
+ reset.runTimers();
+ expect(reset.start()).toEqual({ ok: true, replay: 'z'.repeat(16) });
+ });
+
test('delivers immediate output and exit in order without needing later input', () => {
const h = reserve();
const utility = h.forked[0];