You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
feat(insights): count AI token usage and show it in an AI usage tab - #5823
Related issue: N/A
Validation tasks: none changed. The AI request paths of #1213 (metadata translation), #1164 (generated subtitles) and #1145 (recommendations) now also record usage; what they return is unchanged.
Other clients: Apple N/A (no Insights screen); Android N/A (no Insights screen); Roku N/A (no admin screens)
Administrators who connect AI providers have no way to see how much Silo uses them. Subtitle translation, description translation, transcription and recommendation embeddings all call paid or rate-limited models, and the only place to look is each provider's own billing page, which can't say which Silo feature spent the tokens. This adds an AI usage tab to Admin > Insights, next to Bandwidth. It shows total tokens, tokens per model, tokens per feature and per day, and the audio length sent to speech models. Prices aren't shown: Silo has no price list per model, so it counts tokens only.
Approach
Recording. The LLM client (internal/ai/llm) files every 200 attempt from its shared retry loop, and the ChatGPT-plan stream files the usage in its completion event. The embeddings client files each batch. Each record is upserted into a new daily table, ai_usage_daily, keyed by UTC day, provider ID, model and feature (internal/ai/usage). The upsert adds to the row, so several API replicas can write the same row. Usage is the provider's own count: Chat Completions and Responses token fields, transcription duration or usage.seconds, embedding prompt_tokens or Gemini usageMetadata.promptTokenCount.
What counts. A retried reply Silo couldn't use still counts when the provider reported usage, since the provider billed it. Refusals don't count: a 4xx, or an error object or failed stream event inside a 200 without usage. A usable reply from a server that reports no usage, such as some local servers, counts as a request with zero tokens.
Feature tags. Callers mark their context with usage.WithFeature (subtitle translation, metadata translation); transcription and embeddings tag their own requests. Anything untagged is filed as other.
API.GET /api/v2/admin/insights/ai (getAdminInsightsAI) returns the summary, per-model and per-feature totals, and daily points for the usual Insights window. Provider names come from the current provider registry at read time, so a removed provider shows as "Removed provider". tracking_since is the UTC date counting began (the migration's apply day, or the first recorded day if earlier), and the tab says when the window starts before it. API keys with the monitor scope can read it. GET /admin/insights/capabilities gains ai_usage. Documented in docs/admin-api.md and docs/api-keys-api.md.
Web. The tab follows the Bandwidth tab's layout: summary cards, a tokens-per-day chart with Total / Input / Output and By model / By feature views, and By model and By feature tables. Like Bandwidth, it has no library or timezone filter, since usage is kept per UTC day for the whole server. ShareBar moved into insightsShared.tsx so both tabs use one copy. Strings come from feat(web): add AI usage Insights tab strings silo-translations#218.
Backups.ai_usage_daily is classified as restored data, next to dashboard_metric_daily.
Not covered: settings connection checks build their own clients and aren't counted, and usage from before this migration isn't recoverable.
Validation
Go: build, gofmt, go mod tidy -diff, vet, make lint-changed (0 issues), make lint-router-recovery, make test-go: passed.
Postgres tests: concurrent writes from two stores, day bucketing and the full report (internal/ai/usage); the handler's all-time and 30-day windows, including a non-UTC timezone (internal/api/handlers). Both are listed in scripts/ci/db-contracts.txt.
Unit tests cover what counts: Chat Completions, Responses, ChatGPT-plan stream, a retried unusable reply, a refusal inside a 200, a ChatGPT rate-limit event, a 4xx, transcription duration, and OpenAI and Gemini embeddings.
Web: lint, format check, build, budget check, make test-web: passed.
End to end: on a local server with an OpenAI-compatible test provider, a real metadata translation was recorded as one metadata_translation request with the provider's input and output tokens, and showed in the tab.
Surface and build: web admin, desktop and phone width, this branch's commit against a local server. The charts show 30 days of seeded sample usage plus one real recorded translation. Before is the same page on the merge base, where the tab doesn't exist.
Risks
One new migration (ai_usage_daily, a new table; nothing existing changes).
Each answered AI request now does one small upsert, after the provider call returns. A failed write is logged and never fails the AI request.
Each test this pull request adds meets "Decide what to test" in CONTRIBUTING.md.
The Evidence section shows every change a user can see, or how I checked a change nobody sees.
AI Disclosure
Harness: Claude Code in T3 Code
Tool(s): Claude Code; Codex CLI (review)
Model(s): claude-opus-5-5; gpt-6.2-sol (review)
Involvement: Fully AI-generated, human verified
Adversarial review: two independent reviews of the full branch diff (gpt-6.2-sol via Codex CLI and claude-opus-5-5), each on correctness, repo standards and the request, run before and after a cleanup pass. Fixed: a stale route manifest, the missing backup classification, a custom range charting an extra day, the all-time window in non-UTC timezones, sub-minute audio showing as zero, refused ChatGPT-plan stream attempts counting as requests, Gemini token counts being ignored, and an untested all-time window. Kept as designed: the configured model name rather than the one a router reports, and connection checks not being counted.
Note
Add AI token usage tracking and an AI usage tab to Admin Insights
Records per-request AI usage (input, cached, output tokens; audio seconds) for chat, transcription, embeddings, and translation requests, and aggregates it into a new daily usage table (migration). Usage writes are best-effort with a 5-second timeout and clamped nonnegative values.
Adds GET /api/v2/admin/insights/ai (openapi.json) with per-model, per-feature, and daily breakdowns, plus an ai_usage capability flag; the endpoint requires the admin:monitor:read scope.
Adds a new AI tab to the Admin Insights page (AiUsageTab.tsx) with model/feature split charts, provider badges, and locale-aware token formatting. The tab hides library, account, and timezone filters.
Usage attribution follows the provider configured at request time; the embeddings client now swaps credentials via SetCredential (replacing SetAPIKey), so in-flight requests keep their earlier provider ID and key.
Behavioral Change: the daily usage table is included in backup restores, and usage.TrackingSince bounds all-time reports to the earlier of the first recorded usage day or the tracking migration's applied date.
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.
The change adds AI usage capture and daily reporting, an administrator Insights API, and a dashboard tab with localized labels. It also updates API contracts, fixtures, and documentation, reuses a share bar in bandwidth insights, and changes the backup classification of anime_ids.
Changes: AI Usage Insights
Layer / File(s)
Summary
Usage contract and daily storage internal/ai/usage/*, migrations/sql/*, scripts/ci/db-contracts.txt
Defines usage features and records, creates the daily usage table, and adds recording, tracking-date, aggregation, ordering, and database contract tests.
AI usage capture and provider wiring internal/ai/llm/*, internal/ai/chatgpt/selection.go, internal/recommendations/*, internal/metadata/translation/service.go, internal/subtitles/ai/translator.go, cmd/silo/main.go, internal/api/router.go
Captures usage from chat, Responses API, ChatGPT streams, transcription, and embeddings. Tags translation requests by feature and wires provider IDs and recorders into AI clients.
Admin report and endpoint internal/api/handlers/admin_insights_ai.go, internal/apiv2/*, internal/api/middleware/api_key_scopes.go, internal/api/testdata/media_routes.txt, internal/apiv2/admin_insights_test.go, internal/api/handlers/admin_insights_db_test.go
Resolves Insights windows, reads tracking and usage data, adds provider metadata, registers the endpoint and capability, and adds report, database-window, and access-scope tests.
Insights API contract and query client contracts/api/v2/*, docs/*api.md, web/src/api/v2/*, web/src/hooks/queries/*
Adds AI usage schemas, endpoint parameters, capability flag, fixtures, and documentation. Adds the web API operation, response types, query key, and query hook.
Admin AI usage dashboard web/src/pages/admin-insights/*, web/src/locales/*, .silo-translations
Adds the AI usage tab with charts, KPIs, model and feature tables, and loading, error, and empty states. Adds localized labels and shared share-bar rendering used by bandwidth insights.
sequenceDiagram
participant AiUsageTab
participant useAdminInsightsAI
participant AdminInsightsAIEndpoint
participant ReadAdminInsightsAI
participant UsageStore
AiUsageTab->>useAdminInsightsAI: Request report for selected window
useAdminInsightsAI->>AdminInsightsAIEndpoint: GET AI insights with query parameters
AdminInsightsAIEndpoint->>ReadAdminInsightsAI: ReadAdminInsightsAI(query)
ReadAdminInsightsAI->>UsageStore: Read usage for resolved date range
UsageStore-->>ReadAdminInsightsAI: Aggregated usage report
ReadAdminInsightsAI-->>AdminInsightsAIEndpoint: Report, window, and provider metadata
AdminInsightsAIEndpoint-->>useAdminInsightsAI: AdminInsightsAI response
useAdminInsightsAI-->>AiUsageTab: Return usage data
Loading
Suggested reviewers:quick104
Merge Risk: Low · previous review 220b9
Embedding requests could fail against a provider or gateway that sends a malformed usage object, even though the vectors are usable. Fix this before merge. Also repin the translation catalog to a published release once the catalog change lands.
Security architecture risk: Moderate · up to 220b9
Silo can lose or delay an otherwise usable AI result because of usage accounting, even when nobody opens Insights. A faulty or compromised configured provider can also distort server-wide usage totals. The identified effects are on AI availability, credential refresh, and reporting integrity—not on provider billing or access permissions.
Minor · reliability · inferred: Silo intentionally records answered attempts even if the caller cancels, so billed work can still be counted. Unlike the merge base, the current design makes existing AI callers wait for that write: pool starvation or daily-row contention can consume the five-second database budget per recorded attempt, and the LLM retry loop closes the response body only after the callback returns. This cost applies even when the caller never requests Insights.
Minor · reliability · inferred: The merge base ignored optional accounting fields in the primary decoders. The current head tolerates incompatible individual token counts, but an incompatible usage object or nested detail can still cause both embedding adapters to reject usable vectors or cause the ChatGPT stream parser to fail before recognizing completion or classifying a provider rejection. In the credential-rejection case, the parse error takes the generic retry path instead of the refresh-once path. Disabling the recorder does not change these decoders.
Minor · security · inferred: A faulty or compromised configured provider can supply positive token counts that pass the current per-field range check but are too large for safe accumulation. PostgreSQL can accept the initial count and reject later increments to that daily row; Go can wrap signed totals in reports that include the row. The new exposure extends beyond that provider's own display line to shared Insights summaries, but does not change provider billing or authorization.
Security review details
Security Blast Radius
inferred — One configured provider serving a Silo request can affect its own daily rows and the installation-wide Insights totals that include those rows. The report combines usage across provider IDs; it does not limit aggregate influence to each provider's own entry.
Security Findings and Attack Paths
inferred — The reporting-integrity path requires influence over a configured provider's reply. Silo's database identity writes the accepted counts; the provider needs neither database credentials nor access to Admin Insights. A count that fits one stored column is not necessarily safe to include in a later aggregate.
Trust Boundaries and Controls
observed — The token decoder converts nonnumeric, negative, or out-of-range scalar counts to zero, and the store clamps negative values before writing. Neither control checks whether an accepted positive count can be added safely to a stored row or report total.
Data and control flow
observed — Silo attributes provider-reported counts to its own provider, model, and feature identifiers, adds them to a UTC daily row, then aggregates rows across the selected reporting window.
Resilience and Maintainability Implications
observed — A failed accounting write is logged rather than returned as an AI request error. That guarantee isolates the returned error, not latency: the caller still waits, cancellation does not stop the write, and a later qualifying LLM attempt has its own write budget.
inferred — Turning off the recorder stops writes but does not restore the previous response handling. The embedding and stream decoders still read typed usage metadata before delivering vectors or classifying a streamed credential rejection.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title "feat(insights): count AI token usage and show it in an AI usage tab" matches the main change. The changeset adds AI usage recording (token and audio counts for chat, transcription, embeddin…
Description check
The description explains the problem (administrators cannot see how much Silo spends on AI providers), the approach (recording in the LLM client and embeddings client, a new ai_usage_daily table, the …
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Full details: Title check
Explanation
The title "feat(insights): count AI token usage and show it in an AI usage tab" matches the main change. The changeset adds AI usage recording (token and audio counts for chat, transcription, embeddings, and translation), a daily usage table, a GET /api/v2/admin/insights/ai endpoint, and an AI usage tab in Admin Insights.
Full details: Description check
Explanation
The description explains the problem (administrators cannot see how much Silo spends on AI providers), the approach (recording in the LLM client and embeddings client, a new ai_usage_daily table, the new API endpoint, and the web tab), validation steps, and risks. It relates directly to the changeset.
Finishing Touches
Generate unit tests (beta)
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.
Reviewing changes in Silo
Include the related issue, expected behavior, and validation steps in the PR description.
For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
Follow this repository's AGENTS.md and CONTRIBUTING.md.
Request another review with @kody start-review in a PR comment.
React with 👍 or 👎 to give feedback on individual suggestions.
Review settingsReview Options
The following review options are enabled or disabled:
Options
Enabled
Bug
✅
Performance
✅
Security
✅
Business Logic
❌
⚠️ 5 Kody Rule(s) were not evaluated
These rules declare that they need repository context beyond this diff, and the review could not retrieve it, so they were not judged on this pull request:
Preserve optional store capabilities through production wrappers
Detach mandatory cleanup from request cancellation and bound its lifetime
Preserve durable media identity and share identity-evidence precedence
Bound decoder throughput trades and share direct-play eligibility
Retain distributed firing claims through their own validity windows
Accounting now runs inline before existing AI callers receive the provider result. A slow pool or contended usage row can consume the five-second write budget even after caller cancellation, and the delay can recur on separately recorded retry attempts. Calling an AI feature now incurs this wait even when the caller never requests an Insights report.
1
Both embedding adapters decode newly typed usage metadata together with the vectors. If the provider supplies usage metadata with an incompatible type, the adapter rejects otherwise usable vectors; the merge base ignored those fields. This lets an accounting-format change interrupt recommendation work even when recording is disabled.
Review info
Run configuration
Source mode: Auto
Repository: Unavailable
Branch: Unavailable
File: No configuration file from this repository applied
Commit: Unavailable
Layers: Organization UI
Review profile: CHILL
Plan: Advanced
Run ID: 99a43066-4564-4a7f-8c7c-ab637beadcc1
Commits
Reviewing files that changed from the base of the PR and between fc87128 and 4b01666.
Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.
Metering puts a synchronous Postgres write between an answered provider request and the AI caller receiving its result. A slow pool or contended daily row can delay that result after caller cancellation, and the wait can recur on separately recorded retry attempts. This is a failure-containment regression for existing AI callers, not an inherent cost of opening the Insights report.
OpenAI-compatible and Gemini embedding adapters reject otherwise usable vectors if newly typed accounting fields cannot be decoded. ChatGPT stream handling has the same regression: decoding usage can fail before the parser recognizes completion or classifies a provider error, including the credential rejection that triggers refresh. The merge base ignored these fields in the primary decoders, and disabling the recorder does not restore that behavior.
Review info
Run configuration
Source mode: Auto
Repository: Unavailable
Branch: Unavailable
File: No configuration file from this repository applied
Commit: Unavailable
Layers: Organization UI
Review profile: CHILL
Plan: Advanced
Run ID: d7cd0a08-0b30-4ac8-9669-1127c3632008
Commits
Reviewing files that changed from the base of the PR and between 4b01666 and f94cd7a.
Files skipped from review as they are similar to previous changes: 4
web/src/locales/ar-XB.json
web/src/locales/en-XA.json
web/src/locales/en.json
web/src/locales/keys.ts
Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 1 remain after this review.
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments
2
Accounting adds a synchronous PostgreSQL wait to existing AI operations, even when nobody requests the report. A slow pool or contended daily row can consume the five-second budget after caller cancellation. On separately metered LLM retry attempts this wait can recur; in the shared retry loop the response body is not closed until the callback returns. The merge base did not put this write between provider response processing and delivery of the result.
Both embedding adapters and the ChatGPT plan stream now decode typed usage fields in their primary response decoders. An incompatible accounting field can reject otherwise usable vectors or stop the stream parser before it recognizes completion or classifies a provider rejection. In particular, a streamed credential rejection can become a generic retryable parse error instead of triggering token refresh. The merge base ignored these usage fields, and removing the recorder does not restore that behavior.
Review info
Run configuration
Source mode: Auto
Repository: Unavailable
Branch: Unavailable
File: No configuration file from this repository applied
Commit: Unavailable
Layers: Organization UI
Review profile: CHILL
Plan: Advanced
Run ID: 0dccc7ff-d88e-4485-9d3f-0a5d47e0e70f
Commits
Reviewing files that changed from the base of the PR and between f94cd7a and 19da3aa.
Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.
Record every answered AI provider request (chat, Responses API, ChatGPT plan,
transcription, embeddings) into a daily ai_usage_daily rollup keyed by UTC day,
provider, model and feature, and serve it at GET /api/v2/admin/insights/ai for
a new AI usage tab next to Bandwidth. Tokens only; no pricing.
…rs pass validation
A reply with the expected number of vectors but an empty one was counted
before being rejected. Provider-reported usage on a rejected reply is
still recorded.
Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.
Reviewing changes in Silo
Include the related issue, expected behavior, and validation steps in the PR description.
For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
Follow this repository's AGENTS.md and CONTRIBUTING.md.
Request another review with @kody start-review in a PR comment.
React with 👍 or 👎 to give feedback on individual suggestions.
Review settingsReview Options
The following review options are enabled or disabled:
Options
Enabled
Bug
✅
Performance
✅
Security
✅
Business Logic
❌
⚠️ 4 Kody Rule(s) were not evaluated
These rules declare that they need repository context beyond this diff, and the review could not retrieve it, so they were not judged on this pull request:
Preserve optional store capabilities through production wrappers
Detach mandatory cleanup from request cancellation and bound its lifetime
Preserve durable media identity and share identity-evidence precedence
Bound decoder throughput trades and share direct-play eligibility
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments
1
The new accounting boundary accepts token counts from configured providers, clamps negative values, and applies no upper bound that protects later sums. Oversized positive counts can persist successfully, make later increments to the same daily row fail, or wrap the report's signed totals when combined with other rows. A faulty or compromised configured provider can therefore corrupt server-wide usage summaries, not just its own display line. This affects operational reporting, not provider billing or authorization.
Review info
Run configuration
Source mode: Auto
Repository: Unavailable
Branch: Unavailable
File: No configuration file from this repository applied
Commit: Unavailable
Layers: Organization UI
Review profile: CHILL
Plan: Advanced
Run ID: 2814f731-fd01-4157-a71a-b6d26ad33c08
Commits
Reviewing files that changed from the base of the PR and between 19da3aa and 0417772.
Files selected for processing: 7
.silo-translations
contracts/api/v2/openapi.json
internal/api/router.go
internal/api/testdata/media_routes.txt
scripts/ci/db-contracts.txt
web/src/api/v2/schema.ts
web/src/locales/keys.ts
Files skipped from review as they are similar to previous changes: 1
web/src/locales/keys.ts
Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 1 remain after this review.
Resolve the translation pin conflict by re-syncing the web locales from a
local catalog build of main's pinned release plus Silo-Server/silo-translations#218.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…abase timezone
goose_db_version.tstamp is a timestamp without time zone written in the
server's TimeZone. Reading it as UTC moved tracking_since a day early on
servers west of UTC and a day late east of it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…known features
tracking_since names a UTC day, so it is a YYYY-MM-DD date as the API
contract requires for day-only values, not an instant a client could shift
into the day before. The contract fixture's window now starts at UTC
midnight, as the field's description says.
A feature value a newer server adds reads as unattributed in the tab rather
than looking up a label that doesn't exist.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Token counts were decoded as int64 inside the embedding and ChatGPT stream
replies, so a provider sending 3.0 or a non-number made a usable reply fail
to decode. Counts now read leniently and fall back to zero.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nslations#218
Local build of main's pinned catalog release plus Silo-Server/silo-translations#218
with its translation pass. Re-pin to the release once Silo-Server#218 merges.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.
Reviewing changes in Silo
Include the related issue, expected behavior, and validation steps in the PR description.
For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
Follow this repository's AGENTS.md and CONTRIBUTING.md.
Request another review with @kody start-review in a PR comment.
React with 👍 or 👎 to give feedback on individual suggestions.
Review settingsReview Options
The following review options are enabled or disabled:
Options
Enabled
Bug
✅
Performance
✅
Security
✅
Business Logic
❌
⚠️ 4 Kody Rule(s) were not evaluated
These rules declare that they need repository context beyond this diff, and the review could not retrieve it, so they were not judged on this pull request:
Preserve optional store capabilities through production wrappers
Detach mandatory cleanup from request cancellation and bound its lifetime
Preserve durable media identity and share identity-evidence precedence
Bound decoder throughput trades and share direct-play eligibility
The reason will be displayed to describe this comment to others. Learn more.
I reviewed this after merging main into the branch. I found four problems and fixed each one in a commit on this branch, so you don't need to change anything. The summary comment below has the scores and what's left for the maintainers.
Re-sync the web locales from a local catalog build of main's new pinned
release (2026.12.04-d577fe4) plus Silo-Server/silo-translations#218.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Fit: 7/10 · Readiness: 8/10 — conditional (reviewed head 220b9c3348, assuming CI is green)
Fit. Admins who connect paid or rate-limited AI providers had no way to see what Silo spends. This tab answers that without changing what any AI feature does. It lives in web admin with no app counterpart, which suits an admin-only screen. It's held below 9 because Silo's 1.0 work is focused on correctness and polish (see AGENTS.md). This adds a new table, an endpoint and a capability field that becomes permanent API surface once /api/v2 locks, and none of them closes a gap in the core experience.
Readiness. The approach is sound. The counting rules (200 attempts only, refusals left out, billed retries kept), the upsert that replicas share, the migration and the backup classification all held up under review. Before merge, the translation pin has to move to a published release. One design choice is left for maintainers.
Fixed on this branch
74fb97ec96: tracking_since was a day off on databases not in UTC, because it read goose's zoneless tstamp as UTC. I reproduced this in Postgres. The DB test now checks a Tokyo migration time, and that check failed on the earlier head.
fbcd11726e: tracking_since is now a YYYY-MM-DD date, as the API contract requires for day-only values. The fixture's from starts at UTC midnight as documented. A feature value the web build doesn't know falls back to the Other label.
823805a572: token counts are read leniently. Before this, a usage field like "prompt_tokens": 3.0 failed an otherwise valid embedding or ChatGPT reply. A new TestEmbedRecordsUsage case covers it and failed on the earlier head.
Synchronous usage write (maintainer decision). Each answered provider request waits for one upsert, capped at 5 s and detached from the caller's cancellation. That includes the query embedding behind semantic search, which has a 2 s budget. In normal operation the upsert is one fast row write. When the database stalls, every AI call and uncached search can wait up to 5 s longer. The author chose this over an async buffer that could lose counts when a replica stops. Writing from a goroutine on the search path alone would remove the risk to search. Nobody measured the latency, so this is a decision, not a defect.
tracking_since if the database timezone changes later (open Kody thread). The date is read back in the server's current timezone. If that changed after the migration ran, the "counted from" date can move by one day. Recorded usage is never hidden, because the window can't start after the first recorded row.
Smaller points nobody fixed, for the record:
A feature with both tokens and audio shows only tokens in its row.
The By feature model list merges same-named models from different providers.
Search and indexing embeddings share one feature label.
Settings connection checks aren't counted (the PR says so).
The tab isn't gated on ai_usage, like the other Insights tabs.
Tests: the PR's own new tests exercise code this PR adds, so they can't run on the base. The two regression checks I added failed on the earlier head and pass now. The focused Go suites (internal/ai/..., internal/recommendations/..., internal/apiv2, middleware, the Insights handler DB test), the web typecheck and the API contract checks pass locally. I didn't verify live on a sandbox; the author's end-to-end run is in the description.
Other clients: Apple and Android have no Insights screens, and Roku has no admin screens. The Other clients: line is right.
jellycompat: not affected.
Council
Reviewers: Sol (gpt-6.2-sol, attack), Opus (claude-opus-5-5, cut), Gemini (gemini-4-neon, check), all at medium effort, two rounds.
Round 1 (00b2585510): Sol 6/10, Opus 8/10, Gemini 8.5/10.
Round 2 (fbcd11726e): Sol 7/10, Opus 8/10, Gemini 8/10.
Round 1 led to the timezone, date-format and unknown-feature fixes, and round 2 to the lenient token counts. The commits after round 2 are that fix, the locale sync and a merge of main. No round reviewed them.
Files skipped from review as they are similar to previous changes: 1
web/src/locales/keys.ts
Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 0 remain after this review.
Count.UnmarshalJSON returned nil inside an error branch, which nilerr
rejects. It now zeroes the count first and assigns only a valid number,
with one nil return. A non-number, negative or out-of-range count still
reads as zero and a fractional count is still truncated; a unit test
pins both.
Resolve the generated translation conflicts by syncing to the published
silo-translations release 2026.12.04-0b3cec1, which carries this branch's
AI usage strings.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…vectors
A provider that sends "usage": [] (or Gemini's "usageMetadata": [])
failed the whole decode, so usage tracking threw away vectors Silo could
use. Decode the vectors strictly and read usage on its own, ignoring a
malformed value, as the chat client already does.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.
Reviewing changes in Silo
Include the related issue, expected behavior, and validation steps in the PR description.
For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
Follow this repository's AGENTS.md and CONTRIBUTING.md.
Request another review with @kody start-review in a PR comment.
React with 👍 or 👎 to give feedback on individual suggestions.
Review settingsReview Options
The following review options are enabled or disabled:
Options
Enabled
Bug
✅
Performance
✅
Security
✅
Business Logic
❌
⚠️ 4 Kody Rule(s) were not evaluated
These rules declare that they need repository context beyond this diff, and the review could not retrieve it, so they were not judged on this pull request:
Preserve optional store capabilities through production wrappers
Detach mandatory cleanup from request cancellation and bound its lifetime
Preserve durable media identity and share identity-evidence precedence
Bound decoder throughput trades and share direct-play eligibility
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
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.
Problem
Related issue: N/A
Validation tasks: none changed. The AI request paths of #1213 (metadata translation), #1164 (generated subtitles) and #1145 (recommendations) now also record usage; what they return is unchanged.
Other clients: Apple N/A (no Insights screen); Android N/A (no Insights screen); Roku N/A (no admin screens)
Administrators who connect AI providers have no way to see how much Silo uses them. Subtitle translation, description translation, transcription and recommendation embeddings all call paid or rate-limited models, and the only place to look is each provider's own billing page, which can't say which Silo feature spent the tokens. This adds an AI usage tab to Admin > Insights, next to Bandwidth. It shows total tokens, tokens per model, tokens per feature and per day, and the audio length sent to speech models. Prices aren't shown: Silo has no price list per model, so it counts tokens only.
Approach
internal/ai/llm) files every 200 attempt from its shared retry loop, and the ChatGPT-plan stream files the usage in its completion event. The embeddings client files each batch. Each record is upserted into a new daily table,ai_usage_daily, keyed by UTC day, provider ID, model and feature (internal/ai/usage). The upsert adds to the row, so several API replicas can write the same row. Usage is the provider's own count: Chat Completions and Responses token fields, transcriptiondurationorusage.seconds, embeddingprompt_tokensor GeminiusageMetadata.promptTokenCount.usage.WithFeature(subtitle translation, metadata translation); transcription and embeddings tag their own requests. Anything untagged is filed asother.GET /api/v2/admin/insights/ai(getAdminInsightsAI) returns the summary, per-model and per-feature totals, and daily points for the usual Insights window. Provider names come from the current provider registry at read time, so a removed provider shows as "Removed provider".tracking_sinceis the UTC date counting began (the migration's apply day, or the first recorded day if earlier), and the tab says when the window starts before it. API keys with the monitor scope can read it.GET /admin/insights/capabilitiesgainsai_usage. Documented indocs/admin-api.mdanddocs/api-keys-api.md.ShareBarmoved intoinsightsShared.tsxso both tabs use one copy. Strings come from feat(web): add AI usage Insights tab strings silo-translations#218.ai_usage_dailyis classified as restored data, next todashboard_metric_daily.Not covered: settings connection checks build their own clients and aren't counted, and usage from before this migration isn't recoverable.
Validation
go mod tidy -diff, vet,make lint-changed(0 issues),make lint-router-recovery,make test-go: passed.internal/ai/usage); the handler's all-time and 30-day windows, including a non-UTC timezone (internal/api/handlers). Both are listed inscripts/ci/db-contracts.txt.make test-web: passed.verify-apiv2-openapi,verify-apiv2-fixtures,verify-apiv2-web-types,verify-apiv2-contract,verify-route-inventory,verify-local-paths,migrate-validate: passed.metadata_translationrequest with the provider's input and output tokens, and showed in the tab.Evidence
Evidence: https://evidence.siloserver.org/r/silo-server/pr-5823/
Surface and build: web admin, desktop and phone width, this branch's commit against a local server. The charts show 30 days of seeded sample usage plus one real recorded translation. Before is the same page on the merge base, where the tab doesn't exist.
Risks
ai_usage_daily, a new table; nothing existing changes)..silo-translationspoints at a local build of main's catalog release plus feat(web): add AI usage Insights tab strings silo-translations#218, which now carries its translation pass. Once feat(plugins): add image resolver registry #218 merges and is released, the web catalog needs a re-sync to the release before this merges.Checklist
AI Disclosure
Note
Add AI token usage tracking and an AI usage tab to Admin Insights
GET /api/v2/admin/insights/ai(openapi.json) with per-model, per-feature, and daily breakdowns, plus anai_usagecapability flag; the endpoint requires theadmin:monitor:readscope.SetCredential(replacingSetAPIKey), so in-flight requests keep their earlier provider ID and key.usage.TrackingSincebounds all-time reports to the earlier of the first recorded usage day or the tracking migration's applied date.Changes since #5823 opened
usage.Count.UnmarshalJSONdecoder in theusagepackage to set the receiver to zero before decoding. [ffeae8b]usage.TestCountReadsLenientlyin theusagepackage forusage.CountJSON decoding. [ffeae8b]Macroscope summarized 823805a.