Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
feat(web): redesign usage and settings pages (#259)
Leoc8ac7143c564
diff --git a/apps/mobile/src/features/usage/usageProviders.ts b/apps/mobile/src/features/usage/usageProviders.tsindex 9986f7d25..80980d609 100644--- a/apps/mobile/src/features/usage/usageProviders.ts+++ b/apps/mobile/src/features/usage/usageProviders.ts@@ -5,11 +5,22 @@ import { useAppearancePreferences } from "../settings/appearance/AppearancePrefe* Series and table order. The chart stacks providers from the bottom in this* order, so it also fixes which band sits on top of the bars.*/-export const PROVIDER_ORDER: readonly UsageProviderKind[] = ["codex", "claude"];+export const PROVIDER_ORDER: readonly UsageProviderKind[] = [+ "codex",+ "claude",+ "cursor",+ "grok",+ "kimi",+ "opencode",+];export const PROVIDER_LABEL: Record<UsageProviderKind, string> = {claude: "Claude",codex: "Codex",+ cursor: "Cursor",+ grok: "Grok",+ kimi: "Kimi For Coding",+ opencode: "OpenCode",};/**@@ -21,5 +32,9 @@ export function useProviderColors(): Record<UsageProviderKind, string> {return {claude: "#d97757",codex: scheme === "dark" ? "#e6e6e6" : "#3c3c43",+ cursor: "#a78bfa",+ grok: "#94a3b8",+ kimi: "#60a5fa",+ opencode: "#34d399",};}diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 24c0c4284..82817eb95 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -42,6 +42,7 @@ import * as BitbucketApi from "./sourceControl/BitbucketApi.ts";import * as GitHubCli from "./sourceControl/GitHubCli.ts";import * as GitLabCli from "./sourceControl/GitLabCli.ts";import * as TextGeneration from "./textGeneration/TextGeneration.ts";+import * as ProviderUsageHistory from "./usage/ProviderUsageHistory.ts";import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts";import * as TerminalManager from "./terminal/Manager.ts";import * as McpHttpServer from "./mcp/McpHttpServer.ts";@@ -166,7 +167,10 @@ const BackgroundLayerLive = BackgroundPolicy.layer.pipe(Layer.provideMerge(ServerSettingsLayerLive),);-const UsageLayerLive = UsageService.layer.pipe(Layer.provide(ServerSettingsLayerLive));+const ProviderUsageHistoryLayerLive = ProviderUsageHistory.layer.pipe(+ Layer.provide(SqlitePersistenceLayerLive),+);+const UsageLayerLive = UsageService.layer.pipe(Layer.provide(ProviderUsageHistoryLayerLive));const ResourceDiagnosticsLayerLive = Layer.mergeAll(ResourceTelemetryLayerLive,diff --git a/apps/server/src/usage/ProviderUsageHistory.ts b/apps/server/src/usage/ProviderUsageHistory.tsnew file mode 100644index 000000000..93e2bcc1e--- /dev/null+++ b/apps/server/src/usage/ProviderUsageHistory.ts@@ -0,0 +1,86 @@+import { AkeruUsageEntry } from "@t3tools/contracts";+import * as Context from "effect/Context";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as Schema from "effect/Schema";+import * as SqlClient from "effect/unstable/sql/SqlClient";++import {+ type PersistenceDecodeError,+ PersistenceSqlError,+ toPersistenceDecodeError,+ toPersistenceSqlError,+} from "../persistence/Errors.ts";++export interface ProviderUsageWindow {+ readonly sinceAt: string;+ readonly untilAt: string;+}++export class ProviderUsageHistory extends Context.Service<+ ProviderUsageHistory,+ {+ readonly readReported: (+ window: ProviderUsageWindow,+ ) => Effect.Effect<+ ReadonlyArray<AkeruUsageEntry>,+ PersistenceSqlError | PersistenceDecodeError+ >;+ }+>()("akeru-bot/usage/ProviderUsageHistory") {}++const UsageRow = Schema.Struct({+ reservationId: Schema.String,+ sourceKey: Schema.String,+ botId: Schema.String,+ threadId: Schema.NullOr(Schema.String),+ turnId: Schema.NullOr(Schema.String),+ category: Schema.String,+ state: Schema.String,+ reservedTokens: Schema.Number,+ inputTokens: Schema.NullOr(Schema.Number),+ outputTokens: Schema.NullOr(Schema.Number),+ reasoningTokens: Schema.NullOr(Schema.Number),+ provider: Schema.NullOr(Schema.String),+ model: Schema.NullOr(Schema.String),+ unavailableReason: Schema.NullOr(Schema.String),+ createdAt: Schema.String,+ settledAt: Schema.NullOr(Schema.String),+});+type UsageRow = typeof UsageRow.Type;+const decodeUsageEntry = Schema.decodeUnknownEffect(AkeruUsageEntry);++const make = Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;++ const readReported = Effect.fn("ProviderUsageHistory.readReported")(function* (+ window: ProviderUsageWindow,+ ) {+ const rows = yield* sql<UsageRow>`+ SELECT+ reservation_id AS "reservationId", source_key AS "sourceKey", bot_id AS "botId",+ thread_id AS "threadId", turn_id AS "turnId", category, state,+ reserved_tokens AS "reservedTokens", input_tokens AS "inputTokens",+ output_tokens AS "outputTokens", reasoning_tokens AS "reasoningTokens",+ provider, model, unavailable_reason AS "unavailableReason",+ created_at AS "createdAt", settled_at AS "settledAt"+ FROM akeru_bot_usage_entries+ WHERE state = 'reported'+ AND provider IS NOT NULL+ AND model IS NOT NULL+ AND created_at >= ${window.sinceAt}+ AND created_at < ${window.untilAt}+ ORDER BY created_at ASC, reservation_id ASC+ `.pipe(Effect.mapError(toPersistenceSqlError("ProviderUsageHistory.readReported")));++ return yield* Effect.forEach(rows, (row) =>+ decodeUsageEntry(row).pipe(+ Effect.mapError(toPersistenceDecodeError("ProviderUsageHistory.readReported")),+ ),+ );+ });++ return ProviderUsageHistory.of({ readReported });+});++export const layer = Layer.effect(ProviderUsageHistory, make);diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.tsindex 37ef63df4..00beaf5d6 100644--- a/apps/server/src/usage/UsageService.test.ts+++ b/apps/server/src/usage/UsageService.test.ts@@ -1,45 +1,43 @@import * as NodeServices from "@effect/platform-node/NodeServices";import { expect, it } from "@effect/vitest";-import { UsageDay, type UsageSummaryInput } from "@t3tools/contracts";-import * as Schema from "effect/Schema";-import * as Clock from "effect/Clock";+import {+ AkeruUsageReservationId,+ BotId,+ ProviderDriverKind,+ ThreadId,+ type AkeruUsageEntry,+ type SubscriptionProviderId,+} from "@t3tools/contracts";import * as Deferred from "effect/Deferred";import * as Effect from "effect/Effect";-import * as Exit from "effect/Exit";import * as Fiber from "effect/Fiber";import * as FileSystem from "effect/FileSystem";-import * as Path from "effect/Path";-import * as Scope from "effect/Scope";import * as TestClock from "effect/testing/TestClock";import { HttpClient, HttpClientResponse } from "effect/unstable/http";-import { afterEach, vi } from "vite-plus/test";+import { afterEach, describe, vi } from "vite-plus/test";import * as ServerConfig from "../config.ts";-import * as ServerSettings from "../serverSettings.ts";+import { ProviderUsageHistory } from "./ProviderUsageHistory.ts";import * as UsageService from "./UsageService.ts";-import * as TranscriptReader from "./usageTranscriptReader.ts";vi.mock("../subscription-auth/service.ts", () => ({SubscriptionAuthService: {- forSecretsDir: () => ({ reload: () => {}, getPlanAccessToken: async () => undefined }),+ forSecretsDir: () => ({+ reload: () => {},+ statuses: () => [],+ getPlanAccessToken: async () => undefined,+ }),},}));vi.mock("./usagePlanLimits.ts", () => ({ readPlanLimits: async () => [] }));afterEach(() => vi.restoreAllMocks());-const DAY = 24 * 60 * 60 * 1000;const rateDocument = {- "claude-fable-5": { input_cost_per_token: 0.001, output_cost_per_token: 0.002 },-};-const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));-const input: UsageSummaryInput = {- sinceDay: UsageDay.make("2026-09-07"),- untilDay: UsageDay.make("2026-09-07"),- timeZone: "UTC",+ "test-model": { input_cost_per_token: 0.001, output_cost_per_token: 0.002 },};-const step = {- model: "claude-fable-5",+const pricedStep = {+ model: "test-model",totals: {uncachedInputTokens: 100,cachedInputTokens: 0,@@ -49,325 +47,124 @@ const step = {},reportedCostUsd: null,};-const transcript =- encodeJson({- type: "assistant",- timestamp: "2026-09-07T04:05:13.944Z",- sessionId: "session",- message: {- id: "message",- model: "claude-fable-5",- usage: { input_tokens: 100, output_tokens: 20 },- },- }) + "\n";-const makeFixture = Effect.fnUntraced(function* (- options: {- response?: Effect.Effect<Response>;- diskRates?: { fetchedAtMs: number; document: unknown };- } = {},-) {+const makeFixture = Effect.fnUntraced(function* (response: Effect.Effect<Response>) {const fs = yield* FileSystem.FileSystem;- const path = yield* Path.Path;const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "akeru-usage-test-" });const config = yield* ServerConfig.ServerConfig.pipe(Effect.provide(ServerConfig.layerTest("/tmp", baseDir)),);- const claude = path.join(config.baseDir, "claude");- const projects = path.join(claude, "projects");- yield* fs.makeDirectory(projects, { recursive: true });- const transcriptPath = path.join(projects, "session.jsonl");- yield* fs.writeFileString(transcriptPath, transcript);- const ratesPath = path.join(config.stateDir, "usage-model-rates.json");- if (options.diskRates) yield* fs.writeFileString(ratesPath, encodeJson(options.diskRates));- const persisted = yield* Deferred.make<void>();let fetches = 0;const client = HttpClient.make((request) =>Effect.gen(function* () {fetches += 1;- const response = yield* options.response ?? Effect.succeed(Response.json(rateDocument));- return HttpClientResponse.fromWeb(request, response);+ return HttpClientResponse.fromWeb(request, yield* response);}),);const service = yield* UsageService.make.pipe(Effect.provideService(ServerConfig.ServerConfig, config),Effect.provideService(HttpClient.HttpClient, client),- Effect.provideService(FileSystem.FileSystem, {- ...fs,- writeFileString: (target, contents, settings) =>- fs- .writeFileString(target, contents, settings)- .pipe(- Effect.tap(() =>- target === ratesPath ? Deferred.succeed(persisted, undefined) : Effect.void,- ),- ),- }),- Effect.provide(- ServerSettings.layerTest({- providers: {- claudeAgent: { homePath: claude },- codex: { homePath: path.join(config.baseDir, "codex") },- },- }),+ Effect.provideService(+ ProviderUsageHistory,+ ProviderUsageHistory.of({ readReported: () => Effect.succeed([]) }),),);+ return { service, fetches: () => fetches };+});++function entry(provider: string): AkeruUsageEntry {return {- service,- fetches: () => fetches,- persisted: Deferred.await(persisted),- transcriptPath,- fs,+ reservationId: AkeruUsageReservationId.make(`usage-${provider}`),+ sourceKey: `turn:${provider}`,+ botId: BotId.make("bot-1"),+ threadId: ThreadId.make("thread-1"),+ turnId: null,+ category: "turn",+ state: "reported",+ reservedTokens: 200,+ inputTokens: 100,+ outputTokens: 20,+ reasoningTokens: 5,+ provider: ProviderDriverKind.make(provider),+ model: "test-model",+ unavailableReason: null,+ createdAt: "2026-09-13T12:00:00.000Z",+ settledAt: "2026-09-13T12:00:01.000Z",};+}++describe("usageRecordFromEntry", () => {+ it("drops ledger usage when its provider is not connected in Akeru", () => {+ expect(UsageService.usageRecordFromEntry(entry("codex"), new Set())).toBeNull();+ });++ it.each([+ ["claudeAgent", "anthropic", "claude"],+ ["codex", "openai-codex", "codex"],+ ["cursor", "cursor", "cursor"],+ ["grok", "xai", "grok"],+ ["kimi", "kimi-for-coding", "kimi"],+ ["opencode", "opencode-go", "opencode"],+ ["opencodeGo", "opencode-go", "opencode"],+ ] as const)("maps %s usage through its %s connection", (driver, connection, provider) => {+ const connected = new Set<SubscriptionProviderId>([connection]);+ expect(UsageService.usageRecordFromEntry(entry(driver), connected)).toMatchObject({+ provider,+ model: "test-model",+ sessionId: "thread-1",+ totals: { uncachedInputTokens: 100, outputTokens: 20, reasoningTokens: 5 },+ });+ });});-it.layer(NodeServices.layer)("UsageService single-flight", (it) => {- it.effect("shares simultaneous cold summaries, transcript scans, and step pricing", () =>+it.layer(NodeServices.layer)("UsageService pricing", (it) => {+ it.effect("reads the usage ledger's filesystem identity", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "akeru-usage-volume-" });+ const databasePath = `${directory}/state.sqlite`;+ yield* fs.writeFileString(databasePath, "fixture");++ expect(yield* UsageService.readUsageStoreVolumeId(fs, databasePath)).toMatch(/^\d+:\d+$/);+ expect(yield* UsageService.readUsageStoreVolumeId(fs, `${directory}/missing.sqlite`)).toBe(+ "",+ );+ }),+ );++ it.effect("shares simultaneous cold pricing fetches", () =>Effect.gen(function* () {const started = yield* Deferred.make<void>();const reply = yield* Deferred.make<Response>();- const { service, fetches } = yield* makeFixture({- response: Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(reply))),- });- const walks = vi.spyOn(TranscriptReader, "listTranscriptFiles");- const reads = vi.spyOn(TranscriptReader, "readTranscriptRecords");- const summaries = yield* Effect.all(- Array.from({ length: 8 }, () => service.readSummary(input)),- { concurrency: "unbounded" },- ).pipe(Effect.forkChild);+ const { service, fetches } = yield* makeFixture(+ Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(reply))),+ );const prices = yield* Effect.all(- Array.from({ length: 8 }, () => service.priceStepUsage(step)),+ Array.from({ length: 8 }, () => service.priceStepUsage(pricedStep)),{ concurrency: "unbounded" },).pipe(Effect.forkChild);yield* Deferred.await(started);expect(fetches()).toBe(1);yield* Deferred.succeed(reply, Response.json(rateDocument));- const results = yield* Fiber.join(summaries);expect((yield* Fiber.join(prices)).every((price) => price.costSource === "modelPriced")).toBe(true,);- expect(results.every((result) => result === results[0])).toBe(true);- expect(walks).toHaveBeenCalledTimes(1);- expect(reads).toHaveBeenCalledTimes(1);- expect(results[0]!.pricing.status).toBe("fresh");- expect(fetches()).toBe(1);- yield* service.readSummary(input);- expect(walks).toHaveBeenCalledTimes(2);- expect(reads).toHaveBeenCalledTimes(1);- }),- );-- it.effect("keeps a shared scan alive when its first caller disconnects", () =>- Effect.gen(function* () {- const started = yield* Deferred.make<void>();- const reply = yield* Deferred.make<Response>();- const { service, fetches } = yield* makeFixture({- response: Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(reply))),- });- const first = yield* service.readSummary(input).pipe(Effect.forkChild);- yield* Deferred.await(started);- const remaining = yield* service.readSummary(input).pipe(Effect.forkChild);- yield* Fiber.interrupt(first);- yield* Deferred.succeed(reply, Response.json(rateDocument));- const summary = yield* Fiber.join(remaining);- expect(summary.pricing.status).toBe("fresh");- expect(summary.sources[0]!.scannedFiles).toBe(1);- expect(fetches()).toBe(1);- }),- );-- it.effect("keeps a shared pricing refresh alive when its first step caller disconnects", () =>- Effect.gen(function* () {- const started = yield* Deferred.make<void>();- const reply = yield* Deferred.make<Response>();- const { service, fetches } = yield* makeFixture({- response: Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(reply))),- });- const first = yield* service.priceStepUsage(step).pipe(Effect.forkChild);- yield* Deferred.await(started);- const remaining = yield* service.priceStepUsage(step).pipe(Effect.forkChild);- yield* Fiber.interrupt(first);- yield* Deferred.succeed(reply, Response.json(rateDocument));- expect((yield* Fiber.join(remaining)).costSource).toBe("modelPriced");expect(fetches()).toBe(1);}),);- it.effect(- "shares per-file parsing across different summary windows without sharing aggregates",- () =>- Effect.gen(function* () {- const now = yield* Clock.currentTimeMillis;- const { service } = yield* makeFixture({- diskRates: { fetchedAtMs: now, document: rateDocument },- });- const reads = vi.spyOn(TranscriptReader, "readTranscriptRecords");- const results = yield* Effect.all(- [- service.readSummary(input),- service.readSummary({- ...input,- sinceDay: UsageDay.make("2026-09-06"),- timeZone: "America/New_York",- }),- ],- { concurrency: "unbounded" },- );- expect(reads).toHaveBeenCalledTimes(1);- expect(results[0]!.timeZone).toBe("UTC");- expect(results[1]!.timeZone).toBe("America/New_York");- }),- );-- it.effect(- "shares failures, backs off repeated HTTP and malformed responses, and resets after success",- () =>- Effect.gen(function* () {- let response = () => new Response("offline", { status: 503 });- const { service, fetches } = yield* makeFixture({- response: Effect.sync(() => response()),- });- const failed = yield* Effect.all(- Array.from({ length: 8 }, () => service.readSummary(input)),- { concurrency: "unbounded" },- );- expect(fetches()).toBe(1);- expect(failed[0]!.pricing.status).toBe("unavailable");- yield* service.priceStepUsage(step);- yield* TestClock.adjust(59_999);- yield* service.priceStepUsage(step);- expect(fetches()).toBe(1);- yield* TestClock.adjust(1);- response = () => Response.json({ invalid: {} });- yield* service.priceStepUsage(step);- expect(fetches()).toBe(2);- yield* TestClock.adjust(119_999);- yield* service.priceStepUsage(step);- expect(fetches()).toBe(2);- yield* TestClock.adjust(1);- response = () => Response.json(rateDocument);- expect((yield* service.priceStepUsage(step)).costSource).toBe("modelPriced");- expect(fetches()).toBe(3);- expect((yield* service.readSummary(input)).pricing.status).toBe("fresh");- expect(fetches()).toBe(3);- }),- );-- it.effect("shares a timed-out fetch and waits for the failure backoff before retrying", () =>+ it.effect("backs off a failed refresh before retrying", () =>Effect.gen(function* () {- const started = yield* Deferred.make<void>();- let response: Effect.Effect<Response> = Effect.never;- const { service, fetches } = yield* makeFixture({- response: Deferred.succeed(started, undefined).pipe(- Effect.andThen(Effect.suspend(() => response)),- ),- });- const prices = yield* Effect.all(- Array.from({ length: 4 }, () => service.priceStepUsage(step)),- { concurrency: "unbounded" },- ).pipe(Effect.forkChild);- yield* Deferred.await(started);- yield* TestClock.adjust(10_000);- expect((yield* Fiber.join(prices)).every((price) => price.costSource === "unpriced")).toBe(- true,- );- expect((yield* service.readSummary(input)).pricing.status).toBe("unavailable");+ let response = () => new Response("offline", { status: 503 });+ const { service, fetches } = yield* makeFixture(Effect.sync(() => response()));+ expect((yield* service.priceStepUsage(pricedStep)).costSource).toBe("unpriced");yield* TestClock.adjust(59_999);- yield* service.priceStepUsage(step);+ yield* service.priceStepUsage(pricedStep);expect(fetches()).toBe(1);- response = Effect.succeed(Response.json(rateDocument));+ response = () => Response.json(rateDocument);yield* TestClock.adjust(1);- expect((yield* service.priceStepUsage(step)).costSource).toBe("modelPriced");+ expect((yield* service.priceStepUsage(pricedStep)).costSource).toBe("modelPriced");expect(fetches()).toBe(2);}),);-- it.effect("interrupts a detached stale-pricing refresh when the service scope closes", () =>- Effect.gen(function* () {- yield* TestClock.setTime(2 * DAY);- const started = yield* Deferred.make<void>();- const stopped = yield* Deferred.make<void>();- const scope = yield* Scope.make();- const { service, fetches } = yield* makeFixture({- diskRates: { fetchedAtMs: 0, document: rateDocument },- response: Deferred.succeed(started, undefined).pipe(- Effect.andThen(Effect.never),- Effect.ensuring(Deferred.succeed(stopped, undefined)),- ),- }).pipe(Effect.provideService(Scope.Scope, scope));- expect((yield* service.priceStepUsage(step)).costSource).toBe("modelPriced");- yield* Deferred.await(started);- yield* Scope.close(scope, Exit.void);- yield* Deferred.await(stopped);- expect(fetches()).toBe(1);- }),- );-- it.effect("serves stale prices immediately with cached status while one refresh is blocked", () =>- Effect.gen(function* () {- yield* TestClock.setTime(2 * DAY);- const started = yield* Deferred.make<void>();- const reply = yield* Deferred.make<Response>();- const { service, fetches, persisted } = yield* makeFixture({- diskRates: { fetchedAtMs: 0, document: rateDocument },- response: Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(reply))),- });- const summary = yield* service.readSummary(input);- yield* Deferred.await(started);- expect(summary.pricing).toMatchObject({- status: "cached",- fetchedAt: "1970-01-01T00:00:00.000Z",- knownModels: 1,- });- const prices = yield* Effect.all(- Array.from({ length: 8 }, () => service.priceStepUsage(step)),- { concurrency: "unbounded" },- );- expect(prices.every((price) => price.costSource === "modelPriced")).toBe(true);- expect(fetches()).toBe(1);- yield* Deferred.succeed(reply, Response.json(rateDocument));- yield* persisted;- expect((yield* service.readSummary(input)).pricing.status).toBe("fresh");- }),- );-- it.effect(- "marks a once-fresh table cached before failed refreshes and keeps its successful timestamp",- () =>- Effect.gen(function* () {- let response = () => Response.json(rateDocument);- const { service, fetches } = yield* makeFixture({- response: Effect.sync(() => response()),- });- const fresh = yield* service.readSummary(input);- yield* TestClock.adjust(DAY);- response = () => new Response("offline", { status: 503 });- const stale = yield* service.readSummary(input);- expect(stale.pricing.status).toBe("cached");- expect(stale.pricing.fetchedAt).toBe(fresh.pricing.fetchedAt);- expect(stale.pricing.knownModels).toBe(1);- yield* service.readSummary(input);- expect(fetches()).toBe(2);- }),- );-- it.effect("does not cache failed transcript reads and reparses changed files", () =>- Effect.gen(function* () {- const now = yield* Clock.currentTimeMillis;- const { service, transcriptPath, fs } = yield* makeFixture({- diskRates: { fetchedAtMs: now, document: rateDocument },- });- const reads = vi.spyOn(TranscriptReader, "readTranscriptRecords").mockResolvedValueOnce(null);- const failed = yield* service.readSummary(input);- expect(failed.sources[0]!.scannedFiles).toBe(0);- const retried = yield* service.readSummary(input);- expect(retried.sources[0]!.scannedFiles).toBe(1);- yield* fs.writeFileString(- transcriptPath,- transcript + transcript.replace('"message"', '"second"'),- );- yield* service.readSummary(input);- expect(reads).toHaveBeenCalledTimes(3);- }),- );});diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.tsindex c7a8eed6c..a7a4c688e 100644--- a/apps/server/src/usage/UsageService.ts+++ b/apps/server/src/usage/UsageService.ts@@ -1,13 +1,9 @@/**- * UsageService - scans provider transcripts and returns priced usage buckets.+ * UsageService - reports usage created by Akeru's connected provider runtimes.*- * The scan reads the provider CLIs' own session files rather than Akeru Bot's- * orchestration projections, so usage covers turns driven outside Akeru Bot too.- * This is the approach `ccusage` takes.- *- * Transcripts are append-only, so parsed records are memoised per file by- * `(size, mtime)`. A cold 30-day scan of ~1.4 GB lands around 2-3 seconds; warm- * scans only reparse files that changed.+ * The usage ledger is environment-local. Provider CLI transcript directories+ * are intentionally not consulted: a machine-wide CLI login is not an Akeru+ * Settings -> Providers connection and must never appear on this page.** @module UsageService*/@@ -15,6 +11,8 @@ import * as NodeOS from "node:os";import {USAGE_CONTRACT_VERSION,+ type AkeruUsageEntry,+ type SubscriptionProviderId,type UsageProviderKind,type UsageSource,type UsageSummary,@@ -22,7 +20,6 @@ import {type UsageTokenTotals,UsageReadError,} from "@t3tools/contracts";-import * as Cause from "effect/Cause";import * as Clock from "effect/Clock";import * as Context from "effect/Context";import * as DateTime from "effect/DateTime";@@ -34,50 +31,24 @@ import * as Option from "effect/Option";import * as Path from "effect/Path";import * as Schema from "effect/Schema";import * as Scope from "effect/Scope";-import * as Semaphore from "effect/Semaphore";import { HttpClient, HttpClientResponse } from "effect/unstable/http";import { ServerConfig } from "../config.ts";-import * as ServerSettings from "../serverSettings.ts";import { SubscriptionAuthService } from "../subscription-auth/service.ts";-import { resolveClaudeHomePath } from "../provider/Drivers/ClaudeHome.ts";-import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts";+import { ProviderUsageHistory } from "./ProviderUsageHistory.ts";import { UsageAggregator } from "./usageAggregation.ts";import { parseRateTable, priceUsage, type PricedUsage, type RateTable } from "./usagePricing.ts";-import {- listTranscriptFiles,- readDirectoryVolumeId,- readTranscriptRecords,-} from "./usageTranscriptReader.ts";-import {- decodeScanCache,- dedupeWithinFile,- encodeScanCache,- pruneScanCache,- type ScanCache,-} from "./usageScanCache.ts";-import type { UsageRecord } from "./usageTranscripts.ts";import { readPlanLimits } from "./usagePlanLimits.ts";+import type { UsageRecord } from "./usageTranscripts.ts";const LITELLM_RATES_URL ="https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";--/** Rates move rarely; a day-old table keeps the page working offline. */const RATES_TTL_MS = 24 * 60 * 60 * 1000;const RATES_FAILURE_BACKOFF_MS = 60_000;const RATES_MAX_FAILURE_BACKOFF_MS = 60 * 60 * 1000;--/**- * Files are filtered by mtime before opening. The slack covers a session whose- * last write lands just before local midnight on the window's first day.- */-const MTIME_SLACK_MS = 36 * 60 * 60 * 1000;const MAX_HOURLY_WINDOW_MS = 24 * 60 * 60 * 1000;+const DAILY_QUERY_SLACK_HOURS = 36;-/** Longest window the UI offers, plus slack. Older entries are pruned. */-const CACHE_RETENTION_DAYS = 90;--/** On-disk shape of the rate snapshot. */const RatesCacheFile = Schema.Struct({fetchedAtMs: Schema.Number,document: Schema.Unknown,@@ -89,10 +60,18 @@ const encodeRatesCache = Schema.encodeEffect(Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),);-/** The scan cache is narrowed by hand in `usageScanCache`, so JSON is enough here. */-const ScanCacheJson = Schema.fromJsonString(Schema.Unknown as unknown as Schema.Codec<unknown>);-const decodeScanCacheFile = Schema.decodeUnknownEffect(ScanCacheJson);-const encodeScanCacheFile = Schema.encodeEffect(ScanCacheJson);+const DRIVER_CONNECTIONS = {+ claudeAgent: { provider: "claude", connection: "anthropic" },+ codex: { provider: "codex", connection: "openai-codex" },+ cursor: { provider: "cursor", connection: "cursor" },+ grok: { provider: "grok", connection: "xai" },+ kimi: { provider: "kimi", connection: "kimi-for-coding" },+ opencode: { provider: "opencode", connection: "opencode-go" },+ opencodeGo: { provider: "opencode", connection: "opencode-go" },+} as const satisfies Record<+ string,+ { readonly provider: UsageProviderKind; readonly connection: SubscriptionProviderId }+>;export interface PriceStepUsageInput {readonly model: string;@@ -108,6 +87,48 @@ export class UsageService extends Context.Service<}>()("akeru-bot/usage/UsageService") {}+/** Maps one ledger row only when its Akeru provider connection is active. */+export function usageRecordFromEntry(+ entry: AkeruUsageEntry,+ connectedProviders: ReadonlySet<SubscriptionProviderId>,+): UsageRecord | null {+ if (entry.provider === null || entry.model === null) return null;+ const mapping = DRIVER_CONNECTIONS[entry.provider as keyof typeof DRIVER_CONNECTIONS];+ if (mapping === undefined || !connectedProviders.has(mapping.connection)) return null;++ const timestamp = DateTime.make(entry.createdAt);+ if (Option.isNone(timestamp)) return null;++ const outputTokens = entry.outputTokens ?? 0;+ return {+ provider: mapping.provider,+ timestampMs: DateTime.toEpochMillis(timestamp.value),+ model: entry.model,+ sessionId: entry.threadId ?? entry.botId,+ totals: {+ uncachedInputTokens: entry.inputTokens ?? 0,+ cachedInputTokens: 0,+ cacheCreationTokens: 0,+ outputTokens,+ reasoningTokens: Math.min(entry.reasoningTokens ?? 0, outputTokens),+ },+ reportedCostUsd: null,+ dedupeKey: entry.reservationId,+ };+}++/** Filesystem identity of an environment's usage ledger, as `device:inode`. */+export const readUsageStoreVolumeId = Effect.fn("UsageService.readUsageStoreVolumeId")(function* (+ fileSystem: FileSystem.FileSystem,+ databasePath: string,+) {+ const stats = yield* fileSystem+ .stat(databasePath)+ .pipe(Effect.catchCause(() => Effect.succeed(null)));+ if (stats === null || Option.isNone(stats.ino)) return "";+ return `${stats.dev}:${stats.ino.value}`;+});+/** Empty summary, for suites that only need the RPC surface to resolve. */export const layerTestWithRates = (rateTable: RateTable) =>Layer.succeed(@@ -129,6 +150,8 @@ export const layerTestWithRates = (rateTable: RateTable) =>knownModels: rateTable.size,},scanDurationMs: 0,+ planLimits: [],+ connectedProviders: [],}),priceStepUsage: (input) =>Effect.succeed(priceUsage(rateTable, input.model, input.totals, input.reportedCostUsd)),@@ -165,25 +188,19 @@ export const make = Effect.gen(function* () {const fileSystem = yield* FileSystem.FileSystem;const path = yield* Path.Path;const config = yield* ServerConfig;- const settingsService = yield* ServerSettings.ServerSettingsService;const httpClient = yield* HttpClient.HttpClient;+ const providerUsageHistory = yield* ProviderUsageHistory;const subscriptionAuth = SubscriptionAuthService.forSecretsDir(config.secretsDir);const scope = yield* Scope.Scope;- const fileCache: ScanCache = new Map();const shareSummary = singleFlight<UsageSummary, UsageReadError>(scope);- const shareFile = singleFlight<readonly UsageRecord[], never>(scope);const shareRates = singleFlight<void, never>(scope);- const persistLock = yield* Semaphore.make(1);- let cacheRevision = 0;- let persistedRevision = 0;const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json");- const scanCachePath = path.join(config.stateDir, "usage-scan-cache.json");+ const usageDatabasePath = path.join(config.stateDir, "state.sqlite");let rates: RateTable = new Map();let ratesFetchedAtMs: number | null = null;let ratesStatus: UsageSummary["pricing"]["status"] = "unavailable";-let ratesNextAttemptAtMs = 0;let ratesFailures = 0;let ratesRefreshRunning = false;@@ -266,121 +283,6 @@ export const make = Effect.gen(function* () {(effect) => shareRates("rates", effect),);- /**- * Claude's config dir is the home itself when overridden, but a default- * install nests transcripts under `~/.claude/projects`. Probe both.- */- const resolveClaudeTranscriptDir = (homePath: string) =>- Effect.gen(function* () {- const nested = path.join(homePath, ".claude", "projects");- const nestedExists = yield* fileSystem- .exists(nested)- .pipe(Effect.catchCause(() => Effect.succeed(false)));- return nestedExists ? nested : path.join(homePath, "projects");- });-- /** Resolves the transcript directory for each provider. */- const resolveTranscriptDirs = Effect.fn("UsageService.resolveTranscriptDirs")(function* () {- // A settings failure must surface as an error: swallowing it here would- // present "zero usage from every provider" as a valid answer.- const settings = yield* settingsService.getSettings.pipe(- Effect.catchCause(- (cause) =>- new UsageReadError({- reason: "scanFailed",- // Bounded description; the squashed failure travels as the cause.- // Squashed, not the Cause tree: a full tree in a Defect field is- // the unbounded wire payload the bounded detail exists to avoid.- detail: "Server settings could not be read.",- cause: Cause.squash(cause),- }),- ),- );-- const claudeHome = yield* resolveClaudeHomePath(settings.providers.claudeAgent);- const claudeDir = yield* resolveClaudeTranscriptDir(claudeHome);- const codexLayout = yield* resolveCodexHomeLayout(settings.providers.codex);-- return [- { provider: "claude" as const, dir: claudeDir, homePath: claudeHome },- {- provider: "codex" as const,- dir: path.join(codexLayout.sharedHomePath, "sessions"),- homePath: codexLayout.sharedHomePath,- },- ];- });-- /**- * Loads the persisted scan cache exactly once per process.- *- * `Effect.cached` makes concurrent first readers await the same load rather- * than each seeing a "loaded" flag set before the read finished and cold- * scanning against an empty cache.- */- const ensureScanCacheLoaded = yield* Effect.cached(- Effect.gen(function* () {- const document = yield* fileSystem.readFileString(scanCachePath).pipe(- Effect.flatMap((raw) => decodeScanCacheFile(raw)),- Effect.catchCause(() => Effect.succeed(null)),- );- if (document === null) return;- for (const [path, entry] of decodeScanCache(document)) fileCache.set(path, entry);- }),- );-- const persistScanCache = Effect.fn("UsageService.persistScanCache")(function* () {- if (cacheRevision === persistedRevision) return;- const revision = cacheRevision;- // Only acknowledge this revision; another scan can change the cache during the write.- yield* encodeScanCacheFile(encodeScanCache(fileCache)).pipe(- Effect.flatMap((serialized) => fileSystem.writeFileString(scanCachePath, serialized)),- Effect.map(() => {- persistedRevision = revision;- }),- // A cache we cannot write is a slower next start, not a failed read.- Effect.catchCause(() => Effect.void),- );- }, persistLock.withPermit);-- /** Parses one transcript, reusing the cached result when it is unchanged. */- const readFileRecords = (- filePath: string,- size: number,- mtimeMs: number,- provider: UsageProviderKind,- ): Effect.Effect<readonly UsageRecord[]> =>- shareFile(- JSON.stringify([filePath, size, mtimeMs, provider]),- Effect.gen(function* () {- const cached = fileCache.get(filePath);- // Provider is part of the identity: if both providers were ever pointed- // at one directory, a hit parsed by the other parser must not be reused.- if (- cached &&- cached.size === size &&- cached.mtimeMs === mtimeMs &&- cached.provider === provider- ) {- return cached.records;- }-- const parsed = yield* Effect.promise(() =>- readTranscriptRecords(filePath, provider, { size, mtimeMs }),- );- // A read failure is not an empty transcript: caching it under this- // (size, mtime) would silently drop the file's usage until it changes.- if (parsed === null) return [];- // Stored already de-duplicated within the file, which is 99% of all- // duplicates. The aggregator still runs the cross-file dedupe pass.- const records = dedupeWithinFile(parsed);-- fileCache.set(filePath, { size, mtimeMs, provider, records });- cacheRevision += 1;- return records;- }),- );-const priceStepUsage = Effect.fn("UsageService.priceStepUsage")(function* (input: PriceStepUsageInput,) {@@ -420,33 +322,47 @@ export const make = Effect.gen(function* () {hourlyWindow = { sinceTimeMs, untilTimeMs };}- const startedAtMs = yield* Clock.currentTimeMillis;- yield* ensureRates();- yield* ensureScanCacheLoaded;-- const hostId = NodeOS.hostname();- // The home resolvers ask for `Path` themselves; satisfy them from the- // instance we already hold so `readSummary` stays context-free.- const dirs = yield* resolveTranscriptDirs().pipe(Effect.provideService(Path.Path, path));- const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);- if (Option.isNone(windowStart)) {+ const sinceBoundary = DateTime.make(`${input.sinceDay}T00:00:00Z`);+ const untilBoundary = DateTime.make(`${input.untilDay}T00:00:00Z`);+ if (Option.isNone(sinceBoundary) || Option.isNone(untilBoundary)) {return yield* new UsageReadError({reason: "invalidWindow",- detail: `sinceDay '${input.sinceDay}' is not a valid date`,+ detail: "Usage day window contains an invalid date",});}- const windowStartMs =- (hourlyWindow?.sinceTimeMs ?? DateTime.toEpochMillis(windowStart.value)) - MTIME_SLACK_MS;-- const pricing = {- status: ratesStatus,- source: LITELLM_RATES_URL,- fetchedAt:- ratesFetchedAtMs === null- ? null- : DateTime.formatIso(DateTime.makeUnsafe(ratesFetchedAtMs)),- knownModels: rates.size,- };++ const startedAtMs = yield* Clock.currentTimeMillis;+ yield* ensureRates();+ subscriptionAuth.reload();+ const connectedProviders = subscriptionAuth+ .statuses()+ .filter((status) => status.connected)+ .map((status) => status.provider);+ const connectedSet = new Set<SubscriptionProviderId>(connectedProviders);++ const querySince = hourlyWindow+ ? DateTime.makeUnsafe(hourlyWindow.sinceTimeMs)+ : DateTime.subtract(sinceBoundary.value, { hours: DAILY_QUERY_SLACK_HOURS });+ const queryUntil = hourlyWindow+ ? DateTime.makeUnsafe(hourlyWindow.untilTimeMs)+ : DateTime.add(untilBoundary.value, { hours: 24 + DAILY_QUERY_SLACK_HOURS });++ const entries = yield* providerUsageHistory+ .readReported({+ sinceAt: DateTime.formatIso(querySince),+ untilAt: DateTime.formatIso(queryUntil),+ })+ .pipe(+ Effect.mapError(+ (cause) =>+ new UsageReadError({+ reason: "scanFailed",+ detail: "Akeru provider usage could not be read.",+ cause,+ }),+ ),+ );+const aggregator = new UsageAggregator({timeZone: input.timeZone,sinceDay: input.sinceDay,@@ -455,79 +371,36 @@ export const make = Effect.gen(function* () {...hourlyWindow,rates,});-- const sources: UsageSource[] = [];- const livePaths = new Set<string>();- const walkedRoots: string[] = [];-- for (const { provider, dir } of dirs) {- const volumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));- const exists = yield* fileSystem- .exists(dir)- .pipe(Effect.catchCause(() => Effect.succeed(false)));-- if (!exists) {- sources.push({- fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },- status: "missing",- scannedFiles: 0,- skippedFiles: 0,- malformedRecords: 0,- distinctSessions: 0,- message: "No transcript directory on this environment.",- });- continue;- }-- walkedRoots.push(dir);- const files = yield* Effect.promise(() => listTranscriptFiles(dir, windowStartMs));- let scannedFiles = 0;- let skippedFiles = 0;- // Distinct per directory. Buckets carry per-cell session counts, but a- // session spans days and models, so clients total this figure instead.- const sessionIds = new Set<string>();-- for (const file of files) {- livePaths.add(file.path);- const records = yield* readFileRecords(file.path, file.size, file.mtimeMs, provider);- if (records.length === 0) {- skippedFiles += 1;- continue;- }- scannedFiles += 1;- for (const record of records) {- // Only sessions that contributed in-window count: the mtime slack- // admits boundary files whose records fall outside the range.- if (aggregator.add(record) && record.sessionId.length > 0) {- sessionIds.add(record.sessionId);- }- }- }-- sources.push({- fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },- status: "ok",- scannedFiles,- skippedFiles,- malformedRecords: 0,- distinctSessions: sessionIds.size,- message: null,- });+ const sessionsByProvider = new Map<UsageProviderKind, Set<string>>();+ for (const entry of entries) {+ const record = usageRecordFromEntry(entry, connectedSet);+ if (record === null || !aggregator.add(record)) continue;+ const sessions = sessionsByProvider.get(record.provider) ?? new Set<string>();+ if (record.sessionId.length > 0) sessions.add(record.sessionId);+ sessionsByProvider.set(record.provider, sessions);}- const pruned = pruneScanCache(fileCache, {- livePaths,- walkedRoots,- windowStartMs,- retentionCutoffMs: startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000,- });- if (pruned > 0) cacheRevision += 1;- yield* persistScanCache();+ const hostId = NodeOS.hostname();+ const volumeId = yield* readUsageStoreVolumeId(fileSystem, usageDatabasePath);+ const sources: UsageSource[] = [+ ...new Set(+ Object.values(DRIVER_CONNECTIONS)+ .filter((mapping) => connectedSet.has(mapping.connection))+ .map((mapping) => mapping.provider),+ ),+ ].map((provider) => ({+ fingerprint: { hostId, provider, resolvedHomePath: usageDatabasePath, volumeId },+ status: "ok",+ scannedFiles: 0,+ skippedFiles: 0,+ malformedRecords: 0,+ distinctSessions: sessionsByProvider.get(provider)?.size ?? 0,+ message: null,+ }));const aggregated = aggregator.finish();const readAt = yield* DateTime.now;const finishedAtMs = yield* Clock.currentTimeMillis;- subscriptionAuth.reload();const planLimits = yield* Effect.promise(() =>readPlanLimits((provider) => subscriptionAuth.getPlanAccessToken(provider)),).pipe(Effect.catchCause(() => Effect.succeed([])));@@ -541,7 +414,16 @@ export const make = Effect.gen(function* () {buckets: aggregated.buckets,sources,planLimits,- pricing,+ connectedProviders,+ pricing: {+ status: ratesStatus,+ source: LITELLM_RATES_URL,+ fetchedAt:+ ratesFetchedAtMs === null+ ? null+ : DateTime.formatIso(DateTime.makeUnsafe(ratesFetchedAtMs)),+ knownModels: rates.size,+ },scanDurationMs: Math.max(0, finishedAtMs - startedAtMs),} satisfies UsageSummary;});diff --git a/apps/web/index.html b/apps/web/index.htmlindex 94bd6fb6d..223c1648c 100644--- a/apps/web/index.html+++ b/apps/web/index.html@@ -7,7 +7,7 @@content="width=device-width, initial-scale=1.0, viewport-fit=cover, interactive-widget=resizes-content"/><meta name="theme-color" content="#111111" />- <link rel="icon" href="/favicon.ico" sizes="48x48" />+ <link rel="icon" href="/apple-touch-icon.png?v=2" type="image/png" /><link rel="apple-touch-icon" href="/apple-touch-icon.png" /><link rel="manifest" href="/manifest.webmanifest" /><script>diff --git a/apps/web/public/manifest.webmanifest b/apps/web/public/manifest.webmanifestindex be5836da8..e679cda10 100644--- a/apps/web/public/manifest.webmanifest+++ b/apps/web/public/manifest.webmanifest@@ -9,8 +9,8 @@"theme_color": "#161616","icons": [{- "src": "/favicon-32x32.png",- "sizes": "32x32",+ "src": "/apple-touch-icon.png?v=2",+ "sizes": "180x180","type": "image/png"},{diff --git a/apps/web/src/components/AkeruMark.tsx b/apps/web/src/components/AkeruMark.tsxdeleted file mode 100644index 9b2ac766f..000000000--- a/apps/web/src/components/AkeruMark.tsx+++ /dev/null@@ -1,23 +0,0 @@-import type { ComponentProps } from "react";--import { cn } from "../lib/utils";--export function AkeruMark({ className, ...props }: ComponentProps<"svg">) {- return (- <svg- aria-label="Akeru"- className={cn("h-2.5 w-auto shrink-0", className)}- viewBox="28 34 72 60"- xmlns="http://www.w3.org/2000/svg"- {...props}- >- <path- clipRule="evenodd"- d="M64 34L100 94H28L64 34ZM64 55L83 87H45L64 55Z"- fill="currentColor"- fillRule="evenodd"- />- <path d="M47 72H81V81H47V72Z" fill="currentColor" />- </svg>- );-}diff --git a/apps/web/src/components/AkeruWordmark.tsx b/apps/web/src/components/AkeruWordmark.tsxnew file mode 100644index 000000000..45872c597--- /dev/null+++ b/apps/web/src/components/AkeruWordmark.tsx@@ -0,0 +1,18 @@+import type { ComponentProps } from "react";++import { cn } from "../lib/utils";++/** The product wordmark used in the primary roster and every secondary surface. */+export function AkeruWordmark({ className, ...props }: ComponentProps<"span">) {+ return (+ <span+ className={cn(+ "truncate text-xl leading-none tracking-tight [font-family:var(--font-brand-serif)]",+ className,+ )}+ {...props}+ >+ akeru+ </span>+ );+}diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsxindex 4f7121404..4cea100f1 100644--- a/apps/web/src/components/AppSidebarLayout.tsx+++ b/apps/web/src/components/AppSidebarLayout.tsx@@ -7,6 +7,7 @@ import {type CSSProperties,type ReactNode,} from "react";+import { useLocation } from "@tanstack/react-router";import { isElectron } from "../env";import { getLocalStorageItem, removeLocalStorageItem } from "../hooks/useLocalStorage";@@ -14,6 +15,7 @@ import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings"import { cn, isMacPlatform } from "../lib/utils";import { primaryServerKeybindingsAtom } from "../state/server";import BotRosterSidebar from "./roster/BotRosterSidebar";+import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";import { useServerRosterSync } from "./roster/useServerRoster";import { openSettings } from "~/settingsDialogStore";import { openProductFeedback } from "~/productFeedbackStore";@@ -142,6 +144,8 @@ function ProjectProjectionRetention() {export function AppSidebarLayout({ children }: { children: ReactNode }) {useServerRosterSync();+ const pathname = useLocation({ select: (location) => location.pathname });+ const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/");const stageArtworkVisible = false;const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);@@ -225,7 +229,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {onResize: setSidebarWidth,}}>- <BotRosterSidebar />+ {isOnSettings ? <SettingsSidebarNav /> : <BotRosterSidebar />}<SidebarRail onDoubleClick={resetSidebarWidth} /></Sidebar>{children}diff --git a/apps/web/src/components/SurfaceNavigationCoordinator.tsx b/apps/web/src/components/SurfaceNavigationCoordinator.tsxnew file mode 100644index 000000000..ced794815--- /dev/null+++ b/apps/web/src/components/SurfaceNavigationCoordinator.tsx@@ -0,0 +1,47 @@+import { useEffect } from "react";+import { useLocation, useNavigate } from "@tanstack/react-router";++import { acknowledgePluginsNavigation, usePluginsDialogStore } from "../pluginsDialogStore";+import {+ acknowledgeSettingsNavigation,+ clearSettingsEnvironment,+ useSettingsDialogStore,+} from "../settingsDialogStore";+import { closeUsage, useUsageDialogStore } from "../usageDialogStore";++/** Bridges legacy imperative open helpers to the routed workspace surfaces. */+export function SurfaceNavigationCoordinator() {+ const navigate = useNavigate();+ const pathname = useLocation({ select: (location) => location.pathname });+ const settingsSection = useSettingsDialogStore((state) => state.section);+ const settingsTarget = useSettingsDialogStore((state) => state.targetId);+ const pluginsOpen = usePluginsDialogStore((state) => state.open);+ const usageOpen = useUsageDialogStore((state) => state.open);++ useEffect(() => {+ if (settingsSection !== null) {+ void navigate({+ to: "/settings/$section",+ params: { section: settingsSection },+ hash: settingsTarget ?? "",+ });+ acknowledgeSettingsNavigation();+ return;+ }+ if (!pathname.startsWith("/settings")) clearSettingsEnvironment();+ }, [navigate, pathname, settingsSection, settingsTarget]);++ useEffect(() => {+ if (!pluginsOpen) return;+ void navigate({ to: "/plugins" });+ acknowledgePluginsNavigation();+ }, [navigate, pluginsOpen]);++ useEffect(() => {+ if (!usageOpen) return;+ void navigate({ to: "/usage" });+ closeUsage();+ }, [navigate, usageOpen]);++ return null;+}diff --git a/apps/web/src/components/plugins/PluginDetails.tsx b/apps/web/src/components/plugins/PluginDetails.tsxindex c2f11060b..d1336d236 100644--- a/apps/web/src/components/plugins/PluginDetails.tsx+++ b/apps/web/src/components/plugins/PluginDetails.tsx@@ -14,6 +14,7 @@ import {} from "./pluginPresentation";interface PluginDetailsContentProps {+ readonly standalone?: boolean;readonly plugin: PluginDirectoryDefinition;readonly server: McpServer | undefined;readonly accessStatus?: ProviderAccessStatus;@@ -252,6 +253,7 @@ export function PluginDetailsContent({}export function PluginDetails({+ standalone = false,plugin,server,accessStatus,@@ -271,7 +273,11 @@ export function PluginDetails({<Button aria-label="Back to plugins" size="icon-sm" variant="ghost" onClick={onBack}><ChevronLeftIcon className="size-4" /></Button>- <DialogTitle className="text-base">Plugin details</DialogTitle>+ {standalone ? (+ <h1 className="text-base font-semibold">Plugin details</h1>+ ) : (+ <DialogTitle className="text-base">Plugin details</DialogTitle>+ )}</div></DialogHeader><PluginDetailsContentdiff --git a/apps/web/src/components/plugins/PluginsDialog.tsx b/apps/web/src/components/plugins/PluginsDialog.tsxindex d6ca7cc44..aaee3cf81 100644--- a/apps/web/src/components/plugins/PluginsDialog.tsx+++ b/apps/web/src/components/plugins/PluginsDialog.tsx@@ -42,6 +42,7 @@ import { Input } from "../ui/input";import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";import { Textarea } from "../ui/textarea";import { toastManager } from "../ui/toast";+import { SidebarInset } from "../ui/sidebar";import {CustomMcpServers,ComposioToolkitResults,@@ -153,7 +154,13 @@ export function validateMcpServerDraft(draft: McpServerDraft): string | null {}}-function PluginsDialogForEnvironment({ environmentId }: { readonly environmentId: EnvironmentId }) {+function PluginsDialogForEnvironment({+ environmentId,+ standalone = false,+}: {+ readonly environmentId: EnvironmentId;+ readonly standalone?: boolean;+}) {const requestedQuery = usePluginsDialogStore((state) => state.requestedQuery);const servers = useAtomValue(environmentMcpServersAtom(environmentId));const bots = useAtomValue(environmentBotsAtom(environmentId));@@ -554,6 +561,7 @@ function PluginsDialogForEnvironment({ environmentId }: { readonly environmentId<>{selectedPlugin ? (<PluginDetails+ standalone={standalone}plugin={selectedPlugin}server={selectedPluginServer}{...(selectedPluginAccess ? { accessStatus: selectedPluginAccess } : {})}@@ -579,7 +587,11 @@ function PluginsDialogForEnvironment({ environmentId }: { readonly environmentId<><DialogHeader className={PLUGIN_DIRECTORY_HEADER_CLASS_NAME}><div className="pe-8">- <DialogTitle>Plugins</DialogTitle>+ {standalone ? (+ <h1 className="font-heading text-xl font-semibold leading-none">Plugins</h1>+ ) : (+ <DialogTitle>Plugins</DialogTitle>+ )}</div><div className="relative"><SearchIcon@@ -813,3 +825,26 @@ export function PluginsDialog() {</Dialog>);}++export function PluginsPage() {+ const environmentId = usePrimaryEnvironmentId();+ return (+ <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">+ <div+ className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground"+ data-slot="dialog-popup"+ >+ {environmentId ? (+ <PluginsDialogForEnvironment environmentId={environmentId} standalone />+ ) : (+ <div className="p-6">+ <h1 className="font-heading text-xl font-semibold">Plugins</h1>+ <p className="mt-2 text-sm text-muted-foreground">+ Connect an environment to manage plugins.+ </p>+ </div>+ )}+ </div>+ </SidebarInset>+ );+}diff --git a/apps/web/src/components/roster/BotRosterSidebar.tsx b/apps/web/src/components/roster/BotRosterSidebar.tsxindex e4734da05..08d08ced2 100644--- a/apps/web/src/components/roster/BotRosterSidebar.tsx+++ b/apps/web/src/components/roster/BotRosterSidebar.tsx@@ -54,6 +54,7 @@ import { primaryServerKeybindingsAtom } from "../../state/server";import { useAtomCommand } from "../../state/use-atom-command";import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../../terminalUiStateStore";import { SidebarChromeFooter } from "../sidebar/SidebarChrome";+import { AkeruWordmark } from "../AkeruWordmark";import { Button } from "../ui/button";import {Menu,@@ -181,9 +182,7 @@ const RosterSidebarHeader = memo(function RosterSidebarHeader({to="/"className="flex items-center justify-center rounded-md text-sidebar-foreground outline-none ring-ring focus-visible:ring-2 [-webkit-app-region:no-drag]">- <span className="truncate text-xl leading-none tracking-tight [font-family:var(--font-brand-serif)]">- akeru- </span>+ <AkeruWordmark /></Link><div className="flex items-center justify-end"><Menu>diff --git a/apps/web/src/components/settings/SettingsDialog.tsx b/apps/web/src/components/settings/SettingsDialog.tsxindex a90585bd7..9ed546854 100644--- a/apps/web/src/components/settings/SettingsDialog.tsx+++ b/apps/web/src/components/settings/SettingsDialog.tsx@@ -3,6 +3,8 @@ import {BotIcon,BrowserIcon,CallIcon,+ Bug02Icon,+ GitBranchIcon,HardDriveIcon,KeyboardIcon,Link02Icon,@@ -80,6 +82,21 @@ const SECTION_PANELS: Readonly<Record<SettingsSection, ComponentType>> = {diagnostics: DiagnosticsSettingsPanel,};+export function SettingsPanelForSection({ section }: { readonly section: SettingsSection }) {+ const Panel = SECTION_PANELS[section];+ return (+ <Suspense+ fallback={+ <div className="flex flex-1 items-center justify-center">+ <Spinner />+ </div>+ }+ >+ <Panel />+ </Suspense>+ );+}+/** Sections with a nav row. Anything else is reached from a link inside a panel. */export const SETTINGS_NAV_ITEMS: ReadonlyArray<{readonly section: SettingsSection;@@ -98,12 +115,13 @@ export const SETTINGS_NAV_ITEMS: ReadonlyArray<{{ section: "inbox", label: "Errors", icon: AlertCircleIcon },{ section: "connections", label: "Connections", icon: Link02Icon },{ section: "keybindings", label: "Keybindings", icon: KeyboardIcon },+ { section: "source-control", label: "Source control", icon: GitBranchIcon },+ { section: "diagnostics", label: "Diagnostics", icon: Bug02Icon },];export function SettingsDialog() {const section = useSettingsDialogStore((state) => state.section);const openSettings = useSettingsDialogStore((state) => state.openSettings);- const Panel = section ? SECTION_PANELS[section] : null;return (<Dialog@@ -144,15 +162,7 @@ export function SettingsDialog() {</nav><div className="flex min-h-0 min-w-0 flex-1 flex-col">- <Suspense- fallback={- <div className="flex flex-1 items-center justify-center">- <Spinner />- </div>- }- >- {Panel ? <Panel /> : null}- </Suspense>+ {section ? <SettingsPanelForSection section={section} /> : null}</div></DialogPopup></Dialog>diff --git a/apps/web/src/components/settings/SettingsRoutePage.tsx b/apps/web/src/components/settings/SettingsRoutePage.tsxnew file mode 100644index 000000000..02285b950--- /dev/null+++ b/apps/web/src/components/settings/SettingsRoutePage.tsx@@ -0,0 +1,41 @@+import { Outlet, useLocation } from "@tanstack/react-router";++import { isElectron } from "../../env";+import { settingsSectionFromPathname } from "../../settingsDialogStore";+import { SidebarInset } from "../ui/sidebar";+import {+ WorkspaceBreadcrumb,+ WorkspaceBreadcrumbItem,+ WorkspaceBreadcrumbSeparator,+} from "../WorkspaceBreadcrumb";+import { WorkspacePageHeader } from "../WorkspacePageHeader";+import { SETTINGS_NAV_ITEMS } from "./SettingsDialog";++export function SettingsRoutePage() {+ const pathname = useLocation({ select: (location) => location.pathname });+ const section = settingsSectionFromPathname(pathname);+ const label =+ SETTINGS_NAV_ITEMS.find((item) => item.section === section)?.label ??+ section.replaceAll("-", " ");++ return (+ <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">+ <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">+ <WorkspacePageHeader electron={isElectron} className="border-b border-border/70">+ <WorkspaceBreadcrumb ariaLabel="Settings breadcrumb">+ <WorkspaceBreadcrumbItem>+ <h1>Settings</h1>+ </WorkspaceBreadcrumbItem>+ <WorkspaceBreadcrumbSeparator />+ <WorkspaceBreadcrumbItem current className="capitalize">+ {label}+ </WorkspaceBreadcrumbItem>+ </WorkspaceBreadcrumb>+ </WorkspacePageHeader>+ <div className="flex min-h-0 flex-1 flex-col">+ <Outlet />+ </div>+ </div>+ </SidebarInset>+ );+}diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsxnew file mode 100644index 000000000..a4ecd01a3--- /dev/null+++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx@@ -0,0 +1,71 @@+import { ArrowLeftIcon } from "lucide-react";+import { useLocation, useNavigate } from "@tanstack/react-router";++import { cn } from "../../lib/utils";+import { AppIcon } from "../ui/app-icon";+import {+ SidebarContent,+ SidebarFooter,+ SidebarGroup,+ SidebarMenu,+ SidebarMenuButton,+ SidebarMenuItem,+ useSidebar,+} from "../ui/sidebar";+import { SidebarChromeHeader } from "../sidebar/SidebarChrome";+import { SETTINGS_NAV_ITEMS } from "./SettingsDialog";+import { isElectron } from "../../env";++export function SettingsSidebarNav() {+ const pathname = useLocation({ select: (location) => location.pathname });+ const navigate = useNavigate();+ const { isMobile, setOpenMobile } = useSidebar();+ const go = (to: string) => {+ if (isMobile) setOpenMobile(false);+ void navigate({ to });+ };++ return (+ <>+ <SidebarChromeHeader isElectron={isElectron} />+ <SidebarContent className="overflow-x-hidden">+ <SidebarGroup className="p-[var(--sidebar-content-inset)]">+ <SidebarMenu>+ {SETTINGS_NAV_ITEMS.map((item) => {+ const to = `/settings/${item.section}`;+ const active = pathname === to;+ return (+ <SidebarMenuItem key={item.section}>+ <SidebarMenuButton+ aria-current={active ? "page" : undefined}+ isActive={active}+ onClick={() => go(to)}+ tooltip={item.label}+ >+ <AppIcon+ className={cn("size-4", !active && "text-sidebar-muted-foreground")}+ icon={item.icon}+ />+ <span className="truncate group-data-[collapsible=icon]:hidden">+ {item.label}+ </span>+ </SidebarMenuButton>+ </SidebarMenuItem>+ );+ })}+ </SidebarMenu>+ </SidebarGroup>+ </SidebarContent>+ <SidebarFooter className="p-[var(--sidebar-content-inset)]">+ <SidebarMenu>+ <SidebarMenuItem>+ <SidebarMenuButton onClick={() => go("/")} tooltip="Back to chats">+ <ArrowLeftIcon />+ <span className="group-data-[collapsible=icon]:hidden">Back to chats</span>+ </SidebarMenuButton>+ </SidebarMenuItem>+ </SidebarMenu>+ </SidebarFooter>+ </>+ );+}diff --git a/apps/web/src/components/sidebar/SidebarChrome.tsx b/apps/web/src/components/sidebar/SidebarChrome.tsxindex de4d5ad42..47cf763a6 100644--- a/apps/web/src/components/sidebar/SidebarChrome.tsx+++ b/apps/web/src/components/sidebar/SidebarChrome.tsx@@ -31,7 +31,7 @@ import { environmentMcpServersAtom, mcpServerEnvironment } from "../../state/mcpimport { environmentSnapshotAtom } from "../../state/shell";import { threadEnvironment } from "../../state/threads";import { useAtomCommand } from "../../state/use-atom-command";-import { AkeruMark } from "../AkeruMark";+import { AkeruWordmark } from "../AkeruWordmark";import { isBuiltinMcpServer } from "../plugins/pluginRegistry";import { cn } from "../../lib/utils";import {@@ -76,57 +76,50 @@ export const SidebarChromeHeader = memo(function SidebarChromeHeader({return (<SidebarHeaderclassName={cn(- "@container/sidebar-header relative h-[var(--workspace-topbar-height)] shrink-0 flex-row items-center px-3 py-0 md:px-0",+ "@container/sidebar-header relative h-[var(--workspace-topbar-height)] shrink-0 flex-row items-center gap-1 px-3 py-0 md:px-2",isElectron && "drag-region",)}>{backdropVariant ? <SidebarStageBackdrop variant={backdropVariant} /> : null}- <SidebarTrigger- className={cn(- "relative z-10 md:hidden",- backdropVariant &&- "focus-visible:ring-white/90 [&_svg]:stroke-white/90! [&_svg]:opacity-100! [&_svg]:hover:stroke-white! [:hover,[data-pressed]]:bg-white/15",- backdropVariant && resolveSidebarStageFocusRingOffsetClass(backdropVariant),- )}- />- <SidebarBrand onBackdrop={backdropVariant !== null} />- {pillLabel ? (- <Badge- className="relative z-10 ml-1 rounded-full px-1.5 text-muted-foreground"- data-environment-identification="pill"- size="sm"- variant="secondary"- >- {pillLabel}- </Badge>- ) : null}+ <div className="relative z-10 grid min-w-0 flex-1 grid-cols-[1fr_auto_1fr] items-center group-data-[collapsible=icon]:hidden">+ <div className="flex items-center justify-start">+ <SidebarTrigger+ className={cn(+ "md:hidden",+ backdropVariant &&+ "focus-visible:ring-white/90 [&_svg]:stroke-white/90! [&_svg]:opacity-100! [&_svg]:hover:stroke-white! [:hover,[data-pressed]]:bg-white/15",+ backdropVariant && resolveSidebarStageFocusRingOffsetClass(backdropVariant),+ )}+ />+ </div>+ <div className="relative flex items-center justify-center">+ <Link+ aria-label="Go to chats"+ className={cn(+ "flex items-center justify-center rounded-md outline-none ring-ring focus-visible:ring-2 [-webkit-app-region:no-drag]",+ backdropVariant ? "text-white" : "text-sidebar-foreground",+ )}+ to="/"+ >+ <AkeruWordmark />+ </Link>+ {pillLabel ? (+ <Badge+ className="absolute left-full ml-2 rounded-full px-1.5 text-muted-foreground"+ data-environment-identification="pill"+ size="sm"+ variant="secondary"+ >+ {pillLabel}+ </Badge>+ ) : null}+ </div>+ <div aria-hidden />+ </div></SidebarHeader>);});-function SidebarBrand({ onBackdrop }: { onBackdrop: boolean }) {- return (- <Link- aria-label="Go to chats"- className={cn(- "relative z-10 ml-[var(--workspace-titlebar-content-left)] hidden h-7 w-fit min-w-0 shrink-0 items-center gap-1 overflow-hidden rounded-md outline-hidden ring-ring focus-visible:ring-2 md:flex",- onBackdrop ? "text-white" : "text-foreground",- )}- to="/"- >- <AkeruMark aria-hidden />- <span- className={cn(- "-translate-y-px truncate text-sm font-medium tracking-tight",- onBackdrop ? "text-white/70" : "text-muted-foreground",- )}- >- Akeru Bot- </span>- </Link>- );-}-const PLUGIN_CATALOG = loadCatalog();const COMPUTER_USE_SERVER_ID = "builtin-computer-use";diff --git a/apps/web/src/components/threadSidebarWidth.test.ts b/apps/web/src/components/threadSidebarWidth.test.tsindex e38d5c374..de9b82214 100644--- a/apps/web/src/components/threadSidebarWidth.test.ts+++ b/apps/web/src/components/threadSidebarWidth.test.ts@@ -35,14 +35,15 @@ describe("thread sidebar width", () => {expect(resolveInitialThreadSidebarWidth(900, 700)).toBe(THREAD_SIDEBAR_MIN_WIDTH);});- it("shows the desktop wordmark across the sidebar's full legal width range", () => {+ it("centers the wordmark across the sidebar's full legal width range", () => {const sidebarSource = NodeFS.readFileSync(new URL("./sidebar/SidebarChrome.tsx", import.meta.url),"utf8",);- expect(sidebarSource).toContain("hidden h-7 w-fit min-w-0 shrink-0 items-center gap-1");- expect(sidebarSource).toContain("md:flex");+ expect(sidebarSource).toContain("grid-cols-[1fr_auto_1fr]");+ expect(sidebarSource).toContain("min-w-0 flex-1");+ expect(sidebarSource).toContain("group-data-[collapsible=icon]:hidden");expect(THREAD_SIDEBAR_MIN_WIDTH).toBe(13 * 16);});});diff --git a/apps/web/src/components/usage/UsageCharts.tsx b/apps/web/src/components/usage/UsageCharts.tsxindex 4ccf142ab..c2fec184e 100644--- a/apps/web/src/components/usage/UsageCharts.tsx+++ b/apps/web/src/components/usage/UsageCharts.tsx@@ -9,8 +9,6 @@ import type { DailyTotals } from "@t3tools/shared/usageMerge";import { Line } from "../dither-kit/area";import { LineChart } from "../dither-kit/area-chart";-import { Bar } from "../dither-kit/bar";-import { BarChart } from "../dither-kit/bar-chart";import { BlockLegend } from "../dither-kit/block-legend";import type { ChartConfig } from "../dither-kit/chart-context";import type { DitherColor } from "../dither-kit/palette";@@ -77,51 +75,53 @@ export function UsagePlanMeters(props: { readonly limits: UsageProviderPlanLimitprops.limits.plan === null? presentation.label: `${presentation.label} · ${props.limits.plan}`;- const data = props.limits.windows.map((window) => ({- label: window.label,- left: remainingPercent(window),- }));-return (<section className="flex min-w-0 flex-col gap-3">- <h2 className="flex items-center gap-2 text-sm font-medium text-foreground">+ <h2 className="flex items-center gap-2 px-1 text-sm font-medium text-foreground"><ProviderMark icon={presentation.icon} />{title}</h2>{props.limits.windows.length === 0 ? (- <p className="text-sm text-muted-foreground">+ <p className="rounded-xl border border-border/70 px-4 py-5 text-sm text-muted-foreground">{props.limits.message ?? "No limit data yet."}</p>) : (- <>- <BarChart- data={data}- config={{ left: { label: "Left", color: presentation.color } }}- animate={false}- bloom="off"- className="h-48 w-full"- margins={{ top: 8, right: 8, bottom: 22, left: 36 }}- >- <Grid vertical={false} />- <XAxis dataKey="label" />- <YAxis tickFormatter={(value) => `${Math.round(value)}%`} tickCount={5} />- <Tooltip valueFormatter={(value) => `${Math.round(value)}% left`} />- <Bar dataKey="left" variant="gradient" />- </BarChart>- <ul className="flex flex-col gap-1 text-sm text-muted-foreground">- {props.limits.windows.map((window) => (- <li+ <div className="divide-y divide-border/60 overflow-hidden rounded-xl border border-border/70">+ {props.limits.windows.map((window) => {+ const left = remainingPercent(window);+ return (+ <divkey={`${window.kind}:${window.label}`}- className="flex items-baseline justify-between gap-3"+ className="grid gap-3 px-4 py-4 md:grid-cols-[10rem_minmax(0,1fr)_7rem] md:items-center md:gap-5">- <span className="text-foreground">- {window.label} {Math.round(remainingPercent(window))}% left+ <div className="flex items-baseline justify-between gap-3 md:block">+ <span className="text-sm font-medium text-foreground">{window.label}</span>+ <span className="text-2xl font-semibold text-foreground tabular-nums md:mt-1 md:block">+ {Math.round(left)}%+ <span className="ms-1 text-xs font-normal text-muted-foreground">left</span>+ </span>+ </div>+ <div+ role="img"+ aria-label={`${window.label}: ${Math.round(left)}% left`}+ className="relative h-7 overflow-hidden rounded-md bg-muted/70"+ >+ <div+ className="absolute inset-y-0 start-0 rounded-md opacity-75"+ style={{+ width: `${left}%`,+ backgroundColor: `var(--color-${presentation.color}-500, var(--foreground))`,+ }}+ />+ <div className="absolute inset-0 bg-[repeating-linear-gradient(135deg,transparent_0,transparent_4px,var(--border)_4px,var(--border)_5px)] opacity-30" />+ </div>+ <span className="text-xs text-muted-foreground tabular-nums md:text-end">+ {formatReset(window.resetsAt)}</span>- <span className="tabular-nums">{formatReset(window.resetsAt)}</span>- </li>- ))}- </ul>- </>+ </div>+ );+ })}+ </div>)}</section>);@@ -130,6 +130,10 @@ export function UsagePlanMeters(props: { readonly limits: UsageProviderPlanLimitconst ACTIVITY_COLOR: Record<UsageProviderKind, DitherColor> = {claude: "orange",codex: "green",+ cursor: "purple",+ grok: "grey",+ kimi: "blue",+ opencode: "green",};export function UsageActivityChart(props: {diff --git a/apps/web/src/components/usage/UsagePage.test.tsx b/apps/web/src/components/usage/UsagePage.test.tsxindex e9a5e7f20..32662596f 100644--- a/apps/web/src/components/usage/UsagePage.test.tsx+++ b/apps/web/src/components/usage/UsagePage.test.tsx@@ -1,4 +1,4 @@-import { USAGE_CONTRACT_VERSION } from "@t3tools/contracts";+import { EnvironmentId, USAGE_CONTRACT_VERSION, UsageDay } from "@t3tools/contracts";import { mergeUsage } from "@t3tools/shared/usageMerge";import type { ReactNode } from "react";import { renderToStaticMarkup } from "react-dom/server";@@ -35,6 +35,7 @@ vi.mock("./UsageCharts", async (importOriginal) => {});import { UsagePage } from "./UsagePage";+import { saveUsagePagePreferences } from "./usagePagePreferences";const connectedPlanLimits = [{@@ -57,6 +58,7 @@ const connectedPlanLimits = [];beforeEach(() => {+ saveUsagePagePreferences({ metric: "limits", windowDays: 30 });testState.useUsage.mockReturnValue({merged: {...mergeUsage([], USAGE_CONTRACT_VERSION),@@ -111,7 +113,7 @@ describe("UsagePage", () => {expect(markup).not.toContain("Weekly 55% left");expect(markup).not.toContain("Connect a subscription");expect(markup).not.toContain("Connect an environment");- expect(markup).toContain("Activity");+ expect(markup).not.toContain("Activity");expect(markup).not.toContain("animate-spin");});@@ -146,8 +148,8 @@ describe("UsagePage", () => {expect(markup).toContain("Weekly 55% left");expect(markup).not.toContain("Reading plan limits");- expect(markup).toContain("Activity");- expect(markup).toContain("activity-chart");+ expect(markup).not.toContain("Activity");+ expect(markup).not.toContain("activity-chart");expect(markup).not.toContain("animate-spin");});@@ -183,10 +185,12 @@ describe("UsagePage", () => {expect(markup).toContain("anthropic");});- it("labels model activity by its transcript provider, not its model name", () => {+ it("labels model activity by its recorded provider, not its model name", () => {+ saveUsagePagePreferences({ metric: "tokens", windowDays: 30 });testState.useUsage.mockReturnValue({merged: {...mergeUsage([], USAGE_CONTRACT_VERSION),+ connectedProviders: ["openai-codex" as const, "anthropic" as const],models: [{provider: "codex" as const,@@ -226,4 +230,124 @@ describe("UsagePage", () => {expect(markup).toContain("Claude · gpt-5.6-sol");expect(markup).not.toContain("Claude · claude-opus-5");});++ it("does not show machine-wide transcript costs when no provider is connected", () => {+ saveUsagePagePreferences({ metric: "cost", windowDays: 30 });+ const summary = {+ contractVersion: USAGE_CONTRACT_VERSION,+ readAt: "2026-09-13T00:00:00.000Z",+ timeZone: "UTC",+ sinceDay: UsageDay.make("2026-08-15"),+ untilDay: UsageDay.make("2026-09-13"),+ buckets: [+ {+ day: UsageDay.make("2026-09-13"),+ provider: "codex" as const,+ model: "gpt-5.6-sol",+ totals: {+ uncachedInputTokens: 1_000,+ cachedInputTokens: 0,+ cacheCreationTokens: 0,+ outputTokens: 100,+ reasoningTokens: 0,+ },+ costUsd: 12.34,+ cacheSavingsUsd: 0,+ costSource: "modelPriced" as const,+ records: 1,+ unpricedRecords: 0,+ sessions: 1,+ },+ ],+ sources: [+ {+ fingerprint: {+ hostId: "test-machine",+ provider: "codex" as const,+ resolvedHomePath: "/home/test/.codex/sessions",+ volumeId: "1:1",+ },+ status: "ok" as const,+ scannedFiles: 1,+ skippedFiles: 0,+ malformedRecords: 0,+ distinctSessions: 1,+ message: null,+ },+ ],+ planLimits: [],+ connectedProviders: [],+ pricing: { status: "fresh" as const, source: "litellm", fetchedAt: null, knownModels: 1 },+ scanDurationMs: 1,+ };+ testState.useUsage.mockReturnValue({+ merged: mergeUsage(+ [{ environmentId: EnvironmentId.make("env-1"), label: "This Mac", summary }],+ USAGE_CONTRACT_VERSION,+ ),+ environments: [+ {+ environmentId: "env-1",+ label: "This Mac",+ isPending: false,+ error: null,+ summary,+ },+ ],+ isPending: false,+ isPartial: false,+ refresh: vi.fn(),+ });++ const markup = renderToStaticMarkup(<UsagePage />);++ expect(markup).not.toContain("$12.34");+ expect(markup).toContain("Connect a provider in Settings");+ });++ it("explains stale environment coverage before suggesting a provider connection", () => {+ saveUsagePagePreferences({ metric: "cost", windowDays: 30 });+ const staleSummary = {+ contractVersion: USAGE_CONTRACT_VERSION - 1,+ readAt: "2026-09-13T00:00:00.000Z",+ timeZone: "UTC",+ sinceDay: UsageDay.make("2026-08-15"),+ untilDay: UsageDay.make("2026-09-13"),+ buckets: [],+ sources: [],+ planLimits: [],+ connectedProviders: ["openai-codex" as const],+ pricing: { status: "fresh" as const, source: "litellm", fetchedAt: null, knownModels: 1 },+ scanDurationMs: 1,+ };+ testState.useUsage.mockReturnValue({+ merged: mergeUsage(+ [+ {+ environmentId: EnvironmentId.make("env-1"),+ label: "This Mac",+ summary: staleSummary,+ },+ ],+ USAGE_CONTRACT_VERSION,+ ),+ environments: [+ {+ environmentId: "env-1",+ label: "This Mac",+ isPending: false,+ error: null,+ summary: staleSummary,+ },+ ],+ isPending: false,+ isPartial: false,+ refresh: vi.fn(),+ });++ const markup = renderToStaticMarkup(<UsagePage />);++ expect(markup).toContain("This Mac runs an older server version");+ expect(markup).not.toContain("Connect a provider in Settings");+ });});diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsxindex 125a546b6..0515fdf6e 100644--- a/apps/web/src/components/usage/UsagePage.tsx+++ b/apps/web/src/components/usage/UsagePage.tsx@@ -1,108 +1,609 @@+import type { UsageProviderKind, UsageProviderPlanLimits } from "@t3tools/contracts";import { CheckIcon, RefreshCwIcon, XIcon } from "lucide-react";-import { useState } from "react";+import { useEffect, useMemo, useState } from "react";-import { formatTokens, formatUsd, makeWindow } from "@t3tools/shared/usageFormat";+import type { DailyTotals, HourlyTotals } from "@t3tools/shared/usageMerge";+import { isElectron } from "../../env";+import { useClientSettings } from "../../hooks/useSettings";+import { cn } from "../../lib/utils";import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";+import {+ enumerateDays,+ enumerateHourStarts,+ formatCount,+ formatDateTimeShort,+ formatDayShort,+ formatHourShort,+ formatPercent,+ formatTokens,+ formatUsd,+ makeWindow,+} from "@t3tools/shared/usageFormat";import { Button } from "../ui/button";-import { DialogClose, DialogHeader, DialogPanel, DialogTitle } from "../ui/dialog";-import { PLAN_PROVIDER_ORDER, UsageActivityChart, UsagePlanMeters } from "./UsageCharts";-import { PROVIDER_PRESENTATION } from "./usageProviders";+import { ScrollArea } from "../ui/scroll-area";+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";+import { SidebarInset } from "../ui/sidebar";+import { Skeleton } from "../ui/skeleton";+import { Toggle, ToggleGroup } from "../ui/toggle-group";+import {+ WorkspaceBreadcrumb,+ WorkspaceBreadcrumbItem,+ WorkspaceBreadcrumbSeparator,+} from "../WorkspaceBreadcrumb";+import { WorkspacePageContainer } from "../WorkspacePageContainer";+import { WorkspacePageHeader } from "../WorkspacePageHeader";+import { PLAN_PROVIDER_ORDER, UsagePlanMeters } from "./UsageCharts";+import { UsageProviderChart, type UsageChartMetric } from "./UsageProviderChart";+import { PROVIDER_ORDER, PROVIDER_PRESENTATION, providersWithUsage } from "./usageProviders";+import {+ readUsagePagePreferences,+ saveUsagePagePreferences,+ type UsagePagePreferences,+} from "./usagePagePreferences";++type UsageMetric = UsageChartMetric | "limits";+const METRIC_OPTIONS = [+ { value: "cost", label: "Cost" },+ { value: "tokens", label: "Tokens" },+ { value: "limits", label: "Limits" },+] as const satisfies readonly { value: UsageMetric; label: string }[];++function isUsageMetric(value: string | null | undefined): value is UsageMetric {+ return METRIC_OPTIONS.some((option) => option.value === value);+}++function isUsageWindowDays(value: number): value is UsagePagePreferences["windowDays"] {+ return WINDOW_OPTIONS.some((option) => option.days === value);+}++const WINDOW_OPTIONS = [+ { days: 1, label: "Past 24h" },+ { days: 7, label: "7 days" },+ { days: 30, label: "30 days" },+ { days: 90, label: "90 days" },+] as const;export function UsagePage() {- const [window] = useState(() => makeWindow(30));- const { merged, environments, isPending, refresh } = useUsage(window);+ const [preferences, setPreferences] = useState(readUsagePagePreferences);+ const [windowSelection, setWindowSelection] = useState(() => ({+ days: preferences.windowDays,+ window: makeWindow(+ preferences.windowDays,+ undefined,+ preferences.windowDays === 1 ? "hour" : "day",+ ),+ }));+ const metric = preferences.metric;+ const showingLimits = metric === "limits";+ const [breakdown, setBreakdown] = useState<"model" | "time">("model");+ const { days: windowDays, window } = windowSelection;+ const isPast24Hours = windowDays === 1;+ const { merged, environments, isPending, isPartial, refresh } = useUsage(window);+ const refreshMinutes = useClientSettings((settings) => settings.usageRefreshMinutes);const planLimits = PLAN_PROVIDER_ORDER.map((provider) =>merged.planLimits.find((entry) => entry.provider === provider && entry.status === "ok"),).filter((entry) => entry !== undefined);- return (- <>- <DialogHeader className="flex flex-row items-center justify-between gap-3 border-b px-5 py-3">- <DialogTitle>Usage</DialogTitle>- <div className="flex items-center gap-1">- <Button- onClick={() => refresh()}- aria-label="Refresh usage"- size="icon"+ useEffect(() => {+ const timer = globalThis.setInterval(refresh, Math.max(1, refreshMinutes) * 60 * 1000);+ return () => globalThis.clearInterval(timer);+ }, [refresh, refreshMinutes]);++ const days = useMemo(+ () => enumerateDays(window.sinceDay, window.untilDay),+ [window.sinceDay, window.untilDay],+ );+ const hours = useMemo(+ () =>+ window.sinceTime === undefined || window.untilTime === undefined+ ? []+ : enumerateHourStarts(window.sinceTime, window.untilTime),+ [window.sinceTime, window.untilTime],+ );+ // Newest first: the window can run 90 periods, so the interesting end+ // belongs at the top of the table.+ const breakdownPeriods = useMemo<readonly (DailyTotals | HourlyTotals)[]>(+ () => (isPast24Hours ? merged.hourly : merged.daily).toReversed(),+ [isPast24Hours, merged.daily, merged.hourly],+ );+ const breakdownModels = useMemo(+ () =>+ breakdown === "model" && metric === "tokens"+ ? merged.models.toSorted(+ (left, right) => right.totalTokens - left.totalTokens || right.costUsd - left.costUsd,+ )+ : merged.models,+ [breakdown, merged.models, metric],+ );+ const activeProviders = useMemo(() => providersWithUsage(merged.providers), [merged.providers]);+ const timeValueColumnWidth = `${60 / (activeProviders.length + 2)}%`;++ const selectWindow = (days: number) => {+ if (!isUsageWindowDays(days)) return;+ const nextPreferences = { metric, windowDays: days };+ setPreferences(nextPreferences);+ saveUsagePagePreferences(nextPreferences);+ setWindowSelection({+ days,+ window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),+ });+ };+ const selectMetric = (nextMetric: UsageMetric) => {+ const nextPreferences = { metric: nextMetric, windowDays };+ setPreferences(nextPreferences);+ saveUsagePagePreferences(nextPreferences);+ };+ const refreshWindow = () => {+ if (showingLimits) {+ refresh();+ return;+ }+ const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");+ if (+ nextWindow.sinceDay === window.sinceDay &&+ nextWindow.untilDay === window.untilDay &&+ nextWindow.sinceTime === window.sinceTime &&+ nextWindow.untilTime === window.untilTime+ ) {+ refresh();+ } else {+ setWindowSelection({ days: windowDays, window: nextWindow });+ }+ };+ const windowLabel =+ isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined+ ? `${formatDateTimeShort(window.sinceTime, window.timeZone)} to ${formatDateTimeShort(window.untilTime, window.timeZone)}`+ : `${formatDayShort(window.sinceDay)} to ${formatDayShort(window.untilDay)}`;+ const topbarContent = (+ <div className="flex w-full min-w-0 items-center gap-3">+ <WorkspaceBreadcrumb ariaLabel="Usage breadcrumb" className="min-w-0">+ <WorkspaceBreadcrumbItem current>+ <h1>Usage</h1>+ </WorkspaceBreadcrumbItem>+ {showingLimits ? null : (+ <>+ <WorkspaceBreadcrumbSeparator className="hidden md:flex" />+ <WorkspaceBreadcrumbItem className="hidden min-w-0 shrink md:flex">+ <span className="truncate">{windowLabel}</span>+ </WorkspaceBreadcrumbItem>+ </>+ )}+ </WorkspaceBreadcrumb>+ <div className="ms-auto hidden min-w-0 items-center justify-end gap-2 lg:flex">+ <ToggleGroup+ aria-label="Usage metric"+ variant="segmented"+ value={[metric]}+ onValueChange={(next) => {+ const value = next[0];+ if (isUsageMetric(value)) selectMetric(value);+ }}+ >+ {METRIC_OPTIONS.map((option) => (+ <Toggle key={option.value} value={option.value}>+ {option.label}+ </Toggle>+ ))}+ </ToggleGroup>+ {/* The period does not apply to Limits, so it stays in place but+ disabled; unmounting it shifted the metric toggle ~300px. */}+ <ToggleGroup+ aria-label="Usage period"+ variant="segmented"+ value={[String(windowDays)]}+ disabled={showingLimits}+ onValueChange={(next) => {+ const value = next[0];+ if (value) selectWindow(Number(value));+ }}+ >+ {WINDOW_OPTIONS.map((option) => (+ <Toggle key={option.days} value={String(option.days)}>+ {option.label}+ </Toggle>+ ))}+ </ToggleGroup>+ <Button+ onClick={refreshWindow}+ aria-label={showingLimits ? "Refresh limits" : "Refresh usage"}+ size="icon-sm"+ variant="ghost"+ >+ <RefreshCwIcon className="size-3.5" />+ </Button>+ </div>+ <div className="ms-auto flex min-w-0 items-center justify-end gap-1 lg:hidden">+ <Select+ value={metric}+ onValueChange={(value) => {+ if (isUsageMetric(value)) selectMetric(value);+ }}+ >+ <SelectTrigger+ aria-label="Usage metric"+ size="compact"variant="ghost"- disabled={isPending}+ className="w-auto min-w-0">- <RefreshCwIcon />- </Button>- <DialogClose aria-label="Close" render={<Button size="icon" variant="ghost" />}>- <XIcon />- </DialogClose>- </div>- </DialogHeader>-- <DialogPanel className="space-y-6 p-5">- {environments.length > 1 ? <UsageDeviceStrip environments={environments} /> : null}- <UsageCoverageNotice- environments={environments}- duplicateSources={merged.duplicateSources}- staleEnvironments={merged.staleEnvironments}- />- {planLimits.length > 0 ? (- <div className="grid gap-10 lg:grid-cols-2">- {planLimits.map((limits) => (- <UsagePlanMeters key={limits.provider} limits={limits} />+ <SelectValue>+ {METRIC_OPTIONS.find((option) => option.value === metric)?.label}+ </SelectValue>+ </SelectTrigger>+ <SelectPopup align="end" alignItemWithTrigger={false}>+ {METRIC_OPTIONS.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>))}- </div>- ) : isPending ? null : environments.length === 0 ? (- <p className="text-sm text-muted-foreground">Connect an environment to see usage.</p>- ) : (- <p className="text-sm text-muted-foreground">- Connect a subscription in Settings to see plan limits.- </p>- )}+ </SelectPopup>+ </Select>+ <Select+ value={String(windowDays)}+ disabled={showingLimits}+ onValueChange={(value) => selectWindow(Number(value))}+ >+ <SelectTrigger+ aria-label="Usage period"+ size="compact"+ variant="ghost"+ className="w-auto min-w-0"+ >+ <SelectValue>+ {WINDOW_OPTIONS.find((option) => option.days === windowDays)?.label}+ </SelectValue>+ </SelectTrigger>+ <SelectPopup align="end" alignItemWithTrigger={false}>+ {WINDOW_OPTIONS.map((option) => (+ <SelectItem key={option.days} value={String(option.days)}>+ {option.label}+ </SelectItem>+ ))}+ </SelectPopup>+ </Select>+ <Button+ onClick={refreshWindow}+ aria-label={showingLimits ? "Refresh limits" : "Refresh usage"}+ size="icon-sm"+ variant="ghost"+ >+ <RefreshCwIcon className="size-3.5" />+ </Button>+ </div>+ </div>+ );- <section className="flex flex-col gap-4 border-t border-border pt-6">- <h2 className="text-sm font-medium text-foreground">Activity</h2>- {isPending && merged.totalTokens === 0 ? (- <p className="text-sm text-muted-foreground">Reading transcripts…</p>- ) : (- <>- <UsageActivityChart- sinceDay={window.sinceDay}- untilDay={window.untilDay}- daily={merged.daily}- providers={merged.providers}+ return (+ <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">+ <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">+ <WorkspacePageHeader electron={isElectron}>{topbarContent}</WorkspacePageHeader>++ <ScrollArea className="min-h-0 flex-1">+ <WorkspacePageContainer width="wide">+ {showingLimits ? (+ <UsageLimitsOverview+ planLimits={planLimits}+ environments={environments}+ isPending={isPending}/>- <div className="grid grid-cols-2 gap-x-6 gap-y-3 md:grid-cols-4">- <Metric label="Processed tokens" value={formatTokens(merged.totalTokens)} />- <Metric label="Cached input" value={formatTokens(merged.cachedInputTokens)} />- <Metric label="Output" value={formatTokens(merged.outputTokens)} />- <Metric- label="Cache savings"- value={formatUsd(merged.costQuality.cacheSavingsUsd)}- />+ ) : isPending ? (+ <>+ {environments.length > 1 ? <UsageDeviceStrip environments={environments} /> : null}+ <UsageSkeleton />+ </>+ ) : merged.staleEnvironments.length > 0 && merged.connectedProviders.length === 0 ? (+ <UsageCoverageNotice+ environments={environments}+ duplicateSources={merged.duplicateSources}+ staleEnvironments={merged.staleEnvironments}+ />+ ) : merged.connectedProviders.length === 0 ? (+ <div className="rounded-xl border border-border/70 px-5 py-6">+ <h2 className="text-sm font-medium text-foreground">No provider usage yet</h2>+ <p className="mt-1 text-sm text-muted-foreground">+ Connect a provider in Settings to start tracking usage.+ </p></div>- {merged.models.length > 0 ? (- <ul className="flex flex-col gap-1.5 text-sm">- {merged.models.slice(0, 8).map((model) => (- <li- key={`${model.provider}:${model.model}`}- className="flex items-baseline justify-between gap-3"- >- <span className="min-w-0 truncate text-foreground">- {PROVIDER_PRESENTATION[model.provider].label} · {model.model}+ ) : (+ <>+ {isPartial && environments.length > 1 ? (+ <UsageDeviceStrip environments={environments} />+ ) : null}+ <UsageCoverageNotice+ environments={environments}+ duplicateSources={merged.duplicateSources}+ staleEnvironments={merged.staleEnvironments}+ />++ <section className="grid gap-6 lg:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]">+ <div className="flex min-w-0 flex-col gap-5">+ <div className="flex flex-col gap-1">+ <span className="text-4xl font-semibold text-foreground tabular-nums">+ {metric === "cost"+ ? formatUsd(merged.costUsd)+ : formatTokens(merged.totalTokens)}</span>- <span className="shrink-0 text-muted-foreground tabular-nums">- {formatTokens(model.totalTokens)}+ <span className="text-xs text-muted-foreground">+ {metric === "cost"+ ? merged.costQuality.unpricedShare > 0+ ? `${formatCount(merged.sessions)} sessions · estimate excludes ${formatPercent(merged.costQuality.unpricedShare)} unpriced records`+ : `${formatCount(merged.sessions)} sessions · API estimate`+ : `${formatCount(merged.sessions)} sessions`}</span>- </li>- ))}- </ul>- ) : null}- </>- )}- </section>- </DialogPanel>- </>+ </div>++ {activeProviders.map((provider) => {+ const totals = merged.providers.find((entry) => entry.provider === provider);+ const share =+ metric === "cost" ? (totals?.costShare ?? 0) : (totals?.tokenShare ?? 0);+ const providerSessions = totals?.sessions ?? 0;+ const sessionLabel = `${formatCount(providerSessions)} ${+ providerSessions === 1 ? "session" : "sessions"+ }`;+ return (+ <div key={provider} className="flex flex-col gap-1">+ <div className="flex items-baseline justify-between gap-4">+ <span className="flex min-w-0 items-center gap-2 text-sm text-foreground">+ <span+ aria-hidden+ className="size-2 shrink-0 rounded-full"+ style={{+ backgroundColor: PROVIDER_PRESENTATION[provider].color,+ }}+ />+ <ProviderMark provider={provider} className="size-4" />+ <span className="flex min-w-0 items-baseline gap-1.5">+ <span className="truncate">+ {PROVIDER_PRESENTATION[provider].label}+ </span>+ <span className="shrink-0 whitespace-nowrap text-[11px] text-muted-foreground tabular-nums">+ {sessionLabel}+ </span>+ </span>+ </span>+ <span className="shrink-0 text-sm font-medium text-foreground tabular-nums">+ {metric === "cost"+ ? formatUsd(totals?.costUsd ?? 0)+ : formatTokens(totals?.totalTokens ?? 0)}+ </span>+ </div>+ <span className="text-xs text-muted-foreground">+ {metric === "cost"+ ? `${formatPercent(share)} of cost · ${formatTokens(totals?.totalTokens ?? 0)} tokens`+ : `${formatPercent(share)} of tokens · ${formatUsd(totals?.costUsd ?? 0)}`}+ </span>+ </div>+ );+ })}+ </div>++ <div className="flex min-w-0 flex-col gap-3">+ <h2 className="text-sm font-medium text-foreground">+ {isPast24Hours ? "Hourly" : "Daily"}{" "}+ {metric === "tokens" ? "processed tokens" : "cost"}+ </h2>+ <UsageProviderChart+ providers={activeProviders}+ days={days}+ daily={merged.daily}+ hours={hours}+ hourly={merged.hourly}+ metric={metric}+ referenceTime={window.untilTime}+ resolution={isPast24Hours ? "hour" : "day"}+ timeZone={window.timeZone}+ />+ </div>+ </section>++ <section className="flex flex-col gap-2">+ <h2 className="text-sm font-medium text-foreground">Totals</h2>+ <div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">+ <Metric label="Processed tokens" value={formatTokens(merged.totalTokens)} />+ <Metric label="Cached input" value={formatTokens(merged.cachedInputTokens)} />+ <Metric+ label="Uncached input"+ value={formatTokens(merged.uncachedInputTokens)}+ />+ <Metric label="Output" value={formatTokens(merged.outputTokens)} />+ <Metric+ label="Cache savings"+ value={formatUsd(merged.costQuality.cacheSavingsUsd)}+ />+ </div>+ </section>++ <section className="flex flex-col gap-3">+ <div className="flex items-center justify-between gap-3">+ <h2 className="text-sm font-medium text-foreground">Breakdown</h2>+ <ToggleGroup+ aria-label="Usage breakdown"+ variant="segmented"+ value={[breakdown]}+ onValueChange={(next) => {+ const value = next[0];+ if (value === "model" || value === "time") setBreakdown(value);+ }}+ >+ {(+ [+ { value: "model", label: "Model" },+ { value: "time", label: isPast24Hours ? "Hour" : "Day" },+ ] as const+ ).map((option) => (+ <Toggle key={option.value} value={option.value}>+ {option.label}+ </Toggle>+ ))}+ </ToggleGroup>+ </div>++ {breakdown === "model" ? (+ <table className="w-full table-fixed text-sm">+ <colgroup>+ <col className="w-2/5" />+ <col className="w-1/5" />+ <col className="w-1/5" />+ <col className="w-1/5" />+ </colgroup>+ <thead>+ <tr className="border-b border-border text-left text-xs text-muted-foreground">+ <th className="py-2 font-normal">Model</th>+ <th className="py-2 text-right font-normal">Cost</th>+ <th className="py-2 text-right font-normal">Share</th>+ <th className="py-2 text-right font-normal">Tokens</th>+ </tr>+ </thead>+ <tbody>+ {breakdownModels.length === 0 ? (+ <tr>+ <td colSpan={4} className="py-6 text-center text-muted-foreground">+ No activity in this window.+ </td>+ </tr>+ ) : (+ breakdownModels.map((model) => (+ <tr+ key={`${model.provider}:${model.model}`}+ className="border-b border-border/50 transition-colors hover:bg-muted/50"+ >+ <td className="py-2 text-foreground">+ <span className="flex items-center gap-2">+ <ProviderMark provider={model.provider} className="size-3.5" />+ {PROVIDER_PRESENTATION[model.provider].label} · {model.model}+ </span>+ </td>+ <td className="py-2 text-right text-foreground tabular-nums">+ {formatUsd(model.costUsd)}+ </td>+ <td className="py-2 text-right text-muted-foreground tabular-nums">+ {formatPercent(model.costShare)}+ </td>+ <td className="py-2 text-right text-muted-foreground tabular-nums">+ {formatTokens(model.totalTokens)}+ </td>+ </tr>+ ))+ )}+ </tbody>+ </table>+ ) : (+ <table className="w-full table-fixed text-sm">+ <colgroup>+ <col className="w-2/5" />+ {activeProviders.map((provider) => (+ <col key={provider} style={{ width: timeValueColumnWidth }} />+ ))}+ <col style={{ width: timeValueColumnWidth }} />+ <col style={{ width: timeValueColumnWidth }} />+ </colgroup>+ <thead>+ <tr className="border-b border-border text-left text-xs text-muted-foreground">+ <th className="py-2 font-normal">{isPast24Hours ? "Hour" : "Day"}</th>+ {activeProviders.map((provider) => (+ <th key={provider} className="py-2 text-right font-normal">+ {PROVIDER_PRESENTATION[provider].label}+ </th>+ ))}+ <th className="py-2 text-right font-normal">Total</th>+ <th className="py-2 text-right font-normal">Tokens</th>+ </tr>+ </thead>+ <tbody>+ {breakdownPeriods.length === 0 ? (+ <tr>+ <td+ colSpan={activeProviders.length + 3}+ className="py-6 text-center text-muted-foreground"+ >+ No activity in this window.+ </td>+ </tr>+ ) : (+ breakdownPeriods.map((period) => (+ <tr+ key={"hourStart" in period ? period.hourStart : period.day}+ className="border-b border-border/50 transition-colors hover:bg-muted/50"+ >+ <td className="py-2 text-foreground">+ {"hourStart" in period+ ? formatHourShort(period.hourStart, window.timeZone)+ : formatDayShort(period.day)}+ </td>+ {activeProviders.map((provider) => (+ <td+ key={provider}+ className="py-2 text-right text-muted-foreground tabular-nums"+ >+ {formatUsd(period.byProvider.get(provider)?.costUsd ?? 0)}+ </td>+ ))}+ <td className="py-2 text-right text-foreground tabular-nums">+ {formatUsd(period.costUsd)}+ </td>+ <td className="py-2 text-right text-muted-foreground tabular-nums">+ {formatTokens(period.totalTokens)}+ </td>+ </tr>+ ))+ )}+ </tbody>+ </table>+ )}+ </section>+ </>+ )}+ </WorkspacePageContainer>+ </ScrollArea>+ </div>+ </SidebarInset>);}+function UsageLimitsOverview({+ planLimits,+ environments,+ isPending,+}: {+ readonly planLimits: readonly UsageProviderPlanLimits[];+ readonly environments: readonly EnvironmentUsageStatus[];+ readonly isPending: boolean;+}) {+ if (isPending && planLimits.length === 0) {+ return <UsageSkeleton />;+ }++ return (+ <div className="flex flex-col gap-9">+ {environments.length > 1 ? <UsageDeviceStrip environments={environments} /> : null}+ {planLimits.length > 0 ? (+ planLimits.map((limits) => <UsagePlanMeters key={limits.provider} limits={limits} />)+ ) : environments.length === 0 ? (+ <p className="text-sm text-muted-foreground">Connect an environment to see usage.</p>+ ) : (+ <div className="rounded-xl border border-border/70 px-5 py-6">+ <h2 className="text-sm font-medium text-foreground">No subscription limits yet</h2>+ <p className="mt-1 text-sm text-muted-foreground">+ Connect a provider subscription in Settings, then refresh this page.+ </p>+ </div>+ )}+ </div>+ );+}++/** Brand mark for the harness a row belongs to. */+function ProviderMark({+ provider,+ className,+}: {+ readonly provider: UsageProviderKind;+ readonly className: string;+}) {+ const Mark = PROVIDER_PRESENTATION[provider].mark;+ return <Mark className={cn("shrink-0", className)} aria-hidden />;+}+function Metric({ label, value }: { readonly label: string; readonly value: string }) {return (<div className="flex min-w-0 flex-col gap-0.5">@@ -112,6 +613,12 @@ function Metric({ label, value }: { readonly label: string; readonly value: stri);}+/**+ * Says plainly when the totals are incomplete: an environment that failed, or+ * one whose transcripts another environment already reported. Environments+ * that are still answering never reach this notice; the page shows the+ * loading skeleton until every one is terminal.+ */function UsageCoverageNotice({environments,duplicateSources,@@ -141,7 +648,7 @@ function UsageCoverageNotice({))}{duplicateSources.length > 0 ? (<span>- Counted once across environments sharing a transcript directory:{" "}+ Counted once across clients sharing an environment usage store:{" "}{duplicateSources.join(", ")}</span>) : null}@@ -149,6 +656,11 @@ function UsageCoverageNotice({);}+/**+ * Per-device progress while the page waits for every environment to answer.+ * Only rendered with two or more devices; a lone device has nothing to+ * enumerate.+ */function UsageDeviceStrip({environments,}: {@@ -199,3 +711,66 @@ function UsageDeviceStrip({</div>);}++/**+ * Stand-in with the loaded page's shape, using the shared `Skeleton` bars so it+ * breathes with the same `animate-skeleton` pulse as every other loading state.+ * Blocks fill in exactly once when the last device answers.+ */+function UsageSkeleton() {+ return (+ <>+ <section className="grid gap-6 lg:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]">+ <div className="flex flex-col gap-5">+ <div className="flex flex-col gap-1">+ <Skeleton className="h-10 w-36" />+ <Skeleton className="h-4 w-32" />+ </div>+ {PROVIDER_ORDER.map((provider) => (+ <div key={provider} className="flex flex-col gap-1">+ <div className="flex min-h-5 items-center justify-between gap-4">+ <span className="flex items-center gap-2">+ <Skeleton className="size-2 shrink-0 rounded-full" />+ <Skeleton className="size-4 shrink-0 rounded-full" />+ <Skeleton className="h-3.5 w-20" />+ </span>+ <Skeleton className="h-3.5 w-14" />+ </div>+ <Skeleton className="h-4 w-36" />+ </div>+ ))}+ </div>++ <div className="flex flex-col gap-3">+ <Skeleton className="h-5 w-24" />+ <div className="flex flex-col gap-1">+ <Skeleton className="ml-16 h-56 bg-muted-foreground/10" />+ <Skeleton className="ml-16 h-4 bg-muted-foreground/10" />+ </div>+ </div>+ </section>++ <section className="flex flex-col gap-2">+ <h2 className="text-sm font-medium text-foreground">Totals</h2>+ <div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">+ {["Processed tokens", "Cached input", "Uncached input", "Output", "Cache savings"].map(+ (label) => (+ <div key={label} className="flex flex-col gap-0.5">+ <span className="text-xs text-muted-foreground">{label}</span>+ <Skeleton className="h-6 w-16" />+ </div>+ ),+ )}+ </div>+ </section>++ <section className="flex flex-col gap-3">+ <div className="flex items-center justify-between gap-3">+ <h2 className="text-sm font-medium text-foreground">Breakdown</h2>+ <Skeleton className="h-7 w-28 rounded-lg" />+ </div>+ <Skeleton className="h-44 bg-muted-foreground/10" />+ </section>+ </>+ );+}diff --git a/apps/web/src/components/usage/UsageProviderChart.tsx b/apps/web/src/components/usage/UsageProviderChart.tsxnew file mode 100644index 000000000..26d49e664--- /dev/null+++ b/apps/web/src/components/usage/UsageProviderChart.tsx@@ -0,0 +1,470 @@+import type { UsageProviderKind } from "@t3tools/contracts";+import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";++import type { DailyTotals, HourlyTotals } from "@t3tools/shared/usageMerge";+import {+ formatDayShort,+ formatHourShort,+ formatRelativeHourShort,+ formatTokens,+ formatUsd,+} from "@t3tools/shared/usageFormat";+import { PROVIDER_ORDER, PROVIDER_PRESENTATION } from "./usageProviders";++const VIEW_WIDTH = 960;+const VIEW_HEIGHT = 260;+const TICK_COUNT = 4;+const PLOT_TOP = 8;++export type UsageChartMetric = "tokens" | "cost";++interface UsageProviderChartProps {+ readonly providers: readonly UsageProviderKind[];+ readonly days: readonly string[];+ readonly daily: readonly DailyTotals[];+ readonly hours: readonly string[];+ readonly hourly: readonly HourlyTotals[];+ readonly metric: UsageChartMetric;+ readonly referenceTime: string | undefined;+ readonly resolution: "day" | "hour";+ readonly timeZone: string;+}++/** One day's per-provider values, shared by the paths and the hover readout. */+export interface DayColumn {+ readonly bands: readonly {+ readonly provider: UsageProviderKind;+ readonly value: number;+ }[];+ readonly total: number;+}++interface Point {+ readonly x: number;+ readonly y: number;+}++function valueFor(+ totals: DailyTotals | HourlyTotals | undefined,+ provider: UsageProviderKind,+ metric: UsageChartMetric,+): number {+ const entry = totals?.byProvider.get(provider);+ if (entry === undefined) return 0;+ return metric === "tokens" ? entry.totalTokens : entry.costUsd;+}++function buildPeriodColumns(+ periods: readonly string[],+ byPeriod: ReadonlyMap<string, DailyTotals | HourlyTotals>,+ metric: UsageChartMetric,+): readonly DayColumn[] {+ return periods.map((period) => {+ const entry = byPeriod.get(period);+ const bands = PROVIDER_ORDER.map((provider) => ({+ provider,+ value: valueFor(entry, provider, metric),+ }));+ return { bands, total: bands.reduce((sum, band) => sum + band.value, 0) };+ });+}++/** Shape-preserving cubic tangents that cannot overshoot spiky usage data. */+function monotoneTangents(points: readonly Point[]): readonly number[] {+ const count = points.length;+ if (count < 2) return [0];++ const slopes: number[] = [];+ for (let index = 0; index < count - 1; index += 1) {+ const dx = (points[index + 1]?.x ?? 0) - (points[index]?.x ?? 0);+ const dy = (points[index + 1]?.y ?? 0) - (points[index]?.y ?? 0);+ slopes.push(dx === 0 ? 0 : dy / dx);+ }++ const tangents: number[] = Array.from({ length: count }, () => 0);+ tangents[0] = slopes[0] ?? 0;+ tangents[count - 1] = slopes[count - 2] ?? 0;+ for (let index = 1; index < count - 1; index += 1) {+ const previous = slopes[index - 1] ?? 0;+ const next = slopes[index] ?? 0;+ tangents[index] = previous * next <= 0 ? 0 : (previous + next) / 2;+ }++ for (let index = 0; index < count - 1; index += 1) {+ const slope = slopes[index] ?? 0;+ if (slope === 0) {+ tangents[index] = 0;+ tangents[index + 1] = 0;+ continue;+ }+ const a = (tangents[index] ?? 0) / slope;+ const b = (tangents[index + 1] ?? 0) / slope;+ const magnitude = a * a + b * b;+ if (magnitude > 9) {+ const scale = 3 / Math.sqrt(magnitude);+ tangents[index] = scale * a * slope;+ tangents[index + 1] = scale * b * slope;+ }+ }++ return tangents;+}++interface CurveSegment {+ readonly from: Point;+ readonly c1: Point;+ readonly c2: Point;+ readonly to: Point;+}++function smoothCurve(points: readonly Point[]): readonly CurveSegment[] {+ if (points.length < 2) return [];+ const tangents = monotoneTangents(points);+ const segments: CurveSegment[] = [];++ for (let index = 0; index < points.length - 1; index += 1) {+ const from = points[index];+ const to = points[index + 1];+ if (from === undefined || to === undefined) continue;+ const dx = to.x - from.x;+ segments.push({+ from,+ c1: { x: from.x + dx / 3, y: from.y + ((tangents[index] ?? 0) * dx) / 3 },+ c2: { x: to.x - dx / 3, y: to.y - ((tangents[index + 1] ?? 0) * dx) / 3 },+ to,+ });+ }+ return segments;+}++function curvePath(segments: readonly CurveSegment[]): string {+ const first = segments[0];+ if (first === undefined) return "";+ let path = `M${first.from.x.toFixed(2)},${first.from.y.toFixed(2)}`;+ for (const segment of segments) {+ path += ` C${segment.c1.x.toFixed(2)},${segment.c1.y.toFixed(2)} ${segment.c2.x.toFixed(2)},${segment.c2.y.toFixed(2)} ${segment.to.x.toFixed(2)},${segment.to.y.toFixed(2)}`;+ }+ return path;+}++/**+ * Builds a scale whose maximum is a readable 1/2/5 x 10^n step at or above the+ * peak.+ *+ * Rounding the maximum *up* is the point: stopping at the last step below the+ * peak leaves the tallest day drawn past the top of the plot, where it is+ * clipped.+ */+export function niceScale(peak: number, count: number): { max: number; ticks: readonly number[] } {+ if (peak <= 0) return { max: 0, ticks: [0] };++ const rawStep = peak / count;+ const magnitude = 10 ** Math.floor(Math.log10(rawStep));+ const normalized = rawStep / magnitude;+ const step = (normalized > 5 ? 10 : normalized > 2 ? 5 : normalized > 1 ? 2 : 1) * magnitude;++ const max = Math.ceil(peak / step) * step;+ const ticks: number[] = [];+ for (let value = 0; value <= max + step * 1e-6; value += step) ticks.push(value);+ return { max, ticks };+}++/**+ * Turns the merged daily totals into one column per day.+ *+ * Values are absolute, not cumulative: each provider is drawn from the same+ * zero baseline so the chart never implies that one provider is always larger.+ *+ * The chart paths and the hover readout both consume this, so the number under+ * the cursor is by construction the number that was plotted rather than a+ * second derivation that can drift from it.+ */+export function buildDayColumns(+ days: readonly string[],+ byDay: ReadonlyMap<string, DailyTotals>,+ metric: UsageChartMetric,+): readonly DayColumn[] {+ return buildPeriodColumns(days, byDay, metric);+}++export function UsageProviderChart({+ providers,+ days,+ daily,+ hours,+ hourly,+ metric,+ referenceTime,+ resolution,+ timeZone,+}: UsageProviderChartProps) {+ const periods = resolution === "hour" ? hours : days;+ const byPeriod = useMemo(+ () =>+ resolution === "hour"+ ? new Map(hourly.map((entry) => [entry.hourStart, entry]))+ : new Map(daily.map((entry) => [entry.day, entry])),+ [daily, hourly, resolution],+ );+ const [hoverIndex, setHoverIndex] = useState<number | null>(null);+ const plotRef = useRef<HTMLDivElement | null>(null);+ const tooltipRef = useRef<HTMLDivElement | null>(null);+ const hoverPositionRef = useRef<{ x: number; y: number } | null>(null);++ const { paths, ticks, stepX, toY, series } = useMemo(() => {+ if (periods.length === 0) {+ return {+ paths: [],+ series: [] as readonly DayColumn[],+ stepX: 0,+ ticks: [0] as readonly number[],+ toY: () => VIEW_HEIGHT,+ };+ }++ const columns = buildPeriodColumns(periods, byPeriod, metric);+ // The scale tops out at the largest single provider-period, not the sum:+ // layered series each measure from zero, so a combined peak would leave+ // the plot permanently half empty.+ const peak = columns.reduce(+ (max, column) => column.bands.reduce((inner, band) => Math.max(inner, band.value), max),+ 0,+ );+ const { max, ticks: tickValues } = niceScale(peak, TICK_COUNT);+ const step = periods.length === 1 ? 0 : VIEW_WIDTH / (periods.length - 1);+ // Leave room above the top gridline so the constant-width stroke is not+ // clipped when a series reaches the peak.+ const toY = (value: number) =>+ max === 0 ? VIEW_HEIGHT : VIEW_HEIGHT - (value / max) * (VIEW_HEIGHT - PLOT_TOP);++ const built = providers.map((provider) => {+ const providerIndex = PROVIDER_ORDER.indexOf(provider);+ const line = curvePath(+ smoothCurve(+ columns.map((column, periodIndex) => ({+ x: periodIndex * step,+ y: toY(column.bands[providerIndex]?.value ?? 0),+ })),+ ),+ );+ return {+ provider,+ total: columns.reduce((sum, column) => sum + (column.bands[providerIndex]?.value ?? 0), 0),+ area: line === "" ? "" : `${line} L${VIEW_WIDTH},${VIEW_HEIGHT} L0,${VIEW_HEIGHT} Z`,+ line,+ };+ });++ // Paint the heavier series first so the lighter one is not buried.+ return {+ paths: built.toSorted((a, b) => b.total - a.total),+ series: columns,+ stepX: step,+ ticks: tickValues,+ toY,+ };+ }, [byPeriod, metric, periods, providers]);++ const format = metric === "tokens" ? formatTokens : formatUsd;++ const positionTooltip = useCallback(() => {+ const plot = plotRef.current;+ const tooltip = tooltipRef.current;+ const hoverPosition = hoverPositionRef.current;+ if (plot === null || tooltip === null || hoverPosition === null) return;++ const gap = 12;+ const tooltipWidth = tooltip.offsetWidth;+ const tooltipHeight = tooltip.offsetHeight;+ const plotWidth = plot.clientWidth;+ const plotHeight = plot.clientHeight;+ const preferredLeft =+ hoverPosition.x + gap + tooltipWidth <= plotWidth+ ? hoverPosition.x + gap+ : hoverPosition.x - gap - tooltipWidth;+ const preferredTop =+ hoverPosition.y + gap + tooltipHeight <= plotHeight+ ? hoverPosition.y + gap+ : hoverPosition.y - gap - tooltipHeight;+ const left = Math.min(Math.max(0, preferredLeft), Math.max(0, plotWidth - tooltipWidth));+ const top = Math.min(Math.max(0, preferredTop), Math.max(0, plotHeight - tooltipHeight));+ plot.style.setProperty("--usage-tooltip-left", `${left}px`);+ plot.style.setProperty("--usage-tooltip-top", `${top}px`);+ }, []);++ useLayoutEffect(() => {+ if (hoverIndex === null) return;+ positionTooltip();++ const plot = plotRef.current;+ const tooltip = tooltipRef.current;+ if (plot === null || tooltip === null || typeof ResizeObserver === "undefined") return;++ const observer = new ResizeObserver(positionTooltip);+ observer.observe(plot);+ observer.observe(tooltip);+ return () => observer.disconnect();+ }, [hoverIndex, positionTooltip]);++ const handleMove = useCallback(+ (event: React.MouseEvent<HTMLDivElement>) => {+ const plot = plotRef.current;+ if (plot === null || periods.length === 0) return;+ const bounds = plot.getBoundingClientRect();+ if (bounds.width === 0) return;+ const localX = Math.min(bounds.width, Math.max(0, event.clientX - bounds.left));+ const localY = Math.min(bounds.height, Math.max(0, event.clientY - bounds.top));+ const fraction = localX / bounds.width;+ const index = Math.round(fraction * (periods.length - 1));+ hoverPositionRef.current = { x: localX, y: localY };+ positionTooltip();+ setHoverIndex(Math.min(periods.length - 1, Math.max(0, index)));+ },+ [periods.length, positionTooltip],+ );++ const hoveredPeriod = hoverIndex === null ? undefined : periods[hoverIndex];+ const hoveredColumn = hoverIndex === null ? undefined : series[hoverIndex];+ const formatPeriod = (period: string) =>+ resolution === "hour" ? formatHourShort(period, timeZone) : formatDayShort(period);+ const formatTooltipPeriod = (period: string) =>+ resolution === "hour" && referenceTime !== undefined+ ? formatRelativeHourShort(period, referenceTime, timeZone)+ : formatPeriod(period);++ return (+ <div className="flex flex-col gap-1">+ <div className="flex gap-2">+ {/* Axis labels sit outside the plot so they stay aligned to gridlines. */}+ <div className="relative h-56 w-14 shrink-0">+ {ticks.map((tick) => (+ <span+ key={tick}+ className="absolute right-0 -translate-y-1/2 text-[10px] text-muted-foreground tabular-nums"+ style={{ top: `${(toY(tick) / VIEW_HEIGHT) * 100}%` }}+ >+ {tick === 0 ? "0" : format(tick)}+ </span>+ ))}+ </div>++ <div+ ref={plotRef}+ className="relative h-56 flex-1"+ onMouseMove={handleMove}+ onMouseLeave={() => {+ hoverPositionRef.current = null;+ setHoverIndex(null);+ }}+ >+ <svg+ className="h-full w-full"+ viewBox={`0 0 ${VIEW_WIDTH} ${VIEW_HEIGHT}`}+ preserveAspectRatio="none"+ role="img"+ aria-label={`${resolution === "hour" ? "Hourly" : "Daily"} ${metric === "tokens" ? "processed tokens" : "cost"} by provider`}+ >+ {ticks.map((tick) => {+ const y = toY(tick);+ return (+ <line+ key={tick}+ x1={0}+ x2={VIEW_WIDTH}+ y1={y}+ y2={y}+ stroke="currentColor"+ strokeWidth={1}+ className="text-border"+ vectorEffect="non-scaling-stroke"+ />+ );+ })}++ {/* Fills first, then every stroke, so no series covers another's line. */}+ {paths.map(({ provider, area }) => (+ <path+ key={provider}+ d={area}+ fill={PROVIDER_PRESENTATION[provider].color}+ fillOpacity={0.12}+ />+ ))}+ {paths.map(({ provider, line }) => (+ <path+ key={provider}+ d={line}+ fill="none"+ stroke={PROVIDER_PRESENTATION[provider].color}+ strokeWidth={2}+ vectorEffect="non-scaling-stroke"+ />+ ))}++ {hoverIndex === null ? null : (+ <line+ x1={hoverIndex * stepX}+ x2={hoverIndex * stepX}+ y1={PLOT_TOP}+ y2={VIEW_HEIGHT}+ stroke="currentColor"+ strokeWidth={1}+ className="text-muted-foreground"+ vectorEffect="non-scaling-stroke"+ />+ )}+ </svg>++ {hoveredPeriod === undefined ? null : (+ <div+ ref={tooltipRef}+ className="surface-glass pointer-events-none absolute z-10 min-w-36 max-w-full rounded-xl border border-border/50 px-2.5 py-2 text-xs shadow-lg"+ style={{+ left: "var(--usage-tooltip-left, 0px)",+ top: "var(--usage-tooltip-top, 0px)",+ }}+ >+ <div className="mb-1 text-muted-foreground">{formatTooltipPeriod(hoveredPeriod)}</div>+ {providers.map((provider) => {+ const { label, mark: Mark } = PROVIDER_PRESENTATION[provider];+ return (+ <div key={provider} className="flex items-center justify-between gap-3">+ <span className="flex items-center gap-1.5 text-muted-foreground">+ <Mark className="size-3 shrink-0" aria-hidden />+ {label}+ </span>+ <span className="text-foreground tabular-nums">+ {format(+ hoveredColumn?.bands.find((band) => band.provider === provider)?.value ?? 0,+ )}+ </span>+ </div>+ );+ })}+ <div className="mt-1 flex items-center justify-between gap-3 border-t border-border pt-1">+ <span className="text-muted-foreground">Total</span>+ <span className="text-foreground tabular-nums">+ {format(hoveredColumn?.total ?? 0)}+ </span>+ </div>+ </div>+ )}+ </div>+ </div>++ <div className="flex justify-between pl-16 text-[10px] text-muted-foreground uppercase">+ <span>{periods[0] === undefined ? "" : formatPeriod(periods[0])}</span>+ <span>+ {periods[Math.floor(periods.length / 2)] === undefined+ ? ""+ : formatPeriod(periods[Math.floor(periods.length / 2)] ?? "")}+ </span>+ <span>+ {periods[periods.length - 1] === undefined+ ? ""+ : formatPeriod(periods[periods.length - 1] ?? "")}+ </span>+ </div>+ </div>+ );+}diff --git a/apps/web/src/components/usage/usagePagePreferences.ts b/apps/web/src/components/usage/usagePagePreferences.tsnew file mode 100644index 000000000..36f08095e--- /dev/null+++ b/apps/web/src/components/usage/usagePagePreferences.ts@@ -0,0 +1,31 @@+import * as Schema from "effect/Schema";++import { getLocalStorageItem, setLocalStorageItem } from "../../hooks/useLocalStorage";++const UsagePagePreferencesSchema = Schema.Struct({+ metric: Schema.Literals(["cost", "tokens", "limits"]),+ windowDays: Schema.Literals([1, 7, 30, 90]),+});+export type UsagePagePreferences = typeof UsagePagePreferencesSchema.Type;++const STORAGE_KEY = "akeru:usage-page-preferences:v1";+const DEFAULT_PREFERENCES: UsagePagePreferences = { metric: "limits", windowDays: 30 };++export function readUsagePagePreferences(): UsagePagePreferences {+ try {+ return getLocalStorageItem(STORAGE_KEY, UsagePagePreferencesSchema) ?? DEFAULT_PREFERENCES;+ } catch (error) {+ console.error("Could not read Usage page preferences.", error);+ return DEFAULT_PREFERENCES;+ }+}++export function saveUsagePagePreferences(preferences: UsagePagePreferences): void {+ try {+ setLocalStorageItem(STORAGE_KEY, preferences, UsagePagePreferencesSchema);+ } catch (error) {+ console.error("Could not save Usage page preferences.", error);+ // A private or locked-down browser can deny storage. The page still works+ // for the current visit, so persistence remains best effort.+ }+}diff --git a/apps/web/src/components/usage/usageProviders.ts b/apps/web/src/components/usage/usageProviders.tsindex 571445707..c213f23e7 100644--- a/apps/web/src/components/usage/usageProviders.ts+++ b/apps/web/src/components/usage/usageProviders.ts@@ -1,6 +1,14 @@import type { UsageProviderKind } from "@t3tools/contracts";-import { ClaudeAI, type Icon, OpenAI } from "../Icons";+import {+ ClaudeAI,+ CursorIcon,+ GrokIcon,+ KimiIcon,+ OpenCodeIcon,+ type Icon,+ OpenAI,+} from "../Icons";type UsageProviderPresentation = {readonly label: string;@@ -24,6 +32,26 @@ export const PROVIDER_PRESENTATION = {color: "#d97757",mark: ClaudeAI,},+ cursor: {+ label: "Cursor",+ color: "#a78bfa",+ mark: CursorIcon,+ },+ grok: {+ label: "Grok",+ color: "#94a3b8",+ mark: GrokIcon,+ },+ kimi: {+ label: "Kimi For Coding",+ color: "#60a5fa",+ mark: KimiIcon,+ },+ opencode: {+ label: "OpenCode",+ color: "#34d399",+ mark: OpenCodeIcon,+ },} satisfies Record<UsageProviderKind, UsageProviderPresentation>;/** Stable provider reading order across charts, summaries, tables, and hover rows. */diff --git a/apps/web/src/pluginsDialogStore.ts b/apps/web/src/pluginsDialogStore.tsindex 2de25166d..5d1cce0e3 100644--- a/apps/web/src/pluginsDialogStore.ts+++ b/apps/web/src/pluginsDialogStore.ts@@ -5,6 +5,7 @@ interface PluginsDialogState {readonly requestedQuery: string | null;readonly openPlugins: (query?: string) => void;readonly closePlugins: () => void;+ readonly acknowledgeNavigation: () => void;}export const usePluginsDialogStore = create<PluginsDialogState>((set) => ({@@ -12,6 +13,7 @@ export const usePluginsDialogStore = create<PluginsDialogState>((set) => ({requestedQuery: null,openPlugins: (query) => set({ open: true, requestedQuery: query?.trim() || null }),closePlugins: () => set({ open: false, requestedQuery: null }),+ acknowledgeNavigation: () => set({ open: false }),}));export function openPlugins(query?: string): void {@@ -22,6 +24,10 @@ export function closePlugins(): void {usePluginsDialogStore.getState().closePlugins();}+export function acknowledgePluginsNavigation(): void {+ usePluginsDialogStore.getState().acknowledgeNavigation();+}+export function isLegacyPluginsPath(pathname: string): boolean {return pathname.replace(/^\/settings\/?/, "").split("/")[0] === "plugins";}diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.tsindex 4727bdeb8..625cd0d79 100644--- a/apps/web/src/routeTree.gen.ts+++ b/apps/web/src/routeTree.gen.ts@@ -11,9 +11,11 @@import { Route as rootRouteImport } from './routes/__root'import { Route as UsageRouteImport } from './routes/usage'import { Route as SettingsRouteImport } from './routes/settings'+import { Route as PluginsRouteImport } from './routes/plugins'import { Route as PairRouteImport } from './routes/pair'import { Route as ChatRouteImport } from './routes/_chat'import { Route as ChatIndexRouteImport } from './routes/_chat.index'+import { Route as SettingsSectionRouteImport } from './routes/settings.$section'import { Route as SettingsSplatRouteImport } from './routes/settings.$'import { Route as ProjectsProjectKeyRouteImport } from './routes/projects.$projectKey'import { Route as ChatGroupsGroupIdRouteImport } from './routes/_chat.groups.$groupId'@@ -31,6 +33,11 @@ const SettingsRoute = SettingsRouteImport.update({path: '/settings',getParentRoute: () => rootRouteImport,} as any)+const PluginsRoute = PluginsRouteImport.update({+ id: '/plugins',+ path: '/plugins',+ getParentRoute: () => rootRouteImport,+} as any)const PairRoute = PairRouteImport.update({id: '/pair',path: '/pair',@@ -45,6 +52,11 @@ const ChatIndexRoute = ChatIndexRouteImport.update({path: '/',getParentRoute: () => ChatRoute,} as any)+const SettingsSectionRoute = SettingsSectionRouteImport.update({+ id: '/$section',+ path: '/$section',+ getParentRoute: () => SettingsRoute,+} as any)const SettingsSplatRoute = SettingsSplatRouteImport.update({id: '/$',path: '/$',@@ -80,10 +92,12 @@ const ChatEnvironmentIdThreadIdRoute =export interface FileRoutesByFullPath {'/': typeof ChatIndexRoute'/pair': typeof PairRoute+ '/plugins': typeof PluginsRoute'/settings': typeof SettingsRouteWithChildren'/usage': typeof UsageRoute'/projects/$projectKey': typeof ProjectsProjectKeyRoute'/settings/$': typeof SettingsSplatRoute+ '/settings/$section': typeof SettingsSectionRoute'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute'/bots/$botId': typeof ChatBotsBotIdRoute'/draft/$draftId': typeof ChatDraftDraftIdRoute@@ -91,10 +105,12 @@ export interface FileRoutesByFullPath {}export interface FileRoutesByTo {'/pair': typeof PairRoute+ '/plugins': typeof PluginsRoute'/settings': typeof SettingsRouteWithChildren'/usage': typeof UsageRoute'/projects/$projectKey': typeof ProjectsProjectKeyRoute'/settings/$': typeof SettingsSplatRoute+ '/settings/$section': typeof SettingsSectionRoute'/': typeof ChatIndexRoute'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute'/bots/$botId': typeof ChatBotsBotIdRoute@@ -105,10 +121,12 @@ export interface FileRoutesById {__root__: typeof rootRouteImport'/_chat': typeof ChatRouteWithChildren'/pair': typeof PairRoute+ '/plugins': typeof PluginsRoute'/settings': typeof SettingsRouteWithChildren'/usage': typeof UsageRoute'/projects/$projectKey': typeof ProjectsProjectKeyRoute'/settings/$': typeof SettingsSplatRoute+ '/settings/$section': typeof SettingsSectionRoute'/_chat/': typeof ChatIndexRoute'/_chat/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute'/_chat/bots/$botId': typeof ChatBotsBotIdRoute@@ -120,10 +138,12 @@ export interface FileRouteTypes {fullPaths:| '/'| '/pair'+ | '/plugins'| '/settings'| '/usage'| '/projects/$projectKey'| '/settings/$'+ | '/settings/$section'| '/$environmentId/$threadId'| '/bots/$botId'| '/draft/$draftId'@@ -131,10 +151,12 @@ export interface FileRouteTypes {fileRoutesByTo: FileRoutesByToto:| '/pair'+ | '/plugins'| '/settings'| '/usage'| '/projects/$projectKey'| '/settings/$'+ | '/settings/$section'| '/'| '/$environmentId/$threadId'| '/bots/$botId'@@ -144,10 +166,12 @@ export interface FileRouteTypes {| '__root__'| '/_chat'| '/pair'+ | '/plugins'| '/settings'| '/usage'| '/projects/$projectKey'| '/settings/$'+ | '/settings/$section'| '/_chat/'| '/_chat/$environmentId/$threadId'| '/_chat/bots/$botId'@@ -158,6 +182,7 @@ export interface FileRouteTypes {export interface RootRouteChildren {ChatRoute: typeof ChatRouteWithChildrenPairRoute: typeof PairRoute+ PluginsRoute: typeof PluginsRouteSettingsRoute: typeof SettingsRouteWithChildrenUsageRoute: typeof UsageRouteProjectsProjectKeyRoute: typeof ProjectsProjectKeyRoute@@ -179,6 +204,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SettingsRouteImportparentRoute: typeof rootRouteImport}+ '/plugins': {+ id: '/plugins'+ path: '/plugins'+ fullPath: '/plugins'+ preLoaderRoute: typeof PluginsRouteImport+ parentRoute: typeof rootRouteImport+ }'/pair': {id: '/pair'path: '/pair'@@ -200,6 +232,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof ChatIndexRouteImportparentRoute: typeof ChatRoute}+ '/settings/$section': {+ id: '/settings/$section'+ path: '/$section'+ fullPath: '/settings/$section'+ preLoaderRoute: typeof SettingsSectionRouteImport+ parentRoute: typeof SettingsRoute+ }'/settings/$': {id: '/settings/$'path: '/$'@@ -265,10 +304,12 @@ const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren)interface SettingsRouteChildren {SettingsSplatRoute: typeof SettingsSplatRoute+ SettingsSectionRoute: typeof SettingsSectionRoute}const SettingsRouteChildren: SettingsRouteChildren = {SettingsSplatRoute: SettingsSplatRoute,+ SettingsSectionRoute: SettingsSectionRoute,}const SettingsRouteWithChildren = SettingsRoute._addFileChildren(@@ -278,6 +319,7 @@ const SettingsRouteWithChildren = SettingsRoute._addFileChildren(const rootRouteChildren: RootRouteChildren = {ChatRoute: ChatRouteWithChildren,PairRoute: PairRoute,+ PluginsRoute: PluginsRoute,SettingsRoute: SettingsRouteWithChildren,UsageRoute: UsageRoute,ProjectsProjectKeyRoute: ProjectsProjectKeyRoute,diff --git a/apps/web/src/routes/RootRouteErrorView.tsx b/apps/web/src/routes/RootRouteErrorView.tsxindex 306233bdc..72577b388 100644--- a/apps/web/src/routes/RootRouteErrorView.tsx+++ b/apps/web/src/routes/RootRouteErrorView.tsx@@ -1,7 +1,7 @@import type { ErrorComponentProps } from "@tanstack/react-router";import { APP_DISPLAY_NAME } from "../branding";-import { AkeruMark } from "../components/AkeruMark";+import { AkeruWordmark } from "../components/AkeruWordmark";import { Button } from "../components/ui/button";function reloadApp() {@@ -21,7 +21,7 @@ export function RootRouteErrorView({ error, reset, reload = reloadApp }: RootRouclassName="flex h-full min-h-0 flex-col bg-background text-foreground"><header className="flex h-[var(--workspace-topbar-height)] shrink-0 items-center gap-1.5 pl-[var(--workspace-controls-left)] pr-[var(--workspace-controls-right)]">- <AkeruMark aria-hidden className="text-foreground" />+ <AkeruWordmark aria-hidden className="text-2xl text-foreground" /><span className="truncate text-sm font-medium tracking-tight text-muted-foreground">{APP_DISPLAY_NAME}</span>diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsxindex 34610be7c..66700de6c 100644--- a/apps/web/src/routes/__root.tsx+++ b/apps/web/src/routes/__root.tsx@@ -14,9 +14,7 @@ import { ReplyPlaybackProvider } from "../components/chat/ReplyPlaybackProvider"import { VoiceCallProvider } from "../components/voice/VoiceCall";import { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";-import { SettingsDialog } from "../components/settings/SettingsDialog";-import { PluginsDialog } from "../components/plugins/PluginsDialog";-import { UsageDialog } from "../components/usage/UsageDialog";+import { SurfaceNavigationCoordinator } from "../components/SurfaceNavigationCoordinator";import { ProductFeedbackDialog } from "../components/productFeedback/ProductFeedbackDialog";import { PolicyNotice } from "../components/privacy/PolicyNotice";import { RootRouteErrorView } from "./RootRouteErrorView";@@ -138,14 +136,12 @@ function RootRouteView() {<ConfirmDialogHost /><SlowRpcRequestToastCoordinator /><HostedStaticEnvironmentBootstrap />+ <SurfaceNavigationCoordinator />{primaryEnvironmentAuthenticated ? <EventRouter /> : null}{primaryEnvironmentAuthenticated ? <PlanAgentSelectionHeal /> : null}<ReplyPlaybackProvider><VoiceCallProvider>{appShell}</VoiceCallProvider>- <SettingsDialog /></ReplyPlaybackProvider>- <PluginsDialog />- <UsageDialog /><ProductFeedbackDialog /><PolicyNotice />{/* Above the router: a theme draft is judged by walking the app, so thediff --git a/apps/web/src/routes/plugins.tsx b/apps/web/src/routes/plugins.tsxnew file mode 100644index 000000000..2500d5937--- /dev/null+++ b/apps/web/src/routes/plugins.tsx@@ -0,0 +1,15 @@+import { createFileRoute, redirect } from "@tanstack/react-router";++import { PluginsPage } from "../components/plugins/PluginsDialog";++export const Route = createFileRoute("/plugins")({+ beforeLoad: async ({ context }) => {+ if (+ context.authGateState.status !== "authenticated" &&+ context.authGateState.status !== "hosted-static"+ ) {+ throw redirect({ to: "/pair", replace: true });+ }+ },+ component: PluginsPage,+});diff --git a/apps/web/src/routes/settings.$section.tsx b/apps/web/src/routes/settings.$section.tsxnew file mode 100644index 000000000..f36fa7614--- /dev/null+++ b/apps/web/src/routes/settings.$section.tsx@@ -0,0 +1,27 @@+import { createFileRoute, redirect } from "@tanstack/react-router";++import { SettingsPanelForSection } from "../components/settings/SettingsDialog";+import { SETTINGS_SECTIONS, type SettingsSection } from "../settingsDialogStore";++function isSettingsSection(value: string): value is SettingsSection {+ return (SETTINGS_SECTIONS as readonly string[]).includes(value);+}++export const Route = createFileRoute("/settings/$section")({+ beforeLoad: ({ params }) => {+ if (!isSettingsSection(params.section)) {+ throw redirect({+ to: "/settings/$section",+ params: { section: "general" },+ replace: true,+ });+ }+ },+ component: SettingsSectionPage,+});++function SettingsSectionPage() {+ const { section } = Route.useParams();+ if (!isSettingsSection(section)) return null;+ return <SettingsPanelForSection section={section} />;+}diff --git a/apps/web/src/routes/settings.tsx b/apps/web/src/routes/settings.tsxindex d122ebf59..76fda3ea9 100644--- a/apps/web/src/routes/settings.tsx+++ b/apps/web/src/routes/settings.tsx@@ -1,13 +1,7 @@import { createFileRoute, redirect } from "@tanstack/react-router";-import { isLegacyPluginsPath, openPlugins } from "../pluginsDialogStore";-import { openSettings, settingsSectionFromPathname } from "../settingsDialogStore";+import { SettingsRoutePage } from "../components/settings/SettingsRoutePage";-/**- * Settings is a modal now. The route only survives so old deep links and- * history entries still land somewhere useful: it opens the dialog and hands- * the user back to the workspace.- */export const Route = createFileRoute("/settings")({beforeLoad: async ({ context, location }) => {if (@@ -16,12 +10,13 @@ export const Route = createFileRoute("/settings")({) {throw redirect({ to: "/pair", replace: true });}-- if (isLegacyPluginsPath(location.pathname)) {- openPlugins();- } else {- openSettings(settingsSectionFromPathname(location.pathname));+ if (location.pathname === "/settings") {+ throw redirect({+ to: "/settings/$section",+ params: { section: "general" },+ replace: true,+ });}- throw redirect({ to: "/", replace: true });},+ component: SettingsRoutePage,});diff --git a/apps/web/src/routes/usage.tsx b/apps/web/src/routes/usage.tsxindex c11f32d2d..9f765b5e6 100644--- a/apps/web/src/routes/usage.tsx+++ b/apps/web/src/routes/usage.tsx@@ -1,12 +1,7 @@import { createFileRoute, redirect } from "@tanstack/react-router";-import { openUsage } from "../usageDialogStore";+import { UsagePage } from "../components/usage/UsagePage";-/**- * Usage is a modal now. The route only survives so old deep links and- * history entries still land somewhere useful: it opens the dialog and hands- * the user back to the workspace.- */export const Route = createFileRoute("/usage")({beforeLoad: async ({ context }) => {if (@@ -15,8 +10,6 @@ export const Route = createFileRoute("/usage")({) {throw redirect({ to: "/pair", replace: true });}-- openUsage();- throw redirect({ to: "/", replace: true });},+ component: UsagePage,});diff --git a/apps/web/src/settingsDialogStore.ts b/apps/web/src/settingsDialogStore.tsindex 332d4b3d4..894c45fbe 100644--- a/apps/web/src/settingsDialogStore.ts+++ b/apps/web/src/settingsDialogStore.ts@@ -42,6 +42,8 @@ interface SettingsDialogState {environmentId?: EnvironmentId | null,) => void;readonly clearTarget: () => void;+ readonly acknowledgeNavigation: () => void;+ readonly clearEnvironment: () => void;readonly closeSettings: () => void;}@@ -56,6 +58,8 @@ export const useSettingsDialogStore = create<SettingsDialogState>((set) => ({environmentId: environmentId === undefined ? state.environmentId : environmentId,})),clearTarget: () => set({ targetId: null }),+ acknowledgeNavigation: () => set({ section: null, targetId: null }),+ clearEnvironment: () => set({ environmentId: null }),closeSettings: () => set({ section: null, targetId: null, environmentId: null }),}));@@ -82,6 +86,14 @@ export function closeSettings(): void {useSettingsDialogStore.getState().closeSettings();}+export function acknowledgeSettingsNavigation(): void {+ useSettingsDialogStore.getState().acknowledgeNavigation();+}++export function clearSettingsEnvironment(): void {+ useSettingsDialogStore.getState().clearEnvironment();+}+/** Map a legacy `/settings/...` pathname onto a dialog section. */export function settingsSectionFromPathname(pathname: string): SettingsSection {const slug = pathname.replace(/^\/settings\/?/, "").split("/")[0] ?? "";diff --git a/docs/user/usage.md b/docs/user/usage.mdindex ef85d2536..fd28e737e 100644--- a/docs/user/usage.md+++ b/docs/user/usage.md@@ -1,31 +1,35 @@# Review usageOpen **Usage** from the sidebar to review subscription limits and recent model activity across your-connected environments.+connected environments. Usage opens as a workspace page, so it has its own URL and works with normal+back and forward navigation.## Plan limits-The plan section shows available limits for ChatGPT, Claude, Cursor, Grok, and Kimi For Coding.+The **Limits** tab opens by default and shows available limits for ChatGPT, Claude, Cursor, Grok,+Kimi For Coding, and OpenCode Go.Disconnected accounts and limits that a provider does not report stay hidden.Each meter shows the percentage used or left and the next reset time. Provider plans expose differentwindows, such as five-hour, weekly, or plan-wide limits.-## Activity+## Cost and tokens-The **Activity** section summarizes the last 30 days of local Codex and Claude transcript usage. It-shows processed tokens, cached input, output, estimated cache savings, and totals by model when that-data exists.+Use the **Cost** and **Tokens** tabs to review activity Akeru recorded through providers connected in+**Settings > Providers**. Choose the past 24 hours, 7 days, 30 days, or 90 days. The page shows+provider totals, an hourly or daily chart, processed token totals, estimated cost, and breakdowns by+model or time.-Akeru reads transcripts from each environment. It deduplicates shared transcript directories so the-same usage is not counted twice. A notice identifies environments that are still loading, stale, or-unavailable.+Akeru never imports machine-wide Claude, Codex, or other CLI history. Each environment reports only+its own Akeru provider activity, and disconnected providers stay hidden. A notice identifies+environments that are still loading, stale, or unavailable.Web and desktop charts stay still when idle. Hover over a chart to inspect a value.## Refresh usage-Akeru refreshes usage every five minutes by default. Select **Refresh usage** to reload it now.+Akeru refreshes usage every five minutes by default. Select the refresh button to reload it now. The+page remembers the last tab and time range you selected.Change **Usage refresh** in **Settings > General** to a value from 1 to 60 minutes. Mobile also showsUsage under General settings and supports pull-to-refresh.diff --git a/packages/contracts/src/usage.ts b/packages/contracts/src/usage.tsindex 9d132de0b..549220551 100644--- a/packages/contracts/src/usage.ts+++ b/packages/contracts/src/usage.ts@@ -1,14 +1,12 @@/*** Usage reporting contract.*- * Each environment scans the provider CLIs' own on-disk session transcripts- * (`~/.claude/projects/**\/*.jsonl`, `~/.codex/sessions/**\/*.jsonl`) rather than- * relying on Akeru Bot's own orchestration projections, so usage stays complete- * even for turns that were never driven through Akeru Bot. This mirrors the- * approach `ccusage` takes.+ * Each environment reports usage recorded by Akeru Bot's provider runtime.+ * Machine-wide CLI transcripts are deliberately excluded: a local Claude or+ * Codex login is not an Akeru provider connection.** Environments return pre-aggregated `(day, hourStart?, provider, model)`- * buckets. Raw transcript records never cross the wire.+ * buckets. Raw ledger records never cross the wire.** @module usage*/@@ -22,9 +20,16 @@ import { SubscriptionProviderId } from "./subscriptionAuth.ts";* client renders partial coverage when an environment reports an older version* rather than failing the whole page.*/-export const USAGE_CONTRACT_VERSION = 4 as const;--export const UsageProviderKind = Schema.Literals(["claude", "codex"]);+export const USAGE_CONTRACT_VERSION = 5 as const;++export const UsageProviderKind = Schema.Literals([+ "claude",+ "codex",+ "cursor",+ "grok",+ "kimi",+ "opencode",+]);export type UsageProviderKind = typeof UsageProviderKind.Type;/**@@ -46,7 +51,7 @@ export type UsageResolution = typeof UsageResolution.Type;/*** Why a bucket's cost is what it is.*- * - `providerReported` - the transcript carried an explicit cost figure.+ * - `providerReported` - the provider carried an explicit cost figure.* - `modelPriced` - we matched the model against the LiteLLM rate table.* - `unpriced` - tokens are known, rates are not. Counted in totals, excluded* from cost.@@ -97,13 +102,13 @@ export const UsageBucket = Schema.Struct({/** Distinct assistant responses, after de-duplication. */records: NonNegativeInt,unpricedRecords: NonNegativeInt,- /** Distinct transcript sessions that contributed to this cell. */+ /** Distinct Akeru chats that contributed to this cell. */sessions: NonNegativeInt,});export type UsageBucket = typeof UsageBucket.Type;/**- * Identifies the physical transcript directory a source read from.+ * Identifies the environment-local provider usage ledger a source read from.** Two environments on the same machine (worktree servers, for example) resolve* the same provider home and would otherwise double count. The client drops@@ -114,13 +119,10 @@ export const UsageSourceFingerprint = Schema.Struct({provider: UsageProviderKind,resolvedHomePath: TrimmedNonEmptyString,/**- * Filesystem identity of the transcript directory, as `device:inode`.+ * Filesystem identity of the usage store, as `device:inode`.*- * Hostname and path alone are not enough: every Mac in a fleet resolves- * `/Users/<user>/.claude`, so two machines that happen to share a hostname- * would look like one source and have their usage silently dropped. The- * device/inode pair is stable for two servers reading the same directory and- * effectively never collides across machines. Empty when it cannot be read.+ * Hostname and path alone are not enough when environments use matching home+ * paths. Empty when filesystem identity cannot be read.*/volumeId: Schema.String,});@@ -137,7 +139,7 @@ export const UsageSource = Schema.Struct({/** Records that parsed but carried no recognisable usage payload. */malformedRecords: NonNegativeInt,/**- * Distinct transcript sessions seen under this directory. Buckets also carry+ * Distinct Akeru chats seen in this store. Buckets also carry* per-bucket session counts, but a session spans days and models, so summing* those overcounts; this is the figure clients should total.*/@@ -216,8 +218,10 @@ export const UsageSummary = Schema.Struct({pricing: UsagePricing,/** Wall-clock cost of the scan, surfaced in diagnostics. */scanDurationMs: NonNegativeInt,- /** Live Claude and Codex plan windows. Absent on older servers. */+ /** Live plan windows for connected provider subscriptions. */planLimits: Schema.optional(Schema.Array(UsageProviderPlanLimits)),+ /** Settings -> Providers connections that may contribute usage. Absent on older servers. */+ connectedProviders: Schema.optional(Schema.Array(SubscriptionProviderId)),});export type UsageSummary = typeof UsageSummary.Type;diff --git a/packages/shared/src/usageMerge.test.ts b/packages/shared/src/usageMerge.test.tsindex 3bee4a9bd..cc48cd8ed 100644--- a/packages/shared/src/usageMerge.test.ts+++ b/packages/shared/src/usageMerge.test.ts@@ -43,6 +43,14 @@ function summary(}[],contractVersion: number = USAGE_CONTRACT_VERSION,): UsageSummary {+ const connectionByProvider = {+ claude: "anthropic",+ codex: "openai-codex",+ cursor: "cursor",+ grok: "xai",+ kimi: "kimi-for-coding",+ opencode: "opencode-go",+ } as const;return {contractVersion,readAt: "2026-08-07T00:00:00.000Z",@@ -66,6 +74,9 @@ function summary(})),pricing: { status: "fresh", source: "litellm", fetchedAt: null, knownModels: 10 },scanDurationMs: 1,+ connectedProviders: [+ ...new Set(sources.map((source) => connectionByProvider[source.provider])),+ ],};}diff --git a/packages/shared/src/usageMerge.ts b/packages/shared/src/usageMerge.tsindex 1b79f5a7c..f8491ac19 100644--- a/packages/shared/src/usageMerge.ts+++ b/packages/shared/src/usageMerge.ts@@ -83,10 +83,11 @@ export interface MergedUsage {readonly contributingEnvironments: readonly EnvironmentId[];readonly staleEnvironments: readonly EnvironmentId[];readonly planLimits: readonly UsageProviderPlanLimits[];+ readonly connectedProviders: readonly SubscriptionProviderId[];}/**- * Two sources are the same physical transcript directory only when host,+ * Two sources are the same physical provider-usage store only when host,* provider, path and filesystem identity all agree.** `volumeId` is what stops two machines that happen to share a hostname and a@@ -103,10 +104,10 @@ function fingerprintKey(fingerprint: UsageSourceFingerprint): string {}/**- * Decides which environment owns each physical transcript directory.+ * Decides which environment owns each physical provider-usage store.*- * Several environments on one machine (worktree servers, for instance) resolve- * the same provider home and would otherwise double count every token. The+ * Several clients can report one environment and would otherwise double count+ * every token. The* first environment in a stable order claims a fingerprint; the rest have that* provider's buckets dropped. Environments are sorted by id so the winner does* not change between renders.@@ -144,6 +145,11 @@ function ownedContribution(readonly sessionsByProvider: ReadonlyMap<UsageProviderKind, number>;} {const ownedProviders = new Set<UsageProviderKind>();+ const connectedUsageProviders = new Set<UsageProviderKind>();+ for (const provider of environment.summary.connectedProviders ?? []) {+ const usageProvider = USAGE_PROVIDER_BY_CONNECTION[provider];+ if (usageProvider !== undefined) connectedUsageProviders.add(usageProvider);+ }const sessionsByProvider = new Map<UsageProviderKind, number>();for (const source of environment.summary.sources) {if (source.status === "missing") continue;@@ -160,11 +166,23 @@ function ownedContribution(}}return {- buckets: environment.summary.buckets.filter((bucket) => ownedProviders.has(bucket.provider)),+ buckets: environment.summary.buckets.filter(+ (bucket) =>+ ownedProviders.has(bucket.provider) && connectedUsageProviders.has(bucket.provider),+ ),sessionsByProvider,};}+const USAGE_PROVIDER_BY_CONNECTION = {+ anthropic: "claude",+ "openai-codex": "codex",+ cursor: "cursor",+ xai: "grok",+ "kimi-for-coding": "kimi",+ "opencode-go": "opencode",+} as const satisfies Record<SubscriptionProviderId, UsageProviderKind>;+function bucketTokens(bucket: UsageBucket): number {// reasoningTokens is a subset of outputTokens and must not be added again.return (@@ -199,6 +217,7 @@ const EMPTY_MERGED: MergedUsage = {contributingEnvironments: [],staleEnvironments: [],planLimits: [],+ connectedProviders: [],};/**@@ -418,6 +437,9 @@ export function mergeUsage(contributingEnvironments,staleEnvironments,planLimits: mergePlanLimits(current),+ connectedProviders: [+ ...new Set(current.flatMap((environment) => environment.summary.connectedProviders ?? [])),+ ],};}