Skip to content

Rebuild the dashboard UI into five sections with a shared repository filter and live updates #2479

Closed

Description

@propr-dev

Context

propr-ui/src/components/Dashboard.tsx currently renders a metrics-first screen: a StatsGrid of four numbers, then TaskStatsChart, RepositoryBreakdown, TopModels, ActivitySparkline, and an embedded TaskList in a 70/30 split. It answers "how much work happened" but not "what needs my attention right now".

The specification replaces this with five sections, with live work getting most of the space:

  1. Summary strip — four clickable counts.
  2. Needs attention — what the user should do next.
  3. Happening now — the main operational view.
  4. Recent outcomes — a flat feed of meaningful results.
  5. Historical stats — three metrics and one compact chart.

The current top-model and repository-breakdown charts move out of the dashboard into a fuller analytics view, because "the dashboard benefits more from space for ongoing work."

This task consumes the API layer built in the previous task. It also has to get several live-update details right that the current dashboard does not handle: stable ordering while tasks run, distinguishing idle from unavailable, and showing a reconnecting state that retains the last known data.

Requirements

Summary strip

  • Four compact, clickable numbers: Needs attention, Running, Queued, Completed today.
  • Neutral colors for normal operation. Stronger emphasis on the attention count only when there is a problem or pending decision.
  • Every number opens the corresponding filtered list.

Needs attention

  • Show the three most important items, then "View all".
  • Each row: reason, repository + issue/PR reference, readable title, waiting duration, one primary action.
  • When empty, collapse to a quiet "Nothing needs your attention" (and on desktop, hide the panel entirely so it does not consume space).

Happening now

  • Compact rows with state, repository, reference, title, elapsed time, and latest meaningful progress.
  • Show five active items initially with inline expansion.
  • Keep ordering stable while tasks run — rows must not jump on every update.
  • Below active work, a compact queue summary with the reason for waiting when available.
  • Do not display invented percentage progress and do not infer a stall from missing chat messages.

Recent outcomes

  • Flat feed, last 24 hours by default with a seven-day option, eight items initially.
  • Title prominent; score only when relevant with its scale labelled; optional short third line.
  • Clicking a row opens the relevant task, review, or PR.

Historical stats

  • Three metrics (Completed, Success rate, Spend) plus a small daily completions chart.
  • Default seven days with a comparison against the preceding seven days.
  • Unavailable data renders as unavailable, not as zero. Cost labelled "Recorded spend".

Layout

  • Desktop: summary strip across the top; running work and recent outcomes in the main column; needs attention and historical stats in a narrower right column; empty attention panel hidden.
  • Mobile: summary counts in a compact 2×2, then attention, happening now, recent outcomes, historical stats.
  • Titles may wrap to two lines. Hide or relocate secondary metadata before truncating a title. A score column may align on desktop but must not reserve empty space on mobile.

Filtering and live updates

  • One repository filter applying to every section, defaulting to all accessible repositories, preserved during navigation.
  • Keep live sections current automatically; avoid reordering while someone is clicking or expanding a row.
  • On disconnect, retain last known data and show "Reconnecting · Last updated 2 minutes ago".
  • "No work running" and "Unable to load running work" must look different.

Implementation Specification

  • Create propr-ui/src/components/Dashboard/ section components: SummaryStrip.tsx, NeedsAttentionPanel.tsx, HappeningNowSection.tsx, RecentOutcomesFeed.tsx, HistoricalStatsPanel.tsx.
  • Rewrite propr-ui/src/components/Dashboard.tsx as the composition root holding only the repository filter, the socket subscription, and the responsive layout.
  • Share row styling and metadata components with the inbox, as the spec requires. Reuse RepositoryIcon, ProviderLogo, ScoreBadge (from TaskList/ScoreBadge.tsx), and the relative-time helpers in TaskList/utils.tsx rather than writing new ones.
  • Use RepositorySelector for the filter and persist the selection in the URL query string so it survives navigation.
  • Use useSocket for live updates and useLiveRefreshScheduler to coalesce bursts, exactly as TaskList.tsx and LiveFileChips.tsx already do.
  • Move RepositoryBreakdown and TopModels off the dashboard into a new /analytics route. Do not delete the components.

Acceptance Criteria

  • With zero attention items, the right-hand attention panel is absent from the desktop DOM (not merely visually hidden), and mobile shows the quiet empty line.
  • With attention items present, the attention count in the summary strip uses the emphasised style; with zero, it uses the neutral style.
  • Clicking each of the four summary numbers navigates to the correspondingly filtered list.
  • Changing the repository filter updates all five sections and writes the selection into the URL; reloading the page restores it.
  • Ten rapid task-update socket events produce a single refresh per section, verified by a test asserting the API call count.
  • While a row is expanded, subsequent live updates do not reorder the list.
  • With the socket disconnected, the previously loaded rows remain rendered and a "Reconnecting · Last updated …" line appears.
  • An empty running list renders "No work running"; a failed running-work request renders "Unable to load running work" with a retry affordance. A test asserts these two states produce different text.
  • Historical stats render "—" (or equivalent) for a null success rate rather than "0%".
  • At 320px, no horizontal page overflow occurs and no empty score column is reserved.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Sep 23, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    This implementation splits the dashboard into five independently-fetching section components under a thin composition root, rather than keeping one large component that fetches everything.

    The main reason is the spec's live-update requirements. Each section has different freshness needs — "Happening now" must update continuously while "Historical stats" is a seven-day rollup — and different failure modes. If one component owns all five fetches, a stats failure blanks the running-work list, which directly violates "Distinguish an idle system from an unavailable system." Independent sections let each own its loading, empty, and error state.

    An alternative considered was a single useDashboardData hook returning everything. It was rejected because it forces all five sections to share one error boundary and one refresh cadence, and because it makes the "retain last known data while reconnecting" behaviour apply globally instead of per-section.

    For stable ordering, the approach is to sort once on first receipt and then merge updates in place by task ID, appending only genuinely new rows. Re-sorting on every socket event is what causes rows to jump; the spec calls this out explicitly. The trade-off is that a long-running row keeps its original position even if a newer task would technically sort above it — this is intentional, because predictable position beats strict ordering for a list the user is actively clicking.

    For reuse, the row components deliberately import ScoreBadge, RepositoryIcon, ProviderLogo and the time helpers from TaskList/ rather than reimplementing them, satisfying the spec's "Share row styling and metadata components with the inbox."


    File: propr-ui/src/components/Dashboard/useDashboardSection.ts (new file)

    Why this file: Every section repeats the same lifecycle: fetch, coalesce socket-driven refreshes, keep last-known data on failure, and expose whether we are reconnecting. Extracting it once prevents five slightly-different implementations of the "retain last known data" rule, which is the behaviour most likely to be implemented inconsistently.

    import { useCallback, useEffect, useRef, useState } from 'react';
    import { useSocket } from '../../contexts/SocketContext';
    import { useLiveRefreshScheduler } from '../../hooks/useLiveRefreshScheduler';
    
    export interface SectionState<T> {
      data: T | null;
      /** True only before the first successful load; later refreshes stay silent. */
      initialLoading: boolean;
      /** Set when the most recent attempt failed, even though `data` may still hold stale rows. */
      error: string | null;
      /** When the currently-held data was last successfully fetched. */
      lastUpdated: Date | null;
      refresh: () => void;
    }
    
    /**
     * Shared fetch + live-refresh lifecycle for a dashboard section.
     *
     * Two behaviours here are product requirements rather than conveniences:
     *
     * 1. On failure we keep the previous `data` instead of clearing it. The spec
     *    requires that a disconnect retains the last known data and shows a
     *    "Reconnecting" line; clearing state on error would show an empty list,
     *    which reads as "nothing is running" and is actively misleading.
     *
     * 2. `initialLoading` is only true before the first success. Subsequent
     *    refreshes must not flash a skeleton over rows the user is reading.
     */
    export function useDashboardSection<T>(
      fetcher: () => Promise<T>,
      deps: unknown[],
      options: { live?: boolean } = {},
    ): SectionState<T> {
      const [data, setData] = useState<T | null>(null);
      const [initialLoading, setInitialLoading] = useState(true);
      const [error, setError] = useState<string | null>(null);
      const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
      const { onTaskUpdate } = useSocket();
    
      // A generation counter discards responses from a superseded filter selection.
      // Without it, switching repositories quickly can let an older, slower response
      // overwrite the newer one -- the same stale-response class of bug that
      // useTaskData already guards against for task details.
      const generation = useRef(0);
    
      const load = useCallback(async () => {
        const current = ++generation.current;
        try {
          const result = await fetcher();
          if (generation.current !== current) return;
          setData(result);
          setError(null);
          setLastUpdated(new Date());
        } catch (err) {
          if (generation.current !== current) return;
          // Deliberately do not clear `data`. Stale rows plus a visible error is
          // strictly more useful than an empty list that looks like an idle system.
          setError(err instanceof Error ? err.message : 'Request failed');
        } finally {
          if (generation.current === current) setInitialLoading(false);
        }
      }, deps);
    
      useEffect(() => { void load(); }, [load]);
    
      // Coalesce bursts of socket events into one refresh. A plan finalization can
      // emit a dozen task updates in a second; refetching per event would hammer
      // the API and cause visible list churn.
      const scheduleRefresh = useLiveRefreshScheduler(() => { void load(); });
    
      useEffect(() => {
        if (!options.live) return;
        return onTaskUpdate(() => scheduleRefresh());
      }, [options.live, onTaskUpdate, scheduleRefresh]);
    
      return { data, initialLoading, error, lastUpdated, refresh: () => { void load(); } };
    }

    File: propr-ui/src/components/Dashboard/SummaryStrip.tsx (new file)

    Why this file: The four counts are the first thing a user reads, and they must be clickable entry points into filtered lists. Isolating them keeps the emphasis rule ("stronger emphasis only when there is a problem") in one testable place.

    import { useNavigate } from 'react-router-dom';
    import { getDashboardSummary, type DashboardSummary } from '../../api/dashboardApi';
    import { useDashboardSection } from './useDashboardSection';
    
    interface Props { repository: string; }
    
    interface CountProps {
      label: string;
      value: number | null;
      onClick: () => void;
      /** Emphasis is a signal, not decoration -- reserve it for real problems. */
      emphasised?: boolean;
    }
    
    function Count({ label, value, onClick, emphasised }: CountProps) {
      return (
        <button
          type="button"
          onClick={onClick}
          // Neutral by default so the strip reads calmly during normal operation.
          // Amber is applied only when there is something to act on, which keeps
          // the colour meaningful instead of ambient.
          className={`flex flex-col items-start rounded-md px-3 py-2 text-left transition-colors ${
            emphasised
              ? 'bg-amber-50 text-amber-900 hover:bg-amber-100'
              : 'text-slate-700 hover:bg-slate-50'
          }`}
        >
          {/* Render a dash rather than 0 while unknown: a zero here would claim
              "nothing needs attention", which we cannot yet assert. */}
          <span className="text-2xl font-semibold tabular-nums">{value ?? '—'}</span>
          <span className="text-xs text-slate-500">{label}</span>
        </button>
      );
    }
    
    export function SummaryStrip({ repository }: Props) {
      const navigate = useNavigate();
      const { data } = useDashboardSection<DashboardSummary>(
        () => getDashboardSummary(repository), [repository], { live: true },
      );
    
      // Every number opens the corresponding filtered list, so the strip is a
      // navigation surface rather than a read-only readout.
      const go = (status: string) => () =>
        navigate(`/tasks?status=${status}&repository=${encodeURIComponent(repository)}`);
    
      return (
        <div
          className="grid grid-cols-2 gap-2 sm:grid-cols-4"
          data-testid="dashboard-summary-strip"
        >
          <Count
            label="Needs attention"
            value={data?.needsAttention ?? null}
            onClick={go('needs_attention')}
            // Emphasis is driven by the count itself, so a healthy system never
            // shows a warning colour.
            emphasised={(data?.needsAttention ?? 0) > 0}
          />
          <Count label="Running" value={data?.running ?? null} onClick={go('active')} />
          <Count label="Queued" value={data?.queued ?? null} onClick={go('waiting')} />
          <Count label="Completed today" value={data?.completedToday ?? null} onClick={go('completed')} />
        </div>
      );
    }

    File: propr-ui/src/components/Dashboard/NeedsAttentionPanel.tsx (new file)

    Why this file: Attention is the highest-value section and has the strictest rule: it must never consume space when empty on desktop. Returning null from a dedicated component is the cleanest way to guarantee the panel is truly absent from the DOM rather than merely hidden with CSS.

    import { Link } from 'react-router-dom';
    import { getAttentionItems, type AttentionItem } from '../../api/dashboardApi';
    import { formatRelativeTime } from '../TaskList/utils';
    import { useDashboardSection } from './useDashboardSection';
    
    interface Props {
      repository: string;
      /** Desktop hides the panel entirely when empty; mobile keeps a quiet line. */
      hideWhenEmpty: boolean;
    }
    
    const ACTION_LABEL: Record<AttentionItem['primaryAction'], string> = {
      inspect_failure: 'Inspect failure',
      review_plan: 'Review plan',
      answer_question: 'Answer question',
    };
    
    const REASON_LABEL: Record<AttentionItem['reason'], string> = {
      failed: 'Failed',
      approval: 'Approval',
      question: 'Question',
      manual_decision: 'Waiting',
    };
    
    /** Each row offers exactly one primary action, as the spec requires. */
    function AttentionRow({ item }: { item: AttentionItem }) {
      const reference = item.prNumber ? `PR#${item.prNumber}` : `#${item.issueNumber}`;
      const target = item.primaryAction === 'review_plan'
        ? `/studio/${item.id.split(':')[1]}`
        : `/tasks/${item.id}`;
    
      return (
        <Link to={target} className="flex items-start gap-3 px-3 py-2 hover:bg-slate-50">
          <span className="w-20 shrink-0 text-xs font-medium text-slate-500">
            {REASON_LABEL[item.reason]}
          </span>
          {/* min-w-0 lets the title wrap and shrink instead of forcing horizontal
              overflow on narrow viewports. */}
          <span className="min-w-0 flex-1">
            <span className="block text-sm text-slate-900">{item.title}</span>
            <span className="block text-xs text-slate-500">
              {item.repository} {reference}
            </span>
          </span>
          {/* Waiting duration answers "how long has this been stuck", which is the
              question that makes an operator decide to act now versus later. */}
          <span className="shrink-0 text-xs text-slate-400">
            {formatRelativeTime(item.waitingSince)}
          </span>
          <span className="shrink-0 text-xs font-medium text-teal-700">
            {ACTION_LABEL[item.primaryAction]} →
          </span>
        </Link>
      );
    }
    
    export function NeedsAttentionPanel({ repository, hideWhenEmpty }: Props) {
      const { data, initialLoading, error } = useDashboardSection(
        () => getAttentionItems(repository), [repository], { live: true },
      );
    
      if (initialLoading) return <div className="h-24 animate-pulse rounded bg-slate-50" />;
    
      // An error must not masquerade as "nothing needs attention". Silence here
      // would be the most dangerous possible failure for this particular section.
      if (error && !data) {
        return (
          <section aria-labelledby="attention-heading">
            <h2 id="attention-heading" className="text-sm font-semibold">Needs attention</h2>
            <p className="text-sm text-red-700">Unable to load attention items.</p>
          </section>
        );
      }
    
      const items = data?.items ?? [];
    
      if (items.length === 0) {
        // Returning null removes the panel from the DOM entirely, which is what
        // "Hide the empty attention panel so it does not consume space" requires.
        // A `hidden` class would still occupy a grid track.
        if (hideWhenEmpty) return null;
        return (
          <p className="px-3 py-2 text-sm text-slate-500">Nothing needs your attention.</p>
        );
      }
    
      return (
        <section aria-labelledby="attention-heading" className="rounded-lg border border-slate-200">
          <div className="flex items-center justify-between px-3 py-2">
            <h2 id="attention-heading" className="text-sm font-semibold">Needs attention</h2>
            {/* "View all" only matters when the list is truncated, so it is
                rendered conditionally rather than always. */}
            {(data?.total ?? 0) > items.length && (
              <Link to="/tasks?status=needs_attention" className="text-xs text-teal-700">
                View all →
              </Link>
            )}
          </div>
          <div className="divide-y divide-slate-100">
            {items.map(item => <AttentionRow key={item.id} item={item} />)}
          </div>
        </section>
      );
    }

    File: propr-ui/src/components/Dashboard/HappeningNowSection.tsx (new file)

    Why this file: This is the largest and most behaviourally demanding section. It owns the stable-ordering rule, the expand-without-reorder rule, the queue summary, and the idle-versus-unavailable distinction — all of which need to live together because they interact.

    import { useEffect, useRef, useState } from 'react';
    import { Link } from 'react-router-dom';
    import { getActiveWork, type ActiveWorkItem } from '../../api/dashboardApi';
    import { formatDuration } from '../TaskList/utils';
    import { useDashboardSection } from './useDashboardSection';
    
    interface Props { repository: string; }
    
    const INITIAL_VISIBLE = 5;
    
    /**
     * Merge new server data into the existing order.
     *
     * Rows keep the position they were first given; only genuinely new task IDs are
     * appended. Re-sorting on every update is what makes rows jump under the
     * user's cursor, which the spec explicitly forbids ("Keep ordering stable while
     * tasks run so rows do not jump around with every update").
     *
     * The accepted trade-off is that a newly started task always appears at the
     * bottom even if it would sort higher. Predictable position is worth more here
     * than strict ordering, because this list is clicked, not scanned.
     */
    function mergeStable(previous: ActiveWorkItem[], incoming: ActiveWorkItem[]): ActiveWorkItem[] {
      const byId = new Map(incoming.map(item => [item.task_id, item]));
      const retained = previous
        .filter(item => byId.has(item.task_id))
        .map(item => byId.get(item.task_id)!);
      const known = new Set(retained.map(item => item.task_id));
      return [...retained, ...incoming.filter(item => !known.has(item.task_id))];
    }
    
    function ActiveRow({ item }: { item: ActiveWorkItem }) {
      const reference = item.pr_number ? `PR#${item.pr_number}` : `#${item.issue_number}`;
      const elapsed = formatDuration(new Date(item.created_at).getTime(), Date.now());
    
      return (
        <Link to={`/tasks/${item.task_id}`} className="block px-3 py-2 hover:bg-slate-50">
          <div className="flex items-baseline gap-2">
            <span className="text-xs font-medium text-slate-600">{item.status}</span>
            <span className="min-w-0 truncate text-xs text-slate-500">
              {item.repository} {reference}
            </span>
            <span className="ml-auto shrink-0 text-xs tabular-nums text-slate-400">
              {elapsed} elapsed
            </span>
          </div>
          {/* Show only a phase the backend actually reported. No percentage is
              derived, and the absence of progress is not treated as a stall --
              both are explicit requirements. */}
          {item.progressLabel && (
            <div className="text-xs text-slate-500">{item.progressLabel}</div>
          )}
        </Link>
      );
    }
    
    export function HappeningNowSection({ repository }: Props) {
      const { data, initialLoading, error, lastUpdated, refresh } = useDashboardSection(
        () => getActiveWork(repository), [repository], { live: true },
      );
      const [expanded, setExpanded] = useState(false);
      // Ordering is held outside the fetch state so refreshes cannot reshuffle it.
      const orderRef = useRef<ActiveWorkItem[]>([]);
    
      useEffect(() => {
        if (data?.running) orderRef.current = mergeStable(orderRef.current, data.running);
      }, [data]);
    
      // Reset the retained order when the filter changes: rows from a different
      // repository scope must not persist into the new selection.
      useEffect(() => { orderRef.current = []; setExpanded(false); }, [repository]);
    
      if (initialLoading) return <div className="h-40 animate-pulse rounded bg-slate-50" />;
    
      const rows = orderRef.current;
      const visible = expanded ? rows : rows.slice(0, INITIAL_VISIBLE);
    
      return (
        <section aria-labelledby="happening-heading" className="rounded-lg border border-slate-200">
          <div className="flex items-baseline justify-between px-3 py-2">
            <h2 id="happening-heading" className="text-sm font-semibold">Happening now</h2>
            {/* Retaining stale rows behind a "Reconnecting" line is what lets the
                operator keep reading real data during a transient outage. */}
            {error && rows.length > 0 && lastUpdated && (
              <span className="text-xs text-amber-700">
                Reconnecting · Last updated {formatDuration(lastUpdated.getTime(), Date.now())} ago
              </span>
            )}
          </div>
    
          {/* These two states must be visually and textually distinct: an idle
              system and a broken read mean completely different things. */}
          {error && rows.length === 0 ? (
            <div className="px-3 py-6 text-center">
              <p className="text-sm text-red-700">Unable to load running work</p>
              <button type="button" onClick={refresh} className="mt-2 text-xs text-teal-700">
                Try again
              </button>
            </div>
          ) : rows.length === 0 ? (
            <p className="px-3 py-6 text-center text-sm text-slate-500">No work running</p>
          ) : (
            <div className="divide-y divide-slate-100">
              {visible.map(item => <ActiveRow key={item.task_id} item={item} />)}
              {rows.length > INITIAL_VISIBLE && (
                <button
                  type="button"
                  onClick={() => setExpanded(value => !value)}
                  className="w-full px-3 py-2 text-xs text-teal-700"
                >
                  {expanded ? 'Show fewer' : `Show all ${rows.length} running →`}
                </button>
              )}
            </div>
          )}
    
          {/* Queue summary sits below active work and states the reason only when
              the backend supplied one. No estimated start time is shown. */}
          {(data?.queue.count ?? 0) > 0 && (
            <div className="border-t border-slate-100 px-3 py-2 text-xs text-slate-500">
              <strong className="font-medium text-slate-700">{data!.queue.count} queued</strong>
              {data!.queue.reason && ` · ${data!.queue.reason}`}
            </div>
          )}
        </section>
      );
    }

    File: propr-ui/src/components/Dashboard/HistoricalStatsPanel.tsx (new file)

    Why this file: The stats section is where the "unavailable is not zero" rule matters most, because a 0% success rate and an unknown success rate look identical if implemented carelessly. Keeping it small and separate makes that rule easy to assert in a test.

    import { useState } from 'react';
    import { getDashboardStats, type DashboardStats } from '../../api/dashboardApi';
    import { ActivitySparkline } from '../ActivitySparkline';
    import { useDashboardSection } from './useDashboardSection';
    
    interface Props { repository: string; }
    
    /** Render unknown values as unavailable rather than zero, per the spec. */
    function Metric({ label, value, comparison }: {
      label: string;
      value: string | null;
      comparison?: string | null;
    }) {
      return (
        <div>
          <div className="text-xl font-semibold tabular-nums text-slate-900">
            {/* "—" is deliberate: showing 0% for an unknown success rate would read
                as total failure and is materially misleading. */}
            {value ?? '—'}
          </div>
          <div className="text-xs text-slate-500">{label}</div>
          {comparison && <div className="text-xs text-slate-400">{comparison}</div>}
        </div>
      );
    }
    
    function percentagePointDelta(current: number | null, previous: number | null): string | null {
      // A comparison is only meaningful when both endpoints are known; inventing a
      // delta against a null baseline would fabricate a trend.
      if (current === null || previous === null) return null;
      const points = Math.round((current - previous) * 100);
      const sign = points >= 0 ? '+' : '';
      return `${sign}${points} percentage points`;
    }
    
    export function HistoricalStatsPanel({ repository }: Props) {
      const [period, setPeriod] = useState<'7d' | '30d'>('7d');
      const { data, initialLoading } = useDashboardSection<DashboardStats>(
        () => getDashboardStats(repository, period), [repository, period],
      );
    
      if (initialLoading) return <div className="h-32 animate-pulse rounded bg-slate-50" />;
    
      const days = period === '7d' ? 7 : 30;
    
      return (
        <section aria-labelledby="stats-heading" className="rounded-lg border border-slate-200 p-3">
          <div className="flex items-center justify-between">
            <h2 id="stats-heading" className="text-sm font-semibold">Last {days} days</h2>
            <select
              value={period}
              onChange={event => setPeriod(event.target.value as '7d' | '30d')}
              className="text-xs text-slate-600"
              aria-label="Statistics period"
            >
              <option value="7d">Last 7 days</option>
              <option value="30d">Last 30 days</option>
            </select>
          </div>
    
          <div className="mt-3 grid grid-cols-3 gap-3">
            <Metric label="completed" value={String(data?.completed ?? '—')} />
            <Metric
              label="success"
              value={data?.successRate == null ? null : `${Math.round(data.successRate * 100)}%`}
              comparison={percentagePointDelta(data?.successRate ?? null, data?.previous.successRate ?? null)}
            />
            <Metric
              // "Recorded spend" rather than "Spend": cost tracking can be
              // incomplete, and the label must not overclaim.
              label="recorded spend"
              value={data?.recordedSpend == null ? null : `$${data.recordedSpend.toFixed(0)}`}
            />
          </div>
    
          <div className="mt-3 h-16">
            <ActivitySparkline data={data?.dailyCompleted ?? []} />
          </div>
        </section>
      );
    }

    File: propr-ui/src/components/Dashboard.tsx

    Why this file: This becomes a thin composition root. All fetching moved into the section components, so what remains is the shared repository filter, URL persistence, and the responsive layout described by the spec. Keeping it thin is what makes the desktop/mobile ordering difference easy to read.

    --- a/propr-ui/src/components/Dashboard.tsx
    +++ b/propr-ui/src/components/Dashboard.tsx
    @@
    -import { getTaskStats, getStatsOverview } from '../api/taskStatsApi';
    -import { getQueueStats } from '../api/proprApi';
    -import { TaskStatsChart } from './TaskStatsChart';
    -import { RepositoryBreakdown } from './RepositoryBreakdown';
    -import { TopModels } from './TopModels';
    -import { TaskList } from './TaskList';
    +import { useSearchParams } from 'react-router-dom';
    +import { RepositorySelector } from './RepositorySelector';
    +import { SummaryStrip } from './Dashboard/SummaryStrip';
    +import { NeedsAttentionPanel } from './Dashboard/NeedsAttentionPanel';
    +import { HappeningNowSection } from './Dashboard/HappeningNowSection';
    +import { RecentOutcomesFeed } from './Dashboard/RecentOutcomesFeed';
    +import { HistoricalStatsPanel } from './Dashboard/HistoricalStatsPanel';
     
    -// StatsGrid and the metrics-first layout are replaced entirely. The previous
    -// screen answered "how much work happened"; the new one answers "what needs
    -// attention, what is running, what just happened". RepositoryBreakdown and
    -// TopModels are not deleted -- they move to the /analytics route, where a
    -// fuller breakdown belongs and where they no longer compete with live work.
    +/**
    + * Dashboard composition root.
    + *
    + * This component deliberately owns no data fetching. Each section fetches
    + * independently so that one failing read (for example, stats) cannot blank the
    + * running-work list. That separation is what makes "idle" and "unavailable"
    + * distinguishable per section rather than globally.
    + */
     export function Dashboard() {
    -  // ... previous stats state and effects removed
    +  // The filter lives in the URL so it survives navigation and reload, which is
    +  // the spec's "preserve the selection during navigation" requirement. Local
    +  // component state alone would reset on every route change.
    +  const [searchParams, setSearchParams] = useSearchParams();
    +  const repository = searchParams.get('repository') ?? 'all';
    +
    +  const setRepository = (next: string) => {
    +    const params = new URLSearchParams(searchParams);
    +    if (next === 'all') params.delete('repository');
    +    else params.set('repository', next);
    +    // replace: true keeps filter changes out of the back-button history, so
    +    // Back returns to the previous page rather than the previous filter.
    +    setSearchParams(params, { replace: true });
    +  };
    +
    +  return (
    +    <div className="flex flex-col gap-4 p-4">
    +      <div className="flex items-center justify-between">
    +        <h1 className="text-lg font-semibold">Dashboard</h1>
    +        {/* One filter drives every section; each section receives the value as
    +            a prop rather than reading the URL itself, so there is a single
    +            place where filter semantics are defined. */}
    +        <RepositorySelector
    +          selectedRepo={repository === 'all' ? '' : repository}
    +          onSelect={value => setRepository(value || 'all')}
    +          allowAll
    +        />
    +      </div>
    +
    +      <SummaryStrip repository={repository} />
    +
    +      {/* Mobile ordering: attention, happening now, outcomes, stats.
    +          Rendered as a single column and hidden above the breakpoint rather
    +          than duplicated conditionally in JS, so the DOM order is exactly the
    +          reading order the spec prescribes for small screens. */}
    +      <div className="flex flex-col gap-4 lg:hidden">
    +        <NeedsAttentionPanel repository={repository} hideWhenEmpty={false} />
    +        <HappeningNowSection repository={repository} />
    +        <RecentOutcomesFeed repository={repository} />
    +        <HistoricalStatsPanel repository={repository} />
    +      </div>
    +
    +      {/* Desktop: live work takes the wide main column; attention and stats sit
    +          in the narrower right column. The attention panel is passed
    +          hideWhenEmpty so it unmounts entirely when there is nothing to do,
    +          freeing the column instead of leaving an empty card. */}
    +      <div className="hidden gap-4 lg:grid lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
    +        <div className="flex min-w-0 flex-col gap-4">
    +          <HappeningNowSection repository={repository} />
    +          <RecentOutcomesFeed repository={repository} />
    +        </div>
    +        <div className="flex min-w-0 flex-col gap-4">
    +          <NeedsAttentionPanel repository={repository} hideWhenEmpty />
    +          <HistoricalStatsPanel repository={repository} />
    +        </div>
    +      </div>
    +    </div>
    +  );
     }

    File: propr-ui/src/components/Dashboard/RecentOutcomesFeed.tsx (new file)

    Why this file: Outcomes are a flat feed with their own time-window control and their own score-display rule. Separating it keeps the "score only when relevant, scale labelled, no empty column on mobile" rule in one place.

    import { useState } from 'react';
    import { Link } from 'react-router-dom';
    import { getRecentOutcomes } from '../../api/dashboardApi';
    import { ScoreBadge } from '../TaskList/ScoreBadge';
    import { formatRelativeTime } from '../TaskList/utils';
    import { useDashboardSection } from './useDashboardSection';
    
    interface Props { repository: string; }
    
    export function RecentOutcomesFeed({ repository }: Props) {
      const [window, setWindow] = useState<'24h' | '7d'>('24h');
      const { data, initialLoading, error } = useDashboardSection(
        () => getRecentOutcomes(repository, window), [repository, window], { live: true },
      );
    
      if (initialLoading) return <div className="h-48 animate-pulse rounded bg-slate-50" />;
    
      const outcomes = data?.outcomes ?? [];
    
      return (
        <section aria-labelledby="outcomes-heading" className="rounded-lg border border-slate-200">
          <div className="flex items-center justify-between px-3 py-2">
            <h2 id="outcomes-heading" className="text-sm font-semibold">Recent outcomes</h2>
            <select
              value={window}
              onChange={event => setWindow(event.target.value as '24h' | '7d')}
              className="text-xs text-slate-600"
              aria-label="Outcome window"
            >
              <option value="24h">Last 24 hours</option>
              <option value="7d">Last 7 days</option>
            </select>
          </div>
    
          {error && outcomes.length === 0 ? (
            <p className="px-3 py-6 text-center text-sm text-red-700">Unable to load outcomes</p>
          ) : outcomes.length === 0 ? (
            <p className="px-3 py-6 text-center text-sm text-slate-500">No recent outcomes</p>
          ) : (
            <div className="divide-y divide-slate-100">
              {outcomes.slice(0, 8).map((outcome: any) => (
                <Link
                  key={outcome.task_id}
                  to={`/tasks/${outcome.task_id}`}
                  className="flex items-start gap-3 px-3 py-2 hover:bg-slate-50"
                >
                  {/* Title first and prominent: it is the only field that tells the
                      operator what actually changed. */}
                  <span className="min-w-0 flex-1">
                    <span className="block text-sm text-slate-900">{outcome.title}</span>
                    <span className="block text-xs text-slate-500">
                      {outcome.repository}{' '}
                      {outcome.pr_number ? `PR#${outcome.pr_number}` : `#${outcome.issue_number}`}
                    </span>
                  </span>
                  {/* Score renders only when one exists, so no empty column is
                      reserved on narrow screens. The badge labels its own /10
                      scale, which keeps the number interpretable. */}
                  {outcome.critiqueScore != null && (
                    <span className="hidden shrink-0 sm:block">
                      <ScoreBadge score={outcome.critiqueScore} />
                    </span>
                  )}
                  <span className="shrink-0 text-xs text-slate-400">
                    {formatRelativeTime(outcome.completed_at)}
                  </span>
                </Link>
              ))}
            </div>
          )}
    
          <div className="border-t border-slate-100 px-3 py-2 text-right">
            <Link to="/tasks" className="text-xs text-teal-700">View history →</Link>
          </div>
        </section>
      );
    }

    File: propr-ui/src/components/AnalyticsPage.tsx (new file)

    Why this file: The spec says to move the top-model and repository-breakdown charts into a fuller analytics view rather than delete them. A dedicated route preserves the existing, working components while freeing dashboard space for live work.

    import { RepositoryBreakdown } from './RepositoryBreakdown';
    import { TopModels } from './TopModels';
    import { TaskStatsChart } from './TaskStatsChart';
    
    /**
     * Fuller analytics view.
     *
     * These components are intentionally reused unchanged. The dashboard change is
     * about where they belong, not about whether they are correct -- rewriting them
     * here would add regression risk for no product benefit.
     */
    export function AnalyticsPage() {
      return (
        <div className="flex flex-col gap-6 p-4">
          <h1 className="text-lg font-semibold">Analytics</h1>
          <TaskStatsChart mode="all" />
          <div className="grid gap-6 lg:grid-cols-2">
            <RepositoryBreakdown />
            <TopModels />
          </div>
        </div>
      );
    }
  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: 2479/claude-opus-5-rebuild-the-dashboard-ui--20260923-1302-rj9
    • Base Branch: 2478-epic-dashboard-data-2ki
    • Worktree: issue-2479-20260923-1302-claude-opus-5-rj9

    🔍 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