Open History to see the last commit
1import { msg } from "gt-react";
2import { errorDisplayMessage, thrownErrorMessage } from "@t3tools/client-runtime/errors";
3import { m } from "~/i18n/messages";
4import type { ToolCallDiffTarget } from "../../diffPanelStore";
5import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
6import type { ThreadPreviewState } from "../../previewStateStore";
7import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions";
8import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
9import { useStableCallback } from "../../hooks/useStableCallback";
10import { type ScopedThreadRef, type RunId } from "@t3tools/contracts";
11import { scopedThreadKey } from "@t3tools/client-runtime/environment";
12import { useEffect } from "react";
13import {
14 isAtomCommandInterrupted,
15 squashAtomCommandFailure,
16} from "@t3tools/client-runtime/state/runtime";
17import { useDiffPanelStore } from "../../diffPanelStore";
18import { type ThreadPanelPresentation } from "../../rightPanelLayout";
19import {
20 selectThreadPanelOpen,
21 type RightPanelSurface,
22 useRightPanelStore,
23} from "../../rightPanelStore";
24import { requestWorkspaceContentFocus, requestWorkspaceFocus } from "../../lib/workspaceFocus";
25import { setActivePreviewTab } from "../../previewStateStore";
26import { isBrowserSettingsReadError } from "../../browser/openFileInPreview";
27import { addBrowserSurface } from "../preview/addBrowserSurface";
28import { focusActivePanelTerminal, focusTerminal } from "../../lib/terminalFocus";
29import { subscribePreviewAction } from "../preview/previewActionBus";
30import { floatDeviceSurface } from "../preview/agentOpenedPreviews";
31import { browserMiniPlayerSource, usePreviewMiniPlayerStore } from "../../previewMiniPlayerStore";
32import type { threadPullRequestPanelTarget } from "../pullRequest/pullRequestDetail.logic";
33import type { useDeviceState } from "../../state/device";
34import { stackedThreadToast, toastManager } from "../ui/toast";
35import { openDeviceSetupDialog } from "./ChatOverlayHosts";
36import { previewEnvironment } from "../../state/preview";
37import { useAtomCommand } from "../../state/use-atom-command";
38import type { ChatShortcutCommands } from "./useChatShortcuts";
39interface RightPanelActionsInput {
40 readonly activeThreadRef: ScopedThreadRef | null;
41 readonly activeProject: EnvironmentProject | null;
42 readonly activeRightPanelSurface: RightPanelSurface | null;
43 readonly activePreviewState: ThreadPreviewState;
44 readonly deviceState: ReturnType<typeof useDeviceState>["state"];
45 readonly deviceStateLoaded: boolean;
46 readonly pullRequestPanelTarget: ReturnType<typeof threadPullRequestPanelTarget> | null;
47 readonly threadPanelPresentation: ThreadPanelPresentation;
48 readonly isServerThread: boolean;
49 /** A side chat pane; the main view already answers preview bus actions. */
50 readonly embedded: boolean;
51 readonly isGitRepo: boolean;
52 readonly browserAvailable: boolean;
53 readonly canOperatePreview: boolean;
54 readonly diffOpen: boolean;
55 readonly previewPanelOpen: boolean;
56 readonly rightPanelOpen: boolean;
57 readonly canMaximizeRightPanel: boolean;
58 readonly rightPanelMaximized: boolean;
59 readonly supportsPullRequests: boolean;
60 readonly pullRequestsSurfaceAvailable: boolean;
61 readonly gitCwd: string | null;
62 readonly activeProjectCwd: string | 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 onDiffPanelOpen,
97 } = input;
98
99 const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false });
100 const onToggleDiff = () => {
101 if (!isServerThread) {
102 return;
103 }
104 if (!diffOpen) {
105 onDiffPanelOpen?.();
106 }
107 if (activeThreadRef) {
108 useRightPanelStore.getState().toggle(activeThreadRef, "diff");
109 }
110 };
111 const onToggleDiffStable = useStableCallback(onToggleDiff);
112 const createBrowserSurface = (profileId?: string) => {
113 if (!activeThreadRef || !canOperatePreview) return;
114 void addBrowserSurface({
115 threadRef: activeThreadRef,
116 openPreview,
117 ...(profileId === undefined ? {} : { profileId }),
118 }).then((result) => {
119 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
120 const error = squashAtomCommandFailure(result);
121 if (isBrowserSettingsReadError(error)) {
122 toastManager.add(
123 stackedThreadToast({
124 type: "error",
125 title: m(msg("Unable to open browser")),
126 description: errorDisplayMessage(error, m) ?? error.message,
127 }),
128 );
129 }
130 });
131 };
132 const createBrowserSurfaceStable = useStableCallback(createBrowserSurface);
133 const addDiffSurface = () => {
134 if (!activeThreadRef || !isServerThread || !isGitRepo) return;
135 useDiffPanelStore.getState().selectGitScope(activeThreadRef, "branch");
136 useRightPanelStore.getState().open(activeThreadRef, "diff");
137 onDiffPanelOpen?.();
138 };
139 const addDiffSurfaceStable = useStableCallback(addDiffSurface);
140 const openChangesFromThreadPanel = () => {
141 addDiffSurface();
142 };
143 const openChangesFromThreadPanelStable = useStableCallback(openChangesFromThreadPanel);
144 const addFilesSurface = () => {
145 if (!activeThreadRef || !activeProject) return;
146 useRightPanelStore.getState().open(activeThreadRef, "files");
147 };
148 const addFilesSurfaceStable = useStableCallback(addFilesSurface);
149 const addPullRequestsSurface = () => {
150 if (!activeThreadRef || !pullRequestsSurfaceAvailable) return;
151 useRightPanelStore.getState().open(activeThreadRef, "pull-requests");
152 };
153 const addPullRequestsSurfaceStable = useStableCallback(addPullRequestsSurface);
154 const addDeviceSurface = () => {
155 if (!activeThreadRef) return;
156 if (!deviceState.onboardingCompleted || deviceState.hostStatus === "disabled") {
157 openDeviceSetupDialog(scopedThreadKey(activeThreadRef));
158 return;
159 }
160 useRightPanelStore.getState().open(activeThreadRef, "device");
161 };
162 const addDeviceSurfaceStable = useStableCallback(addDeviceSurface);
163 const openFileSurface = (relativePath: string) => {
164 if (!activeThreadRef || !activeProject) return;
165 useRightPanelStore.getState().openFile(activeThreadRef, relativePath);
166 };
167 const openFileSurfaceStable = useStableCallback(openFileSurface);
168 const closePreviewPanel = () => {
169 if (activeThreadRef) {
170 if (activeRightPanelSurface?.kind === "preview" && activeRightPanelSurface.resourceId) {
171 usePreviewMiniPlayerStore
172 .getState()
173 .open(activeThreadRef, browserMiniPlayerSource(activeRightPanelSurface.resourceId));
174 } else if (activeRightPanelSurface?.kind === "device" && activeRightPanelSurface.target) {
175 floatDeviceSurface(
176 activeThreadRef,
177 { kind: "device", ...activeRightPanelSurface.target },
178 deviceStateLoaded ? deviceState : null,
179 );
180 }
181 useRightPanelStore.getState().setMaximized(activeThreadRef, false);
182 useRightPanelStore.getState().close(activeThreadRef);
183 }
184 };
185 const closePreviewPanelStable = useStableCallback(closePreviewPanel);
186 const togglePreviewPanel = () => {
187 if (!activeThreadRef || !browserAvailable) return;
188 if (previewPanelOpen) {
189 closePreviewPanel();
190 return;
191 }
192 if (!canOperatePreview) return;
193 const activeTabId = activePreviewState.activeTabId;
194 if (activeTabId) {
195 useRightPanelStore.getState().openBrowser(activeThreadRef, activeTabId);
196 } else {
197 createBrowserSurface();
198 }
199 };
200 const togglePreviewPanelStable = useStableCallback(togglePreviewPanel);
201 const activateRightPanelSurface = (surface: RightPanelSurface) => {
202 if (!activeThreadRef) return;
203 useRightPanelStore.getState().activateSurface(activeThreadRef, surface.id);
204 if (surface.kind === "preview" && surface.resourceId) {
205 setActivePreviewTab(activeThreadRef, surface.resourceId);
206 }
207 if (surface.kind === "terminal") {
208 focusTerminal(activeThreadRef, surface.activeTerminalId);
209 }
210 if (surface.kind === "side-chat") {
211 requestWorkspaceFocus({
212 area: "panel",
213 selector: `[data-side-chat-pane="${CSS.escape(surface.threadId)}"] [data-workspace-area="composer"] [contenteditable="true"]`,
214 });
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: m(msg("Failed to copy path")),
264 description: m(msg("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(undefined, (error) => {
275 toastManager.add(
276 stackedThreadToast({
277 type: "error",
278 title: m(msg("Failed to copy path")),
279 description: thrownErrorMessage(error, m) ?? m(msg("An error occurred.")),
280 }),
281 );
282 });
283 };
284 const copyRightPanelFilePathStable = useStableCallback(copyRightPanelFilePath);
285 const addPullRequestSurface = () => {
286 if (!supportsPullRequests || activeThreadRef === null || pullRequestPanelTarget === null)
287 return;
288 useRightPanelStore.getState().openPullRequest(activeThreadRef, pullRequestPanelTarget);
289 };
290 const addPullRequestSurfaceStable = useStableCallback(addPullRequestSurface);
291 const onOpenTurnDiff = (runId: RunId, filePath?: string) => {
292 if (!isServerThread || !activeThreadRef) return;
293 useDiffPanelStore.getState().selectTurn(activeThreadRef, runId, filePath);
294 useRightPanelStore.getState().open(activeThreadRef, "diff");
295 onDiffPanelOpen?.();
296 };
297 const onOpenToolDiffStable = useStableCallback((target: ToolCallDiffTarget) => {
298 if (!isServerThread || !activeThreadRef) return;
299 useDiffPanelStore.getState().selectToolCall(activeThreadRef, target);
300 useRightPanelStore.getState().open(activeThreadRef, "diff");
301 onDiffPanelOpen?.();
302 });
303 const onOpenTurnDiffStable = useStableCallback(onOpenTurnDiff);
304 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the preview action bus to toggle the preview panel
305 useEffect(
306 () =>
307 embedded
308 ? undefined
309 : subscribePreviewAction((action) => {
310 if (action === "toggle-panel") togglePreviewPanelStable();
311 }),
312 [embedded, togglePreviewPanelStable],
313 );
314
315 const shortcuts = {
316 "rightPanel.toggle": () => toggleRightPanel(),
317 "rightPanel.toggleMaximized": ({ event }) => {
318 if (!event.repeat) toggleRightPanelMaximized();
319 },
320 "threadPanel.toggle": () => toggleThreadPanel(),
321 "rightPanel.close": ({ event }) => {
322 if (!activeRightPanelSurface) return false;
323 if (!event.repeat) closeRightPanelSurface(activeRightPanelSurface);
324 },
325 "diff.toggle": () => onToggleDiff(),
326 } satisfies ChatShortcutCommands;
327
328 return {
329 shortcuts,
330 activateRightPanelSurfaceStable,
331 addDeviceSurfaceStable,
332 addDiffSurfaceStable,
333 addFilesSurfaceStable,
334 addPullRequestSurfaceStable,
335 addPullRequestsSurfaceStable,
336 closePreviewPanelStable,
337 copyRightPanelFilePathStable,
338 createBrowserSurface,
339 createBrowserSurfaceStable,
340 moveRightPanelSurfaceStable,
341 onOpenToolDiffStable,
342 onOpenTurnDiffStable,
343 onToggleDiffStable,
344 openChangesFromThreadPanelStable,
345 openFileSurfaceStable,
346 toggleRightPanelMaximizedStable,
347 toggleRightPanelStable,
348 toggleThreadPanelStable,
349 };
350}