Open History to see the last commit
1import type { ContextMenuItem, PreviewSessionSnapshot, PullRequestState } from "@t3tools/contracts";
2import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
3import {
4 Bot,
5 FileDiff,
6 Files,
7 GitPullRequest,
8 Globe2,
9 Plus,
10 TerminalSquare,
11 Volume2,
12 VolumeOff,
13} from "lucide-react";
14import {
15 type KeyboardEvent as ReactKeyboardEvent,
16 type MouseEvent as ReactMouseEvent,
17 type ReactElement,
18 type ReactNode,
19 useCallback,
20 useEffect,
21 useRef,
22 useState,
23} from "react";
24
25import { isElectron } from "~/env";
26import type { DesktopPreviewOverlay } from "~/previewStateStore";
27import type { RightPanelSurface } from "~/rightPanelStore";
28import { cn } from "~/lib/utils";
29import { readLocalApi } from "~/localApi";
30import { Button } from "~/components/ui/button";
31import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
32import { Kbd } from "~/components/ui/kbd";
33import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "~/components/ui/menu";
34import { ScrollArea } from "~/components/ui/scroll-area";
35import { PanelTabCloseButton } from "~/components/ui/panel-tab-close-button";
36import { faviconUrlForOrigin } from "~/lib/favicon";
37import { useTheme } from "~/hooks/useTheme";
38import type { PreviewPanelInlineSize } from "~/hooks/usePreviewPanelInlineSize";
39import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
40
41import { PreviewPanelShell, type PreviewPanelMode } from "./preview/PreviewPanelShell";
42import { FaviconImage } from "./preview/PreviewFaviconIcon";
43import { previewBridge } from "./preview/previewBridge";
44import { PierreEntryIcon } from "./chat/PierreEntryIcon";
45
46interface RightPanelTabsProps {
47 mode: PreviewPanelMode;
48 maximized?: boolean;
49 /** Forwarded to PreviewPanelShell so this surface persists its own width. */
50 widthStorageKey?: string;
51 /** Forwarded to PreviewPanelShell as the initial width before a user resize. */
52 defaultWidth?: number;
53 inlineSize?: PreviewPanelInlineSize;
54 layoutControls?: ReactNode;
55 surfaces: readonly RightPanelSurface[];
56 activeSurfaceId: string | null;
57 pendingSurfaceIds: ReadonlySet<string>;
58 previewSessions: Readonly<Record<string, PreviewSessionSnapshot>>;
59 desktopByTabId: Readonly<Record<string, DesktopPreviewOverlay>>;
60 /**
61 * Maps a server session tab id to the desktop runtime tab id the Electron
62 * preview manager is keyed by. Session ids are only unique within one server
63 * process, so desktop operations must not be addressed with them.
64 */
65 previewRuntimeTabId?: ((tabId: string) => string) | undefined;
66 terminalLabelsById: ReadonlyMap<string, string>;
67 onActivate: (surface: RightPanelSurface) => void;
68 onCloseSurface: (surface: RightPanelSurface) => void;
69 onCloseOtherSurfaces: (surface: RightPanelSurface) => void;
70 onCloseSurfacesToRight: (surface: RightPanelSurface) => void;
71 onCloseAllSurfaces: () => void;
72 onCopyFilePath: (relativePath: string) => void;
73 onAddBrowser: () => void;
74 onAddTerminal: () => void;
75 onAddDiff: () => void;
76 onAddFiles: () => void;
77 onAddPullRequest: () => void;
78 onAddAgents: () => void;
79 browserAvailable: boolean;
80 terminalAvailable: boolean;
81 diffAvailable: boolean;
82 filesAvailable: boolean;
83 pullRequestAvailable: boolean;
84 agentsAvailable: boolean;
85 pullRequestStatuses?: Readonly<Record<string, PullRequestTabStatus>>;
86 /** Running + waiting subagents; badges the Agents card in the empty state. */
87 liveAgentCount: number;
88 children: ReactNode;
89}
90
91export interface PullRequestTabStatus {
92 projectId: string;
93 repository: string;
94 number: number;
95 state: PullRequestState;
96 isDraft: boolean;
97}
98
99const SURFACE_DISABLED_REASONS = {
100 browser: "Browser previews are only available in the T3 Code desktop app.",
101 terminal: "Terminal surfaces are only available from a project thread.",
102 files: "Files are only available when a project is open.",
103 diff: "Diff is only available for server threads in Git repositories.",
104 pullRequest: "This thread's branch has no pull request yet.",
105 agents: "Agents are only available from a thread.",
106} as const;
107
108/** Overlays that must win over the launcher's letter shortcuts. */
109const LAUNCHER_SHORTCUT_BLOCKING_LAYERS = [
110 '[data-slot="dialog-popup"]',
111 '[data-slot="alert-dialog-popup"]',
112 '[data-slot="command-dialog-popup"]',
113 '[data-slot="menu-popup"]',
114 '[data-slot="select-popup"]',
115 '[data-slot="popover-popup"]',
116 '[data-slot="combobox-popup"]',
117 '[data-slot="autocomplete-popup"]',
118].join(",");
119
120/** One-line unavailability hints for the empty-state cards. */
121const SURFACE_UNAVAILABLE_HINTS = {
122 browser: "Only available in the desktop app.",
123 terminal: "Available when a project is open.",
124 files: "Available when a project is open.",
125 diff: "Available for Git repositories.",
126 pullRequest: "No pull request on this branch yet.",
127 agents: "Available from a thread.",
128} as const;
129
130type TabContextMenuAction =
131 | "copy-path"
132 | "toggle-mute"
133 | "close"
134 | "close-others"
135 | "close-to-right"
136 | "close-all";
137
138/**
139 * Desktop preview tab backing a surface, or null for non-preview surfaces, the
140 * "new browser tab" placeholder, and the web build where no desktop tab exists.
141 */
142function previewTabIdOf(
143 surface: RightPanelSurface,
144 sessions: Readonly<Record<string, PreviewSessionSnapshot>>,
145): string | null {
146 if (surface.kind !== "preview" || !surface.resourceId) return null;
147 return sessions[surface.resourceId]?.tabId ?? null;
148}
149
150/**
151 * Label and enabled state for a preview tab's mute menu entry.
152 * Stays disabled until desktop overlay state arrives: a server session id can
153 * resolve while the preview manager's createTab is still in flight, and muting
154 * then fails with a PreviewTabNotFoundError nothing surfaces to the user.
155 */
156export function tabMuteMenuItem(input: {
157 overlay: DesktopPreviewOverlay | null;
158 canResolveRuntimeTabId: boolean;
159}): { label: string; disabled: boolean } {
160 const muted = input.overlay?.audioMuted ?? false;
161 return {
162 label: muted ? "Unmute tab" : "Mute tab",
163 disabled: input.overlay === null || !input.canResolveRuntimeTabId,
164 };
165}
166
167type TabAudioState = "none" | "audible" | "muted";
168
169/**
170 * A muted tab that is not making sound shows nothing: mute is armed silently,
171 * and the indicator only appears once there is audio to speak of.
172 */
173function tabAudioState(overlay: DesktopPreviewOverlay | null): TabAudioState {
174 if (!overlay?.audible) return "none";
175 return overlay.audioMuted ? "muted" : "audible";
176}
177
178type SurfaceShortcutEvent = Pick<
179 KeyboardEvent,
180 "altKey" | "ctrlKey" | "defaultPrevented" | "isComposing" | "key" | "metaKey"
181>;
182
183export function surfaceShortcutActionForKey<
184 const Action extends { available: boolean; shortcut: string },
185>(actions: readonly Action[], event: SurfaceShortcutEvent): Action | null {
186 if (event.defaultPrevented || event.isComposing) return null;
187 if (event.metaKey || event.ctrlKey || event.altKey) return null;
188 return (
189 actions.find(
190 (action) => action.available && action.shortcut.toLowerCase() === event.key.toLowerCase(),
191 ) ?? null
192 );
193}
194
195/**
196 * A focused editable is a typing context whether or not it has text yet: an
197 * empty chat composer at rest is still where the user's next keystrokes are
198 * meant to land, and claiming launcher letters from it would redirect prompts
199 * into whatever surface opens. The `:not` clause lets `closest` see past
200 * non-editable islands (`contenteditable="false"`) to an editable host around
201 * them, matching ComposerPendingUserInputPanel's typing guard.
202 */
203export function surfaceShortcutTargetsTypingContext(
204 target: { closest(selectors: string): unknown } | null,
205): boolean {
206 return (
207 target?.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"])') !=
208 null
209 );
210}
211
212function DisabledReasonTooltip(props: { reason: string; trigger: ReactElement }) {
213 return (
214 <Tooltip>
215 <TooltipTrigger render={props.trigger} />
216 <TooltipPopup side="top">{props.reason}</TooltipPopup>
217 </Tooltip>
218 );
219}
220
221function SurfaceMenuItem(props: {
222 available: boolean;
223 disabledReason?: string;
224 shortcut: string;
225 onClick: () => void;
226 children: ReactNode;
227}) {
228 const item = (
229 <MenuItem
230 className={!props.available ? "data-disabled:pointer-events-auto" : undefined}
231 onClick={props.onClick}
232 disabled={!props.available}
233 aria-keyshortcuts={props.shortcut}
234 >
235 {props.children}
236 <MenuShortcut>{props.shortcut}</MenuShortcut>
237 </MenuItem>
238 );
239 if (props.available || !props.disabledReason) return item;
240 return <DisabledReasonTooltip reason={props.disabledReason} trigger={item} />;
241}
242
243/**
244 * Card launcher shown when the right panel has no surfaces. Keyboard-first
245 * without palette chrome: a surface's letter opens it directly from anywhere
246 * outside a typing context, and arrows plus Enter work while the launcher is
247 * focused. The highlight only appears on hover or arrow use. Unavailable
248 * surfaces stay visible with a one-line reason.
249 */
250function RightPanelEmptyState(props: {
251 onAddBrowser: () => void;
252 onAddTerminal: () => void;
253 onAddDiff: () => void;
254 onAddFiles: () => void;
255 onAddPullRequest: () => void;
256 onAddAgents: () => void;
257 browserAvailable: boolean;
258 terminalAvailable: boolean;
259 diffAvailable: boolean;
260 filesAvailable: boolean;
261 pullRequestAvailable: boolean;
262 agentsAvailable: boolean;
263 liveAgentCount: number;
264}) {
265 // -1 means no highlight: it only appears on hover or arrow use.
266 const [highlight, setHighlight] = useState(-1);
267
268 const actions = [
269 {
270 label: "Browser",
271 description: "Open a local app or URL.",
272 icon: Globe2,
273 shortcut: "B",
274 available: props.browserAvailable,
275 disabledReason: SURFACE_UNAVAILABLE_HINTS.browser,
276 onClick: props.onAddBrowser,
277 badgeCount: 0,
278 },
279 {
280 label: "Terminal",
281 description: "Start a shell in this workspace.",
282 icon: TerminalSquare,
283 shortcut: "T",
284 available: props.terminalAvailable,
285 disabledReason: SURFACE_UNAVAILABLE_HINTS.terminal,
286 onClick: props.onAddTerminal,
287 badgeCount: 0,
288 },
289 {
290 label: "Files",
291 description: "Browse and read workspace files.",
292 icon: Files,
293 shortcut: "F",
294 available: props.filesAvailable,
295 disabledReason: SURFACE_UNAVAILABLE_HINTS.files,
296 onClick: props.onAddFiles,
297 badgeCount: 0,
298 },
299 {
300 label: "Diff",
301 description: "Review changes in this thread.",
302 icon: FileDiff,
303 shortcut: "D",
304 available: props.diffAvailable,
305 disabledReason: SURFACE_UNAVAILABLE_HINTS.diff,
306 onClick: props.onAddDiff,
307 badgeCount: 0,
308 },
309 {
310 label: "Pull request",
311 description: "Open this branch's pull request.",
312 icon: GitPullRequest,
313 shortcut: "P",
314 available: props.pullRequestAvailable,
315 disabledReason: SURFACE_UNAVAILABLE_HINTS.pullRequest,
316 onClick: props.onAddPullRequest,
317 badgeCount: 0,
318 },
319 {
320 label: "Agents",
321 description: "Follow subagents and workflows.",
322 icon: Bot,
323 shortcut: "A",
324 available: props.agentsAvailable,
325 disabledReason: SURFACE_UNAVAILABLE_HINTS.agents,
326 onClick: props.onAddAgents,
327 badgeCount: props.liveAgentCount,
328 },
329 ] as const;
330
331 type SurfaceAction = (typeof actions)[number];
332
333 const availableActions = actions.filter((action) => action.available);
334 const highlightIndex =
335 availableActions.length === 0 ? -1 : Math.min(highlight, availableActions.length - 1);
336
337 // Letter shortcuts work while the launcher is visible, not only while it
338 // is focused; focus moves around too easily (stray clicks) to carry them.
339 // Capture phase so app-level key handlers cannot swallow the event first;
340 // typing contexts and already-handled events are left alone.
341 const shortcutActionsRef = useRef(availableActions);
342 useEffect(() => {
343 shortcutActionsRef.current = availableActions;
344 });
345 useEffect(() => {
346 const handler = (event: KeyboardEvent) => {
347 const action = surfaceShortcutActionForKey(shortcutActionsRef.current, event);
348 if (!action) return;
349 if (document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS)) return;
350 const target = event.target;
351 if (target instanceof Element && surfaceShortcutTargetsTypingContext(target)) return;
352 event.preventDefault();
353 event.stopPropagation();
354 action.onClick();
355 };
356 window.addEventListener("keydown", handler, true);
357 return () => window.removeEventListener("keydown", handler, true);
358 }, []);
359
360 const handleKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
361 if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return;
362 if (availableActions.length === 0) return;
363 if (event.key === "ArrowDown" || event.key === "ArrowRight") {
364 event.preventDefault();
365 setHighlight((highlightIndex + 1) % availableActions.length);
366 return;
367 }
368 if (event.key === "ArrowUp" || event.key === "ArrowLeft") {
369 event.preventDefault();
370 setHighlight(
371 highlightIndex === -1
372 ? availableActions.length - 1
373 : (highlightIndex - 1 + availableActions.length) % availableActions.length,
374 );
375 return;
376 }
377 if (event.key === "Enter") {
378 // A focused card button owns its own activation; only open from the
379 // highlight when the container itself has focus.
380 if (event.target instanceof HTMLElement && event.target.closest("button")) return;
381 const action = availableActions[highlightIndex];
382 if (!action) return;
383 event.preventDefault();
384 action.onClick();
385 }
386 };
387
388 // Stable identity so React only runs this callback ref on mount/unmount;
389 // an inline arrow would re-attach and re-focus on every render.
390 const focusOnMount = useCallback((node: HTMLDivElement | null) => {
391 node?.focus();
392 }, []);
393
394 const isHighlighted = (action: SurfaceAction) =>
395 highlightIndex !== -1 && availableActions[highlightIndex] === action;
396
397 const actionIcon = (action: SurfaceAction, iconClassName = "size-4") => {
398 const Icon = action.icon;
399 return (
400 <span className="relative inline-flex shrink-0">
401 <Icon className={iconClassName} />
402 {action.badgeCount > 0 ? (
403 <span
404 aria-hidden
405 className="absolute -top-1.5 -right-2 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-info px-1 text-[9px] font-semibold tabular-nums text-white"
406 >
407 {action.badgeCount}
408 </span>
409 ) : null}
410 </span>
411 );
412 };
413
414 const cardShellClass =
415 "rounded-lg border border-border/80 bg-card dark:border-transparent dark:shadow-none dark:inset-ring-1 dark:inset-ring-white/5";
416 const highlightedCardClass = "bg-accent/60 dark:inset-ring-white/20";
417
418 return (
419 <div
420 ref={focusOnMount}
421 tabIndex={0}
422 onKeyDown={handleKeyDown}
423 aria-label="Open a surface"
424 data-surface-launcher-keys={availableActions.map((action) => action.shortcut).join("")}
425 className={cn(
426 "flex min-h-0 flex-1 items-center justify-center overflow-y-auto px-6 pt-6 outline-none",
427 // The panel topbar sits above this container; matching bottom padding
428 // keeps the cards centered against the full panel, not the leftover.
429 "pb-[calc(var(--workspace-topbar-height)+--spacing(6))]",
430 )}
431 >
432 <div className="relative w-full max-w-lg">
433 <div className="absolute inset-x-0 bottom-full mb-5 text-center">
434 <h3 className="font-medium text-foreground text-sm">Open a surface</h3>
435 <p className="mt-1 text-muted-foreground text-xs">
436 Choose what to show in the right panel.
437 </p>
438 </div>
439 <div className="grid grid-cols-2 gap-2">
440 {actions.map((action) =>
441 action.available ? (
442 <button
443 key={action.label}
444 type="button"
445 onClick={action.onClick}
446 onMouseEnter={() => setHighlight(availableActions.indexOf(action))}
447 onMouseLeave={() =>
448 setHighlight((current) =>
449 current === availableActions.indexOf(action) ? -1 : current,
450 )
451 }
452 className={cn(
453 "relative flex w-full cursor-pointer flex-col items-start p-4 text-left transition hover:border-border hover:bg-accent/60",
454 cardShellClass,
455 isHighlighted(action) && highlightedCardClass,
456 )}
457 >
458 <Kbd className="absolute top-3 right-3">{action.shortcut}</Kbd>
459 <span className="flex items-center gap-2 pe-8">
460 {actionIcon(action)}
461 <span className="font-medium text-sm">{action.label}</span>
462 </span>
463 <span className="mt-1.5 text-muted-foreground text-xs leading-relaxed">
464 {action.description}
465 </span>
466 </button>
467 ) : (
468 <div
469 key={action.label}
470 className={cn(
471 "relative flex w-full flex-col items-start p-4 opacity-40",
472 cardShellClass,
473 )}
474 >
475 <Kbd className="absolute top-3 right-3">{action.shortcut}</Kbd>
476 <span className="flex items-center gap-2 pe-8">
477 {actionIcon(action)}
478 <span className="font-medium text-sm">{action.label}</span>
479 </span>
480 <span className="mt-1.5 text-muted-foreground text-xs leading-relaxed">
481 {action.disabledReason}
482 </span>
483 </div>
484 ),
485 )}
486 </div>
487 </div>
488 </div>
489 );
490}
491
492function surfaceTitle(
493 surface: RightPanelSurface,
494 sessions: Readonly<Record<string, PreviewSessionSnapshot>>,
495 terminalLabelsById: ReadonlyMap<string, string>,
496): string {
497 switch (surface.kind) {
498 case "diff":
499 return "Diff";
500 case "files":
501 return "Files";
502 case "file":
503 return surface.relativePath.slice(surface.relativePath.lastIndexOf("/") + 1);
504 case "terminal":
505 return (
506 terminalLabelsById.get(surface.activeTerminalId) ??
507 getTerminalLabel(surface.activeTerminalId)
508 );
509 case "pull-request":
510 return `#${surface.number}`;
511 case "agents":
512 return "Agents";
513 case "preview": {
514 const snapshot = surface.resourceId ? sessions[surface.resourceId] : null;
515 if (!snapshot || snapshot.navStatus._tag === "Idle") return "Browser";
516 if (snapshot.navStatus.title.trim().length > 0) return snapshot.navStatus.title;
517 try {
518 return new URL(snapshot.navStatus.url).host || "Browser";
519 } catch {
520 return "Browser";
521 }
522 }
523 }
524}
525
526function PreviewFavicon({ capturedUrl, url }: { capturedUrl: string | null; url: string | null }) {
527 const publicProviderUrl = faviconUrlForOrigin(url, 32);
528 return (
529 <FaviconImage
530 sources={[capturedUrl, publicProviderUrl]}
531 fallback={<Globe2 className="size-3 shrink-0" />}
532 className="size-3 shrink-0 rounded-sm object-contain"
533 />
534 );
535}
536
537function sameOrigin(left: string, right: string): boolean {
538 try {
539 return new URL(left).origin === new URL(right).origin;
540 } catch {
541 return false;
542 }
543}
544
545function SurfaceIcon({
546 surface,
547 sessions,
548 desktopByTabId,
549 theme,
550 pullRequestStatuses,
551}: {
552 surface: RightPanelSurface;
553 sessions: Readonly<Record<string, PreviewSessionSnapshot>>;
554 desktopByTabId: Readonly<Record<string, DesktopPreviewOverlay>>;
555 theme: "light" | "dark";
556 pullRequestStatuses: Readonly<Record<string, PullRequestTabStatus>> | undefined;
557}) {
558 switch (surface.kind) {
559 case "preview": {
560 const snapshot = surface.resourceId ? sessions[surface.resourceId] : null;
561 const url = !snapshot || snapshot.navStatus._tag === "Idle" ? null : snapshot.navStatus.url;
562 const favicon = snapshot ? (desktopByTabId[snapshot.tabId]?.favicon ?? null) : null;
563 const capturedUrl =
564 favicon && url && sameOrigin(favicon.pageUrl, url) ? favicon.dataUrl : null;
565 return <PreviewFavicon capturedUrl={capturedUrl} url={url} />;
566 }
567 case "diff":
568 return <FileDiff className="size-3 shrink-0" />;
569 case "files":
570 return <Files className="size-3 shrink-0" />;
571 case "file":
572 return (
573 <PierreEntryIcon
574 pathValue={surface.relativePath}
575 kind="file"
576 theme={theme}
577 className="size-3"
578 />
579 );
580 case "terminal":
581 return <TerminalSquare className="size-3 shrink-0" />;
582 case "pull-request": {
583 const status = pullRequestStatuses?.[surface.id] ?? null;
584 const toneClassName =
585 status?.state === "merged"
586 ? "text-violet-600 dark:text-violet-300/90"
587 : status?.state === "closed"
588 ? "text-red-600 dark:text-red-300/90"
589 : status?.isDraft
590 ? "text-zinc-500 dark:text-zinc-400/80"
591 : status?.state === "open"
592 ? "text-emerald-600 dark:text-emerald-300/90"
593 : "text-muted-foreground";
594 return <GitPullRequest className={cn("size-3 shrink-0", toneClassName)} />;
595 }
596 case "agents":
597 return <Bot className="size-3 shrink-0" />;
598 }
599}
600
601export function RightPanelTabs(props: RightPanelTabsProps) {
602 const ownsDesktopTitleBar = isElectron && props.mode === "inline";
603 const { resolvedTheme } = useTheme();
604 const tabListRef = useRef<HTMLDivElement>(null);
605 const [addSurfaceMenuOpen, setAddSurfaceMenuOpen] = useState(false);
606
607 const addSurfaceActions = [
608 {
609 label: "Browser",
610 icon: Globe2,
611 shortcut: "B",
612 available: props.browserAvailable,
613 disabledReason: SURFACE_DISABLED_REASONS.browser,
614 onClick: props.onAddBrowser,
615 },
616 {
617 label: "Terminal",
618 icon: TerminalSquare,
619 shortcut: "T",
620 available: props.terminalAvailable,
621 disabledReason: SURFACE_DISABLED_REASONS.terminal,
622 onClick: props.onAddTerminal,
623 },
624 {
625 label: "Files",
626 icon: Files,
627 shortcut: "F",
628 available: props.filesAvailable,
629 disabledReason: SURFACE_DISABLED_REASONS.files,
630 onClick: props.onAddFiles,
631 },
632 {
633 label: "Diff",
634 icon: FileDiff,
635 shortcut: "D",
636 available: props.diffAvailable,
637 disabledReason: SURFACE_DISABLED_REASONS.diff,
638 onClick: props.onAddDiff,
639 },
640 {
641 label: "Pull request",
642 icon: GitPullRequest,
643 shortcut: "P",
644 available: props.pullRequestAvailable,
645 disabledReason: SURFACE_DISABLED_REASONS.pullRequest,
646 onClick: props.onAddPullRequest,
647 },
648 {
649 label: "Agents",
650 icon: Bot,
651 shortcut: "A",
652 available: props.agentsAvailable,
653 disabledReason: SURFACE_DISABLED_REASONS.agents,
654 onClick: props.onAddAgents,
655 },
656 ] as const;
657
658 const handleAddSurfaceMenuKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
659 const action = surfaceShortcutActionForKey(addSurfaceActions, event.nativeEvent);
660 if (!action) return;
661 event.preventDefault();
662 event.stopPropagation();
663 setAddSurfaceMenuOpen(false);
664 action.onClick();
665 };
666
667 const handleTabContextMenu = useCallback(
668 async (event: ReactMouseEvent, surface: RightPanelSurface) => {
669 event.preventDefault();
670 event.stopPropagation();
671
672 const api = readLocalApi();
673 if (!api) return;
674
675 const surfaceIndex = props.surfaces.findIndex((entry) => entry.id === surface.id);
676 if (surfaceIndex < 0) return;
677
678 const items: ContextMenuItem<TabContextMenuAction>[] = [];
679 if (surface.kind === "file") {
680 items.push({ id: "copy-path", label: "Copy path" });
681 }
682 const menuPreviewTabId = previewTabIdOf(surface, props.previewSessions);
683 // Desktop overlay state only arrives once the preview manager has created
684 // the tab. A server session id alone can still be ahead of that, and
685 // muting then fails with PreviewTabNotFoundError that nobody surfaces.
686 const menuOverlay = menuPreviewTabId
687 ? (props.desktopByTabId[menuPreviewTabId] ?? null)
688 : null;
689 const menuMuted = menuOverlay?.audioMuted ?? false;
690 if (surface.kind === "preview") {
691 // Not gated on audibility: silencing a quiet tab ahead of time is the
692 // point, so the item is offered whenever the tab is mutable at all.
693 items.push({
694 id: "toggle-mute",
695 ...tabMuteMenuItem({
696 overlay: menuOverlay,
697 canResolveRuntimeTabId: props.previewRuntimeTabId !== undefined,
698 }),
699 });
700 }
701 items.push(
702 { id: "close", label: "Close" },
703 {
704 id: "close-others",
705 label: "Close others",
706 disabled: props.surfaces.length <= 1,
707 },
708 {
709 id: "close-to-right",
710 label: "Close to the right",
711 disabled: surfaceIndex >= props.surfaces.length - 1,
712 },
713 {
714 id: "close-all",
715 label: "Close all",
716 disabled: props.surfaces.length === 0,
717 },
718 );
719
720 const action = await api.contextMenu.show(items, { x: event.clientX, y: event.clientY });
721 switch (action) {
722 case "copy-path":
723 if (surface.kind === "file") props.onCopyFilePath(surface.relativePath);
724 break;
725 case "toggle-mute": {
726 // menuOverlay repeats the disabled gate above: the desktop tab must
727 // exist before it can be addressed, however the menu was dismissed.
728 const runtimeTabId =
729 menuPreviewTabId && menuOverlay
730 ? (props.previewRuntimeTabId?.(menuPreviewTabId) ?? null)
731 : null;
732 if (runtimeTabId) {
733 void previewBridge?.setAudioMuted(runtimeTabId, !menuMuted).catch(() => undefined);
734 }
735 break;
736 }
737 case "close":
738 props.onCloseSurface(surface);
739 break;
740 case "close-others":
741 props.onCloseOtherSurfaces(surface);
742 break;
743 case "close-to-right":
744 props.onCloseSurfacesToRight(surface);
745 break;
746 case "close-all":
747 props.onCloseAllSurfaces();
748 break;
749 case null:
750 break;
751 }
752 },
753 [props],
754 );
755 const handleTabMouseDown = useCallback((event: ReactMouseEvent) => {
756 if (event.button !== 1) return;
757 event.preventDefault();
758 }, []);
759 const handleTabAuxClick = useCallback(
760 (event: ReactMouseEvent, surface: RightPanelSurface) => {
761 if (event.button !== 1) return;
762 event.preventDefault();
763 event.stopPropagation();
764 props.onCloseSurface(surface);
765 },
766 [props],
767 );
768
769 useEffect(() => {
770 const activeTab = tabListRef.current?.querySelector<HTMLElement>("[data-active-tab='true']");
771 activeTab?.scrollIntoView({ block: "nearest", inline: "nearest" });
772 }, [props.activeSurfaceId]);
773
774 return (
775 <PreviewPanelShell
776 mode={props.mode}
777 {...(props.maximized !== undefined ? { maximized: props.maximized } : {})}
778 {...(props.widthStorageKey !== undefined ? { widthStorageKey: props.widthStorageKey } : {})}
779 {...(props.defaultWidth !== undefined ? { defaultWidth: props.defaultWidth } : {})}
780 {...(props.inlineSize ? { inlineSize: props.inlineSize } : {})}
781 >
782 <div
783 className={cn(
784 "flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center gap-1 pl-2",
785 // The sheet overlays from the viewport top, so its tab bar keeps
786 // the titlebar's height: a compact row re-centers the layout
787 // controls a few pixels higher and the cluster jumps on open.
788 props.mode === "inline" && !props.layoutControls ? "pr-28" : "pr-3",
789 ownsDesktopTitleBar && "wco:pr-[calc(var(--workspace-native-controls-inset)+6rem)]",
790 props.mode === "inline" && props.maximized && COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
791 )}
792 data-right-panel-tabbar
793 >
794 <ScrollArea
795 ref={tabListRef}
796 hideScrollbars
797 scrollFade
798 className={cn("min-w-0 flex-1 rounded-none", ownsDesktopTitleBar && "drag-region")}
799 data-right-panel-tab-list
800 >
801 <div className="flex h-full w-max min-w-full items-center gap-1">
802 {props.surfaces.map((surface) => {
803 const active = surface.id === props.activeSurfaceId;
804 const pending = props.pendingSurfaceIds.has(surface.id);
805 const title = surfaceTitle(surface, props.previewSessions, props.terminalLabelsById);
806 const previewTabId = previewTabIdOf(surface, props.previewSessions);
807 // Desktop state is keyed by the session id, but desktop actions
808 // must be addressed with the runtime id.
809 const audio = tabAudioState(
810 previewTabId ? (props.desktopByTabId[previewTabId] ?? null) : null,
811 );
812 const audioRuntimeTabId = previewTabId
813 ? (props.previewRuntimeTabId?.(previewTabId) ?? null)
814 : null;
815 return (
816 <div
817 key={surface.id}
818 data-active-tab={active}
819 onMouseDown={handleTabMouseDown}
820 onAuxClick={(event) => handleTabAuxClick(event, surface)}
821 onContextMenu={(event) => void handleTabContextMenu(event, surface)}
822 className={cn(
823 "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",
824 active
825 ? "bg-accent text-foreground"
826 : "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
827 )}
828 >
829 <PanelTabCloseButton
830 label={`Close ${title}`}
831 onClick={() => props.onCloseSurface(surface)}
832 >
833 <SurfaceIcon
834 surface={surface}
835 sessions={props.previewSessions}
836 desktopByTabId={props.desktopByTabId}
837 theme={resolvedTheme}
838 pullRequestStatuses={props.pullRequestStatuses}
839 />
840 {pending ? (
841 <span
842 className="absolute -right-0.5 -bottom-0.5 size-1.5 rounded-full bg-current"
843 aria-hidden
844 />
845 ) : null}
846 </PanelTabCloseButton>
847 {audio === "none" || !audioRuntimeTabId ? null : (
848 <Tooltip>
849 <TooltipTrigger
850 render={
851 <button
852 type="button"
853 className="cursor-pointer flex size-4 shrink-0 items-center justify-center rounded-sm hover:bg-muted"
854 aria-label={audio === "muted" ? `Unmute ${title}` : `Mute ${title}`}
855 onClick={(event) => {
856 // Sibling of the close button, inside a tab that
857 // activates on click: keep this to the toggle.
858 event.stopPropagation();
859 void previewBridge
860 ?.setAudioMuted(audioRuntimeTabId, audio !== "muted")
861 .catch(() => undefined);
862 }}
863 >
864 {audio === "muted" ? (
865 <VolumeOff className="size-3" />
866 ) : (
867 <Volume2 className="size-3" />
868 )}
869 </button>
870 }
871 />
872 <TooltipPopup>{audio === "muted" ? "Unmute tab" : "Mute tab"}</TooltipPopup>
873 </Tooltip>
874 )}
875 <Tooltip>
876 <TooltipTrigger
877 render={
878 <button
879 type="button"
880 className="cursor-pointer flex min-w-0 items-center"
881 onClick={() => props.onActivate(surface)}
882 >
883 <span className="truncate">{title}</span>
884 </button>
885 }
886 />
887 <TooltipPopup>{title}</TooltipPopup>
888 </Tooltip>
889 </div>
890 );
891 })}
892 {props.surfaces.length > 0 ? (
893 <Menu open={addSurfaceMenuOpen} onOpenChange={setAddSurfaceMenuOpen}>
894 <MenuTrigger
895 render={
896 <Button
897 aria-label="Add panel surface"
898 className="size-6 shrink-0 text-muted-foreground hover:text-foreground"
899 size="icon-xs"
900 variant="ghost"
901 />
902 }
903 >
904 <Plus className="size-3.5" />
905 </MenuTrigger>
906 <MenuPopup
907 align="start"
908 side="bottom"
909 sideOffset={6}
910 className="min-w-44"
911 onKeyDownCapture={handleAddSurfaceMenuKeyDown}
912 >
913 {addSurfaceActions.map((action) => {
914 const Icon = action.icon;
915 return (
916 <SurfaceMenuItem
917 key={action.label}
918 available={action.available}
919 disabledReason={action.disabledReason}
920 shortcut={action.shortcut}
921 onClick={action.onClick}
922 >
923 <Icon />
924 {action.label}
925 </SurfaceMenuItem>
926 );
927 })}
928 </MenuPopup>
929 </Menu>
930 ) : null}
931 </div>
932 </ScrollArea>
933 {props.layoutControls}
934 </div>
935 <div className="flex min-h-0 flex-1 flex-col" data-right-panel-surface-content>
936 {props.activeSurfaceId === null ? (
937 <RightPanelEmptyState
938 onAddBrowser={props.onAddBrowser}
939 onAddTerminal={props.onAddTerminal}
940 onAddDiff={props.onAddDiff}
941 onAddFiles={props.onAddFiles}
942 onAddPullRequest={props.onAddPullRequest}
943 onAddAgents={props.onAddAgents}
944 browserAvailable={props.browserAvailable}
945 terminalAvailable={props.terminalAvailable}
946 diffAvailable={props.diffAvailable}
947 filesAvailable={props.filesAvailable}
948 pullRequestAvailable={props.pullRequestAvailable}
949 agentsAvailable={props.agentsAvailable}
950 liveAgentCount={props.liveAgentCount}
951 />
952 ) : (
953 props.children
954 )}
955 </div>
956 </PreviewPanelShell>
957 );
958}