Skip to content

Agents v1 (16/17): Web UI — run history, run detail, report view, Run now and approve/reject #2815

Closed

Description

@propr-dev

Context

Issue 15 built the Agents list and the detail/edit view. This issue completes the master-detail UI: the agent's run history list, the run detail view, the report view, and the actions around them — Run now, Approve / Reject for preview mode, Cancel, and a capacity warning before running near a subscription limit.

Run detail deliberately links to the underlying tasks (/tasks/<reportTaskId> and /tasks/<actionTaskId>) instead of re-implementing live logs: the report and acting steps are ordinary tasks, so the existing TaskDetails view already shows their timeline, live output, cost and logs.

Requirements

  1. propr-ui/src/components/Agents/AgentRunHistory.tsx: in the agent's Runs tab; newest first; columns: started (relative time), trigger (Run now / Schedule / API / MCP / CLI + source tooltip), state badge, duration, one-line report preview (first non-empty line, loaded lazily on hover or from the detail); "Load more" using nextOffset; ListSkeleton while loading. Clicking a row navigates to /agents/:definitionId/runs/:runId. Back from a run returns to the history ("← Runs").
  2. propr-ui/src/components/Agents/AgentRunDetail.tsx:
    • Header: state badge, trigger + source, timestamps (created, reported, finished), autonomy mode used by this run.
    • Skip/defer/failure reason in a SystemAlert when present (shows cost-gate messages verbatim).
    • Report view: the report rendered with MarkdownRenderer (no raw HTML), a "Copy" button and a "Report truncated — full output in the task log" note when reportTruncated.
    • Awaiting approval state: an approval panel with an optional note textarea (≤2,000 chars), Approve and act and Reject buttons (confirm dialogs), explaining what the acting agent can do (ProPR tools on the agent's repositories; cannot merge or change settings).
    • Acting/completed: "What the acting agent did" section rendering actionSummary with MarkdownRenderer.
    • Links: "Open report task" → /tasks/<reportTaskId>, "Open acting task" → /tasks/<actionTaskId>.
    • Cancel button while queued, deferred, running, awaiting_approval or acting.
    • While non-terminal, refresh every 10 s (and immediately on socket task:update events for its task ids via useSocket().onTaskUpdate), stop when terminal.
  3. Run now button in the agent header (issue 15's AgentDetail): calls triggerAgentRun, then navigates to the new run. Before triggering, fetch getAgentCapacity; when near_limit, show a confirm dialog "Claude is at 94% of its session window (pause threshold 90%). Run anyway?" — attended runs are allowed to proceed, but the user decides knowingly. Disabled when the agent is disabled or in demo mode.
  4. List badges: the Agents list (issue 15) shows the last run's state; an awaiting_approval run shows a "Needs review" badge so preview-mode work is discoverable.
  5. Tests: AgentRunDetail.test.tsx (report rendering, approve flow with note, reject, polling stops at terminal), AgentRunHistory.test.tsx (paging, row navigation), Run now capacity confirmation test.

Implementation Specification

  • Shared AgentRunStateBadge component maps each AgentRunState to label + color (gray queued/deferred, teal running/acting, amber awaiting_approval, green completed, red failed, slate skipped/rejected/cancelled).
  • Reports are untrusted model output: rely on MarkdownRenderer (react-markdown, no rehype-raw) and keep links rel="noopener noreferrer".
  • Use the useDocumentTitle hook: "Run · ".

Acceptance Criteria

  • A completed run shows its Markdown report, with copy and links to its task.
  • A preview-mode run in awaiting_approval can be approved with a note (POST body contains the note) or rejected; buttons disappear after the transition.
  • A skipped run shows the cost-gate reason.
  • Run now near the limit asks for confirmation; cancelling the dialog sends no request.
  • Polling stops once the run is terminal (verified with fake timers).

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Oct 6, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    The run views are read-mostly projections of the agent_runs receipt plus links into the existing task views. We intentionally do not duplicate live logs, cost or timeline rendering — the report and acting steps are normal tasks and TaskDetails already renders them; this keeps the UI change small and consistent with "reuse, don't reinvent".

    Polling every 10 s while non-terminal, nudged by existing task:update socket events for the run's task ids, is enough for a run that takes minutes; a dedicated agent-run socket channel is unnecessary in v1.

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

    Why this file: One mapping from run state to label/color used by the list, history and detail.

    import React from 'react';
    import type { AgentRunState } from '@propr/shared';
    
    const STYLES: Record<AgentRunState, [string, string]> = {
      queued: ['Queued', 'bg-slate-100 text-slate-700'], deferred: ['Deferred', 'bg-slate-100 text-slate-700'],
      running: ['Running', 'bg-teal-50 text-teal-700'], report_ready: ['Report ready', 'bg-teal-50 text-teal-700'],
      awaiting_approval: ['Needs review', 'bg-amber-50 text-amber-800'], acting: ['Acting', 'bg-teal-50 text-teal-700'],
      completed: ['Completed', 'bg-green-50 text-green-700'], failed: ['Failed', 'bg-red-50 text-red-700'],
      skipped: ['Skipped', 'bg-slate-100 text-slate-500'], rejected: ['Rejected', 'bg-slate-100 text-slate-500'], cancelled: ['Cancelled', 'bg-slate-100 text-slate-500'],
    };
    
    export default function AgentRunStateBadge({ state }: { state: AgentRunState }) {
      const [label, style] = STYLES[state];
      return <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-semibold ${style}`}>{label}</span>;
    }

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

    Why this file: Run detail + report view + the human half of preview autonomy.

    import React, { useCallback, useEffect, useState } from 'react';
    import { Link } from 'react-router-dom';
    import { TERMINAL_AGENT_RUN_STATES, type AgentRun } from '@propr/shared';
    import { approveAgentRun, cancelAgentRun, getAgentRun, rejectAgentRun } from '../../api/agentDefinitionsApi';
    import MarkdownRenderer from '../TaskDetails/MarkdownRenderer';
    import { SystemAlert } from '../ui/SystemAlert';
    import { useOptionalSocket } from '../../contexts/useSocket';
    import AgentRunStateBadge from './AgentRunStateBadge';
    
    const POLL_MS = 10_000;
    const CANCELLABLE = ['queued', 'deferred', 'running', 'awaiting_approval', 'acting'];
    
    export default function AgentRunDetail({ runId, definitionId }: { runId: string; definitionId: string }) {
      const [run, setRun] = useState<AgentRun | null>(null);
      const [error, setError] = useState<string | null>(null);
      const [note, setNote] = useState('');
      const [busy, setBusy] = useState(false);
      const socket = useOptionalSocket();
    
      const load = useCallback(async () => {
        try { setRun(await getAgentRun(runId)); setError(null); } catch (cause) { setError((cause as Error).message); }
      }, [runId]);
    
      const terminal = run ? (TERMINAL_AGENT_RUN_STATES as readonly string[]).includes(run.state) : false;
      useEffect(() => { void load(); }, [load]);
      useEffect(() => {
        // Poll only while something can still change; terminal runs are immutable.
        if (!run || terminal) return;
        const timer = setInterval(() => { void load(); }, POLL_MS);
        const unsubscribe = socket?.onTaskUpdate?.(payload => {
          if (payload.taskId === run.reportTaskId || payload.taskId === run.actionTaskId) void load();
        });
        return () => { clearInterval(timer); unsubscribe?.(); };
      }, [run, terminal, load, socket]);
    
      async function act(action: () => Promise<AgentRun>, confirmText: string) {
        if (!window.confirm(confirmText)) return;
        setBusy(true);
        try { setRun(await action()); } catch (cause) { setError((cause as Error).message); } finally { setBusy(false); }
      }
    
      if (!run) return error ? <SystemAlert>{error}</SystemAlert> : <div className="p-4 text-sm text-slate-500">Loading run…</div>;
      const reason = run.failureReason ?? run.skipReason;
    
      return (
        <article className="space-y-5 p-4" aria-label="Agent run">
          <Link to={`/agents/${encodeURIComponent(definitionId)}?tab=runs`} className="text-sm text-slate-600 hover:text-slate-900">← Runs</Link>
          <header className="flex flex-wrap items-center gap-3">
            <AgentRunStateBadge state={run.state} />
            <span className="text-sm text-slate-600">{run.trigger}{run.triggerSource ? ` · ${run.triggerSource}` : ''}</span>
            <span className="text-xs text-slate-400">Started {new Date(run.createdAt).toLocaleString()}{run.finishedAt ? ` · finished ${new Date(run.finishedAt).toLocaleString()}` : ''}</span>
            <span className="text-xs text-slate-400">Autonomy: {run.autonomyMode.replace('_', ' ')}</span>
            {CANCELLABLE.includes(run.state) && (
              <button type="button" disabled={busy} className="ml-auto text-sm text-red-600" onClick={() => act(() => cancelAgentRun(run.id), 'Cancel this run?')}>Cancel run</button>
            )}
          </header>
    
          {/* Cost-gate and failure reasons are full sentences written for this banner. */}
          {reason && <SystemAlert>{reason}</SystemAlert>}
    
          {run.state === 'awaiting_approval' && (
            <section className="rounded-md border border-amber-200 bg-amber-50 p-3" aria-label="Approval">
              <p className="text-sm text-amber-900">Approve to let a separate acting agent use ProPR tools (tasks, TODOs, comments) on this agent's repositories based on the report. It cannot merge or change settings.</p>
              <textarea aria-label="Note for the acting agent" maxLength={2000} value={note} onChange={event => setNote(event.target.value)}
                placeholder="Optional guidance, e.g. only create TODOs, no tasks" className="mt-2 w-full rounded border border-amber-200 p-2 text-sm" />
              <div className="mt-2 flex gap-2">
                <button type="button" disabled={busy} className="rounded-md bg-primary-600 px-3 py-1.5 text-sm text-white" onClick={() => act(() => approveAgentRun(run.id, note.trim() || undefined), 'Approve and let the acting agent act on this report?')}>Approve and act</button>
                <button type="button" disabled={busy} className="rounded-md border border-slate-300 px-3 py-1.5 text-sm" onClick={() => act(() => rejectAgentRun(run.id), 'Reject this report? Nothing will be acted on.')}>Reject</button>
              </div>
            </section>
          )}
    
          <section aria-label="Report">
            <div className="mb-2 flex items-center justify-between">
              <h2 className="text-xs font-bold uppercase tracking-widest text-slate-500">Report</h2>
              {run.report && <button type="button" className="text-xs text-slate-500" onClick={() => void navigator.clipboard.writeText(run.report!)}>Copy</button>}
            </div>
            {/* react-markdown without raw HTML: reports are untrusted model output. */}
            {run.report ? <MarkdownRenderer text={run.report} /> : <p className="text-sm text-slate-500">{terminal ? 'This run produced no report.' : 'The report will appear here when the run finishes.'}</p>}
            {run.reportTruncated && <p className="mt-2 text-xs text-slate-500">Report truncated — the full output is in the report task log.</p>}
          </section>
    
          {run.actionSummary && (
            <section aria-label="What the acting agent did">
              <h2 className="mb-2 text-xs font-bold uppercase tracking-widest text-slate-500">What the acting agent did</h2>
              <MarkdownRenderer text={run.actionSummary} />
            </section>
          )}
    
          <footer className="flex gap-4 text-sm">
            {run.reportTaskId && <Link to={`/tasks/${encodeURIComponent(run.reportTaskId)}`} className="text-primary-600">Open report task</Link>}
            {run.actionTaskId && <Link to={`/tasks/${encodeURIComponent(run.actionTaskId)}`} className="text-primary-600">Open acting task</Link>}
          </footer>
        </article>
      );
    }

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

    Why this file: The per-agent run history list.

    import React, { useCallback, useEffect, useState } from 'react';
    import { useNavigate } from 'react-router-dom';
    import type { AgentRun } from '@propr/shared';
    import { listAgentRuns } from '../../api/agentDefinitionsApi';
    import { ListSkeleton } from '../ui/Skeleton';
    import AgentRunStateBadge from './AgentRunStateBadge';
    import { formatDuration, formatRelativeTime } from '../TaskList/utils.tsx';
    
    const TRIGGER_LABEL: Record<string, string> = { manual: 'Run now', schedule: 'Schedule', api: 'API', mcp: 'MCP', cli: 'CLI' };
    
    export default function AgentRunHistory({ definitionId, refreshKey }: { definitionId: string; refreshKey: number }) {
      const [runs, setRuns] = useState<AgentRun[] | null>(null);
      const [nextOffset, setNextOffset] = useState<number | null>(null);
      const navigate = useNavigate();
    
      const load = useCallback(async (offset: number) => {
        const page = await listAgentRuns(definitionId, offset);
        setRuns(current => (offset === 0 ? page.runs : [...(current ?? []), ...page.runs]));
        setNextOffset(page.nextOffset);
      }, [definitionId]);
      useEffect(() => { void load(0); }, [load, refreshKey]);
    
      if (!runs) return <ListSkeleton rows={5} layout="row" label="Loading runs…" />;
      if (!runs.length) return <p className="p-4 text-sm text-slate-500">No runs yet. Use Run now, set a schedule, or trigger it from the API, MCP or CLI.</p>;
      return (
        <div role="table" aria-label="Agent runs" className="divide-y divide-slate-100">
          {runs.map(run => (
            <button key={run.id} type="button" role="row" onClick={() => navigate(`/agents/${encodeURIComponent(definitionId)}/runs/${encodeURIComponent(run.id)}`)}
              className="grid w-full grid-cols-[8rem_7rem_8rem_5rem_1fr] items-center gap-3 px-4 py-2 text-left text-sm hover:bg-slate-50">
              <span title={new Date(run.createdAt).toLocaleString()}>{formatRelativeTime(run.createdAt)}</span>
              <span title={run.triggerSource ?? undefined}>{TRIGGER_LABEL[run.trigger] ?? run.trigger}</span>
              <AgentRunStateBadge state={run.state} />
              <span className="font-mono text-xs text-slate-500">{run.finishedAt ? formatDuration(run.startedAt ?? run.createdAt, run.finishedAt) : '—'}</span>
              <span className="truncate text-slate-600">{run.skipReason ?? run.failureReason ?? ''}</span>
            </button>
          ))}
          {nextOffset !== null && <button type="button" className="w-full py-2 text-sm text-primary-600" onClick={() => void load(nextOffset)}>Load more</button>}
        </div>
      );
    }

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

    Why this file: Attended runs bypass the cost gate, so the UI is where the user is warned before spending near a limit.

    import React, { useState } from 'react';
    import { useNavigate } from 'react-router-dom';
    import type { AgentDefinition } from '@propr/shared';
    import { getAgentCapacity, triggerAgentRun } from '../../api/agentDefinitionsApi';
    import { useDemoMode } from '../../contexts/DemoModeContext';
    
    export default function RunNowButton({ definition, onTriggered }: { definition: AgentDefinition; onTriggered: () => void }) {
      const [busy, setBusy] = useState(false);
      const [error, setError] = useState<string | null>(null);
      const navigate = useNavigate();
      const { isDemoMode } = useDemoMode();
    
      async function run() {
        setBusy(true);
        try {
          const { threshold, capacity } = await getAgentCapacity(definition.id).catch(() => ({ threshold: 0, capacity: { status: 'unknown' as const } }));
          if (capacity.status === 'near_limit') {
            const percent = Math.round(Math.max(capacity.sessionPercent ?? 0, capacity.weeklyPercent ?? 0));
            // Manual runs are allowed through the gate; make the trade-off explicit.
            if (!window.confirm(`${capacity.provider ?? definition.agentAlias} is at ${percent}% of its subscription window (pause threshold ${threshold}%). Run anyway?`)) return;
          }
          const { run: created } = await triggerAgentRun(definition.id);
          onTriggered();
          navigate(`/agents/${encodeURIComponent(definition.id)}/runs/${encodeURIComponent(created.id)}`);
        } catch (cause) { setError((cause as Error).message); } finally { setBusy(false); }
      }
    
      return (
        <>
          <button type="button" disabled={busy || !definition.enabled || isDemoMode} onClick={() => void run()} className="rounded-md bg-primary-600 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-50">Run now</button>
          {error && <span role="alert" className="ml-2 text-xs text-red-600">{error}</span>}
        </>
      );
    }

    Wire into AgentDetail (issue 15): header renders RunNowButton; when runId is present the right pane renders AgentRunDetail instead of the tabs; the Runs tab renders AgentRunHistory. The list (AgentList) receives each definition's last run state from an added lastRun field on the list endpoint (listAgentDefinitions joins the newest agent_runs row per definition — small server change in agentDefinitionStore.listAgentDefinitions).

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

    Why this file: Covers the approval flow and the stop-polling rule.

    import { describe, expect, it, vi, beforeEach } from 'vitest';
    import { fireEvent, render, screen, waitFor } from '@testing-library/react';
    import { MemoryRouter } from 'react-router-dom';
    import AgentRunDetail from './AgentRunDetail';
    import { approveAgentRun, getAgentRun } from '../../api/agentDefinitionsApi';
    
    vi.mock('../../api/agentDefinitionsApi', () => ({ getAgentRun: vi.fn(), approveAgentRun: vi.fn(), rejectAgentRun: vi.fn(), cancelAgentRun: vi.fn() }));
    vi.mock('../../contexts/useSocket', () => ({ useOptionalSocket: () => null }));
    
    const base = { id: 'run-1', definitionId: 'def-1', ownerId: 'u', trigger: 'schedule', triggerSource: null, reportTaskId: 'agent-run-run-1-report', actionTaskId: null, reportTruncated: false, actionSummary: null, skipReason: null, failureReason: null, autonomyMode: 'preview', approvedBy: null, createdAt: '2026-10-06T09:00:00Z', startedAt: null, reportedAt: null, finishedAt: null };
    
    describe('AgentRunDetail', () => {
      beforeEach(() => { vi.spyOn(window, 'confirm').mockReturnValue(true); });
    
      it('renders the report and approves with a note', async () => {
        vi.mocked(getAgentRun).mockResolvedValue({ ...base, state: 'awaiting_approval', report: '## Summary\nTwo new bugs.' } as never);
        vi.mocked(approveAgentRun).mockResolvedValue({ ...base, state: 'acting', report: '## Summary\nTwo new bugs.' } as never);
        render(<MemoryRouter><AgentRunDetail runId="run-1" definitionId="def-1" /></MemoryRouter>);
        expect(await screen.findByText('Two new bugs.')).toBeInTheDocument();
        fireEvent.change(screen.getByLabelText('Note for the acting agent'), { target: { value: 'Only TODOs' } });
        fireEvent.click(screen.getByRole('button', { name: 'Approve and act' }));
        await waitFor(() => expect(approveAgentRun).toHaveBeenCalledWith('run-1', 'Only TODOs'));
        expect(screen.queryByRole('button', { name: 'Approve and act' })).not.toBeInTheDocument();
      });
    
      it('shows the cost-gate reason for a skipped run', async () => {
        vi.mocked(getAgentRun).mockResolvedValue({ ...base, state: 'skipped', report: null, skipReason: 'Skipped: weekly subscription usage for claude is at 93% (pause threshold 90%).' } as never);
        render(<MemoryRouter><AgentRunDetail runId="run-1" definitionId="def-1" /></MemoryRouter>);
        expect(await screen.findByText(/weekly subscription usage/)).toBeInTheDocument();
      });
    });
  2. propr-dev commented on Oct 7, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using claude agent with claude-opus-5-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-5
    • Branch: 2815/claude-opus-5-5-agents-v1-16-17-web-ui-ru-20261007-1500-60s
    • Base Branch: 2800-epic-agents-v1-y7t
    • Worktree: issue-2815-20261007-1500-claude-opus-5-5-60s

    🔍 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