Skip to content

Commit 64968b3

Browse files
Batuhan1999claudemaria-rcks
authored
fix(web): a branch restore in one thread no longer blocks another thread (#24060)
Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: maria-rcks <[email protected]> Co-authored-by: maria-rcks <[email protected]>
1 parent ae45ccd commit 64968b3

3 files changed

Lines changed: 205 additions & 10 deletions

File tree

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2399,7 +2399,6 @@ export default function ChatView(props: ChatViewProps) {
23992399
clearUsageLimitsFor,
24002400
beginLocalDispatch,
24012401
resetLocalDispatch,
2402-
scheduleComposerFocus,
24032402
scrollToEnd,
24042403
persistThreadSettingsForNextTurn,
24052404
});
Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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‎

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,6 @@ interface ThreadLifecycleInput {
114114
readonly clearUsageLimitsFor: (threadKey: string) => void;
115115
readonly beginLocalDispatch: LocalDispatchState["beginLocalDispatch"];
116116
readonly resetLocalDispatch: LocalDispatchState["resetLocalDispatch"];
117-
readonly scheduleComposerFocus: () => void;
118117
readonly scrollToEnd: (animated?: boolean) => void;
119118
readonly persistThreadSettingsForNextTurn: (input: {
120119
threadId: ThreadId;
@@ -163,7 +162,6 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {
163162
clearUsageLimitsFor,
164163
beginLocalDispatch,
165164
resetLocalDispatch,
166-
scheduleComposerFocus,
167165
scrollToEnd,
168166
persistThreadSettingsForNextTurn,
169167
} = input;
@@ -294,7 +292,11 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {
294292
setUnsnoozingThreadKey((current) => (current === threadKey ? null : current));
295293
};
296294
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);
298300
const [revealedBranchMismatchKey, setRevealedBranchMismatchKey] = useState<string | null>(null);
299301
const [, setBranchMismatchDismissTick] = useState(0);
300302
const composerHasDraftContent = useComposerDraftStore((store) =>
@@ -329,7 +331,14 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {
329331
) {
330332
return;
331333
}
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));
333342
const checkoutResult = await switchGitRef({
334343
environmentId,
335344
input: {
@@ -338,7 +347,7 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {
338347
},
339348
});
340349
if (checkoutResult._tag === "Failure") {
341-
setIsRestoringThreadBranch(false);
350+
finishRestore();
342351
if (!isAtomCommandInterrupted(checkoutResult)) {
343352
toastManager.add(
344353
stackedThreadToast({
@@ -352,7 +361,7 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {
352361
}
353362

354363
if (!readEnvironmentScope(environmentId, AuthSourceControlWriteScope)) {
355-
setIsRestoringThreadBranch(false);
364+
finishRestore();
356365
return;
357366
}
358367
const nextBranch = checkoutResult.value.refName ?? localCheckoutBranchMismatch.threadBranch;
@@ -362,7 +371,7 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {
362371
input: { threadId: activeThread.id, branch: nextBranch, worktreePath: null },
363372
});
364373
if (updateResult._tag === "Failure") {
365-
setIsRestoringThreadBranch(false);
374+
finishRestore();
366375
if (!isAtomCommandInterrupted(updateResult)) {
367376
toastManager.add(
368377
stackedThreadToast({
@@ -377,8 +386,12 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {
377386
}
378387
}
379388
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+
}
382395
};
383396
const handleSwitchCheckoutToThreadStable = useStableCallback(() => {
384397
void handleSwitchCheckoutToThread();

0 commit comments

Comments
 (0)