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