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