Compare commits

..
Author SHA1 Message Date
Theo BrowneandClaude Fable 5 ee46b611d2 feat(usage): local usage analytics — durable ledger, usage.getSummary RPC, settings page
Records token/cost usage facts from live provider events into a replayable
projection, exposes a dashboard-shaped RPC, and adds Settings > Usage.

Server:
- New thread.usage-recorded orchestration event (internal thread.usage.record
  command) carrying immutable per-model interval facts with provider-native
  session identity; emitted from runtime ingestion for Codex cumulative
  token-usage updates and Claude turn.completed modelUsage settlements
  (exact cost in integer micro-USD; stale completions recorded, flagged).
- Registered projection.usage projector -> projection_usage_facts (fact_id
  upsert, migration 033). Deliberately does NOT prune on thread.reverted
  (billing history is immutable); thread deletion redacts linkage.
- Cumulative->delta baselines keyed by native session + model, reseeded from
  fact sums after restart to prevent double counting.
- ClaudeAdapter: providerRefs now carry the SDK session id. CodexAdapter:
  snapshots now include cumulative total* fields; native thread id attached
  to usage events (separates concurrent subagent sessions on one thread).
- usage.getSummary RPC (orchestration:read scope): totals, by-model, daily,
  hour-of-week, by-project buckets grouped in the caller's IANA timezone.
- Pricing: versioned effective-dated list-price catalog in shared runtime
  code; estimates computed at query time only, never stored, always flagged.
  Unpriced models surface as token-only, never $0.

Web:
- Settings > Usage per the approved mock: harness-level twin donuts
  (tokens + cost, model shades within family, striped estimate slices),
  KPI tiles, tokens-per-day stacks, hour x weekday heatmap, models table,
  project bars.

Tests: pure accounting (delta/reset/normalization), projector (idempotent
replay, revert retention, deletion redaction, session-model sums), adapter
fixtures updated for the new snapshot fields.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-24 04:49:36 -07:00
Theo BrowneandClaude Fable 5 6f34ad3e87 fix(claude): handle all SDK stream messages; stop spurious work-log warning rows (#4244)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-21 19:58:39 -07:00
Theo BrowneandClaude Fable 5 62cf461759 fix: better defaults — Claude 1M context, Codex gpt-5.6, worktrees from origin main (#4240)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-21 17:13:44 -07:00
Theo BrowneandClaude Fable 5 23c18fda7a fix(web): keep composer editable while disconnected (#4241)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-21 14:29:23 -07:00
Theo BrowneandClaude Fable 5 c0bb237345 fix(web): always show environment chip for remote projects (#4217)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-20 18:27:57 -07:00
53 changed files with 6176 additions and 205 deletions

No files matched your search

@@ -58,6 +58,8 @@ import { type VcsRef } from "@t3tools/client-runtime/state/vcs";
type WorkspaceMode = "local" | "worktree";
const EMPTY_BRANCH_REFS: ReadonlyArray<VcsRef> = [];
function pendingTaskDraftKey(messageId: string): string {
return `pending-task:${messageId}`;
}
@@ -348,7 +350,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
const startFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin ?? false;
// Keep the user's explicit choice separate from the resolved display value:
// only the explicit flag is ever written back to the draft, so the resolved
// value keeps tracking the server setting when the config loads late.
const draftStartFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin;
const startFromOrigin =
draftStartFromOrigin ??
selectedEnvironmentServerConfig?.settings.newWorktreesStartFromOrigin ??
true;
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
@@ -368,6 +377,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const selectedModel =
selectedProjectDraft.modelSelection ??
selectedProject?.defaultModelSelection ??
modelOptions.find((option) => option.isDefault)?.selection ??
modelOptions[0]?.selection ??
null;
const selectedModelKey = selectedModel
@@ -475,13 +485,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
);
const branchState = useBranches(branchTarget);
const branchesLoading = branchState.isPending;
const allBranchRefs = branchState.data?.refs ?? EMPTY_BRANCH_REFS;
const availableBranches = useMemo(
() =>
pipe(
branchState.data?.refs ?? [],
allBranchRefs,
Arr.filter((branch) => !branch.isRemote),
),
[branchState.data?.refs],
[allBranchRefs],
);
const filteredBranches = useMemo(() => {
@@ -543,11 +554,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
mode,
branch: selectedBranchName,
worktreePath: selectedWorktreePath,
startFromOrigin,
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
},
});
},
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath, startFromOrigin],
[draftStartFromOrigin, selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
);
const selectBranch = useCallback(
@@ -560,11 +571,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
mode: workspaceMode,
branch: branch.name,
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
startFromOrigin,
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
},
});
},
[selectedProject, selectedProjectDraftKey, startFromOrigin, workspaceMode],
[draftStartFromOrigin, selectedProject, selectedProjectDraftKey, workspaceMode],
);
const setStartFromOrigin = useCallback(
@@ -597,14 +608,16 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
return;
}
// The default may only exist as origin/<default> (isRemote), which
// availableBranches filters out — search the unfiltered refs for it.
const preferredBranch =
allBranchRefs.find((branch) => branch.isDefault) ??
availableBranches.find((branch) => branch.current) ??
availableBranches.find((branch) => branch.isDefault) ??
null;
if (preferredBranch) {
selectBranch(preferredBranch);
}
}, [availableBranches, selectBranch, selectedBranchName, workspaceMode]);
}, [allBranchRefs, availableBranches, selectBranch, selectedBranchName, workspaceMode]);
const setRuntimeMode = useCallback(
(value: RuntimeMode) => {
@@ -696,7 +709,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
workspaceMode: mode,
branch: workspaceSelection?.branch ?? null,
worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null),
...(workspaceSelection?.startFromOrigin ? { startFromOrigin: true } : {}),
// The draft only carries the flag when the user touched it; fall
// back to the resolved default (server settings) so queued tasks
// drain with the same origin mode the composer displayed.
...((workspaceSelection?.startFromOrigin ?? startFromOrigin)
? { startFromOrigin: true }
: {}),
},
createdAt: metadata.createdAt,
};
@@ -707,6 +725,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
selectedModel,
selectedProject,
selectedProjectDraftKey,
startFromOrigin,
],
);
+3
View File
@@ -15,6 +15,7 @@ export type ModelOption = {
readonly providerKey: string;
readonly providerLabel: string;
readonly providerDriver: string;
readonly isDefault: boolean;
readonly capabilities: ModelCapabilities | null;
readonly selection: ModelSelection;
};
@@ -78,6 +79,7 @@ export function buildModelOptions(
providerKey: provider.instanceId,
providerLabel,
providerDriver: provider.driver,
isDefault: model.isDefault === true,
capabilities: model.capabilities,
selection: normalizeSelectionOptions(
{
@@ -107,6 +109,7 @@ export function buildModelOptions(
providerKey: fallbackModelSelection.instanceId,
providerLabel,
providerDriver: fallbackModelSelection.instanceId,
isDefault: false,
capabilities: null,
selection: fallbackModelSelection,
});
@@ -18,6 +18,7 @@ import { OrchestrationEventStore } from "../../persistence/Services/Orchestratio
import { ProjectionPendingApprovalRepository } from "../../persistence/Services/ProjectionPendingApprovals.ts";
import { ProjectionProjectRepository } from "../../persistence/Services/ProjectionProjects.ts";
import { ProjectionStateRepository } from "../../persistence/Services/ProjectionState.ts";
import { ProjectionUsageRepository } from "../../persistence/Services/ProjectionUsage.ts";
import { ProjectionThreadActivityRepository } from "../../persistence/Services/ProjectionThreadActivities.ts";
import { type ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts";
import {
@@ -37,6 +38,7 @@ import { ProjectionThreadRepository } from "../../persistence/Services/Projectio
import { ProjectionPendingApprovalRepositoryLive } from "../../persistence/Layers/ProjectionPendingApprovals.ts";
import { ProjectionProjectRepositoryLive } from "../../persistence/Layers/ProjectionProjects.ts";
import { ProjectionStateRepositoryLive } from "../../persistence/Layers/ProjectionState.ts";
import { ProjectionUsageRepositoryLive } from "../../persistence/Layers/ProjectionUsage.ts";
import { ProjectionThreadActivityRepositoryLive } from "../../persistence/Layers/ProjectionThreadActivities.ts";
import { ProjectionThreadMessageRepositoryLive } from "../../persistence/Layers/ProjectionThreadMessages.ts";
import { ProjectionThreadProposedPlanRepositoryLive } from "../../persistence/Layers/ProjectionThreadProposedPlans.ts";
@@ -65,6 +67,7 @@ export const ORCHESTRATION_PROJECTOR_NAMES = {
threadTurns: "projection.thread-turns",
checkpoints: "projection.checkpoints",
pendingApprovals: "projection.pending-approvals",
usage: "projection.usage",
} as const;
type ProjectorName =
@@ -480,6 +483,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository;
const projectionTurnRepository = yield* ProjectionTurnRepository;
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
const projectionUsageRepository = yield* ProjectionUsageRepository;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -1007,6 +1011,51 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
});
});
const applyUsageProjection: ProjectorDefinition["apply"] = Effect.fn("applyUsageProjection")(
function* (event, _attachmentSideEffects) {
switch (event.type) {
case "thread.usage-recorded":
yield* Effect.forEach(
event.payload.facts,
(fact) =>
projectionUsageRepository.upsertFact({
factId: fact.factId,
threadId: event.payload.threadId,
turnId: event.payload.turnId,
projectId: event.payload.projectId,
provider: fact.provider,
providerInstanceId: fact.providerInstanceId ?? null,
providerSessionId: fact.providerSessionId,
model: fact.model,
modelRaw: fact.modelRaw,
reasoningEffort: fact.reasoningEffort ?? null,
kind: fact.kind,
inputTokens: fact.tokens.inputTokens,
cachedInputTokens: fact.tokens.cachedInputTokens,
cacheCreationTokens: fact.tokens.cacheCreationTokens,
outputTokens: fact.tokens.outputTokens,
reasoningOutputTokens: fact.tokens.reasoningOutputTokens,
costMicroUsd: fact.costMicroUsd ?? null,
stale: fact.stale ?? false,
observedAt: fact.observedAt,
}),
{ concurrency: 1 },
).pipe(Effect.asVoid);
return;
case "thread.deleted":
yield* projectionUsageRepository.redactThread({
threadId: event.payload.threadId,
});
return;
// No thread.reverted case: usage facts are immutable billing history and survive reverts.
default:
return;
}
},
);
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = Effect.fn(
"applyThreadTurnsProjection",
)(function* (event, _attachmentSideEffects) {
@@ -1480,6 +1529,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
apply: applyThreadSessionsProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.usage,
apply: applyUsageProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.threadTurns,
apply: applyThreadTurnsProjection,
@@ -1596,6 +1649,7 @@ export const OrchestrationProjectionPipelineLive = Layer.effect(
Layer.provideMerge(ProjectionThreadProposedPlanRepositoryLive),
Layer.provideMerge(ProjectionThreadActivityRepositoryLive),
Layer.provideMerge(ProjectionThreadSessionRepositoryLive),
Layer.provideMerge(ProjectionUsageRepositoryLive),
Layer.provideMerge(ProjectionTurnRepositoryLive),
Layer.provideMerge(ProjectionPendingApprovalRepositoryLive),
Layer.provideMerge(ProjectionStateRepositoryLive),
@@ -0,0 +1,557 @@
import {
CommandId,
EventId,
IsoDateTime,
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
ThreadId,
TurnId,
type UsageFact,
UsageFactId,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";
import { ProjectionUsageRepository } from "../../persistence/Services/ProjectionUsage.ts";
import { ServerConfig } from "../../config.ts";
import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
const BaseTestLayer = OrchestrationProjectionPipelineLive.pipe(
Layer.provideMerge(OrchestrationEventStoreLive),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), { prefix: "t3-projection-pipeline-usage-test-" }),
),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(NodeServices.layer),
);
const threadId = ThreadId.make("thread-usage");
const turnId = TurnId.make("turn-usage");
const projectId = ProjectId.make("project-usage");
const observedAt = IsoDateTime.make("2026-04-01T12:00:00.000Z");
function makeFact(factId: string, overrides: Partial<UsageFact> = {}): UsageFact {
return {
factId: UsageFactId.make(factId),
kind: "final",
provider: ProviderDriverKind.make("claudeAgent"),
providerInstanceId: ProviderInstanceId.make("claude-primary"),
providerSessionId: "session-claude-1",
model: "claude-fable-5",
modelRaw: "claude-fable-5[1m]",
reasoningEffort: "high",
tokens: {
inputTokens: 100,
cachedInputTokens: 1_000,
cacheCreationTokens: 200,
outputTokens: 50,
reasoningOutputTokens: 0,
},
costMicroUsd: 1_250_000,
observedAt,
...overrides,
};
}
it.layer(BaseTestLayer)("usage projection", (it) => {
it.effect("projects every usage fact with exact persisted values", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
yield* appendAndProject({
type: "thread.usage-recorded",
eventId: EventId.make("evt-usage-single"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: observedAt,
commandId: CommandId.make("cmd-usage-single"),
causationEventId: null,
correlationId: CommandId.make("cmd-usage-single"),
metadata: {},
payload: {
threadId,
turnId,
projectId,
facts: [
makeFact("fact-final"),
makeFact("fact-interval", {
kind: "interval",
provider: ProviderDriverKind.make("codex"),
providerInstanceId: undefined,
providerSessionId: "session-codex-1",
model: "gpt-5.6",
modelRaw: "gpt-5.6",
reasoningEffort: undefined,
tokens: {
inputTokens: 300,
cachedInputTokens: 75,
cacheCreationTokens: 0,
outputTokens: 125,
reasoningOutputTokens: 40,
},
costMicroUsd: undefined,
observedAt: IsoDateTime.make("2026-04-01T12:00:01.000Z"),
}),
],
recordedAt: IsoDateTime.make("2026-04-01T12:00:02.000Z"),
},
});
const rows = yield* sql<{
readonly factId: string;
readonly threadId: string;
readonly turnId: string | null;
readonly projectId: string | null;
readonly provider: string;
readonly providerInstanceId: string | null;
readonly providerSessionId: string;
readonly model: string;
readonly modelRaw: string;
readonly reasoningEffort: string | null;
readonly kind: string;
readonly inputTokens: number;
readonly cachedInputTokens: number;
readonly cacheCreationTokens: number;
readonly outputTokens: number;
readonly reasoningOutputTokens: number;
readonly costMicroUsd: number | null;
readonly stale: number;
readonly observedAt: string;
}>`
SELECT
fact_id AS "factId",
thread_id AS "threadId",
turn_id AS "turnId",
project_id AS "projectId",
provider,
provider_instance_id AS "providerInstanceId",
provider_session_id AS "providerSessionId",
model,
model_raw AS "modelRaw",
reasoning_effort AS "reasoningEffort",
kind,
input_tokens AS "inputTokens",
cached_input_tokens AS "cachedInputTokens",
cache_creation_tokens AS "cacheCreationTokens",
output_tokens AS "outputTokens",
reasoning_output_tokens AS "reasoningOutputTokens",
cost_micro_usd AS "costMicroUsd",
stale,
observed_at AS "observedAt"
FROM projection_usage_facts
ORDER BY fact_id ASC
`;
assert.deepEqual(rows, [
{
factId: "fact-final",
threadId: "thread-usage",
turnId: "turn-usage",
projectId: "project-usage",
provider: "claudeAgent",
providerInstanceId: "claude-primary",
providerSessionId: "session-claude-1",
model: "claude-fable-5",
modelRaw: "claude-fable-5[1m]",
reasoningEffort: "high",
kind: "final",
inputTokens: 100,
cachedInputTokens: 1_000,
cacheCreationTokens: 200,
outputTokens: 50,
reasoningOutputTokens: 0,
costMicroUsd: 1_250_000,
stale: 0,
observedAt: "2026-04-01T12:00:00.000Z",
},
{
factId: "fact-interval",
threadId: "thread-usage",
turnId: "turn-usage",
projectId: "project-usage",
provider: "codex",
providerInstanceId: null,
providerSessionId: "session-codex-1",
model: "gpt-5.6",
modelRaw: "gpt-5.6",
reasoningEffort: null,
kind: "interval",
inputTokens: 300,
cachedInputTokens: 75,
cacheCreationTokens: 0,
outputTokens: 125,
reasoningOutputTokens: 40,
costMicroUsd: null,
stale: 0,
observedAt: "2026-04-01T12:00:01.000Z",
},
]);
}),
);
it.effect("upserts repeated facts by fact id", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
const facts = [makeFact("fact-replay-1"), makeFact("fact-replay-2", { kind: "interval" })];
for (const suffix of ["one", "two"] as const) {
yield* appendAndProject({
type: "thread.usage-recorded",
eventId: EventId.make(`evt-usage-replay-${suffix}`),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: observedAt,
commandId: CommandId.make(`cmd-usage-replay-${suffix}`),
causationEventId: null,
correlationId: CommandId.make(`cmd-usage-replay-${suffix}`),
metadata: {},
payload: {
threadId,
turnId,
projectId,
facts,
recordedAt: observedAt,
},
});
}
const rows = yield* sql<{ readonly factId: string }>`
SELECT fact_id AS "factId"
FROM projection_usage_facts
WHERE fact_id IN ('fact-replay-1', 'fact-replay-2')
ORDER BY fact_id ASC
`;
assert.deepEqual(rows, [{ factId: "fact-replay-1" }, { factId: "fact-replay-2" }]);
}),
);
it.effect("retains usage facts after a thread revert", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
yield* appendAndProject({
type: "thread.usage-recorded",
eventId: EventId.make("evt-usage-before-revert"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: observedAt,
commandId: CommandId.make("cmd-usage-before-revert"),
causationEventId: null,
correlationId: CommandId.make("cmd-usage-before-revert"),
metadata: {},
payload: {
threadId,
turnId,
projectId,
facts: [makeFact("fact-retained")],
recordedAt: observedAt,
},
});
const before = yield* sql<{
readonly factId: string;
readonly threadId: string;
readonly projectId: string | null;
readonly outputTokens: number;
readonly costMicroUsd: number | null;
}>`
SELECT
fact_id AS "factId",
thread_id AS "threadId",
project_id AS "projectId",
output_tokens AS "outputTokens",
cost_micro_usd AS "costMicroUsd"
FROM projection_usage_facts
WHERE fact_id = 'fact-retained'
`;
yield* appendAndProject({
type: "thread.reverted",
eventId: EventId.make("evt-usage-reverted"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: IsoDateTime.make("2026-04-01T12:01:00.000Z"),
commandId: CommandId.make("cmd-usage-reverted"),
causationEventId: null,
correlationId: CommandId.make("cmd-usage-reverted"),
metadata: {},
payload: { threadId, turnCount: 0 },
});
const after = yield* sql<{
readonly factId: string;
readonly threadId: string;
readonly projectId: string | null;
readonly outputTokens: number;
readonly costMicroUsd: number | null;
}>`
SELECT
fact_id AS "factId",
thread_id AS "threadId",
project_id AS "projectId",
output_tokens AS "outputTokens",
cost_micro_usd AS "costMicroUsd"
FROM projection_usage_facts
WHERE fact_id = 'fact-retained'
`;
assert.deepEqual(after, before);
assert.deepEqual(after, [
{
factId: "fact-retained",
threadId: "thread-usage",
projectId: "project-usage",
outputTokens: 50,
costMicroUsd: 1_250_000,
},
]);
}),
);
it.effect("redacts thread and project attribution after thread deletion", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
yield* appendAndProject({
type: "thread.usage-recorded",
eventId: EventId.make("evt-usage-before-delete"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: observedAt,
commandId: CommandId.make("cmd-usage-before-delete"),
causationEventId: null,
correlationId: CommandId.make("cmd-usage-before-delete"),
metadata: {},
payload: {
threadId,
turnId,
projectId,
facts: [makeFact("fact-redacted-1"), makeFact("fact-redacted-2")],
recordedAt: observedAt,
},
});
yield* appendAndProject({
type: "thread.deleted",
eventId: EventId.make("evt-usage-deleted"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: IsoDateTime.make("2026-04-01T12:01:00.000Z"),
commandId: CommandId.make("cmd-usage-deleted"),
causationEventId: null,
correlationId: CommandId.make("cmd-usage-deleted"),
metadata: {},
payload: {
threadId,
deletedAt: IsoDateTime.make("2026-04-01T12:01:00.000Z"),
},
});
const rows = yield* sql<{
readonly factId: string;
readonly threadId: string;
readonly projectId: string | null;
}>`
SELECT
fact_id AS "factId",
thread_id AS "threadId",
project_id AS "projectId"
FROM projection_usage_facts
WHERE fact_id IN ('fact-redacted-1', 'fact-redacted-2')
ORDER BY fact_id ASC
`;
assert.deepEqual(rows, [
{ factId: "fact-redacted-1", threadId: "deleted", projectId: null },
{ factId: "fact-redacted-2", threadId: "deleted", projectId: null },
]);
}),
);
it.effect("persists the stale flag", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
yield* appendAndProject({
type: "thread.usage-recorded",
eventId: EventId.make("evt-usage-stale"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: observedAt,
commandId: CommandId.make("cmd-usage-stale"),
causationEventId: null,
correlationId: CommandId.make("cmd-usage-stale"),
metadata: {},
payload: {
threadId,
turnId,
projectId: null,
facts: [makeFact("fact-stale", { stale: true })],
recordedAt: observedAt,
},
});
const rows = yield* sql<{ readonly factId: string; readonly stale: number }>`
SELECT fact_id AS "factId", stale
FROM projection_usage_facts
WHERE fact_id = 'fact-stale'
`;
assert.deepEqual(rows, [{ factId: "fact-stale", stale: 1 }]);
}),
);
it.effect("sums final and interval facts by session and model", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const usageRepository = yield* ProjectionUsageRepository;
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
yield* appendAndProject({
type: "thread.usage-recorded",
eventId: EventId.make("evt-usage-sums"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: observedAt,
commandId: CommandId.make("cmd-usage-sums"),
causationEventId: null,
correlationId: CommandId.make("cmd-usage-sums"),
metadata: {},
payload: {
threadId,
turnId,
projectId,
facts: [
makeFact("fact-sum-fable-final", {
providerSessionId: "session-target",
tokens: {
inputTokens: 100,
cachedInputTokens: 10,
cacheCreationTokens: 5,
outputTokens: 20,
reasoningOutputTokens: 2,
},
costMicroUsd: 1_000,
}),
makeFact("fact-sum-fable-interval", {
kind: "interval",
providerSessionId: "session-target",
tokens: {
inputTokens: 50,
cachedInputTokens: 5,
cacheCreationTokens: 3,
outputTokens: 10,
reasoningOutputTokens: 1,
},
costMicroUsd: 500,
}),
makeFact("fact-sum-opus", {
providerSessionId: "session-target",
model: "claude-opus-4-8",
modelRaw: "claude-opus-4-8",
tokens: {
inputTokens: 200,
cachedInputTokens: 20,
cacheCreationTokens: 8,
outputTokens: 40,
reasoningOutputTokens: 4,
},
costMicroUsd: 2_000,
}),
makeFact("fact-sum-turn-total", {
kind: "turn-total",
providerSessionId: "session-target",
tokens: {
inputTokens: 9_999,
cachedInputTokens: 9_999,
cacheCreationTokens: 9_999,
outputTokens: 9_999,
reasoningOutputTokens: 9_999,
},
costMicroUsd: 9_999,
}),
makeFact("fact-sum-other-session", {
providerSessionId: "session-other",
tokens: {
inputTokens: 8_888,
cachedInputTokens: 8_888,
cacheCreationTokens: 8_888,
outputTokens: 8_888,
reasoningOutputTokens: 8_888,
},
costMicroUsd: 8_888,
}),
],
recordedAt: observedAt,
},
});
const sums = yield* usageRepository.sumBySessionModel({
providerSessionId: "session-target",
});
assert.deepEqual(
[...sums].toSorted((left, right) => left.model.localeCompare(right.model)),
[
{
model: "claude-fable-5",
inputTokens: 150,
cachedInputTokens: 15,
cacheCreationTokens: 8,
outputTokens: 30,
reasoningOutputTokens: 3,
costMicroUsd: 1_500,
},
{
model: "claude-opus-4-8",
inputTokens: 200,
cachedInputTokens: 20,
cacheCreationTokens: 8,
outputTokens: 40,
reasoningOutputTokens: 4,
costMicroUsd: 2_000,
},
],
);
}),
);
});
@@ -3,6 +3,9 @@ import {
type AssistantDeliveryMode,
CommandId,
MessageId,
type OrchestrationThreadShell,
type UsageFact,
UsageFactId,
type OrchestrationEvent,
type OrchestrationMessage,
type OrchestrationProposedPlanId,
@@ -30,6 +33,17 @@ import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
import { ProjectionUsageRepository } from "../../persistence/Services/ProjectionUsage.ts";
import { ProjectionUsageRepositoryLive } from "../../persistence/Layers/ProjectionUsage.ts";
import {
ZERO_USAGE_COUNTERS,
type UsageCumulativeCounters,
canonicalModelId,
claudeCumulativeByModel,
codexCumulativeFromSnapshot,
isZeroUsage,
usageDelta,
} from "../usageAccounting.ts";
import { isGitRepository } from "../../git/Utils.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
@@ -697,6 +711,7 @@ const make = Effect.gen(function* () {
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => CommandId.make(`provider:${event.eventId}:${tag}:${uuid}`)),
);
const projectionUsageRepository = yield* ProjectionUsageRepository;
const turnMessageIdsByTurnKey = yield* Cache.make<string, Set<MessageId>>({
capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,
@@ -1290,6 +1305,194 @@ const make = Effect.gen(function* () {
},
);
// ---------------------------------------------------------------------
// Usage accounting: converts provider-cumulative counters into interval
// usage facts dispatched as thread.usage.record commands. Baselines are
// keyed by provider-native session id + model; on first sight of a session
// they are reseeded from projection_usage_facts sums so a server restart
// between samples never double counts.
// ---------------------------------------------------------------------
const usageBaselines = new Map<string, UsageCumulativeCounters>();
const seededUsageSessions = new Set<string>();
const usageBaselineKey = (providerSessionId: string, model: string) =>
`${providerSessionId}|${model}`;
const seedUsageBaselines = Effect.fn("seedUsageBaselines")(function* (providerSessionId: string) {
if (seededUsageSessions.has(providerSessionId)) {
return;
}
seededUsageSessions.add(providerSessionId);
const sums = yield* projectionUsageRepository.sumBySessionModel({ providerSessionId });
for (const sum of sums) {
const key = usageBaselineKey(providerSessionId, sum.model);
if (!usageBaselines.has(key)) {
usageBaselines.set(key, {
inputTokens: sum.inputTokens,
cachedInputTokens: sum.cachedInputTokens,
cacheCreationTokens: sum.cacheCreationTokens,
outputTokens: sum.outputTokens,
reasoningOutputTokens: sum.reasoningOutputTokens,
costMicroUsd: sum.costMicroUsd,
});
}
}
});
const reasoningEffortFromThread = (thread: OrchestrationThreadShell): string | undefined => {
const options = thread.modelSelection.options;
if (!options) return undefined;
for (const option of options) {
if (option.id === "reasoningEffort" && typeof option.value === "string") {
return option.value;
}
}
return undefined;
};
const dispatchUsageFacts = (input: {
readonly event: ProviderRuntimeEvent;
readonly threadId: ThreadId;
readonly projectId: OrchestrationThreadShell["projectId"] | null;
readonly turnId: TurnId | null;
readonly facts: ReadonlyArray<UsageFact>;
}) =>
providerCommandId(input.event, "usage-record").pipe(
Effect.flatMap((commandId) =>
orchestrationEngine.dispatch({
type: "thread.usage.record",
commandId,
threadId: input.threadId,
turnId: input.turnId,
projectId: input.projectId,
facts: input.facts,
createdAt: input.event.createdAt,
}),
),
Effect.asVoid,
);
const recordUsageForRuntimeEvent = (
event: ProviderRuntimeEvent,
thread: OrchestrationThreadShell,
options: { readonly staleCompletion: boolean },
) =>
Effect.gen(function* () {
// Codex path: cumulative totals ride every token-usage notification and
// are attributed by the provider-native thread id. Snapshots without
// native identity or cumulative fields are context-window telemetry
// only and carry no accounting weight.
if (event.type === "thread.token-usage.updated") {
const cumulative = codexCumulativeFromSnapshot(event.payload.usage);
const providerSessionId = event.providerRefs?.providerSessionId;
if (!cumulative || !providerSessionId || isZeroUsage(cumulative)) {
return;
}
const model = canonicalModelId(thread.modelSelection.model);
yield* seedUsageBaselines(providerSessionId);
const key = usageBaselineKey(providerSessionId, model);
const baseline = usageBaselines.get(key) ?? ZERO_USAGE_COUNTERS;
const { delta, nextBaseline } = usageDelta(baseline, cumulative);
usageBaselines.set(key, nextBaseline);
if (isZeroUsage(delta)) {
return;
}
const effort = reasoningEffortFromThread(thread);
const fact: UsageFact = {
factId: UsageFactId.make(`usage:${event.eventId}:${model}`),
kind: "interval",
provider: event.provider,
...(event.providerInstanceId !== undefined
? { providerInstanceId: event.providerInstanceId }
: {}),
providerSessionId,
model,
modelRaw: thread.modelSelection.model,
...(effort !== undefined ? { reasoningEffort: effort } : {}),
tokens: {
inputTokens: delta.inputTokens,
cachedInputTokens: delta.cachedInputTokens,
cacheCreationTokens: delta.cacheCreationTokens,
outputTokens: delta.outputTokens,
reasoningOutputTokens: delta.reasoningOutputTokens,
},
observedAt: event.createdAt,
};
yield* dispatchUsageFacts({
event,
threadId: thread.id,
projectId: thread.projectId,
turnId: toTurnId(event.turnId) ?? null,
facts: [fact],
});
return;
}
// Claude path: turn.completed carries the SDK's session-cumulative
// per-model usage map (exact cost included). Settle each model's delta
// as a final fact; stale completions are recorded but flagged.
if (event.type === "turn.completed") {
const byModel = claudeCumulativeByModel(event.payload.modelUsage);
if (!byModel || byModel.size === 0) {
return;
}
const providerSessionId = event.providerRefs?.providerSessionId ?? thread.id;
yield* seedUsageBaselines(providerSessionId);
const facts: Array<UsageFact> = [];
for (const [rawModel, cumulative] of byModel) {
const model = canonicalModelId(rawModel);
const key = usageBaselineKey(providerSessionId, model);
const baseline = usageBaselines.get(key) ?? ZERO_USAGE_COUNTERS;
const { delta, nextBaseline } = usageDelta(baseline, cumulative);
usageBaselines.set(key, nextBaseline);
if (isZeroUsage(delta)) {
continue;
}
facts.push({
factId: UsageFactId.make(`usage:${event.eventId}:${model}`),
kind: "final",
provider: event.provider,
...(event.providerInstanceId !== undefined
? { providerInstanceId: event.providerInstanceId }
: {}),
providerSessionId,
model,
modelRaw: rawModel,
tokens: {
inputTokens: delta.inputTokens,
cachedInputTokens: delta.cachedInputTokens,
cacheCreationTokens: delta.cacheCreationTokens,
outputTokens: delta.outputTokens,
reasoningOutputTokens: delta.reasoningOutputTokens,
},
...(delta.costMicroUsd > 0 ? { costMicroUsd: delta.costMicroUsd } : {}),
...(options.staleCompletion ? { stale: true } : {}),
observedAt: event.createdAt,
});
}
if (facts.length === 0) {
return;
}
yield* dispatchUsageFacts({
event,
threadId: thread.id,
projectId: thread.projectId,
turnId: toTurnId(event.turnId) ?? null,
facts,
});
}
}).pipe(
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.failCause(cause);
}
return Effect.logWarning("usage accounting failed for runtime event", {
eventId: event.eventId,
eventType: event.type,
cause: Cause.pretty(cause),
});
}),
);
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
Effect.gen(function* () {
const thread = yield* resolveThreadShell(event.threadId);
@@ -1360,6 +1563,13 @@ const make = Effect.gen(function* () {
? yield* getSourceProposedPlanReferenceForAcceptedTurnStart(thread.id, eventTurnId)
: null;
// Usage accounting runs for every usage-bearing event, including
// lifecycle-rejected completions (recorded with stale: true) — tokens
// were consumed regardless of what the turn state machine thinks.
yield* recordUsageForRuntimeEvent(event, thread, {
staleCompletion: event.type === "turn.completed" && !shouldApplyThreadLifecycle,
});
if (
event.type === "session.started" ||
event.type === "session.state.changed" ||
@@ -1822,4 +2032,4 @@ const make = Effect.gen(function* () {
export const ProviderRuntimeIngestionLive = Layer.effect(
ProviderRuntimeIngestionService,
make,
).pipe(Layer.provide(ProjectionTurnRepositoryLive));
).pipe(Layer.provide(ProjectionTurnRepositoryLive), Layer.provide(ProjectionUsageRepositoryLive));
+24
View File
@@ -774,6 +774,30 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.usage.record": {
yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
type: "thread.usage-recorded",
payload: {
threadId: command.threadId,
turnId: command.turnId,
projectId: command.projectId,
facts: command.facts,
recordedAt: command.createdAt,
},
};
}
default: {
command satisfies never;
const fallback = command as never as { type: string };
@@ -2,6 +2,7 @@ import * as Layer from "effect/Layer";
import { OrchestrationCommandReceiptRepositoryLive } from "../persistence/Layers/OrchestrationCommandReceipts.ts";
import { OrchestrationEventStoreLive } from "../persistence/Layers/OrchestrationEventStore.ts";
import { ProjectionUsageRepositoryLive } from "../persistence/Layers/ProjectionUsage.ts";
import { OrchestrationEngineLive } from "./Layers/OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./Layers/ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./Layers/ProjectionSnapshotQuery.ts";
@@ -19,6 +20,8 @@ export const OrchestrationInfrastructureLayerLive = Layer.mergeAll(
OrchestrationProjectionSnapshotQueryLive,
OrchestrationEventInfrastructureLayerLive,
OrchestrationProjectionPipelineLayerLive,
// Exposed for the usage.getSummary RPC handler in ws.ts.
ProjectionUsageRepositoryLive,
);
export const OrchestrationLayerLive = Layer.mergeAll(
@@ -0,0 +1,194 @@
import { describe, expect, it } from "@effect/vitest";
import {
canonicalModelId,
claudeCumulativeByModel,
codexCumulativeFromSnapshot,
isZeroUsage,
usageDelta,
ZERO_USAGE_COUNTERS,
} from "./usageAccounting.ts";
describe("usageAccounting", () => {
describe("usageDelta", () => {
it("computes interval counters from cumulative counters", () => {
const result = usageDelta(
{
inputTokens: 100,
cachedInputTokens: 20,
cacheCreationTokens: 10,
outputTokens: 50,
reasoningOutputTokens: 5,
costMicroUsd: 1_000_000,
},
{
inputTokens: 175,
cachedInputTokens: 35,
cacheCreationTokens: 18,
outputTokens: 90,
reasoningOutputTokens: 12,
costMicroUsd: 1_750_000,
},
);
expect(result).toEqual({
delta: {
inputTokens: 75,
cachedInputTokens: 15,
cacheCreationTokens: 8,
outputTokens: 40,
reasoningOutputTokens: 7,
costMicroUsd: 750_000,
},
nextBaseline: {
inputTokens: 175,
cachedInputTokens: 35,
cacheCreationTokens: 18,
outputTokens: 90,
reasoningOutputTokens: 12,
costMicroUsd: 1_750_000,
},
reset: false,
});
});
it("returns a zero delta when baseline equals cumulative", () => {
const cumulative = {
inputTokens: 100,
cachedInputTokens: 20,
cacheCreationTokens: 10,
outputTokens: 50,
reasoningOutputTokens: 5,
costMicroUsd: 1_000_000,
};
expect(usageDelta(cumulative, cumulative)).toEqual({
delta: ZERO_USAGE_COUNTERS,
nextBaseline: cumulative,
reset: false,
});
});
it("treats a counter regression as a provider session reset", () => {
const cumulative = {
inputTokens: 125,
cachedInputTokens: 25,
cacheCreationTokens: 12,
outputTokens: 10,
reasoningOutputTokens: 6,
costMicroUsd: 1_250_000,
};
expect(
usageDelta(
{
inputTokens: 100,
cachedInputTokens: 20,
cacheCreationTokens: 10,
outputTokens: 50,
reasoningOutputTokens: 5,
costMicroUsd: 1_000_000,
},
cumulative,
),
).toEqual({
delta: cumulative,
nextBaseline: cumulative,
reset: true,
});
});
});
describe("claudeCumulativeByModel", () => {
it("decodes per-model cumulative usage and converts USD to micro-USD", () => {
const result = claudeCumulativeByModel({
"claude-fable-5[1m]": {
inputTokens: 100,
outputTokens: 50,
cacheReadInputTokens: 1_000,
cacheCreationInputTokens: 200,
costUSD: 1.25,
},
"claude-opus-4-8": {
inputTokens: 80,
outputTokens: 30,
cacheReadInputTokens: 400,
cacheCreationInputTokens: 25,
},
});
expect(result).toEqual(
new Map([
[
"claude-fable-5[1m]",
{
inputTokens: 100,
cachedInputTokens: 1_000,
cacheCreationTokens: 200,
outputTokens: 50,
reasoningOutputTokens: 0,
costMicroUsd: 1_250_000,
},
],
[
"claude-opus-4-8",
{
inputTokens: 80,
cachedInputTokens: 400,
cacheCreationTokens: 25,
outputTokens: 30,
reasoningOutputTokens: 0,
costMicroUsd: 0,
},
],
]),
);
});
it("returns undefined for malformed input", () => {
expect(claudeCumulativeByModel({ model: "not usage" })).toBeUndefined();
expect(claudeCumulativeByModel(null)).toBeUndefined();
});
});
describe("codexCumulativeFromSnapshot", () => {
it("stores only the uncached share in inputTokens", () => {
expect(
codexCumulativeFromSnapshot({
totalInputTokens: 1_000,
totalCachedInputTokens: 250,
totalOutputTokens: 400,
totalReasoningOutputTokens: 125,
}),
).toEqual({
inputTokens: 750,
cachedInputTokens: 250,
cacheCreationTokens: 0,
outputTokens: 400,
reasoningOutputTokens: 125,
costMicroUsd: 0,
});
});
it("returns undefined when no cumulative total fields are present", () => {
expect(codexCumulativeFromSnapshot({})).toBeUndefined();
expect(
codexCumulativeFromSnapshot({
totalCachedInputTokens: 100,
totalReasoningOutputTokens: 20,
}),
).toBeUndefined();
});
});
it("canonicalizes provider capacity suffixes", () => {
expect(canonicalModelId("claude-fable-5[1m]")).toBe("claude-fable-5");
expect(canonicalModelId("claude-opus-4-8")).toBe("claude-opus-4-8");
});
it("detects zero usage", () => {
expect(isZeroUsage(ZERO_USAGE_COUNTERS)).toBe(true);
expect(isZeroUsage({ ...ZERO_USAGE_COUNTERS, outputTokens: 1 })).toBe(false);
expect(isZeroUsage({ ...ZERO_USAGE_COUNTERS, costMicroUsd: 1 })).toBe(false);
});
});
@@ -0,0 +1,136 @@
import * as Schema from "effect/Schema";
import { ClaudeModelUsageMap, type UsageTokenCounters } from "@t3tools/contracts";
/**
* Pure delta accounting for usage facts.
*
* Providers report session-cumulative counters (Codex `tokenUsage.total`,
* Claude `modelUsage`). A usage fact must carry interval counters, so every
* emission subtracts a baseline: the sum of everything already recorded for
* that provider-native session and model. Baselines survive restarts by
* reseeding from `projection_usage_facts` sums.
*/
export interface UsageCumulativeCounters extends UsageTokenCounters {
readonly costMicroUsd: number;
}
export const ZERO_USAGE_COUNTERS: UsageCumulativeCounters = {
inputTokens: 0,
cachedInputTokens: 0,
cacheCreationTokens: 0,
outputTokens: 0,
reasoningOutputTokens: 0,
costMicroUsd: 0,
};
export interface UsageDeltaResult {
readonly delta: UsageCumulativeCounters;
/** The cumulative counters that become the next baseline. */
readonly nextBaseline: UsageCumulativeCounters;
/** True when any counter went backwards (provider session reset); the
* absolute cumulative value is used as the delta in that case. */
readonly reset: boolean;
}
function nonNegative(value: number): number {
return value > 0 ? Math.round(value) : 0;
}
export function usageDelta(
baseline: UsageCumulativeCounters,
cumulative: UsageCumulativeCounters,
): UsageDeltaResult {
const reset =
cumulative.inputTokens < baseline.inputTokens ||
cumulative.cachedInputTokens < baseline.cachedInputTokens ||
cumulative.outputTokens < baseline.outputTokens;
if (reset) {
return { delta: cumulative, nextBaseline: cumulative, reset: true };
}
return {
delta: {
inputTokens: nonNegative(cumulative.inputTokens - baseline.inputTokens),
cachedInputTokens: nonNegative(cumulative.cachedInputTokens - baseline.cachedInputTokens),
cacheCreationTokens: nonNegative(
cumulative.cacheCreationTokens - baseline.cacheCreationTokens,
),
outputTokens: nonNegative(cumulative.outputTokens - baseline.outputTokens),
reasoningOutputTokens: nonNegative(
cumulative.reasoningOutputTokens - baseline.reasoningOutputTokens,
),
costMicroUsd: nonNegative(cumulative.costMicroUsd - baseline.costMicroUsd),
},
nextBaseline: cumulative,
reset: false,
};
}
export function isZeroUsage(counters: UsageCumulativeCounters): boolean {
return (
counters.inputTokens === 0 &&
counters.cachedInputTokens === 0 &&
counters.cacheCreationTokens === 0 &&
counters.outputTokens === 0 &&
counters.reasoningOutputTokens === 0 &&
counters.costMicroUsd === 0
);
}
/** Strip provider capacity suffixes (`claude-fable-5[1m]` → `claude-fable-5`)
* while keeping the raw id available for display and pricing overrides. */
export function canonicalModelId(rawModel: string): string {
return rawModel.replace(/\[[^\]]+\]$/, "");
}
const decodeClaudeModelUsage = Schema.decodeUnknownOption(ClaudeModelUsageMap);
/** Claude's `modelUsage` map is cumulative per SDK session. Returns cumulative
* counters per raw model id, or undefined when the payload doesn't parse. */
export function claudeCumulativeByModel(
modelUsage: unknown,
): ReadonlyMap<string, UsageCumulativeCounters> | undefined {
const decoded = decodeClaudeModelUsage(modelUsage);
if (decoded._tag === "None") {
return undefined;
}
const result = new Map<string, UsageCumulativeCounters>();
for (const [rawModel, entry] of Object.entries(decoded.value)) {
result.set(rawModel, {
inputTokens: nonNegative(entry.inputTokens),
cachedInputTokens: nonNegative(entry.cacheReadInputTokens),
cacheCreationTokens: nonNegative(entry.cacheCreationInputTokens),
outputTokens: nonNegative(entry.outputTokens),
reasoningOutputTokens: 0,
costMicroUsd: entry.costUSD !== undefined ? nonNegative(entry.costUSD * 1_000_000) : 0,
});
}
return result;
}
/** Codex cumulative totals from a ThreadTokenUsageSnapshot's `total*` fields.
* Codex reports input inclusive of cached reads; the uncached share is the
* difference. Returns undefined when the snapshot has no cumulative fields
* (Claude context-window snapshots land here and are settled at turn end). */
export function codexCumulativeFromSnapshot(usage: {
readonly totalInputTokens?: number | undefined;
readonly totalCachedInputTokens?: number | undefined;
readonly totalOutputTokens?: number | undefined;
readonly totalReasoningOutputTokens?: number | undefined;
}): UsageCumulativeCounters | undefined {
if (usage.totalInputTokens === undefined && usage.totalOutputTokens === undefined) {
return undefined;
}
const totalInput = usage.totalInputTokens ?? 0;
const cached = usage.totalCachedInputTokens ?? 0;
return {
inputTokens: nonNegative(totalInput - cached),
cachedInputTokens: nonNegative(cached),
cacheCreationTokens: 0,
outputTokens: nonNegative(usage.totalOutputTokens ?? 0),
reasoningOutputTokens: nonNegative(usage.totalReasoningOutputTokens ?? 0),
costMicroUsd: 0,
};
}
@@ -0,0 +1,276 @@
import type { UsageAggregate, UsageSummaryResponse } from "@t3tools/contracts";
import { USAGE_PRICING_VERSION, estimateCostMicroUsd } from "@t3tools/shared/usagePricing";
import type { ProjectionUsageFact } from "../persistence/Services/ProjectionUsage.ts";
/**
* Pure aggregation of usage facts into the dashboard-shaped summary. Calendar
* bucketing happens in the requested IANA timezone via Intl (DST folds into
* the local calendar naturally). `turn-total` facts are reconciliation-only
* and excluded from all sums; stale facts count (tokens were consumed).
*/
interface MutableAggregate {
inputTokens: number;
cachedInputTokens: number;
cacheCreationTokens: number;
outputTokens: number;
reasoningOutputTokens: number;
totalTokens: number;
turns: number;
exactCostMicroUsd: number;
estimatedCostMicroUsd: number;
}
function newAggregate(): MutableAggregate {
return {
inputTokens: 0,
cachedInputTokens: 0,
cacheCreationTokens: 0,
outputTokens: 0,
reasoningOutputTokens: 0,
totalTokens: 0,
turns: 0,
exactCostMicroUsd: 0,
estimatedCostMicroUsd: 0,
};
}
function addFact(
aggregate: MutableAggregate,
fact: ProjectionUsageFact,
estimatedMicroUsd: number | undefined,
): void {
aggregate.inputTokens += fact.inputTokens;
aggregate.cachedInputTokens += fact.cachedInputTokens;
aggregate.cacheCreationTokens += fact.cacheCreationTokens;
aggregate.outputTokens += fact.outputTokens;
aggregate.reasoningOutputTokens += fact.reasoningOutputTokens;
aggregate.totalTokens +=
fact.inputTokens + fact.cachedInputTokens + fact.cacheCreationTokens + fact.outputTokens;
if (fact.costMicroUsd !== null) {
aggregate.exactCostMicroUsd += fact.costMicroUsd;
} else if (estimatedMicroUsd !== undefined) {
aggregate.estimatedCostMicroUsd += estimatedMicroUsd;
}
}
function toAggregate(mutable: MutableAggregate): UsageAggregate {
return { ...mutable };
}
function makeCalendarFormatter(timeZone: string): Intl.DateTimeFormat {
return new Intl.DateTimeFormat("en-CA", {
timeZone,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
hour12: false,
weekday: "short",
});
}
const WEEKDAY_INDEX: Record<string, number> = {
Sun: 0,
Mon: 1,
Tue: 2,
Wed: 3,
Thu: 4,
Fri: 5,
Sat: 6,
};
interface CalendarParts {
readonly day: string;
readonly hour: number;
readonly dayOfWeek: number;
}
function calendarParts(formatter: Intl.DateTimeFormat, iso: string): CalendarParts {
const parts = formatter.formatToParts(Date.parse(iso));
let year = "",
month = "",
day = "",
hour = 0,
dayOfWeek = 0;
for (const part of parts) {
switch (part.type) {
case "year":
year = part.value;
break;
case "month":
month = part.value;
break;
case "day":
day = part.value;
break;
case "hour":
hour = Number(part.value) % 24;
break;
case "weekday":
dayOfWeek = WEEKDAY_INDEX[part.value] ?? 0;
break;
}
}
return { day: `${year}-${month}-${day}`, hour, dayOfWeek };
}
export type UsageProjectTitleLookup = (projectId: string) => string | null;
export function summarizeUsageFacts(input: {
readonly facts: ReadonlyArray<ProjectionUsageFact>;
readonly timeZone: string;
readonly earliestFactAt: string | null;
readonly projectTitle: UsageProjectTitleLookup;
}): UsageSummaryResponse {
const formatter = makeCalendarFormatter(input.timeZone);
const totals = newAggregate();
const byModel = new Map<
string,
MutableAggregate & { provider: ProjectionUsageFact["provider"]; hasEstimate: boolean }
>();
const daily = new Map<
string,
MutableAggregate & {
day: string;
provider: ProjectionUsageFact["provider"];
model: string;
}
>();
const hourOfWeek = new Map<
string,
{ dayOfWeek: number; hour: number; turns: number; totalTokens: number }
>();
const byProject = new Map<
string,
MutableAggregate & { projectId: ProjectionUsageFact["projectId"] }
>();
const unpricedModels = new Set<string>();
const turnKeys = new Set<string>();
const turnKeysByScope = new Map<string, Set<string>>();
const scopedTurnCount = (scope: string, turnKey: string): number => {
let keys = turnKeysByScope.get(scope);
if (!keys) {
keys = new Set();
turnKeysByScope.set(scope, keys);
}
const before = keys.size;
keys.add(turnKey);
return keys.size - before;
};
for (const fact of input.facts) {
if (fact.kind === "turn-total") {
continue;
}
const estimated =
fact.costMicroUsd === null
? estimateCostMicroUsd(fact.model, fact.observedAt, {
inputTokens: fact.inputTokens,
cachedInputTokens: fact.cachedInputTokens,
cacheCreationTokens: fact.cacheCreationTokens,
outputTokens: fact.outputTokens,
})
: undefined;
if (fact.costMicroUsd === null && estimated === undefined) {
unpricedModels.add(fact.model);
}
const cal = calendarParts(formatter, fact.observedAt);
const turnKey = `${fact.threadId}|${fact.turnId ?? fact.factId}`;
const factTokens =
fact.inputTokens + fact.cachedInputTokens + fact.cacheCreationTokens + fact.outputTokens;
addFact(totals, fact, estimated);
if (!turnKeys.has(turnKey)) {
turnKeys.add(turnKey);
totals.turns += 1;
}
const modelKey = `${fact.provider}|${fact.model}`;
let model = byModel.get(modelKey);
if (!model) {
model = { ...newAggregate(), provider: fact.provider, hasEstimate: false };
byModel.set(modelKey, model);
}
addFact(model, fact, estimated);
if (estimated !== undefined) model.hasEstimate = true;
model.turns += scopedTurnCount(`model:${modelKey}`, turnKey);
const dayKey = `${cal.day}|${fact.provider}|${fact.model}`;
let dayBucket = daily.get(dayKey);
if (!dayBucket) {
dayBucket = { ...newAggregate(), day: cal.day, provider: fact.provider, model: fact.model };
daily.set(dayKey, dayBucket);
}
addFact(dayBucket, fact, estimated);
dayBucket.turns += scopedTurnCount(`day:${dayKey}`, turnKey);
const howKey = `${cal.dayOfWeek}|${cal.hour}`;
let how = hourOfWeek.get(howKey);
if (!how) {
how = { dayOfWeek: cal.dayOfWeek, hour: cal.hour, turns: 0, totalTokens: 0 };
hourOfWeek.set(howKey, how);
}
how.totalTokens += factTokens;
how.turns += scopedTurnCount(`how:${howKey}`, turnKey);
const projectKey = fact.projectId ?? "__none__";
let project = byProject.get(projectKey);
if (!project) {
project = { ...newAggregate(), projectId: fact.projectId };
byProject.set(projectKey, project);
}
addFact(project, fact, estimated);
project.turns += scopedTurnCount(`project:${projectKey}`, turnKey);
}
const modelBuckets = [...byModel.entries()]
.map(([key, aggregate]) => ({
...toAggregate(aggregate),
provider: aggregate.provider,
model: key.slice(key.indexOf("|") + 1),
costSource:
aggregate.exactCostMicroUsd > 0
? ("exact" as const)
: aggregate.hasEstimate
? ("estimated" as const)
: ("none" as const),
}))
.sort((a, b) => b.totalTokens - a.totalTokens);
const dailyBuckets = [...daily.values()]
.map((bucket) => ({
...toAggregate(bucket),
day: bucket.day,
provider: bucket.provider,
model: bucket.model,
}))
.sort((a, b) => (a.day === b.day ? b.totalTokens - a.totalTokens : a.day.localeCompare(b.day)));
const hourBuckets = [...hourOfWeek.values()].sort(
(a, b) => a.dayOfWeek - b.dayOfWeek || a.hour - b.hour,
);
const projectBuckets = [...byProject.values()]
.map((bucket) => ({
...toAggregate(bucket),
projectId: bucket.projectId,
projectTitle: bucket.projectId ? input.projectTitle(bucket.projectId) : null,
}))
.sort((a, b) => b.totalTokens - a.totalTokens);
return {
totals: toAggregate(totals),
byModel: modelBuckets,
daily: dailyBuckets,
hourOfWeek: hourBuckets,
byProject: projectBuckets,
unpricedModels: [...unpricedModels].sort(),
pricingVersion: USAGE_PRICING_VERSION,
earliestFactAt: input.earliestFactAt,
} as UsageSummaryResponse;
}
@@ -0,0 +1,221 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Struct from "effect/Struct";
import { IsoDateTime } from "@t3tools/contracts";
import { toPersistenceSqlError } from "../Errors.ts";
import {
ListProjectionUsageFactsInput,
ProjectionUsageFact,
ProjectionUsageRepository,
type ProjectionUsageRepositoryShape,
ProjectionUsageSessionModelSum,
RedactProjectionUsageThreadInput,
} from "../Services/ProjectionUsage.ts";
const ProjectionUsageFactDbRowSchema = ProjectionUsageFact.mapFields(
Struct.assign({
stale: Schema.Number,
}),
);
const EarliestObservedAtRowSchema = Schema.Struct({
earliestObservedAt: Schema.NullOr(IsoDateTime),
});
function toProjectionUsageFact(
row: Schema.Schema.Type<typeof ProjectionUsageFactDbRowSchema>,
): ProjectionUsageFact {
return {
...row,
stale: row.stale === 1,
};
}
const makeProjectionUsageRepository = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const upsertProjectionUsageFactRow = SqlSchema.void({
Request: ProjectionUsageFact,
execute: (row) =>
sql`
INSERT INTO projection_usage_facts (
fact_id,
thread_id,
turn_id,
project_id,
provider,
provider_instance_id,
provider_session_id,
model,
model_raw,
reasoning_effort,
kind,
input_tokens,
cached_input_tokens,
cache_creation_tokens,
output_tokens,
reasoning_output_tokens,
cost_micro_usd,
stale,
observed_at
)
VALUES (
${row.factId},
${row.threadId},
${row.turnId},
${row.projectId},
${row.provider},
${row.providerInstanceId},
${row.providerSessionId},
${row.model},
${row.modelRaw},
${row.reasoningEffort},
${row.kind},
${row.inputTokens},
${row.cachedInputTokens},
${row.cacheCreationTokens},
${row.outputTokens},
${row.reasoningOutputTokens},
${row.costMicroUsd},
${row.stale ? 1 : 0},
${row.observedAt}
)
ON CONFLICT (fact_id)
DO UPDATE SET
thread_id = excluded.thread_id,
turn_id = excluded.turn_id,
project_id = excluded.project_id,
provider = excluded.provider,
provider_instance_id = excluded.provider_instance_id,
provider_session_id = excluded.provider_session_id,
model = excluded.model,
model_raw = excluded.model_raw,
reasoning_effort = excluded.reasoning_effort,
kind = excluded.kind,
input_tokens = excluded.input_tokens,
cached_input_tokens = excluded.cached_input_tokens,
cache_creation_tokens = excluded.cache_creation_tokens,
output_tokens = excluded.output_tokens,
reasoning_output_tokens = excluded.reasoning_output_tokens,
cost_micro_usd = excluded.cost_micro_usd,
stale = excluded.stale,
observed_at = excluded.observed_at
`,
});
const redactProjectionUsageThreadRows = SqlSchema.void({
Request: RedactProjectionUsageThreadInput,
execute: ({ threadId }) =>
sql`
UPDATE projection_usage_facts
SET thread_id = 'deleted', project_id = NULL
WHERE thread_id = ${threadId}
`,
});
const listProjectionUsageFactRows = SqlSchema.findAll({
Request: ListProjectionUsageFactsInput,
Result: ProjectionUsageFactDbRowSchema,
execute: ({ sinceIso, untilIso }) =>
sql`
SELECT
fact_id AS "factId",
thread_id AS "threadId",
turn_id AS "turnId",
project_id AS "projectId",
provider,
provider_instance_id AS "providerInstanceId",
provider_session_id AS "providerSessionId",
model,
model_raw AS "modelRaw",
reasoning_effort AS "reasoningEffort",
kind,
input_tokens AS "inputTokens",
cached_input_tokens AS "cachedInputTokens",
cache_creation_tokens AS "cacheCreationTokens",
output_tokens AS "outputTokens",
reasoning_output_tokens AS "reasoningOutputTokens",
cost_micro_usd AS "costMicroUsd",
stale,
observed_at AS "observedAt"
FROM projection_usage_facts
WHERE (${sinceIso ?? null} IS NULL OR observed_at >= ${sinceIso ?? null})
AND (${untilIso ?? null} IS NULL OR observed_at < ${untilIso ?? null})
ORDER BY observed_at ASC
`,
});
const readSessionModelSums = SqlSchema.findAll({
Request: Schema.Struct({ providerSessionId: Schema.String }),
Result: ProjectionUsageSessionModelSum,
execute: ({ providerSessionId }) =>
sql`
SELECT
model,
COALESCE(SUM(input_tokens), 0) AS "inputTokens",
COALESCE(SUM(cached_input_tokens), 0) AS "cachedInputTokens",
COALESCE(SUM(cache_creation_tokens), 0) AS "cacheCreationTokens",
COALESCE(SUM(output_tokens), 0) AS "outputTokens",
COALESCE(SUM(reasoning_output_tokens), 0) AS "reasoningOutputTokens",
COALESCE(SUM(COALESCE(cost_micro_usd, 0)), 0) AS "costMicroUsd"
FROM projection_usage_facts
WHERE provider_session_id = ${providerSessionId}
AND kind IN ('final', 'interval')
GROUP BY model
`,
});
const readEarliestObservedAt = SqlSchema.findOne({
Request: Schema.Void,
Result: EarliestObservedAtRowSchema,
execute: () =>
sql`
SELECT MIN(observed_at) AS "earliestObservedAt"
FROM projection_usage_facts
`,
});
const upsertFact: ProjectionUsageRepositoryShape["upsertFact"] = (row) =>
upsertProjectionUsageFactRow(row).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionUsageRepository.upsertFact:query")),
);
const redactThread: ProjectionUsageRepositoryShape["redactThread"] = (input) =>
redactProjectionUsageThreadRows(input).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionUsageRepository.redactThread:query")),
);
const listFacts: ProjectionUsageRepositoryShape["listFacts"] = (input) =>
listProjectionUsageFactRows(input).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionUsageRepository.listFacts:query")),
Effect.map((rows) => rows.map(toProjectionUsageFact)),
);
const earliestObservedAt: ProjectionUsageRepositoryShape["earliestObservedAt"] = () =>
readEarliestObservedAt(undefined).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionUsageRepository.earliestObservedAt:query")),
Effect.map((row) => row.earliestObservedAt),
);
const sumBySessionModel: ProjectionUsageRepositoryShape["sumBySessionModel"] = (input) =>
readSessionModelSums(input).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionUsageRepository.sumBySessionModel:query")),
);
return {
upsertFact,
redactThread,
listFacts,
earliestObservedAt,
sumBySessionModel,
} satisfies ProjectionUsageRepositoryShape;
});
export const ProjectionUsageRepositoryLive = Layer.effect(
ProjectionUsageRepository,
makeProjectionUsageRepository,
);
@@ -45,6 +45,7 @@ import Migration0029 from "./Migrations/029_ProjectionThreadDetailOrderingIndexe
import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.ts";
import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
import Migration0033 from "./Migrations/033_ProjectionUsage.ts";
/**
* Migration loader with all migrations defined inline.
@@ -89,6 +90,7 @@ export const migrationEntries = [
[30, "ProjectionThreadShellArchiveIndexes", Migration0030],
[31, "AuthAuthorizationScopes", Migration0031],
[32, "AuthPairingProofKeyThumbprint", Migration0032],
[33, "ProjectionUsage", Migration0033],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -0,0 +1,45 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
CREATE TABLE IF NOT EXISTS projection_usage_facts (
fact_id TEXT PRIMARY KEY,
thread_id TEXT NOT NULL,
turn_id TEXT,
project_id TEXT,
provider TEXT NOT NULL,
provider_instance_id TEXT,
provider_session_id TEXT NOT NULL,
model TEXT NOT NULL,
model_raw TEXT NOT NULL,
reasoning_effort TEXT,
kind TEXT NOT NULL,
input_tokens INTEGER NOT NULL DEFAULT 0,
cached_input_tokens INTEGER NOT NULL DEFAULT 0,
cache_creation_tokens INTEGER NOT NULL DEFAULT 0,
output_tokens INTEGER NOT NULL DEFAULT 0,
reasoning_output_tokens INTEGER NOT NULL DEFAULT 0,
cost_micro_usd INTEGER,
stale INTEGER NOT NULL DEFAULT 0,
observed_at TEXT NOT NULL
)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_usage_facts_observed_at
ON projection_usage_facts(observed_at)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_usage_facts_provider_model
ON projection_usage_facts(provider, model)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_usage_facts_thread_id
ON projection_usage_facts(thread_id)
`;
});
@@ -0,0 +1,89 @@
import {
IsoDateTime,
NonNegativeInt,
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
ThreadId,
TrimmedNonEmptyString,
TurnId,
UsageFactId,
UsageFactKind,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import type { ProjectionRepositoryError } from "../Errors.ts";
export const ProjectionUsageFact = Schema.Struct({
factId: UsageFactId,
threadId: ThreadId,
turnId: Schema.NullOr(TurnId),
projectId: Schema.NullOr(ProjectId),
provider: ProviderDriverKind,
providerInstanceId: Schema.NullOr(ProviderInstanceId),
providerSessionId: TrimmedNonEmptyString,
model: TrimmedNonEmptyString,
modelRaw: TrimmedNonEmptyString,
reasoningEffort: Schema.NullOr(TrimmedNonEmptyString),
kind: UsageFactKind,
inputTokens: NonNegativeInt,
cachedInputTokens: NonNegativeInt,
cacheCreationTokens: NonNegativeInt,
outputTokens: NonNegativeInt,
reasoningOutputTokens: NonNegativeInt,
costMicroUsd: Schema.NullOr(NonNegativeInt),
stale: Schema.Boolean,
observedAt: IsoDateTime,
});
export type ProjectionUsageFact = typeof ProjectionUsageFact.Type;
export const RedactProjectionUsageThreadInput = Schema.Struct({
threadId: ThreadId,
});
export type RedactProjectionUsageThreadInput = typeof RedactProjectionUsageThreadInput.Type;
export const ListProjectionUsageFactsInput = Schema.Struct({
sinceIso: Schema.optional(IsoDateTime),
untilIso: Schema.optional(IsoDateTime),
});
export type ListProjectionUsageFactsInput = typeof ListProjectionUsageFactsInput.Type;
/** Per-model sums of everything already recorded for one provider-native
* session. Used as the durable baseline when converting a provider's
* cumulative counters into interval facts — after a restart the in-memory
* baseline is gone, and resuming from recorded sums prevents double counting. */
export const ProjectionUsageSessionModelSum = Schema.Struct({
model: TrimmedNonEmptyString,
inputTokens: NonNegativeInt,
cachedInputTokens: NonNegativeInt,
cacheCreationTokens: NonNegativeInt,
outputTokens: NonNegativeInt,
reasoningOutputTokens: NonNegativeInt,
costMicroUsd: NonNegativeInt,
});
export type ProjectionUsageSessionModelSum = typeof ProjectionUsageSessionModelSum.Type;
export interface ProjectionUsageRepositoryShape {
readonly upsertFact: (row: ProjectionUsageFact) => Effect.Effect<void, ProjectionRepositoryError>;
readonly redactThread: (
input: RedactProjectionUsageThreadInput,
) => Effect.Effect<void, ProjectionRepositoryError>;
readonly listFacts: (
input: ListProjectionUsageFactsInput,
) => Effect.Effect<ReadonlyArray<ProjectionUsageFact>, ProjectionRepositoryError>;
readonly earliestObservedAt: () => Effect.Effect<string | null, ProjectionRepositoryError>;
readonly sumBySessionModel: (input: {
readonly providerSessionId: string;
}) => Effect.Effect<ReadonlyArray<ProjectionUsageSessionModelSum>, ProjectionRepositoryError>;
}
export class ProjectionUsageRepository extends Context.Service<
ProjectionUsageRepository,
ProjectionUsageRepositoryShape
>()("t3/persistence/Services/ProjectionUsage/ProjectionUsageRepository") {}
@@ -1711,6 +1711,133 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("consumes undeclared and UX-internal system subtypes without warning rows", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => runtimeEvents.push(event)),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
// Undeclared wire-only roster snapshot + every typed UX-internal
// subtype and top-level type consumed silently: none may surface as
// unknown-subtype warnings.
for (const message of [
{
type: "system",
subtype: "background_tasks_changed",
tasks: [{ task_id: "t1", task_type: "local_agent", description: "Say hi" }],
session_id: "session",
uuid: "roster",
},
{
type: "system",
subtype: "task_updated",
task_id: "t1",
patch: { status: "running" },
session_id: "session",
uuid: "tu",
},
{ type: "system", subtype: "commands_changed", session_id: "session", uuid: "cc" },
{ type: "system", subtype: "model_refusal_fallback", session_id: "session", uuid: "mrf" },
{ type: "system", subtype: "local_command_output", session_id: "session", uuid: "lco" },
{ type: "system", subtype: "plugin_install", session_id: "session", uuid: "pi" },
{ type: "system", subtype: "memory_recall", session_id: "session", uuid: "mr" },
{ type: "system", subtype: "elicitation_complete", session_id: "session", uuid: "ec" },
{ type: "prompt_suggestion", suggestion: "try this", session_id: "session", uuid: "ps" },
{
type: "system",
subtype: "notification",
key: "context",
text: "low priority note",
priority: "low",
session_id: "session",
uuid: "notif",
},
]) {
harness.query.emit(message as unknown as SDKMessage);
}
// High-priority notifications DO surface as a warning row.
harness.query.emit({
type: "system",
subtype: "notification",
key: "limit",
text: "context window nearly full",
priority: "high",
session_id: "session",
uuid: "notif-high",
} as unknown as SDKMessage);
// session_state_changed maps to the matching session states.
for (const [state, uuid] of [
["running", "ssc-run"],
["requires_action", "ssc-req"],
["idle", "ssc-idle"],
]) {
harness.query.emit({
type: "system",
subtype: "session_state_changed",
state,
session_id: "session",
uuid,
} as unknown as SDKMessage);
}
// api_retry maps to a session heartbeat, not a warning row.
harness.query.emit({
type: "system",
subtype: "api_retry",
attempt: 3,
max_retries: 10,
retry_delay_ms: 1000,
error_status: 502,
error: { type: "api_error" },
session_id: "session",
uuid: "retry",
} as unknown as SDKMessage);
yield* Effect.yieldNow;
yield* Effect.yieldNow;
const warnings = runtimeEvents.filter((event) => event.type === "runtime.warning");
// Exactly one warning: the high-priority notification. Nothing else.
assert.deepEqual(
warnings.map((event) => event.payload.message),
["context window nearly full"],
);
const sessionStates = runtimeEvents
.filter((event) => event.type === "session.state.changed")
.map((event) =>
event.type === "session.state.changed"
? `${event.payload.state}:${event.payload.reason ?? ""}`
: "",
)
.filter(
(entry) => entry.startsWith("running:session_state") || entry.includes("session_state"),
);
assert.deepEqual(sessionStates, [
"running:session_state:running",
"waiting:session_state:requires_action",
"ready:session_state:idle",
]);
const heartbeat = runtimeEvents.find(
(event) =>
event.type === "session.state.changed" &&
typeof event.payload.reason === "string" &&
event.payload.reason.startsWith("api_retry:"),
);
assert.equal(heartbeat?.type, "session.state.changed");
runtimeEventsFiber.interruptUnsafe();
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("emits thread token usage updates from Claude task progress", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -2675,9 +2802,7 @@ describe("ClaudeAdapterLive", () => {
if (requested.value.type !== "request.opened") {
return;
}
assert.deepEqual(requested.value.providerRefs, {
providerItemId: ProviderItemId.make("tool-use-1"),
});
assert.equal(requested.value.providerRefs?.providerItemId, ProviderItemId.make("tool-use-1"));
const runtimeRequestId = requested.value.requestId;
assert.equal(typeof runtimeRequestId, "string");
if (runtimeRequestId === undefined) {
@@ -2701,9 +2826,7 @@ describe("ClaudeAdapterLive", () => {
}
assert.equal(resolved.value.requestId, requested.value.requestId);
assert.equal(resolved.value.payload.decision, "accept");
assert.deepEqual(resolved.value.providerRefs, {
providerItemId: ProviderItemId.make("tool-use-1"),
});
assert.equal(resolved.value.providerRefs?.providerItemId, ProviderItemId.make("tool-use-1"));
const permissionResult = yield* Effect.promise(() => permissionPromise);
assert.equal((permissionResult as PermissionResult).behavior, "allow");
@@ -3045,7 +3168,7 @@ describe("ClaudeAdapterLive", () => {
attachments: [],
});
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6"]);
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6[1m]"]);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
@@ -3143,10 +3266,11 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello again",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "contextWindow", value: "200k" }],
),
attachments: [],
});
@@ -3312,9 +3436,10 @@ describe("ClaudeAdapterLive", () => {
return;
}
assert.equal(proposedEvent.value.payload.planMarkdown, "# Ship it\n\n- one\n- two");
assert.deepEqual(proposedEvent.value.providerRefs, {
providerItemId: ProviderItemId.make("tool-exit-1"),
});
assert.equal(
proposedEvent.value.providerRefs?.providerItemId,
ProviderItemId.make("tool-exit-1"),
);
const permissionResult = yield* Effect.promise(() => permissionPromise);
assert.equal((permissionResult as PermissionResult).behavior, "deny");
@@ -3390,9 +3515,10 @@ describe("ClaudeAdapterLive", () => {
return;
}
assert.equal(proposedEvent.value.payload.planMarkdown, "# Final plan\n\n- capture it");
assert.deepEqual(proposedEvent.value.providerRefs, {
providerItemId: ProviderItemId.make("tool-exit-2"),
});
assert.equal(
proposedEvent.value.providerRefs?.providerItemId,
ProviderItemId.make("tool-exit-2"),
);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
@@ -3484,9 +3610,10 @@ describe("ClaudeAdapterLive", () => {
// Regression for #2388: `id` must equal the full question text so the
// UI's draft-answer key matches what the SDK looks up downstream.
assert.equal(requestedEvent.value.payload.questions[0]?.id, "Which framework?");
assert.deepEqual(requestedEvent.value.providerRefs, {
providerItemId: ProviderItemId.make("tool-ask-1"),
});
assert.equal(
requestedEvent.value.providerRefs?.providerItemId,
ProviderItemId.make("tool-ask-1"),
);
// Respond with the user's answers.
yield* adapter.respondToUserInput(session.threadId, ApprovalRequestId.make(requestId!), {
@@ -3506,9 +3633,10 @@ describe("ClaudeAdapterLive", () => {
assert.deepEqual(resolvedEvent.value.payload.answers, {
"Which framework?": "React",
});
assert.deepEqual(resolvedEvent.value.providerRefs, {
providerItemId: ProviderItemId.make("tool-ask-1"),
});
assert.equal(
resolvedEvent.value.providerRefs?.providerItemId,
ProviderItemId.make("tool-ask-1"),
);
// The canUseTool promise should resolve with the answers in SDK format.
const permissionResult = yield* Effect.promise(() => permissionPromise);
@@ -77,6 +77,7 @@ import {
isClaudeUltracodeEffort,
normalizeClaudeCliEffort,
resolveClaudeApiModelId,
resolveClaudeContextWindow,
resolveClaudeEffort,
} from "./ClaudeProvider.ts";
import {
@@ -341,24 +342,18 @@ function selectedClaudeContextWindow(
switch (modelSelection?.model) {
case "claude-opus-4-8":
case "claude-opus-4-7":
// Always 1M at the API; these models expose no contextWindow option.
return 1_000_000;
}
const optionValue = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
if (optionValue === "1m") {
return 1_000_000;
switch (resolveClaudeContextWindow(modelSelection)) {
case "1m":
return 1_000_000;
case "200k":
return 200_000;
default:
return undefined;
}
if (optionValue === "200k") {
return 200_000;
}
const caps = getClaudeModelCapabilities(modelSelection?.model);
const hasContextWindowOption = getProviderOptionDescriptors({ caps }).some(
(descriptor) => descriptor.type === "select" && descriptor.id === "contextWindow",
);
if (hasContextWindowOption) {
return 200_000;
}
return undefined;
}
function finiteNonNegativeInteger(value: unknown): number | undefined {
@@ -1019,17 +1014,21 @@ function streamKindFromDeltaType(deltaType: string): ClaudeTextStreamKind {
}
function nativeProviderRefs(
_context: ClaudeSessionContext,
context: ClaudeSessionContext,
options?: {
readonly providerItemId?: string | undefined;
},
): NonNullable<ProviderRuntimeEvent["providerRefs"]> {
// The Claude SDK session id is the provider-native identity that usage
// accounting keys cumulative counters on; carry it on every event.
const sessionRef = context.resumeSessionId ? { providerSessionId: context.resumeSessionId } : {};
if (options?.providerItemId) {
return {
...sessionRef,
providerItemId: ProviderItemId.make(options.providerItemId),
};
}
return {};
return sessionRef;
}
function extractAssistantTextBlocks(message: SDKMessage): Array<string> {
@@ -2590,6 +2589,17 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
};
// Undeclared-but-real subtypes (absent from the SDK's union, so they can't
// be switch cases): consumed intentionally without emitting, otherwise
// they fall through to the unknown-subtype warning and surface as spurious
// error rows in client work logs. `background_tasks_changed` is a roster
// snapshot ({tasks: [...]}) — the task_* lifecycle events carry the
// authoritative per-agent data and the typed background_tasks control
// request is the reconciliation source.
if ((message.subtype as string) === "background_tasks_changed") {
return;
}
switch (message.subtype) {
case "init":
yield* offerRuntimeEvent({
@@ -2702,6 +2712,11 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
});
return;
// Task state patch (status/backgrounded/end_time). No runtime mapping
// yet — the terminal task_notification reports the outcome — but it
// must not surface as an unknown-subtype warning row.
case "task_updated":
return;
case "task_notification":
yield* emitThreadTokenUsage(
context,
@@ -2746,6 +2761,52 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
return;
case "thinking_tokens":
return;
case "api_retry":
// Transport-level retry heartbeat. Surfacing each attempt as a
// warning row spammed the work log (10 rows during a 502 storm);
// the terminal result/error path reports the actual failure. Keep
// the session visibly alive instead.
yield* offerRuntimeEvent({
...base,
type: "session.state.changed",
payload: {
state: "running",
reason: `api_retry:${message.attempt}/${message.max_retries}`,
},
});
return;
case "session_state_changed":
// Authoritative turn-over signal from the CLI.
yield* offerRuntimeEvent({
...base,
type: "session.state.changed",
payload: {
state:
message.state === "running"
? "running"
: message.state === "requires_action"
? "waiting"
: "ready",
reason: `session_state:${message.state}`,
},
});
return;
case "notification":
// User-facing CLI notification (e.g. context-limit warnings). Only
// high-priority ones warrant a work-log row.
if (message.priority === "high" || message.priority === "immediate") {
yield* emitRuntimeWarning(context, message.text, message);
}
return;
// Inner protocol/UX details with no T3 surface today — consumed
// deliberately so they don't masquerade as unknown-subtype warnings.
case "model_refusal_fallback":
case "local_command_output":
case "plugin_install":
case "commands_changed":
case "memory_recall":
case "elicitation_complete":
return;
case "permission_denied":
yield* offerRuntimeEvent({
...base,
@@ -2765,13 +2826,21 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
message,
);
return;
default:
default: {
// Exhaustiveness guard: every subtype in the SDK's typed union is
// handled above, so `message` narrows to never here — a new SDK
// release adding a subtype fails this typecheck instead of silently
// warning at runtime. The runtime fallback still catches undeclared
// wire-only subtypes (like background_tasks_changed used to be).
message satisfies never;
const unknownMessage = message as never as { subtype: string };
yield* emitRuntimeWarning(
context,
describeUnknownSdkMessage(`Claude system message '${message.subtype}'`, message),
describeUnknownSdkMessage(`Claude system message '${unknownMessage.subtype}'`, message),
message,
);
return;
}
}
});
@@ -2879,13 +2948,21 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
case "rate_limit_event":
yield* handleSdkTelemetryMessage(context, message);
return;
default:
// Composer prompt suggestions have no T3 surface; consumed deliberately.
case "prompt_suggestion":
return;
default: {
// Exhaustiveness guard (see handleSystemMessage): new SDK top-level
// message types fail typecheck here instead of warning at runtime.
message satisfies never;
const unknownMessage = message as never as { type: string };
yield* emitRuntimeWarning(
context,
describeUnknownSdkMessage(`Claude SDK message '${message.type}'`, message),
describeUnknownSdkMessage(`Claude SDK message '${unknownMessage.type}'`, message),
message,
);
return;
}
}
});
@@ -76,8 +76,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
],
}),
],
@@ -162,8 +162,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
],
}),
],
@@ -214,6 +214,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
// Sonnet is 200k-default in Claude Code (1M is opt-in there too).
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
@@ -243,6 +244,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
// Sonnet is 200k-default in Claude Code (1M is opt-in there too).
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
@@ -369,8 +371,22 @@ export function isClaudeUltracodeEffort(effort: string | null | undefined): bool
return effort === "ultracode";
}
export function resolveClaudeContextWindow(
modelSelection: ModelSelection | undefined,
): string | undefined {
const caps = getClaudeModelCapabilities(modelSelection?.model);
const raw = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
const descriptors = getProviderOptionDescriptors({
caps,
...(raw ? { selections: [{ id: "contextWindow", value: raw }] } : {}),
});
const descriptor = descriptors.find((candidate) => candidate.id === "contextWindow");
const value = getProviderOptionCurrentValue(descriptor);
return typeof value === "string" ? value : undefined;
}
export function resolveClaudeApiModelId(modelSelection: ModelSelection): string {
switch (getModelSelectionStringOptionValue(modelSelection, "contextWindow")) {
switch (resolveClaudeContextWindow(modelSelection)) {
case "1m":
return `${modelSelection.model}[1m]`;
default:
@@ -1136,6 +1136,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
NodeAssert.deepEqual(firstEvent.value.payload.usage, {
usedTokens: 126,
totalProcessedTokens: 11_839,
totalInputTokens: 11_833,
totalCachedInputTokens: 3456,
totalOutputTokens: 6,
totalReasoningOutputTokens: 0,
maxTokens: 258_400,
inputTokens: 120,
cachedInputTokens: 0,
@@ -1148,6 +1152,9 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
lastReasoningOutputTokens: 0,
compactsAutomatically: true,
});
// The Codex-native thread id must ride providerRefs so usage accounting
// can separate concurrent provider sessions on one canonical thread.
NodeAssert.equal(firstEvent.value.providerRefs?.providerSessionId, "thread-1");
}),
);
});
@@ -168,9 +168,17 @@ function normalizeCodexTokenUsage(
const cachedInputTokens = usage.last.cachedInputTokens;
const outputTokens = usage.last.outputTokens;
const reasoningOutputTokens = usage.last.reasoningOutputTokens;
const totalInputTokens = usage.total.inputTokens;
const totalCachedInputTokens = usage.total.cachedInputTokens;
const totalOutputTokens = usage.total.outputTokens;
const totalReasoningOutputTokens = usage.total.reasoningOutputTokens;
return {
usedTokens,
...(totalInputTokens !== undefined ? { totalInputTokens } : {}),
...(totalCachedInputTokens !== undefined ? { totalCachedInputTokens } : {}),
...(totalOutputTokens !== undefined ? { totalOutputTokens } : {}),
...(totalReasoningOutputTokens !== undefined ? { totalReasoningOutputTokens } : {}),
...(totalProcessedTokens !== undefined && totalProcessedTokens > usedTokens
? { totalProcessedTokens }
: {}),
@@ -741,10 +749,17 @@ function mapToRuntimeEvents(
if (!normalizedUsage) {
return [];
}
const base = runtimeEventBase(event, canonicalThreadId);
// The Codex-native thread id disambiguates cumulative counters when
// several provider sessions (subagents) share one canonical T3 thread.
const nativeThreadId = payload?.threadId;
return [
{
type: "thread.token-usage.updated",
...runtimeEventBase(event, canonicalThreadId),
...base,
...(nativeThreadId
? { providerRefs: { ...base.providerRefs, providerSessionId: nativeThreadId } }
: {}),
payload: {
usage: normalizedUsage,
},
@@ -1,6 +1,6 @@
import { assert, it } from "@effect/vitest";
import { mapCodexModelCapabilities } from "./CodexProvider.ts";
import { applyPreferredCodexDefaultModel, mapCodexModelCapabilities } from "./CodexProvider.ts";
it("maps current Codex model capability fields", () => {
const capabilities = mapCodexModelCapabilities({
@@ -102,3 +102,45 @@ it("uses standard routing when the catalog has no default service tier", () => {
},
]);
});
it("marks the most preferred available model as default", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.6-terra", name: "GPT-5.6-Terra", isCustom: false, capabilities: null },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
]);
assert.deepStrictEqual(
models.map((model) => ({ slug: model.slug, isDefault: model.isDefault })),
[
{ slug: "gpt-5.6-terra", isDefault: true },
{ slug: "gpt-5.4", isDefault: undefined },
],
);
});
it("prefers sol over terra when both are available", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.6-terra", name: "GPT-5.6-Terra", isCustom: false, capabilities: null },
{ slug: "gpt-5.6-sol", name: "GPT-5.6-Sol", isCustom: false, capabilities: null },
]);
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.6-sol");
});
it("keeps Codex's own default when no preferred model is available", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.5", name: "GPT-5.5", isCustom: false, capabilities: null },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
]);
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.4");
});
it("ignores custom models that shadow a preferred slug", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.6-sol", name: "gpt-5.6-sol", isCustom: true, capabilities: null },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
]);
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.4");
});
@@ -22,7 +22,7 @@ import type {
ServerProviderModel,
ServerProviderSkill,
} from "@t3tools/contracts";
import { ServerSettingsError } from "@t3tools/contracts";
import { PREFERRED_DEFAULT_CODEX_MODELS, ServerSettingsError } from "@t3tools/contracts";
import { createModelCapabilities } from "@t3tools/shared/model";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
@@ -189,10 +189,36 @@ function parseCodexModelListResponse(
slug: model.model,
name: toDisplayName(model),
isCustom: false,
...(model.isDefault ? { isDefault: true } : {}),
capabilities: mapCodexModelCapabilities(model),
}));
}
/**
* Prefer our own default-model ranking when one of the preferred slugs is in
* the live catalog; otherwise keep whatever Codex itself flagged as default.
*/
export function applyPreferredCodexDefaultModel(
models: ReadonlyArray<ServerProviderModel>,
): ReadonlyArray<ServerProviderModel> {
const preferredSlug = PREFERRED_DEFAULT_CODEX_MODELS.find((slug) =>
models.some((model) => model.slug === slug && !model.isCustom),
);
if (!preferredSlug) {
return models;
}
return models.map((model) => {
if (model.slug === preferredSlug) {
return model.isDefault ? model : { ...model, isDefault: true };
}
if (!model.isDefault) {
return model;
}
const { isDefault: _isDefault, ...rest } = model;
return rest;
});
}
function appendCustomCodexModels(
models: ReadonlyArray<ServerProviderModel>,
customModels: ReadonlyArray<string>,
@@ -376,7 +402,9 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
return {
account: accountResponse,
version,
models: appendCustomCodexModels(models, input.customModels ?? []),
models: applyPreferredCodexDefaultModel(
appendCustomCodexModels(models, input.customModels ?? []),
),
skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
} satisfies CodexAppServerProviderSnapshot;
});
+27 -17
View File
@@ -80,6 +80,7 @@ import * as ExternalLauncher from "./process/externalLauncher.ts";
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
import { OrchestrationListenerCallbackError } from "./orchestration/Errors.ts";
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import { ProjectionUsageRepository } from "./persistence/Services/ProjectionUsage.ts";
import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.ts";
import { PersistenceSqlError } from "./persistence/Errors.ts";
import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts";
@@ -713,23 +714,32 @@ const buildAppUnderTest = (options?: {
}),
),
Layer.provide(
Layer.mock(CheckpointDiffQuery.CheckpointDiffQuery)({
getTurnDiff: () =>
Effect.succeed({
threadId: defaultThreadId,
fromTurnCount: 0,
toTurnCount: 0,
diff: "",
}),
getFullThreadDiff: () =>
Effect.succeed({
threadId: defaultThreadId,
fromTurnCount: 0,
toTurnCount: 0,
diff: "",
}),
...options?.layers?.checkpointDiffQuery,
}),
Layer.mergeAll(
Layer.mock(ProjectionUsageRepository)({
upsertFact: () => Effect.void,
redactThread: () => Effect.void,
listFacts: () => Effect.succeed([]),
earliestObservedAt: () => Effect.succeed(null),
sumBySessionModel: () => Effect.succeed([]),
}),
Layer.mock(CheckpointDiffQuery.CheckpointDiffQuery)({
getTurnDiff: () =>
Effect.succeed({
threadId: defaultThreadId,
fromTurnCount: 0,
toTurnCount: 0,
diff: "",
}),
getFullThreadDiff: () =>
Effect.succeed({
threadId: defaultThreadId,
fromTurnCount: 0,
toTurnCount: 0,
diff: "",
}),
...options?.layers?.checkpointDiffQuery,
}),
),
),
);
@@ -596,6 +596,26 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
}),
);
it.effect("marks the origin default ref as default when no local copy exists", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
const { initialBranch } = yield* initRepoWithCommit(cwd);
yield* git(remote, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", remote]);
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
yield* git(cwd, ["remote", "set-head", "origin", initialBranch]);
yield* git(cwd, ["checkout", "-b", "feature/only-local"]);
yield* git(cwd, ["branch", "-D", initialBranch]);
const driver = yield* GitVcsDriver.GitVcsDriver;
const refs = yield* driver.listRefs({ cwd });
const remoteDefault = refs.refs.find((ref) => ref.name === `origin/${initialBranch}`);
assert.equal(remoteDefault?.isRemote, true);
assert.equal(remoteDefault?.isDefault, true);
}),
);
it.effect("creates, checks out, renames, and lists refs", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
+14 -2
View File
@@ -2217,7 +2217,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
name: refName.name,
current: false,
isRemote: true,
isDefault: false,
// origin/HEAD's target is the repo default even when no local
// copy of the default branch exists.
isDefault:
defaultBranch !== null &&
parsedRemoteRef?.remoteName === "origin" &&
parsedRemoteRef.branchName === defaultBranch,
worktreePath: null,
};
if (parsedRemoteRef) {
@@ -2232,9 +2237,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
})
: [];
const allBranches = input.includeMatchingRemoteRefs
const combinedBranches = input.includeMatchingRemoteRefs
? [...localBranches, ...remoteBranches]
: dedupeRemoteBranchesWithLocalMatches([...localBranches, ...remoteBranches]);
// Keep current/default refs on the first page even when the default
// only exists as origin/<default> (remote refs sort after all locals).
const allBranches = combinedBranches.toSorted((a, b) => {
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
return aPriority - bPriority;
});
const branchesForKind =
input.refKind === "local"
? allBranches.filter((ref) => !ref.isRemote)
+36
View File
@@ -71,6 +71,8 @@ import * as ExternalLauncher from "./process/externalLauncher.ts";
import { normalizeDispatchCommand } from "./orchestration/Normalizer.ts";
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import { ProjectionUsageRepository } from "./persistence/Services/ProjectionUsage.ts";
import { summarizeUsageFacts } from "./orchestration/usageSummary.ts";
import {
observeRpcEffect as instrumentRpcEffect,
observeRpcStream as instrumentRpcStream,
@@ -302,6 +304,7 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
[WS_METHODS.serverUpdateSettings, AuthOrchestrationOperateScope],
[WS_METHODS.serverDiscoverSourceControl, AuthOrchestrationReadScope],
[WS_METHODS.serverGetTraceDiagnostics, AuthOrchestrationReadScope],
[WS_METHODS.usageGetSummary, AuthOrchestrationReadScope],
[WS_METHODS.serverGetProcessDiagnostics, AuthOrchestrationReadScope],
[WS_METHODS.serverGetProcessResourceHistory, AuthOrchestrationReadScope],
[WS_METHODS.serverSignalProcess, AuthOrchestrationOperateScope],
@@ -405,6 +408,7 @@ const makeWsRpcLayer = (
const currentSessionId = currentSession.sessionId;
const crypto = yield* Crypto.Crypto;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const projectionUsageRepository = yield* ProjectionUsageRepository;
const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery;
const keybindings = yield* Keybindings.Keybindings;
@@ -1533,6 +1537,38 @@ const makeWsRpcLayer = (
"rpc.aggregate": "server",
},
),
[WS_METHODS.usageGetSummary]: (input) =>
observeRpcEffect(
WS_METHODS.usageGetSummary,
Effect.gen(function* () {
const facts = yield* projectionUsageRepository.listFacts({
...(input.since !== undefined ? { sinceIso: input.since } : {}),
...(input.until !== undefined ? { untilIso: input.until } : {}),
});
const earliestFactAt = yield* projectionUsageRepository.earliestObservedAt();
const projectIds = [
...new Set(facts.flatMap((fact) => (fact.projectId ? [fact.projectId] : []))),
];
const projectTitles = new Map<string, string | null>();
yield* Effect.forEach(
projectIds,
(projectId) =>
projectionSnapshotQuery.getProjectShellById(projectId).pipe(
Effect.map((shell) => {
projectTitles.set(projectId, Option.isSome(shell) ? shell.value.title : null);
}),
),
{ concurrency: 4 },
);
return summarizeUsageFacts({
facts,
timeZone: input.timeZone,
earliestFactAt,
projectTitle: (projectId: string) => projectTitles.get(projectId) ?? null,
});
}).pipe(Effect.orDie),
{ "rpc.aggregate": "usage" },
),
[WS_METHODS.serverGetProcessDiagnostics]: (_input) =>
observeRpcEffect(WS_METHODS.serverGetProcessDiagnostics, processDiagnostics.read, {
"rpc.aggregate": "server",
@@ -12,6 +12,7 @@ import {
resolveBranchToolbarValue,
resolveLockedWorkspaceLabel,
shouldIncludeBranchPickerItem,
shouldShowEnvironmentIndicator,
} from "./BranchToolbar.logic";
const localEnvironmentId = EnvironmentId.make("environment-local");
@@ -119,6 +120,44 @@ describe("resolveEnvironmentOptionLabel", () => {
});
});
describe("shouldShowEnvironmentIndicator", () => {
it("shows the indicator whenever multiple environments are pickable", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: { isPrimary: true },
canPickEnvironment: true,
}),
).toBe(true);
});
it("shows a sole remote environment so the user knows where the project runs", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: { isPrimary: false },
canPickEnvironment: false,
}),
).toBe(true);
});
it("hides a sole primary (this-device) environment", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: { isPrimary: true },
canPickEnvironment: false,
}),
).toBe(false);
});
it("hides the indicator when the active environment is unknown", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: null,
canPickEnvironment: false,
}),
).toBe(false);
});
});
describe("resolveEffectiveEnvMode", () => {
it("treats draft threads already attached to a worktree as current-checkout mode", () => {
expect(
@@ -42,6 +42,17 @@ export function resolveEnvironmentOptionLabel(input: {
return runtimeLabel ?? savedLabel ?? input.environmentId;
}
// A remote (non-primary) environment is always surfaced, even when it is the
// only environment available: with a single connected machine there is nothing
// to pick, but the user still needs to see where the project runs.
export function shouldShowEnvironmentIndicator(input: {
activeEnvironment: Pick<EnvironmentOption, "isPrimary"> | null;
canPickEnvironment: boolean;
}): boolean {
if (input.canPickEnvironment) return true;
return input.activeEnvironment !== null && !input.activeEnvironment.isPrimary;
}
export function resolveEnvModeLabel(mode: EnvMode): string {
return mode === "worktree" ? "New worktree" : "Current checkout";
}
+14 -4
View File
@@ -20,6 +20,7 @@ import {
resolveEnvModeLabel,
resolveEffectiveEnvMode,
resolveLockedWorkspaceLabel,
shouldShowEnvironmentIndicator,
} from "./BranchToolbar.logic";
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector";
@@ -60,6 +61,7 @@ interface MobileRunContextSelectorProps {
environmentId: EnvironmentId;
availableEnvironments: readonly EnvironmentOption[] | undefined;
showEnvironmentPicker: boolean;
showEnvironmentIndicator: boolean;
onEnvironmentChange: ((environmentId: EnvironmentId) => void) | undefined;
effectiveEnvMode: EnvMode;
activeWorktreePath: string | null;
@@ -72,6 +74,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
environmentId,
availableEnvironments,
showEnvironmentPicker,
showEnvironmentIndicator,
onEnvironmentChange,
effectiveEnvMode,
activeWorktreePath,
@@ -94,7 +97,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
: resolveCurrentWorkspaceLabel(activeWorktreePath);
const isLocked = envLocked || envModeLocked;
const EnvironmentIcon = activeEnvironment?.isPrimary ? MonitorIcon : CloudIcon;
const icon = showEnvironmentPicker ? (
const icon = showEnvironmentIndicator ? (
// Button's base styles apply `-mx-0.5` to descendant SVGs, which eats 4px
// out of whatever gap we set. mx-0! cancels that so gap-0.5 reads as 2px.
<span className="inline-flex shrink-0 items-center gap-0.5">
@@ -108,7 +111,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
<>
{icon}
<span className="min-w-0 truncate">
{showEnvironmentPicker ? (activeEnvironment?.label ?? "Run on") : workspaceLabel}
{showEnvironmentIndicator ? (activeEnvironment?.label ?? "Run on") : workspaceLabel}
</span>
</>
);
@@ -234,6 +237,12 @@ export const BranchToolbar = memo(function BranchToolbar({
const showEnvironmentPicker = Boolean(
availableEnvironments && availableEnvironments.length > 1 && onEnvironmentChange,
);
const activeEnvironmentOption =
availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null;
const showEnvironmentIndicator = shouldShowEnvironmentIndicator({
activeEnvironment: activeEnvironmentOption,
canPickEnvironment: showEnvironmentPicker,
});
const isMobile = useIsMobile();
if (!hasActiveThread || !activeProject) return null;
@@ -247,6 +256,7 @@ export const BranchToolbar = memo(function BranchToolbar({
environmentId={environmentId}
availableEnvironments={availableEnvironments}
showEnvironmentPicker={showEnvironmentPicker}
showEnvironmentIndicator={showEnvironmentIndicator}
onEnvironmentChange={onEnvironmentChange}
effectiveEnvMode={effectiveEnvMode}
activeWorktreePath={activeWorktreePath}
@@ -254,13 +264,13 @@ export const BranchToolbar = memo(function BranchToolbar({
/>
) : (
<div className="flex min-w-0 shrink-0 items-center gap-1">
{showEnvironmentPicker && availableEnvironments && onEnvironmentChange && (
{showEnvironmentIndicator && availableEnvironments && (
<>
<BranchToolbarEnvironmentSelector
envLocked={envLocked}
environmentId={environmentId}
availableEnvironments={availableEnvironments}
onEnvironmentChange={onEnvironmentChange}
{...(showEnvironmentPicker && onEnvironmentChange ? { onEnvironmentChange } : {})}
/>
<Separator orientation="vertical" className="mx-0.5 h-3.5!" />
</>
@@ -422,17 +422,32 @@ export function BranchToolbarBranchSelector({
});
};
// Default the worktree base to the repo default branch (origin/HEAD), only
// falling back to the checked-out branch when no default is known.
const defaultBranchName = useMemo(
() => refs.find((refName) => refName.isDefault)?.name ?? null,
[refs],
);
const worktreeBaseBranchCandidate = isInitialBranchesLoadPending
? null
: (defaultBranchName ?? currentGitBranch);
useEffect(() => {
if (
effectiveEnvMode !== "worktree" ||
activeWorktreePath ||
activeThreadBranch ||
!currentGitBranch
!worktreeBaseBranchCandidate
) {
return;
}
setThreadBranch(currentGitBranch, null);
}, [activeThreadBranch, activeWorktreePath, currentGitBranch, effectiveEnvMode, setThreadBranch]);
setThreadBranch(worktreeBaseBranchCandidate, null);
}, [
activeThreadBranch,
activeWorktreePath,
effectiveEnvMode,
setThreadBranch,
worktreeBaseBranchCandidate,
]);
// ---------------------------------------------------------------------------
// Combobox / list plumbing
@@ -17,7 +17,9 @@ interface BranchToolbarEnvironmentSelectorProps {
envLocked: boolean;
environmentId: EnvironmentId;
availableEnvironments: readonly EnvironmentOption[];
onEnvironmentChange: (environmentId: EnvironmentId) => void;
// Absent when there is only one environment to show: the indicator still
// renders (as a static label) so remote projects are always identifiable.
onEnvironmentChange?: (environmentId: EnvironmentId) => void;
}
export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvironmentSelector({
@@ -39,7 +41,7 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
[availableEnvironments],
);
if (envLocked) {
if (envLocked || onEnvironmentChange === undefined) {
return (
<span className="inline-flex items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
{activeEnvironment?.isPrimary ? (
+8 -12
View File
@@ -1159,6 +1159,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isSendBusy ||
isConnecting ||
projectSelectionRequired ||
environmentUnavailable !== null ||
!composerSendState.hasSendableContent;
const collapsedComposerPrimaryActionLabel = "Send message";
const showMobilePendingAnswerActions =
@@ -1697,7 +1698,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const shouldBlurMobileComposerOnSubmit = useCallback(() => {
if (!isMobileViewport) return false;
if (isSendBusy || isConnecting || phase === "running") return false;
if (isSendBusy || isConnecting || environmentUnavailable !== null || phase === "running") {
return false;
}
if (activePendingProgress) {
return activePendingProgress.isLastQuestion && Boolean(activePendingResolvedAnswers);
}
@@ -1706,6 +1709,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
activePendingProgress,
activePendingResolvedAnswers,
composerSendState.hasSendableContent,
environmentUnavailable,
isConnecting,
isMobileViewport,
isSendBusy,
@@ -1892,8 +1896,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isConnecting ||
isComposerApprovalState ||
pendingUserInputs.length > 0 ||
projectSelectionRequired ||
(environmentUnavailable !== null && activePendingProgress === null)
projectSelectionRequired
) {
return false;
}
@@ -2101,8 +2104,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isComposerApprovalState,
pendingUserInputs.length,
projectSelectionRequired,
environmentUnavailable,
activePendingProgress,
applyPromptReplacement,
isComposerModelPickerOpen,
readComposerSnapshot,
@@ -2144,7 +2145,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
className={cn(
"chat-composer-glass rounded-[20px] border transition-[background-color] duration-200 has-focus-visible:border-ring/45",
isDragOverComposer ? "border-primary/70 bg-accent/45" : "border-border",
environmentUnavailable || projectSelectionRequired ? "opacity-75" : null,
projectSelectionRequired ? "opacity-75" : null,
composerProviderState.composerSurfaceClassName,
)}
onFocusCapture={(event) => {
@@ -2502,12 +2503,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
? "Ask for follow-up changes or attach images"
: "Ask anything, @tag files/folders, $use skills, or / for commands"
}
disabled={
isConnecting ||
isComposerApprovalState ||
projectSelectionRequired ||
(environmentUnavailable !== null && activePendingProgress === null)
}
disabled={isConnecting || isComposerApprovalState || projectSelectionRequired}
/>
{showMobilePendingAnswerActions ? (
<div
@@ -3,6 +3,7 @@ import {
ArchiveIcon,
ArrowLeftIcon,
BotIcon,
ChartColumnIcon,
GitBranchIcon,
KeyboardIcon,
Link2Icon,
@@ -28,6 +29,7 @@ export type SettingsSectionPath =
| "/settings/providers"
| "/settings/source-control"
| "/settings/connections"
| "/settings/usage"
| "/settings/archived";
export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
@@ -40,6 +42,7 @@ export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
{ label: "Providers", to: "/settings/providers", icon: BotIcon },
{ label: "Source Control", to: "/settings/source-control", icon: GitBranchIcon },
{ label: "Connections", to: "/settings/connections", icon: Link2Icon },
{ label: "Usage", to: "/settings/usage", icon: ChartColumnIcon },
{ label: "Archive", to: "/settings/archived", icon: ArchiveIcon },
];
@@ -0,0 +1,605 @@
import { useMemo } from "react";
import type { UsageDailyBucket, UsageModelBucket, UsageSummaryResponse } from "@t3tools/contracts";
import { cn } from "../../lib/utils";
import { useEnvironmentQuery } from "../../state/query";
import { serverEnvironment } from "../../state/server";
import { usePrimaryEnvironment } from "../../state/environments";
import { ClaudeAI, OpenAI } from "../Icons";
import { Button } from "../ui/button";
import { SettingsPageContainer, SettingsSection } from "./settingsLayout";
// Family color system from the approved mock: hue = harness, lightness =
// model within the family. Codex renders as off-white on dark surfaces.
const CLAUDE_COLOR = "#cf6b48";
const CODEX_COLOR = "#e8e8e3";
const harnessColor = (provider: string): string =>
provider === "claudeAgent" ? CLAUDE_COLOR : CODEX_COLOR;
const CLAUDE_MODEL_SHADES = ["#cf6b48", "#f2c1a4", "#a3492a"];
const CODEX_MODEL_SHADES = ["#e8e8e3", "#9c9c96"];
const NEUTRAL_SHADE = "#8a8880";
const T3_ACCENT = "#9085e9";
function isClaudeProvider(provider: string): boolean {
return provider === "claudeAgent";
}
function formatTokens(value: number): string {
if (value >= 1_000_000_000) return `${(value / 1_000_000_000).toFixed(2)}B`;
if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
if (value >= 1_000) return `${(value / 1_000).toFixed(0)}K`;
return `${value}`;
}
function formatMicroUsd(micro: number): string {
const usd = micro / 1_000_000;
if (usd >= 100) return `$${Math.round(usd).toLocaleString()}`;
return `$${usd.toFixed(2)}`;
}
function providerLogo(provider: string, className?: string) {
return isClaudeProvider(provider) ? (
<ClaudeAI className={cn("size-3.5 shrink-0", className)} />
) : (
<OpenAI className={cn("size-3.5 shrink-0", className)} />
);
}
interface DonutSlice {
readonly key: string;
readonly value: number;
readonly color: string;
readonly estimated?: boolean;
readonly groupColor: string;
readonly groupShare: number;
readonly groupStart: boolean;
}
function assignModelShades(models: ReadonlyArray<UsageModelBucket>): Map<string, string> {
const shades = new Map<string, string>();
let claudeIndex = 0;
let codexIndex = 0;
for (const bucket of models) {
if (isClaudeProvider(bucket.provider)) {
shades.set(bucket.model, CLAUDE_MODEL_SHADES[claudeIndex] ?? NEUTRAL_SHADE);
claudeIndex += 1;
} else {
shades.set(bucket.model, CODEX_MODEL_SHADES[codexIndex] ?? NEUTRAL_SHADE);
codexIndex += 1;
}
}
return shades;
}
function Donut({
slices,
center,
centerSub,
ariaLabel,
}: {
slices: ReadonlyArray<DonutSlice>;
center: string;
centerSub: string;
ariaLabel: string;
}) {
const total = slices.reduce((sum, slice) => sum + slice.value, 0);
const cx = 150;
const cy = 150;
const outer = 140;
const inner = 96;
const tau = Math.PI * 2;
const point = (angle: number, radius: number) =>
`${(cx + Math.cos(angle) * radius).toFixed(2)} ${(cy + Math.sin(angle) * radius).toFixed(2)}`;
let angle = -Math.PI / 2;
const paths: Array<{ d: string; color: string; estimated: boolean; title: string }> = [];
const labels: Array<{ x: number; y: number; text: string; dark: boolean }> = [];
let groupStartAngle = angle;
for (const slice of slices) {
if (slice.groupStart) {
groupStartAngle = angle;
}
const sweep = total > 0 ? (slice.value / total) * tau : 0;
const end = angle + sweep;
const gap = Math.min(0.014, sweep * 0.3);
const from = angle + gap / 2;
const to = end - gap / 2;
if (to > from) {
const large = to - from > Math.PI ? 1 : 0;
paths.push({
d: `M ${point(from, outer)} A ${outer} ${outer} 0 ${large} 1 ${point(to, outer)} L ${point(to, inner)} A ${inner} ${inner} 0 ${large} 0 ${point(from, inner)} Z`,
color: slice.color,
estimated: slice.estimated ?? false,
title: slice.key,
});
}
angle = end;
const groupShare = slice.groupShare;
const isGroupEnd =
slices.indexOf(slice) === slices.length - 1 || slices[slices.indexOf(slice) + 1]?.groupStart;
if (isGroupEnd && groupShare >= 0.08) {
const mid = (groupStartAngle + angle) / 2;
const radius = (outer + inner) / 2;
const hex = slice.groupColor.replace("#", "");
const luminance =
parseInt(hex.slice(0, 2), 16) * 0.299 +
parseInt(hex.slice(2, 4), 16) * 0.587 +
parseInt(hex.slice(4, 6), 16) * 0.114;
labels.push({
x: cx + Math.cos(mid) * radius,
y: cy + Math.sin(mid) * radius,
text: `${Math.round(groupShare * 100)}%`,
dark: luminance > 150,
});
}
}
return (
<div className="relative mx-auto w-full max-w-[270px]">
<svg viewBox="0 0 300 300" role="img" aria-label={ariaLabel}>
<defs>
<pattern
id="usage-est-stripes"
patternUnits="userSpaceOnUse"
width="7"
height="7"
patternTransform="rotate(45)"
>
<line x1="0" y1="0" x2="0" y2="7" stroke="rgba(0,0,0,0.35)" strokeWidth="2.5" />
</pattern>
</defs>
{paths.map((path) => (
<g key={path.title + path.d.slice(0, 24)}>
<path d={path.d} fill={path.color}>
<title>{path.title}</title>
</path>
{path.estimated ? <path d={path.d} fill="url(#usage-est-stripes)" /> : null}
</g>
))}
{labels.map((label) => (
<text
key={`${label.x}-${label.y}`}
x={label.x}
y={label.y}
textAnchor="middle"
dominantBaseline="middle"
style={{ fill: label.dark ? "#1a1a19" : "#fff", fontSize: 15, fontWeight: 680 }}
>
{label.text}
</text>
))}
</svg>
<div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center">
<div className="text-3xl font-semibold tracking-tight">{center}</div>
<div className="mt-1 text-[11px] text-muted-foreground">{centerSub}</div>
</div>
</div>
);
}
function DailyBars({ daily }: { daily: ReadonlyArray<UsageDailyBucket> }) {
const byDay = useMemo(() => {
const map = new Map<string, Array<UsageDailyBucket>>();
for (const bucket of daily) {
const list = map.get(bucket.day) ?? [];
list.push(bucket);
map.set(bucket.day, list);
}
return [...map.entries()].sort((a, b) => a[0].localeCompare(b[0]));
}, [daily]);
const maxDay = Math.max(
1,
...byDay.map(([, buckets]) => buckets.reduce((sum, bucket) => sum + bucket.totalTokens, 0)),
);
if (byDay.length === 0) {
return null;
}
return (
<div className="flex h-40 items-end gap-[3px] overflow-x-auto rounded-md bg-black/20 p-3">
{byDay.map(([day, buckets]) => {
const dayTotal = buckets.reduce((sum, bucket) => sum + bucket.totalTokens, 0);
return (
<div
key={day}
className="flex min-w-[14px] flex-1 flex-col-reverse gap-px"
title={`${day}: ${formatTokens(dayTotal)} tokens`}
>
{buckets.map((bucket) => (
<div
key={`${day}-${bucket.provider}-${bucket.model}`}
style={{
height: `${Math.max((bucket.totalTokens / maxDay) * 100, 1.5)}%`,
background: harnessColor(bucket.provider),
}}
className="w-full rounded-[2px]"
/>
))}
</div>
);
})}
</div>
);
}
function HourHeatmap({ summary }: { summary: UsageSummaryResponse }) {
const grid = useMemo(() => {
const cells = new Map<string, number>();
let max = 0;
for (const bucket of summary.hourOfWeek) {
cells.set(`${bucket.dayOfWeek}-${bucket.hour}`, bucket.turns);
max = Math.max(max, bucket.turns);
}
return { cells, max: Math.max(max, 1) };
}, [summary.hourOfWeek]);
const dayLabels = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
return (
<div className="overflow-x-auto">
<div className="grid min-w-[560px] grid-cols-[34px_repeat(24,1fr)] gap-[2px]">
<div />
{Array.from({ length: 24 }, (_, hour) => (
<div key={hour} className="text-center text-[9px] text-muted-foreground">
{hour % 6 === 0
? hour === 0
? "12a"
: hour < 12
? `${hour}a`
: hour === 12
? "12p"
: `${hour - 12}p`
: ""}
</div>
))}
{dayLabels.map((label, dayOfWeek) => (
<>
<div key={label} className="self-center text-[10px] text-muted-foreground">
{label}
</div>
{Array.from({ length: 24 }, (_, hour) => {
const turns = grid.cells.get(`${dayOfWeek}-${hour}`) ?? 0;
const alpha = turns === 0 ? 0 : 0.18 + 0.82 * Math.sqrt(turns / grid.max);
return (
<div
key={`${label}-${hour}`}
title={`${label} ${hour}:00 — ${turns} turn${turns === 1 ? "" : "s"}`}
className="aspect-[1.5] min-w-[14px] rounded-[3px]"
style={{
background:
turns === 0
? "rgba(255,255,255,0.03)"
: `rgba(144,133,233,${alpha.toFixed(2)})`,
}}
/>
);
})}
</>
))}
</div>
</div>
);
}
export function UsageSettingsPanel() {
const primaryEnvironment = usePrimaryEnvironment();
const environmentId = primaryEnvironment?.environmentId ?? null;
const timeZone = useMemo(() => Intl.DateTimeFormat().resolvedOptions().timeZone, []);
const { data, error, isPending, refresh } = useEnvironmentQuery(
environmentId === null
? null
: serverEnvironment.usageSummary({ environmentId, input: { timeZone } }),
);
const summary = data ?? null;
const modelShades = useMemo(
() => (summary ? assignModelShades(summary.byModel) : new Map<string, string>()),
[summary],
);
const tokenSlices = useMemo(() => {
if (!summary) return [];
const claude = summary.byModel.filter((bucket) => isClaudeProvider(bucket.provider));
const codex = summary.byModel.filter((bucket) => !isClaudeProvider(bucket.provider));
const total = Math.max(summary.totals.totalTokens, 1);
const groupTotal = (buckets: ReadonlyArray<UsageModelBucket>) =>
buckets.reduce((sum, bucket) => sum + bucket.totalTokens, 0);
const slices: Array<DonutSlice> = [];
for (const [group, groupColor] of [
[claude, CLAUDE_COLOR],
[codex, CODEX_COLOR],
] as const) {
group.forEach((bucket, index) => {
slices.push({
key: `${bucket.model}: ${formatTokens(bucket.totalTokens)} tokens`,
value: bucket.totalTokens,
color: modelShades.get(bucket.model) ?? NEUTRAL_SHADE,
groupColor,
groupShare: groupTotal(group) / total,
groupStart: index === 0,
});
});
}
return slices;
}, [summary, modelShades]);
const costSlices = useMemo(() => {
if (!summary) return [];
const priced = summary.byModel.filter(
(bucket) => bucket.exactCostMicroUsd > 0 || bucket.estimatedCostMicroUsd > 0,
);
const claude = priced.filter((bucket) => isClaudeProvider(bucket.provider));
const codex = priced.filter((bucket) => !isClaudeProvider(bucket.provider));
const total = Math.max(
priced.reduce(
(sum, bucket) => sum + bucket.exactCostMicroUsd + bucket.estimatedCostMicroUsd,
0,
),
1,
);
const groupTotal = (buckets: ReadonlyArray<UsageModelBucket>) =>
buckets.reduce(
(sum, bucket) => sum + bucket.exactCostMicroUsd + bucket.estimatedCostMicroUsd,
0,
);
const slices: Array<DonutSlice> = [];
for (const [group, groupColor] of [
[claude, CLAUDE_COLOR],
[codex, CODEX_COLOR],
] as const) {
group.forEach((bucket, index) => {
const value = bucket.exactCostMicroUsd + bucket.estimatedCostMicroUsd;
const estimated = bucket.exactCostMicroUsd === 0;
slices.push({
key: `${bucket.model}: ${formatMicroUsd(value)}${estimated ? " (est.)" : ""}`,
value,
color: modelShades.get(bucket.model) ?? NEUTRAL_SHADE,
estimated,
groupColor,
groupShare: groupTotal(group) / total,
groupStart: index === 0,
});
});
}
return slices;
}, [summary, modelShades]);
if (environmentId === null) {
return (
<SettingsPageContainer>
<UsagePageHeader />
<p className="text-sm text-muted-foreground">Connect an environment to see usage.</p>
</SettingsPageContainer>
);
}
if (isPending && !summary) {
return (
<SettingsPageContainer>
<UsagePageHeader />
<p className="text-sm text-muted-foreground">Loading usage…</p>
</SettingsPageContainer>
);
}
if (error || !summary) {
return (
<SettingsPageContainer>
<UsagePageHeader />
<div>
<p className="text-sm text-muted-foreground">Could not load usage data.</p>
<Button variant="outline" size="sm" className="mt-3" onClick={() => refresh()}>
Retry
</Button>
</div>
</SettingsPageContainer>
);
}
const exactCost = summary.totals.exactCostMicroUsd;
const estimatedCost = summary.totals.estimatedCostMicroUsd;
const cacheHitRate =
summary.totals.inputTokens + summary.totals.cachedInputTokens > 0
? (summary.totals.cachedInputTokens /
(summary.totals.inputTokens +
summary.totals.cachedInputTokens +
summary.totals.cacheCreationTokens)) *
100
: 0;
return (
<SettingsPageContainer>
<UsagePageHeader />
<SettingsSection title="Overview">
<div className="grid gap-8 md:grid-cols-2">
<div>
<div className="mb-3 text-center text-[13px] font-semibold">
Tokens
<span className="block text-[11px] font-normal text-muted-foreground">
all processed, by harness
</span>
</div>
<Donut
slices={tokenSlices}
center={formatTokens(summary.totals.totalTokens)}
centerSub={
summary.earliestFactAt ? `since ${summary.earliestFactAt.slice(0, 10)}` : "all time"
}
ariaLabel="Tokens by harness and model"
/>
</div>
<div>
<div className="mb-3 text-center text-[13px] font-semibold">
Cost
<span className="block text-[11px] font-normal text-muted-foreground">
exact where metered · striped slices are list-price estimates
</span>
</div>
<Donut
slices={costSlices}
center={formatMicroUsd(exactCost + estimatedCost)}
centerSub={`${formatMicroUsd(exactCost)} exact + ${formatMicroUsd(estimatedCost)} est.`}
ariaLabel="Cost by harness and model"
/>
</div>
</div>
<div className="mt-6 grid grid-cols-2 gap-2 lg:grid-cols-5">
<StatTile
label="Output tokens"
value={formatTokens(summary.totals.outputTokens)}
sub="generated text"
/>
<StatTile label="Exact spend" value={formatMicroUsd(exactCost)} sub="provider-metered" />
<StatTile
label="Estimated value"
value={`~${formatMicroUsd(estimatedCost)}`}
sub="list price · plan-covered"
/>
<StatTile label="Turns" value={`${summary.totals.turns}`} sub="recorded in ledger" />
<StatTile
label="Cache hit rate"
value={`${cacheHitRate.toFixed(1)}%`}
sub="of input tokens"
accent
/>
</div>
</SettingsSection>
<SettingsSection title="Tokens per day">
<DailyBars daily={summary.daily} />
</SettingsSection>
<SettingsSection title="When you use T3 Code">
<p className="mb-3 text-xs text-muted-foreground">
Turn starts by local hour and weekday ({timeZone}). Darker means more turns.
</p>
<HourHeatmap summary={summary} />
</SettingsSection>
<SettingsSection title="Models">
<table className="w-full text-[13px]">
<thead>
<tr className="border-b border-border/60 text-[11px] text-muted-foreground">
<th className="py-1.5 text-left font-medium">Model</th>
<th className="py-1.5 text-right font-medium">Turns</th>
<th className="py-1.5 text-right font-medium">Tokens</th>
<th className="py-1.5 text-right font-medium">Output</th>
<th className="py-1.5 text-right font-medium">Cost</th>
</tr>
</thead>
<tbody>
{summary.byModel.map((bucket) => (
<tr key={`${bucket.provider}-${bucket.model}`} className="border-b border-border/40">
<td className="flex items-center gap-2 py-2">
{providerLogo(bucket.provider)}
<span
className="inline-block size-2.5 rounded-[3px]"
style={{ background: modelShades.get(bucket.model) ?? NEUTRAL_SHADE }}
/>
{bucket.model}
</td>
<td className="py-2 text-right tabular-nums text-muted-foreground">
{bucket.turns}
</td>
<td className="py-2 text-right tabular-nums text-muted-foreground">
{formatTokens(bucket.totalTokens)}
</td>
<td className="py-2 text-right tabular-nums text-muted-foreground">
{formatTokens(bucket.outputTokens)}
</td>
<td className="py-2 text-right tabular-nums text-muted-foreground">
{bucket.costSource === "exact"
? formatMicroUsd(bucket.exactCostMicroUsd)
: bucket.costSource === "estimated"
? `~${formatMicroUsd(bucket.estimatedCostMicroUsd)} est.`
: "—"}
</td>
</tr>
))}
</tbody>
</table>
{summary.unpricedModels.length > 0 ? (
<p className="mt-2 text-[11px] text-muted-foreground">
No pricing data for: {summary.unpricedModels.join(", ")} — shown as tokens only, never
$0.
</p>
) : null}
</SettingsSection>
<SettingsSection title="Projects">
<div className="flex flex-col gap-2">
{summary.byProject.slice(0, 8).map((bucket) => {
const max = Math.max(summary.byProject[0]?.totalTokens ?? 1, 1);
return (
<div
key={bucket.projectId ?? "none"}
className="grid grid-cols-[140px_1fr_72px] items-center gap-3 text-[12.5px]"
>
<span className="truncate text-muted-foreground">
{bucket.projectTitle ?? (bucket.projectId ? "(unknown)" : "(no project)")}
</span>
<div className="h-4 rounded bg-black/20">
<div
className="h-full rounded"
style={{
width: `${Math.max((bucket.totalTokens / max) * 100, 1.5)}%`,
background: T3_ACCENT,
}}
/>
</div>
<span className="text-right tabular-nums text-muted-foreground">
{formatTokens(bucket.totalTokens)}
</span>
</div>
);
})}
</div>
</SettingsSection>
<p className="mt-4 text-[11px] leading-relaxed text-muted-foreground">
Usage facts are recorded from live provider events into this environment's local ledger
(history begins when this feature shipped). Claude costs are exact, reported by the SDK per
turn. Codex reports no cost over its protocol; its dollars are list-price estimates and
always marked as such. Pricing catalog {summary.pricingVersion}.
</p>
</SettingsPageContainer>
);
}
function UsagePageHeader() {
return (
<div>
<h1 className="text-lg font-semibold">Usage</h1>
<p className="text-[13px] text-muted-foreground">
Local analytics from this environment's usage ledger. Nothing leaves your machines.
</p>
</div>
);
}
function StatTile({
label,
value,
sub,
accent,
}: {
label: string;
value: string;
sub: string;
accent?: boolean;
}) {
return (
<div className="rounded-lg border border-border/60 bg-black/20 px-3 py-2.5">
<div className="text-[11px] text-muted-foreground">{label}</div>
<div className={cn("text-lg font-semibold tracking-tight", accent && "text-emerald-500")}>
{value}
</div>
<div className="text-[10.5px] text-muted-foreground/80">{sub}</div>
</div>
);
}
+4
View File
@@ -75,6 +75,7 @@ export interface AppModelOption {
shortName?: string;
subProvider?: string;
isCustom: boolean;
isDefault?: boolean;
}
function toAppModelOption(model: ServerProvider["models"][number]): AppModelOption {
@@ -85,6 +86,7 @@ function toAppModelOption(model: ServerProvider["models"][number]): AppModelOpti
};
if (model.shortName) option.shortName = model.shortName;
if (model.subProvider) option.subProvider = model.subProvider;
if (model.isDefault) option.isDefault = true;
return option;
}
@@ -247,7 +249,9 @@ export function resolveAppModelSelectionForInstance(
const options = getAppModelOptionsForInstance(settings, entry);
return (
resolveSelectableModel(entry.driverKind, selectedModel, options) ??
options.find((option) => option.isDefault)?.slug ??
options[0]?.slug ??
entry.models.find((model) => model.isDefault)?.slug ??
entry.models[0]?.slug ??
null
);
+1
View File
@@ -92,6 +92,7 @@ export function getDefaultServerModel(
): string {
const models = getProviderModels(providers, provider);
return (
models.find((model) => model.isDefault && !model.isCustom)?.slug ??
models.find((model) => !model.isCustom)?.slug ??
models[0]?.slug ??
DEFAULT_MODEL_BY_PROVIDER[provider] ??
+21
View File
@@ -14,6 +14,7 @@ import { Route as PairRouteImport } from './routes/pair'
import { Route as ConnectRouteImport } from './routes/connect'
import { Route as ChatRouteImport } from './routes/_chat'
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
import { Route as SettingsUsageRouteImport } from './routes/settings.usage'
import { Route as SettingsSourceControlRouteImport } from './routes/settings.source-control'
import { Route as SettingsProvidersRouteImport } from './routes/settings.providers'
import { Route as SettingsKeybindingsRouteImport } from './routes/settings.keybindings'
@@ -49,6 +50,11 @@ const ChatIndexRoute = ChatIndexRouteImport.update({
path: '/',
getParentRoute: () => ChatRoute,
} as any)
const SettingsUsageRoute = SettingsUsageRouteImport.update({
id: '/usage',
path: '/usage',
getParentRoute: () => SettingsRoute,
} as any)
const SettingsSourceControlRoute = SettingsSourceControlRouteImport.update({
id: '/source-control',
path: '/source-control',
@@ -114,6 +120,7 @@ export interface FileRoutesByFullPath {
'/settings/keybindings': typeof SettingsKeybindingsRoute
'/settings/providers': typeof SettingsProvidersRoute
'/settings/source-control': typeof SettingsSourceControlRoute
'/settings/usage': typeof SettingsUsageRoute
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
'/draft/$draftId': typeof ChatDraftDraftIdRoute
}
@@ -129,6 +136,7 @@ export interface FileRoutesByTo {
'/settings/keybindings': typeof SettingsKeybindingsRoute
'/settings/providers': typeof SettingsProvidersRoute
'/settings/source-control': typeof SettingsSourceControlRoute
'/settings/usage': typeof SettingsUsageRoute
'/': typeof ChatIndexRoute
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
'/draft/$draftId': typeof ChatDraftDraftIdRoute
@@ -147,6 +155,7 @@ export interface FileRoutesById {
'/settings/keybindings': typeof SettingsKeybindingsRoute
'/settings/providers': typeof SettingsProvidersRoute
'/settings/source-control': typeof SettingsSourceControlRoute
'/settings/usage': typeof SettingsUsageRoute
'/_chat/': typeof ChatIndexRoute
'/_chat/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
'/_chat/draft/$draftId': typeof ChatDraftDraftIdRoute
@@ -166,6 +175,7 @@ export interface FileRouteTypes {
| '/settings/keybindings'
| '/settings/providers'
| '/settings/source-control'
| '/settings/usage'
| '/$environmentId/$threadId'
| '/draft/$draftId'
fileRoutesByTo: FileRoutesByTo
@@ -181,6 +191,7 @@ export interface FileRouteTypes {
| '/settings/keybindings'
| '/settings/providers'
| '/settings/source-control'
| '/settings/usage'
| '/'
| '/$environmentId/$threadId'
| '/draft/$draftId'
@@ -198,6 +209,7 @@ export interface FileRouteTypes {
| '/settings/keybindings'
| '/settings/providers'
| '/settings/source-control'
| '/settings/usage'
| '/_chat/'
| '/_chat/$environmentId/$threadId'
| '/_chat/draft/$draftId'
@@ -283,6 +295,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsDiagnosticsRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/usage': {
id: '/settings/usage'
path: '/usage'
fullPath: '/settings/usage'
preLoaderRoute: typeof SettingsUsageRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/connections': {
id: '/settings/connections'
path: '/connections'
@@ -343,6 +362,7 @@ interface SettingsRouteChildren {
SettingsKeybindingsRoute: typeof SettingsKeybindingsRoute
SettingsProvidersRoute: typeof SettingsProvidersRoute
SettingsSourceControlRoute: typeof SettingsSourceControlRoute
SettingsUsageRoute: typeof SettingsUsageRoute
}
const SettingsRouteChildren: SettingsRouteChildren = {
@@ -353,6 +373,7 @@ const SettingsRouteChildren: SettingsRouteChildren = {
SettingsKeybindingsRoute: SettingsKeybindingsRoute,
SettingsProvidersRoute: SettingsProvidersRoute,
SettingsSourceControlRoute: SettingsSourceControlRoute,
SettingsUsageRoute: SettingsUsageRoute,
}
const SettingsRouteWithChildren = SettingsRoute._addFileChildren(
+7
View File
@@ -0,0 +1,7 @@
import { createFileRoute } from "@tanstack/react-router";
import { UsageSettingsPanel } from "../components/settings/UsageSettings";
export const Route = createFileRoute("/settings/usage")({
component: UsageSettingsPanel,
});
File diff suppressed because it is too large. Load diff
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import {
DEFAULT_MODEL,
EnvironmentId,
ProjectId,
CommandId,
@@ -139,7 +140,7 @@ describe("add project shared logic", () => {
createWorkspaceRootIfMissing: true,
defaultModelSelection: {
instanceId: "codex",
model: "gpt-5.4",
model: DEFAULT_MODEL,
},
});
});
@@ -294,6 +294,10 @@ export function createServerEnvironmentAtoms<R, E>(
label: "environment-data:server:process-diagnostics",
tag: WS_METHODS.serverGetProcessDiagnostics,
}),
usageSummary: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:server:usage-summary",
tag: WS_METHODS.usageGetSummary,
}),
processResourceHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:server:process-resource-history",
tag: WS_METHODS.serverGetProcessResourceHistory,
+1
View File
@@ -26,3 +26,4 @@ export * from "./review.ts";
export * from "./preview.ts";
export * from "./previewAutomation.ts";
export * from "./rpc.ts";
export * from "./usage.ts";
+12 -2
View File
@@ -133,8 +133,18 @@ const CURSOR_DRIVER_KIND = ProviderDriverKind.make("cursor");
const GROK_DRIVER_KIND = ProviderDriverKind.make("grok");
const OPENCODE_DRIVER_KIND = ProviderDriverKind.make("opencode");
export const DEFAULT_MODEL = "gpt-5.4";
export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.4-mini";
export const DEFAULT_MODEL = "gpt-5.6-sol";
/**
* Codex default-model preference, most preferred first. The provider snapshot
* marks the first of these present in the live `model/list` response as
* default; when none are available, Codex's own `isDefault` flag wins.
*/
export const PREFERRED_DEFAULT_CODEX_MODELS: ReadonlyArray<string> = [
"gpt-5.6-sol",
"gpt-5.6-terra",
];
export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.6-luna";
export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, string>> = {
[CODEX_DRIVER_KIND]: DEFAULT_MODEL,
+28
View File
@@ -21,6 +21,7 @@ import {
TurnId,
} from "./baseSchemas.ts";
import { ProviderInstanceId } from "./providerInstance.ts";
import { UsageFact } from "./usage.ts";
export const ORCHESTRATION_WS_METHODS = {
dispatchCommand: "orchestration.dispatchCommand",
@@ -798,6 +799,17 @@ const ThreadRevertCompleteCommand = Schema.Struct({
createdAt: IsoDateTime,
});
const ThreadUsageRecordCommand = Schema.Struct({
type: Schema.Literal("thread.usage.record"),
commandId: CommandId,
threadId: ThreadId,
turnId: Schema.NullOr(TurnId),
projectId: Schema.NullOr(ProjectId),
facts: Schema.Array(UsageFact),
createdAt: IsoDateTime,
});
export type ThreadUsageRecordCommand = typeof ThreadUsageRecordCommand.Type;
const InternalOrchestrationCommand = Schema.Union([
ThreadSessionSetCommand,
ThreadMessageAssistantDeltaCommand,
@@ -806,6 +818,7 @@ const InternalOrchestrationCommand = Schema.Union([
ThreadTurnDiffCompleteCommand,
ThreadActivityAppendCommand,
ThreadRevertCompleteCommand,
ThreadUsageRecordCommand,
]);
export type InternalOrchestrationCommand = typeof InternalOrchestrationCommand.Type;
@@ -838,6 +851,7 @@ export const OrchestrationEventType = Schema.Literals([
"thread.proposed-plan-upserted",
"thread.turn-diff-completed",
"thread.activity-appended",
"thread.usage-recorded",
]);
export type OrchestrationEventType = typeof OrchestrationEventType.Type;
@@ -1012,6 +1026,15 @@ export const ThreadActivityAppendedPayload = Schema.Struct({
activity: OrchestrationThreadActivity,
});
export const ThreadUsageRecordedPayload = Schema.Struct({
threadId: ThreadId,
turnId: Schema.NullOr(TurnId),
/** Project attribution captured at fact time (historical-at-use). */
projectId: Schema.NullOr(ProjectId),
facts: Schema.Array(UsageFact),
recordedAt: IsoDateTime,
});
export const OrchestrationEventMetadata = Schema.Struct({
providerTurnId: Schema.optional(TrimmedNonEmptyString),
providerItemId: Schema.optional(ProviderItemId),
@@ -1144,6 +1167,11 @@ export const OrchestrationEvent = Schema.Union([
type: Schema.Literal("thread.activity-appended"),
payload: ThreadActivityAppendedPayload,
}),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.usage-recorded"),
payload: ThreadUsageRecordedPayload,
}),
]);
export type OrchestrationEvent = typeof OrchestrationEvent.Type;
+12
View File
@@ -46,6 +46,10 @@ const ProviderRefs = Schema.Struct({
providerTurnId: Schema.optional(TrimmedNonEmptyStringSchema),
providerItemId: Schema.optional(ProviderItemId),
providerRequestId: Schema.optional(ProviderRequestId),
/** Provider-native session/thread identity (Claude session_id, Codex thread
* id). Required to attribute cumulative usage counters when several
* provider sessions run concurrently under one T3 thread. */
providerSessionId: Schema.optional(TrimmedNonEmptyStringSchema),
});
export type ProviderRefs = typeof ProviderRefs.Type;
@@ -320,6 +324,14 @@ export const ThreadTokenUsageSnapshot = Schema.Struct({
toolUses: Schema.optional(NonNegativeInt),
durationMs: Schema.optional(NonNegativeInt),
compactsAutomatically: Schema.optional(Schema.Boolean),
/** Session-cumulative counters (monotonic within one provider-native
* session). Present only when the adapter can report them; usage accounting
* derives interval deltas from these, never from the context-window fields
* above. `totalInputTokens` includes cached reads, mirroring the provider. */
totalInputTokens: Schema.optional(NonNegativeInt),
totalCachedInputTokens: Schema.optional(NonNegativeInt),
totalOutputTokens: Schema.optional(NonNegativeInt),
totalReasoningOutputTokens: Schema.optional(NonNegativeInt),
});
export type ThreadTokenUsageSnapshot = typeof ThreadTokenUsageSnapshot.Type;
+9
View File
@@ -132,6 +132,7 @@ import {
ServerUpsertKeybindingResult,
} from "./server.ts";
import { ServerSettings, ServerSettingsError, ServerSettingsPatch } from "./settings.ts";
import { UsageSummaryRequest, UsageSummaryResponse } from "./usage.ts";
import {
SourceControlCloneRepositoryInput,
SourceControlCloneRepositoryResult,
@@ -211,6 +212,7 @@ export const WS_METHODS = {
serverUpdateSettings: "server.updateSettings",
serverDiscoverSourceControl: "server.discoverSourceControl",
serverGetTraceDiagnostics: "server.getTraceDiagnostics",
usageGetSummary: "usage.getSummary",
serverGetProcessDiagnostics: "server.getProcessDiagnostics",
serverGetProcessResourceHistory: "server.getProcessResourceHistory",
serverSignalProcess: "server.signalProcess",
@@ -303,6 +305,12 @@ export const WsServerGetTraceDiagnosticsRpc = Rpc.make(WS_METHODS.serverGetTrace
error: EnvironmentAuthorizationError,
});
export const WsUsageGetSummaryRpc = Rpc.make(WS_METHODS.usageGetSummary, {
payload: UsageSummaryRequest,
success: UsageSummaryResponse,
error: EnvironmentAuthorizationError,
});
export const WsServerGetProcessDiagnosticsRpc = Rpc.make(WS_METHODS.serverGetProcessDiagnostics, {
payload: Schema.Struct({}),
success: ServerProcessDiagnosticsResult,
@@ -699,6 +707,7 @@ export const WsRpcGroup = RpcGroup.make(
WsServerUpdateSettingsRpc,
WsServerDiscoverSourceControlRpc,
WsServerGetTraceDiagnosticsRpc,
WsUsageGetSummaryRpc,
WsServerGetProcessDiagnosticsRpc,
WsServerGetProcessResourceHistoryRpc,
WsServerSignalProcessRpc,
+1
View File
@@ -64,6 +64,7 @@ export const ServerProviderModel = Schema.Struct({
shortName: Schema.optional(TrimmedNonEmptyString),
subProvider: Schema.optional(TrimmedNonEmptyString),
isCustom: Schema.Boolean,
isDefault: Schema.optional(Schema.Boolean),
capabilities: Schema.NullOr(ModelCapabilities),
});
export type ServerProviderModel = typeof ServerProviderModel.Type;
+4 -4
View File
@@ -88,14 +88,14 @@ describe("ServerSettings.providerInstances (slice-2 invariant)", () => {
});
describe("ServerSettings worktree defaults", () => {
it("defaults start-from-origin off for legacy configs", () => {
expect(decodeServerSettings({}).newWorktreesStartFromOrigin).toBe(false);
it("defaults start-from-origin on for legacy configs", () => {
expect(decodeServerSettings({}).newWorktreesStartFromOrigin).toBe(true);
});
it("accepts start-from-origin updates", () => {
expect(
decodeServerSettingsPatch({ newWorktreesStartFromOrigin: true }).newWorktreesStartFromOrigin,
).toBe(true);
decodeServerSettingsPatch({ newWorktreesStartFromOrigin: false }).newWorktreesStartFromOrigin,
).toBe(false);
});
});
+1 -1
View File
@@ -382,7 +382,7 @@ export const ServerSettings = Schema.Struct({
Schema.withDecodingDefault(Effect.succeed("local" as const satisfies ThreadEnvMode)),
),
newWorktreesStartFromOrigin: Schema.Boolean.pipe(
Schema.withDecodingDefault(Effect.succeed(false)),
Schema.withDecodingDefault(Effect.succeed(true)),
),
addProjectBaseDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
textGenerationModelSelection: ModelSelection.pipe(
+153
View File
@@ -0,0 +1,153 @@
import * as Schema from "effect/Schema";
import { IsoDateTime, NonNegativeInt, ProjectId, TrimmedNonEmptyString } from "./baseSchemas.ts";
import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";
// ---------------------------------------------------------------------------
// Usage facts
//
// A usage fact is an immutable accounting record: interval token counters (never
// cumulative) attributed to a provider-native session so that concurrent or
// resumed provider sessions on one T3 thread can never be conflated. Facts are
// persisted as `thread.usage-recorded` orchestration events and projected into
// `projection_usage_facts` / `projection_usage_daily` by a registered projector.
// ---------------------------------------------------------------------------
export const UsageFactId = TrimmedNonEmptyString.pipe(Schema.brand("UsageFactId"));
export type UsageFactId = typeof UsageFactId.Type;
/** Interval (delta) token counters. Adapters convert cumulative provider
* counters into deltas before a fact is emitted; a fact never carries a
* running total. `cachedInputTokens` are cache reads; `cacheCreationTokens`
* are cache writes — they are priced differently and never summed silently. */
export const UsageTokenCounters = Schema.Struct({
inputTokens: NonNegativeInt,
cachedInputTokens: NonNegativeInt,
cacheCreationTokens: NonNegativeInt,
outputTokens: NonNegativeInt,
reasoningOutputTokens: NonNegativeInt,
});
export type UsageTokenCounters = typeof UsageTokenCounters.Type;
/** `final` — per-model settlement derived from a provider's terminal report
* (Claude modelUsage deltas). `interval` — an accumulated slice of a turn
* flushed before settlement (Codex per-update deltas); intervals and finals
* both sum linearly. `turn-total` — the provider's own turn-level cost figure
* kept only to reconcile against per-model facts, never added to them. */
export const UsageFactKind = Schema.Literals(["final", "interval", "turn-total"]);
export type UsageFactKind = typeof UsageFactKind.Type;
export const UsageFact = Schema.Struct({
factId: UsageFactId,
kind: UsageFactKind,
provider: ProviderDriverKind,
providerInstanceId: Schema.optional(ProviderInstanceId),
/** Provider-native session identity (Claude session_id, Codex thread id).
* Falls back to the T3 thread id when a driver exposes nothing better. */
providerSessionId: TrimmedNonEmptyString,
model: TrimmedNonEmptyString,
/** Model id exactly as the provider reported it (e.g. with `[1m]` suffix). */
modelRaw: TrimmedNonEmptyString,
reasoningEffort: Schema.optional(TrimmedNonEmptyString),
tokens: UsageTokenCounters,
/** Exact provider-reported cost in integer micro-USD. Absent when the
* provider does not meter (Codex); estimates are computed at query time and
* never stored. */
costMicroUsd: Schema.optional(NonNegativeInt),
/** True when the originating runtime event was rejected by the turn
* lifecycle guard (stale completion); recorded rather than dropped. */
stale: Schema.optional(Schema.Boolean),
observedAt: IsoDateTime,
});
export type UsageFact = typeof UsageFact.Type;
// ---------------------------------------------------------------------------
// Claude SDK modelUsage — typed replacement for the UnknownRecord that rides
// on `turn.completed`. Keys of the map are raw model ids.
// ---------------------------------------------------------------------------
export const ClaudeModelUsageEntry = Schema.Struct({
inputTokens: NonNegativeInt,
outputTokens: NonNegativeInt,
cacheReadInputTokens: NonNegativeInt,
cacheCreationInputTokens: NonNegativeInt,
costUSD: Schema.optional(Schema.Number),
});
export type ClaudeModelUsageEntry = typeof ClaudeModelUsageEntry.Type;
export const ClaudeModelUsageMap = Schema.Record(Schema.String, ClaudeModelUsageEntry);
export type ClaudeModelUsageMap = typeof ClaudeModelUsageMap.Type;
// ---------------------------------------------------------------------------
// usage.summary RPC — one dashboard-shaped request so the Usage page renders
// from a single round trip. All aggregates are integers (tokens) or integer
// micro-USD; grouping happens in the requested IANA timezone.
// ---------------------------------------------------------------------------
export const UsageSummaryRequest = Schema.Struct({
/** Inclusive ISO date-time lower bound; omit for all time. */
since: Schema.optional(IsoDateTime),
/** Exclusive ISO date-time upper bound; omit for now. */
until: Schema.optional(IsoDateTime),
/** IANA timezone used for calendar bucketing (daily, hour-of-week). */
timeZone: TrimmedNonEmptyString,
});
export type UsageSummaryRequest = typeof UsageSummaryRequest.Type;
export const UsageCostSource = Schema.Literals(["exact", "estimated", "none"]);
export type UsageCostSource = typeof UsageCostSource.Type;
const UsageAggregate = Schema.Struct({
...UsageTokenCounters.fields,
totalTokens: NonNegativeInt,
turns: NonNegativeInt,
exactCostMicroUsd: NonNegativeInt,
estimatedCostMicroUsd: NonNegativeInt,
});
export type UsageAggregate = typeof UsageAggregate.Type;
export const UsageModelBucket = Schema.Struct({
...UsageAggregate.fields,
provider: ProviderDriverKind,
model: TrimmedNonEmptyString,
costSource: UsageCostSource,
});
export type UsageModelBucket = typeof UsageModelBucket.Type;
export const UsageDailyBucket = Schema.Struct({
...UsageAggregate.fields,
/** Local calendar date (YYYY-MM-DD) in the request timezone. */
day: TrimmedNonEmptyString,
provider: ProviderDriverKind,
model: TrimmedNonEmptyString,
});
export type UsageDailyBucket = typeof UsageDailyBucket.Type;
export const UsageHourOfWeekBucket = Schema.Struct({
/** 0 = Sunday, per JS Date#getDay in the request timezone. */
dayOfWeek: NonNegativeInt,
hour: NonNegativeInt,
turns: NonNegativeInt,
totalTokens: NonNegativeInt,
});
export type UsageHourOfWeekBucket = typeof UsageHourOfWeekBucket.Type;
export const UsageProjectBucket = Schema.Struct({
...UsageAggregate.fields,
projectId: Schema.NullOr(ProjectId),
projectTitle: Schema.NullOr(TrimmedNonEmptyString),
});
export type UsageProjectBucket = typeof UsageProjectBucket.Type;
export const UsageSummaryResponse = Schema.Struct({
totals: UsageAggregate,
byModel: Schema.Array(UsageModelBucket),
daily: Schema.Array(UsageDailyBucket),
hourOfWeek: Schema.Array(UsageHourOfWeekBucket),
byProject: Schema.Array(UsageProjectBucket),
/** Models with token volume but no pricing entry — surfaced, never $0. */
unpricedModels: Schema.Array(TrimmedNonEmptyString),
pricingVersion: TrimmedNonEmptyString,
/** Earliest fact in the ledger, for "history starts here" honesty. */
earliestFactAt: Schema.NullOr(IsoDateTime),
});
export type UsageSummaryResponse = typeof UsageSummaryResponse.Type;
+4
View File
@@ -3,6 +3,10 @@
"private": true,
"type": "module",
"exports": {
"./usagePricing": {
"types": "./src/usagePricing.ts",
"import": "./src/usagePricing.ts"
},
"./projectFavicon": {
"types": "./src/projectFavicon.ts",
"import": "./src/projectFavicon.ts"
+79
View File
@@ -0,0 +1,79 @@
/**
* Versioned list-price catalog for estimating usage cost when a provider does
* not meter (Codex reports tokens only). Estimates are computed at query time
* from immutable token facts and are always labeled as estimates — they are
* never persisted and never blended with provider-reported exact cost.
*
* Rates are USD per million tokens, effective-dated so a price change never
* silently revalues history. `cacheWritePerMTok` covers cache-creation
* tokens; providers without a cache-write concept omit it.
*/
export interface UsageModelPricing {
readonly model: string;
/** Inclusive ISO date this rate takes effect. */
readonly effectiveFrom: string;
readonly inputPerMTok: number;
readonly cachedInputPerMTok: number;
readonly cacheWritePerMTok?: number;
readonly outputPerMTok: number;
}
export const USAGE_PRICING_VERSION = "2026-07-24";
const CATALOG: ReadonlyArray<UsageModelPricing> = [
// OpenAI list prices (verified against ccusage output to the cent).
{
model: "gpt-5.6-sol",
effectiveFrom: "2026-01-01",
inputPerMTok: 10,
cachedInputPerMTok: 1,
outputPerMTok: 60,
},
{
model: "gpt-5.5",
effectiveFrom: "2025-11-01",
inputPerMTok: 10,
cachedInputPerMTok: 1,
outputPerMTok: 60,
},
];
export interface UsageTokenBreakdown {
readonly inputTokens: number;
readonly cachedInputTokens: number;
readonly cacheCreationTokens: number;
readonly outputTokens: number;
}
function rateFor(model: string, observedAtIso: string): UsageModelPricing | undefined {
let best: UsageModelPricing | undefined;
for (const entry of CATALOG) {
if (entry.model !== model) continue;
if (entry.effectiveFrom > observedAtIso.slice(0, 10)) continue;
if (!best || entry.effectiveFrom > best.effectiveFrom) {
best = entry;
}
}
return best;
}
/** Integer micro-USD estimate, or undefined when the model has no rate (the
* caller surfaces it as unpriced rather than $0). */
export function estimateCostMicroUsd(
model: string,
observedAtIso: string,
tokens: UsageTokenBreakdown,
): number | undefined {
const rate = rateFor(model, observedAtIso);
if (!rate) {
return undefined;
}
const usd =
(tokens.inputTokens * rate.inputPerMTok +
tokens.cachedInputTokens * rate.cachedInputPerMTok +
tokens.cacheCreationTokens * (rate.cacheWritePerMTok ?? rate.inputPerMTok) +
tokens.outputTokens * rate.outputPerMTok) /
1_000_000;
return Math.round(usd * 1_000_000);
}
-56
View File
@@ -14,7 +14,6 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { SshPasswordPrompt } from "./auth.ts";
import {
buildSupervisedSshTunnelArgs,
buildRemoteLaunchScript,
buildRemotePairingScript,
buildRemoteStopScript,
@@ -90,50 +89,6 @@ function commandArgs(command: ChildProcess.Command): ReadonlyArray<string> {
}
describe("ssh tunnel scripts", () => {
it("disables connection multiplexing for the supervised port-forward command", () => {
const target = {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
} as const;
assert.deepEqual(
buildSupervisedSshTunnelArgs({
target,
batchMode: "no",
localPort: 41_773,
remotePort: 3_773,
hostSpec: "julius@devbox",
}),
[
"-o",
"BatchMode=no",
"-o",
"ConnectTimeout=10",
"-p",
"2222",
"-o",
"ControlMaster=no",
"-o",
"ControlPath=none",
"-o",
"ControlPersist=no",
"-o",
"ExitOnForwardFailure=yes",
"-o",
"ServerAliveInterval=15",
"-o",
"ServerAliveCountMax=3",
"-n",
"-N",
"-L",
"41773:127.0.0.1:3773",
"julius@devbox",
],
);
});
it("builds the remote t3 runner with npx and npm fallbacks", () => {
const script = buildRemoteT3RunnerScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE });
@@ -427,17 +382,6 @@ describe("ssh tunnel scripts", () => {
const first = yield* manager.ensureEnvironment(target);
assert.equal(first.httpBaseUrl, "http://127.0.0.1:41773/");
const firstTunnelArgs = spawnedCommands.find((args) => args.includes("-N"));
assert.isDefined(firstTunnelArgs);
assert.include(firstTunnelArgs, "ControlMaster=no");
assert.include(firstTunnelArgs, "ControlPath=none");
assert.include(firstTunnelArgs, "ControlPersist=no");
for (const args of spawnedCommands.filter((entry) => !entry.includes("-N"))) {
assert.notInclude(args, "ControlMaster=no");
assert.notInclude(args, "ControlPath=none");
assert.notInclude(args, "ControlPersist=no");
}
yield* manager.disconnectEnvironment(target);
assert.equal(tunnelKillCount, 1);
assert.equal(stopCommandCount, 1);
+15 -38
View File
@@ -917,38 +917,6 @@ const reserveLocalTunnelPort = Effect.fn("ssh/tunnel.reserveLocalTunnelPort")(fu
return yield* net.reserveLoopbackPort();
});
export function buildSupervisedSshTunnelArgs(input: {
readonly target: DesktopSshEnvironmentTarget;
readonly batchMode: "yes" | "no";
readonly localPort: number;
readonly remotePort: number;
readonly hostSpec: string;
}): ReadonlyArray<string> {
return [
...baseSshArgs(input.target, { batchMode: input.batchMode }),
// This process owns the tunnel lifecycle. Inherited ControlMaster settings
// can otherwise hand the forward to an existing master and let `ssh -N`
// exit while the manager believes it still supervises the connection.
"-o",
"ControlMaster=no",
"-o",
"ControlPath=none",
"-o",
"ControlPersist=no",
"-o",
"ExitOnForwardFailure=yes",
"-o",
"ServerAliveInterval=15",
"-o",
"ServerAliveCountMax=3",
"-n",
"-N",
"-L",
`${input.localPort}:127.0.0.1:${input.remotePort}`,
input.hostSpec,
];
}
const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: {
readonly key: string;
readonly resolvedTarget: DesktopSshEnvironmentTarget;
@@ -988,13 +956,22 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
}),
),
);
const args = buildSupervisedSshTunnelArgs({
target: input.resolvedTarget,
batchMode: input.authOptions.batchMode ?? "no",
localPort: input.localPort,
remotePort: input.remotePort,
const args = [
...baseSshArgs(input.resolvedTarget, {
batchMode: input.authOptions.batchMode ?? "no",
}),
"-o",
"ExitOnForwardFailure=yes",
"-o",
"ServerAliveInterval=15",
"-o",
"ServerAliveCountMax=3",
"-n",
"-N",
"-L",
`${input.localPort}:127.0.0.1:${input.remotePort}`,
hostSpec,
});
];
const sshCommand = yield* resolveSshCommand;
const tunnelCommand = [sshCommand, ...args];
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;