The best way to control Claude Code, Codex and more from any computer or phone
fix(web): large terminal pastes reach the program intact (#37103)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Wout Stiens committed
Nov 15, 2026 at 10:41 UTC
8dba23e4206083c3736654bcd18996ae38e730f9
12 files changed
+669
-80
apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
+16
-9
@@ -2,6 +2,7 @@ import * as Dialog from "../../components/ui/Dialog";
2
import {
3
AuthTerminalReadScope,
4
AuthTerminalOperateScope,
5
+ chunkTerminalWrite,
6
DEFAULT_TERMINAL_ID,
7
EnvironmentId,
8
ThreadId,
@@ -607,15 +608,21 @@ function ThreadTerminal(props: {
608
return false;
609
}
610
610
- const result = await writeTerminal({
611
- environmentId: selectedThread.environmentId,
612
- input: {
613
- threadId: selectedThread.id,
614
- terminalId,
615
- data,
616
- },
617
- });
618
- return result._tag === "Success";
611
+ // Android's IME delivers a system paste as one input, which can exceed one write.
612
+ const isSameShell = pasteSession.liveness();
613
+ for (const chunk of chunkTerminalWrite(data)) {
614
+ if (!isSameShell()) return false;
615
+ const result = await writeTerminal({
616
+ environmentId: selectedThread.environmentId,
617
+ input: {
618
+ threadId: selectedThread.id,
619
+ terminalId,
620
+ data: chunk,
621
+ },
622
+ });
623
+ if (result._tag !== "Success") return false;
624
+ }
625
+ return true;
626
};
627
628
const pasteText = async (readText: () => Promise<string>) => {
apps/mobile/src/features/terminal/terminalInput.test.ts
+1
-26
@@ -1,11 +1,6 @@
1
import { describe, expect, it } from "vite-plus/test";
2
3
-import {
4
- chunkTerminalWrite,
5
- encodeTerminalPaste,
6
- resolveModifiedTerminalInput,
7
- TERMINAL_WRITE_MAX_LENGTH,
8
-} from "./terminalInput";
3
+import { encodeTerminalPaste, resolveModifiedTerminalInput } from "./terminalInput";
4
5
const byte = (code: number) => String.fromCharCode(code);
6
const ESC = byte(0x1b);
@@ -78,23 +73,3 @@ describe("encodeTerminalPaste", () => {
73
expect(encodeTerminalPaste(`safe${ESC}[201~; rm -rf /\n`)).toBe("safe [201~; rm -rf /\r");
74
});
75
});
81
-
82
-describe("chunkTerminalWrite", () => {
83
- it("splits oversized writes so every chunk fits the contract", () => {
84
- const chunks = chunkTerminalWrite("y".repeat(TERMINAL_WRITE_MAX_LENGTH * 2 + 5));
85
- expect(chunks.map((chunk) => chunk.length)).toEqual([
86
- TERMINAL_WRITE_MAX_LENGTH,
87
- TERMINAL_WRITE_MAX_LENGTH,
88
- 5,
89
- ]);
90
- expect(chunks.join("")).toHaveLength(TERMINAL_WRITE_MAX_LENGTH * 2 + 5);
91
- });
92
-
93
- it("does not cut a surrogate pair in half at the boundary", () => {
94
- const data = `${"z".repeat(TERMINAL_WRITE_MAX_LENGTH - 1)}😀tail`;
95
- const chunks = chunkTerminalWrite(data);
96
- expect(chunks[0]).toHaveLength(TERMINAL_WRITE_MAX_LENGTH - 1);
97
- expect(chunks[1]).toBe("😀tail");
98
- expect(chunks.join("")).toBe(data);
99
- });
100
-});
apps/mobile/src/features/terminal/terminalInput.ts
-18
@@ -3,9 +3,6 @@ import type { ExecutionEnvironmentPlatformOs } from "@t3tools/contracts";
3
export type PendingModifier = "ctrl" | "meta";
4
export type HostPlatform = "mac" | "linux" | "windows" | "unknown";
5
6
-/** Upper bound of `TerminalWriteInput.data`; longer writes are rejected by the server. */
7
-export const TERMINAL_WRITE_MAX_LENGTH = 65_536;
8
-
6
export type ModifiedTerminalInput =
7
| { readonly kind: "write"; readonly data: string }
8
| { readonly kind: "paste" };
@@ -64,21 +61,6 @@ export function encodeTerminalPaste(text: string): string {
61
return text.replace(UNSAFE_PASTE_BYTES, " ").replace(/\r\n|\n/g, "\r");
62
}
63
67
-export function chunkTerminalWrite(data: string): ReadonlyArray<string> {
68
- const chunks: string[] = [];
69
- let start = 0;
70
- while (start < data.length) {
71
- let end = Math.min(start + TERMINAL_WRITE_MAX_LENGTH, data.length);
72
- const last = data.charCodeAt(end - 1);
73
- if (end < data.length && last >= 0xd800 && last <= 0xdbff) {
74
- end -= 1;
75
- }
76
- chunks.push(data.slice(start, end));
77
- start = end;
78
- }
79
- return chunks;
80
-}
81
-
64
/** Returns null for unknown OSes so callers can try weaker signals. */
65
export function hostPlatformFromOs(os: ExecutionEnvironmentPlatformOs | null): HostPlatform | null {
66
if (os === "darwin") return "mac";
apps/mobile/src/features/terminal/terminalPaste.test.ts
+10
-1
@@ -1,6 +1,6 @@
1
import { describe, expect, it } from "vite-plus/test";
2
3
-import { TERMINAL_WRITE_MAX_LENGTH } from "./terminalInput";
3
+import { TERMINAL_WRITE_MAX_LENGTH } from "@t3tools/contracts";
4
import { createTerminalPasteSession } from "./terminalPaste";
5
6
function deferred<T>() {
@@ -34,6 +34,15 @@ describe("terminal paste session", () => {
34
expect(writes).toEqual([]);
35
});
36
37
+ it("reports a liveness change after capture, including a restart in place", () => {
38
+ const session = createTerminalPasteSession();
39
+ session.reset(true);
40
+ const isSameShell = session.liveness();
41
+ expect(isSameShell()).toBe(true);
42
+ session.reset(true);
43
+ expect(isSameShell()).toBe(false);
44
+ });
45
+
46
it("never overlaps writes from rapid paste requests", async () => {
47
const session = createTerminalPasteSession();
48
session.reset(true);
apps/mobile/src/features/terminal/terminalPaste.ts
+10
-1
@@ -1,4 +1,6 @@
1
-import { chunkTerminalWrite, encodeTerminalPaste } from "./terminalInput";
1
+import { chunkTerminalWrite } from "@t3tools/contracts";
2
+
3
+import { encodeTerminalPaste } from "./terminalInput";
4
5
interface TerminalPasteInput {
6
readonly readText: () => Promise<string>;
@@ -8,6 +10,8 @@ interface TerminalPasteInput {
10
11
export interface TerminalPasteSession {
12
readonly reset: (active: boolean) => void;
13
+ /** True until the terminal's liveness changes (stop, start or restart) after this call. */
14
+ readonly liveness: () => () => boolean;
15
readonly paste: (input: TerminalPasteInput) => Promise<void>;
16
}
17
@@ -21,6 +25,11 @@ export function createTerminalPasteSession(): TerminalPasteSession {
25
liveTarget = active ? {} : null;
26
},
27
28
+ liveness() {
29
+ const target = liveTarget;
30
+ return () => liveTarget === target;
31
+ },
32
+
33
async paste({ readText, write, onReadError }) {
34
const target = liveTarget;
35
if (target === null) {
apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx
+143
-3
@@ -1,4 +1,7 @@
1
-import { EMPTY_TERMINAL_SESSION_STATE } from "@t3tools/client-runtime/state/terminal";
1
+import {
2
+ applyTerminalAttachStreamEvent,
3
+ EMPTY_TERMINAL_SESSION_STATE,
4
+} from "@t3tools/client-runtime/state/terminal";
5
import {
6
EnvironmentId,
7
ThreadId,
@@ -24,6 +27,7 @@ const fixture = vi.hoisted(() => ({
27
typeIntoSurface: null as ((data: string) => void) | null,
28
pressKey: null as ((event: KeyboardEvent) => boolean) | null,
29
writes: [] as Array<{ threadId: string; data: string }>,
30
+ messages: [] as string[],
31
resetSessions: () => {},
32
setSession: (
33
_thread: ScopedThreadRef,
@@ -31,9 +35,11 @@ const fixture = vi.hoisted(() => ({
35
_version: number,
36
_generation?: number,
37
) => {},
38
+ sessionEvent: (_thread: ScopedThreadRef, _type: "snapshot" | "restarted", _pid = 123) => {},
39
surfaceOptions: [] as GhosttyTerminalSurfaceOptions[],
40
reportedSize: null as { cols: number; rows: number } | null,
41
resizeCommand: {},
42
+ runWrite: (): Promise<{ _tag: "Success" }> => Promise.resolve({ _tag: "Success" }),
43
runResize: (_input: unknown): Promise<AsyncResult.AsyncResult<unknown, unknown>> =>
44
Promise.resolve(AsyncResult.success(undefined)),
45
metadata: new Map<
@@ -46,6 +52,7 @@ const fixture = vi.hoisted(() => ({
52
const fakeSurface: object = new Proxy(
53
{
54
input: document.createElement("textarea"),
55
+ write: (data: string) => fixture.messages.push(data),
56
// The real surface re-reports its measured grid.
57
resendSize: () => {
58
const size = fixture.reportedSize;
@@ -73,9 +80,23 @@ vi.mock("~/terminal/ghostty/surface", () => ({
80
vi.mock("../state/terminalSessions", async () => {
81
const Atom = await import("effect/reactivity/Atom");
82
// A strong map, not Atom.family: a family holds weakly, so a GC could hand setSession a new atom.
83
+ const summary = (threadId: ThreadId, pid: number) => ({
84
+ threadId,
85
+ terminalId: "term-1",
86
+ cwd: "/repo",
87
+ worktreePath: null,
88
+ status: "running" as const,
89
+ pid,
90
+ exitCode: null,
91
+ exitSignal: null,
92
+ hasRunningSubprocess: false,
93
+ label: "Terminal 1",
94
+ updatedAt: "2026-11-15T00:00:00.000Z",
95
+ });
96
const makeSession = (threadId: ThreadId) =>
97
Atom.make<typeof EMPTY_TERMINAL_SESSION_STATE>({
98
...EMPTY_TERMINAL_SESSION_STATE,
99
+ summary: summary(threadId, 123),
100
status: fixture.statusByThreadId.get(threadId) ?? "closed",
101
version: 1,
102
});
@@ -99,6 +120,32 @@ vi.mock("../state/terminalSessions", async () => {
120
: { output: { ...EMPTY_TERMINAL_SESSION_STATE.output, generation } }),
121
});
122
};
123
+ fixture.sessionEvent = (thread, type, pid = 123) => {
124
+ const atom = session(thread.environmentId, thread.threadId);
125
+ const current = appAtomRegistry.get(atom);
126
+ appAtomRegistry.set(atom, {
127
+ ...current,
128
+ summary: summary(thread.threadId, pid),
129
+ ...applyTerminalAttachStreamEvent(current, {
130
+ type,
131
+ threadId: thread.threadId,
132
+ terminalId: "term-1",
133
+ snapshot: {
134
+ threadId: thread.threadId,
135
+ terminalId: "term-1",
136
+ cwd: "/repo",
137
+ worktreePath: null,
138
+ status: "running",
139
+ pid,
140
+ history: "",
141
+ exitCode: null,
142
+ exitSignal: null,
143
+ label: "Terminal 1",
144
+ updatedAt: "2026-11-15T00:00:00.000Z",
145
+ },
146
+ }),
147
+ });
148
+ };
149
return {
150
attachedTerminalSessionAtom: (environmentId: EnvironmentId, terminal: { threadId: ThreadId }) =>
151
session(environmentId, terminal.threadId),
@@ -114,6 +161,7 @@ vi.mock("../state/use-atom-command", () => ({
161
if (command === fixture.resizeCommand) return fixture.runResize(args);
162
if (args.input.data !== undefined) {
163
fixture.writes.push({ threadId: args.input.threadId, data: args.input.data });
164
+ return fixture.runWrite();
165
}
166
return { _tag: "Success" };
167
},
@@ -194,11 +242,11 @@ function Drawer(props: {
242
function setup(originalStatus: "starting" | "exited" = "exited") {
243
fixture.resetSessions();
244
const original: ScopedThreadRef = {
197
- environmentId: EnvironmentId.make("environment-a"),
245
+ environmentId: EnvironmentId.make(`environment-a-${expect.getState().currentTestName}`),
246
threadId: ThreadId.make("thread-a"),
247
};
248
const other: ScopedThreadRef = {
201
- environmentId: EnvironmentId.make("environment-b"),
249
+ environmentId: EnvironmentId.make(`environment-b-${expect.getState().currentTestName}`),
250
threadId: ThreadId.make("thread-b"),
251
};
252
fixture.statusByThreadId = new Map([
@@ -209,9 +257,11 @@ function setup(originalStatus: "starting" | "exited" = "exited") {
257
fixture.typeIntoSurface = null;
258
fixture.pressKey = null;
259
fixture.writes = [];
260
+ fixture.messages = [];
261
fixture.surfaceOptions = [];
262
fixture.reportedSize = null;
263
fixture.runResize = () => Promise.resolve(AsyncResult.success(undefined));
264
+ fixture.runWrite = () => Promise.resolve({ _tag: "Success" });
265
fixture.metadata.clear();
266
useRightPanelStore.setState(useRightPanelStore.getInitialState());
267
useTerminalUiStateStore.setState(useTerminalUiStateStore.getInitialState());
@@ -377,6 +427,96 @@ it("only activates terminal paths confirmed to exist on their environment", asyn
427
expect(canActivate("~/notes.ts:5:2")).toBe(true);
428
});
429
430
+it("drops the rest of a split paste when the shell restarts mid-paste", async () => {
431
+ const { other: threadRef } = setup();
432
+ let settleWrite = () => {};
433
+ fixture.runWrite = () =>
434
+ new Promise((resolve) => {
435
+ settleWrite = () => resolve({ _tag: "Success" });
436
+ });
437
+ await using _screen = await render(<Drawer threadRef={threadRef} onCloseTerminal={() => {}} />);
438
+ await act(async () => {
439
+ fixture.pendingSurfaces.shift()?.();
440
+ });
441
+ fixture.typeIntoSurface?.("p".repeat(70_000));
442
+ await act(async () => {
443
+ fixture.sessionEvent(threadRef, "restarted");
444
+ settleWrite();
445
+ });
446
+ fixture.typeIntoSurface?.("after");
447
+ expect(fixture.writes.map(({ data }) => data.length)).toEqual([65_536, 5]);
448
+});
449
+
450
+it.each([
451
+ { pid: 123, closes: true },
452
+ { pid: 456, closes: false },
453
+])(
454
+ "closes interrupted bracket framing only for its process (PID $pid)",
455
+ async ({ pid, closes }) => {
456
+ const { other: threadRef } = setup();
457
+ let settleWrite = () => {};
458
+ fixture.runWrite = () =>
459
+ new Promise((resolve) => {
460
+ settleWrite = () => {
461
+ fixture.runWrite = () => Promise.resolve({ _tag: "Success" });
462
+ resolve({ _tag: "Success" });
463
+ };
464
+ });
465
+ await using _screen = await render(<Drawer threadRef={threadRef} onCloseTerminal={() => {}} />);
466
+ await act(async () => {
467
+ fixture.pendingSurfaces.shift()?.();
468
+ });
469
+ const large = `\x1b[200~${"p".repeat(70_000)}\x1b[201~`;
470
+ fixture.typeIntoSurface?.(large);
471
+ await act(async () => {
472
+ fixture.sessionEvent(threadRef, "snapshot", pid);
473
+ settleWrite();
474
+ });
475
+ await act(async () => {
476
+ fixture.typeIntoSurface?.("after");
477
+ });
478
+ expect(
479
+ fixture.messages.filter((message) => message.includes("paste interrupted")),
480
+ ).toHaveLength(1);
481
+ expect(fixture.writes.map(({ data }) => data)).toEqual([
482
+ large.slice(0, 65_536),
483
+ ...(closes ? ["\x1b[201~"] : []),
484
+ "after",
485
+ ]);
486
+ },
487
+);
488
+
489
+it("closes an interrupted paste after disposal before input from a remounted view", async () => {
490
+ const { other: threadRef } = setup();
491
+ let settleWrite = () => {};
492
+ fixture.runWrite = () =>
493
+ new Promise((resolve) => {
494
+ settleWrite = () => {
495
+ fixture.runWrite = () => Promise.resolve({ _tag: "Success" });
496
+ resolve({ _tag: "Success" });
497
+ };
498
+ });
499
+ await using screen = await render(<Drawer threadRef={threadRef} onCloseTerminal={() => {}} />);
500
+ await act(async () => {
501
+ fixture.pendingSurfaces.shift()?.();
502
+ });
503
+ const large = `\x1b[200~${"p".repeat(70_000)}\x1b[201~`;
504
+ fixture.typeIntoSurface?.(large);
505
+ fixture.typeIntoSurface?.("stale");
506
+ await screen.rerender(<div />);
507
+ await act(async () => {
508
+ settleWrite();
509
+ });
510
+ await screen.rerender(<Drawer threadRef={threadRef} onCloseTerminal={() => {}} />);
511
+ await act(async () => {
512
+ fixture.pendingSurfaces.shift()?.();
513
+ });
514
+ await act(async () => {
515
+ fixture.typeIntoSurface?.("after");
516
+ });
517
+ expect(fixture.writes.map(({ data }) => data.length)).toEqual([65_536, 6, 5]);
518
+});
519
+
520
it("resends a failed resize once in each writable session", async () => {
521
const { other: threadRef } = setup();
522
const resizes: unknown[] = [];
apps/web/src/components/ThreadTerminalDrawer.tsx
+64
-21
@@ -88,6 +88,7 @@ import { readEnvironmentScope } from "../state/session";
88
import { terminalEnvironment } from "../state/terminal";
89
import { useEnvironmentScope } from "../state/session";
90
import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview";
91
+import { terminalInputWriter } from "./terminal/terminalInputWriter";
92
import { useAtomCommand } from "../state/use-atom-command";
93
import { preventTerminalCloseShortcut } from "../lib/terminalCloseShortcut";
94
import { observeResize } from "../lib/observeResize";
@@ -575,6 +576,8 @@ function TerminalSessionViewport({
576
const runTerminalWrite = useAtomCommand(terminalEnvironment.write, {
577
reportFailure: false,
578
});
579
+ // Recovery keeps the original registry-bound command after this viewport unmounts.
580
+ const retainedTerminalWrite = useRef(runTerminalWrite);
581
const runTerminalResize = useAtomCommand(terminalEnvironment.resize, {
582
reportFailure: false,
583
});
@@ -622,12 +625,6 @@ function TerminalSessionViewport({
625
(listener: (session: TerminalSessionState) => void) =>
626
appAtomRegistry.subscribe(terminalSessionAtom, listener),
627
);
625
- const writeTerminal = useEffectEvent((data: string) =>
626
- runTerminalWrite({
627
- environmentId,
628
- input: { threadId, terminalId, data },
629
- }),
630
- );
628
// The surface reports a resent grid like any other, so the next report is the retry.
629
const resizeRetryGenerationRef = useRef<number | null>(null);
630
const resizeTerminal = useEffectEvent(async (cols: number, rows: number) => {
@@ -928,21 +925,67 @@ function TerminalSessionViewport({
925
}
926
};
927
931
- const sendTerminalInput = async (data: string, fallbackError: string) => {
928
+ const readInputSession = () => appAtomRegistry.get(terminalSessionAtom);
929
+ const canWriteInput = () => readEnvironmentScope(environmentId, AuthTerminalOperateScope);
930
+ const writeInputChunk = (data: string) =>
931
+ retainedTerminalWrite.current({
932
+ environmentId,
933
+ input: { threadId, terminalId, data },
934
+ });
935
+ const sendTerminalInput = (data: string, fallbackError: string) => {
936
// The server rejects input until the shell runs, and each rejection would print an error.
933
- if (writableSessionGeneration(readTerminalSession(), hasTerminalWriteAccess()) === null) {
934
- return;
935
- }
936
- const activeTerminal = terminalRef.current;
937
- if (!activeTerminal) return;
938
- const result = await writeTerminal(data);
939
- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
940
- const error = squashAtomCommandFailure(result);
941
- writeSystemMessage(
942
- activeTerminal,
943
- error instanceof Error ? error.message : fallbackError,
944
- );
945
- }
937
+ // Input belongs to the shell and surface it was typed into; a restart the client has seen drops what is left.
938
+ const session = readTerminalSession();
939
+ const generation = writableSessionGeneration(session, hasTerminalWriteAccess());
940
+ const lifecycleVersion = session.lifecycleVersion;
941
+ if (generation === null) return;
942
+ const writeInput = terminalInputWriter(
943
+ JSON.stringify([environmentId, threadId, terminalId]),
944
+ () => appAtomRegistry.mount(terminalSessionAtom),
945
+ );
946
+ let reported = false;
947
+ const report = (message: string) => {
948
+ if (reported || terminalRef.current !== terminal) return;
949
+ reported = true;
950
+ writeSystemMessage(terminal, message);
951
+ };
952
+ return writeInput(
953
+ data,
954
+ async (chunk) => {
955
+ const currentSession = readInputSession();
956
+ if (
957
+ terminalRef.current !== terminal ||
958
+ currentSession.lifecycleVersion !== lifecycleVersion ||
959
+ writableSessionGeneration(currentSession, canWriteInput()) !== generation
960
+ ) {
961
+ return "not-dispatched";
962
+ }
963
+ const result = await writeInputChunk(chunk);
964
+ if (result._tag === "Success") return true;
965
+ if (terminalRef.current === terminal && !isAtomCommandInterrupted(result)) {
966
+ const error = squashAtomCommandFailure(result);
967
+ report(error instanceof Error ? error.message : fallbackError);
968
+ }
969
+ return false;
970
+ },
971
+ // Close the bracket only for the process that saw it open; wait while its pid is unknown.
972
+ async () => {
973
+ const pid = session.summary?.pid ?? null;
974
+ const current = readInputSession();
975
+ const currentPid = current.summary?.pid ?? null;
976
+ if (currentPid === null) return false;
977
+ if (pid !== null && currentPid !== pid) return true;
978
+ if (writableSessionGeneration(current, canWriteInput()) === null) return false;
979
+ const result = await writeInputChunk("\x1b[201~");
980
+ if (result._tag === "Success") return true;
981
+ if (!isAtomCommandInterrupted(result)) {
982
+ const error = squashAtomCommandFailure(result);
983
+ report(error instanceof Error ? error.message : "Failed to close interrupted paste");
984
+ }
985
+ return false;
986
+ },
987
+ () => report("Terminal paste interrupted. Paste again when the terminal is ready."),
988
+ );
989
};
990
991
function handleBeforeKey(event: KeyboardEvent): boolean {
@@ -1104,7 +1147,7 @@ function TerminalSessionViewport({
1147
mount.focus({ preventScroll: true });
1148
}
1149
};
1107
- }, [cwd, environmentId, terminalId]);
1150
+ }, [cwd, environmentId, terminalId, terminalSessionAtom, threadId]);
1151
1152
const attachContainer = (mount: HTMLDivElement) => {
1153
containerRef.current = mount;
apps/web/src/components/terminal/terminalInputWriter.test.ts
new
+170
@@ -0,0 +1,170 @@
1
+import { TerminalWriteInput } from "@t3tools/contracts";
2
+import * as Schema from "effect/Schema";
3
+import { describe, expect, it, vi } from "vite-plus/test";
4
+
5
+import { createTerminalInputWriter } from "./terminalInputWriter";
6
+
7
+const isWriteInput = Schema.is(TerminalWriteInput);
8
+const fitsWrite = (data: string) => isWriteInput({ threadId: "t", terminalId: "default", data });
9
+
10
+/** A `send` whose calls stay pending until the test settles them. */
11
+function heldSend() {
12
+ const sent: Array<{ readonly chunk: string; readonly settle: (ok: boolean) => void }> = [];
13
+ const waiters: Array<{ readonly count: number; readonly resolve: () => void }> = [];
14
+ return {
15
+ sent,
16
+ chunks: () => sent.map(({ chunk }) => chunk),
17
+ /** Resolves once `count` chunks have been sent. */
18
+ sends: (count: number) =>
19
+ new Promise<void>((resolve) => {
20
+ if (sent.length >= count) resolve();
21
+ else waiters.push({ count, resolve });
22
+ }),
23
+ send: (chunk: string) =>
24
+ new Promise<boolean>((settle) => {
25
+ sent.push({ chunk, settle });
26
+ for (const waiter of waiters) if (sent.length >= waiter.count) waiter.resolve();
27
+ }),
28
+ };
29
+}
30
+
31
+describe("createTerminalInputWriter", () => {
32
+ const line = ' {"file":"src/日本語.ts","message":"Review 🧑🏽💻 café changes"},\n';
33
+ const paste = (length: number) =>
34
+ line.repeat(Math.ceil(length / line.length)).slice(0, length - 1) + "\n";
35
+
36
+ it("delivers a bracketed paste over the limit as writes the server accepts", async () => {
37
+ const data = `\x1b[200~${paste(100_000)}\x1b[201~`;
38
+ const sent: string[] = [];
39
+ await createTerminalInputWriter()(data, async (chunk) => {
40
+ sent.push(chunk);
41
+ return true;
42
+ });
43
+
44
+ expect(sent).toHaveLength(2);
45
+ expect(sent.every(fitsWrite)).toBe(true);
46
+ expect(sent.join("")).toBe(data);
47
+ });
48
+
49
+ it("sends one chunk per round trip and holds later input behind a split write", async () => {
50
+ const write = createTerminalInputWriter();
51
+ const { sent, chunks, sends, send } = heldSend();
52
+ const large = `\x1b[200~${"p".repeat(70_000)}\x1b[201~`;
53
+ const [first, second] = [large.slice(0, 65_536), large.slice(65_536)];
54
+
55
+ void write("a", send);
56
+ const pasted = write(large, send);
57
+ void write("b", send);
58
+ void write("c", send);
59
+ expect(chunks()).toEqual(["a"]);
60
+ sent[0]!.settle(true);
61
+ await sends(2);
62
+ expect(chunks()).toEqual(["a", first]);
63
+
64
+ sent[1]!.settle(true);
65
+ await sends(3);
66
+ expect(chunks()).toEqual(["a", first, second]);
67
+ sent[2]!.settle(true);
68
+ await pasted;
69
+ await sends(4);
70
+ expect(chunks()).toEqual(["a", first, second, "b"]);
71
+ sent[3]!.settle(true);
72
+ await sends(5);
73
+ expect(chunks()).toEqual(["a", first, second, "b", "c"]);
74
+ });
75
+
76
+ it("dispatches small writes without waiting for acknowledgements and queues a paste behind them", async () => {
77
+ const write = createTerminalInputWriter();
78
+ const { sent, chunks, sends, send } = heldSend();
79
+ const inputs = Array.from({ length: 32 }, (_, index) => `key-${index}`);
80
+ const smallWrites = inputs.map((data) => write(data, send));
81
+ expect(chunks()).toEqual(inputs);
82
+
83
+ const large = "p".repeat(70_000);
84
+ const pasted = write(large, send);
85
+ const after = write("after", send);
86
+ // Finishing newer sends first must not let queued input overtake the oldest write.
87
+ for (let index = inputs.length - 1; index > 0; index--) sent[index]!.settle(true);
88
+ await Promise.all(smallWrites.slice(1));
89
+ expect(sent).toHaveLength(32);
90
+ sent[0]!.settle(true);
91
+ await sends(33);
92
+ expect(sent[32]!.chunk).toBe(large.slice(0, 65_536));
93
+ sent[32]!.settle(true);
94
+ await sends(34);
95
+ expect(sent[33]!.chunk).toBe(large.slice(65_536));
96
+ sent[33]!.settle(true);
97
+ await pasted;
98
+ await sends(35);
99
+ expect(sent[34]!.chunk).toBe("after");
100
+ sent[34]!.settle(true);
101
+ await after;
102
+ });
103
+
104
+ it("closes an interrupted bracketed paste before later input", async () => {
105
+ const write = createTerminalInputWriter();
106
+ const { sent, chunks, sends, send } = heldSend();
107
+ const large = `\x1b[200~${"p".repeat(140_000)}\x1b[201~`;
108
+ const pasted = write(large, send);
109
+ const after = write("after", send);
110
+ sent[0]!.settle(true);
111
+ await sends(2);
112
+ sent[1]!.settle(false);
113
+ await sends(3);
114
+ expect(chunks()).toEqual([large.slice(0, 65_536), large.slice(65_536, 131_072), "\x1b[201~"]);
115
+ sent[2]!.settle(false);
116
+ await pasted;
117
+ await sends(4);
118
+ expect(sent[3]!.chunk).toBe("\x1b[201~");
119
+ sent[3]!.settle(true);
120
+ await sends(5);
121
+ expect(sent[4]!.chunk).toBe("after");
122
+ sent[4]!.settle(true);
123
+ await after;
124
+ });
125
+
126
+ it("closes an opening chunk whose acknowledgement was lost without retrying payload", async () => {
127
+ const sent: string[] = [];
128
+ const write = createTerminalInputWriter();
129
+ const send = async (chunk: string) => {
130
+ sent.push(chunk);
131
+ return chunk === "\x1b[201~" || chunk === "after";
132
+ };
133
+ const large = `\x1b[200~${"p".repeat(70_000)}\x1b[201~`;
134
+ await write(large, send);
135
+ await write("after", send);
136
+ expect(sent).toEqual([large.slice(0, 65_536), "\x1b[201~", "after"]);
137
+ });
138
+
139
+ it("reports each input blocked by failed framing recovery without retrying payload", async () => {
140
+ const sent: string[] = [];
141
+ const interrupted = vi.fn();
142
+ const write = createTerminalInputWriter();
143
+ const send = async (chunk: string) => {
144
+ sent.push(chunk);
145
+ return false;
146
+ };
147
+ const recover = async () => {
148
+ sent.push("\x1b[201~");
149
+ return false;
150
+ };
151
+ const large = `\x1b[200~${"p".repeat(70_000)}\x1b[201~`;
152
+ await write(large, send, recover, interrupted);
153
+ await write("after", send, recover, interrupted);
154
+ expect(sent).toEqual([large.slice(0, 65_536), "\x1b[201~", "\x1b[201~"]);
155
+ expect(interrupted).toHaveBeenCalledTimes(2);
156
+ });
157
+
158
+ it("drops the rest of a split write after a failed chunk and keeps later input", async () => {
159
+ const write = createTerminalInputWriter();
160
+ const { sent, chunks, sends, send } = heldSend();
161
+
162
+ const pasted = write("q".repeat(140_000), send);
163
+ void write("next", send);
164
+ sent[0]!.settle(false);
165
+ await pasted;
166
+ await sends(2);
167
+
168
+ expect(chunks()).toEqual(["q".repeat(65_536), "next"]);
169
+ });
170
+});
apps/web/src/components/terminal/terminalInputWriter.ts
new
+106
@@ -0,0 +1,106 @@
1
+import { chunkTerminalWrite } from "@t3tools/contracts";
2
+
3
+/** Sends one chunk of terminal input; resolves false when it failed and the rest should drop. */
4
+type SendTerminalChunk = (chunk: string) => Promise<boolean | "not-dispatched">;
5
+
6
+/**
7
+ * Orders one terminal's input into writes that fit `terminal.write`. A split write goes one chunk
8
+ * per round trip and later input waits behind it; other writes go out immediately, like keystrokes.
9
+ */
10
+export function createTerminalInputWriter(onIdle = () => {}) {
11
+ let pending: Promise<void> | null = null;
12
+ const immediate = new Set<Promise<void>>();
13
+
14
+ let closeInterruptedPaste: (() => Promise<boolean>) | null = null;
15
+ const closePaste = async () => {
16
+ if (closeInterruptedPaste === null) return true;
17
+ if (!(await closeInterruptedPaste())) return false;
18
+ closeInterruptedPaste = null;
19
+ return true;
20
+ };
21
+
22
+ const sendChunks = async (
23
+ data: string,
24
+ chunks: ReadonlyArray<string>,
25
+ send: SendTerminalChunk,
26
+ recover: () => Promise<boolean>,
27
+ interrupted: () => void,
28
+ ) => {
29
+ if (closeInterruptedPaste !== null && !(await closePaste())) {
30
+ interrupted();
31
+ return;
32
+ }
33
+ const bracketed =
34
+ chunks.length > 1 && data.startsWith("\x1b[200~") && data.endsWith("\x1b[201~");
35
+ let opened = false;
36
+ try {
37
+ for (const chunk of chunks) {
38
+ const result = await send(chunk);
39
+ if (result !== true) {
40
+ if (result !== "not-dispatched") opened = bracketed;
41
+ if (chunks.length > 1) interrupted();
42
+ return;
43
+ }
44
+ opened = bracketed;
45
+ }
46
+ opened = false;
47
+ } finally {
48
+ if (opened) {
49
+ closeInterruptedPaste = recover;
50
+ await closePaste();
51
+ }
52
+ }
53
+ };
54
+
55
+ return (
56
+ data: string,
57
+ send: SendTerminalChunk,
58
+ recover: () => Promise<boolean> = async () => (await send("\x1b[201~")) === true,
59
+ interrupted = () => {},
60
+ ): Promise<void> => {
61
+ const idle = () => {
62
+ if (pending === null && immediate.size === 0 && closeInterruptedPaste === null) onIdle();
63
+ };
64
+ const chunks = chunkTerminalWrite(data);
65
+ const run = () => sendChunks(data, chunks, send, recover, interrupted);
66
+ if (pending === null && closeInterruptedPaste === null && chunks.length === 1) {
67
+ const current = run();
68
+ immediate.add(current);
69
+ void current.then(
70
+ () => {
71
+ immediate.delete(current);
72
+ idle();
73
+ },
74
+ () => {
75
+ immediate.delete(current);
76
+ idle();
77
+ },
78
+ );
79
+ return current;
80
+ }
81
+ const previous = pending ?? (immediate.size > 0 ? Promise.allSettled(immediate) : null);
82
+ const current = previous === null ? run() : previous.then(run, run);
83
+ pending = current;
84
+ const reset = () => {
85
+ if (pending === current) pending = null;
86
+ idle();
87
+ };
88
+ void current.then(reset, reset);
89
+ return current;
90
+ };
91
+}
92
+
93
+const writers = new Map<string, ReturnType<typeof createTerminalInputWriter>>();
94
+
95
+/** Retain ordering and framing obligations until acknowledged, across terminal view remounts. */
96
+export function terminalInputWriter(key: string, retain: () => () => void) {
97
+ const existing = writers.get(key);
98
+ if (existing) return existing;
99
+ const release = retain();
100
+ const writer = createTerminalInputWriter(() => {
101
+ if (writers.get(key) === writer) writers.delete(key);
102
+ release();
103
+ });
104
+ writers.set(key, writer);
105
+ return writer;
106
+}
packages/contracts/src/terminal.test.ts
+22
@@ -2,7 +2,9 @@ import * as Schema from "effect/Schema";
2
import { describe, expect, it } from "vite-plus/test";
3
4
import {
5
+ chunkTerminalWrite,
6
DEFAULT_TERMINAL_ID,
7
+ TERMINAL_WRITE_MAX_LENGTH,
8
TerminalError,
9
TerminalOpenInput,
10
TerminalProviderEnvironmentError,
@@ -49,3 +51,23 @@ describe("TerminalOpenInput", () => {
51
expect(parsed.env).toEqual({ GOOD_KEY: "2" });
52
});
53
});
54
+
55
+describe("chunkTerminalWrite", () => {
56
+ it("splits oversized writes so every chunk fits the contract", () => {
57
+ const chunks = chunkTerminalWrite("y".repeat(TERMINAL_WRITE_MAX_LENGTH * 2 + 5));
58
+ expect(chunks.map((chunk) => chunk.length)).toEqual([
59
+ TERMINAL_WRITE_MAX_LENGTH,
60
+ TERMINAL_WRITE_MAX_LENGTH,
61
+ 5,
62
+ ]);
63
+ expect(chunks.join("")).toHaveLength(TERMINAL_WRITE_MAX_LENGTH * 2 + 5);
64
+ });
65
+
66
+ it("does not cut a surrogate pair in half at the boundary", () => {
67
+ const data = `${"z".repeat(TERMINAL_WRITE_MAX_LENGTH - 1)}😀tail`;
68
+ const chunks = chunkTerminalWrite(data);
69
+ expect(chunks[0]).toHaveLength(TERMINAL_WRITE_MAX_LENGTH - 1);
70
+ expect(chunks[1]).toBe("😀tail");
71
+ expect(chunks.join("")).toBe(data);
72
+ });
73
+});
packages/contracts/src/terminal.ts
+22
-1
@@ -190,12 +190,33 @@ export type TerminalAttachInput = typeof TerminalAttachInput.Type;
190
export const TerminalObserveInput = TerminalSessionInput;
191
export type TerminalObserveInput = Schema.Codec.Encoded<typeof TerminalObserveInput>;
192
193
+/** Longest `data` one `terminal.write` carries, in UTF-16 code units. */
194
+export const TERMINAL_WRITE_MAX_LENGTH = 65_536;
195
+
196
export const TerminalWriteInput = Schema.Struct({
197
...TerminalSessionInput.fields,
195
- data: Schema.String.check(Schema.isNonEmpty()).check(Schema.isMaxLength(65_536)),
198
+ data: Schema.String.check(Schema.isNonEmpty()).check(
199
+ Schema.isMaxLength(TERMINAL_WRITE_MAX_LENGTH),
200
+ ),
201
});
202
export type TerminalWriteInput = Schema.Codec.Encoded<typeof TerminalWriteInput>;
203
204
+/** Splits input into writes that fit `TerminalWriteInput`, never between a surrogate pair. */
205
+export function chunkTerminalWrite(data: string): ReadonlyArray<string> {
206
+ const chunks: string[] = [];
207
+ let start = 0;
208
+ while (start < data.length) {
209
+ let end = Math.min(start + TERMINAL_WRITE_MAX_LENGTH, data.length);
210
+ const last = data.charCodeAt(end - 1);
211
+ if (end < data.length && last >= 0xd800 && last <= 0xdbff) {
212
+ end -= 1;
213
+ }
214
+ chunks.push(data.slice(start, end));
215
+ start = end;
216
+ }
217
+ return chunks;
218
+}
219
+
220
export const TerminalResizeInput = Schema.Struct({
221
...TerminalSessionInput.fields,
222
cols: TerminalColsSchema,
scripts/scenarios/terminal-large-paste-reaches-program.e2e.ts
new
+105
@@ -0,0 +1,105 @@
1
+/// <reference lib="dom" />
2
+// The DOM lib types the function this scenario runs in the page.
3
+import { expect } from "e2e";
4
+import * as Effect from "effect/Effect";
5
+import * as FileSystem from "effect/FileSystem";
6
+
7
+import { runPromise, test, WEB } from "./t3.ts";
8
+
9
+// A raw-mode program that turns on bracketed paste, logs every byte it receives to `received`,
10
+// and exits once the paste's closing marker arrives.
11
+const PROBE = String.raw`import { appendFileSync, writeFileSync } from "node:fs";
12
+
13
+const log = new URL("received", import.meta.url);
14
+let tail = "";
15
+let bytes = 0;
16
+
17
+writeFileSync(log, "");
18
+process.stdin.setRawMode(true);
19
+process.stdin.on("data", (chunk) => {
20
+ appendFileSync(log, chunk);
21
+ bytes += chunk.length;
22
+ tail = (tail + chunk.toString("latin1")).slice(-6);
23
+ if (tail === "\x1b[201~") {
24
+ process.stdin.setRawMode(false);
25
+ process.stdout.write("\x1b[?2004l\r\nreceived " + bytes + " bytes\r\n");
26
+ process.exit(0);
27
+ }
28
+});
29
+process.stdout.write("\x1b[?2004h");
30
+writeFileSync(new URL("ready", import.meta.url), "ready");
31
+`;
32
+
33
+// Over the 65,536-unit write limit, multiline, with a surrogate pair straddling the first
34
+// 65,536-unit boundary of the bracketed paste (6 units of ESC[200~ come first).
35
+const LINE = ' {"file":"src/日本語.ts","message":"café changes"},\n';
36
+const EMOJI_LINE = ' {"user":"🧑🏽💻","note":"naïve 𝔘𝔫𝔦𝔠𝔬𝔡𝔢"},\n';
37
+const HEAD = LINE.repeat(Math.ceil(65_529 / LINE.length)).slice(0, 65_529);
38
+const PASTE = HEAD + "🧑🏽💻" + EMOJI_LINE.repeat(Math.ceil(34_000 / EMOJI_LINE.length));
39
+const EXPECTED = Buffer.from("\x1b[200~" + PASTE + "\x1b[201~");
40
+const compare = (received: Uint8Array) => ({
41
+ bytes: received.length,
42
+ intact: EXPECTED.equals(received),
43
+});
44
+
45
+test(
46
+ "A web terminal paste larger than one write reaches the program intact",
47
+ WEB,
48
+ async ({ t3, app, browser, screen }) => {
49
+ await browser.emulateMedia({ colorScheme: "dark" });
50
+ const project = await t3.project("demo", { "paste-probe.mjs": PROBE });
51
+ const thread = await t3.thread({ project, title: "Paste", messages: ["hello"] });
52
+ const read = (file: string) =>
53
+ runPromise(
54
+ Effect.gen(function* () {
55
+ const fs = yield* FileSystem.FileSystem;
56
+ return yield* fs.readFileString(`${project}/${file}`);
57
+ }).pipe(Effect.orElseSucceed(() => "")),
58
+ );
59
+ const received = () =>
60
+ runPromise(
61
+ Effect.gen(function* () {
62
+ const fs = yield* FileSystem.FileSystem;
63
+ return compare(yield* fs.readFile(`${project}/received`));
64
+ }).pipe(Effect.orElseSucceed(() => compare(new Uint8Array()))),
65
+ );
66
+ await t3.open(thread);
67
+
68
+ await screen.getByRole("button", "Toggle terminal drawer").tap();
69
+ const terminal = screen.getByLabel("Terminal input");
70
+
71
+ // Input sent before the shell runs is dropped, so retype until it lands.
72
+ await expect
73
+ .poll(
74
+ async () => {
75
+ await terminal.focus();
76
+ await browser.keyboard.type(`echo ready > '${project}/shell-ready'`);
77
+ await browser.keyboard.press("Enter");
78
+ return read("shell-ready");
79
+ },
80
+ { timeout: 30_000 },
81
+ )
82
+ .toBe("ready\n");
83
+
84
+ await terminal.focus();
85
+ await browser.keyboard.type(`'${process.execPath}' '${project}/paste-probe.mjs'`);
86
+ await browser.keyboard.press("Enter");
87
+ await expect.poll(() => read("ready"), { timeout: 15_000 }).toBe("ready");
88
+
89
+ await browser.evaluate((text) => {
90
+ const input = document.querySelector('[aria-label="Terminal input"]');
91
+ if (!input) throw new Error("no terminal input");
92
+ const clipboardData = new DataTransfer();
93
+ clipboardData.setData("text/plain", text);
94
+ input.dispatchEvent(
95
+ new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }),
96
+ );
97
+ return null;
98
+ }, PASTE);
99
+
100
+ await expect
101
+ .poll(received, { timeout: 20_000 })
102
+ .toEqual({ bytes: EXPECTED.length, intact: true });
103
+ await app.screenshot("pasted");
104
+ },
105
+);