TypeScript
feat(mobile): paste the phone clipboard into the terminal (#9199)
Lars Nieuwenhuisd5b941008630
diff --git a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsxindex a51e084efc9..351082580d6 100644--- a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx+++ b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx@@ -6,6 +6,8 @@ import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/Stacimport { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { Platform, Pressable, View } from "react-native";+import * as Clipboard from "expo-clipboard";+import * as Schema from "effect/Schema";import {KeyboardController,KeyboardEvents,@@ -27,6 +29,7 @@ import { environmentCatalog } from "../../connection/catalog";import { useEnvironmentPresentation } from "../../state/presentation";import { terminalEnvironment } from "../../state/terminal";import { useAtomCommand } from "../../state/use-atom-command";+import { useServerConfigs } from "../../state/entities";import { useWorkspaceState } from "../../state/workspace";import {MAX_TERMINAL_FONT_SIZE,@@ -65,6 +68,13 @@ import {resolveTerminalSessionLabel,type TerminalMenuSession,} from "./terminalMenu";+import {+ hostPlatformFromOs,+ resolveModifiedTerminalInput,+ type HostPlatform,+ type PendingModifier,+} from "./terminalInput";+import { createTerminalPasteSession } from "./terminalPaste";import { cacheTerminalGridSize, getCachedTerminalGridSize } from "./terminalUiState";const DEFAULT_TERMINAL_COLS = 80;@@ -72,12 +82,19 @@ const DEFAULT_TERMINAL_ROWS = 24;const TERMINAL_ACCESSORY_HEIGHT = 52;const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";-type PendingModifier = "ctrl" | "meta";-type HostPlatform = "mac" | "linux" | "windows" | "unknown";+class TerminalClipboardReadError extends Schema.TaggedErrorClass<TerminalClipboardReadError>()(+ "TerminalClipboardReadError",+ { terminalId: Schema.String, cause: Schema.Defect() },+) {+ override get message(): string {+ return `Failed to read the clipboard for a paste into terminal ${this.terminalId}.`;+ }+}type TerminalToolbarAction =| { readonly kind: "send"; readonly key: string; readonly label: string; readonly data: string }| { readonly kind: "clear"; readonly key: string; readonly label: string }+ | { readonly kind: "paste"; readonly key: string; readonly label: string }| {readonly kind: "modifier";readonly key: string;@@ -114,28 +131,6 @@ function inferHostPlatform(environmentLabel: string | null): HostPlatform {return "unknown";}-function applyCtrlModifier(input: string): string {- const firstCharacter = input[0];- if (!firstCharacter) {- return input;- }-- const lowerCharacter = firstCharacter.toLowerCase();- if (lowerCharacter >= "a" && lowerCharacter <= "z") {- return String.fromCharCode(lowerCharacter.charCodeAt(0) - 96);- }-- if (firstCharacter === "@") return "\u0000";- if (firstCharacter === "[") return "\u001b";- if (firstCharacter === "\\") return "\u001c";- if (firstCharacter === "]") return "\u001d";- if (firstCharacter === "^") return "\u001e";- if (firstCharacter === "_") return "\u001f";- if (firstCharacter === "?") return "\u007f";-- return input;-}-function pickRunningTerminalSessionForBootstrap(sessions: ReadonlyArray<KnownTerminalSession>,): KnownTerminalSession | null {@@ -462,9 +457,17 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)});}, [terminal.buffer, terminal.buffer.length, terminalKey]);const cwd = terminal.summary?.cwd ?? selectedThreadProject?.workspaceRoot ?? null;+ const serverConfigs = useServerConfigs();+ const hostOs =+ routeEnvironmentId === null+ ? null+ : (serverConfigs.get(routeEnvironmentId)?.environment.platform.os ?? null);+ // The descriptor is authoritative; the label is only a hint until it arrives.const hostPlatform = useMemo(- () => inferHostPlatform(selectedEnvironmentConnection?.environmentLabel ?? null),- [selectedEnvironmentConnection?.environmentLabel],+ () =>+ hostPlatformFromOs(hostOs) ??+ inferHostPlatform(selectedEnvironmentConnection?.environmentLabel ?? null),+ [hostOs, selectedEnvironmentConnection?.environmentLabel],);const terminalTheme = getMobileTerminalTheme(themeId, appearanceScheme);@@ -488,6 +491,7 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps){ kind: "send", key: "esc", label: "esc", data: "\u001b" },...modifierActions,{ kind: "send", key: "tab", label: "tab", data: "\t" },+ { kind: "paste", key: "paste", label: "paste" },{ kind: "clear", key: "clear", label: "clear" },{ kind: "send", key: "up", label: "↑", data: "\u001b[A" },{ kind: "send", key: "down", label: "↓", data: "\u001b[B" },@@ -693,13 +697,14 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)setHasMeasuredSurface(true);}, [routeEnvironmentId, routeThreadId, terminalId]);+ /** Resolves true once the pty accepted the write, false if it was skipped or rejected. */const writeInput = useCallback(- (data: string) => {+ async (data: string): Promise<boolean> => {if (!selectedThread || !isRunning) {- return;+ return false;}- void writeTerminal({+ const result = await writeTerminal({environmentId: selectedThread.environmentId,input: {threadId: selectedThread.id,@@ -707,27 +712,67 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)data,},});+ return result._tag === "Success";},[isRunning, selectedThread, terminalId, writeTerminal],);+ const pasteSessionRef = useRef<ReturnType<typeof createTerminalPasteSession> | null>(null);+ if (pasteSessionRef.current === null) {+ pasteSessionRef.current = createTerminalPasteSession();+ }+ const pasteSession = pasteSessionRef.current;++ // Drop delayed clipboard reads whenever the route or attached pty changes.+ useEffect(() => {+ pasteSession.reset(isRunning);+ return () => {+ pasteSession.reset(false);+ };+ }, [isRunning, pasteSession, terminal.lifecycleVersion, terminalKey]);++ const pasteFromClipboard = useCallback(async () => {+ await pasteSession.paste({+ readText: Clipboard.getStringAsync,+ write: writeInput,+ onReadError: (cause) => {+ console.error(new TerminalClipboardReadError({ terminalId, cause }));+ },+ });+ }, [pasteSession, terminalId, writeInput]);++ /** Sends a key through the armed toolbar modifier, if any, and disarms it. */+ const writeModifiedInput = useCallback(+ (data: string) => {+ if (pendingModifier === null) {+ void writeInput(data);+ return;+ }++ setPendingModifierState({ terminalId, value: null });+ const resolved = resolveModifiedTerminalInput({+ data,+ modifier: pendingModifier,+ hostPlatform,+ });+ if (resolved.kind === "paste") {+ void pasteFromClipboard();+ return;+ }+ void writeInput(resolved.data);+ },+ [hostPlatform, pasteFromClipboard, pendingModifier, terminalId, writeInput],+ );+const handleInput = useCallback((data: string) => {if (data.length === 0) {return;}- if (pendingModifier === "ctrl") {- setPendingModifierState({ terminalId, value: null });- writeInput(applyCtrlModifier(data));- } else if (pendingModifier === "meta") {- setPendingModifierState({ terminalId, value: null });- writeInput(`\u001b${data}`);- } else {- writeInput(data);- }+ writeModifiedInput(data);},- [pendingModifier, terminalId, writeInput],+ [writeModifiedInput],);const handleResize = useCallback(@@ -1021,16 +1066,15 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)return;}- setPendingModifierState({ terminalId, value: null });- if (pendingModifier === "ctrl") {- writeInput(applyCtrlModifier(action.data));- } else if (pendingModifier === "meta") {- writeInput(`\u001b${action.data}`);- } else {- writeInput(action.data);+ if (action.kind === "paste") {+ setPendingModifierState({ terminalId, value: null });+ void pasteFromClipboard();+ return;}++ writeModifiedInput(action.data);},- [handleClearTerminal, pendingModifier, terminalId, writeInput],+ [handleClearTerminal, pasteFromClipboard, terminalId, writeModifiedInput],);const handleDismissKeyboard = useCallback(() => {diff --git a/apps/mobile/src/features/terminal/terminalInput.test.ts b/apps/mobile/src/features/terminal/terminalInput.test.tsnew file mode 100644index 00000000000..aebc00649ce--- /dev/null+++ b/apps/mobile/src/features/terminal/terminalInput.test.ts@@ -0,0 +1,125 @@+import { describe, expect, it } from "vite-plus/test";++import {+ applyCtrlModifier,+ chunkTerminalWrite,+ encodeTerminalPaste,+ hostPlatformFromOs,+ resolveModifiedTerminalInput,+ TERMINAL_WRITE_MAX_LENGTH,+} from "./terminalInput";++const byte = (code: number) => String.fromCharCode(code);+const ESC = byte(0x1b);+const CTRL_C = byte(0x03);+const CTRL_V = byte(0x16);++describe("applyCtrlModifier", () => {+ it("maps letters to control bytes regardless of case", () => {+ expect(applyCtrlModifier("c")).toBe(CTRL_C);+ expect(applyCtrlModifier("C")).toBe(CTRL_C);+ expect(applyCtrlModifier("z")).toBe(byte(0x1a));+ });++ it("maps the punctuation control keys and leaves the rest untouched", () => {+ expect(applyCtrlModifier("[")).toBe(ESC);+ expect(applyCtrlModifier("?")).toBe(byte(0x7f));+ expect(applyCtrlModifier("1")).toBe("1");+ expect(applyCtrlModifier("")).toBe("");+ });+});++describe("resolveModifiedTerminalInput", () => {+ it("pastes on ctrl+v for windows, linux, and unknown hosts", () => {+ for (const hostPlatform of ["windows", "linux", "unknown"] as const) {+ expect(resolveModifiedTerminalInput({ data: "v", modifier: "ctrl", hostPlatform })).toEqual({+ kind: "paste",+ });+ expect(resolveModifiedTerminalInput({ data: "V", modifier: "ctrl", hostPlatform })).toEqual({+ kind: "paste",+ });+ }+ });++ it("keeps alt+v as a meta chord on non-mac hosts", () => {+ expect(+ resolveModifiedTerminalInput({ data: "v", modifier: "meta", hostPlatform: "windows" }),+ ).toEqual({ kind: "write", data: `${ESC}v` });+ });++ it("pastes on cmd+v and forwards raw ctrl+v on mac hosts", () => {+ expect(+ resolveModifiedTerminalInput({ data: "v", modifier: "meta", hostPlatform: "mac" }),+ ).toEqual({ kind: "paste" });+ expect(+ resolveModifiedTerminalInput({ data: "v", modifier: "ctrl", hostPlatform: "mac" }),+ ).toEqual({ kind: "write", data: CTRL_V });+ });++ it("still encodes every other modified key", () => {+ expect(+ resolveModifiedTerminalInput({ data: "c", modifier: "ctrl", hostPlatform: "windows" }),+ ).toEqual({ kind: "write", data: CTRL_C });+ expect(+ resolveModifiedTerminalInput({ data: "[A", modifier: "meta", hostPlatform: "linux" }),+ ).toEqual({ kind: "write", data: `${ESC}[A` });+ });+});++describe("encodeTerminalPaste", () => {+ it("passes single-line text through unchanged", () => {+ expect(encodeTerminalPaste("git switch -c fix/paste")).toBe("git switch -c fix/paste");+ expect(encodeTerminalPaste("")).toBe("");+ });++ it("turns LF and CRLF line breaks into a single carriage return each", () => {+ expect(encodeTerminalPaste("one\ntwo\r\nthree\n")).toBe("one\rtwo\rthree\r");+ });++ it("replaces unsafe control bytes with spaces but keeps tabs", () => {+ expect(encodeTerminalPaste(`a${byte(0)}b${ESC}c${byte(0x7f)}d\te`)).toBe("a b c d\te");+ });++ it("never lets a bracketed-paste end marker reach the shell", () => {+ expect(encodeTerminalPaste(`safe${ESC}[201~; rm -rf /\n`)).toBe("safe [201~; rm -rf /\r");+ });+});++describe("chunkTerminalWrite", () => {+ it("leaves writes within the wire limit whole", () => {+ expect(chunkTerminalWrite("")).toEqual([]);+ expect(chunkTerminalWrite("ls")).toEqual(["ls"]);+ expect(chunkTerminalWrite("x".repeat(TERMINAL_WRITE_MAX_LENGTH))).toHaveLength(1);+ });++ it("splits oversized writes so every chunk fits the contract", () => {+ const chunks = chunkTerminalWrite("y".repeat(TERMINAL_WRITE_MAX_LENGTH * 2 + 5));+ expect(chunks.map((chunk) => chunk.length)).toEqual([+ TERMINAL_WRITE_MAX_LENGTH,+ TERMINAL_WRITE_MAX_LENGTH,+ 5,+ ]);+ expect(chunks.join("")).toHaveLength(TERMINAL_WRITE_MAX_LENGTH * 2 + 5);+ });++ it("does not cut a surrogate pair in half at the boundary", () => {+ const data = `${"z".repeat(TERMINAL_WRITE_MAX_LENGTH - 1)}😀tail`;+ const chunks = chunkTerminalWrite(data);+ expect(chunks[0]).toHaveLength(TERMINAL_WRITE_MAX_LENGTH - 1);+ expect(chunks[1]).toBe("😀tail");+ expect(chunks.join("")).toBe(data);+ });+});++describe("hostPlatformFromOs", () => {+ it("maps the descriptor os onto the toolbar layout", () => {+ expect(hostPlatformFromOs("darwin")).toBe("mac");+ expect(hostPlatformFromOs("windows")).toBe("windows");+ expect(hostPlatformFromOs("linux")).toBe("linux");+ });++ it("defers to the caller when the os is unknown or not loaded yet", () => {+ expect(hostPlatformFromOs("unknown")).toBeNull();+ expect(hostPlatformFromOs(null)).toBeNull();+ });+});diff --git a/apps/mobile/src/features/terminal/terminalInput.ts b/apps/mobile/src/features/terminal/terminalInput.tsnew file mode 100644index 00000000000..d7cd60dd756--- /dev/null+++ b/apps/mobile/src/features/terminal/terminalInput.ts@@ -0,0 +1,108 @@+import type { ExecutionEnvironmentPlatformOs } from "@t3tools/contracts";++export type PendingModifier = "ctrl" | "meta";+export type HostPlatform = "mac" | "linux" | "windows" | "unknown";++/** Upper bound of `TerminalWriteInput.data`; longer writes are rejected by the server. */+export const TERMINAL_WRITE_MAX_LENGTH = 65_536;++export type ModifiedTerminalInput =+ | { readonly kind: "write"; readonly data: string }+ | { readonly kind: "paste" };++// C0 controls other than tab, LF, and CR, plus DEL.+// eslint-disable-next-line no-control-regex -- Pasted text must not carry raw terminal controls.+const UNSAFE_PASTE_BYTES = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g;++/**+ * Encodes a key pressed while the toolbar's one-shot ctrl modifier is armed+ * into the control byte a terminal expects.+ */+export function applyCtrlModifier(input: string): string {+ const firstCharacter = input[0];+ if (!firstCharacter) {+ return input;+ }++ const lowerCharacter = firstCharacter.toLowerCase();+ if (lowerCharacter >= "a" && lowerCharacter <= "z") {+ return String.fromCharCode(lowerCharacter.charCodeAt(0) - 96);+ }++ if (firstCharacter === "@") return "\u0000";+ if (firstCharacter === "[") return "\u001b";+ if (firstCharacter === "\\") return "\u001c";+ if (firstCharacter === "]") return "\u001d";+ if (firstCharacter === "^") return "\u001e";+ if (firstCharacter === "_") return "\u001f";+ if (firstCharacter === "?") return "\u007f";++ return input;+}++/**+ * Resolves what a keypress means once a toolbar modifier is armed. The host's+ * paste chord (cmd+v on a macOS host, ctrl+v elsewhere) pastes the device+ * clipboard instead of reaching the remote shell as a raw control byte, which+ * matches what the web terminal does with the same chord. Forwarding the byte+ * is never what a phone user means: PowerShell binds ctrl+v to paste from the+ * host machine's clipboard, so the shell inserts whatever the desktop last+ * copied rather than the text on the phone.+ */+export function resolveModifiedTerminalInput(input: {+ readonly data: string;+ readonly modifier: PendingModifier;+ readonly hostPlatform: HostPlatform;+}): ModifiedTerminalInput {+ const pasteModifier: PendingModifier = input.hostPlatform === "mac" ? "meta" : "ctrl";+ if (input.modifier === pasteModifier && input.data.toLowerCase() === "v") {+ return { kind: "paste" };+ }++ return {+ kind: "write",+ data: input.modifier === "ctrl" ? applyCtrlModifier(input.data) : `\u001b${input.data}`,+ };+}++/**+ * Encodes clipboard text for the remote pty the way the web terminal does when+ * bracketed paste is off: unsafe control bytes become spaces (which also+ * defuses an embedded bracketed-paste end marker, since its ESC goes too) and+ * line breaks become carriage returns, since a bare LF is Ctrl+J to a raw-mode+ * TUI. The native mobile surface does not expose DECSET 2004, so mobile never+ * wraps a paste in bracketed-paste markers.+ */+export function encodeTerminalPaste(text: string): string {+ return text.replace(UNSAFE_PASTE_BYTES, " ").replace(/\r\n|\n/g, "\r");+}++/**+ * Splits terminal input into writes the wire contract accepts, never cutting+ * through a surrogate pair so every chunk stays valid UTF-16.+ */+export function chunkTerminalWrite(data: string): ReadonlyArray<string> {+ const chunks: string[] = [];+ let start = 0;+ while (start < data.length) {+ let end = Math.min(start + TERMINAL_WRITE_MAX_LENGTH, data.length);+ const last = data.charCodeAt(end - 1);+ if (end < data.length && last >= 0xd800 && last <= 0xdbff) {+ end -= 1;+ }+ chunks.push(data.slice(start, end));+ start = end;+ }+ return chunks;+}++/**+ * Maps the OS reported by the environment descriptor onto the toolbar's host+ * layout. Returns null for "unknown" so callers can fall back to a weaker signal.+ */+export function hostPlatformFromOs(os: ExecutionEnvironmentPlatformOs | null): HostPlatform | null {+ if (os === "darwin") return "mac";+ if (os === "linux") return "linux";+ if (os === "windows") return "windows";+ return null;+}diff --git a/apps/mobile/src/features/terminal/terminalMenu.test.ts b/apps/mobile/src/features/terminal/terminalMenu.test.tsindex 96631227095..bbb16a08145 100644--- a/apps/mobile/src/features/terminal/terminalMenu.test.ts+++ b/apps/mobile/src/features/terminal/terminalMenu.test.ts@@ -61,6 +61,7 @@ function makeKnownSession(input: {hasRunningSubprocess: false,updatedAt: input.updatedAt ?? "2026-04-15T20:00:00.000Z",version: 1,+ lifecycleVersion: 1,},};}diff --git a/apps/mobile/src/features/terminal/terminalPaste.test.ts b/apps/mobile/src/features/terminal/terminalPaste.test.tsnew file mode 100644index 00000000000..ec9bd9d74d9--- /dev/null+++ b/apps/mobile/src/features/terminal/terminalPaste.test.ts@@ -0,0 +1,82 @@+import { describe, expect, it } from "vite-plus/test";++import { TERMINAL_WRITE_MAX_LENGTH } from "./terminalInput";+import { createTerminalPasteSession } from "./terminalPaste";++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((resolvePromise) => {+ resolve = resolvePromise;+ });+ return { promise, resolve };+}++describe("terminal paste session", () => {+ it("drops a clipboard read when the pty restarts in place", async () => {+ const session = createTerminalPasteSession();+ session.reset(true);+ const clipboardRead = deferred<string>();+ const writes: string[] = [];++ const paste = session.paste({+ readText: () => clipboardRead.promise,+ write: async (data) => {+ writes.push(data);+ return true;+ },+ onReadError: () => undefined,+ });++ session.reset(true);+ clipboardRead.resolve("stale");+ await paste;++ expect(writes).toEqual([]);+ });++ it("never overlaps writes from rapid paste requests", async () => {+ const session = createTerminalPasteSession();+ session.reset(true);++ const firstWrite = deferred<boolean>();+ const firstWriteStarted = deferred<void>();+ const writes: string[] = [];+ let activeWrites = 0;+ let maximumActiveWrites = 0;+ const write = async (data: string) => {+ writes.push(data);+ activeWrites += 1;+ maximumActiveWrites = Math.max(maximumActiveWrites, activeWrites);+ if (writes.length === 1) {+ firstWriteStarted.resolve();+ await firstWrite.promise;+ }+ activeWrites -= 1;+ return true;+ };++ const olderPaste = session.paste({+ readText: async () => "a".repeat(TERMINAL_WRITE_MAX_LENGTH + 1),+ write,+ onReadError: () => undefined,+ });+ await firstWriteStarted.promise;++ const newerPaste = session.paste({+ readText: async () => "newer",+ write,+ onReadError: () => undefined,+ });+ await Promise.resolve();++ expect(writes.map((chunk) => chunk.length)).toEqual([TERMINAL_WRITE_MAX_LENGTH]);+ expect(maximumActiveWrites).toBe(1);++ firstWrite.resolve(true);+ await Promise.all([olderPaste, newerPaste]);++ expect(writes.map((chunk) => chunk.length)).toEqual([TERMINAL_WRITE_MAX_LENGTH, 5]);+ expect(writes[1]).toBe("newer");+ expect(maximumActiveWrites).toBe(1);+ });+});diff --git a/apps/mobile/src/features/terminal/terminalPaste.ts b/apps/mobile/src/features/terminal/terminalPaste.tsnew file mode 100644index 00000000000..3368cd3a5bb--- /dev/null+++ b/apps/mobile/src/features/terminal/terminalPaste.ts@@ -0,0 +1,60 @@+import { chunkTerminalWrite, encodeTerminalPaste } from "./terminalInput";++interface TerminalPasteInput {+ readonly readText: () => Promise<string>;+ readonly write: (data: string) => Promise<boolean>;+ readonly onReadError: (cause: unknown) => void;+}++export interface TerminalPasteSession {+ readonly reset: (active: boolean) => void;+ readonly paste: (input: TerminalPasteInput) => Promise<void>;+}++/** Coordinates clipboard reads and writes for the currently attached pty. */+export function createTerminalPasteSession(): TerminalPasteSession {+ let liveTarget: object | null = null;+ let latestRequest = 0;+ let writeTail: Promise<void> = Promise.resolve();++ return {+ reset(active) {+ liveTarget = active ? {} : null;+ },++ async paste({ readText, write, onReadError }) {+ const target = liveTarget;+ if (target === null) {+ return;+ }+ const request = ++latestRequest;+ const isCurrent = () => liveTarget === target && latestRequest === request;++ let text: string;+ try {+ text = await readText();+ } catch (cause) {+ onReadError(cause);+ return;+ }++ if (!isCurrent()) {+ return;+ }++ const writePaste = async () => {+ for (const chunk of chunkTerminalWrite(encodeTerminalPaste(text))) {+ if (!isCurrent() || !(await write(chunk))) {+ return;+ }+ }+ };+ const queuedWrite = writeTail.then(writePaste, writePaste);+ writeTail = queuedWrite.then(+ () => undefined,+ () => undefined,+ );+ await queuedWrite;+ },+ };+}diff --git a/packages/client-runtime/src/state/terminalSession.test.ts b/packages/client-runtime/src/state/terminalSession.test.tsindex 85c57592d11..2f3e3777a96 100644--- a/packages/client-runtime/src/state/terminalSession.test.ts+++ b/packages/client-runtime/src/state/terminalSession.test.ts@@ -133,6 +133,44 @@ describe("terminal session reducers", () => {});});+ it("does not advance the lifecycle for the initial attach snapshot", () => {+ const snapshot = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {+ type: "snapshot",+ snapshot: BASE_SNAPSHOT,+ });++ expect(snapshot).toMatchObject({ status: "running", lifecycleVersion: 0 });+ });++ it("advances the lifecycle for a live started snapshot", () => {+ const initial = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {+ type: "snapshot",+ snapshot: BASE_SNAPSHOT,+ });+ const started = applyTerminalAttachStreamEvent(initial, {+ type: "snapshot",+ snapshot: { ...BASE_SNAPSHOT, pid: 456 },+ });++ expect(started).toMatchObject({ status: "running", lifecycleVersion: 1 });+ });++ it("advances the lifecycle when a running terminal restarts in place", () => {+ const snapshot = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {+ type: "snapshot",+ snapshot: BASE_SNAPSHOT,+ });+ const restarted = applyTerminalAttachStreamEvent(snapshot, {+ type: "restarted",+ threadId: TARGET.threadId,+ terminalId: TARGET.terminalId,+ snapshot: { ...BASE_SNAPSHOT, pid: 456 },+ });++ expect(snapshot).toMatchObject({ status: "running", lifecycleVersion: 0 });+ expect(restarted).toMatchObject({ status: "running", lifecycleVersion: 1 });+ });+it("reduces terminal metadata snapshots, upserts, and removals", () => {const initial = applyTerminalMetadataStreamEvent([], {type: "snapshot",diff --git a/packages/client-runtime/src/state/terminalSession.ts b/packages/client-runtime/src/state/terminalSession.tsindex ee444e36db4..b4508d38704 100644--- a/packages/client-runtime/src/state/terminalSession.ts+++ b/packages/client-runtime/src/state/terminalSession.ts@@ -15,6 +15,7 @@ export interface TerminalSessionState {readonly hasRunningSubprocess: boolean;readonly updatedAt: string | null;readonly version: number;+ readonly lifecycleVersion: number;}export interface TerminalBufferState {@@ -23,6 +24,7 @@ export interface TerminalBufferState {readonly error: string | null;readonly updatedAt: string | null;readonly version: number;+ readonly lifecycleVersion: number;}export interface KnownTerminalSessionTarget {@@ -50,6 +52,7 @@ export const EMPTY_TERMINAL_BUFFER_STATE = Object.freeze<TerminalBufferState>({error: null,updatedAt: null,version: 0,+ lifecycleVersion: 0,});export const EMPTY_TERMINAL_SESSION_STATE = Object.freeze<TerminalSessionState>({@@ -60,6 +63,7 @@ export const EMPTY_TERMINAL_SESSION_STATE = Object.freeze<TerminalSessionState>(hasRunningSubprocess: false,updatedAt: null,version: 0,+ lifecycleVersion: 0,});export const DEFAULT_MAX_TERMINAL_BUFFER_BYTES = 512 * 1024;@@ -98,6 +102,7 @@ export function terminalBufferStateFromSnapshot(error: null,updatedAt: snapshot.updatedAt,version: 1,+ lifecycleVersion: 0,};}@@ -119,6 +124,7 @@ export function combineTerminalSessionState(hasRunningSubprocess: summary?.hasRunningSubprocess ?? false,updatedAt: latestTimestamp(summary?.updatedAt ?? null, buffer.updatedAt),version: buffer.version,+ lifecycleVersion: buffer.lifecycleVersion,};}@@ -129,8 +135,16 @@ export function applyTerminalAttachStreamEvent(): TerminalBufferState {switch (event.type) {case "snapshot":+ return {+ ...terminalBufferStateFromSnapshot(event.snapshot, maxBufferBytes),+ lifecycleVersion:+ current.version === 0 ? current.lifecycleVersion : current.lifecycleVersion + 1,+ };case "restarted":- return terminalBufferStateFromSnapshot(event.snapshot, maxBufferBytes);+ return {+ ...terminalBufferStateFromSnapshot(event.snapshot, maxBufferBytes),+ lifecycleVersion: current.lifecycleVersion + 1,+ };case "output":return {...current,