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