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