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

RightPanelTabs.tsx

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