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

RightPanelTabs.tsx

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