@devries-cameron20 / t3code Mirror · read-only / commits / 64968b3109
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 10:45 UTC

fix(web): a branch restore in one thread no longer blocks another thread (#24060)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com>

Batuhan1999 committed Oct 30, 2026 at 22:02 UTC 64968b3109dd4421e0d4fca80bbab69dfbd73854
3 files changed +205 -10
apps/web/src/components/ChatView.tsx
-1
@@ -2399,7 +2399,6 @@ export default function ChatView(props: ChatViewProps) {
2399 clearUsageLimitsFor,
2400 beginLocalDispatch,
2401 resetLocalDispatch,
2402 - scheduleComposerFocus,
2402 scrollToEnd,
2403 persistThreadSettingsForNextTurn,
2404 });
apps/web/src/components/chat/useThreadLifecycle.browser.test.tsx new
+183
@@ -0,0 +1,183 @@
1 +import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
2 +import { EnvironmentId, ThreadId } from "@t3tools/contracts";
3 +import { expect, it, vi } from "vite-plus/test";
4 +import { page } from "vite-plus/test/browser";
5 +
6 +const state = vi.hoisted(() => ({
7 + switchRef: (async () => undefined) as (input: unknown) => Promise<unknown>,
8 +}));
9 +
10 +vi.mock(import("../../state/session"), async (importOriginal) => ({
11 + ...(await importOriginal()),
12 + useEnvironmentScope: (() => true) as never,
13 + readEnvironmentScope: (() => true) as never,
14 +}));
15 +
16 +vi.mock(import("../../state/use-atom-command"), async (importOriginal) => ({
17 + ...(await importOriginal()),
18 + useAtomCommand: (() => (input: unknown) => state.switchRef(input)) as never,
19 +}));
20 +
21 +vi.mock(import("../../state/use-orchestration-command"), async (importOriginal) => ({
22 + ...(await importOriginal()),
23 + useOrchestrationCommand: (() => async () => ({ _tag: "Success", value: undefined })) as never,
24 +}));
25 +
26 +vi.mock(import("../../hooks/useThreadActions"), async (importOriginal) => ({
27 + ...(await importOriginal()),
28 + useThreadActions: (() => ({})) as never,
29 + useAcknowledgeThreadWoke: (() => () => undefined) as never,
30 +}));
31 +
32 +vi.mock(import("../../state/entities"), async (importOriginal) => ({
33 + ...(await importOriginal()),
34 + useChildThreadInputs: (() => []) as never,
35 +}));
36 +
37 +import { render } from "../../../test/render";
38 +import { useThreadLifecycle } from "./useThreadLifecycle";
39 +
40 +const environmentId = EnvironmentId.make("environment:test");
41 +
42 +function setup() {
43 + state.switchRef = async () => undefined;
44 +}
45 +
46 +function threadInput(threadId: string, branch: string) {
47 + const ref = scopeThreadRef(environmentId, ThreadId.make(threadId));
48 + const thread = { id: ref.threadId, environmentId, branch, worktreePath: null };
49 + return {
50 + routeThreadKey: scopedThreadKey(ref),
51 + activeThread: thread as never,
52 + activeThreadId: ref.threadId,
53 + activeThreadRef: ref,
54 + threadDetailRef: ref,
55 + activeThreadKey: scopedThreadKey(ref),
56 + localCheckoutBranchMismatch: { threadBranch: branch, currentBranch: "main" },
57 + };
58 +}
59 +
60 +type ThreadInput = ReturnType<typeof threadInput>;
61 +
62 +function RestoreBranchHarness(props: {
63 + readonly thread: ThreadInput;
64 + readonly currentRouteThreadKeyRef: { readonly current: string | null };
65 + readonly refreshGitStatus: () => void;
66 + readonly focusComposer: () => void;
67 +}) {
68 + const lifecycle = useThreadLifecycle({
69 + ...props.thread,
70 + environmentId,
71 + currentRouteThreadKeyRef: props.currentRouteThreadKeyRef,
72 + canOperateThread: true,
73 + clientSettingsHydrated: true,
74 + activeThreadShell: null,
75 + activeLatestRun: null as never,
76 + activeProjectCwd: "/repo",
77 + serverConfig: null,
78 + runtimeMode: "full-access" as never,
79 + isWorking: false,
80 + pendingBackgroundTasks: [],
81 + turnItems: [],
82 + activePendingApproval: null as never,
83 + activePendingUserInput: null as never,
84 + gitStatusQuery: { refresh: props.refreshGitStatus },
85 + nowMinute: "",
86 + composerRef: { current: { focusAtEnd: props.focusComposer } } as never,
87 + composerDraftTarget: { kind: "thread", ref: props.thread.activeThreadRef } as never,
88 + sendInFlightRef: { current: false },
89 + setOptimisticUserMessages: () => undefined,
90 + setThreadError: () => undefined,
91 + clearUsageLimitsFor: () => undefined,
92 + beginLocalDispatch: () => undefined,
93 + resetLocalDispatch: () => undefined,
94 + scrollToEnd: () => undefined,
95 + persistThreadSettingsForNextTurn: async () => ({ _tag: "Success", value: undefined }) as never,
96 + });
97 + return (
98 + <button
99 + type="button"
100 + disabled={lifecycle.isRestoringThreadBranch}
101 + onClick={lifecycle.handleSwitchCheckoutToThreadStable}
102 + >
103 + {lifecycle.isRestoringThreadBranch ? "Restoring..." : "Restore branch"}
104 + </button>
105 + );
106 +}
107 +
108 +it.each(["a", "b", "navigation"] as const)(
109 + "isolates restore completion and queued focus for %s",
110 + async (scenario) => {
111 + const first = scenario === "b" ? "b" : "a";
112 + setup();
113 + const completions: Array<(result: unknown) => void> = [];
114 + const switchRef = vi.fn(() => new Promise<unknown>((resolve) => completions.push(resolve)));
115 + state.switchRef = switchRef;
116 + const threadA = threadInput("thread:a", "feature-a");
117 + const threadB = threadInput("thread:b", "feature-b");
118 + const currentRouteThreadKeyRef = { current: threadA.routeThreadKey };
119 + const refreshGitStatus = vi.fn();
120 + const focusComposer = vi.fn();
121 + const harness = (thread: ThreadInput) => (
122 + <RestoreBranchHarness
123 + thread={thread}
124 + currentRouteThreadKeyRef={currentRouteThreadKeyRef}
125 + refreshGitStatus={refreshGitStatus}
126 + focusComposer={focusComposer}
127 + />
128 + );
129 + await using screen = await render(harness(threadA));
130 + const focusFrames: FrameRequestCallback[] = [];
131 + using _frame = vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {
132 + focusFrames.push(callback);
133 + return 0;
134 + });
135 +
136 + await page.getByRole("button", { name: "Restore branch" }).click();
137 + await expect.element(page.getByRole("button", { name: "Restoring..." })).toBeDisabled();
138 +
139 + // ChatView stays mounted across server threads, so the hook sees thread B in place.
140 + currentRouteThreadKeyRef.current = threadB.routeThreadKey;
141 + await screen.rerender(harness(threadB));
142 + await expect.element(page.getByRole("button", { name: "Restore branch" })).toBeEnabled();
143 + await page.getByRole("button", { name: "Restore branch" }).click();
144 + expect(switchRef).toHaveBeenLastCalledWith(
145 + expect.objectContaining({ input: { cwd: "/repo", refName: "feature-b" } }),
146 + );
147 +
148 + // Back on thread A, its own restore is still pending, so it can't start a second one.
149 + currentRouteThreadKeyRef.current = threadA.routeThreadKey;
150 + await screen.rerender(harness(threadA));
151 + await expect.element(page.getByRole("button", { name: "Restoring..." })).toBeDisabled();
152 + currentRouteThreadKeyRef.current = threadB.routeThreadKey;
153 + await screen.rerender(harness(threadB));
154 +
155 + const completed = first === "a" ? threadA : threadB;
156 + const pending = first === "a" ? threadB : threadA;
157 + currentRouteThreadKeyRef.current = pending.routeThreadKey;
158 + await screen.rerender(harness(pending));
159 + completions[first === "a" ? 0 : 1]!({
160 + _tag: "Success",
161 + value: { refName: completed.localCheckoutBranchMismatch.threadBranch },
162 + });
163 + await vi.waitFor(() => expect(refreshGitStatus).toHaveBeenCalledOnce());
164 + expect(focusComposer).not.toHaveBeenCalled();
165 + await expect.element(page.getByRole("button", { name: "Restoring..." })).toBeDisabled();
166 + expect(switchRef).toHaveBeenCalledTimes(2);
167 +
168 + completions[first === "a" ? 1 : 0]!({
169 + _tag: "Success",
170 + value: { refName: pending.localCheckoutBranchMismatch.threadBranch },
171 + });
172 + await expect.element(page.getByRole("button", { name: "Restore branch" })).toBeEnabled();
173 + expect(refreshGitStatus).toHaveBeenCalledTimes(2);
174 + expect(focusComposer).not.toHaveBeenCalled();
175 + expect(focusFrames).toHaveLength(1);
176 + if (scenario === "navigation") {
177 + currentRouteThreadKeyRef.current = completed.routeThreadKey;
178 + await screen.rerender(harness(completed));
179 + }
180 + focusFrames[0]!(0);
181 + expect(focusComposer).toHaveBeenCalledTimes(scenario === "navigation" ? 0 : 1);
182 + },
183 +);
apps/web/src/components/chat/useThreadLifecycle.tsx
+22 -9
@@ -114,7 +114,6 @@ interface ThreadLifecycleInput {
114 readonly clearUsageLimitsFor: (threadKey: string) => void;
115 readonly beginLocalDispatch: LocalDispatchState["beginLocalDispatch"];
116 readonly resetLocalDispatch: LocalDispatchState["resetLocalDispatch"];
117 - readonly scheduleComposerFocus: () => void;
117 readonly scrollToEnd: (animated?: boolean) => void;
118 readonly persistThreadSettingsForNextTurn: (input: {
119 threadId: ThreadId;
@@ -163,7 +162,6 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {
162 clearUsageLimitsFor,
163 beginLocalDispatch,
164 resetLocalDispatch,
166 - scheduleComposerFocus,
165 scrollToEnd,
166 persistThreadSettingsForNextTurn,
167 } = input;
@@ -294,7 +292,11 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {
292 setUnsnoozingThreadKey((current) => (current === threadKey ? null : current));
293 };
294 const handleUnsnoozeActiveThreadStable = useStableCallback(handleUnsnoozeActiveThread);
297 - const [isRestoringThreadBranch, setIsRestoringThreadBranch] = useState(false);
295 + const [restoringBranchThreadKeys, setRestoringBranchThreadKeys] = useState<ReadonlySet<string>>(
296 + () => new Set(),
297 + );
298 + const isRestoringThreadBranch =
299 + activeThreadKey !== null && restoringBranchThreadKeys.has(activeThreadKey);
300 const [revealedBranchMismatchKey, setRevealedBranchMismatchKey] = useState<string | null>(null);
301 const [, setBranchMismatchDismissTick] = useState(0);
302 const composerHasDraftContent = useComposerDraftStore((store) =>
@@ -329,7 +331,14 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {
331 ) {
332 return;
333 }
332 - setIsRestoringThreadBranch(true);
334 + const threadKey = scopedThreadKey(scopeThreadRef(environmentId, activeThread.id));
335 + const finishRestore = () =>
336 + setRestoringBranchThreadKeys((current) => {
337 + const next = new Set(current);
338 + next.delete(threadKey);
339 + return next;
340 + });
341 + setRestoringBranchThreadKeys((current) => new Set(current).add(threadKey));
342 const checkoutResult = await switchGitRef({
343 environmentId,
344 input: {
@@ -338,7 +347,7 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {
347 },
348 });
349 if (checkoutResult._tag === "Failure") {
341 - setIsRestoringThreadBranch(false);
350 + finishRestore();
351 if (!isAtomCommandInterrupted(checkoutResult)) {
352 toastManager.add(
353 stackedThreadToast({
@@ -352,7 +361,7 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {
361 }
362
363 if (!readEnvironmentScope(environmentId, AuthSourceControlWriteScope)) {
355 - setIsRestoringThreadBranch(false);
364 + finishRestore();
365 return;
366 }
367 const nextBranch = checkoutResult.value.refName ?? localCheckoutBranchMismatch.threadBranch;
@@ -362,7 +371,7 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {
371 input: { threadId: activeThread.id, branch: nextBranch, worktreePath: null },
372 });
373 if (updateResult._tag === "Failure") {
365 - setIsRestoringThreadBranch(false);
374 + finishRestore();
375 if (!isAtomCommandInterrupted(updateResult)) {
376 toastManager.add(
377 stackedThreadToast({
@@ -377,8 +386,12 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {
386 }
387 }
388 gitStatusQuery.refresh();
380 - setIsRestoringThreadBranch(false);
381 - scheduleComposerFocus();
389 + finishRestore();
390 + if (currentRouteThreadKeyRef.current === routeThreadKey) {
391 + window.requestAnimationFrame(() => {
392 + if (currentRouteThreadKeyRef.current === routeThreadKey) composerRef.current?.focusAtEnd();
393 + });
394 + }
395 };
396 const handleSwitchCheckoutToThreadStable = useStableCallback(() => {
397 void handleSwitchCheckoutToThread();