The best way to control Claude Code, Codex and more from any computer or phone

main
ts 249 lines 7.25 KB
Raw
1 import type {
2 EnvironmentId,
3 TerminalAttachStreamEvent,
4 TerminalMetadataStreamEvent,
5 TerminalSessionSnapshot,
6 TerminalSummary,
7 ThreadId,
8 } from "@t3tools/contracts";
9 import { DEFAULT_MAX_TERMINAL_BUFFER_BYTES } from "@t3tools/contracts";
10 import {
11 appendOutput,
12 clearOutput,
13 EMPTY_TERMINAL_OUTPUT_STATE,
14 resetOutput,
15 type TerminalOutputState,
16 } from "./terminalOutput.ts";
17
18 export {
19 INITIAL_TERMINAL_OUTPUT_CURSOR,
20 readTerminalOutputUpdate,
21 terminalOutputReplay,
22 terminalOutputText,
23 type TerminalOutputCursor,
24 type TerminalOutputState,
25 type TerminalOutputUpdate,
26 } from "./terminalOutput.ts";
27 export { DEFAULT_MAX_TERMINAL_BUFFER_BYTES } from "@t3tools/contracts";
28
29 /** The PTY grid every renderer of a shared terminal draws. */
30 export interface TerminalGrid {
31 readonly cols: number;
32 readonly rows: number;
33 }
34
35 export interface TerminalSessionState {
36 readonly summary: TerminalSummary | null;
37 readonly output: TerminalOutputState;
38 /** Null when the server predates shared terminal geometry. */
39 readonly grid: TerminalGrid | null;
40 readonly status: TerminalSessionSnapshot["status"] | "closed";
41 readonly error: string | null;
42 readonly hasRunningSubprocess: boolean;
43 readonly updatedAt: string | null;
44 readonly version: number;
45 readonly lifecycleVersion: number;
46 }
47
48 export interface TerminalBufferState {
49 readonly output: TerminalOutputState;
50 readonly grid: TerminalGrid | null;
51 readonly status: TerminalSessionSnapshot["status"] | "closed";
52 readonly error: string | null;
53 readonly updatedAt: string | null;
54 readonly version: number;
55 readonly lifecycleVersion: number;
56 }
57
58 export interface KnownTerminalSessionTarget {
59 readonly environmentId: EnvironmentId;
60 readonly threadId: ThreadId;
61 readonly terminalId: string;
62 }
63
64 export interface KnownTerminalSession {
65 readonly target: KnownTerminalSessionTarget;
66 readonly state: TerminalSessionState;
67 }
68
69 export function selectRunningSubprocessTerminalIds(
70 sessions: ReadonlyArray<KnownTerminalSession>,
71 ): ReadonlyArray<string> {
72 return sessions
73 .filter((session) => session.state.hasRunningSubprocess)
74 .map((session) => session.target.terminalId);
75 }
76
77 export const EMPTY_TERMINAL_BUFFER_STATE = Object.freeze<TerminalBufferState>({
78 output: EMPTY_TERMINAL_OUTPUT_STATE,
79 grid: null,
80 status: "closed",
81 error: null,
82 updatedAt: null,
83 version: 0,
84 lifecycleVersion: 0,
85 });
86
87 export const EMPTY_TERMINAL_SESSION_STATE = Object.freeze<TerminalSessionState>({
88 summary: null,
89 output: EMPTY_TERMINAL_OUTPUT_STATE,
90 grid: null,
91 status: "closed",
92 error: null,
93 hasRunningSubprocess: false,
94 updatedAt: null,
95 version: 0,
96 lifecycleVersion: 0,
97 });
98
99 let terminalAttachGeneration = 0;
100
101 /** A reinstalled attach stream must not reuse an old renderer's output cursor. */
102 export function nextTerminalAttachSeedState(): TerminalBufferState {
103 return {
104 ...EMPTY_TERMINAL_BUFFER_STATE,
105 output: {
106 ...EMPTY_TERMINAL_OUTPUT_STATE,
107 generation: ++terminalAttachGeneration,
108 },
109 };
110 }
111
112 function terminalBufferStateFromSnapshot(
113 snapshot: TerminalSessionSnapshot,
114 maxBufferBytes: number,
115 current: TerminalBufferState = EMPTY_TERMINAL_BUFFER_STATE,
116 ): TerminalBufferState {
117 return {
118 output: resetOutput(current.output, snapshot.history, maxBufferBytes),
119 grid: nextGrid(current.grid, snapshot),
120 status: snapshot.status,
121 error: snapshot.error ?? null,
122 updatedAt: snapshot.updatedAt,
123 version: current.version + 1,
124 lifecycleVersion: current.lifecycleVersion,
125 };
126 }
127
128 function nextGrid(
129 current: TerminalGrid | null,
130 source: { readonly cols?: number | undefined; readonly rows?: number | undefined },
131 ): TerminalGrid | null {
132 if (source.cols === undefined || source.rows === undefined) return current;
133 return current?.cols === source.cols && current.rows === source.rows
134 ? current
135 : { cols: source.cols, rows: source.rows };
136 }
137
138 function latestTimestamp(left: string | null, right: string | null): string | null {
139 if (left === null) return right;
140 if (right === null) return left;
141 return Date.parse(left) >= Date.parse(right) ? left : right;
142 }
143
144 export function combineTerminalSessionState(
145 summary: TerminalSummary | null,
146 buffer: TerminalBufferState,
147 ): TerminalSessionState {
148 return {
149 summary,
150 output: buffer.output,
151 grid: buffer.grid,
152 status: buffer.version > 0 ? buffer.status : (summary?.status ?? buffer.status),
153 error: buffer.error,
154 hasRunningSubprocess: summary?.hasRunningSubprocess ?? false,
155 updatedAt: latestTimestamp(summary?.updatedAt ?? null, buffer.updatedAt),
156 version: buffer.version,
157 lifecycleVersion: buffer.lifecycleVersion,
158 };
159 }
160
161 export function applyTerminalAttachStreamEvent(
162 current: TerminalBufferState,
163 event: TerminalAttachStreamEvent,
164 maxBufferBytes = DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
165 ): TerminalBufferState {
166 switch (event.type) {
167 case "snapshot": {
168 if (current.version === 0) {
169 return terminalBufferStateFromSnapshot(event.snapshot, maxBufferBytes, current);
170 }
171 // A later snapshot is a new server attachment, as after a socket reconnect. It starts a
172 // new generation because viewers replay their measured grid once per generation.
173 const reattached = {
174 ...current,
175 output: { ...current.output, generation: ++terminalAttachGeneration },
176 };
177 return {
178 ...terminalBufferStateFromSnapshot(event.snapshot, maxBufferBytes, reattached),
179 lifecycleVersion: current.lifecycleVersion + 1,
180 };
181 }
182 case "restarted":
183 return {
184 ...terminalBufferStateFromSnapshot(event.snapshot, maxBufferBytes, current),
185 lifecycleVersion: current.lifecycleVersion + 1,
186 };
187 case "output":
188 return {
189 ...current,
190 output: appendOutput(current.output, event.data, maxBufferBytes),
191 status: current.status === "closed" ? "running" : current.status,
192 error: null,
193 version: current.version + 1,
194 };
195 case "cleared":
196 return {
197 ...current,
198 output: clearOutput(current.output, maxBufferBytes),
199 error: null,
200 version: current.version + 1,
201 };
202 case "exited":
203 return {
204 ...current,
205 status: "exited",
206 error: null,
207 version: current.version + 1,
208 };
209 case "closed":
210 return {
211 ...current,
212 status: "closed",
213 error: null,
214 version: current.version + 1,
215 };
216 case "error":
217 return {
218 ...current,
219 status: "error",
220 error: event.message,
221 version: current.version + 1,
222 };
223 case "activity": {
224 const grid = nextGrid(current.grid, event);
225 return grid === current.grid ? current : { ...current, grid };
226 }
227 }
228 }
229
230 export function applyTerminalMetadataStreamEvent(
231 current: ReadonlyArray<TerminalSummary>,
232 event: TerminalMetadataStreamEvent,
233 ): ReadonlyArray<TerminalSummary> {
234 if (event.type === "snapshot") {
235 return event.terminals;
236 }
237 if (event.type === "remove") {
238 return current.filter(
239 (terminal) =>
240 terminal.threadId !== event.threadId || terminal.terminalId !== event.terminalId,
241 );
242 }
243 const next = current.filter(
244 (terminal) =>
245 terminal.threadId !== event.terminal.threadId ||
246 terminal.terminalId !== event.terminal.terminalId,
247 );
248 return [...next, event.terminal];
249 }