The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 00:30 UTC
fix(clients): keep a checkout terminal off the thread's worktree (#16039)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>
Alex Southwell committed
Oct 20, 2026 at 02:49 UTC
62880642c08421389e9e2c5b6724775605c53dac
8 files changed
+328
-66
apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
+25
-51
@@ -70,7 +70,7 @@ import {
70
TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS,
71
} from "./terminalBufferReplay";
72
import {
73
- resolveTerminalOpenLocation,
73
+ useInitialTerminalLaunchLocation,
74
takePendingTerminalLaunch,
75
type PendingTerminalLaunch,
76
} from "./terminalLaunchContext";
@@ -396,36 +396,25 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
396
requestedTerminalId === null &&
397
runningSession !== null &&
398
runningSession.target.terminalId !== terminalId;
399
- const launchLocationCandidate = useMemo(() => {
400
- if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
401
- return null;
402
- }
403
- if (pendingLaunch) {
404
- return {
405
- cwd: pendingLaunch.cwd,
406
- worktreePath: pendingLaunch.worktreePath,
407
- };
408
- }
409
- return resolveTerminalOpenLocation({
410
- terminalLocation: activeKnownSession?.state.summary ?? null,
411
- activeSessionLocation: activeKnownSession?.state.summary ?? null,
412
- workspaceRoot: selectedThreadProject.workspaceRoot,
413
- threadShellWorktreePath: selectedThread.worktreePath ?? null,
414
- threadDetailWorktreePath: selectedThreadDetailWorktreePath,
415
- });
416
- }, [
417
- activeKnownSession?.state.summary,
399
+ const launchLocation = useInitialTerminalLaunchLocation({
400
+ targetKey: launchTargetKey,
401
pendingLaunch,
419
- selectedThread,
420
- selectedThreadDetailWorktreePath,
421
- selectedThreadProject?.workspaceRoot,
422
- ]);
423
- const [initialLaunchLocationEntry, setInitialLaunchLocationEntry] = useState(() => ({
424
- key: launchTargetKey,
425
- location: launchLocationCandidate,
426
- }));
427
- const launchLocation =
428
- initialLaunchLocationEntry.key === launchTargetKey ? initialLaunchLocationEntry.location : null;
402
+ hasResolvedPendingLaunch,
403
+ isAuthenticated,
404
+ canRead: canReadTerminal,
405
+ canOperate: canOperateTerminal,
406
+ hasLoadedSessions: knownSessions !== null,
407
+ location:
408
+ selectedThread && selectedThreadProject?.workspaceRoot
409
+ ? {
410
+ terminalLocation: activeKnownSession?.state.summary ?? null,
411
+ activeSessionLocation: activeKnownSession?.state.summary ?? null,
412
+ workspaceRoot: selectedThreadProject.workspaceRoot,
413
+ threadShellWorktreePath: selectedThread.worktreePath ?? null,
414
+ threadDetailWorktreePath: selectedThreadDetailWorktreePath,
415
+ }
416
+ : null,
417
+ });
418
const terminalAttachInput = useMemo(
419
() =>
420
selectedThread !== null &&
@@ -670,27 +659,6 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
659
});
660
}, [cachedRouteGridSize, initialAttachGridEntry.key, launchTargetKey]);
661
673
- useEffect(() => {
674
- if (
675
- initialLaunchLocationEntry.key === launchTargetKey &&
676
- initialLaunchLocationEntry.location !== null
677
- ) {
678
- return;
679
- }
680
- if (initialLaunchLocationEntry.key === launchTargetKey && launchLocationCandidate === null) {
681
- return;
682
- }
683
- setInitialLaunchLocationEntry({
684
- key: launchTargetKey,
685
- location: launchLocationCandidate,
686
- });
687
- }, [
688
- initialLaunchLocationEntry.key,
689
- initialLaunchLocationEntry.location,
690
- launchLocationCandidate,
691
- launchTargetKey,
692
- ]);
693
-
662
useEffect(() => {
663
if (!shouldRedirectToRunningTerminal || !selectedThread || !runningSession) {
664
return;
@@ -1243,6 +1211,12 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
1211
"This connection does not have permission to view terminals."
1212
}
1213
/>
1214
+ ) : canOperateTerminal && launchLocation === null ? (
1215
+ sessionsError !== null ? (
1216
+ <EmptyState title="Could not load terminals" detail={sessionsError} />
1217
+ ) : (
1218
+ <EmptyState title="Loading terminals" detail="Reading existing terminal sessions." />
1219
+ )
1220
) : !canOperateTerminal && !hasTerminalTarget && sessionsPending ? (
1221
<EmptyState title="Loading terminals" detail="Reading existing terminal sessions." />
1222
) : !canOperateTerminal && !hasTerminalTarget && sessionsError !== null ? (
apps/mobile/src/features/terminal/terminalLaunchContext.test.ts
+127
-1
@@ -1,4 +1,6 @@
1
-import { describe, expect, it } from "vite-plus/test";
1
+import * as NodeModule from "node:module";
2
+import { act, createElement, useEffect, type ReactNode } from "react";
3
+import { describe, expect, it, vi } from "vite-plus/test";
4
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
5
6
import {
@@ -6,6 +8,7 @@ import {
8
resolveTerminalOpenLocation,
9
stagePendingTerminalLaunch,
10
takePendingTerminalLaunch,
11
+ useInitialTerminalLaunchLocation,
12
} from "./terminalLaunchContext";
13
14
describe("resolvePreferredThreadWorktreePath", () => {
@@ -61,6 +64,34 @@ describe("resolveTerminalOpenLocation", () => {
64
worktreePath: "/repo/worktrees/feature",
65
});
66
});
67
+
68
+ it("preserves checkout cwd and identity from the selected terminal or active session", () => {
69
+ const checkout = { cwd: "/repo/root/packages/app", worktreePath: null };
70
+ const threadLocation = {
71
+ workspaceRoot: "/repo/root",
72
+ threadShellWorktreePath: "/repo/worktrees/feature",
73
+ threadDetailWorktreePath: "/repo/worktrees/feature",
74
+ };
75
+
76
+ expect(
77
+ resolveTerminalOpenLocation({
78
+ ...threadLocation,
79
+ terminalLocation: checkout,
80
+ activeSessionLocation: {
81
+ cwd: "/repo/worktrees/other",
82
+ worktreePath: "/repo/worktrees/other",
83
+ },
84
+ }),
85
+ ).toEqual(checkout);
86
+
87
+ expect(
88
+ resolveTerminalOpenLocation({
89
+ ...threadLocation,
90
+ terminalLocation: null,
91
+ activeSessionLocation: checkout,
92
+ }),
93
+ ).toEqual(checkout);
94
+ });
95
});
96
97
describe("pending terminal launches", () => {
@@ -120,3 +151,98 @@ describe("pending terminal launches", () => {
151
});
152
});
153
});
154
+
155
+describe("initial terminal launch location", () => {
156
+ it("waits for session metadata before retaining a location for each route target", async () => {
157
+ const { createRoot } = NodeModule.createRequire(import.meta.url)("react-dom/client") as {
158
+ createRoot(container: Element): {
159
+ render(children: ReactNode): void;
160
+ unmount(): void;
161
+ };
162
+ };
163
+ const document = { nodeType: 9, addEventListener() {}, removeEventListener() {} };
164
+ const container = {
165
+ nodeType: 1,
166
+ tagName: "DIV",
167
+ namespaceURI: "http://www.w3.org/1999/xhtml",
168
+ ownerDocument: document,
169
+ addEventListener() {},
170
+ removeEventListener() {},
171
+ };
172
+ vi.stubGlobal("document", document);
173
+ vi.stubGlobal("window", { document, HTMLIFrameElement: EventTarget });
174
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
175
+ const root = createRoot(container as unknown as HTMLElement);
176
+ type Input = Parameters<typeof useInitialTerminalLaunchLocation>[0];
177
+ let location: ReturnType<typeof useInitialTerminalLaunchLocation> = null;
178
+ function Probe(input: Input) {
179
+ const selectedLocation = useInitialTerminalLaunchLocation(input);
180
+ useEffect(() => {
181
+ location = selectedLocation;
182
+ }, [selectedLocation]);
183
+ return null;
184
+ }
185
+ const threadLocation = {
186
+ terminalLocation: null,
187
+ activeSessionLocation: null,
188
+ workspaceRoot: "/repo/root",
189
+ threadShellWorktreePath: "/repo/worktrees/feature",
190
+ threadDetailWorktreePath: "/repo/worktrees/feature",
191
+ };
192
+ const checkout = { cwd: "/repo/root/packages/app", worktreePath: null };
193
+ const input: Input = {
194
+ targetKey: "environment:thread:term-1",
195
+ pendingLaunch: null,
196
+ hasResolvedPendingLaunch: true,
197
+ isAuthenticated: true,
198
+ canRead: true,
199
+ canOperate: true,
200
+ hasLoadedSessions: false,
201
+ location: threadLocation,
202
+ };
203
+ const render = (changes: Partial<Input> = {}) =>
204
+ act(() => root.render(createElement(Probe, { ...input, ...changes })));
205
+ try {
206
+ // Thread/project are ready before authentication and the metadata snapshot.
207
+ await render({ isAuthenticated: false, canRead: false, canOperate: false });
208
+ expect(location).toBeNull();
209
+ await render();
210
+ expect(location).toBeNull();
211
+ await render({
212
+ hasLoadedSessions: true,
213
+ canOperate: false,
214
+ location: { ...threadLocation, terminalLocation: checkout },
215
+ });
216
+ expect(location).toEqual(checkout);
217
+
218
+ // Reconnects and subsequent thread changes must not move the selected terminal.
219
+ await render({ location: { ...threadLocation, threadDetailWorktreePath: "/repo/other" } });
220
+ expect(location).toEqual(checkout);
221
+
222
+ const nextTarget = { targetKey: "environment:thread:term-2" };
223
+ await render(nextTarget);
224
+ expect(location).toBeNull();
225
+ // A loaded empty session list permits the fresh-open thread fallback.
226
+ await render({ ...nextTarget, hasLoadedSessions: true });
227
+ expect(location).toEqual({
228
+ cwd: "/repo/worktrees/feature",
229
+ worktreePath: "/repo/worktrees/feature",
230
+ });
231
+
232
+ await render({ targetKey: "environment:thread:term-3", hasResolvedPendingLaunch: false });
233
+ expect(location).toBeNull();
234
+ await render({ targetKey: "environment:thread:term-3", pendingLaunch: checkout });
235
+ expect(location).toEqual(checkout);
236
+
237
+ // Operate-only grants cannot load metadata, so they still use the thread default.
238
+ await render({ targetKey: "environment:thread:term-4", canRead: false });
239
+ expect(location).toEqual({
240
+ cwd: "/repo/worktrees/feature",
241
+ worktreePath: "/repo/worktrees/feature",
242
+ });
243
+ } finally {
244
+ await act(() => root.unmount());
245
+ vi.unstubAllGlobals();
246
+ }
247
+ });
248
+});
apps/mobile/src/features/terminal/terminalLaunchContext.ts
+46
-10
@@ -1,4 +1,5 @@
1
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
2
+import { useEffect, useState } from "react";
3
4
interface TerminalLocationLike {
5
readonly cwd: string;
@@ -65,20 +66,55 @@ export function resolveTerminalOpenLocation(input: {
66
readonly cwd: string;
67
readonly worktreePath: string | null;
68
} {
69
+ const sessionLocation = input.terminalLocation ?? input.activeSessionLocation;
70
+
71
+ // Keep cwd paired with its identity; null identifies the project checkout.
72
+ if (sessionLocation !== null) {
73
+ return { cwd: sessionLocation.cwd, worktreePath: sessionLocation.worktreePath };
74
+ }
75
const preferredThreadWorktreePath = resolvePreferredThreadWorktreePath({
76
threadShellWorktreePath: input.threadShellWorktreePath,
77
threadDetailWorktreePath: input.threadDetailWorktreePath,
78
});
72
-
79
return {
74
- cwd:
75
- input.terminalLocation?.cwd ??
76
- input.activeSessionLocation?.cwd ??
77
- preferredThreadWorktreePath ??
78
- input.workspaceRoot,
79
- worktreePath:
80
- input.terminalLocation?.worktreePath ??
81
- input.activeSessionLocation?.worktreePath ??
82
- preferredThreadWorktreePath,
80
+ cwd: preferredThreadWorktreePath ?? input.workspaceRoot,
81
+ worktreePath: preferredThreadWorktreePath,
82
};
83
}
84
+
85
+export function useInitialTerminalLaunchLocation(input: {
86
+ readonly targetKey: string | null;
87
+ readonly pendingLaunch: PendingTerminalLaunch | null;
88
+ readonly hasResolvedPendingLaunch: boolean;
89
+ readonly isAuthenticated: boolean;
90
+ readonly canRead: boolean;
91
+ readonly canOperate: boolean;
92
+ readonly hasLoadedSessions: boolean;
93
+ readonly location: Parameters<typeof resolveTerminalOpenLocation>[0] | null;
94
+}) {
95
+ let candidate: TerminalLocationLike | null = null;
96
+ if (
97
+ input.location !== null &&
98
+ input.hasResolvedPendingLaunch &&
99
+ input.isAuthenticated &&
100
+ (input.canRead || input.canOperate)
101
+ ) {
102
+ if (input.pendingLaunch !== null) {
103
+ candidate = {
104
+ cwd: input.pendingLaunch.cwd,
105
+ worktreePath: input.pendingLaunch.worktreePath,
106
+ };
107
+ } else if (!input.canRead || input.hasLoadedSessions) {
108
+ // Metadata must establish whether this target has a location before we retain a fallback.
109
+ candidate = resolveTerminalOpenLocation(input.location);
110
+ }
111
+ }
112
+ const [entry, setEntry] = useState(() => ({ key: input.targetKey, location: candidate }));
113
+ useEffect(() => {
114
+ if (entry.key === input.targetKey && (entry.location !== null || candidate === null)) {
115
+ return;
116
+ }
117
+ setEntry({ key: input.targetKey, location: candidate });
118
+ }, [candidate, entry.key, entry.location, input.targetKey]);
119
+ return entry.key === input.targetKey ? entry.location : null;
120
+}
apps/web/src/components/ChatView.logic.test.ts
+27
@@ -89,6 +89,7 @@ import {
89
hasServerAcknowledgedLocalDispatch,
90
isBranchMismatchDismissedForSession,
91
reconcileMountedTerminalThreadIds,
92
+ resolveTerminalWorktreePath,
93
resolveDraftPromotionNavigationTarget,
94
resolveEffectiveInteractionMode,
95
resolveThreadMetadataUpdateForNextTurn,
@@ -520,6 +521,32 @@ describe("session branch mismatch dismissal", () => {
521
});
522
});
523
524
+describe("resolveTerminalWorktreePath", () => {
525
+ it("uses the terminal's checkout identity until neither launch nor session is known", () => {
526
+ const threadWorktreePath = "/repo/.worktrees/feature";
527
+
528
+ expect(
529
+ resolveTerminalWorktreePath({
530
+ launchContext: { worktreePath: null },
531
+ summary: { worktreePath: "/repo/.worktrees/other" },
532
+ threadWorktreePath,
533
+ }),
534
+ ).toBeNull();
535
+
536
+ expect(
537
+ resolveTerminalWorktreePath({
538
+ launchContext: null,
539
+ summary: { worktreePath: null },
540
+ threadWorktreePath,
541
+ }),
542
+ ).toBeNull();
543
+
544
+ expect(
545
+ resolveTerminalWorktreePath({ launchContext: null, summary: null, threadWorktreePath }),
546
+ ).toBe(threadWorktreePath);
547
+ });
548
+});
549
+
550
describe("reconcileMountedTerminalThreadIds", () => {
551
it("keeps open threads and makes the active thread most recent", () => {
552
expect(
apps/web/src/components/ChatView.logic.ts
+11
@@ -681,6 +681,17 @@ export function reconcileMountedTerminalThreadIds(input: {
681
return nextThreadIds;
682
}
683
684
+// Null identifies the project checkout when a launch or session is known.
685
+export function resolveTerminalWorktreePath(input: {
686
+ launchContext: { readonly worktreePath: string | null } | null;
687
+ summary: { readonly worktreePath: string | null } | null;
688
+ threadWorktreePath: string | null;
689
+}): string | null {
690
+ if (input.launchContext !== null) return input.launchContext.worktreePath;
691
+ if (input.summary !== null) return input.summary.worktreePath;
692
+ return input.threadWorktreePath;
693
+}
694
+
695
export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
696
if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
697
return;
apps/web/src/components/PersistentThreadTerminals.tsx
+11
-4
@@ -24,6 +24,7 @@ import { useKnownTerminalSessions } from "../state/terminalSessions";
24
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
25
import { useThreadTerminalActions } from "./terminal/useThreadTerminalActions";
26
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
27
+import { resolveTerminalWorktreePath } from "./ChatView.logic";
28
29
/** Where a drawer or panel opens new terminals when a script run overrides the thread's own. */
30
export type PersistentTerminalLaunchContext = {
@@ -346,8 +347,11 @@ export const PersistentThreadTerminalPanel = memo(function PersistentThreadTermi
347
const activeSummary =
348
knownTerminalSessions?.find((session) => session.target.terminalId === surface.activeTerminalId)
349
?.state.summary ?? null;
349
- const worktreePath =
350
- launchContext?.worktreePath ?? activeSummary?.worktreePath ?? threadWorktreePath;
350
+ const worktreePath = resolveTerminalWorktreePath({
351
+ launchContext,
352
+ summary: activeSummary,
353
+ threadWorktreePath,
354
+ });
355
const cwd =
356
launchContext?.cwd ??
357
activeSummary?.cwd ??
@@ -363,8 +367,11 @@ export const PersistentThreadTerminalPanel = memo(function PersistentThreadTermi
367
.summary ?? null;
368
terminalLabelsById.set(terminalId, resolveTerminalSessionLabel(terminalId, summary));
369
if (!project) continue;
366
- const terminalWorktreePath =
367
- launchContext?.worktreePath ?? summary?.worktreePath ?? threadWorktreePath;
370
+ const terminalWorktreePath = resolveTerminalWorktreePath({
371
+ launchContext,
372
+ summary,
373
+ threadWorktreePath,
374
+ });
375
terminalLaunchLocationsById.set(terminalId, {
376
cwd:
377
launchContext?.cwd ??
packages/client-runtime/src/state/runtime.test.ts
+79
@@ -3,6 +3,8 @@ import {
3
EnvironmentId,
4
type TerminalAttachInput,
5
type TerminalAttachStreamEvent,
6
+ type TerminalMetadataStreamEvent,
7
+ type TerminalSummary,
8
WS_METHODS,
9
} from "@t3tools/contracts";
10
import * as Cause from "effect/Cause";
@@ -388,6 +390,83 @@ describe("finite environment subscription lifecycle", () => {
390
});
391
392
describe("environment query lifecycle", () => {
393
+ it.effect(
394
+ "terminal metadata waits for snapshots and retains known sessions across restarts",
395
+ () =>
396
+ Effect.gen(function* () {
397
+ const harness = yield* makeEnvironmentQueryHarness(Effect.void);
398
+ const started = yield* Queue.unbounded<void>();
399
+ const events = yield* Queue.unbounded<TerminalMetadataStreamEvent>();
400
+ const receivedCheckout = yield* Deferred.make<void>();
401
+ const receivedEmpty = yield* Deferred.make<void>();
402
+ const checkout: TerminalSummary = {
403
+ threadId: "thread-1",
404
+ terminalId: "terminal-1",
405
+ cwd: "/repo/root/packages/app",
406
+ worktreePath: null,
407
+ status: "running",
408
+ pid: 123,
409
+ exitCode: null,
410
+ exitSignal: null,
411
+ hasRunningSubprocess: false,
412
+ label: "Terminal 1",
413
+ updatedAt: "2026-04-01T00:00:00.000Z",
414
+ };
415
+ const client = {
416
+ [WS_METHODS.subscribeTerminalMetadata]: () =>
417
+ Stream.fromEffect(Queue.offer(started, undefined)).pipe(
418
+ Stream.drain,
419
+ Stream.concat(Stream.fromQueue(events)),
420
+ ),
421
+ } as unknown as RpcSession.RpcSession["client"];
422
+ const session = { ...QUERY_RPC_SESSION, client };
423
+ yield* SubscriptionRef.set(harness.supervisorSession, Option.some(session));
424
+ const atoms = createTerminalEnvironmentAtoms(harness.runtime);
425
+ const atom = atoms.metadata({
426
+ environmentId: QUERY_ENVIRONMENT.environmentId,
427
+ input: null,
428
+ });
429
+ const registry = AtomRegistry.make();
430
+ const observed: Array<ReadonlyArray<TerminalSummary>> = [];
431
+ const unsubscribe = registry.subscribe(
432
+ atom,
433
+ (result) => {
434
+ if (!AsyncResult.isSuccess(result)) return;
435
+ observed.push(result.value);
436
+ if (result.value.length > 0) Deferred.doneUnsafe(receivedCheckout, Exit.void);
437
+ else Deferred.doneUnsafe(receivedEmpty, Exit.void);
438
+ },
439
+ { immediate: true },
440
+ );
441
+ yield* Effect.addFinalizer(() =>
442
+ Effect.sync(() => {
443
+ unsubscribe();
444
+ registry.dispose();
445
+ }),
446
+ );
447
+
448
+ yield* Queue.take(started);
449
+ expect(selectEnvironmentQueryData(registry.get(atom))).toBeNull();
450
+ expect(observed).toEqual([]);
451
+
452
+ yield* Queue.offer(events, { type: "snapshot", terminals: [checkout] });
453
+ yield* Deferred.await(receivedCheckout);
454
+ expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]);
455
+
456
+ yield* SubscriptionRef.set(harness.supervisorSession, Option.some({ ...session }));
457
+ yield* Queue.take(started);
458
+ expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]);
459
+
460
+ yield* SubscriptionRef.update(harness.streamGeneration, (generation) => generation + 1);
461
+ yield* Queue.take(started);
462
+ expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]);
463
+
464
+ yield* Queue.offer(events, { type: "snapshot", terminals: [] });
465
+ yield* Deferred.await(receivedEmpty);
466
+ expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([]);
467
+ }),
468
+ );
469
+
470
it.effect("terminal attach resubscribes with resume only after the stream replied", () =>
471
Effect.gen(function* () {
472
const harness = yield* makeEnvironmentQueryHarness(Effect.void);
packages/client-runtime/src/state/terminal.ts
+2
@@ -73,6 +73,8 @@ export function createTerminalEnvironmentAtoms<R, E>(
73
subscribe: (_input: null) =>
74
subscribe(WS_METHODS.subscribeTerminalMetadata, {}).pipe(
75
Stream.scan((): ReadonlyArray<TerminalSummary> => [], applyTerminalMetadataStreamEvent),
76
+ // The scan seed is not an authoritative empty server snapshot.
77
+ Stream.drop(1),
78
),
79
}),
80
open: createEnvironmentRpcCommand(runtime, {