Skip to content
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f

## [Unreleased]

### Fixes & Improvements

- **The Usage page stays responsive while it rescans, and Refresh always rescans.** The usage report is now computed in a worker thread, so a cold scan of every transcript no longer stops the server from answering other requests. An explicit **Refresh** always rescans instead of reusing a recent report, a refresh that arrives during a running scan joins it rather than starting a second one, and a report older than five minutes is never served from the cache while a rescan runs. The page also asks again when the server answers with a cached report, so it stops showing the previous visit's numbers as soon as the new scan lands; a failed re-ask keeps the cached numbers on screen, shows the error and retries with the same bounded backoff instead of stopping for good. A refresh that fails leaves the last successful report in place as a fallback. The single-file releases now ship the worker as `lib/usage-worker.mjs` beside the binary, where a compiled binary can start it, and its own build's dependencies are covered by the shipped third-party licenses.
- **`GET /api/usage` rejects incomplete and over-wide windows.** A window must now name both ends or neither: a lone `from` or `to` used to be accepted, ignored by the report (which applies a window only when both are present) and keyed separately, so it answered the plain 30-day report under its own cache key and paid for a full transcript scan every time. An explicit `from`/`to` pair that spans more than 400 days, is backwards, or is not a whole non-negative number now answers 400 `invalid_usage_window` instead of running a full transcript scan per distinct window. Every distinct `from`/`to` pair is its own cache key and its own scan, so an unbounded window let one client explore the transcript tree without limit; 400 days covers the page's widest range. Callers that passed `from=0` to mean "everything" must switch to `range=all` or send a window inside the limit.
- **A failed or killed refresh no longer empties the usage database.** An explicit refresh used to delete every stored row before the re-sync transaction opened, so a scan that hit the worker's deadline or failed midway left an empty database behind — and the next request then cached a zero-usage report as current. The delete now happens inside the same transaction as the re-sync: a refresh that does not commit rolls back and the previous numbers stay.

## [v0.7.4] - 2026-11-20

### Fixed
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1049,6 +1049,8 @@ Stop it with `Stop-ScheduledTask ompweb-host`, then end the running host with
| `OMP_WEB_STT_ENDPOINT` | OpenAI-compatible transcription endpoint URL. Leave unset to transcribe with `OMP_WEB_STT_MODEL` through omp's own credentials | _None_ |
| `OMP_WEB_STT_KEY` | Optional API key for the STT endpoint | _None_ |
| `OMP_WEB_STT_MODEL` | Model name for the STT endpoint. Without an endpoint: an omp speech-to-text model run with omp's logins, such as `openai-codex/codex-transcribe` (ChatGPT subscription; needs an omp version with that model) | _None (disabled without an endpoint)_ |
| `OMP_WEB_USAGE_WORKER` | Absolute path to the module that computes a usage report. It wins over the worker shipped with ompweb in every layout, including a release or compiled binary. Relative values are ignored with a warning: the worker runs with the server's provider credentials | _the worker shipped in `lib/`_ (`usage-worker.mjs` in a release, `usage-worker.ts` in a checkout) |
| `OMP_WEB_USAGE_TIMEOUT_MS` | How long a usage scan may run before it is killed and `GET /api/usage` answers `504 usage_timeout`. Raise it on a very large transcript tree | `600000` (10 minutes) |

**`OMP_WEB_NAME` and installed apps.** An installed app (PWA) is usually named after the page it was installed from. If you later change `OMP_WEB_NAME`, or reach omp-web through a different address while `OMP_WEB_NAME` is `url`, `host` or `domain`, your operating system may rename the installed app as well. Leave `OMP_WEB_NAME` empty, or set a name that identifies this omp-web server whatever domain name or address is used to reach it.

Expand Down
91 changes: 64 additions & 27 deletions app/api/usage/route.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,79 @@
import { apiErrorResponse } from "@/lib/api-utils";
import { isRecord } from "@/lib/type-guards";
import { getUsageReport } from "@/lib/usage-service";
import type { UsageGranularity, UsageTimeRange } from "@/lib/usage-types";

/** The usage page never needs a wider window; a wider one would just make each
* distinct `from` a fresh full transcript scan. */
const MAX_USAGE_WINDOW_MS = 400 * 24 * 60 * 60 * 1000;

function invalidWindow(): Response {
return Response.json({ error: "Invalid usage window", code: "invalid_usage_window" }, { status: 400 });
}

/** Epoch milliseconds, digits only; undefined when absent, null when invalid. */
function parseTimestamp(raw: string | null): number | undefined | null {
if (raw === null || raw === "") return undefined;
if (!/^\d{1,16}$/.test(raw)) return null;
const value = Number(raw);
return Number.isSafeInteger(value) ? value : null;
}

export async function GET(req: Request) {
try {
const url = new URL(req.url);
const rangeParam = url.searchParams.get("range");
const granularityParam = url.searchParams.get("granularity");
const projectParam = url.searchParams.get("project");
const fromParam = url.searchParams.get("from");
const toParam = url.searchParams.get("to");
const refreshParam = url.searchParams.get("refresh");

const validRanges: UsageTimeRange[] = ["today", "7d", "30d", "90d", "month", "all"];
const range: UsageTimeRange = validRanges.includes(rangeParam as UsageTimeRange)
? (rangeParam as UsageTimeRange)
: "30d";

const validGranularities: UsageGranularity[] = ["daily", "monthly", "projects"];
const granularity: UsageGranularity = validGranularities.includes(granularityParam as UsageGranularity)
? (granularityParam as UsageGranularity)
: "daily";

const from = fromParam ? parseInt(fromParam, 10) : undefined;
const to = toParam ? parseInt(toParam, 10) : undefined;
const forceRefresh = refreshParam === "true" || refreshParam === "1";
const url = new URL(req.url);
const rangeParam = url.searchParams.get("range");
const granularityParam = url.searchParams.get("granularity");
const projectParam = url.searchParams.get("project");
const refreshParam = url.searchParams.get("refresh");

const validRanges: UsageTimeRange[] = ["today", "7d", "30d", "90d", "month", "all"];
const range: UsageTimeRange = validRanges.includes(rangeParam as UsageTimeRange)
? (rangeParam as UsageTimeRange)
: "30d";

const validGranularities: UsageGranularity[] = ["daily", "monthly", "projects"];
const granularity: UsageGranularity = validGranularities.includes(granularityParam as UsageGranularity)
? (granularityParam as UsageGranularity)
: "daily";

const from = parseTimestamp(url.searchParams.get("from"));
const to = parseTimestamp(url.searchParams.get("to"));
if (from === null || to === null) return invalidWindow();
// A lone bound is rejected rather than ignored: the report only applies an
// explicit window when BOTH ends are present, so `from=<now-1d>` used to
// answer the plain 30-day report under its own cache key — a wrong answer
// that also paid for a full transcript scan per distinct value.
if ((from === undefined) !== (to === undefined)) return invalidWindow();
// Every distinct from/to pair is its own cache key and its own full scan, so
// an unbounded/backwards/open window would let one client explore the
// transcript tree without limit. 400 days covers the UI's widest range.
if (from !== undefined && to !== undefined && (from > to || to - from > MAX_USAGE_WINDOW_MS)) return invalidWindow();

const forceRefresh = refreshParam === "true" || refreshParam === "1";

try {
const report = await getUsageReport({
range,
granularity,
project: projectParam || undefined,
from: !isNaN(from as number) ? from : undefined,
to: !isNaN(to as number) ? to : undefined,
from,
to,
forceRefresh,
});

return Response.json(report);
} catch (error) {
return apiErrorResponse(error);
// Paths and database messages stay in the server log; the client gets a
// stable code it can act on. Match on the code, not `instanceof`: a
// re-evaluated module or a worker restart need not share class identity.
// Log the message only: the error object carries a stack and often a
// transcript path, neither of which belongs in the log.
console.error("[api/usage]", error instanceof Error ? error.message : String(error));
const code = isRecord(error) && typeof error.code === "string" ? error.code : undefined;
if (code === "usage_busy") {
return Response.json({ error: "Usage scan busy", code: "usage_busy" }, { status: 503 });
}
if (code === "usage_timeout") {
return Response.json({ error: "Usage scan timed out", code: "usage_timeout" }, { status: 504 });
}
return Response.json({ error: "Usage report failed", code: "usage_failed" }, { status: 500 });
}
}
198 changes: 198 additions & 0 deletions components/UsageConfig.stale.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
import "../tests/setup-dom.mjs";
import assert from "node:assert/strict";
import test, { afterEach } from "node:test";
const { act, cleanup, fireEvent, render, screen, within } = await import("@testing-library/react/pure.js");
const { createElement } = await import("react");

const { UsageConfig, STALE_POLL_MS } = await import("./UsageConfig.tsx");

const originalFetch = globalThis.fetch;

afterEach(() => {
cleanup();
globalThis.fetch = originalFetch;
});

/**
* One report shaped like the API's. `records` is what the footer prints, so a
* test can tell two answers apart without depending on the chart's layout.
*/
function report(records, stale) {
return {
timeRange: "30d",
granularity: "daily",
summary: {
totalCost: 1,
totalTokens: 1000,
inputTokens: 1000,
outputTokens: 0,
reasoningTokens: 0,
cacheReadTokens: 0,
cacheWriteTokens: 0,
cacheSavings: 0,
activeDays: 1,
tokensPerActiveDay: 1000,
cachePercentage: 0,
costQuality: { providerReported: 100, modelPriced: 0, unpriced: 0 },
},
providers: [],
timeSeries: [],
modelBreakdown: [],
dayBreakdown: [],
projectBreakdown: [],
scanInfo: { transcriptsScanned: 1, transcriptsOutsideWindow: 0, usageRecordsCount: records, durationSeconds: 0.1, scannedAt: Date.now() },
stale,
scannedAt: Date.now(),
};
}

/** The footer's "Scanned … · N usage records · …" line, which names the served report. */
function recordsShown() {
// Testing Library matches every ancestor too; the innermost one is the footer.
const footer = screen.getAllByText(/^Scanned .* usage records/).reduce((a, b) => (a.textContent.length <= b.textContent.length ? a : b));
return Number(/· (\d+) usage records ·/.exec(footer.textContent ?? "")?.[1]);
}

/** Answers with `answers` in order, repeating the last one; records each URL. */
function serve(answers) {
const requested = [];
globalThis.fetch = async (url) => {
requested.push(String(url));
const answer = answers[Math.min(requested.length - 1, answers.length - 1)];
return { ok: true, json: async () => answer };
};
return requested;
}

test("a stale report is re-fetched until the background scan lands, so the page never keeps old numbers", async (t) => {
t.mock.timers.enable({ apis: ["setTimeout"] });
const requested = serve([
report(11, true), // the server served its cache while it rescans
report(22, false), // the rescan landed
]);

render(createElement(UsageConfig));
await act(async () => {});
assert.equal(requested.length, 1, "the first load asks once");
assert.equal(recordsShown(), 11, "the cached numbers show while the rescan runs");

await act(async () => t.mock.timers.tick(STALE_POLL_MS));
await act(async () => {});
assert.equal(requested.length, 2, "the stale answer triggers a second request");
assert.equal(recordsShown(), 22, "the page shows the rescanned numbers");

// The fresh answer ends the polling: no third request without a new reason.
await act(async () => t.mock.timers.tick(STALE_POLL_MS * 10));
await act(async () => {});
assert.equal(requested.length, 2, "a fresh report stops the re-fetch loop");
});

test("a fresh report is not re-fetched", async (t) => {
t.mock.timers.enable({ apis: ["setTimeout"] });
const requested = serve([report(11, false)]);

render(createElement(UsageConfig));
await act(async () => {});
await act(async () => t.mock.timers.tick(STALE_POLL_MS * 10));
await act(async () => {});
assert.equal(requested.length, 1);
assert.equal(recordsShown(), 11);
});

test("the refresh button asks for a rescan instead of reusing the cached report", async (t) => {
t.mock.timers.enable({ apis: ["setTimeout"] });
const requested = serve([report(11, false), report(33, false)]);

render(createElement(UsageConfig));
await act(async () => {});
assert.equal(requested.length, 1);

const refresh = screen.getByRole("button", { name: "Refresh usage data" });
await act(async () => refresh.click());
await act(async () => {});

assert.equal(requested.length, 2);
assert.match(requested[1], /refresh=true/);
assert.equal(recordsShown(), 33, "the refreshed numbers replace the old ones");
});

test("a slow earlier answer cannot overwrite a newer report", async (t) => {
t.mock.timers.enable({ apis: ["setTimeout"] });
const requested = [];
let releaseSlow;
const slow = new Promise((resolve) => { releaseSlow = resolve; });
globalThis.fetch = async (url) => {
requested.push(String(url));
// The second request (the refresh) is the slow one.
if (requested.length === 2) return { ok: true, json: () => slow };
return { ok: true, json: async () => report(requested.length === 1 ? 11 : 44, false) };
};

render(createElement(UsageConfig));
await act(async () => {});
assert.equal(recordsShown(), 11);

const refresh = screen.getByRole("button", { name: "Refresh usage data" });
await act(async () => refresh.click());
await act(async () => {});
// The slow refresh is still pending; a different query answers meanwhile.
// The range picker is a ThemedSelect (main replaced the native select with a
// Base UI listbox), so choose the option the way SettingsConfig's tests do.
// No waitFor here: this test mocks setTimeout, so waiting would never tick.
await act(async () => fireEvent.click(screen.getByLabelText("Time range")));
const sevenDays = within(document.body).getByRole("option", { name: "Last 7 days", exact: true });
await act(async () => {
fireEvent.pointerDown(sevenDays, { pointerType: "mouse" });
fireEvent.click(sevenDays);
});
await act(async () => {});
assert.equal(recordsShown(), 44, "the newer query's report is on screen");

// The refresh answers last with numbers for the old query; they must not win.
await act(async () => releaseSlow(report(99, false)));
await act(async () => {});
assert.equal(recordsShown(), 44, "the newer report stays on screen");
});

test("a failed stale poll reschedules with the bounded backoff and shows the error until a fresh report lands", async (t) => {
t.mock.timers.enable({ apis: ["setTimeout"] });
// The maintainer's sequence: stale report, 503 on the first poll, then a
// recovered fresh report. The 503 must neither stop the polling nor hide.
const requested = [];
globalThis.fetch = async (url) => {
requested.push(String(url));
if (requested.length === 1) return { ok: true, json: async () => report(11, true) };
if (requested.length === 2) return { ok: false, status: 503, statusText: "Service Unavailable", json: async () => ({}) };
return { ok: true, json: async () => report(22, false) };
};

render(createElement(UsageConfig));
await act(async () => {});
assert.equal(requested.length, 1);
assert.equal(recordsShown(), 11, "the stale report shows while the rescan runs");

await act(async () => t.mock.timers.tick(STALE_POLL_MS));
await act(async () => {});
assert.equal(requested.length, 2, "the stale answer schedules the first poll");
assert.equal(recordsShown(), 11, "the stale report stays on screen after a failed poll");
assert.ok(
screen.getByRole("alert").textContent?.includes("Service Unavailable"),
"the failure is visible while the stale report is shown",
);

// The next attempt uses the existing bounded backoff (2x), not a tight loop.
await act(async () => t.mock.timers.tick(STALE_POLL_MS));
await act(async () => {});
assert.equal(requested.length, 2, "no request before the doubled backoff elapsed");

await act(async () => t.mock.timers.tick(STALE_POLL_MS));
await act(async () => {});
assert.equal(requested.length, 3, "the failed poll rescheduled the next attempt");
assert.equal(recordsShown(), 22, "the recovered fresh report replaces the stale numbers");
assert.equal(screen.queryByRole("alert"), null, "the error clears once a report arrives");

// A fresh report ends the loop again.
await act(async () => t.mock.timers.tick(STALE_POLL_MS * 10));
await act(async () => {});
assert.equal(requested.length, 3, "a fresh report stops the re-fetch loop");
});
Loading
Loading