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