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 { 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;
87}
88
89export interface PullRequestTabStatus {
90 projectId: string;
91 repository: string;
92 number: number;
93 state: PullRequestState;
94 isDraft: boolean;
95}
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;
146}
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 };
163}
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";
174}
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 );
191}
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 );
208}
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 );
217}
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} />;
239}
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 );
488}
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(
502 Math.max(surface.relativePath.lastIndexOf("/"), surface.relativePath.lastIndexOf("\\")) + 1,
503 );
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 >
781 <div
782 className={cn(
783 "flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center gap-1 pl-2",
784 // The sheet overlays from the viewport top, so its tab bar keeps
785 // the titlebar's height: a compact row re-centers the layout
786 // controls a few pixels higher and the cluster jumps on open.
787 props.mode === "inline" && !props.layoutControls ? "pr-28" : "pr-3",
788 ownsDesktopTitleBar && "wco:pr-[calc(var(--workspace-native-controls-inset)+6rem)]",
789 props.mode === "inline" && props.maximized && COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
790 )}
791 data-right-panel-tabbar
792 >
793 <ScrollArea
794 ref={tabListRef}
795 hideScrollbars
796 scrollFade
797 className={cn("min-w-0 flex-1 rounded-none", ownsDesktopTitleBar && "drag-region")}
798 data-right-panel-tab-list
799 >
800 <div className="flex h-full w-max min-w-full items-center gap-1">
801 {props.surfaces.map((surface) => {
802 const active = surface.id === props.activeSurfaceId;
803 const pending = props.pendingSurfaceIds.has(surface.id);
804 const title = surfaceTitle(surface, props.previewSessions, props.terminalLabelsById);
805 const previewTabId = previewTabIdOf(surface, props.previewSessions);
806 // Desktop state is keyed by the session id, but desktop actions
807 // must be addressed with the runtime id.
808 const audio = tabAudioState(
809 previewTabId ? (props.desktopByTabId[previewTabId] ?? null) : null,
810 );
811 const audioRuntimeTabId = previewTabId
812 ? (props.previewRuntimeTabId?.(previewTabId) ?? null)
813 : null;
814 return (
815 <div
816 key={surface.id}
817 data-active-tab={active}
818 onMouseDown={handleTabMouseDown}
819 onAuxClick={(event) => handleTabAuxClick(event, surface)}
820 onContextMenu={(event) => void handleTabContextMenu(event, surface)}
821 className={cn(
822 "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",
823 active
824 ? "bg-accent text-foreground"
825 : "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
826 )}
827 >
828 <PanelTabCloseButton
829 label={`Close ${title}`}
830 onClick={() => props.onCloseSurface(surface)}
831 >
832 <SurfaceIcon
833 surface={surface}
834 sessions={props.previewSessions}
835 desktopByTabId={props.desktopByTabId}
836 theme={resolvedTheme}
837 pullRequestStatuses={props.pullRequestStatuses}
838 />
839 {pending ? (
840 <span
841 className="absolute -right-0.5 -bottom-0.5 size-1.5 rounded-full bg-current"
842 aria-hidden
843 />
844 ) : null}
845 </PanelTabCloseButton>
846 {audio === "none" || !audioRuntimeTabId ? null : (
847 <Tooltip>
848 <TooltipTrigger
849 render={
850 <button
851 type="button"
852 className="cursor-pointer flex size-4 shrink-0 items-center justify-center rounded-sm hover:bg-muted"
853 aria-label={audio === "muted" ? `Unmute ${title}` : `Mute ${title}`}
854 onClick={(event) => {
855 // Sibling of the close button, inside a tab that
856 // activates on click: keep this to the toggle.
857 event.stopPropagation();
858 void previewBridge
859 ?.setAudioMuted(audioRuntimeTabId, audio !== "muted")
860 .catch(() => undefined);
861 }}
862 >
863 {audio === "muted" ? (
864 <VolumeOff className="size-3" />
865 ) : (
866 <Volume2 className="size-3" />
867 )}
868 </button>
869 }
870 />
871 <TooltipPopup>{audio === "muted" ? "Unmute tab" : "Mute tab"}</TooltipPopup>
872 </Tooltip>
873 )}
874 <Tooltip>
875 <TooltipTrigger
876 render={
877 <button
878 type="button"
879 className="cursor-pointer flex min-w-0 items-center"
880 onClick={() => props.onActivate(surface)}
881 >
882 <span className="truncate">{title}</span>
883 </button>
884 }
885 />
886 <TooltipPopup>{title}</TooltipPopup>
887 </Tooltip>
888 </div>
889 );
890 })}
891 {props.surfaces.length > 0 ? (
892 <Menu open={addSurfaceMenuOpen} onOpenChange={setAddSurfaceMenuOpen}>
893 <MenuTrigger
894 render={
895 <Button
896 aria-label="Add panel surface"
897 className="size-6 shrink-0 text-muted-foreground hover:text-foreground"
898 size="icon-xs"
899 variant="ghost"
900 />
901 }
902 >
903 <Plus className="size-3.5" />
904 </MenuTrigger>
905 <MenuPopup
906 align="start"
907 side="bottom"
908 sideOffset={6}
909 className="min-w-44"
910 onKeyDownCapture={handleAddSurfaceMenuKeyDown}
911 >
912 {addSurfaceActions.map((action) => {
913 const Icon = action.icon;
914 return (
915 <SurfaceMenuItem
916 key={action.label}
917 available={action.available}
918 disabledReason={action.disabledReason}
919 shortcut={action.shortcut}
920 onClick={action.onClick}
921 >
922 <Icon />
923 {action.label}
924 </SurfaceMenuItem>
925 );
926 })}
927 </MenuPopup>
928 </Menu>
929 ) : null}
930 </div>
931 </ScrollArea>
932 {props.layoutControls}
933 </div>
934 <div className="flex min-h-0 flex-1 flex-col" data-right-panel-surface-content>
935 {props.activeSurfaceId === null ? (
936 <RightPanelEmptyState
937 onAddBrowser={props.onAddBrowser}
938 onAddTerminal={props.onAddTerminal}
939 onAddDiff={props.onAddDiff}
940 onAddFiles={props.onAddFiles}
941 onAddPullRequest={props.onAddPullRequest}
942 onAddAgents={props.onAddAgents}
943 browserAvailable={props.browserAvailable}
944 terminalAvailable={props.terminalAvailable}
945 diffAvailable={props.diffAvailable}
946 filesAvailable={props.filesAvailable}
947 pullRequestAvailable={props.pullRequestAvailable}
948 agentsAvailable={props.agentsAvailable}
949 liveAgentCount={props.liveAgentCount}
950 />
951 ) : (
952 props.children
953 )}
954 </div>
955 </PreviewPanelShell>
956 );
957}