Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

Say which token limit ran out and when it resets

Ramshouriesh Ra47faf0c971a
diff --git a/apps/app/src/app/lib/omnirush-usage.ts b/apps/app/src/app/lib/omnirush-usage.ts
new file mode 100644
index 00000000..449a138f
--- /dev/null
+++ b/apps/app/src/app/lib/omnirush-usage.ts
@@ -0,0 +1,92 @@
+import type { OmniRushAccountUsage } from "@omnirush/types/desktop-ipc";
+
+/** The user's clock; tests pin it, the app uses the system's. */
+export type UsageClock = { now?: number; timeZone?: string; hourCycle?: Intl.DateTimeFormatOptions["hourCycle"] };
+
+export type UsageSummary = {
+ /** The sidebar footer's line: "3.2M tokens left today". */
+ short: string;
+ /** The Settings account line, with when the binding limit resets. */
+ line: string;
+ /** How full the meter is, 0–100. */
+ percent: number;
+};
+
+export function compactTokenCount(value: number): string {
+ return new Intl.NumberFormat("en-US", { notation: "compact", maximumFractionDigits: 1 }).format(Math.max(0, value));
+}
+
+function percentUsed(used: number, limit: number): number {
+ return limit > 0 ? Math.min(100, Math.max(0, (used * 100) / limit)) : 0;
+}
+
+/** "5:30 AM (in 3 h)", or "Monday 5:30 AM (in 4 days)" for the week, on the user's clock; null without a time. */
+export function localReset(iso: string | null | undefined, scope: "day" | "week", clock: UsageClock = {}): string | null {
+ const at = Date.parse(iso ?? "");
+ if (!Number.isFinite(at)) return null;
+ const { timeZone } = clock;
+ const hourCycle = clock.hourCycle ?? new Intl.DateTimeFormat(undefined, { hour: "numeric" }).resolvedOptions().hourCycle;
+ const time = new Intl.DateTimeFormat("en-US", { hour: "numeric", minute: "2-digit", hourCycle, timeZone }).format(at);
+ const local = scope === "week" ? `${new Intl.DateTimeFormat("en-US", { weekday: "long", timeZone }).format(at)} ${time}` : time;
+ const left = at - (clock.now ?? Date.now());
+ if (left <= 0) return local;
+ const minutes = Math.max(1, Math.round(left / 60_000));
+ const hours = Math.round(minutes / 60);
+ const relative = minutes < 60 ? `${minutes} min` : hours < 48 ? `${hours} h` : `${Math.round(hours / 24)} days`;
+ return `${local} (in ${relative})`;
+}
+
+/**
+ * The account's tokens in words. With daily grants: today's allowance under
+ * the weekly cap, then the one-time bonus pot, and when the limit that binds
+ * resets. Only the weekly cap (an account's own cap): the week. Otherwise
+ * (the weekly model, an older backend) the grant as before.
+ */
+export function omnirushUsageSummary(usage: OmniRushAccountUsage, clock: UsageClock = {}): UsageSummary {
+ const pot = Math.max(0, usage.pot ?? 0);
+ const potNote = pot > 0 ? ` · ${compactTokenCount(pot)} bonus pot` : "";
+ const potCover = pot > 0 ? ` Your ${compactTokenCount(pot)} bonus pot covers you until then.` : "";
+ const week = usage.week ?? null;
+ const day = usage.grantModel === "daily" && usage.limitScope !== "week" ? usage.day : null;
+ if (day) {
+ if (day.allowance <= 0) {
+ const tokens = pot > 0 ? `${compactTokenCount(pot)} one-time tokens left` : "No tokens left";
+ return { short: tokens, line: `${tokens}. Link Discord or GitHub to get tokens every day.`, percent: pot > 0 ? 0 : 100 };
+ }
+ const dayLeft = Math.max(0, day.allowance - day.used - day.reserved);
+ const weekLeft = week ? Math.max(0, week.limit - week.used - day.reserved) : null;
+ const left = weekLeft === null ? dayLeft : Math.min(dayLeft, weekLeft);
+ const capped = weekLeft !== null && weekLeft < dayLeft;
+ if (left <= 0) {
+ const line = capped
+ ? `This week's cap is reached. It resets ${localReset(week?.resetsAt, "week", clock) ?? "Monday 00:00 UTC"}.`
+ : `Today's tokens are used up. They refill at ${localReset(day.resetsAt, "day", clock) ?? "00:00 UTC"}.`;
+ return { short: `${capped ? "Weekly cap reached" : "Today's tokens used up"}${potNote}`, line: `${line}${potCover}`, percent: 100 };
+ }
+ const reset = capped ? localReset(week?.resetsAt, "week", clock) : localReset(day.resetsAt, "day", clock);
+ const when = reset ? ` · ${capped ? "cap resets" : "refills at"} ${reset}` : "";
+ return {
+ short: `${compactTokenCount(left)} tokens left today`,
+ line: `${capped ? `${compactTokenCount(left)} tokens left today (weekly cap)` : `${compactTokenCount(left)} of ${compactTokenCount(day.allowance)} tokens left today`}${when}${potNote}`,
+ percent: percentUsed(day.allowance - left, day.allowance),
+ };
+ }
+ if (usage.grantModel === "daily" && week) {
+ const left = Math.max(0, week.limit - week.used);
+ const reset = localReset(week.resetsAt, "week", clock);
+ if (left <= 0) {
+ return { short: `Weekly cap reached${potNote}`, line: `This week's cap is reached. It resets ${reset ?? "Monday 00:00 UTC"}.${potCover}`, percent: 100 };
+ }
+ return {
+ short: `${compactTokenCount(left)} tokens left this week`,
+ line: `${compactTokenCount(left)} of ${compactTokenCount(week.limit)} tokens left this week${reset ? ` · resets ${reset}` : ""}${potNote}`,
+ percent: percentUsed(week.used, week.limit),
+ };
+ }
+ const period = usage.period === "week" ? "this week" : "today";
+ return {
+ short: `${compactTokenCount(usage.remainingTokens)} tokens left ${period}`,
+ line: `${compactTokenCount(usage.remainingTokens)} of ${compactTokenCount(usage.tokenLimit)} tokens left ${period}`,
+ percent: percentUsed(usage.usedTokens, usage.tokenLimit),
+ };
+}
diff --git a/apps/app/src/app/lib/voice-core/transcriber.ts b/apps/app/src/app/lib/voice-core/transcriber.ts
index e6400640..f4617c59 100644
--- a/apps/app/src/app/lib/voice-core/transcriber.ts
+++ b/apps/app/src/app/lib/voice-core/transcriber.ts
@@ -35,8 +35,20 @@ export function errorCode(body: unknown): string | null {
return null;
}
-/** Maps a transcription service answer to the error the user reads. */
-export function voiceErrorFromResponse(status: number, code: string | null, retryAfter: number | null): VoiceError {
+/** The readable message of `{"error":{"message":"x"}}`, which the local broker writes for a spent grant. */
+function errorMessage(body: unknown): string | null {
+ if (!body || typeof body !== "object") return null;
+ const error = (body as Record<string, unknown>).error;
+ const message = error && typeof error === "object" ? (error as Record<string, unknown>).message : null;
+ return typeof message === "string" && message.trim() ? message.trim() : null;
+}
+
+/**
+ * Maps a transcription service answer to the error the user reads. `message`
+ * is the service's own words for a spent grant (which limit ran out and when
+ * it resets); without them the general copy stands.
+ */
+export function voiceErrorFromResponse(status: number, code: string | null, retryAfter: number | null, message: string | null = null): VoiceError {
if (status === 401 || code === "omnirush_account_required") {
return new VoiceError("signed_out", "Sign in to omnirush.ai to use voice.", { status });
}
@@ -57,7 +69,7 @@ export function voiceErrorFromResponse(status: number, code: string | null, retr
return new VoiceError(
"rate_limited",
code === "daily_grant_exhausted"
- ? "You have used today's model allowance, which voice falls back on. It refills at 00:00 UTC."
+ ? message ?? "You have used today's model allowance, which voice falls back on. It refills at 00:00 UTC."
: budget ? "You have used today's voice allowance. It refills at 00:00 UTC." : "Voice is busy. Try again in a moment.",
{ status, retryable: !budget, retryAfterMs: retryAfter },
);
@@ -125,7 +137,7 @@ export class RemoteTranscriber implements Transcriber {
} catch {
body = null;
}
- if (!response.ok) throw voiceErrorFromResponse(response.status, errorCode(body), retryAfterMs(response));
+ if (!response.ok) throw voiceErrorFromResponse(response.status, errorCode(body), retryAfterMs(response), errorMessage(body));
const value = body && typeof body === "object" ? (body as Record<string, unknown>).text : null;
if (typeof value !== "string") {
throw new VoiceError("network", "The transcription service sent an unexpected answer.", { retryable: true, status: response.status });
diff --git a/apps/app/src/components/chat/message-list.tsx b/apps/app/src/components/chat/message-list.tsx
index adab11ea..83dd68e3 100644
--- a/apps/app/src/components/chat/message-list.tsx
+++ b/apps/app/src/components/chat/message-list.tsx
@@ -849,6 +849,7 @@ const MessageComponent = React.memo(
showDescriptionOnResume={presentation?.kind === "provider-incomplete"}
resumePrompt={presentation?.recoveryPrompt}
technicalDetails={presentation?.technicalDetails}
+ action={presentation?.action}
/>
)
}
@@ -946,6 +947,8 @@ interface ErrorMessageProps {
resumePrompt?: string | null
/** Error type, status, provider, code, response body — for bug reports and support. */
technicalDetails?: string | null
+ /** A page that fixes the error ("Open console"), opened in the browser. */
+ action?: { label: string; link: string } | null
}
/**
@@ -1010,7 +1013,7 @@ function SessionErrorTechnicalDetails({ details, tone }: { details: string; tone
)
}
-function ErrorMessage({ error, description, showDescriptionOnResume, resumePrompt, technicalDetails }: ErrorMessageProps) {
+function ErrorMessage({ error, description, showDescriptionOnResume, resumePrompt, technicalDetails, action }: ErrorMessageProps) {
const { onResumeInterrupted, developerMode } = useMessageList()
// Status codes, provider names, and response bodies are for developers,
// admins, and support — not the plain-language card end users see. They
@@ -1060,6 +1063,17 @@ function ErrorMessage({ error, description, showDescriptionOnResume, resumePromp
{description && (!resumePrompt || showDescriptionOnResume) ? (
<p className="text-sm text-destructive/80 whitespace-pre-wrap">{description}</p>
) : null}
+ {action?.link ? (
+ <Button
+ variant="outline"
+ size="sm"
+ data-testid="session-error-action"
+ className="mt-1 h-7 w-fit text-xs"
+ onClick={() => void openDesktopUrl(action.link)}
+ >
+ {action.label}
+ </Button>
+ ) : null}
</div>
</div>
{details ? <SessionErrorTechnicalDetails details={details} tone="card" /> : null}
diff --git a/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx b/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx
index 8c53ef83..5d2f61d6 100644
--- a/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx
+++ b/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx
@@ -38,6 +38,7 @@ import { LazyMotion, Reorder, domMax, m, useDragControls } from "motion/react";
import { getDisplaySessionTitle } from "../../../../app/lib/session-title";
import { omnirushAccountStatus, type WorkspaceInfo } from "../../../../app/lib/desktop";
+import { omnirushUsageSummary } from "../../../../app/lib/omnirush-usage";
import { isDesktopRuntime } from "../../../../app/lib/runtime-env";
import { OmniRushDenHelpLink } from "../../workspace/omnirush-den-help-link";
import { NotificationBell } from "../../../shell/notification-center";
@@ -975,13 +976,6 @@ function OmniRushWordmark({ className }: { className?: string }) {
);
}
-function compactTokenCount(value: number): string {
- return new Intl.NumberFormat(undefined, {
- notation: "compact",
- maximumFractionDigits: 1,
- }).format(Math.max(0, value));
-}
-
function NativeAccountFooter({ onOpenAccountSettings }: { onOpenAccountSettings: () => void }) {
const [status, setStatus] = React.useState<NativeAccountStatus | null>(null);
@@ -1004,15 +998,12 @@ function NativeAccountFooter({ onOpenAccountSettings }: { onOpenAccountSettings:
const accountLabel = connected
? status?.displayName?.trim() || status?.email?.trim() || "Your account"
: "sign in to omnirush.ai";
- const usage = connected ? status?.usage : null;
- const usagePercent = usage && usage.tokenLimit > 0
- ? Math.min(100, Math.max(0, (usage.usedTokens / usage.tokenLimit) * 100))
- : 0;
+ const usage = connected && status?.usage ? omnirushUsageSummary(status.usage) : null;
// The account server label ("omnirush.ai", "localhost:8090 (local API)")
// only matters while connected; a signed-out footer keeps the sign-in hint.
const serverHost = connected ? status?.gatewayHost?.trim() || null : null;
const accountDetail = usage
- ? `${compactTokenCount(usage.remainingTokens)} tokens left today${serverHost ? ` · ${serverHost}` : ""}`
+ ? `${usage.short}${serverHost ? ` · ${serverHost}` : ""}`
: connected
? serverHost
? `connected to ${serverHost}`
@@ -1055,7 +1046,7 @@ function NativeAccountFooter({ onOpenAccountSettings }: { onOpenAccountSettings:
</span>
{usage ? (
<span className="mt-1 block h-0.5 overflow-hidden rounded-full bg-sidebar-border" aria-hidden="true">
- <span className="block h-full rounded-full bg-[#b9f45a]" style={{ width: `${usagePercent}%` }} />
+ <span className="block h-full rounded-full bg-[#b9f45a]" style={{ width: `${usage.percent}%` }} />
</span>
) : null}
</span>
diff --git a/apps/app/src/react-app/domains/session/sync/session-error.ts b/apps/app/src/react-app/domains/session/sync/session-error.ts
index 2437cbde..e652e305 100644
--- a/apps/app/src/react-app/domains/session/sync/session-error.ts
+++ b/apps/app/src/react-app/domains/session/sync/session-error.ts
@@ -11,8 +11,20 @@ export type OpencodeSessionErrorPresentation = {
description: string | null;
technicalDetails: string;
recoveryPrompt: string | null;
+ /** A page that fixes the error, opened in the browser (omnirush.ai's console for an account out of tokens). */
+ action?: { label: string; link: string } | null;
};
+/**
+ * An omnirush.ai error that ends with its console page ("… earn tokens every
+ * day: https://omnirush.ai/console/account"): the sentence without the link,
+ * and the link as the card's "Open console" button.
+ */
+function consoleLinkAction(message: string | null): { text: string; action: { label: string; link: string } } | null {
+ const [, text, link] = (message && /^(omnirush\.ai: [\s\S]+?):\s*(https?:\/\/\S+\/console\/account)\s*$/.exec(message)) || [];
+ return text && link ? { text: `${text}.`, action: { label: "Open console", link } } : null;
+}
+
export const interruptedTaskRecoveryPrompt = [
"Continue the interrupted task from the current state.",
"First inspect the conversation and workspace to verify which actions already completed.",
@@ -198,13 +210,15 @@ function technicalErrorDetails(error: unknown, fallback: string, fields: ReturnT
export function presentOpencodeSessionError(error: unknown, fallback = "Session failed"): OpencodeSessionErrorPresentation {
const fields = sessionErrorFields(error, fallback);
const kind = sessionErrorKind(fields.name, fields.message, fields.code, fields.responseBody);
- const fallbackTitle = normalizeSessionError(fields.message ?? defaultErrorMessage(fields.name, fallback));
+ const consoleLink = consoleLinkAction(fields.message);
+ const fallbackTitle = normalizeSessionError(consoleLink?.text ?? fields.message ?? defaultErrorMessage(fields.name, fallback));
return {
kind,
title: errorTitle(kind, fallbackTitle),
description: errorDescription(kind),
technicalDetails: technicalErrorDetails(error, fallback, fields),
recoveryPrompt: errorRecoveryPrompt(kind),
+ ...(consoleLink ? { action: consoleLink.action } : {}),
};
}
diff --git a/apps/app/src/react-app/domains/settings/pages/general-view.tsx b/apps/app/src/react-app/domains/settings/pages/general-view.tsx
index 24c5651c..b3c95e88 100644
--- a/apps/app/src/react-app/domains/settings/pages/general-view.tsx
+++ b/apps/app/src/react-app/domains/settings/pages/general-view.tsx
@@ -25,6 +25,7 @@ import {
omnirushAccountStatus,
} from "../../../../app/lib/desktop";
import type { OmniRushRuntimeApprovals } from "../../../../app/lib/omnirush-server";
+import { omnirushUsageSummary } from "../../../../app/lib/omnirush-usage";
import { isElectronRuntime } from "../../../../app/utils";
import {
FULL_PERMISSIONS_HELP,
@@ -98,13 +99,6 @@ function SettingsCard(props: {
);
}
-function compactTokenCount(value: number): string {
- return new Intl.NumberFormat(undefined, {
- notation: "compact",
- maximumFractionDigits: 1,
- }).format(Math.max(0, value));
-}
-
export type AccountSignOutOutcome = {
remoteRevoked: boolean;
/** Absent when the desktop bridge predates the outcome reasons. */
@@ -226,6 +220,7 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {
}
const serverLine = account ? accountServerLine(account) : null;
+ const usage = account?.connected && account.usage ? omnirushUsageSummary(account.usage) : null;
return (
<div className="w-full max-w-3xl space-y-8">
@@ -252,8 +247,8 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {
) : null}
<div className="mt-0.5 text-[11px] text-dls-secondary">
{accountMessage || (account.connected
- ? account.usage
- ? `${compactTokenCount(account.usage.remainingTokens)} of ${compactTokenCount(account.usage.tokenLimit)} tokens left today`
+ ? usage
+ ? usage.line
: "omnirush.ai models are ready on this Mac."
: account.gatewayConfigured
? account.reauthorizationRequired
@@ -268,11 +263,11 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {
Signed in. Your system has no keyring, so the sign-in is kept in a private file on this computer.
</div>
) : null}
- {account.connected && account.usage?.tokenLimit ? (
- <div className="mt-2 h-1.5 overflow-hidden rounded-full bg-dls-hover" aria-label={`${account.usage.usedTokens} tokens used today`}>
+ {usage ? (
+ <div className="mt-2 h-1.5 overflow-hidden rounded-full bg-dls-hover" aria-label={`${Math.round(usage.percent)}% used`}>
<div
className="h-full rounded-full bg-[#b9f45a]"
- style={{ width: `${Math.min(100, Math.max(0, (account.usage.usedTokens / account.usage.tokenLimit) * 100))}%` }}
+ style={{ width: `${usage.percent}%` }}
/>
</div>
) : null}
diff --git a/apps/app/tests/general-view-account.test.ts b/apps/app/tests/general-view-account.test.ts
index 7cbfe396..59950d7b 100644
--- a/apps/app/tests/general-view-account.test.ts
+++ b/apps/app/tests/general-view-account.test.ts
@@ -1,10 +1,82 @@
import { describe, expect, test } from "bun:test";
+import type { OmniRushAccountUsage } from "@omnirush/types/desktop-ipc";
+
+import { omnirushUsageSummary, type UsageClock } from "../src/app/lib/omnirush-usage";
import {
accountServerLine,
accountSignOutMessage,
} from "../src/react-app/domains/settings/pages/general-view";
+describe("account usage in words", () => {
+ // Wednesday 21:00 UTC; the day resets at 00:00 UTC, the week on Monday.
+ const clock: UsageClock = { now: Date.parse("2026-09-30T21:00:00Z"), timeZone: "Asia/Kolkata", hourCycle: "h12" };
+ const daily = (day: Partial<NonNullable<OmniRushAccountUsage["day"]>>, extra: Partial<OmniRushAccountUsage> = {}): OmniRushAccountUsage => ({
+ tokenLimit: 0,
+ usedTokens: 0,
+ remainingTokens: 0,
+ period: "day",
+ grantModel: "daily",
+ limitScope: "day",
+ day: { allowance: 10_000_000, used: 0, reserved: 0, resetsAt: "2026-10-01T00:00:00Z", ...day },
+ week: { limit: 50_000_000, used: 0, resetsAt: "2026-10-05T00:00:00Z" },
+ pot: 0,
+ ...extra,
+ });
+
+ test("today's allowance, when it refills, and the bonus pot", () => {
+ expect(omnirushUsageSummary(daily({ used: 6_800_000 }, { pot: 500_000 }), clock)).toEqual({
+ short: "3.2M tokens left today",
+ line: "3.2M of 10M tokens left today · refills at 5:30 AM (in 3 h) · 500K bonus pot",
+ percent: 68,
+ });
+ });
+
+ test("says which limit ran out and when it resets", () => {
+ expect(omnirushUsageSummary(daily({ used: 10_000_000 }), clock)).toEqual({
+ short: "Today's tokens used up",
+ line: "Today's tokens are used up. They refill at 5:30 AM (in 3 h).",
+ percent: 100,
+ });
+ expect(omnirushUsageSummary(daily({ used: 1_000_000 }, { week: { limit: 50_000_000, used: 50_000_000, resetsAt: "2026-10-05T00:00:00Z" }, pot: 400_000 }), clock)).toEqual({
+ short: "Weekly cap reached · 400K bonus pot",
+ line: "This week's cap is reached. It resets Monday 5:30 AM (in 4 days). Your 400K bonus pot covers you until then.",
+ percent: 100,
+ });
+ // The cap leaves less than today's allowance: it is what binds.
+ expect(omnirushUsageSummary(daily({ used: 1_000_000 }, { week: { limit: 50_000_000, used: 48_000_000, resetsAt: "2026-10-05T00:00:00Z" } }), clock).line)
+ .toBe("2M tokens left today (weekly cap) · cap resets Monday 5:30 AM (in 4 days)");
+ });
+
+ test("an account without daily tokens: the one-time pot, and how to earn every day", () => {
+ expect(omnirushUsageSummary(daily({ allowance: 0 }, { pot: 500_000 }), clock)).toEqual({
+ short: "500K one-time tokens left",
+ line: "500K one-time tokens left. Link Discord or GitHub to get tokens every day.",
+ percent: 0,
+ });
+ expect(omnirushUsageSummary(daily({ allowance: 0 }), clock).line).toBe("No tokens left. Link Discord or GitHub to get tokens every day.");
+ });
+
+ test("an account with only its own weekly cap meters the week", () => {
+ const usage = daily({}, { limitScope: "week", week: { limit: 200_000_000, used: 50_000_000, resetsAt: "2026-10-05T00:00:00Z" } });
+ expect(omnirushUsageSummary(usage, clock)).toEqual({
+ short: "150M tokens left this week",
+ line: "150M of 200M tokens left this week · resets Monday 5:30 AM (in 4 days)",
+ percent: 25,
+ });
+ });
+
+ test("the weekly model and an older backend read as before", () => {
+ const legacy: OmniRushAccountUsage = { tokenLimit: 100_000, usedTokens: 1_234, remainingTokens: 98_766 };
+ expect(omnirushUsageSummary(legacy, clock)).toEqual({
+ short: "98.8K tokens left today",
+ line: "98.8K of 100K tokens left today",
+ percent: 1.234,
+ });
+ expect(omnirushUsageSummary({ ...legacy, period: "week", grantModel: "weekly" }, clock).short).toBe("98.8K tokens left this week");
+ });
+});
+
describe("settings sign-out message", () => {
test("says exactly what happened to the remote device session", () => {
expect(accountSignOutMessage({ remoteRevoked: true, reason: "revoked" }, "omnirush.ai")).toBe(
diff --git a/apps/app/tests/session-error-resilience.test.tsx b/apps/app/tests/session-error-resilience.test.tsx
index c1697648..54d4d323 100644
--- a/apps/app/tests/session-error-resilience.test.tsx
+++ b/apps/app/tests/session-error-resilience.test.tsx
@@ -291,6 +291,40 @@ describe("session error resilience", () => {
expect(html).not.toContain("bg-destructive/5")
})
+ test("an account out of tokens gets the console as a button, not a bare link", () => {
+ const error = {
+ name: "APIError",
+ data: {
+ message: "omnirush.ai: you have no tokens left. Link Discord or connect GitHub in the console to earn tokens every day: https://omnirush.ai/console/account",
+ statusCode: 429,
+ isRetryable: false,
+ },
+ }
+ const presentation = presentOpencodeSessionError(error)
+ expect(presentation.title).toBe(
+ "omnirush.ai: you have no tokens left. Link Discord or connect GitHub in the console to earn tokens every day.",
+ )
+ expect(presentation.action).toEqual({ label: "Open console", link: "https://omnirush.ai/console/account" })
+ // It survives the reload: the synthetic message keeps the button.
+ expect(sessionErrorPresentationFromUIMessage(createSessionErrorUIMessage("turn", presentation))?.action)
+ .toEqual(presentation.action)
+
+ const html = renderErrorTranscriptWithResume(error)
+ expect(html).toContain('data-testid="session-error-action"')
+ expect(html).toContain(">Open console<")
+ expect(html).not.toContain("https://omnirush.ai/console/account")
+ expect(html).not.toContain('data-testid="session-error-resume"')
+
+ // A spent day or week is words only.
+ const day = presentOpencodeSessionError({
+ name: "APIError",
+ data: { message: "omnirush.ai: today's tokens are used up. They refill at 5:30 AM (in 3 h).", statusCode: 429 },
+ })
+ expect(day.title).toBe("omnirush.ai: today's tokens are used up. They refill at 5:30 AM (in 3 h).")
+ expect(day.action).toBeUndefined()
+ expect(renderErrorTranscriptWithResume({ name: "APIError", data: { message: day.title } })).not.toContain("session-error-action")
+ })
+
test("keeps the destructive card for errors that cannot be resumed", () => {
const html = renderErrorTranscriptWithResume({
name: "ProviderAuthError",
diff --git a/apps/app/tests/voice-core.test.ts b/apps/app/tests/voice-core.test.ts
index 3e76b691..63762797 100644
--- a/apps/app/tests/voice-core.test.ts
+++ b/apps/app/tests/voice-core.test.ts
@@ -471,6 +471,20 @@ describe("remote transcriber", () => {
if (status === 429) expect((error as VoiceError).retryAfterMs).toBe(2_000);
});
+ test("a spent model grant reads the local broker's words for which limit ran out", async () => {
+ const message = "This week's cap is reached. It resets Monday 5:30 AM (in 4 days).";
+ const spent = (body: unknown) => new RemoteTranscriber({
+ url: "http://x",
+ fetch: async () => new Response(JSON.stringify(body), { status: 429, headers: { "retry-after": "60" } }),
+ }).transcribe(request, new AbortController().signal).catch((e: unknown) => e);
+ const worded = await spent({ error: { code: "daily_grant_exhausted", message } });
+ expect(worded).toBeInstanceOf(VoiceError);
+ expect((worded as VoiceError).message).toBe(message);
+ expect((worded as VoiceError).retryable).toBe(false);
+ const bare = await spent({ detail: "daily_grant_exhausted" });
+ expect((bare as VoiceError).message).toBe("You have used today's model allowance, which voice falls back on. It refills at 00:00 UTC.");
+ });
+
test("a connection failure is a retryable network error", async () => {
const transcriber = new RemoteTranscriber({ url: "http://x", fetch: async () => { throw new TypeError("fetch failed"); } });
const error = await transcriber.transcribe(request, new AbortController().signal).catch((e: unknown) => e);
diff --git a/apps/desktop/electron/omnirush-account.mjs b/apps/desktop/electron/omnirush-account.mjs
index d8efcd37..c7822f61 100644
--- a/apps/desktop/electron/omnirush-account.mjs
+++ b/apps/desktop/electron/omnirush-account.mjs
@@ -16,6 +16,7 @@ import {
const execFileAsync = promisify(execFile);
/** @typedef {import("@omnirush/types/desktop-ipc").OmniRushAccountStatus} AccountStatus */
+/** @typedef {import("@omnirush/types/desktop-ipc").OmniRushAccountUsage} AccountUsage */
/** @typedef {import("@omnirush/types/desktop-ipc").OmniRushAccountSignOutReason} SignOutReason */
/** @typedef {{ remoteRevoked: boolean, reason: SignOutReason }} SignOutOutcome */
/**
@@ -187,17 +188,49 @@ function displayNameFromEmail(email) {
.join(" ");
}
+/** An ISO time the backend sent, or null. */
+function isoTime(value) {
+ return typeof value === "string" && Number.isFinite(Date.parse(value)) ? value : null;
+}
+
+/**
+ * /device/me `usage`: what can be used now (`token_limit`, `used_tokens`,
+ * `remaining_tokens`: the grant left plus the pot) and, from a backend with
+ * daily grants, today's allowance, the weekly cap over it and the one-time
+ * pot, so the app says which limit binds and when it resets.
+ * @returns {AccountUsage | null}
+ */
+function accountUsage(usage) {
+ if (!usage || typeof usage !== "object") return null;
+ const day = usage.day && typeof usage.day === "object" ? usage.day : null;
+ const week = usage.week && typeof usage.week === "object" ? usage.week : null;
+ return {
+ tokenLimit: Number(usage.token_limit) || 0,
+ usedTokens: Number(usage.used_tokens) || 0,
+ remainingTokens: Number(usage.remaining_tokens) || 0,
+ period: usage.period === "week" ? "week" : "day",
+ grantModel: usage.grant_model === "daily" || usage.grant_model === "weekly" ? usage.grant_model : null,
+ limitScope: usage.limit_scope === "day" || usage.limit_scope === "week" ? usage.limit_scope : null,
+ day: day
+ ? {
+ allowance: Number(day.allowance) || 0,
+ used: Number(day.used) || 0,
+ reserved: Number(day.reserved) || 0,
+ resetsAt: isoTime(day.resets_at),
+ }
+ : null,
+ week: week
+ ? { limit: Number(week.limit) || 0, used: Number(week.used) || 0, resetsAt: isoTime(week.resets_at) }
+ : null,
+ pot: usage.pot && typeof usage.pot === "object" ? Math.max(0, Number(usage.pot.balance) || 0) : 0,
+ };
+}
+
function accountProfile(value) {
if (!value || typeof value !== "object") return null;
const email = normalizeCredential(value.email);
if (!email) return null;
- const usage = value.usage && typeof value.usage === "object"
- ? {
- tokenLimit: Number(value.usage.token_limit) || 0,
- usedTokens: Number(value.usage.used_tokens) || 0,
- remainingTokens: Number(value.usage.remaining_tokens) || 0,
- }
- : null;
+ const usage = accountUsage(value.usage);
return {
email,
displayName: normalizeCredential(value.display_name) ?? displayNameFromEmail(email),
diff --git a/apps/desktop/electron/omnirush-account.test.mjs b/apps/desktop/electron/omnirush-account.test.mjs
index b4d744f9..d66e0525 100644
--- a/apps/desktop/electron/omnirush-account.test.mjs
+++ b/apps/desktop/electron/omnirush-account.test.mjs
@@ -175,6 +175,48 @@ test("profile lookup refreshes an expired device credential and persists the rot
assert.match(await readFile(options.filePath, "utf8"), /rotated-refresh/);
});
+test("status carries today's allowance, the weekly cap and the pot of daily grants", async () => {
+ const options = await storeOptions({
+ env: {
+ OMNIRUSH_DEV_MODE: "1",
+ OMNIRUSH_GATEWAY_URL: "http://localhost:8090/omnirush/v1",
+ OMNIRUSH_ACCESS_TOKEN: "access",
+ OMNIRUSH_REFRESH_TOKEN: "refresh",
+ },
+ fetchImpl: async (url) => {
+ assert.match(new URL(url).pathname, /\/device\/me$/);
+ return Response.json({
+ email: "[email protected]",
+ status: "active",
+ usage: {
+ token_limit: 10_500_000,
+ used_tokens: 6_800_000,
+ remaining_tokens: 3_700_000,
+ period: "day",
+ resets_at: "2026-10-01T00:00:00Z",
+ grant_model: "daily",
+ limit_scope: "day",
+ day: { allowance: 10_000_000, used: 6_800_000, reserved: 0, discord: 5_000_000, github: 5_000_000, power: 0, resets_at: "2026-10-01T00:00:00Z" },
+ week: { limit: 50_000_000, used: 20_000_000, resets_at: "2026-10-05T00:00:00Z" },
+ pot: { balance: 500_000 },
+ },
+ });
+ },
+ });
+ const status = await createDesktopOmniRushAccountStore(options).status();
+ assert.deepEqual(status.usage, {
+ tokenLimit: 10_500_000,
+ usedTokens: 6_800_000,
+ remainingTokens: 3_700_000,
+ period: "day",
+ grantModel: "daily",
+ limitScope: "day",
+ day: { allowance: 10_000_000, used: 6_800_000, reserved: 0, resetsAt: "2026-10-01T00:00:00Z" },
+ week: { limit: 50_000_000, used: 20_000_000, resetsAt: "2026-10-05T00:00:00Z" },
+ pot: 500_000,
+ });
+});
+
test("sign out prevents legacy credentials from being imported again", async () => {
let logoutBody = null;
const options = await storeOptions({
diff --git a/apps/server/src/omnirush-gateway-broker.test.ts b/apps/server/src/omnirush-gateway-broker.test.ts
index f0d01fc2..17dc1a3c 100644
--- a/apps/server/src/omnirush-gateway-broker.test.ts
+++ b/apps/server/src/omnirush-gateway-broker.test.ts
@@ -4,7 +4,7 @@ import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
-import { OmniRushGatewayBroker, guardEventStream } from "./omnirush-gateway-broker.js";
+import { OmniRushGatewayBroker, grantExhaustedCopy, guardEventStream, type GrantClock } from "./omnirush-gateway-broker.js";
import { OmniRushReasoningEffort } from "./opencode-plugins/omnirush-reasoning-effort.js";
import type { OmniRushGatewayCredentialBundle } from "./types.js";
@@ -940,6 +940,69 @@ describe("readable gateway errors", () => {
}
});
+ test("a spent grant says which limit ran out and when it resets, and is never resent", async () => {
+ const spent = (headers: Record<string, string>) => refusingBroker(429, JSON.stringify({ detail: "daily_grant_exhausted" }), {
+ "content-type": "application/json",
+ "retry-after": "60",
+ "x-ratelimit-limit-tokens": "5000000",
+ "x-ratelimit-remaining-tokens": "0",
+ ...headers,
+ }).handle(gatewayRequest({ model: "gpt-6-astra", input: "hi", stream: true }), "responses");
+
+ const resetsAt = new Date(Date.now() + 3 * 3_600_000).toISOString();
+ const day = await spent({ "x-omnirush-grant-scope": "day", "x-omnirush-grant-resets-at": resetsAt });
+ expect(day.status).toBe(429);
+ // The engine would otherwise resend it ten times, a Retry-After apart.
+ expect(day.headers.get("x-should-retry")).toBe("false");
+ expect(day.headers.get("retry-after")).toBe("60");
+ expect(day.headers.get("x-omnirush-grant-scope")).toBe("day");
+ const dayError = (await day.json() as { error: { message: string; code: string } }).error;
+ expect(dayError.code).toBe("daily_grant_exhausted");
+ expect(dayError.message).toMatch(/^omnirush\.ai: today's tokens are used up\. They refill at \d{1,2}:\d{2}( [AP]M)? \(in 3 h\)\.$/);
+
+ const week = await spent({ "x-omnirush-grant-scope": "week", "x-omnirush-grant-resets-at": new Date(Date.now() + 4 * 86_400_000).toISOString() });
+ expect((await week.json() as { error: { message: string } }).error.message)
+ .toMatch(/^omnirush\.ai: this week's cap is reached\. It resets [A-Z][a-z]+day \d{1,2}:\d{2}( [AP]M)? \(in 4 days\)\.$/);
+
+ const empty = await spent({ "x-omnirush-grant-scope": "empty" });
+ expect((await empty.json() as { error: { message: string } }).error.message).toBe(
+ "omnirush.ai: you have no tokens left. Link Discord or connect GitHub in the console to earn tokens every day: https://gateway.example/console/account",
+ );
+
+ // An older gateway without the headers: the general copy, still not resent.
+ const older = await spent({});
+ expect(older.headers.get("x-should-retry")).toBe("false");
+ expect((await older.json() as { error: { message: string } }).error.message).toBe(
+ "omnirush.ai: you have used today's model allowance. It refills at 00:00 UTC.",
+ );
+ });
+
+ test("grant copy on the user's clock: local time, then how long until it", () => {
+ const now = Date.parse("2026-09-30T21:00:00Z");
+ const headers = (scope: string, resetsAt?: string) => new Headers({
+ "x-omnirush-grant-scope": scope,
+ ...(resetsAt ? { "x-omnirush-grant-resets-at": resetsAt } : {}),
+ });
+ const india: GrantClock = { now, timeZone: "Asia/Kolkata", hourCycle: "h12" };
+ expect(grantExhaustedCopy(headers("day", "2026-10-01T00:00:00Z"), null, india))
+ .toBe("Today's tokens are used up. They refill at 5:30 AM (in 3 h).");
+ expect(grantExhaustedCopy(headers("week", "2026-10-05T00:00:00Z"), null, india))
+ .toBe("This week's cap is reached. It resets Monday 5:30 AM (in 4 days).");
+ // West of UTC the week resets on Sunday afternoon; 24-hour clocks stay 24-hour.
+ expect(grantExhaustedCopy(headers("week", "2026-10-05T00:00:00Z"), null, { now, timeZone: "America/Los_Angeles", hourCycle: "h12" }))
+ .toBe("This week's cap is reached. It resets Sunday 5:00 PM (in 4 days).");
+ expect(grantExhaustedCopy(headers("day", "2026-09-30T21:40:00Z"), null, { now, timeZone: "Europe/Berlin", hourCycle: "h23" }))
+ .toBe("Today's tokens are used up. They refill at 23:40 (in 40 min).");
+ // Without a reset time the known UTC reset; a scope in another case still reads.
+ expect(grantExhaustedCopy(headers("DAY"), null, india)).toBe("Today's tokens are used up. They refill at 00:00 UTC.");
+ expect(grantExhaustedCopy(headers("week"), null, india)).toBe("This week's cap is reached. It resets Monday 00:00 UTC.");
+ expect(grantExhaustedCopy(headers("empty"), null, india))
+ .toBe("You have no tokens left. Link Discord or connect GitHub in the console to earn tokens every day.");
+ // No scope, or one this app does not know: the caller's general copy.
+ expect(grantExhaustedCopy(new Headers(), null, india)).toBeNull();
+ expect(grantExhaustedCopy(headers("month", "2026-10-01T00:00:00Z"), null, india)).toBeNull();
+ });
+
test("keep what a provider error names as refused", async () => {
const body = { error: { type: "upstream_error", code: "provider_error", message: "Upstream returned an error: Unknown parameter: 'stop'.", param: "stop" } };
const response = await refusingBroker(400, JSON.stringify(body)).handle(gatewayRequest({ model: "meta-muse-spark", input: "hi" }), "responses");
diff --git a/apps/server/src/omnirush-gateway-broker.ts b/apps/server/src/omnirush-gateway-broker.ts
index 44b752e9..c0ec98d1 100644
--- a/apps/server/src/omnirush-gateway-broker.ts
+++ b/apps/server/src/omnirush-gateway-broker.ts
@@ -154,6 +154,42 @@ export function gatewayErrorMessage(code: string, detail?: string | null): strin
return why ? `omnirush.ai: ${copy} (${why})` : `omnirush.ai: ${copy}`;
}
+/** The user's clock for a grant reset; tests pin it, the app uses the system's. */
+export type GrantClock = { now?: number; timeZone?: string; hourCycle?: Intl.DateTimeFormatOptions["hourCycle"] };
+
+/**
+ * What a `daily_grant_exhausted` refusal ran out of, from the gateway's
+ * `x-omnirush-grant-scope` ('day' | 'week' | 'empty') and
+ * `x-omnirush-grant-resets-at` (UTC ISO 8601), with the reset on the user's
+ * clock: "Today's tokens are used up. They refill at 5:30 AM (in 3 h)."
+ * Null without a known scope (an older gateway): the caller keeps its
+ * general copy.
+ */
+export function grantExhaustedCopy(headers: Headers, consoleUrl: string | null, clock: GrantClock = {}): string | null {
+ const scope = headers.get("x-omnirush-grant-scope")?.trim().toLowerCase();
+ if (scope === "empty") {
+ return `You have no tokens left. Link Discord or connect GitHub in the console to earn tokens every day${consoleUrl ? `: ${consoleUrl}` : "."}`;
+ }
+ if (scope !== "day" && scope !== "week") return null;
+ const at = Date.parse(headers.get("x-omnirush-grant-resets-at") ?? "");
+ const when = Number.isFinite(at) ? localReset(at, scope, clock) : scope === "day" ? "00:00 UTC" : "Monday 00:00 UTC";
+ return scope === "day" ? `Today's tokens are used up. They refill at ${when}.` : `This week's cap is reached. It resets ${when}.`;
+}
+
+/** "5:30 AM (in 3 h)", or "Monday 5:30 AM (in 4 days)" for the week: English words, the user's time zone and 12/24-hour style. */
+function localReset(at: number, scope: "day" | "week", clock: GrantClock): string {
+ const { timeZone } = clock;
+ const hourCycle = clock.hourCycle ?? new Intl.DateTimeFormat(undefined, { hour: "numeric" }).resolvedOptions().hourCycle;
+ const time = new Intl.DateTimeFormat("en-US", { hour: "numeric", minute: "2-digit", hourCycle, timeZone }).format(at);
+ const local = scope === "week" ? `${new Intl.DateTimeFormat("en-US", { weekday: "long", timeZone }).format(at)} ${time}` : time;
+ const left = at - (clock.now ?? Date.now());
+ if (left <= 0) return local;
+ const minutes = Math.max(1, Math.round(left / 60_000));
+ const hours = Math.round(minutes / 60);
+ const relative = minutes < 60 ? `${minutes} min` : hours < 48 ? `${hours} h` : `${Math.round(hours / 24)} days`;
+ return `${local} (in ${relative})`;
+}
+
function stringField(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
@@ -411,9 +447,10 @@ export function guardEventStream(
* A gateway error body with readable copy for the codes the gateway and the
* relay use (`{"detail":"<code>"}` from the gateway itself, or an
* OpenAI-shaped `{"error":{code,message}}`), in the OpenAI shape the engine
- * reads its message from. Null leaves the body as it came.
+ * reads its message from. Null leaves the body as it came. `grant` is a
+ * spent grant's copy (grantExhaustedCopy), used for `daily_grant_exhausted`.
*/
-function readableErrorBody(text: string): string | null {
+function readableErrorBody(text: string, grant: string | null): { body: string; code: string } | null {
let payload: unknown;
try {
payload = JSON.parse(text);
@@ -425,21 +462,30 @@ function readableErrorBody(text: string): string | null {
const bareCode = stringField(payload.detail) ?? stringField(payload.error);
const code = bareCode ?? stringField(nested?.code);
if (!code) return null;
- const message = gatewayErrorMessage(code, stringField(nested?.message))
+ const message = (grant && code === "daily_grant_exhausted" ? `omnirush.ai: ${grant.charAt(0).toLowerCase()}${grant.slice(1)}` : null)
+ ?? gatewayErrorMessage(code, stringField(nested?.message))
?? (bareCode ? `omnirush.ai could not complete the model request (${code}).` : null);
if (!message) return null;
const param = stringField(nested?.param);
- return JSON.stringify({
- error: { message, type: stringField(nested?.type) ?? "omnirush_error", code, ...(param ? { param } : {}) },
- });
+ return {
+ body: JSON.stringify({
+ error: { message, type: stringField(nested?.type) ?? "omnirush_error", code, ...(param ? { param } : {}) },
+ }),
+ code,
+ };
}
-async function readableErrorResponse(response: Response): Promise<Response> {
+async function readableErrorResponse(response: Response, consoleUrl: string | null): Promise<Response> {
const text = await response.text().catch(() => "");
- return new Response(readableErrorBody(text) ?? text, {
+ const readable = readableErrorBody(text, grantExhaustedCopy(response.headers, consoleUrl));
+ const headers = responseHeaders(response.headers);
+ // A spent grant stays spent until its reset: the engine would otherwise
+ // resend the request ten times, each after the 429's Retry-After (60 s).
+ if (readable?.code === "daily_grant_exhausted") headers.set("x-should-retry", "false");
+ return new Response(readable?.body ?? text, {
status: response.status,
statusText: response.statusText,
- headers: responseHeaders(response.headers),
+ headers,
});
}
@@ -841,6 +887,11 @@ export class OmniRushGatewayBroker {
return Boolean(this.state && this.engineToken);
}
+ /** The console's Account page on the account's server (where Discord and GitHub are linked). */
+ get consoleUrl(): string | null {
+ return this.state ? new URL("/console/account", this.state.gatewayUrl).toString() : null;
+ }
+
async handle(request: Request, path: string): Promise<Response> {
if (!this.enabled || !this.state) return Response.json({ error: "omnirush_account_required" }, { status: 401 });
if (!secureEqual(bearerToken(request), this.engineToken)) {
@@ -902,7 +953,7 @@ export class OmniRushGatewayBroker {
// Sign-in failures keep their own answer above; every other gateway
// refusal reaches the user as readable copy instead of a bare code.
if (!response.ok && response.status !== 401 && contentType.includes("application/json")) {
- return await readableErrorResponse(response);
+ return await readableErrorResponse(response, this.consoleUrl);
}
const streamed = response.ok && response.body && contentType.includes("text/event-stream");
const responseBody = streamed && response.body
diff --git a/apps/server/src/omnirush-voice.test.ts b/apps/server/src/omnirush-voice.test.ts
index 69d23a21..7f60b0a7 100644
--- a/apps/server/src/omnirush-voice.test.ts
+++ b/apps/server/src/omnirush-voice.test.ts
@@ -92,6 +92,26 @@ describe("voice through the gateway broker", () => {
expect((await service.availability()).available).toBeNull();
});
+ test("a spent model grant says which limit ran out; without its headers the answer passes as it came", async () => {
+ const refusal = (headers: Record<string, string>) => new OmniRushVoiceService(broker(() => Response.json(
+ { detail: "daily_grant_exhausted" },
+ { status: 429, headers: { "retry-after": "60", ...headers } },
+ )));
+ const empty = await refusal({ "x-omnirush-grant-scope": "empty" }).transcribe(segmentUpload());
+ expect(empty.status).toBe(429);
+ expect(empty.headers.get("retry-after")).toBe("60");
+ expect(await empty.json()).toEqual({
+ error: {
+ code: "daily_grant_exhausted",
+ message: "You have no tokens left. Link Discord or connect GitHub in the console to earn tokens every day: https://gateway.example/console/account",
+ },
+ });
+ const day = await refusal({ "x-omnirush-grant-scope": "day" }).transcribe(segmentUpload());
+ expect(((await day.json()) as { error: { message: string } }).error.message).toBe("Today's tokens are used up. They refill at 00:00 UTC.");
+ const older = await refusal({}).transcribe(segmentUpload());
+ expect(await older.json()).toEqual({ detail: "daily_grant_exhausted" });
+ });
+
test("an older backend without the route (404) reads as voice unavailable", async () => {
const service = new OmniRushVoiceService(broker(() => new Response("not found", { status: 404 })));
const response = await service.transcribe(segmentUpload());
diff --git a/apps/server/src/omnirush-voice.ts b/apps/server/src/omnirush-voice.ts
index f83ec6ee..35ab9330 100644
--- a/apps/server/src/omnirush-voice.ts
+++ b/apps/server/src/omnirush-voice.ts
@@ -9,7 +9,7 @@
import { execFile } from "node:child_process";
import path from "node:path";
-import type { OmniRushGatewayBroker } from "./omnirush-gateway-broker.js";
+import { grantExhaustedCopy, type OmniRushGatewayBroker } from "./omnirush-gateway-broker.js";
/** 125 s of 16 kHz mono WAV plus multipart overhead; the backend enforces the same cap. */
export const VOICE_MAX_UPLOAD_BYTES = 4 * 1024 * 1024;
@@ -59,7 +59,7 @@ export function voiceStatusFromBody(body: unknown): VoiceAvailabilityState {
};
}
-type VoiceBroker = Pick<OmniRushGatewayBroker, "enabled" | "modelCatalog" | "voiceStatus" | "transcribe">;
+type VoiceBroker = Pick<OmniRushGatewayBroker, "enabled" | "consoleUrl" | "modelCatalog" | "voiceStatus" | "transcribe">;
type VoiceLog = (level: "info" | "warn", message: string, attributes?: Record<string, unknown>) => void;
export class OmniRushVoiceService {
@@ -175,6 +175,9 @@ export class OmniRushVoiceService {
if (response.status === 404 && !code) {
return Response.json({ error: { code: "voice_unavailable", message: "Voice input is not available on this account yet." } }, { status: 503 });
}
+ // Voice runs on the model grant: say which limit ran out and when it resets.
+ const grant = code === "daily_grant_exhausted" ? grantExhaustedCopy(response.headers, this.broker.consoleUrl) : null;
+ if (grant) return Response.json({ error: { code, message: grant } }, { status: response.status, headers });
return new Response(text, { status: response.status, headers });
}
}
diff --git a/packages/types/src/desktop-ipc.ts b/packages/types/src/desktop-ipc.ts
index dd349a73..d0db18e7 100644
--- a/packages/types/src/desktop-ipc.ts
+++ b/packages/types/src/desktop-ipc.ts
@@ -150,6 +150,26 @@ export type OmniRushAccountSignOutResult = {
reason: OmniRushAccountSignOutReason;
};
+/**
+ * The account's tokens (/device/me `usage`). The first three are what can be
+ * used now (the grant left plus the pot). With daily grants (`grantModel`
+ * "daily"), `day` is today's allowance (resets 00:00 UTC), `week` the weekly
+ * cap over it (resets Monday 00:00 UTC) and `pot` the one-time tokens used
+ * once either runs out; `limitScope` "week" means only the weekly cap binds.
+ * The grant fields are optional: an older desktop bridge leaves them out.
+ */
+export type OmniRushAccountUsage = {
+ tokenLimit: number;
+ usedTokens: number;
+ remainingTokens: number;
+ period?: "day" | "week";
+ grantModel?: "weekly" | "daily" | null;
+ limitScope?: "day" | "week" | null;
+ day?: { allowance: number; used: number; reserved: number; resetsAt: string | null } | null;
+ week?: { limit: number; used: number; resetsAt: string | null } | null;
+ pot?: number;
+};
+
export type OmniRushAccountStatus = {
connected: boolean;
gatewayConfigured: boolean;
@@ -157,7 +177,7 @@ export type OmniRushAccountStatus = {
email?: string | null;
displayName?: string | null;
accountStatus?: string | null;
- usage?: { tokenLimit: number; usedTokens: number; remainingTokens: number } | null;
+ usage?: OmniRushAccountUsage | null;
/** Gateway URL the connected account uses, or the configured default while signed out. */
gatewayUrl?: string | null;
/** Display label for the account server, e.g. "omnirush.ai" or "localhost:8090 (local API)". */