Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

RightPanelTabs.tsx

960 lines34.8 KB

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