Skip to content

Commit d3716bd

Browse files
committed
fix(mobile): guard terminal paste against a stale target
Address review on #9199: the clipboard read is async, so a paste started on one terminal could land in whichever pty the screen showed by the time the read resolved. Track the live write target (terminal key while the session runs) in a ref, capture it before the read, and drop the paste if it no longer matches or the screen unmounted. Also split pastes into writes the wire contract accepts (65,536 chars, never through a surrogate pair), and read the host OS from the environment descriptor, falling back to the label sniff only until it arrives.
1 parent 87d3aa4 commit d3716bd

3 files changed

Lines changed: 108 additions & 6 deletions

File tree

‎apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx‎

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import { environmentCatalog } from "../../connection/catalog";
2929
import { useEnvironmentPresentation } from "../../state/presentation";
3030
import { terminalEnvironment } from "../../state/terminal";
3131
import { useAtomCommand } from "../../state/use-atom-command";
32+
import { useServerConfigs } from "../../state/entities";
3233
import { useWorkspaceState } from "../../state/workspace";
3334
import {
3435
MAX_TERMINAL_FONT_SIZE,
@@ -68,7 +69,9 @@ import {
6869
type TerminalMenuSession,
6970
} from "./terminalMenu";
7071
import {
72+
chunkTerminalWrite,
7173
encodeTerminalPaste,
74+
hostPlatformFromOs,
7275
resolveModifiedTerminalInput,
7376
type HostPlatform,
7477
type PendingModifier,
@@ -455,9 +458,17 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
455458
});
456459
}, [terminal.buffer, terminal.buffer.length, terminalKey]);
457460
const cwd = terminal.summary?.cwd ?? selectedThreadProject?.workspaceRoot ?? null;
461+
const serverConfigs = useServerConfigs();
462+
const hostOs =
463+
routeEnvironmentId === null
464+
? null
465+
: (serverConfigs.get(routeEnvironmentId)?.environment.platform.os ?? null);
466+
// The descriptor is authoritative; the label is only a hint until it arrives.
458467
const hostPlatform = useMemo(
459-
() => inferHostPlatform(selectedEnvironmentConnection?.environmentLabel ?? null),
460-
[selectedEnvironmentConnection?.environmentLabel],
468+
() =>
469+
hostPlatformFromOs(hostOs) ??
470+
inferHostPlatform(selectedEnvironmentConnection?.environmentLabel ?? null),
471+
[hostOs, selectedEnvironmentConnection?.environmentLabel],
461472
);
462473

463474
const terminalTheme = getMobileTerminalTheme(themeId, appearanceScheme);
@@ -705,20 +716,34 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
705716
[isRunning, selectedThread, terminalId, writeTerminal],
706717
);
707718

719+
// The terminal a paste may still land in once the clipboard read resolves.
720+
// Cleared when the route moves on, the session ends, or the screen unmounts,
721+
// so a slow read never writes into a different pty than the one it started in.
722+
const liveWriteTargetRef = useRef<string | null>(null);
723+
useEffect(() => {
724+
liveWriteTargetRef.current = isRunning ? terminalKey : null;
725+
return () => {
726+
liveWriteTargetRef.current = null;
727+
};
728+
}, [isRunning, terminalKey]);
729+
708730
const pasteFromClipboard = useCallback(async () => {
731+
const target = terminalKey;
709732
let text: string;
710733
try {
711734
text = await Clipboard.getStringAsync();
712735
} catch (cause) {
713736
console.error(new TerminalClipboardReadError({ cause }));
714737
return;
715738
}
739+
if (liveWriteTargetRef.current !== target) {
740+
return;
741+
}
716742

717-
const encoded = encodeTerminalPaste(text);
718-
if (encoded.length > 0) {
719-
writeInput(encoded);
743+
for (const chunk of chunkTerminalWrite(encodeTerminalPaste(text))) {
744+
writeInput(chunk);
720745
}
721-
}, [writeInput]);
746+
}, [terminalKey, writeInput]);
722747

723748
/** Sends a key through the armed toolbar modifier, if any, and disarms it. */
724749
const writeModifiedInput = useCallback(

‎apps/mobile/src/features/terminal/terminalInput.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,11 @@ import { describe, expect, it } from "vite-plus/test";
22

33
import {
44
applyCtrlModifier,
5+
chunkTerminalWrite,
56
encodeTerminalPaste,
7+
hostPlatformFromOs,
68
resolveModifiedTerminalInput,
9+
TERMINAL_WRITE_MAX_LENGTH,
710
} from "./terminalInput";
811

912
const byte = (code: number) => String.fromCharCode(code);
@@ -81,3 +84,42 @@ describe("encodeTerminalPaste", () => {
8184
expect(encodeTerminalPaste(`safe${ESC}[201~; rm -rf /\n`)).toBe("safe [201~; rm -rf /\r");
8285
});
8386
});
87+
88+
describe("chunkTerminalWrite", () => {
89+
it("leaves writes within the wire limit whole", () => {
90+
expect(chunkTerminalWrite("")).toEqual([]);
91+
expect(chunkTerminalWrite("ls")).toEqual(["ls"]);
92+
expect(chunkTerminalWrite("x".repeat(TERMINAL_WRITE_MAX_LENGTH))).toHaveLength(1);
93+
});
94+
95+
it("splits oversized writes so every chunk fits the contract", () => {
96+
const chunks = chunkTerminalWrite("y".repeat(TERMINAL_WRITE_MAX_LENGTH * 2 + 5));
97+
expect(chunks.map((chunk) => chunk.length)).toEqual([
98+
TERMINAL_WRITE_MAX_LENGTH,
99+
TERMINAL_WRITE_MAX_LENGTH,
100+
5,
101+
]);
102+
expect(chunks.join("")).toHaveLength(TERMINAL_WRITE_MAX_LENGTH * 2 + 5);
103+
});
104+
105+
it("does not cut a surrogate pair in half at the boundary", () => {
106+
const data = `${"z".repeat(TERMINAL_WRITE_MAX_LENGTH - 1)}😀tail`;
107+
const chunks = chunkTerminalWrite(data);
108+
expect(chunks[0]).toHaveLength(TERMINAL_WRITE_MAX_LENGTH - 1);
109+
expect(chunks[1]).toBe("😀tail");
110+
expect(chunks.join("")).toBe(data);
111+
});
112+
});
113+
114+
describe("hostPlatformFromOs", () => {
115+
it("maps the descriptor os onto the toolbar layout", () => {
116+
expect(hostPlatformFromOs("darwin")).toBe("mac");
117+
expect(hostPlatformFromOs("windows")).toBe("windows");
118+
expect(hostPlatformFromOs("linux")).toBe("linux");
119+
});
120+
121+
it("defers to the caller when the os is unknown or not loaded yet", () => {
122+
expect(hostPlatformFromOs("unknown")).toBeNull();
123+
expect(hostPlatformFromOs(null)).toBeNull();
124+
});
125+
});

‎apps/mobile/src/features/terminal/terminalInput.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
1+
import type { ExecutionEnvironmentPlatformOs } from "@t3tools/contracts";
2+
13
export type PendingModifier = "ctrl" | "meta";
24
export type HostPlatform = "mac" | "linux" | "windows" | "unknown";
35

6+
/** Upper bound of `TerminalWriteInput.data`; longer writes are rejected by the server. */
7+
export const TERMINAL_WRITE_MAX_LENGTH = 65_536;
8+
49
export type ModifiedTerminalInput =
510
| { readonly kind: "write"; readonly data: string }
611
| { readonly kind: "paste" };
@@ -71,3 +76,33 @@ export function resolveModifiedTerminalInput(input: {
7176
export function encodeTerminalPaste(text: string): string {
7277
return text.replace(UNSAFE_PASTE_BYTES, " ").replace(/\r\n|\n/g, "\r");
7378
}
79+
80+
/**
81+
* Splits terminal input into writes the wire contract accepts, never cutting
82+
* through a surrogate pair so every chunk stays valid UTF-16.
83+
*/
84+
export function chunkTerminalWrite(data: string): ReadonlyArray<string> {
85+
const chunks: string[] = [];
86+
let start = 0;
87+
while (start < data.length) {
88+
let end = Math.min(start + TERMINAL_WRITE_MAX_LENGTH, data.length);
89+
const last = data.charCodeAt(end - 1);
90+
if (end < data.length && last >= 0xd800 && last <= 0xdbff) {
91+
end -= 1;
92+
}
93+
chunks.push(data.slice(start, end));
94+
start = end;
95+
}
96+
return chunks;
97+
}
98+
99+
/**
100+
* Maps the OS reported by the environment descriptor onto the toolbar's host
101+
* layout. Returns null for "unknown" so callers can fall back to a weaker signal.
102+
*/
103+
export function hostPlatformFromOs(os: ExecutionEnvironmentPlatformOs | null): HostPlatform | null {
104+
if (os === "darwin") return "mac";
105+
if (os === "linux") return "linux";
106+
if (os === "windows") return "windows";
107+
return null;
108+
}

0 commit comments

Comments
 (0)