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