From 496eaf6e0f469a5d85430062b943186ef8b4d1d8 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:17:03 +0100 Subject: [PATCH 1/7] test(web): drawer removes a terminal closed by another client Co-authored-by: Claude Opus 5.5 --- apps/web/src/terminalUiStateStore.test.ts | 18 +++++ ...inal-closed-elsewhere-leaves-drawer.e2e.ts | 70 +++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 scripts/scenarios/terminal-closed-elsewhere-leaves-drawer.e2e.ts diff --git a/apps/web/src/terminalUiStateStore.test.ts b/apps/web/src/terminalUiStateStore.test.ts index 1ad8ba86c06ae..a5f6ef98b8cfe 100644 --- a/apps/web/src/terminalUiStateStore.test.ts +++ b/apps/web/src/terminalUiStateStore.test.ts @@ -182,4 +182,22 @@ describe("terminalUiStateStore actions", () => { ).terminalIds, ).toEqual(["term-2", "term-1"]); }); + + it("drops terminals the server stops reporting but keeps ones it has not reported yet", () => { + const store = useTerminalUiStateStore.getState(); + store.setTerminalOpen(THREAD_REF, true); + store.newTerminal(THREAD_REF, "term-2"); + store.newTerminal(THREAD_REF, "term-3"); + const terminalIds = () => + selectThreadTerminalUiState( + useTerminalUiStateStore.getState().terminalUiStateByThreadKey, + THREAD_REF, + ).terminalIds; + + store.reconcileTerminalIds(THREAD_REF, [DEFAULT_THREAD_TERMINAL_ID, "term-2"]); + expect(terminalIds()).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-2", "term-3"]); + + store.reconcileTerminalIds(THREAD_REF, [DEFAULT_THREAD_TERMINAL_ID]); + expect(terminalIds()).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-3"]); + }); }); diff --git a/scripts/scenarios/terminal-closed-elsewhere-leaves-drawer.e2e.ts b/scripts/scenarios/terminal-closed-elsewhere-leaves-drawer.e2e.ts new file mode 100644 index 0000000000000..938f062b1f611 --- /dev/null +++ b/scripts/scenarios/terminal-closed-elsewhere-leaves-drawer.e2e.ts @@ -0,0 +1,70 @@ +import * as NodeWS from "@effect/platform-node/NodeWS"; +import { ORCHESTRATION_PROTOCOL_VERSION, ThreadId, WsRpcGroup } from "@t3tools/contracts"; +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; +import { RpcClient, RpcSerialization } from "effect/rpc"; +import { Socket } from "effect/socket"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +const terminalClient = Effect.fn("scenario.terminalClient")(function* (origin: string) { + const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]); + const { ticket } = yield* HttpClient.execute( + HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe( + HttpClientRequest.bearerToken(issued.stdout.trim()), + ), + ).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))), + Effect.provide(FetchHttpClient.layer), + ); + const protocol = yield* Layer.build( + RpcClient.layerProtocolSocket().pipe( + Layer.provide( + Socket.layerWebSocket( + `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`, + ), + ), + Layer.provide(RpcSerialization.layerJson), + Layer.provide(NodeWS.layerWebSocketConstructor), + ), + ); + return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol)); +}); + +test("The drawer removes a terminal closed by another client", WEB, async ({ t3, app, screen }) => { + const cwd = await t3.project("demo"); + const thread = await t3.thread({ project: cwd, title: "Shared terminals", messages: ["first"] }); + const threadId = ThreadId.make(thread.threadId); + const origin = app.baseUrl ?? ""; + const kept = "kept-shell"; + const closed = "closed-elsewhere"; + + await runPromise( + Effect.gen(function* () { + const client = yield* terminalClient(origin); + for (const terminalId of [kept, closed]) { + yield* client["terminal.open"]({ threadId, terminalId, cwd }); + } + }).pipe(Effect.scoped), + ); + await t3.open(thread); + await screen.getByRole("button", "Toggle terminal drawer").tap(); + await screen.getByRole("button", kept, { exact: true }).tap(); + const closedTab = screen.getByRole("button", closed, { exact: true }); + await closedTab.waitFor(); + + await runPromise( + Effect.gen(function* () { + const client = yield* terminalClient(origin); + yield* client["terminal.close"]({ threadId, terminalId: closed, deleteHistory: true }); + }).pipe(Effect.scoped), + ); + + await app.screenshot("after-close-from-another-client"); + await expect(closedTab).toBeHidden(); +}); From 4908935fee1ba9a8c6f8c474cda46088d5735c05 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:21:06 +0100 Subject: [PATCH 2/7] fix(web): drawer drops a background terminal closed by another client The drawer skipped reconciling whenever the server listed a strict subset of its tabs, so a terminal closed elsewhere stayed as a dead tab. The terminal UI store now remembers the server's last list per thread and drops ids the server stopped reporting, while still keeping ids opened here that the server has not reported yet. Co-authored-by: Claude Opus 5.5 --- .../components/PersistentThreadTerminals.tsx | 47 +--------- apps/web/src/terminalUiStateStore.test.ts | 1 + apps/web/src/terminalUiStateStore.ts | 89 ++++++++++++++----- 3 files changed, 73 insertions(+), 64 deletions(-) diff --git a/apps/web/src/components/PersistentThreadTerminals.tsx b/apps/web/src/components/PersistentThreadTerminals.tsx index 9aa1958adcf21..b4585c68d6acc 100644 --- a/apps/web/src/components/PersistentThreadTerminals.tsx +++ b/apps/web/src/components/PersistentThreadTerminals.tsx @@ -34,40 +34,6 @@ export type PersistentTerminalLaunchContext = { readonly worktreePath: string | null; }; -function terminalIdListsEqual(left: readonly string[], right: readonly string[]): boolean { - if (left.length !== right.length) { - return false; - } - if (left.length === 0) { - return true; - } - const sortedLeft = left.toSorted((a, b) => a.localeCompare(b)); - const sortedRight = right.toSorted((a, b) => a.localeCompare(b)); - for (let index = 0; index < sortedLeft.length; index += 1) { - if (sortedLeft[index] !== sortedRight[index]) { - return false; - } - } - return true; -} - -/** Server sessions lag terminal.open; reconciling strict subsets would discard new split layouts. */ -function serverTerminalIdsStrictSubsetOfClient( - serverIds: readonly string[], - clientIds: readonly string[], -): boolean { - if (serverIds.length >= clientIds.length || clientIds.length === 0) { - return false; - } - const clientSet = new Set(clientIds); - for (const id of serverIds) { - if (!clientSet.has(id)) { - return false; - } - } - return true; -} - interface TerminalLaunchLocationWithEnv { readonly cwd: string; readonly worktreePath: string | null; @@ -164,18 +130,11 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm const storeCloseTerminal = useTerminalUiStateStore((state) => state.closeTerminal); const reconcileTerminalIds = useTerminalUiStateStore((state) => state.reconcileTerminalIds); - // 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 + // 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 useEffect(() => { - if (terminalIdListsEqual(serverOrderedTerminalIds, terminalUiState.terminalIds)) { - return; - } - if ( - serverTerminalIdsStrictSubsetOfClient(serverOrderedTerminalIds, terminalUiState.terminalIds) - ) { - return; - } + if (knownTerminalSessions === null) return; reconcileTerminalIds(threadRef, serverOrderedTerminalIds); - }, [reconcileTerminalIds, serverOrderedTerminalIds, terminalUiState.terminalIds, threadRef]); + }, [knownTerminalSessions, reconcileTerminalIds, serverOrderedTerminalIds, threadRef]); const worktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null; const effectiveWorktreePath = launchContext !== null ? launchContext.worktreePath : worktreePath; const cwd = diff --git a/apps/web/src/terminalUiStateStore.test.ts b/apps/web/src/terminalUiStateStore.test.ts index a5f6ef98b8cfe..22938528663de 100644 --- a/apps/web/src/terminalUiStateStore.test.ts +++ b/apps/web/src/terminalUiStateStore.test.ts @@ -19,6 +19,7 @@ describe("terminalUiStateStore actions", () => { useTerminalUiStateStore.setState({ terminalUiStateByThreadKey: {}, suppressedTerminalIdsByThreadKey: {}, + serverTerminalIdsByThreadKey: {}, }); }); diff --git a/apps/web/src/terminalUiStateStore.ts b/apps/web/src/terminalUiStateStore.ts index b442e855ca12d..66740f4e2e5e6 100644 --- a/apps/web/src/terminalUiStateStore.ts +++ b/apps/web/src/terminalUiStateStore.ts @@ -451,12 +451,25 @@ function closeThreadTerminal( function reconcileThreadTerminalSessionIds( state: ThreadTerminalUiState, - nextIds: string[], + serverIds: string[], + previousServerIds: readonly string[], ): ThreadTerminalUiState { const normalized = normalizeThreadTerminalUiState(state); - if (arraysEqual(normalized.terminalIds, nextIds)) { + const serverIdSet = new Set(serverIds); + const unreportedIds = normalized.terminalIds.filter((id) => !serverIdSet.has(id)); + const serverIdsAllShown = serverIds.every((id) => normalized.terminalIds.includes(id)); + if (unreportedIds.length === 0 && serverIdsAllShown) { return normalized; } + // Server sessions lag terminal.open, so only drop ids the server reported before and no longer does. + let nextIds = serverIds; + if (serverIdsAllShown) { + const previousIdSet = new Set(previousServerIds); + nextIds = normalized.terminalIds.filter((id) => serverIdSet.has(id) || !previousIdSet.has(id)); + if (nextIds.length === normalized.terminalIds.length) { + return normalized; + } + } const nextActiveTerminalId = nextIds.includes(normalized.activeTerminalId) ? normalized.activeTerminalId @@ -561,6 +574,8 @@ function removeRecordEntry(record: Record, key: string): Record; suppressedTerminalIdsByThreadKey: Record; + /** The server's last reported terminal ids per thread, to tell a removal from a terminal still opening. */ + serverTerminalIdsByThreadKey: Record; setTerminalOpen: (threadRef: ScopedThreadRef, open: boolean) => void; setTerminalHeight: (threadRef: ScopedThreadRef, height: number) => void; splitTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void; @@ -584,19 +599,14 @@ export const useTerminalUiStateStore = create()( (set, get) => { const updateTerminal = ( threadRef: ScopedThreadRef, - updater: ( - state: ThreadTerminalUiState, - suppressedTerminalIds: readonly string[], - ) => ThreadTerminalUiState, + updater: (state: ThreadTerminalUiState) => ThreadTerminalUiState, suppression?: { terminalId: string; suppressed: boolean }, ) => { set((state) => { - const threadKey = terminalThreadKey(threadRef); - const suppressedTerminalIds = state.suppressedTerminalIdsByThreadKey[threadKey] ?? []; const nextTerminalUiStateByThreadKey = updateTerminalUiStateByThreadKey( state.terminalUiStateByThreadKey, threadRef, - (terminalState) => updater(terminalState, suppressedTerminalIds), + updater, ); const nextSuppressedTerminalIdsByThreadKey = suppression ? updateSuppressedTerminalId( @@ -622,6 +632,7 @@ export const useTerminalUiStateStore = create()( return { terminalUiStateByThreadKey: {}, suppressedTerminalIdsByThreadKey: {}, + serverTerminalIdsByThreadKey: {}, setTerminalOpen: (threadRef, open) => { const terminalState = selectThreadTerminalUiState( get().terminalUiStateByThreadKey, @@ -684,16 +695,37 @@ export const useTerminalUiStateStore = create()( terminalId, suppressed: true, }), - reconcileTerminalIds: (threadRef, nextIds) => - updateTerminal(threadRef, (state, suppressedTerminalIds) => { - if (suppressedTerminalIds.length === 0) { - return reconcileThreadTerminalSessionIds(state, nextIds); - } - const suppressedIds = new Set(suppressedTerminalIds); - return reconcileThreadTerminalSessionIds( - state, - nextIds.filter((terminalId) => !suppressedIds.has(terminalId)), + reconcileTerminalIds: (threadRef, serverIds) => + set((state) => { + if (threadRef.threadId.length === 0) return state; + const threadKey = terminalThreadKey(threadRef); + const previousServerIds = state.serverTerminalIdsByThreadKey[threadKey] ?? []; + const suppressedIds = new Set(state.suppressedTerminalIdsByThreadKey[threadKey]); + const nextTerminalUiStateByThreadKey = updateTerminalUiStateByThreadKey( + state.terminalUiStateByThreadKey, + threadRef, + (terminalState) => + reconcileThreadTerminalSessionIds( + terminalState, + serverIds.filter((terminalId) => !suppressedIds.has(terminalId)), + previousServerIds, + ), ); + const nextServerTerminalIdsByThreadKey = arraysEqual(previousServerIds, serverIds) + ? state.serverTerminalIdsByThreadKey + : serverIds.length === 0 + ? removeRecordEntry(state.serverTerminalIdsByThreadKey, threadKey) + : { ...state.serverTerminalIdsByThreadKey, [threadKey]: serverIds }; + if ( + nextTerminalUiStateByThreadKey === state.terminalUiStateByThreadKey && + nextServerTerminalIdsByThreadKey === state.serverTerminalIdsByThreadKey + ) { + return state; + } + return { + terminalUiStateByThreadKey: nextTerminalUiStateByThreadKey, + serverTerminalIdsByThreadKey: nextServerTerminalIdsByThreadKey, + }; }), clearTerminalUiState: (threadRef) => set((state) => { @@ -705,9 +737,12 @@ export const useTerminalUiStateStore = create()( ); const hadSuppressedTerminalIds = state.suppressedTerminalIdsByThreadKey[threadKey] !== undefined; + const hadServerTerminalIds = + state.serverTerminalIdsByThreadKey[threadKey] !== undefined; if ( nextTerminalUiStateByThreadKey === state.terminalUiStateByThreadKey && - !hadSuppressedTerminalIds + !hadSuppressedTerminalIds && + !hadServerTerminalIds ) { return state; } @@ -717,6 +752,10 @@ export const useTerminalUiStateStore = create()( state.suppressedTerminalIdsByThreadKey, threadKey, ), + serverTerminalIdsByThreadKey: removeRecordEntry( + state.serverTerminalIdsByThreadKey, + threadKey, + ), }; }), removeTerminalUiState: (threadRef) => @@ -725,7 +764,9 @@ export const useTerminalUiStateStore = create()( const hadTerminalUiState = state.terminalUiStateByThreadKey[threadKey] !== undefined; const hadSuppressedTerminalIds = state.suppressedTerminalIdsByThreadKey[threadKey] !== undefined; - if (!hadTerminalUiState && !hadSuppressedTerminalIds) { + const hadServerTerminalIds = + state.serverTerminalIdsByThreadKey[threadKey] !== undefined; + if (!hadTerminalUiState && !hadSuppressedTerminalIds && !hadServerTerminalIds) { return state; } return { @@ -737,6 +778,10 @@ export const useTerminalUiStateStore = create()( state.suppressedTerminalIdsByThreadKey, threadKey, ), + serverTerminalIdsByThreadKey: removeRecordEntry( + state.serverTerminalIdsByThreadKey, + threadKey, + ), }; }), removeOrphanedTerminalUiStates: (activeThreadKeys) => @@ -745,6 +790,7 @@ export const useTerminalUiStateStore = create()( [ ...Object.keys(state.terminalUiStateByThreadKey), ...Object.keys(state.suppressedTerminalIdsByThreadKey), + ...Object.keys(state.serverTerminalIdsByThreadKey), ].filter((key) => !activeThreadKeys.has(key)), ); if (orphanedIds.size === 0) { @@ -754,13 +800,16 @@ export const useTerminalUiStateStore = create()( const nextSuppressedTerminalIdsByThreadKey = { ...state.suppressedTerminalIdsByThreadKey, }; + const nextServerTerminalIdsByThreadKey = { ...state.serverTerminalIdsByThreadKey }; for (const id of orphanedIds) { delete nextTerminalUiStateByThreadKey[id]; delete nextSuppressedTerminalIdsByThreadKey[id]; + delete nextServerTerminalIdsByThreadKey[id]; } return { terminalUiStateByThreadKey: nextTerminalUiStateByThreadKey, suppressedTerminalIdsByThreadKey: nextSuppressedTerminalIdsByThreadKey, + serverTerminalIdsByThreadKey: nextServerTerminalIdsByThreadKey, }; }), }; From 3165d45594f09be7829913303eeaa29cf00f82be Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:38:24 +0100 Subject: [PATCH 3/7] fix(web): preserve terminal drawer layout during metadata reconnects Co-authored-by: GPT 6.2 Sol --- .../components/PersistentThreadTerminals.tsx | 15 +- apps/web/src/state/terminalSessions.ts | 34 +++++ apps/web/src/terminalUiStateStore.test.ts | 60 +++++++- apps/web/src/terminalUiStateStore.ts | 132 +++++++----------- .../client-runtime/src/state/runtime.test.ts | 12 +- packages/client-runtime/src/state/terminal.ts | 35 +++-- 6 files changed, 186 insertions(+), 102 deletions(-) diff --git a/apps/web/src/components/PersistentThreadTerminals.tsx b/apps/web/src/components/PersistentThreadTerminals.tsx index b4585c68d6acc..f389dbd40f80d 100644 --- a/apps/web/src/components/PersistentThreadTerminals.tsx +++ b/apps/web/src/components/PersistentThreadTerminals.tsx @@ -22,7 +22,7 @@ import { } from "../rightPanelStore"; import { useProject, useQuietThreadShell } from "../state/entities"; import { useEnvironmentScope } from "../state/session"; -import { useKnownTerminalSessions } from "../state/terminalSessions"; +import { useKnownTerminalSessions, useTerminalDrawerSessions } from "../state/terminalSessions"; import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; import { useThreadTerminalActions } from "./terminal/useThreadTerminalActions"; import ThreadTerminalDrawer from "./ThreadTerminalDrawer"; @@ -82,10 +82,9 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm selectThreadTerminalUiState(state.terminalUiStateByThreadKey, threadRef), ); const visible = active && terminalUiState.terminalOpen; - const knownTerminalSessions = useKnownTerminalSessions({ - environmentId: threadRef.environmentId, - threadId, - }); + const metadata = useTerminalDrawerSessions(threadRef.environmentId, threadId); + const knownTerminalSessions = metadata?.sessions; + const snapshotId = metadata?.snapshotId; const panelSurfaces = useRightPanelStore( (state) => selectThreadRightPanelState(state.byThreadKey, threadRef).surfaces, ); @@ -132,9 +131,9 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm // 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 useEffect(() => { - if (knownTerminalSessions === null) return; - reconcileTerminalIds(threadRef, serverOrderedTerminalIds); - }, [knownTerminalSessions, reconcileTerminalIds, serverOrderedTerminalIds, threadRef]); + if (snapshotId === undefined) return; + reconcileTerminalIds(threadRef, serverOrderedTerminalIds, snapshotId); + }, [reconcileTerminalIds, serverOrderedTerminalIds, snapshotId, threadRef]); const worktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null; const effectiveWorktreePath = launchContext !== null ? launchContext.worktreePath : worktreePath; const cwd = diff --git a/apps/web/src/state/terminalSessions.ts b/apps/web/src/state/terminalSessions.ts index 79dfdae7f705e..a00f681e12759 100644 --- a/apps/web/src/state/terminalSessions.ts +++ b/apps/web/src/state/terminalSessions.ts @@ -233,6 +233,40 @@ export function useKnownTerminalSessions(input: { ); } +interface TerminalDrawerSessions { + readonly sessions: ReadonlyArray; + readonly snapshotId: symbol; +} + +const noTerminalDrawerSessions = Atom.make(null); + +const terminalDrawerSessionsFamily = Atom.family((key: string) => { + const [environmentId, threadId] = Option.getOrThrow(decodeKnownSessionsKey(key)); + return Atom.make((get): TerminalDrawerSessions | null => { + const metadata = get(terminalEnvironment.metadataFeed({ environmentId, input: null })); + if (!AsyncResult.isSuccess(metadata)) return null; + const { terminals, snapshotId } = metadata.value; + return { + sessions: selectKnownTerminalSessions(terminals, environmentId, threadId), + snapshotId, + }; + }).pipe( + Atom.withEquality( + (left, right) => left?.sessions === right?.sessions && left?.snapshotId === right?.snapshotId, + ), + Atom.withLabel(`web-terminal-drawer-sessions:${key}`), + ); +}); + +export function useTerminalDrawerSessions(environmentId: EnvironmentId, threadId: ThreadId) { + const canRead = useEnvironmentScope(environmentId, AuthTerminalReadScope); + return useAtomValue( + canRead + ? terminalDrawerSessionsFamily(JSON.stringify([environmentId, threadId])) + : noTerminalDrawerSessions, + ); +} + export function useThreadRunningTerminalIds(input: { readonly environmentId: EnvironmentId | null; readonly threadId: ThreadId | null; diff --git a/apps/web/src/terminalUiStateStore.test.ts b/apps/web/src/terminalUiStateStore.test.ts index 22938528663de..4fc339e642c5a 100644 --- a/apps/web/src/terminalUiStateStore.test.ts +++ b/apps/web/src/terminalUiStateStore.test.ts @@ -15,11 +15,11 @@ const OTHER_THREAD_REF = scopeThreadRef("environment-b" as never, THREAD_ID); describe("terminalUiStateStore actions", () => { beforeEach(() => { + useTerminalUiStateStore.getState().removeOrphanedTerminalUiStates(new Set()); useTerminalUiStateStore.persist.clearStorage(); useTerminalUiStateStore.setState({ terminalUiStateByThreadKey: {}, suppressedTerminalIdsByThreadKey: {}, - serverTerminalIdsByThreadKey: {}, }); }); @@ -202,3 +202,61 @@ describe("terminalUiStateStore actions", () => { expect(terminalIds()).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-3"]); }); }); + +describe("server terminal reconciliation", () => { + const layout = () => + selectThreadTerminalUiState( + useTerminalUiStateStore.getState().terminalUiStateByThreadKey, + THREAD_REF, + ); + + beforeEach(() => { + useTerminalUiStateStore.getState().removeTerminalUiState(THREAD_REF); + }); + + it("preserves a vertical split while the terminals reattach to a restarted server", () => { + const store = useTerminalUiStateStore.getState(); + const firstSnapshot = Symbol(); + const restartSnapshot = Symbol(); + store.setTerminalOpen(THREAD_REF, true); + store.splitTerminalVertical(THREAD_REF, "split"); + const beforeRestart = layout(); + + store.reconcileTerminalIds(THREAD_REF, [DEFAULT_THREAD_TERMINAL_ID, "split"], firstSnapshot); + store.reconcileTerminalIds(THREAD_REF, [], restartSnapshot); + expect(layout()).toEqual(beforeRestart); + + store.reconcileTerminalIds(THREAD_REF, [DEFAULT_THREAD_TERMINAL_ID], restartSnapshot); + store.reconcileTerminalIds(THREAD_REF, [DEFAULT_THREAD_TERMINAL_ID, "split"], restartSnapshot); + expect(layout()).toEqual(beforeRestart); + + store.reconcileTerminalIds(THREAD_REF, [DEFAULT_THREAD_TERMINAL_ID], restartSnapshot); + expect(layout().terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]); + }); + + it("preserves a pending local split when another client opens a tab", () => { + const store = useTerminalUiStateStore.getState(); + store.reconcileTerminalIds(THREAD_REF, ["first"]); + store.splitTerminalVertical(THREAD_REF, "pending"); + + store.reconcileTerminalIds(THREAD_REF, ["first", "elsewhere"]); + store.reconcileTerminalIds(THREAD_REF, ["first", "elsewhere", "pending"]); + + expect(layout().terminalGroups).toEqual([ + { id: "group-first", terminalIds: ["first", "pending"], splitDirection: "vertical" }, + { id: "group-elsewhere", terminalIds: ["elsewhere"] }, + ]); + expect(layout().activeTerminalId).toBe("pending"); + }); + + it("resets the drawer when another client closes the last terminal", () => { + const store = useTerminalUiStateStore.getState(); + const defaultLayout = layout(); + store.setTerminalOpen(THREAD_REF, true); + store.reconcileTerminalIds(THREAD_REF, [DEFAULT_THREAD_TERMINAL_ID]); + + store.reconcileTerminalIds(THREAD_REF, []); + + expect(layout()).toEqual(defaultLayout); + }); +}); diff --git a/apps/web/src/terminalUiStateStore.ts b/apps/web/src/terminalUiStateStore.ts index 66740f4e2e5e6..d36e59b9e2324 100644 --- a/apps/web/src/terminalUiStateStore.ts +++ b/apps/web/src/terminalUiStateStore.ts @@ -456,35 +456,19 @@ function reconcileThreadTerminalSessionIds( ): ThreadTerminalUiState { const normalized = normalizeThreadTerminalUiState(state); const serverIdSet = new Set(serverIds); - const unreportedIds = normalized.terminalIds.filter((id) => !serverIdSet.has(id)); - const serverIdsAllShown = serverIds.every((id) => normalized.terminalIds.includes(id)); - if (unreportedIds.length === 0 && serverIdsAllShown) { - return normalized; - } - // Server sessions lag terminal.open, so only drop ids the server reported before and no longer does. - let nextIds = serverIds; - if (serverIdsAllShown) { - const previousIdSet = new Set(previousServerIds); - nextIds = normalized.terminalIds.filter((id) => serverIdSet.has(id) || !previousIdSet.has(id)); - if (nextIds.length === normalized.terminalIds.length) { - return normalized; - } - } - - const nextActiveTerminalId = nextIds.includes(normalized.activeTerminalId) - ? normalized.activeTerminalId - : (nextIds[0] ?? ""); - - const terminalGroups = normalizeTerminalGroups(normalized.terminalGroups, nextIds); - const activeGroupIdFromTerminal = - terminalGroups.find((group) => group.terminalIds.includes(nextActiveTerminalId))?.id ?? null; + const previousIdSet = new Set(previousServerIds); + const localIdSet = new Set(normalized.terminalIds); + const nextIds = [ + ...normalized.terminalIds.filter((id) => serverIdSet.has(id) || !previousIdSet.has(id)), + ...serverIds.filter((id) => !localIdSet.has(id)), + ]; + if (arraysEqual(nextIds, normalized.terminalIds)) return normalized; + if (nextIds.length === 0) return getDefaultThreadTerminalUiState(); return normalizeThreadTerminalUiState({ ...normalized, terminalIds: nextIds, - activeTerminalId: nextActiveTerminalId, - terminalGroups, - activeTerminalGroupId: activeGroupIdFromTerminal ?? terminalGroups[0]?.id ?? "", + activeTerminalGroupId: "", }); } @@ -574,8 +558,6 @@ function removeRecordEntry(record: Record, key: string): Record; suppressedTerminalIdsByThreadKey: Record; - /** The server's last reported terminal ids per thread, to tell a removal from a terminal still opening. */ - serverTerminalIdsByThreadKey: Record; setTerminalOpen: (threadRef: ScopedThreadRef, open: boolean) => void; setTerminalHeight: (threadRef: ScopedThreadRef, height: number) => void; splitTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void; @@ -588,7 +570,11 @@ interface TerminalUiStateStoreState { ) => void; setActiveTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void; closeTerminal: (threadRef: ScopedThreadRef, terminalId: string) => void; - reconcileTerminalIds: (threadRef: ScopedThreadRef, nextIds: string[]) => void; + reconcileTerminalIds: ( + threadRef: ScopedThreadRef, + serverIds: string[], + snapshotId?: symbol, + ) => void; clearTerminalUiState: (threadRef: ScopedThreadRef) => void; removeTerminalUiState: (threadRef: ScopedThreadRef) => void; removeOrphanedTerminalUiStates: (activeThreadKeys: Set) => void; @@ -597,6 +583,11 @@ interface TerminalUiStateStoreState { export const useTerminalUiStateStore = create()( persist( (set, get) => { + const serverObservations = new Map< + string, + { ids: string[]; snapshotId: symbol | undefined } + >(); + const updateTerminal = ( threadRef: ScopedThreadRef, updater: (state: ThreadTerminalUiState) => ThreadTerminalUiState, @@ -632,7 +623,6 @@ export const useTerminalUiStateStore = create()( return { terminalUiStateByThreadKey: {}, suppressedTerminalIdsByThreadKey: {}, - serverTerminalIdsByThreadKey: {}, setTerminalOpen: (threadRef, open) => { const terminalState = selectThreadTerminalUiState( get().terminalUiStateByThreadKey, @@ -695,38 +685,32 @@ export const useTerminalUiStateStore = create()( terminalId, suppressed: true, }), - reconcileTerminalIds: (threadRef, serverIds) => - set((state) => { - if (threadRef.threadId.length === 0) return state; - const threadKey = terminalThreadKey(threadRef); - const previousServerIds = state.serverTerminalIdsByThreadKey[threadKey] ?? []; - const suppressedIds = new Set(state.suppressedTerminalIdsByThreadKey[threadKey]); - const nextTerminalUiStateByThreadKey = updateTerminalUiStateByThreadKey( - state.terminalUiStateByThreadKey, - threadRef, - (terminalState) => - reconcileThreadTerminalSessionIds( - terminalState, - serverIds.filter((terminalId) => !suppressedIds.has(terminalId)), - previousServerIds, - ), - ); - const nextServerTerminalIdsByThreadKey = arraysEqual(previousServerIds, serverIds) - ? state.serverTerminalIdsByThreadKey - : serverIds.length === 0 - ? removeRecordEntry(state.serverTerminalIdsByThreadKey, threadKey) - : { ...state.serverTerminalIdsByThreadKey, [threadKey]: serverIds }; - if ( - nextTerminalUiStateByThreadKey === state.terminalUiStateByThreadKey && - nextServerTerminalIdsByThreadKey === state.serverTerminalIdsByThreadKey - ) { - return state; - } - return { - terminalUiStateByThreadKey: nextTerminalUiStateByThreadKey, - serverTerminalIdsByThreadKey: nextServerTerminalIdsByThreadKey, - }; - }), + reconcileTerminalIds: (threadRef, serverIds, snapshotId) => { + if (threadRef.threadId.length === 0) return; + const threadKey = terminalThreadKey(threadRef); + const previous = serverObservations.get(threadKey); + const state = get(); + const suppressedIds = new Set(state.suppressedTerminalIdsByThreadKey[threadKey]); + const terminalUiStateByThreadKey = updateTerminalUiStateByThreadKey( + state.terminalUiStateByThreadKey, + threadRef, + (terminalState) => + reconcileThreadTerminalSessionIds( + terminalState, + serverIds.filter((id) => !suppressedIds.has(id)), + // A new snapshot can come from an empty manager before old sessions reattach. + previous?.snapshotId === snapshotId ? (previous?.ids ?? []) : [], + ), + ); + if (serverIds.length === 0) { + serverObservations.delete(threadKey); + } else { + serverObservations.set(threadKey, { ids: serverIds, snapshotId }); + } + if (terminalUiStateByThreadKey !== state.terminalUiStateByThreadKey) { + set({ terminalUiStateByThreadKey }); + } + }, clearTerminalUiState: (threadRef) => set((state) => { const threadKey = terminalThreadKey(threadRef); @@ -737,12 +721,10 @@ export const useTerminalUiStateStore = create()( ); const hadSuppressedTerminalIds = state.suppressedTerminalIdsByThreadKey[threadKey] !== undefined; - const hadServerTerminalIds = - state.serverTerminalIdsByThreadKey[threadKey] !== undefined; + serverObservations.delete(threadKey); if ( nextTerminalUiStateByThreadKey === state.terminalUiStateByThreadKey && - !hadSuppressedTerminalIds && - !hadServerTerminalIds + !hadSuppressedTerminalIds ) { return state; } @@ -752,10 +734,6 @@ export const useTerminalUiStateStore = create()( state.suppressedTerminalIdsByThreadKey, threadKey, ), - serverTerminalIdsByThreadKey: removeRecordEntry( - state.serverTerminalIdsByThreadKey, - threadKey, - ), }; }), removeTerminalUiState: (threadRef) => @@ -764,9 +742,8 @@ export const useTerminalUiStateStore = create()( const hadTerminalUiState = state.terminalUiStateByThreadKey[threadKey] !== undefined; const hadSuppressedTerminalIds = state.suppressedTerminalIdsByThreadKey[threadKey] !== undefined; - const hadServerTerminalIds = - state.serverTerminalIdsByThreadKey[threadKey] !== undefined; - if (!hadTerminalUiState && !hadSuppressedTerminalIds && !hadServerTerminalIds) { + serverObservations.delete(threadKey); + if (!hadTerminalUiState && !hadSuppressedTerminalIds) { return state; } return { @@ -778,19 +755,17 @@ export const useTerminalUiStateStore = create()( state.suppressedTerminalIdsByThreadKey, threadKey, ), - serverTerminalIdsByThreadKey: removeRecordEntry( - state.serverTerminalIdsByThreadKey, - threadKey, - ), }; }), removeOrphanedTerminalUiStates: (activeThreadKeys) => set((state) => { + for (const threadKey of serverObservations.keys()) { + if (!activeThreadKeys.has(threadKey)) serverObservations.delete(threadKey); + } const orphanedIds = new Set( [ ...Object.keys(state.terminalUiStateByThreadKey), ...Object.keys(state.suppressedTerminalIdsByThreadKey), - ...Object.keys(state.serverTerminalIdsByThreadKey), ].filter((key) => !activeThreadKeys.has(key)), ); if (orphanedIds.size === 0) { @@ -800,16 +775,13 @@ export const useTerminalUiStateStore = create()( const nextSuppressedTerminalIdsByThreadKey = { ...state.suppressedTerminalIdsByThreadKey, }; - const nextServerTerminalIdsByThreadKey = { ...state.serverTerminalIdsByThreadKey }; for (const id of orphanedIds) { delete nextTerminalUiStateByThreadKey[id]; delete nextSuppressedTerminalIdsByThreadKey[id]; - delete nextServerTerminalIdsByThreadKey[id]; } return { terminalUiStateByThreadKey: nextTerminalUiStateByThreadKey, suppressedTerminalIdsByThreadKey: nextSuppressedTerminalIdsByThreadKey, - serverTerminalIdsByThreadKey: nextServerTerminalIdsByThreadKey, }; }), }; diff --git a/packages/client-runtime/src/state/runtime.test.ts b/packages/client-runtime/src/state/runtime.test.ts index 59093d2d9dbdc..ac4642f20d157 100644 --- a/packages/client-runtime/src/state/runtime.test.ts +++ b/packages/client-runtime/src/state/runtime.test.ts @@ -591,10 +591,9 @@ describe("environment query lifecycle", () => { const session = { ...QUERY_RPC_SESSION, client }; yield* SubscriptionRef.set(harness.supervisorSession, Option.some(session)); const atoms = createTerminalEnvironmentAtoms(harness.runtime); - const atom = atoms.metadata({ - environmentId: QUERY_ENVIRONMENT.environmentId, - input: null, - }); + const target = { environmentId: QUERY_ENVIRONMENT.environmentId, input: null }; + const atom = atoms.metadata(target); + const feed = atoms.metadataFeed(target); const registry = AtomRegistry.make(); const observed: Array> = []; const unsubscribe = registry.subscribe( @@ -621,6 +620,8 @@ describe("environment query lifecycle", () => { yield* Queue.offer(events, { type: "snapshot", terminals: [checkout] }); yield* Deferred.await(receivedCheckout); expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]); + const initialSnapshotId = selectEnvironmentQueryData(registry.get(feed))?.snapshotId; + expect(initialSnapshotId).toBeTypeOf("symbol"); yield* SubscriptionRef.set(harness.supervisorSession, Option.some({ ...session })); yield* Queue.take(started); @@ -633,6 +634,9 @@ describe("environment query lifecycle", () => { yield* Queue.offer(events, { type: "snapshot", terminals: [] }); yield* Deferred.await(receivedEmpty); expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([]); + expect(selectEnvironmentQueryData(registry.get(feed))?.snapshotId).not.toBe( + initialSnapshotId, + ); }), ); diff --git a/packages/client-runtime/src/state/terminal.ts b/packages/client-runtime/src/state/terminal.ts index e55ff78304980..16e0723d15f64 100644 --- a/packages/client-runtime/src/state/terminal.ts +++ b/packages/client-runtime/src/state/terminal.ts @@ -33,6 +33,11 @@ import { } from "./terminalSession.ts"; import { terminalOutputText } from "./terminalOutput.ts"; +interface TerminalMetadataFeed { + readonly terminals: ReadonlyArray; + readonly snapshotId: symbol; +} + export function createTerminalEnvironmentAtoms( runtime: Atom.AtomRuntime, ) { @@ -53,6 +58,24 @@ export function createTerminalEnvironmentAtoms( readonly input: { readonly threadId: string; readonly terminalId?: string | undefined }; }) => JSON.stringify([environmentId, input.threadId, input.terminalId ?? null]); const lifecycleConcurrency = { mode: "serial" as const, key: terminalThreadKey }; + const metadataFeed = createEnvironmentSubscriptionAtomFamily(runtime, { + label: "environment-data:terminal:metadata", + subscribe: (_input: null) => + subscribe(WS_METHODS.subscribeTerminalMetadata, {}).pipe( + Stream.scan( + (): TerminalMetadataFeed => ({ terminals: [], snapshotId: Symbol() }), + (feed, event): TerminalMetadataFeed => ({ + terminals: applyTerminalMetadataStreamEvent(feed.terminals, event), + snapshotId: event.type === "snapshot" ? Symbol() : feed.snapshotId, + }), + ), + // The scan seed is not an authoritative empty server snapshot. + Stream.drop(1), + ), + }); + const terminalMetadataSummaries = Atom.family((feed: ReturnType) => + Atom.mapResult(feed, ({ terminals }) => terminals), + ); const atoms = { observe: createEnvironmentSubscriptionAtomFamily(runtime, { label: "environment-data:terminal:observe", @@ -86,15 +109,9 @@ export function createTerminalEnvironmentAtoms( ); }, }), - metadata: createEnvironmentSubscriptionAtomFamily(runtime, { - label: "environment-data:terminal:metadata", - subscribe: (_input: null) => - subscribe(WS_METHODS.subscribeTerminalMetadata, {}).pipe( - Stream.scan((): ReadonlyArray => [], applyTerminalMetadataStreamEvent), - // The scan seed is not an authoritative empty server snapshot. - Stream.drop(1), - ), - }), + metadataFeed, + metadata: (target: { readonly environmentId: EnvironmentId; readonly input: null }) => + terminalMetadataSummaries(metadataFeed(target)), open: createEnvironmentRpcCommand(runtime, { label: "environment-data:terminal:open", tag: WS_METHODS.terminalOpen, From 8886a5d0541754544d9640644fb9f0de04fd6d51 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:39:46 +0100 Subject: [PATCH 4/7] fix(web): type the drawer metadata comparison Co-authored-by: GPT 6.2 Sol --- apps/web/src/state/terminalSessions.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/state/terminalSessions.ts b/apps/web/src/state/terminalSessions.ts index a00f681e12759..0f0fd7aad68fc 100644 --- a/apps/web/src/state/terminalSessions.ts +++ b/apps/web/src/state/terminalSessions.ts @@ -251,7 +251,7 @@ const terminalDrawerSessionsFamily = Atom.family((key: string) => { snapshotId, }; }).pipe( - Atom.withEquality( + Atom.withEquality( (left, right) => left?.sessions === right?.sessions && left?.snapshotId === right?.snapshotId, ), Atom.withLabel(`web-terminal-drawer-sessions:${key}`), From ebf1e2b82dbc22fe262cee06f30d44ff60e1e945 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:50:43 +0100 Subject: [PATCH 5/7] fix(web): reconcile terminal closures across drawer reconnects Co-authored-by: GPT 6.2 Sol --- apps/server/src/terminal/Manager.ts | 2 + apps/web/src/state/terminalSessions.ts | 2 +- apps/web/src/terminalUiStateStore.test.ts | 34 +++- apps/web/src/terminalUiStateStore.ts | 162 ++++++++++-------- .../client-runtime/src/state/runtime.test.ts | 16 +- packages/client-runtime/src/state/terminal.ts | 4 +- packages/contracts/src/terminal.ts | 1 + .../mention-finds-older-linked-thread.e2e.ts | 41 +---- scripts/scenarios/t3.ts | 42 ++++- ...inal-closed-elsewhere-leaves-drawer.e2e.ts | 39 +---- 10 files changed, 181 insertions(+), 162 deletions(-) diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 141c18997304c..a294ba7f1afe2 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -1931,6 +1931,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* fileSystem.makeDirectory(logsDir, { recursive: true }).pipe(Effect.orDie); + const managerId = NodeCrypto.randomUUID(); const managerStateRef = yield* SynchronizedRef.make({ sessions: new Map(), killFibers: new Map(), @@ -3744,6 +3745,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* listener({ type: "snapshot", terminals, + managerId, }); for (const event of bufferedEvents) { diff --git a/apps/web/src/state/terminalSessions.ts b/apps/web/src/state/terminalSessions.ts index 0f0fd7aad68fc..8eaca1b774c85 100644 --- a/apps/web/src/state/terminalSessions.ts +++ b/apps/web/src/state/terminalSessions.ts @@ -235,7 +235,7 @@ export function useKnownTerminalSessions(input: { interface TerminalDrawerSessions { readonly sessions: ReadonlyArray; - readonly snapshotId: symbol; + readonly snapshotId: string | symbol; } const noTerminalDrawerSessions = Atom.make(null); diff --git a/apps/web/src/terminalUiStateStore.test.ts b/apps/web/src/terminalUiStateStore.test.ts index 4fc339e642c5a..cfc60b5829d06 100644 --- a/apps/web/src/terminalUiStateStore.test.ts +++ b/apps/web/src/terminalUiStateStore.test.ts @@ -216,8 +216,8 @@ describe("server terminal reconciliation", () => { it("preserves a vertical split while the terminals reattach to a restarted server", () => { const store = useTerminalUiStateStore.getState(); - const firstSnapshot = Symbol(); - const restartSnapshot = Symbol(); + const firstSnapshot = "manager-1"; + const restartSnapshot = "manager-2"; store.setTerminalOpen(THREAD_REF, true); store.splitTerminalVertical(THREAD_REF, "split"); const beforeRestart = layout(); @@ -234,6 +234,36 @@ describe("server terminal reconciliation", () => { expect(layout().terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID]); }); + it("drops a background terminal that closed before the drawer reloaded", async () => { + const store = useTerminalUiStateStore.getState(); + store.setTerminalOpen(THREAD_REF, true); + store.reconcileTerminalIds(THREAD_REF, [DEFAULT_THREAD_TERMINAL_ID, "old"], "manager-1"); + const { name, storage } = useTerminalUiStateStore.persist.getOptions(); + if (!name || !storage) throw new Error("Terminal layout storage is unavailable"); + const saved = await storage.getItem(name); + if (!saved) throw new Error("Terminal layout was not saved"); + store.removeTerminalUiState(THREAD_REF); + await storage.setItem(name, saved); + await useTerminalUiStateStore.persist.rehydrate(); + + store.reconcileTerminalIds(THREAD_REF, [DEFAULT_THREAD_TERMINAL_ID, "new"], "manager-1"); + + expect(layout().terminalIds).toEqual([DEFAULT_THREAD_TERMINAL_ID, "new"]); + }); + + it("keeps the surviving pane active when another client closes its split sibling", () => { + const store = useTerminalUiStateStore.getState(); + store.newTerminal(THREAD_REF, "first"); + store.newTerminal(THREAD_REF, "second"); + store.splitTerminalVertical(THREAD_REF, "split"); + store.reconcileTerminalIds(THREAD_REF, ["first", "second", "split"]); + + store.reconcileTerminalIds(THREAD_REF, ["first", "second"]); + + expect(layout().activeTerminalId).toBe("second"); + expect(layout().activeTerminalGroupId).toBe("group-second"); + }); + it("preserves a pending local split when another client opens a tab", () => { const store = useTerminalUiStateStore.getState(); store.reconcileTerminalIds(THREAD_REF, ["first"]); diff --git a/apps/web/src/terminalUiStateStore.ts b/apps/web/src/terminalUiStateStore.ts index d36e59b9e2324..6e0d88e784d47 100644 --- a/apps/web/src/terminalUiStateStore.ts +++ b/apps/web/src/terminalUiStateStore.ts @@ -456,20 +456,28 @@ function reconcileThreadTerminalSessionIds( ): ThreadTerminalUiState { const normalized = normalizeThreadTerminalUiState(state); const serverIdSet = new Set(serverIds); - const previousIdSet = new Set(previousServerIds); const localIdSet = new Set(normalized.terminalIds); - const nextIds = [ - ...normalized.terminalIds.filter((id) => serverIdSet.has(id) || !previousIdSet.has(id)), - ...serverIds.filter((id) => !localIdSet.has(id)), - ]; - if (arraysEqual(nextIds, normalized.terminalIds)) return normalized; - if (nextIds.length === 0) return getDefaultThreadTerminalUiState(); + const added = serverIds.filter((id) => !localIdSet.has(id)); + let next = + added.length === 0 + ? normalized + : normalizeThreadTerminalUiState({ + ...normalized, + terminalIds: [...normalized.terminalIds, ...added], + }); - return normalizeThreadTerminalUiState({ - ...normalized, - terminalIds: nextIds, - activeTerminalGroupId: "", - }); + for (const id of previousServerIds) { + if (id !== normalized.activeTerminalId && !serverIdSet.has(id)) { + next = closeThreadTerminal(next, id); + } + } + if ( + !serverIdSet.has(normalized.activeTerminalId) && + previousServerIds.includes(normalized.activeTerminalId) + ) { + next = closeThreadTerminal(next, normalized.activeTerminalId); + } + return next; } export function selectThreadTerminalUiState( @@ -555,7 +563,13 @@ function removeRecordEntry(record: Record, key: string): Record; terminalUiStateByThreadKey: Record; suppressedTerminalIdsByThreadKey: Record; setTerminalOpen: (threadRef: ScopedThreadRef, open: boolean) => void; @@ -573,7 +587,7 @@ interface TerminalUiStateStoreState { reconcileTerminalIds: ( threadRef: ScopedThreadRef, serverIds: string[], - snapshotId?: symbol, + snapshotId?: string | symbol, ) => void; clearTerminalUiState: (threadRef: ScopedThreadRef) => void; removeTerminalUiState: (threadRef: ScopedThreadRef) => void; @@ -583,10 +597,31 @@ interface TerminalUiStateStoreState { export const useTerminalUiStateStore = create()( persist( (set, get) => { - const serverObservations = new Map< - string, - { ids: string[]; snapshotId: symbol | undefined } - >(); + const removeTerminalUiState = (threadRef: ScopedThreadRef) => + set((state) => { + const threadKey = terminalThreadKey(threadRef); + if ( + state.terminalUiStateByThreadKey[threadKey] === undefined && + state.suppressedTerminalIdsByThreadKey[threadKey] === undefined && + state.serverObservationsByThreadKey[threadKey] === undefined + ) { + return state; + } + return { + terminalUiStateByThreadKey: removeRecordEntry( + state.terminalUiStateByThreadKey, + threadKey, + ), + suppressedTerminalIdsByThreadKey: removeRecordEntry( + state.suppressedTerminalIdsByThreadKey, + threadKey, + ), + serverObservationsByThreadKey: removeRecordEntry( + state.serverObservationsByThreadKey, + threadKey, + ), + }; + }); const updateTerminal = ( threadRef: ScopedThreadRef, @@ -622,6 +657,7 @@ export const useTerminalUiStateStore = create()( return { terminalUiStateByThreadKey: {}, + serverObservationsByThreadKey: {}, suppressedTerminalIdsByThreadKey: {}, setTerminalOpen: (threadRef, open) => { const terminalState = selectThreadTerminalUiState( @@ -688,8 +724,8 @@ export const useTerminalUiStateStore = create()( reconcileTerminalIds: (threadRef, serverIds, snapshotId) => { if (threadRef.threadId.length === 0) return; const threadKey = terminalThreadKey(threadRef); - const previous = serverObservations.get(threadKey); const state = get(); + const previous = state.serverObservationsByThreadKey[threadKey]; const suppressedIds = new Set(state.suppressedTerminalIdsByThreadKey[threadKey]); const terminalUiStateByThreadKey = updateTerminalUiStateByThreadKey( state.terminalUiStateByThreadKey, @@ -698,74 +734,44 @@ export const useTerminalUiStateStore = create()( reconcileThreadTerminalSessionIds( terminalState, serverIds.filter((id) => !suppressedIds.has(id)), - // A new snapshot can come from an empty manager before old sessions reattach. + // A different manager can start empty before old sessions reattach. previous?.snapshotId === snapshotId ? (previous?.ids ?? []) : [], ), ); - if (serverIds.length === 0) { - serverObservations.delete(threadKey); - } else { - serverObservations.set(threadKey, { ids: serverIds, snapshotId }); + // Metadata is ordered by activity, which does not change which terminals were seen. + const observedIds = [...serverIds].sort(); + let serverObservationsByThreadKey = state.serverObservationsByThreadKey; + if (observedIds.length === 0) { + serverObservationsByThreadKey = removeRecordEntry( + serverObservationsByThreadKey, + threadKey, + ); + } else if ( + !previous || + previous.snapshotId !== snapshotId || + !arraysEqual(previous.ids, observedIds) + ) { + serverObservationsByThreadKey = { + ...serverObservationsByThreadKey, + [threadKey]: { ids: observedIds, snapshotId }, + }; } - if (terminalUiStateByThreadKey !== state.terminalUiStateByThreadKey) { - set({ terminalUiStateByThreadKey }); + if ( + terminalUiStateByThreadKey !== state.terminalUiStateByThreadKey || + serverObservationsByThreadKey !== state.serverObservationsByThreadKey + ) { + set({ terminalUiStateByThreadKey, serverObservationsByThreadKey }); } }, - clearTerminalUiState: (threadRef) => - set((state) => { - const threadKey = terminalThreadKey(threadRef); - const nextTerminalUiStateByThreadKey = updateTerminalUiStateByThreadKey( - state.terminalUiStateByThreadKey, - threadRef, - () => createDefaultThreadTerminalUiState(), - ); - const hadSuppressedTerminalIds = - state.suppressedTerminalIdsByThreadKey[threadKey] !== undefined; - serverObservations.delete(threadKey); - if ( - nextTerminalUiStateByThreadKey === state.terminalUiStateByThreadKey && - !hadSuppressedTerminalIds - ) { - return state; - } - return { - terminalUiStateByThreadKey: nextTerminalUiStateByThreadKey, - suppressedTerminalIdsByThreadKey: removeRecordEntry( - state.suppressedTerminalIdsByThreadKey, - threadKey, - ), - }; - }), - removeTerminalUiState: (threadRef) => - set((state) => { - const threadKey = terminalThreadKey(threadRef); - const hadTerminalUiState = state.terminalUiStateByThreadKey[threadKey] !== undefined; - const hadSuppressedTerminalIds = - state.suppressedTerminalIdsByThreadKey[threadKey] !== undefined; - serverObservations.delete(threadKey); - if (!hadTerminalUiState && !hadSuppressedTerminalIds) { - return state; - } - return { - terminalUiStateByThreadKey: removeRecordEntry( - state.terminalUiStateByThreadKey, - threadKey, - ), - suppressedTerminalIdsByThreadKey: removeRecordEntry( - state.suppressedTerminalIdsByThreadKey, - threadKey, - ), - }; - }), + clearTerminalUiState: removeTerminalUiState, + removeTerminalUiState, removeOrphanedTerminalUiStates: (activeThreadKeys) => set((state) => { - for (const threadKey of serverObservations.keys()) { - if (!activeThreadKeys.has(threadKey)) serverObservations.delete(threadKey); - } const orphanedIds = new Set( [ ...Object.keys(state.terminalUiStateByThreadKey), ...Object.keys(state.suppressedTerminalIdsByThreadKey), + ...Object.keys(state.serverObservationsByThreadKey), ].filter((key) => !activeThreadKeys.has(key)), ); if (orphanedIds.size === 0) { @@ -775,13 +781,16 @@ export const useTerminalUiStateStore = create()( const nextSuppressedTerminalIdsByThreadKey = { ...state.suppressedTerminalIdsByThreadKey, }; + const serverObservationsByThreadKey = { ...state.serverObservationsByThreadKey }; for (const id of orphanedIds) { delete nextTerminalUiStateByThreadKey[id]; delete nextSuppressedTerminalIdsByThreadKey[id]; + delete serverObservationsByThreadKey[id]; } return { terminalUiStateByThreadKey: nextTerminalUiStateByThreadKey, suppressedTerminalIdsByThreadKey: nextSuppressedTerminalIdsByThreadKey, + serverObservationsByThreadKey, }; }), }; @@ -793,6 +802,11 @@ export const useTerminalUiStateStore = create()( migrate: migratePersistedTerminalUiStateStoreState, partialize: (state) => ({ terminalUiStateByThreadKey: state.terminalUiStateByThreadKey, + serverObservationsByThreadKey: Object.fromEntries( + Object.entries(state.serverObservationsByThreadKey).filter( + ([, observation]) => typeof observation.snapshotId === "string", + ), + ), }), }, ), diff --git a/packages/client-runtime/src/state/runtime.test.ts b/packages/client-runtime/src/state/runtime.test.ts index ac4642f20d157..0a8af6c77a0ae 100644 --- a/packages/client-runtime/src/state/runtime.test.ts +++ b/packages/client-runtime/src/state/runtime.test.ts @@ -560,7 +560,7 @@ describe("finite environment subscription lifecycle", () => { describe("environment query lifecycle", () => { it.effect( - "terminal metadata waits for snapshots and retains known sessions across restarts", + "terminal metadata retains known sessions until a new snapshot and keeps the manager identity", () => Effect.gen(function* () { const harness = yield* makeEnvironmentQueryHarness(Effect.void); @@ -617,11 +617,15 @@ describe("environment query lifecycle", () => { expect(selectEnvironmentQueryData(registry.get(atom))).toBeNull(); expect(observed).toEqual([]); - yield* Queue.offer(events, { type: "snapshot", terminals: [checkout] }); + yield* Queue.offer(events, { + type: "snapshot", + terminals: [checkout], + managerId: "manager-1", + }); yield* Deferred.await(receivedCheckout); expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]); const initialSnapshotId = selectEnvironmentQueryData(registry.get(feed))?.snapshotId; - expect(initialSnapshotId).toBeTypeOf("symbol"); + expect(initialSnapshotId).toBe("manager-1"); yield* SubscriptionRef.set(harness.supervisorSession, Option.some({ ...session })); yield* Queue.take(started); @@ -631,12 +635,10 @@ describe("environment query lifecycle", () => { yield* Queue.take(started); expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]); - yield* Queue.offer(events, { type: "snapshot", terminals: [] }); + yield* Queue.offer(events, { type: "snapshot", terminals: [], managerId: "manager-1" }); yield* Deferred.await(receivedEmpty); expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([]); - expect(selectEnvironmentQueryData(registry.get(feed))?.snapshotId).not.toBe( - initialSnapshotId, - ); + expect(selectEnvironmentQueryData(registry.get(feed))?.snapshotId).toBe(initialSnapshotId); }), ); diff --git a/packages/client-runtime/src/state/terminal.ts b/packages/client-runtime/src/state/terminal.ts index 16e0723d15f64..572c116a4b7e3 100644 --- a/packages/client-runtime/src/state/terminal.ts +++ b/packages/client-runtime/src/state/terminal.ts @@ -35,7 +35,7 @@ import { terminalOutputText } from "./terminalOutput.ts"; interface TerminalMetadataFeed { readonly terminals: ReadonlyArray; - readonly snapshotId: symbol; + readonly snapshotId: string | symbol; } export function createTerminalEnvironmentAtoms( @@ -66,7 +66,7 @@ export function createTerminalEnvironmentAtoms( (): TerminalMetadataFeed => ({ terminals: [], snapshotId: Symbol() }), (feed, event): TerminalMetadataFeed => ({ terminals: applyTerminalMetadataStreamEvent(feed.terminals, event), - snapshotId: event.type === "snapshot" ? Symbol() : feed.snapshotId, + snapshotId: event.type === "snapshot" ? (event.managerId ?? Symbol()) : feed.snapshotId, }), ), // The scan seed is not an authoritative empty server snapshot. diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts index fea5f216f80bd..09678600764b2 100644 --- a/packages/contracts/src/terminal.ts +++ b/packages/contracts/src/terminal.ts @@ -281,6 +281,7 @@ export type TerminalSummary = typeof TerminalSummary.Type; const TerminalMetadataSnapshotEvent = Schema.Struct({ type: Schema.Literal("snapshot"), terminals: Schema.Array(TerminalSummary), + managerId: Schema.optional(Schema.String), }); const TerminalMetadataUpsertEvent = Schema.Struct({ diff --git a/scripts/scenarios/mention-finds-older-linked-thread.e2e.ts b/scripts/scenarios/mention-finds-older-linked-thread.e2e.ts index 064f04fb92924..e6e59dd00b720 100644 --- a/scripts/scenarios/mention-finds-older-linked-thread.e2e.ts +++ b/scripts/scenarios/mention-finds-older-linked-thread.e2e.ts @@ -1,54 +1,17 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; -import * as NodeWS from "@effect/platform-node/NodeWS"; -import { - CommandId, - ORCHESTRATION_PROTOCOL_VERSION, - ThreadId, - WsRpcGroup, -} from "@t3tools/contracts"; +import { CommandId, ThreadId } from "@t3tools/contracts"; import { expect } from "e2e"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; -import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; -import { RpcClient, RpcSerialization } from "effect/rpc"; -import { Socket } from "effect/socket"; import { T3_HOME } from "../e2e.config.ts"; import { SECOND_HOME, startSecondServer } from "./second-server.ts"; -import { makeState, runPromise, test, WEB } from "./t3.ts"; +import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; // A shell keeps an environment's 25 newest settled threads; older ones come from search. const NEWER_SETTLED = 25; -/** The typed RPC client of the server on `home` at `origin`, signed in through its own CLI. */ -const rpcClient = Effect.fn("scenario.rpcClient")(function* (home: string, origin: string) { - const issued = yield* makeState(home).cli(["auth", "session", "issue", "--token-only"]); - const { ticket } = yield* HttpClient.execute( - HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe( - HttpClientRequest.bearerToken(issued.stdout.trim()), - ), - ).pipe( - Effect.flatMap(HttpClientResponse.filterStatusOk), - Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))), - Effect.provide(FetchHttpClient.layer), - ); - // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns. - const protocol = yield* Layer.build( - RpcClient.layerProtocolSocket().pipe( - Layer.provide( - Socket.layerWebSocket( - `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`, - ), - ), - Layer.provide(RpcSerialization.layerJson), - Layer.provide(NodeWS.layerWebSocketConstructor), - ), - ); - return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol)); -}); - const uuid = Effect.flatMap(SecureRandom.SecureRandom, (random) => random.uuidV4()); const decodePairing = Schema.decodeEffect( Schema.fromJsonString(Schema.Struct({ credential: Schema.String })), diff --git a/scripts/scenarios/t3.ts b/scripts/scenarios/t3.ts index 132322ef4f216..b08bcbf54732f 100644 --- a/scripts/scenarios/t3.ts +++ b/scripts/scenarios/t3.ts @@ -2,18 +2,29 @@ // app. `t3-mobile.ts` is the same for the iOS app. import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as NodeWS from "@effect/platform-node/NodeWS"; import { test as base } from "@e2e-dev/web"; import { expect } from "e2e"; -import { CommandId, EnvironmentHttpApi, type ProjectMutation, ProjectId } from "@t3tools/contracts"; +import { + CommandId, + EnvironmentHttpApi, + ORCHESTRATION_PROTOCOL_VERSION, + type ProjectMutation, + ProjectId, + WsRpcGroup, +} from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as HttpApiClient from "effect/http-api/HttpApiClient"; +import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; -import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http"; +import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; +import { RpcClient, RpcSerialization } from "effect/rpc"; +import { Socket } from "effect/socket"; import { APP_DIR, T3_HOME } from "../e2e.config.ts"; import { run, ScenarioError } from "./shell.ts"; @@ -53,6 +64,33 @@ export interface T3 extends T3State { export const runPromise = (effect: Effect.Effect) => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer))); +/** The typed RPC client of the server on `home` at `origin`, signed in through its own CLI. */ +export const rpcClient = Effect.fn("scenario.rpcClient")(function* (home: string, origin: string) { + const issued = yield* makeState(home).cli(["auth", "session", "issue", "--token-only"]); + const { ticket } = yield* HttpClient.execute( + HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe( + HttpClientRequest.bearerToken(issued.stdout.trim()), + ), + ).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))), + Effect.provide(FetchHttpClient.layer), + ); + // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns. + const protocol = yield* Layer.build( + RpcClient.layerProtocolSocket().pipe( + Layer.provide( + Socket.layerWebSocket( + `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`, + ), + ), + Layer.provide(RpcSerialization.layerJson), + Layer.provide(NodeWS.layerWebSocketConstructor), + ), + ); + return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol)); +}); + const decodeLaunched = Schema.decodeUnknownEffect( Schema.fromJsonString(Schema.Struct({ threadId: Schema.String })), ); diff --git a/scripts/scenarios/terminal-closed-elsewhere-leaves-drawer.e2e.ts b/scripts/scenarios/terminal-closed-elsewhere-leaves-drawer.e2e.ts index 938f062b1f611..35e737ba7544b 100644 --- a/scripts/scenarios/terminal-closed-elsewhere-leaves-drawer.e2e.ts +++ b/scripts/scenarios/terminal-closed-elsewhere-leaves-drawer.e2e.ts @@ -1,40 +1,9 @@ -import * as NodeWS from "@effect/platform-node/NodeWS"; -import { ORCHESTRATION_PROTOCOL_VERSION, ThreadId, WsRpcGroup } from "@t3tools/contracts"; +import { ThreadId } from "@t3tools/contracts"; import { expect } from "e2e"; import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Schema from "effect/Schema"; -import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; -import { RpcClient, RpcSerialization } from "effect/rpc"; -import { Socket } from "effect/socket"; import { T3_HOME } from "../e2e.config.ts"; -import { makeState, runPromise, test, WEB } from "./t3.ts"; - -const terminalClient = Effect.fn("scenario.terminalClient")(function* (origin: string) { - const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]); - const { ticket } = yield* HttpClient.execute( - HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe( - HttpClientRequest.bearerToken(issued.stdout.trim()), - ), - ).pipe( - Effect.flatMap(HttpClientResponse.filterStatusOk), - Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))), - Effect.provide(FetchHttpClient.layer), - ); - const protocol = yield* Layer.build( - RpcClient.layerProtocolSocket().pipe( - Layer.provide( - Socket.layerWebSocket( - `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`, - ), - ), - Layer.provide(RpcSerialization.layerJson), - Layer.provide(NodeWS.layerWebSocketConstructor), - ), - ); - return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol)); -}); +import { rpcClient, runPromise, test, WEB } from "./t3.ts"; test("The drawer removes a terminal closed by another client", WEB, async ({ t3, app, screen }) => { const cwd = await t3.project("demo"); @@ -46,7 +15,7 @@ test("The drawer removes a terminal closed by another client", WEB, async ({ t3, await runPromise( Effect.gen(function* () { - const client = yield* terminalClient(origin); + const client = yield* rpcClient(T3_HOME, origin); for (const terminalId of [kept, closed]) { yield* client["terminal.open"]({ threadId, terminalId, cwd }); } @@ -60,7 +29,7 @@ test("The drawer removes a terminal closed by another client", WEB, async ({ t3, await runPromise( Effect.gen(function* () { - const client = yield* terminalClient(origin); + const client = yield* rpcClient(T3_HOME, origin); yield* client["terminal.close"]({ threadId, terminalId: closed, deleteHistory: true }); }).pipe(Effect.scoped), ); From 1035cb2b01aff48be3656401dc68e4e8711cfbf4 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 19 Nov 2026 07:53:29 +0100 Subject: [PATCH 6/7] test(web): preserve the original terminal drawer reproduction Co-authored-by: GPT 6.2 Sol --- .../mention-finds-older-linked-thread.e2e.ts | 41 +++++++++++++++++- scripts/scenarios/t3.ts | 42 +------------------ ...inal-closed-elsewhere-leaves-drawer.e2e.ts | 39 +++++++++++++++-- 3 files changed, 76 insertions(+), 46 deletions(-) diff --git a/scripts/scenarios/mention-finds-older-linked-thread.e2e.ts b/scripts/scenarios/mention-finds-older-linked-thread.e2e.ts index e6e59dd00b720..064f04fb92924 100644 --- a/scripts/scenarios/mention-finds-older-linked-thread.e2e.ts +++ b/scripts/scenarios/mention-finds-older-linked-thread.e2e.ts @@ -1,17 +1,54 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; -import { CommandId, ThreadId } from "@t3tools/contracts"; +import * as NodeWS from "@effect/platform-node/NodeWS"; +import { + CommandId, + ORCHESTRATION_PROTOCOL_VERSION, + ThreadId, + WsRpcGroup, +} from "@t3tools/contracts"; import { expect } from "e2e"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; +import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; +import { RpcClient, RpcSerialization } from "effect/rpc"; +import { Socket } from "effect/socket"; import { T3_HOME } from "../e2e.config.ts"; import { SECOND_HOME, startSecondServer } from "./second-server.ts"; -import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; // A shell keeps an environment's 25 newest settled threads; older ones come from search. const NEWER_SETTLED = 25; +/** The typed RPC client of the server on `home` at `origin`, signed in through its own CLI. */ +const rpcClient = Effect.fn("scenario.rpcClient")(function* (home: string, origin: string) { + const issued = yield* makeState(home).cli(["auth", "session", "issue", "--token-only"]); + const { ticket } = yield* HttpClient.execute( + HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe( + HttpClientRequest.bearerToken(issued.stdout.trim()), + ), + ).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))), + Effect.provide(FetchHttpClient.layer), + ); + // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns. + const protocol = yield* Layer.build( + RpcClient.layerProtocolSocket().pipe( + Layer.provide( + Socket.layerWebSocket( + `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`, + ), + ), + Layer.provide(RpcSerialization.layerJson), + Layer.provide(NodeWS.layerWebSocketConstructor), + ), + ); + return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol)); +}); + const uuid = Effect.flatMap(SecureRandom.SecureRandom, (random) => random.uuidV4()); const decodePairing = Schema.decodeEffect( Schema.fromJsonString(Schema.Struct({ credential: Schema.String })), diff --git a/scripts/scenarios/t3.ts b/scripts/scenarios/t3.ts index b08bcbf54732f..132322ef4f216 100644 --- a/scripts/scenarios/t3.ts +++ b/scripts/scenarios/t3.ts @@ -2,29 +2,18 @@ // app. `t3-mobile.ts` is the same for the iOS app. import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import * as NodeWS from "@effect/platform-node/NodeWS"; import { test as base } from "@e2e-dev/web"; import { expect } from "e2e"; -import { - CommandId, - EnvironmentHttpApi, - ORCHESTRATION_PROTOCOL_VERSION, - type ProjectMutation, - ProjectId, - WsRpcGroup, -} from "@t3tools/contracts"; +import { CommandId, EnvironmentHttpApi, type ProjectMutation, ProjectId } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as HttpApiClient from "effect/http-api/HttpApiClient"; -import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; -import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; -import { RpcClient, RpcSerialization } from "effect/rpc"; -import { Socket } from "effect/socket"; +import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http"; import { APP_DIR, T3_HOME } from "../e2e.config.ts"; import { run, ScenarioError } from "./shell.ts"; @@ -64,33 +53,6 @@ export interface T3 extends T3State { export const runPromise = (effect: Effect.Effect) => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer))); -/** The typed RPC client of the server on `home` at `origin`, signed in through its own CLI. */ -export const rpcClient = Effect.fn("scenario.rpcClient")(function* (home: string, origin: string) { - const issued = yield* makeState(home).cli(["auth", "session", "issue", "--token-only"]); - const { ticket } = yield* HttpClient.execute( - HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe( - HttpClientRequest.bearerToken(issued.stdout.trim()), - ), - ).pipe( - Effect.flatMap(HttpClientResponse.filterStatusOk), - Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))), - Effect.provide(FetchHttpClient.layer), - ); - // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns. - const protocol = yield* Layer.build( - RpcClient.layerProtocolSocket().pipe( - Layer.provide( - Socket.layerWebSocket( - `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`, - ), - ), - Layer.provide(RpcSerialization.layerJson), - Layer.provide(NodeWS.layerWebSocketConstructor), - ), - ); - return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol)); -}); - const decodeLaunched = Schema.decodeUnknownEffect( Schema.fromJsonString(Schema.Struct({ threadId: Schema.String })), ); diff --git a/scripts/scenarios/terminal-closed-elsewhere-leaves-drawer.e2e.ts b/scripts/scenarios/terminal-closed-elsewhere-leaves-drawer.e2e.ts index 35e737ba7544b..938f062b1f611 100644 --- a/scripts/scenarios/terminal-closed-elsewhere-leaves-drawer.e2e.ts +++ b/scripts/scenarios/terminal-closed-elsewhere-leaves-drawer.e2e.ts @@ -1,9 +1,40 @@ -import { ThreadId } from "@t3tools/contracts"; +import * as NodeWS from "@effect/platform-node/NodeWS"; +import { ORCHESTRATION_PROTOCOL_VERSION, ThreadId, WsRpcGroup } from "@t3tools/contracts"; import { expect } from "e2e"; import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; +import { RpcClient, RpcSerialization } from "effect/rpc"; +import { Socket } from "effect/socket"; import { T3_HOME } from "../e2e.config.ts"; -import { rpcClient, runPromise, test, WEB } from "./t3.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +const terminalClient = Effect.fn("scenario.terminalClient")(function* (origin: string) { + const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]); + const { ticket } = yield* HttpClient.execute( + HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe( + HttpClientRequest.bearerToken(issued.stdout.trim()), + ), + ).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))), + Effect.provide(FetchHttpClient.layer), + ); + const protocol = yield* Layer.build( + RpcClient.layerProtocolSocket().pipe( + Layer.provide( + Socket.layerWebSocket( + `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`, + ), + ), + Layer.provide(RpcSerialization.layerJson), + Layer.provide(NodeWS.layerWebSocketConstructor), + ), + ); + return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol)); +}); test("The drawer removes a terminal closed by another client", WEB, async ({ t3, app, screen }) => { const cwd = await t3.project("demo"); @@ -15,7 +46,7 @@ test("The drawer removes a terminal closed by another client", WEB, async ({ t3, await runPromise( Effect.gen(function* () { - const client = yield* rpcClient(T3_HOME, origin); + const client = yield* terminalClient(origin); for (const terminalId of [kept, closed]) { yield* client["terminal.open"]({ threadId, terminalId, cwd }); } @@ -29,7 +60,7 @@ test("The drawer removes a terminal closed by another client", WEB, async ({ t3, await runPromise( Effect.gen(function* () { - const client = yield* rpcClient(T3_HOME, origin); + const client = yield* terminalClient(origin); yield* client["terminal.close"]({ threadId, terminalId: closed, deleteHistory: true }); }).pipe(Effect.scoped), ); From cd556c022cccf20a19a32b686f45df965dfdcc3d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 07:16:01 +0000 Subject: [PATCH 7/7] refactor: share the scenario RPC client and trim drawer reconciliation tests Move the authenticated WsRpcGroup client into scripts/scenarios/t3.ts so the terminal-drawer and mention scenarios share one ticket and socket setup, fold the reconciliation cases into the existing store suite, and drop the last-terminal reset case that closing the last terminal already covers. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/terminalUiStateStore.test.ts | 30 +++---------- .../mention-finds-older-linked-thread.e2e.ts | 41 +----------------- scripts/scenarios/t3.ts | 42 ++++++++++++++++++- ...inal-closed-elsewhere-leaves-drawer.e2e.ts | 39 ++--------------- 4 files changed, 52 insertions(+), 100 deletions(-) diff --git a/apps/web/src/terminalUiStateStore.test.ts b/apps/web/src/terminalUiStateStore.test.ts index cfc60b5829d06..6b043606f564b 100644 --- a/apps/web/src/terminalUiStateStore.test.ts +++ b/apps/web/src/terminalUiStateStore.test.ts @@ -12,13 +12,18 @@ import { DEFAULT_THREAD_TERMINAL_ID } from "./types"; const THREAD_ID = ThreadId.make("thread-1"); const THREAD_REF = scopeThreadRef("environment-a" as never, THREAD_ID); const OTHER_THREAD_REF = scopeThreadRef("environment-b" as never, THREAD_ID); +const layout = () => + selectThreadTerminalUiState( + useTerminalUiStateStore.getState().terminalUiStateByThreadKey, + THREAD_REF, + ); describe("terminalUiStateStore actions", () => { beforeEach(() => { - useTerminalUiStateStore.getState().removeOrphanedTerminalUiStates(new Set()); useTerminalUiStateStore.persist.clearStorage(); useTerminalUiStateStore.setState({ terminalUiStateByThreadKey: {}, + serverObservationsByThreadKey: {}, suppressedTerminalIdsByThreadKey: {}, }); }); @@ -201,18 +206,6 @@ describe("terminalUiStateStore actions", () => { store.reconcileTerminalIds(THREAD_REF, [DEFAULT_THREAD_TERMINAL_ID]); expect(terminalIds()).toEqual([DEFAULT_THREAD_TERMINAL_ID, "term-3"]); }); -}); - -describe("server terminal reconciliation", () => { - const layout = () => - selectThreadTerminalUiState( - useTerminalUiStateStore.getState().terminalUiStateByThreadKey, - THREAD_REF, - ); - - beforeEach(() => { - useTerminalUiStateStore.getState().removeTerminalUiState(THREAD_REF); - }); it("preserves a vertical split while the terminals reattach to a restarted server", () => { const store = useTerminalUiStateStore.getState(); @@ -278,15 +271,4 @@ describe("server terminal reconciliation", () => { ]); expect(layout().activeTerminalId).toBe("pending"); }); - - it("resets the drawer when another client closes the last terminal", () => { - const store = useTerminalUiStateStore.getState(); - const defaultLayout = layout(); - store.setTerminalOpen(THREAD_REF, true); - store.reconcileTerminalIds(THREAD_REF, [DEFAULT_THREAD_TERMINAL_ID]); - - store.reconcileTerminalIds(THREAD_REF, []); - - expect(layout()).toEqual(defaultLayout); - }); }); diff --git a/scripts/scenarios/mention-finds-older-linked-thread.e2e.ts b/scripts/scenarios/mention-finds-older-linked-thread.e2e.ts index 064f04fb92924..e6e59dd00b720 100644 --- a/scripts/scenarios/mention-finds-older-linked-thread.e2e.ts +++ b/scripts/scenarios/mention-finds-older-linked-thread.e2e.ts @@ -1,54 +1,17 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; -import * as NodeWS from "@effect/platform-node/NodeWS"; -import { - CommandId, - ORCHESTRATION_PROTOCOL_VERSION, - ThreadId, - WsRpcGroup, -} from "@t3tools/contracts"; +import { CommandId, ThreadId } from "@t3tools/contracts"; import { expect } from "e2e"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; -import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; -import { RpcClient, RpcSerialization } from "effect/rpc"; -import { Socket } from "effect/socket"; import { T3_HOME } from "../e2e.config.ts"; import { SECOND_HOME, startSecondServer } from "./second-server.ts"; -import { makeState, runPromise, test, WEB } from "./t3.ts"; +import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; // A shell keeps an environment's 25 newest settled threads; older ones come from search. const NEWER_SETTLED = 25; -/** The typed RPC client of the server on `home` at `origin`, signed in through its own CLI. */ -const rpcClient = Effect.fn("scenario.rpcClient")(function* (home: string, origin: string) { - const issued = yield* makeState(home).cli(["auth", "session", "issue", "--token-only"]); - const { ticket } = yield* HttpClient.execute( - HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe( - HttpClientRequest.bearerToken(issued.stdout.trim()), - ), - ).pipe( - Effect.flatMap(HttpClientResponse.filterStatusOk), - Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))), - Effect.provide(FetchHttpClient.layer), - ); - // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns. - const protocol = yield* Layer.build( - RpcClient.layerProtocolSocket().pipe( - Layer.provide( - Socket.layerWebSocket( - `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`, - ), - ), - Layer.provide(RpcSerialization.layerJson), - Layer.provide(NodeWS.layerWebSocketConstructor), - ), - ); - return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol)); -}); - const uuid = Effect.flatMap(SecureRandom.SecureRandom, (random) => random.uuidV4()); const decodePairing = Schema.decodeEffect( Schema.fromJsonString(Schema.Struct({ credential: Schema.String })), diff --git a/scripts/scenarios/t3.ts b/scripts/scenarios/t3.ts index 132322ef4f216..29a05573b3425 100644 --- a/scripts/scenarios/t3.ts +++ b/scripts/scenarios/t3.ts @@ -2,18 +2,29 @@ // app. `t3-mobile.ts` is the same for the iOS app. import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as NodeWS from "@effect/platform-node/NodeWS"; import { test as base } from "@e2e-dev/web"; import { expect } from "e2e"; -import { CommandId, EnvironmentHttpApi, type ProjectMutation, ProjectId } from "@t3tools/contracts"; +import { + CommandId, + EnvironmentHttpApi, + ORCHESTRATION_PROTOCOL_VERSION, + type ProjectMutation, + ProjectId, + WsRpcGroup, +} from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as HttpApiClient from "effect/http-api/HttpApiClient"; +import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; -import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http"; +import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; +import { RpcClient, RpcSerialization } from "effect/rpc"; +import { Socket } from "effect/socket"; import { APP_DIR, T3_HOME } from "../e2e.config.ts"; import { run, ScenarioError } from "./shell.ts"; @@ -234,6 +245,33 @@ const environmentId = (baseUrl: string) => Effect.provide(FetchHttpClient.layer), ); +/** The typed RPC client of the server on `home` at `origin`, signed in through its own CLI. */ +export const rpcClient = Effect.fn("scenario.rpcClient")(function* (home: string, origin: string) { + const issued = yield* makeState(home).cli(["auth", "session", "issue", "--token-only"]); + const { ticket } = yield* HttpClient.execute( + HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe( + HttpClientRequest.bearerToken(issued.stdout.trim()), + ), + ).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))), + Effect.provide(FetchHttpClient.layer), + ); + // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns. + const protocol = yield* Layer.build( + RpcClient.layerProtocolSocket().pipe( + Layer.provide( + Socket.layerWebSocket( + `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`, + ), + ), + Layer.provide(RpcSerialization.layerJson), + Layer.provide(NodeWS.layerWebSocketConstructor), + ), + ); + return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol)); +}); + export const test = base.extend<{ t3: T3 }>({ t3: async ({ app, browser }, use) => { const { state, cleanup } = makeState(T3_HOME); diff --git a/scripts/scenarios/terminal-closed-elsewhere-leaves-drawer.e2e.ts b/scripts/scenarios/terminal-closed-elsewhere-leaves-drawer.e2e.ts index 938f062b1f611..35e737ba7544b 100644 --- a/scripts/scenarios/terminal-closed-elsewhere-leaves-drawer.e2e.ts +++ b/scripts/scenarios/terminal-closed-elsewhere-leaves-drawer.e2e.ts @@ -1,40 +1,9 @@ -import * as NodeWS from "@effect/platform-node/NodeWS"; -import { ORCHESTRATION_PROTOCOL_VERSION, ThreadId, WsRpcGroup } from "@t3tools/contracts"; +import { ThreadId } from "@t3tools/contracts"; import { expect } from "e2e"; import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Schema from "effect/Schema"; -import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; -import { RpcClient, RpcSerialization } from "effect/rpc"; -import { Socket } from "effect/socket"; import { T3_HOME } from "../e2e.config.ts"; -import { makeState, runPromise, test, WEB } from "./t3.ts"; - -const terminalClient = Effect.fn("scenario.terminalClient")(function* (origin: string) { - const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]); - const { ticket } = yield* HttpClient.execute( - HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe( - HttpClientRequest.bearerToken(issued.stdout.trim()), - ), - ).pipe( - Effect.flatMap(HttpClientResponse.filterStatusOk), - Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))), - Effect.provide(FetchHttpClient.layer), - ); - const protocol = yield* Layer.build( - RpcClient.layerProtocolSocket().pipe( - Layer.provide( - Socket.layerWebSocket( - `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`, - ), - ), - Layer.provide(RpcSerialization.layerJson), - Layer.provide(NodeWS.layerWebSocketConstructor), - ), - ); - return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol)); -}); +import { rpcClient, runPromise, test, WEB } from "./t3.ts"; test("The drawer removes a terminal closed by another client", WEB, async ({ t3, app, screen }) => { const cwd = await t3.project("demo"); @@ -46,7 +15,7 @@ test("The drawer removes a terminal closed by another client", WEB, async ({ t3, await runPromise( Effect.gen(function* () { - const client = yield* terminalClient(origin); + const client = yield* rpcClient(T3_HOME, origin); for (const terminalId of [kept, closed]) { yield* client["terminal.open"]({ threadId, terminalId, cwd }); } @@ -60,7 +29,7 @@ test("The drawer removes a terminal closed by another client", WEB, async ({ t3, await runPromise( Effect.gen(function* () { - const client = yield* terminalClient(origin); + const client = yield* rpcClient(T3_HOME, origin); yield* client["terminal.close"]({ threadId, terminalId: closed, deleteHistory: true }); }).pipe(Effect.scoped), );