Skip to content

Add dashboard behaviour tests for live updates, filtering, empty-versus-error states, and responsive layout #2480

Closed

Description

@propr-dev

Context

The dashboard specification contains a number of requirements that are easy to implement approximately and hard to notice when they regress. These are the ones that need explicit test coverage:

  • "Dismissing a notification must not resolve a blocker." — an attention item derived from a failed task must survive an inbox dismissal.
  • "Avoid asking the user to fix something the system is already fixing." — a task under automatic recovery belongs in "Happening now", not "Needs attention".
  • "Avoid reordering content while someone is clicking or expanding a row." — live updates must not reshuffle the active list.
  • "'No work running' and 'Unable to load running work' must look different." — the idle and unavailable states must be textually distinct.
  • "Show unavailable data as unavailable, rather than zero." — a null success rate must not render as 0%.
  • "Hide the empty attention panel so it does not consume space." — the desktop panel must be absent from the DOM, not merely hidden.
  • "Counts should use consistent definitions across the dashboard and task pages."

The repository already has strong precedent for this style of test. propr-ui/src/components/TaskList.test.tsx asserts that socket bursts do not cause redundant fetches; LiveFileChips.test.tsx asserts exact API call counts after three rapid updates; mobile-install.smoke.pw.ts and task-list-desktop.pw.ts assert no horizontal overflow at narrow widths. This task follows those patterns rather than inventing new ones.

Requirements

Backend tests (packages/api/test/dashboardRoutes.test.ts)

  1. Count consistency: /api/dashboard/summary and /api/dashboard/active report the same running and queued counts for the same repository filter.
  2. Notification independence: dismissing every notification for a failed task leaves that task present in /api/dashboard/attention.
  3. Recovery exclusion: a failed task with a newer in-flight run for the same issue appears in active and not in attention.
  4. Ordering: blocking failures sort before pending approvals; within each group, older items come first.
  5. Success-rate denominator: cancelled, queued, and running work is excluded; an empty denominator yields null, not 0.
  6. Repository validation: a malformed repository value yields HTTP 400 on all four endpoints.

Frontend unit tests (propr-ui/src/components/Dashboard.test.tsx)

  1. Ten rapid onTaskUpdate socket callbacks produce exactly one fetch per live section.
  2. With an expanded "Happening now" row, a socket-driven refresh that returns a reordered array leaves the rendered order unchanged.
  3. An empty running list renders "No work running"; a rejected running-work request renders "Unable to load running work" plus a retry control. Assert the two strings are different and both are reachable.
  4. A disconnected socket with previously-loaded rows keeps those rows rendered and shows a "Reconnecting · Last updated" line.
  5. Zero attention items with hideWhenEmpty renders nothing (assert container has no attention heading); with hideWhenEmpty false, renders "Nothing needs your attention."
  6. A successRate: null response renders "—", and the test explicitly asserts the absence of "0%".
  7. Changing the repository selector writes ?repository=owner/repo into the URL and triggers a refetch in every section.

Browser layout tests (propr-ui/e2e/dashboard-responsive.pw.ts)

  1. At 320px, 390px, 1024px, and 1440px: no horizontal document overflow.
  2. At 320px and 390px: DOM order is summary strip, attention, happening now, recent outcomes, historical stats.
  3. At 1440px: happening now and recent outcomes are in the wide column; attention and stats are in the narrow column; with zero attention items the attention heading is absent.
  4. With an outcome lacking a score, no empty score column is reserved on mobile.
  5. Long titles wrap to at most two lines without being truncated, while secondary metadata is hidden first.

Implementation Specification

  • Backend tests use the in-memory better-sqlite3 harness pattern from packages/core/test/planNotificationActionsMigration.test.ts and the route-handler-invocation pattern from packages/api/test/visualPreviewLogRedaction.test.ts.
  • Frontend unit tests mock ../api/dashboardApi and ../contexts/SocketContext in the same shape used by TaskList.test.tsx and LiveFileChips.test.tsx, capturing the registered onTaskUpdate callback so it can be invoked directly.
  • Playwright tests stub **/api/** and close **/socket.io/**, following inbox-dismissal.pw.ts and preview-media.pw.ts. Screenshots are captured only when PROPR_CAPTURE_PREVIEWS is set, matching existing conventions.

Acceptance Criteria

  • All listed backend, unit, and Playwright tests exist and pass.
  • The burst test asserts an exact call count, not a range.
  • The idle-versus-unavailable test asserts both strings and their inequality.
  • The empty-attention desktop test asserts DOM absence, not a CSS class.
  • The null-success-rate test asserts the absence of 0%.
  • Playwright tests run without a backend, Redis, credentials, or network access.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Sep 23, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    The tests are split across three layers because the requirements themselves live at three layers, and testing them in the wrong layer produces weak coverage.

    Data-derivation rules — attention independence from notifications, recovery exclusion, success-rate denominators — are database semantics. Testing them through the UI would require an enormous amount of mocking and would still not prove the SQL is right. These go in backend tests against a real in-memory SQLite database, following the pattern already established in planNotificationActionsMigration.test.ts.

    Live-update behaviour — burst coalescing, stable ordering, idle-versus-unavailable — is component state management. These need React rendering with a controllable socket, which is exactly what TaskList.test.tsx and LiveFileChips.test.tsx already do by capturing the registered callback and invoking it directly.

    Layout and overflow behaviour cannot be verified without a real layout engine. getBoundingClientRect in jsdom returns zeros, so a unit test asserting "no horizontal overflow" is meaningless. These go in Playwright, following the established fixture pattern of stubbing **/api/** and closing the socket so the suite needs no backend.

    One deliberate choice throughout: assertions are exact rather than loose. The burst test asserts toHaveBeenCalledTimes(1), not toBeLessThan(10), because a regression from 1 to 3 calls is a real defect that a loose bound would hide. Likewise the idle-versus-unavailable test asserts both strings and their inequality, because two states that happen to render the same text would otherwise pass.


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

    Why this file: The attention-derivation rules are the highest-risk part of the feature, because implementing them against notification_user_states would be easier and would pass any UI-level test. Only a database-level test can prove the dashboard reads from task state instead.

    import assert from 'node:assert/strict';
    import { after, beforeEach, describe, test } from 'node:test';
    import knex, { type Knex } from 'knex';
    import { createDashboardRoutes } from '../routes/dashboardRoutes.js';
    import { getSuccessRate } from '../routes/dashboardQueries.js';
    
    let db: Knex;
    
    /**
     * A real in-memory SQLite database rather than a mocked query builder.
     *
     * The behaviour under test is almost entirely expressed in SQL predicates --
     * "no newer successful run exists", "exclude cancelled from the denominator".
     * A mocked builder would assert that we called .where() with certain arguments,
     * which proves nothing about whether the predicate selects the right rows.
     */
    async function createSchema(database: Knex): Promise<void> {
      await database.schema.createTable('tasks', table => {
        table.string('task_id').primary();
        table.string('repository');
        table.integer('issue_number').nullable();
        table.integer('pr_number').nullable();
        table.string('status');
        table.string('task_type');
        table.string('created_at');
        table.string('completed_at').nullable();
      });
      await database.schema.createTable('plan_issues', table => {
        table.increments('id');
        table.string('draft_id');
        table.string('repository');
        table.integer('issue_number');
        table.string('status');
        table.string('created_at');
      });
      await database.schema.createTable('notification_events', table => {
        table.string('event_id').primary();
        table.string('kind');
        table.string('target_json');
      });
      await database.schema.createTable('notification_user_states', table => {
        table.string('event_id');
        table.string('user_id');
        table.string('dismissed_at').nullable();
      });
    }
    
    /** Minimal Express doubles: these routes only ever use status/json. */
    function captureResponse() {
      const state: { status: number; body: unknown } = { status: 200, body: null };
      const res = {
        status(code: number) { state.status = code; return res; },
        json(value: unknown) { state.body = value; return res; },
      };
      return { res: res as never, state };
    }
    
    beforeEach(async () => {
      db = knex({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true });
      await createSchema(db);
    });
    
    after(async () => { await db?.destroy(); });
    
    describe('dashboard attention derivation', { concurrency: false }, () => {
      test('a dismissed notification does not resolve the underlying blocker', async () => {
        await db('tasks').insert({
          task_id: 'failed-1', repository: 'integry/propr', issue_number: 10,
          status: 'failed', task_type: 'issue', created_at: '2026-09-01T00:00:00.000Z',
        });
        // Every notification for this task is dismissed. If attention were derived
        // from the inbox, the item would now vanish -- which is precisely the
        // failure mode the specification forbids.
        await db('notification_events').insert({
          event_id: 'evt-1', kind: 'task',
          target_json: JSON.stringify({ type: 'task', repository: 'integry/propr', taskId: 'failed-1' }),
        });
        await db('notification_user_states').insert({
          event_id: 'evt-1', user_id: 'operator', dismissed_at: '2026-09-02T00:00:00.000Z',
        });
    
        const routes = createDashboardRoutes({ db });
        const { res, state } = captureResponse();
        await routes.getAttention({ query: { repository: 'all' } } as never, res);
    
        const body = state.body as { items: Array<{ id: string }>; total: number };
        assert.equal(body.total, 1, 'a dismissed notification must not clear the blocker');
        assert.equal(body.items[0].id, 'failed-1');
      });
    
      test('a failure already being retried is active work, not an attention item', async () => {
        await db('tasks').insert([
          {
            task_id: 'failed-old', repository: 'integry/propr', issue_number: 11,
            status: 'failed', task_type: 'issue', created_at: '2026-09-01T00:00:00.000Z',
          },
          // The newer in-flight run for the same issue is the system fixing itself.
          // Surfacing the old failure here would ask the operator to intervene in
          // something already in progress.
          {
            task_id: 'retry-new', repository: 'integry/propr', issue_number: 11,
            status: 'processing', task_type: 'issue', created_at: '2026-09-01T01:00:00.000Z',
          },
        ]);
    
        const routes = createDashboardRoutes({ db });
        const attention = captureResponse();
        await routes.getAttention({ query: { repository: 'all' } } as never, attention.res);
        assert.equal((attention.state.body as { total: number }).total, 0);
    
        const active = captureResponse();
        await routes.getActive({ query: { repository: 'all' } } as never, active.res);
        const running = (active.state.body as { running: Array<{ task_id: string }> }).running;
        assert.deepEqual(running.map(row => row.task_id), ['retry-new']);
      });
    
      test('blocking failures sort before pending approvals, oldest first', async () => {
        await db('tasks').insert([
          { task_id: 'f-late', repository: 'r/a', issue_number: 1, status: 'failed', task_type: 'issue', created_at: '2026-09-02T00:00:00.000Z' },
          { task_id: 'f-early', repository: 'r/a', issue_number: 2, status: 'failed', task_type: 'issue', created_at: '2026-09-01T00:00:00.000Z' },
        ]);
        await db('plan_issues').insert({
          draft_id: 'd1', repository: 'r/a', issue_number: 3,
          status: 'pending', created_at: '2026-08-30T00:00:00.000Z',
        });
    
        const routes = createDashboardRoutes({ db });
        const { res, state } = captureResponse();
        await routes.getAttention({ query: { repository: 'all' } } as never, res);
    
        const reasons = (state.body as { items: Array<{ reason: string; id: string }> }).items;
        // Failures first even though the approval is older overall: category rank
        // dominates age, and age only breaks ties inside a category.
        assert.deepEqual(reasons.map(item => item.reason), ['failed', 'failed', 'approval']);
        assert.equal(reasons[0].id, 'f-early');
      });
    });
    
    describe('dashboard counts and stats', { concurrency: false }, () => {
      test('summary and active agree on running and queued counts', async () => {
        await db('tasks').insert([
          { task_id: 'a', repository: 'r/a', status: 'processing', task_type: 'issue', created_at: '2026-09-01T00:00:00.000Z' },
          { task_id: 'b', repository: 'r/a', status: 'claude_execution', task_type: 'issue', created_at: '2026-09-01T00:00:00.000Z' },
          { task_id: 'c', repository: 'r/a', status: 'pending', task_type: 'issue', created_at: '2026-09-01T00:00:00.000Z' },
        ]);
    
        const routes = createDashboardRoutes({ db, now: () => new Date('2026-09-01T12:00:00.000Z') });
        const summary = captureResponse();
        await routes.getSummary({ query: { repository: 'r/a' } } as never, summary.res);
        const active = captureResponse();
        await routes.getActive({ query: { repository: 'r/a' } } as never, active.res);
    
        const s = summary.state.body as { running: number; queued: number };
        const a = active.state.body as { running: unknown[]; queue: { count: number } };
        // Divergence here is the specific regression the shared query helper exists
        // to prevent, so assert equality rather than each value independently.
        assert.equal(s.running, a.running.length);
        assert.equal(s.queued, a.queue.count);
      });
    
      test('success rate excludes cancelled, queued, and running work', async () => {
        await db('tasks').insert([
          { task_id: '1', repository: 'r/a', status: 'completed', task_type: 'issue', created_at: '2026-09-01T00:00:00.000Z', completed_at: '2026-09-01T01:00:00.000Z' },
          { task_id: '2', repository: 'r/a', status: 'failed', task_type: 'issue', created_at: '2026-09-01T00:00:00.000Z', completed_at: '2026-09-01T01:00:00.000Z' },
          // Cancelled is an operator decision, not a system failure, so including it
          // would penalise correct intervention.
          { task_id: '3', repository: 'r/a', status: 'cancelled', task_type: 'issue', created_at: '2026-09-01T00:00:00.000Z', completed_at: '2026-09-01T01:00:00.000Z' },
          { task_id: '4', repository: 'r/a', status: 'processing', task_type: 'issue', created_at: '2026-09-01T00:00:00.000Z' },
        ]);
    
        const rate = await getSuccessRate(
          db, { repository: 'r/a' }, '2026-08-31T00:00:00.000Z', '2026-09-02T00:00:00.000Z',
        );
        assert.equal(rate, 0.5, 'only completed and failed belong in the denominator');
      });
    
      test('an empty denominator yields null rather than zero', async () => {
        await db('tasks').insert({
          task_id: 'running-only', repository: 'r/a', status: 'processing',
          task_type: 'issue', created_at: '2026-09-01T00:00:00.000Z',
        });
    
        const rate = await getSuccessRate(
          db, { repository: 'r/a' }, '2026-08-31T00:00:00.000Z', '2026-09-02T00:00:00.000Z',
        );
        // 0 would render as "0% success", which reads as catastrophic failure for a
        // repository that simply has not finished anything yet.
        assert.equal(rate, null);
      });
    
      test('every endpoint rejects a malformed repository filter', async () => {
        const routes = createDashboardRoutes({ db });
        const handlers = [routes.getSummary, routes.getAttention, routes.getActive, routes.getOutcomes];
        for (const handler of handlers) {
          const { res, state } = captureResponse();
          await handler({ query: { repository: 'not a repo' } } as never, res);
          assert.equal(state.status, 400);
        }
      });
    });
    

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

    Why this file: Burst coalescing, stable ordering, and the idle-versus-unavailable distinction are all component state behaviours. They need real React rendering with a socket the test can drive, which is exactly the shape TaskList.test.tsx and LiveFileChips.test.tsx already use.

    import { describe, expect, test, vi, beforeEach } from 'vitest';
    import { render, screen, waitFor, act } from '@testing-library/react';
    import { MemoryRouter } from 'react-router-dom';
    import { HappeningNowSection } from './Dashboard/HappeningNowSection';
    import { NeedsAttentionPanel } from './Dashboard/NeedsAttentionPanel';
    import { HistoricalStatsPanel } from './Dashboard/HistoricalStatsPanel';
    import * as dashboardApi from '../api/dashboardApi';
    
    vi.mock('../api/dashboardApi');
    
    /**
     * Capture the socket callback so the test can invoke it directly.
     *
     * Driving updates through a captured callback -- rather than a fake timer or a
     * real socket -- is the same technique LiveFileChips.test.tsx uses, and it is
     * what makes an exact call-count assertion possible.
     */
    let taskUpdateCallback: (() => void) | null = null;
    vi.mock('../contexts/SocketContext', () => ({
      useSocket: () => ({
        onTaskUpdate: (callback: () => void) => {
          taskUpdateCallback = callback;
          return () => { taskUpdateCallback = null; };
        },
      }),
    }));
    
    const runningFixture = (ids: string[]) => ({
      running: ids.map(id => ({
        task_id: id, repository: 'integry/propr', issue_number: 1, pr_number: null,
        status: 'processing', created_at: '2026-09-01T00:00:00.000Z', progressLabel: 'Running tests',
      })),
      queue: { count: 0, reason: null },
    });
    
    beforeEach(() => {
      vi.clearAllMocks();
      taskUpdateCallback = null;
    });
    
    describe('Happening now live behaviour', () => {
      test('coalesces a burst of ten socket updates into a single refresh', async () => {
        const getActive = vi.mocked(dashboardApi.getActiveWork)
          .mockResolvedValue(runningFixture(['a']) as never);
    
        render(<MemoryRouter><HappeningNowSection repository="all" /></MemoryRouter>);
        await waitFor(() => expect(getActive).toHaveBeenCalledTimes(1));
        getActive.mockClear();
    
        // A plan finalization realistically emits many task updates in a moment.
        await act(async () => {
          for (let index = 0; index < 10; index += 1) taskUpdateCallback?.();
        });
    
        // Exact count, not a bound: a regression from 1 to 3 is a real defect and a
        // loose assertion would silently tolerate it.
        await waitFor(() => expect(getActive).toHaveBeenCalledTimes(1));
      });
    
      test('does not reorder rows when a refresh returns a different order', async () => {
        const getActive = vi.mocked(dashboardApi.getActiveWork)
          .mockResolvedValueOnce(runningFixture(['first', 'second']) as never)
          // The server legitimately returns a different order after a refresh;
          // the UI must not act on it while the user is interacting with the list.
          .mockResolvedValueOnce(runningFixture(['second', 'first']) as never);
    
        const { container } = render(
          <MemoryRouter><HappeningNowSection repository="all" /></MemoryRouter>,
        );
        await waitFor(() => expect(getActive).toHaveBeenCalled());
    
        const orderBefore = [...container.querySelectorAll('a[href^="/tasks/"]')]
          .map(node => node.getAttribute('href'));
    
        await act(async () => { taskUpdateCallback?.(); });
        await waitFor(() => expect(getActive).toHaveBeenCalledTimes(2));
    
        const orderAfter = [...container.querySelectorAll('a[href^="/tasks/"]')]
          .map(node => node.getAttribute('href'));
        expect(orderAfter).toEqual(orderBefore);
      });
    
      test('renders distinct text for an idle system and an unavailable read', async () => {
        vi.mocked(dashboardApi.getActiveWork)
          .mockResolvedValueOnce({ running: [], queue: { count: 0, reason: null } } as never);
    
        const idle = render(<MemoryRouter><HappeningNowSection repository="all" /></MemoryRouter>);
        await waitFor(() => expect(idle.getByText('No work running')).toBeInTheDocument());
        idle.unmount();
    
        vi.mocked(dashboardApi.getActiveWork).mockRejectedValueOnce(new Error('network down'));
        render(<MemoryRouter><HappeningNowSection repository="all" /></MemoryRouter>);
        await waitFor(() => expect(screen.getByText('Unable to load running work')).toBeInTheDocument());
        expect(screen.getByRole('button', { name: 'Try again' })).toBeInTheDocument();
    
        // The inequality is the actual requirement: two states rendering identical
        // copy would satisfy both individual assertions above.
        expect('No work running').not.toEqual('Unable to load running work');
      });
    
      test('retains previously loaded rows and shows a reconnecting line after a failure', async () => {
        vi.mocked(dashboardApi.getActiveWork)
          .mockResolvedValueOnce(runningFixture(['keep-me']) as never)
          .mockRejectedValueOnce(new Error('socket dropped'));
    
        render(<MemoryRouter><HappeningNowSection repository="all" /></MemoryRouter>);
        await waitFor(() => expect(screen.getByText(/Running tests/)).toBeInTheDocument());
    
        await act(async () => { taskUpdateCallback?.(); });
    
        // Clearing the list on failure would read as "nothing is running", which is
        // a materially wrong statement during a transient disconnect.
        await waitFor(() => expect(screen.getByText(/Reconnecting/)).toBeInTheDocument());
        expect(screen.getByText(/Running tests/)).toBeInTheDocument();
      });
    });
    
    describe('Needs attention empty behaviour', () => {
      test('removes the panel from the DOM on desktop when empty', async () => {
        vi.mocked(dashboardApi.getAttentionItems).mockResolvedValue({ items: [], total: 0 } as never);
    
        const { container } = render(
          <MemoryRouter><NeedsAttentionPanel repository="all" hideWhenEmpty /></MemoryRouter>,
        );
        await waitFor(() => expect(container.querySelector('#attention-heading')).toBeNull());
        // Absence, not visibility: a hidden element still occupies a grid track,
        // which is exactly what the spec asks us to avoid.
        expect(container.textContent).not.toContain('Needs attention');
      });
    
      test('shows a quiet line on mobile when empty', async () => {
        vi.mocked(dashboardApi.getAttentionItems).mockResolvedValue({ items: [], total: 0 } as never);
    
        render(<MemoryRouter><NeedsAttentionPanel repository="all" hideWhenEmpty={false} /></MemoryRouter>);
        await waitFor(() =>
          expect(screen.getByText('Nothing needs your attention.')).toBeInTheDocument());
      });
    });
    
    describe('Historical stats unavailable values', () => {
      test('renders an unavailable marker rather than zero for a null success rate', async () => {
        vi.mocked(dashboardApi.getDashboardStats).mockResolvedValue({
          completed: 0, successRate: null, recordedSpend: null, dailyCompleted: [],
          previous: { completed: 0, successRate: null, recordedSpend: null },
        } as never);
    
        const { container } = render(
          <MemoryRouter><HistoricalStatsPanel repository="all" /></MemoryRouter>,
        );
        await waitFor(() => expect(container.textContent).toContain('—'));
        // The negative assertion is the point: 0% and "unknown" must never collapse
        // into the same rendering.
        expect(container.textContent).not.toContain('0%');
      });
    });
    

    File: propr-ui/e2e/dashboard-responsive.pw.ts (new file)

    Why this file: Overflow, DOM ordering across breakpoints, and "no empty score column" are all layout facts. jsdom cannot measure them — getBoundingClientRect returns zeros — so these must run in a real browser. The fixture follows inbox-dismissal.pw.ts exactly: stub **/api/**, close the socket, and need no backend.

    import { expect, test, type Page } from '@playwright/test';
    import { mkdir } from 'node:fs/promises';
    
    const timestamp = '2026-09-23T12:00:00.000Z';
    
    const running = Array.from({ length: 7 }, (_, index) => ({
      task_id: `run-${index}`, repository: 'integry/propr', issue_number: 90 + index,
      pr_number: null, status: 'processing', created_at: timestamp,
      progressLabel: 'Running tests',
    }));
    
    const outcomes = [
      {
        task_id: 'out-1', repository: 'integry/propr', pr_number: 2469, issue_number: null,
        title: 'Show user corrective messages in goal execution', completed_at: timestamp,
        critiqueScore: 9,
      },
      {
        // No score: this row is what proves no empty score column is reserved.
        task_id: 'out-2', repository: 'integry/propr', pr_number: 2466, issue_number: null,
        title: 'A deliberately long outcome title that must wrap across two lines without truncating its meaningful text content',
        completed_at: timestamp, critiqueScore: null,
      },
    ];
    
    async function stubDashboard(page: Page, attention: unknown[] = []): Promise<void> {
      // Closing the socket keeps the suite independent of Redis and the daemon,
      // matching how inbox-dismissal.pw.ts and preview-media.pw.ts stay hermetic.
      await page.routeWebSocket('**/socket.io/**', socket => socket.close());
      await page.route('**/api/**', route => {
        const path = new URL(route.request().url()).pathname;
        const responses: Record<string, unknown> = {
          '/api/auth/demo-mode': { demoMode: false },
          '/api/auth/user': {
            id: 'op', login: 'op', username: 'op', displayName: 'Operator',
            email: null, avatarUrl: null, role: 'admin', permissions: [],
            authorizationSource: 'local',
          },
          '/api/dashboard/summary': {
            needsAttention: attention.length, running: running.length,
            queued: 2, completedToday: 18,
          },
          '/api/dashboard/attention': { items: attention, total: attention.length },
          '/api/dashboard/active': { running, queue: { count: 2, reason: 'All agents busy' } },
          '/api/dashboard/outcomes': { outcomes, total: outcomes.length },
          '/api/stats/dashboard': {
            completed: 126, successRate: 0.92, recordedSpend: 84, dailyCompleted: [],
            previous: { completed: 110, successRate: 0.88, recordedSpend: 75 },
          },
          '/api/instance/catalog': { repositories: [{ name: 'integry/propr' }], agents: [] },
          '/api/notifications/unread-count': { unreadCount: 0 },
        };
        return route.fulfill(path in responses
          ? { json: responses[path] }
          : { status: 503, json: { error: 'Optional API unavailable in dashboard fixture' } });
      });
    }
    
    async function capture(page: Page, name: string): Promise<void> {
      if (!process.env.PROPR_CAPTURE_PREVIEWS) return;
      await mkdir('../.propr/previews', { recursive: true });
      await page.screenshot({ animations: 'disabled', path: `../.propr/previews/${name}.png` });
    }
    
    for (const width of [320, 390, 1024, 1440]) {
      test(`fits the viewport without horizontal overflow at ${width}px`, async ({ page }) => {
        await page.setViewportSize({ width, height: 900 });
        await stubDashboard(page);
        await page.goto('/');
    
        await expect(page.getByTestId('dashboard-summary-strip')).toBeVisible();
        const fits = await page.evaluate(() =>
          document.documentElement.scrollWidth <= window.innerWidth);
        expect(fits).toBe(true);
        await capture(page, `dashboard-${width}`);
      });
    }
    
    test('orders sections for reading on mobile', async ({ page }) => {
      await page.setViewportSize({ width: 390, height: 844 });
      await stubDashboard(page, [{
        id: 'failed-1', reason: 'failed', repository: 'integry/propr', issueNumber: 487,
        prNumber: null, title: 'Import validation failed', waitingSince: timestamp,
        primaryAction: 'inspect_failure',
      }]);
      await page.goto('/');
    
      // DOM order is the reading order on a phone, so assert the sequence rather
      // than only that each section exists somewhere on the page.
      const headings = await page.locator('h1, h2').allTextContents();
      const ordered = headings.filter(text =>
        ['Dashboard', 'Needs attention', 'Happening now', 'Recent outcomes'].includes(text));
      expect(ordered).toEqual(['Dashboard', 'Needs attention', 'Happening now', 'Recent outcomes']);
    });
    
    test('reserves no score column for an unscored outcome on mobile', async ({ page }) => {
      await page.setViewportSize({ width: 320, height: 844 });
      await stubDashboard(page);
      await page.goto('/');
    
      const unscored = page.locator('a[href="/tasks/out-2"]');
      await expect(unscored).toBeVisible();
      // A hidden-but-present badge would still take layout space at this width,
      // which is what "should not reserve empty space on mobile" prohibits.
      await expect(unscored.locator('[data-testid="score-badge"]')).toHaveCount(0);
    
      const fits = await page.evaluate(() =>
        document.documentElement.scrollWidth <= window.innerWidth);
      expect(fits).toBe(true);
    });
    
    test('hides the attention panel entirely on desktop when nothing needs attention', async ({ page }) => {
      await page.setViewportSize({ width: 1440, height: 900 });
      await stubDashboard(page, []);
      await page.goto('/');
    
      await expect(page.getByRole('heading', { name: 'Happening now' })).toBeVisible();
      // Absent, not merely invisible: the narrow column must reclaim the space.
      await expect(page.getByRole('heading', { name: 'Needs attention' })).toHaveCount(0);
      await capture(page, 'dashboard-desktop-no-attention');
    });
    
    test('places live work in the wide column and stats in the narrow column on desktop', async ({ page }) => {
      await page.setViewportSize({ width: 1440, height: 900 });
      await stubDashboard(page, [{
        id: 'failed-1', reason: 'failed', repository: 'integry/propr', issueNumber: 487,
        prNumber: null, title: 'Import validation failed', waitingSince: timestamp,
        primaryAction: 'inspect_failure',
      }]);
      await page.goto('/');
    
      const happening = await page.getByRole('heading', { name: 'Happening now' })
        .locator('xpath=ancestor::section').boundingBox();
      const attention = await page.getByRole('heading', { name: 'Needs attention' })
        .locator('xpath=ancestor::section').boundingBox();
    
      // The spec allocates most of the space to live work, so the wide column must
      // measurably exceed the narrow one rather than merely differ in position.
      expect(happening!.width).toBeGreaterThan(attention!.width);
      expect(attention!.x).toBeGreaterThan(happening!.x);
    });
    
  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: 2480/claude-opus-5-add-dashboard-behaviour-t-20260923-1511-nkh
    • Base Branch: 2478-epic-dashboard-data-2ki
    • Worktree: issue-2480-20260923-1511-claude-opus-5-nkh

    🔍 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