Open History to see the last commit
1import { m } from "../i18n/messages";
2import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
3import { useAtomValue } from "@effect/atom-react";
4import {
5 scopeProjectRef,
6 scopedThreadKey,
7 scopeThreadRef,
8} from "@t3tools/client-runtime/environment";
9import { EnvironmentId, type ScopedThreadRef } from "@t3tools/contracts";
10import { linkOptions, useNavigate, useParams, useRouter } from "@tanstack/react-router";
11import * as Effect from "effect/Effect";
12import { AtomRegistry } from "effect/reactivity";
13import { useGT } from "gt-react";
14import { useEffect, useEffectEvent, useRef } from "react";
15
16import { isCommandPaletteOpen } from "../commandPaletteBus";
17import { useClosedViewStore } from "../closedViewStore";
18import { useComposerDraftStore } from "../composerDraftStore";
19import { environmentCatalog } from "../connection/catalog";
20import { effectiveShortcutsForCommand, resolveShortcutCommand } from "../keybindings";
21import { isEditableFocused } from "../lib/editableFocus";
22import { onNavigationBlocked } from "../lib/navigationBlockers";
23import { isPreviewFocused } from "../lib/previewFocus";
24import { isTerminalFocused } from "../lib/terminalFocus";
25import { isModelPickerOpen } from "../modelPickerVisibility";
26import {
27 planNextReopen,
28 issuesSearchForRestore,
29 pullRequestsSearchForRestore,
30 reopenClosedView,
31} from "../reopenClosedView";
32import {
33 ISSUES_PANEL_REF,
34 PULL_REQUESTS_PANEL_REF,
35 selectActiveRightPanel,
36 selectSelectedRightPanelSurface,
37 selectThreadRightPanelState,
38 useRightPanelStore,
39} from "../rightPanelStore";
40import { serverEnvironment } from "../state/server";
41import { appAtomRegistry } from "../rpc/atomRegistry";
42import { readProject, readThreadShell } from "../state/entities";
43import { previewEnvironment } from "../state/preview";
44import { primaryServerKeybindingsAtom } from "../state/server";
45import { environmentShell } from "../state/shell";
46import { useAtomCommand } from "../state/use-atom-command";
47import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
48import {
49 buildDraftThreadRouteParams,
50 buildThreadRouteParams,
51 resolveThreadRouteTarget,
52} from "../threadRoutes";
53import { toastManager } from "./ui/toast";
54import { readIssueListPreferences } from "./issue/issueListPreferences";
55import { readPullRequestListPreferences } from "./pullRequest/pullRequestListPreferences";
56import { readWorkflowEnvironmentIds } from "./workflows/useWorkflowEnvironmentIds";
57
58declare module "@tanstack/react-router" {
59 interface HistoryState {
60 reopenedViewId?: string;
61 }
62}
63
64const PREVIEW_FORWARDED_COMMANDS = [
65 "workspace.focusNext",
66 "workspace.focusPrevious",
67 "sidebar.toggle",
68 "rightPanel.toggle",
69 "rightPanel.toggleMaximized",
70 "rightPanel.new",
71 "rightPanel.close",
72 "preview.focusUrl",
73 "preview.zoomIn",
74 "preview.zoomOut",
75 "preview.resetZoom",
76 "preview.find",
77] as const;
78
79const isGlobalPullRequests = (ref: ScopedThreadRef) =>
80 scopedThreadKey(ref) === scopedThreadKey(PULL_REQUESTS_PANEL_REF);
81const isGlobalIssues = (ref: ScopedThreadRef) =>
82 scopedThreadKey(ref) === scopedThreadKey(ISSUES_PANEL_REF);
83
84/** The runs the Workflows page can open, or null when the list does not arrive. */
85const readWorkflowRunIds = (environmentId: EnvironmentId) =>
86 Effect.runPromise(
87 AtomRegistry.getResult(
88 appAtomRegistry,
89 serverEnvironment.workflowsLive({ environmentId, input: {} }),
90 ).pipe(
91 Effect.map((snapshot) => new Set(snapshot.runs.map((run) => run.runId))),
92 Effect.timeout("5 seconds"),
93 Effect.orElseSucceed(() => null),
94 ),
95 );
96
97export function ReopenClosedViewShortcut() {
98 const gt = useGT();
99 const navigate = useNavigate();
100 const router = useRouter();
101 const params = useParams({ strict: false });
102 const target = resolveThreadRouteTarget(params);
103 const draft = useComposerDraftStore((state) =>
104 target?.kind === "draft" ? state.getDraftSession(target.draftId) : null,
105 );
106 const threadRef =
107 target?.kind === "server"
108 ? target.threadRef
109 : draft
110 ? (draft.promotedTo ?? scopeThreadRef(draft.environmentId, draft.threadId))
111 : null;
112 const terminalOpen = useTerminalUiStateStore(
113 (state) =>
114 selectThreadTerminalUiState(state.terminalUiStateByThreadKey, threadRef).terminalOpen,
115 );
116 const previewOpen = useRightPanelStore(
117 (state) => selectActiveRightPanel(state.byThreadKey, threadRef) === "preview",
118 );
119 const rightPanelOpen = useRightPanelStore(
120 (state) => selectThreadRightPanelState(state.byThreadKey, threadRef).isOpen,
121 );
122 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
123 const hasHistory = useClosedViewStore((state) => state.entries.length > 0);
124 const openPreview = useAtomCommand(previewEnvironment.open);
125 const pending = useRef(Promise.resolve());
126 type ReopenNavigation = { location: typeof router.history.location };
127 const reopenNavigation = useRef<ReopenNavigation | null>(null);
128
129 /** Plans from live state, limited to the history this press started with. */
130 const planReopen = (
131 requested: ReadonlySet<string>,
132 workflowRunIds: ReadonlyMap<EnvironmentId, ReadonlySet<string> | null>,
133 ) => {
134 const catalog = appAtomRegistry.get(environmentCatalog.catalogValueAtom);
135 const drafts = useComposerDraftStore.getState();
136 const panelsByThread = useRightPanelStore.getState().byThreadKey;
137 const entries = useClosedViewStore
138 .getState()
139 .entries.filter((entry) => requested.has(entry.id));
140 return planNextReopen(entries, (entry) => {
141 const ref = entry.threadRef;
142 const panel = selectThreadRightPanelState(panelsByThread, ref);
143 if (entry.kind === "panel-tab" && entry.surface.kind === "workflow-run") {
144 const id = EnvironmentId.make(entry.surface.environmentId);
145 return {
146 environmentKnown: !catalog.isReady || catalog.entries.has(id),
147 catalogReady: catalog.isReady,
148 ownerExists: readWorkflowEnvironmentIds().includes(id),
149 // History retention removes runs, and the page could only say this one is not here.
150 // A run list that failed to load leaves the run unverified, so it is skipped but kept.
151 sideChatExists: workflowRunIds.has(id)
152 ? (workflowRunIds.get(id)?.has(entry.surface.runId) ?? false)
153 : true,
154 shellLive: appAtomRegistry.get(environmentShell.stateValueAtom(id)).status === "live",
155 panel,
156 };
157 }
158 if (isGlobalPullRequests(ref) || isGlobalIssues(ref)) {
159 return {
160 environmentKnown: true,
161 catalogReady: true,
162 ownerExists: true,
163 sideChatExists: true,
164 shellLive: true,
165 panel,
166 };
167 }
168 return {
169 environmentKnown: catalog.entries.has(ref.environmentId),
170 catalogReady: catalog.isReady,
171 ownerExists: readThreadShell(ref) !== null || drafts.getDraftThreadByRef(ref) !== null,
172 sideChatExists:
173 entry.kind !== "panel-tab" ||
174 entry.surface.kind !== "thread" ||
175 readThreadShell(scopeThreadRef(ref.environmentId, entry.surface.threadId)) !== null ||
176 // The shell leaves idle subagents out, so one it does not list may still exist.
177 appAtomRegistry.get(serverEnvironment.configValueAtom(ref.environmentId))
178 ?.shellThreadFamilies === true,
179 shellLive:
180 appAtomRegistry.get(environmentShell.stateValueAtom(ref.environmentId)).status === "live",
181 panel,
182 };
183 });
184 };
185
186 const reopenNext = useEffectEvent(async (request: ReopenNavigation) => {
187 const requested = new Set(useClosedViewStore.getState().entries.map((entry) => entry.id));
188 const workflowRunIds = new Map<EnvironmentId, ReadonlySet<string> | null>();
189 let plan = planReopen(requested, workflowRunIds);
190 // Only a workflow run about to be restored needs its environment's run list.
191 while (plan.restore?.kind === "panel-tab" && plan.restore.surface.kind === "workflow-run") {
192 const id = EnvironmentId.make(plan.restore.surface.environmentId);
193 if (workflowRunIds.has(id)) break;
194 if (appAtomRegistry.get(environmentShell.stateValueAtom(id)).status !== "live") break;
195 workflowRunIds.set(id, await readWorkflowRunIds(id));
196 plan = planReopen(requested, workflowRunIds);
197 }
198 const { drop, restore } = plan;
199 for (const entry of drop) useClosedViewStore.getState().remove(entry.id);
200 if (!restore) {
201 if ([...workflowRunIds.values()].includes(null)) {
202 toastManager.add({ type: "error", title: gt`Could not reopen view` });
203 }
204 return;
205 }
206 const drafts = useComposerDraftStore.getState();
207 const ref = restore.threadRef;
208 const globalPullRequests = isGlobalPullRequests(ref);
209 const globalIssues = isGlobalIssues(ref);
210 const workflowRun =
211 restore.kind === "panel-tab" && restore.surface.kind === "workflow-run"
212 ? restore.surface
213 : null;
214 const thread = globalPullRequests || globalIssues || workflowRun ? null : readThreadShell(ref);
215 if (!workflowRun) {
216 const owner = thread ?? drafts.getDraftThreadByRef(ref);
217 const project = owner
218 ? readProject(scopeProjectRef(ref.environmentId, owner.projectId))
219 : null;
220 if (
221 !(await reopenClosedView(restore, { openPreview, workspaceAvailable: project !== null }))
222 ) {
223 useClosedViewStore.getState().defer(restore.id);
224 return;
225 }
226 useClosedViewStore.getState().remove(restore.id);
227 }
228 // Workflows need a navigation to restore. Leave the entry for the next press
229 // if the user has already moved elsewhere.
230 if (router.history.location !== request.location) return;
231
232 let destination;
233 if (workflowRun) {
234 // The Workflows route opens the panel for the run it names.
235 destination = linkOptions({
236 to: "/workflows",
237 search: { env: workflowRun.environmentId, run: workflowRun.runId },
238 });
239 } else if (globalPullRequests || globalIssues) {
240 const selected = selectSelectedRightPanelSurface(
241 useRightPanelStore.getState().byThreadKey,
242 ref,
243 );
244 destination = globalPullRequests
245 ? linkOptions({
246 to: "/pull-requests",
247 search: pullRequestsSearchForRestore(readPullRequestListPreferences(), selected),
248 })
249 : linkOptions({
250 to: "/issues",
251 search: issuesSearchForRestore(readIssueListPreferences(), selected),
252 });
253 } else {
254 const draftId = thread === null ? drafts.getDraftIdByRef(ref) : null;
255 destination =
256 draftId !== null
257 ? linkOptions({ to: "/draft/$draftId", params: buildDraftThreadRouteParams(draftId) })
258 : linkOptions({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(ref) });
259 }
260
261 const { history } = router;
262 const consumeWorkflowRun = () => {
263 if (
264 workflowRun &&
265 readWorkflowEnvironmentIds().includes(EnvironmentId.make(workflowRun.environmentId))
266 ) {
267 useClosedViewStore.getState().remove(restore.id);
268 }
269 };
270 if (router.buildLocation(destination).publicHref === history.location.href) {
271 const { reopenedViewId } = history.location.state;
272 await navigate({ ...destination, state: reopenedViewId ? { reopenedViewId } : {} });
273 consumeWorkflowRun();
274 return;
275 }
276
277 // An allowing blocker can defer the commit. Only the reopen's first history hop extends the queue.
278 const unsubscribe = history.subscribe(({ location, action }) => {
279 if (location === request.location) return;
280 unsubscribe();
281 if (action.type === "PUSH" && location.state.reopenedViewId === restore.id) {
282 request.location = location;
283 // The workflow run is reopened by navigation, which an unsaved draft can block.
284 consumeWorkflowRun();
285 }
286 });
287 // TanStack leaves navigate pending when a history blocker declines the push.
288 const canceled = Promise.withResolvers<void>();
289 const unsubscribeBlocked = onNavigationBlocked(history, (state) => {
290 if (state.reopenedViewId === restore.id) canceled.resolve();
291 });
292 const stopWatching = () => {
293 unsubscribeBlocked();
294 unsubscribe();
295 };
296 try {
297 await Promise.race([
298 navigate({ ...destination, state: { reopenedViewId: restore.id } }),
299 canceled.promise,
300 ]);
301 } catch (error) {
302 stopWatching();
303 throw error;
304 }
305 stopWatching();
306 });
307
308 const enqueueReopen = useEffectEvent(() => {
309 const location = router.history.location;
310 const previous = reopenNavigation.current;
311 const request = previous?.location === location ? previous : { location };
312 reopenNavigation.current = request;
313 pending.current = pending.current
314 .then(() => reopenNext(request))
315 .catch((error: unknown) => {
316 toastManager.add({
317 type: "error",
318 title: gt`Could not reopen view`,
319 description: thrownErrorMessage(error, m) ?? String(error),
320 });
321 });
322 });
323
324 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to window keydown and the desktop menu action for the reopen closed view shortcut
325 useEffect(() => {
326 const onKeyDown = (event: KeyboardEvent) => {
327 if (
328 event.defaultPrevented ||
329 isCommandPaletteOpen() ||
330 useClosedViewStore.getState().entries.length === 0 ||
331 (event.target instanceof HTMLElement && event.target.closest("[data-keybinding-capture]"))
332 )
333 return;
334 const command = resolveShortcutCommand(event, keybindings, {
335 context: {
336 terminalFocus: isTerminalFocused(),
337 terminalOpen,
338 previewFocus: isPreviewFocused(),
339 previewOpen,
340 rightPanelOpen,
341 editableFocus: isEditableFocused(event.target),
342 modelPickerOpen: isModelPickerOpen(),
343 },
344 });
345 if (command !== "view.reopenClosed") return;
346 event.preventDefault();
347 event.stopPropagation();
348 if (!event.repeat) enqueueReopen();
349 };
350 window.addEventListener("keydown", onKeyDown, true);
351 const unsubscribe = window.desktopBridge?.onMenuAction((action) => {
352 if (action === "view.reopenClosed" && !isCommandPaletteOpen()) enqueueReopen();
353 });
354 return () => {
355 window.removeEventListener("keydown", onKeyDown, true);
356 unsubscribe?.();
357 };
358 }, [keybindings, previewOpen, rightPanelOpen, terminalOpen]);
359
360 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers forwarded shortcut chords with the desktop preview bridge and clears them on cleanup
361 useEffect(() => {
362 const preview = window.desktopBridge?.preview;
363 if (!preview) return;
364 const options = {
365 context: {
366 previewFocus: true,
367 previewOpen: true,
368 rightPanelOpen: true,
369 terminalFocus: false,
370 terminalOpen,
371 editableFocus: false,
372 modelPickerOpen: false,
373 isDesktop: true,
374 isWeb: false,
375 },
376 };
377 // Guest browser processes miss app keydown listeners; desktop forwards the chords as menu actions.
378 const commands = [
379 ...(hasHistory ? (["view.reopenClosed"] as const) : []),
380 ...PREVIEW_FORWARDED_COMMANDS,
381 ];
382 void preview
383 .setForwardedShortcuts(
384 commands.flatMap((command) =>
385 effectiveShortcutsForCommand(keybindings, command, options).map((shortcut) => ({
386 command,
387 shortcut,
388 })),
389 ),
390 )
391 .catch(() => undefined);
392 return () => {
393 void preview.setForwardedShortcuts([]).catch(() => undefined);
394 };
395 }, [hasHistory, keybindings, terminalOpen]);
396
397 return null;
398}