Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8466: STOE-30: report per-run token usage incrementally from ACP usage_update (#9791)
Kasper Stöckel485140d89049
diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsxindex b2ab463a73..d07c35814e 100644--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx@@ -11,7 +11,7 @@ import { defaultStorage } from "../platform/storage";import { issueKeys } from "../issues/queries";import { chatKeys } from "../chat/queries";import { runtimeKeys } from "../runtimes/queries";-import { workspaceWorkingAgentsKeys } from "../agents/queries";+import { agentTasksKeys, workspaceWorkingAgentsKeys } from "../agents/queries";import { workspaceKeys } from "../workspace/queries";import { issueStatusKeys } from "../issue-statuses/queries";import { issueWorkflowKeys } from "../issue-workflows/queries";@@ -458,6 +458,28 @@ describe("useRealtimeSync — comment folded into a queued run", () => {});});+describe("useRealtimeSync — live usage", () => {+ afterEach(() => {+ cleanup();+ vi.useRealTimers();+ });++ it("refreshes open run and usage queries without a task lifecycle change", async () => {+ vi.useFakeTimers();+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });+ const ws = createMockWs();+ renderHook(() => useRealtimeSync(ws, createStores()), { wrapper: createWrapper(qc) });+ const onAny = vi.mocked(ws.onAny).mock.calls[0]![0];+ const keys = [issueKeys.tasks("issue-1"), issueKeys.usage("issue-1"), agentTasksKeys.detail("ws-1", "agent-1")];+ for (const key of keys) qc.setQueryData(key, []);++ onAny({ type: "task:usage", payload: { task_id: "task-1" } });+ await vi.advanceTimersByTimeAsync(1_000);++ for (const key of keys) expect(qc.getQueryState(key)?.isInvalidated).toBe(true);+ });+});+describe("useRealtimeSync — Table server membership invalidation", () => {let qc: QueryClient;let stores: RealtimeSyncStores;diff --git a/packages/core/types/events.ts b/packages/core/types/events.tsindex c86a40912b..bc44fb0974 100644--- a/packages/core/types/events.ts+++ b/packages/core/types/events.ts@@ -29,6 +29,7 @@ export type WSEventType =| "task:running"| "task:waiting_local_directory"| "task:progress"+ | "task:usage"| "task:completed"| "task:failed"| "task:message"@@ -383,6 +384,10 @@ export interface TaskRunningPayload {status: string;}+export interface TaskUsageUpdatedPayload {+ task_id: string;+}+// task:waiting_local_directory fires when the daemon dequeues a task but// can't immediately acquire the on-disk path lock — another task on this// daemon is already executing in the same local_directory. `wait_reason` names@@ -649,6 +654,7 @@ export interface WSEventPayloadMap {"task:message": TaskMessagePayload;"task:cancelled": TaskCancelledPayload;"task:progress": unknown;+ "task:usage": TaskUsageUpdatedPayload;"inbox:new": InboxNewPayload;"inbox:read": InboxReadPayload;"inbox:unread": InboxUnreadPayload;diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex 4be7d41c54..0c0f5de0f2 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -667,6 +667,21 @@ func (c *Client) ReportTaskUsage(ctx context.Context, taskID string, usage []Tas}, nil)}+// ReportTaskUsageSnapshot posts the same rows mid-run, as a cumulative snapshot+// of what the agent has spent so far (STOE-30). UpsertTaskUsage overwrites per+// (task_id, provider, model), so snapshots cannot accumulate; the flag is what+// keeps the server's additive metrics counter and per-run log on the terminal+// report, where they would otherwise bill each flush against the last.+func (c *Client) ReportTaskUsageSnapshot(ctx context.Context, taskID string, usage []TaskUsageEntry) error {+ if len(usage) == 0 {+ return nil+ }+ return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/usage", taskID), map[string]any{+ "usage": usage,+ "snapshot": true,+ }, nil)+}+func (c *Client) FailTask(ctx context.Context, taskID, errMsg, sessionID, workDir, branchName, failureReason string, sessionRolloutMissing bool, retiredSessionID, durableWorkDir string) error {return c.failTaskWithRetrySchedule(ctx, taskID, errMsg, sessionID, workDir, branchName, failureReason, sessionRolloutMissing, retiredSessionID, durableWorkDir, defaultTerminalRetrySchedule)}diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex d017934c74..2ab8d0f500 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -9033,6 +9033,19 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot id.reportThinkingLevelWarning(ctx, task.ID, selection.ThinkingLevelWarning, &msgSeq, taskLog)outputObserver := &taskOutputObserver{}ctx = withTaskOutputObserver(ctx, outputObserver)+ // STOE-30: mirror the agent's cumulative token counters into task_usage+ // while the run is live, so a long run's cost moves on the board instead of+ // appearing only after it ends. The backend calls OnUsage from its protocol+ // reader goroutine, so this records the latest snapshot only; the flush+ // goroutine owns the HTTP call and its cadence.+ var liveUsage atomic.Value // []TaskUsageEntry+ execOpts.OnUsage = func(usage map[string]agent.TokenUsage) {+ if entries := taskUsageEntries(provider, usage); len(entries) > 0 {+ liveUsage.Store(entries)+ }+ }+ stopUsageFlush := d.startUsageFlush(ctx, task.ID, &liveUsage, taskLog)+ defer stopUsageFlush()result, tools, err := d.executeAndDrain(ctx, backend, prompt, execOpts, taskLog, task.ID, env.CodexHome, &msgSeq)if err != nil {return TaskResult{}, err@@ -9085,7 +9098,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i}freshPrompt := BuildPrompt(task, provider, promptOptions...)- retryResult, retryTools, retryErr := d.executeAndDrain(ctx, backend, freshPrompt, execOpts, taskLog, task.ID, env.CodexHome, &msgSeq)+ retryResult, retryTools, retryErr := d.executeAndDrain(ctx, backend, freshPrompt, withPriorTaskUsage(execOpts, firstUsage), taskLog, task.ID, env.CodexHome, &msgSeq)if retryErr != nil {taskLog.Error("fresh session also failed to start; keeping the original poisoned result", "error", retryErr)} else if retryResult.Status != "completed" && retryResult.SessionID == "" {@@ -9144,22 +9157,9 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i"agent_error", result.Error,)- // Convert agent usage map to task usage entries.- var usageEntries []TaskUsageEntry- for model, u := range result.Usage {- if u.InputTokens == 0 && u.OutputTokens == 0 && u.CacheReadTokens == 0 && u.CacheWriteTokens == 0 && u.CostUSDTicks <= 0 {- continue- }- usageEntries = append(usageEntries, TaskUsageEntry{- Provider: provider,- Model: model,- InputTokens: u.InputTokens,- OutputTokens: u.OutputTokens,- CacheReadTokens: u.CacheReadTokens,- CacheWriteTokens: u.CacheWriteTokens,- CostUSDTicks: u.CostUSDTicks,- })- }+ // Convert agent usage map to task usage entries. Same conversion the live+ // flush above uses, so both reports write the same rows.+ usageEntries := taskUsageEntries(provider, result.Usage)// MUL-5305: withhold a Codex session whose rollout never reached the per-issue// store, for ANY terminal state — including `completed`, since a completed@@ -9537,7 +9537,7 @@ func (d *Daemon) repairWorktreeDelivery(ctx context.Context, backend agent.BacketaskLog.Warn("local_directory: worktree delivery would be refused; asking the agent to repair it","branch", problem.Branch, "base", problem.BaseCommit, "tip", problem.Tip, "reason", problem.Reason)- opts := execOpts+ opts := withPriorTaskUsage(execOpts, result.Usage)// Continue the conversation when there is one, so the agent knows what it// just did; the prompt is self-contained for the backends that cannot.opts.ResumeSessionID = result.SessionID@@ -9630,6 +9630,106 @@ func freshSessionMayHelp(errText string) bool {}}+// withPriorTaskUsage keeps retries and repair turns on the same task-wide total+// as the terminal report, even though each backend execution starts at zero.+func withPriorTaskUsage(opts agent.ExecOptions, prior map[string]agent.TokenUsage) agent.ExecOptions {+ if report := opts.OnUsage; report != nil && len(prior) > 0 {+ opts.OnUsage = func(usage map[string]agent.TokenUsage) { report(mergeUsage(prior, usage)) }+ }+ return opts+}++// taskUsageEntries converts a backend's per-model usage map into the rows the+// server upserts. A model whose buckets are all zero is skipped rather than+// written as 0: an unreported run keeps its cost NULL server-side, which is what+// makes the board render it as unknown instead of $0.+func taskUsageEntries(provider string, usage map[string]agent.TokenUsage) []TaskUsageEntry {+ var entries []TaskUsageEntry+ for model, u := range usage {+ if u.InputTokens == 0 && u.OutputTokens == 0 && u.CacheReadTokens == 0 && u.CacheWriteTokens == 0 && u.CostUSDTicks <= 0 {+ continue+ }+ entries = append(entries, TaskUsageEntry{+ Provider: provider,+ Model: model,+ InputTokens: u.InputTokens,+ OutputTokens: u.OutputTokens,+ CacheReadTokens: u.CacheReadTokens,+ CacheWriteTokens: u.CacheWriteTokens,+ CostUSDTicks: u.CostUSDTicks,+ })+ }+ // Stable ordering lets the flush compare snapshots across map iterations.+ sort.Slice(entries, func(i, j int) bool { return entries[i].Model < entries[j].Model })+ return entries+}++// liveUsageFlushEvery bounds how often a running task's cumulative counters are+// POSTed. The agent emits them per model call; this only bounds the traffic.+const liveUsageFlushEvery = 30 * time.Second++// startUsageFlush POSTs the newest snapshot held in `live` until the returned+// stop func runs, so a long run's cost is visible before it ends (STOE-30).+// Repeating it is safe by construction: UpsertTaskUsage overwrites absolutely+// per (task_id, provider, model) and bumps updated_at, which is what makes the+// hourly rollup re-aggregate those rows, so cumulative snapshots cannot add up+// twice. It is sent as a snapshot so the server keeps its additive metrics+// counter on the terminal report (see Client.ReportTaskUsageSnapshot). That+// report stays the authoritative final value, so the caller stops this flush+// before the terminal report is made.+func (d *Daemon) startUsageFlush(ctx context.Context, taskID string, live *atomic.Value, taskLog *slog.Logger) (stop func()) {+ done := make(chan struct{})+ stopped := make(chan struct{})+ go func() {+ defer close(stopped)+ ticker := time.NewTicker(liveUsageFlushEvery)+ defer ticker.Stop()+ var reported string+ for {+ select {+ case <-done:+ return+ case <-ctx.Done():+ return+ case <-ticker.C:+ select {+ case <-done:+ return+ case <-ctx.Done():+ return+ default:+ }+ entries, _ := live.Load().([]TaskUsageEntry)+ if len(entries) == 0 {+ continue+ }+ // An idle agent costs nothing: re-posting the numbers the server+ // already has is traffic, not information.+ key := fmt.Sprintf("%v", entries)+ if key == reported {+ continue+ }+ // Preserve ordering with the terminal report even when the run is+ // cancelled. The HTTP timeout still bounds an in-flight request.+ if err := d.client.ReportTaskUsageSnapshot(context.WithoutCancel(ctx), taskID, entries); err != nil {+ // Not fatal — the terminal report carries the run's usage+ // again if a flush is lost.+ taskLog.Warn("live usage flush failed", "error", err)+ continue+ }+ reported = key+ }+ }+ }()+ return sync.OnceFunc(func() {+ close(done)+ // Let an in-flight POST finish before the terminal overwrite. Cancelling+ // only the client request can return before the server finishes writing.+ // The control-plane HTTP client's timeout bounds this wait.+ <-stopped+ })+}+// executeAndDrain runs a backend, drains its message stream (forwarding to the// server), and waits for the final result. msgSeq numbers the reported task// messages and is owned by the caller so a same-task retry continues thediff --git a/server/internal/daemon/usage_flush_test.go b/server/internal/daemon/usage_flush_test.gonew file mode 100644index 0000000000..95b0e4ea05--- /dev/null+++ b/server/internal/daemon/usage_flush_test.go@@ -0,0 +1,174 @@+package daemon++import (+ "context"+ "encoding/json"+ "io"+ "log/slog"+ "net/http"+ "strings"+ "sync/atomic"+ "testing"+ "testing/synctest"+ "time"++ "github.com/multica-ai/multica/server/pkg/agent"+)++type liveUsageReport struct {+ Usage []TaskUsageEntry `json:"usage"`+ Snapshot bool `json:"snapshot"`+}++type liveUsageTransport func(*http.Request) (*http.Response, error)++func (f liveUsageTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }++func newLiveUsageTestDaemon(t *testing.T, report func(liveUsageReport) int) *Daemon {+ t.Helper()+ client := NewClient("http://usage.invalid")+ client.client.Transport = liveUsageTransport(func(r *http.Request) (*http.Response, error) {+ if r.Method != http.MethodPost || r.URL.Path != "/api/daemon/tasks/task/usage" {+ t.Errorf("unexpected usage request: %s %s", r.Method, r.URL.Path)+ }+ var payload liveUsageReport+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {+ t.Errorf("decode usage: %v", err)+ return nil, err+ }+ return &http.Response{StatusCode: report(payload), Body: io.NopCloser(strings.NewReader(`{}`)), Header: make(http.Header)}, nil+ })+ return &Daemon{client: client}+}++func TestUsageFlushStopWaitsForInFlightSnapshot(t *testing.T) {+ synctest.Test(t, func(t *testing.T) {+ release := make(chan struct{})+ snapshots := 0+ var stored int64+ d := newLiveUsageTestDaemon(t, func(report liveUsageReport) int {+ if report.Snapshot {+ snapshots+++ <-release+ }+ stored = report.Usage[0].InputTokens+ return http.StatusOK+ })+ var live atomic.Value+ live.Store([]TaskUsageEntry{{Provider: "hermes", Model: "m", InputTokens: 10}})+ stop := d.startUsageFlush(context.Background(), "task", &live, slog.Default())+ synctest.Wait()+ time.Sleep(liveUsageFlushEvery)+ synctest.Wait()+ if snapshots != 1 {+ t.Fatalf("in-flight snapshots = %d, want 1", snapshots)+ }++ stopped := make(chan struct{})+ go func() { stop(); close(stopped) }()+ synctest.Wait()+ select {+ case <-stopped:+ t.Error("stop returned while an old snapshot could still overwrite the terminal report")+ default:+ }+ close(release)+ <-stopped+ synctest.Wait()+ if err := d.client.ReportTaskUsage(context.Background(), "task", []TaskUsageEntry{{Provider: "hermes", Model: "m", InputTokens: 100}}); err != nil {+ t.Fatal(err)+ }+ time.Sleep(2 * liveUsageFlushEvery)+ synctest.Wait()+ if snapshots != 1 || stored != 100 {+ t.Fatalf("after terminal report: snapshots=%d stored=%d, want 1 and 100", snapshots, stored)+ }+ })+}++func TestUsageFlushSkipsUnknownAndUnchangedButRetriesFailures(t *testing.T) {+ synctest.Test(t, func(t *testing.T) {+ reports := 0+ d := newLiveUsageTestDaemon(t, func(report liveUsageReport) int {+ reports+++ if !report.Snapshot {+ t.Error("mid-run report did not carry snapshot=true")+ }+ if reports == 1 {+ return http.StatusServiceUnavailable+ }+ return http.StatusOK+ })+ var live atomic.Value+ stop := d.startUsageFlush(context.Background(), "task", &live, slog.Default())+ defer stop()+ synctest.Wait()+ tick := func() { time.Sleep(liveUsageFlushEvery); synctest.Wait() }+ tick()+ if reports != 0 {+ t.Fatal("unknown usage was reported as zero")+ }+ live.Store([]TaskUsageEntry{{Provider: "hermes", Model: "m", InputTokens: 10}})+ tick()+ tick()+ tick()+ if reports != 2 {+ t.Fatalf("reports after failure, retry and unchanged tick = %d, want 2", reports)+ }+ live.Store([]TaskUsageEntry{{Provider: "hermes", Model: "m", InputTokens: 20}})+ tick()+ if reports != 3 {+ t.Fatalf("reports after new usage = %d, want 3", reports)+ }+ })+}++func TestUsageFlushCancellationStillWaitsForTheServerWrite(t *testing.T) {+ synctest.Test(t, func(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ release := make(chan struct{})+ d := newLiveUsageTestDaemon(t, func(liveUsageReport) int { <-release; return http.StatusOK })+ transport := d.client.client.Transport+ var requestCtx context.Context+ d.client.client.Transport = liveUsageTransport(func(r *http.Request) (*http.Response, error) {+ requestCtx = r.Context()+ return transport.RoundTrip(r)+ })+ var live atomic.Value+ live.Store([]TaskUsageEntry{{Provider: "hermes", Model: "m", InputTokens: 10}})+ stop := d.startUsageFlush(ctx, "task", &live, slog.Default())+ synctest.Wait()+ time.Sleep(liveUsageFlushEvery)+ synctest.Wait()+ cancel()+ if requestCtx == nil || requestCtx.Err() != nil {+ t.Error("run cancellation abandoned an in-flight server write")+ }+ stopped := make(chan struct{})+ go func() { stop(); close(stopped) }()+ synctest.Wait()+ select {+ case <-stopped:+ t.Error("stop returned before the server write settled on cancellation")+ default:+ }+ close(release)+ <-stopped+ stop()+ })+}++func TestTaskUsageSnapshotsRetainPreviousAttempts(t *testing.T) {+ prior := map[string]agent.TokenUsage{"m": {InputTokens: 100, OutputTokens: 50, CacheReadTokens: 20, CacheWriteTokens: 10, CostUSDTicks: 100}, "other": {InputTokens: 40}}+ var got map[string]agent.TokenUsage+ opts := withPriorTaskUsage(agent.ExecOptions{OnUsage: func(usage map[string]agent.TokenUsage) { got = usage }}, prior)+ opts.OnUsage(map[string]agent.TokenUsage{"m": {InputTokens: 3, OutputTokens: 2, CacheReadTokens: 1, CostUSDTicks: 5}})+ opts.OnUsage(map[string]agent.TokenUsage{"m": {InputTokens: 7, OutputTokens: 4, CacheReadTokens: 3, CacheWriteTokens: 2, CostUSDTicks: 8}})+ if want := (agent.TokenUsage{InputTokens: 107, OutputTokens: 54, CacheReadTokens: 23, CacheWriteTokens: 12, CostUSDTicks: 108}); got["m"] != want || got["other"] != prior["other"] {+ t.Fatalf("task-wide live usage = %v, want m=%+v and previous other model", got, want)+ }+ if prior["m"].InputTokens != 100 {+ t.Fatal("live snapshots mutated the previous attempt's terminal usage")+ }+}diff --git a/server/internal/daemon/worktree_delivery_repair_test.go b/server/internal/daemon/worktree_delivery_repair_test.goindex 4eda82e039..4d7be4fcb5 100644--- a/server/internal/daemon/worktree_delivery_repair_test.go+++ b/server/internal/daemon/worktree_delivery_repair_test.go@@ -152,6 +152,9 @@ func (b *repairingBackend) Execute(_ context.Context, prompt string, opts agent.msgCh := make(chan agent.Message)resCh := make(chan agent.Result, 1)close(msgCh)+ if opts.OnUsage != nil {+ opts.OnUsage(map[string]agent.TokenUsage{"m": {InputTokens: 7}})+ }resCh <- agent.Result{Status: "completed", Output: "moved the work back onto the branch", SessionID: "sess-repair",Usage: map[string]agent.TokenUsage{"m": {InputTokens: 7}}}return &agent.Session{Messages: msgCh, Result: resCh}, nil@@ -223,10 +226,15 @@ func TestRepairWorktreeDeliveryLetsTheAgentFixItsBranch(t *testing.T) {d, _ := newPinRecorder(t)backend := &repairingBackend{worktree: wt, problem: problem, comply: true}- original := agent.Result{Status: "completed", Output: "the real reply", SessionID: "sess-1"}+ original := agent.Result{Status: "completed", Output: "the real reply", SessionID: "sess-1", Usage: map[string]agent.TokenUsage{"m": {InputTokens: 100}}}env := &execenv.Environment{LocalWorktree: wt}- got, _ := d.repairWorktreeDelivery(context.Background(), backend, agent.ExecOptions{Timeout: time.Hour}, original, 1, problem, env, slog.Default(), "task-repair", new(atomic.Int32))+ var liveUsage map[string]agent.TokenUsage+ opts := agent.ExecOptions{Timeout: time.Hour, OnUsage: func(usage map[string]agent.TokenUsage) { liveUsage = usage }}+ got, _ := d.repairWorktreeDelivery(context.Background(), backend, opts, original, 1, problem, env, slog.Default(), "task-repair", new(atomic.Int32))+ if liveUsage["m"].InputTokens != 107 || liveUsage["m"] != got.Usage["m"] {+ t.Errorf("repair's live usage = %v, want terminal task total %v", liveUsage, got.Usage)+ }if backend.runErr != nil {t.Fatalf("the repair prompt's commands failed: %v", backend.runErr)}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex efb8698f24..2827b2cffc 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -5449,13 +5449,21 @@ func (h *Handler) ReportTaskUsage(w http.ResponseWriter, r *http.Request) {taskID := chi.URLParam(r, "taskId")// Verify the caller owns this task's workspace.- task, ok := h.requireDaemonTaskAccess(w, r, taskID)+ task, workspaceID, ok := h.requireDaemonTaskAccessWithWorkspace(w, r, taskID)if !ok {return}var req struct {Usage []TaskUsagePayload `json:"usage"`+ // Snapshot marks a mid-run cumulative report from a daemon that meters+ // while its agent works (STOE-30). The rows are upserted identically —+ // UpsertTaskUsage overwrites per (task_id, provider, model), so a+ // snapshot can never add up twice — but the additive metrics counter and+ // the per-run cache-ratio log stay on the terminal report: summing each+ // cumulative snapshot into RecordLLMUsage would bill the same tokens+ // once per flush.+ Snapshot bool `json:"snapshot"`}if err := json.NewDecoder(r.Body).Decode(&req); err != nil {writeError(w, http.StatusBadRequest, "invalid request body")@@ -5468,6 +5476,7 @@ func (h *Handler) ReportTaskUsage(w http.ResponseWriter, r *http.Request) {// resolve to a provider instead of landing as '' and pricing $0.var runtimeProvider stringruntimeProviderLoaded := false+ updated := falsefor _, u := range req.Usage {provider := normalizeProvider(u.Provider)if provider == "" {@@ -5483,7 +5492,7 @@ func (h *Handler) ReportTaskUsage(w http.ResponseWriter, r *http.Request) {provider = runtimeProvider}if err := h.Queries.UpsertTaskUsage(r.Context(), db.UpsertTaskUsageParams{- TaskID: parseUUID(taskID),+ TaskID: task.ID,Provider: provider,Model: u.Model,InputTokens: u.InputTokens,@@ -5495,27 +5504,47 @@ func (h *Handler) ReportTaskUsage(w http.ResponseWriter, r *http.Request) {slog.Warn("upsert task usage failed", "task_id", taskID, "model", u.Model, "error", err)continue}- h.TaskService.CaptureTaskUsage(r.Context(), task, provider, u.Model, u.InputTokens, u.OutputTokens, u.CacheReadTokens, u.CacheWriteTokens, u.CostUSDTicks)+ updated = true+ // A snapshot reports the run's total so far, so it is not a new charge:+ // RecordLLMUsage adds, and each flush would bill the tokens the previous+ // flush already billed. The terminal report carries them once.+ if !req.Snapshot {+ h.TaskService.CaptureTaskUsage(r.Context(), task, provider, u.Model, u.InputTokens, u.OutputTokens, u.CacheReadTokens, u.CacheWriteTokens, u.CostUSDTicks)+ }// Surface prompt-cache effectiveness per run so cache hit rates are// observable in logs, not just queryable from runtime_usage. The ratio// is cached input over total input-side tokens; a persistently low// value flags a prompt prefix that is not being reused across runs// (e.g. volatile values poisoning the cacheable prefix). MUL-3887.- if totalInput := u.InputTokens + u.CacheReadTokens + u.CacheWriteTokens; totalInput > 0 {- slog.Info("task prompt-cache usage",- "task_id", taskID,- "provider", provider,- "model", u.Model,- "input_tokens", u.InputTokens,- "output_tokens", u.OutputTokens,- "cache_read_tokens", u.CacheReadTokens,- "cache_write_tokens", u.CacheWriteTokens,- "cache_read_ratio", float64(u.CacheReadTokens)/float64(totalInput),- )+ if !req.Snapshot {+ if totalInput := u.InputTokens + u.CacheReadTokens + u.CacheWriteTokens; totalInput > 0 {+ slog.Info("task prompt-cache usage",+ "task_id", taskID,+ "provider", provider,+ "model", u.Model,+ "input_tokens", u.InputTokens,+ "output_tokens", u.OutputTokens,+ "cache_read_tokens", u.CacheReadTokens,+ "cache_write_tokens", u.CacheWriteTokens,+ "cache_read_ratio", float64(u.CacheReadTokens)/float64(totalInput),+ )+ }}}+ if updated {+ // This invalidates the existing task and issue-usage queries without+ // broadcasting token counts or changing task progress/status.+ h.Bus.Publish(events.Event{+ Type: protocol.EventTaskUsage,+ WorkspaceID: workspaceID,+ ActorType: "system",+ TaskID: uuidToString(task.ID),+ Payload: protocol.TaskUsageUpdatedPayload{TaskID: uuidToString(task.ID)},+ })+ }+writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})}diff --git a/server/internal/handler/task_usage_snapshot_test.go b/server/internal/handler/task_usage_snapshot_test.gonew file mode 100644index 0000000000..935b1fe061--- /dev/null+++ b/server/internal/handler/task_usage_snapshot_test.go@@ -0,0 +1,98 @@+package handler++import (+ "context"+ "math"+ "net/http"+ "testing"++ "github.com/google/uuid"+ "github.com/multica-ai/multica/server/internal/events"+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func TestReportTaskUsageSnapshotsReplaceRowsAndOnlyMeterTerminal(t *testing.T) {+ issueID := dbfx.Issue(t, "live usage")+ agentID := dbfx.Agent(t, "live usage agent", testRuntimeID)+ taskID := dbfx.Task(t, agentID, testutil.Cols{"issue_id": issueID, "runtime_id": testRuntimeID, "status": "running"})+ h := *testHandler+ h.Bus = events.New()+ h.TaskService = service.NewTaskService(h.Queries, testPool, h.Hub, h.Bus)+ m := obsmetrics.NewBusinessMetrics()+ h.TaskService.Metrics = m+ var updates []events.Event+ h.Bus.Subscribe(protocol.EventTaskUsage, func(e events.Event) { updates = append(updates, e) })+ path := "/api/daemon/tasks/" + taskID + "/usage"+ entry := TaskUsagePayload{Provider: "Anthropic", Model: "claude-opus-5", InputTokens: 100, OutputTokens: 50,+ CacheReadTokens: 20, CacheWriteTokens: 10, CostUSDTicks: 10_000_000_000}+ report := func(snapshot bool) {+ t.Helper()+ body := map[string]any{"usage": []TaskUsagePayload{entry}}+ if snapshot {+ body["snapshot"] = true+ }+ req := withURLParam(newOwnerDaemonRequest(http.MethodPost, path, body), "taskId", taskID)+ var response map[string]string+ testutil.Call(t, h.ReportTaskUsage, req).Want(http.StatusOK).JSON(&response)+ if response["status"] != "ok" {+ t.Fatalf("usage response = %v", response)+ }+ }++ // Neither malformed input nor an unrelated daemon may write or notify.+ bad := withURLParam(newOwnerDaemonRequest(http.MethodPost, path, map[string]any{+ "usage": []TaskUsagePayload{entry}, "snapshot": "yes",+ }), "taskId", taskID)+ testutil.Call(t, h.ReportTaskUsage, bad).Want(http.StatusBadRequest)+ denied := withURLParam(newDaemonTokenRequest(http.MethodPost, path, map[string]any{+ "usage": []TaskUsagePayload{entry}, "snapshot": true,+ }, uuid.NewString(), uuid.NewString()), "taskId", taskID)+ testutil.Call(t, h.ReportTaskUsage, denied).Want(http.StatusNotFound)+ empty := withURLParam(newOwnerDaemonRequest(http.MethodPost, path, map[string]any{"usage": []TaskUsagePayload{}, "snapshot": true}), "taskId", taskID)+ testutil.Call(t, h.ReportTaskUsage, empty).Want(http.StatusOK)+ if len(updates) != 0 {+ t.Fatal("rejected or empty usage published a refresh")+ }++ report(true)+ entry.InputTokens = 200+ report(true)+ rows, err := h.Queries.GetTaskUsage(context.Background(), parseUUID(taskID))+ if err != nil || len(rows) != 1 {+ t.Fatalf("snapshot rows = %v, err=%v; want one overwritten row", rows, err)+ }+ if rows[0].InputTokens != 200 || rows[0].Provider != "anthropic" || rows[0].CostUsdTicks.Int64 != entry.CostUSDTicks {+ t.Fatalf("latest cumulative snapshot was not preserved: %+v", rows[0])+ }+ for _, name := range []string{"multica_llm_tokens_total", "multica_llm_cost_usd_total"} {+ if got := counterValue(t, m, name); got != 0 {+ t.Errorf("snapshots incremented %s by %v", name, got)+ }+ }++ // Omitting snapshot is the existing daemon contract and still meters once.+ entry.InputTokens = 300+ report(false)+ rows, err = h.Queries.GetTaskUsage(context.Background(), parseUUID(taskID))+ if err != nil || len(rows) != 1 || rows[0].InputTokens != 300 {+ t.Fatalf("terminal usage = %v, err=%v; want one row with 300 input tokens", rows, err)+ }+ if got := counterValue(t, m, "multica_llm_tokens_total"); got != 380 {+ t.Errorf("metered tokens = %v, want final total 380", got)+ }+ if got := counterValue(t, m, "multica_llm_cost_usd_total"); math.Abs(got-1) > 1e-10 {+ t.Errorf("metered cost = %v, want final cost $1", got)+ }+ if len(updates) != 3 {+ t.Fatalf("refresh events = %d, want one per successful report", len(updates))+ }+ for _, update := range updates {+ payload, ok := update.Payload.(protocol.TaskUsageUpdatedPayload)+ if !ok || update.WorkspaceID != testWorkspaceID || update.TaskID != taskID || payload.TaskID != taskID {+ t.Errorf("usage refresh has wrong scope: %+v", update)+ }+ }+}diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex 1897a9dce8..a70829ca05 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -147,6 +147,17 @@ type ExecOptions struct {// EnableTaskSupplement, to accept additional messages; other providers// ignore it.CursorHookCommand []string+ // OnUsage optionally receives the backend's cumulative usage snapshot while+ // the run is still live, keyed exactly like Result.Usage so a mid-run flush+ // and the terminal report upsert the same (task, provider, model) rows+ // instead of adding a second row the rollup would charge twice. Backends+ // that cannot meter mid-run never call it.+ //+ // The callback runs on the backend's protocol reader goroutine and MUST NOT+ // block: a daemon that reports from here holds the agent's stdout open and+ // can trip its idle watchdog. Take the snapshot and report on your own+ // goroutine.+ OnUsage func(map[string]TokenUsage)// piMcpExtensionPath is set by piBackend.Execute after it writes the// temporary MCP extension. The daemon does not fill it.piMcpExtensionPath stringdiff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.goindex 6643319fcd..ad3c749fce 100644--- a/server/pkg/agent/hermes.go+++ b/server/pkg/agent/hermes.go@@ -600,6 +600,7 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOptdefault:}},+ onUsage: opts.OnUsage,}// Start reading stdout in background.@@ -772,6 +773,14 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt}c.sessionID = sessionID+ // Fix the usage key for the whole run here, once the handshake has+ // settled on the model the session actually runs on: the mid-run+ // snapshots below and the terminal usage map must land on the same+ // (provider, model) row, or the server's per-model upsert would count+ // the run twice.+ c.usageMu.Lock()+ c.usageModel = effectiveModel+ c.usageMu.Unlock()b.cfg.Logger.Info("hermes session created", "session_id", sessionID)// 3. If the caller picked a model (via agent.model from the// UI dropdown), ask hermes to switch the session to it@@ -1167,6 +1176,13 @@ type hermesClient struct {sessionID stringonMessage func(Message)onPromptDone func(hermesPromptResult)+ // onUsage mirrors the run's cumulative usage to the daemon while the turn is+ // live (agent.ExecOptions.OnUsage). Nil means the caller does not meter live.+ onUsage func(map[string]TokenUsage)+ // usageModel is the model id the terminal usage map is keyed by, captured+ // once the session handshake settles so a mid-run snapshot lands on the same+ // (provider, model) row the terminal report writes instead of a second one.+ usageModel string// selectPermission lets an ACP dialect narrow the generic headless// permission policy. Reasonix uses this to reject user questions and// fresh-human approvals that also happen to carry allow_once options.@@ -2433,11 +2449,18 @@ func extractACPToolCallText(blocks []json.RawMessage) string {func (c *hermesClient) handleUsageUpdate(data json.RawMessage) {var msg struct {Usage json.RawMessage `json:"usage"`+ // Hermes' cumulative per-run counters arrive on the ACP extensibility+ // key: the standard `usage_update` carries only `size`/`used`, so+ // `_meta.usage` is the only place those counters can reach the daemon+ // mid-run. Same `_meta`-aware shape extractPromptResult already uses.+ Meta json.RawMessage `json:"_meta"`}if err := json.Unmarshal(data, &msg); err != nil {return}- c.mergeUsage(parseACPTokenUsageSnapshot(msg.Usage))+ c.mergeUsage(parseACPTokenUsageSnapshot(msg.Usage).+ withFallback(parseACPTokenUsageSnapshotFromMeta(msg.Meta)))+ c.notifyUsage()}func (c *hermesClient) mergeUsage(usage acpUsageSnapshot) {@@ -2452,6 +2475,35 @@ func (c *hermesClient) accumulatedUsage() TokenUsage {return c.usage.TokenUsage}+// liveUsage is the mid-run view of the accumulator the terminal Result.Usage is+// built from, keyed the same way so both reports upsert one (provider, model)+// row. Nil means nothing is known yet: a run that has not completed a provider+// call has to stay unknown on the board, not a reported zero.+func (c *hermesClient) liveUsage() map[string]TokenUsage {+ c.usageMu.Lock()+ usage, model := c.usage.TokenUsage, c.usageModel+ c.usageMu.Unlock()+ if !acpUsagePresent(usage) {+ return nil+ }+ if model == "" {+ model = "unknown"+ }+ return map[string]TokenUsage{model: usage}+}++// notifyUsage passes the current snapshot to the daemon's live metering sink.+// This runs on the stdout reader goroutine, so the callback is the daemon's own+// non-blocking recorder — see agent.ExecOptions.OnUsage.+func (c *hermesClient) notifyUsage() {+ if c.onUsage == nil {+ return+ }+ if usage := c.liveUsage(); usage != nil {+ c.onUsage(usage)+ }+}+// ── Helpers ──// extractACPSessionID pulls `sessionId` out of a session/new ordiff --git a/server/pkg/agent/hermes_test.go b/server/pkg/agent/hermes_test.goindex 47a052258b..3b9a031c65 100644--- a/server/pkg/agent/hermes_test.go+++ b/server/pkg/agent/hermes_test.go@@ -1780,6 +1780,95 @@ func TestHermesClientHandleUsageUpdateCumulative(t *testing.T) {}}+// Hermes' adapter carries no token fields on the standard usage_update frame —+// only `size`/`used` — so its cumulative per-run counters ride on the ACP+// extensibility key (STOE-30).+func TestHermesClientHandleUsageUpdateFromMeta(t *testing.T) {+ t.Parallel()++ c := &hermesClient{pending: make(map[int]*pendingRPC)}++ c.handleLine(`{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_1","update":{"sessionUpdate":"usage_update","size":131072,"used":4096,"_meta":{"usage":{"inputTokens":73752,"outputTokens":7511,"cachedReadTokens":685384,"cachedWriteTokens":0}}}}}`)++ c.usageMu.Lock()+ defer c.usageMu.Unlock()++ if c.usage.InputTokens != 73752 {+ t.Errorf("inputTokens: got %d, want 73752", c.usage.InputTokens)+ }+ if c.usage.OutputTokens != 7511 {+ t.Errorf("outputTokens: got %d, want 7511", c.usage.OutputTokens)+ }+ if c.usage.CacheReadTokens != 685384 {+ t.Errorf("cacheReadTokens: got %d, want 685384", c.usage.CacheReadTokens)+ }+}++// The standard top-level usage stays authoritative when a runtime reports both+// representations, matching withFallback's precedence.+func TestHermesClientHandleUsageUpdatePrefersTopLevelUsage(t *testing.T) {+ t.Parallel()++ c := &hermesClient{pending: make(map[int]*pendingRPC)}++ c.handleLine(`{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_1","update":{"sessionUpdate":"usage_update","usage":{"inputTokens":100,"outputTokens":50},"_meta":{"usage":{"inputTokens":900,"outputTokens":900}}}}}`)++ c.usageMu.Lock()+ defer c.usageMu.Unlock()++ if c.usage.InputTokens != 100 {+ t.Errorf("inputTokens: got %d, want 100", c.usage.InputTokens)+ }+ if c.usage.OutputTokens != 50 {+ t.Errorf("outputTokens: got %d, want 50", c.usage.OutputTokens)+ }+}++// The daemon's live metering sink (ExecOptions.OnUsage) has to see the same+// cumulative totals, keyed by the model the terminal usage map will use.+func TestHermesClientLiveUsageMidRun(t *testing.T) {+ t.Parallel()++ var got []map[string]TokenUsage+ c := &hermesClient{+ pending: make(map[int]*pendingRPC),+ usageModel: "nous:moonshotai/kimi-k2.6",+ onUsage: func(usage map[string]TokenUsage) { got = append(got, usage) },+ }++ // Before any usage frame the run is unknown, not zero.+ if u := c.liveUsage(); u != nil {+ t.Errorf("liveUsage with no usage frame: got %v, want nil", u)+ }++ c.handleLine(`{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_1","update":{"sessionUpdate":"usage_update","_meta":{"usage":{"inputTokens":100,"outputTokens":50}}}}}`)+ c.handleLine(`{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_1","update":{"sessionUpdate":"usage_update","_meta":{"usage":{"inputTokens":300,"outputTokens":120,"cachedReadTokens":80}}}}}`)++ if len(got) != 2 {+ t.Fatalf("onUsage calls: got %d, want 2", len(got))+ }+ u := got[1]["nous:moonshotai/kimi-k2.6"]+ if u.InputTokens != 300 || u.OutputTokens != 120 || u.CacheReadTokens != 80 {+ t.Errorf("live snapshot: got %+v", u)+ }+ if terminal := c.liveUsage(); terminal["nous:moonshotai/kimi-k2.6"].InputTokens != 300 {+ t.Errorf("terminal snapshot key/values: got %+v", terminal)+ }+}++// A backend that is not metered live must not pay for the snapshot.+func TestHermesClientLiveUsageWithoutSink(t *testing.T) {+ t.Parallel()++ c := &hermesClient{pending: make(map[int]*pendingRPC)}+ c.handleLine(`{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_1","update":{"sessionUpdate":"usage_update","_meta":{"usage":{"inputTokens":100,"outputTokens":50}}}}}`)++ if c.usage.InputTokens != 100 {+ t.Errorf("inputTokens: got %d, want 100", c.usage.InputTokens)+ }+ c.notifyUsage() // nil onUsage must be a no-op, not a panic+}+// ── extractPromptResult ──func TestHermesClientExtractPromptResult(t *testing.T) {diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.goindex 42c318c894..9ed914c0fa 100644--- a/server/pkg/protocol/events.go+++ b/server/pkg/protocol/events.go@@ -29,7 +29,7 @@ const (EventAgentRestored = "agent:restored"// Task events (server <-> daemon).- // Each event maps to a status transition on agent_task_queue. Front-end+ // Events describe task lifecycle or recorded usage changes. Front-end// subscribes by `task:` prefix and invalidates the workspace task// snapshot, so the granularity here is "what does the user want to see// change" — not "every internal status flip".@@ -39,6 +39,7 @@ const (EventTaskRunning = "task:running" // dispatched → running (daemon started)EventTaskWaitingLocalDirectory = "task:waiting_local_directory" // dispatched → waiting_local_directory (daemon parked on a busy local_directory path)EventTaskProgress = "task:progress"+ EventTaskUsage = "task:usage"EventTaskCompleted = "task:completed" // running → completedEventTaskFailed = "task:failed" // running → failedEventTaskMessage = "task:message"diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.goindex a98b435d75..fcf1ec9a38 100644--- a/server/pkg/protocol/messages.go+++ b/server/pkg/protocol/messages.go@@ -204,6 +204,12 @@ type TaskProgressPayload struct {Total int `json:"total,omitempty"`}+// TaskUsageUpdatedPayload invalidates cached usage after a successful report.+// It carries no usage values; clients refetch through their authorized APIs.+type TaskUsageUpdatedPayload struct {+ TaskID string `json:"task_id"`+}+// TaskCompletedPayload is sent from daemon to server when a task finishes.type TaskCompletedPayload struct {TaskID string `json:"task_id"`