CodeNomad/scripts/test-service-usage-native.mjs
Pascal André 6f8881d5ae
fix(stats): restore cached totals and refresh only while visible (#1041)
## Summary
Replace the renderer-only workspace-ID cache with bounded validated
display snapshots in backend-owned state.ui.serviceUsage. Cache survives
recreated renderer/backend/workspace identity, keyed by authenticated
service/discovery/execution-host/folder fingerprint and period/timezone.
Eight entries, 1 MiB maximum; no plaintext credentials or paths.
Preferences does not write the opener's client-state journal.

Show previous totals/charts immediately with a cached-state label while
revalidating; preserve them on error. Hidden/unmounted Stats starts no
reads, cancels trailing work and fences late results. Visibility resumes
one read; execution hints use the existing activity cooldown instead of
one native scan per descendant. Manual refresh, period, reconnect and
deletion/pruning paths retained.

## Validation
- Rebased on current dev 7a2ee897e, retaining #1037 shared fixture
cache/shutdown and token UI plus #1039 launcher changes.
- Server/UI typechecks pass; cache/scheduler units 8/8; browser
service-usage 5/5, usage-metrics 4/4, status-tokens 4/4, sequentially.
- Real renderer AND backend recreation with a two-second stats delay:
2098 ms cold / 68 ms restored, then fresh totals replace cached values.
- Hidden-start regression: base makes one unwanted read; fixed makes
zero. Tests cover hidden events, visibility, burst scheduling, identity
changes, retention/errors and malformed cache bounds.
- Isolated native fixture with four synthetic sessions passes; repeated
native reads ~15–19 ms. OpenCode still repeats aggregation; no claim to
optimize large-history scans.
- No app/shared daemon/user data touched. Live installed app and
non-Windows native acceptance not tested.

## Oversized touched files
http-server.ts ~2446 lines; api-client.ts ~817; 10 locale settings.ts
files ~735–749. No unrelated refactor.
2026-10-20 19:49:45 +02:00

53 lines
3.3 KiB
JavaScript

import assert from "node:assert/strict"
import { mkdir, writeFile } from "node:fs/promises"
import { spawnSync } from "node:child_process"
import path from "node:path"
import { withProductRuntime } from "./native-product-fixture.mjs"
import { ServiceUsage } from "../packages/server/src/opencode/service-usage.ts"
const git = (cwd, ...args) => {
const result = spawnSync("git", args, { cwd, encoding: "utf8", env: { ...process.env, GIT_CONFIG_GLOBAL: path.join(cwd, "empty-git-config"), GIT_CONFIG_NOSYSTEM: "1" } })
assert.equal(result.status, 0, result.stderr); return result.stdout.trim()
}
let projectRoot, worktree, other, clone
await withProductRuntime(process.argv[2], async ({ root }) => {
projectRoot = path.join(root, "repo"); worktree = path.join(root, "worktree"); other = path.join(root, "other")
for (const directory of [projectRoot, other]) {
await mkdir(directory); git(directory, "init")
await writeFile(path.join(directory, "fixture.txt"), directory)
git(directory, "add", "fixture.txt")
git(directory, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "-c", "commit.gpgsign=false", "commit", "-m", "fixture")
}
git(projectRoot, "worktree", "add", "-b", "fixture-worktree", worktree)
clone = path.join(root, "independent-clone")
git(root, "clone", projectRoot, clone)
}, async ({ client }) => {
const from = Date.now() - 60_000
const locations = []
for (const directory of [projectRoot, worktree, other, clone]) {
locations.push(await client.location.get({ location: { directory } }))
const session = await client.session.create({ location: { directory } })
await client.session.prompt({ sessionID: session.id, text: "Synthetic usage fixture", model: { providerID: "fixture", id: "fixture" } })
await client.session.wait({ sessionID: session.id })
}
const record = {}, connection = { client, assertCurrent() {} }
assert.equal(locations[0].project.id, locations[3].project.id, "Independent clones share native project identity")
const usage = new ServiceUsage({ get: () => record, getSharedServiceConnection: async () => connection })
const result = await usage.read("fixture", { from, to: Date.now() + 1000, timezone: "UTC" })
assert.equal(result.scope, "service")
assert.equal(result.stats.sessions, 4, "Explicit service scope includes worktrees, independent clones and unrelated projects")
assert.equal(result.stats.prompts, 4); assert.equal(result.stats.steps, 4)
assert.equal(result.stats.tokens.input, 40); assert.equal(result.stats.tokens.output, 20)
assert.equal(result.stats.models.length, 1); assert.equal(result.stats.models[0].model.providerID, "fixture")
assert.deepEqual(result.stats.tools, { mode: "none" })
assert.equal(result.stats.activity.reduce((sum, row) => sum + row.steps, 0), 4)
const query = { from, to: Date.now() + 1000, timezone: "UTC" }, timings = []
for (let index = 0; index < 3; index++) {
const start = performance.now()
const unchanged = await usage.read("fixture", query)
timings.push(Math.round((performance.now() - start) * 100) / 100)
assert.equal(unchanged.stats.steps, 4)
}
console.log(`Native Stats repeated identical service reads (4 synthetic sessions, tools:none), ms: ${JSON.stringify(timings)}`)
console.log("PASS explicitly authorized service-wide usage including independent clone, durable tokens/models/activity and tools:none")
})