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