TypeScript
refactor(web): move right panel surface closing out of ChatView (#20315)
Julius Marmingec07eddfbed54
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex eb7166518df..6d2ff0ca77c 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -240,7 +240,6 @@ import { BrowserSettingsReadError, openUrlInPreview } from "../browser/openFileIimport { resolveDiscoveredServerUrl } from "../browser/browserTargetResolver";import { previewRuntimeTabId } from "../browser/previewRuntimeTabId";import { addBrowserSurface } from "./preview/addBrowserSurface";-import { closePreviewSession } from "./preview/closePreviewSession";import { ThreadPreviewMiniPlayer } from "./preview/ThreadPreviewMiniPlayer";import { usePreviewSession } from "./preview/usePreviewSession";import { subscribePreviewAction } from "./preview/previewActionBus";@@ -462,6 +461,7 @@ import {import { QueuedRunsControl, type QueuedRunsControlHandle } from "./chat/QueuedRunsControl";import { useThreadLinkedPullRequest } from "./pullRequest/useThreadLinkedPullRequest";import { useProactivePanels } from "../hooks/useProactivePanels";+import { useRightPanelSurfaceClose } from "../hooks/useRightPanelSurfaceClose";import { useAgentOpenedPreviews } from "./preview/useAgentOpenedPreviews";import type { ComposerBannerStackItem } from "./chat/ComposerBannerStack";import { ThreadStatusLine } from "./chat/ThreadStatusLine";@@ -487,7 +487,6 @@ import {import type { ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch";import {MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,- agentControlledBrowserCloseConfirmation,branchMismatchKey,buildExpiredTerminalContextToastCopy,buildLocalDraftThread,@@ -1040,7 +1039,6 @@ export default function ChatView(props: ChatViewProps) {reportFailure: false,});const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false });- const closePreview = useAtomCommand(previewEnvironment.close, "preview close");const { environments } = useEnvironments();const primaryEnvironment = usePrimaryEnvironment();const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, { reportFailure: false });@@ -4336,126 +4334,16 @@ export default function ChatView(props: ChatViewProps) {useRightPanelStore.getState().setMaximized(activeThreadRef, !rightPanelMaximized);};const toggleRightPanelMaximizedStable = useStableCallback(toggleRightPanelMaximized);- const cleanupRightPanelSurfaces = (surfaces: readonly RightPanelSurface[]) => {- if (!activeThreadRef) return;- for (const surface of surfaces) {- if (canOperatePreview && surface.kind === "preview" && surface.resourceId) {- void closePreviewSession({- closePreview,- snapshot: activePreviewState.sessions[surface.resourceId] ?? null,- tabId: surface.resourceId,- threadRef: activeThreadRef,- });- }- if (- surface.kind === "terminal" &&- readEnvironmentScope(activeThreadRef.environmentId, AuthTerminalOperateScope)- ) {- for (const terminalId of surface.terminalIds) {- storeCloseTerminal(activeThreadRef, terminalId);- terminalActions.closeTerminalSession(terminalId);- }- }- }- };- const closeAfterAgentBrowserConfirmation = (- surfaces: readonly RightPanelSurface[],- closeSurfaces: () => void,- ) => {- const message = agentControlledBrowserCloseConfirmation(- surfaces,- activePreviewState.desktopByTabId,- );- if (!message) {- closeSurfaces();- return;- }- const localApi = readLocalApi();- if (!localApi) return;- void localApi.dialogs.confirm(message, { variant: "destructive" }).then(- (confirmed) => {- if (confirmed) closeSurfaces();- },- () => undefined,- );- };- const syncActivePreviewSurface = () => {- if (!activeThreadRef) return;- const nextActiveSurface = selectActiveRightPanelSurface(- useRightPanelStore.getState().byThreadKey,- activeThreadRef,- );- if (nextActiveSurface?.kind === "preview" && nextActiveSurface.resourceId) {- setActivePreviewTab(activeThreadRef, nextActiveSurface.resourceId);- }- };- const finishRightPanelSurfaceClose = (surfaces: readonly RightPanelSurface[]) => {- if (!activeThreadRef) return;- const store = useRightPanelStore.getState();- const activeId = selectThreadRightPanelState(- store.byThreadKey,- activeThreadRef,- ).activeSurfaceId;- const ordered = surfaces.toSorted(- (left, right) => Number(left.id === activeId) - Number(right.id === activeId),- );- for (const surface of ordered) {- cleanupRightPanelSurfaces([surface]);- store.closeSurface(activeThreadRef, surface.id);- }- syncActivePreviewSurface();- };- const closeRightPanelSurface = (surface: RightPanelSurface) => {- if (!activeThreadRef) return;- const finishClose = () => finishRightPanelSurfaceClose([surface]);- if (surface.kind === "preview") {- closeAfterAgentBrowserConfirmation([surface], finishClose);- return;- }- if (- surface.kind !== "terminal" ||- !readEnvironmentScope(activeThreadRef.environmentId, AuthTerminalOperateScope)- ) {- finishClose();- return;- }- const activeLabel =- activeTerminalLabelsById.get(surface.activeTerminalId) ??- getTerminalLabel(surface.activeTerminalId);- const otherLabels = surface.terminalIds- .filter((terminalId) => terminalId !== surface.activeTerminalId)- .map(- (terminalId) => activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId),- );- void confirmTerminalClose([activeLabel, ...otherLabels]).then((confirmed) => {- if (confirmed) {- finishClose();- }- });- };- const closeRightPanelSurfaceStable = useStableCallback(closeRightPanelSurface);- const closeOtherRightPanelSurfaces = (surface: RightPanelSurface) => {- if (!activeThreadRef) return;- const surfaces = rightPanelState.surfaces.filter((entry) => entry.id !== surface.id);- const finishClose = () => finishRightPanelSurfaceClose(surfaces);- closeAfterAgentBrowserConfirmation(surfaces, finishClose);- };- const closeOtherRightPanelSurfacesStable = useStableCallback(closeOtherRightPanelSurfaces);- const closeRightPanelSurfacesToRight = (surface: RightPanelSurface) => {- if (!activeThreadRef) return;- const surfaceIndex = rightPanelState.surfaces.findIndex((entry) => entry.id === surface.id);- if (surfaceIndex < 0) return;- const surfaces = rightPanelState.surfaces.slice(surfaceIndex + 1);- const finishClose = () => finishRightPanelSurfaceClose(surfaces);- closeAfterAgentBrowserConfirmation(surfaces, finishClose);- };- const closeRightPanelSurfacesToRightStable = useStableCallback(closeRightPanelSurfacesToRight);- const closeAllRightPanelSurfaces = () => {- if (!activeThreadRef) return;- const finishClose = () => finishRightPanelSurfaceClose(rightPanelState.surfaces);- closeAfterAgentBrowserConfirmation(rightPanelState.surfaces, finishClose);- };- const closeAllRightPanelSurfacesStable = useStableCallback(closeAllRightPanelSurfaces);+ const {+ closeSurface: closeRightPanelSurface,+ closeOtherSurfaces: closeOtherRightPanelSurfacesStable,+ closeSurfacesToRight: closeRightPanelSurfacesToRightStable,+ closeAllSurfaces: closeAllRightPanelSurfacesStable,+ } = useRightPanelSurfaceClose({+ threadRef: activeThreadRef,+ terminalLabelsById: activeTerminalLabelsById,+ });+ const closeRightPanelSurfaceStable = closeRightPanelSurface;const moveRightPanelSurface = (surfaceId: string, toIndex: number) => {if (activeThreadRef)useRightPanelStore.getState().moveSurface(activeThreadRef, surfaceId, toIndex);diff --git a/apps/web/src/hooks/useRightPanelSurfaceClose.ts b/apps/web/src/hooks/useRightPanelSurfaceClose.tsnew file mode 100644index 00000000000..77667248fb6--- /dev/null+++ b/apps/web/src/hooks/useRightPanelSurfaceClose.ts@@ -0,0 +1,147 @@+import {+ AuthPreviewOperateScope,+ AuthTerminalOperateScope,+ type ScopedThreadRef,+} from "@t3tools/contracts";+import { getTerminalLabel } from "@t3tools/shared/terminalLabels";+import { agentControlledBrowserCloseConfirmation } from "../components/ChatView.logic";+import { closePreviewSession } from "../components/preview/closePreviewSession";+import { useThreadTerminalActions } from "../components/terminal/useThreadTerminalActions";+import { confirmTerminalClose } from "../lib/terminalCloseConfirm";+import { readLocalApi } from "../localApi";+import { setActivePreviewTab, useThreadPreviewState } from "../previewStateStore";+import {+ selectActiveRightPanelSurface,+ selectThreadRightPanelState,+ useRightPanelStore,+ type RightPanelSurface,+} from "../rightPanelStore";+import { previewEnvironment } from "../state/preview";+import { readEnvironmentScope, useEnvironmentScope } from "../state/session";+import { useAtomCommand } from "../state/use-atom-command";+import { useTerminalUiStateStore } from "../terminalUiStateStore";+import { useStableCallback } from "./useStableCallback";++/**+ * Closes right panel surfaces for a thread. A surface's live resources go with+ * it: a browser's preview session and a terminal tab's sessions. Closing a+ * browser an agent is driving, or a terminal tab, asks first.+ */+export function useRightPanelSurfaceClose(input: {+ readonly threadRef: ScopedThreadRef | null;+ readonly terminalLabelsById: ReadonlyMap<string, string>;+}) {+ const { threadRef, terminalLabelsById } = input;+ const closePreview = useAtomCommand(previewEnvironment.close, "preview close");+ const canOperatePreview = useEnvironmentScope(+ threadRef?.environmentId ?? null,+ AuthPreviewOperateScope,+ );+ const previewState = useThreadPreviewState(threadRef);+ const terminalActions = useThreadTerminalActions(threadRef);+ const storeCloseTerminal = useTerminalUiStateStore((state) => state.closeTerminal);+ const surfaces = useRightPanelStore(+ (state) => selectThreadRightPanelState(state.byThreadKey, threadRef).surfaces,+ );++ const releaseSurfaceResources = (ref: ScopedThreadRef, surface: RightPanelSurface) => {+ // Without preview access only the local surface goes away. The+ // server record is in-memory bookkeeping, not a live view, and stays+ // listed until a client with the scope closes it or the server restarts.+ if (canOperatePreview && surface.kind === "preview" && surface.resourceId) {+ void closePreviewSession({+ closePreview,+ snapshot: previewState.sessions[surface.resourceId] ?? null,+ tabId: surface.resourceId,+ threadRef: ref,+ });+ }+ if (+ surface.kind === "terminal" &&+ readEnvironmentScope(ref.environmentId, AuthTerminalOperateScope)+ ) {+ for (const terminalId of surface.terminalIds) {+ storeCloseTerminal(ref, terminalId);+ terminalActions.closeTerminalSession(terminalId);+ }+ }+ };+ const closeAfterAgentBrowserConfirmation = (+ toClose: readonly RightPanelSurface[],+ closeSurfaces: () => void,+ ) => {+ const message = agentControlledBrowserCloseConfirmation(toClose, previewState.desktopByTabId);+ if (!message) {+ closeSurfaces();+ return;+ }+ const localApi = readLocalApi();+ if (!localApi) return;+ void localApi.dialogs.confirm(message, { variant: "destructive" }).then(+ (confirmed) => {+ if (confirmed) closeSurfaces();+ },+ () => undefined,+ );+ };+ // The active surface closes last so the panel does not flash through it.+ const finishClose = (toClose: readonly RightPanelSurface[]) => {+ if (!threadRef) return;+ const store = useRightPanelStore.getState();+ const activeId = selectThreadRightPanelState(store.byThreadKey, threadRef).activeSurfaceId;+ const ordered = toClose.toSorted(+ (left, right) => Number(left.id === activeId) - Number(right.id === activeId),+ );+ for (const surface of ordered) {+ releaseSurfaceResources(threadRef, surface);+ store.closeSurface(threadRef, surface.id);+ }+ const nextActiveSurface = selectActiveRightPanelSurface(+ useRightPanelStore.getState().byThreadKey,+ threadRef,+ );+ if (nextActiveSurface?.kind === "preview" && nextActiveSurface.resourceId) {+ setActivePreviewTab(threadRef, nextActiveSurface.resourceId);+ }+ };+ const labelFor = (terminalId: string) =>+ terminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId);+ const closeSurfaces = (toClose: readonly RightPanelSurface[]) => {+ if (!threadRef) return;+ closeAfterAgentBrowserConfirmation(toClose, () => finishClose(toClose));+ };++ const closeSurface = useStableCallback((surface: RightPanelSurface) => {+ if (!threadRef) return;+ if (surface.kind === "preview") {+ closeSurfaces([surface]);+ return;+ }+ if (+ surface.kind !== "terminal" ||+ !readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope)+ ) {+ finishClose([surface]);+ return;+ }+ const otherLabels = surface.terminalIds+ .filter((terminalId) => terminalId !== surface.activeTerminalId)+ .map(labelFor);+ void confirmTerminalClose([labelFor(surface.activeTerminalId), ...otherLabels]).then(+ (confirmed) => {+ if (confirmed) finishClose([surface]);+ },+ );+ });+ const closeOtherSurfaces = useStableCallback((surface: RightPanelSurface) =>+ closeSurfaces(surfaces.filter((entry) => entry.id !== surface.id)),+ );+ const closeSurfacesToRight = useStableCallback((surface: RightPanelSurface) => {+ const surfaceIndex = surfaces.findIndex((entry) => entry.id === surface.id);+ if (surfaceIndex < 0) return;+ closeSurfaces(surfaces.slice(surfaceIndex + 1));+ });+ const closeAllSurfaces = useStableCallback(() => closeSurfaces(surfaces));++ return { closeSurface, closeOtherSurfaces, closeSurfacesToRight, closeAllSurfaces };+}diff --git a/vite.config.ts b/vite.config.tsindex 8657c819785..23f232b7ce9 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -334,6 +334,7 @@ export default defineConfig({"apps/web/src/components/preview/useAgentOpenedPreviews.ts","apps/web/src/components/terminal/**","apps/web/src/hooks/useProactivePanels.ts",+ "apps/web/src/hooks/useRightPanelSurfaceClose.ts",],rules: {"react/exhaustive-effect-dependencies": "error",