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

RightPanelTabs.tsx

1,271 lines47.1 KB

1import type {
2 ContextMenuItem,
3 EnvironmentId,
4 PreviewSessionSnapshot,
5 ProjectId,
6 PullRequestState,
7} from "@t3tools/contracts";
8import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
9import {
10 Bot,
11 ChevronDown,
12 ChevronLeft,
13 ChevronRight,
14 FileDiff,
15 Files,
16 GitPullRequest,
17 Globe2,
18 Plus,
19 TerminalSquare,
20 Volume2,
21 VolumeOff,
22} from "lucide-react";
23import {
24 type KeyboardEvent as ReactKeyboardEvent,
25 type MouseEvent as ReactMouseEvent,
26 type ReactElement,
27 type ReactNode,
28 useCallback,
29 useEffect,
30 useRef,
31 useState,
32} from "react";
33​
34import { isElectron } from "~/env";
35import type { DesktopPreviewOverlay } from "~/previewStateStore";
36import type { RightPanelSurface } from "~/rightPanelStore";
37import { cn } from "~/lib/utils";
38import { readLocalApi } from "~/localApi";
39import { Button } from "~/components/ui/button";
40import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
41import { Kbd } from "~/components/ui/kbd";
42import {
43 Menu,
44 MenuItem,
45 MenuPopup,
46 MenuShortcut,
47 MenuSub,
48 MenuSubPopup,
49 MenuSubTrigger,
50 MenuTrigger,
51} from "~/components/ui/menu";
52import { useBrowserDefaults } from "~/browser/browserDefaults";
53import { ScrollArea } from "~/components/ui/scroll-area";
54import { PanelTabCloseButton } from "~/components/ui/panel-tab-close-button";
55import { faviconUrlForOrigin } from "~/lib/favicon";
56import { useTheme } from "~/hooks/useTheme";
57import type { PreviewPanelInlineSize } from "~/hooks/usePreviewPanelInlineSize";
58import { pullRequestEnvironment } from "~/state/pullRequests";
59import { useEnvironmentQuery } from "~/state/query";
60import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
61​
62import { PreviewPanelShell, type PreviewPanelMode } from "./preview/PreviewPanelShell";
63import { FaviconImage } from "./preview/PreviewFaviconIcon";
64import { previewBridge } from "./preview/previewBridge";
65import { PierreEntryIcon } from "./chat/PierreEntryIcon";
66import { resolvePullRequestState } from "./pullRequest/pullRequestPresentation";
67​
68interface RightPanelTabsProps {
69 mode: PreviewPanelMode;
70 maximized?: boolean;
71 open?: boolean;
72 /** Forwarded to PreviewPanelShell so this surface persists its own width. */
73 widthStorageKey?: string;
74 /** Forwarded to PreviewPanelShell as the initial width before a user resize. */
75 defaultWidth?: number;
76 inlineSize?: PreviewPanelInlineSize;
77 layoutControls?: ReactNode;
78 surfaces: readonly RightPanelSurface[];
79 /** Fallback environment for surfaces that do not carry their own. */
80 environmentId: EnvironmentId | null;
81 activeSurfaceId: string | null;
82 pendingSurfaceIds: ReadonlySet<string>;
83 previewSessions: Readonly<Record<string, PreviewSessionSnapshot>>;
84 desktopByTabId: Readonly<Record<string, DesktopPreviewOverlay>>;
85 /**
86 * Maps a server session tab id to the desktop runtime tab id the Electron
87 * preview manager is keyed by. Session ids are only unique within one server
88 * process, so desktop operations must not be addressed with them.
89 */
90 previewRuntimeTabId?: ((tabId: string) => string) | undefined;
91 terminalLabelsById: ReadonlyMap<string, string>;
92 onActivate: (surface: RightPanelSurface) => void;
93 onCloseSurface: (surface: RightPanelSurface) => void;
94 onCloseOtherSurfaces: (surface: RightPanelSurface) => void;
95 onCloseSurfacesToRight: (surface: RightPanelSurface) => void;
96 onCloseAllSurfaces: () => void;
97 onCopyFilePath: (relativePath: string) => void;
98 onAddBrowser: () => void;
99 /**
100 * Separate from `onAddBrowser` on purpose: that one is passed directly as a
101 * DOM click handler, and a `(profileId?: string)` signature would silently
102 * accept the MouseEvent as a profile id.
103 */
104 onAddBrowserInProfile: (profileId: string) => void;
105 onAddTerminal: () => void;
106 onAddDiff: () => void;
107 onAddFiles: () => void;
108 onAddPullRequest: () => void;
109 onAddAgents: () => void;
110 browserAvailable: boolean;
111 terminalAvailable: boolean;
112 diffAvailable: boolean;
113 filesAvailable: boolean;
114 pullRequestAvailable: boolean;
115 agentsAvailable: boolean;
116 pullRequestStatusSeeds?: Readonly<Record<string, PullRequestTabStatusSeed>>;
117 /** Running + waiting subagents; badges the Agents card in the empty state. */
118 liveAgentCount: number;
119 children: ReactNode;
121​
122export interface PullRequestTabStatus {
123 projectId: string;
124 repository: string;
125 number: number;
126 state: PullRequestState;
127 isDraft: boolean;
129​
130export type PullRequestTabStatusSeed = Pick<PullRequestTabStatus, "state" | "isDraft">;
131​
132export function shouldOpenDefaultBrowserProfileFromMenuClick(
133 pointerType: string | undefined,
134): boolean {
135 return pointerType !== "touch";
137​
138const SURFACE_DISABLED_REASONS = {
139 browser: "Browser previews are only available in the T3 Code desktop app.",
140 terminal: "Terminal surfaces are only available from a project thread.",
141 files: "Files are only available when a project is open.",
142 diff: "Diff is only available for server threads in Git repositories.",
143 pullRequest: "This thread's branch has no pull request yet.",
144 agents: "Agents are only available from a thread.",
145} as const;
146​
147/** Overlays that must win over the launcher's letter shortcuts. */
148const LAUNCHER_SHORTCUT_BLOCKING_LAYERS = [
149 '[data-slot="dialog-popup"]',
150 '[data-slot="alert-dialog-popup"]',
151 '[data-slot="command-dialog-popup"]',
152 '[data-slot="menu-popup"]',
153 '[data-slot="select-popup"]',
154 '[data-slot="popover-popup"]',
155 '[data-slot="combobox-popup"]',
156 '[data-slot="autocomplete-popup"]',
157].join(",");
158​
159/** One-line unavailability hints for the empty-state cards. */
160const SURFACE_UNAVAILABLE_HINTS = {
161 browser: "Only available in the desktop app.",
162 terminal: "Available when a project is open.",
163 files: "Available when a project is open.",
164 diff: "Available for Git repositories.",
165 pullRequest: "No pull request on this branch yet.",
166 agents: "Available from a thread.",
167} as const;
168​
169type TabContextMenuAction =
170 | "copy-path"
171 | "toggle-mute"
172 | "close"
173 | "close-others"
174 | "close-to-right"
175 | "close-all";
176​
177const TAB_SCROLL_EDGE_TOLERANCE = 1;
178​
179function tabScrollViewport(root: HTMLDivElement | null): HTMLDivElement | null {
180 return root?.querySelector<HTMLDivElement>('[data-slot="scroll-area-viewport"]') ?? null;
182​
183/**
184 * Desktop preview tab backing a surface, or null for non-preview surfaces, the
185 * "new browser tab" placeholder, and the web build where no desktop tab exists.
186 */
187function previewTabIdOf(
188 surface: RightPanelSurface,
189 sessions: Readonly<Record<string, PreviewSessionSnapshot>>,
190): string | null {
191 if (surface.kind !== "preview" || !surface.resourceId) return null;
192 return sessions[surface.resourceId]?.tabId ?? null;
194​
195/**
196 * Label and enabled state for a preview tab's mute menu entry.
197 * Stays disabled until desktop overlay state arrives: a server session id can
198 * resolve while the preview manager's createTab is still in flight, and muting
199 * then fails with a PreviewTabNotFoundError nothing surfaces to the user.
200 */
201export function tabMuteMenuItem(input: {
202 overlay: DesktopPreviewOverlay | null;
203 canResolveRuntimeTabId: boolean;
204}): { label: string; disabled: boolean } {
205 const muted = input.overlay?.audioMuted ?? false;
206 return {
207 label: muted ? "Unmute tab" : "Mute tab",
208 disabled: input.overlay === null || !input.canResolveRuntimeTabId,
209 };
211​
212type TabAudioState = "none" | "audible" | "muted";
213​
214/**
215 * A muted tab that is not making sound shows nothing: mute is armed silently,
216 * and the indicator only appears once there is audio to speak of.
217 */
218function tabAudioState(overlay: DesktopPreviewOverlay | null): TabAudioState {
219 if (!overlay?.audible) return "none";
220 return overlay.audioMuted ? "muted" : "audible";
222​
223type SurfaceShortcutEvent = Pick<
224 KeyboardEvent,
225 "altKey" | "ctrlKey" | "defaultPrevented" | "isComposing" | "key" | "metaKey"
226>;
227​
228export function surfaceShortcutActionForKey<
229 const Action extends { available: boolean; shortcut: string },
230>(actions: readonly Action[], event: SurfaceShortcutEvent): Action | null {
231 if (event.defaultPrevented || event.isComposing) return null;
232 if (event.metaKey || event.ctrlKey || event.altKey) return null;
233 return (
234 actions.find(
235 (action) => action.available && action.shortcut.toLowerCase() === event.key.toLowerCase(),
236 ) ?? null
237 );
239​
240/**
241 * A focused editable is a typing context whether or not it has text yet: an
242 * empty chat composer at rest is still where the user's next keystrokes are
243 * meant to land, and claiming launcher letters from it would redirect prompts
244 * into whatever surface opens. The `:not` clause lets `closest` see past
245 * non-editable islands (`contenteditable="false"`) to an editable host around
246 * them, matching ComposerPendingUserInputPanel's typing guard.
247 */
248export function surfaceShortcutTargetsTypingContext(
249 target: { closest(selectors: string): unknown } | null,
250): boolean {
251 return (
252 target?.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"])') !=
253 null
254 );
256​
257function DisabledReasonTooltip(props: { reason: string; trigger: ReactElement }) {
258 return (
259 <Tooltip>
260 <TooltipTrigger render={props.trigger} />
261 <TooltipPopup side="top">{props.reason}</TooltipPopup>
262 </Tooltip>
263 );
265​
266function SurfaceMenuItem(props: {
267 available: boolean;
268 disabledReason?: string;
269 shortcut: string;
270 onClick: () => void;
271 children: ReactNode;
272}) {
273 const item = (
274 <MenuItem
275 className={!props.available ? "data-disabled:pointer-events-auto" : undefined}
276 onClick={props.onClick}
277 disabled={!props.available}
278 aria-keyshortcuts={props.shortcut}
279 >
280 {props.children}
281 <MenuShortcut>{props.shortcut}</MenuShortcut>
282 </MenuItem>
283 );
284 if (props.available || !props.disabledReason) return item;
285 return <DisabledReasonTooltip reason={props.disabledReason} trigger={item} />;
287​
288/**
289 * Card launcher shown when the right panel has no surfaces. Keyboard-first
290 * without palette chrome: a surface's letter opens it directly from anywhere
291 * outside a typing context, and arrows plus Enter work while the launcher is
292 * focused. The highlight only appears on hover or arrow use. Unavailable
293 * surfaces stay visible with a one-line reason.
294 */
295function RightPanelEmptyState(props: {
296 onAddBrowser: () => void;
297 onAddBrowserInProfile: (profileId: string) => void;
298 browserProfiles: ReadonlyArray<{ readonly id: string; readonly name: string }>;
299 onAddTerminal: () => void;
300 onAddDiff: () => void;
301 onAddFiles: () => void;
302 onAddPullRequest: () => void;
303 onAddAgents: () => void;
304 browserAvailable: boolean;
305 terminalAvailable: boolean;
306 diffAvailable: boolean;
307 filesAvailable: boolean;
308 pullRequestAvailable: boolean;
309 agentsAvailable: boolean;
310 liveAgentCount: number;
311}) {
312 // -1 means no highlight: it only appears on hover or arrow use.
313 const [highlight, setHighlight] = useState(-1);
314​
315 const actions = [
316 {
317 label: "Browser",
318 description: "Open a local app or URL.",
319 icon: Globe2,
320 shortcut: "B",
321 available: props.browserAvailable,
322 disabledReason: SURFACE_UNAVAILABLE_HINTS.browser,
323 onClick: props.onAddBrowser,
324 badgeCount: 0,
325 },
326 {
327 label: "Terminal",
328 description: "Start a shell in this workspace.",
329 icon: TerminalSquare,
330 shortcut: "T",
331 available: props.terminalAvailable,
332 disabledReason: SURFACE_UNAVAILABLE_HINTS.terminal,
333 onClick: props.onAddTerminal,
334 badgeCount: 0,
335 },
336 {
337 label: "Files",
338 description: "Browse and read workspace files.",
339 icon: Files,
340 shortcut: "F",
341 available: props.filesAvailable,
342 disabledReason: SURFACE_UNAVAILABLE_HINTS.files,
343 onClick: props.onAddFiles,
344 badgeCount: 0,
345 },
346 {
347 label: "Diff",
348 description: "Review changes in this thread.",
349 icon: FileDiff,
350 shortcut: "D",
351 available: props.diffAvailable,
352 disabledReason: SURFACE_UNAVAILABLE_HINTS.diff,
353 onClick: props.onAddDiff,
354 badgeCount: 0,
355 },
356 {
357 label: "Pull request",
358 description: "Open this branch's pull request.",
359 icon: GitPullRequest,
360 shortcut: "P",
361 available: props.pullRequestAvailable,
362 disabledReason: SURFACE_UNAVAILABLE_HINTS.pullRequest,
363 onClick: props.onAddPullRequest,
364 badgeCount: 0,
365 },
366 {
367 label: "Agents",
368 description: "Follow subagents and workflows.",
369 icon: Bot,
370 shortcut: "A",
371 available: props.agentsAvailable,
372 disabledReason: SURFACE_UNAVAILABLE_HINTS.agents,
373 onClick: props.onAddAgents,
374 badgeCount: props.liveAgentCount,
375 },
376 ] as const;
377​
378 type SurfaceAction = (typeof actions)[number];
379​
380 const availableActions = actions.filter((action) => action.available);
381 const highlightIndex =
382 availableActions.length === 0 ? -1 : Math.min(highlight, availableActions.length - 1);
383​
384 // Letter shortcuts work while the launcher is visible, not only while it
385 // is focused; focus moves around too easily (stray clicks) to carry them.
386 // Capture phase so app-level key handlers cannot swallow the event first;
387 // typing contexts and already-handled events are left alone.
388 const shortcutActionsRef = useRef(availableActions);
389 useEffect(() => {
390 shortcutActionsRef.current = availableActions;
391 });
392 useEffect(() => {
393 const handler = (event: KeyboardEvent) => {
394 const action = surfaceShortcutActionForKey(shortcutActionsRef.current, event);
395 if (!action) return;
396 if (document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS)) return;
397 const target = event.target;
398 if (target instanceof Element && surfaceShortcutTargetsTypingContext(target)) return;
399 event.preventDefault();
400 event.stopPropagation();
401 action.onClick();
402 };
403 window.addEventListener("keydown", handler, true);
404 return () => window.removeEventListener("keydown", handler, true);
405 }, []);
406​
407 const handleKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
408 if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return;
409 if (availableActions.length === 0) return;
410 if (event.key === "ArrowDown" || event.key === "ArrowRight") {
411 event.preventDefault();
412 setHighlight((highlightIndex + 1) % availableActions.length);
413 return;
414 }
415 if (event.key === "ArrowUp" || event.key === "ArrowLeft") {
416 event.preventDefault();
417 setHighlight(
418 highlightIndex === -1
419 ? availableActions.length - 1
420 : (highlightIndex - 1 + availableActions.length) % availableActions.length,
421 );
422 return;
423 }
424 if (event.key === "Enter") {
425 // A focused card button owns its own activation; only open from the
426 // highlight when the container itself has focus.
427 if (event.target instanceof HTMLElement && event.target.closest("button")) return;
428 const action = availableActions[highlightIndex];
429 if (!action) return;
430 event.preventDefault();
431 action.onClick();
432 }
433 };
434​
435 // Stable identity so React only runs this callback ref on mount/unmount;
436 // an inline arrow would re-attach and re-focus on every render.
437 const focusOnMount = useCallback((node: HTMLDivElement | null) => {
438 node?.focus();
439 }, []);
440​
441 const isHighlighted = (action: SurfaceAction) =>
442 highlightIndex !== -1 && availableActions[highlightIndex] === action;
443​
444 const actionIcon = (action: SurfaceAction, iconClassName = "size-4") => {
445 const Icon = action.icon;
446 return (
447 <span className="relative inline-flex shrink-0">
448 <Icon className={iconClassName} />
449 {action.badgeCount > 0 ? (
450 <span
451 aria-hidden
452 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"
453 >
454 {action.badgeCount}
455 </span>
456 ) : null}
457 </span>
458 );
459 };
460​
461 const cardShellClass =
462 "rounded-lg border border-border/80 bg-card dark:border-transparent dark:shadow-none dark:inset-ring-1 dark:inset-ring-white/5";
463 const highlightedCardClass = "bg-accent/60 dark:inset-ring-white/20";
464​
465 return (
466 <div
467 ref={focusOnMount}
468 tabIndex={0}
469 onKeyDown={handleKeyDown}
470 aria-label="Open a surface"
471 data-surface-launcher-keys={availableActions.map((action) => action.shortcut).join("")}
472 className={cn(
473 "flex min-h-0 flex-1 items-center justify-center overflow-y-auto px-6 pt-6 outline-none",
474 // The panel topbar sits above this container; matching bottom padding
475 // keeps the cards centered against the full panel, not the leftover.
476 "pb-[calc(var(--workspace-topbar-height)+--spacing(6))]",
477 )}
478 >
479 <div className="relative w-full max-w-lg">
480 <div className="absolute inset-x-0 bottom-full mb-5 text-center">
481 <h3 className="font-medium text-foreground text-sm">Open a surface</h3>
482 <p className="mt-1 text-muted-foreground text-xs">
483 Choose what to show in the right panel.
484 </p>
485 </div>
486 <div className="grid grid-cols-2 gap-2">
487 {actions.map((action) =>
488 action.available ? (
489 // The card is itself a button, so the profile chooser sits beside
490 // it in a wrapper rather than inside it. Hover lives on the
491 // wrapper: the chooser overlays the card, and a pointer moving
492 // onto it must not read as leaving the card.
493 <div
494 key={action.label}
495 className="group relative"
496 onMouseEnter={() => setHighlight(availableActions.indexOf(action))}
497 onMouseLeave={() =>
498 setHighlight((current) =>
499 current === availableActions.indexOf(action) ? -1 : current,
500 )
501 }
502 >
503 <button
504 type="button"
505 onClick={action.onClick}
506 className={cn(
507 // Full height: the wrapper is the grid item that stretches
508 // to the row, so the button must fill it to stay level with
509 // its neighbour and keep the chooser anchored inside.
510 "relative flex h-full w-full cursor-pointer flex-col items-start p-4 text-left transition group-hover:border-border group-hover:bg-accent/60",
511 cardShellClass,
512 isHighlighted(action) && highlightedCardClass,
513 )}
514 >
515 <Kbd className="absolute top-3 right-3">{action.shortcut}</Kbd>
516 <span className="flex items-center gap-2 pe-8">
517 {actionIcon(action)}
518 <span className="font-medium text-sm">{action.label}</span>
519 </span>
520 <span className="mt-1.5 text-muted-foreground text-xs leading-relaxed">
521 {action.description}
522 </span>
523 </button>
524 {/*
525 Same choice the tab bar's "+" menu offers: the card opens the
526 default profile, the chevron picks another. Only worth showing
527 once there is something to choose between.
528 */}
529 {action.label === "Browser" && props.browserProfiles.length > 1 ? (
530 <Menu>
531 <MenuTrigger
532 render={
533 <Button
534 aria-label="Open browser in a profile"
535 className="absolute right-3 bottom-3 [--control-icon-color:currentColor]"
536 size="icon-xs"
537 variant="ghost-muted"
538 />
539 }
540 >
541 <ChevronDown className="size-3.5" />
542 </MenuTrigger>
543 <MenuPopup
544 align="end"
545 side="bottom"
546 sideOffset={6}
547 className="min-w-40 max-w-56"
548 >
549 {props.browserProfiles.map((profile) => (
550 <MenuItem
551 key={profile.id}
552 onClick={() => props.onAddBrowserInProfile(profile.id)}
553 >
554 <span className="min-w-0 truncate">{profile.name}</span>
555 </MenuItem>
556 ))}
557 </MenuPopup>
558 </Menu>
559 ) : null}
560 </div>
561 ) : (
562 <div
563 key={action.label}
564 className={cn(
565 "relative flex w-full flex-col items-start p-4 opacity-40",
566 cardShellClass,
567 )}
568 >
569 <Kbd className="absolute top-3 right-3">{action.shortcut}</Kbd>
570 <span className="flex items-center gap-2 pe-8">
571 {actionIcon(action)}
572 <span className="font-medium text-sm">{action.label}</span>
573 </span>
574 <span className="mt-1.5 text-muted-foreground text-xs leading-relaxed">
575 {action.disabledReason}
576 </span>
577 </div>
578 ),
579 )}
580 </div>
581 </div>
582 </div>
583 );
585​
586function surfaceTitle(
587 surface: RightPanelSurface,
588 sessions: Readonly<Record<string, PreviewSessionSnapshot>>,
589 terminalLabelsById: ReadonlyMap<string, string>,
590): string {
591 switch (surface.kind) {
592 case "diff":
593 return "Diff";
594 case "files":
595 return "Files";
596 case "file":
597 return surface.relativePath.slice(
598 Math.max(surface.relativePath.lastIndexOf("/"), surface.relativePath.lastIndexOf("\\")) + 1,
599 );
600 case "terminal":
601 return (
602 terminalLabelsById.get(surface.activeTerminalId) ??
603 getTerminalLabel(surface.activeTerminalId)
604 );
605 case "pull-request":
606 return `#${surface.number}`;
607 case "agents":
608 return "Agents";
609 case "preview": {
610 const snapshot = surface.resourceId ? sessions[surface.resourceId] : null;
611 if (!snapshot || snapshot.navStatus._tag === "Idle") return "Browser";
612 if (snapshot.navStatus.title.trim().length > 0) return snapshot.navStatus.title;
613 try {
614 return new URL(snapshot.navStatus.url).host || "Browser";
615 } catch {
616 return "Browser";
617 }
618 }
619 }
621​
622function PreviewFavicon({ capturedUrl, url }: { capturedUrl: string | null; url: string | null }) {
623 const publicProviderUrl = faviconUrlForOrigin(url, 32);
624 return (
625 <FaviconImage
626 sources={[capturedUrl, publicProviderUrl]}
627 fallback={<Globe2 className="size-3 shrink-0" />}
628 className="size-3 shrink-0 rounded-sm object-contain"
629 />
630 );
632​
633function sameOrigin(left: string, right: string): boolean {
634 try {
635 return new URL(left).origin === new URL(right).origin;
636 } catch {
637 return false;
638 }
640​
641function SurfaceIcon({
642 surface,
643 sessions,
644 desktopByTabId,
645 theme,
646 environmentId,
647 pullRequestStatusSeeds,
648}: {
649 surface: RightPanelSurface;
650 sessions: Readonly<Record<string, PreviewSessionSnapshot>>;
651 desktopByTabId: Readonly<Record<string, DesktopPreviewOverlay>>;
652 theme: "light" | "dark";
653 environmentId: EnvironmentId | null;
654 pullRequestStatusSeeds: Readonly<Record<string, PullRequestTabStatusSeed>> | undefined;
655}) {
656 switch (surface.kind) {
657 case "preview": {
658 const snapshot = surface.resourceId ? sessions[surface.resourceId] : null;
659 const url = !snapshot || snapshot.navStatus._tag === "Idle" ? null : snapshot.navStatus.url;
660 const favicon = snapshot ? (desktopByTabId[snapshot.tabId]?.favicon ?? null) : null;
661 const capturedUrl =
662 favicon && url && sameOrigin(favicon.pageUrl, url) ? favicon.dataUrl : null;
663 return <PreviewFavicon capturedUrl={capturedUrl} url={url} />;
664 }
665 case "diff":
666 return <FileDiff className="size-3 shrink-0" />;
667 case "files":
668 return <Files className="size-3 shrink-0" />;
669 case "file":
670 return (
671 <PierreEntryIcon
672 pathValue={surface.relativePath}
673 kind="file"
674 theme={theme}
675 className="size-3"
676 />
677 );
678 case "terminal":
679 return <TerminalSquare className="size-3 shrink-0" />;
680 case "pull-request":
681 return (
682 <PullRequestSurfaceIcon
683 surface={surface}
684 environmentId={environmentId}
685 seed={pullRequestStatusSeeds?.[surface.id]}
686 />
687 );
688 case "agents":
689 return <Bot className="size-3 shrink-0" />;
690 }
692​
693function PullRequestSurfaceIcon({
694 surface,
695 environmentId,
696 seed,
697}: {
698 surface: Extract<RightPanelSurface, { kind: "pull-request" }>;
699 environmentId: EnvironmentId | null;
700 seed: PullRequestTabStatusSeed | undefined;
701}) {
702 const resolvedEnvironmentId =
703 (surface.environmentId as EnvironmentId | undefined) ?? environmentId;
704 const detail = useEnvironmentQuery(
705 resolvedEnvironmentId === null
706 ? null
707 : pullRequestEnvironment.detail({
708 environmentId: resolvedEnvironmentId,
709 input: {
710 projectId: surface.projectId as ProjectId,
711 repository: surface.repository,
712 number: surface.number,
713 },
714 }),
715 ).data;
716 // Only state and draft reach the tab. A list seed cannot know mergeability, so feeding the
717 // full detail would flip an open tab to the conflict glyph the moment its read lands.
718 const status =
719 detail === null ? (seed ?? null) : { state: detail.state, isDraft: detail.isDraft };
720 if (status === null) {
721 return <GitPullRequest className="size-3 shrink-0 text-muted-foreground" />;
722 }
723 const presentation = resolvePullRequestState(status);
724 return <presentation.Icon className={cn("size-3 shrink-0", presentation.toneClassName)} />;
726​
727export function RightPanelTabs(props: RightPanelTabsProps) {
728 const ownsDesktopTitleBar = isElectron && props.mode === "inline";
729 const browserProfiles = useBrowserDefaults().profiles;
730 const { resolvedTheme } = useTheme();
731 const tabListRef = useRef<HTMLDivElement>(null);
732 const [addSurfaceMenuOpen, setAddSurfaceMenuOpen] = useState(false);
733 const [tabScrollState, setTabScrollState] = useState({
734 hasOverflow: false,
735 canScrollLeft: false,
736 canScrollRight: false,
737 });
738​
739 const updateTabScrollState = useCallback(() => {
740 const viewport = tabScrollViewport(tabListRef.current);
741 if (!viewport) return;
742​
743 const hasOverflow = viewport.scrollWidth - viewport.clientWidth > TAB_SCROLL_EDGE_TOLERANCE;
744 const canScrollLeft = hasOverflow && viewport.scrollLeft > TAB_SCROLL_EDGE_TOLERANCE;
745 const canScrollRight =
746 hasOverflow &&
747 viewport.scrollLeft + viewport.clientWidth < viewport.scrollWidth - TAB_SCROLL_EDGE_TOLERANCE;
748 setTabScrollState((current) => {
749 if (
750 current.hasOverflow === hasOverflow &&
751 current.canScrollLeft === canScrollLeft &&
752 current.canScrollRight === canScrollRight
753 ) {
754 return current;
755 }
756 return { hasOverflow, canScrollLeft, canScrollRight };
757 });
758 }, []);
759​
760 const scrollTabs = useCallback((direction: -1 | 1) => {
761 const viewport = tabScrollViewport(tabListRef.current);
762 if (!viewport) return;
763 const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
764 viewport.scrollBy({
765 left: direction * Math.max(120, viewport.clientWidth * 0.75),
766 behavior: reduceMotion ? "auto" : "smooth",
767 });
768 }, []);
769​
770 const addSurfaceActions = [
771 {
772 label: "Browser",
773 icon: Globe2,
774 shortcut: "B",
775 available: props.browserAvailable,
776 disabledReason: SURFACE_DISABLED_REASONS.browser,
777 onClick: props.onAddBrowser,
778 },
779 {
780 label: "Terminal",
781 icon: TerminalSquare,
782 shortcut: "T",
783 available: props.terminalAvailable,
784 disabledReason: SURFACE_DISABLED_REASONS.terminal,
785 onClick: props.onAddTerminal,
786 },
787 {
788 label: "Files",
789 icon: Files,
790 shortcut: "F",
791 available: props.filesAvailable,
792 disabledReason: SURFACE_DISABLED_REASONS.files,
793 onClick: props.onAddFiles,
794 },
795 {
796 label: "Diff",
797 icon: FileDiff,
798 shortcut: "D",
799 available: props.diffAvailable,
800 disabledReason: SURFACE_DISABLED_REASONS.diff,
801 onClick: props.onAddDiff,
802 },
803 {
804 label: "Pull request",
805 icon: GitPullRequest,
806 shortcut: "P",
807 available: props.pullRequestAvailable,
808 disabledReason: SURFACE_DISABLED_REASONS.pullRequest,
809 onClick: props.onAddPullRequest,
810 },
811 {
812 label: "Agents",
813 icon: Bot,
814 shortcut: "A",
815 available: props.agentsAvailable,
816 disabledReason: SURFACE_DISABLED_REASONS.agents,
817 onClick: props.onAddAgents,
818 },
819 ] as const;
820​
821 const handleAddSurfaceMenuKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
822 const action = surfaceShortcutActionForKey(addSurfaceActions, event.nativeEvent);
823 if (!action) return;
824 event.preventDefault();
825 event.stopPropagation();
826 setAddSurfaceMenuOpen(false);
827 action.onClick();
828 };
829​
830 const handleTabContextMenu = useCallback(
831 async (event: ReactMouseEvent, surface: RightPanelSurface) => {
832 event.preventDefault();
833 event.stopPropagation();
834​
835 const api = readLocalApi();
836 if (!api) return;
837​
838 const surfaceIndex = props.surfaces.findIndex((entry) => entry.id === surface.id);
839 if (surfaceIndex < 0) return;
840​
841 const items: ContextMenuItem<TabContextMenuAction>[] = [];
842 if (surface.kind === "file" && surface.attachment === undefined) {
843 items.push({ id: "copy-path", label: "Copy path" });
844 }
845 const menuPreviewTabId = previewTabIdOf(surface, props.previewSessions);
846 // Desktop overlay state only arrives once the preview manager has created
847 // the tab. A server session id alone can still be ahead of that, and
848 // muting then fails with PreviewTabNotFoundError that nobody surfaces.
849 const menuOverlay = menuPreviewTabId
850 ? (props.desktopByTabId[menuPreviewTabId] ?? null)
851 : null;
852 const menuMuted = menuOverlay?.audioMuted ?? false;
853 if (surface.kind === "preview") {
854 // Not gated on audibility: silencing a quiet tab ahead of time is the
855 // point, so the item is offered whenever the tab is mutable at all.
856 items.push({
857 id: "toggle-mute",
858 ...tabMuteMenuItem({
859 overlay: menuOverlay,
860 canResolveRuntimeTabId: props.previewRuntimeTabId !== undefined,
861 }),
862 });
863 }
864 items.push(
865 { id: "close", label: "Close" },
866 {
867 id: "close-others",
868 label: "Close others",
869 disabled: props.surfaces.length <= 1,
870 },
871 {
872 id: "close-to-right",
873 label: "Close to the right",
874 disabled: surfaceIndex >= props.surfaces.length - 1,
875 },
876 {
877 id: "close-all",
878 label: "Close all",
879 disabled: props.surfaces.length === 0,
880 },
881 );
882​
883 const action = await api.contextMenu.show(items, { x: event.clientX, y: event.clientY });
884 switch (action) {
885 case "copy-path":
886 if (surface.kind === "file" && surface.attachment === undefined) {
887 props.onCopyFilePath(surface.relativePath);
888 }
889 break;
890 case "toggle-mute": {
891 // menuOverlay repeats the disabled gate above: the desktop tab must
892 // exist before it can be addressed, however the menu was dismissed.
893 const runtimeTabId =
894 menuPreviewTabId && menuOverlay
895 ? (props.previewRuntimeTabId?.(menuPreviewTabId) ?? null)
896 : null;
897 if (runtimeTabId) {
898 void previewBridge?.setAudioMuted(runtimeTabId, !menuMuted).catch(() => undefined);
899 }
900 break;
901 }
902 case "close":
903 props.onCloseSurface(surface);
904 break;
905 case "close-others":
906 props.onCloseOtherSurfaces(surface);
907 break;
908 case "close-to-right":
909 props.onCloseSurfacesToRight(surface);
910 break;
911 case "close-all":
912 props.onCloseAllSurfaces();
913 break;
914 case null:
915 break;
916 }
917 },
918 [props],
919 );
920 const handleTabMouseDown = useCallback((event: ReactMouseEvent) => {
921 if (event.button !== 1) return;
922 event.preventDefault();
923 }, []);
924 const handleTabAuxClick = useCallback(
925 (event: ReactMouseEvent, surface: RightPanelSurface) => {
926 if (event.button !== 1) return;
927 event.preventDefault();
928 event.stopPropagation();
929 props.onCloseSurface(surface);
930 },
931 [props],
932 );
933​
934 useEffect(() => {
935 if (!props.activeSurfaceId || !tabScrollState.hasOverflow) return;
936 const activeTab = tabListRef.current?.querySelector<HTMLElement>("[data-active-tab='true']");
937 activeTab?.scrollIntoView({ block: "nearest", inline: "nearest" });
938 }, [props.activeSurfaceId, tabScrollState.hasOverflow]);
939​
940 useEffect(() => {
941 const viewport = tabScrollViewport(tabListRef.current);
942 if (!viewport) return;
943​
944 const content = viewport.firstElementChild;
945 const resizeObserver = new ResizeObserver(updateTabScrollState);
946 resizeObserver.observe(viewport);
947 if (content) resizeObserver.observe(content);
948 viewport.addEventListener("scroll", updateTabScrollState, { passive: true });
949 updateTabScrollState();
950​
951 return () => {
952 resizeObserver.disconnect();
953 viewport.removeEventListener("scroll", updateTabScrollState);
954 };
955 }, [updateTabScrollState]);
956​
957 useEffect(() => {
958 const viewport = tabScrollViewport(tabListRef.current);
959 if (!viewport) return;
960​
961 const handleWheel = (event: WheelEvent) => {
962 if (event.ctrlKey) return;
963 let delta = Math.abs(event.deltaX) > Math.abs(event.deltaY) ? event.deltaX : event.deltaY;
964 if (event.deltaMode === WheelEvent.DOM_DELTA_LINE) delta *= 16;
965 if (event.deltaMode === WheelEvent.DOM_DELTA_PAGE) delta *= viewport.clientWidth;
966 if (delta === 0) return;
967​
968 const previousScrollLeft = viewport.scrollLeft;
969 viewport.scrollLeft += delta;
970 if (viewport.scrollLeft === previousScrollLeft) return;
971 event.preventDefault();
972 updateTabScrollState();
973 };
974​
975 viewport.addEventListener("wheel", handleWheel, { passive: false });
976 return () => viewport.removeEventListener("wheel", handleWheel);
977 }, [updateTabScrollState]);
978​
979 return (
980 <PreviewPanelShell
981 mode={props.mode}
982 {...(props.maximized !== undefined ? { maximized: props.maximized } : {})}
983 {...(props.open !== undefined ? { open: props.open } : {})}
984 {...(props.widthStorageKey !== undefined ? { widthStorageKey: props.widthStorageKey } : {})}
985 {...(props.defaultWidth !== undefined ? { defaultWidth: props.defaultWidth } : {})}
986 {...(props.inlineSize ? { inlineSize: props.inlineSize } : {})}
987 >
988 <div
989 className={cn(
990 "flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center gap-1 pl-2",
991 // The sheet overlays from the viewport top, so its tab bar keeps
992 // the titlebar's height: a compact row re-centers the layout
993 // controls a few pixels higher and the cluster jumps on open.
994 props.mode === "inline" && !props.layoutControls ? "pr-28" : "pr-3",
995 ownsDesktopTitleBar && "drag-region",
996 ownsDesktopTitleBar &&
997 (props.layoutControls
998 ? "wco:pr-[var(--workspace-native-controls-inset)]"
999 : "wco:pr-[calc(var(--workspace-native-controls-inset)+6rem)]"),
1000 props.mode === "inline" && props.maximized && COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
1001 )}
1002 data-right-panel-tabbar
1004 <ScrollArea
1005 ref={tabListRef}
1006 hideScrollbars
1007 scrollFade
1008 className="min-w-0 flex-1 rounded-none"
1009 data-right-panel-tab-list
1011 <div className="flex h-full w-max min-w-full items-center gap-1">
1012 {props.surfaces.map((surface) => {
1013 const active = surface.id === props.activeSurfaceId;
1014 const pending = props.pendingSurfaceIds.has(surface.id);
1015 const title = surfaceTitle(surface, props.previewSessions, props.terminalLabelsById);
1016 const previewTabId = previewTabIdOf(surface, props.previewSessions);
1017 // Desktop state is keyed by the session id, but desktop actions
1018 // must be addressed with the runtime id.
1019 const audio = tabAudioState(
1020 previewTabId ? (props.desktopByTabId[previewTabId] ?? null) : null,
1021 );
1022 const audioRuntimeTabId = previewTabId
1023 ? (props.previewRuntimeTabId?.(previewTabId) ?? null)
1024 : null;
1025 return (
1026 <div
1027 key={surface.id}
1028 data-active-tab={active}
1029 onMouseDown={handleTabMouseDown}
1030 onAuxClick={(event) => handleTabAuxClick(event, surface)}
1031 onContextMenu={(event) => void handleTabContextMenu(event, surface)}
1032 className={cn(
1033 "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",
1034 ownsDesktopTitleBar && "[-webkit-app-region:no-drag]",
1035 active
1036 ? "bg-accent text-foreground"
1037 : "text-muted-foreground hover:bg-accent/60 hover:text-foreground",
1038 )}
1040 <PanelTabCloseButton
1041 label={`Close ${title}`}
1042 onClick={() => props.onCloseSurface(surface)}
1044 <SurfaceIcon
1045 surface={surface}
1046 sessions={props.previewSessions}
1047 desktopByTabId={props.desktopByTabId}
1048 theme={resolvedTheme}
1049 environmentId={props.environmentId}
1050 pullRequestStatusSeeds={props.pullRequestStatusSeeds}
1051 />
1052 {pending ? (
1053 <span
1054 className="absolute -right-0.5 -bottom-0.5 size-1.5 rounded-full bg-current"
1055 aria-hidden
1056 />
1057 ) : null}
1058 </PanelTabCloseButton>
1059 {audio === "none" || !audioRuntimeTabId ? null : (
1060 <Tooltip>
1061 <TooltipTrigger
1062 render={
1063 <button
1064 type="button"
1065 className="cursor-pointer flex size-4 shrink-0 items-center justify-center rounded-sm hover:bg-muted"
1066 aria-label={audio === "muted" ? `Unmute ${title}` : `Mute ${title}`}
1067 onClick={(event) => {
1068 // Sibling of the close button, inside a tab that
1069 // activates on click: keep this to the toggle.
1070 event.stopPropagation();
1071 void previewBridge
1072 ?.setAudioMuted(audioRuntimeTabId, audio !== "muted")
1073 .catch(() => undefined);
1074 }}
1076 {audio === "muted" ? (
1077 <VolumeOff className="size-3" />
1078 ) : (
1079 <Volume2 className="size-3" />
1080 )}
1081 </button>
1083 />
1084 <TooltipPopup>{audio === "muted" ? "Unmute tab" : "Mute tab"}</TooltipPopup>
1085 </Tooltip>
1086 )}
1087 <Tooltip>
1088 <TooltipTrigger
1089 render={
1090 <button
1091 type="button"
1092 className="cursor-pointer flex min-w-0 items-center"
1093 onClick={() => props.onActivate(surface)}
1095 <span className="truncate">{title}</span>
1096 </button>
1098 />
1099 <TooltipPopup>{title}</TooltipPopup>
1100 </Tooltip>
1101 </div>
1102 );
1103 })}
1104 {props.surfaces.length > 0 ? (
1105 <Menu open={addSurfaceMenuOpen} onOpenChange={setAddSurfaceMenuOpen}>
1106 <MenuTrigger
1107 render={
1108 <Button
1109 aria-label="Add panel surface"
1110 className="size-6 shrink-0 text-muted-foreground hover:text-foreground"
1111 size="icon-xs"
1112 variant="ghost"
1113 />
1116 <Plus className="size-3.5" />
1117 </MenuTrigger>
1118 <MenuPopup
1119 align="start"
1120 side="bottom"
1121 sideOffset={6}
1122 className="min-w-44"
1123 onKeyDownCapture={handleAddSurfaceMenuKeyDown}
1125 {addSurfaceActions.map((action) => {
1126 const Icon = action.icon;
1127 // Browser collapses into one row: clicking the trigger opens
1128 // the default profile (the common case stays one click),
1129 // while hover or arrow reveals the profiles. The choice
1130 // lives at open time because a tab's profile is fixed then —
1131 // Electron only honours a partition before attach.
1132 if (action.label === "Browser" && action.available) {
1133 return (
1134 <MenuSub key={action.label}>
1135 <MenuSubTrigger
1136 className="[&>svg:last-child]:ms-0"
1137 aria-keyshortcuts={action.shortcut}
1138 onClick={(event) => {
1139 const pointerType =
1140 "pointerType" in event.nativeEvent &&
1141 typeof event.nativeEvent.pointerType === "string"
1142 ? event.nativeEvent.pointerType
1143 : undefined;
1144 // Touch has no hover path to the profile choices:
1145 // its first tap opens the submenu, then a profile
1146 // is selected there. Mouse click keeps the common
1147 // default-profile action at one click.
1148 if (!shouldOpenDefaultBrowserProfileFromMenuClick(pointerType))
1149 return;
1150 setAddSurfaceMenuOpen(false);
1151 action.onClick();
1152 }}
1154 <Icon />
1155 {action.label}
1156 <MenuShortcut>{action.shortcut}</MenuShortcut>
1157 </MenuSubTrigger>
1158 {/*
1159 Capped and truncated: profile names are user-supplied
1160 and run to 48 characters, which would otherwise widen
1161 the popup to fit-content and wrap.
1162 */}
1163 <MenuSubPopup className="min-w-40 max-w-56">
1164 {browserProfiles.map((profile) => (
1165 <MenuItem
1166 key={profile.id}
1167 onClick={() => props.onAddBrowserInProfile(profile.id)}
1169 <span className="min-w-0 truncate">{profile.name}</span>
1170 </MenuItem>
1171 ))}
1172 </MenuSubPopup>
1173 </MenuSub>
1174 );
1176 return (
1177 <SurfaceMenuItem
1178 key={action.label}
1179 available={action.available}
1180 disabledReason={action.disabledReason}
1181 shortcut={action.shortcut}
1182 onClick={action.onClick}
1184 <Icon />
1185 {action.label}
1186 </SurfaceMenuItem>
1187 );
1188 })}
1189 </MenuPopup>
1190 </Menu>
1191 ) : null}
1192 </div>
1193 </ScrollArea>
1194 {tabScrollState.hasOverflow ? (
1195 <div
1196 className="flex shrink-0 items-center gap-0.5 [-webkit-app-region:no-drag]"
1197 role="group"
1198 aria-label="Scroll panel tabs"
1200 <Tooltip>
1201 <TooltipTrigger
1202 render={
1203 <span className="inline-flex">
1204 <Button
1205 aria-label="Scroll tabs left"
1206 disabled={!tabScrollState.canScrollLeft}
1207 onClick={() => scrollTabs(-1)}
1208 size="icon-xs"
1209 variant="ghost"
1211 <ChevronLeft />
1212 </Button>
1213 </span>
1215 />
1216 <TooltipPopup>Scroll tabs left</TooltipPopup>
1217 </Tooltip>
1218 <Tooltip>
1219 <TooltipTrigger
1220 render={
1221 <span className="inline-flex">
1222 <Button
1223 aria-label="Scroll tabs right"
1224 disabled={!tabScrollState.canScrollRight}
1225 onClick={() => scrollTabs(1)}
1226 size="icon-xs"
1227 variant="ghost"
1229 <ChevronRight />
1230 </Button>
1231 </span>
1233 />
1234 <TooltipPopup>Scroll tabs right</TooltipPopup>
1235 </Tooltip>
1236 </div>
1237 ) : null}
1238 {props.layoutControls}
1239 {ownsDesktopTitleBar ? (
1240 <span
1241 aria-hidden
1242 className="pointer-events-none fixed top-[var(--workspace-controls-top)] right-[var(--workspace-controls-right)] h-[var(--workspace-topbar-height)] w-28 [-webkit-app-region:no-drag]"
1243 />
1244 ) : null}
1245 </div>
1246 <div className="flex min-h-0 flex-1 flex-col" data-right-panel-surface-content>
1247 {props.activeSurfaceId === null ? (
1248 <RightPanelEmptyState
1249 onAddBrowser={props.onAddBrowser}
1250 onAddBrowserInProfile={props.onAddBrowserInProfile}
1251 browserProfiles={browserProfiles}
1252 onAddTerminal={props.onAddTerminal}
1253 onAddDiff={props.onAddDiff}
1254 onAddFiles={props.onAddFiles}
1255 onAddPullRequest={props.onAddPullRequest}
1256 onAddAgents={props.onAddAgents}
1257 browserAvailable={props.browserAvailable}
1258 terminalAvailable={props.terminalAvailable}
1259 diffAvailable={props.diffAvailable}
1260 filesAvailable={props.filesAvailable}
1261 pullRequestAvailable={props.pullRequestAvailable}
1262 agentsAvailable={props.agentsAvailable}
1263 liveAgentCount={props.liveAgentCount}
1264 />
1265 ) : (
1266 props.children
1267 )}
1268 </div>
1269 </PreviewPanelShell>
1270 );