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

RightPanelTabs.tsx

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