Compare commits

...
Author SHA1 Message Date
maria-rcks 2dd5525de4 feat(web): refresh pull request details 2026-08-15 22:10:34 -04:00
maria-rcks 9ac145fda6 feat(web): redesign usage insights 2026-08-15 22:04:10 -04:00
maria-rcks e20c6800cd feat(web): unify workspace navigation 2026-08-15 22:00:39 -04:00
45 changed files with 1778 additions and 1333 deletions

No files matched your search

+36 -1
View File
@@ -98,7 +98,10 @@ describe("ElectronMenu", () => {
const electronMenu = yield* ElectronMenu.ElectronMenu;
const selectedItemId = yield* electronMenu.showContextMenu({
window: makeWindow(2),
items: [{ id: "copy", label: "Copy" }],
items: [
{ id: "copy", label: "Copy" },
{ id: "delete", label: "Delete", destructive: true, separatorBefore: true },
],
position: Option.some({ x: 10.8, y: 20.2 }),
});
@@ -110,6 +113,38 @@ describe("ElectronMenu", () => {
enabled: true,
click: buildFromTemplateMock.mock.calls[0]?.[0][0].click,
});
assert.deepEqual(
buildFromTemplateMock.mock.calls[0]?.[0].map(
(item: Electron.MenuItemConstructorOptions) => item.type ?? item.label,
),
["Copy", "separator", "Delete"],
);
}).pipe(Effect.provide(TestLayer)),
);
it.effect("keeps a preceding non-destructive action in the destructive section", () =>
Effect.gen(function* () {
buildFromTemplateMock.mockImplementation(() => ({
popup: (options: Electron.PopupOptions) => options.callback?.(),
}));
const electronMenu = yield* ElectronMenu.ElectronMenu;
yield* electronMenu.showContextMenu({
window: makeWindow(),
items: [
{ id: "copy", label: "Copy" },
{ id: "archive", label: "Archive", separatorBefore: true },
{ id: "delete", label: "Delete", destructive: true },
],
position: Option.none(),
});
assert.deepEqual(
buildFromTemplateMock.mock.calls[0]?.[0].map(
(item: Electron.MenuItemConstructorOptions) => item.type ?? item.label,
),
["Copy", "separator", "Archive", "Delete"],
);
}).pipe(Effect.provide(TestLayer)),
);
+17 -2
View File
@@ -78,6 +78,7 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM
label: sourceItem.label,
destructive: sourceItem.destructive === true,
disabled: sourceItem.disabled === true,
...(sourceItem.separatorBefore === true ? { separatorBefore: true } : {}),
};
if (sourceItem.children) {
@@ -141,10 +142,24 @@ export const make = Effect.gen(function* () {
): Electron.MenuItemConstructorOptions[] => {
const template: Electron.MenuItemConstructorOptions[] = [];
let hasInsertedDestructiveSeparator = false;
let sectionStartedByExplicitSeparator = false;
const appendSeparator = () => {
if (template.length === 0 || template.at(-1)?.type === "separator") return;
template.push({ type: "separator" });
};
for (const item of entries) {
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
template.push({ type: "separator" });
if (item.separatorBefore) {
appendSeparator();
sectionStartedByExplicitSeparator = true;
}
if (
item.destructive &&
!hasInsertedDestructiveSeparator &&
!sectionStartedByExplicitSeparator &&
template.length > 0
) {
appendSeparator();
hasInsertedDestructiveSeparator = true;
}
+6 -16
View File
@@ -169,7 +169,6 @@ import {
WifiOffIcon,
} from "lucide-react";
import { cn, randomHex } from "~/lib/utils";
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
import { stackedThreadToast, toastManager } from "./ui/toast";
import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings";
import { type NewProjectScriptInput } from "./ProjectScriptsControl";
@@ -258,6 +257,7 @@ import { ChatHeader } from "./chat/ChatHeader";
import { PanelLayoutControls, RightPanelMaximizeControl } from "./chat/PanelLayoutControls";
import { type ExpandedImagePreview } from "./chat/ExpandedImagePreview";
import { NoActiveThreadState } from "./NoActiveThreadState";
import { WorkspacePageHeader } from "./WorkspacePageContainer";
import {
resolveEffectiveEnvMode,
resolveLocalCheckoutBranchMismatch,
@@ -6160,7 +6160,6 @@ function ChatViewContent(props: ChatViewProps) {
? "thread"
: "page"
}
chromeVariant="collapse"
composerDraftTarget={composerDraftTarget}
onStateChange={handlePullRequestTabStatusChange}
/>
@@ -6211,20 +6210,11 @@ function ChatViewContent(props: ChatViewProps) {
data-chat-column-maximized-away={rightPanelMaximized ? "true" : "false"}
>
{/* Top bar */}
<header
<WorkspacePageHeader
data-chat-header
className={cn(
"bg-background transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none",
isElectron
? cn(
"drag-region relative flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center px-3 sm:px-5",
reserveTitleBarControlInset &&
!inlineRightPanelOwnsTitleBar &&
"wco:pr-[var(--workspace-native-controls-inset)]",
)
: "flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center pl-[calc(env(safe-area-inset-left)+0.75rem)] pr-[calc(env(safe-area-inset-right)+0.75rem)] sm:pl-[calc(env(safe-area-inset-left)+1.25rem)] sm:pr-[calc(env(safe-area-inset-right)+1.25rem)]",
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
)}
electron={isElectron}
reserveNativeControls={reserveTitleBarControlInset && !inlineRightPanelOwnsTitleBar}
className="relative bg-background"
>
{!rightPanelOpen ? panelLayoutControls : null}
<ChatHeader
@@ -6255,7 +6245,7 @@ function ChatViewContent(props: ChatViewProps) {
onUpdateProjectScript={updateProjectScript}
onDeleteProjectScript={deleteProjectScript}
/>
</header>
</WorkspacePageHeader>
<ThreadErrorBanner
error={visibleThreadError}
@@ -0,0 +1,33 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vite-plus/test";
import { HeaderFilterMenu } from "./HeaderFilterMenu";
describe("HeaderFilterMenu", () => {
it("uses the shared button contract for its trigger", () => {
const markup = renderToStaticMarkup(
<HeaderFilterMenu
label="Usage metric"
value="cost"
options={[
{ value: "cost", label: "Cost" },
{ value: "tokens", label: "Tokens" },
]}
onChange={() => {}}
/>,
);
expect(markup).toContain('data-slot="menu-trigger"');
expect(markup).toContain("focus-visible:ring-2");
expect(markup).toContain('aria-label="Usage metric"');
expect(markup).toContain("Cost");
});
it("renders nothing when there are no options", () => {
const markup = renderToStaticMarkup(
<HeaderFilterMenu label="Empty filter" value="none" options={[]} onChange={() => {}} />,
);
expect(markup).toBe("");
});
});
@@ -0,0 +1,66 @@
import { ChevronDownIcon } from "lucide-react";
import type { ReactNode } from "react";
import { Button } from "./ui/button";
import { Menu, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "./ui/menu";
export interface HeaderFilterMenuOption<Value extends string> {
value: Value;
label: string;
icon?: ReactNode;
disabledReason?: string;
}
export function HeaderFilterMenu<Value extends string>({
label,
value,
options,
onChange,
align = "start",
popupClassName,
}: {
label: string;
value: Value;
options: ReadonlyArray<HeaderFilterMenuOption<Value>>;
onChange: (value: Value) => void;
align?: "start" | "center" | "end";
popupClassName?: string;
}) {
const current = options.find((option) => option.value === value) ?? options[0];
if (!current) return null;
return (
<Menu>
<MenuTrigger
render={
<Button size="compact" variant="ghost-muted" aria-label={label} className="text-sm" />
}
>
{current.label}
<ChevronDownIcon aria-hidden className="size-3 text-muted-foreground/70" />
</MenuTrigger>
<MenuPopup align={align} side="bottom" className={popupClassName ?? "min-w-40"}>
<MenuRadioGroup value={current.value} onValueChange={(next) => onChange(next as Value)}>
{options.map((option) => (
<MenuRadioItem
key={option.value}
value={option.value}
disabled={option.disabledReason !== undefined}
>
<span className="flex min-w-0 flex-1 items-center gap-2">
<span className="flex min-w-0 items-center gap-2">
{option.icon}
{option.label}
</span>
{option.disabledReason !== undefined ? (
<span className="ms-auto text-xs text-muted-foreground">
{option.disabledReason || "Unavailable"}
</span>
) : null}
</span>
</MenuRadioItem>
))}
</MenuRadioGroup>
</MenuPopup>
</Menu>
);
}
@@ -1,26 +1,15 @@
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "./ui/empty";
import { SidebarInset } from "./ui/sidebar";
import { isElectron } from "../env";
import { cn } from "~/lib/utils";
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
import { WorkspacePageHeader } from "./WorkspacePageContainer";
export function NoActiveThreadState() {
return (
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">
<header
className={cn(
"border-b border-border px-3 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none sm:px-5",
isElectron
? "drag-region flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center"
: "flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center",
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
)}
>
<WorkspacePageHeader electron={isElectron} className="border-b border-border">
{isElectron ? (
<span className="text-xs text-muted-foreground/50 wco:pr-[var(--workspace-native-controls-inset)]">
No active thread
</span>
<span className="text-xs text-muted-foreground/50">No active thread</span>
) : (
<div className="flex items-center gap-2">
<span className="text-sm font-medium text-foreground md:text-muted-foreground/60">
@@ -28,7 +17,7 @@ export function NoActiveThreadState() {
</span>
</div>
)}
</header>
</WorkspacePageHeader>
<Empty className="flex-1">
<div className="w-full max-w-lg px-8 py-12">
@@ -442,6 +442,10 @@ describe("shouldCreateNewThreadInCurrentProject", () => {
expect(shouldCreateNewThreadInCurrentProject(false, 2)).toBe(false);
});
it("creates directly when the sidebar is scoped to a project", () => {
expect(shouldCreateNewThreadInCurrentProject(false, 2, true)).toBe(true);
});
it("creates directly on any click with a single project", () => {
expect(shouldCreateNewThreadInCurrentProject(false, 1)).toBe(true);
expect(shouldCreateNewThreadInCurrentProject(true, 1)).toBe(true);
+2 -1
View File
@@ -299,8 +299,9 @@ export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
export function shouldCreateNewThreadInCurrentProject(
shiftKey: boolean,
projectGroupCount: number,
hasProjectScope = false,
): boolean {
return shiftKey || projectGroupCount <= 1;
return hasProjectScope || shiftKey || projectGroupCount <= 1;
}
export function orderItemsByPreferredIds<TItem, TId>(input: {
+205 -168
View File
@@ -91,6 +91,7 @@ import { useOpenPrLink } from "../lib/openPullRequestLink";
import { readLocalApi } from "../localApi";
import { getProjectOrderKey, selectProjectGroupingSettings } from "../logicalProject";
import {
buildSidebarProjectPickerEntries,
buildSidebarProjectSnapshots,
type SidebarProjectSnapshot,
} from "../sidebarProjectGrouping";
@@ -99,7 +100,7 @@ import { useThreadSelectionStore } from "../threadSelectionStore";
import { useThreadActions } from "../hooks/useThreadActions";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { openCommandPalette } from "../commandPaletteBus";
import { startNewThreadFromContext } from "../lib/chatThreadActions";
import { resolveThreadActionProjectRef, startNewThreadFromContext } from "../lib/chatThreadActions";
import { useClientSettings } from "../hooks/useSettings";
import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
import { useLocalStorage } from "../hooks/useLocalStorage";
@@ -193,6 +194,7 @@ const SETTLED_TAIL_PAGE_COUNT = 25;
// Keep the v2 key so existing preferences survive the v2-to-default rename.
const SETTLED_SHELF_EXPANDED_KEY = "t3code:sidebar-v2:settled-expanded";
const SNOOZED_SHELF_EXPANDED_KEY = "t3code:sidebar-v2:snoozed-expanded";
const SIDEBAR_LIFECYCLE_ICON_CLASS = "size-3 shrink-0";
function compactSidebarTimeLabel(label: string): string {
if (label === "just now") return "now";
@@ -389,26 +391,20 @@ function SnoozePopoverButton(props: {
);
return (
<Popover open={open} onOpenChange={onOpenChange}>
<Tooltip>
<TooltipTrigger
render={
<PopoverTrigger
render={
<button
type="button"
aria-label="Snooze thread"
onClick={(event) => event.stopPropagation()}
onDoubleClick={(event) => event.stopPropagation()}
className="inline-flex h-full cursor-pointer items-center gap-0.5 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground"
/>
}
/>
}
>
<ClockIcon className="size-3" />
</TooltipTrigger>
<TooltipPopup>Snooze thread</TooltipPopup>
</Tooltip>
<PopoverTrigger
render={
<Button
size="icon-micro"
variant="ghost-muted"
aria-label="Snooze thread"
title="Snooze thread"
onClick={(event) => event.stopPropagation()}
onDoubleClick={(event) => event.stopPropagation()}
/>
}
>
<ClockIcon aria-hidden className={SIDEBAR_LIFECYCLE_ICON_CLASS} />
</PopoverTrigger>
<PopoverPopup side="bottom" align="end" className="w-56" viewportClassName="p-1">
{presets.map((preset) => (
<button
@@ -1252,9 +1248,9 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
aria-label="Dismiss Woke notification"
title="Dismiss Woke notification"
onClick={handleAcknowledgeWokeClick}
className="inline-flex cursor-pointer items-center gap-1 rounded-sm text-xs font-medium text-amber-700 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring dark:text-amber-300"
className="inline-flex h-6 cursor-pointer items-center gap-1 rounded-sm text-xs font-medium text-amber-700 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring dark:text-amber-300"
>
<AlarmClockIcon aria-hidden className="size-3" />
<AlarmClockIcon aria-hidden className={SIDEBAR_LIFECYCLE_ICON_CLASS} />
<span role="status">Woke</span>
</button>
) : (
@@ -1267,42 +1263,48 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
</span>
{variantAction === "unsnooze" ? (
!props.snoozeSupported ? null : (
<button
<Button
type="button"
size="icon-micro"
variant="ghost-muted"
aria-label="Wake thread now"
onClick={handleUnsnoozeClick}
className={cn(
"pointer-events-none absolute inset-y-0 right-0 -mr-1 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/sidebar-row:pointer-events-auto group-hover/sidebar-row:opacity-100",
"pointer-events-none absolute inset-y-0 right-0 -mr-1 my-auto opacity-0 transition-opacity focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/sidebar-row:pointer-events-auto group-hover/sidebar-row:opacity-100",
isWoke && "group-hover/sidebar-row:static",
)}
>
<AlarmClockOffIcon className="mb-px size-3" />
</button>
<AlarmClockOffIcon aria-hidden className={SIDEBAR_LIFECYCLE_ICON_CLASS} />
</Button>
)
) : !props.settlementSupported ? null : variantAction === "unsettle" ? (
<button
<Button
type="button"
size="icon-micro"
variant="ghost-muted"
aria-label="Un-settle thread"
onClick={handleUnsettleClick}
className={cn(
"pointer-events-none absolute inset-y-0 right-0 -mr-1 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/sidebar-row:pointer-events-auto group-hover/sidebar-row:opacity-100",
"pointer-events-none absolute inset-y-0 right-0 -mr-1 my-auto opacity-0 transition-opacity focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/sidebar-row:pointer-events-auto group-hover/sidebar-row:opacity-100",
isWoke && "group-hover/sidebar-row:static",
)}
>
<Undo2Icon className="mb-px size-3.5" />
</button>
<Undo2Icon aria-hidden className={SIDEBAR_LIFECYCLE_ICON_CLASS} />
</Button>
) : (
<button
<Button
type="button"
size="icon-micro"
variant="ghost-muted"
aria-label="Settle thread"
onClick={handleSettleClick}
className={cn(
"pointer-events-none absolute inset-y-0 right-0 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-2 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/sidebar-row:pointer-events-auto group-hover/sidebar-row:opacity-100",
"pointer-events-none absolute inset-y-0 right-0 my-auto opacity-0 transition-opacity focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/sidebar-row:pointer-events-auto group-hover/sidebar-row:opacity-100",
isWoke && "group-hover/sidebar-row:static",
)}
>
<CheckIcon className="size-3" />
</button>
<CheckIcon aria-hidden className={SIDEBAR_LIFECYCLE_ICON_CLASS} />
</Button>
)}
</span>
{props.jumpLabel ? <JumpHintBadge label={props.jumpLabel} /> : null}
@@ -1370,130 +1372,129 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
) : (
<span className="flex-1" />
)}
{props.isPinned ? (
props.pinningSupported ? (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label="Unpin thread"
onClick={handleUnpinClick}
className="inline-flex cursor-pointer items-center rounded-sm text-muted-foreground/65 outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
/>
}
<span className="ml-auto flex h-5 shrink-0 items-center">
{props.isPinned ? (
props.pinningSupported ? (
<Button
size="icon-micro"
variant="ghost-muted"
aria-label="Unpin thread"
title="Unpin thread"
onClick={handleUnpinClick}
>
<PinIcon aria-hidden className="size-3 shrink-0" />
</TooltipTrigger>
<TooltipPopup>Unpin thread</TooltipPopup>
</Tooltip>
) : (
<PinIcon
aria-label="Pinned"
role="img"
className="size-3 shrink-0 text-muted-foreground/65"
/>
)
) : null}
{/* The visible state owns this slot's width: status at rest,
actions on hover/keyboard focus or while the popover is open. Keeping
the hidden state out of flow lets the project label reclaim
space without either state overlapping it. */}
<span className="group/sidebar-status-slot relative ml-auto flex h-5 min-w-8 shrink-0 items-stretch justify-end text-xs">
{/* Read-only status labels yield to the hover actions. Woke is
itself an action, so it stays pointer-enabled and visible
while the other controls appear beside it. */}
<PinIcon aria-hidden className={SIDEBAR_LIFECYCLE_ICON_CLASS} />
</Button>
) : (
<span className="inline-flex size-5 shrink-0 items-center justify-center">
<PinIcon
aria-label="Pinned"
role="img"
className={cn(SIDEBAR_LIFECYCLE_ICON_CLASS, "text-muted-foreground")}
/>
</span>
)
) : null}
{/* Only the visible state owns this slot's width: the pin stays
directly beside the idle status and beside the first action
when the hover controls replace it. */}
<span
className={cn(
isWokeStatus
? "pointer-events-auto"
: "pointer-events-none group-has-[:focus-visible]/sidebar-status-slot:absolute group-has-[:focus-visible]/sidebar-status-slot:right-0 group-has-[:focus-visible]/sidebar-status-slot:opacity-0 group-hover/sidebar-row:absolute group-hover/sidebar-row:right-0 group-hover/sidebar-row:opacity-0",
"self-center justify-self-end tabular-nums text-secondary-label transition-opacity",
snoozeMenuOpen && "pointer-events-none absolute right-0 opacity-0",
"group/sidebar-status-slot relative flex h-5 shrink-0 items-stretch justify-end text-xs",
props.isPinned ? "min-w-0" : "min-w-8",
)}
>
{topStatus ? (
isWokeStatus ? (
<button
type="button"
aria-label="Dismiss Woke notification"
title="Dismiss Woke notification"
onClick={handleAcknowledgeWokeClick}
className={cn(
"inline-flex cursor-pointer items-center gap-1 rounded-sm font-medium outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring",
topStatus.className,
)}
>
<AlarmClockIcon aria-hidden className="size-4 shrink-0" />
<span role="status">{topStatus.label}</span>
</button>
) : (
<span
className={cn(
"inline-flex items-center gap-1 font-medium",
topStatus.className,
)}
>
{topStatus.icon === "working" ? (
<CircleDashedIcon aria-hidden className="size-4 shrink-0" />
) : topStatus.icon === "done" ? (
<CircleCheckIcon aria-hidden className="size-4 shrink-0" />
) : null}
{/* The label alone is the live region: a role="status"
wrapper around the ticking duration would make
screen readers announce every second. */}
<span role="status">{topStatus.label}</span>
{status === "working" ? (
<span aria-hidden>
<WorkingDuration startedAt={resolveWorkingStartedAt(thread)} />
</span>
) : null}
</span>
)
) : (
threadTimeLabel(thread)
)}
</span>
{props.settlementSupported || showSnoozeButton ? (
{/* Read-only status labels yield to the hover actions. Woke is
itself an action, so it stays pointer-enabled and visible
while the other controls appear beside it. */}
<span
className={cn(
// focus-visible, not focus-within: a mouse click leaves
// the Settle button focused, and a plain focus-within
// would keep the controls pinned over the status label
// once the pointer moves away (e.g. after a failed
// settle) instead of cross-fading back.
"pointer-events-none absolute inset-y-0 right-0 flex items-stretch opacity-0 transition-opacity has-[:focus-visible]:pointer-events-auto has-[:focus-visible]:static has-[:focus-visible]:opacity-100 group-hover/sidebar-row:pointer-events-auto group-hover/sidebar-row:static group-hover/sidebar-row:opacity-100",
snoozeMenuOpen && "pointer-events-auto static opacity-100",
isWokeStatus
? "pointer-events-auto"
: "pointer-events-none group-has-[:focus-visible]/sidebar-status-slot:absolute group-has-[:focus-visible]/sidebar-status-slot:right-0 group-has-[:focus-visible]/sidebar-status-slot:opacity-0 group-hover/sidebar-row:absolute group-hover/sidebar-row:right-0 group-hover/sidebar-row:opacity-0",
"self-center tabular-nums text-secondary-label transition-opacity",
snoozeMenuOpen && "pointer-events-none absolute right-0 opacity-0",
)}
>
{showSnoozeButton ? (
<SnoozePopoverButton
open={snoozeMenuOpen}
onOpenChange={setSnoozeMenuOpen}
onSnooze={handleSnoozePreset}
timestampFormat={props.timestampFormat}
/>
) : null}
{props.settlementSupported ? (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label="Settle thread"
onClick={handleSettleClick}
className="-mr-1 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground"
/>
}
{topStatus ? (
isWokeStatus ? (
<button
type="button"
aria-label="Dismiss Woke notification"
title="Dismiss Woke notification"
onClick={handleAcknowledgeWokeClick}
className={cn(
"inline-flex h-5 cursor-pointer items-center gap-1 rounded-sm font-medium outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring",
topStatus.className,
)}
>
<CheckIcon className="size-3.5" />
Settle
</TooltipTrigger>
<TooltipPopup>Settle thread</TooltipPopup>
</Tooltip>
) : null}
<AlarmClockIcon aria-hidden className={SIDEBAR_LIFECYCLE_ICON_CLASS} />
<span role="status">{topStatus.label}</span>
</button>
) : (
<span
className={cn(
"inline-flex items-center gap-1 font-medium",
topStatus.className,
)}
>
{topStatus.icon === "working" ? (
<CircleDashedIcon
aria-hidden
className={SIDEBAR_LIFECYCLE_ICON_CLASS}
/>
) : topStatus.icon === "done" ? (
<CircleCheckIcon aria-hidden className={SIDEBAR_LIFECYCLE_ICON_CLASS} />
) : null}
{/* The label alone is the live region: a role="status"
wrapper around the ticking duration would make
screen readers announce every second. */}
<span role="status">{topStatus.label}</span>
{status === "working" ? (
<span aria-hidden>
<WorkingDuration startedAt={resolveWorkingStartedAt(thread)} />
</span>
) : null}
</span>
)
) : (
threadTimeLabel(thread)
)}
</span>
) : null}
{props.settlementSupported || showSnoozeButton ? (
<span
className={cn(
// focus-visible, not focus-within: a mouse click leaves
// the Settle button focused, and a plain focus-within
// would keep the controls pinned over the status label
// once the pointer moves away (e.g. after a failed
// settle) instead of cross-fading back.
"pointer-events-none absolute inset-y-0 right-0 flex items-stretch opacity-0 transition-opacity has-[:focus-visible]:pointer-events-auto has-[:focus-visible]:static has-[:focus-visible]:opacity-100 group-hover/sidebar-row:pointer-events-auto group-hover/sidebar-row:static group-hover/sidebar-row:opacity-100",
snoozeMenuOpen && "pointer-events-auto static opacity-100",
)}
>
{showSnoozeButton ? (
<SnoozePopoverButton
open={snoozeMenuOpen}
onOpenChange={setSnoozeMenuOpen}
onSnooze={handleSnoozePreset}
timestampFormat={props.timestampFormat}
/>
) : null}
{props.settlementSupported ? (
<Button
size="micro"
variant="ghost-muted"
aria-label="Settle thread"
onClick={handleSettleClick}
className="-mr-1 ps-1 pe-1.5"
>
<CheckIcon aria-hidden className={SIDEBAR_LIFECYCLE_ICON_CLASS} />
Settle
</Button>
) : null}
</span>
) : null}
</span>
</span>
</div>
<div className="mt-1 flex min-w-0">
@@ -1901,6 +1902,26 @@ export default function Sidebar() {
: (projectGroups.find((project) => project.projectKey === projectScopeKey) ?? null),
[projectGroups, projectScopeKey],
);
const contextualProjectRef = useMemo(
() =>
resolveThreadActionProjectRef({
activeDraftThread: newThreadContext.activeDraftThread,
activeThread: newThreadContext.activeThread ?? undefined,
defaultProjectRef: newThreadContext.defaultProjectRef,
handleNewThread: newThreadContext.handleNewThread,
}),
[newThreadContext],
);
const scopedProjectTarget = useMemo(
() =>
scopedProjectGroup === null
? null
: (buildSidebarProjectPickerEntries({
groups: [scopedProjectGroup],
preferredProjectRef: contextualProjectRef,
})[0]?.targetProject ?? null),
[contextualProjectRef, scopedProjectGroup],
);
const scopedProjectKeys = useMemo(
() =>
scopedProjectGroup === null
@@ -3301,17 +3322,25 @@ export default function Sidebar() {
autoAnimate(node, { duration: 150, easing: "ease-out" });
}, []);
// New thread defaults to the project you're in (active thread's project,
// falling back to the top project) — same resolution the command palette
// uses. The command palette already offers a "New thread in..." submenu
// for multi-project setups.
// A selected project scope owns creation: users should not have to choose
// the same project twice. "All projects" keeps the picker in multi-project
// setups, while Shift+click retains the direct-create shortcut.
const handleNewThreadClick = useCallback(
(event?: ReactMouseEvent) => {
// One project: nothing to pick, create immediately. Shift+click creates
// directly in the current project even with several projects, skipping
// the palette picker.
if (shouldCreateNewThreadInCurrentProject(event?.shiftKey ?? false, projectGroups.length)) {
if (
shouldCreateNewThreadInCurrentProject(
event?.shiftKey ?? false,
projectGroups.length,
scopedProjectGroup !== null,
)
) {
if (isMobile) setOpenMobile(false);
if (scopedProjectTarget) {
void newThreadContext.handleNewThread(
scopeProjectRef(scopedProjectTarget.environmentId, scopedProjectTarget.id),
);
return;
}
void startNewThreadFromContext({
activeDraftThread: newThreadContext.activeDraftThread,
activeThread: newThreadContext.activeThread ?? undefined,
@@ -3323,20 +3352,26 @@ export default function Sidebar() {
if (isMobile) setOpenMobile(false);
openCommandPalette({ open: "new-thread-in" });
},
[isMobile, newThreadContext, projectGroups.length, setOpenMobile],
[
isMobile,
newThreadContext,
projectGroups.length,
scopedProjectGroup,
scopedProjectTarget,
setOpenMobile,
],
);
// The button mirrors chat.new: in multi-project setups both route through
// the command palette's "New thread in..." picker, and in single-project
// setups both create immediately. In multi-project setups the label is only
// the picker's shortcut: falling back to chat.newLocal would advertise the
// same shortcut for both the picker and direct create. In single-project
// setups both commands create directly, so chat.newLocal is a valid
// fallback. The second tooltip line (multi-project only) advertises
// shift+click and its keyboard twin chat.newLocal for direct create.
// With no explicit scope the button mirrors chat.new. A scoped button has
// intentionally more specific behavior, so it does not advertise the
// broader command's shortcut.
const newThreadShortcutLabel =
shortcutLabelForCommand(keybindings, "chat.new") ??
(projectGroups.length <= 1 ? shortcutLabelForCommand(keybindings, "chat.newLocal") : undefined);
scopedProjectGroup === null
? (shortcutLabelForCommand(keybindings, "chat.new") ??
(projectGroups.length <= 1
? shortcutLabelForCommand(keybindings, "chat.newLocal")
: undefined))
: undefined;
const newThreadInProjectShortcutLabel = shortcutLabelForCommand(keybindings, "chat.newLocal");
return (
<>
@@ -3415,7 +3450,9 @@ export default function Sidebar() {
/>
</TooltipTrigger>
<TooltipPopup side="right">
{projectGroups.length > 1 ? (
{scopedProjectGroup ? (
`New thread in ${scopedProjectGroup.displayName}`
) : projectGroups.length > 1 ? (
<span className="flex flex-col gap-0.5">
<span>
{newThreadShortcutLabel
@@ -45,9 +45,9 @@ export function WorkspaceBreadcrumbItem({
);
}
export function WorkspaceBreadcrumbSeparator() {
export function WorkspaceBreadcrumbSeparator({ className }: { readonly className?: string }) {
return (
<li aria-hidden="true" className="flex shrink-0 items-center text-icon-muted">
<li aria-hidden="true" className={cn("flex shrink-0 items-center text-icon-muted", className)}>
/
</li>
);
@@ -0,0 +1,62 @@
import type { ComponentPropsWithoutRef } from "react";
import { cn } from "../lib/utils";
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "../workspaceTitlebar";
export type WorkspacePageWidth = "readable" | "wide" | "expanded";
const WIDTH_CLASS: Record<WorkspacePageWidth, string> = {
readable: "max-w-4xl",
wide: "max-w-5xl",
expanded: "max-w-6xl",
};
/** Shared full-page frame for workspace routes beneath their top bar. */
export function WorkspacePageContainer({
width = "readable",
className,
...props
}: ComponentPropsWithoutRef<"div"> & { readonly width?: WorkspacePageWidth }) {
return (
<div
className={cn(
"mx-auto flex w-full flex-col gap-6 px-5 pt-6 pb-12 sm:px-6",
WIDTH_CLASS[width],
className,
)}
{...props}
/>
);
}
/** Shared top-bar geometry for every full-width workspace surface. */
export function WorkspacePageHeader({
electron = false,
reserveNativeControls = electron,
className,
...props
}: ComponentPropsWithoutRef<"header"> & {
readonly electron?: boolean;
readonly reserveNativeControls?: boolean;
}) {
return (
<header
className={cn(
"flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center gap-3 pl-[calc(env(safe-area-inset-left)+0.75rem)] pr-[calc(env(safe-area-inset-right)+0.75rem)] transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none sm:pl-[calc(env(safe-area-inset-left)+1.25rem)] sm:pr-[calc(env(safe-area-inset-right)+1.25rem)]",
electron && "drag-region",
reserveNativeControls && "wco:pr-[var(--workspace-native-controls-inset)]",
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
className,
)}
{...props}
/>
);
}
/** Keeps an icon glyph on the content edge while its larger hit target extends outward. */
export function WorkspacePageHeaderEdgeControl({
className,
...props
}: ComponentPropsWithoutRef<"div">) {
return <div className={cn("-me-[7px] flex shrink-0", className)} {...props} />;
}
@@ -12,6 +12,7 @@ interface PanelLayoutControlsProps {
rightPanelAvailable: boolean;
rightPanelOpen: boolean;
rightPanelShortcutLabel: string | null;
rightPanelUnavailableLabel?: string;
/** Running + waiting subagents in this thread; badges the right panel toggle. */
liveAgentCount: number;
onToggleTerminal: () => void;
@@ -26,6 +27,7 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({
rightPanelAvailable,
rightPanelOpen,
rightPanelShortcutLabel,
rightPanelUnavailableLabel = "Right panel is unavailable",
liveAgentCount,
onToggleTerminal,
onToggleRightPanel,
@@ -94,7 +96,7 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({
? ` · ${liveAgentCount} ${liveAgentCount === 1 ? "agent" : "agents"} working`
: ""
}`
: "Right panel is unavailable"}
: rightPanelUnavailableLabel}
</TooltipPopup>
</Tooltip>
</div>
@@ -2,7 +2,7 @@
// composer honors the prompt font-size preference). The chat variant pins the
// original 12px, where every em value resolves to the same pixels as before.
const INLINE_CHIP_CLASS_NAME =
"inline-flex max-w-full items-center gap-[0.33em] rounded-[0.5em] border border-border/70 bg-accent/40 px-[0.5em] py-[0.08em] font-medium leading-[1.1] text-foreground align-middle";
"inline-flex h-[1.41em] max-w-full items-center gap-[0.33em] rounded-[0.5em] border border-border/70 bg-accent/40 px-[0.5em] font-medium leading-none text-foreground align-middle";
export const CHAT_INLINE_CHIP_CLASS_NAME = `${INLINE_CHIP_CLASS_NAME} text-[12px]`;
@@ -11,18 +11,18 @@ export const COMPOSER_INLINE_CHIP_CLASS_NAME = `${INLINE_CHIP_CLASS_NAME} text-[
export const COMPOSER_INLINE_CHIP_DECORATOR_CLASS_NAME =
"relative inline-flex align-[-0.125em] leading-none data-[composer-chip-selected]:after:pointer-events-none data-[composer-chip-selected]:after:absolute data-[composer-chip-selected]:after:inset-0 data-[composer-chip-selected]:after:rounded-[6px] data-[composer-chip-selected]:after:bg-[Highlight] data-[composer-chip-selected]:after:opacity-30 data-[composer-chip-selected]:after:content-['']";
export const COMPOSER_INLINE_CHIP_ICON_CLASS_NAME = "size-[1.17em] shrink-0 opacity-85";
export const COMPOSER_INLINE_CHIP_ICON_CLASS_NAME =
"block size-[1.17em] shrink-0 self-center opacity-85 [&>svg]:block";
export const CHAT_INLINE_CHIP_LABEL_CLASS_NAME = "truncate leading-tight";
export const COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME = `${CHAT_INLINE_CHIP_LABEL_CLASS_NAME} select-none`;
export const COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME =
"block self-center truncate leading-none select-none";
// The skill label is smaller than the surrounding prompt text; offset its
// glyphs without moving the pill box or changing the editor's line height.
export const COMPOSER_INLINE_SKILL_CHIP_LABEL_CLASS_NAME = `${COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME} relative top-[0.15em]`;
export const COMPOSER_INLINE_SKILL_CHIP_LABEL_CLASS_NAME = COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME;
export const COMPOSER_INLINE_SKILL_CHIP_CLASS_NAME =
"inline-flex max-w-full select-none items-center gap-[0.33em] rounded-[0.5em] border border-fuchsia-500/25 bg-fuchsia-500/12 px-[0.5em] py-[0.08em] font-medium text-[0.86em] leading-[1.1] text-fuchsia-700 align-middle dark:text-fuchsia-300";
"inline-flex h-[1.41em] max-w-full select-none items-center gap-[0.33em] rounded-[0.5em] border border-fuchsia-500/25 bg-fuchsia-500/12 px-[0.5em] font-medium text-[0.86em] leading-none text-fuchsia-700 align-middle dark:text-fuchsia-300";
export const SKILL_CHIP_ICON_SVG = `<svg width="100%" height="100%" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.85" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></svg>`;
File diff suppressed because it is too large. Load diff
@@ -45,13 +45,11 @@ export function PullRequestListGhost({
<GhostBar className="size-4 rounded-full" />
<div className="min-w-0 space-y-1.5">
<GhostBar className={cn("h-3.5", TITLE_WIDTHS[index % TITLE_WIDTHS.length])} />
<GhostBar
className={cn("bg-muted-foreground/10", META_WIDTHS[index % META_WIDTHS.length])}
/>
<GhostBar className={META_WIDTHS[index % META_WIDTHS.length]} />
</div>
<div className="flex flex-col items-end gap-1.5">
<GhostBar className="w-12" />
<GhostBar className="w-16 bg-muted-foreground/10" />
<GhostBar className="w-16" />
</div>
</div>
))}
@@ -59,32 +57,101 @@ export function PullRequestListGhost({
);
}
/** The summary's own shape: a title, a byline, the facts rows, the description. */
/**
* The detail panel's current expanded shape. Keeping the chrome, summary facts, and description
* boundaries in the ghost prevents the loaded pull request from replacing one layout with
* another a moment later.
*/
export function PullRequestDetailGhost() {
return (
<div
role="status"
aria-label="Loading pull request"
className="animate-ghost-pulse space-y-6 px-4 py-5"
className="animate-ghost-pulse flex h-full min-h-0 flex-col overflow-hidden bg-background"
>
<div className="space-y-2">
<GhostBar className="h-5 w-4/5" />
<GhostBar className="w-2/5 bg-muted-foreground/10" />
</div>
<div className="space-y-3">
{Array.from({ length: 4 }, (_, index) => (
<div key={index} className="flex items-center gap-3">
<GhostBar className="size-3.5 rounded-full" />
<GhostBar className="w-20 bg-muted-foreground/10" />
<GhostBar className={TITLE_WIDTHS[(index + 1) % TITLE_WIDTHS.length]} />
<div className="shrink-0 border-b border-border/60">
<div className="flex h-7 items-center justify-between gap-3 px-4">
<div className="flex min-w-0 flex-1 items-center gap-1.5">
<GhostBar className="w-24" />
<GhostBar className="w-9" />
</div>
))}
<div className="flex shrink-0 items-center gap-1">
<GhostBar className="h-5 w-16 rounded-md" />
<GhostBar className="size-5 rounded-md" />
</div>
</div>
<div className="px-4 pb-4 pt-1">
<GhostBar className="h-5 w-4/5 max-w-md" />
<div className="mt-2 flex items-center gap-1.5">
<GhostBar className="size-4 rounded-full" />
<GhostBar className="w-24" />
</div>
<div className="mt-4 flex min-w-0 items-center gap-2">
<GhostBar className="h-6 w-24 rounded-md" />
<GhostBar className="size-3 rounded-full" />
<GhostBar className="h-6 w-32 rounded-md" />
<div className="ml-auto flex shrink-0 items-center gap-2">
<GhostBar className="w-10" />
<GhostBar className="w-20" />
</div>
</div>
</div>
<div className="flex min-h-10 items-center justify-between gap-3 border-t border-border/60 px-4 py-2">
<div className="flex items-center gap-1 p-0.5">
<GhostBar className="h-6 w-16 rounded-md" />
<GhostBar className="h-6 w-16 rounded-md" />
<GhostBar className="h-6 w-12 rounded-md" />
</div>
<GhostBar className="w-20" />
</div>
</div>
<div className="space-y-2 pt-1">
<GhostBar className="w-full bg-muted-foreground/10" />
<GhostBar className="w-11/12 bg-muted-foreground/10" />
<GhostBar className="w-4/5 bg-muted-foreground/10" />
<GhostBar className="w-2/3 bg-muted-foreground/10" />
<div className="min-h-0 flex-1 overflow-hidden">
<section className="px-4 py-3">
<div className="grid min-h-8 grid-cols-[6rem_minmax(0,1fr)] items-center gap-2">
<div className="flex items-center gap-1.5">
<GhostBar className="size-3.5 rounded-full" />
<GhostBar className="w-14" />
</div>
<div className="flex items-center gap-1">
<GhostBar className="size-4 rounded-full" />
<GhostBar className="size-4 rounded-full" />
<GhostBar className="ml-1 size-5 rounded-md" />
</div>
</div>
<div className="grid min-h-8 grid-cols-[6rem_minmax(0,1fr)] items-center gap-2">
<div className="flex items-center gap-1.5">
<GhostBar className="size-3.5 rounded-full" />
<GhostBar className="w-10" />
</div>
<div className="flex items-center gap-1">
<GhostBar className="h-5 w-24 rounded-full" />
<GhostBar className="h-5 w-20 rounded-full" />
</div>
</div>
<div className="grid min-h-8 grid-cols-[6rem_minmax(0,1fr)] items-center gap-2">
<div className="flex items-center gap-1.5">
<GhostBar className="size-3.5 rounded-full" />
<GhostBar className="w-14" />
</div>
<GhostBar className="w-20" />
</div>
</section>
<section className="border-t border-border/60">
<div className="flex min-h-11 items-center gap-1.5 px-4 py-3">
<GhostBar className="h-4 w-24" />
<GhostBar className="size-3.5 rounded-full" />
</div>
<div className="space-y-2 px-4 pb-4">
<GhostBar className="w-full" />
<GhostBar className="w-11/12" />
<GhostBar className="w-4/5" />
<GhostBar className="w-2/3" />
</div>
</section>
</div>
</div>
);
@@ -113,7 +180,7 @@ export function PullRequestTimelineGhost({ rows = 6 }: { rows?: number }) {
<div key={index} className="relative pb-5">
<GhostBar className="absolute -left-[1.55rem] top-1 size-2 rounded-full" />
<GhostBar className={cn("h-3.5", TITLE_WIDTHS[index % TITLE_WIDTHS.length])} />
<GhostBar className="mt-1.5 w-16 bg-muted-foreground/10" />
<GhostBar className="mt-1.5 w-16" />
</div>
))}
</div>
@@ -134,8 +201,8 @@ export function PullRequestConversationGhost({ rows = 3 }: { rows?: number }) {
<GhostBar className="size-5 shrink-0 rounded-full" />
<div className="flex-1 space-y-1.5">
<GhostBar className={META_WIDTHS[index % META_WIDTHS.length]} />
<GhostBar className="w-full bg-muted-foreground/10" />
<GhostBar className="w-3/4 bg-muted-foreground/10" />
<GhostBar className="w-full" />
<GhostBar className="w-3/4" />
</div>
</div>
))}
@@ -25,6 +25,7 @@ import { cn } from "~/lib/utils";
import { getSourceControlPresentationForKind } from "~/sourceControlPresentation";
import { ProjectFavicon } from "../ProjectFavicon";
import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group";
import { Button } from "../ui/button";
import {
Menu,
@@ -261,12 +262,14 @@ export function PullRequestFiltersMenu({
return (
<Menu>
<MenuTrigger
className={cn(
// The icon-button size that pairs with a full-height input, so the two read as one strip.
"relative inline-flex size-9 shrink-0 items-center justify-center rounded-lg border border-input text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground sm:size-8",
filtered && "text-foreground",
)}
aria-label="Filter pull requests"
render={
<Button
className={cn("relative", filtered && "[--control-icon-color:currentColor]")}
size="icon"
variant="outline"
aria-label="Filter pull requests"
/>
}
>
<ListFilterIcon className="size-4" />
{filtered ? (
@@ -196,12 +196,12 @@ function MetaRow({
children: ReactNode;
}) {
return (
<div className="flex items-center gap-2 py-1.5 text-xs">
<span className="flex w-24 shrink-0 items-center gap-1.5 text-muted-foreground">
<div className="grid min-h-8 grid-cols-[6rem_minmax(0,1fr)] items-center gap-2 py-1.5 text-xs">
<span className="flex min-w-0 items-center gap-1.5 text-muted-foreground">
{icon}
{label}
</span>
<span className="min-w-0 flex-1 text-foreground">{children}</span>
<span className="min-w-0 text-foreground">{children}</span>
</div>
);
}
@@ -16,6 +16,7 @@ import {
groupPullRequestTimelineConversations,
handoffPrompt,
handoffReviewComments,
isStackedPullRequestBase,
isThreadOwnPullRequest,
orderPullRequestComments,
pullRequestActionMenuHasGroup,
@@ -101,6 +102,47 @@ describe("pull request composer target", () => {
});
});
describe("stacked pull request classification", () => {
it("requires a known default branch", () => {
expect(isStackedPullRequestBase("main", [{ name: "main", isDefault: false }])).toBe(false);
});
it("recognizes local and remote forms of the default branch", () => {
expect(
isStackedPullRequestBase("main", [{ name: "main", isDefault: true, isRemote: false }]),
).toBe(false);
expect(
isStackedPullRequestBase("main", [
{ name: "origin/main", isDefault: true, isRemote: true, remoteName: "origin" },
]),
).toBe(false);
});
it("classifies a non-default base as stacked once the default is known", () => {
expect(
isStackedPullRequestBase("feature-base", [
{ name: "origin/main", isDefault: true, isRemote: true, remoteName: "origin" },
]),
).toBe(true);
});
it("does not mistake a nested branch suffix for the default branch", () => {
expect(
isStackedPullRequestBase("main", [
{
name: "origin/feature/main",
isDefault: true,
isRemote: true,
remoteName: "origin",
},
]),
).toBe(true);
expect(
isStackedPullRequestBase("1.0", [{ name: "release/1.0", isDefault: true, isRemote: false }]),
).toBe(true);
});
});
describe("ordering comments", () => {
it("reverses the chronological list for newest first, and leaves oldest first alone", () => {
const comments = [{ createdAt: "a" }, { createdAt: "b" }, { createdAt: "c" }];
@@ -10,6 +10,7 @@ import type {
PullRequestReviewThread,
PullRequestState,
PullRequestUpdateMethod,
VcsRef,
} from "@t3tools/contracts";
import { inferReviewCommentFenceLanguage, type ReviewCommentContext } from "~/reviewCommentContext";
@@ -73,6 +74,20 @@ export function pullRequestActionMenuHasGroup(
return showsDraftToggle || showsAutoMerge || showsMergeMethods;
}
export function isStackedPullRequestBase(
baseBranch: string,
refs: ReadonlyArray<Pick<VcsRef, "name" | "isDefault" | "isRemote" | "remoteName">>,
): boolean {
const defaultRef = refs.find((refName) => refName.isDefault);
if (!defaultRef) return false;
if (defaultRef.isRemote !== true) return defaultRef.name !== baseBranch;
const remotePrefix = `${defaultRef.remoteName ?? defaultRef.name.split("/")[0]}/`;
const defaultBranch = defaultRef.name.startsWith(remotePrefix)
? defaultRef.name.slice(remotePrefix.length)
: defaultRef.name;
return defaultBranch !== baseBranch;
}
/** Plain-language state, shown beside the author. Conflicts are a merge signal, not a state. */
export function describePullRequestState(state: PullRequestState, isDraft: boolean): string {
if (state === "merged") return "Merged";
@@ -992,7 +992,7 @@ export function DiagnosticsSettingsPanel() {
: false;
return (
<SettingsPageContainer className="max-w-6xl gap-10">
<SettingsPageContainer width="expanded" className="gap-10">
<ResourceTelemetryDiagnostics />
<SettingsSection
@@ -1195,7 +1195,7 @@ export function KeybindingsSettingsPanel() {
);
return (
<SettingsPageContainer className="max-w-5xl">
<SettingsPageContainer width="wide">
<SettingsSection
{...searchableSetting("keybindings")}
headerAction={
@@ -81,8 +81,6 @@ import {
type NewProjectScriptInput,
type ProjectScriptEditorRequest,
} from "../projectScriptEditor";
import { cn } from "../../lib/utils";
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "../../workspaceTitlebar";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import {
@@ -102,6 +100,7 @@ import {
WorkspaceBreadcrumbItem,
WorkspaceBreadcrumbSeparator,
} from "../WorkspaceBreadcrumb";
import { WorkspacePageHeader } from "../WorkspacePageContainer";
import {
SettingResetButton,
SettingsPageContainer,
@@ -174,26 +173,9 @@ export function ProjectSettingsPage({ projectKey }: { projectKey: string }) {
return (
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
{!isElectron && (
<header
className={cn(
"flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center px-3 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none sm:px-5",
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
)}
>
<ProjectSettingsBreadcrumb projectKey={projectKey} />
</header>
)}
{isElectron && (
<div
className={cn(
"drag-region flex h-[52px] shrink-0 items-center px-5 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none wco:h-[env(titlebar-area-height)] wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]",
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
)}
>
<ProjectSettingsBreadcrumb projectKey={projectKey} />
</div>
)}
<WorkspacePageHeader electron={isElectron}>
<ProjectSettingsBreadcrumb projectKey={projectKey} />
</WorkspacePageHeader>
<ProjectSettingsPanel projectKey={projectKey} />
</div>
</SidebarInset>
@@ -9,7 +9,6 @@ import {
} from "react";
import {
ArchiveIcon,
ArrowLeftIcon,
BotIcon,
GitBranchIcon,
KeyboardIcon,
@@ -19,7 +18,7 @@ import {
Settings2Icon,
XIcon,
} from "lucide-react";
import { useCanGoBack, useLocation, useNavigate } from "@tanstack/react-router";
import { useLocation, useNavigate } from "@tanstack/react-router";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
@@ -34,6 +33,7 @@ import {
useSidebar,
} from "../ui/sidebar";
import { T3ConnectSidebarAvatar, T3ConnectSidebarSignIn } from "../clerk/T3ConnectSidebarSignIn";
import { SidebarUtilityMenu } from "../sidebar/SidebarChrome";
import { scrollToSettingsTarget } from "./settingsLayout";
import {
searchSettings,
@@ -72,7 +72,6 @@ function SettingsSectionIcon({ to }: { to: SettingsPath }) {
export function SettingsSidebarNav({ pathname }: { pathname: string }) {
const navigate = useNavigate();
const currentHash = useLocation({ select: (location) => location.hash });
const canGoBack = useCanGoBack();
const { isMobile, setOpenMobile, open, setOpen } = useSidebar();
const searchInputRef = useRef<HTMLInputElement>(null);
const [query, setQuery] = useState("");
@@ -176,17 +175,6 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
},
[activeResultIndex, clearSearch, handleSearchResultClick, isSearching, results],
);
const handleBackClick = useCallback(() => {
if (isMobile) {
setOpenMobile(false);
}
if (canGoBack) {
window.history.back();
return;
}
void navigate({ to: "/" });
}, [canGoBack, isMobile, navigate, setOpenMobile]);
return (
<>
<SidebarContent className="overflow-x-hidden">
@@ -296,14 +284,9 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
<SidebarFooter className="p-[var(--sidebar-content-inset)]">
<T3ConnectSidebarSignIn />
<div className="flex items-center gap-1">
<SidebarMenu className="min-w-0 flex-1">
<SidebarMenuItem>
<SidebarMenuButton onClick={handleBackClick}>
<ArrowLeftIcon />
<span>Back</span>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
<div className="min-w-0 flex-1">
<SidebarUtilityMenu />
</div>
<T3ConnectSidebarAvatar />
</div>
</SidebarFooter>
@@ -768,7 +768,7 @@ export function ThemeLibrary({
<TooltipProvider>
<div
className="mx-auto grid w-full max-w-[56rem] gap-2 px-3 sm:px-4"
style={{ gridTemplateColumns: "repeat(auto-fit, minmax(min(100%, 17rem), 1fr))" }}
style={{ gridTemplateColumns: "repeat(auto-fit, minmax(min(100%, 16rem), 1fr))" }}
>
{STANDARD_THEME_CARDS.map((standardTheme) => (
<ThemeLibraryCard
@@ -12,6 +12,7 @@ import {
} from "react";
import { cn } from "../../lib/utils";
import { WorkspacePageContainer, type WorkspacePageWidth } from "../WorkspacePageContainer";
import { Button } from "../ui/button";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
@@ -233,9 +234,11 @@ export function SettingResetButton({
export function SettingsPageContainer({
children,
className,
width = "readable",
}: {
children: ReactNode;
className?: string;
width?: WorkspacePageWidth;
}) {
const navigate = useNavigate();
const hash = useLocation({ select: (location) => location.hash });
@@ -247,12 +250,12 @@ export function SettingsPageContainer({
return (
<SettingsSearchTargetProvider targetId={targetId} onTargetHandled={clearTargetHash}>
<div
className="topbar-scroll-fade scrollbar-gutter-both flex-1 overflow-y-auto px-4 pt-10 pb-7 sm:px-8 sm:pt-12 sm:pb-10"
className="topbar-scroll-fade scrollbar-gutter-both flex-1 overflow-y-auto [--topbar-scroll-fade-height:1.5rem] sm:[--topbar-scroll-fade-height:1.5rem]"
data-settings-page-scroll
>
<div className={cn("mx-auto flex w-full max-w-4xl flex-col gap-12", className)}>
<WorkspacePageContainer width={width} className={cn("gap-12", className)}>
{children}
</div>
</WorkspacePageContainer>
</div>
</SettingsSearchTargetProvider>
);
@@ -4,8 +4,9 @@ import {
GitPullRequestIcon,
SettingsIcon,
} from "lucide-react";
import type { ReactNode } from "react";
import { memo, useCallback } from "react";
import { Link, useLocation, useNavigate } from "@tanstack/react-router";
import { Link, useCanGoBack, useLocation, useNavigate } from "@tanstack/react-router";
import { useEnvironmentIdentificationMode } from "../../hooks/useSettings";
import { cn } from "../../lib/utils";
@@ -117,16 +118,44 @@ function T3Wordmark() {
);
}
export const SidebarChromeFooter = memo(function SidebarChromeFooter() {
function SidebarUtilityItem({
icon,
label,
onClick,
}: {
icon: ReactNode;
label: string;
onClick: () => void;
}) {
return (
<SidebarMenuItem className="shrink-0">
<Tooltip>
<TooltipTrigger
render={
<SidebarMenuButton aria-label={label} onClick={onClick} size="icon">
{icon}
</SidebarMenuButton>
}
/>
<TooltipPopup side="top">{label}</TooltipPopup>
</Tooltip>
</SidebarMenuItem>
);
}
export const SidebarUtilityMenu = memo(function SidebarUtilityMenu() {
const navigate = useNavigate();
const canGoBack = useCanGoBack();
const { isMobile, setOpenMobile } = useSidebar();
const currentFooterPage = useLocation({
select: (location) =>
location.pathname === "/usage"
? "usage"
: location.pathname === "/pull-requests"
? "pull-requests"
: null,
/^\/settings(?:\/|$)/.test(location.pathname)
? "settings"
: location.pathname === "/usage"
? "usage"
: location.pathname === "/pull-requests"
? "pull-requests"
: null,
});
const { environments } = useEnvironments();
// The page reads every connected server, so one of them offering pull requests is enough for
@@ -157,73 +186,54 @@ export const SidebarChromeFooter = memo(function SidebarChromeFooter() {
const handleBackClick = useCallback(() => {
closeMobileSidebar();
if (canGoBack) {
window.history.back();
return;
}
void navigate({ to: "/" });
}, [closeMobileSidebar, navigate]);
}, [canGoBack, closeMobileSidebar, navigate]);
return (
<SidebarMenu className="flex-row items-center">
{currentFooterPage ? (
<SidebarMenuItem className="min-w-0 flex-1">
<SidebarMenuButton onClick={handleBackClick}>
<ArrowLeftIcon />
<span>Back</span>
</SidebarMenuButton>
</SidebarMenuItem>
) : (
<>
<SidebarUtilityItem
icon={<SettingsIcon />}
label="Settings"
onClick={handleSettingsClick}
/>
{pullRequestsSupported ? (
<SidebarUtilityItem
icon={<GitPullRequestIcon />}
label="Pull Requests"
onClick={handlePullRequestsClick}
/>
) : null}
<SidebarUtilityItem
icon={<ChartNoAxesColumnIcon />}
label="Usage"
onClick={handleUsageClick}
/>
</>
)}
<SidebarUpdatePill />
</SidebarMenu>
);
});
export const SidebarChromeFooter = memo(function SidebarChromeFooter() {
return (
<SidebarFooter className="p-[var(--sidebar-content-inset)]">
<SidebarProviderUpdatePill />
<SidebarUpdateArchitectureWarning />
<SidebarMenu className="flex-row items-center">
{currentFooterPage ? (
<SidebarMenuItem className="min-w-0 flex-1">
<SidebarMenuButton onClick={handleBackClick}>
<ArrowLeftIcon />
<span>Back</span>
</SidebarMenuButton>
</SidebarMenuItem>
) : (
<>
<SidebarMenuItem className="shrink-0">
<Tooltip>
<TooltipTrigger
render={
<SidebarMenuButton
aria-label="Settings"
onClick={handleSettingsClick}
size="icon"
>
<SettingsIcon />
</SidebarMenuButton>
}
/>
<TooltipPopup side="top">Settings</TooltipPopup>
</Tooltip>
</SidebarMenuItem>
{pullRequestsSupported ? (
<SidebarMenuItem className="shrink-0">
<Tooltip>
<TooltipTrigger
render={
<SidebarMenuButton
aria-label="Pull Requests"
onClick={handlePullRequestsClick}
size="icon"
>
<GitPullRequestIcon />
</SidebarMenuButton>
}
/>
<TooltipPopup side="top">Pull Requests</TooltipPopup>
</Tooltip>
</SidebarMenuItem>
) : null}
<SidebarMenuItem className="shrink-0">
<Tooltip>
<TooltipTrigger
render={
<SidebarMenuButton aria-label="Usage" onClick={handleUsageClick} size="icon">
<ChartNoAxesColumnIcon />
</SidebarMenuButton>
}
/>
<TooltipPopup side="top">Usage</TooltipPopup>
</Tooltip>
</SidebarMenuItem>
</>
)}
<SidebarUpdatePill />
</SidebarMenu>
<SidebarUtilityMenu />
</SidebarFooter>
);
});
@@ -20,6 +20,12 @@ function ids(state: ThreadActionMenuState): string[] {
return buildThreadActionMenuItems(state).map((item) => item.id);
}
function allIds(state: ThreadActionMenuState): string[] {
const flatten = (items: ReturnType<typeof buildThreadActionMenuItems>): string[] =>
items.flatMap((item) => [item.id, ...(item.children ? flatten(item.children) : [])]);
return flatten(buildThreadActionMenuItems(state));
}
describe("buildThreadActionMenuItems", () => {
it("hides lifecycle items when the environment lacks the capabilities", () => {
expect(
@@ -27,15 +33,15 @@ describe("buildThreadActionMenuItems", () => {
...baseState,
supports: { settlement: false, snooze: false, pinning: false, titleRegeneration: false },
}),
).toEqual(["rename", "mark-unread", "copy-path", "copy-thread-id", "archive", "delete"]);
).toEqual(["rename", "mark-unread", "copy", "archive", "delete"]);
});
it("includes branch items only for threads with a branch", () => {
const withBranch = ids({ ...baseState, branch: "feat/menu" });
const withBranch = allIds({ ...baseState, branch: "feat/menu" });
expect(withBranch).toContain("new-thread-on-branch");
expect(withBranch).toContain("copy-branch");
expect(ids(baseState)).not.toContain("new-thread-on-branch");
expect(ids(baseState)).not.toContain("copy-branch");
expect(allIds(baseState)).not.toContain("new-thread-on-branch");
expect(allIds(baseState)).not.toContain("copy-branch");
});
it("flips lifecycle labels with thread state", () => {
@@ -64,7 +70,6 @@ describe("buildThreadActionMenuItems", () => {
const items = buildThreadActionMenuItems({ ...baseState, branch: "main" });
expect(items.at(-1)).toMatchObject({ id: "delete", destructive: true });
});
it("offers archive as a non-destructive action right before delete", () => {
const items = buildThreadActionMenuItems(baseState);
const archiveItem = items.at(-2);
@@ -18,6 +18,7 @@ export type ThreadActionMenuId =
| "rename"
| "regenerate-title"
| "mark-unread"
| "copy"
| "copy-path"
| "copy-branch"
| "copy-thread-id"
@@ -56,14 +57,15 @@ export function buildThreadActionMenuItems(
{
id: "new-thread-on-branch" as const,
label: `New thread on ${state.branch}`,
icon: "message-square-plus",
},
]
: []),
...(state.supports.pinning
? [
state.isPinned
? { id: "unpin" as const, label: "Unpin thread" }
: { id: "pin" as const, label: "Pin thread" },
? { id: "unpin" as const, label: "Unpin thread", icon: "pin-off" }
: { id: "pin" as const, label: "Pin thread", icon: "pin" },
]
: []),
// Both lifecycle actions stay available on pinned threads: settling
@@ -72,17 +74,18 @@ export function buildThreadActionMenuItems(
...(state.supports.settlement
? [
state.isSettled
? { id: "unsettle" as const, label: "Un-settle thread" }
: { id: "settle" as const, label: "Settle thread" },
? { id: "unsettle" as const, label: "Un-settle thread", icon: "circle-check" }
: { id: "settle" as const, label: "Settle thread", icon: "circle-check" },
]
: []),
...(state.supports.snooze
? [
state.isSnoozed
? { id: "unsnooze" as const, label: "Wake thread" }
? { id: "unsnooze" as const, label: "Wake thread", icon: "clock" }
: {
id: "snooze" as const,
label: "Snooze",
icon: "clock",
disabled: !state.canSnoozeNow,
children: state.snoozePresets.map((preset) => ({
id: `snooze:${preset.id}` as const,
@@ -91,26 +94,48 @@ export function buildThreadActionMenuItems(
},
]
: []),
{ id: "rename", label: "Rename thread" },
{ id: "rename", label: "Rename thread", icon: "pencil", separatorBefore: true },
...(state.supports.titleRegeneration
? [
{
id: "regenerate-title" as const,
label: state.isRegeneratingTitle ? "Regenerating…" : "Regenerate title",
icon: "refresh-cw",
disabled: state.isRegeneratingTitle,
},
]
: []),
{ id: "mark-unread", label: "Mark unread" },
{ id: "copy-path", label: "Copy path", icon: "copy" },
...(state.branch ? [{ id: "copy-branch" as const, label: "Copy branch", icon: "copy" }] : []),
{ id: "copy-thread-id", label: "Copy thread ID", icon: "copy" },
{ id: "mark-unread", label: "Mark unread", icon: "mail-open" },
{
id: "copy",
label: "Copy",
icon: "copy",
separatorBefore: true,
children: [
{ id: "copy-path", label: "Path", icon: "folder" },
...(state.branch
? [{ id: "copy-branch" as const, label: "Branch", icon: "git-branch" }]
: []),
{ id: "copy-thread-id", label: "Thread ID", icon: "hash" },
],
},
// Archive removes the thread from the sidebar while keeping its
// conversation under Settings > Archived threads — distinct from Settle
// (stays visible in the Settled shelf) and Delete (clears history for
// good), so it sits beside Delete without borrowing its destructive
// styling.
{ id: "archive", label: "Archive thread", disabled: state.isRunning },
{ id: "delete", label: "Delete", destructive: true, icon: "trash" },
{
id: "archive",
label: "Archive thread",
icon: "folder",
disabled: state.isRunning,
separatorBefore: true,
},
{
id: "delete",
label: "Delete",
destructive: true,
icon: "trash",
},
];
}
+2
View File
@@ -29,6 +29,8 @@ const buttonVariants = cva(
"icon-xs":
"size-7 sm:size-6 not-in-data-[slot=input-group]:[&_svg:not([class*='size-'])]:size-4 sm:not-in-data-[slot=input-group]:[&_svg:not([class*='size-'])]:size-3.5",
lg: "h-10 px-[calc(--spacing(3.5)-1px)] sm:h-9",
micro:
"h-5 gap-1 rounded-sm px-[calc(--spacing(1.5)-1px)] text-xs before:rounded-[calc(var(--radius-sm)-1px)] [&_svg:not([class*='size-'])]:size-3",
sm: "h-8 gap-1.5 px-[calc(--spacing(2.5)-1px)] sm:h-7",
xl: "h-11 px-[calc(--spacing(4)-1px)] text-lg sm:h-10 sm:text-base [&_svg:not([class*='size-'])]:size-5 sm:[&_svg:not([class*='size-'])]:size-4.5",
xs: "h-7 gap-1 px-[calc(--spacing(2)-1px)] text-sm sm:h-6 sm:text-xs [&_svg:not([class*='size-'])]:size-4 sm:[&_svg:not([class*='size-'])]:size-3.5",
+7 -5
View File
@@ -30,11 +30,13 @@ function ToggleGroup({
orientation === "horizontal"
? "*:pointer-coarse:after:min-w-auto"
: "*:pointer-coarse:after:min-h-auto",
variant === "default"
? "gap-0.5"
: orientation === "horizontal"
? "*:not-first:not-data-[slot=separator]:before:-start-[0.5px] *:not-last:not-data-[slot=separator]:before:-end-[0.5px] *:not-first:rounded-s-none *:not-last:rounded-e-none *:not-first:border-s-0 *:not-last:border-e-0 *:not-first:before:rounded-s-none *:not-last:before:rounded-e-none"
: "*:not-first:not-data-[slot=separator]:before:-top-[0.5px] *:not-last:not-data-[slot=separator]:before:-bottom-[0.5px] flex-col *:not-first:rounded-t-none *:not-last:rounded-b-none *:not-first:border-t-0 *:not-last:border-b-0 *:not-first:before:rounded-t-none *:not-last:before:rounded-b-none *:data-[slot=toggle]:not-last:before:hidden dark:*:last:before:hidden dark:*:first:before:block",
variant === "segmented"
? "gap-0.5 rounded-lg bg-muted/45 p-0.5"
: variant === "default"
? "gap-0.5"
: orientation === "horizontal"
? "*:not-first:not-data-[slot=separator]:before:-start-[0.5px] *:not-last:not-data-[slot=separator]:before:-end-[0.5px] *:not-first:rounded-s-none *:not-last:rounded-e-none *:not-first:border-s-0 *:not-last:border-e-0 *:not-first:before:rounded-s-none *:not-last:before:rounded-e-none"
: "*:not-first:not-data-[slot=separator]:before:-top-[0.5px] *:not-last:not-data-[slot=separator]:before:-bottom-[0.5px] flex-col *:not-first:rounded-t-none *:not-last:rounded-b-none *:not-first:border-t-0 *:not-last:border-b-0 *:not-first:before:rounded-t-none *:not-last:before:rounded-b-none *:data-[slot=toggle]:not-last:before:hidden dark:*:last:before:hidden dark:*:first:before:block",
className,
)}
data-size={size}
+4
View File
@@ -18,6 +18,8 @@ const toggleVariants = cva(
"h-7 min-w-7 rounded-md px-[calc(--spacing(1)-1px)] text-xs before:rounded-[calc(var(--radius-md)-1px)] [&_svg:not([class*='size-'])]:size-3.5",
default: "h-9 min-w-9 px-[calc(--spacing(2)-1px)] sm:h-8 sm:min-w-8",
lg: "h-10 min-w-10 px-[calc(--spacing(2.5)-1px)] sm:h-9 sm:min-w-9",
segmented:
"h-6 min-w-0 rounded-md px-2.5 text-xs before:rounded-[calc(var(--radius-md)-1px)]",
sm: "h-8 min-w-8 px-[calc(--spacing(1.5)-1px)] sm:h-7 sm:min-w-7",
xs: "h-7 min-w-7 px-[calc(--spacing(1)-1px)] sm:h-6 sm:min-w-6 rounded-md",
},
@@ -27,6 +29,8 @@ const toggleVariants = cva(
"border-transparent text-foreground shadow-none [:disabled,:active,[data-pressed]]:shadow-none before:shadow-none data-pressed:bg-accent data-pressed:text-accent-foreground disabled:opacity-100 disabled:text-muted-foreground disabled:[&_svg]:opacity-100",
outline:
"border-input bg-background not-dark:bg-clip-padding shadow-xs/5 not-disabled:not-active:not-data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:bg-input/32 dark:data-pressed:bg-input dark:hover:bg-input/64 dark:not-disabled:not-active:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)] dark:not-disabled:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/2%)] [:disabled,:active,[data-pressed]]:shadow-none",
segmented:
"border-transparent text-muted-foreground shadow-none transition-colors before:shadow-none hover:bg-accent/45 hover:text-foreground data-pressed:bg-accent data-pressed:text-foreground data-pressed:shadow-xs/5",
},
},
},
+204 -245
View File
@@ -19,12 +19,22 @@ import {
formatUsd,
makeWindow,
} from "@t3tools/shared/usageFormat";
import { ScrollArea } from "../ui/scroll-area";
import { Button } from "../ui/button";
import { ScrollArea } from "../ui/scroll-area";
import { SidebarInset } from "../ui/sidebar";
import { WorkspaceBreadcrumb, WorkspaceBreadcrumbItem } from "../WorkspaceBreadcrumb";
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "../../workspaceTitlebar";
import { UsageChartLegend, UsageProviderChart, type UsageChartMetric } from "./UsageProviderChart";
import { Toggle, ToggleGroup } from "../ui/toggle-group";
import {
WorkspaceBreadcrumb,
WorkspaceBreadcrumbItem,
WorkspaceBreadcrumbSeparator,
} from "../WorkspaceBreadcrumb";
import {
WorkspacePageContainer,
WorkspacePageHeader,
WorkspacePageHeaderEdgeControl,
} from "../WorkspacePageContainer";
import { HeaderFilterMenu } from "../HeaderFilterMenu";
import { UsageProviderChart, type UsageChartMetric } from "./UsageProviderChart";
import { PROVIDER_ORDER, PROVIDER_PRESENTATION } from "./usageProviders";
const WINDOW_OPTIONS = [
@@ -66,21 +76,6 @@ export function UsagePage() {
[isPast24Hours, merged.daily, merged.hourly],
);
// Ranked by whatever the toggle is showing, so the bars always descend.
const orderedProviders = useMemo(
() =>
merged.providers.toSorted((a, b) =>
metric === "cost" ? b.costUsd - a.costUsd : b.totalTokens - a.totalTokens,
),
[merged.providers, metric],
);
const activePeriods = (isPast24Hours ? merged.hourly : merged.daily).filter(
(period) => period.totalTokens > 0,
).length;
const periodAverage = activePeriods === 0 ? 0 : merged.totalTokens / activePeriods;
const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens;
const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput;
const selectWindow = (days: number) => {
setWindowSelection({
days,
@@ -100,78 +95,103 @@ export function UsagePage() {
setWindowSelection({ days: windowDays, window: nextWindow });
}
};
const windowLabel =
isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined
? `${formatDateTimeShort(window.sinceTime, window.timeZone)} to ${formatDateTimeShort(window.untilTime, window.timeZone)}`
: `${formatDayShort(window.sinceDay)} to ${formatDayShort(window.untilDay)}`;
const topbarContent = (
<div className="flex w-full min-w-0 items-center gap-3">
<WorkspaceBreadcrumb ariaLabel="Usage breadcrumb" className="min-w-0">
<WorkspaceBreadcrumbItem current>
<h1>Usage</h1>
</WorkspaceBreadcrumbItem>
<WorkspaceBreadcrumbSeparator className="hidden md:flex" />
<WorkspaceBreadcrumbItem className="hidden min-w-0 shrink md:flex">
<span className="truncate">{windowLabel}</span>
</WorkspaceBreadcrumbItem>
</WorkspaceBreadcrumb>
<div className="ms-auto hidden min-w-0 items-center justify-end gap-2 lg:flex">
<ToggleGroup
aria-label="Usage metric"
size="segmented"
variant="segmented"
value={[metric]}
onValueChange={(next) => {
const value = next[0];
if (value === "cost" || value === "tokens") setMetric(value);
}}
>
{(["cost", "tokens"] as const).map((option) => (
<Toggle key={option} value={option}>
{option === "cost" ? "Cost" : "Tokens"}
</Toggle>
))}
</ToggleGroup>
<ToggleGroup
aria-label="Usage period"
size="segmented"
variant="segmented"
value={[String(windowDays)]}
onValueChange={(next) => {
const value = next[0];
if (value) selectWindow(Number(value));
}}
>
{WINDOW_OPTIONS.map((option) => (
<Toggle key={option.days} value={String(option.days)}>
{option.label}
</Toggle>
))}
</ToggleGroup>
<WorkspacePageHeaderEdgeControl>
<Button onClick={refreshWindow} aria-label="Refresh usage" size="icon-sm" variant="ghost">
<RefreshCwIcon className="size-3.5" />
</Button>
</WorkspacePageHeaderEdgeControl>
</div>
<div className="ms-auto flex min-w-0 items-center justify-end gap-1 lg:hidden">
<HeaderFilterMenu
label="Usage metric"
value={metric}
options={[
{ value: "cost", label: "Cost" },
{ value: "tokens", label: "Tokens" },
]}
onChange={setMetric}
align="end"
popupClassName="min-w-32"
/>
<HeaderFilterMenu
label="Usage period"
value={String(windowDays)}
options={WINDOW_OPTIONS.map((option) => ({
value: String(option.days),
label: option.label,
}))}
onChange={(value) => selectWindow(Number(value))}
align="end"
popupClassName="min-w-32"
/>
<WorkspacePageHeaderEdgeControl>
<Button onClick={refreshWindow} aria-label="Refresh usage" size="icon-sm" variant="ghost">
<RefreshCwIcon className="size-3.5" />
</Button>
</WorkspacePageHeaderEdgeControl>
</div>
</div>
);
return (
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
{!isElectron && (
<header
className={cn(
"flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center px-3 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none sm:px-5",
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
)}
>
<WorkspaceBreadcrumb ariaLabel="Usage breadcrumb">
<WorkspaceBreadcrumbItem current>Usage</WorkspaceBreadcrumbItem>
</WorkspaceBreadcrumb>
</header>
)}
{isElectron && (
<div
className={cn(
"drag-region flex h-[52px] shrink-0 items-center px-5 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none wco:h-[env(titlebar-area-height)] wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]",
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
)}
>
<WorkspaceBreadcrumb ariaLabel="Usage breadcrumb">
<WorkspaceBreadcrumbItem current>Usage</WorkspaceBreadcrumbItem>
</WorkspaceBreadcrumb>
</div>
)}
<WorkspacePageHeader electron={isElectron}>{topbarContent}</WorkspacePageHeader>
<ScrollArea className="min-h-0 flex-1">
<div className="mx-auto flex w-full max-w-6xl flex-col gap-8 px-6 py-6">
<div className="flex flex-wrap items-center justify-between gap-4">
<p className="text-sm text-muted-foreground">
{isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined
? `${formatDateTimeShort(window.sinceTime, window.timeZone)} to ${formatDateTimeShort(window.untilTime, window.timeZone)}`
: `${formatDayShort(window.sinceDay)} to ${formatDayShort(window.untilDay)}`}
</p>
<div className="flex items-center gap-2">
<div className="flex rounded-md border border-border">
{WINDOW_OPTIONS.map((option) => (
<button
key={option.days}
type="button"
aria-pressed={option.days === windowDays}
onClick={() => selectWindow(option.days)}
className={cn(
"relative cursor-pointer px-3 py-1.5 text-xs outline-none first:rounded-s-[calc(var(--radius-md)-1px)] last:rounded-e-[calc(var(--radius-md)-1px)] focus-visible:z-10 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
option.days === windowDays
? "bg-muted text-foreground"
: "text-muted-foreground hover:text-foreground",
)}
>
{option.label}
</button>
))}
</div>
<Button
size="icon"
variant="outline"
onClick={refreshWindow}
aria-label="Refresh usage"
>
<RefreshCwIcon className="size-3.5" />
</Button>
</div>
</div>
<WorkspacePageContainer width="wide">
{settling ? (
<>
{environments.length > 1 ? <UsageDeviceStrip environments={environments} /> : null}
<UsageSkeleton resolution={isPast24Hours ? "hour" : "day"} />
<UsageSkeleton />
</>
) : (
<>
@@ -181,88 +201,71 @@ export function UsagePage() {
staleEnvironments={merged.staleEnvironments}
/>
{/* Cost first: the financial answer, then the provider split. */}
<section className="grid gap-6 lg:grid-cols-[minmax(0,20rem)_minmax(0,1fr)]">
{/* The summary follows the chart toggle, so the headline and the
series are always reading the same units. */}
<div className="flex flex-col gap-5">
<section className="grid gap-6 lg:grid-cols-[minmax(0,16rem)_minmax(0,1fr)]">
<div className="flex min-w-0 flex-col gap-5">
<div className="flex flex-col gap-1">
<span className="text-xs tracking-wide text-muted-foreground uppercase">
{metric === "cost" ? "Raw token cost" : "Processed tokens"}
</span>
<span className="text-4xl font-semibold text-foreground tabular-nums">
{metric === "cost"
? `${formatUsd(merged.costUsd)}*`
? formatUsd(merged.costUsd)
: formatTokens(merged.totalTokens)}
</span>
<span className="text-xs text-muted-foreground">
{metric === "cost"
? "* if billed at full API rate"
: `Input, cache reads and output across ${formatCount(merged.sessions)} sessions.`}
? `${formatCount(merged.sessions)} sessions · API estimate`
: `${formatCount(merged.sessions)} sessions`}
</span>
</div>
{orderedProviders.map((provider) => {
const share = metric === "cost" ? provider.costShare : provider.tokenShare;
{PROVIDER_ORDER.map((provider) => {
const totals = merged.providers.find((entry) => entry.provider === provider);
const share =
metric === "cost" ? (totals?.costShare ?? 0) : (totals?.tokenShare ?? 0);
const providerSessions = totals?.sessions ?? 0;
const sessionLabel = `${formatCount(providerSessions)} ${
providerSessions === 1 ? "session" : "sessions"
}`;
return (
<div key={provider.provider} className="flex flex-col gap-1.5">
<div className="flex items-baseline justify-between">
<span className="flex items-center gap-2 text-sm text-foreground">
<ProviderMark provider={provider.provider} className="size-4" />
{PROVIDER_PRESENTATION[provider.provider].label}
<div key={provider} className="flex flex-col gap-1">
<div className="flex items-baseline justify-between gap-4">
<span className="flex min-w-0 items-center gap-2 text-sm text-foreground">
<span
aria-hidden
className="size-2 shrink-0 rounded-full"
style={{
backgroundColor: PROVIDER_PRESENTATION[provider].color,
}}
/>
<ProviderMark provider={provider} className="size-4" />
<span className="flex min-w-0 items-baseline gap-1.5">
<span className="truncate">
{PROVIDER_PRESENTATION[provider].label}
</span>
<span className="shrink-0 whitespace-nowrap text-[11px] text-muted-foreground tabular-nums">
{sessionLabel}
</span>
</span>
</span>
<span className="text-sm text-foreground tabular-nums">
<span className="shrink-0 text-sm font-medium text-foreground tabular-nums">
{metric === "cost"
? formatUsd(provider.costUsd)
: formatTokens(provider.totalTokens)}
? formatUsd(totals?.costUsd ?? 0)
: formatTokens(totals?.totalTokens ?? 0)}
</span>
</div>
<div className="h-1 w-full overflow-hidden rounded-full bg-muted">
<div
className="h-full"
style={{
width: `${(share * 100).toFixed(1)}%`,
backgroundColor: PROVIDER_PRESENTATION[provider.provider].color,
}}
/>
</div>
<span className="text-xs text-muted-foreground">
{metric === "cost"
? `${formatPercent(share)} of cost · ${formatTokens(provider.totalTokens)} tokens`
: `${formatPercent(share)} of tokens · ${formatUsd(provider.costUsd)}`}
? `${formatPercent(share)} of cost · ${formatTokens(totals?.totalTokens ?? 0)} tokens`
: `${formatPercent(share)} of tokens · ${formatUsd(totals?.costUsd ?? 0)}`}
</span>
</div>
);
})}
</div>
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-center justify-between gap-3">
<h2 className="text-sm font-medium text-foreground">
{isPast24Hours ? "Hourly" : "Daily"}{" "}
{metric === "tokens" ? "processed tokens" : "cost"}
</h2>
<div className="flex items-center gap-4">
<div className="flex overflow-hidden rounded-md border border-border">
{(["cost", "tokens"] as const).map((option) => (
<button
key={option}
type="button"
onClick={() => setMetric(option)}
className={cn(
"cursor-pointer px-2.5 py-1 text-[10px] tracking-wide uppercase",
option === metric
? "bg-muted text-foreground"
: "text-muted-foreground hover:text-foreground",
)}
>
{option}
</button>
))}
</div>
<UsageChartLegend />
</div>
</div>
<div className="flex min-w-0 flex-col gap-3">
<h2 className="text-sm font-medium text-foreground">
{isPast24Hours ? "Hourly" : "Daily"}{" "}
{metric === "tokens" ? "processed tokens" : "cost"}
</h2>
<UsageProviderChart
days={days}
daily={merged.daily}
@@ -276,63 +279,47 @@ export function UsagePage() {
</div>
</section>
<section className="grid grid-cols-2 gap-px border-y border-border bg-border md:grid-cols-5">
<Metric
label="Processed tokens"
value={formatTokens(merged.totalTokens)}
detail={`${formatTokens(periodAverage)} per active ${isPast24Hours ? "hour" : "day"}`}
/>
<Metric
label="Cached input"
value={formatTokens(merged.cachedInputTokens)}
detail={`${formatPercent(cachedShare)} of observed input`}
/>
<Metric
label="Uncached input"
value={formatTokens(merged.uncachedInputTokens)}
detail={`${formatTokens(merged.cacheCreationTokens)} cache writes`}
/>
<Metric
label="Output"
value={formatTokens(merged.outputTokens)}
detail={`includes ${formatTokens(merged.reasoningTokens)} reasoning`}
/>
<Metric
label="Cache savings"
value={formatUsd(merged.costQuality.cacheSavingsUsd)}
detail={
merged.costUsd > 0
? `${(merged.costQuality.cacheSavingsUsd / merged.costUsd).toFixed(1)}x the raw token cost`
: "vs full input rates"
}
/>
<section className="flex flex-col gap-2">
<h2 className="text-sm font-medium text-foreground">Totals</h2>
<div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">
<Metric label="Processed tokens" value={formatTokens(merged.totalTokens)} />
<Metric label="Cached input" value={formatTokens(merged.cachedInputTokens)} />
<Metric
label="Uncached input"
value={formatTokens(merged.uncachedInputTokens)}
/>
<Metric label="Output" value={formatTokens(merged.outputTokens)} />
<Metric
label="Cache savings"
value={formatUsd(merged.costQuality.cacheSavingsUsd)}
/>
</div>
</section>
<section className="flex flex-col gap-3">
<div className="flex items-center justify-between gap-3">
<h2 className="text-sm font-medium text-foreground">Breakdown</h2>
<div className="flex overflow-hidden rounded-md border border-border">
<ToggleGroup
aria-label="Usage breakdown"
size="segmented"
variant="segmented"
value={[breakdown]}
onValueChange={(next) => {
const value = next[0];
if (value === "model" || value === "time") setBreakdown(value);
}}
>
{(
[
{ value: "model", label: "model" },
{ value: "time", label: isPast24Hours ? "hour" : "day" },
{ value: "model", label: "Model" },
{ value: "time", label: isPast24Hours ? "Hour" : "Day" },
] as const
).map((option) => (
<button
key={option.value}
type="button"
onClick={() => setBreakdown(option.value)}
className={cn(
"cursor-pointer px-2.5 py-1 text-[10px] tracking-wide uppercase",
option.value === breakdown
? "bg-muted text-foreground"
: "text-muted-foreground hover:text-foreground",
)}
>
<Toggle key={option.value} value={option.value}>
{option.label}
</button>
</Toggle>
))}
</div>
</ToggleGroup>
</div>
{breakdown === "model" ? (
@@ -356,7 +343,7 @@ export function UsagePage() {
merged.models.map((model) => (
<tr
key={`${model.provider}:${model.model}`}
className="border-b border-border/50"
className="hover:bg-muted/20"
>
<td className="py-2 text-foreground">
<span className="flex items-center gap-2">
@@ -403,7 +390,7 @@ export function UsagePage() {
recentPeriods.map((period) => (
<tr
key={"hourStart" in period ? period.hourStart : period.day}
className="border-b border-border/50"
className="hover:bg-muted/20"
>
<td className="py-2 text-foreground">
{"hourStart" in period
@@ -433,7 +420,7 @@ export function UsagePage() {
</section>
</>
)}
</div>
</WorkspacePageContainer>
</ScrollArea>
</div>
</SidebarInset>
@@ -452,20 +439,11 @@ function ProviderMark({
return <Mark className={cn("shrink-0", className)} aria-hidden />;
}
function Metric({
label,
value,
detail,
}: {
readonly label: string;
readonly value: string;
readonly detail: string;
}) {
function Metric({ label, value }: { readonly label: string; readonly value: string }) {
return (
<div className="flex flex-col gap-0.5 bg-background px-4 py-3">
<div className="flex min-w-0 flex-col gap-0.5">
<span className="text-xs text-muted-foreground">{label}</span>
<span className="text-lg text-foreground tabular-nums">{value}</span>
<span className="text-xs text-muted-foreground">{detail}</span>
<span className="text-base font-medium text-foreground tabular-nums">{value}</span>
</div>
);
}
@@ -569,70 +547,51 @@ function UsageDeviceStrip({
);
}
/** Deterministic bar heights (each unique: they double as keys). */
const SKELETON_BAR_HEIGHTS = [34, 58, 41, 72, 22, 12, 49, 63, 80, 38, 55, 26, 44, 67];
/**
* Static stand-in with the loaded page's shape: headline, provider split,
* chart and metrics strip. No shimmer; blocks fill in exactly once when the
* last device answers.
* Static stand-in with the loaded page's shape. No shimmer; blocks fill in
* exactly once when the last device answers.
*/
function UsageSkeleton({ resolution }: { readonly resolution: "day" | "hour" }) {
function UsageSkeleton() {
return (
<>
<section className="grid gap-6 lg:grid-cols-[minmax(0,20rem)_minmax(0,1fr)]">
<section className="grid gap-6 lg:grid-cols-[minmax(0,16rem)_minmax(0,1fr)]">
<div className="flex flex-col gap-5">
<div className="flex flex-col gap-1">
<span className="text-xs tracking-wide text-muted-foreground uppercase">
Raw token cost
</span>
<div className="my-1.5 h-8 w-36 rounded-sm bg-muted" />
<div className="h-3 w-28 rounded-sm bg-muted" />
<div className="h-8 w-36 rounded-sm bg-muted" />
<div className="h-3 w-32 rounded-sm bg-muted" />
</div>
{PROVIDER_ORDER.map((provider) => (
<div key={provider} className="flex flex-col gap-1.5">
<div className="flex items-center justify-between">
<span className="flex items-center gap-2 text-sm text-foreground">
<div key={provider} className="flex flex-col gap-1">
<div className="flex items-center justify-between gap-4">
<span className="flex items-center gap-2">
<ProviderMark provider={provider} className="size-4" />
{PROVIDER_PRESENTATION[provider].label}
<div className="h-3.5 w-20 rounded-sm bg-muted" />
</span>
<div className="h-3.5 w-14 rounded-sm bg-muted" />
</div>
<div className="h-1 w-full rounded-full bg-muted" />
<div className="h-3 w-36 rounded-sm bg-muted" />
</div>
))}
</div>
<div className="flex flex-col gap-3">
<h2 className="py-1 text-sm font-medium text-foreground">
{resolution === "hour" ? "Hourly" : "Daily"} cost
</h2>
{/* Mirrors the chart's h-56 body and w-14 axis gutter to avoid a
relayout when the real chart swaps in. */}
<div className="flex h-56 items-end gap-1 pl-16">
{SKELETON_BAR_HEIGHTS.map((height) => (
<div
key={height}
className="flex-1 rounded-sm bg-muted"
style={{ height: `${height}%` }}
/>
))}
</div>
<div className="h-4 w-24 rounded-sm bg-muted" />
<div className="h-56 rounded-sm bg-muted/35" />
</div>
</section>
<section className="grid grid-cols-2 gap-px border-y border-border bg-border md:grid-cols-5">
{["Processed tokens", "Cached input", "Uncached input", "Output", "Cache savings"].map(
(label) => (
<div key={label} className="flex flex-col gap-0.5 bg-background px-4 py-3">
<span className="text-xs text-muted-foreground">{label}</span>
<div className="my-1 h-5 w-16 rounded-sm bg-muted" />
<div className="h-3 w-24 rounded-sm bg-muted" />
</div>
),
)}
<section className="flex flex-col gap-2">
<h2 className="text-sm font-medium text-foreground">Totals</h2>
<div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">
{["Processed tokens", "Cached input", "Uncached input", "Output", "Cache savings"].map(
(label) => (
<div key={label} className="flex flex-col gap-0.5">
<span className="text-xs text-muted-foreground">{label}</span>
<div className="my-0.5 h-4 w-16 rounded-sm bg-muted" />
</div>
),
)}
</div>
</section>
</>
);
@@ -1,5 +1,5 @@
import type { UsageProviderKind } from "@t3tools/contracts";
import { useCallback, useMemo, useRef, useState } from "react";
import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
import type { DailyTotals, HourlyTotals } from "@t3tools/shared/usageMerge";
import {
@@ -68,13 +68,7 @@ function buildPeriodColumns(
});
}
/**
* Monotone cubic tangents (Fritsch-Carlson).
*
* Plain cubic smoothing overshoots on spiky daily data and would dip the area
* below zero between points, which reads as negative spend. This variant is
* shape-preserving, so a smoothed series never leaves the range of its samples.
*/
/** Shape-preserving cubic tangents that cannot overshoot spiky usage data. */
function monotoneTangents(points: readonly Point[]): readonly number[] {
const count = points.length;
if (count < 2) return [0];
@@ -115,7 +109,6 @@ function monotoneTangents(points: readonly Point[]): readonly number[] {
return tangents;
}
/** One cubic segment of a smoothed boundary. */
interface CurveSegment {
readonly from: Point;
readonly c1: Point;
@@ -123,7 +116,6 @@ interface CurveSegment {
readonly to: Point;
}
/** Smoothed polyline through `points`, as explicit cubic control points. */
function smoothCurve(points: readonly Point[]): readonly CurveSegment[] {
if (points.length < 2) return [];
const tangents = monotoneTangents(points);
@@ -144,10 +136,10 @@ function smoothCurve(points: readonly Point[]): readonly CurveSegment[] {
return segments;
}
function curvePath(segments: readonly CurveSegment[], startCommand: "M" | "L"): string {
function curvePath(segments: readonly CurveSegment[]): string {
const first = segments[0];
if (first === undefined) return "";
let path = `${startCommand}${first.from.x.toFixed(2)},${first.from.y.toFixed(2)}`;
let path = `M${first.from.x.toFixed(2)},${first.from.y.toFixed(2)}`;
for (const segment of segments) {
path += ` C${segment.c1.x.toFixed(2)},${segment.c1.y.toFixed(2)} ${segment.c2.x.toFixed(2)},${segment.c2.y.toFixed(2)} ${segment.to.x.toFixed(2)},${segment.to.y.toFixed(2)}`;
}
@@ -179,10 +171,8 @@ export function niceScale(peak: number, count: number): { max: number; ticks: re
/**
* Turns the merged daily totals into one column per day.
*
* Values are absolute, not cumulative: the series are layered from a shared
* zero baseline rather than stacked. A stacked chart puts whichever provider is
* drawn last permanently above the other, which reads as "that one is bigger"
* even on days where it is not.
* Values are absolute, not cumulative: each provider is drawn from the same
* zero baseline so the chart never implies that one provider is always larger.
*
* The chart paths and the hover readout both consume this, so the number under
* the cursor is by construction the number that was plotted rather than a
@@ -216,42 +206,39 @@ export function UsageProviderChart({
);
const [hoverIndex, setHoverIndex] = useState<number | null>(null);
const plotRef = useRef<HTMLDivElement | null>(null);
const tooltipRef = useRef<HTMLDivElement | null>(null);
const hoverPositionRef = useRef<{ x: number; y: number } | null>(null);
const { paths, ticks, stepX, toY, series } = useMemo(() => {
const { paths, series, stepX, ticks, toY } = useMemo(() => {
if (periods.length === 0) {
return {
paths: [],
ticks: [0] as readonly number[],
stepX: 0,
toY: () => VIEW_HEIGHT,
series: [] as readonly DayColumn[],
stepX: 0,
ticks: [0] as readonly number[],
toY: () => VIEW_HEIGHT,
};
}
const columns = buildPeriodColumns(periods, byPeriod, metric);
// The scale tops out at the largest single provider-day, not the largest
// sum: layered series each measure from zero, so a combined peak would
// leave the plot permanently half empty.
const peak = columns.reduce(
(max, column) => column.bands.reduce((inner, band) => Math.max(inner, band.value), max),
0,
);
const { max, ticks: tickValues } = niceScale(peak, TICK_COUNT);
const step = periods.length === 1 ? 0 : VIEW_WIDTH / (periods.length - 1);
// Reserve a sliver above the top gridline so the series stroke, which is
// drawn at constant screen width, is not shaved off at a peak.
const toY = (value: number) =>
max === 0 ? VIEW_HEIGHT : VIEW_HEIGHT - (value / max) * (VIEW_HEIGHT - PLOT_TOP);
const built = PROVIDER_ORDER.map((provider, providerIndex) => {
const curve = smoothCurve(
columns.map((column, dayIndex) => ({
x: dayIndex * step,
y: toY(column.bands[providerIndex]?.value ?? 0),
})),
const line = curvePath(
smoothCurve(
columns.map((column, periodIndex) => ({
x: periodIndex * step,
y: toY(column.bands[providerIndex]?.value ?? 0),
})),
),
);
const line = curvePath(curve, "M");
return {
provider,
total: columns.reduce((sum, column) => sum + (column.bands[providerIndex]?.value ?? 0), 0),
@@ -260,30 +247,75 @@ export function UsageProviderChart({
};
});
// Paint the heavier series first so the lighter one is never buried under
// it. The fills are faint enough that the order barely shows, but the
// strokes are drawn in a second pass regardless, so neither can be hidden.
const ordered = [...built].sort((a, b) => b.total - a.total);
return { paths: ordered, ticks: tickValues, stepX: step, toY, series: columns };
return {
paths: built.toSorted((a, b) => b.total - a.total),
series: columns,
stepX: step,
ticks: tickValues,
toY,
};
}, [byPeriod, metric, periods]);
const format = metric === "tokens" ? formatTokens : formatUsd;
const positionTooltip = useCallback(() => {
const plot = plotRef.current;
const tooltip = tooltipRef.current;
const hoverPosition = hoverPositionRef.current;
if (plot === null || tooltip === null || hoverPosition === null) return;
const gap = 12;
const tooltipWidth = tooltip.offsetWidth;
const tooltipHeight = tooltip.offsetHeight;
const plotWidth = plot.clientWidth;
const plotHeight = plot.clientHeight;
const preferredLeft =
hoverPosition.x + gap + tooltipWidth <= plotWidth
? hoverPosition.x + gap
: hoverPosition.x - gap - tooltipWidth;
const preferredTop =
hoverPosition.y + gap + tooltipHeight <= plotHeight
? hoverPosition.y + gap
: hoverPosition.y - gap - tooltipHeight;
const left = Math.min(Math.max(0, preferredLeft), Math.max(0, plotWidth - tooltipWidth));
const top = Math.min(Math.max(0, preferredTop), Math.max(0, plotHeight - tooltipHeight));
plot.style.setProperty("--usage-tooltip-left", `${left}px`);
plot.style.setProperty("--usage-tooltip-top", `${top}px`);
}, []);
useLayoutEffect(() => {
if (hoverIndex === null) return;
positionTooltip();
const plot = plotRef.current;
const tooltip = tooltipRef.current;
if (plot === null || tooltip === null || typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(positionTooltip);
observer.observe(plot);
observer.observe(tooltip);
return () => observer.disconnect();
}, [hoverIndex, positionTooltip]);
const handleMove = useCallback(
(event: React.MouseEvent<HTMLDivElement>) => {
const bounds = plotRef.current?.getBoundingClientRect();
if (bounds === undefined || bounds.width === 0 || periods.length === 0) return;
const fraction = (event.clientX - bounds.left) / bounds.width;
const plot = plotRef.current;
if (plot === null || periods.length === 0) return;
const bounds = plot.getBoundingClientRect();
if (bounds.width === 0) return;
const localX = Math.min(bounds.width, Math.max(0, event.clientX - bounds.left));
const localY = Math.min(bounds.height, Math.max(0, event.clientY - bounds.top));
const fraction = localX / bounds.width;
const index = Math.round(fraction * (periods.length - 1));
hoverPositionRef.current = { x: localX, y: localY };
positionTooltip();
setHoverIndex(Math.min(periods.length - 1, Math.max(0, index)));
},
[periods.length],
[periods.length, positionTooltip],
);
const hoveredPeriod = hoverIndex === null ? undefined : periods[hoverIndex];
const hoveredColumn = hoverIndex === null ? undefined : series[hoverIndex];
const hoverLeft = periods.length <= 1 ? 0 : ((hoverIndex ?? 0) / (periods.length - 1)) * 100;
const formatPeriod = (period: string) =>
resolution === "hour" ? formatHourShort(period, timeZone) : formatDayShort(period);
const formatTooltipPeriod = (period: string) =>
@@ -311,7 +343,10 @@ export function UsageProviderChart({
ref={plotRef}
className="relative h-56 flex-1"
onMouseMove={handleMove}
onMouseLeave={() => setHoverIndex(null)}
onMouseLeave={() => {
hoverPositionRef.current = null;
setHoverIndex(null);
}}
>
<svg
className="h-full w-full"
@@ -337,7 +372,6 @@ export function UsageProviderChart({
);
})}
{/* Fills first, then every stroke, so no series covers another's line. */}
{paths.map(({ provider, area }) => (
<path
key={provider}
@@ -373,10 +407,11 @@ export function UsageProviderChart({
{hoveredPeriod === undefined ? null : (
<div
className="pointer-events-none absolute top-0 z-10 min-w-36 border border-border bg-background/95 px-2 py-1.5 text-xs"
ref={tooltipRef}
className="surface-glass pointer-events-none absolute z-10 min-w-36 max-w-full rounded-xl border border-border/50 px-2.5 py-2 text-xs shadow-lg"
style={{
left: `${hoverLeft}%`,
transform: hoverLeft > 60 ? "translateX(-100%)" : "translateX(0)",
left: "var(--usage-tooltip-left, 0px)",
top: "var(--usage-tooltip-top, 0px)",
}}
>
<div className="mb-1 text-muted-foreground">{formatTooltipPeriod(hoveredPeriod)}</div>
@@ -423,21 +458,3 @@ export function UsageProviderChart({
</div>
);
}
export function UsageChartLegend() {
return (
<div className="flex items-center gap-4">
{PROVIDER_ORDER.map((provider) => {
// Brand marks keep monochrome providers identifiable even when their
// chart series use distinct colors.
const { label, mark: Mark } = PROVIDER_PRESENTATION[provider];
return (
<span key={provider} className="flex items-center gap-1.5 text-xs text-muted-foreground">
<Mark className="size-3.5 shrink-0" aria-hidden />
{label}
</span>
);
})}
</div>
);
}
@@ -26,5 +26,5 @@ export const PROVIDER_PRESENTATION = {
},
} satisfies Record<UsageProviderKind, UsageProviderPresentation>;
/** The chart layers every series from zero, so order only controls how it is read. */
/** Stable provider reading order across charts, summaries, tables, and hover rows. */
export const PROVIDER_ORDER = Object.keys(PROVIDER_PRESENTATION) as UsageProviderKind[];
+92 -6
View File
@@ -4,6 +4,15 @@ const SVG_NS = "http://www.w3.org/2000/svg";
// Inline Lucide-style icon paths (stroke-based, viewBox 0 0 24 24, strokeWidth 2).
const ICON_PATHS: Record<string, ReadonlyArray<{ tag: string; attrs: Record<string, string> }>> = {
"chevron-right": [{ tag: "path", attrs: { d: "m9 19 7-7-7-7" } }],
"circle-check": [
{ tag: "circle", attrs: { cx: "12", cy: "12", r: "10" } },
{ tag: "path", attrs: { d: "m9 12 2 2 4-4" } },
],
clock: [
{ tag: "path", attrs: { d: "M12 6v6l4 2" } },
{ tag: "circle", attrs: { cx: "12", cy: "12", r: "10" } },
],
pencil: [
{
tag: "path",
@@ -17,6 +26,71 @@ const ICON_PATHS: Record<string, ReadonlyArray<{ tag: string; attrs: Record<stri
{ tag: "rect", attrs: { width: "14", height: "14", x: "8", y: "8", rx: "2", ry: "2" } },
{ tag: "path", attrs: { d: "M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" } },
],
folder: [
{
tag: "path",
attrs: {
d: "M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",
},
},
],
"git-branch": [
{ tag: "line", attrs: { x1: "6", x2: "6", y1: "3", y2: "15" } },
{ tag: "circle", attrs: { cx: "18", cy: "6", r: "3" } },
{ tag: "circle", attrs: { cx: "6", cy: "18", r: "3" } },
{ tag: "path", attrs: { d: "M18 9a9 9 0 0 1-9 9" } },
],
hash: [
{ tag: "line", attrs: { x1: "4", x2: "20", y1: "9", y2: "9" } },
{ tag: "line", attrs: { x1: "4", x2: "20", y1: "15", y2: "15" } },
{ tag: "line", attrs: { x1: "10", x2: "8", y1: "3", y2: "21" } },
{ tag: "line", attrs: { x1: "16", x2: "14", y1: "3", y2: "21" } },
],
"mail-open": [
{
tag: "path",
attrs: {
d: "M21.2 8.4c.5.38.8.97.8 1.6v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V10a2 2 0 0 1 .8-1.6l8-6a2 2 0 0 1 2.4 0l8 6Z",
},
},
{ tag: "path", attrs: { d: "m22 10-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 10" } },
],
"message-square-plus": [
{
tag: "path",
attrs: {
d: "M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",
},
},
{ tag: "path", attrs: { d: "M12 8v6" } },
{ tag: "path", attrs: { d: "M9 11h6" } },
],
pin: [
{ tag: "path", attrs: { d: "M12 17v5" } },
{
tag: "path",
attrs: {
d: "M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z",
},
},
],
"pin-off": [
{ tag: "path", attrs: { d: "M12 17v5" } },
{ tag: "path", attrs: { d: "M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89" } },
{ tag: "path", attrs: { d: "m2 2 20 20" } },
{
tag: "path",
attrs: {
d: "M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h11",
},
},
],
"refresh-cw": [
{ tag: "path", attrs: { d: "M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8" } },
{ tag: "path", attrs: { d: "M21 3v5h-5" } },
{ tag: "path", attrs: { d: "M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16" } },
{ tag: "path", attrs: { d: "M8 16H3v5" } },
],
"folder-tree": [
{
tag: "path",
@@ -44,7 +118,7 @@ const ICON_PATHS: Record<string, ReadonlyArray<{ tag: string; attrs: Record<stri
function createIconElement(name: string, tone: "neutral" | "destructive"): SVGSVGElement | null {
const paths = ICON_PATHS[name];
if (!paths) {
if (!paths || typeof document.createElementNS !== "function") {
return null;
}
const svg = document.createElementNS(SVG_NS, "svg");
@@ -57,7 +131,7 @@ function createIconElement(name: string, tone: "neutral" | "destructive"): SVGSV
svg.setAttribute("stroke-linejoin", "round");
svg.setAttribute(
"class",
tone === "destructive" ? "size-3.5 shrink-0" : "size-3.5 shrink-0 text-muted-foreground",
tone === "destructive" ? "size-4 shrink-0" : "size-4 shrink-0 text-muted-foreground",
);
for (const node of paths) {
const child = document.createElementNS(SVG_NS, node.tag);
@@ -200,6 +274,16 @@ export function showContextMenuFallback<T extends string>(
"max-height:min(24rem,70vh);min-width:0;max-width:24rem;overflow-x:hidden;overflow-y:auto;padding:0.25rem;";
for (const item of entries) {
if (item.separatorBefore === true && inner.childElementCount > 0) {
const separator = document.createElement("div");
separator.className = "my-1 h-px bg-border/70";
separator.style.cssText =
"height:1px;margin:0.25rem 0;background:var(--border);opacity:0.7;";
separator.dataset.contextMenuSeparator = "true";
separator.setAttribute("role", "separator");
inner.appendChild(separator);
}
if (item.header === true) {
const header = document.createElement("div");
header.className = "px-2 py-1.5 font-medium text-muted-foreground text-xs";
@@ -247,10 +331,12 @@ export function showContextMenuFallback<T extends string>(
button.appendChild(label);
if (hasChildren) {
const chevron = document.createElement("span");
chevron.className = "ms-auto shrink-0 text-muted-foreground/80 text-sm leading-none";
chevron.textContent = ">";
button.appendChild(chevron);
const chevron = createIconElement("chevron-right", "neutral");
if (chevron) {
chevron.setAttribute("class", "ms-auto size-4 shrink-0 text-muted-foreground/80");
chevron.dataset.contextMenuChevron = "true";
button.appendChild(chevron);
}
}
if (!isDisabled) {
+6 -5
View File
@@ -1356,15 +1356,16 @@ html[data-theme-id] [data-chat-header] [data-toolbar-control] {
/* The panel layout toggles stay ghost: they render both inside the header and
in the titlebar strip, so filling them would make them change appearance as
the panel opens. They only take the themed foreground; hover and pressed
keep the base ghost accent. The tooltip trigger's data-slot wins over the
toggle's when the trigger renders the toggle, so match both. */
the panel opens. Their icons use the same themed foreground as the toolbar
action text; hover and pressed keep the base ghost accent. The tooltip
trigger's data-slot wins over the toggle's when it renders the toggle, so
match both. */
html[data-theme-id] [data-panel-layout-controls] [data-slot="toggle"],
html[data-theme-id] [data-panel-layout-controls] [data-slot="tooltip-trigger"],
html[data-theme-id] [data-workspace-titlebar-controls] [data-slot="toggle"],
html[data-theme-id] [data-workspace-titlebar-controls] [data-slot="tooltip-trigger"] {
--control-icon-color: var(--toolbar-foreground);
color: var(--toolbar-foreground);
--control-icon-color: var(--toolbar-control-foreground);
color: var(--toolbar-control-foreground);
}
html[data-theme-id] [data-chat-header] [data-slot="button"]:hover,
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from "vite-plus/test";
import {
changeRequestRepositoryUrl,
findProjectForChangeRequest,
openPullRequestLink,
parseChangeRequestUrl,
@@ -8,6 +9,24 @@ import {
shouldOpenPullRequestExternally,
} from "./openPullRequestLink";
describe("changeRequestRepositoryUrl", () => {
it("preserves repository path casing", () => {
expect(
changeRequestRepositoryUrl(
"https://gitlab.example.test/Team/Platform/Repo/-/merge_requests/42/diffs#note_1",
),
).toBe("https://gitlab.example.test/Team/Platform/Repo");
});
it("keeps pull-like segments inside nested GitLab repository paths", () => {
expect(
changeRequestRepositoryUrl(
"https://gitlab.example.test/group/pull/123/repo/-/merge_requests/42",
),
).toBe("https://gitlab.example.test/group/pull/123/repo");
});
});
describe("openPullRequestLink", () => {
it("opens the requested pull request URL", async () => {
const openExternal = vi.fn(async () => undefined);
+17
View File
@@ -118,6 +118,23 @@ export function parseChangeRequestUrl(targetUrl: string): ChangeRequestLink | nu
return null;
}
/** The repository root behind a recognised change-request URL, without PR-specific state. */
export function changeRequestRepositoryUrl(targetUrl: string): string | null {
const changeRequest = parseChangeRequestUrl(targetUrl);
if (changeRequest === null) return null;
const url = new URL(targetUrl);
const repositoryPath =
/^(.*?)\/-\/merge_requests\/\d+(?:\/|$)/iu.exec(url.pathname)?.[1] ??
/^(.*?)(?:\/pull\/\d+|\/-\/merge_requests\/\d+|\/pull-requests\/\d+|\/pullrequest\/\d+)(?:\/|$)/iu.exec(
url.pathname,
)?.[1];
if (!repositoryPath) return null;
url.pathname = repositoryPath;
url.search = "";
url.hash = "";
return url.toString();
}
function claim(host: string, match: RegExpExecArray | null): ChangeRequestLink | null {
const repository = match?.[1];
const number = Number(match?.[2]);
@@ -15,9 +15,7 @@ describe("hosted static onboarding header", () => {
const onboardingHeader = routeSource.slice(onboardingStart, onboardingEnd);
expect(onboardingHeader).toContain("h-[var(--workspace-topbar-height)]");
expect(onboardingHeader).toContain("min-h-[var(--workspace-topbar-height)]");
expect(onboardingHeader).toContain("COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS");
expect(onboardingHeader).toContain('<WorkspacePageHeader className="border-b border-border">');
expect(onboardingHeader).not.toMatch(/(?:^|\s)(?:[\w-]+:)*py-/);
});
});
+3 -9
View File
@@ -8,6 +8,7 @@ import { sortScopedProjectsForSidebar } from "../components/Sidebar.logic";
import { Button } from "../components/ui/button";
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../components/ui/empty";
import { SidebarInset } from "../components/ui/sidebar";
import { WorkspacePageHeader } from "../components/WorkspacePageContainer";
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
import {
useAllEnvironmentShellsBootstrapped,
@@ -17,8 +18,6 @@ import {
import { useEnvironments } from "../state/environments";
import { APP_DISPLAY_NAME } from "~/branding";
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
import { cn } from "~/lib/utils";
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
function ChatIndexRouteView() {
const { authGateState } = Route.useRouteContext();
@@ -143,18 +142,13 @@ function HostedStaticOnboardingState() {
return (
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">
<header
className={cn(
"flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center border-b border-border px-3 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none sm:px-5",
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
)}
>
<WorkspacePageHeader className="border-b border-border">
<div className="flex items-center gap-2">
<span className="text-sm font-medium text-foreground md:text-muted-foreground/60">
{APP_DISPLAY_NAME}
</span>
</div>
</header>
</WorkspacePageHeader>
<Empty className="flex-1">
<div className="w-full max-w-xl rounded-3xl border border-border/55 bg-card/20 px-8 py-12 shadow-sm/5">
+80 -73
View File
@@ -13,7 +13,6 @@ import type {
} from "@t3tools/contracts";
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import {
ChevronDownIcon,
EyeIcon,
MonitorIcon,
ServerIcon,
@@ -69,14 +68,20 @@ import { PullRequestListGhost } from "../components/pullRequest/PullRequestGhost
import { PullRequestRow } from "../components/pullRequest/PullRequestRow";
import { PullRequestsUnavailableState } from "../components/pullRequest/PullRequestsUnavailableState";
import { RightPanelTabs, type PullRequestTabStatus } from "../components/RightPanelTabs";
import { HeaderFilterMenu, type HeaderFilterMenuOption } from "../components/HeaderFilterMenu";
import {
WorkspaceBreadcrumb,
WorkspaceBreadcrumbItem,
WorkspaceBreadcrumbSeparator,
} from "../components/WorkspaceBreadcrumb";
import {
WorkspacePageContainer,
WorkspacePageHeader,
WorkspacePageHeaderEdgeControl,
} from "../components/WorkspacePageContainer";
import { isElectron } from "../env";
import { PanelLayoutControls } from "../components/chat/PanelLayoutControls";
import { Button } from "../components/ui/button";
import { Menu, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "../components/ui/menu";
import { SidebarInset } from "../components/ui/sidebar";
import { useLiveRefresh } from "../hooks/useLiveRefresh";
import {
@@ -99,7 +104,6 @@ import {
import { useAtomCommand } from "../state/use-atom-command";
import { cn } from "~/lib/utils";
import { getSourceControlPresentationForKind } from "~/sourceControlPresentation";
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
export interface PullRequestsSearch {
readonly involvement: PullRequestInvolvement;
@@ -1181,6 +1185,17 @@ function PullRequestsRouteView() {
: null,
[search.number, search.repository, selectedProject],
);
const linkedSelectionMatchesSurface =
linkedSelection !== null &&
selectedPullRequestSurface !== null &&
linkedSelection.environmentId === selectedPullRequestSurface.environmentId &&
linkedSelection.projectId === selectedPullRequestSurface.projectId &&
linkedSelection.repository === selectedPullRequestSurface.repository &&
linkedSelection.number === selectedPullRequestSurface.number;
// A closed panel keeps its tabs so reopening does not discard work. Those retained tabs are
// history, though, not a current selection: without this check they leave the toggle looking
// available after the selected pull request has been cleared.
const rightPanelAvailable = activePullRequestSurface !== null || linkedSelectionMatchesSurface;
useEffect(() => {
if (!pullRequestsSupported || rightPanelRef === null || linkedSelection === null) return;
useRightPanelStore.getState().openPullRequest(rightPanelRef, linkedSelection);
@@ -1294,9 +1309,10 @@ function PullRequestsRouteView() {
terminalAvailable={false}
terminalOpen={false}
terminalShortcutLabel={null}
rightPanelAvailable={rightPanelState.surfaces.length > 0}
rightPanelAvailable={rightPanelAvailable}
rightPanelOpen={rightPanelState.isOpen}
rightPanelShortcutLabel={null}
rightPanelUnavailableLabel="Select a pull request first"
liveAgentCount={0}
onToggleTerminal={() => undefined}
onToggleRightPanel={toggleRightPanel}
@@ -1603,7 +1619,6 @@ function PullRequestsRouteView() {
reviewingQuery.refresh();
}}
onStateChange={handlePullRequestTabStatusChange}
chromeVariant="collapse"
/>
</RightPanelTabs>
) : null}
@@ -1612,10 +1627,7 @@ function PullRequestsRouteView() {
);
}
/**
* A compact stand-in for one pill group: the trigger wears the current choice, the choices
* live in a menu. Same options, same handler — only the footprint changes.
*/
/** Adapts pull-request filter metadata to the shared header menu. */
function CompactFilterMenu<Value extends string>({
label,
value,
@@ -1627,37 +1639,18 @@ function CompactFilterMenu<Value extends string>({
options: ReadonlyArray<PullRequestFilterOption<Value>>;
onChange: (value: Value) => void;
}) {
const current = options.find((option) => option.value === value) ?? options[0]!;
const headerOptions = useMemo<ReadonlyArray<HeaderFilterMenuOption<Value>>>(
() =>
options.map((option) => ({
value: option.value,
label: option.label,
icon: <option.Icon aria-hidden className="size-3.5" />,
...(option.unavailable !== undefined ? { disabledReason: option.unavailable } : {}),
})),
[options],
);
return (
<Menu>
<MenuTrigger
aria-label={label}
className="inline-flex h-7 shrink-0 items-center gap-1 rounded-md px-1.5 text-sm font-medium text-muted-foreground hover:bg-accent hover:text-foreground"
>
{current.label}
<ChevronDownIcon aria-hidden className="size-3 text-muted-foreground/70" />
</MenuTrigger>
<MenuPopup align="start" side="bottom" className="min-w-40">
<MenuRadioGroup value={value} onValueChange={(next) => onChange(next as Value)}>
{options.map((option) => (
<MenuRadioItem
key={option.value}
value={option.value}
// A host the server has already said it cannot read is not a choice here either.
// The pills disable it; a menu that offers it would answer the press by replacing
// a working list with the same failure the pill row exists to explain.
disabled={option.unavailable !== undefined}
title={option.unavailable}
>
<span className="flex min-w-0 items-center gap-2">
<option.Icon aria-hidden className="size-3.5" />
{option.label}
</span>
</MenuRadioItem>
))}
</MenuRadioGroup>
</MenuPopup>
</Menu>
<HeaderFilterMenu label={label} value={value} options={headerOptions} onChange={onChange} />
);
}
@@ -1827,18 +1820,10 @@ function PullRequestsColumn({
// Painted flat like the chat column: the inset underneath carries the chrome grain, and a
// content surface that lets it show reads as a different background than every thread.
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background">
<header
className={cn(
"drag-region flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center gap-1.5 px-3 sm:px-5",
// A closed right panel leaves this column full-width, so its header runs
// underneath the native window controls on Windows; reserve the inset the
// way Settings and the chat view do. While the panel is open the column
// ends at the panel's left edge and the absolute controls strip (already
// WCO-aware) owns the top-right corner.
!rightPanelOpen && "wco:pr-[var(--workspace-native-controls-inset)]",
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
)}
>
{/* A closed right panel leaves this column full-width, so the shared header
reserves native window controls. While the panel is open, the column ends
at the panel and the absolute controls strip owns the top-right corner. */}
<WorkspacePageHeader electron={isElectron} reserveNativeControls={!rightPanelOpen}>
{condensed ? (
<WorkspaceBreadcrumb ariaLabel="Pull request scope">
{/* The page name remains the foreground anchor in both states; the live filters are
@@ -1880,27 +1865,24 @@ function PullRequestsColumn({
)}
<div className="min-w-0 flex-1" />
{condensed ? (
<ExpandableSearch
searchInput={searchInput}
searchValue={searchValue}
open={searchOpen}
onOpenChange={setSearchOpen}
focusToken={searchFocusToken}
onFocusWithin={(focused) => {
topbarSearchFocusedRef.current = focused;
}}
/>
<div className="flex shrink-0 items-center gap-1.5">
<ExpandableSearch
searchInput={searchInput}
searchValue={searchValue}
open={searchOpen}
onOpenChange={setSearchOpen}
focusToken={searchFocusToken}
onFocusWithin={(focused) => {
topbarSearchFocusedRef.current = focused;
}}
/>
<PullRequestRefreshControl compact refreshing={refreshing} onRefresh={onRefresh} />
</div>
) : null}
<Button
size="icon-sm"
variant="ghost"
aria-label="Refresh pull requests"
onClick={onRefresh}
>
<RefreshCwIcon className={cn("size-4", refreshing && "animate-spin")} />
</Button>
{rightPanelControl}
</header>
{rightPanelControl ? (
<WorkspacePageHeaderEdgeControl>{rightPanelControl}</WorkspacePageHeaderEdgeControl>
) : null}
</WorkspacePageHeader>
<div
ref={scrollRef}
@@ -1909,19 +1891,44 @@ function PullRequestsColumn({
{/* The top padding is the fade band's own height (1.5rem here), the same pairing the
settings page makes: at rest the controls sit fully below the mask, and only
content actually passing under the chrome fades. */}
<div className="mx-auto flex w-full max-w-4xl flex-col gap-4 px-5 pt-6 pb-12">
<WorkspacePageContainer className="gap-4">
<div className="flex flex-col gap-3">
<div ref={inFlowSearchRef} className="flex items-center gap-2">
{searchInput}
{filtersMenu}
{!condensed ? (
<PullRequestRefreshControl refreshing={refreshing} onRefresh={onRefresh} />
) : null}
</div>
{/* Scrolled past this marker, the controls are gone and the title takes over. */}
<div ref={markerRef} aria-hidden className="-mt-3 h-px w-full" />
</div>
{listBody}
</div>
</WorkspacePageContainer>
</div>
</div>
);
}
function PullRequestRefreshControl({
compact = false,
refreshing,
onRefresh,
}: {
compact?: boolean;
refreshing: boolean;
onRefresh: () => void;
}) {
return (
<Button
size={compact ? "icon-sm" : "icon"}
variant={compact ? "ghost" : "outline"}
aria-label="Refresh pull requests"
onClick={onRefresh}
disabled={refreshing}
>
<RefreshCwIcon className={cn("size-4", refreshing && "animate-spin")} />
</Button>
);
}
+10 -36
View File
@@ -13,9 +13,8 @@ import { useSettingsRestore } from "../components/settings/SettingsPanels";
import { SettingsBreadcrumb } from "../components/settings/SettingsBreadcrumb";
import { Button } from "../components/ui/button";
import { SidebarInset } from "../components/ui/sidebar";
import { WorkspacePageHeader } from "../components/WorkspacePageContainer";
import { isElectron } from "../env";
import { cn } from "~/lib/utils";
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
function RestoreDefaultsButton({ onRestored }: { onRestored: () => void }) {
const { changedSettingLabels, restoreDefaults } = useSettingsRestore(onRestored);
@@ -72,41 +71,16 @@ function SettingsContentLayout() {
return (
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">
<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">
{!isElectron && (
<header
className={cn(
"flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center px-3 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none sm:px-5",
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
)}
>
<div className="flex w-full items-center gap-2">
<SettingsBreadcrumb pathname={location.pathname} />
{showRestoreDefaults ? (
<div className="ms-auto flex items-center gap-2">
<RestoreDefaultsButton onRestored={handleRestored} />
</div>
) : null}
</div>
</header>
)}
{isElectron && (
<div
className={cn(
"drag-region flex h-[52px] shrink-0 items-center px-5 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none wco:h-[env(titlebar-area-height)] wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]",
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
)}
>
<div className="flex w-full items-center gap-2">
<SettingsBreadcrumb pathname={location.pathname} />
{showRestoreDefaults ? (
<div className="ms-auto flex items-center gap-2">
<RestoreDefaultsButton onRestored={handleRestored} />
</div>
) : null}
</div>
<WorkspacePageHeader electron={isElectron}>
<div className="flex w-full items-center gap-3">
<SettingsBreadcrumb pathname={location.pathname} />
{showRestoreDefaults ? (
<div className="ms-auto flex items-center gap-2">
<RestoreDefaultsButton onRestored={handleRestored} />
</div>
) : null}
</div>
)}
</WorkspacePageHeader>
<div key={restoreSignal} className="min-h-0 flex flex-1 flex-col">
<Outlet />
+4
View File
@@ -111,6 +111,8 @@ export interface ContextMenuItem<T extends string = string> {
header?: boolean;
/** Icon keyword resolved by the web fallback. Stripped on desktop native menus. */
icon?: string;
/** Inserts a visual section divider immediately before this item. */
separatorBefore?: boolean;
children?: readonly ContextMenuItem<T>[];
}
@@ -121,6 +123,7 @@ export interface ContextMenuItemSchemaType {
readonly disabled?: boolean;
readonly header?: boolean;
readonly icon?: string;
readonly separatorBefore?: boolean;
readonly children?: readonly ContextMenuItemSchemaType[];
}
@@ -131,6 +134,7 @@ export const ContextMenuItemSchema: Schema.Codec<ContextMenuItemSchemaType> = Sc
disabled: Schema.optionalKey(Schema.Boolean),
header: Schema.optionalKey(Schema.Boolean),
icon: Schema.optionalKey(Schema.String),
separatorBefore: Schema.optionalKey(Schema.Boolean),
children: Schema.optionalKey(
Schema.Array(
Schema.suspend((): Schema.Codec<ContextMenuItemSchemaType> => ContextMenuItemSchema),
+31
View File
@@ -138,6 +138,12 @@ describe("mergeUsage", () => {
"claude",
"codex",
]);
expect(merged.sessions).toBe(2);
expect(
Object.fromEntries(
merged.providers.map((provider) => [provider.provider, provider.sessions]),
),
).toEqual({ claude: 1, codex: 1 });
});
it("excludes an environment reporting an older contract version", () => {
@@ -248,6 +254,31 @@ describe("mergeUsage", () => {
);
expect(merged.sessions).toBe(1);
expect(merged.providers[0]?.sessions).toBe(1);
});
it("omits providers whose owned sources have no activity", () => {
const merged = mergeUsage(
[
environment(
"env-a",
summary(
[],
[
{
provider: "claude",
hostId: "mac",
homePath: "/a/.claude",
distinctSessions: 0,
},
],
),
),
],
USAGE_CONTRACT_VERSION,
);
expect(merged.providers).toEqual([]);
});
it("returns empty totals with no environments", () => {
+36 -11
View File
@@ -25,6 +25,7 @@ export interface ProviderTotals {
readonly costUsd: number;
readonly totalTokens: number;
readonly records: number;
readonly sessions: number;
readonly costShare: number;
readonly tokenShare: number;
}
@@ -135,22 +136,29 @@ function claimSources(environments: readonly EnvironmentUsage[]): {
function ownedContribution(
environment: EnvironmentUsage,
ownerByFingerprint: ReadonlyMap<string, EnvironmentId>,
): { readonly buckets: readonly UsageBucket[]; readonly sessions: number } {
): {
readonly buckets: readonly UsageBucket[];
readonly sessionsByProvider: ReadonlyMap<UsageProviderKind, number>;
} {
const ownedProviders = new Set<UsageProviderKind>();
let sessions = 0;
const sessionsByProvider = new Map<UsageProviderKind, number>();
for (const source of environment.summary.sources) {
if (source.status === "missing") continue;
const key = fingerprintKey(source.fingerprint);
if (ownerByFingerprint.get(key) === environment.environmentId) {
ownedProviders.add(source.fingerprint.provider);
const provider = source.fingerprint.provider;
ownedProviders.add(provider);
// Distinct within a directory. Summing per-bucket session counts instead
// would count a session once per day and model it spans.
sessions += source.distinctSessions;
sessionsByProvider.set(
provider,
(sessionsByProvider.get(provider) ?? 0) + source.distinctSessions,
);
}
}
return {
buckets: environment.summary.buckets.filter((bucket) => ownedProviders.has(bucket.provider)),
sessions,
sessionsByProvider,
};
}
@@ -228,7 +236,7 @@ export function mergeUsage(
const providerAccumulator = new Map<
UsageProviderKind,
{ costUsd: number; totalTokens: number; records: number }
{ costUsd: number; totalTokens: number; records: number; sessions: number }
>();
const modelAccumulator = new Map<
string,
@@ -255,12 +263,20 @@ export function mergeUsage(
const contributingEnvironments: EnvironmentId[] = [];
for (const environment of current) {
const { buckets, sessions: environmentSessions } = ownedContribution(
environment,
ownerByFingerprint,
);
const { buckets, sessionsByProvider } = ownedContribution(environment, ownerByFingerprint);
if (buckets.length > 0) contributingEnvironments.push(environment.environmentId);
sessions += environmentSessions;
for (const [providerKind, providerSessions] of sessionsByProvider) {
sessions += providerSessions;
const provider = providerAccumulator.get(providerKind) ?? {
costUsd: 0,
totalTokens: 0,
records: 0,
sessions: 0,
};
provider.sessions += providerSessions;
providerAccumulator.set(providerKind, provider);
}
for (const bucket of buckets) {
const tokens = bucketTokens(bucket);
@@ -280,6 +296,7 @@ export function mergeUsage(
costUsd: 0,
totalTokens: 0,
records: 0,
sessions: 0,
};
provider.costUsd += bucket.costUsd;
provider.totalTokens += tokens;
@@ -341,9 +358,17 @@ export function mergeUsage(
costUsd: totals.costUsd,
totalTokens: totals.totalTokens,
records: totals.records,
sessions: totals.sessions,
costShare: costUsd === 0 ? 0 : totals.costUsd / costUsd,
tokenShare: totalTokens === 0 ? 0 : totals.totalTokens / totalTokens,
}))
.filter(
(provider) =>
provider.costUsd !== 0 ||
provider.totalTokens !== 0 ||
provider.records !== 0 ||
provider.sessions !== 0,
)
.sort((a, b) => b.costUsd - a.costUsd);
const models: ModelTotals[] = [...modelAccumulator.entries()]