Open History to see the last commit
1import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
2import {
3 AuthOrchestrationOperateScope,
4 AuthSourceControlWriteScope,
5 EnvironmentId,
6 GitManagerError,
7 type GitResolvePullRequestResult,
8 ProjectId,
9 ThreadId,
10} from "@t3tools/contracts";
11import * as Cause from "effect/Cause";
12import * as Effect from "effect/Effect";
13import { AsyncResult, Atom } from "effect/reactivity";
14import { useRef, useState } from "react";
15import { expect, it, vi } from "vite-plus/test";
16import { page, userEvent } from "vite-plus/test/browser";
17
18import "~/index.css";
19import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
20import type { ComposerHandleRef } from "~/composerHandleContext";
21import { AppAtomRegistryProvider, appAtomRegistry } from "~/rpc/atomRegistry";
22import { gitEnvironment } from "~/state/git";
23import { environmentProjects } from "~/state/projects";
24import { environmentSession } from "~/state/session";
25import { vcsActionManager, vcsEnvironment } from "~/state/vcs";
26import { act, fakeTimers, render } from "../../test/render";
27import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
28import { PullRequestThreadDialog } from "./PullRequestThreadDialog";
29import { useComposerFocus } from "./chat/useComposerFocus";
30
31it("keeps another caller's checkout failure out of the dialog", async () => {
32 const target = { environmentId: EnvironmentId.make("checkout-error-test"), cwd: "/repo" };
33 const failure = AsyncResult.failure(Cause.fail(new Error("Pull request #42 has local changes.")));
34 const reply = Promise.withResolvers<typeof failure>();
35
36 await using _screen = await render(
37 <AppAtomRegistryProvider>
38 <PullRequestThreadDialog
39 {...target}
40 open
41 initialReference={null}
42 threadId={ThreadId.make("checkout-error-test")}
43 onOpenChange={() => {}}
44 onPrepared={() => {}}
45 />
46 </AppAtomRegistryProvider>,
47 );
48
49 const dialog = page.getByRole("dialog");
50 const cancel = dialog.getByRole("button", { name: "Cancel" });
51 const checkout = vcsActionManager.track(
52 appAtomRegistry,
53 target,
54 { operation: "prepare_pull_request_thread", label: "Preparing pull request thread" },
55 () => reply.promise,
56 );
57 await expect.element(cancel).toBeDisabled();
58 await act(async () => {
59 reply.resolve(failure);
60 await checkout;
61 });
62 await expect.element(cancel).toBeEnabled();
63 expect(dialog.getByText(/Failed to prepare .* request thread\./).query()).toBeNull();
64});
65
66it("hides a stale resolution error while debouncing or refetching a pull request reference", async () => {
67 const target = { environmentId: EnvironmentId.make("resolution-error-test"), cwd: "/repo" };
68 const failure = AsyncResult.failure<GitResolvePullRequestResult, GitManagerError>(
69 Cause.fail(
70 new GitManagerError({
71 operation: "resolvePullRequest",
72 cwd: target.cwd,
73 detail: "Pull request #99999 not found.",
74 }),
75 ),
76 );
77 const failedResolution =
78 Atom.make<AsyncResult.AsyncResult<GitResolvePullRequestResult, GitManagerError>>(failure);
79 const pendingResolution = Atom.make(
80 AsyncResult.initial<GitResolvePullRequestResult, never>(true),
81 );
82 using _resolve = vi
83 .spyOn(gitEnvironment, "pullRequestResolution")
84 .mockImplementation(({ input }) =>
85 input.reference === "99999" ? failedResolution : pendingResolution,
86 );
87
88 await using _screen = await render(
89 <AppAtomRegistryProvider>
90 <PullRequestThreadDialog
91 {...target}
92 open
93 initialReference="#99999"
94 threadId={ThreadId.make("resolution-error-test")}
95 onOpenChange={() => {}}
96 onPrepared={() => {}}
97 />
98 </AppAtomRegistryProvider>,
99 );
100
101 const dialog = page.getByRole("dialog");
102 const resolving = dialog.getByText("Resolving pull request...");
103 const staleError = dialog.getByText(/Pull request #99999 not found\./);
104 await expect.element(staleError).toBeVisible();
105
106 await act(() => {
107 appAtomRegistry.set(failedResolution, AsyncResult.waiting(failure));
108 });
109 expect(resolving.element()).toBeVisible();
110 expect(staleError.query()).toBeNull();
111
112 await act(() => {
113 appAtomRegistry.set(failedResolution, failure);
114 });
115 expect(staleError.element()).toBeVisible();
116
117 using _timers = fakeTimers();
118 await userEvent.fill(dialog.getByRole("textbox"), "#123");
119
120 expect(resolving.element()).toBeVisible();
121 expect(staleError.query()).toBeNull();
122
123 await act(() => vi.advanceTimersByTime(450));
124 await userEvent.fill(dialog.getByRole("textbox"), "#99999");
125 await act(() => vi.advanceTimersByTime(450));
126 expect(staleError.element()).toBeVisible();
127});
128
129it("keeps focus in the dialog when the branch selector opens it", async () => {
130 const environmentId = EnvironmentId.make("pr-dialog-focus-env");
131 const projectId = ProjectId.make("pr-dialog-focus-project");
132 const threadId = ThreadId.make("pr-dialog-focus-thread");
133 const draftId = DraftId.make("pr-dialog-focus-draft");
134 const cwd = "/repo";
135 const projectRef = scopeProjectRef(environmentId, projectId);
136 const threadRef = scopeThreadRef(environmentId, threadId);
137
138 useComposerDraftStore.getState().setProjectDraftThreadId(projectRef, draftId, {
139 threadId,
140 branch: "main",
141 worktreePath: null,
142 envMode: "worktree",
143 });
144 using _clearDraft = {
145 [Symbol.dispose]() {
146 useComposerDraftStore.getState().clearProjectDraftThreadId(projectRef);
147 useComposerDraftStore.getState().clearDraftThread(threadRef);
148 },
149 };
150
151 const sessionAtom = Atom.make(
152 AsyncResult.success({
153 authenticated: true,
154 scopes: [AuthSourceControlWriteScope, AuthOrchestrationOperateScope],
155 }),
156 );
157 const projectAtom = Atom.make({
158 id: projectId,
159 environmentId,
160 title: "Demo Repo",
161 workspaceRoot: cwd,
162 scripts: [],
163 });
164 const statusAtom = Atom.make(
165 AsyncResult.success({
166 isRepo: true,
167 hasPrimaryRemote: true,
168 isDefaultRef: true,
169 refName: "main",
170 hasWorkingTreeChanges: false,
171 workingTree: { files: [], insertions: 0, deletions: 0 },
172 hasUpstream: true,
173 aheadCount: 0,
174 behindCount: 0,
175 aheadOfDefaultCount: 0,
176 pr: null,
177 }),
178 );
179 const refsAtom = Atom.make(
180 AsyncResult.success({
181 refs: [{ name: "main", current: true, isDefault: true }],
182 isRepo: true,
183 hasPrimaryRemote: true,
184 nextCursor: null,
185 totalCount: 1,
186 }),
187 );
188 const pendingResolution = Atom.make(
189 AsyncResult.initial<GitResolvePullRequestResult, never>(true),
190 );
191
192 using _session = vi
193 .spyOn(environmentSession, "sessionStateAtom")
194 .mockReturnValue(sessionAtom as never);
195 using _project = vi
196 .spyOn(environmentProjects, "projectAtom")
197 .mockReturnValue(projectAtom as never);
198 using _status = vi.spyOn(vcsEnvironment, "status").mockReturnValue(statusAtom as never);
199 using _listRefs = vi.spyOn(vcsEnvironment, "listRefs").mockReturnValue(refsAtom as never);
200 using _resolve = vi
201 .spyOn(gitEnvironment, "pullRequestResolution")
202 .mockReturnValue(pendingResolution);
203
204 function Harness() {
205 const [prDialogRef, setPrDialogRef] = useState<string | null>(null);
206 const composerInputRef = useRef<HTMLTextAreaElement>(null);
207 const composerHandleRef = useRef({
208 focusAtEnd: () => composerInputRef.current?.focus(),
209 }) as ComposerHandleRef;
210 const { scheduleComposerFocus } = useComposerFocus(composerHandleRef);
211
212 return (
213 <AppAtomRegistryProvider>
214 <div className="pt-80">
215 <textarea aria-label="Composer" ref={composerInputRef} />
216 <BranchToolbarBranchSelector
217 environmentId={environmentId}
218 threadId={threadId}
219 draftId={draftId}
220 envLocked={false}
221 effectiveEnvModeOverride="worktree"
222 startFromOrigin={false}
223 onStartFromOriginChange={() => {}}
224 onCheckoutPullRequestRequest={(reference) => setPrDialogRef(reference)}
225 onComposerFocusRequest={scheduleComposerFocus}
226 />
227 </div>
228 <PullRequestThreadDialog
229 environmentId={environmentId}
230 cwd={cwd}
231 open={prDialogRef !== null}
232 initialReference={prDialogRef}
233 threadId={threadId}
234 onOpenChange={(nextOpen) => {
235 if (!nextOpen) setPrDialogRef(null);
236 }}
237 onPrepared={() => {}}
238 />
239 </AppAtomRegistryProvider>
240 );
241 }
242
243 await using _screen = await render(<Harness />);
244
245 await userEvent.click(page.getByRole("combobox", { name: /Branch:/ }));
246
247 const searchInput = page.getByPlaceholder("Search refs...");
248 await userEvent.fill(searchInput, "#123");
249 await userEvent.click(page.getByRole("option", { name: /Checkout pull request/ }));
250
251 const dialog = page.getByRole("dialog");
252 await expect.element(dialog).toBeVisible();
253 const prInput = dialog.getByRole("textbox");
254 await userEvent.keyboard("456");
255
256 await expect.element(prInput).toHaveFocus();
257 await expect.element(prInput).toHaveValue("456");
258});
259
260it("clears the branch search query when selecting or creating a branch with Enter", async () => {
261 const environmentId = EnvironmentId.make("branch-enter-clear-env");
262 const projectId = ProjectId.make("branch-enter-clear-project");
263 const threadId = ThreadId.make("branch-enter-clear-thread");
264 const draftId = DraftId.make("branch-enter-clear-draft");
265 const cwd = "/repo";
266 const projectRef = scopeProjectRef(environmentId, projectId);
267 const threadRef = scopeThreadRef(environmentId, threadId);
268 const allRefs = [
269 { name: "main", current: true, isDefault: true, worktreePath: null },
270 { name: "develop", current: false, isDefault: false, worktreePath: null },
271 { name: "feature/login", current: false, isDefault: false, worktreePath: null },
272 ];
273
274 useComposerDraftStore.getState().setProjectDraftThreadId(projectRef, draftId, {
275 threadId,
276 branch: "main",
277 worktreePath: null,
278 envMode: "local",
279 });
280 using _clearDraft = {
281 [Symbol.dispose]() {
282 useComposerDraftStore.getState().clearProjectDraftThreadId(projectRef);
283 useComposerDraftStore.getState().clearDraftThread(threadRef);
284 },
285 };
286
287 const sessionAtom = Atom.make(
288 AsyncResult.success({
289 authenticated: true,
290 scopes: [AuthSourceControlWriteScope, AuthOrchestrationOperateScope],
291 }),
292 );
293 const projectAtom = Atom.make({
294 id: projectId,
295 environmentId,
296 title: "Demo Repo",
297 workspaceRoot: cwd,
298 scripts: [],
299 });
300 const statusAtom = Atom.make(
301 AsyncResult.success({
302 isRepo: true,
303 hasPrimaryRemote: true,
304 isDefaultRef: true,
305 refName: "main",
306 hasWorkingTreeChanges: false,
307 workingTree: { files: [], insertions: 0, deletions: 0 },
308 hasUpstream: true,
309 aheadCount: 0,
310 behindCount: 0,
311 aheadOfDefaultCount: 0,
312 pr: null,
313 }),
314 );
315 const makeRefsAtom = (query: string) => {
316 const refs = query ? allRefs.filter((ref) => ref.name.includes(query)) : allRefs;
317 return Atom.make(
318 AsyncResult.success({
319 refs,
320 isRepo: true,
321 hasPrimaryRemote: true,
322 nextCursor: null,
323 totalCount: refs.length,
324 }),
325 );
326 };
327 const refsAtoms = new Map<string, ReturnType<typeof makeRefsAtom>>();
328 const getRefsAtom = (query: string) => {
329 const existing = refsAtoms.get(query);
330 if (existing) return existing;
331 const atom = makeRefsAtom(query);
332 refsAtoms.set(query, atom);
333 return atom;
334 };
335
336 using _session = vi
337 .spyOn(environmentSession, "sessionStateAtom")
338 .mockReturnValue(sessionAtom as never);
339 using _project = vi
340 .spyOn(environmentProjects, "projectAtom")
341 .mockReturnValue(projectAtom as never);
342 using _status = vi.spyOn(vcsEnvironment, "status").mockReturnValue(statusAtom as never);
343 using _listRefs = vi
344 .spyOn(vcsEnvironment, "listRefs")
345 .mockImplementation(({ input }) => getRefsAtom(input.query ?? "") as never);
346 using _refresh = vi
347 .spyOn(vcsEnvironment.refreshLocalStatusForPicker, "run")
348 .mockReturnValue(Effect.void as never);
349 using _switchRef = vi
350 .spyOn(vcsEnvironment.switchRef, "run")
351 .mockImplementation(
352 (_registry, { input }) => Effect.succeed({ refName: input.refName }) as never,
353 );
354 using _createRef = vi
355 .spyOn(vcsEnvironment.createRef, "run")
356 .mockImplementation(
357 (_registry, { input }) => Effect.succeed({ refName: input.refName }) as never,
358 );
359
360 await using _screen = await render(
361 <AppAtomRegistryProvider>
362 <BranchToolbarBranchSelector
363 environmentId={environmentId}
364 threadId={threadId}
365 draftId={draftId}
366 envLocked={false}
367 effectiveEnvModeOverride="local"
368 startFromOrigin={false}
369 onStartFromOriginChange={() => {}}
370 />
371 </AppAtomRegistryProvider>,
372 );
373
374 const trigger = page.getByRole("combobox", { name: /Branch:/ });
375 const searchInput = page.getByPlaceholder("Search refs...");
376
377 await userEvent.click(trigger);
378 await userEvent.type(searchInput, "login");
379 await expect
380 .element(page.getByRole("option", { name: /feature\/\s*login/ }))
381 .toHaveAttribute("data-highlighted");
382 await userEvent.keyboard("{Enter}");
383 await expect.element(searchInput).not.toBeInTheDocument();
384
385 await userEvent.click(trigger);
386 await expect.element(searchInput).toHaveValue("");
387
388 await userEvent.type(searchInput, "feature/new-ref");
389 await expect
390 .element(page.getByRole("option", { name: 'Create new ref "feature/new-ref"' }))
391 .toHaveAttribute("data-highlighted");
392 await userEvent.keyboard("{Enter}");
393 await expect.element(searchInput).not.toBeInTheDocument();
394
395 await userEvent.click(trigger);
396 await expect.element(searchInput).toHaveValue("");
397});