Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useThreadLifecycle.browser.test.tsx

228 lines9.2 KB

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