Open History to see the last commit
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 { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore";
87import { useTerminalUiStateStore } from "../terminalUiStateStore";
88import { ReopenClosedViewShortcut } from "./ReopenClosedViewShortcut";
89
90const ref = { environmentId: "remote", threadId: "thread-1" } as ScopedThreadRef;
91const snapshot = {
92 threadId: ref.threadId,
93 tabId: "closed-tab",
94 navStatus: { _tag: "Success", url: "https://example.com", title: "Example" },
95 canGoBack: false,
96 canGoForward: false,
97 updatedAt: "2026-09-22T12:00:00.000Z",
98} as const;
99let menuAction: ((action: string) => void) | undefined;
100
101function setup() {
102 vi.clearAllMocks();
103 Object.assign(state, {
104 keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
105 params: {},
106 workspaceAvailable: true,
107 });
108 state.navigate.mockResolvedValue(undefined);
109 state.openPreview.mockReset();
110 useClosedViewStore.setState({ entries: [] });
111 useRightPanelStore.setState({ byThreadKey: {}, userActionRevisionByThreadKey: {} });
112 useTerminalUiStateStore.setState({
113 terminalUiStateByThreadKey: {},
114 suppressedTerminalIdsByThreadKey: {},
115 });
116}
117
118async function renderShortcut() {
119 await using stack = new AsyncDisposableStack();
120 stack.use(vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64"));
121 window.desktopBridge = {
122 preview: { setForwardedShortcuts: state.setShortcuts },
123 onMenuAction: (listener: (action: string) => void) => {
124 menuAction = listener;
125 return () => {
126 menuAction = undefined;
127 };
128 },
129 } as unknown as NonNullable<typeof window.desktopBridge>;
130 stack.defer(() => {
131 delete window.desktopBridge;
132 });
133 const screen = stack.use(await render(<ReopenClosedViewShortcut />));
134 const environment = stack.move();
135 return {
136 router: screen.router!,
137 /** Attaches an element to the document until the test ends. */
138 append(element: HTMLElement) {
139 document.body.append(element);
140 environment.defer(() => element.remove());
141 return element;
142 },
143 [Symbol.asyncDispose]: () => environment.disposeAsync(),
144 };
145}
146
147function press(target: Element = document.body) {
148 const event = new KeyboardEvent("keydown", {
149 key: "T",
150 ctrlKey: true,
151 shiftKey: true,
152 bubbles: true,
153 cancelable: true,
154 });
155 target.dispatchEvent(event);
156 return event;
157}
158
159describe("root reopen shortcut", () => {
160 it.each([
161 { action: "switch routes", goBack: false, expectedPath: "/newer" },
162 { action: "leave and return", goBack: true, expectedPath: "/" },
163 ])(
164 "restores both queued views without navigating when you $action during the reopen",
165 async ({ goBack, expectedPath }) => {
166 setup();
167 const store = useClosedViewStore.getState();
168 store.remember({ kind: "panel-tab", threadRef: ref, surface: { kind: "diff", id: "diff" } });
169 store.remember({ kind: "browser", threadRef: ref, snapshot });
170 const result = Promise.withResolvers<ReturnType<typeof AsyncResult.success>>();
171 state.openPreview.mockReturnValue(result.promise);
172 await using view = await renderShortcut();
173 const { history } = view.router;
174 state.navigate.mockImplementation(async () => {
175 history.push("/restored-owner");
176 });
177
178 await act(() => {
179 press();
180 menuAction?.("view.reopenClosed");
181 });
182 await act(() => {
183 history.push("/newer");
184 if (goBack) history.back();
185 });
186 await act(() => result.resolve(AsyncResult.success({ tabId: "new-tab" })));
187
188 expect(useClosedViewStore.getState().entries).toEqual([]);
189 const panel = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref);
190 expect(panel.surfaces.map((surface) => surface.id)).toEqual(
191 expect.arrayContaining(["browser:new-tab", "diff"]),
192 );
193 expect(history.location.pathname).toBe(expectedPath);
194 },
195 );
196
197 it("serializes deliberate presses while a browser restore waits for RPC", async () => {
198 setup();
199 useClosedViewStore
200 .getState()
201 .remember({ kind: "panel-tab", threadRef: ref, surface: { kind: "files", id: "files" } });
202 useClosedViewStore.getState().remember({ kind: "browser", threadRef: ref, snapshot });
203 let finish!: (value: ReturnType<typeof AsyncResult.success>) => void;
204 state.openPreview.mockReturnValue(
205 new Promise((resolve) => {
206 finish = resolve;
207 }),
208 );
209 await using _view = await renderShortcut();
210 await act(() => {
211 press();
212 press();
213 });
214 expect(state.openPreview).toHaveBeenCalledTimes(1);
215 expect(state.navigate).not.toHaveBeenCalled();
216 await act(() => {
217 finish(AsyncResult.success({ tabId: "new-tab" }));
218 });
219 expect(state.navigate).toHaveBeenCalledTimes(2);
220 expect(useClosedViewStore.getState().entries).toEqual([]);
221 });
222
223 it("follows both queued restores from a page with an allowing navigation blocker", async () => {
224 setup();
225 const olderRef = { ...ref, threadId: "thread-2" } as ScopedThreadRef;
226 const store = useClosedViewStore.getState();
227 store.remember({
228 kind: "panel-tab",
229 threadRef: olderRef,
230 surface: { kind: "diff", id: "diff" },
231 });
232 store.remember({ kind: "browser", threadRef: ref, snapshot });
233 const opened = Promise.withResolvers<ReturnType<typeof AsyncResult.success>>();
234 state.openPreview.mockReturnValue(opened.promise);
235
236 const history = createMemoryHistory({ initialEntries: ["/welcome"] });
237 const root = createRootRoute({
238 component: () => (
239 <>
240 <ReopenClosedViewShortcut />
241 <Outlet />
242 </>
243 ),
244 });
245 const router = createRouter({
246 history,
247 routeTree: root.addChildren([
248 createRoute({ getParentRoute: () => root, path: "welcome" }),
249 createRoute({ getParentRoute: () => root, path: "$environmentId/$threadId" }),
250 ]),
251 });
252 state.navigate.mockImplementation(router.navigate);
253 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
254 // The test supplies its own routes and history.
255 await using _view = await render(<RouterProvider router={router} />, { router: false });
256 using _blocker = {
257 [Symbol.dispose]: history.block({ blockerFn: () => false, enableBeforeUnload: false }),
258 };
259
260 await act(() => {
261 press();
262 press();
263 });
264 await act(() => opened.resolve(AsyncResult.success({ tabId: "new-tab" })));
265
266 expect(useClosedViewStore.getState().entries).toEqual([]);
267 expect(history.location.pathname).toBe("/remote/thread-2");
268 });
269
270 it("does not create a second browser when navigation fails after restoring it", async () => {
271 setup();
272 const store = useClosedViewStore.getState();
273 const older = store.remember({
274 kind: "panel-tab",
275 threadRef: ref,
276 surface: { kind: "diff", id: "diff" },
277 });
278 store.remember({ kind: "browser", threadRef: ref, snapshot });
279 state.openPreview.mockResolvedValue(AsyncResult.success({ tabId: "new-tab" }));
280 state.navigate.mockRejectedValueOnce(new Error("navigation failed"));
281 await using _view = await renderShortcut();
282 await act(() => {
283 press();
284 });
285 expect(
286 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref).activeSurfaceId,
287 ).toBe("browser:new-tab");
288 expect(state.toast).toHaveBeenCalledWith(
289 expect.objectContaining({ title: "Could not reopen view" }),
290 );
291 expect(useClosedViewStore.getState().entries.map((entry) => entry.id)).toEqual([older]);
292 await act(() => {
293 menuAction?.("view.reopenClosed");
294 });
295 expect(state.openPreview).toHaveBeenCalledOnce();
296 expect(
297 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref).activeSurfaceId,
298 ).toBe("diff");
299 expect(useClosedViewStore.getState().entries).toEqual([]);
300 });
301
302 it.each(["files", "file", "browser"] as const)(
303 "keeps a failed %s restore retryable without blocking older history",
304 async (kind) => {
305 setup();
306 const store = useClosedViewStore.getState();
307 const older = store.remember({
308 kind: "panel-tab",
309 threadRef: ref,
310 surface: { kind: "diff", id: "diff" },
311 });
312 const failed = store.remember(
313 kind === "browser"
314 ? { kind: "browser", threadRef: ref, snapshot }
315 : {
316 kind: "panel-tab",
317 threadRef: ref,
318 surface:
319 kind === "files"
320 ? { kind: "files", id: "files" }
321 : {
322 kind: "file",
323 id: "file:src/app.ts",
324 relativePath: "src/app.ts",
325 revealLine: null,
326 revealRequestId: 0,
327 },
328 },
329 );
330 state.workspaceAvailable = false;
331 state.openPreview.mockResolvedValue(AsyncResult.failure(Cause.fail(new Error("offline"))));
332 await using _view = await renderShortcut();
333 await act(() => {
334 press();
335 });
336 expect(useClosedViewStore.getState().entries.map((entry) => entry.id)).toEqual([
337 older,
338 failed,
339 ]);
340 expect(state.navigate).not.toHaveBeenCalled();
341 await act(() => {
342 menuAction?.("view.reopenClosed");
343 });
344 expect(
345 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref).activeSurfaceId,
346 ).toBe("diff");
347 expect(useClosedViewStore.getState().entries.map((entry) => entry.id)).toEqual([failed]);
348 state.workspaceAvailable = true;
349 state.openPreview.mockResolvedValue(AsyncResult.success({ ...snapshot, tabId: "new-tab" }));
350 await act(() => {
351 press();
352 });
353 expect(
354 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref).activeSurfaceId,
355 ).toBe(
356 kind === "browser" ? "browser:new-tab" : kind === "file" ? "file:src/app.ts" : "files",
357 );
358 expect(useClosedViewStore.getState().entries).toEqual([]);
359 },
360 );
361 it("forwards address-bar focus, zoom, and panel new and close from a focused desktop page", async () => {
362 setup();
363 await using _shortcut = await renderShortcut();
364 expect(state.setShortcuts).toHaveBeenLastCalledWith(
365 expect.arrayContaining(
366 [
367 "preview.focusUrl",
368 "preview.zoomIn",
369 "preview.zoomOut",
370 "preview.resetZoom",
371 "rightPanel.new",
372 "rightPanel.close",
373 ].map((command) => expect.objectContaining({ command })),
374 ),
375 );
376 });
377});