Skip to content

Commit abeb75f

Browse files
refactor(client): terminal sessions keep one driver per mode
A terminal session now holds one observing driver and one attached driver, instead of a JSON-keyed atom family over every mode it was ever given plus a guard against a replaced attachment's late release. Mobile mounts one session per terminal and its attach input is fixed for that mount, so neither case can happen. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 3a1b3a7 commit abeb75f

2 files changed

Lines changed: 33 additions & 43 deletions

File tree

‎packages/client-runtime/src/state/terminal.test.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -231,15 +231,15 @@ it("reopens instead of closing a shell that ended while detached", () => {
231231
expect(of("open")).toHaveLength(1);
232232
});
233233

234-
it("keeps a replaced attachment's late release from resetting the new one", () => {
235-
const { attached, flush, emit, mount, of, exits } = setup();
234+
it("keeps one attached driver, so a remount before release keeps its state", () => {
235+
const { session, attached, flush, emit, mount, of, exits } = setup();
236+
const driver = session.driver(attached);
237+
expect(session.driver({ ...attached })).toBe(driver);
236238
const unmountFirst = mount(attached);
237239
emit({ status: "running", version: 1 });
238-
mount({
239-
kind: "attached",
240-
input: { threadId, terminalId: "term-1", cwd: "/repo/worktree", cols: 80, rows: 24 },
241-
});
240+
// A brief disconnect unmounts and remounts the driver before its release runs.
242241
unmountFirst();
242+
mount(attached);
243243
flush();
244244
emit({ status: "exited", version: 2 });
245245
expect(of("close")).toHaveLength(1);

‎packages/client-runtime/src/state/terminal.ts‎

Lines changed: 27 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,8 @@ export interface TerminalSessionOptions {
247247
export interface TerminalSession {
248248
/**
249249
* Mount while the session follows a terminal: attached to operate it, or
250-
* observing it read-only. `null` follows nothing.
250+
* observing it read-only. `null` follows nothing. A session keeps the first
251+
* attach input it is given; a different input needs a new session.
251252
*/
252253
readonly driver: (mode: TerminalSessionMode | null) => Atom.Atom<void>;
253254
/** The surface measured a new grid; the shell is resized while it runs. */
@@ -273,9 +274,6 @@ export function createTerminalSession(
273274
let lastStatus: TerminalBufferState["status"] | null = null;
274275
let loggedFirstOutput = false;
275276
let resizeRegistry: AtomRegistry.AtomRegistry | null = null;
276-
// Driver atoms are released on a scheduled task, so an attachment replaced by
277-
// another one must not reset state the newer attachment already set.
278-
let currentAttachment: object | null = null;
279277

280278
const sendResize = () => {
281279
if (generation === null || resizeRegistry === null || !options.canOperate()) return;
@@ -294,7 +292,7 @@ export function createTerminalSession(
294292
const apply = (
295293
event: TerminalLifecycleEvent,
296294
registry: AtomRegistry.AtomRegistry,
297-
input: TerminalAttachInput | null,
295+
input: TerminalAttachInput,
298296
) => {
299297
const step = transitionTerminalLifecycle(lifecycle, event);
300298
lifecycle = step.state;
@@ -309,7 +307,7 @@ export function createTerminalSession(
309307
}
310308
if (step.command !== "reopen") return;
311309
const reopen = async () => {
312-
if (input?.cwd === undefined || !options.canOperate()) return false;
310+
if (input.cwd === undefined || !options.canOperate()) return false;
313311
const result = await runAtomCommand(registry, atoms.open, {
314312
environmentId,
315313
input: {
@@ -380,31 +378,25 @@ export function createTerminalSession(
380378
apply({ type: "status", status, version: buffer.version }, registry, input);
381379
};
382380

381+
const label = `terminal-session:${environmentId}:${threadId}:${terminalId}`;
383382
const idle = Atom.make<void>(undefined);
384-
const modes = new Map<string, TerminalSessionMode>();
385-
const drivers = Atom.family((key: string) => {
386-
const mode = modes.get(key)!;
387-
return Atom.make((get) => {
383+
// Viewing read-only counts as observed before the first snapshot lands, so a
384+
// grant that arrives early still leaves the ended shell's history alone.
385+
const observing = Atom.make((get) => {
386+
// `subscribe`, not `get`: a rebuild would resubscribe on every output chunk.
387+
get.subscribe(
388+
atoms.observe({ environmentId, input: { threadId, terminalId } }),
389+
() => {
390+
if (options.canOperate()) return;
391+
lifecycle = transitionTerminalLifecycle(lifecycle, { type: "observed" }).state;
392+
},
393+
{ immediate: true },
394+
);
395+
}).pipe(Atom.withLabel(`${label}:observing`));
396+
const makeAttached = (input: TerminalAttachInput) =>
397+
Atom.make((get) => {
388398
const registry = get.registry;
389-
// `subscribe`, not `get`: a rebuild would resubscribe on every output chunk.
390-
if (mode.kind === "observing") {
391-
// Viewing read-only counts as observed before the first snapshot lands, so
392-
// a grant that arrives early still leaves the ended shell's history alone.
393-
get.subscribe(
394-
atoms.observe({ environmentId, input: { threadId, terminalId } }),
395-
() => {
396-
if (options.canOperate()) return;
397-
lifecycle = transitionTerminalLifecycle(lifecycle, { type: "observed" }).state;
398-
},
399-
{ immediate: true },
400-
);
401-
return;
402-
}
403-
const attachment = {};
404-
currentAttachment = attachment;
405399
get.addFinalizer(() => {
406-
if (currentAttachment !== attachment) return;
407-
currentAttachment = null;
408400
generation = null;
409401
lastStatus = null;
410402
setLive(null);
@@ -414,21 +406,19 @@ export function createTerminalSession(
414406
}).state;
415407
});
416408
get.subscribe(
417-
atoms.attach({ environmentId, input: mode.input }),
418-
(result) => onAttachment(registry, mode.input, result),
409+
atoms.attach({ environmentId, input }),
410+
(result) => onAttachment(registry, input, result),
419411
{ immediate: true },
420412
);
421-
}).pipe(
422-
Atom.withLabel(`terminal-session:${environmentId}:${threadId}:${terminalId}:${mode.kind}`),
423-
);
424-
});
413+
}).pipe(Atom.withLabel(`${label}:attached`));
414+
let attached: Atom.Atom<void> | null = null;
425415

426416
return {
427417
driver: (mode) => {
428418
if (mode === null) return idle;
429-
const key = JSON.stringify(mode);
430-
if (!modes.has(key)) modes.set(key, mode);
431-
return drivers(key);
419+
if (mode.kind === "observing") return observing;
420+
attached ??= makeAttached(mode.input);
421+
return attached;
432422
},
433423
reportGridSize: (size) => {
434424
if (size.cols === gridSize.cols && size.rows === gridSize.rows) return;

0 commit comments

Comments
 (0)