Open History to see the last commit
1import type { ToolCallDiffTarget } from "../../diffPanelStore";
2import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
3import type { ThreadPreviewState } from "../../previewStateStore";
4import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions";
5import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
6import { resolveExplicitDiffOpenOnActivate } from "../ChatView.logic";
7import { useStableCallback } from "../../hooks/useStableCallback";
8import { type ScopedThreadRef, type RunId } from "@t3tools/contracts";
9import { scopedThreadKey } from "@t3tools/client-runtime/environment";
10import { useEffect } from "react";
11import {
12 isAtomCommandInterrupted,
13 squashAtomCommandFailure,
14} from "@t3tools/client-runtime/state/runtime";
15import { useDiffPanelStore } from "../../diffPanelStore";
16import { type ThreadPanelPresentation } from "../../rightPanelLayout";
17import {
18 selectActiveRightPanel,
19 selectThreadPanelOpen,
20 type RightPanelSurface,
21 useRightPanelStore,
22} from "../../rightPanelStore";
23import { requestWorkspaceContentFocus, requestWorkspaceFocus } from "../../lib/workspaceFocus";
24import { setActivePreviewTab } from "../../previewStateStore";
25import { BrowserSettingsReadError } from "../../browser/openFileInPreview";
26import { addBrowserSurface } from "../preview/addBrowserSurface";
27import { focusActivePanelTerminal, focusTerminal } from "../../lib/terminalFocus";
28import { subscribePreviewAction } from "../preview/previewActionBus";
29import { floatDeviceSurface } from "../preview/agentOpenedPreviews";
30import { browserMiniPlayerSource, usePreviewMiniPlayerStore } from "../../previewMiniPlayerStore";
31import type { threadPullRequestPanelTarget } from "../pullRequest/pullRequestDetail.logic";
32import type { useDeviceState } from "../../state/device";
33import { stackedThreadToast, toastManager } from "../ui/toast";
34import { openDeviceSetupDialog } from "./ChatOverlayHosts";
35import { previewEnvironment } from "../../state/preview";
36import { useAtomCommand } from "../../state/use-atom-command";
37import type { ChatShortcutCommands } from "./useChatShortcuts";
38interface RightPanelActionsInput {
39 readonly activeThreadRef: ScopedThreadRef | null;
40 readonly activeProject: EnvironmentProject | null;
41 readonly activeRightPanelSurface: RightPanelSurface | null;
42 readonly activePreviewState: ThreadPreviewState;
43 readonly deviceState: ReturnType<typeof useDeviceState>["state"];
44 readonly deviceStateLoaded: boolean;
45 readonly pullRequestPanelTarget: ReturnType<typeof threadPullRequestPanelTarget> | null;
46 readonly threadPanelPresentation: ThreadPanelPresentation;
47 readonly isServerThread: boolean;
48 /** A side chat pane; the main view already answers preview bus actions. */
49 readonly embedded: boolean;
50 readonly isGitRepo: boolean;
51 readonly browserAvailable: boolean;
52 readonly canOperatePreview: boolean;
53 readonly diffOpen: boolean;
54 readonly previewPanelOpen: boolean;
55 readonly rightPanelOpen: boolean;
56 readonly canMaximizeRightPanel: boolean;
57 readonly rightPanelMaximized: boolean;
58 readonly supportsPullRequests: boolean;
59 readonly pullRequestsSurfaceAvailable: boolean;
60 readonly gitCwd: string | null;
61 readonly activeProjectCwd: string | null;
62 readonly explicitDiffOpenRef: { current: ScopedThreadRef | null };
63 readonly onDiffPanelOpen: (() => void) | undefined;
64 readonly closeRightPanelSurface: (surface: RightPanelSurface) => void;
65}
66
67/**
68 * Opening, closing, and arranging the right panel's surfaces: browser, diff, files, pull
69 * requests, device, and terminal tabs.
70 */
71export function useRightPanelActions(input: RightPanelActionsInput) {
72 const {
73 closeRightPanelSurface,
74 activeThreadRef,
75 activeProject,
76 activeRightPanelSurface,
77 activePreviewState,
78 deviceState,
79 deviceStateLoaded,
80 pullRequestPanelTarget,
81 threadPanelPresentation,
82 isServerThread,
83 embedded,
84 isGitRepo,
85 browserAvailable,
86 canOperatePreview,
87 diffOpen,
88 previewPanelOpen,
89 rightPanelOpen,
90 canMaximizeRightPanel,
91 rightPanelMaximized,
92 supportsPullRequests,
93 pullRequestsSurfaceAvailable,
94 gitCwd,
95 activeProjectCwd,
96 explicitDiffOpenRef,
97 onDiffPanelOpen,
98 } = input;
99
100 const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false });
101 const onToggleDiff = () => {
102 if (!isServerThread) {
103 return;
104 }
105 if (!diffOpen) {
106 onDiffPanelOpen?.();
107 }
108 if (activeThreadRef) {
109 useRightPanelStore.getState().toggle(activeThreadRef, "diff");
110 }
111 };
112 const onToggleDiffStable = useStableCallback(onToggleDiff);
113 const createBrowserSurface = (profileId?: string) => {
114 if (!activeThreadRef || !canOperatePreview) return;
115 void addBrowserSurface({
116 threadRef: activeThreadRef,
117 openPreview,
118 ...(profileId === undefined ? {} : { profileId }),
119 }).then((result) => {
120 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
121 const error = squashAtomCommandFailure(result);
122 if (error instanceof BrowserSettingsReadError) {
123 toastManager.add(
124 stackedThreadToast({
125 type: "error",
126 title: "Unable to open browser",
127 description: error.message,
128 }),
129 );
130 }
131 });
132 };
133 const createBrowserSurfaceStable = useStableCallback(createBrowserSurface);
134 const addDiffSurface = () => {
135 if (!activeThreadRef || !isServerThread || !isGitRepo) return;
136 useDiffPanelStore.getState().selectGitScope(activeThreadRef, "branch");
137 useRightPanelStore.getState().open(activeThreadRef, "diff");
138 onDiffPanelOpen?.();
139 };
140 const addDiffSurfaceStable = useStableCallback(addDiffSurface);
141 const openChangesFromThreadPanel = () => {
142 addDiffSurface();
143 };
144 const openChangesFromThreadPanelStable = useStableCallback(openChangesFromThreadPanel);
145 const addFilesSurface = () => {
146 if (!activeThreadRef || !activeProject) return;
147 useRightPanelStore.getState().open(activeThreadRef, "files");
148 };
149 const addFilesSurfaceStable = useStableCallback(addFilesSurface);
150 const addPullRequestsSurface = () => {
151 if (!activeThreadRef || !pullRequestsSurfaceAvailable) return;
152 useRightPanelStore.getState().open(activeThreadRef, "pull-requests");
153 };
154 const addPullRequestsSurfaceStable = useStableCallback(addPullRequestsSurface);
155 const addDeviceSurface = () => {
156 if (!activeThreadRef) return;
157 if (!deviceState.onboardingCompleted || deviceState.hostStatus === "disabled") {
158 openDeviceSetupDialog(scopedThreadKey(activeThreadRef));
159 return;
160 }
161 useRightPanelStore.getState().open(activeThreadRef, "device");
162 };
163 const addDeviceSurfaceStable = useStableCallback(addDeviceSurface);
164 const openFileSurface = (relativePath: string) => {
165 if (!activeThreadRef || !activeProject) return;
166 useRightPanelStore.getState().openFile(activeThreadRef, relativePath);
167 };
168 const openFileSurfaceStable = useStableCallback(openFileSurface);
169 const closePreviewPanel = () => {
170 if (activeThreadRef) {
171 if (activeRightPanelSurface?.kind === "preview" && activeRightPanelSurface.resourceId) {
172 usePreviewMiniPlayerStore
173 .getState()
174 .open(activeThreadRef, browserMiniPlayerSource(activeRightPanelSurface.resourceId));
175 } else if (activeRightPanelSurface?.kind === "device" && activeRightPanelSurface.target) {
176 floatDeviceSurface(
177 activeThreadRef,
178 { kind: "device", ...activeRightPanelSurface.target },
179 deviceStateLoaded ? deviceState : null,
180 );
181 }
182 useRightPanelStore.getState().setMaximized(activeThreadRef, false);
183 useRightPanelStore.getState().close(activeThreadRef);
184 }
185 };
186 const closePreviewPanelStable = useStableCallback(closePreviewPanel);
187 const togglePreviewPanel = () => {
188 if (!activeThreadRef || !browserAvailable) return;
189 if (previewPanelOpen) {
190 closePreviewPanel();
191 return;
192 }
193 if (!canOperatePreview) return;
194 const activeTabId = activePreviewState.activeTabId;
195 if (activeTabId) {
196 useRightPanelStore.getState().openBrowser(activeThreadRef, activeTabId);
197 } else {
198 createBrowserSurface();
199 }
200 };
201 const togglePreviewPanelStable = useStableCallback(togglePreviewPanel);
202 const activateRightPanelSurface = (surface: RightPanelSurface) => {
203 if (!activeThreadRef) return;
204 explicitDiffOpenRef.current = resolveExplicitDiffOpenOnActivate({
205 surfaceKind: surface.kind,
206 diffOpen,
207 activeThreadRef,
208 });
209 useRightPanelStore.getState().activateSurface(activeThreadRef, surface.id);
210 if (surface.kind === "preview" && surface.resourceId) {
211 setActivePreviewTab(activeThreadRef, surface.resourceId);
212 }
213 if (surface.kind === "terminal") {
214 focusTerminal(activeThreadRef, surface.activeTerminalId);
215 }
216 if (surface.kind === "diff" && !diffOpen) {
217 onDiffPanelOpen?.();
218 }
219 };
220 const activateRightPanelSurfaceStable = useStableCallback(activateRightPanelSurface);
221 const toggleRightPanel = () => {
222 if (!activeThreadRef) return;
223 if (rightPanelOpen) {
224 closePreviewPanel();
225 return;
226 }
227 useRightPanelStore.getState().toggleVisibility(activeThreadRef);
228 focusActivePanelTerminal(activeThreadRef);
229 };
230 const toggleRightPanelStable = useStableCallback(toggleRightPanel);
231 const toggleThreadPanel = () => {
232 if (!activeThreadRef) return;
233 const store = useRightPanelStore.getState();
234 if (threadPanelPresentation === "inline") {
235 const open = selectThreadPanelOpen(
236 store.threadPanelVisibilityByThreadKey,
237 activeThreadRef,
238 "inline",
239 );
240 if (!open) requestWorkspaceFocus({ area: "details" });
241 else if (document.activeElement?.closest('[data-workspace-area="details"]'))
242 requestWorkspaceContentFocus();
243 }
244 store.toggleThreadPanel(activeThreadRef, threadPanelPresentation);
245 };
246 const toggleThreadPanelStable = useStableCallback(toggleThreadPanel);
247 const toggleRightPanelMaximized = () => {
248 if (!canMaximizeRightPanel || !activeThreadRef) return;
249 if (!rightPanelMaximized) requestWorkspaceFocus({ area: "panel" });
250 useRightPanelStore.getState().setMaximized(activeThreadRef, !rightPanelMaximized);
251 };
252 const toggleRightPanelMaximizedStable = useStableCallback(toggleRightPanelMaximized);
253 const moveRightPanelSurface = (surfaceId: string, toIndex: number) => {
254 if (activeThreadRef)
255 useRightPanelStore.getState().moveSurface(activeThreadRef, surfaceId, toIndex);
256 };
257 const moveRightPanelSurfaceStable = useStableCallback(moveRightPanelSurface);
258 const copyRightPanelFilePath = (relativePath: string) => {
259 if (typeof window === "undefined" || !navigator.clipboard?.writeText) {
260 toastManager.add(
261 stackedThreadToast({
262 type: "error",
263 title: "Failed to copy path",
264 description: "Clipboard API unavailable.",
265 }),
266 );
267 return;
268 }
269
270 const clipboardPath = formatFilePathForClipboard(
271 relativePath,
272 resolvePathLinkTarget(relativePath, gitCwd ?? activeProjectCwd ?? ""),
273 );
274 void navigator.clipboard.writeText(clipboardPath).then(
275 () => {
276 toastManager.add({
277 type: "success",
278 title: "Path copied",
279 description: clipboardPath,
280 });
281 },
282 (error) => {
283 toastManager.add(
284 stackedThreadToast({
285 type: "error",
286 title: "Failed to copy path",
287 description: error instanceof Error ? error.message : "An error occurred.",
288 }),
289 );
290 },
291 );
292 };
293 const copyRightPanelFilePathStable = useStableCallback(copyRightPanelFilePath);
294 const addPullRequestSurface = () => {
295 if (!supportsPullRequests || activeThreadRef === null || pullRequestPanelTarget === null)
296 return;
297 useRightPanelStore.getState().openPullRequest(activeThreadRef, pullRequestPanelTarget);
298 };
299 const addPullRequestSurfaceStable = useStableCallback(addPullRequestSurface);
300 const onOpenTurnDiff = (runId: RunId, filePath?: string) => {
301 if (!isServerThread || !activeThreadRef) return;
302 const diffOpen =
303 selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, activeThreadRef) === "diff";
304 explicitDiffOpenRef.current = diffOpen ? null : activeThreadRef;
305 useDiffPanelStore.getState().selectTurn(activeThreadRef, runId, filePath);
306 useRightPanelStore.getState().open(activeThreadRef, "diff");
307 onDiffPanelOpen?.();
308 };
309 const onOpenToolDiffStable = useStableCallback((target: ToolCallDiffTarget) => {
310 if (!isServerThread || !activeThreadRef) return;
311 const diffOpen =
312 selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, activeThreadRef) === "diff";
313 explicitDiffOpenRef.current = diffOpen ? null : activeThreadRef;
314 useDiffPanelStore.getState().selectToolCall(activeThreadRef, target);
315 useRightPanelStore.getState().open(activeThreadRef, "diff");
316 onDiffPanelOpen?.();
317 });
318 const onOpenTurnDiffStable = useStableCallback(onOpenTurnDiff);
319 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the preview action bus to toggle the preview panel
320 useEffect(
321 () =>
322 embedded
323 ? undefined
324 : subscribePreviewAction((action) => {
325 if (action === "toggle-panel") togglePreviewPanelStable();
326 }),
327 [embedded, togglePreviewPanelStable],
328 );
329
330 const shortcuts = {
331 "rightPanel.toggle": () => toggleRightPanel(),
332 "rightPanel.toggleMaximized": ({ event }) => {
333 if (!event.repeat) toggleRightPanelMaximized();
334 },
335 "threadPanel.toggle": () => toggleThreadPanel(),
336 "rightPanel.close": ({ event }) => {
337 if (!activeRightPanelSurface) return false;
338 if (!event.repeat) closeRightPanelSurface(activeRightPanelSurface);
339 },
340 "diff.toggle": () => onToggleDiff(),
341 } satisfies ChatShortcutCommands;
342
343 return {
344 shortcuts,
345 activateRightPanelSurfaceStable,
346 addDeviceSurfaceStable,
347 addDiffSurfaceStable,
348 addFilesSurfaceStable,
349 addPullRequestSurfaceStable,
350 addPullRequestsSurfaceStable,
351 closePreviewPanelStable,
352 copyRightPanelFilePathStable,
353 createBrowserSurface,
354 createBrowserSurfaceStable,
355 moveRightPanelSurfaceStable,
356 onOpenToolDiffStable,
357 onOpenTurnDiffStable,
358 onToggleDiffStable,
359 openChangesFromThreadPanelStable,
360 openFileSurfaceStable,
361 toggleRightPanelMaximizedStable,
362 toggleRightPanelStable,
363 toggleThreadPanelStable,
364 };
365}