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 } from "vite-plus/test/browser";
7
8const state = vi.hoisted(() => ({
9 childThreadInputs: [] as EnvironmentThreadShell[],
10 switchRef: (async () => undefined) as (input: unknown) => Promise<unknown>,
11}));
12
13vi.mock(import("../../state/session"), async (importOriginal) => ({
14 ...(await importOriginal()),
15 useEnvironmentScope: (() => true) as never,
16 readEnvironmentScope: (() => true) as never,
17}));
18
19vi.mock(import("../../state/use-atom-command"), async (importOriginal) => ({
20 ...(await importOriginal()),
21 useAtomCommand: (() => (input: unknown) => state.switchRef(input)) as never,
22}));
23
24vi.mock(import("../../state/use-orchestration-command"), async (importOriginal) => ({
25 ...(await importOriginal()),
26 useOrchestrationCommand: (() => (input: unknown) => state.switchRef(input)) as never,
27}));
28
29vi.mock(import("../../hooks/useThreadActions"), async (importOriginal) => ({
30 ...(await importOriginal()),
31 useThreadActions: (() => ({})) as never,
32 useAcknowledgeThreadWoke: (() => () => undefined) as never,
33}));
34
35vi.mock(import("../../state/entities"), async (importOriginal) => ({
36 ...(await importOriginal()),
37 useChildThreadInputs: (() => state.childThreadInputs) as never,
38}));
39
40import { render } from "../../../test/render";
41import { useThreadLifecycle } from "./useThreadLifecycle";
42
43const environmentId = EnvironmentId.make("environment:test");
44
45function setup() {
46 state.childThreadInputs = [];
47 state.switchRef = async () => undefined;
48}
49
50function threadInput(threadId: string, branch: string) {
51 const ref = scopeThreadRef(environmentId, ThreadId.make(threadId));
52 const thread = { id: ref.threadId, environmentId, branch, worktreePath: null };
53 return {
54 routeThreadKey: scopedThreadKey(ref),
55 activeThread: thread as never,
56 activeThreadId: ref.threadId,
57 activeThreadRef: ref,
58 threadDetailRef: ref,
59 activeThreadKey: scopedThreadKey(ref),
60 localCheckoutBranchMismatch: { threadBranch: branch, currentBranch: "main" },
61 };
62}
63
64type ThreadInput = ReturnType<typeof threadInput>;
65
66it.each([
67 { remote: false, approval: false, link: "Open question" },
68 { remote: true, approval: false, link: "Open question" },
69 { remote: true, approval: false, link: "Child" },
70 { remote: true, approval: true, link: "Open approval" },
71])("opens the child in its environment ($remote, $link)", async ({ remote, approval, link }) => {
72 setup();
73 const parent = threadInput("parent", "main");
74 const childEnvironmentId = remote ? EnvironmentId.make("remote") : environmentId;
75 state.childThreadInputs = [
76 {
77 id: ThreadId.make("child"),
78 environmentId: childEnvironmentId,
79 title: "Child",
80 hasPendingApprovals: approval,
81 lineage: { sideChat: false },
82 } as EnvironmentThreadShell,
83 ];
84 await using screen = await render(
85 <RestoreBranchHarness
86 thread={parent}
87 currentRouteThreadKeyRef={{ current: parent.routeThreadKey }}
88 refreshGitStatus={() => undefined}
89 focusComposer={() => undefined}
90 />,
91 { router: "/environment:test/parent" },
92 );
93 await screen.getByRole("button", { name: link, exact: true }).click();
94 await vi.waitFor(() =>
95 expect(screen.router?.state.location.pathname).toBe(
96 `/${encodeURIComponent(childEnvironmentId)}/child`,
97 ),
98 );
99});
100
101function RestoreBranchHarness(props: {
102 readonly thread: ThreadInput;
103 readonly currentRouteThreadKeyRef: { readonly current: string | null };
104 readonly refreshGitStatus: () => void;
105 readonly focusComposer: () => void;
106}) {
107 const lifecycle = useThreadLifecycle({
108 ...props.thread,
109 environmentId,
110 currentRouteThreadKeyRef: props.currentRouteThreadKeyRef,
111 canOperateThread: true,
112 clientSettingsHydrated: true,
113 activeThreadShell: null,
114 limitRecoveryHoldsSnooze: false,
115 activeLatestRun: null as never,
116 activeProjectCwd: "/repo",
117 serverConfig: null,
118 runtimeMode: "full-access" as never,
119 isWorking: false,
120 pendingBackgroundTasks: [{ taskId: "background-command", kind: "command" }] as never,
121 turnItems: [],
122 activePendingApproval: null as never,
123 activePendingUserInput: null as never,
124 gitStatusQuery: { refresh: props.refreshGitStatus },
125 nowMinute: "",
126 composerRef: { current: { focusAtEnd: props.focusComposer } } as never,
127 composerDraftTarget: { kind: "thread", ref: props.thread.activeThreadRef } as never,
128 sendInFlightRef: { current: false },
129 setOptimisticUserMessages: () => undefined,
130 setThreadError: () => undefined,
131 clearUsageLimitsFor: () => undefined,
132 beginLocalDispatch: () => undefined,
133 resetLocalDispatch: () => undefined,
134 scrollToEnd: () => undefined,
135 persistThreadSettingsForNextTurn: async () => ({ _tag: "Success", value: undefined }) as never,
136 });
137 return (
138 <>
139 {lifecycle.childInputNow?.description}
140 {lifecycle.childInputNow?.actions}
141 {lifecycle.workNow?.actions}
142 <button
143 type="button"
144 disabled={lifecycle.isRestoringThreadBranch}
145 onClick={lifecycle.handleSwitchCheckoutToThreadStable}
146 >
147 {lifecycle.isRestoringThreadBranch ? "Restoring..." : "Restore branch"}
148 </button>
149 </>
150 );
151}
152
153it.each(["a", "b", "navigation"] as const)(
154 "isolates restore completion and queued focus for %s",
155 async (scenario) => {
156 const first = scenario === "b" ? "b" : "a";
157 setup();
158 const completions: Array<(result: unknown) => void> = [];
159 const switchRef = vi.fn(() => new Promise<unknown>((resolve) => completions.push(resolve)));
160 state.switchRef = switchRef;
161 const threadA = threadInput("thread:a", "feature-a");
162 const threadB = threadInput("thread:b", "feature-b");
163 const currentRouteThreadKeyRef = { current: threadA.routeThreadKey };
164 const refreshGitStatus = vi.fn();
165 const focusComposer = vi.fn();
166 const harness = (thread: ThreadInput) => (
167 <RestoreBranchHarness
168 thread={thread}
169 currentRouteThreadKeyRef={currentRouteThreadKeyRef}
170 refreshGitStatus={refreshGitStatus}
171 focusComposer={focusComposer}
172 />
173 );
174 await using screen = await render(harness(threadA));
175 const focusFrames: FrameRequestCallback[] = [];
176 using _frame = vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {
177 focusFrames.push(callback);
178 return 0;
179 });
180
181 await page.getByRole("button", { name: "Restore branch" }).click();
182 await expect.element(page.getByRole("button", { name: "Restoring..." })).toBeDisabled();
183
184 // ChatView stays mounted across server threads, so the hook sees thread B in place.
185 currentRouteThreadKeyRef.current = threadB.routeThreadKey;
186 await screen.rerender(harness(threadB));
187 await expect.element(page.getByRole("button", { name: "Restore branch" })).toBeEnabled();
188 await page.getByRole("button", { name: "Restore branch" }).click();
189 expect(switchRef).toHaveBeenLastCalledWith(
190 expect.objectContaining({ input: { cwd: "/repo", refName: "feature-b" } }),
191 );
192
193 // Back on thread A, its own restore is still pending, so it can't start a second one.
194 currentRouteThreadKeyRef.current = threadA.routeThreadKey;
195 await screen.rerender(harness(threadA));
196 await expect.element(page.getByRole("button", { name: "Restoring..." })).toBeDisabled();
197 currentRouteThreadKeyRef.current = threadB.routeThreadKey;
198 await screen.rerender(harness(threadB));
199
200 const completed = first === "a" ? threadA : threadB;
201 const pending = first === "a" ? threadB : threadA;
202 currentRouteThreadKeyRef.current = pending.routeThreadKey;
203 await screen.rerender(harness(pending));
204 completions[first === "a" ? 0 : 1]!({
205 _tag: "Success",
206 value: { refName: completed.localCheckoutBranchMismatch.threadBranch },
207 });
208 await vi.waitFor(() => expect(refreshGitStatus).toHaveBeenCalledOnce());
209 expect(focusComposer).not.toHaveBeenCalled();
210 await expect.element(page.getByRole("button", { name: "Restoring..." })).toBeDisabled();
211 expect(switchRef).toHaveBeenCalledTimes(2);
212
213 completions[first === "a" ? 1 : 0]!({
214 _tag: "Success",
215 value: { refName: pending.localCheckoutBranchMismatch.threadBranch },
216 });
217 await expect.element(page.getByRole("button", { name: "Restore branch" })).toBeEnabled();
218 expect(refreshGitStatus).toHaveBeenCalledTimes(2);
219 expect(focusComposer).not.toHaveBeenCalled();
220 expect(focusFrames).toHaveLength(1);
221 if (scenario === "navigation") {
222 currentRouteThreadKeyRef.current = completed.routeThreadKey;
223 await screen.rerender(harness(completed));
224 }
225 focusFrames[0]!(0);
226 expect(focusComposer).toHaveBeenCalledTimes(scenario === "navigation" ? 0 : 1);
227 },
228);
229
230it.each(["Success", "Failure"] as const)(
231 "keeps background stop requests per thread after %s",
232 async (outcome) => {
233 setup();
234 const completions: Array<(result: unknown) => void> = [];
235 state.switchRef = vi.fn(() => new Promise((resolve) => completions.push(resolve)));
236 const threadA = threadInput("thread:a", "feature-a");
237 const threadB = threadInput("thread:b", "feature-b");
238 const currentRouteThreadKeyRef = { current: threadA.routeThreadKey };
239 const harness = (thread: ThreadInput) => (
240 <RestoreBranchHarness
241 thread={thread}
242 currentRouteThreadKeyRef={currentRouteThreadKeyRef}
243 refreshGitStatus={() => undefined}
244 focusComposer={() => undefined}
245 />
246 );
247 await using screen = await render(harness(threadA));
248 await page.getByRole("button", { name: "Stop", exact: true }).click();
249 await expect.element(page.getByRole("button", { name: "Stopping..." })).toBeDisabled();
250 await screen.rerender(harness(threadB));
251 await page.getByRole("button", { name: "Stop", exact: true }).click();
252 await screen.rerender(harness(threadA));
253 await expect.element(page.getByRole("button", { name: "Stopping..." })).toBeDisabled();
254 completions[0]!(
255 outcome === "Success"
256 ? { _tag: "Success", value: undefined }
257 : { _tag: "Failure", cause: Cause.fail(new Error("stop failed")) },
258 );
259 if (outcome === "Success") {
260 await expect.element(page.getByRole("button", { name: "Stopping..." })).toBeDisabled();
261 } else {
262 await expect.element(page.getByRole("button", { name: "Stop", exact: true })).toBeEnabled();
263 }
264 await screen.rerender(harness(threadB));
265 await expect.element(page.getByRole("button", { name: "Stopping..." })).toBeDisabled();
266 expect(state.switchRef).toHaveBeenCalledTimes(2);
267 completions[1]!({ _tag: "Success", value: undefined });
268 },
269);