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

RightPanelTabs.tsx

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