fix(web): address review findings on usage reporting
Per-environment auth, correct Codex fast-mode pricing, and several accuracy fixes raised by review. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
1 parent
98e451c6b8
commit
575d03fbef
12 files changed
+276
-100
No files matched your search
@@ -109,7 +109,7 @@ import {
|
||||
} from "./serverRuntimeState.ts";
|
||||
import { orchestrationHttpApiLayer } from "./orchestration/http.ts";
|
||||
import { usageHttpApiLayer } from "./usage/http.ts";
|
||||
import { UsageServiceLayer } from "./usage/UsageService.ts";
|
||||
import * as UsageService from "./usage/UsageService.ts";
|
||||
import * as NetService from "@t3tools/shared/Net";
|
||||
import * as RelayClient from "@t3tools/shared/relayClient";
|
||||
import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
|
||||
@@ -438,7 +438,7 @@ export const makeRoutesLayer = Layer.mergeAll(
|
||||
// usage reporting existed. Layer memoization shares the one connection.
|
||||
Layer.provide(
|
||||
usageHttpApiLayer.pipe(
|
||||
Layer.provide(UsageServiceLayer.pipe(Layer.provide(PersistenceLayerLive))),
|
||||
Layer.provide(UsageService.layer.pipe(Layer.provide(PersistenceLayerLive))),
|
||||
),
|
||||
),
|
||||
Layer.provide(serverEnvironmentHttpApiLayer),
|
||||
|
||||
@@ -14,6 +14,7 @@ import { readLocalAgentUsage } from "./localAgentUsage.ts";
|
||||
/** Scans cost real IO, so a snapshot is reused briefly rather than recomputed per request. */
|
||||
const CACHE_TTL_MILLIS = Duration.toMillis(Duration.seconds(60));
|
||||
const DEFAULT_WINDOW_DAYS = 30;
|
||||
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
const emptyTokens = {
|
||||
inputTokens: 0,
|
||||
@@ -32,69 +33,82 @@ export class UsageService extends Context.Service<
|
||||
}
|
||||
>()("t3/usage/UsageService") {}
|
||||
|
||||
export const UsageServiceLayer = Layer.effect(UsageService)(
|
||||
Effect.gen(function* () {
|
||||
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
|
||||
// Captured once so the returned effects carry no outstanding requirements.
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
export const make = Effect.gen(function* () {
|
||||
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
|
||||
// Captured once so the returned effects carry no outstanding requirements.
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
// Keyed by the resolved window so a narrower request cannot serve a wider
|
||||
// cached answer, or the reverse.
|
||||
const cache = new Map<
|
||||
string,
|
||||
{ readonly at: number; readonly snapshot: EnvironmentUsageSnapshot }
|
||||
>();
|
||||
// Keyed by the resolved window so a narrower request cannot serve a wider
|
||||
// cached answer, or the reverse.
|
||||
const cache = new Map<
|
||||
string,
|
||||
{ readonly at: number; readonly snapshot: EnvironmentUsageSnapshot }
|
||||
>();
|
||||
|
||||
const build = (sinceDate: string): Effect.Effect<EnvironmentUsageSnapshot> =>
|
||||
Effect.gen(function* () {
|
||||
const descriptor = yield* serverEnvironment.getDescriptor;
|
||||
const generatedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const activity = yield* readActivitySummary(`${sinceDate}T00:00:00.000Z`).pipe(
|
||||
Effect.provideService(SqlClient.SqlClient, sql),
|
||||
);
|
||||
const local = yield* Effect.tryPromise(() => readLocalAgentUsage({ sinceDate })).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Failed to read local agent usage logs", { cause }).pipe(
|
||||
Effect.as(undefined),
|
||||
),
|
||||
/** Snapshot plus whether the log scan actually succeeded. */
|
||||
const build = (
|
||||
sinceDate: string,
|
||||
): Effect.Effect<{ snapshot: EnvironmentUsageSnapshot; complete: boolean }> =>
|
||||
Effect.gen(function* () {
|
||||
const descriptor = yield* serverEnvironment.getDescriptor;
|
||||
const generatedAt = DateTime.formatIso(yield* DateTime.now);
|
||||
const activity = yield* readActivitySummary(`${sinceDate}T00:00:00.000Z`).pipe(
|
||||
Effect.provideService(SqlClient.SqlClient, sql),
|
||||
);
|
||||
const local = yield* Effect.tryPromise(() => readLocalAgentUsage({ sinceDate })).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("Failed to read local agent usage logs", { cause }).pipe(
|
||||
Effect.as(undefined),
|
||||
),
|
||||
);
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
environmentId: descriptor.environmentId,
|
||||
generatedAt,
|
||||
firstDate: local?.firstDate,
|
||||
lastDate: local?.lastDate,
|
||||
costUsd: local?.costUsd ?? 0,
|
||||
tokens: local?.tokens ?? emptyTokens,
|
||||
messages: local?.messages ?? 0,
|
||||
sessions: local?.sessions ?? 0,
|
||||
models: local?.models ?? [],
|
||||
daily: local?.daily ?? [],
|
||||
projects: local?.projects ?? [],
|
||||
rateLimits: local?.rateLimits ?? [],
|
||||
sources: local?.sources ?? [],
|
||||
activity,
|
||||
} satisfies EnvironmentUsageSnapshot;
|
||||
});
|
||||
const snapshot = {
|
||||
environmentId: descriptor.environmentId,
|
||||
generatedAt,
|
||||
firstDate: local?.firstDate,
|
||||
lastDate: local?.lastDate,
|
||||
costUsd: local?.costUsd ?? 0,
|
||||
tokens: local?.tokens ?? emptyTokens,
|
||||
messages: local?.messages ?? 0,
|
||||
sessions: local?.sessions ?? 0,
|
||||
models: local?.models ?? [],
|
||||
daily: local?.daily ?? [],
|
||||
projects: local?.projects ?? [],
|
||||
rateLimits: local?.rateLimits ?? [],
|
||||
sources: local?.sources ?? [],
|
||||
activity,
|
||||
} satisfies EnvironmentUsageSnapshot;
|
||||
return { snapshot, complete: local !== undefined };
|
||||
});
|
||||
|
||||
return {
|
||||
getSnapshot: (sinceDate) =>
|
||||
Effect.gen(function* () {
|
||||
const now = yield* DateTime.now;
|
||||
const resolved =
|
||||
sinceDate ??
|
||||
DateTime.formatIso(DateTime.subtract(now, { days: DEFAULT_WINDOW_DAYS })).slice(0, 10);
|
||||
return {
|
||||
getSnapshot: (sinceDate: string | undefined) =>
|
||||
Effect.gen(function* () {
|
||||
const now = yield* DateTime.now;
|
||||
const fallback = DateTime.formatIso(
|
||||
DateTime.subtract(now, { days: DEFAULT_WINDOW_DAYS }),
|
||||
).slice(0, 10);
|
||||
// The wire type is a plain string, so anything that is not a calendar
|
||||
// date falls back to the default window instead of reaching the query.
|
||||
const resolved = sinceDate !== undefined && ISO_DATE.test(sinceDate) ? sinceDate : fallback;
|
||||
|
||||
const nowMillis = yield* Clock.currentTimeMillis;
|
||||
const cached = cache.get(resolved);
|
||||
if (cached !== undefined && nowMillis - cached.at < CACHE_TTL_MILLIS) {
|
||||
return cached.snapshot;
|
||||
}
|
||||
const snapshot = yield* build(resolved);
|
||||
cache.set(resolved, { at: nowMillis, snapshot });
|
||||
return snapshot;
|
||||
}),
|
||||
};
|
||||
}),
|
||||
);
|
||||
const startedAt = yield* Clock.currentTimeMillis;
|
||||
const cached = cache.get(resolved);
|
||||
if (cached !== undefined && startedAt - cached.at < CACHE_TTL_MILLIS) {
|
||||
return cached.snapshot;
|
||||
}
|
||||
const { snapshot, complete } = yield* build(resolved);
|
||||
// Only cache a complete read, and stamp it on completion so a slow
|
||||
// scan does not immediately expire. A failed scan reports zeros once
|
||||
// rather than pinning the page at $0 for the whole TTL.
|
||||
if (complete) {
|
||||
const finishedAt = yield* Clock.currentTimeMillis;
|
||||
cache.set(resolved, { at: finishedAt, snapshot });
|
||||
}
|
||||
return snapshot;
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(UsageService, make);
|
||||
@@ -81,6 +81,9 @@ export const readActivitySummary = (
|
||||
LIMIT ${TOP_N}
|
||||
`;
|
||||
|
||||
// Timestamps are stored as ISO-8601 UTC, so these buckets are UTC hours.
|
||||
// Keeping them UTC is what makes them safe to sum across environments in
|
||||
// different timezones; the UI labels the axis accordingly.
|
||||
const hourRows = yield* sql<{ hour: unknown; count: unknown }>`
|
||||
SELECT
|
||||
CAST(strftime('%H', requested_at) AS INTEGER) AS hour,
|
||||
@@ -98,7 +101,11 @@ export const readActivitySummary = (
|
||||
WHERE kind = 'tool.completed' AND created_at >= ${sinceIso}) AS toolCalls,
|
||||
(SELECT COUNT(*) FROM projection_thread_activities
|
||||
WHERE kind = 'tool.completed' AND created_at >= ${sinceIso}
|
||||
AND json_extract(payload_json, '$.data.item.exitCode') NOT IN (0)) AS toolFailures
|
||||
AND (
|
||||
json_extract(payload_json, '$.data.item.exitCode') NOT IN (0)
|
||||
-- Claude tool results carry no exit code; they flag failure here.
|
||||
OR json_extract(payload_json, '$.data.result.is_error') = 1
|
||||
)) AS toolFailures
|
||||
`;
|
||||
|
||||
const churn = yield* sql<Record<string, unknown>>`
|
||||
|
||||
@@ -3,7 +3,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
|
||||
import { annotateEnvironmentRequest, requireEnvironmentScope } from "../auth/http.ts";
|
||||
import { UsageService } from "./UsageService.ts";
|
||||
import * as UsageService from "./UsageService.ts";
|
||||
|
||||
/**
|
||||
* Usage is read-only reporting over data the host already has, so it rides the
|
||||
@@ -13,7 +13,7 @@ export const usageHttpApiLayer = HttpApiBuilder.group(
|
||||
EnvironmentHttpApi,
|
||||
"usage",
|
||||
Effect.fnUntraced(function* (handlers) {
|
||||
const usage = yield* UsageService;
|
||||
const usage = yield* UsageService.UsageService;
|
||||
|
||||
return handlers.handle(
|
||||
"snapshot",
|
||||
|
||||
@@ -176,6 +176,26 @@ describe("readLocalAgentUsage", () => {
|
||||
expect(result.costUsd).toBe(0);
|
||||
});
|
||||
|
||||
it("does not charge Codex fast rates when the log reports no premium tier", async () => {
|
||||
const result = await withFixture(async ({ codex }) => {
|
||||
await write(NodePath.join(codex, "2099", "s.jsonl"), [
|
||||
{ type: "turn_context", payload: { model: "gpt-5.6-sol", service_tier: "default" } },
|
||||
codexTokenCount({ input: 1_000_000, cached: 0, output: 0 }),
|
||||
]);
|
||||
});
|
||||
|
||||
const pricing = lookupPricing("gpt-5.6-sol");
|
||||
expect(pricing?.fastMultiplier).toBe(2);
|
||||
// Standard tier bills the base rate, not the doubled fast rate.
|
||||
expect(result.costUsd).toBeCloseTo(pricing!.input, 6);
|
||||
});
|
||||
|
||||
it("resolves a dated model slug to its family but not an unrelated slug", () => {
|
||||
expect(lookupPricing("claude-haiku-4-5-20251001")).toEqual(lookupPricing("claude-haiku-4-5"));
|
||||
// `gpt-5000` starts with `gpt-5` but is a different model, not a variant.
|
||||
expect(lookupPricing("gpt-5000-turbo")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns empty totals when neither agent has logs on this host", async () => {
|
||||
const result = await withFixture(async () => {});
|
||||
|
||||
|
||||
@@ -142,7 +142,11 @@ async function isStale(path: string, sinceDate: string | undefined): Promise<boo
|
||||
if (sinceDate === undefined) return false;
|
||||
try {
|
||||
const info = await NodeFSP.stat(path);
|
||||
return info.mtime.toISOString().slice(0, 10) < sinceDate;
|
||||
// One day of slack: mtime is UTC while sinceDate is a calendar day, and a
|
||||
// boundary file must never be dropped just because the two disagree.
|
||||
const cutoff = new Date(`${sinceDate}T00:00:00.000Z`);
|
||||
cutoff.setUTCDate(cutoff.getUTCDate() - 1);
|
||||
return info.mtime < cutoff;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
@@ -204,7 +208,7 @@ function record(
|
||||
|
||||
const projectOf = (cwd: unknown): string => {
|
||||
if (typeof cwd !== "string" || cwd.length === 0) return "unknown";
|
||||
const parts = cwd.split("/").filter((part) => part.length > 0);
|
||||
const parts = cwd.split(/[/\\]/).filter((part) => part.length > 0);
|
||||
return parts.at(-1) ?? "unknown";
|
||||
};
|
||||
|
||||
@@ -336,6 +340,10 @@ async function scanCodex(
|
||||
let previous: CodexSnapshot | undefined;
|
||||
let model = "unknown";
|
||||
let cwd: unknown;
|
||||
// Codex only writes a service tier when the turn ran on a premium tier.
|
||||
// Absent that marker the turn is standard, so cost is never inflated by
|
||||
// assuming the multiplier applies.
|
||||
let fast = false;
|
||||
|
||||
for await (const entry of readJsonLines(file)) {
|
||||
const payload = entry["payload"];
|
||||
@@ -349,6 +357,8 @@ async function scanCodex(
|
||||
if (typeof candidate === "string" && candidate.length > 0) model = candidate;
|
||||
const candidateCwd = payloadRecord?.["cwd"];
|
||||
if (typeof candidateCwd === "string") cwd = candidateCwd;
|
||||
const tier = payloadRecord?.["service_tier"];
|
||||
if (typeof tier === "string") fast = tier === "fast" || tier === "priority";
|
||||
}
|
||||
if (payloadRecord?.["type"] !== "token_count") continue;
|
||||
|
||||
@@ -415,7 +425,7 @@ async function scanCodex(
|
||||
cacheReadTokens: delta.cacheReadTokens,
|
||||
cacheWrite5mTokens: 0,
|
||||
cacheWrite1hTokens: 0,
|
||||
fast: true,
|
||||
fast,
|
||||
},
|
||||
pricing,
|
||||
);
|
||||
|
||||
@@ -68,13 +68,22 @@ const PRICING: Readonly<Record<string, ModelPricing>> = {
|
||||
|
||||
const SLUGS_BY_LENGTH = Object.keys(PRICING).sort((a, b) => b.length - a.length);
|
||||
|
||||
/**
|
||||
* A prefix only matches on a version boundary, so `claude-haiku-4-5-20251001`
|
||||
* resolves to the `claude-haiku-4-5` family while an unrelated `gpt-5000` does
|
||||
* not silently inherit `gpt-5` pricing.
|
||||
*/
|
||||
const matchesFamily = (slug: string, family: string): boolean =>
|
||||
slug.startsWith(family) &&
|
||||
(slug.length === family.length || /[-_@:.]/.test(slug[family.length] ?? ""));
|
||||
|
||||
/** Returns undefined for unknown slugs so callers can surface them explicitly. */
|
||||
export function lookupPricing(model: string): ModelPricing | undefined {
|
||||
const slug = model.trim().toLowerCase();
|
||||
const direct = PRICING[slug];
|
||||
if (direct !== undefined) return direct;
|
||||
const prefix = SLUGS_BY_LENGTH.find((candidate) => slug.startsWith(candidate));
|
||||
return prefix === undefined ? undefined : PRICING[prefix];
|
||||
const family = SLUGS_BY_LENGTH.find((candidate) => matchesFamily(slug, candidate));
|
||||
return family === undefined ? undefined : PRICING[family];
|
||||
}
|
||||
|
||||
export type CostInput = {
|
||||
|
||||
@@ -33,6 +33,37 @@ const compactTokens = (value: number): string => {
|
||||
const percent = (numerator: number, denominator: number): string =>
|
||||
denominator === 0 ? "0%" : `${((numerator / denominator) * 100).toFixed(1)}%`;
|
||||
|
||||
/** Providers report differently sized quota windows, so the tile names the real one. */
|
||||
const limitWindowLabel = (windowMinutes: number): string => {
|
||||
if (windowMinutes >= 10080) return `${Math.round(windowMinutes / 10080)}w`;
|
||||
if (windowMinutes >= 1440) return `${Math.round(windowMinutes / 1440)}d`;
|
||||
if (windowMinutes >= 60) return `${Math.round(windowMinutes / 60)}h`;
|
||||
return `${windowMinutes}m`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Days with no usage are absent from the series, so they are filled back in.
|
||||
* Without this the columns would sit adjacent and a quiet week would read as
|
||||
* continuous activity.
|
||||
*/
|
||||
const fillMissingDays = (daily: MergedUsage["daily"]): MergedUsage["daily"] => {
|
||||
const first = daily.at(0)?.date;
|
||||
const last = daily.at(-1)?.date;
|
||||
if (first === undefined || last === undefined) return daily;
|
||||
const byDate = new Map(daily.map((day) => [day.date, day]));
|
||||
const startMs = Date.parse(`${first}T00:00:00.000Z`);
|
||||
const endMs = Date.parse(`${last}T00:00:00.000Z`);
|
||||
if (Number.isNaN(startMs) || Number.isNaN(endMs) || endMs < startMs) return daily;
|
||||
|
||||
const DAY_MS = 86_400_000;
|
||||
// Bounded so a stray date can never produce an unbounded series.
|
||||
const span = Math.min(Math.round((endMs - startMs) / DAY_MS) + 1, 400);
|
||||
return Array.from({ length: span }, (_unused, index) => {
|
||||
const date = new Date(startMs + index * DAY_MS).toISOString().slice(0, 10);
|
||||
return byDate.get(date) ?? { date, costUsd: 0, totalTokens: 0, byProvider: [] };
|
||||
});
|
||||
};
|
||||
|
||||
function StatTile({ label, value, detail }: { label: string; value: string; detail?: string }) {
|
||||
return (
|
||||
<div className="min-w-0 px-4 py-3 sm:px-5">
|
||||
@@ -53,12 +84,13 @@ function StatTile({ label, value, detail }: { label: string; value: string; deta
|
||||
* Stacked columns, one per day, split by provider. Heights are percentages of
|
||||
* the busiest day so the chart needs no measurement pass.
|
||||
*/
|
||||
function DailyChart({ daily }: { daily: MergedUsage["daily"] }) {
|
||||
if (daily.length === 0) {
|
||||
function DailyChart({ daily: input }: { daily: MergedUsage["daily"] }) {
|
||||
if (input.length === 0) {
|
||||
return (
|
||||
<div className="px-4 py-8 text-xs text-muted-foreground sm:px-5">No usage recorded.</div>
|
||||
);
|
||||
}
|
||||
const daily = fillMissingDays(input);
|
||||
const max = Math.max(...daily.map((day) => day.costUsd), 0.01);
|
||||
return (
|
||||
<div className="px-4 sm:px-5">
|
||||
@@ -276,7 +308,7 @@ function HourStrip({ turnsByHour }: { turnsByHour: ReadonlyArray<number> }) {
|
||||
const max = Math.max(...turnsByHour, 1);
|
||||
return (
|
||||
<div className="px-4 sm:px-5">
|
||||
<div className="grid grid-cols-24 gap-[2px]">
|
||||
<div className="grid gap-[2px]" style={{ gridTemplateColumns: "repeat(24, minmax(0, 1fr))" }}>
|
||||
{turnsByHour.map((count, hour) => (
|
||||
<span
|
||||
key={`hour-${String(hour)}`}
|
||||
@@ -375,7 +407,11 @@ export function UsageSettings() {
|
||||
detail={`${merged.toolCalls.toLocaleString("en-US")} calls`}
|
||||
/>
|
||||
<StatTile
|
||||
label={rateLimit === undefined ? "Code written" : "Weekly limit"}
|
||||
label={
|
||||
rateLimit === undefined
|
||||
? "Code written"
|
||||
: `${limitWindowLabel(rateLimit.windowMinutes)} limit`
|
||||
}
|
||||
value={
|
||||
rateLimit === undefined
|
||||
? `+${compactTokens(merged.linesAdded)}`
|
||||
@@ -408,7 +444,7 @@ export function UsageSettings() {
|
||||
<EnvironmentsTable entries={entries} />
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection title="Turns by hour">
|
||||
<SettingsSection title="Turns by hour (UTC)">
|
||||
<HourStrip turnsByHour={merged.turnsByHour} />
|
||||
</SettingsSection>
|
||||
|
||||
|
||||
+40
-23
@@ -1,4 +1,5 @@
|
||||
import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc";
|
||||
import { ManagedRelay } from "@t3tools/client-runtime/relay";
|
||||
import { fetchEnvironmentUsageSnapshot } from "@t3tools/client-runtime/state/usage";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
EnvironmentUsageSnapshot,
|
||||
@@ -7,11 +8,11 @@ import type {
|
||||
UsageModelTotals,
|
||||
UsageProvider,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Data from "effect/Data";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { primaryEnvironmentHttpLayer } from "../environments/primary/httpLayer";
|
||||
import { runtime } from "../lib/runtime";
|
||||
import { readPreparedConnection } from "./session";
|
||||
import { useEnvironments } from "./environments";
|
||||
|
||||
@@ -178,21 +179,15 @@ export function mergeUsage(entries: ReadonlyArray<EnvironmentUsageEntry>): Merge
|
||||
}
|
||||
|
||||
/** Any failure reaching one environment, flattened so callers handle one type. */
|
||||
export class UsageFetchError extends Data.TaggedError("UsageFetchError")<{
|
||||
readonly cause: unknown;
|
||||
}> {}
|
||||
|
||||
const fetchSnapshot = (
|
||||
httpBaseUrl: string,
|
||||
sinceDate: string,
|
||||
): Effect.Effect<EnvironmentUsageSnapshot, UsageFetchError> =>
|
||||
Effect.gen(function* () {
|
||||
const client = yield* makeEnvironmentHttpApiClient(httpBaseUrl);
|
||||
return yield* client.usage.snapshot({ headers: {}, payload: { sinceDate } });
|
||||
}).pipe(
|
||||
Effect.provide(primaryEnvironmentHttpLayer),
|
||||
Effect.mapError((cause) => new UsageFetchError({ cause })),
|
||||
);
|
||||
export class UsageFetchError extends Schema.TaggedErrorClass<UsageFetchError>()("UsageFetchError", {
|
||||
environmentId: Schema.String,
|
||||
sinceDate: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
}) {
|
||||
override get message(): string {
|
||||
return `Failed to read usage since ${this.sinceDate} from environment ${this.environmentId}.`;
|
||||
}
|
||||
}
|
||||
|
||||
const isoDaysAgo = (days: number): string => {
|
||||
const date = new Date();
|
||||
@@ -206,13 +201,20 @@ export function useUsage(windowDays: number) {
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const requestId = useRef(0);
|
||||
|
||||
// Keyed on connection phase as well as identity: an environment that finishes
|
||||
// connecting after first paint must trigger a refetch, otherwise it would sit
|
||||
// at "Not connected" until the user manually refreshed.
|
||||
const targetKey = environments
|
||||
.map((environment) => `${environment.environmentId}:${environment.connection.phase}`)
|
||||
.join(",");
|
||||
|
||||
const targets = useMemo(
|
||||
() =>
|
||||
environments.map((environment) => ({
|
||||
environmentId: environment.environmentId,
|
||||
label: environment.label,
|
||||
})),
|
||||
[environments],
|
||||
[targetKey],
|
||||
);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
@@ -223,13 +225,28 @@ export function useUsage(windowDays: number) {
|
||||
|
||||
const results = await Promise.all(
|
||||
targets.map(async (target): Promise<EnvironmentUsageEntry> => {
|
||||
const connection = readPreparedConnection(target.environmentId);
|
||||
if (connection === null) {
|
||||
const prepared = readPreparedConnection(target.environmentId);
|
||||
if (prepared === null) {
|
||||
return { ...target, snapshot: null, error: "Not connected" };
|
||||
}
|
||||
try {
|
||||
const snapshot = await Effect.runPromise(
|
||||
fetchSnapshot(connection.httpBaseUrl, sinceDate),
|
||||
// Runs on the shared runtime, which supplies the HTTP client and the
|
||||
// relay DPoP signer, so the request carries this environment's own
|
||||
// credential (cookie, bearer, or DPoP) rather than the primary one's.
|
||||
const snapshot = await runtime.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
|
||||
return yield* fetchEnvironmentUsageSnapshot({ prepared, sinceDate, signer });
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new UsageFetchError({
|
||||
environmentId: target.environmentId,
|
||||
sinceDate,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
return { ...target, snapshot, error: null };
|
||||
} catch {
|
||||
|
||||
@@ -119,6 +119,10 @@
|
||||
"types": "./src/state/terminal.ts",
|
||||
"default": "./src/state/terminal.ts"
|
||||
},
|
||||
"./state/usage": {
|
||||
"types": "./src/state/usageSnapshotHttp.ts",
|
||||
"default": "./src/state/usageSnapshotHttp.ts"
|
||||
},
|
||||
"./state/threads": {
|
||||
"types": "./src/state/threads.ts",
|
||||
"default": "./src/state/threads.ts"
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { EnvironmentUsageSnapshot } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import type * as Option from "effect/Option";
|
||||
|
||||
import type { PreparedConnection } from "../connection/model.ts";
|
||||
import { environmentEndpointUrl } from "../environment/endpoint.ts";
|
||||
import type { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
|
||||
import {
|
||||
executeEnvironmentHttpRequest,
|
||||
makeEnvironmentHttpApiClient,
|
||||
type RemoteEnvironmentRequestError,
|
||||
} from "../rpc/http.ts";
|
||||
import { buildEnvironmentAuthHeaders, withEnvironmentCredentials } from "./environmentHttpAuth.ts";
|
||||
|
||||
/**
|
||||
* Scanning a host's agent session logs is disk-bound and can take seconds on a
|
||||
* machine with a long history, so this allows considerably more time than the
|
||||
* interactive snapshot fetches.
|
||||
*/
|
||||
const DEFAULT_USAGE_SNAPSHOT_TIMEOUT_MS = 30_000;
|
||||
|
||||
/**
|
||||
* Read one environment's usage snapshot over HTTP, authenticated with whatever
|
||||
* credential that connection was prepared with (cookie, bearer, or DPoP).
|
||||
*
|
||||
* Each host owns the agent logs its own runs wrote, so a usage page covering
|
||||
* several environments calls this once per environment and merges the results.
|
||||
*/
|
||||
export const fetchEnvironmentUsageSnapshot = Effect.fn(
|
||||
"clientRuntime.state.fetchEnvironmentUsageSnapshot",
|
||||
)(function* (input: {
|
||||
readonly prepared: PreparedConnection;
|
||||
readonly sinceDate: string;
|
||||
readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;
|
||||
readonly timeoutMs?: number;
|
||||
}) {
|
||||
const requestUrl = environmentEndpointUrl(input.prepared.httpBaseUrl, "/api/usage/snapshot");
|
||||
const client = yield* makeEnvironmentHttpApiClient(input.prepared.httpBaseUrl);
|
||||
const headers = yield* buildEnvironmentAuthHeaders(
|
||||
input.prepared.httpAuthorization,
|
||||
"GET",
|
||||
requestUrl,
|
||||
input.signer,
|
||||
);
|
||||
return yield* executeEnvironmentHttpRequest(
|
||||
requestUrl,
|
||||
input.timeoutMs ?? DEFAULT_USAGE_SNAPSHOT_TIMEOUT_MS,
|
||||
withEnvironmentCredentials(
|
||||
input.prepared.httpAuthorization,
|
||||
client.usage.snapshot({ payload: { sinceDate: input.sinceDate }, headers }),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
export type FetchEnvironmentUsageSnapshotError = RemoteEnvironmentRequestError;
|
||||
export type FetchedEnvironmentUsageSnapshot = EnvironmentUsageSnapshot;
|
||||
@@ -15,7 +15,7 @@ import { NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas.ts";
|
||||
export const UsageProvider = Schema.Literals(["claude", "codex"]);
|
||||
export type UsageProvider = typeof UsageProvider.Type;
|
||||
|
||||
/** An ISO date (YYYY-MM-DD) in the host's local timezone. */
|
||||
/** An ISO calendar date, `YYYY-MM-DD`, in UTC. */
|
||||
export const UsageDate = TrimmedNonEmptyString;
|
||||
export type UsageDate = typeof UsageDate.Type;
|
||||
|
||||
@@ -115,7 +115,10 @@ export const UsageActivitySummary = Schema.Struct({
|
||||
tools: Schema.Array(UsageActivityCount),
|
||||
skills: Schema.Array(UsageActivityCount),
|
||||
subagents: Schema.Array(UsageActivityCount),
|
||||
/** 24 buckets, index 0 is midnight local time. */
|
||||
/**
|
||||
* 24 buckets, index 0 is midnight UTC. UTC rather than host-local so buckets
|
||||
* from environments in different timezones can be summed by index.
|
||||
*/
|
||||
turnsByHour: Schema.Array(NonNegativeInt),
|
||||
totalTurns: NonNegativeInt,
|
||||
totalThreads: NonNegativeInt,
|
||||
|
||||
Reference in new issue
Block a user