Skip to content

Commit d93656b

Browse files
fix(web): keep active turns in their selected worktree
1 parent ddb64f5 commit d93656b

6 files changed

Lines changed: 261 additions & 429 deletions

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

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,6 @@ export function BranchPicker({
4242
onLoadNext,
4343
statusText,
4444
notice,
45-
extraData,
4645
originControl,
4746
popupProps,
4847
renderItem,
@@ -63,8 +62,6 @@ export function BranchPicker({
6362
onLoadNext: () => void;
6463
statusText: string | null;
6564
notice?: string | null | undefined;
66-
/** Rows re-render only when their item or this value changes. */
67-
extraData?: unknown;
6865
originControl?: { checked: boolean; onCheckedChange: (checked: boolean) => void } | undefined;
6966
popupProps: Omit<ComponentProps<typeof ComboboxPopup>, "children">;
7067
renderItem: (value: string, index: number) => ReactNode;
@@ -203,7 +200,7 @@ export function BranchPicker({
203200
keyExtractor={(item) => item}
204201
{...(getItemType ? { getItemType } : {})}
205202
renderItem={({ item, index }) => renderItem(item, index)}
206-
extraData={extraData}
203+
extraData={renderItem}
207204
estimatedItemSize={28}
208205
drawDistance={336}
209206
onLayout={() => {

‎apps/web/src/components/BranchToolbar.logic.test.ts‎

Lines changed: 1 addition & 88 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
1-
import type { ThreadRuntimeSummary } from "@t3tools/client-runtime/state/shell";
2-
import { EnvironmentId, ProviderInstanceId, RunId, type VcsRef } from "@t3tools/contracts";
1+
import { EnvironmentId, type VcsRef } from "@t3tools/contracts";
32
import { describe, expect, it } from "vite-plus/test";
43
import {
54
dedupeRemoteBranchesWithLocalMatches,
65
deriveLocalBranchNameFromRemoteRef,
7-
isWorktreeChangeBlocked,
86
resolveEnvironmentOptionLabel,
97
resolveBranchSelectionTarget,
108
resolveCurrentWorkspaceLabel,
@@ -873,88 +871,3 @@ describe("sanitizeNewRefName", () => {
873871
expect(sanitizeNewRefName("foo--bar")).toBe("foo--bar");
874872
});
875873
});
876-
877-
describe("isWorktreeChangeBlocked", () => {
878-
const runtime = (
879-
status: ThreadRuntimeSummary["status"],
880-
activeRunId: string | null = "run-1",
881-
): ThreadRuntimeSummary => ({
882-
status,
883-
activeRunId: activeRunId === null ? null : RunId.make(activeRunId),
884-
providerInstanceId: ProviderInstanceId.make("codex"),
885-
providerName: null,
886-
lastError: null,
887-
updatedAt: "2026-10-02T00:00:00.000Z",
888-
});
889-
const secondaryWorktree = "/repo/.t3/worktrees/feature-a";
890-
891-
it.each(["preparing", "starting", "running", "waiting"] as const)(
892-
"blocks a worktree change while the run is %s",
893-
(status) => {
894-
expect(
895-
isWorktreeChangeBlocked({
896-
runtime: runtime(status),
897-
currentWorktreePath: null,
898-
nextWorktreePath: secondaryWorktree,
899-
}),
900-
).toBe(true);
901-
},
902-
);
903-
904-
it("blocks a worktree change while a queued run waits on an attached run", () => {
905-
expect(
906-
isWorktreeChangeBlocked({
907-
runtime: runtime("queued"),
908-
currentWorktreePath: null,
909-
nextWorktreePath: secondaryWorktree,
910-
}),
911-
).toBe(true);
912-
});
913-
914-
it.each([
915-
["the thread has no runtime", null],
916-
["the thread is idle", runtime("idle", null)],
917-
["the last run completed", runtime("completed", null)],
918-
["the last run was interrupted", runtime("interrupted", null)],
919-
["only a queued run remains", runtime("queued", null)],
920-
])("allows a worktree change when %s", (_label, threadRuntime) => {
921-
expect(
922-
isWorktreeChangeBlocked({
923-
runtime: threadRuntime,
924-
currentWorktreePath: null,
925-
nextWorktreePath: secondaryWorktree,
926-
}),
927-
).toBe(false);
928-
});
929-
930-
it.each([
931-
["the main checkout", null],
932-
["a secondary worktree", secondaryWorktree],
933-
])("allows staying in %s mid-run", (_label, worktreePath) => {
934-
expect(
935-
isWorktreeChangeBlocked({
936-
runtime: runtime("running"),
937-
currentWorktreePath: worktreePath,
938-
nextWorktreePath: worktreePath,
939-
}),
940-
).toBe(false);
941-
});
942-
943-
it.each([
944-
["a ref checked out in the main repo", { isDefault: false, worktreePath: "/repo" }],
945-
["the default ref with no checkout", { isDefault: true, worktreePath: null }],
946-
])("blocks returning to the main checkout via %s mid-run", (_label, refName) => {
947-
const { nextWorktreePath } = resolveBranchSelectionTarget({
948-
activeProjectCwd: "/repo",
949-
activeWorktreePath: secondaryWorktree,
950-
refName,
951-
});
952-
expect(
953-
isWorktreeChangeBlocked({
954-
runtime: runtime("running"),
955-
currentWorktreePath: secondaryWorktree,
956-
nextWorktreePath,
957-
}),
958-
).toBe(true);
959-
});
960-
});

‎apps/web/src/components/BranchToolbar.logic.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -278,8 +278,6 @@ export function resolveBranchSelectionTarget(input: {
278278
};
279279
}
280280

281-
// The server detaches the provider session when a thread's worktree changes, which
282-
// interrupts the run in progress. Block that while the user could still Stop the run.
283281
export function isWorktreeChangeBlocked(input: {
284282
runtime: ThreadRuntimeSummary | null;
285283
currentWorktreePath: string | null;

‎apps/web/src/components/BranchToolbar.panel.browser.test.tsx‎

Lines changed: 212 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
1-
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
1+
import type { ThreadRuntimeSummary } from "@t3tools/client-runtime/state/shell";
2+
import {
3+
EnvironmentId,
4+
ProjectId,
5+
ProviderInstanceId,
6+
RunId,
7+
ThreadId,
8+
type VcsRef,
9+
} from "@t3tools/contracts";
210
import { act, type ComponentProps } from "react";
311
import { createRoot, type Root } from "react-dom/client";
412
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
@@ -8,6 +16,14 @@ import "~/index.css";
816

917
const state = vi.hoisted(() => ({
1018
worktreePath: "/tmp/worktree" as string | null,
19+
runtime: null as ThreadRuntimeSummary | null,
20+
latest: null as { worktreePath: string | null; runtime: ThreadRuntimeSummary | null } | null,
21+
refs: [] as VcsRef[],
22+
updateMetadata: vi.fn(),
23+
stopSession: vi.fn(),
24+
switchRef: vi.fn(),
25+
createRef: vi.fn(),
26+
refresh: vi.fn(),
1127
showContextMenu: vi.fn(),
1228
writeTextToClipboard: vi.fn(),
1329
}));
@@ -20,21 +36,78 @@ vi.mock(import("../hooks/useCopyToClipboard"), async (original) => ({
2036
...(await original()),
2137
writeTextToClipboard: state.writeTextToClipboard,
2238
}));
23-
vi.mock(import("./BranchToolbarBranchSelector"), async (original) => ({
24-
...(await original()),
25-
BranchToolbarBranchSelector: (() => null) as never,
26-
}));
2739
vi.mock(import("../state/entities"), async (original) => ({
2840
...(await original()),
2941
useQuietThreadShell: (() => ({
42+
id: "thread",
3043
environmentId: "local",
3144
projectId: "project",
45+
branch: "topic",
3246
worktreePath: state.worktreePath,
47+
runtime: state.runtime,
48+
pullRequests: [],
3349
})) as never,
34-
useProject: (() => ({ workspaceRoot: "/tmp/project" })) as never,
50+
readThreadShell: (() =>
51+
state.latest ?? {
52+
worktreePath: state.worktreePath,
53+
runtime: state.runtime,
54+
}) as never,
55+
useProject: (() => ({ id: "project", workspaceRoot: "/tmp/project" })) as never,
3556
useThreadShellsForProjectRefs: () => [],
3657
}));
3758

59+
vi.mock(import("../state/session"), async (original) => ({
60+
...(await original()),
61+
useEnvironmentScope: () => true,
62+
readEnvironmentScope: () => true,
63+
}));
64+
vi.mock(import("../state/use-atom-command"), async (original) => {
65+
const { threadEnvironment } = await import("../state/threads");
66+
const { vcsEnvironment } = await import("../state/vcs");
67+
return {
68+
...(await original()),
69+
useAtomCommand: ((command: unknown) =>
70+
command === threadEnvironment.stopSession
71+
? state.stopSession
72+
: command === threadEnvironment.updateMetadata
73+
? state.updateMetadata
74+
: command === vcsEnvironment.switchRef
75+
? state.switchRef
76+
: state.createRef) as never,
77+
};
78+
});
79+
vi.mock(import("../state/query"), async (original) => ({
80+
...(await original()),
81+
useEnvironmentQuery: (() => ({
82+
data: { refName: "topic", refs: state.refs },
83+
refresh: state.refresh,
84+
})) as never,
85+
}));
86+
vi.mock(import("../state/queries"), async (original) => ({
87+
...(await original()),
88+
usePaginatedBranches: (() => ({
89+
refs: state.refs,
90+
data: { nextCursor: null, totalCount: state.refs.length },
91+
refresh: state.refresh,
92+
isPending: false,
93+
})) as never,
94+
}));
95+
vi.mock(import("../hooks/useSupportsMultiplePullRequests"), async (original) => ({
96+
...(await original()),
97+
useSupportsMultiplePullRequests: () => false,
98+
}));
99+
vi.mock(import("../lib/openPullRequestLink"), async (original) => ({
100+
...(await original()),
101+
useOpenPrLink: () => vi.fn(),
102+
}));
103+
vi.mock(import("./ThreadStatusIndicators"), async (original) => ({
104+
...(await original()),
105+
ThreadPullRequestBadgeControl: (() => null) as never,
106+
prStatusIndicator: () => null,
107+
resolveThreadPullRequestBadge: () => null,
108+
useLinkedThreadPullRequest: () => null,
109+
}));
110+
38111
import { BranchToolbar } from "./BranchToolbar";
39112

40113
let root: Root;
@@ -43,6 +116,32 @@ let container: HTMLDivElement;
43116
beforeEach(() => {
44117
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
45118
state.worktreePath = "/tmp/worktree";
119+
state.runtime = null;
120+
state.latest = null;
121+
state.refs = [
122+
{
123+
name: "main",
124+
isDefault: true,
125+
isRemote: false,
126+
current: false,
127+
worktreePath: "/tmp/project",
128+
},
129+
{
130+
name: "topic",
131+
isDefault: false,
132+
isRemote: false,
133+
current: true,
134+
worktreePath: "/tmp/worktree",
135+
},
136+
{ name: "other", isDefault: false, isRemote: false, current: false, worktreePath: null },
137+
];
138+
state.updateMetadata.mockReset().mockResolvedValue({ _tag: "Success" });
139+
state.stopSession.mockReset().mockResolvedValue({ _tag: "Success" });
140+
state.switchRef.mockReset().mockResolvedValue({ _tag: "Success", value: { refName: "other" } });
141+
state.createRef
142+
.mockReset()
143+
.mockResolvedValue({ _tag: "Success", value: { refName: "new-topic" } });
144+
state.refresh.mockReset();
46145
state.showContextMenu.mockReset().mockResolvedValue("copy-path");
47146
state.writeTextToClipboard.mockReset().mockResolvedValue(true);
48147
container = document.createElement("div");
@@ -146,3 +245,110 @@ it.each([
146245
}
147246
},
148247
);
248+
249+
function running(status: ThreadRuntimeSummary["status"] = "running"): ThreadRuntimeSummary {
250+
return {
251+
status,
252+
activeRunId: RunId.make("new-run"),
253+
providerInstanceId: ProviderInstanceId.make("codex"),
254+
providerName: null,
255+
lastError: null,
256+
updatedAt: "2026-10-16T00:00:00Z",
257+
};
258+
}
259+
260+
const branchProps = { panelSection: "branch", envMode: "worktree", envLocked: true } as const;
261+
262+
async function openBranches() {
263+
await userEvent.click(container.querySelector<HTMLElement>('[data-slot="combobox-trigger"]')!);
264+
await expect.element(page.getByRole("option", { name: "main default" })).toBeVisible();
265+
}
266+
267+
it.each([
268+
["preparing", "panel"],
269+
["starting", "composer"],
270+
["running", "panel"],
271+
["waiting", "composer"],
272+
] as const)("keeps a %s turn in its worktree through the %s picker", async (status, layout) => {
273+
state.runtime = running(status);
274+
const props = { ...branchProps, layout };
275+
await render(props);
276+
await openBranches();
277+
await expect
278+
.element(page.getByRole("option", { name: "main default" }))
279+
.toHaveAttribute("aria-disabled", "true");
280+
await expect.element(page.getByText("Stop the current turn to switch worktrees.")).toBeVisible();
281+
await userEvent.click(page.getByRole("option", { name: "topic current" }));
282+
expect(state.updateMetadata).toHaveBeenCalledWith({
283+
environmentId: "local",
284+
input: { threadId: "thread", branch: "topic", worktreePath: "/tmp/worktree" },
285+
});
286+
expect(state.stopSession).not.toHaveBeenCalled();
287+
288+
await openBranches();
289+
state.runtime = null;
290+
await render(props);
291+
await expect
292+
.element(page.getByRole("option", { name: "main default" }))
293+
.not.toHaveAttribute("aria-disabled", "true");
294+
await userEvent.click(page.getByRole("option", { name: "main default" }));
295+
expect(state.updateMetadata).toHaveBeenLastCalledWith({
296+
environmentId: "local",
297+
input: { threadId: "thread", branch: "main", worktreePath: null },
298+
});
299+
});
300+
301+
it.each(["existing worktree", "worktree base"] as const)(
302+
"rechecks the store before applying a stale %s selection",
303+
async (selection) => {
304+
state.worktreePath = null;
305+
await render({ ...branchProps, envLocked: selection === "existing worktree" });
306+
await openBranches();
307+
const option = page.getByRole("option", {
308+
name: selection === "existing worktree" ? "topic current" : "main default",
309+
});
310+
await expect.element(option).not.toHaveAttribute("aria-disabled", "true");
311+
// Simulate another client's update before React has rendered it.
312+
state.latest = { worktreePath: "/tmp/new-worktree", runtime: running() };
313+
await userEvent.click(option);
314+
expect(state.updateMetadata).not.toHaveBeenCalled();
315+
expect(state.stopSession).not.toHaveBeenCalled();
316+
expect(state.switchRef).not.toHaveBeenCalled();
317+
},
318+
);
319+
320+
it("does not automatically assign a base after another client starts the thread", async () => {
321+
state.worktreePath = null;
322+
state.latest = { worktreePath: "/tmp/new-worktree", runtime: running("preparing") };
323+
await render({ ...branchProps, envLocked: false, activeThreadBranchOverride: null });
324+
expect(state.updateMetadata).not.toHaveBeenCalled();
325+
expect(state.stopSession).not.toHaveBeenCalled();
326+
});
327+
328+
it.each(["checkout", "ref creation"] as const)(
329+
"does not stop or retarget a run that starts while %s awaits",
330+
async (action) => {
331+
const result = { _tag: "Success", value: { refName: "new-topic" } } as const;
332+
let resolve!: (value: typeof result) => void;
333+
const pending = new Promise<typeof result>((done) => {
334+
resolve = done;
335+
});
336+
const mutation = action === "checkout" ? state.switchRef : state.createRef;
337+
mutation.mockReturnValueOnce(pending);
338+
await render(branchProps);
339+
await openBranches();
340+
if (action === "checkout") {
341+
await userEvent.click(page.getByRole("option", { name: "other", exact: true }));
342+
} else {
343+
await userEvent.fill(page.getByPlaceholder("Search refs..."), "new-topic");
344+
await userEvent.click(page.getByRole("option", { name: 'Create new ref "new-topic"' }));
345+
}
346+
expect(mutation).toHaveBeenCalledOnce();
347+
expect(state.updateMetadata).not.toHaveBeenCalled();
348+
state.latest = { worktreePath: "/tmp/new-worktree", runtime: running() };
349+
await act(async () => resolve(result));
350+
expect(state.refresh).toHaveBeenCalled();
351+
expect(state.stopSession).not.toHaveBeenCalled();
352+
expect(state.updateMetadata).not.toHaveBeenCalled();
353+
},
354+
);

0 commit comments

Comments
 (0)