Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6211: feat(agents): expose usage in task history (#7085)
iiwish728d26f0b5cc
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex b8f197d669..05bd26b81e 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -1074,6 +1074,42 @@ describe("ApiClient", () => {expect(tasks[2]?.usage?.[0]?.output_tokens).toBe(0);});+ it("keeps agent detail task history on the lightweight endpoint", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify([+ { id: "task-1", status: "completed", created_at: "2026-08-27T03:00:00Z" },+ { id: "task-2", status: "completed", created_at: "2026-08-27T02:00:00Z" },+ ]),+ { status: 200, headers: { "Content-Type": "application/json" } },+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ const client = new ApiClient("https://api.example.test");+ const tasks = await client.listAgentTasks("agent-1");++ expect(tasks.map((task) => task.id)).toEqual(["task-1", "task-2"]);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(fetchMock.mock.calls[0]?.[0]).toBe(+ "https://api.example.test/api/agents/agent-1/tasks",+ );+ });++ it("falls back to an empty agent task history for a malformed response", async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ tasks: "not-an-array" }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );+ vi.stubGlobal("fetch", fetchMock);++ const client = new ApiClient("https://api.example.test");+ await expect(client.listAgentTasks("agent-1")).resolves.toEqual([]);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+it("uses the expected HTTP contract for autopilot endpoints", async () => {const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(new Response(JSON.stringify({ autopilots: [], runs: [], total: 0 }), {diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 0a05c71c84..92526f1bfd 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -2338,7 +2338,10 @@ export class ApiClient {}async listAgentTasks(agentId: string): Promise<AgentTask[]> {- return this.fetch(`/api/agents/${agentId}/tasks`);+ const raw = await this.fetch<unknown>(`/api/agents/${agentId}/tasks`);+ return parseWithFallback<AgentTask[]>(raw, AgentTaskListSchema, [], {+ endpoint: "GET /api/agents/:id/tasks",+ });}// Workspace-scoped agent task snapshot: every active taskdiff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex dad015fa9c..958ba6d312 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -407,8 +407,8 @@ export interface AgentTask {attribution?: TaskAttribution;/*** This run's own token consumption, one entry per (provider, model) it used.- * Present on the issue execution-log endpoint only; the daemon claim path- * omits it.+ * Present on issue execution logs and explicit agent-history accounting+ * requests; normal UI history and daemon claims omit it.** `undefined` (old backend, or a surface that doesn't hydrate it) and `[]`* (backend hydrated, this run has no recorded usage) both mean "no number todiff --git a/server/cmd/multica/cmd_agent.go b/server/cmd/multica/cmd_agent.goindex afc68df245..54fad5d8b3 100644--- a/server/cmd/multica/cmd_agent.go+++ b/server/cmd/multica/cmd_agent.go@@ -874,15 +874,20 @@ func runAgentTasks(cmd *cobra.Command, args []string) error {return err}+ output, _ := cmd.Flags().GetString("output")+ path := "/api/agents/" + args[0] + "/tasks"+ if output == "json" {+ path += "?include_usage=true"+ }+ctx, cancel := cli.APIContext(context.Background())defer cancel()var tasks []map[string]any- if err := client.GetJSON(ctx, "/api/agents/"+args[0]+"/tasks", &tasks); err != nil {+ if err := client.GetJSON(ctx, path, &tasks); err != nil {return fmt.Errorf("list agent runs: %w", err)}- output, _ := cmd.Flags().GetString("output")if output == "json" {return cli.PrintJSON(os.Stdout, tasks)}diff --git a/server/cmd/multica/cmd_agent_test.go b/server/cmd/multica/cmd_agent_test.goindex 46ef1a7282..6e5e836662 100644--- a/server/cmd/multica/cmd_agent_test.go+++ b/server/cmd/multica/cmd_agent_test.go@@ -33,6 +33,75 @@ func freshAgentEnvSetCmd() *cobra.Command {return c}+func newAgentTasksTestCmd() *cobra.Command {+ cmd := &cobra.Command{Use: "tasks"}+ cmd.Flags().String("output", "json", "")+ cmd.Flags().String("profile", "", "")+ return cmd+}++func TestRunAgentTasksRequestsUsageForJSON(t *testing.T) {+ t.Chdir(t.TempDir())+ t.Setenv("MULTICA_AGENT_ID", "")+ t.Setenv("MULTICA_TASK_ID", "")++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet || r.URL.Path != "/api/agents/agent-123/tasks" {+ t.Fatalf("request = %s %s", r.Method, r.URL.Path)+ }+ if got := r.URL.Query().Get("include_usage"); got != "true" {+ t.Errorf("include_usage = %q, want true for JSON output", got)+ }+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode([]map[string]any{{+ "id": "task-1",+ "usage": []map[string]any{{"provider": "openai", "input_tokens": 12}},+ }})+ }))+ defer srv.Close()+ setCLITestServerEnv(t, srv.URL)++ cmd := newAgentTasksTestCmd()+ out, err := captureStdout(t, func() error { return runAgentTasks(cmd, []string{"agent-123"}) })+ if err != nil {+ t.Fatalf("runAgentTasks: %v", err)+ }+ if !strings.Contains(out, `"input_tokens": 12`) {+ t.Fatalf("JSON output missing usage: %s", out)+ }+}++func TestRunAgentTasksKeepsTableRequestLightweight(t *testing.T) {+ t.Chdir(t.TempDir())+ t.Setenv("MULTICA_AGENT_ID", "")+ t.Setenv("MULTICA_TASK_ID", "")++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet || r.URL.Path != "/api/agents/agent-123/tasks" {+ t.Fatalf("request = %s %s", r.Method, r.URL.Path)+ }+ if got := r.URL.Query().Get("include_usage"); got != "" {+ t.Errorf("include_usage = %q, want omitted for table output", got)+ }+ _ = json.NewEncoder(w).Encode([]map[string]any{{"id": "task-1", "status": "completed"}})+ }))+ defer srv.Close()+ setCLITestServerEnv(t, srv.URL)++ cmd := newAgentTasksTestCmd()+ if err := cmd.Flags().Set("output", "table"); err != nil {+ t.Fatal(err)+ }++ out, err := captureStdout(t, func() error { return runAgentTasks(cmd, []string{"agent-123"}) })+ if err != nil {+ t.Fatalf("runAgentTasks: %v", err)+ }+ if !strings.Contains(out, "task-1") {+ t.Fatalf("output = %s", out)+ }+}+func chdirWithDaemonTaskMarker(t *testing.T) {t.Helper()diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 754c111d7e..62c0385e65 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -515,9 +515,9 @@ type AgentTaskResponse struct {Attribution *TaskAttribution `json:"attribution,omitempty"`// Usage is this run's own token consumption, one entry per (provider, model)// it used — the same grain `task_usage` stores and the same grain the client- // prices at. Hydrated only on the issue-facing execution-log endpoint- // (ListTasksByIssue); the daemon claim path leaves it nil so the claim- // payload does not carry accounting the agent has no use for.+ // prices at. Hydrated on issue execution logs and explicit agent-history+ // accounting requests; normal UI history and daemon claims leave it nil so+ // those payloads do not carry accounting they do not use.//// nil and [] are both "no usage recorded" and the UI renders an em dash for// them — a run that predates usage reporting, or one that died before any@@ -2539,6 +2539,16 @@ func (h *Handler) ListAgentTasks(w http.ResponseWriter, r *http.Request) {return}+ includeUsage := false+ switch raw := strings.TrimSpace(r.URL.Query().Get("include_usage")); raw {+ case "", "false":+ case "true":+ includeUsage = true+ default:+ writeError(w, http.StatusBadRequest, "include_usage must be true or false")+ return+ }+tasks, err := h.Queries.ListAgentTasks(r.Context(), agent.ID)if err != nil {writeError(w, http.StatusInternalServerError, "failed to list agent tasks")@@ -2546,10 +2556,24 @@ func (h *Handler) ListAgentTasks(w http.ResponseWriter, r *http.Request) {}resp := make([]AgentTaskResponse, len(tasks))+ var taskIDs []pgtype.UUID+ if includeUsage {+ taskIDs = make([]pgtype.UUID, len(tasks))+ }for i, t := range tasks {resp[i] = taskToResponse(t, workspaceID)+ if includeUsage {+ taskIDs[i] = t.ID+ }}h.hydrateTaskAttributions(r.Context(), attributionsOf(resp))+ if includeUsage {+ if err := h.hydrateAgentTaskUsage(r.Context(), agent.ID, taskIDs, resp); err != nil {+ slog.Warn("list agent task usage failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)+ writeError(w, http.StatusInternalServerError, "failed to list agent task usage")+ return+ }+ }writeJSON(w, http.StatusOK, resp)}diff --git a/server/internal/handler/agent_task_usage_response_test.go b/server/internal/handler/agent_task_usage_response_test.gonew file mode 100644index 0000000000..d04ba6459b--- /dev/null+++ b/server/internal/handler/agent_task_usage_response_test.go@@ -0,0 +1,210 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "strings"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// TestListAgentTasksHydratesUsage pins the JSON contract used by+// `multica agent tasks --output json`: usage is returned at the stored+// (provider, model) grain, only for tasks owned by the requested agent, and+// remains absent when a task has no recorded usage.+func TestListAgentTasksHydratesUsage(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ agentID := createHandlerTestAgent(t, "AgentTaskUsage", []byte("[]"))+ otherAgentID := createHandlerTestAgent(t, "AgentTaskUsageOther", []byte("[]"))++ newTask := func(agentID string) string {+ return dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": handlerTestRuntimeID(t),+ "status": "completed",+ })+ }++ usageTask := newTask(agentID)+ noUsageTask := newTask(agentID)+ otherAgentTask := newTask(otherAgentID)++ dbfx.Insert(t, "task_usage", testutil.Cols{+ "task_id": usageTask,+ "provider": "anthropic",+ "model": "claude-opus-5",+ "input_tokens": 96000,+ "output_tokens": 34000,+ "cache_read_tokens": 712000,+ "cache_write_tokens": 50000,+ "cost_usd_ticks": nil,+ })+ dbfx.Insert(t, "task_usage", testutil.Cols{+ "task_id": usageTask,+ "provider": "openai",+ "model": "gpt-5.6-terra",+ "input_tokens": 31000,+ "output_tokens": 12000,+ "cache_read_tokens": 158000,+ "cache_write_tokens": 11000,+ "cost_usd_ticks": int64(3310000000),+ })+ dbfx.Insert(t, "task_usage", testutil.Cols{+ "task_id": otherAgentTask,+ "provider": "openai",+ "model": "other-agent-model",+ "input_tokens": 1,+ "output_tokens": 2,+ "cache_read_tokens": 3,+ "cache_write_tokens": 4,+ "cost_usd_ticks": 5,+ })++ usageRows, err := testHandler.Queries.ListAgentTaskUsage(ctx, db.ListAgentTaskUsageParams{+ AgentID: parseUUID(agentID),+ TaskIds: []pgtype.UUID{parseUUID(usageTask), parseUUID(noUsageTask)},+ })+ if err != nil {+ t.Fatalf("list agent task usage: %v", err)+ }+ if len(usageRows) != 2 {+ t.Fatalf("agent-scoped usage rows = %d, want 2: %+v", len(usageRows), usageRows)+ }+ for _, row := range usageRows {+ if uuidToString(row.TaskID) != usageTask {+ t.Fatalf("agent-scoped usage leaked task %s, want only %s", uuidToString(row.TaskID), usageTask)+ }+ }++ req := newRequest(http.MethodGet, "/api/agents/"+agentID+"/tasks?include_usage=true", nil)+ req = withURLParam(req, "id", agentID)+ var resp []AgentTaskResponse+ w := testutil.Call(t, testHandler.ListAgentTasks, req).Want(http.StatusOK).JSON(&resp)++ byID := make(map[string]AgentTaskResponse, len(resp))+ for _, task := range resp {+ byID[task.ID] = task+ }+ if _, ok := byID[otherAgentTask]; ok {+ t.Fatalf("response leaked task %s from another agent", otherAgentTask)+ }++ withUsage, ok := byID[usageTask]+ if !ok {+ t.Fatalf("usage task %s missing from response", usageTask)+ }+ if len(withUsage.Usage) != 2 {+ t.Fatalf("usage rows = %d, want 2: %+v", len(withUsage.Usage), withUsage.Usage)+ }++ byModel := make(map[string]TaskUsageData, len(withUsage.Usage))+ for _, usage := range withUsage.Usage {+ byModel[usage.Model] = usage+ }+ opus, ok := byModel["claude-opus-5"]+ if !ok {+ t.Fatalf("claude-opus-5 row missing: %+v", withUsage.Usage)+ }+ if opus.Provider != "anthropic" || opus.InputTokens != 96000 ||+ opus.OutputTokens != 34000 || opus.CacheReadTokens != 712000 ||+ opus.CacheWriteTokens != 50000 {+ t.Errorf("unexpected claude-opus-5 usage: %+v", opus)+ }+ if opus.CostUsdTicks != nil {+ t.Errorf("claude-opus-5 cost_usd_ticks = %v, want nil", opus.CostUsdTicks)+ }++ terra, ok := byModel["gpt-5.6-terra"]+ if !ok {+ t.Fatalf("gpt-5.6-terra row missing: %+v", withUsage.Usage)+ }+ if terra.CostUsdTicks == nil || *terra.CostUsdTicks != 3310000000 {+ t.Errorf("gpt-5.6-terra cost_usd_ticks = %v, want 3310000000", terra.CostUsdTicks)+ }++ withoutUsage, ok := byID[noUsageTask]+ if !ok {+ t.Fatalf("no-usage task %s missing from response", noUsageTask)+ }+ if len(withoutUsage.Usage) != 0 {+ t.Errorf("task with no recorded usage has %d rows: %+v", len(withoutUsage.Usage), withoutUsage.Usage)+ }++ var raw []map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &raw); err != nil {+ t.Fatalf("decode raw task list: %v", err)+ }+ for _, task := range raw {+ if task["id"] != noUsageTask {+ continue+ }+ if _, present := task["usage"]; present {+ t.Errorf("no-usage task serialises a usage key: %v", task["usage"])+ }+ }++ invalidReq := newRequest(http.MethodGet, "/api/agents/"+agentID+"/tasks?include_usage=yes", nil)+ invalidReq = withURLParam(invalidReq, "id", agentID)+ invalidResp := testutil.Call(t, testHandler.ListAgentTasks, invalidReq).Want(http.StatusBadRequest)+ if !strings.Contains(invalidResp.Body.String(), "include_usage must be true or false") {+ t.Fatalf("invalid include_usage response = %s", invalidResp.Body.String())+ }+}++func TestListAgentTasksReturnsErrorWhenUsageLoadFails(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ agentID := createHandlerTestAgent(t, "AgentTaskUsageFailure", []byte("[]"))+ dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": handlerTestRuntimeID(t),+ "status": "completed",+ })++ lockTx, err := testPool.Begin(context.Background())+ if err != nil {+ t.Fatalf("begin controlled task usage query failure: %v", err)+ }+ t.Cleanup(func() { _ = lockTx.Rollback(context.Background()) })+ if _, err := lockTx.Exec(context.Background(), `LOCK TABLE task_usage IN ACCESS EXCLUSIVE MODE`); err != nil {+ _ = lockTx.Rollback(context.Background())+ t.Fatalf("lock task usage for controlled query failure: %v", err)+ }++ defaultReq := newRequest(http.MethodGet, "/api/agents/"+agentID+"/tasks", nil)+ defaultReq = withURLParam(defaultReq, "id", agentID)+ var defaultResp []AgentTaskResponse+ testutil.Call(t, testHandler.ListAgentTasks, defaultReq).Want(http.StatusOK).JSON(&defaultResp)+ if len(defaultResp) == 0 {+ t.Fatal("default task history unexpectedly empty")+ }+ for _, task := range defaultResp {+ if len(task.Usage) != 0 {+ t.Fatalf("default task history loaded usage while accounting table was locked: %+v", task.Usage)+ }+ }++ req := newRequest(http.MethodGet, "/api/agents/"+agentID+"/tasks?include_usage=true", nil)+ req = withURLParam(req, "id", agentID)+ errorCtx, cancel := context.WithTimeout(req.Context(), 250*time.Millisecond)+ req = req.WithContext(errorCtx)+ w := testutil.Call(t, testHandler.ListAgentTasks, req)+ cancel()+ if err := lockTx.Rollback(context.Background()); err != nil {+ t.Fatalf("release controlled task usage lock: %v", err)+ }++ w.Want(http.StatusInternalServerError)+ if !strings.Contains(w.Body.String(), "failed to list agent task usage") {+ t.Fatalf("usage query failure should not fall back to empty usage: %s", w.Body.String())+ }+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 93a92d0e3f..55fb4a9b18 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -5154,23 +5154,72 @@ func (h *Handler) hydrateTaskUsage(ctx context.Context, issueID pgtype.UUID, resbyTask := make(map[string][]TaskUsageData, len(resp))for _, row := range rows {- var cost *int64- if row.CostUsdTicks.Valid {- v := row.CostUsdTicks.Int64- cost = &v- }- taskID := uuidToString(row.TaskID)- byTask[taskID] = append(byTask[taskID], TaskUsageData{- Provider: row.Provider,- Model: row.Model,- InputTokens: row.InputTokens,- OutputTokens: row.OutputTokens,- CacheReadTokens: row.CacheReadTokens,- CacheWriteTokens: row.CacheWriteTokens,- CostUsdTicks: cost,- })+ appendTaskUsage(byTask, row.TaskID, row.Provider, row.Model,+ row.InputTokens, row.OutputTokens, row.CacheReadTokens,+ row.CacheWriteTokens, row.CostUsdTicks)+ }+ attachTaskUsage(resp, byTask)+}++// hydrateAgentTaskUsage attaches the same per-run accounting shape used by the+// issue execution log to an agent's user-facing task history. One agent-scoped+// query covers exactly the returned task IDs, avoiding unrelated history and an+// N+1 query per task.+func (h *Handler) hydrateAgentTaskUsage(ctx context.Context, agentID pgtype.UUID, taskIDs []pgtype.UUID, resp []AgentTaskResponse) error {+ if len(resp) == 0 {+ return nil+ }++ rows, err := h.Queries.ListAgentTaskUsage(ctx, db.ListAgentTaskUsageParams{+ AgentID: agentID,+ TaskIds: taskIDs,+ })+ if err != nil {+ return err}+ if len(rows) == 0 {+ return nil+ }++ byTask := make(map[string][]TaskUsageData, len(resp))+ for _, row := range rows {+ appendTaskUsage(byTask, row.TaskID, row.Provider, row.Model,+ row.InputTokens, row.OutputTokens, row.CacheReadTokens,+ row.CacheWriteTokens, row.CostUsdTicks)+ }+ attachTaskUsage(resp, byTask)+ return nil+}++func appendTaskUsage(+ byTask map[string][]TaskUsageData,+ taskID pgtype.UUID,+ provider string,+ model string,+ inputTokens int64,+ outputTokens int64,+ cacheReadTokens int64,+ cacheWriteTokens int64,+ costUsdTicks pgtype.Int8,+) {+ var cost *int64+ if costUsdTicks.Valid {+ value := costUsdTicks.Int64+ cost = &value+ }+ id := uuidToString(taskID)+ byTask[id] = append(byTask[id], TaskUsageData{+ Provider: provider,+ Model: model,+ InputTokens: inputTokens,+ OutputTokens: outputTokens,+ CacheReadTokens: cacheReadTokens,+ CacheWriteTokens: cacheWriteTokens,+ CostUsdTicks: cost,+ })+}+func attachTaskUsage(resp []AgentTaskResponse, byTask map[string][]TaskUsageData) {for i := range resp {if usage, ok := byTask[resp[i].ID]; ok {resp[i].Usage = usagediff --git a/server/pkg/db/generated/task_usage.sql.go b/server/pkg/db/generated/task_usage.sql.goindex 29336f6a2e..efabb69a5b 100644--- a/server/pkg/db/generated/task_usage.sql.go+++ b/server/pkg/db/generated/task_usage.sql.go@@ -97,6 +97,72 @@ func (q *Queries) GetTaskUsage(ctx context.Context, taskID pgtype.UUID) ([]TaskUreturn items, nil}+const listAgentTaskUsage = `-- name: ListAgentTaskUsage :many+SELECT+ tu.task_id,+ tu.provider,+ tu.model,+ tu.input_tokens,+ tu.output_tokens,+ tu.cache_read_tokens,+ tu.cache_write_tokens,+ tu.cost_usd_ticks+FROM task_usage tu+JOIN agent_task_queue atq ON atq.id = tu.task_id+WHERE atq.agent_id = $1+ AND tu.task_id = ANY($2::uuid[])+ORDER BY tu.task_id, tu.model+`++type ListAgentTaskUsageParams struct {+ AgentID pgtype.UUID `json:"agent_id"`+ TaskIds []pgtype.UUID `json:"task_ids"`+}++type ListAgentTaskUsageRow struct {+ TaskID pgtype.UUID `json:"task_id"`+ Provider string `json:"provider"`+ Model string `json:"model"`+ InputTokens int64 `json:"input_tokens"`+ OutputTokens int64 `json:"output_tokens"`+ CacheReadTokens int64 `json:"cache_read_tokens"`+ CacheWriteTokens int64 `json:"cache_write_tokens"`+ CostUsdTicks pgtype.Int8 `json:"cost_usd_ticks"`+}++// Per-(task, provider, model) usage rows for one agent's explicitly requested+// task history. ListAgentTasks is already access-gated before this query runs;+// the agent predicate preserves that authorization boundary, while task_ids+// keeps hydration aligned with the exact response without an N+1 query.+func (q *Queries) ListAgentTaskUsage(ctx context.Context, arg ListAgentTaskUsageParams) ([]ListAgentTaskUsageRow, error) {+ rows, err := q.db.Query(ctx, listAgentTaskUsage, arg.AgentID, arg.TaskIds)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListAgentTaskUsageRow{}+ for rows.Next() {+ var i ListAgentTaskUsageRow+ if err := rows.Scan(+ &i.TaskID,+ &i.Provider,+ &i.Model,+ &i.InputTokens,+ &i.OutputTokens,+ &i.CacheReadTokens,+ &i.CacheWriteTokens,+ &i.CostUsdTicks,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listDashboardAgentRunTime = `-- name: ListDashboardAgentRunTime :manySELECTatq.agent_id,diff --git a/server/pkg/db/queries/task_usage.sql b/server/pkg/db/queries/task_usage.sqlindex 89084c8ab4..09b2c7fbee 100644--- a/server/pkg/db/queries/task_usage.sql+++ b/server/pkg/db/queries/task_usage.sql@@ -49,6 +49,26 @@ JOIN agent_task_queue atq ON atq.id = tu.task_idWHERE atq.issue_id = $1ORDER BY tu.task_id, tu.model;+-- name: ListAgentTaskUsage :many+-- Per-(task, provider, model) usage rows for one agent's explicitly requested+-- task history. ListAgentTasks is already access-gated before this query runs;+-- the agent predicate preserves that authorization boundary, while task_ids+-- keeps hydration aligned with the exact response without an N+1 query.+SELECT+ tu.task_id,+ tu.provider,+ tu.model,+ tu.input_tokens,+ tu.output_tokens,+ tu.cache_read_tokens,+ tu.cache_write_tokens,+ tu.cost_usd_ticks+FROM task_usage tu+JOIN agent_task_queue atq ON atq.id = tu.task_id+WHERE atq.agent_id = sqlc.arg('agent_id')+ AND tu.task_id = ANY(sqlc.arg('task_ids')::uuid[])+ORDER BY tu.task_id, tu.model;+-- name: GetIssueUsageSummary :oneSELECTCOALESCE(SUM(tu.input_tokens), 0)::bigint AS total_input_tokens,