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