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

ReopenClosedViewShortcut.browser.test.tsx

482 lines16.3 KB

1import type { ResolvedKeybindingsConfig, ScopedThreadRef } from "@t3tools/contracts";
2import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
3import {
4 createMemoryHistory,
5 createRootRoute,
6 createRoute,
7 createRouter,
8 Outlet,
9 RouterProvider,
10} from "@tanstack/react-router";
11import * as Cause from "effect/Cause";
12import { AsyncResult } from "effect/reactivity";
13import { describe, expect, it, vi } from "vite-plus/test";
14​
15import { act, render } from "../../test/render";
16​
17const state = vi.hoisted(() => ({
18 keybindings: [] as ResolvedKeybindingsConfig,
19 params: {} as Record<string, string>,
20 workspaceAvailable: true,
21 navigate: vi.fn(),
22 openPreview: vi.fn(),
23 setShortcuts: vi.fn(async () => undefined),
24 toast: vi.fn(),
25}));
26​
27vi.mock(import("./preview/openPreviewSession"), async (original) => ({
28 ...(await original()),
29 openPreviewSession: state.openPreview,
30}));
31vi.mock(import("@effect/atom-react"), async (original) => ({
32 ...(await original()),
33 useAtomValue: (() => state.keybindings) as never,
34}));
35vi.mock(import("@tanstack/react-router"), async (original) => ({
36 ...(await original()),
37 useNavigate: (() => state.navigate) as never,
38 useParams: (() => state.params) as never,
39}));
40vi.mock(import("../state/use-atom-command"), async (original) => ({
41 ...(await original()),
42 useAtomCommand: ((command: unknown) => command) as never,
43}));
44vi.mock(import("../state/preview"), async (original) => {
45 const actual = await original();
46 return {
47 ...actual,
48 previewEnvironment: { ...actual.previewEnvironment, open: state.openPreview as never },
49 };
50});
51vi.mock(import("../connection/catalog"), async (original) => {
52 const actual = await original();
53 const { Atom } = await import("effect/reactivity");
54 return {
55 ...actual,
56 environmentCatalog: {
57 ...actual.environmentCatalog,
58 catalogValueAtom: Atom.make({
59 isReady: true,
60 entries: new Map([["remote", { target: { _tag: "DirectConnectionTarget" } }]]),
61 }) as never,
62 },
63 };
64});
65vi.mock(import("../state/shell"), async (original) => {
66 const actual = await original();
67 const { Atom } = await import("effect/reactivity");
68 const live = Atom.make({ status: "live" });
69 return {
70 ...actual,
71 environmentShell: { ...actual.environmentShell, stateValueAtom: (() => live) as never },
72 };
73});
74vi.mock(import("../state/entities"), async (original) => ({
75 ...(await original()),
76 readThreadShell: (() => ({ projectId: "project-1", worktreePath: null })) as never,
77 readProject: (() =>
78 state.workspaceAvailable ? { workspaceRoot: "/work/project" } : null) as never,
79}));
80vi.mock(import("./ui/toast"), async (original) => {
81 const actual = await original();
82 return { ...actual, toastManager: { ...actual.toastManager, add: state.toast } };
83});
84​
85import { useClosedViewStore } from "../closedViewStore";
86import {
87 ISSUES_PANEL_REF,
88 PULL_REQUESTS_PANEL_REF,
89 selectThreadRightPanelState,
90 useRightPanelStore,
91} from "../rightPanelStore";
92import { useTerminalUiStateStore } from "../terminalUiStateStore";
93import { writePullRequestListPreferences } from "./pullRequest/pullRequestListPreferences";
94import { ReopenClosedViewShortcut } from "./ReopenClosedViewShortcut";
95​
96const ref = { environmentId: "remote", threadId: "thread-1" } as ScopedThreadRef;
97const snapshot = {
98 threadId: ref.threadId,
99 tabId: "closed-tab",
100 navStatus: { _tag: "Success", url: "https://example.com", title: "Example" },
101 canGoBack: false,
102 canGoForward: false,
103 updatedAt: "2026-09-22T12:00:00.000Z",
104} as const;
105let menuAction: ((action: string) => void) | undefined;
106​
107function setup() {
108 vi.clearAllMocks();
109 Object.assign(state, {
110 keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
111 params: {},
112 workspaceAvailable: true,
113 });
114 state.navigate.mockResolvedValue(undefined);
115 state.openPreview.mockReset();
116 useClosedViewStore.setState({ entries: [] });
117 useRightPanelStore.setState({ byThreadKey: {}, userActionRevisionByThreadKey: {} });
118 useTerminalUiStateStore.setState({
119 terminalUiStateByThreadKey: {},
120 suppressedTerminalIdsByThreadKey: {},
121 });
123​
124async function renderShortcut() {
125 await using stack = new AsyncDisposableStack();
126 stack.use(vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64"));
127 window.desktopBridge = {
128 preview: { setForwardedShortcuts: state.setShortcuts },
129 onMenuAction: (listener: (action: string) => void) => {
130 menuAction = listener;
131 return () => {
132 menuAction = undefined;
133 };
134 },
135 } as unknown as NonNullable<typeof window.desktopBridge>;
136 stack.defer(() => {
137 delete window.desktopBridge;
138 });
139 const screen = stack.use(await render(<ReopenClosedViewShortcut />));
140 const environment = stack.move();
141 return {
142 router: screen.router!,
143 /** Attaches an element to the document until the test ends. */
144 append(element: HTMLElement) {
145 document.body.append(element);
146 environment.defer(() => element.remove());
147 return element;
148 },
149 [Symbol.asyncDispose]: () => environment.disposeAsync(),
150 };
152​
153function press(target: Element = document.body) {
154 const event = new KeyboardEvent("keydown", {
155 key: "T",
156 ctrlKey: true,
157 shiftKey: true,
158 bubbles: true,
159 cancelable: true,
160 });
161 target.dispatchEvent(event);
162 return event;
164​
165describe("root reopen shortcut", () => {
166 it.each([
167 { action: "switch routes", goBack: false, expectedPath: "/newer" },
168 { action: "leave and return", goBack: true, expectedPath: "/" },
169 ])(
170 "restores both queued views without navigating when you $action during the reopen",
171 async ({ goBack, expectedPath }) => {
172 setup();
173 const store = useClosedViewStore.getState();
174 store.remember({ kind: "panel-tab", threadRef: ref, surface: { kind: "diff", id: "diff" } });
175 store.remember({ kind: "browser", threadRef: ref, snapshot });
176 const result = Promise.withResolvers<ReturnType<typeof AsyncResult.success>>();
177 state.openPreview.mockReturnValue(result.promise);
178 await using view = await renderShortcut();
179 const { history } = view.router;
180 state.navigate.mockImplementation(async () => {
181 history.push("/restored-owner");
182 });
183​
184 await act(() => {
185 press();
186 menuAction?.("view.reopenClosed");
187 });
188 await act(() => {
189 history.push("/newer");
190 if (goBack) history.back();
191 });
192 await act(() => result.resolve(AsyncResult.success({ tabId: "new-tab" })));
193​
194 expect(useClosedViewStore.getState().entries).toEqual([]);
195 const panel = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref);
196 expect(panel.surfaces.map((surface) => surface.id)).toEqual(
197 expect.arrayContaining(["browser:new-tab", "diff"]),
198 );
199 expect(history.location.pathname).toBe(expectedPath);
200 },
201 );
202​
203 it("serializes deliberate presses while a browser restore waits for RPC", async () => {
204 setup();
205 useClosedViewStore
206 .getState()
207 .remember({ kind: "panel-tab", threadRef: ref, surface: { kind: "files", id: "files" } });
208 useClosedViewStore.getState().remember({ kind: "browser", threadRef: ref, snapshot });
209 let finish!: (value: ReturnType<typeof AsyncResult.success>) => void;
210 state.openPreview.mockReturnValue(
211 new Promise((resolve) => {
212 finish = resolve;
213 }),
214 );
215 await using _view = await renderShortcut();
216 await act(() => {
217 press();
218 press();
219 });
220 expect(state.openPreview).toHaveBeenCalledTimes(1);
221 expect(state.navigate).not.toHaveBeenCalled();
222 await act(() => {
223 finish(AsyncResult.success({ tabId: "new-tab" }));
224 });
225 expect(state.navigate).toHaveBeenCalledTimes(2);
226 expect(useClosedViewStore.getState().entries).toEqual([]);
227 });
228​
229 it("follows both queued restores from a page with an allowing navigation blocker", async () => {
230 setup();
231 const olderRef = { ...ref, threadId: "thread-2" } as ScopedThreadRef;
232 const store = useClosedViewStore.getState();
233 store.remember({
234 kind: "panel-tab",
235 threadRef: olderRef,
236 surface: { kind: "diff", id: "diff" },
237 });
238 store.remember({ kind: "browser", threadRef: ref, snapshot });
239 const opened = Promise.withResolvers<ReturnType<typeof AsyncResult.success>>();
240 state.openPreview.mockReturnValue(opened.promise);
241​
242 const history = createMemoryHistory({ initialEntries: ["/welcome"] });
243 const root = createRootRoute({
244 component: () => (
245 <>
246 <ReopenClosedViewShortcut />
247 <Outlet />
248 </>
249 ),
250 });
251 const router = createRouter({
252 history,
253 routeTree: root.addChildren([
254 createRoute({ getParentRoute: () => root, path: "welcome" }),
255 createRoute({ getParentRoute: () => root, path: "$environmentId/$threadId" }),
256 ]),
257 });
258 state.navigate.mockImplementation(router.navigate);
259 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
260 // The test supplies its own routes and history.
261 await using _view = await render(<RouterProvider router={router} />, { router: false });
262 using _blocker = {
263 [Symbol.dispose]: history.block({ blockerFn: () => false, enableBeforeUnload: false }),
264 };
265​
266 await act(() => {
267 press();
268 press();
269 });
270 await act(() => opened.resolve(AsyncResult.success({ tabId: "new-tab" })));
271​
272 expect(useClosedViewStore.getState().entries).toEqual([]);
273 expect(history.location.pathname).toBe("/remote/thread-2");
274 });
275​
276 it("does not create a second browser when navigation fails after restoring it", async () => {
277 setup();
278 const store = useClosedViewStore.getState();
279 const older = store.remember({
280 kind: "panel-tab",
281 threadRef: ref,
282 surface: { kind: "diff", id: "diff" },
283 });
284 store.remember({ kind: "browser", threadRef: ref, snapshot });
285 state.openPreview.mockResolvedValue(AsyncResult.success({ tabId: "new-tab" }));
286 state.navigate.mockRejectedValueOnce(new Error("navigation failed"));
287 await using _view = await renderShortcut();
288 await act(() => {
289 press();
290 });
291 expect(
292 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref).activeSurfaceId,
293 ).toBe("browser:new-tab");
294 expect(state.toast).toHaveBeenCalledWith(
295 expect.objectContaining({ title: "Could not reopen view" }),
296 );
297 expect(useClosedViewStore.getState().entries.map((entry) => entry.id)).toEqual([older]);
298 await act(() => {
299 menuAction?.("view.reopenClosed");
300 });
301 expect(state.openPreview).toHaveBeenCalledOnce();
302 expect(
303 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref).activeSurfaceId,
304 ).toBe("diff");
305 expect(useClosedViewStore.getState().entries).toEqual([]);
306 });
307​
308 it.each(["files", "file", "browser"] as const)(
309 "keeps a failed %s restore retryable without blocking older history",
310 async (kind) => {
311 setup();
312 const store = useClosedViewStore.getState();
313 const older = store.remember({
314 kind: "panel-tab",
315 threadRef: ref,
316 surface: { kind: "diff", id: "diff" },
317 });
318 const failed = store.remember(
319 kind === "browser"
320 ? { kind: "browser", threadRef: ref, snapshot }
321 : {
322 kind: "panel-tab",
323 threadRef: ref,
324 surface:
325 kind === "files"
326 ? { kind: "files", id: "files" }
327 : {
328 kind: "file",
329 id: "file:src/app.ts",
330 relativePath: "src/app.ts",
331 revealLine: null,
332 revealRequestId: 0,
333 },
334 },
335 );
336 state.workspaceAvailable = false;
337 state.openPreview.mockResolvedValue(AsyncResult.failure(Cause.fail(new Error("offline"))));
338 await using _view = await renderShortcut();
339 await act(() => {
340 press();
341 });
342 expect(useClosedViewStore.getState().entries.map((entry) => entry.id)).toEqual([
343 older,
344 failed,
345 ]);
346 expect(state.navigate).not.toHaveBeenCalled();
347 await act(() => {
348 menuAction?.("view.reopenClosed");
349 });
350 expect(
351 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref).activeSurfaceId,
352 ).toBe("diff");
353 expect(useClosedViewStore.getState().entries.map((entry) => entry.id)).toEqual([failed]);
354 state.workspaceAvailable = true;
355 state.openPreview.mockResolvedValue(AsyncResult.success({ ...snapshot, tabId: "new-tab" }));
356 await act(() => {
357 press();
358 });
359 expect(
360 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref).activeSurfaceId,
361 ).toBe(
362 kind === "browser" ? "browser:new-tab" : kind === "file" ? "file:src/app.ts" : "files",
363 );
364 expect(useClosedViewStore.getState().entries).toEqual([]);
365 },
366 );
367 it("includes the reopened issue selection in the /issues URL", async () => {
368 setup();
369 const issueSurface = {
370 id: "issue:remote:project-1:github:github.com:pingdotgg/t3code:42" as const,
371 kind: "issue" as const,
372 environmentId: "remote",
373 projectId: "project-1",
374 tracker: "github",
375 host: "github.com",
376 scope: "pingdotgg/t3code",
377 key: "42",
378 };
379 useClosedViewStore.getState().remember({
380 kind: "panel-tab",
381 threadRef: ISSUES_PANEL_REF,
382 surface: issueSurface,
383 });
384 await using _view = await renderShortcut();
385​
386 await act(() => {
387 press();
388 });
389​
390 expect(state.navigate).toHaveBeenCalledWith(
391 expect.objectContaining({
392 to: "/issues",
393 search: expect.objectContaining({
394 selectedEnvironmentId: "remote",
395 selectedProjectId: "project-1",
396 selectedHost: "github.com",
397 tracker: "github",
398 scope: "pingdotgg/t3code",
399 key: "42",
400 }),
401 }),
402 );
403 });
404​
405 it("reopens a closed pull request tab from another route with saved list preferences and no foreign search params", async () => {
406 setup();
407 window.localStorage.removeItem("t3.pullRequests.preferences");
408 using _cleanup = {
409 [Symbol.dispose]: () => window.localStorage.removeItem("t3.pullRequests.preferences"),
410 };
411 writePullRequestListPreferences({ involvement: "reviewing", state: "merged" });
412 useClosedViewStore.getState().remember({
413 kind: "panel-tab",
414 threadRef: PULL_REQUESTS_PANEL_REF,
415 surface: {
416 id: "pull-request:remote:project-1:github.com:pingdotgg/t3code#42",
417 kind: "pull-request",
418 environmentId: "remote",
419 projectId: "project-1",
420 host: "github.com",
421 repository: "pingdotgg/t3code",
422 number: 42,
423 },
424 });
425​
426 const history = createMemoryHistory({
427 initialEntries: [
428 "/issues?who=assigned&status=closed&q=login&host=linear.app&tracker=linear&scope=ENG&key=ENG-12",
429 ],
430 });
431 const root = createRootRoute({
432 component: () => (
433 <>
434 <ReopenClosedViewShortcut />
435 <Outlet />
436 </>
437 ),
438 });
439 const router = createRouter({
440 history,
441 routeTree: root.addChildren([
442 createRoute({ getParentRoute: () => root, path: "issues" }),
443 createRoute({ getParentRoute: () => root, path: "pull-requests" }),
444 ]),
445 });
446 state.navigate.mockImplementation(router.navigate);
447 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
448 await using _view = await render(<RouterProvider router={router} />, { router: false });
449​
450 await act(() => {
451 press();
452 });
453​
454 expect(router.state.location.pathname).toBe("/pull-requests");
455 expect(router.state.location.search).toEqual({
456 involvement: "reviewing",
457 state: "merged",
458 repository: "pingdotgg/t3code",
459 number: 42,
460 selectedProjectId: "project-1",
461 selectedHost: "github.com",
462 selectedEnvironmentId: "remote",
463 });
464 });
465​
466 it("forwards address-bar focus, zoom, and panel new and close from a focused desktop page", async () => {
467 setup();
468 await using _shortcut = await renderShortcut();
469 expect(state.setShortcuts).toHaveBeenLastCalledWith(
470 expect.arrayContaining(
471 [
472 "preview.focusUrl",
473 "preview.zoomIn",
474 "preview.zoomOut",
475 "preview.resetZoom",
476 "rightPanel.new",
477 "rightPanel.close",
478 ].map((command) => expect.objectContaining({ command })),
479 ),
480 );
481 });
482});