@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 474 lines 16.9 KB
Raw
1 import {
2 DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
3 type EnvironmentId,
4 type TerminalAttachInput,
5 type TerminalCloseInput,
6 type TerminalOpenInput,
7 type TerminalResizeInput,
8 type TerminalSummary,
9 type TerminalWriteInput,
10 type ThreadId,
11 WS_METHODS,
12 } from "@t3tools/contracts";
13 import * as Effect from "effect/Effect";
14 import * as Stream from "effect/Stream";
15 import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
16
17 import {
18 type AtomCommand,
19 createAtomCommandScheduler,
20 createEnvironmentRpcCommand,
21 createEnvironmentSubscriptionAtomFamily,
22 isAtomCommandInterrupted,
23 runAtomCommand,
24 } from "./runtime.ts";
25 import type { EnvironmentRegistry } from "../connection/registry.ts";
26 import { subscribe, subscribeDynamic, type EnvironmentRpcInput } from "../rpc/client.ts";
27 import {
28 applyTerminalAttachStreamEvent,
29 applyTerminalMetadataStreamEvent,
30 EMPTY_TERMINAL_BUFFER_STATE,
31 nextTerminalAttachSeedState,
32 type TerminalBufferState,
33 } from "./terminalSession.ts";
34 import { terminalOutputText } from "./terminalOutput.ts";
35
36 interface TerminalMetadataFeed {
37 readonly terminals: ReadonlyArray<TerminalSummary>;
38 readonly snapshotId: string | symbol;
39 }
40
41 export function createTerminalEnvironmentAtoms<R, E>(
42 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
43 ) {
44 const lifecycleScheduler = createAtomCommandScheduler();
45 const resizeScheduler = createAtomCommandScheduler();
46 const terminalThreadKey = ({
47 environmentId,
48 input,
49 }: {
50 readonly environmentId: string;
51 readonly input: { readonly threadId: string; readonly terminalId?: string | undefined };
52 }) => JSON.stringify([environmentId, input.threadId]);
53 const terminalSessionKey = ({
54 environmentId,
55 input,
56 }: {
57 readonly environmentId: string;
58 readonly input: { readonly threadId: string; readonly terminalId?: string | undefined };
59 }) => JSON.stringify([environmentId, input.threadId, input.terminalId ?? null]);
60 const lifecycleConcurrency = { mode: "serial" as const, key: terminalThreadKey };
61 const metadataFeed = createEnvironmentSubscriptionAtomFamily(runtime, {
62 label: "environment-data:terminal:metadata",
63 subscribe: (_input: null) =>
64 subscribe(WS_METHODS.subscribeTerminalMetadata, {}).pipe(
65 Stream.scan(
66 (): TerminalMetadataFeed => ({ terminals: [], snapshotId: Symbol() }),
67 (feed, event): TerminalMetadataFeed => ({
68 terminals: applyTerminalMetadataStreamEvent(feed.terminals, event),
69 snapshotId: event.type === "snapshot" ? (event.managerId ?? Symbol()) : feed.snapshotId,
70 }),
71 ),
72 // The scan seed is not an authoritative empty server snapshot.
73 Stream.drop(1),
74 ),
75 });
76 const terminalMetadataSummaries = Atom.family((feed: ReturnType<typeof metadataFeed>) =>
77 Atom.mapResult(feed, ({ terminals }) => terminals),
78 );
79 const atoms = {
80 observe: createEnvironmentSubscriptionAtomFamily(runtime, {
81 label: "environment-data:terminal:observe",
82 subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.terminalObserve>) =>
83 Stream.suspend(() =>
84 subscribe(WS_METHODS.terminalObserve, input).pipe(
85 Stream.scan(nextTerminalAttachSeedState, applyTerminalAttachStreamEvent),
86 ),
87 ),
88 }),
89 attach: createEnvironmentSubscriptionAtomFamily(runtime, {
90 label: "environment-data:terminal:attach",
91 // The server sizes the PTY to every attached viewer, so a closed view must detach now.
92 idleTtlMs: 0,
93 subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.terminalAttach>) => {
94 // Retry an unanswered first attach unchanged so it can still open the shell.
95 let replied = false;
96 return subscribeDynamic(WS_METHODS.terminalAttach, () =>
97 Effect.sync(() => ({
98 ...input,
99 ...(replied ? { resume: true } : {}),
100 maxHistoryBytes: DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
101 })),
102 ).pipe(
103 Stream.onFirst(() =>
104 Effect.sync(() => {
105 replied = true;
106 }),
107 ),
108 Stream.scan(nextTerminalAttachSeedState, applyTerminalAttachStreamEvent),
109 );
110 },
111 }),
112 metadataFeed,
113 metadata: (target: { readonly environmentId: EnvironmentId; readonly input: null }) =>
114 terminalMetadataSummaries(metadataFeed(target)),
115 open: createEnvironmentRpcCommand(runtime, {
116 label: "environment-data:terminal:open",
117 tag: WS_METHODS.terminalOpen,
118 scheduler: lifecycleScheduler,
119 concurrency: lifecycleConcurrency,
120 }),
121 write: createEnvironmentRpcCommand(runtime, {
122 label: "environment-data:terminal:write",
123 tag: WS_METHODS.terminalWrite,
124 }),
125 resize: createEnvironmentRpcCommand(runtime, {
126 label: "environment-data:terminal:resize",
127 tag: WS_METHODS.terminalResize,
128 scheduler: resizeScheduler,
129 concurrency: { mode: "latest", key: terminalSessionKey },
130 }),
131 clear: createEnvironmentRpcCommand(runtime, {
132 label: "environment-data:terminal:clear",
133 tag: WS_METHODS.terminalClear,
134 scheduler: lifecycleScheduler,
135 concurrency: lifecycleConcurrency,
136 }),
137 close: createEnvironmentRpcCommand(runtime, {
138 label: "environment-data:terminal:close",
139 tag: WS_METHODS.terminalClose,
140 scheduler: lifecycleScheduler,
141 concurrency: lifecycleConcurrency,
142 }),
143 };
144 return {
145 ...atoms,
146 createSession: (options: TerminalSessionOptions) => createTerminalSession(atoms, options),
147 };
148 }
149
150 export interface TerminalLifecycleState {
151 readonly wasRunning: boolean;
152 /** The user has seen this terminal without operate permission. */
153 readonly observed: boolean;
154 readonly reopened: boolean;
155 }
156
157 export const INITIAL_TERMINAL_LIFECYCLE: TerminalLifecycleState = {
158 wasRunning: false,
159 observed: false,
160 reopened: false,
161 };
162
163 export type TerminalLifecycleEvent =
164 /** A viewer without operate permission is following this terminal. */
165 | { readonly type: "observed" }
166 | { readonly type: "detached"; readonly canOperate: boolean }
167 | {
168 readonly type: "status";
169 readonly status: TerminalBufferState["status"];
170 readonly version: number;
171 }
172 | { readonly type: "reopen-failed" };
173
174 export type TerminalLifecycleCommand = "exit" | "reopen" | null;
175
176 export function transitionTerminalLifecycle(
177 state: TerminalLifecycleState,
178 event: TerminalLifecycleEvent,
179 ): { readonly state: TerminalLifecycleState; readonly command: TerminalLifecycleCommand } {
180 switch (event.type) {
181 case "observed":
182 return { state: { ...state, observed: true }, command: null };
183 case "detached":
184 return {
185 state: {
186 ...state,
187 // Losing operate while the shell runs leaves the viewer reading its history.
188 observed: state.observed || (!event.canOperate && state.wasRunning),
189 wasRunning: false,
190 },
191 command: null,
192 };
193 case "reopen-failed":
194 return { state: { ...state, reopened: false }, command: null };
195 case "status": {
196 if (event.version === 0) return { state, command: null };
197 if (event.status === "running" || event.status === "starting") {
198 return { state: { ...state, wasRunning: true, reopened: false }, command: null };
199 }
200 if (event.status !== "closed" && event.status !== "exited") return { state, command: null };
201 if (state.wasRunning) {
202 return { state: { ...state, wasRunning: false, reopened: true }, command: "exit" };
203 }
204 // An explicit visit can reopen a cached ended session. Granting a viewer
205 // operate permission must leave the history they were reading intact.
206 if (state.observed || state.reopened) return { state, command: null };
207 return { state: { ...state, reopened: true }, command: "reopen" };
208 }
209 }
210 }
211
212 export interface TerminalGridSize {
213 readonly cols: number;
214 readonly rows: number;
215 }
216
217 export type TerminalSessionMode =
218 | { readonly kind: "observing" }
219 | { readonly kind: "attached"; readonly input: TerminalAttachInput };
220
221 type EnvironmentCommand<Input> = AtomCommand<
222 { readonly environmentId: EnvironmentId; readonly input: Input },
223 unknown,
224 unknown
225 >;
226
227 export interface TerminalSessionAtoms {
228 readonly attach: (target: {
229 readonly environmentId: EnvironmentId;
230 readonly input: TerminalAttachInput;
231 }) => Atom.Atom<AsyncResult.AsyncResult<TerminalBufferState, unknown>>;
232 readonly observe: (target: {
233 readonly environmentId: EnvironmentId;
234 readonly input: { readonly threadId: ThreadId; readonly terminalId: string };
235 }) => Atom.Atom<AsyncResult.AsyncResult<TerminalBufferState, unknown>>;
236 readonly open: EnvironmentCommand<TerminalOpenInput>;
237 readonly resize: EnvironmentCommand<TerminalResizeInput>;
238 readonly write: EnvironmentCommand<TerminalWriteInput>;
239 readonly close: EnvironmentCommand<TerminalCloseInput>;
240 }
241
242 export interface TerminalSessionOptions {
243 readonly target: {
244 readonly environmentId: EnvironmentId;
245 readonly threadId: ThreadId;
246 readonly terminalId: string;
247 };
248 readonly gridSize: TerminalGridSize;
249 /** Written once, after the first attachment snapshot lands and the shell has the measured grid. */
250 readonly initialInput?: string | undefined;
251 /** Read right before every command, so revoking operate stops them at once. */
252 readonly canOperate: () => boolean;
253 /** The shell ended while attached; the store has already closed it. */
254 readonly onExit: () => void;
255 /** Fires when the shell starts or stops accepting input, and on every restart. */
256 readonly onLiveChange?: (live: boolean) => void;
257 readonly debugLog?: (message: string, data: Record<string, unknown>) => void;
258 }
259
260 export interface TerminalSession {
261 /**
262 * Mount while the session follows a terminal: attached to operate it, or
263 * observing it read-only. `null` follows nothing. A session keeps the first
264 * attach input it is given; a different input needs a new session.
265 */
266 readonly driver: (mode: TerminalSessionMode | null) => Atom.Atom<void>;
267 /** The surface measured a new grid; the shell is resized while it runs. */
268 readonly reportGridSize: (size: TerminalGridSize) => void;
269 }
270
271 /**
272 * Owns one shown terminal's lifecycle: it reopens an ended shell on an explicit
273 * visit, closes and reports a shell that exits while attached, replays the
274 * measured grid whenever the server starts a new output generation, and writes
275 * the launch's initial input once that grid has reached the shell.
276 */
277 export function createTerminalSession(
278 atoms: TerminalSessionAtoms,
279 options: TerminalSessionOptions,
280 ): TerminalSession {
281 const { environmentId, threadId, terminalId } = options.target;
282 let lifecycle = INITIAL_TERMINAL_LIFECYCLE;
283 let gridSize = options.gridSize;
284 // The seeded grid is a cache or default guess; launch input waits for the surface's own measurement.
285 let gridMeasured = false;
286 let generation: number | null = null;
287 let liveLifecycleVersion: number | null = null;
288 let initialInputPending = Boolean(options.initialInput);
289 let lastStatus: TerminalBufferState["status"] | null = null;
290 let loggedFirstOutput = false;
291 let commandRegistry: AtomRegistry.AtomRegistry | null = null;
292 // Only a successful resize of the current measured grid may release initial input.
293 let shellResized: ReturnType<typeof runAtomCommand> | null = null;
294
295 const sendResize = (retry = false) => {
296 const registry = commandRegistry;
297 if (generation === null || registry === null || !options.canOperate()) return;
298 const resized = runAtomCommand(registry, atoms.resize, {
299 environmentId,
300 input: { threadId, terminalId, cols: gridSize.cols, rows: gridSize.rows },
301 });
302 shellResized = resized;
303 void resized.then((result) => {
304 // Only a new grid or generation sends again, so retry a failure once, unless a newer
305 // resize already replaced this one.
306 if (
307 !retry &&
308 resized === shellResized &&
309 result._tag === "Failure" &&
310 !isAtomCommandInterrupted(result)
311 ) {
312 sendResize(true);
313 return;
314 }
315 const data = options.initialInput;
316 if (
317 result._tag !== "Success" ||
318 resized !== shellResized ||
319 !gridMeasured ||
320 generation === null ||
321 !initialInputPending ||
322 !data ||
323 !options.canOperate()
324 )
325 return;
326 initialInputPending = false;
327 void runAtomCommand(registry, atoms.write, {
328 environmentId,
329 input: { threadId, terminalId, data },
330 });
331 });
332 };
333
334 const setLive = (next: number | null) => {
335 if (next === liveLifecycleVersion) return;
336 liveLifecycleVersion = next;
337 options.onLiveChange?.(next !== null);
338 };
339
340 const apply = (
341 event: TerminalLifecycleEvent,
342 registry: AtomRegistry.AtomRegistry,
343 input: TerminalAttachInput,
344 ) => {
345 const step = transitionTerminalLifecycle(lifecycle, event);
346 lifecycle = step.state;
347 if (step.command === "exit") {
348 if (!options.canOperate()) return;
349 void runAtomCommand(registry, atoms.close, {
350 environmentId,
351 input: { threadId, terminalId },
352 });
353 options.onExit();
354 return;
355 }
356 if (step.command !== "reopen") return;
357 const reopen = async () => {
358 if (input.cwd === undefined || !options.canOperate()) return false;
359 const result = await runAtomCommand(registry, atoms.open, {
360 environmentId,
361 input: {
362 threadId,
363 terminalId,
364 cwd: input.cwd,
365 worktreePath: input.worktreePath,
366 cols: input.cols,
367 rows: input.rows,
368 ...(input.env ? { env: input.env } : {}),
369 },
370 });
371 return result._tag === "Success";
372 };
373 void reopen().then((succeeded) => {
374 if (!succeeded)
375 lifecycle = transitionTerminalLifecycle(lifecycle, { type: "reopen-failed" }).state;
376 });
377 };
378
379 const onAttachment = (
380 registry: AtomRegistry.AtomRegistry,
381 input: TerminalAttachInput,
382 result: AsyncResult.AsyncResult<TerminalBufferState, unknown>,
383 ) => {
384 commandRegistry = registry;
385 const buffer = AsyncResult.getOrElse(result, () => EMPTY_TERMINAL_BUFFER_STATE);
386 const status = result._tag === "Failure" ? "error" : buffer.status;
387 if (status !== lastStatus) {
388 lastStatus = status;
389 options.debugLog?.("session:status", {
390 terminalId,
391 status,
392 error: buffer.error,
393 version: buffer.version,
394 });
395 }
396 if (!loggedFirstOutput && options.debugLog) {
397 const text = terminalOutputText(buffer.output);
398 if (text.length > 0) {
399 loggedFirstOutput = true;
400 options.debugLog("session:first-nonempty-buffer", {
401 terminalId,
402 length: text.length,
403 preview: text.slice(0, 160),
404 });
405 }
406 }
407
408 setLive(status === "running" || status === "starting" ? buffer.lifecycleVersion : null);
409
410 // Resize before the initial input so a launched command starts at the measured grid.
411 const nextGeneration =
412 buffer.version > 0 && status === "running" ? buffer.output.generation : null;
413 if (nextGeneration !== generation) {
414 generation = nextGeneration;
415 shellResized = null;
416 sendResize();
417 }
418
419 apply({ type: "status", status, version: buffer.version }, registry, input);
420 };
421
422 const label = `terminal-session:${environmentId}:${threadId}:${terminalId}`;
423 const idle = Atom.make<void>(undefined);
424 // Viewing read-only counts as observed before the first snapshot lands, so a
425 // grant that arrives early still leaves the ended shell's history alone.
426 const observing = Atom.make((get) => {
427 // `subscribe`, not `get`: a rebuild would resubscribe on every output chunk.
428 get.subscribe(
429 atoms.observe({ environmentId, input: { threadId, terminalId } }),
430 () => {
431 if (options.canOperate()) return;
432 lifecycle = transitionTerminalLifecycle(lifecycle, { type: "observed" }).state;
433 },
434 { immediate: true },
435 );
436 }).pipe(Atom.withLabel(`${label}:observing`));
437 const makeAttached = (input: TerminalAttachInput) =>
438 Atom.make((get) => {
439 const registry = get.registry;
440 get.addFinalizer(() => {
441 generation = null;
442 shellResized = null;
443 lastStatus = null;
444 setLive(null);
445 lifecycle = transitionTerminalLifecycle(lifecycle, {
446 type: "detached",
447 canOperate: options.canOperate(),
448 }).state;
449 });
450 get.subscribe(
451 atoms.attach({ environmentId, input }),
452 (result) => onAttachment(registry, input, result),
453 { immediate: true },
454 );
455 }).pipe(Atom.withLabel(`${label}:attached`));
456 let attached: Atom.Atom<void> | null = null;
457
458 return {
459 driver: (mode) => {
460 if (mode === null) return idle;
461 if (mode.kind === "observing") return observing;
462 attached ??= makeAttached(mode.input);
463 return attached;
464 },
465 reportGridSize: (size) => {
466 if (gridMeasured && size.cols === gridSize.cols && size.rows === gridSize.rows) return;
467 gridMeasured = true;
468 gridSize = size;
469 sendResize();
470 },
471 };
472 }
473
474 export * from "./terminalSession.ts";