mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-12-03 03:29:51 +00:00
fix(opencode): read the 2.x session_v2 and session_message generation (#1436)
OpenCode 2.x (mainline since 2.0.3) writes sessions to session_v2 and messages to session_message, tagged by a type column and ordered by seq, while the legacy session/message/part tables freeze at upgrade. Every session created after the upgrade was invisible to CodeBurn. The parser now branches per database on sqlite_master: when the v2 tables exist they are read and the frozen legacy tables are ignored, otherwise the legacy path runs exactly as before. The two generations are never joined. v2 payloads normalize into the shared message/part shape, so tokens, cost, model refs, tools, bash commands, user attribution, the parent_id child-session walk and the session-level rollup fallback behave as they did on 1.x. Compaction rows carry their own cost and tokens in 2.0.3 and were counted as assistant messages on 1.x, so they are counted here too; a running compaction has no usage and yields nothing. Verified against a real 1.x database: the opencode report is unchanged at $109.91, 4,009 calls, 177 sessions. Fixes #1293.
This commit is contained in:
parent
dd1f11f528
commit
633ea32382
4 changed files with 407 additions and 48 deletions
|
|
@ -26,6 +26,7 @@
|
|||
- **The Capacity Dock card and the popover quota rows no longer print a pace verdict under each window.** The "On pace" / "Lasts until reset" caption from #1314 added a third line to every window cell and made the card read as clutter; the cells are back to percent, label and countdown, up to three windows share one row again with a fourth wrapping to a second, and the pace math still feeds the tooltip and the agent-tab card.
|
||||
|
||||
### Fixed
|
||||
- **OpenCode 2.x sessions show up again.** OpenCode 2.x (mainline since 2.0.3) writes sessions to a new `session_v2` table and messages to `session_message`, tagged by type and ordered by sequence, while the old `session`/`message`/`part` tables freeze at upgrade — so every session created after the upgrade was invisible. CodeBurn now branches per database on what actually exists: when the 2.x tables are there they are read and the frozen legacy tables are ignored, otherwise the legacy path runs exactly as before. Compaction requests keep their own cost and tokens counted, as they were on 1.x. (#1293)
|
||||
- **The Overview model table lists every model with usage in the period instead of stopping at twenty.** The period-scoped model list the table reads is no longer cut at 20 rows by the payload: on a machine with 47 models every local and free model (qwen, llama, deepseek, gemini, grok) had dropped out of the table — exactly the rows whose $0 cost ranks them last — while the same change was busy making those models visible in the Models tables. Every consumer that wants fewer rows already slices its own (the desktop hero takes 8, MCP tables take 5 or the caller's limit) and the macOS menubar reads a per-session list, so nothing else renders more. Two smaller items from the same review: the menubar Models row's compact token count gains a billions rung, so a period cache-read total past a billion reads `12.3B` instead of `12345.7M`, with the exact value still in the row's accessibility text, and the CLI tables gain the same rung through `formatTokens` (a `codeburn models` totals row now reads `29.9B` instead of `29870.8M`); and the desktop Models tables stop dimming the calls column on unpriced rows — calls are observed usage like the token columns, not a pricing artifact — while cost/saved keep their dashes and the add-alias affordance. In the shipped app unpriced rows do not reach that table yet: `codeburn models` defaults to `minCost: 0.01` and drops rows whose cost and savings are both under $0.01, and the desktop's `codeburn:getModels` passes no `--min-cost`/`--unpriced`, so the change only takes effect once that filter is addressed (tracked separately). Status snapshot revision 9 invalidates older cached payloads once, so a warm snapshot cannot keep serving the truncated 20-row list; daily and session cache formats are unchanged. (#1318)
|
||||
- **An unpriced Bedrock model now reaches the Unpriced list instead of being treated as free local inference.** Claude Code with `CLAUDE_CODE_USE_BEDROCK=1` records Bedrock's foundation-model id, which ends in a `-[v]<major>:<minor>` version (`anthropic.claude-haiku-4-5-20251001-v1:0`, `openai.gpt-oss-120b-1:0`). The local-model heuristic read that colon as an Ollama `:tag`, so a Bedrock model with no pricing row was classed as expected-free: it was excluded from `codeburn models --unpriced`, from the unpriced warning and from the pricing-coverage denominator, and its metered spend showed as $0 with nothing flagging the gap. The version shape is now exempted before the tag rule runs; Ollama and LM Studio tags are unaffected.
|
||||
- **The desktop header lists every provider CodeBurn detected, not only the ones that billed something this period.** `hasUsage: false` means a tool is installed and was idle in the selected window, which is a reason to grey the row, not to hide it: on Today the picker showed Claude alone while `codeburn doctor` listed sixteen. Idle providers now appear after the active ones, greyed, in the header picker and the Settings provider list.
|
||||
|
|
|
|||
|
|
@ -29,6 +29,18 @@ Precedence when no `dataDir` argument is passed (the production path):
|
|||
|
||||
SQLite (older builds) or file-based JSON (OpenCode 1.1+, under `storage/`).
|
||||
|
||||
OpenCode 2.x (mainline since 2.0.3, issue #1293) writes a second SQLite
|
||||
generation: `session_v2` + `session_message` (whose FK points at
|
||||
`session_v2(id)`; messages are tagged by a `type` column, ordered by `seq`,
|
||||
payload JSON in `data`). The legacy `session`/`message`/`part` tables freeze at
|
||||
upgrade — a post-upgrade session has rows in `session_message` and zero new
|
||||
rows in `message`. The parser branches per database on `sqlite_master`: when
|
||||
the v2 tables exist they win and the legacy tables are ignored entirely (the
|
||||
generations are never joined); otherwise the legacy path runs unchanged.
|
||||
Session-level cost/token rollups and the `parent_id` child-session walk exist
|
||||
in both generations, so discovery, parsing and dedup behave the same either
|
||||
way.
|
||||
|
||||
## Caching
|
||||
|
||||
None.
|
||||
|
|
|
|||
|
|
@ -48,6 +48,103 @@ type SessionTokenRow = {
|
|||
model?: Uint8Array | string
|
||||
}
|
||||
|
||||
type V2MessageRow = {
|
||||
session_id: string
|
||||
id: string
|
||||
type: string
|
||||
seq: number
|
||||
time_created: number
|
||||
data: Uint8Array | string
|
||||
}
|
||||
|
||||
/**
|
||||
* OpenCode 2.x generations (issue #1293): v2 writes `session_v2` + `session_message`
|
||||
* (its FK points at `session_v2(id)`), while the legacy `session`/`message`/`part`
|
||||
* tables freeze at upgrade and stay frozen — a session created on 2.x has rows in
|
||||
* `session_message` and zero new rows in `message`. The generations are never
|
||||
* joined: whichever exists decides what is read, and v2 wins when present.
|
||||
*/
|
||||
function detectGeneration(db: SqliteDatabase): 'v2' | 'legacy' | null {
|
||||
try {
|
||||
const v2 = db.query<{ cnt: number }>(
|
||||
"SELECT COUNT(*) as cnt FROM sqlite_master WHERE type = 'table' AND name IN ('session_v2', 'session_message')",
|
||||
)
|
||||
if ((v2[0]?.cnt ?? 0) === 2) return 'v2'
|
||||
} catch (err) {
|
||||
if (isSqliteBusyError(err)) throw err
|
||||
}
|
||||
return validateSchemaDetailed(db).ok ? 'legacy' : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes v2 `session_message` rows into the legacy message/part shape the
|
||||
* shared parse loop already consumes. v2 payloads are tagged by the `type`
|
||||
* column (no `role` field); assistant messages carry `content` inline (no part
|
||||
* table), `model` as a `{id, providerID}` ref, and `tokens` in the same
|
||||
* normalized shape legacy stored.
|
||||
*/
|
||||
function v2RowsToLegacyShape(rows: V2MessageRow[]): { messages: MessageRow[]; partsByMsg: Map<string, PartData[]> } {
|
||||
const messages: MessageRow[] = []
|
||||
const partsByMsg = new Map<string, PartData[]>()
|
||||
|
||||
for (const row of rows) {
|
||||
let payload: Record<string, unknown>
|
||||
try {
|
||||
payload = JSON.parse(blobToText(row.data)) as Record<string, unknown>
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
|
||||
if (row.type === 'user') {
|
||||
messages.push({ session_id: row.session_id, id: row.id, time_created: row.time_created, data: JSON.stringify({ role: 'user' }) })
|
||||
const text = typeof payload['text'] === 'string' ? payload['text'] : ''
|
||||
if (text) partsByMsg.set(row.id, [{ type: 'text', text }])
|
||||
continue
|
||||
}
|
||||
// Compaction rows carry their own CompactionUsage (cost + tokens for the
|
||||
// compaction request itself) and counted as assistant messages on 1.x, so
|
||||
// they must keep landing here or every compacted 2.x session undercounts.
|
||||
// A `running` compaction has neither and is dropped by buildAssistantCall.
|
||||
if (row.type !== 'assistant' && row.type !== 'compaction') continue
|
||||
|
||||
const model = payload['model']
|
||||
const data: MessageData = { role: 'assistant' }
|
||||
if (model !== null && typeof model === 'object' && !Array.isArray(model)) {
|
||||
const ref = model as Record<string, unknown>
|
||||
const id = typeof ref['id'] === 'string' ? ref['id'] : ''
|
||||
const providerID = typeof ref['providerID'] === 'string' ? ref['providerID'] : ''
|
||||
if (id && providerID) data.modelID = `${providerID}/${id}`
|
||||
}
|
||||
if (typeof payload['cost'] === 'number') data.cost = payload['cost']
|
||||
const tokens = payload['tokens']
|
||||
if (tokens !== null && typeof tokens === 'object' && !Array.isArray(tokens)) data.tokens = tokens as MessageData['tokens']
|
||||
|
||||
const parts: PartData[] = []
|
||||
const content = payload['content']
|
||||
if (Array.isArray(content)) {
|
||||
for (const item of content) {
|
||||
if (item === null || typeof item !== 'object') continue
|
||||
const c = item as Record<string, unknown>
|
||||
if ((c['type'] === 'text' || c['type'] === 'reasoning') && typeof c['text'] === 'string' && c['text']) {
|
||||
parts.push({ type: c['type'] as string, text: c['text'] })
|
||||
} else if (c['type'] === 'tool') {
|
||||
const state = c['state']
|
||||
const input = state !== null && typeof state === 'object' && (state as Record<string, unknown>)['input'] !== null
|
||||
&& typeof (state as Record<string, unknown>)['input'] === 'object'
|
||||
? (state as Record<string, unknown>)['input'] as Record<string, unknown>
|
||||
: {}
|
||||
parts.push({ type: 'tool', tool: typeof c['name'] === 'string' ? c['name'] : '', state: { input } })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
messages.push({ session_id: row.session_id, id: row.id, time_created: row.time_created, data: JSON.stringify(data) })
|
||||
partsByMsg.set(row.id, parts)
|
||||
}
|
||||
|
||||
return { messages, partsByMsg }
|
||||
}
|
||||
|
||||
function parseSessionModel(value: Uint8Array | string | undefined): string | undefined {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(blobToText(value))
|
||||
|
|
@ -62,15 +159,17 @@ function parseSessionModel(value: Uint8Array | string | undefined): string | und
|
|||
}
|
||||
}
|
||||
|
||||
function tryQuerySessionTokens(db: SqliteDatabase, sessionId: string): {
|
||||
function tryQuerySessionTokens(db: SqliteDatabase, sessionId: string, generation: 'v2' | 'legacy'): {
|
||||
cost: number; input: number; output: number; reasoning: number
|
||||
cacheRead: number; cacheWrite: number; model: string | undefined
|
||||
} | null {
|
||||
try {
|
||||
// Both generations expose the same token columns; only the table name moves.
|
||||
const table = generation === 'v2' ? 'session_v2' : 'session'
|
||||
const rows = db.query<SessionTokenRow>(
|
||||
`SELECT cost, tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write,
|
||||
CAST(model AS BLOB) AS model
|
||||
FROM session WHERE id = ?`,
|
||||
FROM ${table} WHERE id = ?`,
|
||||
[sessionId],
|
||||
)
|
||||
if (rows.length === 0) return null
|
||||
|
|
@ -151,53 +250,78 @@ export function createSqliteSessionParser(
|
|||
}
|
||||
|
||||
try {
|
||||
const schema = validateSchemaDetailed(db)
|
||||
if (!schema.ok) {
|
||||
warnUnrecognizedSchemaOnce(config.displayName, schema.missing)
|
||||
const generation = detectGeneration(db)
|
||||
if (generation === null) {
|
||||
const schema = validateSchemaDetailed(db)
|
||||
if (!schema.ok) warnUnrecognizedSchemaOnce(config.displayName, schema.missing)
|
||||
return
|
||||
}
|
||||
|
||||
const messages = db.query<MessageRow>(
|
||||
`WITH RECURSIVE session_tree(id) AS (
|
||||
SELECT id FROM session WHERE id = ?
|
||||
UNION
|
||||
SELECT child.id
|
||||
FROM session child
|
||||
JOIN session_tree parent ON child.parent_id = parent.id
|
||||
WHERE child.time_archived IS NULL
|
||||
)
|
||||
SELECT session_id, id, time_created, CAST(data AS BLOB) AS data
|
||||
FROM message
|
||||
WHERE session_id IN (SELECT id FROM session_tree)
|
||||
ORDER BY time_created ASC, id ASC`,
|
||||
[sessionId],
|
||||
)
|
||||
let messages: MessageRow[]
|
||||
let partsByMsg: Map<string, PartData[]>
|
||||
|
||||
const parts = db.query<PartRow>(
|
||||
`WITH RECURSIVE session_tree(id) AS (
|
||||
SELECT id FROM session WHERE id = ?
|
||||
UNION
|
||||
SELECT child.id
|
||||
FROM session child
|
||||
JOIN session_tree parent ON child.parent_id = parent.id
|
||||
WHERE child.time_archived IS NULL
|
||||
if (generation === 'v2') {
|
||||
const rows = db.query<V2MessageRow>(
|
||||
`WITH RECURSIVE session_tree(id) AS (
|
||||
SELECT id FROM session_v2 WHERE id = ?
|
||||
UNION
|
||||
SELECT child.id
|
||||
FROM session_v2 child
|
||||
JOIN session_tree parent ON child.parent_id = parent.id
|
||||
WHERE child.time_archived IS NULL
|
||||
)
|
||||
SELECT session_id, id, type, seq, time_created, CAST(data AS BLOB) AS data
|
||||
FROM session_message
|
||||
WHERE session_id IN (SELECT id FROM session_tree)
|
||||
ORDER BY time_created ASC, session_id ASC, seq ASC`,
|
||||
[sessionId],
|
||||
)
|
||||
const normalized = v2RowsToLegacyShape(rows)
|
||||
messages = normalized.messages
|
||||
partsByMsg = normalized.partsByMsg
|
||||
} else {
|
||||
messages = db.query<MessageRow>(
|
||||
`WITH RECURSIVE session_tree(id) AS (
|
||||
SELECT id FROM session WHERE id = ?
|
||||
UNION
|
||||
SELECT child.id
|
||||
FROM session child
|
||||
JOIN session_tree parent ON child.parent_id = parent.id
|
||||
WHERE child.time_archived IS NULL
|
||||
)
|
||||
SELECT session_id, id, time_created, CAST(data AS BLOB) AS data
|
||||
FROM message
|
||||
WHERE session_id IN (SELECT id FROM session_tree)
|
||||
ORDER BY time_created ASC, id ASC`,
|
||||
[sessionId],
|
||||
)
|
||||
SELECT message_id, CAST(data AS BLOB) AS data
|
||||
FROM part
|
||||
WHERE session_id IN (SELECT id FROM session_tree)
|
||||
ORDER BY message_id, id`,
|
||||
[sessionId],
|
||||
)
|
||||
|
||||
const partsByMsg = new Map<string, PartData[]>()
|
||||
for (const part of parts) {
|
||||
try {
|
||||
const parsed = JSON.parse(blobToText(part.data)) as PartData
|
||||
const list = partsByMsg.get(part.message_id) ?? []
|
||||
list.push(parsed)
|
||||
partsByMsg.set(part.message_id, list)
|
||||
} catch {
|
||||
// skip corrupt part data
|
||||
const parts = db.query<PartRow>(
|
||||
`WITH RECURSIVE session_tree(id) AS (
|
||||
SELECT id FROM session WHERE id = ?
|
||||
UNION
|
||||
SELECT child.id
|
||||
FROM session child
|
||||
JOIN session_tree parent ON child.parent_id = parent.id
|
||||
WHERE child.time_archived IS NULL
|
||||
)
|
||||
SELECT message_id, CAST(data AS BLOB) AS data
|
||||
FROM part
|
||||
WHERE session_id IN (SELECT id FROM session_tree)
|
||||
ORDER BY message_id, id`,
|
||||
[sessionId],
|
||||
)
|
||||
|
||||
partsByMsg = new Map<string, PartData[]>()
|
||||
for (const part of parts) {
|
||||
try {
|
||||
const parsed = JSON.parse(blobToText(part.data)) as PartData
|
||||
const list = partsByMsg.get(part.message_id) ?? []
|
||||
list.push(parsed)
|
||||
partsByMsg.set(part.message_id, list)
|
||||
} catch {
|
||||
// skip corrupt part data
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -251,7 +375,7 @@ export function createSqliteSessionParser(
|
|||
}
|
||||
|
||||
if (yieldCount === 0 && messages.length > 0) {
|
||||
const sessionTokens = tryQuerySessionTokens(db, sessionId)
|
||||
const sessionTokens = tryQuerySessionTokens(db, sessionId, generation)
|
||||
if (sessionTokens && (sessionTokens.cost > 0 || sessionTokens.input > 0 || sessionTokens.output > 0)) {
|
||||
const dedupKey = `${config.providerName}:${sessionId}:session-level`
|
||||
if (!seenKeys.has(dedupKey)) {
|
||||
|
|
@ -292,7 +416,7 @@ export function createSqliteSessionParser(
|
|||
process.stderr.write(
|
||||
`codeburn: ${config.displayName} session ${sessionId} has ${messages.length} messages ` +
|
||||
`(${parseFailCount} unparseable, ${roleSkipCount} non-user/assistant roles) ` +
|
||||
`but yielded 0 calls. Parts: ${parts.length}.\n`
|
||||
`but yielded 0 calls.\n`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
@ -331,11 +455,14 @@ export async function discoverSqliteSessions(
|
|||
}
|
||||
|
||||
try {
|
||||
const schema = validateSchemaDetailed(db)
|
||||
if (!schema.ok) continue
|
||||
const generation = detectGeneration(db)
|
||||
if (generation === null) continue
|
||||
|
||||
// Same projection on both generations; only the table name moves.
|
||||
const table = generation === 'v2' ? 'session_v2' : 'session'
|
||||
const rows = db.query<SessionRow>(
|
||||
'SELECT id, CAST(directory AS BLOB) AS directory, CAST(title AS BLOB) AS title, time_created FROM session WHERE time_archived IS NULL AND parent_id IS NULL ORDER BY time_created DESC',
|
||||
`SELECT id, CAST(directory AS BLOB) AS directory, CAST(title AS BLOB) AS title, time_created
|
||||
FROM ${table} WHERE time_archived IS NULL AND parent_id IS NULL ORDER BY time_created DESC`,
|
||||
)
|
||||
|
||||
for (const row of rows) {
|
||||
|
|
|
|||
|
|
@ -1043,3 +1043,222 @@ skipUnlessSqlite('opencode provider - env override discovery', () => {
|
|||
})
|
||||
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// OpenCode 2.x (session_v2 + session_message) — issue #1293.
|
||||
// ejwill's 2.0.3 schema: session_v2 carries the session row (with the same
|
||||
// cost/tokens columns legacy had), session_message is tagged by `type` with
|
||||
// the payload JSON in `data`, ordered by `seq`. Legacy tables freeze at
|
||||
// upgrade; the generations are never joined.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type V2MessageFixture = {
|
||||
text?: string
|
||||
agent?: string
|
||||
model?: { id: string; providerID: string; variant?: string }
|
||||
content?: Array<{ type: string; text?: string; name?: string; state?: { status: string; input?: Record<string, unknown> } }>
|
||||
cost?: number
|
||||
tokens?: { input: number; output: number; reasoning: number; cache: { read: number; write: number } }
|
||||
time?: { created: number }
|
||||
}
|
||||
|
||||
function createV2TestDb(dir: string, opts: { withLegacy?: boolean } = {}): string {
|
||||
const ocDir = join(dir, 'opencode')
|
||||
mkdirSync(ocDir, { recursive: true })
|
||||
const dbPath = join(ocDir, 'opencode.db')
|
||||
|
||||
const { DatabaseSync: Database } = require('node:sqlite')
|
||||
const db = new Database(dbPath)
|
||||
db.exec(`
|
||||
CREATE TABLE session_v2 (
|
||||
id TEXT PRIMARY KEY, project_id TEXT NOT NULL, parent_id TEXT,
|
||||
slug TEXT NOT NULL, directory TEXT NOT NULL, title TEXT, version TEXT NOT NULL,
|
||||
cost REAL NOT NULL DEFAULT 0, tokens_input INTEGER NOT NULL DEFAULT 0,
|
||||
tokens_output INTEGER NOT NULL DEFAULT 0, tokens_reasoning INTEGER NOT NULL DEFAULT 0,
|
||||
tokens_cache_read INTEGER NOT NULL DEFAULT 0, tokens_cache_write INTEGER NOT NULL DEFAULT 0,
|
||||
model TEXT, time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL,
|
||||
time_archived INTEGER
|
||||
)
|
||||
`)
|
||||
db.exec(`
|
||||
CREATE TABLE session_message (
|
||||
id TEXT PRIMARY KEY, session_id TEXT NOT NULL, type TEXT NOT NULL,
|
||||
seq INTEGER NOT NULL, time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL,
|
||||
data TEXT NOT NULL
|
||||
)
|
||||
`)
|
||||
if (opts.withLegacy) {
|
||||
// An in-place upgrade keeps the frozen legacy tables around, empty.
|
||||
db.exec(`CREATE TABLE session (id TEXT PRIMARY KEY, project_id TEXT NOT NULL, parent_id TEXT, slug TEXT NOT NULL, directory TEXT NOT NULL, title TEXT, version TEXT NOT NULL, time_created INTEGER, time_updated INTEGER, time_archived INTEGER)`)
|
||||
db.exec(`CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, time_created INTEGER, data TEXT NOT NULL)`)
|
||||
db.exec(`CREATE TABLE part (id TEXT PRIMARY KEY, message_id TEXT NOT NULL, session_id TEXT NOT NULL, data TEXT NOT NULL)`)
|
||||
}
|
||||
db.close()
|
||||
return dbPath
|
||||
}
|
||||
|
||||
function insertV2Session(
|
||||
db: TestDb,
|
||||
id: string,
|
||||
opts: { directory?: string; title?: string; parentId?: string | null; archived?: number | null; model?: string } = {},
|
||||
): void {
|
||||
db.prepare(`
|
||||
INSERT INTO session_v2 (id, project_id, parent_id, slug, directory, title, version, time_created, time_updated, time_archived, model)
|
||||
VALUES (?, 'proj-1', ?, 'slug-1', ?, ?, '2.0.3', 1700000000000, 1700000000000, ?, ?)
|
||||
`).run(id, opts.parentId ?? null, opts.directory ?? '/home/user/myproject', opts.title ?? 'My Project', opts.archived ?? null, opts.model ?? null)
|
||||
}
|
||||
|
||||
function insertV2Message(db: TestDb, id: string, sessionId: string, type: string, seq: number, timeCreated: number, payload: V2MessageFixture): void {
|
||||
db.prepare(`INSERT INTO session_message (id, session_id, type, seq, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?, ?, ?)`)
|
||||
.run(id, sessionId, type, seq, timeCreated, timeCreated, JSON.stringify(payload))
|
||||
}
|
||||
|
||||
skipUnlessSqlite('opencode provider - v2 generation (session_v2 + session_message)', () => {
|
||||
it('discovers and parses v2 sessions with tokens, cost, model, tools and user attribution', async () => {
|
||||
const dbPath = createV2TestDb(tmpDir)
|
||||
withTestDb(dbPath, (db) => {
|
||||
insertV2Session(db, 'ses_v2_1')
|
||||
insertV2Message(db, 'msg_1', 'ses_v2_1', 'user', 1, 1700000000000, { text: 'fix the login bug' })
|
||||
insertV2Message(db, 'msg_2', 'ses_v2_1', 'assistant', 2, 1700000000123, {
|
||||
agent: 'build',
|
||||
model: { id: 'glm-5.3-flash', providerID: 'opencode', variant: 'max' },
|
||||
content: [
|
||||
{ type: 'text', text: 'looking into it' },
|
||||
{ type: 'tool', name: 'bash', state: { status: 'completed', input: { command: 'grep -rn login src/' } } },
|
||||
],
|
||||
cost: 0.0077,
|
||||
tokens: { input: 21410, output: 2175, reasoning: 0, cache: { read: 112128, write: 0 } },
|
||||
time: { created: 1700000000123 },
|
||||
})
|
||||
})
|
||||
|
||||
const provider = createOpenCodeProvider(tmpDir)
|
||||
const sessions = await provider.discoverSessions()
|
||||
expect(sessions).toHaveLength(1)
|
||||
expect(sessions[0]!.path).toBe(`${dbPath}:ses_v2_1`)
|
||||
expect(sessions[0]!.project).toBe('home-user-myproject')
|
||||
|
||||
const calls = await collectCalls(provider, dbPath, 'ses_v2_1')
|
||||
expect(calls).toHaveLength(1)
|
||||
const call = calls[0]!
|
||||
expect(call.model).toBe('opencode/glm-5.3-flash')
|
||||
expect(call.inputTokens).toBe(21410)
|
||||
expect(call.outputTokens).toBe(2175)
|
||||
expect(call.cacheReadInputTokens).toBe(112128)
|
||||
expect(call.tools).toContain('Bash')
|
||||
expect(call.bashCommands).toEqual(['grep'])
|
||||
expect(call.userMessage).toBe('fix the login bug')
|
||||
expect(call.costUSD).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('counts compaction usage and skips rows with nothing to report', async () => {
|
||||
const dbPath = createV2TestDb(tmpDir)
|
||||
withTestDb(dbPath, (db) => {
|
||||
insertV2Session(db, 'ses_v2_1')
|
||||
insertV2Message(db, 'msg_1', 'ses_v2_1', 'model-switched', 1, 1700000000000, { model: { id: 'x', providerID: 'opencode' } })
|
||||
// CompactionUsage travels on the compaction row itself; 1.x counted
|
||||
// these as assistant messages, so dropping them undercounts compactions.
|
||||
insertV2Message(db, 'msg_2', 'ses_v2_1', 'compaction', 2, 1700000000100, {
|
||||
status: 'completed', reason: 'auto', summary: 's', recent: 'r',
|
||||
model: { id: 'glm-5.3-flash', providerID: 'opencode' },
|
||||
cost: 0.0042,
|
||||
tokens: { input: 18100, output: 900, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
})
|
||||
// A still-running compaction carries no usage and must yield nothing.
|
||||
insertV2Message(db, 'msg_3', 'ses_v2_1', 'compaction', 3, 1700000000150, {
|
||||
status: 'running', reason: 'auto', summary: 's', recent: 'r',
|
||||
})
|
||||
insertV2Message(db, 'msg_4', 'ses_v2_1', 'idle', 4, 1700000000200, { outcome: 'succeeded' })
|
||||
insertV2Message(db, 'msg_5', 'ses_v2_1', 'assistant', 5, 1700000000300, {
|
||||
model: { id: 'gpt-4o', providerID: 'openai' },
|
||||
content: [{ type: 'text', text: 'hi' }],
|
||||
tokens: { input: 10, output: 5, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
})
|
||||
})
|
||||
|
||||
const provider = createOpenCodeProvider(tmpDir)
|
||||
const calls = await collectCalls(provider, dbPath, 'ses_v2_1')
|
||||
expect(calls).toHaveLength(2)
|
||||
expect(calls[0]!.model).toBe('opencode/glm-5.3-flash')
|
||||
expect(calls[0]!.inputTokens).toBe(18100)
|
||||
expect(calls[0]!.costUSD).toBeGreaterThan(0)
|
||||
expect(calls[1]!.model).toBe('openai/gpt-4o')
|
||||
})
|
||||
|
||||
it('walks v2 child sessions through parent_id', async () => {
|
||||
const dbPath = createV2TestDb(tmpDir)
|
||||
withTestDb(dbPath, (db) => {
|
||||
insertV2Session(db, 'ses_parent')
|
||||
insertV2Session(db, 'ses_child', { parentId: 'ses_parent' })
|
||||
insertV2Message(db, 'msg_c1', 'ses_child', 'assistant', 1, 1700000000500, {
|
||||
model: { id: 'm', providerID: 'opencode' },
|
||||
content: [{ type: 'text', text: 'child work' }],
|
||||
tokens: { input: 7, output: 3, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
})
|
||||
})
|
||||
|
||||
const provider = createOpenCodeProvider(tmpDir)
|
||||
const sessions = await provider.discoverSessions()
|
||||
// Only the root is discovered; the child is reached through the tree walk.
|
||||
expect(sessions.map((s) => s.path)).toEqual([`${dbPath}:ses_parent`])
|
||||
|
||||
const calls = await collectCalls(provider, dbPath, 'ses_parent')
|
||||
expect(calls).toHaveLength(1)
|
||||
expect(calls[0]!.sessionId).toBe('ses_parent')
|
||||
expect(calls[0]!.inputTokens).toBe(7)
|
||||
})
|
||||
|
||||
it('prefers the v2 generation on an upgraded database with both table sets', async () => {
|
||||
const dbPath = createV2TestDb(tmpDir, { withLegacy: true })
|
||||
withTestDb(dbPath, (db) => {
|
||||
insertV2Session(db, 'ses_v2_live')
|
||||
insertV2Message(db, 'msg_1', 'ses_v2_live', 'assistant', 1, 1700000000000, {
|
||||
model: { id: 'glm-5.3-flash', providerID: 'opencode' },
|
||||
content: [{ type: 'text', text: 'live v2 turn' }],
|
||||
tokens: { input: 100, output: 50, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
})
|
||||
// Frozen pre-upgrade session still in the legacy table.
|
||||
insertSession(db, 'ses_legacy_frozen', { title: 'frozen' })
|
||||
insertMessage(db, 'lmsg_1', 'ses_legacy_frozen', 1690000000000, {
|
||||
role: 'assistant', modelID: 'opencode/old', tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
})
|
||||
})
|
||||
|
||||
const provider = createOpenCodeProvider(tmpDir)
|
||||
const sessions = await provider.discoverSessions()
|
||||
// v2 wins: the frozen legacy session is not surfaced.
|
||||
expect(sessions.map((s) => s.path)).toEqual([`${dbPath}:ses_v2_live`])
|
||||
|
||||
const v2Calls = await collectCalls(provider, dbPath, 'ses_v2_live')
|
||||
expect(v2Calls).toHaveLength(1)
|
||||
expect(v2Calls[0]!.inputTokens).toBe(100)
|
||||
|
||||
const legacyCalls = await collectCalls(provider, dbPath, 'ses_legacy_frozen')
|
||||
expect(legacyCalls).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('falls back to session_v2 rollups when v2 messages carry no tokens', async () => {
|
||||
const dbPath = createV2TestDb(tmpDir)
|
||||
withTestDb(dbPath, (db) => {
|
||||
db.prepare(`
|
||||
INSERT INTO session_v2 (id, project_id, parent_id, slug, directory, title, version,
|
||||
cost, tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write,
|
||||
model, time_created, time_updated, time_archived)
|
||||
VALUES ('ses_roll', 'proj-1', NULL, 'slug-1', '/home/user/myproject', 't', '2.0.3',
|
||||
0.0077, 21410, 2175, 0, 112128, 0, ?, 1700000000000, 1700000000000, NULL)
|
||||
`).run(JSON.stringify({ id: 'glm-5.3-flash', providerID: 'opencode' }))
|
||||
insertV2Message(db, 'msg_1', 'ses_roll', 'user', 1, 1700000000000, { text: 'hello' })
|
||||
insertV2Message(db, 'msg_2', 'ses_roll', 'assistant', 2, 1700000000100, {
|
||||
model: { id: 'glm-5.3-flash', providerID: 'opencode' },
|
||||
})
|
||||
})
|
||||
|
||||
const provider = createOpenCodeProvider(tmpDir)
|
||||
const calls = await collectCalls(provider, dbPath, 'ses_roll')
|
||||
expect(calls).toHaveLength(1)
|
||||
expect(calls[0]!.model).toBe('opencode/glm-5.3-flash')
|
||||
expect(calls[0]!.inputTokens).toBe(21410)
|
||||
expect(calls[0]!.cacheReadInputTokens).toBe(112128)
|
||||
expect(calls[0]!.costUSD).toBeCloseTo(0.0077, 4)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue