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 readonly resetLocalDispatch?: () => void;
113 readonly setThreadError?: (threadId: ThreadId | null, error: string | null) => void;
114}) {
115 const lifecycle = useThreadLifecycle({
116 ...props.thread,
117 environmentId,
118 currentRouteThreadKeyRef: props.currentRouteThreadKeyRef,
119 canOperateThread: true,
120 clientSettingsHydrated: true,
121 activeThreadShell: props.shell ?? null,
122 limitRecoveryHoldsSnooze: false,
123 activeLatestRun: null as never,
124 activeProjectCwd: "/repo",
125 serverConfig: props.shell ? ({} as never) : null,
126 runtimeMode: "full-access" as never,
127 isWorking: false,
128 runIsLive: false,
129 pendingBackgroundTasks: [{ taskId: "background-command", kind: "command" }] as never,
130 turnItems: [],
131 activePendingApproval: null as never,
132 activePendingUserInput: null as never,
133 gitStatusQuery: { refresh: props.refreshGitStatus },
134 nowMinute: "",
135 composerRef: {
136 current: {
137 focusAtEnd: props.focusComposer,
138 getSendContext: () => ({ providerAvailable: true, selectedModelSelection: null }),
139 },
140 } as never,
141 composerDraftTarget: { kind: "thread", ref: props.thread.activeThreadRef } as never,
142 sendInFlightRef: { current: false },
143 setOptimisticUserMessages: () => undefined,
144 setThreadError: props.setThreadError ?? (() => undefined),
145 clearUsageLimitsFor: () => undefined,
146 beginLocalDispatch: () => undefined,
147 resetLocalDispatch: props.resetLocalDispatch ?? (() => undefined),
148 scrollToEnd: () => undefined,
149 persistThreadSettingsForNextTurn: async () => ({ _tag: "Success", value: undefined }) as never,
150 });
151 props.onShortcuts?.(lifecycle.shortcuts);
152 return (
153 <>
154 {lifecycle.childInputNow?.description}
155 {lifecycle.childInputNow?.actions}
156 {lifecycle.workNow?.actions}
157 <button
158 type="button"
159 disabled={lifecycle.isRestoringThreadBranch}
160 onClick={lifecycle.handleSwitchCheckoutToThreadStable}
161 >
162 {lifecycle.isRestoringThreadBranch ? "Restoring..." : "Restore branch"}
163 </button>
164 <button
165 type="button"
166 onClick={() => void lifecycle.sendStandaloneCommand("/goal clear", "Failed")}
167 >
168 Clear goal
169 </button>
170 </>
171 );
172}
173
174it.each(["a", "b", "navigation"] as const)(
175 "isolates restore completion and queued focus for %s",
176 async (scenario) => {
177 const first = scenario === "b" ? "b" : "a";
178 setup();
179 const completions: Array<(result: unknown) => void> = [];
180 const switchRef = vi.fn(() => new Promise<unknown>((resolve) => completions.push(resolve)));
181 state.switchRef = switchRef;
182 const threadA = threadInput("thread:a", "feature-a");
183 const threadB = threadInput("thread:b", "feature-b");
184 const currentRouteThreadKeyRef = { current: threadA.routeThreadKey };
185 const refreshGitStatus = vi.fn();
186 const focusComposer = vi.fn();
187 const harness = (thread: ThreadInput) => (
188 <RestoreBranchHarness
189 thread={thread}
190 currentRouteThreadKeyRef={currentRouteThreadKeyRef}
191 refreshGitStatus={refreshGitStatus}
192 focusComposer={focusComposer}
193 />
194 );
195 await using screen = await render(harness(threadA));
196 const focusFrames: FrameRequestCallback[] = [];
197 using _frame = vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {
198 focusFrames.push(callback);
199 return 0;
200 });
201
202 await page.getByRole("button", { name: "Restore branch" }).click();
203 await expect.element(page.getByRole("button", { name: "Restoring..." })).toBeDisabled();
204
205 // ChatView stays mounted across server threads, so the hook sees thread B in place.
206 currentRouteThreadKeyRef.current = threadB.routeThreadKey;
207 await screen.rerender(harness(threadB));
208 await expect.element(page.getByRole("button", { name: "Restore branch" })).toBeEnabled();
209 await page.getByRole("button", { name: "Restore branch" }).click();
210 expect(switchRef).toHaveBeenLastCalledWith(
211 expect.objectContaining({ input: { cwd: "/repo", refName: "feature-b" } }),
212 );
213
214 // Back on thread A, its own restore is still pending, so it can't start a second one.
215 currentRouteThreadKeyRef.current = threadA.routeThreadKey;
216 await screen.rerender(harness(threadA));
217 await expect.element(page.getByRole("button", { name: "Restoring..." })).toBeDisabled();
218 currentRouteThreadKeyRef.current = threadB.routeThreadKey;
219 await screen.rerender(harness(threadB));
220
221 const completed = first === "a" ? threadA : threadB;
222 const pending = first === "a" ? threadB : threadA;
223 currentRouteThreadKeyRef.current = pending.routeThreadKey;
224 await screen.rerender(harness(pending));
225 completions[first === "a" ? 0 : 1]!({
226 _tag: "Success",
227 value: { refName: completed.localCheckoutBranchMismatch.threadBranch },
228 });
229 await vi.waitFor(() => expect(refreshGitStatus).toHaveBeenCalledOnce());
230 expect(focusComposer).not.toHaveBeenCalled();
231 await expect.element(page.getByRole("button", { name: "Restoring..." })).toBeDisabled();
232 expect(switchRef).toHaveBeenCalledTimes(2);
233
234 completions[first === "a" ? 1 : 0]!({
235 _tag: "Success",
236 value: { refName: pending.localCheckoutBranchMismatch.threadBranch },
237 });
238 await expect.element(page.getByRole("button", { name: "Restore branch" })).toBeEnabled();
239 expect(refreshGitStatus).toHaveBeenCalledTimes(2);
240 expect(focusComposer).not.toHaveBeenCalled();
241 expect(focusFrames).toHaveLength(1);
242 if (scenario === "navigation") {
243 currentRouteThreadKeyRef.current = completed.routeThreadKey;
244 await screen.rerender(harness(completed));
245 }
246 focusFrames[0]!(0);
247 expect(focusComposer).toHaveBeenCalledTimes(scenario === "navigation" ? 0 : 1);
248 },
249);
250
251it.each(["Success", "Failure"] as const)(
252 "keeps background stop requests per thread after %s",
253 async (outcome) => {
254 setup();
255 const completions: Array<(result: unknown) => void> = [];
256 state.switchRef = vi.fn(() => new Promise((resolve) => completions.push(resolve)));
257 const threadA = threadInput("thread:a", "feature-a");
258 const threadB = threadInput("thread:b", "feature-b");
259 const currentRouteThreadKeyRef = { current: threadA.routeThreadKey };
260 const harness = (thread: ThreadInput) => (
261 <RestoreBranchHarness
262 thread={thread}
263 currentRouteThreadKeyRef={currentRouteThreadKeyRef}
264 refreshGitStatus={() => undefined}
265 focusComposer={() => undefined}
266 />
267 );
268 await using screen = await render(harness(threadA));
269 await page.getByRole("button", { name: "Stop", exact: true }).click();
270 await expect.element(page.getByRole("button", { name: "Stopping..." })).toBeDisabled();
271 await screen.rerender(harness(threadB));
272 await page.getByRole("button", { name: "Stop", exact: true }).click();
273 await screen.rerender(harness(threadA));
274 await expect.element(page.getByRole("button", { name: "Stopping..." })).toBeDisabled();
275 completions[0]!(
276 outcome === "Success"
277 ? { _tag: "Success", value: undefined }
278 : { _tag: "Failure", cause: Cause.fail(new Error("stop failed")) },
279 );
280 if (outcome === "Success") {
281 await expect.element(page.getByRole("button", { name: "Stopping..." })).toBeDisabled();
282 } else {
283 await expect.element(page.getByRole("button", { name: "Stop", exact: true })).toBeEnabled();
284 }
285 await screen.rerender(harness(threadB));
286 await expect.element(page.getByRole("button", { name: "Stopping..." })).toBeDisabled();
287 expect(state.switchRef).toHaveBeenCalledTimes(2);
288 completions[1]!({ _tag: "Success", value: undefined });
289 },
290);
291
292it.each(["thread.settle", "thread.pin"] as const)(
293 "does not toggle back when the %s shortcut is held down",
294 async (command) => {
295 setup();
296 const unsettle = vi.fn(async () => ({ _tag: "Success", value: undefined }));
297 state.switchRef = unsettle;
298 const settleThread = vi.fn(async () => ({ _tag: "Success", value: undefined }));
299 const pinThread = vi.fn(async () => ({ _tag: "Success", value: undefined }));
300 const confirmAndUnpinThread = vi.fn(async () => ({ _tag: "Success", value: undefined }));
301 state.threadActions = { settleThread, pinThread, confirmAndUnpinThread };
302 const thread = threadInput("thread:a", "main");
303 let shortcuts: Shortcuts | undefined;
304 const harness = (shell: Partial<EnvironmentThreadShell>) => (
305 <RestoreBranchHarness
306 thread={thread}
307 currentRouteThreadKeyRef={{ current: thread.routeThreadKey }}
308 refreshGitStatus={() => undefined}
309 focusComposer={() => undefined}
310 shell={{ id: thread.activeThreadId, environmentId, ...shell } as EnvironmentThreadShell}
311 onShortcuts={(latest) => (shortcuts = latest)}
312 />
313 );
314 await using screen = await render(harness({}));
315 const press = (repeat: boolean) =>
316 shortcuts,
318 terminalFocusOwner: null,
319 });
320 expect(press(false)).toBeUndefined();
321 await screen.rerender(
322 harness(
323 command === "thread.settle"
324 ? { settledOverride: "settled" }
325 : { pinnedAt: "2026-01-01T00:00:00.000Z" },
326 ),
327 );
328 // The key is still held, so the browser keeps sending repeats; they are consumed only.
329 expect(press(true)).toBeUndefined();
330 expect(command === "thread.settle" ? settleThread : pinThread).toHaveBeenCalledOnce();
331 expect(unsettle).not.toHaveBeenCalled();
332 expect(confirmAndUnpinThread).not.toHaveBeenCalled();
333 },
334);
335
336it("leaves settle, pin, and regenerate-title shortcuts alone while a menu is open", async () => {
337 setup();
338 const settleThread = vi.fn(async () => ({ _tag: "Success", value: undefined }));
339 const pinThread = vi.fn(async () => ({ _tag: "Success", value: undefined }));
340 const atomCommand = vi.fn(async () => ({ _tag: "Success", value: undefined }));
341 state.switchRef = atomCommand;
342 state.threadActions = { settleThread, pinThread };
343 const thread = threadInput("thread:a", "main");
344 let shortcuts: Shortcuts | undefined;
345 await using screen = await render(
346 <>
347 <RestoreBranchHarness
348 thread={thread}
349 currentRouteThreadKeyRef={{ current: thread.routeThreadKey }}
350 refreshGitStatus={() => undefined}
351 focusComposer={() => undefined}
352 shell={{ id: thread.activeThreadId, environmentId } as EnvironmentThreadShell}
353 onShortcuts={(latest) => (shortcuts = latest)}
354 />
355 <Menu>
356 <MenuTrigger render={<button type="button" />}>Actions</MenuTrigger>
357 <MenuPopup>
358 <MenuItem>Item</MenuItem>
359 </MenuPopup>
360 </Menu>
361 </>,
362 );
363
364 await userEvent.click(screen.getByRole("button", { name: "Actions" }));
365 await expect.element(page.getByRole("menu")).toBeVisible();
366
367 for (const command of ["thread.settle", "thread.pin", "thread.regenerateTitle"] as const) {
368 expect(
369 shortcuts, terminalFocusOwner: null }),
370 ).toBe(false);
371 }
372 expect(settleThread).not.toHaveBeenCalled();
373 expect(pinThread).not.toHaveBeenCalled();
374 expect(atomCommand).not.toHaveBeenCalled();
375});
376
377it.each([
378 { switchThread: false, resets: 1 },
379 { switchThread: true, resets: 0 },
380])(
381 "a failed goal command resets the local send only on its own thread (switch: $switchThread)",
382 async ({ switchThread, resets }) => {
383 setup();
384 const completions: Array<(result: unknown) => void> = [];
385 state.switchRef = vi.fn(() => new Promise((resolve) => completions.push(resolve)));
386 const resetLocalDispatch = vi.fn();
387 const setThreadError = vi.fn();
388 const threadA = threadInput("thread:a", "main");
389 const threadB = threadInput("thread:b", "main");
390 const currentRouteThreadKeyRef = { current: threadA.routeThreadKey };
391 const harness = (thread: ThreadInput) => (
392 <RestoreBranchHarness
393 thread={thread}
394 currentRouteThreadKeyRef={currentRouteThreadKeyRef}
395 refreshGitStatus={() => undefined}
396 focusComposer={() => undefined}
397 resetLocalDispatch={resetLocalDispatch}
398 setThreadError={setThreadError}
399 />
400 );
401 await using screen = await render(harness(threadA));
402 await page.getByRole("button", { name: "Clear goal" }).click();
403 await vi.waitFor(() => expect(completions).toHaveLength(1));
404 if (switchThread) {
405 // ChatView stays mounted, so thread B's own send shares this local dispatch state.
406 currentRouteThreadKeyRef.current = threadB.routeThreadKey;
407 await screen.rerender(harness(threadB));
408 }
409 completions[0]!({ _tag: "Failure", cause: Cause.fail(new Error("clear failed")) });
410 await vi.waitFor(() =>
411 expect(setThreadError).toHaveBeenLastCalledWith(threadA.activeThreadId, "clear failed"),
412 );
413 expect(resetLocalDispatch).toHaveBeenCalledTimes(resets);
414 },
415);