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