Report automation usage costs (#1994)
* feat: report automation usage costs * fix: satisfy max-lines lint
This commit is contained in:
@@ -88,4 +88,105 @@ describe('AutomationService', () => {
|
||||
new Date('2026-05-14T09:00:00').getTime()
|
||||
)
|
||||
})
|
||||
|
||||
it('attaches provider usage when a completed run can be attributed', async () => {
|
||||
vi.setSystemTime(new Date('2026-05-13T10:00:00'))
|
||||
const store = await createStore()
|
||||
store.addRepo(makeRepo())
|
||||
const automation = store.createAutomation({
|
||||
name: 'Costed check',
|
||||
prompt: 'Check spend',
|
||||
agentId: 'claude',
|
||||
projectId: 'r1',
|
||||
workspaceMode: 'existing',
|
||||
workspaceId: 'wt1',
|
||||
timezone: 'UTC',
|
||||
rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0',
|
||||
dtstart: new Date('2026-05-13T00:00:00Z').getTime()
|
||||
})
|
||||
const run = store.createAutomationRun(automation, Date.now(), 'manual')
|
||||
store.updateAutomationRun({
|
||||
runId: run.id,
|
||||
status: 'dispatched',
|
||||
workspaceId: 'wt1',
|
||||
terminalSessionId: 'tab-1',
|
||||
error: null
|
||||
})
|
||||
const usage = {
|
||||
status: 'known' as const,
|
||||
provider: 'claude' as const,
|
||||
model: 'claude-sonnet-4-6',
|
||||
inputTokens: 100,
|
||||
outputTokens: 50,
|
||||
cacheReadTokens: 25,
|
||||
cacheWriteTokens: 10,
|
||||
reasoningOutputTokens: null,
|
||||
totalTokens: 185,
|
||||
estimatedCostUsd: 0.001,
|
||||
estimatedCostSource: 'api_equivalent' as const,
|
||||
providerSessionId: 'provider-session-1',
|
||||
attribution: 'provider_session_time_window' as const,
|
||||
collectedAt: Date.now(),
|
||||
unavailableReason: null,
|
||||
unavailableMessage: null
|
||||
}
|
||||
const getAutomationRunUsage = vi.fn().mockResolvedValue(usage)
|
||||
const service = new AutomationService(store, {
|
||||
tickMs: 60_000,
|
||||
claudeUsage: { getAutomationRunUsage } as never
|
||||
})
|
||||
|
||||
const updated = await service.markDispatchResult({
|
||||
runId: run.id,
|
||||
status: 'completed',
|
||||
workspaceId: 'wt1',
|
||||
terminalSessionId: 'tab-1',
|
||||
error: null
|
||||
})
|
||||
|
||||
expect(updated.usage).toEqual(usage)
|
||||
expect(getAutomationRunUsage).toHaveBeenCalledWith({
|
||||
worktreeId: 'wt1',
|
||||
terminalSessionId: 'tab-1',
|
||||
startedAt: expect.any(Number),
|
||||
completedAt: expect.any(Number)
|
||||
})
|
||||
})
|
||||
|
||||
it('records unsupported usage cleanly for completed agents without local usage stores', async () => {
|
||||
vi.setSystemTime(new Date('2026-05-13T10:00:00'))
|
||||
const store = await createStore()
|
||||
store.addRepo(makeRepo())
|
||||
const automation = store.createAutomation({
|
||||
name: 'Gemini check',
|
||||
prompt: 'Check spend',
|
||||
agentId: 'gemini',
|
||||
projectId: 'r1',
|
||||
workspaceMode: 'existing',
|
||||
workspaceId: 'wt1',
|
||||
timezone: 'UTC',
|
||||
rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0',
|
||||
dtstart: new Date('2026-05-13T00:00:00Z').getTime()
|
||||
})
|
||||
const run = store.createAutomationRun(automation, Date.now(), 'manual')
|
||||
store.updateAutomationRun({
|
||||
runId: run.id,
|
||||
status: 'dispatched',
|
||||
workspaceId: 'wt1',
|
||||
terminalSessionId: 'tab-1',
|
||||
error: null
|
||||
})
|
||||
const service = new AutomationService(store, { tickMs: 60_000 })
|
||||
|
||||
const updated = await service.markDispatchResult({
|
||||
runId: run.id,
|
||||
status: 'completed',
|
||||
workspaceId: 'wt1',
|
||||
terminalSessionId: 'tab-1',
|
||||
error: null
|
||||
})
|
||||
|
||||
expect(updated.usage?.status).toBe('unavailable')
|
||||
expect(updated.usage?.unavailableReason).toBe('provider_unsupported')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -4,8 +4,12 @@ import type {
|
||||
Automation,
|
||||
AutomationDispatchRequest,
|
||||
AutomationDispatchResult,
|
||||
AutomationRun
|
||||
AutomationRun,
|
||||
AutomationRunStatus,
|
||||
AutomationRunUsage
|
||||
} from '../../shared/automations-types'
|
||||
import type { ClaudeUsageStore } from '../claude-usage/store'
|
||||
import type { CodexUsageStore } from '../codex-usage/store'
|
||||
|
||||
const DEFAULT_TICK_MS = 60 * 1000
|
||||
|
||||
@@ -16,10 +20,17 @@ export class AutomationService {
|
||||
private webContents: WebContents | null = null
|
||||
private rendererReady = false
|
||||
private evaluating = false
|
||||
private readonly claudeUsage: ClaudeUsageStore | null
|
||||
private readonly codexUsage: CodexUsageStore | null
|
||||
|
||||
constructor(store: Store, opts: { tickMs?: number } = {}) {
|
||||
constructor(
|
||||
store: Store,
|
||||
opts: { tickMs?: number; claudeUsage?: ClaudeUsageStore; codexUsage?: CodexUsageStore } = {}
|
||||
) {
|
||||
this.store = store
|
||||
this.tickMs = opts.tickMs ?? DEFAULT_TICK_MS
|
||||
this.claudeUsage = opts.claudeUsage ?? null
|
||||
this.codexUsage = opts.codexUsage ?? null
|
||||
}
|
||||
|
||||
setWebContents(webContents: WebContents | null): void {
|
||||
@@ -62,8 +73,97 @@ export class AutomationService {
|
||||
return run
|
||||
}
|
||||
|
||||
markDispatchResult(result: AutomationDispatchResult): AutomationRun {
|
||||
return this.store.updateAutomationRun(result)
|
||||
async markDispatchResult(result: AutomationDispatchResult): Promise<AutomationRun> {
|
||||
const run = this.store.updateAutomationRun(result)
|
||||
if (!isFinalRunStatus(run.status)) {
|
||||
return run
|
||||
}
|
||||
const usage = await this.collectRunUsage(run)
|
||||
return this.store.updateAutomationRun({
|
||||
runId: run.id,
|
||||
status: run.status,
|
||||
workspaceId: run.workspaceId,
|
||||
terminalSessionId: run.terminalSessionId,
|
||||
usage,
|
||||
error: run.error
|
||||
})
|
||||
}
|
||||
|
||||
private async collectRunUsage(run: AutomationRun): Promise<AutomationRunUsage> {
|
||||
const automation = this.store.listAutomations().find((entry) => entry.id === run.automationId)
|
||||
const collectedAt = Date.now()
|
||||
const unavailable = (
|
||||
provider: AutomationRunUsage['provider'],
|
||||
unavailableReason: AutomationRunUsage['unavailableReason'],
|
||||
unavailableMessage: string
|
||||
): AutomationRunUsage => ({
|
||||
status: 'unavailable',
|
||||
provider,
|
||||
model: null,
|
||||
inputTokens: null,
|
||||
outputTokens: null,
|
||||
cacheReadTokens: null,
|
||||
cacheWriteTokens: null,
|
||||
reasoningOutputTokens: null,
|
||||
totalTokens: null,
|
||||
estimatedCostUsd: null,
|
||||
estimatedCostSource: null,
|
||||
providerSessionId: null,
|
||||
attribution: null,
|
||||
collectedAt,
|
||||
unavailableReason,
|
||||
unavailableMessage
|
||||
})
|
||||
|
||||
if (!automation || run.status !== 'completed') {
|
||||
return unavailable(
|
||||
automation?.agentId === 'codex'
|
||||
? 'codex'
|
||||
: automation?.agentId === 'claude'
|
||||
? 'claude'
|
||||
: null,
|
||||
'run_not_finished',
|
||||
'Usage is only collected for completed automation runs.'
|
||||
)
|
||||
}
|
||||
if (automation.executionTargetType === 'ssh') {
|
||||
return unavailable(
|
||||
automation.agentId === 'codex'
|
||||
? 'codex'
|
||||
: automation.agentId === 'claude'
|
||||
? 'claude'
|
||||
: null,
|
||||
'remote_usage_unavailable',
|
||||
'Remote automation usage is not available from local usage logs.'
|
||||
)
|
||||
}
|
||||
if (automation.agentId === 'claude') {
|
||||
if (!this.claudeUsage) {
|
||||
return unavailable('claude', 'scan_failed', 'Claude usage store is unavailable.')
|
||||
}
|
||||
return this.claudeUsage.getAutomationRunUsage({
|
||||
worktreeId: run.workspaceId,
|
||||
terminalSessionId: run.terminalSessionId,
|
||||
startedAt: run.startedAt,
|
||||
completedAt: collectedAt
|
||||
})
|
||||
}
|
||||
if (automation.agentId === 'codex') {
|
||||
if (!this.codexUsage) {
|
||||
return unavailable('codex', 'scan_failed', 'Codex usage store is unavailable.')
|
||||
}
|
||||
return this.codexUsage.getAutomationRunUsage({
|
||||
worktreeId: run.workspaceId,
|
||||
terminalSessionId: run.terminalSessionId,
|
||||
startedAt: run.startedAt,
|
||||
completedAt: collectedAt
|
||||
})
|
||||
}
|
||||
return unavailable(
|
||||
null,
|
||||
'provider_unsupported',
|
||||
'This agent does not report usage to Orca yet.'
|
||||
)
|
||||
}
|
||||
|
||||
private async evaluateDueRuns(): Promise<void> {
|
||||
@@ -128,3 +228,13 @@ export class AutomationService {
|
||||
webContents.send('automations:dispatchRequested', payload)
|
||||
}
|
||||
}
|
||||
|
||||
function isFinalRunStatus(status: AutomationRunStatus): boolean {
|
||||
return (
|
||||
status === 'completed' ||
|
||||
status === 'dispatch_failed' ||
|
||||
status === 'skipped_missed' ||
|
||||
status === 'skipped_unavailable' ||
|
||||
status === 'skipped_needs_interactive_auth'
|
||||
)
|
||||
}
|
||||
|
||||
@@ -257,4 +257,66 @@ describe('ClaudeUsageStore', () => {
|
||||
|
||||
expect(summary.estimatedCostUsd).toBeCloseTo(8.07)
|
||||
})
|
||||
|
||||
it('returns automation usage for a single matching worktree session', async () => {
|
||||
const worktreeId = 'repo-1::/workspace/repo-a'
|
||||
const store = createStoreWithState({
|
||||
scanState: {
|
||||
enabled: true,
|
||||
lastScanStartedAt: 1,
|
||||
lastScanCompletedAt: 2,
|
||||
lastScanError: null
|
||||
},
|
||||
sessions: [
|
||||
{
|
||||
sessionId: 'session-1',
|
||||
firstTimestamp: '2026-04-09T15:00:00.000Z',
|
||||
lastTimestamp: '2026-04-09T15:05:00.000Z',
|
||||
model: 'claude-sonnet-4-6',
|
||||
lastCwd: '/workspace/repo-a',
|
||||
lastGitBranch: 'feature/a',
|
||||
primaryWorktreeId: worktreeId,
|
||||
primaryRepoId: 'repo-1',
|
||||
turnCount: 1,
|
||||
totalInputTokens: 1000,
|
||||
totalOutputTokens: 500,
|
||||
totalCacheReadTokens: 200,
|
||||
totalCacheWriteTokens: 100,
|
||||
locationBreakdown: [
|
||||
{
|
||||
locationKey: `worktree:${worktreeId}`,
|
||||
projectLabel: 'Repo A',
|
||||
repoId: 'repo-1',
|
||||
worktreeId,
|
||||
turnCount: 1,
|
||||
inputTokens: 1000,
|
||||
outputTokens: 500,
|
||||
cacheReadTokens: 200,
|
||||
cacheWriteTokens: 100
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
;(store as unknown as { refresh: typeof store.refresh }).refresh = vi.fn().mockResolvedValue({
|
||||
enabled: true,
|
||||
isScanning: false,
|
||||
lastScanStartedAt: 1,
|
||||
lastScanCompletedAt: 2,
|
||||
lastScanError: null,
|
||||
hasAnyClaudeData: true
|
||||
})
|
||||
|
||||
const usage = await store.getAutomationRunUsage({
|
||||
worktreeId,
|
||||
terminalSessionId: 'tab-1',
|
||||
startedAt: new Date('2026-04-09T14:59:00.000Z').getTime(),
|
||||
completedAt: new Date('2026-04-09T15:06:00.000Z').getTime()
|
||||
})
|
||||
|
||||
expect(usage.status).toBe('known')
|
||||
expect(usage.providerSessionId).toBe('session-1')
|
||||
expect(usage.totalTokens).toBe(1800)
|
||||
expect(usage.estimatedCostUsd).toBeCloseTo(0.010935)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
ClaudeUsageSessionRow,
|
||||
ClaudeUsageSummary
|
||||
} from '../../shared/claude-usage-types'
|
||||
import type { AutomationRunUsage } from '../../shared/automations-types'
|
||||
import type { Store } from '../persistence'
|
||||
import { loadKnownUsageWorktreesByRepo, type UsageWorktreeRef } from '../usage-worktree-metadata'
|
||||
import type { ClaudeUsagePersistedState } from './types'
|
||||
@@ -19,6 +20,7 @@ import { createWorktreeRefs, getSessionProjectLabel, scanClaudeUsageFiles } from
|
||||
|
||||
const SCHEMA_VERSION = 3
|
||||
const STALE_MS = 5 * 60_000
|
||||
const AUTOMATION_ATTRIBUTION_WINDOW_MS = 5 * 60_000
|
||||
|
||||
// Why: capture the path after configureDevUserDataPath() but before app.setName()
|
||||
// mutates Electron's derived userData location, matching the persistence/store pattern.
|
||||
@@ -36,6 +38,13 @@ type ClaudeModelPricing = {
|
||||
cacheWriteAboveThreshold?: number
|
||||
}
|
||||
|
||||
type AutomationUsageLookupInput = {
|
||||
worktreeId: string | null
|
||||
terminalSessionId: string | null
|
||||
startedAt: number | null
|
||||
completedAt: number | null
|
||||
}
|
||||
|
||||
const LONG_CONTEXT_THRESHOLD_TOKENS = 200_000
|
||||
const SONNET_LONG_CONTEXT_PRICING = {
|
||||
thresholdTokens: LONG_CONTEXT_THRESHOLD_TOKENS,
|
||||
@@ -622,6 +631,123 @@ export class ClaudeUsageStore {
|
||||
})
|
||||
}
|
||||
|
||||
async getAutomationRunUsage(input: AutomationUsageLookupInput): Promise<AutomationRunUsage> {
|
||||
const collectedAt = Date.now()
|
||||
const unavailable = (
|
||||
unavailableReason: AutomationRunUsage['unavailableReason'],
|
||||
unavailableMessage: string
|
||||
): AutomationRunUsage => ({
|
||||
status: 'unavailable',
|
||||
provider: 'claude',
|
||||
model: null,
|
||||
inputTokens: null,
|
||||
outputTokens: null,
|
||||
cacheReadTokens: null,
|
||||
cacheWriteTokens: null,
|
||||
reasoningOutputTokens: null,
|
||||
totalTokens: null,
|
||||
estimatedCostUsd: null,
|
||||
estimatedCostSource: null,
|
||||
providerSessionId: null,
|
||||
attribution: null,
|
||||
collectedAt,
|
||||
unavailableReason,
|
||||
unavailableMessage
|
||||
})
|
||||
|
||||
if (!this.state.scanState.enabled) {
|
||||
return unavailable('usage_not_enabled', 'Claude usage tracking is not enabled.')
|
||||
}
|
||||
if (!input.worktreeId || !input.startedAt || !input.completedAt) {
|
||||
return unavailable('no_matching_session', 'Run session metadata is incomplete.')
|
||||
}
|
||||
|
||||
const scanState = await this.refresh(true)
|
||||
if (scanState.lastScanError) {
|
||||
return unavailable('scan_failed', scanState.lastScanError)
|
||||
}
|
||||
|
||||
const windowStart = input.startedAt - AUTOMATION_ATTRIBUTION_WINDOW_MS
|
||||
const windowEnd = input.completedAt + AUTOMATION_ATTRIBUTION_WINDOW_MS
|
||||
const candidates = this.state.sessions.filter((session) => {
|
||||
const first = new Date(session.firstTimestamp).getTime()
|
||||
const last = new Date(session.lastTimestamp).getTime()
|
||||
if (!Number.isFinite(first) || !Number.isFinite(last)) {
|
||||
return false
|
||||
}
|
||||
if (session.sessionId === input.terminalSessionId) {
|
||||
return true
|
||||
}
|
||||
if (first < windowStart || first > windowEnd || last > windowEnd) {
|
||||
return false
|
||||
}
|
||||
return session.locationBreakdown.some((entry) => entry.worktreeId === input.worktreeId)
|
||||
})
|
||||
|
||||
if (candidates.length === 0) {
|
||||
return unavailable('no_matching_session', 'No Claude usage session matched this run.')
|
||||
}
|
||||
if (candidates.length > 1) {
|
||||
return unavailable(
|
||||
'ambiguous_session',
|
||||
'Multiple Claude usage sessions matched this run window.'
|
||||
)
|
||||
}
|
||||
|
||||
const session = candidates[0]
|
||||
const scopedLocations = session.locationBreakdown.filter(
|
||||
(entry) => entry.worktreeId === input.worktreeId
|
||||
)
|
||||
const locations = scopedLocations.length > 0 ? scopedLocations : session.locationBreakdown
|
||||
const totals = locations.reduce(
|
||||
(acc, entry) => {
|
||||
acc.turns += entry.turnCount
|
||||
acc.inputTokens += entry.inputTokens
|
||||
acc.outputTokens += entry.outputTokens
|
||||
acc.cacheReadTokens += entry.cacheReadTokens
|
||||
acc.cacheWriteTokens += entry.cacheWriteTokens
|
||||
return acc
|
||||
},
|
||||
{
|
||||
turns: 0,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
cacheWriteTokens: 0
|
||||
}
|
||||
)
|
||||
const estimatedCostUsd = estimateCostUsd(
|
||||
session.model,
|
||||
totals.inputTokens,
|
||||
totals.outputTokens,
|
||||
totals.cacheReadTokens,
|
||||
totals.cacheWriteTokens
|
||||
)
|
||||
|
||||
return {
|
||||
status: 'known',
|
||||
provider: 'claude',
|
||||
model: session.model,
|
||||
inputTokens: totals.inputTokens,
|
||||
outputTokens: totals.outputTokens,
|
||||
cacheReadTokens: totals.cacheReadTokens,
|
||||
cacheWriteTokens: totals.cacheWriteTokens,
|
||||
reasoningOutputTokens: null,
|
||||
totalTokens:
|
||||
totals.inputTokens + totals.outputTokens + totals.cacheReadTokens + totals.cacheWriteTokens,
|
||||
estimatedCostUsd,
|
||||
estimatedCostSource: estimatedCostUsd === null ? null : 'api_equivalent',
|
||||
providerSessionId: session.sessionId,
|
||||
// Why: Orca terminal tab ids and Claude usage session ids are different
|
||||
// systems today, so attribution is intentionally limited to one local
|
||||
// provider session in the run's worktree/time window.
|
||||
attribution: 'provider_session_time_window',
|
||||
collectedAt,
|
||||
unavailableReason: null,
|
||||
unavailableMessage: null
|
||||
}
|
||||
}
|
||||
|
||||
private getFilteredDaily(scope: ClaudeUsageScope, range: ClaudeUsageRange) {
|
||||
const cutoff = getRangeCutoff(range)
|
||||
return this.state.dailyAggregates.filter((entry) => {
|
||||
|
||||
@@ -661,4 +661,101 @@ describe('CodexUsageStore', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('returns automation usage for a single matching worktree session', async () => {
|
||||
const worktreeId = 'repo-1::/workspace/repo'
|
||||
const store = createStoreWithState({
|
||||
scanState: {
|
||||
enabled: true,
|
||||
lastScanStartedAt: 1,
|
||||
lastScanCompletedAt: 2,
|
||||
lastScanError: null
|
||||
},
|
||||
sessions: [
|
||||
{
|
||||
sessionId: 'session-1',
|
||||
firstTimestamp: '2026-04-10T15:00:00.000Z',
|
||||
lastTimestamp: '2026-04-10T15:05:00.000Z',
|
||||
primaryModel: 'gpt-5',
|
||||
hasMixedModels: false,
|
||||
primaryProjectLabel: 'Repo',
|
||||
hasMixedLocations: false,
|
||||
primaryWorktreeId: worktreeId,
|
||||
primaryRepoId: 'repo-1',
|
||||
eventCount: 1,
|
||||
totalInputTokens: 1000,
|
||||
totalCachedInputTokens: 400,
|
||||
totalOutputTokens: 250,
|
||||
totalReasoningOutputTokens: 100,
|
||||
totalTokens: 1250,
|
||||
hasInferredPricing: false,
|
||||
locationBreakdown: [
|
||||
{
|
||||
locationKey: `worktree:${worktreeId}`,
|
||||
projectLabel: 'Repo',
|
||||
repoId: 'repo-1',
|
||||
worktreeId,
|
||||
eventCount: 1,
|
||||
inputTokens: 1000,
|
||||
cachedInputTokens: 400,
|
||||
outputTokens: 250,
|
||||
reasoningOutputTokens: 100,
|
||||
totalTokens: 1250,
|
||||
hasInferredPricing: false
|
||||
}
|
||||
],
|
||||
modelBreakdown: [
|
||||
{
|
||||
modelKey: 'gpt-5',
|
||||
modelLabel: 'gpt-5',
|
||||
eventCount: 1,
|
||||
inputTokens: 1000,
|
||||
cachedInputTokens: 400,
|
||||
outputTokens: 250,
|
||||
reasoningOutputTokens: 100,
|
||||
totalTokens: 1250,
|
||||
hasInferredPricing: false
|
||||
}
|
||||
],
|
||||
locationModelBreakdown: [
|
||||
{
|
||||
locationKey: `worktree:${worktreeId}`,
|
||||
modelKey: 'gpt-5',
|
||||
modelLabel: 'gpt-5',
|
||||
repoId: 'repo-1',
|
||||
worktreeId,
|
||||
eventCount: 1,
|
||||
inputTokens: 1000,
|
||||
cachedInputTokens: 400,
|
||||
outputTokens: 250,
|
||||
reasoningOutputTokens: 100,
|
||||
totalTokens: 1250,
|
||||
hasInferredPricing: false
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
;(store as unknown as { refresh: typeof store.refresh }).refresh = vi.fn().mockResolvedValue({
|
||||
enabled: true,
|
||||
isScanning: false,
|
||||
lastScanStartedAt: 1,
|
||||
lastScanCompletedAt: 2,
|
||||
lastScanError: null,
|
||||
hasAnyCodexData: true
|
||||
})
|
||||
|
||||
const usage = await store.getAutomationRunUsage({
|
||||
worktreeId,
|
||||
terminalSessionId: 'tab-1',
|
||||
startedAt: new Date('2026-04-10T14:59:00.000Z').getTime(),
|
||||
completedAt: new Date('2026-04-10T15:06:00.000Z').getTime()
|
||||
})
|
||||
|
||||
expect(usage.status).toBe('known')
|
||||
expect(usage.providerSessionId).toBe('session-1')
|
||||
expect(usage.cacheReadTokens).toBe(400)
|
||||
expect(usage.reasoningOutputTokens).toBe(100)
|
||||
expect(usage.estimatedCostUsd).toBeCloseTo(0.0033)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
CodexUsageSessionRow,
|
||||
CodexUsageSummary
|
||||
} from '../../shared/codex-usage-types'
|
||||
import type { AutomationRunUsage } from '../../shared/automations-types'
|
||||
import type { Store } from '../persistence'
|
||||
import { loadKnownUsageWorktreesByRepo, type UsageWorktreeRef } from '../usage-worktree-metadata'
|
||||
import type { CodexUsagePersistedState } from './types'
|
||||
@@ -19,6 +20,7 @@ import { createWorktreeRefs, scanCodexUsageFiles } from './scanner'
|
||||
|
||||
const SCHEMA_VERSION = 3
|
||||
const STALE_MS = 5 * 60_000
|
||||
const AUTOMATION_ATTRIBUTION_WINDOW_MS = 5 * 60_000
|
||||
|
||||
let _codexUsageFile: string | null = null
|
||||
|
||||
@@ -32,6 +34,13 @@ type CodexModelPricing = {
|
||||
outputTiers?: TieredPrice[]
|
||||
}
|
||||
|
||||
type AutomationUsageLookupInput = {
|
||||
worktreeId: string | null
|
||||
terminalSessionId: string | null
|
||||
startedAt: number | null
|
||||
completedAt: number | null
|
||||
}
|
||||
|
||||
const LONG_CONTEXT_THRESHOLD_TOKENS = 272_000
|
||||
|
||||
const MODEL_PRICING: Record<string, CodexModelPricing> = {
|
||||
@@ -635,6 +644,154 @@ export class CodexUsageStore {
|
||||
})
|
||||
}
|
||||
|
||||
async getAutomationRunUsage(input: AutomationUsageLookupInput): Promise<AutomationRunUsage> {
|
||||
const collectedAt = Date.now()
|
||||
const unavailable = (
|
||||
unavailableReason: AutomationRunUsage['unavailableReason'],
|
||||
unavailableMessage: string
|
||||
): AutomationRunUsage => ({
|
||||
status: 'unavailable',
|
||||
provider: 'codex',
|
||||
model: null,
|
||||
inputTokens: null,
|
||||
outputTokens: null,
|
||||
cacheReadTokens: null,
|
||||
cacheWriteTokens: null,
|
||||
reasoningOutputTokens: null,
|
||||
totalTokens: null,
|
||||
estimatedCostUsd: null,
|
||||
estimatedCostSource: null,
|
||||
providerSessionId: null,
|
||||
attribution: null,
|
||||
collectedAt,
|
||||
unavailableReason,
|
||||
unavailableMessage
|
||||
})
|
||||
|
||||
if (!this.state.scanState.enabled) {
|
||||
return unavailable('usage_not_enabled', 'Codex usage tracking is not enabled.')
|
||||
}
|
||||
if (!input.worktreeId || !input.startedAt || !input.completedAt) {
|
||||
return unavailable('no_matching_session', 'Run session metadata is incomplete.')
|
||||
}
|
||||
|
||||
const scanState = await this.refresh(true)
|
||||
if (scanState.lastScanError) {
|
||||
return unavailable('scan_failed', scanState.lastScanError)
|
||||
}
|
||||
|
||||
const windowStart = input.startedAt - AUTOMATION_ATTRIBUTION_WINDOW_MS
|
||||
const windowEnd = input.completedAt + AUTOMATION_ATTRIBUTION_WINDOW_MS
|
||||
const candidates = this.state.sessions.filter((session) => {
|
||||
const first = new Date(session.firstTimestamp).getTime()
|
||||
const last = new Date(session.lastTimestamp).getTime()
|
||||
if (!Number.isFinite(first) || !Number.isFinite(last)) {
|
||||
return false
|
||||
}
|
||||
if (session.sessionId === input.terminalSessionId) {
|
||||
return true
|
||||
}
|
||||
if (first < windowStart || first > windowEnd || last > windowEnd) {
|
||||
return false
|
||||
}
|
||||
return session.locationBreakdown.some((entry) => entry.worktreeId === input.worktreeId)
|
||||
})
|
||||
|
||||
if (candidates.length === 0) {
|
||||
return unavailable('no_matching_session', 'No Codex usage session matched this run.')
|
||||
}
|
||||
if (candidates.length > 1) {
|
||||
return unavailable(
|
||||
'ambiguous_session',
|
||||
'Multiple Codex usage sessions matched this run window.'
|
||||
)
|
||||
}
|
||||
|
||||
const session = candidates[0]
|
||||
const scopedLocations = session.locationBreakdown.filter(
|
||||
(entry) => entry.worktreeId === input.worktreeId
|
||||
)
|
||||
const locations = scopedLocations.length > 0 ? scopedLocations : session.locationBreakdown
|
||||
const totals = locations.reduce(
|
||||
(acc, entry) => {
|
||||
acc.events += entry.eventCount
|
||||
acc.inputTokens += entry.inputTokens
|
||||
acc.cachedInputTokens += entry.cachedInputTokens
|
||||
acc.outputTokens += entry.outputTokens
|
||||
acc.reasoningOutputTokens += entry.reasoningOutputTokens
|
||||
acc.totalTokens += entry.totalTokens
|
||||
return acc
|
||||
},
|
||||
{
|
||||
events: 0,
|
||||
inputTokens: 0,
|
||||
cachedInputTokens: 0,
|
||||
outputTokens: 0,
|
||||
reasoningOutputTokens: 0,
|
||||
totalTokens: 0
|
||||
}
|
||||
)
|
||||
const scopedModelRows = session.locationModelBreakdown.filter(
|
||||
(entry) => entry.worktreeId === input.worktreeId
|
||||
)
|
||||
const modelRows = scopedModelRows.length > 0 ? scopedModelRows : session.modelBreakdown
|
||||
const modelLabels = [...new Set(modelRows.map((entry) => entry.modelLabel))]
|
||||
let estimatedCostUsd = 0
|
||||
let hasKnownCost = false
|
||||
if (scopedModelRows.length > 0) {
|
||||
for (const modelRow of scopedModelRows) {
|
||||
const cost = estimateCostUsd(
|
||||
modelRow.modelKey,
|
||||
modelRow.inputTokens,
|
||||
modelRow.cachedInputTokens,
|
||||
modelRow.outputTokens
|
||||
)
|
||||
if (cost !== null) {
|
||||
hasKnownCost = true
|
||||
estimatedCostUsd += cost
|
||||
}
|
||||
}
|
||||
} else if (!session.hasMixedModels) {
|
||||
const cost = estimateCostUsd(
|
||||
session.primaryModel,
|
||||
totals.inputTokens,
|
||||
totals.cachedInputTokens,
|
||||
totals.outputTokens
|
||||
)
|
||||
if (cost !== null) {
|
||||
hasKnownCost = true
|
||||
estimatedCostUsd += cost
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
status: 'known',
|
||||
provider: 'codex',
|
||||
model:
|
||||
modelLabels.length === 1
|
||||
? modelLabels[0]
|
||||
: session.hasMixedModels
|
||||
? 'Mixed models'
|
||||
: session.primaryModel,
|
||||
inputTokens: totals.inputTokens,
|
||||
outputTokens: totals.outputTokens,
|
||||
cacheReadTokens: totals.cachedInputTokens,
|
||||
cacheWriteTokens: null,
|
||||
reasoningOutputTokens: totals.reasoningOutputTokens,
|
||||
totalTokens: totals.totalTokens,
|
||||
estimatedCostUsd: hasKnownCost ? estimatedCostUsd : null,
|
||||
estimatedCostSource: hasKnownCost ? 'api_equivalent' : null,
|
||||
providerSessionId: session.sessionId,
|
||||
// Why: Orca terminal tab ids and Codex usage session ids are different
|
||||
// systems today, so attribution is intentionally limited to one local
|
||||
// provider session in the run's worktree/time window.
|
||||
attribution: 'provider_session_time_window',
|
||||
collectedAt,
|
||||
unavailableReason: null,
|
||||
unavailableMessage: null
|
||||
}
|
||||
}
|
||||
|
||||
private getFilteredDaily(scope: CodexUsageScope, range: CodexUsageRange) {
|
||||
const cutoff = getRangeCutoff(range)
|
||||
return this.state.dailyAggregates.filter((entry) => {
|
||||
|
||||
+1
-1
@@ -700,7 +700,7 @@ app.whenReady().then(async () => {
|
||||
// and defeat the teardown helper's prefix sweep (design §4.3 wire-up).
|
||||
getLocalProvider: () => getLocalPtyProvider()
|
||||
})
|
||||
automations = new AutomationService(store)
|
||||
automations = new AutomationService(store, { claudeUsage, codexUsage })
|
||||
runtime.setAccountServices({ claudeAccounts, codexAccounts, rateLimits })
|
||||
disposeFeatureWallFirstAgentTour = registerFeatureWallFirstAgentTour({
|
||||
stats,
|
||||
|
||||
@@ -49,7 +49,8 @@ export function registerAutomationHandlers(store: Store, service: AutomationServ
|
||||
)
|
||||
ipcMain.handle(
|
||||
'automations:markDispatchResult',
|
||||
(_event, result: AutomationDispatchResult): AutomationRun => service.markDispatchResult(result)
|
||||
(_event, result: AutomationDispatchResult): Promise<AutomationRun> =>
|
||||
service.markDispatchResult(result)
|
||||
)
|
||||
ipcMain.handle('automations:rendererReady', (): void => {
|
||||
service.setRendererReady()
|
||||
|
||||
@@ -1799,6 +1799,7 @@ export class Store {
|
||||
sessionKind: 'terminal',
|
||||
chatSessionId: null,
|
||||
terminalSessionId: null,
|
||||
usage: null,
|
||||
error: null,
|
||||
startedAt: null,
|
||||
dispatchedAt: null,
|
||||
@@ -1821,6 +1822,7 @@ export class Store {
|
||||
status: result.status,
|
||||
workspaceId: result.workspaceId ?? current.workspaceId,
|
||||
terminalSessionId: result.terminalSessionId ?? current.terminalSessionId,
|
||||
usage: Object.hasOwn(result, 'usage') ? (result.usage ?? null) : (current.usage ?? null),
|
||||
error: result.error ?? null,
|
||||
startedAt: current.startedAt ?? now,
|
||||
dispatchedAt: result.status === 'dispatched' ? now : current.dispatchedAt
|
||||
|
||||
@@ -13,6 +13,12 @@ import {
|
||||
getAutomationRunStatusLabel,
|
||||
getAutomationRunStatusVariant
|
||||
} from './automation-page-parts'
|
||||
import {
|
||||
formatAutomationCost,
|
||||
formatAutomationTokens,
|
||||
getAutomationUsageStatusLabel,
|
||||
summarizeAutomationRunUsage
|
||||
} from './automation-usage-model'
|
||||
|
||||
type AutomationDetailProps = {
|
||||
automation: Automation | null
|
||||
@@ -129,6 +135,13 @@ export function AutomationDetail({
|
||||
</div>
|
||||
)
|
||||
}
|
||||
const usageSummary = summarizeAutomationRunUsage(runs)
|
||||
const usageCoverage =
|
||||
usageSummary.knownRuns > 0
|
||||
? `${usageSummary.knownRuns}/${runs.length} runs`
|
||||
: usageSummary.unavailableRuns > 0
|
||||
? 'Unavailable'
|
||||
: 'No runs'
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-col gap-4">
|
||||
@@ -175,8 +188,7 @@ export function AutomationDetail({
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="grid grid-cols-4 gap-6 rounded-md border border-border/50 bg-muted/30 px-4 py-3 shadow-sm">
|
||||
<DetailMetric label="Run location" value={`${projectName} / ${workspaceName}`} />
|
||||
<div className="grid grid-cols-6 gap-6 rounded-md border border-border/50 bg-muted/30 px-4 py-3 shadow-sm">
|
||||
<DetailMetric
|
||||
label="Next run"
|
||||
value={
|
||||
@@ -189,6 +201,12 @@ export function AutomationDetail({
|
||||
label="Last run"
|
||||
value={formatAutomationDateTimeWithRelative(automation.lastRunAt, now)}
|
||||
/>
|
||||
<DetailMetric
|
||||
label="Est. spend"
|
||||
value={formatAutomationCost(usageSummary.estimatedCostUsd)}
|
||||
/>
|
||||
<DetailMetric label="Tokens" value={formatAutomationTokens(usageSummary.totalTokens)} />
|
||||
<DetailMetric label="Usage coverage" value={usageCoverage} />
|
||||
<DetailMetric label="Grace" value={formatGrace(automation.missedRunGraceMinutes)} />
|
||||
</div>
|
||||
|
||||
@@ -228,9 +246,11 @@ export function AutomationDetail({
|
||||
<div className="text-sm font-medium">Run history</div>
|
||||
<div className="text-xs text-muted-foreground">{runs.length} runs</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-[minmax(10rem,1fr)_minmax(12rem,1.4fr)_minmax(6rem,auto)] gap-3 border-b border-border/50 px-3 py-1.5 text-[11px] font-medium uppercase text-muted-foreground">
|
||||
<div className="grid grid-cols-[minmax(9rem,1fr)_minmax(11rem,1.2fr)_minmax(5rem,.55fr)_minmax(5rem,.55fr)_minmax(6rem,auto)] gap-3 border-b border-border/50 px-3 py-1.5 text-[11px] font-medium uppercase text-muted-foreground">
|
||||
<div>Run</div>
|
||||
<div>Workspace</div>
|
||||
<div>Spend</div>
|
||||
<div>Tokens</div>
|
||||
<div>Status</div>
|
||||
</div>
|
||||
<div className="divide-y divide-border/50">
|
||||
@@ -240,13 +260,16 @@ export function AutomationDetail({
|
||||
? (runWorktree?.displayName ?? 'Missing workspace')
|
||||
: 'Not launched'
|
||||
const rowClassName =
|
||||
'grid grid-cols-[minmax(10rem,1fr)_minmax(12rem,1.4fr)_minmax(6rem,auto)] items-center gap-3 px-3 py-2 text-left text-sm outline-none transition-colors'
|
||||
'grid grid-cols-[minmax(9rem,1fr)_minmax(11rem,1.2fr)_minmax(5rem,.55fr)_minmax(5rem,.55fr)_minmax(6rem,auto)] items-center gap-3 px-3 py-2 text-left text-sm outline-none transition-colors'
|
||||
const usageLabel = getAutomationUsageStatusLabel(run.usage)
|
||||
const rowContent = (
|
||||
<>
|
||||
<div className="min-w-0">
|
||||
<div>{formatAutomationDateTime(run.scheduledFor)}</div>
|
||||
{run.error ? (
|
||||
<div className="mt-1 truncate text-xs text-muted-foreground">{run.error}</div>
|
||||
{run.error || run.usage?.status === 'unavailable' ? (
|
||||
<div className="mt-1 truncate text-xs text-muted-foreground">
|
||||
{run.error ?? run.usage?.unavailableMessage}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div
|
||||
@@ -258,6 +281,28 @@ export function AutomationDetail({
|
||||
>
|
||||
{workspaceLabel}
|
||||
</div>
|
||||
<div
|
||||
className={
|
||||
run.usage?.status === 'known'
|
||||
? 'text-sm tabular-nums'
|
||||
: 'text-sm text-muted-foreground'
|
||||
}
|
||||
title={usageLabel}
|
||||
>
|
||||
{formatAutomationCost(run.usage?.estimatedCostUsd)}
|
||||
</div>
|
||||
<div
|
||||
className={
|
||||
run.usage?.status === 'known'
|
||||
? 'text-sm tabular-nums'
|
||||
: 'text-sm text-muted-foreground'
|
||||
}
|
||||
title={usageLabel}
|
||||
>
|
||||
{run.usage?.status === 'known'
|
||||
? formatAutomationTokens(run.usage.totalTokens)
|
||||
: 'n/a'}
|
||||
</div>
|
||||
<div className="flex justify-start">
|
||||
<Badge variant={getAutomationRunStatusVariant(run.status)}>
|
||||
{getAutomationRunStatusLabel(run.status)}
|
||||
|
||||
@@ -37,6 +37,11 @@ import type {
|
||||
import type { Worktree } from '../../../../shared/types'
|
||||
import { buildAutomationRrule, parseAutomationRrule } from '../../../../shared/automation-schedules'
|
||||
import { formatAutomationDateTimeWithRelative } from './automation-page-parts'
|
||||
import {
|
||||
formatAutomationCost,
|
||||
formatAutomationTokens,
|
||||
summarizeAutomationRunUsage
|
||||
} from './automation-usage-model'
|
||||
import { AutomationDetail } from './AutomationDetail'
|
||||
import { AutomationEditorDialog, type AutomationDraft } from './AutomationEditorDialog'
|
||||
import { ExternalAutomationManagers } from './ExternalAutomationManagers'
|
||||
@@ -739,6 +744,17 @@ export default function AutomationsPage(): React.JSX.Element {
|
||||
automation.workspaceMode === 'new_per_run'
|
||||
? 'New workspace each run'
|
||||
: (automationWorktree?.displayName ?? 'Missing workspace')
|
||||
const usageSummary = summarizeAutomationRunUsage(
|
||||
runs.filter((run) => run.automationId === automation.id)
|
||||
)
|
||||
const usageText =
|
||||
usageSummary.knownRuns > 0
|
||||
? `${formatAutomationCost(
|
||||
usageSummary.estimatedCostUsd
|
||||
)} est. · ${formatAutomationTokens(usageSummary.totalTokens)} tokens`
|
||||
: usageSummary.unavailableRuns > 0
|
||||
? 'Usage unavailable'
|
||||
: 'No run usage yet'
|
||||
return (
|
||||
<ContextMenu key={automation.id}>
|
||||
<ContextMenuTrigger asChild>
|
||||
@@ -774,6 +790,7 @@ export default function AutomationsPage(): React.JSX.Element {
|
||||
)}`
|
||||
: 'Paused'}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">{usageText}</span>
|
||||
</button>
|
||||
</ContextMenuTrigger>
|
||||
<ContextMenuContent className="w-48">
|
||||
|
||||
@@ -121,6 +121,7 @@ export function ExternalAutomationManagers({
|
||||
<Badge variant={job.enabled ? 'secondary' : 'outline'}>
|
||||
{job.enabled ? 'Active' : 'Paused'}
|
||||
</Badge>
|
||||
<Badge variant="outline">Usage unsupported</Badge>
|
||||
</div>
|
||||
<div className="mt-1 truncate text-xs text-muted-foreground">
|
||||
{job.schedule} · next {formatExternalDate(job.nextRunAt, now)}
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { AutomationRun } from '../../../../shared/automations-types'
|
||||
import {
|
||||
formatAutomationCost,
|
||||
formatAutomationTokens,
|
||||
summarizeAutomationRunUsage
|
||||
} from './automation-usage-model'
|
||||
|
||||
function makeRun(overrides: Partial<AutomationRun>): AutomationRun {
|
||||
return {
|
||||
id: 'run-1',
|
||||
automationId: 'automation-1',
|
||||
title: 'Run 1',
|
||||
scheduledFor: 1,
|
||||
status: 'completed',
|
||||
trigger: 'manual',
|
||||
workspaceId: 'wt1',
|
||||
sessionKind: 'terminal',
|
||||
chatSessionId: null,
|
||||
terminalSessionId: 'tab-1',
|
||||
usage: null,
|
||||
error: null,
|
||||
startedAt: 1,
|
||||
dispatchedAt: 1,
|
||||
createdAt: 1,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
describe('automation usage model', () => {
|
||||
it('rolls known run usage up while preserving unavailable coverage', () => {
|
||||
const summary = summarizeAutomationRunUsage([
|
||||
makeRun({
|
||||
usage: {
|
||||
status: 'known',
|
||||
provider: 'codex',
|
||||
model: 'gpt-5.4',
|
||||
inputTokens: 1000,
|
||||
outputTokens: 300,
|
||||
cacheReadTokens: 400,
|
||||
cacheWriteTokens: null,
|
||||
reasoningOutputTokens: 50,
|
||||
totalTokens: 1350,
|
||||
estimatedCostUsd: 0.0042,
|
||||
estimatedCostSource: 'api_equivalent',
|
||||
providerSessionId: 'session-1',
|
||||
attribution: 'provider_session_time_window',
|
||||
collectedAt: 1,
|
||||
unavailableReason: null,
|
||||
unavailableMessage: null
|
||||
}
|
||||
}),
|
||||
makeRun({
|
||||
id: 'run-2',
|
||||
usage: {
|
||||
status: 'unavailable',
|
||||
provider: 'claude',
|
||||
model: null,
|
||||
inputTokens: null,
|
||||
outputTokens: null,
|
||||
cacheReadTokens: null,
|
||||
cacheWriteTokens: null,
|
||||
reasoningOutputTokens: null,
|
||||
totalTokens: null,
|
||||
estimatedCostUsd: null,
|
||||
estimatedCostSource: null,
|
||||
providerSessionId: null,
|
||||
attribution: null,
|
||||
collectedAt: 2,
|
||||
unavailableReason: 'no_matching_session',
|
||||
unavailableMessage: 'No matching session'
|
||||
}
|
||||
})
|
||||
])
|
||||
|
||||
expect(summary).toEqual({
|
||||
knownRuns: 1,
|
||||
unavailableRuns: 1,
|
||||
inputTokens: 1000,
|
||||
outputTokens: 300,
|
||||
cacheTokens: 400,
|
||||
reasoningOutputTokens: 50,
|
||||
totalTokens: 1350,
|
||||
estimatedCostUsd: 0.0042
|
||||
})
|
||||
})
|
||||
|
||||
it('formats compact token and cost labels', () => {
|
||||
expect(formatAutomationTokens(1250)).toBe('1.3k')
|
||||
expect(formatAutomationTokens(1_250_000)).toBe('1.3M')
|
||||
expect(formatAutomationCost(null)).toBe('n/a')
|
||||
expect(formatAutomationCost(0.0042)).toBe('$0.0042')
|
||||
expect(formatAutomationCost(1.234)).toBe('$1.23')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,93 @@
|
||||
import type { AutomationRun, AutomationRunUsage } from '../../../../shared/automations-types'
|
||||
|
||||
export type AutomationUsageSummary = {
|
||||
knownRuns: number
|
||||
unavailableRuns: number
|
||||
inputTokens: number
|
||||
outputTokens: number
|
||||
cacheTokens: number
|
||||
reasoningOutputTokens: number
|
||||
totalTokens: number
|
||||
estimatedCostUsd: number | null
|
||||
}
|
||||
|
||||
export function summarizeAutomationRunUsage(
|
||||
runs: readonly AutomationRun[]
|
||||
): AutomationUsageSummary {
|
||||
let knownRuns = 0
|
||||
let unavailableRuns = 0
|
||||
let inputTokens = 0
|
||||
let outputTokens = 0
|
||||
let cacheTokens = 0
|
||||
let reasoningOutputTokens = 0
|
||||
let totalTokens = 0
|
||||
let estimatedCostUsd = 0
|
||||
let hasKnownCost = false
|
||||
|
||||
for (const run of runs) {
|
||||
const usage = run.usage
|
||||
if (!usage) {
|
||||
unavailableRuns++
|
||||
continue
|
||||
}
|
||||
if (usage.status !== 'known') {
|
||||
unavailableRuns++
|
||||
continue
|
||||
}
|
||||
knownRuns++
|
||||
inputTokens += usage.inputTokens ?? 0
|
||||
outputTokens += usage.outputTokens ?? 0
|
||||
cacheTokens += (usage.cacheReadTokens ?? 0) + (usage.cacheWriteTokens ?? 0)
|
||||
reasoningOutputTokens += usage.reasoningOutputTokens ?? 0
|
||||
totalTokens += usage.totalTokens ?? 0
|
||||
if (usage.estimatedCostUsd !== null) {
|
||||
estimatedCostUsd += usage.estimatedCostUsd
|
||||
hasKnownCost = true
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
knownRuns,
|
||||
unavailableRuns,
|
||||
inputTokens,
|
||||
outputTokens,
|
||||
cacheTokens,
|
||||
reasoningOutputTokens,
|
||||
totalTokens,
|
||||
estimatedCostUsd: hasKnownCost ? estimatedCostUsd : null
|
||||
}
|
||||
}
|
||||
|
||||
export function formatAutomationTokens(value: number | null | undefined): string {
|
||||
if (!value) {
|
||||
return '0'
|
||||
}
|
||||
if (value >= 1_000_000) {
|
||||
return `${(value / 1_000_000).toFixed(value >= 10_000_000 ? 0 : 1)}M`
|
||||
}
|
||||
if (value >= 1_000) {
|
||||
return `${(value / 1_000).toFixed(value >= 10_000 ? 0 : 1)}k`
|
||||
}
|
||||
return value.toLocaleString()
|
||||
}
|
||||
|
||||
export function formatAutomationCost(value: number | null | undefined): string {
|
||||
if (value === null || value === undefined) {
|
||||
return 'n/a'
|
||||
}
|
||||
if (value > 0 && value < 0.01) {
|
||||
return `$${value.toFixed(4)}`
|
||||
}
|
||||
return `$${value.toFixed(2)}`
|
||||
}
|
||||
|
||||
export function getAutomationUsageStatusLabel(
|
||||
usage: AutomationRunUsage | null | undefined
|
||||
): string {
|
||||
if (!usage || usage.status === 'unavailable') {
|
||||
return usage?.unavailableMessage ?? 'Usage unavailable'
|
||||
}
|
||||
const cost = formatAutomationCost(usage.estimatedCostUsd)
|
||||
const tokens = formatAutomationTokens(usage.totalTokens)
|
||||
return `${tokens} tokens · ${cost}`
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
/* eslint-disable max-lines -- Why: this component owns diff rendering, image previews, comment popovers, and expansion state as one synchronized editor row. */
|
||||
import {
|
||||
lazy,
|
||||
useCallback,
|
||||
|
||||
@@ -16,6 +16,36 @@ export type AutomationRunStatus =
|
||||
export type AutomationRunTrigger = 'scheduled' | 'manual'
|
||||
|
||||
export type AutomationSchedulePreset = 'hourly' | 'daily' | 'weekdays' | 'weekly'
|
||||
export type AutomationRunUsageProvider = 'claude' | 'codex'
|
||||
export type AutomationRunUsageStatus = 'known' | 'unavailable'
|
||||
export type AutomationRunUsageAttribution = 'provider_session_time_window'
|
||||
export type AutomationRunUsageUnavailableReason =
|
||||
| 'run_not_finished'
|
||||
| 'provider_unsupported'
|
||||
| 'remote_usage_unavailable'
|
||||
| 'usage_not_enabled'
|
||||
| 'scan_failed'
|
||||
| 'no_matching_session'
|
||||
| 'ambiguous_session'
|
||||
|
||||
export type AutomationRunUsage = {
|
||||
status: AutomationRunUsageStatus
|
||||
provider: AutomationRunUsageProvider | null
|
||||
model: string | null
|
||||
inputTokens: number | null
|
||||
outputTokens: number | null
|
||||
cacheReadTokens: number | null
|
||||
cacheWriteTokens: number | null
|
||||
reasoningOutputTokens: number | null
|
||||
totalTokens: number | null
|
||||
estimatedCostUsd: number | null
|
||||
estimatedCostSource: 'api_equivalent' | null
|
||||
providerSessionId: string | null
|
||||
attribution: AutomationRunUsageAttribution | null
|
||||
collectedAt: number
|
||||
unavailableReason: AutomationRunUsageUnavailableReason | null
|
||||
unavailableMessage: string | null
|
||||
}
|
||||
|
||||
export type Automation = {
|
||||
id: string
|
||||
@@ -52,6 +82,7 @@ export type AutomationRun = {
|
||||
sessionKind: 'terminal'
|
||||
chatSessionId: string | null
|
||||
terminalSessionId: string | null
|
||||
usage: AutomationRunUsage | null
|
||||
error: string | null
|
||||
startedAt: number | null
|
||||
dispatchedAt: number | null
|
||||
@@ -101,6 +132,7 @@ export type AutomationDispatchResult = {
|
||||
status: AutomationRunStatus
|
||||
workspaceId?: string | null
|
||||
terminalSessionId?: string | null
|
||||
usage?: AutomationRunUsage | null
|
||||
error?: string | null
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user