Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

RightPanelTabs.tsx

1,419 lines52.3 KB

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