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