feat: add OpenCode usage statistics #7221
Closedtris203(GitHub profile, opens in a new tab)wants to merge 15 commits into
main fromrefs/pull/7221/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- packages/contracts/src/usage.ts line 27OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -23,4 +24,4 @@2324 */2425 export const USAGE_CONTRACT_VERSION = 4 as const;252626-export const UsageProviderKind = Schema.Literals(["claude", "codex"]);27+export const UsageProviderKind = Schema.Literals(["claude", "codex", "opencode"]);apps/server/src/usage/UsageService.ts line 315OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -261,7 +295,21 @@295+ * window-independent, which holds for the per-session JSONL transcripts.296+ * OpenCode's source is one SQLite database queried with a window filter, so a297+ * cached entry only ever covers the window it was scanned for and a wider298+ * window would silently reuse it. The windowed query is fast enough that the299+ * cache buys nothing, so OpenCode always scans fresh.300+ */261301 const readFileRecords = (262302 filePath: string,263303 size: number,264304 mtimeMs: number,265305 provider: UsageProviderKind,306+ windowStartMs?: number,266307 ): Effect.Effect<readonly UsageRecord[]> =>267308 Effect.gen(function* () {309+ if (provider === "opencode") {310+ const parsed = yield* Effect.promise(() =>311+ readOpenCodeRecords(filePath, windowStartMs ?? 0),312+ );313+ // A read failure is not an empty transcript: reporting zero usage314+ // would silently drop the source's usage.315+ return parsed ?? [];
- apps/web/src/components/usage/usageProviders.ts lines 33 to 37Resolvedby tris203(GitHub profile, opens in a new tab)@@ -24,3 +24,8 @@2424 color: "#d97757",2525 mark: ClaudeAI,2626 },27+ opencode: {28+ label: "OpenCode",29+ color: "#8b5cf6",30+ mark: OpenCodeIcon,31+ },
- apps/server/src/usage/UsageService.ts line 232Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -199,0 +205,21 @@205+ * `<dataHome>/opencode.db`. The data home follows XDG, so a Linux default206+ * install lives in `~/.local/share/opencode` while macOS uses207+ * `~/Library/Application Support/opencode`. `OPENCODE_DATA_HOME` wins when208+ * set, matching the CLI.209+ */210+ const resolveOpenCodeDatabasePath = Effect.fn("UsageService.resolveOpenCodeDatabasePath")(211+ function* () {212+ const platform = yield* HostProcessPlatform;213+ const env = yield* HostProcessEnvironment;214+ const override = env["OPENCODE_DATA_HOME"]?.trim();215+ if (override !== undefined && override.length > 0) {216+ return path.join(path.resolve(expandHomePath(override)), "opencode.db");217+ }218+ const dataHome =219+ platform === "darwin"220+ ? path.join(NodeOS.homedir(), "Library", "Application Support", "opencode")221+ : path.join(222+ env["XDG_DATA_HOME"] ?? path.join(NodeOS.homedir(), ".local", "share"),223+ "opencode",224+ );225+ return path.join(dataHome, "opencode.db");apps/server/src/usage/UsageService.ts line 216OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -197,3 +200,17 @@197200 return nestedExists ? nested : path.join(homePath, "projects");198201 });199202203+ /**204+ * OpenCode keeps its transcripts in a SQLite database at205+ * `<dataHome>/opencode.db`. The data home follows XDG, so a Linux default206+ * install lives in `~/.local/share/opencode` while macOS uses207+ * `~/Library/Application Support/opencode`. `OPENCODE_DATA_HOME` wins when208+ * set, matching the CLI.209+ */210+ const resolveOpenCodeDatabasePath = Effect.fn("UsageService.resolveOpenCodeDatabasePath")(211+ function* () {212+ const platform = yield* HostProcessPlatform;213+ const env = yield* HostProcessEnvironment;214+ const override = env["OPENCODE_DATA_HOME"]?.trim();215+ if (override !== undefined && override.length > 0) {216+ return path.join(path.resolve(expandHomePath(override)), "opencode.db");
- apps/server/src/usage/usageTranscriptReader.ts line 183OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -141,0 +163,21 @@163+ session_id AS sessionId,164+ time_created AS timestampMs,165+ json_extract(data, '$.modelID') AS modelId,166+ json_extract(data, '$.tokens.input') AS inputTokens,167+ json_extract(data, '$.tokens.output') AS outputTokens,168+ json_extract(data, '$.tokens.reasoning') AS reasoningTokens,169+ json_extract(data, '$.tokens.cache.read') AS cacheReadTokens,170+ json_extract(data, '$.tokens.cache.write') AS cacheWriteTokens,171+ json_extract(data, '$.cost') AS costUsd172+ FROM message173+ WHERE time_updated >= ?174+ AND json_valid(data)175+ AND json_extract(data, '$.role') = 'assistant'176+ AND json_extract(data, '$.time.completed') IS NOT NULL177+`;178+179+const OPEN_CODE_CURRENT_USAGE_QUERY = `180+ SELECT181+ id AS messageId,182+ session_id AS sessionId,183+ time_created AS timestampMs,apps/server/src/usage/usageTranscriptReader.ts line 231Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -141,0 +175,21 @@175+ AND json_extract(data, '$.role') = 'assistant'176+ AND json_extract(data, '$.time.completed') IS NOT NULL177+`;178+179+const OPEN_CODE_CURRENT_USAGE_QUERY = `180+ SELECT181+ id AS messageId,182+ session_id AS sessionId,183+ time_created AS timestampMs,184+ json_extract(data, '$.model.id') AS modelId,185+ json_extract(data, '$.tokens.input') AS inputTokens,186+ json_extract(data, '$.tokens.output') AS outputTokens,187+ json_extract(data, '$.tokens.reasoning') AS reasoningTokens,188+ json_extract(data, '$.tokens.cache.read') AS cacheReadTokens,189+ json_extract(data, '$.tokens.cache.write') AS cacheWriteTokens,190+ json_extract(data, '$.cost') AS costUsd191+ FROM session_message192+ WHERE time_created >= ?193+ AND type = 'assistant'194+ AND json_valid(data)195+`;
- apps/server/src/usage/UsageService.ts line 489Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -374,0 +456,21 @@456+ const failed = stats === null || records === null;457+ const scanned = records ?? [];458+ // Distinct per database. Buckets carry per-cell session counts, but a459+ // session spans days and models, so clients total this figure instead.460+ const sessionIds = new Set<string>();461+ for (const record of scanned) {462+ // Only sessions that contributed in-window count: the query slack463+ // admits boundary rows whose timestamps fall outside the range.464+ if (aggregator.add(record) && record.sessionId.length > 0) {465+ sessionIds.add(record.sessionId);466+ }467+ }468+ sources.push({469+ fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },470+ status: failed ? "failed" : "ok",471+ scannedFiles: scanned.length > 0 ? 1 : 0,472+ skippedFiles: scanned.length > 0 ? 0 : 1,473+ malformedRecords: 0,474+ distinctSessions: sessionIds.size,475+ message: failed ? "Transcript database could not be read." : null,476+ });apps/server/src/usage/usageTranscriptReader.ts line 226OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -141,0 +206,21 @@206+ * Reads usage records from OpenCode's SQLite transcript store.207+ *208+ * Unlike the JSONL providers, OpenCode keeps one row per message in209+ * `opencode.db`, so the whole source is one query. The window filter is pushed210+ * into SQL using the completed timestamp, so usage is attributed to the hour211+ * or day the turn finished. The database is opened read-only, and212+ * `-wal`/`-shm` siblings are never created because no write happens.213+ *214+ * An upgraded database can carry the same message ID in both projections; the215+ * current `session_message` row wins. Returns `null` when the database cannot216+ * be read, so the caller reports the source as failed rather than zero usage.217+ */218+export async function readOpenCodeRecords(219+ dbPath: string,220+ sinceMs: number,221+): Promise<readonly UsageRecord[] | null> {222+ let database: NodeSqlite.DatabaseSync;223+ try {224+ database = new NodeSqlite.DatabaseSync(dbPath, { readOnly: true });225+ } catch {226+ return null;
- apps/server/src/usage/usageTranscriptReader.ts line 255OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -141,0 +235,21 @@235+ database = new NodeSqlite.DatabaseSync(dbPath, {236+ readOnly: true,237+ timeout: OPEN_CODE_SQLITE_BUSY_TIMEOUT_MS,238+ });239+ } catch {240+ return null;241+ }242+243+ try {244+ const tables = new Set<OpenCodeMessageTable>();245+ for (const row of database.prepare(OPEN_CODE_MESSAGE_TABLES_QUERY).all()) {246+ const name = (row as Record<string, unknown>)["name"];247+ if (name === "session_message" || name === "message") tables.add(name);248+ }249+ if (tables.size === 0) return null;250+251+ const recordsByKey = new Map<string, UsageRecord>();252+ let anonymous = 0;253+ for (const table of ["session_message", "message"] as const) {254+ if (!tables.has(table)) continue;255+ const rows = database.prepare(OPEN_CODE_TABLE_QUERIES[table]).all(sinceMs);
- apps/server/src/usage/UsageService.ts line 538Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -399,9 +512,12 @@399512400513 sources.push({401514 fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },402- status: "ok",515+ status: listing.hadReadError || failedFiles > 0 ? "partial" : "ok",403516 scannedFiles,404517 skippedFiles,405518 malformedRecords: 0,406519 distinctSessions: sessionIds.size,407- message: null,520+ message:521+ listing.hadReadError || failedFiles > 0522+ ? "Some transcript files could not be read."523+ : null,
t3dotgg(GitHub profile, opens in a new tab) added labelsvouch:trusted
t3dotgg(GitHub profile, opens in a new tab) removed labelsvouch:unvouched
- apps/server/src/usage/UsageService.ts line 530Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -399,4 +512,4 @@399512400513 sources.push({401514 fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },402- status: "ok",515+ status: listing.hadReadError || failedFiles > 0 ? "partial" : "ok",
- apps/server/src/usage/usageTranscriptReader.ts line 81OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -65,3 +78,4 @@6578 }6679 } catch {6780 // Vanished between readdir and stat.81+ hadReadError = true;
- apps/server/src/usage/UsageService.ts line 331Resolvedby tris203(GitHub profile, opens in a new tab)@@ -276,7 +312,20 @@312+ *313+ * The `(size, mtime)` identity assumes a file's contents are314+ * window-independent, which holds for the per-session JSONL transcripts.315+ * OpenCode's source is one SQLite database queried with a window filter, so a316+ * cached entry only ever covers the window it was scanned for and a wider317+ * window would silently reuse it. The scalar-only windowed query is fast318+ * enough that the cache buys nothing, so OpenCode always scans fresh.319+ */276320 const readFileRecords = (277321 filePath: string,278322 size: number,279323 mtimeMs: number,280324 provider: UsageProviderKind,281- ): Effect.Effect<readonly UsageRecord[]> =>325+ windowStartMs?: number,326+ ): Effect.Effect<readonly UsageRecord[] | null> =>282327 Effect.gen(function* () {328+ if (provider === "opencode") {329+ // A read failure is not an empty transcript: returning null lets the330+ // caller report the source as failed instead of zero usage.331+ return yield* Effect.promise(() => readOpenCodeRecords(filePath, windowStartMs ?? 0));
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/usage/usageTranscriptReader.ts line 329OutdatedResolvedby tris203(GitHub profile, opens in a new tab)@@ -158,0 +309,21 @@309+ } catch {310+ return null;311+ }312+ })();313+ if (worker === null) {314+ resolve(null);315+ return;316+ }317+318+ let settled = false;319+ const finish = (value: readonly OpenCodeWorkerRows[] | null) => {320+ if (settled) return;321+ settled = true;322+ resolve(value);323+ };324+325+ worker.once("message", (message: OpenCodeWorkerResult) => {326+ finish(message.status === "ok" ? message.groups : null);327+ });328+ worker.once("error", () => finish(null));329+ worker.once("exit", () => finish(null));
t3dotgg(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
2d6cc8c9-622d-4e86-87ca-e47fc0d72b30You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Comment `@coderabbitai help` to get the list of available commands.