Open History to see the last commit
1import type { ResolvedKeybindingsConfig, ScopedThreadRef } from "@t3tools/contracts";
2import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
3import * as Cause from "effect/Cause";
4import { AsyncResult } from "effect/reactivity";
5import { act } from "react";
6import { createRoot, type Root } from "react-dom/client";
7import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
8
9const state = vi.hoisted(() => ({
10 keybindings: [] as ResolvedKeybindingsConfig,
11 params: {} as Record<string, string>,
12 workspaceAvailable: true,
13 navigate: vi.fn(),
14 openPreview: vi.fn(),
15 setShortcuts: vi.fn(async () => undefined),
16 toast: vi.fn(),
17}));
18
19vi.mock(import("./preview/openPreviewSession"), async (original) => ({
20 ...(await original()),
21 openPreviewSession: state.openPreview,
22}));
23vi.mock(import("@effect/atom-react"), async (original) => ({
24 ...(await original()),
25 useAtomValue: (() => state.keybindings) as never,
26}));
27vi.mock(import("@tanstack/react-router"), async (original) => ({
28 ...(await original()),
29 useNavigate: (() => state.navigate) as never,
30 useParams: (() => state.params) as never,
31}));
32vi.mock(import("../state/use-atom-command"), async (original) => ({
33 ...(await original()),
34 useAtomCommand: ((command: unknown) => command) as never,
35}));
36vi.mock(import("../state/preview"), async (original) => {
37 const actual = await original();
38 return {
39 ...actual,
40 previewEnvironment: { ...actual.previewEnvironment, open: state.openPreview as never },
41 };
42});
43// The remote environment is catalogued and its shell is live.
44vi.mock(import("../connection/catalog"), async (original) => {
45 const actual = await original();
46 const { Atom } = await import("effect/reactivity");
47 return {
48 ...actual,
49 environmentCatalog: {
50 ...actual.environmentCatalog,
51 catalogValueAtom: Atom.make({ isReady: true, entries: new Map([["remote", {}]]) }) as never,
52 },
53 };
54});
55vi.mock(import("../state/shell"), async (original) => {
56 const actual = await original();
57 const { Atom } = await import("effect/reactivity");
58 const live = Atom.make({ status: "live" });
59 return {
60 ...actual,
61 environmentShell: { ...actual.environmentShell, stateValueAtom: (() => live) as never },
62 };
63});
64vi.mock(import("../state/entities"), async (original) => ({
65 ...(await original()),
66 readThreadShell: (() => ({ projectId: "project-1", worktreePath: null })) as never,
67 readProject: (() =>
68 state.workspaceAvailable ? { workspaceRoot: "/work/project" } : null) as never,
69}));
70vi.mock(import("./ui/toast"), async (original) => {
71 const actual = await original();
72 return { ...actual, toastManager: { ...actual.toastManager, add: state.toast } };
73});
74
75import { useClosedViewStore } from "../closedViewStore";
76import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore";
77import { useTerminalUiStateStore } from "../terminalUiStateStore";
78import { ReopenClosedViewShortcut } from "./ReopenClosedViewShortcut";
79
80const ref = { environmentId: "remote", threadId: "thread-1" } as ScopedThreadRef;
81const snapshot = {
82 threadId: ref.threadId,
83 tabId: "closed-tab",
84 navStatus: { _tag: "Success", url: "https://example.com", title: "Example" },
85 canGoBack: false,
86 canGoForward: false,
87 updatedAt: "2026-09-22T12:00:00.000Z",
88} as const;
89let root: Root;
90let menuAction: ((action: string) => void) | undefined;
91
92async function render() {
93 await act(() => root.render(<ReopenClosedViewShortcut />));
94}
95
96function press(target: Element = document.body) {
97 const event = new KeyboardEvent("keydown", {
98 key: "T",
99 ctrlKey: true,
100 shiftKey: true,
101 bubbles: true,
102 cancelable: true,
103 });
104 target.dispatchEvent(event);
105 return event;
106}
107
108function openCommandPalette() {
109 const palette = document.createElement("div");
110 palette.dataset.commandPalette = "";
111 document.body.append(palette);
112 return palette;
113}
114
115beforeEach(() => {
116 vi.clearAllMocks();
117 Object.assign(state, {
118 keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
119 params: {},
120 workspaceAvailable: true,
121 });
122 state.navigate.mockResolvedValue(undefined);
123 state.openPreview.mockReset();
124 useClosedViewStore.setState({ entries: [] });
125 useRightPanelStore.setState({ byThreadKey: {}, userActionRevisionByThreadKey: {} });
126 useTerminalUiStateStore.setState({
127 terminalUiStateByThreadKey: {},
128 suppressedTerminalIdsByThreadKey: {},
129 });
130 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
131 vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
132 window.desktopBridge = {
133 preview: { setForwardedShortcuts: state.setShortcuts },
134 onMenuAction: (listener: (action: string) => void) => {
135 menuAction = listener;
136 return () => {
137 menuAction = undefined;
138 };
139 },
140 } as unknown as NonNullable<typeof window.desktopBridge>;
141 root = createRoot(document.createElement("div"));
142});
143
144afterEach(async () => {
145 await act(() => root.unmount());
146 delete window.desktopBridge;
147 document.body.replaceChildren();
148 vi.restoreAllMocks();
149 vi.unstubAllGlobals();
150});
151
152describe("root reopen shortcut", () => {
153 it("restores a tab from settings to its owning remote thread", async () => {
154 useClosedViewStore
155 .getState()
156 .remember({ kind: "panel-tab", threadRef: ref, surface: { kind: "diff", id: "diff" } });
157 await render();
158 await act(() => {
159 expect(press().defaultPrevented).toBe(true);
160 });
161 expect(
162 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref).activeSurfaceId,
163 ).toBe("diff");
164 expect(state.navigate).toHaveBeenCalledWith({ to: "/$environmentId/$threadId", params: ref });
165 expect(useClosedViewStore.getState().entries).toEqual([]);
166 });
167
168 it("leaves native shortcuts alone without history or while the palette is open", async () => {
169 await render();
170 expect(press().defaultPrevented).toBe(false);
171 await act(() => {
172 useClosedViewStore
173 .getState()
174 .remember({ kind: "panel-tab", threadRef: ref, surface: { kind: "diff", id: "diff" } });
175 });
176 openCommandPalette();
177 expect(press().defaultPrevented).toBe(false);
178 expect(state.navigate).not.toHaveBeenCalled();
179 expect(useClosedViewStore.getState().entries).toHaveLength(1);
180 });
181
182 it("lets the keybinding recorder capture the chord", async () => {
183 useClosedViewStore
184 .getState()
185 .remember({ kind: "panel-tab", threadRef: ref, surface: { kind: "diff", id: "diff" } });
186 await render();
187 const recorder = document.createElement("input");
188 recorder.dataset.keybindingCapture = "";
189 document.body.append(recorder);
190 expect(press(recorder).defaultPrevented).toBe(false);
191 expect(useClosedViewStore.getState().entries).toHaveLength(1);
192 });
193
194 it("serializes deliberate presses while a browser restore waits for RPC", async () => {
195 useClosedViewStore
196 .getState()
197 .remember({ kind: "panel-tab", threadRef: ref, surface: { kind: "files", id: "files" } });
198 useClosedViewStore.getState().remember({ kind: "browser", threadRef: ref, snapshot });
199 let finish!: (value: ReturnType<typeof AsyncResult.success>) => void;
200 state.openPreview.mockReturnValue(
201 new Promise((resolve) => {
202 finish = resolve;
203 }),
204 );
205 await render();
206 await act(() => {
207 press();
208 press();
209 });
210 expect(state.openPreview).toHaveBeenCalledTimes(1);
211 expect(state.navigate).not.toHaveBeenCalled();
212 await act(() => {
213 finish(AsyncResult.success({ tabId: "new-tab" }));
214 });
215 expect(state.navigate).toHaveBeenCalledTimes(2);
216 expect(useClosedViewStore.getState().entries).toEqual([]);
217 });
218
219 it("does not create a second browser when navigation fails after restoring it", async () => {
220 const store = useClosedViewStore.getState();
221 const older = store.remember({
222 kind: "panel-tab",
223 threadRef: ref,
224 surface: { kind: "diff", id: "diff" },
225 });
226 store.remember({ kind: "browser", threadRef: ref, snapshot });
227 state.openPreview.mockResolvedValue(AsyncResult.success({ tabId: "new-tab" }));
228 state.navigate.mockRejectedValueOnce(new Error("navigation failed"));
229 await render();
230 await act(() => {
231 press();
232 });
233 expect(
234 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref).activeSurfaceId,
235 ).toBe("browser:new-tab");
236 expect(state.toast).toHaveBeenCalledWith(
237 expect.objectContaining({ title: "Could not reopen view" }),
238 );
239 expect(useClosedViewStore.getState().entries.map((entry) => entry.id)).toEqual([older]);
240 await act(() => {
241 menuAction?.("view.reopenClosed");
242 });
243 expect(state.openPreview).toHaveBeenCalledOnce();
244 expect(
245 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref).activeSurfaceId,
246 ).toBe("diff");
247 expect(useClosedViewStore.getState().entries).toEqual([]);
248 });
249
250 it.each(["files", "file", "browser"] as const)(
251 "keeps a failed %s restore retryable without blocking older history",
252 async (kind) => {
253 const store = useClosedViewStore.getState();
254 const older = store.remember({
255 kind: "panel-tab",
256 threadRef: ref,
257 surface: { kind: "diff", id: "diff" },
258 });
259 const failed = store.remember(
260 kind === "browser"
261 ? { kind: "browser", threadRef: ref, snapshot }
262 : {
263 kind: "panel-tab",
264 threadRef: ref,
265 surface:
266 kind === "files"
267 ? { kind: "files", id: "files" }
268 : {
269 kind: "file",
270 id: "file:src/app.ts",
271 relativePath: "src/app.ts",
272 revealLine: null,
273 revealRequestId: 0,
274 },
275 },
276 );
277 state.workspaceAvailable = false;
278 state.openPreview.mockResolvedValue(AsyncResult.failure(Cause.fail(new Error("offline"))));
279 await render();
280 await act(() => {
281 press();
282 });
283 expect(useClosedViewStore.getState().entries.map((entry) => entry.id)).toEqual([
284 older,
285 failed,
286 ]);
287 expect(state.navigate).not.toHaveBeenCalled();
288 await act(() => {
289 menuAction?.("view.reopenClosed");
290 });
291 expect(
292 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref).activeSurfaceId,
293 ).toBe("diff");
294 expect(useClosedViewStore.getState().entries.map((entry) => entry.id)).toEqual([failed]);
295 state.workspaceAvailable = true;
296 state.openPreview.mockResolvedValue(AsyncResult.success({ ...snapshot, tabId: "new-tab" }));
297 await act(() => {
298 press();
299 });
300 expect(
301 selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, ref).activeSurfaceId,
302 ).toBe(
303 kind === "browser" ? "browser:new-tab" : kind === "file" ? "file:src/app.ts" : "files",
304 );
305 expect(useClosedViewStore.getState().entries).toEqual([]);
306 },
307 );
308
309 it("forwards the chord to a focused desktop browser only while history exists", async () => {
310 const forwardedCommands = () =>
311 (state.setShortcuts.mock.lastCall as unknown as [Array<{ command: string }>])[0].map(
312 ({ command }) => command,
313 );
314 useClosedViewStore
315 .getState()
316 .remember({ kind: "panel-tab", threadRef: ref, surface: { kind: "diff", id: "diff" } });
317 await render();
318 expect(forwardedCommands()).toContain("view.reopenClosed");
319 await act(() => {
320 menuAction?.("view.reopenClosed");
321 });
322 expect(useClosedViewStore.getState().entries).toEqual([]);
323 expect(forwardedCommands()).not.toContain("view.reopenClosed");
324 });
325
326 it("always forwards the layout toggles out of a focused desktop browser", async () => {
327 await render();
328 expect(state.setShortcuts).toHaveBeenLastCalledWith([
329 expect.objectContaining({ command: "sidebar.toggle" }),
330 expect.objectContaining({ command: "rightPanel.toggle" }),
331 ]);
332 });
333});