Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(usage): add Time and Tasks to daily-trend toggle (MUL-2283) (#2709)

Jiayuan Zhang380c6b512215
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 2f2f292150..23d708a5ea 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -47,6 +47,7 @@ import type {
DashboardUsageDaily,
DashboardUsageByAgent,
DashboardAgentRunTime,
+ DashboardRunTimeDaily,
RuntimeUpdate,
RuntimeModelListRequest,
RuntimeLocalSkillListRequest,
@@ -109,6 +110,7 @@ import {
CommentsListSchema,
CreateAgentFromTemplateResponseSchema,
DashboardAgentRunTimeListSchema,
+ DashboardRunTimeDailyListSchema,
DashboardUsageByAgentListSchema,
DashboardUsageDailyListSchema,
EMPTY_AGENT_TEMPLATE_DETAIL,
@@ -889,6 +891,21 @@ export class ApiClient {
);
}
+ async getDashboardRunTimeDaily(
+ params: { days?: number; project_id?: string | null },
+ ): Promise<DashboardRunTimeDaily[]> {
+ const search = new URLSearchParams();
+ if (params.days) search.set("days", String(params.days));
+ if (params.project_id) search.set("project_id", params.project_id);
+ const raw = await this.fetch<unknown>(`/api/dashboard/runtime/daily?${search}`);
+ return parseWithFallback<DashboardRunTimeDaily[]>(
+ raw,
+ DashboardRunTimeDailyListSchema,
+ [],
+ { endpoint: "GET /api/dashboard/runtime/daily" },
+ );
+ }
+
async initiateUpdate(
runtimeId: string,
targetVersion: string,
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 1d46a0d4c3..79e2071b11 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -238,6 +238,15 @@ const DashboardAgentRunTimeSchema = z.object({
export const DashboardAgentRunTimeListSchema = z.array(DashboardAgentRunTimeSchema);
+const DashboardRunTimeDailySchema = z.object({
+ date: z.string(),
+ total_seconds: z.number().default(0),
+ task_count: z.number().default(0),
+ failed_count: z.number().default(0),
+}).loose();
+
+export const DashboardRunTimeDailyListSchema = z.array(DashboardRunTimeDailySchema);
+
// ---------------------------------------------------------------------------
// Agent template catalog — `/api/agent-templates*` and the
// create-from-template response. The desktop app's create-agent picker
diff --git a/packages/core/dashboard/queries.ts b/packages/core/dashboard/queries.ts
index b4693d06c4..d58c26b67f 100644
--- a/packages/core/dashboard/queries.ts
+++ b/packages/core/dashboard/queries.ts
@@ -22,6 +22,8 @@ export const dashboardKeys = {
[...dashboardKeys.all(wsId), "by-agent", days, projectId] as const,
agentRuntime: (wsId: string, days: number, projectId: string | null) =>
[...dashboardKeys.all(wsId), "agent-runtime", days, projectId] as const,
+ runTimeDaily: (wsId: string, days: number, projectId: string | null) =>
+ [...dashboardKeys.all(wsId), "runtime-daily", days, projectId] as const,
};
// 60s staleTime matches the per-runtime usage queries — the data is rollup-
@@ -70,3 +72,17 @@ export function dashboardAgentRunTimeOptions(
staleTime: STALE_TIME,
});
}
+
+export function dashboardRunTimeDailyOptions(
+ wsId: string,
+ days: number,
+ projectId: string | null,
+) {
+ return queryOptions({
+ queryKey: dashboardKeys.runTimeDaily(wsId, days, projectId),
+ queryFn: () =>
+ api.getDashboardRunTimeDaily({ days, project_id: projectId ?? undefined }),
+ enabled: !!wsId,
+ staleTime: STALE_TIME,
+ });
+}
diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.ts
index abd596acda..63da9a66a9 100644
--- a/packages/core/types/agent.ts
+++ b/packages/core/types/agent.ts
@@ -397,6 +397,17 @@ export interface DashboardAgentRunTime {
failed_count: number;
}
+// One (date) bucket of terminal-task run-time + counts for the workspace
+// dashboard. Powers the Time and Tasks metrics on the daily-trend toggle
+// — same toggle as Tokens / Cost, anchored on completed_at so day buckets
+// line up with the per-agent run-time card.
+export interface DashboardRunTimeDaily {
+ date: string;
+ total_seconds: number;
+ task_count: number;
+ failed_count: number;
+}
+
export type RuntimeUpdateStatus =
| "pending"
| "running"
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 2645da5f5c..5b4c47e101 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -32,6 +32,7 @@ export type {
DashboardUsageDaily,
DashboardUsageByAgent,
DashboardAgentRunTime,
+ DashboardRunTimeDaily,
RuntimeUpdate,
RuntimeUpdateStatus,
RuntimeModel,
diff --git a/packages/views/dashboard/components/dashboard-page.tsx b/packages/views/dashboard/components/dashboard-page.tsx
index 6d4e9ffa57..8f9a25588d 100644
--- a/packages/views/dashboard/components/dashboard-page.tsx
+++ b/packages/views/dashboard/components/dashboard-page.tsx
@@ -18,11 +18,17 @@ import {
dashboardUsageDailyOptions,
dashboardUsageByAgentOptions,
dashboardAgentRunTimeOptions,
+ dashboardRunTimeDailyOptions,
} from "@multica/core/dashboard";
import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";
import { PageHeader } from "../../layout/page-header";
import { KpiCard } from "../../runtimes/components/shared";
-import { DailyCostChart, DailyTokensChart } from "../../runtimes/components/charts";
+import {
+ DailyCostChart,
+ DailyTokensChart,
+ DailyTimeChart,
+ DailyTasksChart,
+} from "../../runtimes/components/charts";
import { ProjectIcon } from "../../projects/components/project-icon";
import { ActorAvatar } from "../../common/actor-avatar";
import {
@@ -34,6 +40,8 @@ import { useT } from "../../i18n";
import {
aggregateAgentTokens,
aggregateDailyCost,
+ aggregateDailyTasks,
+ aggregateDailyTime,
aggregateDailyTokens,
computeDailyTotals,
formatDuration,
@@ -60,6 +68,7 @@ const ALL_PROJECTS = "__all__";
const EMPTY_DAILY: import("@multica/core/types").DashboardUsageDaily[] = [];
const EMPTY_BY_AGENT: import("@multica/core/types").DashboardUsageByAgent[] = [];
const EMPTY_RUNTIME: import("@multica/core/types").DashboardAgentRunTime[] = [];
+const EMPTY_RUNTIME_DAILY: import("@multica/core/types").DashboardRunTimeDaily[] = [];
function fmtMoney(n: number): string {
if (n >= 100) return `$${n.toFixed(0)}`;
@@ -141,27 +150,43 @@ export function DashboardPage() {
const dailyQuery = useQuery(dashboardUsageDailyOptions(wsId, days, projectId));
const byAgentQuery = useQuery(dashboardUsageByAgentOptions(wsId, days, projectId));
const runTimeQuery = useQuery(dashboardAgentRunTimeOptions(wsId, days, projectId));
+ const runTimeDailyQuery = useQuery(
+ dashboardRunTimeDailyOptions(wsId, days, projectId),
+ );
const dailyUsage = dailyQuery.data ?? EMPTY_DAILY;
const byAgentUsage = byAgentQuery.data ?? EMPTY_BY_AGENT;
const runTimeRows = runTimeQuery.data ?? EMPTY_RUNTIME;
+ const runTimeDailyRows = runTimeDailyQuery.data ?? EMPTY_RUNTIME_DAILY;
const isLoading =
- dailyQuery.isLoading || byAgentQuery.isLoading || runTimeQuery.isLoading;
-
- // Three independent rollups, but the empty-state is one decision — only
- // show "no data yet" when ALL three came back empty so a project with
- // tokens but no runs doesn't look broken.
+ dailyQuery.isLoading ||
+ byAgentQuery.isLoading ||
+ runTimeQuery.isLoading ||
+ runTimeDailyQuery.isLoading;
+
+ // Four independent rollups, but the empty-state is one decision — only
+ // show "no data yet" when ALL came back empty so a project with tokens
+ // but no runs (or vice-versa) doesn't look broken.
const hasNoData =
!isLoading &&
dailyUsage.length === 0 &&
byAgentUsage.length === 0 &&
- runTimeRows.length === 0;
+ runTimeRows.length === 0 &&
+ runTimeDailyRows.length === 0;
// Cost / token math — re-derived when usage, days, or pricings change.
const totals = useMemo(() => computeDailyTotals(dailyUsage), [dailyUsage]);
const dailyCost = useMemo(() => aggregateDailyCost(dailyUsage), [dailyUsage]);
const dailyTokens = useMemo(() => aggregateDailyTokens(dailyUsage), [dailyUsage]);
+ const dailyTime = useMemo(
+ () => aggregateDailyTime(runTimeDailyRows),
+ [runTimeDailyRows],
+ );
+ const dailyTasks = useMemo(
+ () => aggregateDailyTasks(runTimeDailyRows),
+ [runTimeDailyRows],
+ );
const agentTokenRows = useMemo(
() => aggregateAgentTokens(byAgentUsage),
[byAgentUsage],
@@ -265,10 +290,16 @@ export function DashboardPage() {
/>
</div>
- {/* Daily trend chart — toggle picks Cost vs Tokens axis,
- mirroring the runtime-detail Usage section so both
- surfaces share one chart language. */}
- <DailyTrendBlock dailyCost={dailyCost} dailyTokens={dailyTokens} />
+ {/* Daily trend chart — toggle picks Tokens / Cost / Time /
+ Tasks. All four share the same x-axis (date) so the user
+ can mentally overlay them by switching the toggle. */}
+ <DailyTrendBlock
+ dailyCost={dailyCost}
+ dailyTokens={dailyTokens}
+ dailyTime={dailyTime}
+ dailyTasks={dailyTasks}
+ lessThanMinuteLabel={t(($) => $.duration.less_than_minute)}
+ />
{/* Per-agent leaderboard — user picks the ranking metric;
the progress bar and column emphasis follow the metric. */}
@@ -342,43 +373,67 @@ function ProjectFilter({
);
}
-type DailyMetric = "cost" | "tokens";
+type DailyMetric = "tokens" | "cost" | "time" | "tasks";
function DailyTrendBlock({
dailyCost,
dailyTokens,
+ dailyTime,
+ dailyTasks,
+ lessThanMinuteLabel,
}: {
dailyCost: ReturnType<typeof aggregateDailyCost>;
dailyTokens: ReturnType<typeof aggregateDailyTokens>;
+ dailyTime: ReturnType<typeof aggregateDailyTime>;
+ dailyTasks: ReturnType<typeof aggregateDailyTasks>;
+ lessThanMinuteLabel: string;
}) {
const { t } = useT("usage");
const [metric, setMetric] = useState<DailyMetric>("tokens");
- // Empty-state is per-metric so a workspace that recorded tokens but
- // has no priced models (unmapped) still gets a real Tokens chart while
- // its Cost view falls through to the empty-state — same convention as
- // the runtimes-side DailyTab in usage-section.tsx.
+ // Empty-state is per-metric so each toggle option independently decides
+ // whether it has data — e.g. tokens recorded but no terminal runs yet
+ // should show Tokens normally while Time / Tasks fall through to empty.
const totalCost = dailyCost.reduce((sum, d) => sum + d.total, 0);
const totalTokens = dailyTokens.reduce(
(sum, d) => sum + d.input + d.output + d.cacheRead + d.cacheWrite,
0,
);
- const isEmpty = metric === "cost" ? totalCost === 0 : totalTokens === 0;
+ const totalSeconds = dailyTime.reduce((sum, d) => sum + d.totalSeconds, 0);
+ const totalTasks = dailyTasks.reduce(
+ (sum, d) => sum + d.completed + d.failed,
+ 0,
+ );
+ const isEmpty =
+ metric === "cost"
+ ? totalCost === 0
+ : metric === "tokens"
+ ? totalTokens === 0
+ : metric === "time"
+ ? totalSeconds === 0
+ : totalTasks === 0;
+
+ const title =
+ metric === "cost"
+ ? t(($) => $.daily.title_cost)
+ : metric === "tokens"
+ ? t(($) => $.daily.title_tokens)
+ : metric === "time"
+ ? t(($) => $.daily.title_time)
+ : t(($) => $.daily.title_tasks);
return (
<div className="rounded-lg border bg-card p-4">
<div className="mb-3 flex flex-wrap items-center justify-between gap-3">
- <h4 className="text-sm font-semibold">
- {metric === "cost"
- ? t(($) => $.daily.title_cost)
- : t(($) => $.daily.title_tokens)}
- </h4>
+ <h4 className="text-sm font-semibold">{title}</h4>
<Segmented
value={metric}
onChange={setMetric}
options={[
{ label: t(($) => $.daily.metric_tokens), value: "tokens" as const },
{ label: t(($) => $.daily.metric_cost), value: "cost" as const },
+ { label: t(($) => $.daily.metric_time), value: "time" as const },
+ { label: t(($) => $.daily.metric_tasks), value: "tasks" as const },
]}
/>
</div>
@@ -392,8 +447,16 @@ function DailyTrendBlock({
</div>
) : metric === "cost" ? (
<DailyCostChart data={dailyCost} />
- ) : (
+ ) : metric === "tokens" ? (
<DailyTokensChart data={dailyTokens} />
+ ) : metric === "time" ? (
+ <DailyTimeChart
+ data={dailyTime}
+ formatY={(s) => formatDuration(s, lessThanMinuteLabel)}
+ formatTooltip={(s) => formatDuration(s, lessThanMinuteLabel)}
+ />
+ ) : (
+ <DailyTasksChart data={dailyTasks} />
)}
</div>
</div>
diff --git a/packages/views/dashboard/utils.ts b/packages/views/dashboard/utils.ts
index db4c93a1bd..4f937306ce 100644
--- a/packages/views/dashboard/utils.ts
+++ b/packages/views/dashboard/utils.ts
@@ -2,8 +2,13 @@ import type {
DashboardUsageDaily,
DashboardUsageByAgent,
DashboardAgentRunTime,
+ DashboardRunTimeDaily,
} from "@multica/core/types";
import { estimateCost, estimateCostBreakdown, type DailyTokenData } from "../runtimes/utils";
+import type {
+ DailyTimeData,
+ DailyTasksData,
+} from "../runtimes/components/charts";
// ---------------------------------------------------------------------------
// Dashboard data aggregations
@@ -212,6 +217,37 @@ export function mergeAgentDashboardRows(
});
}
+// Per-date run-time rows → one row per date with `totalSeconds` for the
+// DailyTimeChart. Sorted ascending so the x-axis reads oldest-to-newest,
+// matching the cost / tokens aggregators.
+export function aggregateDailyTime(rows: DashboardRunTimeDaily[]): DailyTimeData[] {
+ return [...rows]
+ .sort((a, b) => a.date.localeCompare(b.date))
+ .map((r) => ({
+ date: r.date,
+ label: formatDateLabel(r.date),
+ totalSeconds: r.total_seconds,
+ }));
+}
+
+// Per-date run-time rows → one row per date with `completed` and `failed`
+// counts for the DailyTasksChart's stacked bar (failed_count is a subset
+// of task_count, so completed = task_count - failed_count).
+export function aggregateDailyTasks(rows: DashboardRunTimeDaily[]): DailyTasksData[] {
+ return [...rows]
+ .sort((a, b) => a.date.localeCompare(b.date))
+ .map((r) => {
+ const failed = r.failed_count;
+ const completed = Math.max(0, r.task_count - failed);
+ return {
+ date: r.date,
+ label: formatDateLabel(r.date),
+ completed,
+ failed,
+ };
+ });
+}
+
// Compact human duration: "1h 23m" / "12m 30s" / "45s" / "<1m". Used for
// the dashboard run-time KPI and the per-agent run-time column. Keeps two
// segments max — three segments adds visual noise without precision the
diff --git a/packages/views/locales/en/usage.json b/packages/views/locales/en/usage.json
index de0b6e780e..24c4eadc79 100644
--- a/packages/views/locales/en/usage.json
+++ b/packages/views/locales/en/usage.json
@@ -18,8 +18,12 @@
"daily": {
"title_cost": "Daily cost",
"title_tokens": "Daily tokens",
+ "title_time": "Daily run time",
+ "title_tasks": "Daily tasks",
"metric_cost": "Cost",
"metric_tokens": "Tokens",
+ "metric_time": "Time",
+ "metric_tasks": "Tasks",
"no_data": "No usage in this window."
},
"leaderboard": {
diff --git a/packages/views/locales/zh-Hans/usage.json b/packages/views/locales/zh-Hans/usage.json
index f7594c2d44..9baf06d6f3 100644
--- a/packages/views/locales/zh-Hans/usage.json
+++ b/packages/views/locales/zh-Hans/usage.json
@@ -18,8 +18,12 @@
"daily": {
"title_cost": "每日费用",
"title_tokens": "每日 Token",
+ "title_time": "每日运行时长",
+ "title_tasks": "每日任务数",
"metric_cost": "费用",
"metric_tokens": "Token",
+ "metric_time": "运行时长",
+ "metric_tasks": "任务数",
"no_data": "所选时间范围内暂无消耗。"
},
"leaderboard": {
diff --git a/packages/views/runtimes/components/charts/daily-tasks-chart.tsx b/packages/views/runtimes/components/charts/daily-tasks-chart.tsx
new file mode 100644
index 0000000000..2a998f7651
--- /dev/null
+++ b/packages/views/runtimes/components/charts/daily-tasks-chart.tsx
@@ -0,0 +1,89 @@
+import {
+ BarChart,
+ Bar,
+ XAxis,
+ YAxis,
+ CartesianGrid,
+} from "recharts";
+import {
+ ChartContainer,
+ ChartTooltip,
+ ChartTooltipContent,
+ type ChartConfig,
+} from "@multica/ui/components/ui/chart";
+import { useT } from "../../../i18n";
+
+// Two-segment stack — completed runs at the bottom (chart-1, primary
+// brand), failed runs on top (chart-5 for distinct emphasis). Lets the
+// user see day-over-day failure-rate trend without a separate chart.
+const tasksChartConfig = {
+ completed: { label: "Completed", color: "var(--chart-1)" },
+ failed: { label: "Failed", color: "var(--chart-5)" },
+} satisfies ChartConfig;
+
+export interface DailyTasksData {
+ date: string;
+ label: string;
+ completed: number;
+ failed: number;
+}
+
+export function DailyTasksChart({ data }: { data: DailyTasksData[] }) {
+ const { t } = useT("runtimes");
+ return (
+ <ChartContainer config={tasksChartConfig} className="aspect-[3/1] w-full">
+ <BarChart data={data} margin={{ left: 0, right: 0, top: 4, bottom: 0 }}>
+ <CartesianGrid vertical={false} />
+ <XAxis
+ dataKey="label"
+ tickLine={false}
+ axisLine={false}
+ tickMargin={8}
+ interval="preserveStartEnd"
+ />
+ <YAxis
+ tickLine={false}
+ axisLine={false}
+ tickMargin={8}
+ allowDecimals={false}
+ width={40}
+ />
+ <ChartTooltip
+ content={
+ <ChartTooltipContent
+ formatter={(value, name) => `${value} ${name}`}
+ footer={(payload) => {
+ const total = payload.reduce(
+ (sum, item) =>
+ sum +
+ (typeof item.value === "number" ? item.value : 0),
+ 0,
+ );
+ return (
+ <div className="flex items-center justify-between gap-2 font-medium">
+ <span>{t(($) => $.charts.tooltip_total)}</span>
+ <span className="font-mono tabular-nums">
+ {total.toLocaleString()}
+ </span>
+ </div>
+ );
+ }}
+ />
+ }
+ />
+ <Bar
+ dataKey="completed"
+ stackId="tasks"
+ fill="var(--color-completed)"
+ radius={[0, 0, 0, 0]}
+ />
+ <Bar
+ dataKey="failed"
+ stackId="tasks"
+ fill="var(--color-failed)"
+ radius={[3, 3, 0, 0]}
+ />
+ </BarChart>
+ </ChartContainer>
+ );
+}
diff --git a/packages/views/runtimes/components/charts/daily-time-chart.tsx b/packages/views/runtimes/components/charts/daily-time-chart.tsx
new file mode 100644
index 0000000000..10efdd83fe
--- /dev/null
+++ b/packages/views/runtimes/components/charts/daily-time-chart.tsx
@@ -0,0 +1,76 @@
+import {
+ BarChart,
+ Bar,
+ XAxis,
+ YAxis,
+ CartesianGrid,
+} from "recharts";
+import {
+ ChartContainer,
+ ChartTooltip,
+ ChartTooltipContent,
+ type ChartConfig,
+} from "@multica/ui/components/ui/chart";
+
+// Single-series bar — total daily run time in seconds. The y-axis tick
+// formatter and tooltip both use the same `formatDuration` so the user
+// reads the same unit ladder (h / m / s) everywhere.
+const timeChartConfig = {
+ totalSeconds: { label: "Run time", color: "var(--chart-1)" },
+} satisfies ChartConfig;
+
+export interface DailyTimeData {
+ date: string;
+ label: string;
+ totalSeconds: number;
+}
+
+export function DailyTimeChart({
+ data,
+ formatY,
+ formatTooltip,
+}: {
+ data: DailyTimeData[];
+ // Caller passes a `formatDuration`-style fn so the chart stays UI-string
+ // agnostic (the "< 1m" fallback label is localized by the parent).
+ formatY: (seconds: number) => string;
+ formatTooltip: (seconds: number) => string;
+}) {
+ return (
+ <ChartContainer config={timeChartConfig} className="aspect-[3/1] w-full">
+ <BarChart data={data} margin={{ left: 0, right: 0, top: 4, bottom: 0 }}>
+ <CartesianGrid vertical={false} />
+ <XAxis
+ dataKey="label"
+ tickLine={false}
+ axisLine={false}
+ tickMargin={8}
+ interval="preserveStartEnd"
+ />
+ <YAxis
+ tickLine={false}
+ axisLine={false}
+ tickMargin={8}
+ tickFormatter={(v: number) => formatY(v)}
+ width={56}
+ />
+ <ChartTooltip
+ content={
+ <ChartTooltipContent
+ formatter={(value, name) =>
+ typeof value === "number"
+ ? `${formatTooltip(value)} ${name}`
+ : `${value} ${name}`
+ }
+ />
+ }
+ />
+ <Bar
+ dataKey="totalSeconds"
+ fill="var(--color-totalSeconds)"
+ radius={[3, 3, 0, 0]}
+ />
+ </BarChart>
+ </ChartContainer>
+ );
+}
diff --git a/packages/views/runtimes/components/charts/index.ts b/packages/views/runtimes/components/charts/index.ts
index 509ac3d846..3fae5d7298 100644
--- a/packages/views/runtimes/components/charts/index.ts
+++ b/packages/views/runtimes/components/charts/index.ts
@@ -1,4 +1,6 @@
export { DailyCostChart, costStackConfig } from "./daily-cost-chart";
export { DailyTokensChart, tokenStackConfig } from "./daily-tokens-chart";
+export { DailyTimeChart, type DailyTimeData } from "./daily-time-chart";
+export { DailyTasksChart, type DailyTasksData } from "./daily-tasks-chart";
export { ActivityHeatmap } from "./activity-heatmap";
export { HourlyActivityChart } from "./hourly-activity-chart";
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index f1e5e7cb68..d1df209e3e 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -509,6 +509,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/usage/daily", h.GetDashboardUsageDaily)
r.Get("/usage/by-agent", h.GetDashboardUsageByAgent)
r.Get("/agent-runtime", h.GetDashboardAgentRunTime)
+ r.Get("/runtime/daily", h.GetDashboardRunTimeDaily)
})
// Runtimes
diff --git a/server/internal/handler/dashboard.go b/server/internal/handler/dashboard.go
index 865ba00ae8..738a788f86 100644
--- a/server/internal/handler/dashboard.go
+++ b/server/internal/handler/dashboard.go
@@ -17,6 +17,7 @@ import (
// GET /api/dashboard/usage/daily per-(date, model) token rows
// GET /api/dashboard/usage/by-agent per-(agent, model) token rows
// GET /api/dashboard/agent-runtime per-agent run-time + task counts
+// GET /api/dashboard/runtime/daily per-date run-time + task counts
//
// All three accept ?days=N (defaults to 30, capped at 365) and an optional
// ?project_id=<uuid> to scope the rollup to a single project. With no
@@ -272,3 +273,51 @@ func (h *Handler) GetDashboardAgentRunTime(w http.ResponseWriter, r *http.Reques
}
writeJSON(w, http.StatusOK, resp)
}
+
+// DashboardRunTimeDailyResponse is one (date) bucket of terminal-task run
+// time and counts. Powers the workspace dashboard's daily Time and Tasks
+// charts — same toggle as Tokens / Cost, different metric.
+type DashboardRunTimeDailyResponse struct {
+ Date string `json:"date"`
+ TotalSeconds int64 `json:"total_seconds"`
+ TaskCount int32 `json:"task_count"`
+ FailedCount int32 `json:"failed_count"`
+}
+
+// GetDashboardRunTimeDaily returns per-date total task run time and task
+// counts for the workspace, optionally scoped to a project. Only terminal
+// tasks (completed or failed) with both started_at and completed_at
+// populated contribute. Bucketed by completed_at so the day boundaries
+// line up with the per-agent run-time card.
+func (h *Handler) GetDashboardRunTimeDaily(w http.ResponseWriter, r *http.Request) {
+ workspaceID := h.resolveWorkspaceID(r)
+ if _, ok := h.workspaceMember(w, r, workspaceID); !ok {
+ return
+ }
+ projectID, ok := parseProjectIDParam(w, r)
+ if !ok {
+ return
+ }
+ since := parseSinceParam(r, 30)
+
+ rows, err := h.Queries.ListDashboardRunTimeDaily(r.Context(), db.ListDashboardRunTimeDailyParams{
+ WorkspaceID: parseUUID(workspaceID),
+ Since: since,
+ ProjectID: projectID,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list daily runtime")
+ return
+ }
+
+ resp := make([]DashboardRunTimeDailyResponse, len(rows))
+ for i, row := range rows {
+ resp[i] = DashboardRunTimeDailyResponse{
+ Date: row.Date.Time.Format("2006-01-02"),
+ TotalSeconds: row.TotalSeconds,
+ TaskCount: row.TaskCount,
+ FailedCount: row.FailedCount,
+ }
+ }
+ writeJSON(w, http.StatusOK, resp)
+}
diff --git a/server/pkg/db/generated/task_usage.sql.go b/server/pkg/db/generated/task_usage.sql.go
index 25c93b976b..0a5b508ff3 100644
--- a/server/pkg/db/generated/task_usage.sql.go
+++ b/server/pkg/db/generated/task_usage.sql.go
@@ -271,6 +271,73 @@ func (q *Queries) ListDashboardAgentRunTime(ctx context.Context, arg ListDashboa
return items, nil
}
+const listDashboardRunTimeDaily = `-- name: ListDashboardRunTimeDaily :many
+SELECT
+ DATE(atq.completed_at) AS date,
+ COALESCE(
+ SUM(EXTRACT(EPOCH FROM (atq.completed_at - atq.started_at)))::bigint,
+ 0
+ )::bigint AS total_seconds,
+ COUNT(*)::int AS task_count,
+ COUNT(*) FILTER (WHERE atq.status = 'failed')::int AS failed_count
+FROM agent_task_queue atq
+JOIN agent a ON a.id = atq.agent_id
+LEFT JOIN issue i ON i.id = atq.issue_id
+WHERE a.workspace_id = $1
+ AND atq.status IN ('completed', 'failed')
+ AND atq.started_at IS NOT NULL
+ AND atq.completed_at IS NOT NULL
+ AND atq.completed_at >= DATE_TRUNC('day', $2::timestamptz)
+ AND ($3::uuid IS NULL OR i.project_id = $3)
+GROUP BY DATE(atq.completed_at)
+ORDER BY DATE(atq.completed_at) DESC
+`
+
+type ListDashboardRunTimeDailyParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Since pgtype.Timestamptz `json:"since"`
+ ProjectID pgtype.UUID `json:"project_id"`
+}
+
+type ListDashboardRunTimeDailyRow struct {
+ Date pgtype.Date `json:"date"`
+ TotalSeconds int64 `json:"total_seconds"`
+ TaskCount int32 `json:"task_count"`
+ FailedCount int32 `json:"failed_count"`
+}
+
+// Daily per-date run time + task counts for the workspace, optionally
+// scoped to a single project. Powers the workspace dashboard's "Time"
+// and "Tasks" metrics on the same toggle as Tokens / Cost. Bucketed by
+// completed_at (terminal time) — same anchor as ListDashboardAgentRunTime
+// so the day boundaries line up with the per-agent run-time card. Only
+// terminal tasks (completed or failed) with both started_at and
+// completed_at populated contribute.
+func (q *Queries) ListDashboardRunTimeDaily(ctx context.Context, arg ListDashboardRunTimeDailyParams) ([]ListDashboardRunTimeDailyRow, error) {
+ rows, err := q.db.Query(ctx, listDashboardRunTimeDaily, arg.WorkspaceID, arg.Since, arg.ProjectID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListDashboardRunTimeDailyRow{}
+ for rows.Next() {
+ var i ListDashboardRunTimeDailyRow
+ if err := rows.Scan(
+ &i.Date,
+ &i.TotalSeconds,
+ &i.TaskCount,
+ &i.FailedCount,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listDashboardUsageByAgent = `-- name: ListDashboardUsageByAgent :many
SELECT
atq.agent_id,
diff --git a/server/pkg/db/queries/task_usage.sql b/server/pkg/db/queries/task_usage.sql
index c20896da1a..c63207ad8d 100644
--- a/server/pkg/db/queries/task_usage.sql
+++ b/server/pkg/db/queries/task_usage.sql
@@ -159,6 +159,34 @@ WHERE workspace_id = $1
GROUP BY agent_id, model
ORDER BY agent_id, model;
+-- name: ListDashboardRunTimeDaily :many
+-- Daily per-date run time + task counts for the workspace, optionally
+-- scoped to a single project. Powers the workspace dashboard's "Time"
+-- and "Tasks" metrics on the same toggle as Tokens / Cost. Bucketed by
+-- completed_at (terminal time) — same anchor as ListDashboardAgentRunTime
+-- so the day boundaries line up with the per-agent run-time card. Only
+-- terminal tasks (completed or failed) with both started_at and
+-- completed_at populated contribute.
+SELECT
+ DATE(atq.completed_at) AS date,
+ COALESCE(
+ SUM(EXTRACT(EPOCH FROM (atq.completed_at - atq.started_at)))::bigint,
+ 0
+ )::bigint AS total_seconds,
+ COUNT(*)::int AS task_count,
+ COUNT(*) FILTER (WHERE atq.status = 'failed')::int AS failed_count
+FROM agent_task_queue atq
+JOIN agent a ON a.id = atq.agent_id
+LEFT JOIN issue i ON i.id = atq.issue_id
+WHERE a.workspace_id = $1
+ AND atq.status IN ('completed', 'failed')
+ AND atq.started_at IS NOT NULL
+ AND atq.completed_at IS NOT NULL
+ AND atq.completed_at >= DATE_TRUNC('day', @since::timestamptz)
+ AND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))
+GROUP BY DATE(atq.completed_at)
+ORDER BY DATE(atq.completed_at) DESC;
+
-- name: ListDashboardAgentRunTime :many
-- Per-agent total task run time and task count for the workspace, optionally
-- scoped to a single project. Counts only terminal runs (completed or failed)