Open History to see the last commit
1import * as Cause from "effect/Cause";
2import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
3import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
4import { EnvironmentId, ThreadId } from "@t3tools/contracts";
5import { expect, it, vi } from "vite-plus/test";
6import { page, userEvent } from "vite-plus/test/browser";
7
8const state = vi.hoisted(() => ({
9 childThreadInputs: [] as EnvironmentThreadShell[],
10 switchRef: (async () => undefined) as (input: unknown) => Promise<unknown>,
11 threadActions: {} as Record<string, unknown>,
12}));
13
14vi.mock(import("../../state/session"), async (importOriginal) => ({
15 ...(await importOriginal()),
16 useEnvironmentScope: (() => true) as never,
17 readEnvironmentScope: (() => true) as never,
18}));
19
20vi.mock(import("../../state/use-atom-command"), async (importOriginal) => ({
21 ...(await importOriginal()),
22 useAtomCommand: (() => (input: unknown) => state.switchRef(input)) as never,
23}));
24
25vi.mock(import("../../state/use-orchestration-command"), async (importOriginal) => ({
26 ...(await importOriginal()),
27 useOrchestrationCommand: (() => (input: unknown) => state.switchRef(input)) as never,
28}));
29
30vi.mock(import("../../hooks/useThreadActions"), async (importOriginal) => ({
31 ...(await importOriginal()),
32 useThreadActions: (() => state.threadActions) as never,
33 useAcknowledgeThreadWoke: (() => () => undefined) as never,
34}));
35
36vi.mock(import("../../state/entities"), async (importOriginal) => ({
37 ...(await importOriginal()),
38 useChildThreadInputs: (() => state.childThreadInputs) as never,
39}));
40
41import { render } from "../../../test/render";
42import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
43import { useThreadLifecycle } from "./useThreadLifecycle";
44
45const environmentId = EnvironmentId.make("environment:test");
46
47function setup() {
48 state.childThreadInputs = [];
49 state.switchRef = async () => undefined;
50 state.threadActions = {};
51}
52
53function threadInput(threadId: string, branch: string) {
54 const ref = scopeThreadRef(environmentId, ThreadId.make(threadId));
55 const thread = { id: ref.threadId, environmentId, branch, worktreePath: null };
56 return {
57 routeThreadKey: scopedThreadKey(ref),
58 activeThread: thread as never,
59 activeThreadId: ref.threadId,
60 activeThreadRef: ref,
61 threadDetailRef: ref,
62 activeThreadKey: scopedThreadKey(ref),
63 localCheckoutBranchMismatch: { threadBranch: branch, currentBranch: "main" },
64 };
65}
66
67type ThreadInput = ReturnType<typeof threadInput>;
68type Shortcuts = ReturnType<typeof useThreadLifecycle>["shortcuts"];
69
70it.each([
71 { remote: false, approval: false, link: "Open question" },
72 { remote: true, approval: false, link: "Open question" },
73 { remote: true, approval: false, link: "Child" },
74 { remote: true, approval: true, link: "Open approval" },
75])("opens the child in its environment ($remote, $link)", async ({ remote, approval, link }) => {
76 setup();
77 const parent = threadInput("parent", "main");
78 const childEnvironmentId = remote ? EnvironmentId.make("remote") : environmentId;
79 state.childThreadInputs = [
80 {
81 id: ThreadId.make("child"),
82 environmentId: childEnvironmentId,
83 title: "Child",
84 hasPendingApprovals: approval,
85 lineage: { sideChat: false },
86 } as EnvironmentThreadShell,
87 ];
88 await using screen = await render(
89 <RestoreBranchHarness
90 thread={parent}
91 currentRouteThreadKeyRef={{ current: parent.routeThreadKey }}
92 refreshGitStatus={() => undefined}
93 focusComposer={() => undefined}
94 />,
95 { router: "/environment:test/parent" },
96 );
97 await screen.getByRole("button", { name: link, exact: true }).click();
98 await vi.waitFor(() =>
99 expect(screen.router?.state.location.pathname).toBe(
100 `/${encodeURIComponent(childEnvironmentId)}/child`,
101 ),
102 );
103});
104
105function RestoreBranchHarness(props: {
106 readonly thread: ThreadInput;
107 readonly currentRouteThreadKeyRef: { readonly current: string | null };
108 readonly refreshGitStatus: () => void;
109 readonly focusComposer: () => void;
110 readonly shell?: EnvironmentThreadShell;
111 readonly onShortcuts?: (shortcuts: Shortcuts) => void;
112}) {
113 const lifecycle = useThreadLifecycle({
114 ...props.thread,
115 environmentId,
116 currentRouteThreadKeyRef: props.currentRouteThreadKeyRef,
117 canOperateThread: true,
118 clientSettingsHydrated: true,
119 activeThreadShell: props.shell ?? null,
120 limitRecoveryHoldsSnooze: false,
121 activeLatestRun: null as never,
122 activeProjectCwd: "/repo",
123 serverConfig: props.shell ? ({} as never) : null,
124 runtimeMode: "full-access" as never,
125 isWorking: false,
126 runIsLive: false,
127 pendingBackgroundTasks: [{ taskId: "background-command", kind: "command" }] as never,
128 turnItems: [],
129 activePendingApproval: null as never,
130 activePendingUserInput: null as never,
131 gitStatusQuery: { refresh: props.refreshGitStatus },
132 nowMinute: "",
133 composerRef: { current: { focusAtEnd: props.focusComposer } } as never,
134 composerDraftTarget: { kind: "thread", ref: props.thread.activeThreadRef } as never,
135 sendInFlightRef: { current: false },
136 setOptimisticUserMessages: () => undefined,
137 setThreadError: () => undefined,
138 clearUsageLimitsFor: () => undefined,
139 beginLocalDispatch: () => undefined,
140 resetLocalDispatch: () => undefined,
141 scrollToEnd: () => undefined,
142 persistThreadSettingsForNextTurn: async () => ({ _tag: "Success", value: undefined }) as never,
143 });
144 props.onShortcuts?.(lifecycle.shortcuts);
145 return (
146 <>
147 {lifecycle.childInputNow?.description}
148 {lifecycle.childInputNow?.actions}
149 {lifecycle.workNow?.actions}
150 <button
151 type="button"
152 disabled={lifecycle.isRestoringThreadBranch}
153 onClick={lifecycle.handleSwitchCheckoutToThreadStable}
154 >
155 {lifecycle.isRestoringThreadBranch ? "Restoring..." : "Restore branch"}
156 </button>
157 </>
158 );
159}
160
161it.each(["a", "b", "navigation"] as const)(
162 "isolates restore completion and queued focus for %s",
163 async (scenario) => {
164 const first = scenario === "b" ? "b" : "a";
165 setup();
166 const completions: Array<(result: unknown) => void> = [];
167 const switchRef = vi.fn(() => new Promise<unknown>((resolve) => completions.push(resolve)));
168 state.switchRef = switchRef;
169 const threadA = threadInput("thread:a", "feature-a");
170 const threadB = threadInput("thread:b", "feature-b");
171 const currentRouteThreadKeyRef = { current: threadA.routeThreadKey };
172 const refreshGitStatus = vi.fn();
173 const focusComposer = vi.fn();
174 const harness = (thread: ThreadInput) => (
175 <RestoreBranchHarness
176 thread={thread}
177 currentRouteThreadKeyRef={currentRouteThreadKeyRef}
178 refreshGitStatus={refreshGitStatus}
179 focusComposer={focusComposer}
180 />
181 );
182 await using screen = await render(harness(threadA));
183 const focusFrames: FrameRequestCallback[] = [];
184 using _frame = vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {
185 focusFrames.push(callback);
186 return 0;
187 });
188
189 await page.getByRole("button", { name: "Restore branch" }).click();
190 await expect.element(page.getByRole("button", { name: "Restoring..." })).toBeDisabled();
191
192 // ChatView stays mounted across server threads, so the hook sees thread B in place.
193 currentRouteThreadKeyRef.current = threadB.routeThreadKey;
194 await screen.rerender(harness(threadB));
195 await expect.element(page.getByRole("button", { name: "Restore branch" })).toBeEnabled();
196 await page.getByRole("button", { name: "Restore branch" }).click();
197 expect(switchRef).toHaveBeenLastCalledWith(
198 expect.objectContaining({ input: { cwd: "/repo", refName: "feature-b" } }),
199 );
200
201 // Back on thread A, its own restore is still pending, so it can't start a second one.
202 currentRouteThreadKeyRef.current = threadA.routeThreadKey;
203 await screen.rerender(harness(threadA));
204 await expect.element(page.getByRole("button", { name: "Restoring..." })).toBeDisabled();
205 currentRouteThreadKeyRef.current = threadB.routeThreadKey;
206 await screen.rerender(harness(threadB));
207
208 const completed = first === "a" ? threadA : threadB;
209 const pending = first === "a" ? threadB : threadA;
210 currentRouteThreadKeyRef.current = pending.routeThreadKey;
211 await screen.rerender(harness(pending));
212 completions[first === "a" ? 0 : 1]!({
213 _tag: "Success",
214 value: { refName: completed.localCheckoutBranchMismatch.threadBranch },
215 });
216 await vi.waitFor(() => expect(refreshGitStatus).toHaveBeenCalledOnce());
217 expect(focusComposer).not.toHaveBeenCalled();
218 await expect.element(page.getByRole("button", { name: "Restoring..." })).toBeDisabled();
219 expect(switchRef).toHaveBeenCalledTimes(2);
220
221 completions[first === "a" ? 1 : 0]!({
222 _tag: "Success",
223 value: { refName: pending.localCheckoutBranchMismatch.threadBranch },
224 });
225 await expect.element(page.getByRole("button", { name: "Restore branch" })).toBeEnabled();
226 expect(refreshGitStatus).toHaveBeenCalledTimes(2);
227 expect(focusComposer).not.toHaveBeenCalled();
228 expect(focusFrames).toHaveLength(1);
229 if (scenario === "navigation") {
230 currentRouteThreadKeyRef.current = completed.routeThreadKey;
231 await screen.rerender(harness(completed));
232 }
233 focusFrames[0]!(0);
234 expect(focusComposer).toHaveBeenCalledTimes(scenario === "navigation" ? 0 : 1);
235 },
236);
237
238it.each(["Success", "Failure"] as const)(
239 "keeps background stop requests per thread after %s",
240 async (outcome) => {
241 setup();
242 const completions: Array<(result: unknown) => void> = [];
243 state.switchRef = vi.fn(() => new Promise((resolve) => completions.push(resolve)));
244 const threadA = threadInput("thread:a", "feature-a");
245 const threadB = threadInput("thread:b", "feature-b");
246 const currentRouteThreadKeyRef = { current: threadA.routeThreadKey };
247 const harness = (thread: ThreadInput) => (
248 <RestoreBranchHarness
249 thread={thread}
250 currentRouteThreadKeyRef={currentRouteThreadKeyRef}
251 refreshGitStatus={() => undefined}
252 focusComposer={() => undefined}
253 />
254 );
255 await using screen = await render(harness(threadA));
256 await page.getByRole("button", { name: "Stop", exact: true }).click();
257 await expect.element(page.getByRole("button", { name: "Stopping..." })).toBeDisabled();
258 await screen.rerender(harness(threadB));
259 await page.getByRole("button", { name: "Stop", exact: true }).click();
260 await screen.rerender(harness(threadA));
261 await expect.element(page.getByRole("button", { name: "Stopping..." })).toBeDisabled();
262 completions[0]!(
263 outcome === "Success"
264 ? { _tag: "Success", value: undefined }
265 : { _tag: "Failure", cause: Cause.fail(new Error("stop failed")) },
266 );
267 if (outcome === "Success") {
268 await expect.element(page.getByRole("button", { name: "Stopping..." })).toBeDisabled();
269 } else {
270 await expect.element(page.getByRole("button", { name: "Stop", exact: true })).toBeEnabled();
271 }
272 await screen.rerender(harness(threadB));
273 await expect.element(page.getByRole("button", { name: "Stopping..." })).toBeDisabled();
274 expect(state.switchRef).toHaveBeenCalledTimes(2);
275 completions[1]!({ _tag: "Success", value: undefined });
276 },
277);
278
279it.each(["thread.settle", "thread.pin"] as const)(
280 "does not toggle back when the %s shortcut is held down",
281 async (command) => {
282 setup();
283 const unsettle = vi.fn(async () => ({ _tag: "Success", value: undefined }));
284 state.switchRef = unsettle;
285 const settleThread = vi.fn(async () => ({ _tag: "Success", value: undefined }));
286 const pinThread = vi.fn(async () => ({ _tag: "Success", value: undefined }));
287 const confirmAndUnpinThread = vi.fn(async () => ({ _tag: "Success", value: undefined }));
288 state.threadActions = { settleThread, pinThread, confirmAndUnpinThread };
289 const thread = threadInput("thread:a", "main");
290 let shortcuts: Shortcuts | undefined;
291 const harness = (shell: Partial<EnvironmentThreadShell>) => (
292 <RestoreBranchHarness
293 thread={thread}
294 currentRouteThreadKeyRef={{ current: thread.routeThreadKey }}
295 refreshGitStatus={() => undefined}
296 focusComposer={() => undefined}
297 shell={{ id: thread.activeThreadId, environmentId, ...shell } as EnvironmentThreadShell}
298 onShortcuts={(latest) => (shortcuts = latest)}
299 />
300 );
301 await using screen = await render(harness({}));
302 const press = (repeat: boolean) =>
303 shortcuts,
305 terminalFocusOwner: null,
306 });
307 expect(press(false)).toBeUndefined();
308 await screen.rerender(
309 harness(
310 command === "thread.settle"
311 ? { settledOverride: "settled" }
312 : { pinnedAt: "2026-01-01T00:00:00.000Z" },
313 ),
314 );
315 // The key is still held, so the browser keeps sending repeats; they are consumed only.
316 expect(press(true)).toBeUndefined();
317 expect(command === "thread.settle" ? settleThread : pinThread).toHaveBeenCalledOnce();
318 expect(unsettle).not.toHaveBeenCalled();
319 expect(confirmAndUnpinThread).not.toHaveBeenCalled();
320 },
321);
322
323it("leaves settle, pin, and regenerate-title shortcuts alone while a menu is open", async () => {
324 setup();
325 const settleThread = vi.fn(async () => ({ _tag: "Success", value: undefined }));
326 const pinThread = vi.fn(async () => ({ _tag: "Success", value: undefined }));
327 const atomCommand = vi.fn(async () => ({ _tag: "Success", value: undefined }));
328 state.switchRef = atomCommand;
329 state.threadActions = { settleThread, pinThread };
330 const thread = threadInput("thread:a", "main");
331 let shortcuts: Shortcuts | undefined;
332 await using screen = await render(
333 <>
334 <RestoreBranchHarness
335 thread={thread}
336 currentRouteThreadKeyRef={{ current: thread.routeThreadKey }}
337 refreshGitStatus={() => undefined}
338 focusComposer={() => undefined}
339 shell={{ id: thread.activeThreadId, environmentId } as EnvironmentThreadShell}
340 onShortcuts={(latest) => (shortcuts = latest)}
341 />
342 <Menu>
343 <MenuTrigger render={<button type="button" />}>Actions</MenuTrigger>
344 <MenuPopup>
345 <MenuItem>Item</MenuItem>
346 </MenuPopup>
347 </Menu>
348 </>,
349 );
350
351 await userEvent.click(screen.getByRole("button", { name: "Actions" }));
352 await expect.element(page.getByRole("menu")).toBeVisible();
353
354 for (const command of ["thread.settle", "thread.pin", "thread.regenerateTitle"] as const) {
355 expect(
356 shortcuts, terminalFocusOwner: null }),
357 ).toBe(false);
358 }
359 expect(settleThread).not.toHaveBeenCalled();
360 expect(pinThread).not.toHaveBeenCalled();
361 expect(atomCommand).not.toHaveBeenCalled();
362});