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

RightPanelTabs.tsx

1,413 lines52.3 KB

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