Open History to see the last commit
1import {
2 AuthPreviewOperateScope,
3 AuthTerminalOperateScope,
4 type ScopedThreadRef,
5} from "@t3tools/contracts";
6import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
7import { agentControlledBrowserCloseConfirmation } from "../components/ChatView.logic";
8import { closePreviewSession } from "../components/preview/closePreviewSession";
9import { useThreadTerminalActions } from "../components/terminal/useThreadTerminalActions";
10import { confirmTerminalClose } from "../lib/terminalCloseConfirm";
11import { focusPanelTerminalAfterClose } from "../lib/terminalFocus";
12import { readLocalApi } from "../localApi";
13import { setActivePreviewTab, useThreadPreviewState } from "../previewStateStore";
14import {
15 selectActiveRightPanelSurface,
16 selectThreadRightPanelState,
17 useRightPanelStore,
18 type RightPanelSurface,
19} from "../rightPanelStore";
20import { previewEnvironment } from "../state/preview";
21import { readEnvironmentScope, useEnvironmentScope } from "../state/session";
22import { useAtomCommand } from "../state/use-atom-command";
23import { useTerminalUiStateStore } from "../terminalUiStateStore";
24import { useStableCallback } from "./useStableCallback";
25
26/** Closing releases preview and terminal sessions. Agent-driven browsers and terminal tabs require confirmation. */
27export function useRightPanelSurfaceClose(input: {
28 readonly threadRef: ScopedThreadRef | null;
29 readonly terminalLabelsById: ReadonlyMap<string, string>;
30}) {
31 const { threadRef, terminalLabelsById } = input;
32 const closePreview = useAtomCommand(previewEnvironment.close, "preview close");
33 const canOperatePreview = useEnvironmentScope(
34 threadRef?.environmentId ?? null,
35 AuthPreviewOperateScope,
36 );
37 const previewState = useThreadPreviewState(threadRef);
38 const terminalActions = useThreadTerminalActions(threadRef);
39 const storeCloseTerminal = useTerminalUiStateStore((state) => state.closeTerminal);
40 const surfaces = useRightPanelStore(
41 (state) => selectThreadRightPanelState(state.byThreadKey, threadRef).surfaces,
42 );
43
44 const releaseSurfaceResources = (ref: ScopedThreadRef, surface: RightPanelSurface) => {
45 // Without preview access, server state remains until an authorized close or restart.
46 if (canOperatePreview && surface.kind === "preview" && surface.resourceId) {
47 void closePreviewSession({
48 closePreview,
49 snapshot: previewState.sessions[surface.resourceId] ?? null,
50 tabId: surface.resourceId,
51 threadRef: ref,
52 });
53 }
54 if (
55 surface.kind === "terminal" &&
56 readEnvironmentScope(ref.environmentId, AuthTerminalOperateScope)
57 ) {
58 for (const terminalId of surface.terminalIds) {
59 storeCloseTerminal(ref, terminalId);
60 terminalActions.closeTerminalSession(terminalId);
61 }
62 }
63 };
64 const closeAfterAgentBrowserConfirmation = (
65 toClose: readonly RightPanelSurface[],
66 closeSurfaces: () => void,
67 ) => {
68 const message = agentControlledBrowserCloseConfirmation(toClose, previewState.desktopByTabId);
69 if (!message) {
70 closeSurfaces();
71 return;
72 }
73 const localApi = readLocalApi();
74 if (!localApi) return;
75 void localApi.dialogs.confirm(message, { variant: "destructive" }).then(
76 (confirmed) => {
77 if (confirmed) closeSurfaces();
78 },
79 () => undefined,
80 );
81 };
82 // The active surface closes last so the panel does not flash through it.
83 const finishClose = (toClose: readonly RightPanelSurface[]) => {
84 if (!threadRef) return;
85 const store = useRightPanelStore.getState();
86 const activeId = selectThreadRightPanelState(store.byThreadKey, threadRef).activeSurfaceId;
87 const ordered = toClose.toSorted(
88 (left, right) => Number(left.id === activeId) - Number(right.id === activeId),
89 );
90 for (const surface of ordered) {
91 // Releasing a browser drops its session, which prunes the tab automatically; close it
92 // first so the close stays a user action that hides the panel after the last tab.
93 store.closeSurface(threadRef, surface.id);
94 releaseSurfaceResources(threadRef, surface);
95 }
96 const nextActiveSurface = selectActiveRightPanelSurface(
97 useRightPanelStore.getState().byThreadKey,
98 threadRef,
99 );
100 if (nextActiveSurface?.kind === "preview" && nextActiveSurface.resourceId) {
101 setActivePreviewTab(threadRef, nextActiveSurface.resourceId);
102 }
103 focusPanelTerminalAfterClose(threadRef, activeId);
104 };
105 const labelFor = (terminalId: string) =>
106 terminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId);
107 const closeSurfaces = (toClose: readonly RightPanelSurface[]) => {
108 if (!threadRef) return;
109 closeAfterAgentBrowserConfirmation(toClose, () => finishClose(toClose));
110 };
111
112 const closeSurface = useStableCallback((surface: RightPanelSurface) => {
113 if (!threadRef) return;
114 if (surface.kind === "preview") {
115 closeSurfaces([surface]);
116 return;
117 }
118 if (
119 surface.kind !== "terminal" ||
120 !readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope)
121 ) {
122 finishClose([surface]);
123 return;
124 }
125 const otherLabels = surface.terminalIds
126 .filter((terminalId) => terminalId !== surface.activeTerminalId)
127 .map(labelFor);
128 void confirmTerminalClose([labelFor(surface.activeTerminalId), ...otherLabels]).then(
129 (confirmed) => {
130 if (confirmed) finishClose([surface]);
131 },
132 );
133 });
134 const closeOtherSurfaces = useStableCallback((surface: RightPanelSurface) =>
135 closeSurfaces(surfaces.filter((entry) => entry.id !== surface.id)),
136 );
137 const closeSurfacesToRight = useStableCallback((surface: RightPanelSurface) => {
138 const surfaceIndex = surfaces.findIndex((entry) => entry.id === surface.id);
139 if (surfaceIndex < 0) return;
140 closeSurfaces(surfaces.slice(surfaceIndex + 1));
141 });
142 const closeAllSurfaces = useStableCallback(() => closeSurfaces(surfaces));
143
144 return { closeSurface, closeOtherSurfaces, closeSurfacesToRight, closeAllSurfaces };
145}