@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 1,727 lines 61.9 KB
Raw
1 import { msg, T, useGT, useMessages } from "gt-react";
2 import { m, type MessageResolver } from "../i18n/messages";
3 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
4 import { scopeThreadRef } from "@t3tools/client-runtime/environment";
5 import {
6 threadRuntimeIsActive,
7 type EnvironmentThreadShell,
8 } from "@t3tools/client-runtime/state/shell";
9 import {
10 useProjects,
11 useQuietThreadShell,
12 useServerConfigs,
13 useThreadShells,
14 } from "~/state/entities";
15 import {
16 threadPullRequestKeysEqual,
17 visibleThreadPullRequests,
18 } from "@t3tools/client-runtime/thread-pull-requests";
19 import type {
20 ContextMenuItem,
21 EnvironmentId,
22 IssueTrackerKind,
23 PreviewSessionSnapshot,
24 ProjectId,
25 PullRequestState,
26 ResolvedKeybindingsConfig,
27 ThreadId,
28 } from "@t3tools/contracts";
29 import { getTerminalLabel } from "@t3tools/shared/terminalLabelsCopy";
30 import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display";
31 import {
32 closestCenter,
33 DndContext,
34 type DragEndEvent,
35 PointerSensor,
36 useSensor,
37 useSensors,
38 } from "@dnd-kit/core";
39 import { restrictToFirstScrollableAncestor, restrictToHorizontalAxis } from "@dnd-kit/modifiers";
40 import { horizontalListSortingStrategy, SortableContext, useSortable } from "@dnd-kit/sortable";
41 import { CSS } from "@dnd-kit/utilities";
42 import {
43 Bot,
44 CircleDotIcon,
45 Smartphone,
46 ChevronDown,
47 ChevronLeft,
48 ChevronRight,
49 FileDiff,
50 Files,
51 Globe2,
52 MessagesSquare,
53 Plus,
54 TerminalSquare,
55 Volume2Icon,
56 VolumeOffIcon,
57 } from "lucide-react";
58 import {
59 type KeyboardEvent as ReactKeyboardEvent,
60 type MouseEvent as ReactMouseEvent,
61 type ReactElement,
62 type ReactNode,
63 useEffect,
64 useEffectEvent,
65 useRef,
66 useState,
67 } from "react";
68
69 import { isElectron } from "~/env";
70 import type { DesktopPreviewOverlay } from "~/previewStateStore";
71 import { linkedThreadTitle } from "~/linkedThreadSurface";
72 import type { RightPanelSurface } from "~/rightPanelStore";
73 import { cn } from "~/lib/utils";
74 import { issueStatePresentation } from "~/components/issue/issuePresentation";
75 import { issueEnvironment } from "~/state/issues";
76 import { resolveShortcutCommand, type ShortcutMatchContext } from "~/keybindings";
77 import { readLocalApi } from "~/localApi";
78 import { useStableCallback } from "~/hooks/useStableCallback";
79 import { Button } from "~/components/ui/button";
80 import { AndroidIcon, AppleIcon } from "~/components/Icons";
81 import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
82 import { Kbd } from "~/components/ui/kbd";
83 import {
84 Menu,
85 MenuItem,
86 MenuPopup,
87 MenuShortcut,
88 MenuSub,
89 MenuSubPopup,
90 MenuSubTrigger,
91 MenuTrigger,
92 } from "~/components/ui/menu";
93 import { useBrowserDefaults } from "~/browser/browserDefaults";
94 import { ScrollArea } from "~/components/ui/scroll-area";
95 import { PanelTabCloseButton } from "~/components/ui/panel-tab-close-button";
96 import { faviconUrlForOrigin } from "@t3tools/shared/favicon";
97 import { useTheme } from "~/hooks/useTheme";
98 import { useDeviceState } from "~/state/device";
99 import type { PreviewPanelInlineSize } from "~/hooks/usePreviewPanelInlineSize";
100 import {
101 newestPullRequestSummary,
102 pullRequestEnvironment,
103 useSharedPullRequestSummary,
104 } from "~/state/pullRequests";
105 import { useEnvironmentQuery } from "~/state/query";
106 import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
107
108 import { PreviewPanelShell, type PreviewPanelMode } from "./preview/PreviewPanelShell";
109 import { FaviconImage } from "./preview/PreviewFaviconIcon";
110 import { previewBridge } from "./preview/previewBridge";
111 import { dispatchPreviewAction } from "./preview/previewActionBus";
112 import { preventThumbButtonFocus, takeThumbButtonNavigation } from "./preview/thumbButtons";
113 import { PierreEntryIcon } from "./chat/PierreEntryIcon";
114 import { resolvePullRequestState } from "./pullRequest/pullRequestPresentation";
115 import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons";
116 import { observeResize } from "~/lib/observeResize";
117 import { surfaceShortcutKey } from "~/lib/surfaceShortcutKey";
118
119 export interface RightPanelTabsProps {
120 mode: PreviewPanelMode;
121 maximized?: boolean;
122 open?: boolean;
123 keybindings: ResolvedKeybindingsConfig;
124 getShortcutContext: () => ShortcutMatchContext;
125 widthStorageKey?: string;
126 defaultWidth?: number;
127 inlineSize?: PreviewPanelInlineSize;
128 layoutControls?: ReactNode;
129 surfaces: readonly RightPanelSurface[];
130 environmentId: EnvironmentId | null;
131 activeSurfaceId: string | null;
132 pendingSurfaceIds: ReadonlySet<string>;
133 previewSessions: Readonly<Record<string, PreviewSessionSnapshot>>;
134 desktopByTabId: Readonly<Record<string, DesktopPreviewOverlay>>;
135 /** Maps server-local session ids to desktop runtime ids; session ids cannot address desktop operations. */
136 previewRuntimeTabId?: ((tabId: string) => string) | undefined;
137 terminalLabelsById: ReadonlyMap<string, string>;
138 onActivate: (surface: RightPanelSurface) => void;
139 onRenameDevice?: (surfaceId: string, title: string) => void;
140 onCloseSurface: (surface: RightPanelSurface) => void;
141 /** Moves a subagent, side chat or linked thread tab to the main screen. */
142 onOpenInMainView?: (
143 surface: Extract<RightPanelSurface, { kind: "thread" | "linked-thread" }>,
144 ) => void;
145 onCloseOtherSurfaces: (surface: RightPanelSurface) => void;
146 onCloseSurfacesToRight: (surface: RightPanelSurface) => void;
147 onCloseAllSurfaces: () => void;
148 onMoveSurface?: (surfaceId: string, toIndex: number) => void;
149 onCopyFilePath: (relativePath: string) => void;
150 onAddBrowser: () => void;
151 /** Keep separate from the DOM click handler so a MouseEvent cannot become a profile id. */
152 onAddBrowserInProfile: (profileId: string) => void;
153 onAddTerminal: () => void;
154 onAddDiff: () => void;
155 onAddFiles: () => void;
156 onAddPullRequest: () => void;
157 onAddPullRequests: () => void;
158 onAddDevice: () => void;
159 /** Absent where side chats are not offered. */
160 onAddSideChat?: (() => void) | undefined;
161 browserAvailable: boolean;
162 terminalAvailable: boolean;
163 diffAvailable: boolean;
164 filesAvailable: boolean;
165 pullRequestAvailable: boolean;
166 pullRequestsAvailable: boolean;
167 deviceAvailable: boolean;
168 sideChatAvailable?: boolean;
169 /** Overrides the default reason while side chats are available but cannot start. */
170 sideChatDisabledReason?: string | null;
171 pullRequestStatusSeeds?: Readonly<Record<string, PullRequestTabStatusSeed>>;
172 children: ReactNode;
173 }
174
175 export interface PullRequestTabStatus {
176 projectId: string;
177 repository: string;
178 number: number;
179 state: PullRequestState;
180 isDraft: boolean;
181 }
182
183 export type PullRequestTabStatusSeed = Pick<PullRequestTabStatus, "state" | "isDraft">;
184
185 function shouldOpenDefaultBrowserProfileFromMenuClick(pointerType: string | undefined): boolean {
186 return pointerType !== "touch";
187 }
188
189 const SURFACE_DISABLED_REASONS = {
190 browser: msg("Browser previews are only available in the T3 Code desktop app."),
191 terminal: msg("Terminal surfaces are only available from a project thread."),
192 files: msg("Files are only available when a project is open."),
193 diff: msg("Diff is only available for server threads in Git repositories."),
194 pullRequest: msg("This thread's branch has no pull request yet."),
195 pullRequests: msg("This thread has no linked items."),
196 device: msg("Devices are only available from a thread."),
197 sideChat: msg("Side chats start after the first message."),
198 } as const;
199
200 // Closed keepMounted popups must stop blocking shortcuts once their exit transition ends.
201 const LAUNCHER_SHORTCUT_BLOCKING_LAYERS = [
202 "dialog-popup",
203 "alert-dialog-popup",
204 "command-dialog-popup",
205 "menu-popup",
206 "select-popup",
207 "popover-popup",
208 "combobox-popup",
209 "autocomplete-popup",
210 ]
211 .map((slot) => `[data-slot="${slot}"]:is([data-open],[data-ending-style])`)
212 .join(",");
213
214 const SURFACE_UNAVAILABLE_HINTS = {
215 browser: msg("Only available in the desktop app."),
216 terminal: msg("Available when a project is open."),
217 files: msg("Available when a project is open."),
218 diff: msg("Available for Git repositories."),
219 pullRequest: msg("No pull request on this branch yet."),
220 pullRequests: msg("No linked items available."),
221 device: msg("Available from a thread."),
222 sideChat: msg("Available after the first message."),
223 } as const;
224
225 type TabContextMenuAction =
226 | "open-in-main-view"
227 | "rename"
228 | "copy-path"
229 | "toggle-mute"
230 | "close"
231 | "close-others"
232 | "close-to-right"
233 | "close-all";
234
235 const TAB_SCROLL_EDGE_TOLERANCE = 1;
236 const TAB_DRAG_MODIFIERS = [restrictToHorizontalAxis, restrictToFirstScrollableAncestor];
237
238 function tabScrollViewport(root: HTMLDivElement | null): HTMLDivElement | null {
239 return root?.querySelector<HTMLDivElement>('[data-slot="scroll-area-viewport"]') ?? null;
240 }
241
242 function previewTabIdOf(
243 surface: RightPanelSurface,
244 sessions: Readonly<Record<string, PreviewSessionSnapshot>>,
245 ): string | null {
246 if (surface.kind !== "preview" || !surface.resourceId) return null;
247 return sessions[surface.resourceId]?.tabId ?? null;
248 }
249
250 /**
251 * Stays disabled until desktop overlay state arrives: a server session id can
252 * resolve while the preview manager's createTab is still in flight, and muting
253 * then fails with a PreviewTabNotFoundError nothing surfaces to the user.
254 */
255 function tabMuteMenuItem(
256 input: {
257 overlay: DesktopPreviewOverlay | null;
258 canResolveRuntimeTabId: boolean;
259 },
260 resolve: MessageResolver = m,
261 ): { label: string; disabled: boolean } {
262 const muted = input.overlay?.audioMuted ?? false;
263 return {
264 label: muted ? resolve(msg("Unmute tab")) : resolve(msg("Mute tab")),
265 disabled: input.overlay === null || !input.canResolveRuntimeTabId,
266 };
267 }
268
269 type TabAudioState = "none" | "audible" | "muted";
270
271 function tabAudioState(overlay: DesktopPreviewOverlay | null): TabAudioState {
272 if (!overlay?.audible) return "none";
273 return overlay.audioMuted ? "muted" : "audible";
274 }
275
276 type SurfaceShortcutEvent = Pick<
277 KeyboardEvent,
278 "altKey" | "ctrlKey" | "defaultPrevented" | "isComposing" | "key" | "metaKey"
279 > &
280 Partial<Pick<KeyboardEvent, "code" | "getModifierState">>;
281
282 export function surfaceShortcutActionForKey<
283 const Action extends { available: boolean; shortcut: string },
284 >(actions: readonly Action[], event: SurfaceShortcutEvent): Action | null {
285 if (event.defaultPrevented || event.isComposing) return null;
286 if (event.metaKey || event.ctrlKey || event.altKey) return null;
287 const key = surfaceShortcutKey(event);
288 return (
289 actions.find((action) => action.available && action.shortcut.toLowerCase() === key) ?? null
290 );
291 }
292
293 /** Skip contenteditable=false islands to find their editable host, matching the composer typing guard. */
294 export function surfaceShortcutTargetsTypingContext(
295 target: { closest(selectors: string): unknown } | null,
296 ): boolean {
297 return (
298 target?.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"])') !=
299 null
300 );
301 }
302
303 function DisabledReasonTooltip(props: { reason: string; trigger: ReactElement }) {
304 return (
305 <Tooltip>
306 <TooltipTrigger render={props.trigger} />
307 <TooltipPopup side="top">{props.reason}</TooltipPopup>
308 </Tooltip>
309 );
310 }
311
312 function SurfaceMenuItem(props: {
313 available: boolean;
314 disabledReason?: string;
315 shortcut: string;
316 onClick: () => void;
317 children: ReactNode;
318 }) {
319 const item = (
320 <MenuItem
321 className={!props.available ? "data-disabled:pointer-events-auto" : undefined}
322 onClick={props.onClick}
323 disabled={!props.available}
324 aria-keyshortcuts={props.shortcut}
325 >
326 {props.children}
327 <MenuShortcut>{props.shortcut}</MenuShortcut>
328 </MenuItem>
329 );
330 if (props.available || !props.disabledReason) return item;
331 return <DisabledReasonTooltip reason={props.disabledReason} trigger={item} />;
332 }
333
334 function RightPanelEmptyState(props: {
335 onAddBrowser: () => void;
336 onAddBrowserInProfile: (profileId: string) => void;
337 browserProfiles: ReadonlyArray<{ readonly id: string; readonly name: string }>;
338 onAddTerminal: () => void;
339 onAddDiff: () => void;
340 onAddFiles: () => void;
341 onAddPullRequest: () => void;
342 onAddPullRequests: () => void;
343 onAddDevice: () => void;
344 /** Absent where side chats are not offered. */
345 onAddSideChat?: (() => void) | undefined;
346 browserAvailable: boolean;
347 terminalAvailable: boolean;
348 diffAvailable: boolean;
349 filesAvailable: boolean;
350 pullRequestAvailable: boolean;
351 pullRequestsAvailable: boolean;
352 deviceAvailable: boolean;
353 sideChatAvailable: boolean;
354 sideChatDisabledReason: string | null;
355 }) {
356 const gt = useGT();
357 const messages = useMessages();
358 const [highlight, setHighlight] = useState(-1);
359
360 const actions = [
361 {
362 label: msg("Browser"),
363 icon: Globe2,
364 shortcut: "B",
365 available: props.browserAvailable,
366 disabledReason: messages(SURFACE_UNAVAILABLE_HINTS.browser),
367 onClick: props.onAddBrowser,
368 },
369 {
370 label: msg("Terminal"),
371 icon: TerminalSquare,
372 shortcut: "T",
373 available: props.terminalAvailable,
374 disabledReason: messages(SURFACE_UNAVAILABLE_HINTS.terminal),
375 onClick: props.onAddTerminal,
376 },
377 {
378 label: msg("Files"),
379 icon: Files,
380 shortcut: "F",
381 available: props.filesAvailable,
382 disabledReason: messages(SURFACE_UNAVAILABLE_HINTS.files),
383 onClick: props.onAddFiles,
384 },
385 {
386 label: msg("Diff"),
387 icon: FileDiff,
388 shortcut: "D",
389 available: props.diffAvailable,
390 disabledReason: messages(SURFACE_UNAVAILABLE_HINTS.diff),
391 onClick: props.onAddDiff,
392 },
393 {
394 label: msg("Pull request"),
395 icon: PullRequestGlyph.pullRequest,
396 shortcut: "P",
397 available: props.pullRequestAvailable,
398 disabledReason: messages(SURFACE_UNAVAILABLE_HINTS.pullRequest),
399 onClick: props.onAddPullRequest,
400 },
401 {
402 label: msg("Linked items"),
403 icon: PullRequestGlyph.link,
404 shortcut: "L",
405 available: props.pullRequestsAvailable,
406 disabledReason: messages(SURFACE_UNAVAILABLE_HINTS.pullRequests),
407 onClick: props.onAddPullRequests,
408 },
409 {
410 label: msg("Device"),
411 description: msg("Watch an iOS Simulator or Android Emulator."),
412 icon: Smartphone,
413 shortcut: "M",
414 available: props.deviceAvailable,
415 disabledReason: messages(SURFACE_UNAVAILABLE_HINTS.device),
416 onClick: props.onAddDevice,
417 },
418 ...(props.onAddSideChat
419 ? [
420 {
421 label: msg("Side chat"),
422 description: msg("Ask a side question while this thread keeps working."),
423 icon: MessagesSquare,
424 shortcut: "S",
425 available: props.sideChatAvailable && !props.sideChatDisabledReason,
426 disabledReason:
427 props.sideChatDisabledReason ?? messages(SURFACE_UNAVAILABLE_HINTS.sideChat),
428 onClick: props.onAddSideChat,
429 },
430 ]
431 : []),
432 ] as const;
433
434 type SurfaceAction = (typeof actions)[number];
435
436 const availableActions = actions.filter((action) => action.available);
437 const highlightIndex =
438 availableActions.length === 0 ? -1 : Math.min(highlight, availableActions.length - 1);
439
440 const handleShortcut = useEffectEvent((event: KeyboardEvent) => {
441 const action = surfaceShortcutActionForKey(availableActions, event);
442 if (!action) return;
443 if (document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS)) return;
444 const target = event.composedPath()[0] ?? event.target;
445 if (target instanceof Element && surfaceShortcutTargetsTypingContext(target)) return;
446 event.preventDefault();
447 event.stopPropagation();
448 action.onClick();
449 });
450 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes a capture-phase window keydown listener for surface shortcuts while the menu is mounted
451 useEffect(() => {
452 const handler = (event: KeyboardEvent) => handleShortcut(event);
453 window.addEventListener("keydown", handler, true);
454 return () => window.removeEventListener("keydown", handler, true);
455 }, []);
456
457 const handleKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
458 if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return;
459 if (availableActions.length === 0) return;
460 if (event.key === "ArrowDown" || event.key === "ArrowRight") {
461 event.preventDefault();
462 setHighlight((highlightIndex + 1) % availableActions.length);
463 return;
464 }
465 if (event.key === "ArrowUp" || event.key === "ArrowLeft") {
466 event.preventDefault();
467 setHighlight(
468 highlightIndex === -1
469 ? availableActions.length - 1
470 : (highlightIndex - 1 + availableActions.length) % availableActions.length,
471 );
472 return;
473 }
474 if (event.key === "Enter") {
475 if (event.target !== event.currentTarget) return;
476 const action = availableActions[highlightIndex];
477 if (!action) return;
478 event.preventDefault();
479 action.onClick();
480 }
481 };
482
483 const isHighlighted = (action: SurfaceAction) =>
484 highlightIndex !== -1 && availableActions[highlightIndex] === action;
485
486 const actionIcon = (action: SurfaceAction, iconClassName = "size-4") => {
487 const Icon = action.icon;
488 return (
489 <span className="relative inline-flex shrink-0">
490 <Icon className={iconClassName} />
491 </span>
492 );
493 };
494
495 return (
496 <div
497 data-workspace-focus-default
498 tabIndex={0}
499 onKeyDown={handleKeyDown}
500 aria-label={gt("Open a surface")}
501 data-surface-launcher-keys={availableActions.map((action) => action.shortcut).join("")}
502 className={cn(
503 "scrollbar-gutter-both flex min-h-0 flex-1 items-center justify-center overflow-y-auto px-6 outline-none",
504 "pb-(--workspace-topbar-height)",
505 )}
506 >
507 <div className="w-full max-w-xs py-6">
508 <h3 className="mb-3 text-center font-medium text-foreground text-sm">
509 <T>Open a surface</T>
510 </h3>
511 <div className="flex flex-col gap-0.5">
512 {actions.map((action) =>
513 action.available ? (
514 <div
515 key={action.label}
516 className="group relative"
517 onMouseEnter={() => setHighlight(availableActions.indexOf(action))}
518 onMouseLeave={() =>
519 setHighlight((current) =>
520 current === availableActions.indexOf(action) ? -1 : current,
521 )
522 }
523 >
524 <button
525 type="button"
526 onClick={action.onClick}
527 className={cn(
528 "flex h-8 w-full cursor-pointer items-center gap-2.5 rounded-(--control-radius) px-2.5 text-left text-sm transition-colors group-hover:bg-accent/60",
529 isHighlighted(action) && "bg-accent/60",
530 )}
531 >
532 {actionIcon(action, "size-4")}
533 <span
534 className={cn(
535 "min-w-0 flex-1 truncate",
536 action.label === "Browser" && props.browserProfiles.length > 1 && "pr-7",
537 )}
538 >
539 {messages(action.label)}
540 </span>
541 <Kbd>{action.shortcut}</Kbd>
542 </button>
543 {action.label === "Browser" && props.browserProfiles.length > 1 ? (
544 <Menu>
545 <MenuTrigger
546 render={
547 <Button
548 aria-label={gt("Open browser in a profile")}
549 className="absolute top-1/2 right-8 -translate-y-1/2"
550 size="icon-xs"
551 variant="ghost-muted"
552 />
553 }
554 >
555 <ChevronDown className="size-3.5" />
556 </MenuTrigger>
557 <MenuPopup align="end" side="bottom" sideOffset={6} className="max-w-56">
558 {props.browserProfiles.map((profile) => (
559 <MenuItem
560 key={profile.id}
561 onClick={() => props.onAddBrowserInProfile(profile.id)}
562 >
563 <span className="min-w-0 truncate">{profile.name}</span>
564 </MenuItem>
565 ))}
566 </MenuPopup>
567 </Menu>
568 ) : null}
569 </div>
570 ) : (
571 <DisabledReasonTooltip
572 key={action.label}
573 reason={action.disabledReason}
574 trigger={
575 <div
576 tabIndex={0}
577 aria-disabled="true"
578 className="flex h-8 w-full cursor-default items-center gap-2.5 rounded-(--control-radius) px-2.5 text-left text-sm opacity-50"
579 >
580 {actionIcon(action, "size-4")}
581 <span className="min-w-0 flex-1 truncate">{messages(action.label)}</span>
582 <Kbd>{action.shortcut}</Kbd>
583 </div>
584 }
585 />
586 ),
587 )}
588 </div>
589 </div>
590 </div>
591 );
592 }
593
594 function surfaceTitle(
595 surface: RightPanelSurface,
596 sessions: Readonly<Record<string, PreviewSessionSnapshot>>,
597 terminalLabelsById: ReadonlyMap<string, string>,
598 resolve: MessageResolver = m,
599 ): string {
600 switch (surface.kind) {
601 case "diff":
602 return resolve(msg("Diff"));
603 case "files":
604 return resolve(msg("Files"));
605 case "file":
606 return surface.relativePath.slice(
607 Math.max(surface.relativePath.lastIndexOf("/"), surface.relativePath.lastIndexOf("\\")) + 1,
608 );
609 case "terminal":
610 return (
611 terminalLabelsById.get(surface.activeTerminalId) ??
612 getTerminalLabel(surface.activeTerminalId, resolve)
613 );
614 case "pull-request":
615 return `#${surface.number}`;
616 case "pull-requests":
617 return resolve(msg("Linked items"));
618 case "issue":
619 // A git host numbers its issues; a tracker with keys of its own, such as Linear, names them.
620 return /^\d+$/.test(surface.key) ? `#${surface.key}` : surface.key;
621 case "device":
622 return surface.title ?? surface.target?.name ?? resolve(msg("Device"));
623 case "thread":
624 // Until the thread's own title loads.
625 return resolve(msg("Thread"));
626 case "linked-thread":
627 return linkedThreadTitle(
628 surface,
629 resolve(msg("Thread on {label}", { label: surface.label })),
630 );
631 case "preview": {
632 const snapshot = surface.resourceId ? sessions[surface.resourceId] : null;
633 if (!snapshot || snapshot.navStatus._tag === "Idle") return resolve(msg("Browser"));
634 if (snapshot.navStatus.title.trim().length > 0) return snapshot.navStatus.title;
635 try {
636 return new URL(snapshot.navStatus.url).host || resolve(msg("Browser"));
637 } catch {
638 return resolve(msg("Browser"));
639 }
640 }
641 }
642 }
643
644 function PreviewFavicon({ capturedUrl, url }: { capturedUrl: string | null; url: string | null }) {
645 const publicProviderUrl = faviconUrlForOrigin(url, 32);
646 return (
647 <FaviconImage
648 sources={[capturedUrl, publicProviderUrl]}
649 fallback={<Globe2 className="size-3 shrink-0" />}
650 className="size-3 shrink-0 rounded-sm object-contain"
651 />
652 );
653 }
654
655 function sameOrigin(left: string, right: string): boolean {
656 try {
657 return new URL(left).origin === new URL(right).origin;
658 } catch {
659 return false;
660 }
661 }
662
663 function previewFaviconOf(
664 surface: RightPanelSurface,
665 sessions: Readonly<Record<string, PreviewSessionSnapshot>>,
666 desktopByTabId: Readonly<Record<string, DesktopPreviewOverlay>>,
667 ): { url: string | null; capturedUrl: string | null } {
668 const snapshot =
669 surface.kind === "preview" && surface.resourceId ? sessions[surface.resourceId] : null;
670 const url = !snapshot || snapshot.navStatus._tag === "Idle" ? null : snapshot.navStatus.url;
671 const favicon = snapshot ? (desktopByTabId[snapshot.tabId]?.favicon ?? null) : null;
672 const capturedUrl = favicon && url && sameOrigin(favicon.pageUrl, url) ? favicon.dataUrl : null;
673 return { url, capturedUrl };
674 }
675
676 function SurfaceIcon({
677 surface,
678 previewUrl,
679 previewCapturedUrl,
680 theme,
681 environmentId,
682 pullRequestStatusSeed,
683 }: {
684 surface: RightPanelSurface;
685 previewUrl: string | null;
686 previewCapturedUrl: string | null;
687 theme: "light" | "dark";
688 environmentId: EnvironmentId | null;
689 pullRequestStatusSeed: PullRequestTabStatusSeed | undefined;
690 }) {
691 switch (surface.kind) {
692 case "preview":
693 return <PreviewFavicon capturedUrl={previewCapturedUrl} url={previewUrl} />;
694 case "diff":
695 return <FileDiff className="size-3 shrink-0" />;
696 case "files":
697 return <Files className="size-3 shrink-0" />;
698 case "file":
699 return (
700 <PierreEntryIcon
701 pathValue={surface.relativePath}
702 kind="file"
703 theme={theme}
704 className="size-3"
705 />
706 );
707 case "terminal":
708 return <TerminalSquare className="size-3 shrink-0" />;
709 case "pull-request":
710 return (
711 <PullRequestSurfaceIcon
712 surface={surface}
713 environmentId={environmentId}
714 seed={pullRequestStatusSeed}
715 />
716 );
717 case "pull-requests":
718 return <PullRequestGlyph.link className="size-3 shrink-0" />;
719 case "issue":
720 return <IssueSurfaceIcon surface={surface} environmentId={environmentId} />;
721 case "thread":
722 return <SideChatTabIcon environmentId={environmentId} threadId={surface.threadId} />;
723 case "linked-thread":
724 return <MessagesSquare className="size-3 shrink-0" />;
725 case "device":
726 return surface.target?.platform === "ios" ? (
727 <AppleIcon className="size-3 shrink-0" />
728 ) : surface.target?.platform === "android" ? (
729 <AndroidIcon className="size-3 shrink-0" />
730 ) : (
731 <Smartphone className="size-3 shrink-0" />
732 );
733 }
734 }
735
736 const SIDE_CHAT_STATE_LABELS = {
737 "needs approval": msg("needs approval"),
738 "needs input": msg("needs input"),
739 running: msg("running", { $context: "side chat status" }),
740 } as const;
741
742 /** What a side chat tab's dot shows and its title's accessible name says. */
743 function sideChatTabState(shell: EnvironmentThreadShell | null) {
744 if (shell === null) return null;
745 if (shell.hasPendingApprovals || shell.pendingSubagentRequest === "approval") {
746 return "needs approval";
747 }
748 if (shell.hasPendingUserInput || shell.pendingSubagentRequest === "user_input") {
749 return "needs input";
750 }
751 return threadRuntimeIsActive(shell.runtime) ? "running" : null;
752 }
753
754 // Static dots: a side chat or subagent tab can stay open for a whole run.
755 function SideChatTabIcon(props: { environmentId: EnvironmentId | null; threadId: ThreadId }) {
756 const shell = useQuietThreadShell(
757 props.environmentId === null ? null : scopeThreadRef(props.environmentId, props.threadId),
758 );
759 const state = sideChatTabState(shell);
760 const Icon = shell !== null && shell.lineage.sideChat !== true ? Bot : MessagesSquare;
761 return (
762 <>
763 <Icon className="size-3 shrink-0" />
764 {state === null ? null : (
765 <span
766 className={cn(
767 "absolute -top-0.5 -right-0.5 size-1.5 rounded-full",
768 state === "running" ? "bg-muted-foreground" : "bg-info",
769 )}
770 aria-hidden
771 />
772 )}
773 </>
774 );
775 }
776
777 export function resolvePullRequestTabLink(
778 threads: readonly Pick<EnvironmentThreadShell, "environmentId" | "pullRequests">[],
779 environmentId: EnvironmentId | null,
780 host: string | null,
781 reference: { repository: string; number: number },
782 ) {
783 if (environmentId === null || host === null) return undefined;
784 // Keys are cached per object, so one target normalizes once instead of once per link.
785 const target = { host, repository: reference.repository, number: reference.number };
786 let newest: EnvironmentThreadShell["pullRequests"][number] | undefined;
787 for (const thread of threads) {
788 if (thread.environmentId !== environmentId) continue;
789 for (const link of visibleThreadPullRequests(thread.pullRequests)) {
790 if (!threadPullRequestKeysEqual(link, target)) continue;
791 if (
792 newest === undefined ||
793 (link.snapshot?.syncedAt ?? "") > (newest.snapshot?.syncedAt ?? "")
794 )
795 newest = link;
796 }
797 }
798 return newest;
799 }
800
801 /** The issue's own state mark, from the detail its panel already reads; a plain dot until then. */
802 function IssueSurfaceIcon({
803 surface,
804 environmentId,
805 }: {
806 surface: Extract<RightPanelSurface, { kind: "issue" }>;
807 environmentId: EnvironmentId | null;
808 }) {
809 const resolvedEnvironmentId =
810 (surface.environmentId as EnvironmentId | undefined) ?? environmentId;
811 const detail = useEnvironmentQuery(
812 resolvedEnvironmentId === null
813 ? null
814 : issueEnvironment.detail({
815 environmentId: resolvedEnvironmentId,
816 input: {
817 projectId: surface.projectId as ProjectId,
818 tracker: surface.tracker as IssueTrackerKind,
819 ...(surface.host ? { host: surface.host } : {}),
820 scope: surface.scope,
821 key: surface.key,
822 },
823 }),
824 ).data;
825 if (detail === null) return <CircleDotIcon className="size-3 shrink-0" />;
826 const presentation = issueStatePresentation(detail.state);
827 return (
828 <presentation.Icon
829 role="img"
830 aria-label={presentation.label}
831 className={cn("size-3 shrink-0", presentation.toneClassName)}
832 />
833 );
834 }
835
836 function PullRequestSurfaceIcon({
837 surface,
838 environmentId,
839 seed,
840 }: {
841 surface: Extract<RightPanelSurface, { kind: "pull-request" }>;
842 environmentId: EnvironmentId | null;
843 seed: PullRequestTabStatusSeed | undefined;
844 }) {
845 const resolvedEnvironmentId =
846 (surface.environmentId as EnvironmentId | undefined) ?? environmentId;
847 const projects = useProjects();
848 const threads = useThreadShells();
849 const project = projects.find(
850 (entry) => entry.environmentId === resolvedEnvironmentId && entry.id === surface.projectId,
851 );
852 const identity = project?.repositoryIdentity;
853 const host =
854 surface.host ??
855 (identity?.provider
856 ? sourceControlClients.changeRequestHost(identity, identity.provider)
857 : null);
858 const configs = useServerConfigs();
859 const capabilities =
860 resolvedEnvironmentId === null
861 ? undefined
862 : configs.get(resolvedEnvironmentId)?.environment.capabilities;
863 const linkedSnapshot =
864 capabilities !== undefined
865 ? (resolvePullRequestTabLink(threads, resolvedEnvironmentId, host, surface)?.snapshot ?? null)
866 : null;
867 const detail = useEnvironmentQuery(
868 resolvedEnvironmentId === null || capabilities === undefined || linkedSnapshot !== null
869 ? null
870 : pullRequestEnvironment.detail({
871 environmentId: resolvedEnvironmentId,
872 input: {
873 projectId: surface.projectId as ProjectId,
874 ...(capabilities !== undefined && surface.host !== undefined
875 ? { host: surface.host }
876 : {}),
877 repository: surface.repository,
878 number: surface.number,
879 allowStale: false,
880 },
881 }),
882 ).data;
883 const reference = {
884 projectId: surface.projectId as ProjectId,
885 repository: surface.repository,
886 number: surface.number,
887 };
888 const sharedSummary = useSharedPullRequestSummary(resolvedEnvironmentId, reference);
889 const status = linkedSnapshot ?? newestPullRequestSummary(detail, sharedSummary) ?? seed ?? null;
890 if (status === null) {
891 return <PullRequestGlyph.pullRequest className="size-3 shrink-0 text-muted-foreground" />;
892 }
893 const presentation = resolvePullRequestState({
894 state: status.state,
895 isDraft: status.isDraft ?? detail?.isDraft ?? seed?.isDraft ?? false,
896 });
897 return <presentation.Icon className={cn("size-3 shrink-0", presentation.toneClassName)} />;
898 }
899
900 function SortableTabList(props: {
901 surfaces: readonly RightPanelSurface[];
902 onMove: ((surfaceId: string, toIndex: number) => void) | undefined;
903 children: ReactNode;
904 }) {
905 const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));
906 const surfaceIds = props.surfaces.map((surface) => surface.id);
907 const { onMove, surfaces } = props;
908 const handleDragEnd = ({ active, over }: DragEndEvent) => {
909 if (!over || active.id === over.id) return;
910 const toIndex = surfaces.findIndex((surface) => surface.id === over.id);
911 if (toIndex >= 0) onMove?.(String(active.id), toIndex);
912 };
913 return (
914 <DndContext
915 sensors={sensors}
916 collisionDetection={closestCenter}
917 modifiers={TAB_DRAG_MODIFIERS}
918 onDragEnd={handleDragEnd}
919 >
920 <SortableContext items={surfaceIds} strategy={horizontalListSortingStrategy}>
921 {props.children}
922 </SortableContext>
923 </DndContext>
924 );
925 }
926
927 interface RightPanelTabHandlers {
928 onActivate: (surface: RightPanelSurface) => void;
929 onClose: (surface: RightPanelSurface) => void;
930 onAuxClick: (event: ReactMouseEvent, surface: RightPanelSurface) => void;
931 onContextMenu: (event: ReactMouseEvent, surface: RightPanelSurface) => void;
932 onStartRename: (surfaceId: string) => void;
933 onFinishRename: (surfaceId: string, title: string) => void;
934 }
935
936 // Chromium on Linux only suppresses primary-selection paste when mouseup is cancelled.
937 function preventTabMiddleButtonDefault(event: ReactMouseEvent) {
938 if (event.button !== 1) return;
939 event.preventDefault();
940 }
941
942 // Stable handlers and per-tab values let the compiler reuse tabs across parent renders.
943 function RightPanelTab(
944 props: RightPanelTabHandlers & {
945 surface: RightPanelSurface;
946 dragDisabled: boolean;
947 active: boolean;
948 pending: boolean;
949 title: string;
950 audio: TabAudioState;
951 audioRuntimeTabId: string | null;
952 previewUrl: string | null;
953 previewCapturedUrl: string | null;
954 theme: "light" | "dark";
955 environmentId: EnvironmentId | null;
956 pullRequestStatusSeed: PullRequestTabStatusSeed | undefined;
957 renaming: boolean;
958 canRename: boolean;
959 ownsDesktopTitleBar: boolean;
960 },
961 ) {
962 const gt = useGT();
963 const messages = useMessages();
964 const {
965 surface,
966 audio,
967 audioRuntimeTabId,
968 onActivate,
969 onClose,
970 onAuxClick,
971 onContextMenu,
972 onStartRename,
973 onFinishRename,
974 } = props;
975 const { listeners, setNodeRef, transform, transition, isDragging } = useSortable({
976 id: surface.id,
977 disabled: props.dragDisabled,
978 });
979 const sideChatShell = useQuietThreadShell(
980 surface.kind === "thread" && props.environmentId !== null
981 ? scopeThreadRef(props.environmentId, surface.threadId)
982 : null,
983 );
984 const title =
985 sideChatShell === null
986 ? props.title
987 : sideChatShell.lineage.sideChat === true
988 ? sideChatShell.title
989 : formatSubagentDisplayTitle(sideChatShell.title);
990 const sideChatState = sideChatTabState(sideChatShell);
991 const content = (
992 <>
993 <PanelTabCloseButton label={gt("Close {title}", { title })} onClick={() => onClose(surface)}>
994 <SurfaceIcon
995 surface={surface}
996 previewUrl={props.previewUrl}
997 previewCapturedUrl={props.previewCapturedUrl}
998 theme={props.theme}
999 environmentId={props.environmentId}
1000 pullRequestStatusSeed={props.pullRequestStatusSeed}
1001 />
1002 {props.pending ? (
1003 <span
1004 className="absolute -right-0.5 -bottom-0.5 size-1.5 rounded-full bg-current"
1005 aria-hidden
1006 />
1007 ) : null}
1008 </PanelTabCloseButton>
1009 {audio === "none" || !audioRuntimeTabId ? null : (
1010 <Tooltip>
1011 <TooltipTrigger
1012 render={
1013 <button
1014 type="button"
1015 className="cursor-pointer flex size-4 shrink-0 items-center justify-center rounded-sm hover:bg-muted"
1016 aria-label={
1017 audio === "muted"
1018 ? gt("Unmute {title}", { title })
1019 : gt("Mute {title}", { title })
1020 }
1021 onClick={(event) => {
1022 event.stopPropagation();
1023 void previewBridge
1024 ?.setAudioMuted(audioRuntimeTabId, audio !== "muted")
1025 .catch(() => undefined);
1026 }}
1027 >
1028 {audio === "muted" ? (
1029 <VolumeOffIcon className="size-3" />
1030 ) : (
1031 <Volume2Icon className="size-3" />
1032 )}
1033 </button>
1034 }
1035 />
1036 <TooltipPopup>{audio === "muted" ? gt("Unmute tab") : gt("Mute tab")}</TooltipPopup>
1037 </Tooltip>
1038 )}
1039 {props.renaming ? (
1040 <input
1041 aria-label={gt("Device tab name")}
1042 className="w-24 min-w-0 rounded-sm bg-background px-1 outline-none ring-1 ring-inset ring-ring"
1043 defaultValue={title}
1044 ref={(element) => {
1045 element?.focus();
1046 element?.select();
1047 }}
1048 onBlur={(event) => onFinishRename(surface.id, event.currentTarget.value)}
1049 onKeyDown={(event) => {
1050 event.stopPropagation();
1051 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
1052 if (event.key === "Enter") event.currentTarget.blur();
1053 if (event.key === "Escape") {
1054 event.currentTarget.value = title;
1055 event.currentTarget.blur();
1056 }
1057 }}
1058 />
1059 ) : (
1060 <Tooltip>
1061 <TooltipTrigger
1062 render={
1063 <button
1064 type="button"
1065 onDoubleClick={() => {
1066 if (surface.kind === "device" && props.canRename) onStartRename(surface.id);
1067 }}
1068 className="cursor-pointer flex min-w-0 items-center"
1069 aria-label={
1070 sideChatState === null
1071 ? undefined
1072 : gt("{title}, {state}", {
1073 title,
1074 state: messages(SIDE_CHAT_STATE_LABELS[sideChatState]),
1075 })
1076 }
1077 onClick={() => onActivate(surface)}
1078 >
1079 <span className="truncate">{title}</span>
1080 </button>
1081 }
1082 />
1083 <TooltipPopup>
1084 {surface.kind === "device" ? (
1085 <DeviceTabTooltip
1086 surface={surface}
1087 environmentId={props.environmentId}
1088 title={title}
1089 />
1090 ) : (
1091 title
1092 )}
1093 </TooltipPopup>
1094 </Tooltip>
1095 )}
1096 </>
1097 );
1098 return (
1099 <div
1100 data-active-tab={props.active}
1101 onMouseDown={preventTabMiddleButtonDefault}
1102 onMouseUp={preventTabMiddleButtonDefault}
1103 onAuxClick={(event) => onAuxClick(event, surface)}
1104 onContextMenu={(event) => onContextMenu(event, surface)}
1105 {...listeners}
1106 ref={setNodeRef}
1107 style={{ transform: CSS.Translate.toString(transform), transition }}
1108 className={cn(
1109 "cursor-pointer group/tab flex h-6 max-w-36 shrink-0 items-center gap-0.5 rounded-md pr-2 pl-1.5 text-xs",
1110 props.ownsDesktopTitleBar && "[-webkit-app-region:no-drag]",
1111 props.active
1112 ? "bg-accent text-foreground"
1113 : "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
1114 isDragging && "relative z-10",
1115 )}
1116 >
1117 {content}
1118 </div>
1119 );
1120 }
1121
1122 export function RightPanelTabs(props: RightPanelTabsProps) {
1123 const gt = useGT();
1124 const messages = useMessages();
1125 const focusedSurface = props.surfaces.find((surface) => surface.id === props.activeSurfaceId);
1126 const ownsDesktopTitleBar = isElectron && props.mode === "inline";
1127 const browserProfiles = useBrowserDefaults().profiles;
1128 const { resolvedTheme } = useTheme();
1129 const tabListRef = useRef<HTMLDivElement>(null);
1130 const addSurfaceTriggerRef = useRef<HTMLButtonElement>(null);
1131 const [renamingDevice, setRenamingDevice] = useState<string | null>(null);
1132 const [addSurfaceMenuOpen, setAddSurfaceMenuOpen] = useState(false);
1133 const [tabScrollState, setTabScrollState] = useState({
1134 hasOverflow: false,
1135 canScrollLeft: false,
1136 canScrollRight: false,
1137 });
1138
1139 if (props.open === false && addSurfaceMenuOpen) setAddSurfaceMenuOpen(false);
1140
1141 const addSurfaceMenuBlocked = () =>
1142 !addSurfaceMenuOpen && document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS) !== null;
1143 const onNewSurfaceKeyDown = useEffectEvent((event: KeyboardEvent) => {
1144 if (event.defaultPrevented || event.isComposing) return;
1145 if (
1146 resolveShortcutCommand(event, props.keybindings, {
1147 context: { ...props.getShortcutContext(), rightPanelOpen: true },
1148 }) !== "rightPanel.new"
1149 )
1150 return;
1151 if (addSurfaceMenuBlocked()) return;
1152 event.preventDefault();
1153 event.stopPropagation();
1154 if (!event.repeat) {
1155 addSurfaceTriggerRef.current?.focus();
1156 setAddSurfaceMenuOpen(true);
1157 }
1158 });
1159 // Forwarded from a focused browser page. Focusing the trigger here would let ChatView's
1160 // window-focus handler see a plain button and refocus the composer, closing the menu.
1161 const onMenuAction = useEffectEvent((action: string) => {
1162 if (action === "rightPanel.new" && !addSurfaceMenuBlocked()) setAddSurfaceMenuOpen(true);
1163 });
1164 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes document keydown and the desktop menu action (forwarded from a focused browser page) for the new surface shortcut while the panel is open
1165 useEffect(() => {
1166 if (props.open === false) return;
1167 document.addEventListener("keydown", onNewSurfaceKeyDown, true);
1168 const unsubscribe = window.desktopBridge?.onMenuAction(onMenuAction);
1169 return () => {
1170 document.removeEventListener("keydown", onNewSurfaceKeyDown, true);
1171 unsubscribe?.();
1172 };
1173 }, [props.open]);
1174
1175 const updateTabScrollState = (viewport: HTMLDivElement) => {
1176 const hasOverflow = viewport.scrollWidth - viewport.clientWidth > TAB_SCROLL_EDGE_TOLERANCE;
1177 const canScrollLeft = hasOverflow && viewport.scrollLeft > TAB_SCROLL_EDGE_TOLERANCE;
1178 const canScrollRight =
1179 hasOverflow &&
1180 viewport.scrollLeft + viewport.clientWidth < viewport.scrollWidth - TAB_SCROLL_EDGE_TOLERANCE;
1181 setTabScrollState((current) => {
1182 if (
1183 current.hasOverflow === hasOverflow &&
1184 current.canScrollLeft === canScrollLeft &&
1185 current.canScrollRight === canScrollRight
1186 ) {
1187 return current;
1188 }
1189 return { hasOverflow, canScrollLeft, canScrollRight };
1190 });
1191 };
1192
1193 const scrollTabs = (direction: -1 | 1) => {
1194 const viewport = tabScrollViewport(tabListRef.current);
1195 if (!viewport) return;
1196 const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
1197 viewport.scrollBy({
1198 left: direction * Math.max(120, viewport.clientWidth * 0.75),
1199 behavior: reduceMotion ? "auto" : "smooth",
1200 });
1201 };
1202
1203 const addSurfaceActions = [
1204 {
1205 label: msg("Browser"),
1206 icon: Globe2,
1207 shortcut: "B",
1208 available: props.browserAvailable,
1209 disabledReason: messages(SURFACE_DISABLED_REASONS.browser),
1210 onClick: props.onAddBrowser,
1211 },
1212 {
1213 label: msg("Terminal"),
1214 icon: TerminalSquare,
1215 shortcut: "T",
1216 available: props.terminalAvailable,
1217 disabledReason: messages(SURFACE_DISABLED_REASONS.terminal),
1218 onClick: props.onAddTerminal,
1219 },
1220 {
1221 label: msg("Files"),
1222 icon: Files,
1223 shortcut: "F",
1224 available: props.filesAvailable,
1225 disabledReason: messages(SURFACE_DISABLED_REASONS.files),
1226 onClick: props.onAddFiles,
1227 },
1228 {
1229 label: msg("Diff"),
1230 icon: FileDiff,
1231 shortcut: "D",
1232 available: props.diffAvailable,
1233 disabledReason: messages(SURFACE_DISABLED_REASONS.diff),
1234 onClick: props.onAddDiff,
1235 },
1236 {
1237 label: msg("Pull request"),
1238 icon: PullRequestGlyph.pullRequest,
1239 shortcut: "P",
1240 available: props.pullRequestAvailable,
1241 disabledReason: messages(SURFACE_DISABLED_REASONS.pullRequest),
1242 onClick: props.onAddPullRequest,
1243 },
1244 {
1245 label: msg("Linked items"),
1246 icon: PullRequestGlyph.link,
1247 shortcut: "L",
1248 available: props.pullRequestsAvailable,
1249 disabledReason: messages(SURFACE_DISABLED_REASONS.pullRequests),
1250 onClick: props.onAddPullRequests,
1251 },
1252 {
1253 label: msg("Device"),
1254 icon: Smartphone,
1255 shortcut: "M",
1256 available: props.deviceAvailable,
1257 disabledReason: messages(SURFACE_DISABLED_REASONS.device),
1258 onClick: props.onAddDevice,
1259 },
1260 ...(props.onAddSideChat
1261 ? [
1262 {
1263 label: msg("Side chat"),
1264 icon: MessagesSquare,
1265 shortcut: "S",
1266 available: props.sideChatAvailable === true && !props.sideChatDisabledReason,
1267 disabledReason:
1268 props.sideChatDisabledReason ?? messages(SURFACE_DISABLED_REASONS.sideChat),
1269 onClick: props.onAddSideChat,
1270 },
1271 ]
1272 : []),
1273 ] as const;
1274
1275 const handleAddSurfaceMenuKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
1276 const action = surfaceShortcutActionForKey(addSurfaceActions, event.nativeEvent);
1277 if (!action) return;
1278 event.preventDefault();
1279 event.stopPropagation();
1280 setAddSurfaceMenuOpen(false);
1281 action.onClick();
1282 };
1283
1284 const handleTabContextMenu = async (event: ReactMouseEvent, surface: RightPanelSurface) => {
1285 event.preventDefault();
1286 event.stopPropagation();
1287
1288 const api = readLocalApi();
1289 if (!api) return;
1290
1291 const surfaceIndex = props.surfaces.findIndex((entry) => entry.id === surface.id);
1292 if (surfaceIndex < 0) return;
1293
1294 const items: ContextMenuItem<TabContextMenuAction>[] = [];
1295 if ((surface.kind === "thread" || surface.kind === "linked-thread") && props.onOpenInMainView) {
1296 items.push({ id: "open-in-main-view", label: gt("Open in main view") });
1297 }
1298 if (surface.kind === "device" && props.onRenameDevice)
1299 items.push({ id: "rename", label: gt("Rename") });
1300 if (surface.kind === "file" && surface.attachment === undefined) {
1301 items.push({ id: "copy-path", label: gt("Copy path") });
1302 }
1303 const menuPreviewTabId = previewTabIdOf(surface, props.previewSessions);
1304 const menuOverlay = menuPreviewTabId ? (props.desktopByTabId[menuPreviewTabId] ?? null) : null;
1305 const menuMuted = menuOverlay?.audioMuted ?? false;
1306 if (surface.kind === "preview") {
1307 items.push({
1308 id: "toggle-mute",
1309 ...tabMuteMenuItem(
1310 {
1311 overlay: menuOverlay,
1312 canResolveRuntimeTabId: props.previewRuntimeTabId !== undefined,
1313 },
1314 messages,
1315 ),
1316 });
1317 }
1318 items.push(
1319 { id: "close", label: gt("Close") },
1320 {
1321 id: "close-others",
1322 label: gt("Close others"),
1323 disabled: props.surfaces.length <= 1,
1324 },
1325 {
1326 id: "close-to-right",
1327 label: gt("Close to the right"),
1328 disabled: surfaceIndex >= props.surfaces.length - 1,
1329 },
1330 {
1331 id: "close-all",
1332 label: gt("Close all"),
1333 disabled: props.surfaces.length === 0,
1334 },
1335 );
1336
1337 const action = await api.contextMenu.show(items, { x: event.clientX, y: event.clientY });
1338 switch (action) {
1339 case "open-in-main-view":
1340 if (surface.kind === "thread" || surface.kind === "linked-thread") {
1341 props.onOpenInMainView?.(surface);
1342 }
1343 break;
1344 case "rename":
1345 setRenamingDevice(surface.id);
1346 break;
1347 case "copy-path":
1348 if (surface.kind === "file" && surface.attachment === undefined) {
1349 props.onCopyFilePath(surface.relativePath);
1350 }
1351 break;
1352 case "toggle-mute": {
1353 const runtimeTabId =
1354 menuPreviewTabId && menuOverlay
1355 ? (props.previewRuntimeTabId?.(menuPreviewTabId) ?? null)
1356 : null;
1357 if (runtimeTabId) {
1358 void previewBridge?.setAudioMuted(runtimeTabId, !menuMuted).catch(() => undefined);
1359 }
1360 break;
1361 }
1362 case "close":
1363 props.onCloseSurface(surface);
1364 break;
1365 case "close-others":
1366 props.onCloseOtherSurfaces(surface);
1367 break;
1368 case "close-to-right":
1369 props.onCloseSurfacesToRight(surface);
1370 break;
1371 case "close-all":
1372 props.onCloseAllSurfaces();
1373 break;
1374 case null:
1375 break;
1376 }
1377 };
1378 const handleTabAuxClick = (event: ReactMouseEvent, surface: RightPanelSurface) => {
1379 if (event.button !== 1) return;
1380 event.preventDefault();
1381 event.stopPropagation();
1382 props.onCloseSurface(surface);
1383 };
1384 const onActivateTab = useStableCallback(props.onActivate);
1385 const onCloseTab = useStableCallback(props.onCloseSurface);
1386 const onTabAuxClick = useStableCallback(handleTabAuxClick);
1387 const onTabContextMenu = useStableCallback(
1388 (event: ReactMouseEvent, surface: RightPanelSurface) => {
1389 void handleTabContextMenu(event, surface);
1390 },
1391 );
1392 const onStartRenameTab = useStableCallback((surfaceId: string) => setRenamingDevice(surfaceId));
1393 const onFinishRenameTab = useStableCallback((surfaceId: string, title: string) => {
1394 props.onRenameDevice?.(surfaceId, title);
1395 setRenamingDevice(null);
1396 });
1397
1398 // A newly active tab, or tabs that start overflowing, can sit outside the scrolled strip.
1399 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the active tab DOM node into view after it changes or the tab strip starts overflowing
1400 useEffect(() => {
1401 if (!props.activeSurfaceId || !tabScrollState.hasOverflow) return;
1402 const activeTab = tabListRef.current?.querySelector<HTMLElement>("[data-active-tab='true']");
1403 activeTab?.scrollIntoView({ block: "nearest", inline: "nearest" });
1404 }, [props.activeSurfaceId, tabScrollState.hasOverflow]);
1405
1406 const attachTabList = (root: HTMLDivElement | null) => {
1407 tabListRef.current = root;
1408 const viewport = tabScrollViewport(root);
1409 if (!viewport) return;
1410
1411 const update = () => updateTabScrollState(viewport);
1412 // Only a vertical mouse wheel is translated. Horizontal input scrolls natively, since
1413 // consuming it keeps Chromium from starting the gesture scroll that swipe navigation tracks.
1414 const handleWheel = (event: WheelEvent) => {
1415 if (event.ctrlKey || Math.abs(event.deltaX) >= Math.abs(event.deltaY)) return;
1416 let delta = event.deltaY;
1417 if (event.deltaMode === WheelEvent.DOM_DELTA_LINE) delta *= 16;
1418 if (event.deltaMode === WheelEvent.DOM_DELTA_PAGE) delta *= viewport.clientWidth;
1419
1420 const previousScrollLeft = viewport.scrollLeft;
1421 viewport.scrollLeft += delta;
1422 if (viewport.scrollLeft === previousScrollLeft) return;
1423 event.preventDefault();
1424 update();
1425 };
1426
1427 const content = viewport.firstElementChild;
1428 const stopObserving = observeResize(content ? [viewport, content] : viewport, update);
1429 viewport.addEventListener("scroll", update, { passive: true });
1430 viewport.addEventListener("wheel", handleWheel, { passive: false });
1431 update();
1432
1433 return () => {
1434 tabListRef.current = null;
1435 stopObserving();
1436 viewport.removeEventListener("scroll", update);
1437 viewport.removeEventListener("wheel", handleWheel);
1438 };
1439 };
1440
1441 return (
1442 <PreviewPanelShell
1443 workspaceArea
1444 workspaceFocusKey={`panel:${props.environmentId}:${props.activeSurfaceId ?? "empty"}`}
1445 workspaceLabel={
1446 focusedSurface
1447 ? gt("Workspace panel: {title}", {
1448 title: surfaceTitle(
1449 focusedSurface,
1450 props.previewSessions,
1451 props.terminalLabelsById,
1452 messages,
1453 ),
1454 })
1455 : gt("Workspace panel")
1456 }
1457 mode={props.mode}
1458 {...(props.maximized !== undefined ? { maximized: props.maximized } : {})}
1459 {...(props.open !== undefined ? { open: props.open } : {})}
1460 {...(props.widthStorageKey !== undefined ? { widthStorageKey: props.widthStorageKey } : {})}
1461 {...(props.defaultWidth !== undefined ? { defaultWidth: props.defaultWidth } : {})}
1462 {...(props.inlineSize ? { inlineSize: props.inlineSize } : {})}
1463 onMouseDown={preventThumbButtonFocus}
1464 onMouseUp={(event) =>
1465 takeThumbButtonNavigation(
1466 event,
1467 focusedSurface?.kind === "preview" ? dispatchPreviewAction : undefined,
1468 )
1469 }
1470 >
1471 <div
1472 className={cn(
1473 "flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center gap-1 pl-2",
1474 props.mode === "inline" && !props.layoutControls ? "pr-28" : "pr-3",
1475 ownsDesktopTitleBar && "drag-region",
1476 ownsDesktopTitleBar && "wco:pr-(--workspace-native-controls-inset)",
1477 props.mode === "inline" && props.maximized && COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
1478 )}
1479 data-right-panel-tabbar
1480 >
1481 <ScrollArea
1482 radius="none"
1483 ref={attachTabList}
1484 hideScrollbars
1485 scrollFade
1486 className={cn(
1487 "min-w-0 flex-1",
1488 ownsDesktopTitleBar && tabScrollState.hasOverflow && "[-webkit-app-region:no-drag]",
1489 )}
1490 data-right-panel-tab-list
1491 >
1492 <div className="flex h-full w-max min-w-full items-center gap-1">
1493 <SortableTabList surfaces={props.surfaces} onMove={props.onMoveSurface}>
1494 {props.surfaces.map((surface) => {
1495 const previewTabId = previewTabIdOf(surface, props.previewSessions);
1496 const favicon = previewFaviconOf(
1497 surface,
1498 props.previewSessions,
1499 props.desktopByTabId,
1500 );
1501 return (
1502 <RightPanelTab
1503 key={surface.id}
1504 surface={surface}
1505 dragDisabled={!props.onMoveSurface || renamingDevice === surface.id}
1506 active={surface.id === props.activeSurfaceId}
1507 pending={props.pendingSurfaceIds.has(surface.id)}
1508 title={surfaceTitle(
1509 surface,
1510 props.previewSessions,
1511 props.terminalLabelsById,
1512 messages,
1513 )}
1514 audio={tabAudioState(
1515 previewTabId ? (props.desktopByTabId[previewTabId] ?? null) : null,
1516 )}
1517 audioRuntimeTabId={
1518 previewTabId ? (props.previewRuntimeTabId?.(previewTabId) ?? null) : null
1519 }
1520 previewUrl={favicon.url}
1521 previewCapturedUrl={favicon.capturedUrl}
1522 theme={resolvedTheme}
1523 environmentId={props.environmentId}
1524 pullRequestStatusSeed={props.pullRequestStatusSeeds?.[surface.id]}
1525 renaming={renamingDevice === surface.id}
1526 canRename={props.onRenameDevice !== undefined}
1527 ownsDesktopTitleBar={ownsDesktopTitleBar}
1528 onActivate={onActivateTab}
1529 onClose={onCloseTab}
1530 onAuxClick={onTabAuxClick}
1531 onContextMenu={onTabContextMenu}
1532 onStartRename={onStartRenameTab}
1533 onFinishRename={onFinishRenameTab}
1534 />
1535 );
1536 })}
1537 </SortableTabList>
1538 {props.open !== false ? (
1539 <Menu open={addSurfaceMenuOpen} onOpenChange={setAddSurfaceMenuOpen}>
1540 <MenuTrigger
1541 ref={addSurfaceTriggerRef}
1542 render={
1543 <Button
1544 aria-label={gt("Add panel surface")}
1545 className="shrink-0"
1546 size="icon-xs"
1547 variant="ghost-muted"
1548 />
1549 }
1550 >
1551 <Plus className="size-3.5" />
1552 </MenuTrigger>
1553 <MenuPopup
1554 align="start"
1555 side="bottom"
1556 sideOffset={6}
1557 onKeyDownCapture={handleAddSurfaceMenuKeyDown}
1558 >
1559 {addSurfaceActions.map((action) => {
1560 const Icon = action.icon;
1561 if (action.label === "Browser" && action.available) {
1562 return (
1563 <MenuSub key={action.label}>
1564 <MenuSubTrigger
1565 className="[&>svg:last-child]:ms-0"
1566 aria-keyshortcuts={action.shortcut}
1567 onClick={(event) => {
1568 const pointerType =
1569 "pointerType" in event.nativeEvent &&
1570 typeof event.nativeEvent.pointerType === "string"
1571 ? event.nativeEvent.pointerType
1572 : undefined;
1573 if (!shouldOpenDefaultBrowserProfileFromMenuClick(pointerType))
1574 return;
1575 setAddSurfaceMenuOpen(false);
1576 action.onClick();
1577 }}
1578 >
1579 <Icon />
1580 {messages(action.label)}
1581 <MenuShortcut>{action.shortcut}</MenuShortcut>
1582 </MenuSubTrigger>
1583 <MenuSubPopup className="max-w-56">
1584 {browserProfiles.map((profile) => (
1585 <MenuItem
1586 key={profile.id}
1587 onClick={() => props.onAddBrowserInProfile(profile.id)}
1588 >
1589 <span className="min-w-0 truncate">{profile.name}</span>
1590 </MenuItem>
1591 ))}
1592 </MenuSubPopup>
1593 </MenuSub>
1594 );
1595 }
1596 return (
1597 <SurfaceMenuItem
1598 key={action.label}
1599 available={action.available}
1600 disabledReason={action.disabledReason}
1601 shortcut={action.shortcut}
1602 onClick={action.onClick}
1603 >
1604 <Icon />
1605 {messages(action.label)}
1606 </SurfaceMenuItem>
1607 );
1608 })}
1609 </MenuPopup>
1610 </Menu>
1611 ) : null}
1612 </div>
1613 </ScrollArea>
1614 {tabScrollState.hasOverflow ? (
1615 <div
1616 className="flex shrink-0 items-center gap-0.5 [-webkit-app-region:no-drag]"
1617 role="group"
1618 aria-label={gt("Scroll panel tabs")}
1619 >
1620 <Tooltip>
1621 <TooltipTrigger
1622 render={
1623 <span className="inline-flex">
1624 <Button
1625 aria-label={gt("Scroll tabs left")}
1626 disabled={!tabScrollState.canScrollLeft}
1627 onClick={() => scrollTabs(-1)}
1628 size="icon-xs"
1629 variant="ghost"
1630 >
1631 <ChevronLeft />
1632 </Button>
1633 </span>
1634 }
1635 />
1636 <TooltipPopup>
1637 <T>Scroll tabs left</T>
1638 </TooltipPopup>
1639 </Tooltip>
1640 <Tooltip>
1641 <TooltipTrigger
1642 render={
1643 <span className="inline-flex">
1644 <Button
1645 aria-label={gt("Scroll tabs right")}
1646 disabled={!tabScrollState.canScrollRight}
1647 onClick={() => scrollTabs(1)}
1648 size="icon-xs"
1649 variant="ghost"
1650 >
1651 <ChevronRight />
1652 </Button>
1653 </span>
1654 }
1655 />
1656 <TooltipPopup>
1657 <T>Scroll tabs right</T>
1658 </TooltipPopup>
1659 </Tooltip>
1660 </div>
1661 ) : null}
1662 {props.layoutControls}
1663 {ownsDesktopTitleBar && !props.layoutControls ? (
1664 <span aria-hidden className="hidden w-24 shrink-0 wco:block" />
1665 ) : null}
1666 {ownsDesktopTitleBar ? (
1667 <span
1668 aria-hidden
1669 className="pointer-events-none fixed top-[var(--workspace-controls-top)] right-[var(--workspace-controls-right)] h-[var(--workspace-topbar-height)] w-28 [-webkit-app-region:no-drag]"
1670 />
1671 ) : null}
1672 </div>
1673 <div className="flex min-h-0 flex-1 flex-col" data-right-panel-surface-content>
1674 {props.activeSurfaceId === null ? (
1675 <RightPanelEmptyState
1676 onAddBrowser={props.onAddBrowser}
1677 onAddBrowserInProfile={props.onAddBrowserInProfile}
1678 browserProfiles={browserProfiles}
1679 onAddTerminal={props.onAddTerminal}
1680 onAddDiff={props.onAddDiff}
1681 onAddFiles={props.onAddFiles}
1682 onAddPullRequest={props.onAddPullRequest}
1683 onAddPullRequests={props.onAddPullRequests}
1684 onAddDevice={props.onAddDevice}
1685 onAddSideChat={props.onAddSideChat}
1686 browserAvailable={props.browserAvailable}
1687 terminalAvailable={props.terminalAvailable}
1688 diffAvailable={props.diffAvailable}
1689 filesAvailable={props.filesAvailable}
1690 pullRequestAvailable={props.pullRequestAvailable}
1691 pullRequestsAvailable={props.pullRequestsAvailable}
1692 deviceAvailable={props.deviceAvailable}
1693 sideChatAvailable={props.sideChatAvailable === true}
1694 sideChatDisabledReason={props.sideChatDisabledReason ?? null}
1695 />
1696 ) : (
1697 props.children
1698 )}
1699 </div>
1700 </PreviewPanelShell>
1701 );
1702 }
1703
1704 function DeviceTabTooltip(props: {
1705 surface: Extract<RightPanelSurface, { kind: "device" }>;
1706 environmentId: EnvironmentId | null;
1707 title: string;
1708 }) {
1709 const gt = useGT();
1710 const target = props.surface.target;
1711 const { state } = useDeviceState(target ? props.environmentId : null);
1712 const device = target
1713 ? state.devices.find((entry) => entry.hostId === target.hostId && entry.id === target.deviceId)
1714 : undefined;
1715 const host = target ? state.hosts.find((entry) => entry.id === target.hostId) : undefined;
1716 return (
1717 <div className="flex flex-col gap-0.5">
1718 <span>{props.title}</span>
1719 {target ? (
1720 <span className="text-muted-foreground">
1721 {host?.label ?? gt("Device host")} ·{" "}
1722 {device?.version ?? (target.platform === "ios" ? "iOS" : "Android")}
1723 </span>
1724 ) : null}
1725 </div>
1726 );
1727 }