Open History to see the last commit
1import {
2 EnvironmentId,
3 ProjectId,
4 type PullRequestRef,
5 type PullRequestReviewGuide,
6} from "@t3tools/contracts";
7import type { FileDiffMetadata } from "@pierre/diffs";
8import { expect, it, vi } from "vite-plus/test";
9import { page, userEvent } from "vite-plus/test/browser";
10
11const guideDiffFiles = vi.hoisted(() => new Map<string, FileDiffMetadata>());
12vi.mock(import("./guide/useReviewGuideWriter"), () => ({ useReviewGuideWriter: vi.fn() }));
13vi.mock(import("./guide/useGuideDiffFiles"), () => ({
14 useGuideDiffFiles: () => ({
15 files: guideDiffFiles,
16 loading: false,
17 error: null,
18 retry: () => {},
19 }),
20}));
21
22import { getRenderablePatch } from "~/lib/diffRendering";
23import { render } from "../../../test/render";
24import { RightPanelSheet } from "../RightPanelSheet";
25import type { ChatComposerHandle } from "../chat/ChatComposer";
26import { useChatShortcuts } from "../chat/useChatShortcuts";
27import { useReviewGuideWriter } from "./guide/useReviewGuideWriter";
28import { GuideTour } from "./guide/GuideTour";
29import { PullRequestGuideTab } from "./PullRequestGuideTab";
30
31const reference: PullRequestRef = {
32 projectId: ProjectId.make("project"),
33 repository: "owner/repo",
34 number: 1,
35};
36
37const verboseFailure = [
38 "Codex CLI command failed: OpenAI Codex v0.164.0",
39 ...Array.from({ length: 200 }, (_, line) => `prompt line ${line}: read the change in order`),
40 "ERROR: provider auth command `sh` timed out after 5000 ms",
41].join("\n");
42
43it("keeps Try again inside a short panel when a failed guide has long diagnostics", async () => {
44 const write = vi.fn(async () => {});
45 vi.mocked(useReviewGuideWriter).mockReturnValue({
46 query: { isPending: false, error: null } as never,
47 data: {
48 guide: null,
49 run: {
50 _tag: "Failed",
51 headSha: "head",
52 failedAt: "2026-10-27T16:37:47.661Z",
53 detail: verboseFailure,
54 },
55 currentHeadSha: "head",
56 },
57 running: false,
58 canWrite: true,
59 write,
60 });
61 const panel = document.createElement("div");
62 panel.style.cssText = "position: relative; width: 480px; height: 360px; overflow: hidden";
63 const tab = document.createElement("div");
64 tab.style.cssText = "position: absolute; inset: 0";
65 panel.append(tab);
66 document.body.append(panel);
67 using _panel = { [Symbol.dispose]: () => panel.remove() };
68
69 await using screen = await render(
70 <PullRequestGuideTab
71 environmentId={EnvironmentId.make("environment")}
72 reference={reference}
73 title="Test pull request"
74 workspaceRoot="/workspace"
75 active
76 canComment={false}
77 rangeComments={false}
78 completionScope={null}
79 onAskAboutLines={null}
80 onAskAboutStop={null}
81 onFinishReview={null}
82 onOpenFile={() => {}}
83 />,
84 { container: tab },
85 );
86
87 const retry = screen.getByRole("button", { name: "Try again" });
88 await expect.element(retry).toBeVisible();
89 const panelBox = panel.getBoundingClientRect();
90 const retryBox = retry.element().getBoundingClientRect();
91 expect(retryBox.top).toBeGreaterThanOrEqual(panelBox.top);
92 expect(retryBox.bottom).toBeLessThanOrEqual(panelBox.bottom);
93
94 await userEvent.click(retry);
95 expect(write).toHaveBeenCalledOnce();
96});
97
98it("shows a failed guide read instead of the last running status", async () => {
99 const unavailable = "Pull request operation detail failed: GitLab CLI command failed.";
100 vi.mocked(useReviewGuideWriter).mockReturnValue({
101 query: { isPending: false, error: unavailable } as never,
102 data: {
103 guide: null,
104 run: { _tag: "Running", headSha: "head", startedAt: "2026-11-29T08:52:56.000Z" },
105 currentHeadSha: "head",
106 },
107 running: true,
108 canWrite: true,
109 write: async () => {},
110 });
111
112 await using screen = await render(
113 <PullRequestGuideTab
114 environmentId={EnvironmentId.make("environment")}
115 reference={reference}
116 title="Test pull request"
117 workspaceRoot="/workspace"
118 active
119 canComment={false}
120 rangeComments={false}
121 completionScope={null}
122 onAskAboutLines={null}
123 onAskAboutStop={null}
124 onFinishReview={null}
125 onOpenFile={() => {}}
126 />,
127 );
128
129 await expect.element(screen.getByText(unavailable)).toBeVisible();
130});
131
132const threeStopGuide: PullRequestReviewGuide = {
133 headSha: "head",
134 generatedAt: "2026-11-07T00:00:00.000Z",
135 modelSelection: { instanceId: "codex", model: "gpt-6.1-sol" } as never,
136 stops: ["First", "Second", "Third"].map((title) => ({
137 title,
138 summary: `Prose for the ${title.toLowerCase()} stop.`,
139 attention: null,
140 excerpts: [],
141 files: [],
142 notes: [],
143 questions: [],
144 })),
145};
146
147function ChatBeside({
148 composerKeys,
149 maximizedAway,
150}: {
151 composerKeys: string[];
152 maximizedAway: boolean;
153}) {
154 useChatShortcuts({
155 enabled: true,
156 keybindings: [],
157 scriptKeybindings: [],
158 getShortcutContext: () => ({
159 terminalFocus: false,
160 terminalOpen: false,
161 previewFocus: false,
162 previewOpen: false,
163 isWeb: true,
164 isDesktop: false,
165 modelPickerOpen: false,
166 }),
167 threadFindActive: false,
168 composerRef: {
169 current: {
170 insertTextAtEnd: (key: string) => {
171 composerKeys.push(key);
172 return true;
173 },
174 } as Partial<ChatComposerHandle> as ChatComposerHandle,
175 },
176 branchToolbarRef: { current: null },
177 closeThreadFind: () => {},
178 commands: {},
179 fallback: () => undefined,
180 });
181 return <div data-chat-column-maximized-away={maximizedAway ? "true" : "false"} />;
182}
183
184it("steps with J and K beside a chat, also after a stop button or while the chat is maximized away", async () => {
185 vi.mocked(useReviewGuideWriter).mockReturnValue({
186 query: { isPending: false, error: null } as never,
187 data: { guide: threeStopGuide, run: null, currentHeadSha: "head" },
188 running: false,
189 canWrite: false,
190 write: async () => {},
191 });
192 const composerKeys: string[] = [];
193
194 const tree = (maximizedAway: boolean) => (
195 <>
196 <ChatBeside composerKeys={composerKeys} maximizedAway={maximizedAway} />
197 <PullRequestGuideTab
198 environmentId={EnvironmentId.make("environment")}
199 reference={reference}
200 title="Test pull request"
201 workspaceRoot="/workspace"
202 active
203 canComment={false}
204 rangeComments={false}
205 completionScope={null}
206 onAskAboutLines={null}
207 onAskAboutStop={null}
208 onFinishReview={null}
209 onOpenFile={() => {}}
210 />
211 </>
212 );
213 await using screen = await render(tree(true));
214
215 await userEvent.keyboard("j");
216 await expect.element(screen.getByText("Prose for the second stop.")).toBeVisible();
217 await screen.rerender(tree(false));
218 await userEvent.click(screen.getByText("Prose for the second stop."));
219 await userEvent.keyboard("k");
220 await expect.element(screen.getByText("Prose for the first stop.")).toBeVisible();
221 await userEvent.click(screen.getByRole("button", { name: "Next stop" }));
222 await userEvent.keyboard("j");
223 await expect.element(screen.getByText("Prose for the third stop.")).toBeVisible();
224 await userEvent.keyboard("k");
225 await expect.element(screen.getByText("Prose for the second stop.")).toBeVisible();
226 (document.activeElement ?? document.body).dispatchEvent(
227 new KeyboardEvent("keydown", { key: "J", bubbles: true, cancelable: true, composed: true }),
228 );
229 await expect.element(screen.getByText("Prose for the third stop.")).toBeVisible();
230 await userEvent.keyboard("a");
231 expect(composerKeys).toEqual(["a"]);
232});
233
234it("leaves J and K to floating layers, side chats, and IME while stepping inside a panel sheet", async () => {
235 await using _screen = await render(
236 <RightPanelSheet open animationDurationMs={0} onClose={() => {}}>
237 <GuideTour
238 environmentId={EnvironmentId.make("environment")}
239 reference={{ ...reference, number: 2 }}
240 guide={threeStopGuide}
241 banner={null}
242 active
243 commenting={null}
244 onAsk={null}
245 onFinish={null}
246 onOpenFile={() => {}}
247 />
248 <div role="dialog">
249 <button>Dialog action</button>
250 </div>
251 <div role="menu">
252 <button role="menuitem">Menu action</button>
253 </div>
254 <div data-slot="select-popup">
255 <button>Popup action</button>
256 </div>
257 <div data-side-chat-pane>
258 <button>Side chat action</button>
259 </div>
260 <button>IME action</button>
261 </RightPanelSheet>,
262 );
263 await expect.element(page.getByRole("dialog", { name: "Workspace panel" })).toBeVisible();
264 page.getByRole("button", { name: "Next stop" }).element().focus();
265 await userEvent.keyboard("j");
266 await expect.element(page.getByText("Prose for the second stop.")).toBeVisible();
267
268 for (const [name, role, keyCode] of [
269 ["Dialog action", "button", 0],
270 ["Menu action", "menuitem", 0],
271 ["Popup action", "button", 0],
272 ["Side chat action", "button", 0],
273 ["IME action", "button", 229],
274 ] as const) {
275 const target = page.getByRole(role, { name }).element();
276 target.focus();
277 for (const key of ["j", "k"]) {
278 const event = new KeyboardEvent("keydown", { key, keyCode, bubbles: true, cancelable: true });
279 target.dispatchEvent(event);
280 expect(event.defaultPrevented, `${name}: ${key}`).toBe(false);
281 }
282 }
283 page.getByRole("button", { name: "Next stop" }).element().focus();
284 await userEvent.keyboard("j");
285 await expect.element(page.getByText("Prose for the third stop.")).toBeVisible();
286});
287
288it("counts a one-line excerpt as one diff line", async () => {
289 for (const [path, patch] of [
290 [
291 "hello.txt",
292 "diff --git a/hello.txt b/hello.txt\nnew file mode 100644\n--- /dev/null\n+++ b/hello.txt\n@@ -0,0 +1 @@\n+hello\n",
293 ],
294 [
295 "bye.txt",
296 "diff --git a/bye.txt b/bye.txt\ndeleted file mode 100644\n--- a/bye.txt\n+++ /dev/null\n@@ -1 +0,0 @@\n-bye\n",
297 ],
298 ] as const) {
299 const parsed = getRenderablePatch(patch, `guide-${path}`);
300 if (parsed?.kind !== "files") throw new Error("Expected a parsed patch.");
301 guideDiffFiles.set(path, parsed.files[0]!);
302 }
303 const stop = threeStopGuide.stops[0]!;
304 await using screen = await render(
305 <GuideTour
306 environmentId={EnvironmentId.make("environment")}
307 reference={{ ...reference, number: 3 }}
308 guide={{
309 ...threeStopGuide,
310 stops: [
311 {
312 ...stop,
313 excerpts: [
314 { path: "hello.txt", side: "new", start: 1, end: 1, caption: "" },
315 { path: "bye.txt", side: "old", start: 1, end: 1, caption: "" },
316 ],
317 },
318 ],
319 }}
320 banner={null}
321 active
322 commenting={null}
323 onAsk={null}
324 onFinish={null}
325 onOpenFile={() => {}}
326 />,
327 );
328
329 for (const [prefix, expected] of [
330 [/^showing 1 of 1 diff/, "showing 1 of 1 diff line"],
331 [/^removed code, showing 1 of 1 diff/, "removed code, showing 1 of 1 diff line"],
332 ] as const) {
333 const header = screen.getByText(prefix);
334 await expect.element(header).toBeVisible();
335 expect(header.element().textContent).toBe(expected);
336 }
337});