The best way to control Claude Code, Codex and more from any computer or phone

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