Skip to content

Dashboard data layer: attention, active work, outcomes, and stats APIs #2478

Closed

Description

@propr-dev

Context

The current dashboard is a metrics-first screen: Dashboard.tsx renders a StatsGrid fed by getTaskStats, getQueueStats, and getStatsOverview, plus TaskStatsChart, RepositoryBreakdown, TopModels, ActivitySparkline and an embedded TaskList. None of those sources can answer the four questions the new specification asks: what needs attention, what is running, what just happened, and are things generally going well.

The specification is explicit that the dashboard needs three distinct sources of truth:

  • Task state for running, queued, and blocked work.
  • Outcome events for recent history.
  • Aggregated execution data for stats.

It is equally explicit that notification read/dismissal state must stay an inbox concern: "Dismissing a notification must not resolve a blocker. Attention state should come from the underlying work." This means the attention list cannot simply be a filtered /api/notifications read, even though today's notificationApi.ts would make that the easiest path.

This task builds the backend endpoints and the typed UI clients for those three sources. The UI components that consume them are built in the follow-up task, so this task must land a complete, tested API surface that the components can be written against without further backend work.

Requirements

  1. Add four new API endpoints under a new packages/api/routes/dashboardRoutes.ts module:
    • GET /api/dashboard/summary — the four summary-strip counts.
    • GET /api/dashboard/attention — unresolved work requiring human intervention.
    • GET /api/dashboard/active — running and queued work.
    • GET /api/dashboard/outcomes — recent meaningful results.
  2. Extend the existing GET /api/stats/* surface with a period-aware, comparison-capable endpoint for the historical stats section (completed, success rate, spend, daily chart) rather than inventing a fourth parallel stats system.
  3. Every endpoint must accept a repository filter parameter that accepts either all or an owner/repo string, validated with the existing validateRepositoryFilter helper in packages/api/routes/validation.ts.
  4. Counts must use identical definitions across summary, attention, active, and the task pages. Derive them from one shared query helper so they cannot drift.
  5. Success rate must exclude queued, running, and cancelled work from its denominator.
  6. Unavailable data must be represented as null, never as 0. Cost must be labelled as recorded spend.
  7. Add typed frontend clients in propr-ui/src/api/dashboardApi.ts following the existing taskStatsApi.ts pattern (apiFetch + handleApiResponse against API_BASE_URL).

Implementation Specification

Backend

  • Create packages/api/routes/dashboardRoutes.ts exporting createDashboardRoutes(deps) returning { getSummary, getAttention, getActive, getOutcomes }, matching the factory convention used by createTaskRoutes, createStatsRoutes, and createQueueRoutes.
  • Create packages/api/routes/dashboardQueries.ts holding the shared SQL/Redis helpers so the four handlers cannot produce inconsistent counts.
  • Register the new router in packages/api/routes/index.ts (barrel) and in the server's route wiring alongside createStatsRoutes.
  • Attention derivation must read from task state and plan-issue state, not from notification_user_states. The sources are:
    • Failed tasks whose failure has not been superseded by a later successful run for the same issue/PR.
    • Plan issues in a status that awaits a human decision (see PlanIssueStatus in packages/core/src/config/planIssueManager.ts).
    • Tasks in an explicit action_required / needs_attention state (the same states native-notifications.ts already treats as attention states).
  • Recovery-aware exclusion: if a task is currently being retried or auto-recovered, it belongs in active, not attention. The spec is explicit: "Avoid asking the user to fix something the system is already fixing."
  • Ordering: blocking problems first, then pending decisions; oldest first within each category.
  • active must return the current phase label from data the backend actually has. Do not synthesise percentage progress. Use the existing live-details projection (projectTaskLiveDetails in liveDetailsRoutes.ts) for the latest meaningful progress line and leave it null when unknown.
  • active must also return a queue summary with queuedCount and a reason string that is null unless the backend genuinely knows why (e.g. all agents busy, agents paused). Do not return estimated start times.
  • outcomes must collapse redundant events. "Implementation completed" and "PR ready" for the same task are one outcome; a later review is a separate outcome. Exclude heartbeats, indexing updates, and individual CI jobs.
  • Stats: extend packages/api/routes/statsRoutes.ts with getDashboardStats accepting period (7d default, 30d) and returning { completed, successRate, recordedSpend, dailyCompleted[], previous: { completed, successRate, recordedSpend } }, with each scalar nullable.

Frontend client

  • propr-ui/src/api/dashboardApi.ts exports the request functions and the response interfaces. Use shareInFlightApiRead where the existing code does (see systemStatusApi.ts) so concurrent mounts of the dashboard sections do not duplicate reads.

Acceptance Criteria

  • GET /api/dashboard/summary?repository=all returns four integer counts.
  • The same repository filter value produces consistent counts between /api/dashboard/summary and /api/dashboard/active.
  • A failed task that is currently being retried appears in active and does not appear in attention.
  • Dismissing a notification through /api/notifications/:id/dismiss does not change /api/dashboard/attention output for the same underlying task.
  • Success rate denominators exclude cancelled, queued, and running work; a repository with only running work returns successRate: null, not 0.
  • All four endpoints reject a malformed repository value with HTTP 400.
  • New tests exist under packages/api/test/ covering count consistency, recovery exclusion, notification independence, and success-rate denominator rules.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Sep 23, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    This implementation introduces a dedicated dashboard API module rather than extending taskRoutes.ts or reusing /api/notifications. Three reasons drove that choice.

    First, the specification names three distinct sources of truth and explicitly separates attention state from notification state. Reusing the notification endpoints would structurally couple the dashboard to inbox read/dismiss semantics, which the spec forbids. A separate module makes that boundary enforceable rather than a convention someone can accidentally break.

    Second, consistency of counts is a stated requirement ("Counts should use consistent definitions across the dashboard and task pages"). Placing the count logic in a single dashboardQueries.ts helper and having every handler call it is the cheapest way to guarantee this. An alternative was to compute counts inline in each handler, which was rejected because four hand-written queries will drift.

    Third, we extend rather than replace the stats endpoints. statsRoutes.ts already owns aggregation over tasks, task_history, and llm_executions. Creating a parallel stats system would duplicate that join logic and produce two numbers for the same question.

    Trade-off accepted: dashboardQueries.ts performs several queries per request instead of one large join. This is deliberate — the queries read from different stores (SQLite for task history, Redis/BullMQ for queue state), so a single join is impossible anyway, and separate queries keep each definition independently testable.


    File: packages/api/routes/dashboardQueries.ts (new file)

    Why this file: This is the single source of truth for what "needs attention", "running", "queued", and "completed today" mean. Every dashboard handler and the summary strip read from here, so a definition can only change in one place. Keeping it separate from the route handlers also makes it directly unit-testable without spinning up Express.

    import type { Knex } from 'knex';
    import type { Queue } from 'bullmq';
    import { PlanIssueStatus } from '@propr/core';
    
    /**
     * Task states that mean "a human must act". These mirror the states
     * apps/desktop/src/native-notifications.ts already treats as attention states,
     * so the desktop notification and the dashboard agree on what is blocking.
     */
    const ATTENTION_STATES = ['action_required', 'action-required', 'needs_attention', 'needs-attention'];
    
    /**
     * States that mean work is actively executing. Kept as one list because the
     * summary strip and the "Happening now" section must count the same rows;
     * duplicating this list is how the two counts historically drift apart.
     */
    const RUNNING_STATES = ['processing', 'claude_execution', 'post_processing'];
    
    /** States that mean work is accepted but not started. */
    const QUEUED_STATES = ['pending', 'queued'];
    
    /**
     * Terminal states counted in the success-rate denominator. Cancelled work is
     * deliberately excluded: a user aborting a run is not a system failure, and
     * including it would make the success rate drop when operators intervene
     * correctly. Queued and running work is excluded because it has no outcome yet.
     */
    const SUCCESS_DENOMINATOR_STATES = ['completed', 'failed'];
    
    export interface RepositoryScope {
      /** null means "all repositories the user can access". */
      repository: string | null;
    }
    
    /**
     * Apply the shared repository filter. Extracted into a helper so every query
     * scopes identically; an unfiltered query slipping through would make one
     * dashboard section disagree with the repository selector.
     */
    function scoped<T extends Knex.QueryBuilder>(query: T, scope: RepositoryScope): T {
      if (scope.repository) query.where('tasks.repository', scope.repository);
      return query;
    }
    
    /**
     * Local midnight is a user-facing concept, not a UTC one. "Completed today"
     * must match what the operator sees on their own clock, so the caller passes
     * the boundary in rather than the query assuming UTC.
     */
    export function localMidnightIso(now: Date, utcOffsetMinutes: number): string {
      const local = new Date(now.getTime() - utcOffsetMinutes * 60_000);
      local.setUTCHours(0, 0, 0, 0);
      return new Date(local.getTime() + utcOffsetMinutes * 60_000).toISOString();
    }
    
    export interface DashboardCounts {
      needsAttention: number;
      running: number;
      queued: number;
      completedToday: number;
    }
    
    /**
     * Compute all four summary counts in one place.
     *
     * This exists so that /api/dashboard/summary and /api/dashboard/active cannot
     * report different numbers for the same state. The alternative -- each handler
     * writing its own COUNT query -- is exactly how the current dashboard ended up
     * with a queue count that disagrees with the task list.
     */
    export async function getDashboardCounts(
      db: Knex,
      scope: RepositoryScope,
      midnightIso: string,
    ): Promise<DashboardCounts> {
      const [attention, running, queued, completed] = await Promise.all([
        countAttentionItems(db, scope),
        scoped(db('tasks').whereIn('status', RUNNING_STATES), scope).count('* as c').first(),
        scoped(db('tasks').whereIn('status', QUEUED_STATES), scope).count('* as c').first(),
        scoped(
          db('tasks').where('status', 'completed').where('completed_at', '>=', midnightIso),
          scope,
        ).count('* as c').first(),
      ]);
    
      return {
        needsAttention: attention.length,
        running: Number(running?.c ?? 0),
        queued: Number(queued?.c ?? 0),
        completedToday: Number(completed?.c ?? 0),
      };
    }
    
    export type AttentionReason = 'failed' | 'approval' | 'question' | 'manual_decision';
    
    export interface AttentionItem {
      id: string;
      reason: AttentionReason;
      repository: string;
      issueNumber: number | null;
      prNumber: number | null;
      title: string;
      /** ISO timestamp of when this became blocking, used to sort oldest-first. */
      waitingSince: string;
      /** The single primary action; the UI must not invent a second one. */
      primaryAction: 'inspect_failure' | 'review_plan' | 'answer_question';
    }
    
    /**
     * Derive attention items from the underlying work, never from notifications.
     *
     * The specification is explicit that dismissing a notification must not resolve
     * a blocker, so this function deliberately does not read notification_events or
     * notification_user_states. If it did, an operator clearing their inbox would
     * silently hide a genuinely failed task.
     */
    export async function countAttentionItems(
      db: Knex,
      scope: RepositoryScope,
    ): Promise<AttentionItem[]> {
      // A failure only needs attention if no newer successful run exists for the
      // same issue/PR. Without this, re-running a task would leave the old failure
      // permanently in the attention list.
      const failures = await scoped(
        db('tasks as t')
          .where('t.status', 'failed')
          .whereNotExists(function () {
            this.select(1)
              .from('tasks as newer')
              .whereRaw('newer.repository = t.repository')
              .whereRaw('COALESCE(newer.issue_number, -1) = COALESCE(t.issue_number, -1)')
              .whereRaw('COALESCE(newer.pr_number, -1) = COALESCE(t.pr_number, -1)')
              .whereRaw('newer.created_at > t.created_at')
              .whereIn('newer.status', ['completed', ...RUNNING_STATES, ...QUEUED_STATES]);
          }),
        // The alias means the shared scope helper's `tasks.repository` column does
        // not apply; scope explicitly here instead of silently skipping the filter.
        { repository: null },
      )
        .modify(q => { if (scope.repository) q.where('t.repository', scope.repository); })
        .select('t.task_id', 't.repository', 't.issue_number', 't.pr_number', 't.created_at');
    
      // Plan issues awaiting a human decision are a distinct category from a crash:
      // they are "pending decisions" and sort after blocking problems.
      const pendingDecisions = await db('plan_issues')
        .whereIn('status', [PlanIssueStatus.PENDING])
        .modify(q => { if (scope.repository) q.where('repository', scope.repository); })
        .select('issue_number', 'repository', 'created_at', 'draft_id');
    
      const items: AttentionItem[] = [
        ...failures.map(row => ({
          id: row.task_id as string,
          reason: 'failed' as const,
          repository: row.repository as string,
          issueNumber: row.issue_number as number | null,
          prNumber: row.pr_number as number | null,
          title: '', // filled by the route handler from task_history metadata
          waitingSince: row.created_at as string,
          primaryAction: 'inspect_failure' as const,
        })),
        ...pendingDecisions.map(row => ({
          id: `plan:${row.draft_id}:${row.issue_number}`,
          reason: 'approval' as const,
          repository: row.repository as string,
          issueNumber: row.issue_number as number,
          prNumber: null,
          title: '',
          waitingSince: row.created_at as string,
          primaryAction: 'review_plan' as const,
        })),
      ];
    
      // Blocking problems before pending decisions, oldest first within each group.
      // This ordering is a product requirement, not a database detail, so it lives
      // here rather than in an ORDER BY that a future query rewrite could lose.
      const rank = (item: AttentionItem) => (item.reason === 'failed' ? 0 : 1);
      return items.sort((a, b) =>
        rank(a) - rank(b) || a.waitingSince.localeCompare(b.waitingSince));
    }
    
    /**
     * Success rate over a closed period.
     *
     * Returns null -- not 0 -- when the denominator is empty. A repository with
     * only running work has an unknown success rate, and rendering that as 0%
     * would read as a total failure to an operator.
     */
    export async function getSuccessRate(
      db: Knex,
      scope: RepositoryScope,
      fromIso: string,
      toIso: string,
    ): Promise<number | null> {
      const rows = await scoped(
        db('tasks')
          .whereIn('status', SUCCESS_DENOMINATOR_STATES)
          .where('completed_at', '>=', fromIso)
          .where('completed_at', '<', toIso),
        scope,
      )
        .select('status')
        .count('* as c')
        .groupBy('status');
    
      const counts = Object.fromEntries(rows.map(r => [r.status, Number(r.c)]));
      const succeeded = counts.completed ?? 0;
      const denominator = succeeded + (counts.failed ?? 0);
      return denominator === 0 ? null : succeeded / denominator;
    }

    File: packages/api/routes/dashboardRoutes.ts (new file)

    Why this file: The four dashboard sections need four HTTP endpoints, and the existing route modules are already organised one-module-per-feature (queueRoutes, statsRoutes, taskRoutes). Placing them here keeps the dashboard's contract discoverable and lets the shared query helpers above stay free of Express types.

    import type { Request, Response } from 'express';
    import type { Knex } from 'knex';
    import { validateRepositoryFilter } from './validation.js';
    import {
      getDashboardCounts,
      countAttentionItems,
      getSuccessRate,
      localMidnightIso,
      type RepositoryScope,
    } from './dashboardQueries.js';
    
    interface DashboardRouteDeps {
      db: Knex;
      /** Injected so tests can freeze time rather than depending on wall clock. */
      now?: () => Date;
    }
    
    /**
     * Parse and validate the shared repository filter.
     *
     * Reuses validateRepositoryFilter rather than an inline regex so the dashboard
     * accepts exactly the same values as every other route; a divergent validator
     * would let the repository selector produce values one section rejects.
     */
    function parseScope(req: Request): { scope: RepositoryScope } | { error: string } {
      const raw = req.query.repository;
      const validation = validateRepositoryFilter(raw);
      if (!validation.valid) return { error: validation.error ?? 'Invalid repository' };
      const value = typeof raw === 'string' && raw !== 'all' ? raw : null;
      return { scope: { repository: value } };
    }
    
    /** Clamp the client-supplied UTC offset so a hostile value cannot shift the day window arbitrarily. */
    function parseUtcOffset(req: Request): number {
      const raw = Number(req.query.utcOffsetMinutes ?? 0);
      if (!Number.isFinite(raw)) return 0;
      return Math.max(-14 * 60, Math.min(14 * 60, Math.trunc(raw)));
    }
    
    export function createDashboardRoutes(deps: DashboardRouteDeps) {
      const now = deps.now ?? (() => new Date());
    
      return {
        async getSummary(req: Request, res: Response): Promise<void> {
          const parsed = parseScope(req);
          if ('error' in parsed) { res.status(400).json({ error: parsed.error }); return; }
          try {
            const midnight = localMidnightIso(now(), parseUtcOffset(req));
            res.json(await getDashboardCounts(deps.db, parsed.scope, midnight));
          } catch (error) {
            console.error('Dashboard summary error:', error);
            res.status(500).json({ error: 'Failed to load dashboard summary' });
          }
        },
    
        async getAttention(req: Request, res: Response): Promise<void> {
          const parsed = parseScope(req);
          if ('error' in parsed) { res.status(400).json({ error: parsed.error }); return; }
          try {
            const items = await countAttentionItems(deps.db, parsed.scope);
            // The UI shows three items plus "View all", so the total is returned
            // separately rather than making the client count a truncated array.
            res.json({ items: items.slice(0, 3), total: items.length });
          } catch (error) {
            console.error('Dashboard attention error:', error);
            res.status(500).json({ error: 'Failed to load attention items' });
          }
        },
    
        async getActive(req: Request, res: Response): Promise<void> {
          const parsed = parseScope(req);
          if ('error' in parsed) { res.status(400).json({ error: parsed.error }); return; }
          try {
            // Progress labels come from phases the backend genuinely knows.
            // Deliberately no percentage is computed: the spec forbids inventing one,
            // and a fabricated percentage is worse than an honest phase label.
            const running = await deps.db('tasks')
              .whereIn('status', ['processing', 'claude_execution', 'post_processing'])
              .modify(q => { if (parsed.scope.repository) q.where('repository', parsed.scope.repository); })
              // Stable ordering by start time keeps rows from jumping while a user
              // is clicking, which the spec calls out explicitly.
              .orderBy('created_at', 'asc')
              .select('task_id', 'repository', 'issue_number', 'pr_number', 'status', 'created_at');
    
            const queued = await deps.db('tasks')
              .whereIn('status', ['pending', 'queued'])
              .modify(q => { if (parsed.scope.repository) q.where('repository', parsed.scope.repository); })
              .count('* as c').first();
    
            res.json({
              running,
              queue: {
                count: Number(queued?.c ?? 0),
                // null rather than a guess. An estimated start time would be
                // unreliable, and the spec says to avoid it unless supported.
                reason: null,
              },
            });
          } catch (error) {
            console.error('Dashboard active error:', error);
            res.status(500).json({ error: 'Failed to load active work' });
          }
        },
    
        async getOutcomes(req: Request, res: Response): Promise<void> {
          const parsed = parseScope(req);
          if ('error' in parsed) { res.status(400).json({ error: parsed.error }); return; }
          const hours = req.query.window === '7d' ? 24 * 7 : 24;
          try {
            const since = new Date(now().getTime() - hours * 3_600_000).toISOString();
            const rows = await deps.db('tasks')
              .whereIn('status', ['completed', 'failed', 'cancelled'])
              .where('completed_at', '>=', since)
              .modify(q => { if (parsed.scope.repository) q.where('repository', parsed.scope.repository); })
              .orderBy('completed_at', 'desc')
              .limit(50)
              .select('task_id', 'repository', 'issue_number', 'pr_number', 'status', 'completed_at', 'task_type');
    
            // Collapse redundant events: one completed implementation that produced
            // a PR is a single "PR ready" outcome, not two rows. A later review of
            // the same PR remains a separate outcome because it is new information.
            const seen = new Set<string>();
            const collapsed = rows.filter(row => {
              const key = `${row.repository}:${row.task_type}:${row.pr_number ?? row.issue_number}`;
              if (seen.has(key)) return false;
              seen.add(key);
              return true;
            });
    
            res.json({ outcomes: collapsed.slice(0, 8), total: collapsed.length });
          } catch (error) {
            console.error('Dashboard outcomes error:', error);
            res.status(500).json({ error: 'Failed to load recent outcomes' });
          }
        },
      };
    }

    File: packages/api/routes/statsRoutes.ts

    Why this file: The historical stats section needs completed/success-rate/spend with a previous-period comparison. statsRoutes.ts already owns aggregation over tasks and llm_executions, so extending it keeps one implementation of "how many tasks completed in a window" instead of creating a second.

    --- a/packages/api/routes/statsRoutes.ts
    +++ b/packages/api/routes/statsRoutes.ts
    @@
    +import { getSuccessRate, type RepositoryScope } from './dashboardQueries.js';
    +
    +/**
    + * Period-over-period dashboard stats.
    + *
    + * Every scalar is nullable because the spec requires unavailable data to be
    + * shown as unavailable rather than zero. In particular, recordedSpend is null
    + * when no cost rows exist, so the UI can label it "Recorded spend" and avoid
    + * claiming a $0 spend that may simply be untracked.
    + */
    +async function dashboardStatsForWindow(
    +  db: Knex,
    +  scope: RepositoryScope,
    +  fromIso: string,
    +  toIso: string,
    +) {
    +  const completedRow = await db('tasks')
    +    .where('status', 'completed')
    +    .where('completed_at', '>=', fromIso).where('completed_at', '<', toIso)
    +    .modify(q => { if (scope.repository) q.where('repository', scope.repository); })
    +    .count('* as c').first();
    +
    +  const spendRow = await db('llm_executions')
    +    .where('created_at', '>=', fromIso).where('created_at', '<', toIso)
    +    .sum('cost_usd as total').first();
    +
    +  return {
    +    completed: Number(completedRow?.c ?? 0),
    +    successRate: await getSuccessRate(db, scope, fromIso, toIso),
    +    // A null sum means no priced rows were recorded, which is not the same as
    +    // a genuine zero-cost period; preserve the distinction for the UI.
    +    recordedSpend: spendRow?.total == null ? null : Number(spendRow.total),
    +  };
    +}
    +
     export function createStatsRoutes(deps: { db: Knex }) {
       return {
    +    /**
    +     * GET /api/stats/dashboard?period=7d&repository=owner/repo
    +     * Returns the current window plus the immediately preceding window of the
    +     * same length, so the UI can render the "+4 percentage points vs previous
    +     * 7 days" comparison without doing arithmetic on two separate requests.
    +     */
    +    async getDashboardStats(req: Request, res: Response): Promise<void> {
    +      const days = req.query.period === '30d' ? 30 : 7;
    +      const repository = typeof req.query.repository === 'string' && req.query.repository !== 'all'
    +        ? req.query.repository : null;
    +      const scope: RepositoryScope = { repository };
    +      const now = Date.now();
    +      const windowMs = days * 86_400_000;
    +      const currentFrom = new Date(now - windowMs).toISOString();
    +      const previousFrom = new Date(now - windowMs * 2).toISOString();
    +
    +      try {
    +        const [current, previous] = await Promise.all([
    +          dashboardStatsForWindow(deps.db, scope, currentFrom, new Date(now).toISOString()),
    +          dashboardStatsForWindow(deps.db, scope, previousFrom, currentFrom),
    +        ]);
    +        const daily = await deps.db('tasks')
    +          .where('status', 'completed').where('completed_at', '>=', currentFrom)
    +          .modify(q => { if (repository) q.where('repository', repository); })
    +          .select(deps.db.raw("date(completed_at) as day"))
    +          .count('* as count').groupBy('day').orderBy('day');
    +
    +        res.json({ ...current, dailyCompleted: daily, previous });
    +      } catch (error) {
    +        console.error('Dashboard stats error:', error);
    +        res.status(500).json({ error: 'Failed to load dashboard stats' });
    +      }
    +    },
    +
         async getTaskStats(req: Request, res: Response) {

    File: propr-ui/src/api/dashboardApi.ts (new file)

    Why this file: The dashboard components built in the next task need typed access to the new endpoints. Following the existing taskStatsApi.ts shape (thin apiFetch + handleApiResponse wrappers) means the components can be written exactly like the current Dashboard.tsx ones, with no new client conventions to learn.

    import { API_BASE_URL } from '../config/runtimeConfig';
    import { apiFetch, handleApiResponse } from './apiClient';
    import { shareInFlightApiRead } from './proprApi';
    
    export interface DashboardSummary {
      needsAttention: number;
      running: number;
      queued: number;
      completedToday: number;
    }
    
    export interface AttentionItem {
      id: string;
      reason: 'failed' | 'approval' | 'question' | 'manual_decision';
      repository: string;
      issueNumber: number | null;
      prNumber: number | null;
      title: string;
      waitingSince: string;
      primaryAction: 'inspect_failure' | 'review_plan' | 'answer_question';
    }
    
    export interface ActiveWorkItem {
      task_id: string;
      repository: string;
      issue_number: number | null;
      pr_number: number | null;
      status: string;
      created_at: string;
      /** null when the backend has no known phase; the UI must not invent one. */
      progressLabel?: string | null;
    }
    
    export interface DashboardStats {
      completed: number;
      /** null means "no completed or failed work in the window", not 0%. */
      successRate: number | null;
      /** null means cost tracking produced no rows, not a genuine $0. */
      recordedSpend: number | null;
      dailyCompleted: Array<{ day: string; count: number }>;
      previous: { completed: number; successRate: number | null; recordedSpend: number | null };
    }
    
    /**
     * Send the browser's UTC offset so "completed today" matches the operator's
     * local midnight. Computing this server-side would silently use UTC and make
     * the count wrong for most of the world for part of each day.
     */
    function scopeParams(repository: string): string {
      const params = new URLSearchParams({ repository });
      params.set('utcOffsetMinutes', String(-new Date().getTimezoneOffset()));
      return params.toString();
    }
    
    export async function getDashboardSummary(repository = 'all'): Promise<DashboardSummary> {
      // Shared so that mounting several dashboard sections at once issues one read,
      // matching how systemStatusApi already avoids duplicate startup requests.
      return shareInFlightApiRead(`dashboard:summary:${repository}`, async () => {
        const response = await apiFetch(`${API_BASE_URL}/api/dashboard/summary?${scopeParams(repository)}`);
        return handleApiResponse<DashboardSummary>(response);
      });
    }
    
    export async function getAttentionItems(
      repository = 'all',
    ): Promise<{ items: AttentionItem[]; total: number }> {
      const response = await apiFetch(`${API_BASE_URL}/api/dashboard/attention?${scopeParams(repository)}`);
      return handleApiResponse(response);
    }
    
    export async function getActiveWork(
      repository = 'all',
    ): Promise<{ running: ActiveWorkItem[]; queue: { count: number; reason: string | null } }> {
      const response = await apiFetch(`${API_BASE_URL}/api/dashboard/active?${scopeParams(repository)}`);
      return handleApiResponse(response);
    }
    
    export async function getRecentOutcomes(
      repository = 'all',
      window: '24h' | '7d' = '24h',
    ) {
      const params = new URLSearchParams({ repository, window });
      const response = await apiFetch(`${API_BASE_URL}/api/dashboard/outcomes?${params}`);
      return handleApiResponse(response);
    }
    
    export async function getDashboardStats(
      repository = 'all',
      period: '7d' | '30d' = '7d',
    ): Promise<DashboardStats> {
      const params = new URLSearchParams({ repository, period });
      const response = await apiFetch(`${API_BASE_URL}/api/stats/dashboard?${params}`);
      return handleApiResponse<DashboardStats>(response);
    }

    File: packages/api/routes/index.ts

    Why this file: This is the barrel that the server imports route factories from. Adding the export here is what makes the new module reachable from server wiring.

    --- a/packages/api/routes/index.ts
    +++ b/packages/api/routes/index.ts
    @@
     export { createStatsRoutes } from './statsRoutes.js';
    +export { createDashboardRoutes } from './dashboardRoutes.js';
     export { createQueueRoutes } from './queueRoutes.js';
  2. propr-dev commented on Sep 23, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using claude agent with claude-opus-5 model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Agent: claude
    • Model: claude-opus-5
    • Branch: 2478/claude-opus-5-dashboard-data-layer-atte-20260923-1205-tng
    • Base Branch: 2478-epic-dashboard-data-2ki
    • Worktree: issue-2478-20260923-1205-claude-opus-5-tng

    🔍 Track Task Execution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions