Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
useIsDarkTheme,
} from "renderer/assets/app-icons/preset-icons";
import { HotkeyMenuShortcut } from "renderer/components/HotkeyMenuShortcut";
import { useWorkspaceHostUrl } from "renderer/hooks/host-service/useWorkspaceHostUrl";
import { useAgentConfigs } from "renderer/hooks/useAgentConfigs";
import { useBuiltinPresets } from "renderer/hooks/useBuiltinPresets";
import { useParadevShell } from "renderer/hooks/useParadevShell";
Expand All @@ -33,6 +34,7 @@ import { BuiltinPresetBarItem } from "./components/BuiltinPresetBarItem";
import { PresetBarItem } from "./components/PresetBarItem";

interface PresetsBarProps {
workspaceId: string;
matchedPresets: TerminalPresetRow[];
executePreset: (preset: TerminalPresetRow) => void | Promise<void>;
showPresetsBar: boolean;
Expand Down Expand Up @@ -74,6 +76,7 @@ function getVisiblePresetOrder(
}

export function PresetsBar({
workspaceId,
matchedPresets,
executePreset,
showPresetsBar,
Expand All @@ -83,6 +86,7 @@ export function PresetsBar({
const isDark = useIsDarkTheme();
const isParadevShell = useParadevShell();
const collections = useCollections();
const hostUrl = useWorkspaceHostUrl(workspaceId);
const { activeHostUrl } = useLocalHostService();
const { data: agents } = useAgentConfigs(activeHostUrl);
const builtinPresets = useBuiltinPresets();
Expand Down Expand Up @@ -354,12 +358,19 @@ export function PresetsBar({
<PresetBarItem
key={preset.id}
preset={preset}
hostUrl={hostUrl}
visibleIndex={visibleIndex}
hotkeyId={hotkeyId}
isDark={isDark}
agents={agents}
onExecutePreset={executePreset}
onEdit={(presetToEdit) => handleEditPreset(presetToEdit.id)}
onViewUsage={(accountKey) =>
navigate({
to: "/settings/usage",
search: { workspaceId, agent: "codex", accountKey },
})
}
onLocalReorder={handleLocalVisibleReorder}
onPersistReorder={handlePersistVisibleReorder}
/>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,48 +1,77 @@
import { Trans } from "@lingui/react/macro";
import type { HostAgentConfig } from "@superset/host-service/settings";
import { formatPercent } from "@superset/i18n/format";
import { Button } from "@superset/ui/button";
import {
ContextMenu,
ContextMenuContent,
ContextMenuItem,
ContextMenuLabel,
ContextMenuSeparator,
ContextMenuTrigger,
} from "@superset/ui/context-menu";
import { cn } from "@superset/ui/utils";
import { useEffect, useRef } from "react";
import { useDrag, useDrop } from "react-dnd";
import { HiMiniCommandLine } from "react-icons/hi2";
import { QuotaWindowRow } from "renderer/components/QuotaWindowRow";
import { useHostUsageQuota } from "renderer/hooks/host-service/useHostUsageQuota";
import { useNow } from "renderer/hooks/useNow";
import type { HotkeyId } from "renderer/hotkeys";
import { HotkeyTooltip } from "renderer/hotkeys";
import { findLinkedAgent } from "renderer/lib/agent-launch-command";
import { resolvePresetIcon } from "renderer/lib/preset-icon";
import { resolvePresetIconKey } from "renderer/lib/preset-icon-key";
import type { TerminalPresetRow } from "renderer/routes/_authenticated/providers/CollectionsProvider/dashboardSidebarLocal";
import { useSettings } from "renderer/stores/settings";
import { getCodexPresetQuota } from "./utils/getCodexPresetQuota";

const V2_PRESET_BAR_ITEM_TYPE = "V2_PRESET_BAR_ITEM";

interface PresetBarItemProps {
preset: TerminalPresetRow;
hostUrl: string | null;
visibleIndex: number;
hotkeyId?: HotkeyId;
isDark: boolean;
agents: HostAgentConfig[] | undefined;
onExecutePreset: (preset: TerminalPresetRow) => void;
onEdit: (preset: TerminalPresetRow) => void;
onViewUsage: (accountKey?: string) => void;
onLocalReorder: (fromIndex: number, toIndex: number) => void;
onPersistReorder: (presetId: string, targetVisibleIndex: number) => void;
}

export function PresetBarItem({
preset,
hostUrl,
visibleIndex,
hotkeyId,
isDark,
agents,
onExecutePreset,
onEdit,
onViewUsage,
onLocalReorder,
onPersistReorder,
}: PresetBarItemProps) {
const containerRef = useRef<HTMLDivElement>(null);
const icon = resolvePresetIcon(preset, agents, isDark);
const location = useSettings((settings) => settings.codexUsageLocation);
const linked = findLinkedAgent(agents, preset.agentId);
const isCodex =
(linked?.presetId ?? resolvePresetIconKey(preset, undefined)) === "codex";
const showUsage = isCodex && location === "preset";
const quota = useHostUsageQuota(showUsage ? hostUrl : null);
const now = useNow(60_000, showUsage && !!hostUrl);
const { account, windows, summary } = getCodexPresetQuota(
quota.data ?? [],
now.getTime(),
quota.isError,
);
const used = summary
? formatPercent(summary.usedPercent / 100, { maximumFractionDigits: 0 })
: undefined;

const [{ isDragging }, drag] = useDrag(
() => ({
Expand Down Expand Up @@ -90,7 +119,10 @@ export function PresetBarItem({
<Button
variant="ghost"
size="sm"
className="h-6 max-w-32 min-w-0 shrink-0 gap-2 rounded-md px-2 text-xs font-normal text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground"
className={cn(
"h-6 min-w-0 shrink-0 gap-2 rounded-md px-2 text-xs font-normal text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground",
showUsage ? "max-w-56" : "max-w-32",
)}
onClick={() => onExecutePreset(preset)}
>
{icon ? (
Expand All @@ -105,11 +137,52 @@ export function PresetBarItem({
<span className="min-w-0 truncate">
{preset.name || "default"}
</span>
{showUsage && (
<span className="shrink-0 text-[10px] tabular-nums">
{summary && used ? (
<>
{summary.label} · <Trans>{used} used</Trans>
</>
) : (
<Trans>Usage</Trans>
)}
</span>
)}
</Button>
</HotkeyTooltip>
</div>
</ContextMenuTrigger>
<ContextMenuContent>
<ContextMenuContent className={showUsage ? "w-96" : undefined}>
{showUsage && (
<>
<ContextMenuLabel>
<Trans>Usage</Trans> · <Trans>Default</Trans>
</ContextMenuLabel>
{windows.length > 0 ? (
windows.map((window) => (
<QuotaWindowRow
key={window.id}
window={window}
className="px-2"
/>
))
) : (
<output className="block px-2 text-xs text-muted-foreground">
{account?.credentialKind === "api_key" ? (
<Trans>API billing</Trans>
) : quota.isLoading ? (
<Trans>Reading usage…</Trans>
) : (
<Trans>Usage unavailable.</Trans>
)}
</output>
)}
<ContextMenuItem onSelect={() => onViewUsage(account?.accountKey)}>
<Trans>View usage</Trans>
</ContextMenuItem>
<ContextMenuSeparator />
</>
)}
<ContextMenuItem onSelect={() => onExecutePreset(preset)}>
<Trans>Run script</Trans>
</ContextMenuItem>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { expect, test } from "bun:test";
import type {
UsageAccount,
UsageQuotaWindow,
} from "renderer/hooks/host-service/useHostUsageQuota";
import { getCodexPresetQuota } from "./getCodexPresetQuota";

const now = Date.UTC(2026, 10, 20);
const session: UsageQuotaWindow = {
id: "primary",
label: "Session (5h)",
usedPercent: 80,
resetsAt: new Date(now + 3600_000),
};
const weekly: UsageQuotaWindow = {
id: "secondary",
label: "Weekly",
usedPercent: 50,
resetsAt: new Date(now + 2 * 3600_000),
};
const account: UsageAccount = {
agent: "codex",
credentialKind: "subscription",
selection: null,
accountKey: "default",
email: null,
plan: "plus",
status: "ok",
statusDetail: null,
sourceLabel: "default",
windows: [session, weekly],
isDefault: true,
creditsBalance: null,
extraUsage: null,
fetchedAt: new Date(now),
};

test("summarizes the default Codex subscription's weekly window", () => {
const result = getCodexPresetQuota(
[
{ ...account, agent: "claude" },
{ ...account, isDefault: false, accountKey: "other" },
account,
],
now,
false,
);
expect(result.account).toBe(account);
expect(result.summary).toBe(weekly);
expect(result.windows).toEqual([session, weekly]);
});

test("keeps a current window when another window has reset", () => {
const expired = { ...weekly, resetsAt: new Date(now) };
const result = getCodexPresetQuota(
[{ ...account, windows: [session, expired] }],
now,
false,
);
expect(result.summary).toBe(session);
expect(result.windows).toEqual([session]);
});

test("does not substitute another subscription for the default API account", () => {
const result = getCodexPresetQuota(
[
{ ...account, isDefault: false },
{ ...account, credentialKind: "api_key" },
],
now,
false,
);
expect(result.account?.credentialKind).toBe("api_key");
expect(result.summary).toBeUndefined();
});

test("hides cached quota after it expires or the query fails", () => {
expect(getCodexPresetQuota([account], now + 600_000, false).windows).toEqual(
[],
);
expect(getCodexPresetQuota([account], now, true).windows).toEqual([]);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import type { UsageAccount } from "renderer/hooks/host-service/useHostUsageQuota";

const MAX_QUOTA_AGE_MS = 10 * 60_000;

export function getCodexPresetQuota(
accounts: readonly UsageAccount[],
now: number,
failed: boolean,
) {
const account = accounts.find(
(candidate) => candidate.agent === "codex" && candidate.isDefault,
);
const windows =
!failed &&
account?.credentialKind === "subscription" &&
account.status === "ok" &&
now - new Date(account.fetchedAt).getTime() < MAX_QUOTA_AGE_MS
? account.windows.filter(
(window) =>
Number.isFinite(window.usedPercent) &&
window.usedPercent >= 0 &&
(!window.resetsAt || new Date(window.resetsAt).getTime() > now),
)
: [];
const summary =
windows.find(
(window) => window.id === "seven_day" || window.label === "Weekly",
) ??
windows.find((window) => window.id === "secondary") ??
windows[0];
return { account, windows, summary };
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { getCodexPresetQuota } from "./getCodexPresetQuota";
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { useLingui } from "@lingui/react/macro";
import { formatPercent } from "@superset/i18n/format";
import { cn } from "@superset/ui/utils";
import {
DEFAULT_USAGE_WARNING_THRESHOLD,
useSettings,
} from "renderer/stores/settings";
import { useAccountUsage } from "../../hooks/useAccountUsage";

export function UsageWarningDot({
Expand All @@ -11,10 +15,27 @@ export function UsageWarningDot({
terminalId: string;
}) {
const { t } = useLingui();
const { state, tightest } = useAccountUsage(workspaceId, terminalId);
if (state !== "ready" || !tightest || tightest.usedPercent < 70) return null;
const { binding, state, tightest } = useAccountUsage(workspaceId, terminalId);
const location = useSettings((settings) => settings.codexUsageLocation);
const codexThreshold = useSettings((settings) =>
settings.codexUsageThresholdEnabled ? settings.codexUsageThreshold : 0,
);
if (state !== "ready" || !tightest) return null;
const isCodex = binding?.agentId === "codex";
if (isCodex && location !== "session") return null;
const threshold = isCodex ? codexThreshold : DEFAULT_USAGE_WARNING_THRESHOLD;
if (tightest.usedPercent < threshold) return null;

const percent = formatPercent(tightest.usedPercent / 100);
const label = t({ message: `Account usage: ${percent} used` });
if (isCodex) {
return (
<span className="shrink-0 text-[10px] tabular-nums" title={label}>
{percent}
</span>
);
}

return (
<span
role="img"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,35 @@ describe("pane quota selection", () => {
expect(result.state).toBe("api");
expect(result.account).toBeUndefined();
});
test("keeps the current Codex window when another window has reset", () => {
const weekly = {
id: "secondary",
label: "Weekly",
usedPercent: 50,
resetsAt: new Date(now + 3600_000),
};
const result = getAccountUsageState({
...input,
identity: { ...input.identity, agent: "codex" },
accounts: [
{
...account,
agent: "codex",
windows: [
{
id: "primary",
label: "Session",
usedPercent: 99,
resetsAt: new Date(now),
},
weekly,
],
},
],
});
expect(result.state).toBe("ready");
expect(result.tightest).toBe(weekly);
});
test("unsupported agents and missing quota are not zero usage", () => {
expect(getAccountUsageState({ ...input, supported: false }).state).toBe(
"unavailable",
Expand Down
Loading
Loading