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