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