TypeScript
fix(clients): keep a checkout terminal off the thread's worktree (#16039)
Alex Southwell62880642c084
diff --git a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsxindex 239fbeda7d3..c43a50c722b 100644--- a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx+++ b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx@@ -70,7 +70,7 @@ import {TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS,} from "./terminalBufferReplay";import {- resolveTerminalOpenLocation,+ useInitialTerminalLaunchLocation,takePendingTerminalLaunch,type PendingTerminalLaunch,} from "./terminalLaunchContext";@@ -396,36 +396,25 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)requestedTerminalId === null &&runningSession !== null &&runningSession.target.terminalId !== terminalId;- const launchLocationCandidate = useMemo(() => {- if (!selectedThread || !selectedThreadProject?.workspaceRoot) {- return null;- }- if (pendingLaunch) {- return {- cwd: pendingLaunch.cwd,- worktreePath: pendingLaunch.worktreePath,- };- }- return resolveTerminalOpenLocation({- terminalLocation: activeKnownSession?.state.summary ?? null,- activeSessionLocation: activeKnownSession?.state.summary ?? null,- workspaceRoot: selectedThreadProject.workspaceRoot,- threadShellWorktreePath: selectedThread.worktreePath ?? null,- threadDetailWorktreePath: selectedThreadDetailWorktreePath,- });- }, [- activeKnownSession?.state.summary,+ const launchLocation = useInitialTerminalLaunchLocation({+ targetKey: launchTargetKey,pendingLaunch,- selectedThread,- selectedThreadDetailWorktreePath,- selectedThreadProject?.workspaceRoot,- ]);- const [initialLaunchLocationEntry, setInitialLaunchLocationEntry] = useState(() => ({- key: launchTargetKey,- location: launchLocationCandidate,- }));- const launchLocation =- initialLaunchLocationEntry.key === launchTargetKey ? initialLaunchLocationEntry.location : null;+ hasResolvedPendingLaunch,+ isAuthenticated,+ canRead: canReadTerminal,+ canOperate: canOperateTerminal,+ hasLoadedSessions: knownSessions !== null,+ location:+ selectedThread && selectedThreadProject?.workspaceRoot+ ? {+ terminalLocation: activeKnownSession?.state.summary ?? null,+ activeSessionLocation: activeKnownSession?.state.summary ?? null,+ workspaceRoot: selectedThreadProject.workspaceRoot,+ threadShellWorktreePath: selectedThread.worktreePath ?? null,+ threadDetailWorktreePath: selectedThreadDetailWorktreePath,+ }+ : null,+ });const terminalAttachInput = useMemo(() =>selectedThread !== null &&@@ -670,27 +659,6 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)});}, [cachedRouteGridSize, initialAttachGridEntry.key, launchTargetKey]);- useEffect(() => {- if (- initialLaunchLocationEntry.key === launchTargetKey &&- initialLaunchLocationEntry.location !== null- ) {- return;- }- if (initialLaunchLocationEntry.key === launchTargetKey && launchLocationCandidate === null) {- return;- }- setInitialLaunchLocationEntry({- key: launchTargetKey,- location: launchLocationCandidate,- });- }, [- initialLaunchLocationEntry.key,- initialLaunchLocationEntry.location,- launchLocationCandidate,- launchTargetKey,- ]);-useEffect(() => {if (!shouldRedirectToRunningTerminal || !selectedThread || !runningSession) {return;@@ -1243,6 +1211,12 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)"This connection does not have permission to view terminals."}/>+ ) : canOperateTerminal && launchLocation === null ? (+ sessionsError !== null ? (+ <EmptyState title="Could not load terminals" detail={sessionsError} />+ ) : (+ <EmptyState title="Loading terminals" detail="Reading existing terminal sessions." />+ )) : !canOperateTerminal && !hasTerminalTarget && sessionsPending ? (<EmptyState title="Loading terminals" detail="Reading existing terminal sessions." />) : !canOperateTerminal && !hasTerminalTarget && sessionsError !== null ? (diff --git a/apps/mobile/src/features/terminal/terminalLaunchContext.test.ts b/apps/mobile/src/features/terminal/terminalLaunchContext.test.tsindex 470acffa3d4..f68dac9cefd 100644--- a/apps/mobile/src/features/terminal/terminalLaunchContext.test.ts+++ b/apps/mobile/src/features/terminal/terminalLaunchContext.test.ts@@ -1,4 +1,6 @@-import { describe, expect, it } from "vite-plus/test";+import * as NodeModule from "node:module";+import { act, createElement, useEffect, type ReactNode } from "react";+import { describe, expect, it, vi } from "vite-plus/test";import { EnvironmentId, ThreadId } from "@t3tools/contracts";import {@@ -6,6 +8,7 @@ import {resolveTerminalOpenLocation,stagePendingTerminalLaunch,takePendingTerminalLaunch,+ useInitialTerminalLaunchLocation,} from "./terminalLaunchContext";describe("resolvePreferredThreadWorktreePath", () => {@@ -61,6 +64,34 @@ describe("resolveTerminalOpenLocation", () => {worktreePath: "/repo/worktrees/feature",});});++ it("preserves checkout cwd and identity from the selected terminal or active session", () => {+ const checkout = { cwd: "/repo/root/packages/app", worktreePath: null };+ const threadLocation = {+ workspaceRoot: "/repo/root",+ threadShellWorktreePath: "/repo/worktrees/feature",+ threadDetailWorktreePath: "/repo/worktrees/feature",+ };++ expect(+ resolveTerminalOpenLocation({+ ...threadLocation,+ terminalLocation: checkout,+ activeSessionLocation: {+ cwd: "/repo/worktrees/other",+ worktreePath: "/repo/worktrees/other",+ },+ }),+ ).toEqual(checkout);++ expect(+ resolveTerminalOpenLocation({+ ...threadLocation,+ terminalLocation: null,+ activeSessionLocation: checkout,+ }),+ ).toEqual(checkout);+ });});describe("pending terminal launches", () => {@@ -120,3 +151,98 @@ describe("pending terminal launches", () => {});});});++describe("initial terminal launch location", () => {+ it("waits for session metadata before retaining a location for each route target", async () => {+ const { createRoot } = NodeModule.createRequire(import.meta.url)("react-dom/client") as {+ createRoot(container: Element): {+ render(children: ReactNode): void;+ unmount(): void;+ };+ };+ const document = { nodeType: 9, addEventListener() {}, removeEventListener() {} };+ const container = {+ nodeType: 1,+ tagName: "DIV",+ namespaceURI: "http://www.w3.org/1999/xhtml",+ ownerDocument: document,+ addEventListener() {},+ removeEventListener() {},+ };+ vi.stubGlobal("document", document);+ vi.stubGlobal("window", { document, HTMLIFrameElement: EventTarget });+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ const root = createRoot(container as unknown as HTMLElement);+ type Input = Parameters<typeof useInitialTerminalLaunchLocation>[0];+ let location: ReturnType<typeof useInitialTerminalLaunchLocation> = null;+ function Probe(input: Input) {+ const selectedLocation = useInitialTerminalLaunchLocation(input);+ useEffect(() => {+ location = selectedLocation;+ }, [selectedLocation]);+ return null;+ }+ const threadLocation = {+ terminalLocation: null,+ activeSessionLocation: null,+ workspaceRoot: "/repo/root",+ threadShellWorktreePath: "/repo/worktrees/feature",+ threadDetailWorktreePath: "/repo/worktrees/feature",+ };+ const checkout = { cwd: "/repo/root/packages/app", worktreePath: null };+ const input: Input = {+ targetKey: "environment:thread:term-1",+ pendingLaunch: null,+ hasResolvedPendingLaunch: true,+ isAuthenticated: true,+ canRead: true,+ canOperate: true,+ hasLoadedSessions: false,+ location: threadLocation,+ };+ const render = (changes: Partial<Input> = {}) =>+ act(() => root.render(createElement(Probe, { ...input, ...changes })));+ try {+ // Thread/project are ready before authentication and the metadata snapshot.+ await render({ isAuthenticated: false, canRead: false, canOperate: false });+ expect(location).toBeNull();+ await render();+ expect(location).toBeNull();+ await render({+ hasLoadedSessions: true,+ canOperate: false,+ location: { ...threadLocation, terminalLocation: checkout },+ });+ expect(location).toEqual(checkout);++ // Reconnects and subsequent thread changes must not move the selected terminal.+ await render({ location: { ...threadLocation, threadDetailWorktreePath: "/repo/other" } });+ expect(location).toEqual(checkout);++ const nextTarget = { targetKey: "environment:thread:term-2" };+ await render(nextTarget);+ expect(location).toBeNull();+ // A loaded empty session list permits the fresh-open thread fallback.+ await render({ ...nextTarget, hasLoadedSessions: true });+ expect(location).toEqual({+ cwd: "/repo/worktrees/feature",+ worktreePath: "/repo/worktrees/feature",+ });++ await render({ targetKey: "environment:thread:term-3", hasResolvedPendingLaunch: false });+ expect(location).toBeNull();+ await render({ targetKey: "environment:thread:term-3", pendingLaunch: checkout });+ expect(location).toEqual(checkout);++ // Operate-only grants cannot load metadata, so they still use the thread default.+ await render({ targetKey: "environment:thread:term-4", canRead: false });+ expect(location).toEqual({+ cwd: "/repo/worktrees/feature",+ worktreePath: "/repo/worktrees/feature",+ });+ } finally {+ await act(() => root.unmount());+ vi.unstubAllGlobals();+ }+ });+});diff --git a/apps/mobile/src/features/terminal/terminalLaunchContext.ts b/apps/mobile/src/features/terminal/terminalLaunchContext.tsindex af67497a3d2..51966003646 100644--- a/apps/mobile/src/features/terminal/terminalLaunchContext.ts+++ b/apps/mobile/src/features/terminal/terminalLaunchContext.ts@@ -1,4 +1,5 @@import type { EnvironmentId, ThreadId } from "@t3tools/contracts";+import { useEffect, useState } from "react";interface TerminalLocationLike {readonly cwd: string;@@ -65,20 +66,55 @@ export function resolveTerminalOpenLocation(input: {readonly cwd: string;readonly worktreePath: string | null;} {+ const sessionLocation = input.terminalLocation ?? input.activeSessionLocation;++ // Keep cwd paired with its identity; null identifies the project checkout.+ if (sessionLocation !== null) {+ return { cwd: sessionLocation.cwd, worktreePath: sessionLocation.worktreePath };+ }const preferredThreadWorktreePath = resolvePreferredThreadWorktreePath({threadShellWorktreePath: input.threadShellWorktreePath,threadDetailWorktreePath: input.threadDetailWorktreePath,});-return {- cwd:- input.terminalLocation?.cwd ??- input.activeSessionLocation?.cwd ??- preferredThreadWorktreePath ??- input.workspaceRoot,- worktreePath:- input.terminalLocation?.worktreePath ??- input.activeSessionLocation?.worktreePath ??- preferredThreadWorktreePath,+ cwd: preferredThreadWorktreePath ?? input.workspaceRoot,+ worktreePath: preferredThreadWorktreePath,};}++export function useInitialTerminalLaunchLocation(input: {+ readonly targetKey: string | null;+ readonly pendingLaunch: PendingTerminalLaunch | null;+ readonly hasResolvedPendingLaunch: boolean;+ readonly isAuthenticated: boolean;+ readonly canRead: boolean;+ readonly canOperate: boolean;+ readonly hasLoadedSessions: boolean;+ readonly location: Parameters<typeof resolveTerminalOpenLocation>[0] | null;+}) {+ let candidate: TerminalLocationLike | null = null;+ if (+ input.location !== null &&+ input.hasResolvedPendingLaunch &&+ input.isAuthenticated &&+ (input.canRead || input.canOperate)+ ) {+ if (input.pendingLaunch !== null) {+ candidate = {+ cwd: input.pendingLaunch.cwd,+ worktreePath: input.pendingLaunch.worktreePath,+ };+ } else if (!input.canRead || input.hasLoadedSessions) {+ // Metadata must establish whether this target has a location before we retain a fallback.+ candidate = resolveTerminalOpenLocation(input.location);+ }+ }+ const [entry, setEntry] = useState(() => ({ key: input.targetKey, location: candidate }));+ useEffect(() => {+ if (entry.key === input.targetKey && (entry.location !== null || candidate === null)) {+ return;+ }+ setEntry({ key: input.targetKey, location: candidate });+ }, [candidate, entry.key, entry.location, input.targetKey]);+ return entry.key === input.targetKey ? entry.location : null;+}diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.tsindex 0ce4d137414..8a38f9a102a 100644--- a/apps/web/src/components/ChatView.logic.test.ts+++ b/apps/web/src/components/ChatView.logic.test.ts@@ -89,6 +89,7 @@ import {hasServerAcknowledgedLocalDispatch,isBranchMismatchDismissedForSession,reconcileMountedTerminalThreadIds,+ resolveTerminalWorktreePath,resolveDraftPromotionNavigationTarget,resolveEffectiveInteractionMode,resolveThreadMetadataUpdateForNextTurn,@@ -520,6 +521,32 @@ describe("session branch mismatch dismissal", () => {});});+describe("resolveTerminalWorktreePath", () => {+ it("uses the terminal's checkout identity until neither launch nor session is known", () => {+ const threadWorktreePath = "/repo/.worktrees/feature";++ expect(+ resolveTerminalWorktreePath({+ launchContext: { worktreePath: null },+ summary: { worktreePath: "/repo/.worktrees/other" },+ threadWorktreePath,+ }),+ ).toBeNull();++ expect(+ resolveTerminalWorktreePath({+ launchContext: null,+ summary: { worktreePath: null },+ threadWorktreePath,+ }),+ ).toBeNull();++ expect(+ resolveTerminalWorktreePath({ launchContext: null, summary: null, threadWorktreePath }),+ ).toBe(threadWorktreePath);+ });+});+describe("reconcileMountedTerminalThreadIds", () => {it("keeps open threads and makes the active thread most recent", () => {expect(diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.tsindex 7479a289d8f..3e0f7a13e48 100644--- a/apps/web/src/components/ChatView.logic.ts+++ b/apps/web/src/components/ChatView.logic.ts@@ -681,6 +681,17 @@ export function reconcileMountedTerminalThreadIds(input: {return nextThreadIds;}+// Null identifies the project checkout when a launch or session is known.+export function resolveTerminalWorktreePath(input: {+ launchContext: { readonly worktreePath: string | null } | null;+ summary: { readonly worktreePath: string | null } | null;+ threadWorktreePath: string | null;+}): string | null {+ if (input.launchContext !== null) return input.launchContext.worktreePath;+ if (input.summary !== null) return input.summary.worktreePath;+ return input.threadWorktreePath;+}+export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {return;diff --git a/apps/web/src/components/PersistentThreadTerminals.tsx b/apps/web/src/components/PersistentThreadTerminals.tsxindex 44b40f83e75..f7658ba4193 100644--- a/apps/web/src/components/PersistentThreadTerminals.tsx+++ b/apps/web/src/components/PersistentThreadTerminals.tsx@@ -24,6 +24,7 @@ import { useKnownTerminalSessions } from "../state/terminalSessions";import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";import { useThreadTerminalActions } from "./terminal/useThreadTerminalActions";import ThreadTerminalDrawer from "./ThreadTerminalDrawer";+import { resolveTerminalWorktreePath } from "./ChatView.logic";/** Where a drawer or panel opens new terminals when a script run overrides the thread's own. */export type PersistentTerminalLaunchContext = {@@ -346,8 +347,11 @@ export const PersistentThreadTerminalPanel = memo(function PersistentThreadTermiconst activeSummary =knownTerminalSessions?.find((session) => session.target.terminalId === surface.activeTerminalId)?.state.summary ?? null;- const worktreePath =- launchContext?.worktreePath ?? activeSummary?.worktreePath ?? threadWorktreePath;+ const worktreePath = resolveTerminalWorktreePath({+ launchContext,+ summary: activeSummary,+ threadWorktreePath,+ });const cwd =launchContext?.cwd ??activeSummary?.cwd ??@@ -363,8 +367,11 @@ export const PersistentThreadTerminalPanel = memo(function PersistentThreadTermi.summary ?? null;terminalLabelsById.set(terminalId, resolveTerminalSessionLabel(terminalId, summary));if (!project) continue;- const terminalWorktreePath =- launchContext?.worktreePath ?? summary?.worktreePath ?? threadWorktreePath;+ const terminalWorktreePath = resolveTerminalWorktreePath({+ launchContext,+ summary,+ threadWorktreePath,+ });terminalLaunchLocationsById.set(terminalId, {cwd:launchContext?.cwd ??diff --git a/packages/client-runtime/src/state/runtime.test.ts b/packages/client-runtime/src/state/runtime.test.tsindex b1cc4f83506..e31092acc75 100644--- a/packages/client-runtime/src/state/runtime.test.ts+++ b/packages/client-runtime/src/state/runtime.test.ts@@ -3,6 +3,8 @@ import {EnvironmentId,type TerminalAttachInput,type TerminalAttachStreamEvent,+ type TerminalMetadataStreamEvent,+ type TerminalSummary,WS_METHODS,} from "@t3tools/contracts";import * as Cause from "effect/Cause";@@ -388,6 +390,83 @@ describe("finite environment subscription lifecycle", () => {});describe("environment query lifecycle", () => {+ it.effect(+ "terminal metadata waits for snapshots and retains known sessions across restarts",+ () =>+ Effect.gen(function* () {+ const harness = yield* makeEnvironmentQueryHarness(Effect.void);+ const started = yield* Queue.unbounded<void>();+ const events = yield* Queue.unbounded<TerminalMetadataStreamEvent>();+ const receivedCheckout = yield* Deferred.make<void>();+ const receivedEmpty = yield* Deferred.make<void>();+ const checkout: TerminalSummary = {+ threadId: "thread-1",+ terminalId: "terminal-1",+ cwd: "/repo/root/packages/app",+ worktreePath: null,+ status: "running",+ pid: 123,+ exitCode: null,+ exitSignal: null,+ hasRunningSubprocess: false,+ label: "Terminal 1",+ updatedAt: "2026-04-01T00:00:00.000Z",+ };+ const client = {+ [WS_METHODS.subscribeTerminalMetadata]: () =>+ Stream.fromEffect(Queue.offer(started, undefined)).pipe(+ Stream.drain,+ Stream.concat(Stream.fromQueue(events)),+ ),+ } as unknown as RpcSession.RpcSession["client"];+ 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 registry = AtomRegistry.make();+ const observed: Array<ReadonlyArray<TerminalSummary>> = [];+ const unsubscribe = registry.subscribe(+ atom,+ (result) => {+ if (!AsyncResult.isSuccess(result)) return;+ observed.push(result.value);+ if (result.value.length > 0) Deferred.doneUnsafe(receivedCheckout, Exit.void);+ else Deferred.doneUnsafe(receivedEmpty, Exit.void);+ },+ { immediate: true },+ );+ yield* Effect.addFinalizer(() =>+ Effect.sync(() => {+ unsubscribe();+ registry.dispose();+ }),+ );++ yield* Queue.take(started);+ expect(selectEnvironmentQueryData(registry.get(atom))).toBeNull();+ expect(observed).toEqual([]);++ yield* Queue.offer(events, { type: "snapshot", terminals: [checkout] });+ yield* Deferred.await(receivedCheckout);+ expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]);++ yield* SubscriptionRef.set(harness.supervisorSession, Option.some({ ...session }));+ yield* Queue.take(started);+ expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]);++ yield* SubscriptionRef.update(harness.streamGeneration, (generation) => generation + 1);+ yield* Queue.take(started);+ expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]);++ yield* Queue.offer(events, { type: "snapshot", terminals: [] });+ yield* Deferred.await(receivedEmpty);+ expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([]);+ }),+ );+it.effect("terminal attach resubscribes with resume only after the stream replied", () =>Effect.gen(function* () {const harness = yield* makeEnvironmentQueryHarness(Effect.void);diff --git a/packages/client-runtime/src/state/terminal.ts b/packages/client-runtime/src/state/terminal.tsindex 59da22c1859..8c0a1113e15 100644--- a/packages/client-runtime/src/state/terminal.ts+++ b/packages/client-runtime/src/state/terminal.ts@@ -73,6 +73,8 @@ export function createTerminalEnvironmentAtoms<R, E>(subscribe: (_input: null) =>subscribe(WS_METHODS.subscribeTerminalMetadata, {}).pipe(Stream.scan((): ReadonlyArray<TerminalSummary> => [], applyTerminalMetadataStreamEvent),+ // The scan seed is not an authoritative empty server snapshot.+ Stream.drop(1),),}),open: createEnvironmentRpcCommand(runtime, {