Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(conversations): restore background activity rows in processes panel

Steven Enamakel9f6dd5f49732
diff --git a/app/src/features/conversations/components/BackgroundActivityRows.tsx b/app/src/features/conversations/components/BackgroundActivityRows.tsx
deleted file mode 100644
index 776af649e4..0000000000
--- a/app/src/features/conversations/components/BackgroundActivityRows.tsx
+++ /dev/null
@@ -1,215 +0,0 @@
-import Badge, { type BadgeVariant } from '../../../components/ui/Badge';
-import { useT } from '../../../lib/i18n/I18nContext';
-import type { CoreCronJob, CoreCronSchedule } from '../../../utils/tauriCommands/cron';
-import type { MemorySyncStatusRow } from '../../../utils/tauriCommands/memoryTree';
-import type { MemorySyncSummary } from '../hooks/useBackgroundActivity';
-import { formatRelativeTime, formatResetTime } from '../utils/format';
-
-/** Small, grey section divider shared across the background-activity sections. */
-export function SectionHeader({ title, hint }: { title: string; hint?: string }) {
- return (
- <div className="flex items-center justify-between px-2.5 pb-1 pt-3">
- <span className="text-[11px] font-semibold uppercase tracking-wide text-content-faint">
- {title}
- </span>
- {hint ? <span className="text-[11px] text-content-faint">{hint}</span> : null}
- </div>
- );
-}
-
-/** A coloured status dot. */
-function Dot({ className }: { className: string }) {
- return <span className={`mt-1.5 h-2 w-2 shrink-0 rounded-full ${className}`} />;
-}
-
-/** Localised, human-readable summary of a cron schedule. */
-function scheduleLabel(schedule: CoreCronSchedule, t: ReturnType<typeof useT>['t']): string {
- switch (schedule.kind) {
- case 'cron':
- return t('conversations.backgroundTasks.cronSchedCron').replace('{expr}', schedule.expr);
- case 'every':
- return t('conversations.backgroundTasks.cronSchedEvery').replace(
- '{duration}',
- formatDuration(schedule.every_ms)
- );
- case 'at':
- return t('conversations.backgroundTasks.cronSchedAt');
- default:
- return '';
- }
-}
-
-function formatDuration(ms: number): string {
- const mins = Math.round(ms / 60_000);
- if (mins < 60) return `${mins}m`;
- const hours = Math.round(mins / 60);
- if (hours < 24) return `${hours}h`;
- return `${Math.round(hours / 24)}d`;
-}
-
-/** One read-only scheduled (cron) job. */
-export function CronJobRow({ job }: { job: CoreCronJob }) {
- const { t } = useT();
- const name =
- (job.name && job.name.trim()) ||
- (job.prompt && job.prompt.trim()) ||
- (job.command && job.command.trim()) ||
- t('conversations.backgroundTasks.cronUnnamed');
-
- // `coral`, not a raw `red-*` scale: a raw palette value does not follow a
- // user's custom theme, and every other failure surface here is coral.
- const lastDot =
- job.last_status === 'error'
- ? 'bg-coral-500'
- : job.last_status === 'ok'
- ? 'bg-sage-500'
- : 'bg-surface-strong';
-
- const lastLabel = job.last_run
- ? t('conversations.backgroundTasks.cronLast').replace(
- '{time}',
- formatRelativeTime(job.last_run)
- )
- : t('conversations.backgroundTasks.cronNever');
-
- return (
- <div
- data-testid="background-cron-row"
- className={`mb-1 flex items-start gap-2.5 rounded-lg px-2.5 py-2 ${
- job.enabled ? '' : 'opacity-50'
- }`}>
- <Dot className={lastDot} />
- <div className="min-w-0 flex-1">
- <div className="flex items-center justify-between gap-2">
- <span className="truncate text-sm font-medium text-content">{name}</span>
- {job.enabled ? (
- <span className="shrink-0 text-[11px] text-content-faint">
- {job.next_run
- ? t('conversations.backgroundTasks.cronNext').replace(
- '{time}',
- formatResetTime(job.next_run)
- )
- : ''}
- </span>
- ) : (
- <Badge className="shrink-0 rounded-full">
- {t('conversations.backgroundTasks.cronPaused')}
- </Badge>
- )}
- </div>
- <span className="mt-0.5 block truncate text-[12px] text-content-muted">
- {scheduleLabel(job.schedule, t)}
- </span>
- <span className="mt-0.5 block text-[11px] text-content-faint">{lastLabel}</span>
- </div>
- </div>
- );
-}
-
-/**
- * Per-provider status pill, driven *only* by freshness (recency of the last
- * ingested chunk). Deliberately NOT keyed off `batch_total > batch_processed`:
- * an incomplete embedding wave can sit un-drained for days, and treating that
- * as "Syncing now" falsely implies live activity. A stalled backlog is
- * surfaced separately as a muted progress hint — see {@link MemorySection}.
- */
-function providerFreshnessLabel(
- row: MemorySyncStatusRow,
- t: ReturnType<typeof useT>['t']
-): { dot: string; label: string; variant: BadgeVariant } {
- if (row.freshness === 'active') {
- return {
- dot: 'bg-amber-500 animate-pulse',
- label: t('conversations.backgroundTasks.memProviderActive'),
- variant: 'warning',
- };
- }
- if (row.freshness === 'recent') {
- return {
- dot: 'bg-sage-500',
- label: t('conversations.backgroundTasks.memProviderRecent'),
- variant: 'success',
- };
- }
- return {
- dot: 'bg-surface-strong',
- label: t('conversations.backgroundTasks.memProviderIdle'),
- variant: 'neutral',
- };
-}
-
-/** Memory ingestion worker row + per-provider freshness rows. */
-export function MemorySection({ memory }: { memory: MemorySyncSummary }) {
- const { t } = useT();
- const hasActivity = memory.ingesting || memory.queueDepth > 0 || memory.providers.length > 0;
-
- if (!hasActivity) {
- return (
- <div className="px-2.5 py-2 text-[12px] text-content-faint">
- {t('conversations.backgroundTasks.memUpToDate')}
- </div>
- );
- }
-
- return (
- <div>
- {memory.ingesting ? (
- <div
- data-testid="background-memory-ingesting"
- className="mb-1 flex items-start gap-2.5 rounded-lg px-2.5 py-2">
- <Dot className="bg-amber-500 animate-pulse" />
- <div className="min-w-0 flex-1">
- <span className="block truncate text-sm font-medium text-content">
- {memory.currentTitle
- ? t('conversations.backgroundTasks.memIngesting').replace(
- '{title}',
- memory.currentTitle
- )
- : t('conversations.backgroundTasks.memIngestingUntitled')}
- </span>
- {memory.queueDepth > 0 ? (
- <span className="mt-0.5 block text-[11px] text-content-faint">
- {t('conversations.backgroundTasks.memQueued').replace(
- '{count}',
- String(memory.queueDepth)
- )}
- </span>
- ) : null}
- </div>
- </div>
- ) : null}
-
- {memory.providers.map(row => {
- const f = providerFreshnessLabel(row, t);
- // An incomplete embedding wave that is NOT live (freshness !== active):
- // a backlog the index worker hasn't drained, shown as muted progress —
- // never as "Syncing now".
- const backlog =
- row.freshness !== 'active' && row.batch_total > row.batch_processed
- ? `${row.batch_processed}/${row.batch_total} indexed`
- : null;
- return (
- <div
- key={row.provider}
- data-testid="background-memory-provider-row"
- className="mb-1 flex items-start gap-2.5 rounded-lg px-2.5 py-2">
- <Dot className={f.dot} />
- <div className="min-w-0 flex-1">
- <div className="flex items-center justify-between gap-2">
- <span className="truncate text-sm font-medium capitalize text-content">
- {row.provider}
- </span>
- <Badge variant={f.variant} className="shrink-0 rounded-full">
- {f.label}
- </Badge>
- </div>
- {backlog ? (
- <span className="mt-0.5 block text-[11px] text-content-faint">{backlog}</span>
- ) : null}
- </div>
- </div>
- );
- })}
- </div>
- );
-}
diff --git a/app/src/features/conversations/components/BackgroundProcessesPanel.tsx b/app/src/features/conversations/components/BackgroundProcessesPanel.tsx
deleted file mode 100644
index bf2f057cad..0000000000
--- a/app/src/features/conversations/components/BackgroundProcessesPanel.tsx
+++ /dev/null
@@ -1,272 +0,0 @@
-import createDebug from 'debug';
-
-import Badge, { type BadgeVariant } from '../../../components/ui/Badge';
-import Button from '../../../components/ui/Button';
-import { SheetContent, SheetRoot, SheetTitle } from '../../../components/ui/Sheet';
-import { useT } from '../../../lib/i18n/I18nContext';
-import type {
- SubagentActivity,
- ToolTimelineEntry,
- ToolTimelineEntryStatus,
-} from '../../../store/chatRuntimeSlice';
-import { useBackgroundActivity } from '../hooks/useBackgroundActivity';
-import { CronJobRow, MemorySection, SectionHeader } from './BackgroundActivityRows';
-
-const log = createDebug('app:conversations:background-processes');
-
-/**
- * A background process = a *detached* sub-agent spawned with
- * `spawn_async_subagent` (a fire-and-forget tokio task that keeps running after
- * the parent turn returns). The backend marks these with `mode: "async"` on the
- * `SubagentSpawned` event (every blocking spawn emits `mode: "typed"`), and the
- * frontend carries it through on {@link SubagentActivity.mode}. So the whole
- * "is this truly in the background?" question reduces to `mode === 'async'`.
- */
-export interface BackgroundProcess {
- taskId: string;
- name: string;
- goal: string;
- status: ToolTimelineEntryStatus;
- toolCount: number;
- iterations?: number;
-}
-
-const subagentName = (s: SubagentActivity): string =>
- (s.displayName && s.displayName.trim()) || s.agentId || 'sub-agent';
-
-/**
- * Pure selector: the detached background sub-agents spawned in a thread,
- * newest-relevant first, deduped by spawn `taskId`. Driven off the same tool
- * timeline the inline rows use, so a process opened here resolves to the
- * exact same entry in the Agent Process Source panel.
- */
-export function selectBackgroundProcesses(timeline: ToolTimelineEntry[]): BackgroundProcess[] {
- const seen = new Set<string>();
- const out: BackgroundProcess[] = [];
- for (const entry of timeline) {
- const sub = entry.subagent;
- if (!sub || sub.mode !== 'async') continue;
- if (seen.has(sub.taskId)) continue;
- seen.add(sub.taskId);
- out.push({
- taskId: sub.taskId,
- name: subagentName(sub),
- goal: (sub.prompt ?? '').trim(),
- status: entry.status,
- toolCount: sub.toolCalls?.length ?? 0,
- iterations: sub.iterations,
- });
- }
- // Running first, so live work stays at the top of the list.
- return out.sort((a, b) => Number(b.status === 'running') - Number(a.status === 'running'));
-}
-
-type StatusLabelKey =
- | 'conversations.backgroundTasks.statusRunning'
- | 'conversations.backgroundTasks.statusDone'
- | 'conversations.backgroundTasks.statusFailed'
- | 'conversations.backgroundTasks.statusNeedsYou'
- | 'conversations.backgroundTasks.statusCancelled';
-
-/**
- * Dot fill + label key + shared {@link Badge} tone for one process status.
- *
- * The `error` / `awaiting_user` cases used raw Tailwind palette scales
- * (`bg-red-500`, `text-blue-700`) that do not follow a user's theme; they are
- * the semantic `coral` / `primary` tokens now, which is what every other
- * status surface in the conversation panel already used.
- */
-function statusStyle(status: ToolTimelineEntryStatus): {
- dot: string;
- labelKey: StatusLabelKey;
- variant: BadgeVariant;
-} {
- switch (status) {
- case 'running':
- return {
- dot: 'bg-amber-500 animate-pulse',
- labelKey: 'conversations.backgroundTasks.statusRunning',
- variant: 'warning',
- };
- case 'error':
- return {
- dot: 'bg-coral-500',
- labelKey: 'conversations.backgroundTasks.statusFailed',
- variant: 'danger',
- };
- case 'awaiting_user':
- return {
- dot: 'bg-primary-500',
- labelKey: 'conversations.backgroundTasks.statusNeedsYou',
- variant: 'primary',
- };
- case 'cancelled':
- return {
- dot: 'bg-content-faint',
- labelKey: 'conversations.backgroundTasks.statusCancelled',
- variant: 'neutral',
- };
- default:
- return {
- dot: 'bg-sage-500',
- labelKey: 'conversations.backgroundTasks.statusDone',
- variant: 'success',
- };
- }
-}
-
-interface BackgroundProcessesPanelProps {
- open: boolean;
- processes: BackgroundProcess[];
- onClose: () => void;
- onOpenProcess: (taskId: string) => void;
-}
-
-/**
- * Right side-drawer listing the thread's detached background sub-agents. Each
- * row opens the Agent Process Source panel (via `onOpenProcess`), scoped to
- * that task's step, for the full activity — this panel is purely the
- * launcher/overview.
- */
-export function BackgroundProcessesPanel({
- open,
- processes,
- onClose,
- onOpenProcess,
-}: BackgroundProcessesPanelProps) {
- const { t } = useT();
- // Cron jobs + memory syncing — fetched only while open.
- const activity = useBackgroundActivity(open);
-
- if (!open) return null;
-
- const running = processes.filter(p => p.status === 'running').length;
- const runningLabel =
- running > 0
- ? t('conversations.backgroundTasks.running').replace('{count}', String(running))
- : t('conversations.backgroundTasks.noneRunning');
- const totalLabel = t('conversations.backgroundTasks.total').replace(
- '{count}',
- String(processes.length)
- );
-
- log(
- 'render panel processes=%d running=%d cron=%d',
- processes.length,
- running,
- activity.cronJobs.length
- );
-
- // The overlay is the shared Radix-backed `Sheet`: the hand-rolled portal +
- // backdrop `<div onClick>` + `keydown` listener it replaced had no focus
- // trap, no scroll lock, no focus restore, and a backdrop that was not
- // keyboard-reachable at all. `open` is hard-coded because the early return
- // above already renders nothing when closed — `onOpenChange` routes Escape /
- // outside-click back to the caller's `onClose`.
- return (
- <SheetRoot
- open
- onOpenChange={next => {
- if (!next) onClose();
- }}>
- <SheetContent
- side="right"
- aria-describedby={undefined}
- data-testid="background-processes-panel"
- className="max-w-sm">
- <header className="flex shrink-0 items-center justify-between border-b border-line-subtle px-4 py-3">
- <div className="flex flex-col">
- {/* `asChild` keeps the historical h2 so the heading role and its
- accessible name are unchanged. */}
- <SheetTitle asChild>
- <h2 className="text-sm font-semibold text-content">
- {t('conversations.backgroundTasks.title')}
- </h2>
- </SheetTitle>
- <span className="text-[11px] text-content-faint">
- {runningLabel} · {totalLabel}
- </span>
- </div>
- <Button
- iconOnly
- variant="tertiary"
- size="sm"
- aria-label={t('conversations.backgroundTasks.close')}
- onClick={onClose}>
- <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M6 18L18 6M6 6l12 12"
- />
- </svg>
- </Button>
- </header>
-
- <div className="flex-1 overflow-y-auto p-2">
- {/* Section 1 — detached sub-agents spawned in this chat. */}
- <SectionHeader title={t('conversations.backgroundTasks.sectionThisChat')} />
- {processes.length === 0 ? (
- <div className="px-2.5 py-2 text-[12px] text-content-faint">
- {t('conversations.backgroundTasks.empty')}
- </div>
- ) : (
- processes.map(p => {
- const s = statusStyle(p.status);
- const toolCallLabel = (
- p.toolCount === 1
- ? t('conversations.backgroundTasks.toolCallOne')
- : t('conversations.backgroundTasks.toolCallOther')
- ).replace('{count}', String(p.toolCount));
- return (
- <button
- key={p.taskId}
- type="button"
- data-testid="background-process-row"
- onClick={() => onOpenProcess(p.taskId)}
- className="mb-1 flex w-full items-start gap-2.5 rounded-lg px-2.5 py-2 text-left hover:bg-surface-hover">
- <span className={`mt-1.5 h-2 w-2 shrink-0 rounded-full ${s.dot}`} />
- <span className="min-w-0 flex-1">
- <span className="flex items-center justify-between gap-2">
- <span className="truncate text-sm font-medium text-content">{p.name}</span>
- <Badge variant={s.variant} className="shrink-0 rounded-full">
- {t(s.labelKey)}
- </Badge>
- </span>
- {p.goal ? (
- <span className="mt-0.5 line-clamp-2 block text-[12px] text-content-muted">
- {p.goal}
- </span>
- ) : null}
- <span className="mt-0.5 block text-[11px] text-content-faint">
- {toolCallLabel}
- {typeof p.iterations === 'number'
- ? ` · ${t('conversations.backgroundTasks.steps').replace('{count}', String(p.iterations))}`
- : ''}{' '}
- · {t('conversations.backgroundTasks.viewDetails')}
- </span>
- </span>
- </button>
- );
- })
- )}
-
- {/* Section 2 — scheduled (cron) jobs, global, view-only. */}
- <SectionHeader title={t('conversations.backgroundTasks.sectionScheduled')} />
- {activity.cronJobs.length === 0 ? (
- <div className="px-2.5 py-2 text-[12px] text-content-faint">
- {t('conversations.backgroundTasks.cronEmpty')}
- </div>
- ) : (
- activity.cronJobs.map(job => <CronJobRow key={job.id} job={job} />)
- )}
-
- {/* Section 4 — memory syncing / ingestion. */}
- <SectionHeader title={t('conversations.backgroundTasks.sectionMemory')} />
- <MemorySection memory={activity.memory} />
- </div>
- </SheetContent>
- </SheetRoot>
- );
-}
diff --git a/app/src/features/conversations/components/__tests__/BackgroundActivityRows.test.tsx b/app/src/features/conversations/components/__tests__/BackgroundActivityRows.test.tsx
deleted file mode 100644
index 25c62638d3..0000000000
--- a/app/src/features/conversations/components/__tests__/BackgroundActivityRows.test.tsx
+++ /dev/null
@@ -1,152 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { describe, expect, it } from 'vitest';
-
-import type { CoreCronJob } from '../../../../utils/tauriCommands/cron';
-import type { MemorySyncStatusRow } from '../../../../utils/tauriCommands/memoryTree';
-import type { MemorySyncSummary } from '../../hooks/useBackgroundActivity';
-import { CronJobRow, MemorySection } from '../BackgroundActivityRows';
-
-function cronJob(partial: Partial<CoreCronJob> & { id: string }): CoreCronJob {
- return {
- expression: '',
- schedule: { kind: 'cron', expr: '0 9 * * *' },
- command: '',
- job_type: 'agent',
- session_target: 'isolated',
- enabled: true,
- delivery: { mode: 'silent', best_effort: true },
- delete_after_run: false,
- created_at: '2024-01-01T00:00:00Z',
- next_run: '2999-01-01T00:00:00Z',
- ...partial,
- };
-}
-
-describe('CronJobRow', () => {
- it('renders an enabled job with name, schedule and a next-run hint', () => {
- render(<CronJobRow job={cronJob({ id: 'j1', name: 'Daily standup' })} />);
- expect(screen.getByText('Daily standup')).toBeInTheDocument();
- expect(screen.getByText(/0 9 \* \* \*/)).toBeInTheDocument();
- // formatResetTime renders a future "in …" hint for an enabled job.
- expect(screen.getByText(/^Next in /)).toBeInTheDocument();
- expect(screen.queryByText('Paused')).not.toBeInTheDocument();
- });
-
- it('falls back to the prompt, then command, then a generic title', () => {
- const { rerender } = render(
- <CronJobRow job={cronJob({ id: 'j2', prompt: 'summarize my inbox' })} />
- );
- expect(screen.getByText('summarize my inbox')).toBeInTheDocument();
-
- rerender(<CronJobRow job={cronJob({ id: 'j3', command: 'echo hi' })} />);
- expect(screen.getByText('echo hi')).toBeInTheDocument();
-
- rerender(<CronJobRow job={cronJob({ id: 'j4' })} />);
- expect(screen.getByText('Untitled job')).toBeInTheDocument();
- });
-
- it('marks a disabled job as Paused and shows the never-run state', () => {
- const { container } = render(
- <CronJobRow job={cronJob({ id: 'j5', name: 'Paused job', enabled: false })} />
- );
- expect(screen.getByText('Paused')).toBeInTheDocument();
- expect(screen.getByText('Hasn’t run yet')).toBeInTheDocument();
- expect(container.querySelector('[data-testid="background-cron-row"]')?.className).toContain(
- 'opacity-50'
- );
- });
-
- it('summarizes "every" and "at" schedules', () => {
- const { rerender } = render(
- <CronJobRow
- job={cronJob({
- id: 'e1',
- name: 'Interval',
- schedule: { kind: 'every', every_ms: 900_000 },
- })}
- />
- );
- expect(screen.getByText('Every 15m')).toBeInTheDocument();
-
- rerender(
- <CronJobRow
- job={cronJob({
- id: 'a1',
- name: 'One-off run',
- schedule: { kind: 'at', at: '2999-01-01T00:00:00Z' },
- })}
- />
- );
- expect(screen.getByText('One-off run')).toBeInTheDocument();
- expect(screen.getByText('Once')).toBeInTheDocument();
- });
-});
-
-describe('MemorySection', () => {
- function provider(
- partial: Partial<MemorySyncStatusRow> & { provider: string }
- ): MemorySyncStatusRow {
- return {
- chunks_synced: 0,
- chunks_pending: 0,
- batch_total: 0,
- batch_processed: 0,
- last_chunk_at_ms: null,
- freshness: 'idle',
- ...partial,
- };
- }
-
- it('renders the up-to-date empty state when nothing is happening', () => {
- const memory: MemorySyncSummary = { ingesting: false, queueDepth: 0, providers: [] };
- render(<MemorySection memory={memory} />);
- expect(screen.getByText('All memories up to date')).toBeInTheDocument();
- });
-
- it('renders the ingesting row and per-provider freshness', () => {
- const memory: MemorySyncSummary = {
- ingesting: true,
- currentTitle: 'Team channel',
- queueDepth: 2,
- providers: [
- provider({ provider: 'slack', freshness: 'active' }),
- provider({ provider: 'gmail', freshness: 'recent' }),
- provider({ provider: 'notion', freshness: 'idle' }),
- ],
- };
- render(<MemorySection memory={memory} />);
- expect(screen.getByText('Indexing Team channel')).toBeInTheDocument();
- expect(screen.getByText('2 queued')).toBeInTheDocument();
- expect(screen.getByText('slack')).toBeInTheDocument();
- expect(screen.getByText('Syncing now')).toBeInTheDocument();
- expect(screen.getByText('Synced recently')).toBeInTheDocument();
- expect(screen.getByText('Idle')).toBeInTheDocument();
- });
-
- it('does NOT call a stale, un-drained backlog "Syncing now" (idle freshness)', () => {
- // Regression: a fetch wave from days ago whose chunks never finished
- // embedding (batch_total > batch_processed) is a backlog, not live activity.
- const memory: MemorySyncSummary = {
- ingesting: false,
- queueDepth: 0,
- providers: [
- provider({ provider: 'gmail', freshness: 'idle', batch_total: 18, batch_processed: 0 }),
- ],
- };
- render(<MemorySection memory={memory} />);
- expect(screen.queryByText('Syncing now')).not.toBeInTheDocument();
- expect(screen.getByText('Idle')).toBeInTheDocument();
- // The incomplete wave is surfaced as a muted, non-alarming progress hint.
- expect(screen.getByText('0/18 indexed')).toBeInTheDocument();
- });
-
- it('still shows "Syncing now" for genuinely live (active) freshness', () => {
- const memory: MemorySyncSummary = {
- ingesting: false,
- queueDepth: 0,
- providers: [provider({ provider: 'slack', freshness: 'active' })],
- };
- render(<MemorySection memory={memory} />);
- expect(screen.getByText('Syncing now')).toBeInTheDocument();
- });
-});
diff --git a/app/src/features/conversations/components/__tests__/BackgroundProcessesPanel.test.tsx b/app/src/features/conversations/components/__tests__/BackgroundProcessesPanel.test.tsx
deleted file mode 100644
index d275f0c935..0000000000
--- a/app/src/features/conversations/components/__tests__/BackgroundProcessesPanel.test.tsx
+++ /dev/null
@@ -1,198 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import userEvent from '@testing-library/user-event';
-import { describe, expect, it, vi } from 'vitest';
-
-import type {
- SubagentActivity,
- ToolTimelineEntry,
- ToolTimelineEntryStatus,
-} from '../../../../store/chatRuntimeSlice';
-import {
- type BackgroundProcess,
- BackgroundProcessesPanel,
- selectBackgroundProcesses,
-} from '../BackgroundProcessesPanel';
-
-function sub(partial: Partial<SubagentActivity> & { taskId: string }): SubagentActivity {
- return { agentId: 'researcher', toolCalls: [], ...partial };
-}
-
-function entry(
- status: ToolTimelineEntryStatus,
- subagent?: SubagentActivity,
- name = 'subagent:researcher'
-): ToolTimelineEntry {
- return { id: `e-${subagent?.taskId ?? name}`, name, round: 0, seq: 0, status, subagent };
-}
-
-describe('selectBackgroundProcesses', () => {
- it('keeps only detached (mode==="async") sub-agents', () => {
- const timeline: ToolTimelineEntry[] = [
- entry('running', sub({ taskId: 'sub-async', mode: 'async', prompt: 'research towers' })),
- entry('running', sub({ taskId: 'sub-typed', mode: 'typed', prompt: 'inline work' })),
- entry('success', undefined, 'web_search'), // non-subagent tool row
- ];
- const out = selectBackgroundProcesses(timeline);
- expect(out.map(p => p.taskId)).toEqual(['sub-async']);
- expect(out[0].goal).toBe('research towers');
- });
-
- it('dedupes by taskId and sorts running first', () => {
- const timeline: ToolTimelineEntry[] = [
- entry('success', sub({ taskId: 'sub-done', mode: 'async' })),
- entry('running', sub({ taskId: 'sub-live', mode: 'async' })),
- entry('running', sub({ taskId: 'sub-live', mode: 'async' })), // duplicate row
- ];
- const out = selectBackgroundProcesses(timeline);
- expect(out.map(p => p.taskId)).toEqual(['sub-live', 'sub-done']); // running first, deduped
- });
-
- it('derives name, tool count and steps', () => {
- const out = selectBackgroundProcesses([
- entry(
- 'running',
- sub({
- taskId: 'sub-1',
- mode: 'async',
- displayName: 'Researcher',
- iterations: 3,
- toolCalls: [
- { callId: 'a', toolName: 't', status: 'success' },
- { callId: 'b', toolName: 't', status: 'success' },
- ],
- })
- ),
- ]);
- expect(out[0]).toMatchObject({
- name: 'Researcher',
- toolCount: 2,
- iterations: 3,
- status: 'running',
- });
- });
-});
-
-describe('BackgroundProcessesPanel', () => {
- const procs: BackgroundProcess[] = [
- {
- taskId: 'sub-1',
- name: 'Researcher',
- goal: 'research the Eiffel Tower',
- status: 'running',
- toolCount: 16,
- },
- {
- taskId: 'sub-2',
- name: 'Archivist',
- goal: 'summarize notes',
- status: 'success',
- toolCount: 4,
- },
- ];
-
- it('renders nothing when closed', () => {
- render(
- <BackgroundProcessesPanel
- open={false}
- processes={procs}
- onClose={vi.fn()}
- onOpenProcess={vi.fn()}
- />
- );
- // Asserted against document.body, not the render container: the panel
- // portals, so an empty container would pass even if it had rendered.
- expect(document.body.querySelector('[data-testid="background-processes-panel"]')).toBeNull();
- });
-
- it('lists processes and opens one on click', async () => {
- const onOpenProcess = vi.fn();
- render(
- <BackgroundProcessesPanel
- open
- processes={procs}
- onClose={vi.fn()}
- onOpenProcess={onOpenProcess}
- />
- );
- const rows = screen.getAllByTestId('background-process-row');
- expect(rows).toHaveLength(2);
- expect(screen.getByText('Researcher')).toBeInTheDocument();
- expect(screen.getByText('research the Eiffel Tower')).toBeInTheDocument();
-
- await userEvent.click(rows[0]);
- expect(onOpenProcess).toHaveBeenCalledWith('sub-1');
- });
-
- it('shows an empty state when there are no background tasks', () => {
- render(
- <BackgroundProcessesPanel open processes={[]} onClose={vi.fn()} onOpenProcess={vi.fn()} />
- );
- expect(screen.getByText(/No background tasks in this chat/i)).toBeInTheDocument();
- });
-
- it('renders every status variant (running / done / failed / needs-you / cancelled)', () => {
- const all: BackgroundProcess[] = [
- { taskId: 'r', name: 'R', goal: 'g', status: 'running', toolCount: 2 },
- { taskId: 'd', name: 'D', goal: 'g', status: 'success', toolCount: 2 },
- { taskId: 'e', name: 'E', goal: 'g', status: 'error', toolCount: 2 },
- { taskId: 'a', name: 'A', goal: 'g', status: 'awaiting_user', toolCount: 2 },
- { taskId: 'c', name: 'C', goal: 'g', status: 'cancelled', toolCount: 2 },
- ];
- render(
- <BackgroundProcessesPanel open processes={all} onClose={vi.fn()} onOpenProcess={vi.fn()} />
- );
- expect(screen.getByText('Running')).toBeInTheDocument();
- expect(screen.getByText('Done')).toBeInTheDocument();
- expect(screen.getByText('Failed')).toBeInTheDocument();
- expect(screen.getByText('Needs you')).toBeInTheDocument();
- expect(screen.getByText('Cancelled')).toBeInTheDocument();
- });
-
- it('renders singular tool-call wording, step count, and suppresses an empty goal', () => {
- const rows: BackgroundProcess[] = [
- {
- taskId: 'g',
- name: 'WithGoal',
- goal: 'investigate the bridge',
- status: 'success',
- toolCount: 4,
- },
- { taskId: 's1', name: 'NoGoal', goal: '', status: 'running', toolCount: 1, iterations: 3 },
- ];
- render(
- <BackgroundProcessesPanel open processes={rows} onClose={vi.fn()} onOpenProcess={vi.fn()} />
- );
- // The panel portals to document.body, so it is not inside `container`.
- // Scoped to the panel root so unrelated body content cannot satisfy this.
- const panel = document.body.querySelector('[data-testid="background-processes-panel"]');
- expect(panel).not.toBeNull();
- expect(panel!.textContent).toContain('1 tool call'); // singular branch (NoGoal row)
- expect(panel!.textContent).toContain('3 steps'); // iterations branch
- // The goal renders for the row that has one; the goal-less row adds no copy.
- expect(screen.getAllByText('investigate the bridge')).toHaveLength(1);
- });
-
- it('closes on Escape', () => {
- const onClose = vi.fn();
- render(
- <BackgroundProcessesPanel open processes={procs} onClose={onClose} onOpenProcess={vi.fn()} />
- );
- // Radix's dismissable layer listens on the owning `document`, not on
- // `window` — an event dispatched on `window` never reaches `document`.
- fireEvent.keyDown(document, { key: 'Escape' });
- expect(onClose).toHaveBeenCalled();
- });
-
- it('renders the broader activity sections (cron + memory) alongside sub-agents', () => {
- // Outside Tauri the activity hook is a no-op, so these sections fall back to
- // their empty states — which is exactly what we assert here.
- render(
- <BackgroundProcessesPanel open processes={procs} onClose={vi.fn()} onOpenProcess={vi.fn()} />
- );
- expect(screen.getByText('In this chat')).toBeInTheDocument();
- expect(screen.getByText('Scheduled jobs')).toBeInTheDocument();
- expect(screen.getByText('No scheduled jobs.')).toBeInTheDocument();
- expect(screen.getByText('Memory syncing')).toBeInTheDocument();
- expect(screen.getByText('All memories up to date')).toBeInTheDocument();
- });
-});
diff --git a/app/src/pages/dev/ToolCallGallery.tsx b/app/src/pages/dev/ToolCallGallery.tsx
index 380ebb6ba1..5af6821d8d 100644
--- a/app/src/pages/dev/ToolCallGallery.tsx
+++ b/app/src/pages/dev/ToolCallGallery.tsx
@@ -227,6 +227,9 @@ export default function ToolCallGallery() {
const [searchQuery, setSearchQuery] = useState('deploy');
const [searchActive, setSearchActive] = useState(0);
const [citationOpen, setCitationOpen] = useState<number | null>(null);
+ const [connectionPhase, setConnectionPhase] = useState<(typeof MOCK_CONNECTION_PHASES)[number]>(
+ MOCK_CONNECTION_PHASES[0]
+ );
return (
<div className="bg-background text-foreground min-h-screen overflow-auto p-8">
<div className="mx-auto flex max-w-3xl flex-col gap-10">