Repository navigation
Feat/token usage analytics #5736
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
a7e95e4
fix(server): bound editor discovery when loading config
Vedant817 a421c40
feat(contracts): define token usage query contracts
Vedant817 64f415a
feat(contracts): add provider usage observations
Vedant817 f7217d2
feat(server): add durable token usage ledger
Vedant817 2777d32
feat(server): capture provider token usage
Vedant817 f6af197
feat(server): expose token usage query
Vedant817 d8495e4
feat(web): add token usage settings page
Vedant817 57d2853
docs: record token usage analytics implementation
Vedant817 b7a1a7c
Merge remote-tracking branch 'upstream/main' into feat/token-usage-an…
Vedant817 c47b199
Revert "feat(web): add token usage settings page"
Vedant817 99c283a
Revert "feat(server): capture provider token usage"
Vedant817 53642b4
Revert "feat(server): add durable token usage ledger"
Vedant817 b883c5b
Revert "feat(contracts): define token usage query contracts"
Vedant817 9ee2966
feat(usage): include OpenCode activity
Vedant817 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| // @effect-diagnostics nodeBuiltinImport:off | ||
| // @effect-diagnostics globalDate:off | ||
| import * as NodeFS from "node:fs"; | ||
| import * as NodeOS from "node:os"; | ||
| import * as NodePath from "node:path"; | ||
| import * as NodeSqlite from "node:sqlite"; | ||
|
|
||
| import { describe, expect, it } from "@effect/vitest"; | ||
|
|
||
| import { | ||
| parseOpenCodeMessageRow, | ||
| readOpenCodeUsage, | ||
| resolveOpenCodeDataDir, | ||
| } from "./usageOpenCodeReader.ts"; | ||
|
|
||
| function assistantMessage(overrides: Record<string, unknown> = {}) { | ||
| return { | ||
| id: "msg_1", | ||
| sessionID: "ses_1", | ||
| role: "assistant", | ||
| modelID: "deepseek-v4-flash-free", | ||
| providerID: "opencode", | ||
| time: { created: 1_786_211_758_317, completed: 1_786_211_767_010 }, | ||
| cost: 0, | ||
| tokens: { | ||
| input: 137, | ||
| output: 851, | ||
| reasoning: 230, | ||
| cache: { read: 99_200, write: 12 }, | ||
| }, | ||
| ...overrides, | ||
| }; | ||
| } | ||
|
|
||
| describe("parseOpenCodeMessageRow", () => { | ||
| it("maps OpenCode assistant usage without counting cache or reasoning twice", () => { | ||
| const record = parseOpenCodeMessageRow({ | ||
| id: "msg_1", | ||
| sessionId: "ses_1", | ||
| timeCreated: 1_786_211_758_317, | ||
| data: JSON.stringify(assistantMessage()), | ||
| }); | ||
|
|
||
| expect(record).toEqual({ | ||
| provider: "opencode", | ||
| timestampMs: 1_786_211_767_010, | ||
| model: "deepseek-v4-flash-free", | ||
| sessionId: "ses_1", | ||
| totals: { | ||
| uncachedInputTokens: 137, | ||
| cachedInputTokens: 99_200, | ||
| cacheCreationTokens: 12, | ||
| outputTokens: 851, | ||
| reasoningTokens: 230, | ||
| }, | ||
| reportedCostUsd: 0, | ||
| dedupeKey: "opencode:msg_1", | ||
| }); | ||
| }); | ||
|
|
||
| it("ignores non-assistant, malformed, zero-token, and model-less rows", () => { | ||
| const row = (data: unknown) => ({ | ||
| id: "msg_1", | ||
| sessionId: "ses_1", | ||
| timeCreated: 1_786_211_758_317, | ||
| data, | ||
| }); | ||
|
|
||
| expect(parseOpenCodeMessageRow(row("not json"))).toBeNull(); | ||
| expect( | ||
| parseOpenCodeMessageRow(row(JSON.stringify(assistantMessage({ role: "user" })))), | ||
| ).toBeNull(); | ||
| expect( | ||
| parseOpenCodeMessageRow( | ||
| row(JSON.stringify(assistantMessage({ tokens: { input: 0, output: 0 } }))), | ||
| ), | ||
| ).toBeNull(); | ||
| expect( | ||
| parseOpenCodeMessageRow(row(JSON.stringify(assistantMessage({ modelID: "" })))), | ||
| ).toBeNull(); | ||
| }); | ||
| }); | ||
|
|
||
| describe("resolveOpenCodeDataDir", () => { | ||
| it("uses XDG_DATA_HOME when configured and the documented default otherwise", () => { | ||
| expect(resolveOpenCodeDataDir("/home/dev", "/mnt/data")).toBe( | ||
| NodePath.join("/mnt/data", "opencode"), | ||
| ); | ||
| expect(resolveOpenCodeDataDir("/home/dev", undefined)).toBe( | ||
| NodePath.join("/home/dev", ".local", "share", "opencode"), | ||
| ); | ||
| }); | ||
| }); | ||
|
|
||
| describe("readOpenCodeUsage", () => { | ||
| it("reads current OpenCode SQLite messages and excludes older rows", async () => { | ||
| const dataDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-opencode-usage-")); | ||
| const databasePath = NodePath.join(dataDir, "opencode.db"); | ||
| const database = new NodeSqlite.DatabaseSync(databasePath); | ||
| database.exec( | ||
| "CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, time_created INTEGER, data TEXT)", | ||
| ); | ||
| const insert = database.prepare( | ||
| "INSERT INTO message (id, session_id, time_created, data) VALUES (?, ?, ?, ?)", | ||
| ); | ||
| insert.run("msg_old", "ses_old", 100, JSON.stringify(assistantMessage())); | ||
| insert.run( | ||
| "msg_new", | ||
| "ses_new", | ||
| 2_000, | ||
| JSON.stringify( | ||
| assistantMessage({ | ||
| id: "msg_new", | ||
| sessionID: "ses_new", | ||
| time: { created: 2_000, completed: 2_500 }, | ||
| }), | ||
| ), | ||
| ); | ||
| database.close(); | ||
|
|
||
| try { | ||
| const result = await readOpenCodeUsage(dataDir, 1_000); | ||
| expect(result?.storageKind).toBe("sqlite"); | ||
| expect(result?.scannedFiles).toBe(1); | ||
| expect(result?.records.map((record) => record.sessionId)).toEqual(["ses_new"]); | ||
| } finally { | ||
| NodeFS.rmSync(dataDir, { recursive: true, force: true }); | ||
| } | ||
| }); | ||
|
|
||
| it("falls back to the documented JSON message store when no database exists", async () => { | ||
| const dataDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-opencode-usage-")); | ||
| const messageDir = NodePath.join(dataDir, "storage", "message", "ses_legacy"); | ||
| const now = Date.now(); | ||
| NodeFS.mkdirSync(messageDir, { recursive: true }); | ||
| NodeFS.writeFileSync( | ||
| NodePath.join(messageDir, "msg_legacy.json"), | ||
| JSON.stringify( | ||
| assistantMessage({ | ||
| id: "msg_legacy", | ||
| sessionID: "ses_legacy", | ||
| time: { created: now, completed: now }, | ||
| }), | ||
| ), | ||
| ); | ||
|
|
||
| try { | ||
| const result = await readOpenCodeUsage(dataDir, now - 60_000); | ||
| expect(result?.storageKind).toBe("json"); | ||
| expect(result?.records.map((record) => record.sessionId)).toEqual(["ses_legacy"]); | ||
| } finally { | ||
| NodeFS.rmSync(dataDir, { recursive: true, force: true }); | ||
| } | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When
settings.providers.opencode.serverUrltargets an OpenCode server on another machine, this unconditionally scans the T3 server process's local XDG data directory. Sessions driven through the supported external-server path are stored remotely, so the Usage page reports the source as missing or silently omits all of that OpenCode activity; the reader needs to account for the configured server mode rather than treating the local store as authoritative.AGENTS.md reference: AGENTS.md:L19-L21
Useful? React with 👍 / 👎.