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