feat(worker): expose usage/model-usage hub surface and persist run model
Adds GetUsageSnapshot/GetModelUsage/GetTaskUsage to WorkerHub (backed by a shared UsageSnapshotBuilder), a UsageUpdated broadcast fired after every UsageMonitorService poll cycle, and records the resolved model on each task_runs row so per-model/per-task usage can be reported from history.
This commit is contained in:
@@ -17,6 +17,8 @@ using ClaudeDo.Worker.Report;
|
||||
using ClaudeDo.Worker.Report.Interfaces;
|
||||
using ClaudeDo.Worker.Skills;
|
||||
using ClaudeDo.Worker.State;
|
||||
using ClaudeDo.Worker.Usage;
|
||||
using ClaudeDo.Worker.Usage.Interfaces;
|
||||
using ClaudeDo.Worker.Worktrees;
|
||||
using System.Text.Json;
|
||||
using TaskStatus = ClaudeDo.Data.Models.TaskStatus;
|
||||
@@ -103,6 +105,49 @@ public record OnlineInboxConfigInput(
|
||||
string Scopes,
|
||||
string RedirectUri);
|
||||
|
||||
public record UsageLimitDto(
|
||||
string Kind,
|
||||
string Group,
|
||||
double Percent,
|
||||
string Severity,
|
||||
DateTimeOffset? ResetsAt,
|
||||
string? ScopeModelDisplayName,
|
||||
bool IsActive);
|
||||
|
||||
public record UsageSnapshotDto(
|
||||
double? FiveHourPercent,
|
||||
DateTimeOffset? FiveHourResetsAt,
|
||||
double? SevenDayPercent,
|
||||
DateTimeOffset? SevenDayResetsAt,
|
||||
IReadOnlyList<UsageLimitDto> Limits,
|
||||
int FiveHourThresholdPct,
|
||||
int SevenDayThresholdPct,
|
||||
bool IsGateBlocked,
|
||||
string? GateReason,
|
||||
DateTime? FetchedAtUtc,
|
||||
bool IsStale,
|
||||
string? LastError);
|
||||
|
||||
public record ModelUsageRowDto(
|
||||
DateOnly Date,
|
||||
string Model,
|
||||
string Scope,
|
||||
long InputTokens,
|
||||
long OutputTokens,
|
||||
long CacheReadTokens,
|
||||
long CacheCreationTokens,
|
||||
int Messages);
|
||||
|
||||
public record TaskUsageRowDto(
|
||||
string TaskId,
|
||||
string TaskTitle,
|
||||
string ListId,
|
||||
string ListName,
|
||||
string? Model,
|
||||
int Runs,
|
||||
long TokensIn,
|
||||
long TokensOut);
|
||||
|
||||
public sealed class WorkerHub : Microsoft.AspNetCore.SignalR.Hub
|
||||
{
|
||||
private static readonly string Version =
|
||||
@@ -136,6 +181,8 @@ public sealed class WorkerHub : Microsoft.AspNetCore.SignalR.Hub
|
||||
private readonly IInteractiveLaunchSpecService? _interactiveLaunchSpec;
|
||||
private readonly WorktreeManager? _worktreeManager;
|
||||
private readonly Data.Git.GitService? _git;
|
||||
private readonly UsageSnapshotBuilder? _usageSnapshotBuilder;
|
||||
private readonly ITranscriptUsageReader? _usageReader;
|
||||
|
||||
public WorkerHub(
|
||||
QueueService queue,
|
||||
@@ -165,7 +212,9 @@ public sealed class WorkerHub : Microsoft.AspNetCore.SignalR.Hub
|
||||
LogRingBuffer? logBuffer = null,
|
||||
IInteractiveLaunchSpecService? interactiveLaunchSpec = null,
|
||||
WorktreeManager? worktreeManager = null,
|
||||
Data.Git.GitService? git = null)
|
||||
Data.Git.GitService? git = null,
|
||||
UsageSnapshotBuilder? usageSnapshotBuilder = null,
|
||||
ITranscriptUsageReader? usageReader = null)
|
||||
{
|
||||
_queue = queue;
|
||||
_waker = waker;
|
||||
@@ -195,6 +244,8 @@ public sealed class WorkerHub : Microsoft.AspNetCore.SignalR.Hub
|
||||
_interactiveLaunchSpec = interactiveLaunchSpec;
|
||||
_worktreeManager = worktreeManager;
|
||||
_git = git;
|
||||
_usageSnapshotBuilder = usageSnapshotBuilder;
|
||||
_usageReader = usageReader;
|
||||
}
|
||||
|
||||
// Persistence boundary for the session_skills JSON-array columns (task/list/global).
|
||||
@@ -978,4 +1029,65 @@ public sealed class WorkerHub : Microsoft.AspNetCore.SignalR.Hub
|
||||
_onlineTokenStore.Clear();
|
||||
}
|
||||
#pragma warning restore CA1416
|
||||
|
||||
public Task<UsageSnapshotDto> GetUsageSnapshot() => HubGuard(() =>
|
||||
{
|
||||
if (_usageSnapshotBuilder is null)
|
||||
throw new InvalidOperationException("Usage snapshot builder is not configured.");
|
||||
return _usageSnapshotBuilder.BuildAsync(Context.ConnectionAborted);
|
||||
});
|
||||
|
||||
public Task<IReadOnlyList<ModelUsageRowDto>> GetModelUsage(DateOnly from, DateOnly to) => HubGuard(async () =>
|
||||
{
|
||||
if (_usageReader is null)
|
||||
throw new InvalidOperationException("Transcript usage reader is not configured.");
|
||||
var rows = await _usageReader.ReadAsync(from, to, Context.ConnectionAborted);
|
||||
return (IReadOnlyList<ModelUsageRowDto>)rows
|
||||
.Select(r => new ModelUsageRowDto(
|
||||
r.Date, r.Model, r.Scope == UsageScope.ClaudeDo ? "claudedo" : "other",
|
||||
r.InputTokens, r.OutputTokens, r.CacheReadTokens, r.CacheCreationTokens, r.Messages))
|
||||
.ToList();
|
||||
});
|
||||
|
||||
public async Task<IReadOnlyList<TaskUsageRowDto>> GetTaskUsage(DateOnly from, DateOnly to)
|
||||
{
|
||||
var fromDt = from.ToDateTime(TimeOnly.MinValue);
|
||||
var toDt = to.ToDateTime(TimeOnly.MaxValue);
|
||||
|
||||
await using var ctx = await _dbFactory.CreateDbContextAsync(Context.ConnectionAborted);
|
||||
var runs = await ctx.TaskRuns
|
||||
.Where(r => r.StartedAt != null && r.StartedAt >= fromDt && r.StartedAt <= toDt)
|
||||
.ToListAsync(Context.ConnectionAborted);
|
||||
|
||||
if (runs.Count == 0) return Array.Empty<TaskUsageRowDto>();
|
||||
|
||||
var taskIds = runs.Select(r => r.TaskId).Distinct().ToList();
|
||||
var tasks = await ctx.Tasks.Where(t => taskIds.Contains(t.Id)).ToListAsync(Context.ConnectionAborted);
|
||||
var taskById = tasks.ToDictionary(t => t.Id);
|
||||
|
||||
var listIds = tasks.Select(t => t.ListId).Distinct().ToList();
|
||||
var lists = await ctx.Lists.Where(l => listIds.Contains(l.Id)).ToDictionaryAsync(l => l.Id, Context.ConnectionAborted);
|
||||
|
||||
return runs
|
||||
.Where(r => taskById.ContainsKey(r.TaskId))
|
||||
.GroupBy(r => r.TaskId)
|
||||
.Select(g =>
|
||||
{
|
||||
var task = taskById[g.Key];
|
||||
var listName = lists.TryGetValue(task.ListId, out var list) ? list.Name : "";
|
||||
var latestModel = g.OrderByDescending(r => r.StartedAt).First().Model;
|
||||
return new TaskUsageRowDto(
|
||||
task.Id,
|
||||
task.Title,
|
||||
task.ListId,
|
||||
listName,
|
||||
latestModel,
|
||||
g.Count(),
|
||||
g.Sum(r => (long)(r.TokensIn ?? 0)),
|
||||
g.Sum(r => (long)(r.TokensOut ?? 0)));
|
||||
})
|
||||
.OrderByDescending(r => r.TokensIn + r.TokensOut)
|
||||
.Take(100)
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user