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