@devries-cameron20 / t3code Mirror · read-only / commits / 17c401ddc0
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, 06:00 UTC

fix(web): drawer drops a background terminal closed by another client (#38998)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Wout Stiens committed Nov 19, 2026 at 09:00 UTC 17c401ddc0e0dac836eb246c5991fe9e17e1947a
11 files changed +369 -187
apps/server/src/terminal/Manager.ts
+2
@@ -1931,6 +1931,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
1931
1932 yield* fileSystem.makeDirectory(logsDir, { recursive: true }).pipe(Effect.orDie);
1933
1934 + const managerId = NodeCrypto.randomUUID();
1935 const managerStateRef = yield* SynchronizedRef.make<TerminalManagerState>({
1936 sessions: new Map(),
1937 killFibers: new Map(),
@@ -3744,6 +3745,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
3745 yield* listener({
3746 type: "snapshot",
3747 terminals,
3748 + managerId,
3749 });
3750
3751 for (const event of bufferedEvents) {
apps/web/src/components/PersistentThreadTerminals.tsx
+8 -50
@@ -22,7 +22,7 @@ import {
22 } from "../rightPanelStore";
23 import { useProject, useQuietThreadShell } from "../state/entities";
24 import { useEnvironmentScope } from "../state/session";
25 -import { useKnownTerminalSessions } from "../state/terminalSessions";
25 +import { useKnownTerminalSessions, useTerminalDrawerSessions } from "../state/terminalSessions";
26 import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
27 import { useThreadTerminalActions } from "./terminal/useThreadTerminalActions";
28 import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
@@ -34,40 +34,6 @@ export type PersistentTerminalLaunchContext = {
34 readonly worktreePath: string | null;
35 };
36
37 -function terminalIdListsEqual(left: readonly string[], right: readonly string[]): boolean {
38 - if (left.length !== right.length) {
39 - return false;
40 - }
41 - if (left.length === 0) {
42 - return true;
43 - }
44 - const sortedLeft = left.toSorted((a, b) => a.localeCompare(b));
45 - const sortedRight = right.toSorted((a, b) => a.localeCompare(b));
46 - for (let index = 0; index < sortedLeft.length; index += 1) {
47 - if (sortedLeft[index] !== sortedRight[index]) {
48 - return false;
49 - }
50 - }
51 - return true;
52 -}
53 -
54 -/** Server sessions lag terminal.open; reconciling strict subsets would discard new split layouts. */
55 -function serverTerminalIdsStrictSubsetOfClient(
56 - serverIds: readonly string[],
57 - clientIds: readonly string[],
58 -): boolean {
59 - if (serverIds.length >= clientIds.length || clientIds.length === 0) {
60 - return false;
61 - }
62 - const clientSet = new Set(clientIds);
63 - for (const id of serverIds) {
64 - if (!clientSet.has(id)) {
65 - return false;
66 - }
67 - }
68 - return true;
69 -}
70 -
37 interface TerminalLaunchLocationWithEnv {
38 readonly cwd: string;
39 readonly worktreePath: string | null;
@@ -116,10 +82,9 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm
82 selectThreadTerminalUiState(state.terminalUiStateByThreadKey, threadRef),
83 );
84 const visible = active && terminalUiState.terminalOpen;
119 - const knownTerminalSessions = useKnownTerminalSessions({
120 - environmentId: threadRef.environmentId,
121 - threadId,
122 - });
85 + const metadata = useTerminalDrawerSessions(threadRef.environmentId, threadId);
86 + const knownTerminalSessions = metadata?.sessions;
87 + const snapshotId = metadata?.snapshotId;
88 const panelSurfaces = useRightPanelStore(
89 (state) => selectThreadRightPanelState(state.byThreadKey, threadRef).surfaces,
90 );
@@ -164,18 +129,11 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm
129 const storeCloseTerminal = useTerminalUiStateStore((state) => state.closeTerminal);
130 const reconcileTerminalIds = useTerminalUiStateStore((state) => state.reconcileTerminalIds);
131
167 - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reconciles the terminal UI store's ids with the server's terminal list when they diverge
132 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- feeds the server's terminal list into the terminal UI store, which owns how local ids follow it
133 useEffect(() => {
169 - if (terminalIdListsEqual(serverOrderedTerminalIds, terminalUiState.terminalIds)) {
170 - return;
171 - }
172 - if (
173 - serverTerminalIdsStrictSubsetOfClient(serverOrderedTerminalIds, terminalUiState.terminalIds)
174 - ) {
175 - return;
176 - }
177 - reconcileTerminalIds(threadRef, serverOrderedTerminalIds);
178 - }, [reconcileTerminalIds, serverOrderedTerminalIds, terminalUiState.terminalIds, threadRef]);
134 + if (snapshotId === undefined) return;
135 + reconcileTerminalIds(threadRef, serverOrderedTerminalIds, snapshotId);
136 + }, [reconcileTerminalIds, serverOrderedTerminalIds, snapshotId, threadRef]);
137 const worktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
138 const effectiveWorktreePath = launchContext !== null ? launchContext.worktreePath : worktreePath;
139 const cwd =
apps/web/src/state/terminalSessions.ts
+34
@@ -233,6 +233,40 @@ export function useKnownTerminalSessions(input: {
233 );
234 }
235
236 +interface TerminalDrawerSessions {
237 + readonly sessions: ReadonlyArray<KnownTerminalSession>;
238 + readonly snapshotId: string | symbol;
239 +}
240 +
241 +const noTerminalDrawerSessions = Atom.make<TerminalDrawerSessions | null>(null);
242 +
243 +const terminalDrawerSessionsFamily = Atom.family((key: string) => {
244 + const [environmentId, threadId] = Option.getOrThrow(decodeKnownSessionsKey(key));
245 + return Atom.make((get): TerminalDrawerSessions | null => {
246 + const metadata = get(terminalEnvironment.metadataFeed({ environmentId, input: null }));
247 + if (!AsyncResult.isSuccess(metadata)) return null;
248 + const { terminals, snapshotId } = metadata.value;
249 + return {
250 + sessions: selectKnownTerminalSessions(terminals, environmentId, threadId),
251 + snapshotId,
252 + };
253 + }).pipe(
254 + Atom.withEquality<TerminalDrawerSessions | null>(
255 + (left, right) => left?.sessions === right?.sessions && left?.snapshotId === right?.snapshotId,
256 + ),
257 + Atom.withLabel(`web-terminal-drawer-sessions:${key}`),
258 + );
259 +});
260 +
261 +export function useTerminalDrawerSessions(environmentId: EnvironmentId, threadId: ThreadId) {
262 + const canRead = useEnvironmentScope(environmentId, AuthTerminalReadScope);
263 + return useAtomValue(
264 + canRead
265 + ? terminalDrawerSessionsFamily(JSON.stringify([environmentId, threadId]))
266 + : noTerminalDrawerSessions,
267 + );
268 +}
269 +
270 export function useThreadRunningTerminalIds(input: {
271 readonly environmentId: EnvironmentId | null;
272 readonly threadId: ThreadId | null;
apps/web/src/terminalUiStateStore.test.ts
+89
@@ -12,12 +12,18 @@ import { DEFAULT_THREAD_TERMINAL_ID } from "./types";
12 const THREAD_ID = ThreadId.make("thread-1");
13 const THREAD_REF = scopeThreadRef("environment-a" as never, THREAD_ID);
14 const OTHER_THREAD_REF = scopeThreadRef("environment-b" as never, THREAD_ID);
15 +const layout = () =>
16 + selectThreadTerminalUiState(
17 + useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
18 + THREAD_REF,
19 + );
20
21 describe("terminalUiStateStore actions", () => {
22 beforeEach(() => {
23 useTerminalUiStateStore.persist.clearStorage();
24 useTerminalUiStateStore.setState({
25 terminalUiStateByThreadKey: {},
26 + serverObservationsByThreadKey: {},
27 suppressedTerminalIdsByThreadKey: {},
28 });
29 });
@@ -182,4 +188,87 @@ describe("terminalUiStateStore actions", () => {
188 ).terminalIds,
189 ).toEqual(["term-2", "term-1"]);
190 });
191 +
192 + it("drops terminals the server stops reporting but keeps ones it has not reported yet", () => {
193 + const store = useTerminalUiStateStore.getState();
194 + store.setTerminalOpen(THREAD_REF, true);
195 + store.newTerminal(THREAD_REF, "term-2");
196 + store.newTerminal(THREAD_REF, "term-3");
197 + const terminalIds = () =>
198 + selectThreadTerminalUiState(
199 + useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
200 + THREAD_REF,
201 + ).terminalIds;
202 +
203 + store.reconcileTerminalIds(THREAD_REF, [DEFAULT_THREAD_TERMINAL_ID, "term-2"]);
204 + expect(terminalIds()).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"]);
205 +
206 + store.reconcileTerminalIds(THREAD_REF, [DEFAULT_THREAD_TERMINAL_ID]);
207 + expect(terminalIds()).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-3"]);
208 + });
209 +
210 + it("preserves a vertical split while the terminals reattach to a restarted server", () => {
211 + const store = useTerminalUiStateStore.getState();
212 + const firstSnapshot = "manager-1";
213 + const restartSnapshot = "manager-2";
214 + store.setTerminalOpen(THREAD_REF, true);
215 + store.splitTerminalVertical(THREAD_REF, "split");
216 + const beforeRestart = layout();
217 +
218 + store.reconcileTerminalIds(THREAD_REF, [DEFAULT_THREAD_TERMINAL_ID, "split"], firstSnapshot);
219 + store.reconcileTerminalIds(THREAD_REF, [], restartSnapshot);
220 + expect(layout()).toEqual(beforeRestart);
221 +
222 + store.reconcileTerminalIds(THREAD_REF, [DEFAULT_THREAD_TERMINAL_ID], restartSnapshot);
223 + store.reconcileTerminalIds(THREAD_REF, [DEFAULT_THREAD_TERMINAL_ID, "split"], restartSnapshot);
224 + expect(layout()).toEqual(beforeRestart);
225 +
226 + store.reconcileTerminalIds(THREAD_REF, [DEFAULT_THREAD_TERMINAL_ID], restartSnapshot);
227 + expect(layout().terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]);
228 + });
229 +
230 + it("drops a background terminal that closed before the drawer reloaded", async () => {
231 + const store = useTerminalUiStateStore.getState();
232 + store.setTerminalOpen(THREAD_REF, true);
233 + store.reconcileTerminalIds(THREAD_REF, [DEFAULT_THREAD_TERMINAL_ID, "old"], "manager-1");
234 + const { name, storage } = useTerminalUiStateStore.persist.getOptions();
235 + if (!name || !storage) throw new Error("Terminal layout storage is unavailable");
236 + const saved = await storage.getItem(name);
237 + if (!saved) throw new Error("Terminal layout was not saved");
238 + store.removeTerminalUiState(THREAD_REF);
239 + await storage.setItem(name, saved);
240 + await useTerminalUiStateStore.persist.rehydrate();
241 +
242 + store.reconcileTerminalIds(THREAD_REF, [DEFAULT_THREAD_TERMINAL_ID, "new"], "manager-1");
243 +
244 + expect(layout().terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "new"]);
245 + });
246 +
247 + it("keeps the surviving pane active when another client closes its split sibling", () => {
248 + const store = useTerminalUiStateStore.getState();
249 + store.newTerminal(THREAD_REF, "first");
250 + store.newTerminal(THREAD_REF, "second");
251 + store.splitTerminalVertical(THREAD_REF, "split");
252 + store.reconcileTerminalIds(THREAD_REF, ["first", "second", "split"]);
253 +
254 + store.reconcileTerminalIds(THREAD_REF, ["first", "second"]);
255 +
256 + expect(layout().activeTerminalId).toBe("second");
257 + expect(layout().activeTerminalGroupId).toBe("group-second");
258 + });
259 +
260 + it("preserves a pending local split when another client opens a tab", () => {
261 + const store = useTerminalUiStateStore.getState();
262 + store.reconcileTerminalIds(THREAD_REF, ["first"]);
263 + store.splitTerminalVertical(THREAD_REF, "pending");
264 +
265 + store.reconcileTerminalIds(THREAD_REF, ["first", "elsewhere"]);
266 + store.reconcileTerminalIds(THREAD_REF, ["first", "elsewhere", "pending"]);
267 +
268 + expect(layout().terminalGroups).toEqual([
269 + { id: "group-first", terminalIds: ["first", "pending"], splitDirection: "vertical" },
270 + { id: "group-elsewhere", terminalIds: ["elsewhere"] },
271 + ]);
272 + expect(layout().activeTerminalId).toBe("pending");
273 + });
274 });
apps/web/src/terminalUiStateStore.ts
+115 -80
@@ -451,28 +451,33 @@ function closeThreadTerminal(
451
452 function reconcileThreadTerminalSessionIds(
453 state: ThreadTerminalUiState,
454 - nextIds: string[],
454 + serverIds: string[],
455 + previousServerIds: readonly string[],
456 ): ThreadTerminalUiState {
457 const normalized = normalizeThreadTerminalUiState(state);
457 - if (arraysEqual(normalized.terminalIds, nextIds)) {
458 - return normalized;
459 - }
460 -
461 - const nextActiveTerminalId = nextIds.includes(normalized.activeTerminalId)
462 - ? normalized.activeTerminalId
463 - : (nextIds[0] ?? "");
464 -
465 - const terminalGroups = normalizeTerminalGroups(normalized.terminalGroups, nextIds);
466 - const activeGroupIdFromTerminal =
467 - terminalGroups.find((group) => group.terminalIds.includes(nextActiveTerminalId))?.id ?? null;
458 + const serverIdSet = new Set(serverIds);
459 + const localIdSet = new Set(normalized.terminalIds);
460 + const added = serverIds.filter((id) => !localIdSet.has(id));
461 + let next =
462 + added.length === 0
463 + ? normalized
464 + : normalizeThreadTerminalUiState({
465 + ...normalized,
466 + terminalIds: [...normalized.terminalIds, ...added],
467 + });
468
469 - return normalizeThreadTerminalUiState({
470 - ...normalized,
471 - terminalIds: nextIds,
472 - activeTerminalId: nextActiveTerminalId,
473 - terminalGroups,
474 - activeTerminalGroupId: activeGroupIdFromTerminal ?? terminalGroups[0]?.id ?? "",
475 - });
469 + for (const id of previousServerIds) {
470 + if (id !== normalized.activeTerminalId && !serverIdSet.has(id)) {
471 + next = closeThreadTerminal(next, id);
472 + }
473 + }
474 + if (
475 + !serverIdSet.has(normalized.activeTerminalId) &&
476 + previousServerIds.includes(normalized.activeTerminalId)
477 + ) {
478 + next = closeThreadTerminal(next, normalized.activeTerminalId);
479 + }
480 + return next;
481 }
482
483 export function selectThreadTerminalUiState(
@@ -558,7 +563,13 @@ function removeRecordEntry<T>(record: Record<string, T>, key: string): Record<st
563 return remaining;
564 }
565
566 +interface TerminalServerObservation {
567 + readonly ids: string[];
568 + readonly snapshotId: string | symbol | undefined;
569 +}
570 +
571 interface TerminalUiStateStoreState {
572 + serverObservationsByThreadKey: Record<string, TerminalServerObservation>;
573 terminalUiStateByThreadKey: Record<string, ThreadTerminalUiState>;
574 suppressedTerminalIdsByThreadKey: Record<string, string[]>;
575 setTerminalOpen: (threadRef: ScopedThreadRef, open: boolean) => void;
@@ -573,7 +584,11 @@ interface TerminalUiStateStoreState {
584 ) => void;
585 setActiveTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void;
586 closeTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void;
576 - reconcileTerminalIds: (threadRef: ScopedThreadRef, nextIds: string[]) => void;
587 + reconcileTerminalIds: (
588 + threadRef: ScopedThreadRef,
589 + serverIds: string[],
590 + snapshotId?: string | symbol,
591 + ) => void;
592 clearTerminalUiState: (threadRef: ScopedThreadRef) => void;
593 removeTerminalUiState: (threadRef: ScopedThreadRef) => void;
594 removeOrphanedTerminalUiStates: (activeThreadKeys: Set<string>) => void;
@@ -582,21 +597,42 @@ interface TerminalUiStateStoreState {
597 export const useTerminalUiStateStore = create<TerminalUiStateStoreState>()(
598 persist(
599 (set, get) => {
600 + const removeTerminalUiState = (threadRef: ScopedThreadRef) =>
601 + set((state) => {
602 + const threadKey = terminalThreadKey(threadRef);
603 + if (
604 + state.terminalUiStateByThreadKey[threadKey] === undefined &&
605 + state.suppressedTerminalIdsByThreadKey[threadKey] === undefined &&
606 + state.serverObservationsByThreadKey[threadKey] === undefined
607 + ) {
608 + return state;
609 + }
610 + return {
611 + terminalUiStateByThreadKey: removeRecordEntry(
612 + state.terminalUiStateByThreadKey,
613 + threadKey,
614 + ),
615 + suppressedTerminalIdsByThreadKey: removeRecordEntry(
616 + state.suppressedTerminalIdsByThreadKey,
617 + threadKey,
618 + ),
619 + serverObservationsByThreadKey: removeRecordEntry(
620 + state.serverObservationsByThreadKey,
621 + threadKey,
622 + ),
623 + };
624 + });
625 +
626 const updateTerminal = (
627 threadRef: ScopedThreadRef,
587 - updater: (
588 - state: ThreadTerminalUiState,
589 - suppressedTerminalIds: readonly string[],
590 - ) => ThreadTerminalUiState,
628 + updater: (state: ThreadTerminalUiState) => ThreadTerminalUiState,
629 suppression?: { terminalId: string; suppressed: boolean },
630 ) => {
631 set((state) => {
594 - const threadKey = terminalThreadKey(threadRef);
595 - const suppressedTerminalIds = state.suppressedTerminalIdsByThreadKey[threadKey] ?? [];
632 const nextTerminalUiStateByThreadKey = updateTerminalUiStateByThreadKey(
633 state.terminalUiStateByThreadKey,
634 threadRef,
599 - (terminalState) => updater(terminalState, suppressedTerminalIds),
635 + updater,
636 );
637 const nextSuppressedTerminalIdsByThreadKey = suppression
638 ? updateSuppressedTerminalId(
@@ -621,6 +657,7 @@ export const useTerminalUiStateStore = create<TerminalUiStateStoreState>()(
657
658 return {
659 terminalUiStateByThreadKey: {},
660 + serverObservationsByThreadKey: {},
661 suppressedTerminalIdsByThreadKey: {},
662 setTerminalOpen: (threadRef, open) => {
663 const terminalState = selectThreadTerminalUiState(
@@ -684,67 +721,57 @@ export const useTerminalUiStateStore = create<TerminalUiStateStoreState>()(
721 terminalId,
722 suppressed: true,
723 }),
687 - reconcileTerminalIds: (threadRef, nextIds) =>
688 - updateTerminal(threadRef, (state, suppressedTerminalIds) => {
689 - if (suppressedTerminalIds.length === 0) {
690 - return reconcileThreadTerminalSessionIds(state, nextIds);
691 - }
692 - const suppressedIds = new Set(suppressedTerminalIds);
693 - return reconcileThreadTerminalSessionIds(
694 - state,
695 - nextIds.filter((terminalId) => !suppressedIds.has(terminalId)),
696 - );
697 - }),
698 - clearTerminalUiState: (threadRef) =>
699 - set((state) => {
700 - const threadKey = terminalThreadKey(threadRef);
701 - const nextTerminalUiStateByThreadKey = updateTerminalUiStateByThreadKey(
702 - state.terminalUiStateByThreadKey,
703 - threadRef,
704 - () => createDefaultThreadTerminalUiState(),
705 - );
706 - const hadSuppressedTerminalIds =
707 - state.suppressedTerminalIdsByThreadKey[threadKey] !== undefined;
708 - if (
709 - nextTerminalUiStateByThreadKey === state.terminalUiStateByThreadKey &&
710 - !hadSuppressedTerminalIds
711 - ) {
712 - return state;
713 - }
714 - return {
715 - terminalUiStateByThreadKey: nextTerminalUiStateByThreadKey,
716 - suppressedTerminalIdsByThreadKey: removeRecordEntry(
717 - state.suppressedTerminalIdsByThreadKey,
718 - threadKey,
719 - ),
720 - };
721 - }),
722 - removeTerminalUiState: (threadRef) =>
723 - set((state) => {
724 - const threadKey = terminalThreadKey(threadRef);
725 - const hadTerminalUiState = state.terminalUiStateByThreadKey[threadKey] !== undefined;
726 - const hadSuppressedTerminalIds =
727 - state.suppressedTerminalIdsByThreadKey[threadKey] !== undefined;
728 - if (!hadTerminalUiState && !hadSuppressedTerminalIds) {
729 - return state;
730 - }
731 - return {
732 - terminalUiStateByThreadKey: removeRecordEntry(
733 - state.terminalUiStateByThreadKey,
734 - threadKey,
735 - ),
736 - suppressedTerminalIdsByThreadKey: removeRecordEntry(
737 - state.suppressedTerminalIdsByThreadKey,
738 - threadKey,
724 + reconcileTerminalIds: (threadRef, serverIds, snapshotId) => {
725 + if (threadRef.threadId.length === 0) return;
726 + const threadKey = terminalThreadKey(threadRef);
727 + const state = get();
728 + const previous = state.serverObservationsByThreadKey[threadKey];
729 + const suppressedIds = new Set(state.suppressedTerminalIdsByThreadKey[threadKey]);
730 + const terminalUiStateByThreadKey = updateTerminalUiStateByThreadKey(
731 + state.terminalUiStateByThreadKey,
732 + threadRef,
733 + (terminalState) =>
734 + reconcileThreadTerminalSessionIds(
735 + terminalState,
736 + serverIds.filter((id) => !suppressedIds.has(id)),
737 + // A different manager can start empty before old sessions reattach.
738 + previous?.snapshotId === snapshotId ? (previous?.ids ?? []) : [],
739 ),
740 + );
741 + // Metadata is ordered by activity, which does not change which terminals were seen.
742 + const observedIds = [...serverIds].sort();
743 + let serverObservationsByThreadKey = state.serverObservationsByThreadKey;
744 + if (observedIds.length === 0) {
745 + serverObservationsByThreadKey = removeRecordEntry(
746 + serverObservationsByThreadKey,
747 + threadKey,
748 + );
749 + } else if (
750 + !previous ||
751 + previous.snapshotId !== snapshotId ||
752 + !arraysEqual(previous.ids, observedIds)
753 + ) {
754 + serverObservationsByThreadKey = {
755 + ...serverObservationsByThreadKey,
756 + [threadKey]: { ids: observedIds, snapshotId },
757 };
741 - }),
758 + }
759 + if (
760 + terminalUiStateByThreadKey !== state.terminalUiStateByThreadKey ||
761 + serverObservationsByThreadKey !== state.serverObservationsByThreadKey
762 + ) {
763 + set({ terminalUiStateByThreadKey, serverObservationsByThreadKey });
764 + }
765 + },
766 + clearTerminalUiState: removeTerminalUiState,
767 + removeTerminalUiState,
768 removeOrphanedTerminalUiStates: (activeThreadKeys) =>
769 set((state) => {
770 const orphanedIds = new Set(
771 [
772 ...Object.keys(state.terminalUiStateByThreadKey),
773 ...Object.keys(state.suppressedTerminalIdsByThreadKey),
774 + ...Object.keys(state.serverObservationsByThreadKey),
775 ].filter((key) => !activeThreadKeys.has(key)),
776 );
777 if (orphanedIds.size === 0) {
@@ -754,13 +781,16 @@ export const useTerminalUiStateStore = create<TerminalUiStateStoreState>()(
781 const nextSuppressedTerminalIdsByThreadKey = {
782 ...state.suppressedTerminalIdsByThreadKey,
783 };
784 + const serverObservationsByThreadKey = { ...state.serverObservationsByThreadKey };
785 for (const id of orphanedIds) {
786 delete nextTerminalUiStateByThreadKey[id];
787 delete nextSuppressedTerminalIdsByThreadKey[id];
788 + delete serverObservationsByThreadKey[id];
789 }
790 return {
791 terminalUiStateByThreadKey: nextTerminalUiStateByThreadKey,
792 suppressedTerminalIdsByThreadKey: nextSuppressedTerminalIdsByThreadKey,
793 + serverObservationsByThreadKey,
794 };
795 }),
796 };
@@ -772,6 +802,11 @@ export const useTerminalUiStateStore = create<TerminalUiStateStoreState>()(
802 migrate: migratePersistedTerminalUiStateStoreState,
803 partialize: (state) => ({
804 terminalUiStateByThreadKey: state.terminalUiStateByThreadKey,
805 + serverObservationsByThreadKey: Object.fromEntries(
806 + Object.entries(state.serverObservationsByThreadKey).filter(
807 + ([, observation]) => typeof observation.snapshotId === "string",
808 + ),
809 + ),
810 }),
811 },
812 ),
packages/client-runtime/src/state/runtime.test.ts
+13 -7
@@ -607,7 +607,7 @@ describe("finite environment subscription lifecycle", () => {
607
608 describe("environment query lifecycle", () => {
609 it.effect(
610 - "terminal metadata waits for snapshots and retains known sessions across restarts",
610 + "terminal metadata retains known sessions until a new snapshot and keeps the manager identity",
611 () =>
612 Effect.gen(function* () {
613 const harness = yield* makeEnvironmentQueryHarness(Effect.void);
@@ -638,10 +638,9 @@ describe("environment query lifecycle", () => {
638 const session = { ...QUERY_RPC_SESSION, client };
639 yield* SubscriptionRef.set(harness.supervisorSession, Option.some(session));
640 const atoms = createTerminalEnvironmentAtoms(harness.runtime);
641 - const atom = atoms.metadata({
642 - environmentId: QUERY_ENVIRONMENT.environmentId,
643 - input: null,
644 - });
641 + const target = { environmentId: QUERY_ENVIRONMENT.environmentId, input: null };
642 + const atom = atoms.metadata(target);
643 + const feed = atoms.metadataFeed(target);
644 const registry = AtomRegistry.make();
645 const observed: Array<ReadonlyArray<TerminalSummary>> = [];
646 const unsubscribe = registry.subscribe(
@@ -665,9 +664,15 @@ describe("environment query lifecycle", () => {
664 expect(selectEnvironmentQueryData(registry.get(atom))).toBeNull();
665 expect(observed).toEqual([]);
666
668 - yield* Queue.offer(events, { type: "snapshot", terminals: [checkout] });
667 + yield* Queue.offer(events, {
668 + type: "snapshot",
669 + terminals: [checkout],
670 + managerId: "manager-1",
671 + });
672 yield* Deferred.await(receivedCheckout);
673 expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]);
674 + const initialSnapshotId = selectEnvironmentQueryData(registry.get(feed))?.snapshotId;
675 + expect(initialSnapshotId).toBe("manager-1");
676
677 yield* SubscriptionRef.set(harness.supervisorSession, Option.some({ ...session }));
678 yield* Queue.take(started);
@@ -677,9 +682,10 @@ describe("environment query lifecycle", () => {
682 yield* Queue.take(started);
683 expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]);
684
680 - yield* Queue.offer(events, { type: "snapshot", terminals: [] });
685 + yield* Queue.offer(events, { type: "snapshot", terminals: [], managerId: "manager-1" });
686 yield* Deferred.await(receivedEmpty);
687 expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([]);
688 + expect(selectEnvironmentQueryData(registry.get(feed))?.snapshotId).toBe(initialSnapshotId);
689 }),
690 );
691
packages/client-runtime/src/state/terminal.ts
+26 -9
@@ -33,6 +33,11 @@ import {
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 ) {
@@ -53,6 +58,24 @@ export function createTerminalEnvironmentAtoms<R, E>(
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",
@@ -86,15 +109,9 @@ export function createTerminalEnvironmentAtoms<R, E>(
109 );
110 },
111 }),
89 - metadata: createEnvironmentSubscriptionAtomFamily(runtime, {
90 - label: "environment-data:terminal:metadata",
91 - subscribe: (_input: null) =>
92 - subscribe(WS_METHODS.subscribeTerminalMetadata, {}).pipe(
93 - Stream.scan((): ReadonlyArray<TerminalSummary> => [], applyTerminalMetadataStreamEvent),
94 - // The scan seed is not an authoritative empty server snapshot.
95 - Stream.drop(1),
96 - ),
97 - }),
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,
packages/contracts/src/terminal.ts
+1
@@ -281,6 +281,7 @@ export type TerminalSummary = typeof TerminalSummary.Type;
281 const TerminalMetadataSnapshotEvent = Schema.Struct({
282 type: Schema.Literal("snapshot"),
283 terminals: Schema.Array(TerminalSummary),
284 + managerId: Schema.optional(Schema.String),
285 });
286
287 const TerminalMetadataUpsertEvent = Schema.Struct({
scripts/scenarios/mention-finds-older-linked-thread.e2e.ts
+2 -39
@@ -1,54 +1,17 @@
1 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 -import * as NodeWS from "@effect/platform-node/NodeWS";
3 -import {
4 - CommandId,
5 - ORCHESTRATION_PROTOCOL_VERSION,
6 - ThreadId,
7 - WsRpcGroup,
8 -} from "@t3tools/contracts";
2 +import { CommandId, ThreadId } from "@t3tools/contracts";
3 import { expect } from "e2e";
4 import * as SecureRandom from "effect/crypto/SecureRandom";
5 import * as Effect from "effect/Effect";
12 -import * as Layer from "effect/Layer";
6 import * as Schema from "effect/Schema";
14 -import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
15 -import { RpcClient, RpcSerialization } from "effect/rpc";
16 -import { Socket } from "effect/socket";
7
8 import { T3_HOME } from "../e2e.config.ts";
9 import { SECOND_HOME, startSecondServer } from "./second-server.ts";
20 -import { makeState, runPromise, test, WEB } from "./t3.ts";
10 +import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";
11
12 // A shell keeps an environment's 25 newest settled threads; older ones come from search.
13 const NEWER_SETTLED = 25;
14
25 -/** The typed RPC client of the server on `home` at `origin`, signed in through its own CLI. */
26 -const rpcClient = Effect.fn("scenario.rpcClient")(function* (home: string, origin: string) {
27 - const issued = yield* makeState(home).cli(["auth", "session", "issue", "--token-only"]);
28 - const { ticket } = yield* HttpClient.execute(
29 - HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe(
30 - HttpClientRequest.bearerToken(issued.stdout.trim()),
31 - ),
32 - ).pipe(
33 - Effect.flatMap(HttpClientResponse.filterStatusOk),
34 - Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))),
35 - Effect.provide(FetchHttpClient.layer),
36 - );
37 - // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns.
38 - const protocol = yield* Layer.build(
39 - RpcClient.layerProtocolSocket().pipe(
40 - Layer.provide(
41 - Socket.layerWebSocket(
42 - `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`,
43 - ),
44 - ),
45 - Layer.provide(RpcSerialization.layerJson),
46 - Layer.provide(NodeWS.layerWebSocketConstructor),
47 - ),
48 - );
49 - return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));
50 -});
51 -
15 const uuid = Effect.flatMap(SecureRandom.SecureRandom, (random) => random.uuidV4());
16 const decodePairing = Schema.decodeEffect(
17 Schema.fromJsonString(Schema.Struct({ credential: Schema.String })),
scripts/scenarios/t3.ts
+40 -2
@@ -2,18 +2,29 @@
2 // app. `t3-mobile.ts` is the same for the iOS app.
3 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 +import * as NodeWS from "@effect/platform-node/NodeWS";
6 import { test as base } from "@e2e-dev/web";
7 import { expect } from "e2e";
7 -import { CommandId, EnvironmentHttpApi, type ProjectMutation, ProjectId } from "@t3tools/contracts";
8 +import {
9 + CommandId,
10 + EnvironmentHttpApi,
11 + ORCHESTRATION_PROTOCOL_VERSION,
12 + type ProjectMutation,
13 + ProjectId,
14 + WsRpcGroup,
15 +} from "@t3tools/contracts";
16 import * as HostProcess from "@t3tools/shared/HostProcess";
17 import * as SecureRandom from "effect/crypto/SecureRandom";
18 import * as Effect from "effect/Effect";
19 import * as FileSystem from "effect/FileSystem";
20 import * as HttpApiClient from "effect/http-api/HttpApiClient";
21 +import * as Layer from "effect/Layer";
22 import * as Path from "effect/Path";
23 import * as Schedule from "effect/Schedule";
24 import * as Schema from "effect/Schema";
16 -import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";
25 +import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
26 +import { RpcClient, RpcSerialization } from "effect/rpc";
27 +import { Socket } from "effect/socket";
28
29 import { APP_DIR, T3_HOME } from "../e2e.config.ts";
30 import { run, ScenarioError } from "./shell.ts";
@@ -234,6 +245,33 @@ const environmentId = (baseUrl: string) =>
245 Effect.provide(FetchHttpClient.layer),
246 );
247
248 +/** The typed RPC client of the server on `home` at `origin`, signed in through its own CLI. */
249 +export const rpcClient = Effect.fn("scenario.rpcClient")(function* (home: string, origin: string) {
250 + const issued = yield* makeState(home).cli(["auth", "session", "issue", "--token-only"]);
251 + const { ticket } = yield* HttpClient.execute(
252 + HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe(
253 + HttpClientRequest.bearerToken(issued.stdout.trim()),
254 + ),
255 + ).pipe(
256 + Effect.flatMap(HttpClientResponse.filterStatusOk),
257 + Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))),
258 + Effect.provide(FetchHttpClient.layer),
259 + );
260 + // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns.
261 + const protocol = yield* Layer.build(
262 + RpcClient.layerProtocolSocket().pipe(
263 + Layer.provide(
264 + Socket.layerWebSocket(
265 + `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`,
266 + ),
267 + ),
268 + Layer.provide(RpcSerialization.layerJson),
269 + Layer.provide(NodeWS.layerWebSocketConstructor),
270 + ),
271 + );
272 + return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));
273 +});
274 +
275 export const test = base.extend<{ t3: T3 }>({
276 t3: async ({ app, browser }, use) => {
277 const { state, cleanup } = makeState(T3_HOME);
scripts/scenarios/terminal-closed-elsewhere-leaves-drawer.e2e.ts new
+39
@@ -0,0 +1,39 @@
1 +import { ThreadId } from "@t3tools/contracts";
2 +import { expect } from "e2e";
3 +import * as Effect from "effect/Effect";
4 +
5 +import { T3_HOME } from "../e2e.config.ts";
6 +import { rpcClient, runPromise, test, WEB } from "./t3.ts";
7 +
8 +test("The drawer removes a terminal closed by another client", WEB, async ({ t3, app, screen }) => {
9 + const cwd = await t3.project("demo");
10 + const thread = await t3.thread({ project: cwd, title: "Shared terminals", messages: ["first"] });
11 + const threadId = ThreadId.make(thread.threadId);
12 + const origin = app.baseUrl ?? "";
13 + const kept = "kept-shell";
14 + const closed = "closed-elsewhere";
15 +
16 + await runPromise(
17 + Effect.gen(function* () {
18 + const client = yield* rpcClient(T3_HOME, origin);
19 + for (const terminalId of [kept, closed]) {
20 + yield* client["terminal.open"]({ threadId, terminalId, cwd });
21 + }
22 + }).pipe(Effect.scoped),
23 + );
24 + await t3.open(thread);
25 + await screen.getByRole("button", "Toggle terminal drawer").tap();
26 + await screen.getByRole("button", kept, { exact: true }).tap();
27 + const closedTab = screen.getByRole("button", closed, { exact: true });
28 + await closedTab.waitFor();
29 +
30 + await runPromise(
31 + Effect.gen(function* () {
32 + const client = yield* rpcClient(T3_HOME, origin);
33 + yield* client["terminal.close"]({ threadId, terminalId: closed, deleteHistory: true });
34 + }).pipe(Effect.scoped),
35 + );
36 +
37 + await app.screenshot("after-close-from-another-client");
38 + await expect(closedTab).toBeHidden();
39 +});