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