Skip to content

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

chore: migrate test files to co-located `__tests__` directories

Steven Enamakelb59f754ba52a
diff --git a/app/src/components/ProgressIndicator.tsx b/app/src/components/ProgressIndicator.tsx
deleted file mode 100644
index 9b314fb87a..0000000000
--- a/app/src/components/ProgressIndicator.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import { useT } from '../lib/i18n/I18nContext';
-
-interface ProgressIndicatorProps {
- currentStep: number;
- totalSteps: number;
-}
-
-const ProgressIndicator = ({ currentStep, totalSteps }: ProgressIndicatorProps) => {
- const { t } = useT();
- return (
- <div
- role="list"
- aria-label={t('progress.stepsAria')}
- className="flex items-center justify-center space-x-2">
- {Array.from({ length: totalSteps }).map((_, index) => {
- const isCurrent = index === currentStep;
- return (
- <div
- key={index}
- role="listitem"
- aria-label={t('progress.stepAria')
- .replace('{current}', String(index + 1))
- .replace('{total}', String(totalSteps))}
- aria-current={isCurrent ? 'step' : undefined}
- className={`w-2 h-2 rounded-full transition-colors ${
- isCurrent ? 'bg-stone-800' : 'bg-stone-300'
- }`}
- />
- );
- })}
- </div>
- );
-};
-
-export default ProgressIndicator;
diff --git a/app/src/components/__tests__/ProgressIndicator.test.tsx b/app/src/components/__tests__/ProgressIndicator.test.tsx
deleted file mode 100644
index 33dc635468..0000000000
--- a/app/src/components/__tests__/ProgressIndicator.test.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { describe, expect, it } from 'vitest';
-
-import ProgressIndicator from '../ProgressIndicator';
-
-describe('ProgressIndicator', () => {
- it('renders the correct number of step dots', () => {
- render(<ProgressIndicator currentStep={0} totalSteps={3} />);
- const items = screen.getAllByRole('listitem');
- expect(items).toHaveLength(3);
- });
-
- it('container has role="list" and aria-label', () => {
- render(<ProgressIndicator currentStep={1} totalSteps={4} />);
- const list = screen.getByRole('list');
- expect(list).toBeInTheDocument();
- expect(list).toHaveAttribute('aria-label', 'Progress steps');
- });
-
- it('each step has an accessible label', () => {
- render(<ProgressIndicator currentStep={0} totalSteps={3} />);
- expect(screen.getByRole('listitem', { name: 'Step 1 of 3' })).toBeInTheDocument();
- expect(screen.getByRole('listitem', { name: 'Step 2 of 3' })).toBeInTheDocument();
- expect(screen.getByRole('listitem', { name: 'Step 3 of 3' })).toBeInTheDocument();
- });
-
- it('marks the current step with aria-current="step"', () => {
- render(<ProgressIndicator currentStep={1} totalSteps={3} />);
- const currentDot = screen.getByRole('listitem', { name: 'Step 2 of 3' });
- expect(currentDot).toHaveAttribute('aria-current', 'step');
- });
-
- it('does not set aria-current on non-current steps', () => {
- render(<ProgressIndicator currentStep={1} totalSteps={3} />);
- const step1 = screen.getByRole('listitem', { name: 'Step 1 of 3' });
- const step3 = screen.getByRole('listitem', { name: 'Step 3 of 3' });
- expect(step1).not.toHaveAttribute('aria-current');
- expect(step3).not.toHaveAttribute('aria-current');
- });
-
- it('does not use tablist/tab roles (non-interactive indicator)', () => {
- render(<ProgressIndicator currentStep={0} totalSteps={3} />);
- expect(screen.queryByRole('tablist')).not.toBeInTheDocument();
- expect(screen.queryByRole('tab')).not.toBeInTheDocument();
- });
-
- it('does not set aria-selected on any dot', () => {
- render(<ProgressIndicator currentStep={0} totalSteps={3} />);
- screen.getAllByRole('listitem').forEach(dot => {
- expect(dot).not.toHaveAttribute('aria-selected');
- });
- });
-
- it('applies active style class to the current step', () => {
- render(<ProgressIndicator currentStep={2} totalSteps={3} />);
- const activeDot = screen.getByRole('listitem', { name: 'Step 3 of 3' });
- expect(activeDot).toHaveClass('bg-stone-800');
- });
-
- it('applies inactive style class to non-current steps', () => {
- render(<ProgressIndicator currentStep={0} totalSteps={3} />);
- const inactiveDot = screen.getByRole('listitem', { name: 'Step 2 of 3' });
- expect(inactiveDot).toHaveClass('bg-stone-300');
- });
-
- it('renders a single step correctly', () => {
- render(<ProgressIndicator currentStep={0} totalSteps={1} />);
- const items = screen.getAllByRole('listitem');
- expect(items).toHaveLength(1);
- expect(items[0]).toHaveAttribute('aria-current', 'step');
- expect(items[0]).toHaveAttribute('aria-label', 'Step 1 of 1');
- });
-});
diff --git a/app/src/components/commands/CommandScope.tsx b/app/src/components/commands/CommandScope.tsx
deleted file mode 100644
index 40774c92f6..0000000000
--- a/app/src/components/commands/CommandScope.tsx
+++ /dev/null
@@ -1,25 +0,0 @@
-import { type ReactNode, useEffect, useMemo, useState } from 'react';
-
-import { hotkeyManager } from '../../lib/commands/hotkeyManager';
-import { ScopeContext } from '../../lib/commands/ScopeContext';
-import type { ScopeKind } from '../../lib/commands/types';
-
-interface Props {
- id: string;
- kind?: ScopeKind;
- children: ReactNode;
-}
-
-export default function CommandScope({ id, kind = 'page', children }: Props) {
- const [frame] = useState(() => hotkeyManager.pushFrame(kind, id));
-
- useEffect(() => {
- return () => {
- hotkeyManager.popFrame(frame);
- };
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- const value = useMemo(() => frame, [frame]);
- return <ScopeContext.Provider value={value}>{children}</ScopeContext.Provider>;
-}
diff --git a/app/src/components/commands/__tests__/CommandScope.test.tsx b/app/src/components/commands/__tests__/CommandScope.test.tsx
deleted file mode 100644
index c3079130ba..0000000000
--- a/app/src/components/commands/__tests__/CommandScope.test.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-import { render } from '@testing-library/react';
-import { StrictMode } from 'react';
-import { beforeEach, describe, expect, it } from 'vitest';
-
-import { hotkeyManager } from '../../../lib/commands/hotkeyManager';
-import CommandScope from '../CommandScope';
-
-beforeEach(() => {
- hotkeyManager.teardown();
- hotkeyManager.init();
-});
-
-describe('CommandScope', () => {
- it('pushes frame on mount, pops on unmount', () => {
- const { unmount } = render(
- <CommandScope id="home">
- <div />
- </CommandScope>
- );
- expect(hotkeyManager.getStackSymbols().length).toBe(1);
- unmount();
- expect(hotkeyManager.getStackSymbols().length).toBe(0);
- });
-
- it('StrictMode double-mount nets a single frame', () => {
- render(
- <StrictMode>
- <CommandScope id="home">
- <div />
- </CommandScope>
- </StrictMode>
- );
- expect(hotkeyManager.getStackSymbols().length).toBe(1);
- });
-
- it('nested scopes push two frames', () => {
- render(
- <CommandScope id="page">
- <CommandScope id="modal" kind="modal">
- <div />
- </CommandScope>
- </CommandScope>
- );
- expect(hotkeyManager.getStackSymbols().length).toBe(2);
- });
-
- it('pops by symbol (out-of-order unmount safe)', () => {
- function App({ showInner }: { showInner: boolean }) {
- return (
- <CommandScope id="outer">
- {showInner && (
- <CommandScope id="inner">
- <div />
- </CommandScope>
- )}
- </CommandScope>
- );
- }
- const { rerender, unmount } = render(<App showInner={true} />);
- expect(hotkeyManager.getStackSymbols().length).toBe(2);
- rerender(<App showInner={false} />);
- expect(hotkeyManager.getStackSymbols().length).toBe(1);
- unmount();
- expect(hotkeyManager.getStackSymbols().length).toBe(0);
- });
-});
diff --git a/app/src/components/intelligence/AgentsLibraryPanel.test.tsx b/app/src/components/intelligence/AgentsLibraryPanel.test.tsx
deleted file mode 100644
index c20fabcf89..0000000000
--- a/app/src/components/intelligence/AgentsLibraryPanel.test.tsx
+++ /dev/null
@@ -1,122 +0,0 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import type { AgentDefinitionDisplay } from '../../services/api/agentLibraryApi';
-import AgentsLibraryPanel from './AgentsLibraryPanel';
-
-const mockListDefinitions = vi.fn();
-
-vi.mock('../../services/api/agentLibraryApi', () => ({
- agentLibraryApi: { listDefinitions: (...args: unknown[]) => mockListDefinitions(...args) },
-}));
-
-function agent(overrides: Partial<AgentDefinitionDisplay> = {}): AgentDefinitionDisplay {
- return {
- id: 'researcher',
- display_name: 'Researcher',
- when_to_use: 'Use for focused research.',
- tier: 'worker',
- model: { kind: 'hint', value: 'reasoning' },
- direct_tool_count: 1,
- direct_tool_names: ['web_search'],
- uses_wildcard_tools: false,
- subagent_ids: [],
- includes_profile: false,
- includes_memory_md: false,
- includes_memory_context: false,
- can_run_as_user_facing_worker: true,
- write_capable: false,
- source: 'builtin',
- ...overrides,
- };
-}
-
-describe('AgentsLibraryPanel', () => {
- beforeEach(() => {
- mockListDefinitions.mockReset();
- Object.assign(navigator, { clipboard: { writeText: vi.fn().mockResolvedValue(undefined) } });
- });
-
- it('shows loading then an empty state', async () => {
- mockListDefinitions.mockResolvedValueOnce([]);
- render(<AgentsLibraryPanel onRunAgentTask={vi.fn()} />);
-
- expect(screen.getByText(/loading agents/i)).toBeInTheDocument();
- await waitFor(() => {
- expect(screen.getByText(/no runnable agents/i)).toBeInTheDocument();
- });
- });
-
- it('shows a load error', async () => {
- mockListDefinitions.mockRejectedValueOnce(new Error('registry unavailable'));
- render(<AgentsLibraryPanel onRunAgentTask={vi.fn()} />);
-
- await waitFor(() => {
- expect(screen.getByText(/registry unavailable/i)).toBeInTheDocument();
- });
- });
-
- it('renders safe metadata and filters non-runnable chat agents', async () => {
- mockListDefinitions.mockResolvedValueOnce([
- agent({ model: { kind: 'inherit' } }),
- agent({
- id: 'orchestrator',
- display_name: 'Orchestrator',
- tier: 'chat',
- can_run_as_user_facing_worker: false,
- }),
- ]);
- render(<AgentsLibraryPanel onRunAgentTask={vi.fn()} />);
-
- await waitFor(() => {
- expect(screen.getByText('Researcher')).toBeInTheDocument();
- });
- expect(screen.queryByText('Orchestrator')).not.toBeInTheDocument();
- expect(screen.getByText('Inherit')).toBeInTheDocument();
- expect(screen.getByText('Read-only')).toBeInTheDocument();
- expect(screen.getByText('1 tool')).toBeInTheDocument();
- });
-
- it('runs a one-off task for the selected agent', async () => {
- mockListDefinitions.mockResolvedValueOnce([agent()]);
- const onRun = vi.fn().mockResolvedValue(undefined);
- render(<AgentsLibraryPanel onRunAgentTask={onRun} />);
-
- await waitFor(() => {
- expect(screen.getByText('Researcher')).toBeInTheDocument();
- });
- fireEvent.change(screen.getByPlaceholderText(/task for this agent/i), {
- target: { value: 'Find current docs' },
- });
- fireEvent.click(screen.getByRole('button', { name: /run task/i }));
-
- await waitFor(() => expect(onRun).toHaveBeenCalledTimes(1));
- expect(onRun).toHaveBeenCalledWith(
- expect.objectContaining({ id: 'researcher' }),
- 'Find current docs'
- );
- });
-
- it('copies an agent id', async () => {
- mockListDefinitions.mockResolvedValueOnce([agent()]);
- render(<AgentsLibraryPanel onRunAgentTask={vi.fn()} />);
-
- await waitFor(() => {
- expect(screen.getByText('Researcher')).toBeInTheDocument();
- });
- fireEvent.click(screen.getByRole('button', { name: /copy id/i }));
- expect(navigator.clipboard.writeText).toHaveBeenCalledWith('researcher');
- });
-
- it('does not show copied when clipboard write is unavailable', async () => {
- mockListDefinitions.mockResolvedValueOnce([agent()]);
- Object.assign(navigator, { clipboard: {} });
- render(<AgentsLibraryPanel onRunAgentTask={vi.fn()} />);
-
- await waitFor(() => {
- expect(screen.getByText('Researcher')).toBeInTheDocument();
- });
- fireEvent.click(screen.getByRole('button', { name: /copy id/i }));
- expect(screen.queryByRole('button', { name: /copied/i })).not.toBeInTheDocument();
- });
-});
diff --git a/app/src/components/intelligence/AgentsLibraryPanel.tsx b/app/src/components/intelligence/AgentsLibraryPanel.tsx
deleted file mode 100644
index c9824ca8ef..0000000000
--- a/app/src/components/intelligence/AgentsLibraryPanel.tsx
+++ /dev/null
@@ -1,236 +0,0 @@
-import debug from 'debug';
-import { useCallback, useEffect, useMemo, useState } from 'react';
-import { LuBot, LuClipboard, LuPlay, LuRefreshCw, LuSend } from 'react-icons/lu';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import { type AgentDefinitionDisplay, agentLibraryApi } from '../../services/api/agentLibraryApi';
-import Badge from '../ui/Badge';
-import Button from '../ui/Button';
-import TextField from '../ui/TextField';
-
-const log = debug('intelligence:agents-library');
-
-interface AgentsLibraryPanelProps {
- onRunAgentTask: (agent: AgentDefinitionDisplay, prompt: string) => Promise<void>;
- runningAgentId?: string | null;
-}
-
-function modelLabel(
- agent: AgentDefinitionDisplay,
- t: (key: string, fallback?: string) => string
-): string {
- if (agent.model.kind === 'inherit') return t('intelligence.agents.model.inherit', 'inherit');
- return agent.model.value ? `${agent.model.kind}:${agent.model.value}` : agent.model.kind;
-}
-
-function capabilityChips(
- agent: AgentDefinitionDisplay,
- t: (key: string, fallback?: string) => string
-) {
- const chips = [t(`intelligence.agents.tier.${agent.tier}`, agent.tier)];
- chips.push(
- agent.write_capable ? t('intelligence.agents.writeCapable') : t('intelligence.agents.readOnly')
- );
- if (agent.uses_wildcard_tools) {
- chips.push(t('intelligence.agents.allTools'));
- } else if (agent.direct_tool_count > 0) {
- chips.push(
- (agent.direct_tool_count === 1
- ? t('intelligence.agents.toolCountOne')
- : t('intelligence.agents.toolCountOther')
- ).replace('{count}', String(agent.direct_tool_count))
- );
- }
- if (agent.subagent_ids.length > 0) {
- chips.push(
- (agent.subagent_ids.length === 1
- ? t('intelligence.agents.subagentCountOne')
- : t('intelligence.agents.subagentCountOther')
- ).replace('{count}', String(agent.subagent_ids.length))
- );
- }
- return chips;
-}
-
-export default function AgentsLibraryPanel({
- onRunAgentTask,
- runningAgentId,
-}: AgentsLibraryPanelProps) {
- const { t } = useT();
- const [agents, setAgents] = useState<AgentDefinitionDisplay[]>([]);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState<string | null>(null);
- const [drafts, setDrafts] = useState<Record<string, string>>({});
- const [copiedId, setCopiedId] = useState<string | null>(null);
-
- const loadAgents = useCallback(async () => {
- log('[ui-flow][agents-library] load entry');
- setLoading(true);
- setError(null);
- try {
- const definitions = await agentLibraryApi.listDefinitions();
- setAgents(definitions);
- log('[ui-flow][agents-library] load exit count=%d', definitions.length);
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- log('[ui-flow][agents-library] load error=%s', msg);
- setError(msg);
- } finally {
- setLoading(false);
- }
- }, []);
-
- useEffect(() => {
- const handle = window.setTimeout(() => {
- void loadAgents();
- }, 0);
- return () => window.clearTimeout(handle);
- }, [loadAgents]);
-
- const visibleAgents = useMemo(
- () => agents.filter(agent => agent.can_run_as_user_facing_worker),
- [agents]
- );
-
- const handleCopy = useCallback(async (id: string) => {
- try {
- if (!navigator.clipboard?.writeText) return;
- await navigator.clipboard.writeText(id);
- setCopiedId(id);
- window.setTimeout(() => setCopiedId(current => (current === id ? null : current)), 1600);
- } catch (err) {
- log('[ui-flow][agents-library] copy failed id=%s error=%o', id, err);
- }
- }, []);
-
- const handleRun = useCallback(
- async (agent: AgentDefinitionDisplay, prompt: string) => {
- const trimmed = prompt.trim();
- if (!trimmed || runningAgentId) return;
- log('[ui-flow][agents-library] run entry agent=%s chars=%d', agent.id, trimmed.length);
- await onRunAgentTask(agent, trimmed);
- setDrafts(prev => ({ ...prev, [agent.id]: '' }));
- log('[ui-flow][agents-library] run exit agent=%s', agent.id);
- },
- [onRunAgentTask, runningAgentId]
- );
-
- return (
- <section className="space-y-3">
- <div className="flex flex-wrap items-start justify-between gap-2">
- <div className="min-w-0">
- <h3 className="flex items-center gap-2 truncate text-sm font-semibold text-content-secondary">
- <LuBot className="h-4 w-4 text-primary-600 dark:text-primary-400" />
- {t('intelligence.agents.title')}
- </h3>
- <p className="mt-1 text-xs text-content-faint">{t('intelligence.agents.subtitle')}</p>
- </div>
- <Button
- variant="secondary"
- size="sm"
- onClick={() => void loadAgents()}
- leadingIcon={<LuRefreshCw className={`h-3.5 w-3.5 ${loading ? 'animate-spin' : ''}`} />}>
- {t('intelligence.agents.refresh')}
- </Button>
- </div>
-
- {loading && (
- <div className="flex items-center justify-center rounded-xl border border-line py-5 text-sm text-content-faint">
- <div className="mr-2 h-4 w-4 animate-spin rounded-full border-2 border-primary-500 border-t-transparent" />
- {t('intelligence.agents.loading')}
- </div>
- )}
-
- {error && !loading && (
- <div className="rounded-xl border border-coral-200 bg-coral-50 px-4 py-3 text-sm text-coral-700 dark:border-coral-500/30 dark:bg-coral-500/10 dark:text-coral-300">
- {t('intelligence.agents.failedToLoad')}: {error}
- </div>
- )}
-
- {!loading && !error && visibleAgents.length === 0 && (
- <div className="rounded-xl border border-dashed border-line py-6 text-center text-sm text-content-faint">
- {t('intelligence.agents.empty')}
- </div>
- )}
-
- {!loading && !error && visibleAgents.length > 0 && (
- <ul className="divide-y divide-line-subtle rounded-xl border border-line bg-surface">
- {visibleAgents.map(agent => {
- const draft = drafts[agent.id] ?? '';
- const running = runningAgentId === agent.id;
- return (
- <li key={agent.id} className="space-y-3 p-3">
- <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
- <div className="min-w-0 space-y-1">
- <div className="flex flex-wrap items-center gap-1.5">
- <span className="truncate text-sm font-semibold text-content">
- {agent.display_name}
- </span>
- <Badge variant="neutral" dot={false} className="font-mono">
- {agent.id}
- </Badge>
- <Badge variant="primary" dot={false}>
- {modelLabel(agent, t)}
- </Badge>
- </div>
- <p className="text-xs leading-5 text-content-muted">{agent.when_to_use}</p>
- <div className="flex flex-wrap gap-1.5">
- {capabilityChips(agent, t).map(chip => (
- <Badge key={chip} variant="neutral" dot={false}>
- {chip}
- </Badge>
- ))}
- </div>
- </div>
- <div className="flex flex-none flex-wrap gap-1.5">
- <Button
- variant="secondary"
- size="sm"
- onClick={() =>
- void handleRun(agent, t('intelligence.agents.startChatPrompt'))
- }
- disabled={Boolean(runningAgentId)}
- leadingIcon={<LuSend className="h-3.5 w-3.5" />}>
- {t('intelligence.agents.startChat')}
- </Button>
- <Button
- variant="secondary"
- size="sm"
- onClick={() => void handleCopy(agent.id)}
- leadingIcon={<LuClipboard className="h-3.5 w-3.5" />}>
- {copiedId === agent.id
- ? t('intelligence.agents.copied')
- : t('intelligence.agents.copyId')}
- </Button>
- </div>
- </div>
-
- <div className="flex flex-col gap-2 sm:flex-row">
- <TextField
- type="text"
- aria-label={t('intelligence.agents.taskPlaceholder')}
- value={draft}
- onChange={event =>
- setDrafts(prev => ({ ...prev, [agent.id]: event.target.value }))
- }
- placeholder={t('intelligence.agents.taskPlaceholder')}
- className="min-w-0 flex-1"
- />
- <Button
- type="button"
- variant="primary"
- onClick={() => void handleRun(agent, draft)}
- disabled={!draft.trim() || Boolean(runningAgentId)}
- leadingIcon={<LuPlay className="h-4 w-4" />}
- className="flex-none">
- {running ? t('intelligence.agents.running') : t('intelligence.agents.runTask')}
- </Button>
- </div>
- </li>
- );
- })}
- </ul>
- )}
- </section>
- );
-}
diff --git a/app/src/components/intelligence/IntelligenceMemoryTab.test.tsx b/app/src/components/intelligence/IntelligenceMemoryTab.test.tsx
deleted file mode 100644
index ab245bfbb9..0000000000
--- a/app/src/components/intelligence/IntelligenceMemoryTab.test.tsx
+++ /dev/null
@@ -1,125 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { ActionableItem, ActionableItemSource, TimeGroup } from '../../types/intelligence';
-import IntelligenceMemoryTab from './IntelligenceMemoryTab';
-
-function makeItem(overrides: Partial<ActionableItem> = {}): ActionableItem {
- return {
- id: 'i1',
- title: 'Reply to Alice',
- source: 'email',
- priority: 'normal',
- status: 'active',
- createdAt: new Date(),
- updatedAt: new Date(),
- actionable: true,
- ...overrides,
- };
-}
-
-interface Overrides {
- isRunning?: boolean;
- items?: ActionableItem[];
- itemsLoading?: boolean;
- searchFilter?: string;
- sourceFilter?: ActionableItemSource | 'all';
- timeGroups?: TimeGroup[];
- usingMemoryData?: boolean;
-}
-
-function renderTab(overrides: Overrides = {}) {
- const handleAnalyzeNow = vi.fn().mockResolvedValue(undefined);
- const handleComplete = vi.fn().mockResolvedValue(undefined);
- const handleDismiss = vi.fn();
- const handleSnooze = vi.fn().mockResolvedValue(undefined);
- const setSearchFilter = vi.fn();
- const setSourceFilter = vi.fn();
-
- render(
- <IntelligenceMemoryTab
- handleAnalyzeNow={handleAnalyzeNow}
- handleComplete={handleComplete}
- handleDismiss={handleDismiss}
- handleSnooze={handleSnooze}
- isRunning={overrides.isRunning ?? false}
- items={overrides.items ?? []}
- itemsLoading={overrides.itemsLoading ?? false}
- searchFilter={overrides.searchFilter ?? ''}
- setSearchFilter={setSearchFilter}
- setSourceFilter={setSourceFilter}
- sourceFilter={overrides.sourceFilter ?? 'all'}
- timeGroups={overrides.timeGroups ?? []}
- usingMemoryData={overrides.usingMemoryData ?? false}
- />
- );
-
- return {
- handleAnalyzeNow,
- handleComplete,
- handleDismiss,
- handleSnooze,
- setSearchFilter,
- setSourceFilter,
- };
-}
-
-describe('<IntelligenceMemoryTab />', () => {
- it('renders the search input and source filter select', () => {
- renderTab();
- expect(screen.getByRole('textbox')).toBeInTheDocument();
- expect(screen.getByRole('combobox')).toBeInTheDocument();
- });
-
- it('dispatches setSearchFilter on input change', () => {
- const { setSearchFilter } = renderTab();
- fireEvent.change(screen.getByRole('textbox'), { target: { value: 'foo' } });
- expect(setSearchFilter).toHaveBeenCalledWith('foo');
- });
-
- it('dispatches setSourceFilter on select change', () => {
- const { setSourceFilter } = renderTab();
- fireEvent.change(screen.getByRole('combobox'), { target: { value: 'email' } });
- expect(setSourceFilter).toHaveBeenCalledWith('email');
- });
-
- it('renders the loading state when itemsLoading and no memory data yet', () => {
- renderTab({ itemsLoading: true });
- expect(screen.getByRole('heading', { level: 2, name: /Loading Memory/i })).toBeInTheDocument();
- });
-
- it('renders the analyzing state when isRunning and items are empty', () => {
- renderTab({ isRunning: true });
- expect(
- screen.getByRole('heading', { level: 2, name: /Analyzing Memory/i })
- ).toBeInTheDocument();
- });
-
- it('invokes handleAnalyzeNow when the Analyze Now button is clicked', () => {
- const { handleAnalyzeNow } = renderTab({ usingMemoryData: false });
- fireEvent.click(screen.getByRole('button', { name: /Analyze Now/i }));
- expect(handleAnalyzeNow).toHaveBeenCalledTimes(1);
- });
-
- it('renders the no-matches state when filters are active and groups are empty', () => {
- renderTab({ searchFilter: 'foo', sourceFilter: 'email' });
- expect(
- screen.getByRole('heading', { level: 2, name: /No Matches Found/i })
- ).toBeInTheDocument();
- });
-
- it('renders the all-caught-up state when usingMemoryData and no groups', () => {
- renderTab({ usingMemoryData: true });
- expect(screen.getByRole('heading', { level: 2, name: /All Caught Up/i })).toBeInTheDocument();
- });
-
- it('renders time-group sections with their items', () => {
- const items = [makeItem({ id: 'A', title: 'First task' })];
- const timeGroups: TimeGroup[] = [{ label: 'Today', items, count: items.length }];
- renderTab({ items, timeGroups });
- expect(screen.getByText('Today')).toBeInTheDocument();
- expect(screen.getByText('First task')).toBeInTheDocument();
- // Group count badge.
- expect(screen.getByText('1')).toBeInTheDocument();
- });
-});
diff --git a/app/src/components/intelligence/IntelligenceMemoryTab.tsx b/app/src/components/intelligence/IntelligenceMemoryTab.tsx
deleted file mode 100644
index 2a30d993e4..0000000000
--- a/app/src/components/intelligence/IntelligenceMemoryTab.tsx
+++ /dev/null
@@ -1,193 +0,0 @@
-import type { ReactNode } from 'react';
-import { LuLightbulb } from 'react-icons/lu';
-
-import { cn } from '../../lib/cn';
-import { useT } from '../../lib/i18n/I18nContext';
-import type { ActionableItem, ActionableItemSource, TimeGroup } from '../../types/intelligence';
-import Badge from '../ui/Badge';
-import Button from '../ui/Button';
-import NativeSelect from '../ui/NativeSelect';
-import TextField from '../ui/TextField';
-import { ActionableCard } from './ActionableCard';
-
-/**
- * Frosted state panel used for this tab's loading / analyzing / empty states.
- *
- * Replaces the former `.glass` CSS class, which was deleted along with the rest
- * of the bespoke component layer in `index.css`. The values here are a faithful
- * port of it — `blur(12px)` (`backdrop-blur-lg`), `rgb(var(--surface) / 0.8)`,
- * a `rgb(var(--line) / 0.6)` hairline, and the light/dark shadow pair. The two
- * shadow alphas were hardcoded in the original rule too; they are not a new
- * themeability hole, but they are the one part of this that will not follow a
- * custom theme.
- *
- * It exists as a component rather than a shared class string because all three
- * call sites also share the medallion + heading + hint structure. `Card` and
- * `EmptyState` from `components/ui` were both considered and neither fits:
- * `Card` has no translucency and imposes its own heading/divider structure,
- * `EmptyState` is bare text with no icon slot.
- */
-function GlassStatePanel({ icon, children }: { icon: ReactNode; children: ReactNode }) {
- return (
- <div
- className={cn(
- 'backdrop-blur-lg bg-surface/80 border border-line/60',
- 'shadow-[0_2px_8px_rgba(0,0,0,0.06)] dark:shadow-[0_2px_8px_rgba(0,0,0,0.4)]',
- 'rounded-2xl p-8 text-center animate-fade-up'
- )}>
- <div className="w-16 h-16 mx-auto mb-4 flex items-center justify-center rounded-full bg-primary-500/10">
- {icon}
- </div>
- {children}
- </div>
- );
-}
-
-/** Indeterminate ring used by the loading and analyzing states. */
-function PanelSpinner() {
- return (
- <div className="w-8 h-8 border-2 border-primary-400 border-t-transparent rounded-full animate-spin" />
- );
-}
-
-interface IntelligenceMemoryTabProps {
- handleAnalyzeNow: () => Promise<void>;
- handleComplete: (item: ActionableItem) => Promise<void>;
- handleDismiss: (item: ActionableItem) => void;
- handleSnooze: (item: ActionableItem, duration: number) => Promise<void>;
- isRunning: boolean;
- items: ActionableItem[];
- itemsLoading: boolean;
- searchFilter: string;
- setSearchFilter: (value: string) => void;
- setSourceFilter: (value: ActionableItemSource | 'all') => void;
- sourceFilter: ActionableItemSource | 'all';
- timeGroups: TimeGroup[];
- usingMemoryData: boolean;
-}
-
-export default function IntelligenceMemoryTab({
- handleAnalyzeNow,
- handleComplete,
- handleDismiss,
- handleSnooze,
- isRunning,
- items,
- itemsLoading,
- searchFilter,
- setSearchFilter,
- setSourceFilter,
- sourceFilter,
- timeGroups,
- usingMemoryData,
-}: IntelligenceMemoryTabProps) {
- const { t } = useT();
- return (
- <>
- <div className="flex items-center gap-3 mb-6 animate-fade-up">
- <div className="flex-1">
- <label htmlFor="actionable-search" className="sr-only">
- {t('memory.searchAria')}
- </label>
- <TextField
- id="actionable-search"
- type="text"
- placeholder={t('memory.search')}
- value={searchFilter}
- onChange={e => setSearchFilter(e.target.value)}
- className="w-full"
- />
- </div>
- <label htmlFor="actionable-source" className="sr-only">
- {t('memory.sourceFilterAria')}
- </label>
- <NativeSelect
- id="actionable-source"
- value={sourceFilter}
- onChange={e => setSourceFilter(e.target.value as ActionableItemSource | 'all')}>
- <option value="all">{t('memory.sourceFilter.all')}</option>
- <option value="email">{t('memory.sourceFilter.email')}</option>
- <option value="calendar">{t('memory.sourceFilter.calendar')}</option>
- <option value="telegram">{t('memory.sourceFilter.telegram')}</option>
- <option value="ai_insight">{t('memory.sourceFilter.aiInsight')}</option>
- <option value="system">{t('memory.sourceFilter.system')}</option>
- <option value="trading">{t('memory.sourceFilter.trading')}</option>
- <option value="security">{t('memory.sourceFilter.security')}</option>
- </NativeSelect>
- </div>
-
- {itemsLoading && !usingMemoryData ? (
- <GlassStatePanel icon={<PanelSpinner />}>
- <h2 className="text-lg font-semibold text-content mb-2">{t('memory.loading')}</h2>
- <p className="text-content-faint text-sm">{t('memory.fetching')}</p>
- </GlassStatePanel>
- ) : isRunning && items.length === 0 ? (
- <GlassStatePanel icon={<PanelSpinner />}>
- <h2 className="text-lg font-semibold text-content mb-2">{t('memory.analyzing')}</h2>
- <p className="text-content-faint text-sm">{t('memory.analyzingHint')}</p>
- </GlassStatePanel>
- ) : timeGroups.length === 0 ? (
- <GlassStatePanel icon={<LuLightbulb className="w-8 h-8 text-primary-400" />}>
- {searchFilter || sourceFilter !== 'all' ? (
- <>
- <h2 className="text-lg font-semibold text-content mb-2">{t('memory.noMatches')}</h2>
- <p className="text-content-faint text-sm">{t('memory.noMatchesHint')}</p>
- </>
- ) : usingMemoryData ? (
- <>
- <h2 className="text-lg font-semibold text-content mb-2">{t('memory.allCaughtUp')}</h2>
- <p className="text-content-faint text-sm">{t('memory.allCaughtUpHint')}</p>
- </>
- ) : (
- <>
- <h2 className="text-lg font-semibold text-content mb-2">{t('memory.noAnalysis')}</h2>
- <p className="text-content-faint text-sm mb-4">{t('memory.noAnalysisHint')}</p>
- <Button
- variant="primary"
- size="md"
- onClick={() => void handleAnalyzeNow()}
- disabled={isRunning}>
- {t('memory.analyzeNow')}
- </Button>
- </>
- )}
- </GlassStatePanel>
- ) : (
- <div className="space-y-6">
- {isRunning && (
- <div className="flex items-center gap-2 text-xs text-content-faint animate-fade-up">
- <div className="w-3 h-3 border border-line-strong border-t-transparent rounded-full animate-spin" />
- {t('memory.analyzing')}
- </div>
- )}
- {timeGroups.map((group, groupIndex) => (
- <div
- key={group.label}
- className="animate-fade-up"
- style={{ animationDelay: `${groupIndex * 50}ms` }}>
- <div className="flex items-center justify-between mb-3">
- <h2 className="text-sm font-semibold text-content opacity-80">{group.label}</h2>
- <Badge dot={false}>{group.count}</Badge>
- </div>
- <div className="space-y-3">
- {group.items.map((item, itemIndex) => (
- <div
- key={item.id}
- className="animate-fade-up"
- style={{ animationDelay: `${groupIndex * 50 + itemIndex * 25}ms` }}>
- <ActionableCard
- item={item}
- onComplete={handleComplete}
- onDismiss={handleDismiss}
- onSnooze={handleSnooze}
- />
- </div>
- ))}
- </div>
- </div>
- ))}
- </div>
- )}
- </>
- );
-}
diff --git a/app/src/components/intelligence/MemoryChunkDetail.test.tsx b/app/src/components/intelligence/MemoryChunkDetail.test.tsx
deleted file mode 100644
index 4f4b8963c1..0000000000
--- a/app/src/components/intelligence/MemoryChunkDetail.test.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import type { Chunk } from '../../utils/tauriCommands';
-import { MemoryChunkDetail } from './MemoryChunkDetail';
-
-vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
-vi.mock('../../utils/tauriCommands', async () => {
- const actual = await vi.importActual<typeof import('../../utils/tauriCommands')>(
- '../../utils/tauriCommands'
- );
- return {
- ...actual,
- memoryTreeEntityIndexFor: vi.fn().mockResolvedValue([]),
- memoryTreeChunkScore: vi.fn().mockResolvedValue(null),
- };
-});
-
-function chunk(over: Partial<Chunk> = {}): Chunk {
- return {
- id: 'chunk-abcdef1234',
- source_kind: 'obsidian',
- source_id: 'steven|team',
- source_ref: 'obsidian://vault/note.md',
- owner: 'team',
- timestamp_ms: 1_700_000_000_000,
- token_count: 42,
- lifecycle_status: 'active',
- content_preview: 'A short subject line. Followed by the body.',
- has_embedding: true,
- tags: [],
- ...over,
- } as Chunk;
-}
-
-describe('MemoryChunkDetail', () => {
- beforeEach(() => {
- Object.assign(navigator, { clipboard: { writeText: vi.fn().mockResolvedValue(undefined) } });
- });
-
- it('renders the letter with a derived subject and the chunk id footer button', () => {
- render(<MemoryChunkDetail chunk={chunk()} onSelectEntity={vi.fn()} />);
-
- expect(screen.getByTestId('memory-chunk-detail')).toBeInTheDocument();
- expect(screen.getByText('A short subject line')).toBeInTheDocument();
-
- const copyButton = screen.getByRole('button', {
- name: /intelligence.memoryChunk.detail.chunk/,
- });
- expect(copyButton).toHaveAttribute('data-slot', 'button');
- });
-
- it('copies the chunk id to the clipboard on click', async () => {
- render(<MemoryChunkDetail chunk={chunk()} onSelectEntity={vi.fn()} />);
-
- const copyButton = screen.getByRole('button', {
- name: /intelligence.memoryChunk.detail.chunk/,
- });
- fireEvent.click(copyButton);
-
- expect(navigator.clipboard.writeText).toHaveBeenCalledWith('chunk-abcdef1234');
- });
-});
diff --git a/app/src/components/intelligence/MemoryChunkDetail.tsx b/app/src/components/intelligence/MemoryChunkDetail.tsx
deleted file mode 100644
index 25b8eb28f7..0000000000
--- a/app/src/components/intelligence/MemoryChunkDetail.tsx
+++ /dev/null
@@ -1,150 +0,0 @@
-/**
- * Right pane — single-chunk detail rendered as correspondence (a letter):
- *
- * 1. Letterhead (from / to / date)
- * 2. Subject + body (markdown-ish prose; entities highlighted)
- * 3. Mentioned (entity index for the chunk)
- * 4. Why kept (signal breakdown + threshold)
- * 5. Footer (source_ref, chunk id, embedder info)
- */
-import { useEffect, useState } from 'react';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import {
- type Chunk,
- type EntityRef,
- memoryTreeChunkScore,
- memoryTreeEntityIndexFor,
- type ScoreBreakdown,
-} from '../../utils/tauriCommands';
-import Button from '../ui/Button';
-import { MemoryChunkLetterhead } from './MemoryChunkLetterhead';
-import { MemoryChunkMentioned } from './MemoryChunkMentioned';
-import { MemoryChunkScoreBars } from './MemoryChunkScoreBars';
-import { MemoryTextWithEntities } from './MemoryTextWithEntities';
-
-interface MemoryChunkDetailProps {
- chunk: Chunk;
- onSelectEntity: (entity: EntityRef) => void;
-}
-
-function deriveSubject(chunk: Chunk): string {
- const preview = (chunk.content_preview ?? '').trim();
- if (!preview) return chunk.id;
- const firstLine = preview.split(/[.!?\n]/)[0]?.trim() ?? '';
- if (firstLine.length === 0) return chunk.id;
- return firstLine.length > 200 ? `${firstLine.slice(0, 197)}…` : firstLine;
-}
-
-function deriveBody(chunk: Chunk): string {
- const preview = (chunk.content_preview ?? '').trim();
- if (!preview) return '';
- // Drop the subject (first sentence/line) when there's more content after it.
- const firstBreak = preview.search(/[.!?\n](?:\s|$)/);
- if (firstBreak > 0 && preview.length > firstBreak + 2) {
- return preview.slice(firstBreak + 1).trim();
- }
- return preview;
-}
-
-function shortChunkId(id: string): string {
- // Trim "chunk-" prefix if present, then take 8 chars.
- const stripped = id.startsWith('chunk-') ? id.slice('chunk-'.length) : id;
- return stripped.slice(0, 8);
-}
-
-export function MemoryChunkDetail({ chunk, onSelectEntity }: MemoryChunkDetailProps) {
- const { t } = useT();
- const [entities, setEntities] = useState<EntityRef[]>([]);
- const [breakdown, setBreakdown] = useState<ScoreBreakdown | null>(null);
- const [copied, setCopied] = useState(false);
-
- useEffect(() => {
- let cancelled = false;
- console.debug('[ui-flow][memory-workspace] loading detail for chunk', chunk.id);
- void Promise.all([memoryTreeEntityIndexFor(chunk.id), memoryTreeChunkScore(chunk.id)]).then(
- ([ents, score]) => {
- if (cancelled) return;
- setEntities(ents);
- setBreakdown(score);
- console.debug(
- '[ui-flow][memory-workspace] detail loaded',
- chunk.id,
- 'entities=',
- ents.length,
- 'score_total=',
- score?.total ?? null
- );
- }
- );
- return () => {
- cancelled = true;
- };
- }, [chunk.id]);
-
- const handleCopyId = async () => {
- try {
- if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) {
- await navigator.clipboard.writeText(chunk.id);
- }
- setCopied(true);
- setTimeout(() => setCopied(false), 1200);
- } catch (err) {
- console.warn('[ui-flow][memory-workspace] copy chunk id failed', err);
- }
- };
-
- const subject = deriveSubject(chunk);
- const body = deriveBody(chunk);
-
- return (
- <article className="mw-pane-detail" data-testid="memory-chunk-detail">
- <div className="mw-pane-scroll mw-detail-scroll">
- <div className="mw-letter">
- <MemoryChunkLetterhead chunk={chunk} />
-
- <hr className="mw-rule" />
-
- <h1 className="mw-letter-subject">{subject}</h1>
- {body && (
- <div className="mw-letter-body">
- <MemoryTextWithEntities text={body} />
- </div>
- )}
-
- {entities.length > 0 && <hr className="mw-rule" />}
-
- <MemoryChunkMentioned entities={entities} onSelectEntity={onSelectEntity} />
-
- {breakdown && <hr className="mw-rule" />}
-
- {breakdown && <MemoryChunkScoreBars breakdown={breakdown} />}
-
- <footer className="mw-letter-footer">
- {chunk.source_ref && <span>{chunk.source_ref}</span>}
- <span>·</span>
- <Button
- variant="tertiary"
- size="xs"
- className="h-auto rounded-none px-0"
- onClick={() => void handleCopyId()}
- title={t('intelligence.memoryChunk.detail.copyChunkId')}>
- {t('intelligence.memoryChunk.detail.chunk')} {shortChunkId(chunk.id)}
- {copied && (
- <span className="ml-1.5 text-sage-600 dark:text-sage-400">
- {t('intelligence.memoryChunk.detail.copiedHint')}
- </span>
- )}
- </Button>
- <span>·</span>
- <span>
- {chunk.has_embedding
- ? t('intelligence.memoryChunk.detail.embeddingInfo')
- : t('intelligence.memoryChunk.detail.noEmbedding')}
- </span>
- </footer>
- </div>
- </div>
- </article>
- );
-}
diff --git a/app/src/components/intelligence/MemoryInsights.test.tsx b/app/src/components/intelligence/MemoryInsights.test.tsx
deleted file mode 100644
index 211df8bd15..0000000000
--- a/app/src/components/intelligence/MemoryInsights.test.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-import { fireEvent, render, screen, within } from '@testing-library/react';
-import { describe, expect, it } from 'vitest';
-
-import type { GraphRelation } from '../../utils/tauriCommands';
-import { MemoryInsights } from './MemoryInsights';
-
-function makeRel(overrides: Partial<GraphRelation> = {}): GraphRelation {
- return {
- namespace: 'work',
- subject: 'Alice',
- predicate: 'is',
- object: 'a developer',
- attrs: {},
- updatedAt: 1700000000,
- evidenceCount: 1,
- orderIndex: null,
- documentIds: [],
- chunkIds: [],
- ...overrides,
- };
-}
-
-describe('<MemoryInsights />', () => {
- it('renders a loading skeleton when loading', () => {
- const { container } = render(<MemoryInsights relations={[]} loading />);
- expect(container.querySelectorAll('.animate-pulse').length).toBeGreaterThanOrEqual(3);
- });
-
- it('renders the empty state when there are no relations', () => {
- render(<MemoryInsights relations={[]} />);
- // The empty branch falls back to i18n keys but the structure is two text nodes.
- const headings = screen.getAllByRole('heading', { level: 3 });
- expect(headings.length).toBeGreaterThanOrEqual(1);
- expect(headings[0]).toBeInTheDocument();
- });
-
- it('groups relations into the expected predicate categories', () => {
- const relations = [
- makeRel({ subject: 'Alice', predicate: 'is', object: 'a developer' }), // facts
- makeRel({ subject: 'Bob', predicate: 'likes', object: 'jazz' }), // preferences
- makeRel({ subject: 'Carol', predicate: 'knows', object: 'Dave' }), // relationships
- makeRel({ subject: 'Eve', predicate: 'skilled_in', object: 'Rust' }), // skills
- makeRel({ subject: 'Frank', predicate: 'thinks', object: 'TS is great' }), // opinions
- makeRel({ subject: 'Grace', predicate: 'walks', object: 'fast' }), // other
- ];
- render(<MemoryInsights relations={relations} />);
-
- // Subjects from every bucket should be visible because there is one item
- // each (≤ 3 items always shown when collapsed).
- expect(screen.getByText('Alice')).toBeInTheDocument();
- expect(screen.getByText('Bob')).toBeInTheDocument();
- expect(screen.getByText('Carol')).toBeInTheDocument();
- expect(screen.getByText('Eve')).toBeInTheDocument();
- expect(screen.getByText('Frank')).toBeInTheDocument();
- expect(screen.getByText('Grace')).toBeInTheDocument();
- });
-
- it('sorts items inside a group by evidenceCount descending', () => {
- const relations = [
- makeRel({ subject: 'Low', predicate: 'is', evidenceCount: 1 }),
- makeRel({ subject: 'High', predicate: 'is', evidenceCount: 9 }),
- makeRel({ subject: 'Mid', predicate: 'is', evidenceCount: 4 }),
- ];
- render(<MemoryInsights relations={relations} />);
- const items = [
- screen.getByText('High').compareDocumentPosition(screen.getByText('Mid')),
- screen.getByText('Mid').compareDocumentPosition(screen.getByText('Low')),
- ];
- // Both comparisons should report "Mid follows High" / "Low follows Mid".
- expect(items[0] & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
- expect(items[1] & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
- });
-
- it('shows the "+N more" hint when a group has more than 3 items', () => {
- const relations = Array.from({ length: 5 }, (_, i) =>
- makeRel({ subject: `S${i}`, predicate: 'is', object: 'thing', evidenceCount: i + 1 })
- );
- render(<MemoryInsights relations={relations} />);
- // 5 items in `facts`, collapsed view shows 3 → "+2 more"
- expect(screen.getByText(/\+2/)).toBeInTheDocument();
- });
-
- it('expands a group when its header is clicked, revealing more items', () => {
- const relations = Array.from({ length: 8 }, (_, i) =>
- makeRel({ subject: `S${i}`, predicate: 'is', object: 'thing', evidenceCount: i + 1 })
- );
- render(<MemoryInsights relations={relations} />);
-
- // Click the (only) category header — i18n key "insights.knownFacts".
- fireEvent.click(screen.getByRole('button', { name: /Known Facts/i }));
-
- // After expansion the "+N more" hint disappears and all subjects become visible.
- expect(screen.queryByText(/^\+/)).not.toBeInTheDocument();
- for (let i = 0; i < 8; i++) {
- expect(screen.getByText(`S${i}`)).toBeInTheDocument();
- }
- });
-
- it('decorates entity-type info as inline badges when present', () => {
- const relations = [
- makeRel({
- subject: 'Alice',
- predicate: 'is',
- object: 'developer',
- attrs: { entity_types: { subject: 'person', object: 'role' } },
- }),
- ];
- render(<MemoryInsights relations={relations} />);
- // The badge renders as a child of the subject span; query inside it
- // rather than reaching up to the row container.
- const subj = screen.getByText('Alice');
- expect(within(subj).getByText(/person/i)).toBeInTheDocument();
- });
-});
diff --git a/app/src/components/intelligence/MemoryInsights.tsx b/app/src/components/intelligence/MemoryInsights.tsx
deleted file mode 100644
index d5d4feeb55..0000000000
--- a/app/src/components/intelligence/MemoryInsights.tsx
+++ /dev/null
@@ -1,345 +0,0 @@
-import { useMemo, useState } from 'react';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import type { GraphRelation } from '../../utils/tauriCommands';
-import { AccordionContent, AccordionItem, AccordionRoot, AccordionTrigger } from '../ui/Accordion';
-
-interface MemoryInsightsProps {
- relations: GraphRelation[];
- loading?: boolean;
-}
-
-/**
- * Categorizes graph relations into insight types based on their predicates.
- * This gives the user a structured view of what the system has learned.
- */
-type InsightCategory = 'facts' | 'preferences' | 'relationships' | 'skills' | 'opinions' | 'other';
-
-interface InsightGroup {
- category: InsightCategory;
- label: string;
- icon: string;
- color: string;
- bgColor: string;
- borderColor: string;
- items: InsightItem[];
-}
-
-interface InsightItem {
- subject: string;
- predicate: string;
- object: string;
- evidenceCount: number;
- namespace: string | null;
- updatedAt: number;
- subjectType: string | null;
- objectType: string | null;
-}
-
-const PREDICATE_CATEGORIES: Record<string, InsightCategory> = {
- // Facts
- is: 'facts',
- 'is a': 'facts',
- was: 'facts',
- has: 'facts',
- contains: 'facts',
- located_in: 'facts',
- created_by: 'facts',
- founded: 'facts',
- built: 'facts',
- // Preferences
- prefers: 'preferences',
- likes: 'preferences',
- dislikes: 'preferences',
- wants: 'preferences',
- uses: 'preferences',
- favors: 'preferences',
- avoids: 'preferences',
- // Relationships
- knows: 'relationships',
- works_with: 'relationships',
- reports_to: 'relationships',
- manages: 'relationships',
- collaborates_with: 'relationships',
- member_of: 'relationships',
- part_of: 'relationships',
- belongs_to: 'relationships',
- // Skills
- skilled_in: 'skills',
- experienced_with: 'skills',
- certified_in: 'skills',
- specializes_in: 'skills',
- proficient_in: 'skills',
- // Opinions
- thinks: 'opinions',
- believes: 'opinions',
- considers: 'opinions',
- feels: 'opinions',
- views: 'opinions',
-};
-
-function categorize(predicate: string): InsightCategory {
- const normalized = predicate.toLowerCase().replace(/[_-]/g, ' ').trim();
- if (PREDICATE_CATEGORIES[normalized]) return PREDICATE_CATEGORIES[normalized];
-
- // Fuzzy match: check if predicate contains known keywords
- for (const [key, category] of Object.entries(PREDICATE_CATEGORIES)) {
- if (normalized.includes(key) || key.includes(normalized)) return category;
- }
-
- return 'other';
-}
-
-function useInsightCategoryLabels() {
- const { t } = useT();
- return {
- facts: {
- label: t('insights.knownFacts'),
- icon: 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z',
- color: 'text-emerald-600 dark:text-emerald-300',
- bgColor: 'bg-emerald-50 dark:bg-emerald-500/10 ',
- borderColor: 'border-emerald-200 dark:border-emerald-500/30',
- },
- preferences: {
- label: t('insights.preferences'),
- icon: 'M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z',
- color: 'text-rose-600 dark:text-rose-300',
- bgColor: 'bg-rose-50 dark:bg-rose-500/10 ',
- borderColor: 'border-rose-200 dark:border-rose-500/30',
- },
- relationships: {
- label: t('insights.relationships'),
- icon: 'M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z',
- color: 'text-primary-600 dark:text-primary-300',
- bgColor: 'bg-primary-50 dark:bg-primary-500/15',
- borderColor: 'border-primary-200 dark:border-primary-500/30',
- },
- skills: {
- label: t('insights.skills'),
- icon: 'M13 10V3L4 14h7v7l9-11h-7z',
- color: 'text-amber-600 dark:text-amber-300',
- bgColor: 'bg-amber-100 dark:bg-amber-500/20',
- borderColor: 'border-amber-200 dark:border-amber-500/30',
- },
- opinions: {
- label: t('insights.opinions'),
- icon: 'M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z',
- color: 'text-violet-600 dark:text-violet-300',
- bgColor: 'bg-violet-50 dark:bg-violet-500/10 ',
- borderColor: 'border-violet-200 dark:border-violet-500/30',
- },
- other: {
- label: t('insights.other'),
- icon: 'M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z',
- color: 'text-content-secondary',
- bgColor: 'bg-surface-subtle',
- borderColor: 'border-line',
- },
- } as const;
-}
-
-/** Small inline badge that displays an entity type (e.g. "person", "project"). */
-function EntityTypeBadge({ type }: { type: string }) {
- return (
- <span className="inline-block ml-1 px-1 py-px rounded text-[9px] leading-tight font-medium bg-surface/8 text-content-faint border border-line uppercase tracking-wide">
- {type}
- </span>
- );
-}
-
-export function MemoryInsights({ relations, loading }: MemoryInsightsProps) {
- const { t } = useT();
- const [expandedCategory, setExpandedCategory] = useState<InsightCategory | null>(null);
- const config = useInsightCategoryLabels();
-
- const groups = useMemo<InsightGroup[]>(() => {
- const buckets = new Map<InsightCategory, InsightItem[]>();
-
- for (const rel of relations) {
- const category = categorize(rel.predicate);
- const items = buckets.get(category) ?? [];
- const entityTypes = (rel.attrs?.entity_types ?? {}) as Record<string, string>;
- items.push({
- subject: rel.subject,
- predicate: rel.predicate,
- object: rel.object,
- evidenceCount: rel.evidenceCount,
- namespace: rel.namespace,
- updatedAt: rel.updatedAt,
- subjectType: entityTypes.subject ?? null,
- objectType: entityTypes.object ?? null,
- });
- buckets.set(category, items);
- }
-
- // Sort items within each bucket by evidence count descending
- for (const items of buckets.values()) {
- items.sort((a, b) => b.evidenceCount - a.evidenceCount);
- }
-
- const categoryOrder: InsightCategory[] = [
- 'facts',
- 'preferences',
- 'relationships',
- 'skills',
- 'opinions',
- 'other',
- ];
-
- return categoryOrder
- .filter(cat => (buckets.get(cat)?.length ?? 0) > 0)
- .map(cat => ({ category: cat, ...config[cat], items: buckets.get(cat)! }));
- }, [relations, config]);
-
- if (loading) {
- return (
- <div className="rounded-xl border border-line bg-surface-muted p-5">
- <h3 className="text-sm font-semibold text-content mb-4">{t('insights.title')}</h3>
- <div className="grid grid-cols-2 lg:grid-cols-3 gap-3">
- {[1, 2, 3].map(i => (
- <div key={i} className="h-28 rounded-lg bg-surface-strong animate-pulse" />
- ))}
- </div>
- </div>
- );
- }
-
- if (groups.length === 0) {
- return (
- <div className="rounded-xl border border-line bg-surface-muted p-5">
- <h3 className="text-sm font-semibold text-content mb-2">{t('insights.title')}</h3>
- <p className="text-sm text-content-secondary">{t('insights.empty')}</p>
- </div>
- );
- }
-
- return (
- <div className="rounded-xl border border-line bg-surface-muted p-5">
- <div className="flex items-center justify-between mb-4">
- <div>
- <h3 className="text-sm font-semibold text-content">{t('insights.title')}</h3>
- <p className="text-xs text-content-muted mt-0.5">
- {t('insights.description').replace('{count}', String(relations.length))}
- </p>
- </div>
- </div>
-
- {/*
- * Category cards are exclusive — expanding one collapses whatever else
- * was open — so this is Accordion `type="single" collapsible`, not a
- * plain grid of buttons. The first 3 items per category are always
- * visible (a preview, not a disclosure), so only the *extra* items
- * beyond that live inside `AccordionContent` and unmount when the card
- * is collapsed; the preview + "+N more" hint stay outside it.
- */}
- <AccordionRoot
- type="single"
- collapsible
- value={expandedCategory ?? ''}
- onValueChange={value => setExpandedCategory((value || null) as InsightCategory | null)}
- variant="card"
- className="grid grid-cols-2 lg:grid-cols-3 gap-3">
- {groups.map(group => {
- const isExpanded = expandedCategory === group.category;
- const previewItems = group.items.slice(0, 3);
- const extraItems = group.items.slice(3, 20);
-
- return (
- <AccordionItem
- key={group.category}
- value={group.category}
- className={`rounded-lg border ${group.borderColor} ${group.bgColor} p-3 transition-all ${
- isExpanded ? 'col-span-2 lg:col-span-3' : ''
- }`}>
- <AccordionTrigger
- showChevron={false}
- className="h-auto gap-2 p-0 font-normal mb-2 hover:bg-transparent">
- <div
- className={`w-7 h-7 rounded-md ${group.bgColor} flex items-center justify-center shrink-0`}>
- <svg
- className={`w-4 h-4 ${group.color}`}
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={1.5}
- d={group.icon}
- />
- </svg>
- </div>
- <div className="min-w-0 flex-1">
- <div className={`text-xs font-medium ${group.color}`}>{group.label}</div>
- <div className="text-[10px] text-content-muted">
- {group.items.length} {t('insights.items')}
- </div>
- </div>
- <svg
- className={`w-3.5 h-3.5 text-content-muted transition-transform ${isExpanded ? 'rotate-180' : ''}`}
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M19 9l-7 7-7-7"
- />
- </svg>
- </AccordionTrigger>
-
- <div className={`space-y-1.5 ${isExpanded ? 'max-h-80 overflow-y-auto pr-1' : ''}`}>
- {previewItems.map((item, idx) => (
- <InsightItemRow
- key={`${item.subject}-${item.predicate}-${item.object}-${idx}`}
- item={item}
- />
- ))}
- {!isExpanded && group.items.length > 3 && (
- <div className="text-[10px] text-content-muted pt-0.5">
- +{group.items.length - 3} {t('insights.more')}
- </div>
- )}
- {extraItems.length > 0 && (
- <AccordionContent className="p-0">
- <div className="space-y-1.5">
- {extraItems.map((item, idx) => (
- <InsightItemRow
- key={`${item.subject}-${item.predicate}-${item.object}-${idx + 3}`}
- item={item}
- />
- ))}
- </div>
- </AccordionContent>
- )}
- </div>
- </AccordionItem>
- );
- })}
- </AccordionRoot>
- </div>
- );
-}
-
-/** One subject/predicate/object row, shared between the always-visible preview and the expanded extra items. */
-function InsightItemRow({ item }: { item: InsightItem }) {
- return (
- <div className="flex items-start gap-1.5 text-[11px] leading-relaxed">
- <span className="text-content font-medium shrink-0 max-w-[30%] truncate" title={item.subject}>
- {item.subject}
- {item.subjectType && <EntityTypeBadge type={item.subjectType} />}
- </span>
- <span className="text-content-muted shrink-0 italic">{item.predicate}</span>
- <span className="text-content-secondary truncate" title={item.object}>
- {item.object}
- {item.objectType && <EntityTypeBadge type={item.objectType} />}
- </span>
- {item.evidenceCount > 1 && (
- <span className="ml-auto text-[9px] text-content-secondary shrink-0 tabular-nums">
- x{item.evidenceCount}
- </span>
- )}
- </div>
- );
-}
diff --git a/app/src/components/intelligence/MemoryNavigator.test.tsx b/app/src/components/intelligence/MemoryNavigator.test.tsx
deleted file mode 100644
index 6a4041f58b..0000000000
--- a/app/src/components/intelligence/MemoryNavigator.test.tsx
+++ /dev/null
@@ -1,192 +0,0 @@
-import { fireEvent, render, screen, within } from '@testing-library/react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import type { Chunk, EntityRef, Source } from '../../utils/tauriCommands';
-import { MemoryNavigator, type NavigatorSelection } from './MemoryNavigator';
-
-const EMPTY_SELECTION: NavigatorSelection = { sourceIds: [], entityIds: [] };
-
-// Freeze the clock so the today/this-week bucket calculations and any
-// `timestamp_ms: Date.now()` defaults are deterministic. Picked a noon-UTC
-// weekday far from a DST boundary to avoid clock-edge surprises.
-const FROZEN_NOW = new Date('2026-03-04T12:00:00.000Z');
-
-function makeChunk(overrides: Partial<Chunk> = {}): Chunk {
- return {
- id: 'c1',
- source_kind: 'email',
- source_id: 'src-1',
- owner: 'me',
- timestamp_ms: FROZEN_NOW.getTime(),
- token_count: 4,
- lifecycle_status: 'admitted',
- has_embedding: false,
- tags: [],
- ...overrides,
- };
-}
-
-function makeSource(overrides: Partial<Source> = {}): Source {
- return {
- source_id: 'src-1',
- display_name: 'Alice',
- source_kind: 'email',
- chunk_count: 3,
- most_recent_ms: FROZEN_NOW.getTime(),
- ...overrides,
- };
-}
-
-function makeEntity(overrides: Partial<EntityRef> = {}): EntityRef {
- return { entity_id: 'person:Alice', kind: 'person', surface: 'Alice', count: 5, ...overrides };
-}
-
-describe('<MemoryNavigator />', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- vi.setSystemTime(FROZEN_NOW);
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it('renders the search input and dispatches onSearchChange', () => {
- const onSearch = vi.fn();
- render(
- <MemoryNavigator
- chunks={[]}
- sources={[]}
- topPeople={[]}
- topTopics={[]}
- selection={EMPTY_SELECTION}
- onSelectionChange={() => {}}
- searchQuery=""
- onSearchChange={onSearch}
- />
- );
- const input = screen.getByRole('textbox');
- fireEvent.change(input, { target: { value: 'foo' } });
- expect(onSearch).toHaveBeenCalledWith('foo');
- });
-
- it('renders a single navigator pane with a heatmap host', () => {
- render(
- <MemoryNavigator
- chunks={[]}
- sources={[]}
- topPeople={[]}
- topTopics={[]}
- selection={EMPTY_SELECTION}
- onSelectionChange={() => {}}
- searchQuery=""
- onSearchChange={() => {}}
- />
- );
- expect(screen.getByTestId('memory-navigator')).toBeInTheDocument();
- expect(screen.getByTestId('memory-navigator-heatmap')).toBeInTheDocument();
- });
-
- it('toggles a source on click and emits the updated selection', () => {
- const onChange = vi.fn();
- render(
- <MemoryNavigator
- chunks={[]}
- sources={[makeSource({ source_id: 'gmail:alice', display_name: 'Alice' })]}
- topPeople={[]}
- topTopics={[]}
- selection={EMPTY_SELECTION}
- onSelectionChange={onChange}
- searchQuery=""
- onSearchChange={() => {}}
- />
- );
- // Source-kind buckets default-closed; open the inner kind section first.
- const kindHeader = screen.getByRole('button', { expanded: false, name: /email/i });
- fireEvent.click(kindHeader);
- fireEvent.click(screen.getByRole('button', { name: /Alice/i, pressed: false }));
- expect(onChange).toHaveBeenCalledWith({ sourceIds: ['gmail:alice'], entityIds: [] });
- });
-
- it('toggles an entity (person) on click and emits the updated selection', () => {
- const onChange = vi.fn();
- render(
- <MemoryNavigator
- chunks={[]}
- sources={[]}
- topPeople={[makeEntity({ entity_id: 'person:Bob', surface: 'Bob' })]}
- topTopics={[]}
- selection={EMPTY_SELECTION}
- onSelectionChange={onChange}
- searchQuery=""
- onSearchChange={() => {}}
- />
- );
- fireEvent.click(screen.getByRole('button', { name: /Bob/i, pressed: false }));
- expect(onChange).toHaveBeenCalledWith({ sourceIds: [], entityIds: ['person:Bob'] });
- });
-
- it('un-toggles an already-active entity', () => {
- const onChange = vi.fn();
- render(
- <MemoryNavigator
- chunks={[]}
- sources={[]}
- topPeople={[makeEntity({ entity_id: 'person:Bob', surface: 'Bob' })]}
- topTopics={[]}
- selection={{ sourceIds: [], entityIds: ['person:Bob'] }}
- onSelectionChange={onChange}
- searchQuery=""
- onSearchChange={() => {}}
- />
- );
- // aria-pressed=true since Bob is in the active set.
- fireEvent.click(screen.getByRole('button', { name: /Bob/i, pressed: true }));
- expect(onChange).toHaveBeenCalledWith({ sourceIds: [], entityIds: [] });
- });
-
- it('collapses a NavSection when its heading is clicked', () => {
- render(
- <MemoryNavigator
- chunks={[]}
- sources={[]}
- topPeople={[makeEntity({ entity_id: 'person:Bob', surface: 'Bob' })]}
- topTopics={[]}
- selection={EMPTY_SELECTION}
- onSelectionChange={() => {}}
- searchQuery=""
- onSearchChange={() => {}}
- />
- );
- // People section is open by default and Bob is visible.
- expect(screen.getByRole('button', { name: /Bob/i })).toBeInTheDocument();
- const peopleHeader = screen.getByRole('button', { name: /people/i, expanded: true });
- fireEvent.click(peopleHeader);
- expect(screen.queryByRole('button', { name: /Bob/i })).not.toBeInTheDocument();
- });
-
- it('counts chunks within today and the rolling 7-day window', () => {
- const now = FROZEN_NOW.getTime();
- const chunks = [
- makeChunk({ id: 'today', timestamp_ms: now }),
- makeChunk({ id: 'week', timestamp_ms: now - 3 * 24 * 60 * 60 * 1000 }),
- ];
- render(
- <MemoryNavigator
- chunks={chunks}
- sources={[]}
- topPeople={[]}
- topTopics={[]}
- selection={EMPTY_SELECTION}
- onSelectionChange={() => {}}
- searchQuery=""
- onSearchChange={() => {}}
- />
- );
- // The "recent" section renders "<Today label> <n>" and "<This Week label> <n>"
- // — assert against those labeled counters, not loose digits.
- const recent = within(screen.getByTestId('memory-navigator'));
- expect(recent.getByText(/Today\s+1/i)).toBeInTheDocument();
- expect(recent.getByText(/This Week\s+2/i)).toBeInTheDocument();
- });
-});
diff --git a/app/src/components/intelligence/MemoryNavigator.tsx b/app/src/components/intelligence/MemoryNavigator.tsx
deleted file mode 100644
index d8a566db54..0000000000
--- a/app/src/components/intelligence/MemoryNavigator.tsx
+++ /dev/null
@@ -1,285 +0,0 @@
-/**
- * Left pane of MemoryWorkspace — search box, slim heatmap header, and four
- * collapsible lens sections (recent / sources / people / topics).
- *
- * Selections are NOT mutually exclusive: multiple selected items intersect
- * the result list filter. Sections may be collapsed independently.
- */
-import { useEffect, useMemo, useState } from 'react';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import type { Chunk, EntityRef, Source } from '../../utils/tauriCommands';
-import { MemoryHeatmap } from './MemoryHeatmap';
-
-export interface NavigatorSelection {
- sourceIds: string[];
- entityIds: string[];
-}
-
-interface MemoryNavigatorProps {
- chunks: Chunk[];
- sources: Source[];
- topPeople: EntityRef[];
- topTopics: EntityRef[];
- selection: NavigatorSelection;
- onSelectionChange: (next: NavigatorSelection) => void;
- searchQuery: string;
- onSearchChange: (next: string) => void;
-}
-
-const HOUR_MS = 60 * 60 * 1000;
-const DAY_MS = 24 * HOUR_MS;
-
-function dotClassFor(status: string | undefined): string {
- switch (status) {
- case 'admitted':
- return 'mw-dot dot-admitted';
- case 'pending_extraction':
- return 'mw-dot dot-pending';
- case 'buffered':
- return 'mw-dot dot-buffered';
- case 'dropped':
- return 'mw-dot dot-dropped';
- default:
- return 'mw-dot';
- }
-}
-
-interface SectionProps {
- label: string;
- defaultOpen?: boolean;
- countSummary?: string;
- children: React.ReactNode;
-}
-
-function NavSection({ label, defaultOpen = true, countSummary, children }: SectionProps) {
- const [open, setOpen] = useState(defaultOpen);
- return (
- <div className="mw-section">
- <button
- type="button"
- className="mw-section-heading"
- onClick={() => setOpen(o => !o)}
- aria-expanded={open}>
- <span>{label}</span>
- {countSummary && (
- <span
- style={{
- fontFamily: "'JetBrains Mono', monospace",
- fontSize: 10,
- letterSpacing: 0,
- color: 'var(--ink-whisper)',
- marginLeft: 8,
- textTransform: 'none',
- }}>
- {countSummary}
- </span>
- )}
- <span className={`mw-section-chev${open ? ' open' : ''}`} aria-hidden>
- ›
- </span>
- </button>
- {open && children}
- </div>
- );
-}
-
-export function MemoryNavigator({
- chunks,
- sources,
- topPeople,
- topTopics,
- selection,
- onSelectionChange,
- searchQuery,
- onSearchChange,
-}: MemoryNavigatorProps) {
- const { t } = useT();
- const heatmapTimestamps = useMemo(
- () => chunks.map(c => Math.floor(c.timestamp_ms / 1000)),
- [chunks]
- );
-
- // Wall-clock-derived counts. Computed in an effect to keep render pure
- // (the `react-hooks/components-and-hooks-must-be-pure` rule rejects a
- // raw `Date.now()` call inside a `useMemo` body, since two equivalent
- // renders could produce different values).
- const [recentCounts, setRecentCounts] = useState<{ today: number; week: number }>({
- today: 0,
- week: 0,
- });
- useEffect(() => {
- const now = Date.now();
- const startOfDay = new Date(now);
- startOfDay.setHours(0, 0, 0, 0);
- const startOfDayMs = startOfDay.getTime();
- const startOfWeekMs = now - 7 * DAY_MS;
- let today = 0;
- let week = 0;
- for (const c of chunks) {
- if (c.timestamp_ms >= startOfDayMs) today++;
- if (c.timestamp_ms >= startOfWeekMs) week++;
- }
- setRecentCounts({ today, week });
- }, [chunks]);
- const { today: todayCount, week: weekCount } = recentCounts;
-
- const toggleSource = (id: string) => {
- const has = selection.sourceIds.includes(id);
- onSelectionChange({
- ...selection,
- sourceIds: has ? selection.sourceIds.filter(s => s !== id) : [...selection.sourceIds, id],
- });
- };
-
- const toggleEntity = (id: string) => {
- const has = selection.entityIds.includes(id);
- const next = has ? selection.entityIds.filter(s => s !== id) : [...selection.entityIds, id];
- console.debug(
- '[ui-flow][memory-navigator] toggleEntity id=%s wasActive=%o next=%o',
- id,
- has,
- next
- );
- onSelectionChange({ ...selection, entityIds: next });
- };
-
- const renderEntityList = (refs: EntityRef[]) => (
- <ul className="mw-list">
- {refs.map(ref => {
- const tag = `${ref.kind}/${ref.surface.replace(/\s+/g, '-')}`;
- // For tag-based selection we use the raw tag string; for entity_id we
- // compare against tags on chunks. Match either form to be lenient.
- const isActive =
- selection.entityIds.includes(tag) || selection.entityIds.includes(ref.entity_id);
- return (
- <li key={ref.entity_id}>
- <button
- type="button"
- className={`mw-list-item${isActive ? ' is-active' : ''}`}
- onClick={() => toggleEntity(ref.entity_id)}
- aria-pressed={isActive}>
- <span className="mw-dot" aria-hidden />
- <span className="mw-list-name" title={ref.surface}>
- {ref.surface}
- </span>
- <span className="mw-list-count">{ref.count}</span>
- </button>
- </li>
- );
- })}
- {refs.length === 0 && (
- <li style={{ padding: '6px 16px', fontSize: 12, color: 'var(--ink-whisper)' }}>—</li>
- )}
- </ul>
- );
-
- return (
- <aside className="mw-pane-navigator" data-testid="memory-navigator">
- <div className="mw-search-row">
- <input
- type="text"
- className="mw-search-input"
- placeholder={t('memory.searchPlaceholder')}
- value={searchQuery}
- onChange={e => onSearchChange(e.target.value)}
- aria-label={t('memory.search')}
- />
- </div>
-
- <div className="mw-heatmap-host" data-testid="memory-navigator-heatmap">
- <MemoryHeatmap timestamps={heatmapTimestamps} />
- </div>
-
- <div className="mw-pane-scroll">
- <NavSection label={t('navigator.recent')} defaultOpen>
- <div className="mw-recent-summary">
- <span>
- {t('navigator.today')} {todayCount}
- </span>
- <span>
- {t('navigator.thisWeek')} {weekCount}
- </span>
- </div>
- </NavSection>
-
- <NavSection
- label={t('navigator.sources')}
- defaultOpen
- countSummary={String(sources.length)}>
- {sources.length === 0 ? (
- <ul className="mw-list">
- <li style={{ padding: '6px 16px', fontSize: 12, color: 'var(--ink-whisper)' }}>—</li>
- </ul>
- ) : (
- (() => {
- // Group sources by their source_kind ('email', 'slack', 'chat', …)
- // and render each kind as its own nested collapsible. Lets the
- // user filter at the kind level (drill into Email vs Slack) and
- // then by individual sender within each.
- const byKind = new Map<string, Source[]>();
- for (const s of sources) {
- const arr = byKind.get(s.source_kind) ?? [];
- arr.push(s);
- byKind.set(s.source_kind, arr);
- }
- const kindLabel: Record<string, string> = {
- email: t('navigator.email'),
- slack: t('navigator.slack'),
- chat: t('navigator.chat'),
- document: t('navigator.documents'),
- };
- const kinds = Array.from(byKind.entries()).sort((a, b) => b[1].length - a[1].length);
- return (
- <div>
- {kinds.map(([kind, kindSources]) => (
- <NavSection
- key={kind}
- label={kindLabel[kind] ?? kind}
- defaultOpen={false}
- countSummary={String(kindSources.length)}>
- <ul className="mw-list">
- {kindSources.map(src => {
- const isActive = selection.sourceIds.includes(src.source_id);
- return (
- <li key={src.source_id}>
- <button
- type="button"
- className={`mw-list-item${isActive ? ' is-active' : ''}`}
- onClick={() => toggleSource(src.source_id)}
- aria-pressed={isActive}>
- <span className={dotClassFor(src.lifecycle_status)} aria-hidden />
- <span className="mw-list-name" title={src.display_name}>
- {src.display_name}
- </span>
- <span className="mw-list-count">{src.chunk_count}</span>
- </button>
- </li>
- );
- })}
- </ul>
- </NavSection>
- ))}
- </div>
- );
- })()
- )}
- </NavSection>
-
- <NavSection
- label={t('navigator.people')}
- defaultOpen
- countSummary={String(topPeople.length)}>
- {renderEntityList(topPeople)}
- </NavSection>
-
- <NavSection
- label={t('navigator.topics')}
- defaultOpen
- countSummary={String(topTopics.length)}>
- {renderEntityList(topTopics)}
- </NavSection>
- </div>
- </aside>
- );
-}
diff --git a/app/src/components/intelligence/MemoryResultList.test.tsx b/app/src/components/intelligence/MemoryResultList.test.tsx
deleted file mode 100644
index c6d784c33b..0000000000
--- a/app/src/components/intelligence/MemoryResultList.test.tsx
+++ /dev/null
@@ -1,113 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import type { Chunk } from '../../utils/tauriCommands';
-import { MemoryResultList } from './MemoryResultList';
-
-const DAY_MS = 24 * 60 * 60 * 1000;
-
-// Mid-day, mid-week, far from DST — keeps the bucket boundaries (TODAY /
-// YESTERDAY / THIS WEEK / OLDER) deterministic across machines + CI.
-const FROZEN_NOW = new Date('2026-03-04T12:00:00.000Z');
-
-function makeChunk(overrides: Partial<Chunk> = {}): Chunk {
- return {
- id: 'chunk-1',
- source_kind: 'email',
- source_id: 'gmail:[email protected]|thread-1',
- owner: 'me',
- timestamp_ms: FROZEN_NOW.getTime(),
- token_count: 12,
- lifecycle_status: 'admitted',
- has_embedding: true,
- tags: [],
- content_preview: 'Subject of the message line. More body follows.',
- ...overrides,
- };
-}
-
-function startOfTodayMs(): number {
- const d = new Date(FROZEN_NOW);
- d.setHours(0, 0, 0, 0);
- return d.getTime();
-}
-
-describe('<MemoryResultList />', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- vi.setSystemTime(FROZEN_NOW);
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it('renders the no-results state when the list is empty', () => {
- render(<MemoryResultList chunks={[]} selectedChunkId={null} onSelectChunk={() => {}} />);
- expect(screen.getByTestId('memory-result-list')).toBeInTheDocument();
- // Default i18n context falls back to the en translation map.
- expect(screen.getByText(/No memories found/i)).toBeInTheDocument();
- });
-
- it('renders chunks bucketed into the four time-group sections', () => {
- const todayMs = startOfTodayMs();
- const chunks = [
- makeChunk({ id: 'today-1', timestamp_ms: todayMs + 9 * 60 * 60 * 1000 }),
- makeChunk({ id: 'yesterday-1', timestamp_ms: todayMs - 2 * 60 * 60 * 1000 }),
- makeChunk({ id: 'thisweek-1', timestamp_ms: todayMs - 3 * DAY_MS }),
- makeChunk({ id: 'older-1', timestamp_ms: todayMs - 30 * DAY_MS }),
- ];
- render(<MemoryResultList chunks={chunks} selectedChunkId={null} onSelectChunk={() => {}} />);
-
- // Section headers are uppercased literal strings, not i18n keys.
- expect(screen.getByText('TODAY')).toBeInTheDocument();
- expect(screen.getByText('YESTERDAY')).toBeInTheDocument();
- expect(screen.getByText('THIS WEEK')).toBeInTheDocument();
- expect(screen.getByText('OLDER')).toBeInTheDocument();
-
- // One row button per chunk — query by accessible role.
- expect(screen.getAllByRole('button')).toHaveLength(4);
- });
-
- it('marks the active row via aria-pressed', () => {
- const todayMs = startOfTodayMs();
- const chunks = [
- makeChunk({ id: 'a', timestamp_ms: todayMs + 1 }),
- makeChunk({ id: 'b', timestamp_ms: todayMs + 2 }),
- ];
- render(<MemoryResultList chunks={chunks} selectedChunkId="b" onSelectChunk={() => {}} />);
- // Exactly one row carries aria-pressed=true.
- const pressed = screen.getAllByRole('button', { pressed: true });
- expect(pressed).toHaveLength(1);
- expect(screen.getAllByRole('button', { pressed: false })).toHaveLength(1);
- });
-
- it('fires onSelectChunk when a row is clicked', () => {
- const todayMs = startOfTodayMs();
- const onSelect = vi.fn();
- const chunks = [makeChunk({ id: 'click-me', timestamp_ms: todayMs + 1 })];
- render(<MemoryResultList chunks={chunks} selectedChunkId={null} onSelectChunk={onSelect} />);
- fireEvent.click(screen.getByRole('button', { pressed: false }));
- expect(onSelect).toHaveBeenCalledWith('click-me');
- });
-
- it('renders a sender label derived from the source_id', () => {
- const chunks = [
- makeChunk({
- id: 'q',
- source_id: 'gmail:[email protected]|thread-1',
- timestamp_ms: startOfTodayMs() + 1,
- }),
- ];
- render(<MemoryResultList chunks={chunks} selectedChunkId={null} onSelectChunk={() => {}} />);
- expect(screen.getByText(/alice@example\.com/)).toBeInTheDocument();
- });
-
- it('uses the chunk id as the subject when no content preview is provided', () => {
- const chunks = [
- makeChunk({ id: 'no-preview-id', content_preview: '', timestamp_ms: startOfTodayMs() + 1 }),
- ];
- render(<MemoryResultList chunks={chunks} selectedChunkId={null} onSelectChunk={() => {}} />);
- expect(screen.getByText('no-preview-id')).toBeInTheDocument();
- });
-});
diff --git a/app/src/components/intelligence/MemoryResultList.tsx b/app/src/components/intelligence/MemoryResultList.tsx
deleted file mode 100644
index 136668c885..0000000000
--- a/app/src/components/intelligence/MemoryResultList.tsx
+++ /dev/null
@@ -1,178 +0,0 @@
-/**
- * Middle pane of MemoryWorkspace — time-grouped chunk rows.
- *
- * Sections: TODAY / YESTERDAY / THIS WEEK / OLDER, headers are sticky
- * so the user always knows which time bucket is on screen.
- *
- * Auto-scrolls to the active row on mount and on selection change.
- *
- * The list is intentionally non-virtualized for now — mock fixtures
- * top out at ~30 rows. Once real data lands we can swap in react-window
- * (or similar) without changing the public API.
- */
-import { useEffect, useMemo, useRef } from 'react';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import type { Chunk } from '../../utils/tauriCommands';
-
-interface MemoryResultListProps {
- chunks: Chunk[];
- selectedChunkId: string | null;
- onSelectChunk: (id: string) => void;
-}
-
-type GroupKey = 'TODAY' | 'YESTERDAY' | 'THIS WEEK' | 'OLDER';
-
-interface Group {
- key: GroupKey;
- chunks: Chunk[];
-}
-
-const HOUR_MS = 60 * 60 * 1000;
-const DAY_MS = 24 * HOUR_MS;
-
-function startOfLocalDay(d: Date): Date {
- const out = new Date(d);
- out.setHours(0, 0, 0, 0);
- return out;
-}
-
-function bucketFor(
- ts: number,
- todayMs: number,
- yesterdayMs: number,
- weekStartMs: number
-): GroupKey {
- if (ts >= todayMs) return 'TODAY';
- if (ts >= yesterdayMs) return 'YESTERDAY';
- if (ts >= weekStartMs) return 'THIS WEEK';
- return 'OLDER';
-}
-
-function pad2(n: number): string {
- return n < 10 ? `0${n}` : String(n);
-}
-
-const WEEKDAY_SHORT = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
-const MONTH_SHORT = [
- 'Jan',
- 'Feb',
- 'Mar',
- 'Apr',
- 'May',
- 'Jun',
- 'Jul',
- 'Aug',
- 'Sep',
- 'Oct',
- 'Nov',
- 'Dec',
-];
-
-function formatTime(ts: number, group: GroupKey): string {
- const d = new Date(ts);
- if (group === 'TODAY' || group === 'YESTERDAY') {
- return `${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
- }
- if (group === 'THIS WEEK') {
- return `${WEEKDAY_SHORT[d.getDay()]} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
- }
- return `${MONTH_SHORT[d.getMonth()]} ${d.getDate()}`;
-}
-
-function chunkSubject(chunk: Chunk): string {
- const preview = (chunk.content_preview ?? '').trim();
- if (!preview) return chunk.id;
- // Use the first sentence/line as the subject
- const firstLine = preview.split('\n')[0];
- const sentenceEnd = firstLine.search(/[.!?](?:\s|$)/);
- if (sentenceEnd > 16 && sentenceEnd < 120) {
- return firstLine.slice(0, sentenceEnd + 1).trim();
- }
- return firstLine.length > 140 ? `${firstLine.slice(0, 137)}…` : firstLine;
-}
-
-function chunkSenderLabel(chunk: Chunk): string {
- // Try to derive a sender from source_id; fall back to source kind.
- const left = chunk.source_id.split('|')[0];
- const after = left.includes(':') ? left.split(':').slice(1).join(':') : left;
- return after || chunk.source_kind;
-}
-
-export function MemoryResultList({
- chunks,
- selectedChunkId,
- onSelectChunk,
-}: MemoryResultListProps) {
- const { t } = useT();
- const groups = useMemo<Group[]>(() => {
- const today = startOfLocalDay(new Date()).getTime();
- const yesterday = today - DAY_MS;
- const weekStart = today - 7 * DAY_MS;
-
- const buckets: Record<GroupKey, Chunk[]> = {
- TODAY: [],
- YESTERDAY: [],
- 'THIS WEEK': [],
- OLDER: [],
- };
- for (const c of chunks) {
- buckets[bucketFor(c.timestamp_ms, today, yesterday, weekStart)].push(c);
- }
- const order: GroupKey[] = ['TODAY', 'YESTERDAY', 'THIS WEEK', 'OLDER'];
- return order.map(key => ({ key, chunks: buckets[key] })).filter(g => g.chunks.length > 0);
- }, [chunks]);
-
- const activeRowRef = useRef<HTMLButtonElement | null>(null);
-
- useEffect(() => {
- if (activeRowRef.current) {
- activeRowRef.current.scrollIntoView({ block: 'nearest' });
- }
- }, [selectedChunkId]);
-
- if (chunks.length === 0) {
- return (
- <section className="mw-pane-results" data-testid="memory-result-list">
- <div className="mw-results-empty">{t('memory.noResults')}</div>
- </section>
- );
- }
-
- return (
- <section className="mw-pane-results" data-testid="memory-result-list">
- <div className="mw-pane-scroll">
- {groups.map(group => (
- <div key={group.key} className="mw-results-section">
- <div className="mw-results-section-header">{group.key}</div>
- {group.chunks.map(chunk => {
- const isActive = chunk.id === selectedChunkId;
- return (
- <button
- type="button"
- key={chunk.id}
- ref={isActive ? activeRowRef : undefined}
- className={`mw-result-row${isActive ? ' is-active' : ''}`}
- aria-pressed={isActive}
- onClick={() => onSelectChunk(chunk.id)}
- data-chunk-id={chunk.id}>
- <span className="mw-result-time">
- {formatTime(chunk.timestamp_ms, group.key)}
- </span>
- <span className="mw-result-content">
- <span className="mw-result-subject">{chunkSubject(chunk)}</span>
- <span className="mw-result-meta">
- <span className="mw-result-kind">{chunk.source_kind}</span>
- {' · '}
- {chunkSenderLabel(chunk)} · {chunk.token_count} tok
- </span>
- </span>
- </button>
- );
- })}
- </div>
- ))}
- </div>
- </section>
- );
-}
diff --git a/app/src/components/intelligence/SyncConfirmDialog.test.tsx b/app/src/components/intelligence/SyncConfirmDialog.test.tsx
deleted file mode 100644
index 1430088d28..0000000000
--- a/app/src/components/intelligence/SyncConfirmDialog.test.tsx
+++ /dev/null
@@ -1,110 +0,0 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, test, vi } from 'vitest';
-
-import { callCoreRpc } from '../../services/coreRpcClient';
-import SyncConfirmDialog from './SyncConfirmDialog';
-
-vi.mock('../../services/coreRpcClient', () => ({ callCoreRpc: vi.fn() }));
-
-vi.mock('../../lib/i18n/I18nContext', () => ({
- useT: () => ({
- t: (key: string) =>
- ({
- 'syncConfirm.title': 'Confirm sync',
- 'syncConfirm.message':
- 'This sync will process ~{items} items (~{tokens} tokens, estimated ${cost}).',
- 'syncConfirm.budgetNote': 'Budget limit: ${max}',
- 'syncConfirm.proceed': 'Proceed',
- 'syncConfirm.cancel': 'Cancel',
- 'syncConfirm.estimating': 'Estimating cost...',
- 'common.close': 'Close',
- })[key] ?? key,
- }),
-}));
-
-const estimate = {
- item_count: 12,
- estimated_tokens: 2_400,
- estimated_cost_usd: 0.0123,
- budget_max_cost_usd: 1,
- budget_max_tokens: 10_000,
-};
-
-function deferred<T>() {
- let resolve!: (value: T) => void;
- let reject!: (reason?: unknown) => void;
- const promise = new Promise<T>((res, rej) => {
- resolve = res;
- reject = rej;
- });
- return { promise, resolve, reject };
-}
-
-describe('SyncConfirmDialog', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- test('is a named dialog with loading, error, and ready body states', async () => {
- const request = deferred<{ result: typeof estimate }>();
- vi.mocked(callCoreRpc).mockReturnValue(request.promise);
- const onConfirm = vi.fn();
-
- render(<SyncConfirmDialog sourceId="source-1" onConfirm={onConfirm} onCancel={vi.fn()} />);
-
- expect(screen.getByRole('dialog', { name: 'Confirm sync' })).toBeInTheDocument();
- expect(screen.getByText('Estimating cost...')).toBeInTheDocument();
- expect(screen.getByRole('button', { name: 'Proceed' })).toBeDisabled();
- fireEvent.click(screen.getByRole('button', { name: 'Proceed' }));
- expect(onConfirm).not.toHaveBeenCalled();
-
- request.resolve({ result: estimate });
- expect(
- await screen.findByText('This sync will process ~12 items (~2k tokens, estimated $0.0123).')
- ).toBeInTheDocument();
- expect(screen.getByText('Budget limit: $1.00')).toBeInTheDocument();
- expect(screen.getByRole('button', { name: 'Proceed' })).toBeEnabled();
- });
-
- test('shows estimate errors and keeps confirmation disabled', async () => {
- vi.mocked(callCoreRpc).mockRejectedValue(new Error('Estimate unavailable'));
-
- render(<SyncConfirmDialog sourceId="source-1" onConfirm={vi.fn()} onCancel={vi.fn()} />);
-
- expect(await screen.findByText('Estimate unavailable')).toBeInTheDocument();
- expect(screen.getByRole('button', { name: 'Proceed' })).toBeDisabled();
- expect(screen.getByRole('button', { name: 'Cancel' })).toBeEnabled();
- });
-
- test('cancels from Escape and backdrop and restores focus after dismissal', async () => {
- vi.mocked(callCoreRpc).mockResolvedValue({ result: estimate });
- const trigger = document.createElement('button');
- document.body.appendChild(trigger);
- trigger.focus();
- const onCancel = vi.fn();
- const { unmount } = render(
- <SyncConfirmDialog sourceId="source-1" onConfirm={vi.fn()} onCancel={onCancel} />
- );
-
- // The dialog is backed by Radix now: focus lands on the first focusable
- // element inside the panel rather than on the panel itself, and the overlay
- // is a sibling of the panel rather than its parent.
- expect(screen.getByRole('dialog').contains(document.activeElement)).toBe(true);
- fireEvent.keyDown(document, { key: 'Escape' });
- expect(onCancel).toHaveBeenCalledTimes(1);
-
- // Radix registers its outside-pointer listener in a macrotask (so the click
- // that opened a dialog cannot immediately close it) and treats an outside
- // interaction as pointerdown followed by click, so that a drag out of the
- // panel does not dismiss.
- await new Promise(resolve => setTimeout(resolve, 0));
- const overlay = document.querySelector('[data-slot="dialog-overlay"]') as HTMLElement;
- fireEvent.pointerDown(overlay);
- fireEvent.click(overlay);
- expect(onCancel).toHaveBeenCalledTimes(2);
-
- unmount();
- await waitFor(() => expect(trigger).toHaveFocus());
- trigger.remove();
- });
-});
diff --git a/app/src/components/intelligence/SyncConfirmDialog.tsx b/app/src/components/intelligence/SyncConfirmDialog.tsx
deleted file mode 100644
index 6aa1f100c7..0000000000
--- a/app/src/components/intelligence/SyncConfirmDialog.tsx
+++ /dev/null
@@ -1,95 +0,0 @@
-import { useEffect, useState } from 'react';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import { callCoreRpc } from '../../services/coreRpcClient';
-import { ConfirmDialog } from '../ui';
-
-interface SyncEstimate {
- item_count: number;
- estimated_tokens: number;
- estimated_cost_usd: number;
- budget_max_cost_usd: number | null;
- budget_max_tokens: number | null;
-}
-
-interface SyncConfirmDialogProps {
- sourceId: string;
- onConfirm: () => void;
- onCancel: () => void;
-}
-
-export default function SyncConfirmDialog({
- sourceId,
- onConfirm,
- onCancel,
-}: SyncConfirmDialogProps) {
- const { t } = useT();
- const [estimate, setEstimate] = useState<SyncEstimate | null>(null);
- const [error, setError] = useState<string | null>(null);
-
- useEffect(() => {
- let cancelled = false;
- setEstimate(null);
- setError(null);
- (async () => {
- try {
- const resp = await callCoreRpc<{ result: SyncEstimate }>({
- method: 'openhuman.memory_sources_estimate_sync_cost',
- params: { source_id: sourceId },
- });
- if (!cancelled) setEstimate(resp.result);
- } catch (e) {
- if (!cancelled) setError(e instanceof Error ? e.message : String(e));
- }
- })();
- return () => {
- cancelled = true;
- };
- }, [sourceId]);
-
- const tokenStr = estimate
- ? estimate.estimated_tokens > 1000
- ? `${Math.round(estimate.estimated_tokens / 1000)}k`
- : String(estimate.estimated_tokens)
- : '';
-
- return (
- <ConfirmDialog
- title={t('syncConfirm.title')}
- body={
- <>
- {!estimate && !error && (
- <p className="text-sm text-content-muted">{t('syncConfirm.estimating')}</p>
- )}
-
- {error && <p className="text-sm text-coral-600">{error}</p>}
-
- {estimate && (
- <div className="flex flex-col gap-2">
- <p className="text-sm text-content-secondary">
- {t('syncConfirm.message')
- .replace('{items}', String(estimate.item_count))
- .replace('{tokens}', tokenStr)
- .replace('{cost}', estimate.estimated_cost_usd.toFixed(4))}
- </p>
- {estimate.budget_max_cost_usd != null && (
- <p className="text-xs text-content-muted">
- {t('syncConfirm.budgetNote').replace(
- '{max}',
- estimate.budget_max_cost_usd.toFixed(2)
- )}
- </p>
- )}
- </div>
- )}
- </>
- }
- confirmLabel={t('syncConfirm.proceed')}
- cancelLabel={t('syncConfirm.cancel')}
- confirmDisabled={!estimate}
- destructive={false}
- onConfirm={onConfirm}
- onCancel={onCancel}
- />
- );
-}
diff --git a/app/src/components/intelligence/TeamActivityRail.test.tsx b/app/src/components/intelligence/TeamActivityRail.test.tsx
deleted file mode 100644
index 6db97442e4..0000000000
--- a/app/src/components/intelligence/TeamActivityRail.test.tsx
+++ /dev/null
@@ -1,94 +0,0 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { AgentTeamMember, TeamMessage } from '../../services/api/agentTeamApi';
-import { TeamActivityRail } from './TeamActivityRail';
-
-vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
-
-function member(id: string, name: string): AgentTeamMember {
- return {
- id,
- teamId: 'team-1',
- name,
- memberStatus: 'active',
- createdAt: '2026-01-01T00:00:00Z',
- updatedAt: '2026-01-01T00:00:00Z',
- };
-}
-
-function message(seq: number, from: string, to: string | null, content: string): TeamMessage {
- return {
- runId: 'team-1',
- sequence: seq,
- eventType: 'team_message',
- payload: { from, to, content, visibility: 'team' },
- timestamp: '2026-01-01T00:00:00Z',
- };
-}
-
-const members = [member('m1', 'planner'), member('m2', 'builder')];
-
-describe('TeamActivityRail', () => {
- it('shows the empty state when there are no messages', () => {
- render(<TeamActivityRail messages={[]} members={members} />);
- expect(screen.getByText('intelligence.teams.activity.empty')).toBeInTheDocument();
- });
-
- it('renders sender name and message content', () => {
- render(
- <TeamActivityRail messages={[message(1, 'm1', 'm2', 'split the build')]} members={members} />
- );
- expect(screen.getByText('planner')).toBeInTheDocument();
- expect(screen.getByText('split the build')).toBeInTheDocument();
- expect(screen.getByText('builder', { exact: false })).toBeInTheDocument();
- });
-
- it('labels a broadcast (null recipient) as the team', () => {
- render(<TeamActivityRail messages={[message(1, 'm1', null, 'hi all')]} members={members} />);
- expect(
- screen.getByText('intelligence.teams.activity.toTeam', { exact: false })
- ).toBeInTheDocument();
- });
-
- it('renders no composer without onSend', () => {
- render(<TeamActivityRail messages={[]} members={members} />);
- expect(
- screen.queryByPlaceholderText('intelligence.teams.composer.placeholder')
- ).not.toBeInTheDocument();
- });
-
- it('sends a broadcast (null recipient) with the typed content and clears the draft', async () => {
- const onSend = vi.fn().mockResolvedValue(undefined);
- render(<TeamActivityRail messages={[]} members={members} onSend={onSend} />);
- const input = screen.getByPlaceholderText(
- 'intelligence.teams.composer.placeholder'
- ) as HTMLInputElement;
- fireEvent.change(input, { target: { value: 'ship it' } });
- fireEvent.click(screen.getByLabelText('intelligence.teams.composer.send'));
- expect(onSend).toHaveBeenCalledWith(null, 'ship it');
- await waitFor(() => expect(input.value).toBe(''));
- });
-
- it('sends to the selected teammate and submits on Enter', () => {
- const onSend = vi.fn().mockResolvedValue(undefined);
- render(<TeamActivityRail messages={[]} members={members} onSend={onSend} />);
- fireEvent.change(screen.getByLabelText('intelligence.teams.composer.recipient'), {
- target: { value: 'm2' },
- });
- const input = screen.getByPlaceholderText('intelligence.teams.composer.placeholder');
- fireEvent.change(input, { target: { value: 'your turn' } });
- fireEvent.keyDown(input, { key: 'Enter' });
- expect(onSend).toHaveBeenCalledWith('m2', 'your turn');
- });
-
- it('does not send blank content', () => {
- const onSend = vi.fn();
- render(<TeamActivityRail messages={[]} members={members} onSend={onSend} />);
- fireEvent.change(screen.getByPlaceholderText('intelligence.teams.composer.placeholder'), {
- target: { value: ' ' },
- });
- fireEvent.click(screen.getByLabelText('intelligence.teams.composer.send'));
- expect(onSend).not.toHaveBeenCalled();
- });
-});
diff --git a/app/src/components/intelligence/TeamActivityRail.tsx b/app/src/components/intelligence/TeamActivityRail.tsx
deleted file mode 100644
index d0859e257e..0000000000
--- a/app/src/components/intelligence/TeamActivityRail.tsx
+++ /dev/null
@@ -1,158 +0,0 @@
-/**
- * TeamActivityRail — the live teammate-message timeline for an agent team
- * (#3374 PR2).
- *
- * This is the surface's differentiator: a board of owned tasks is commodity,
- * but seeing the agents *talk to each other while they work* is the thing that
- * makes multi-agent coordination legible. Each entry is a `team_message` run
- * event resolved to `from → to` (member names, with the member's deterministic
- * colour) plus the message body. A `null` recipient means the message was sent
- * to the whole team.
- *
- * The rail renders inside a grid cell that collapses *under* the board on
- * narrow widths (handled by the parent tab's responsive grid), so it is always
- * visible on a wide Intelligence pane and stacks gracefully when cramped.
- */
-import { useState } from 'react';
-import { LuSend } from 'react-icons/lu';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import type { AgentTeamMember, TeamMessage } from '../../services/api/agentTeamApi';
-import { AvatarFallback, AvatarRoot } from '../ui/Avatar';
-import Button from '../ui/Button';
-import NativeSelect from '../ui/NativeSelect';
-import TextField from '../ui/TextField';
-import { memberColor } from './memberColors';
-
-interface TeamActivityRailProps {
- messages: TeamMessage[];
- members: AgentTeamMember[];
- /**
- * When provided, renders a composer footer so the user (as the lead) can
- * address a named teammate, or the whole team when `toMemberId` is `null`.
- */
- onSend?: (toMemberId: string | null, content: string) => void | Promise<void>;
- /** True while a send is in flight (disables the composer). */
- sending?: boolean;
-}
-
-export function TeamActivityRail({ messages, members, onSend, sending }: TeamActivityRailProps) {
- const { t } = useT();
- const memberById = new Map(members.map(m => [m.id, m]));
-
- const [draft, setDraft] = useState('');
- const [recipient, setRecipient] = useState<string>('');
-
- const submit = () => {
- const content = draft.trim();
- if (!content || sending || !onSend) return;
- // Clear the draft only on a resolved send; on rejection keep the unsent text
- // so the user can retry. The empty .catch() handles the rejection (the parent
- // surfaces the error via its own notice state) and prevents an unhandled
- // promise rejection from the now-throwing onSend.
- void Promise.resolve(onSend(recipient === '' ? null : recipient, content))
- .then(() => {
- setDraft('');
- })
- .catch(() => {
- /* send failed — draft retained; error surfaced by the parent */
- });
- };
-
- const nameFor = (id: string | null): string => {
- if (!id) return t('intelligence.teams.activity.toTeam');
- return memberById.get(id)?.name ?? id;
- };
-
- return (
- <aside className="rounded-lg border border-line bg-surface p-3">
- <div className="mb-2 flex items-center justify-between">
- <h3 className="text-[11px] font-semibold uppercase tracking-wide text-content-muted">
- {t('intelligence.teams.activity.title')}
- </h3>
- <span className="text-[10px] text-content-faint">{messages.length}</span>
- </div>
-
- {messages.length === 0 ? (
- <p className="py-6 text-center text-[11px] text-content-faint">
- {t('intelligence.teams.activity.empty')}
- </p>
- ) : (
- <div className="space-y-3">
- {messages.map(message => {
- const fromMember = memberById.get(message.payload.from);
- const fromName = fromMember?.name ?? message.payload.from;
- const color = memberColor(message.payload.from);
- return (
- <div key={`${message.runId}-${message.sequence}`} className="flex gap-2">
- <AvatarRoot className="mt-0.5 h-5 w-5 flex-none">
- <AvatarFallback
- className="text-[9px] font-semibold text-content-inverted"
- style={{ backgroundColor: color }}>
- {fromName.charAt(0).toUpperCase()}
- </AvatarFallback>
- </AvatarRoot>
- <div className="min-w-0">
- <div className="text-[10px] text-content-faint">
- <b className="text-content-secondary">{fromName}</b>
- {' → '}
- {nameFor(message.payload.to)}
- </div>
- <p className="wrap-break-word text-[11px] leading-snug text-content-secondary">
- {message.payload.content}
- </p>
- </div>
- </div>
- );
- })}
- </div>
- )}
-
- {onSend && (
- <div className="mt-3 border-t border-line-subtle pt-2">
- <div className="flex items-center gap-1.5">
- <NativeSelect
- inputSize="sm"
- value={recipient}
- onChange={e => setRecipient(e.target.value)}
- aria-label={t('intelligence.teams.composer.recipient')}
- className="max-w-[40%] flex-none text-[11px] text-content-secondary">
- <option value="">{t('intelligence.teams.composer.toTeam')}</option>
- {members.map(m => (
- <option key={m.id} value={m.id}>
- {m.name}
- </option>
- ))}
- </NativeSelect>
- <TextField
- type="text"
- inputSize="sm"
- value={draft}
- disabled={sending}
- onChange={e => setDraft(e.target.value)}
- onKeyDown={e => {
- if (e.key === 'Enter') {
- e.preventDefault();
- submit();
- }
- }}
- placeholder={t('intelligence.teams.composer.placeholder')}
- className="min-w-0 flex-1 text-[11px] text-content-secondary"
- />
- <Button
- variant="primary"
- iconOnly
- size="xs"
- disabled={sending || draft.trim() === ''}
- onClick={submit}
- aria-label={t('intelligence.teams.composer.send')}
- title={t('intelligence.teams.composer.send')}
- className="h-6 w-6 min-w-0 flex-none bg-primary-500 hover:bg-primary-600">
- <LuSend className="h-3 w-3" />
- </Button>
- </div>
- </div>
- )}
- </aside>
- );
-}
diff --git a/app/src/components/intelligence/TeamHeader.test.tsx b/app/src/components/intelligence/TeamHeader.test.tsx
deleted file mode 100644
index 58e95ccc8b..0000000000
--- a/app/src/components/intelligence/TeamHeader.test.tsx
+++ /dev/null
@@ -1,69 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { AgentTeam, AgentTeamMember } from '../../services/api/agentTeamApi';
-import { TeamHeader } from './TeamHeader';
-
-vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
-
-const team: AgentTeam = {
- id: 'team-1',
- leadAgentId: 'lead',
- status: 'active',
- summary: 'ship it',
- createdAt: '2026-01-01T00:00:00Z',
- updatedAt: '2026-01-01T00:00:00Z',
-};
-
-function member(
- id: string,
- name: string,
- status: AgentTeamMember['memberStatus']
-): AgentTeamMember {
- return {
- id,
- teamId: 'team-1',
- name,
- memberStatus: status,
- createdAt: '2026-01-01T00:00:00Z',
- updatedAt: '2026-01-01T00:00:00Z',
- };
-}
-
-describe('TeamHeader', () => {
- it('renders no start affordance without onStartMember', () => {
- render(<TeamHeader team={team} members={[member('m1', 'alice', 'idle')]} taskCount={1} />);
- expect(screen.queryByLabelText(/intelligence.teams.member.start/)).not.toBeInTheDocument();
- });
-
- it('starts an idle member and omits the button on an active member', () => {
- const onStart = vi.fn();
- render(
- <TeamHeader
- team={team}
- members={[member('m1', 'alice', 'idle'), member('m2', 'bob', 'active')]}
- taskCount={2}
- onStartMember={onStart}
- />
- );
- // Only the idle member exposes a start button.
- const buttons = screen.getAllByLabelText(/intelligence.teams.member.start/);
- expect(buttons).toHaveLength(1);
- fireEvent.click(buttons[0]);
- expect(onStart).toHaveBeenCalledWith('m1');
- });
-
- it('disables the start button for the member being dispatched', () => {
- const onStart = vi.fn();
- render(
- <TeamHeader
- team={team}
- members={[member('m1', 'alice', 'idle')]}
- taskCount={1}
- onStartMember={onStart}
- startingMemberId="m1"
- />
- );
- expect(screen.getByLabelText(/intelligence.teams.member.start/)).toBeDisabled();
- });
-});
diff --git a/app/src/components/intelligence/TeamHeader.tsx b/app/src/components/intelligence/TeamHeader.tsx
deleted file mode 100644
index 7c2dc3bae9..0000000000
--- a/app/src/components/intelligence/TeamHeader.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-/**
- * TeamHeader — the identity strip above a team's task board (#3374 PR2).
- *
- * Shows the team's summary (falling back to its lead agent id), the lead, a
- * task/member count line, and a compact roster of member chips. Each chip
- * carries the member's deterministic colour (so a member reads the same on the
- * header, the board border and the activity rail) and a status dot
- * (active / pending / idle / stopped). For the small teams this surface targets
- * (≈2–5 members) a header strip is the right density — a full sidebar would be
- * heavy furniture for three chips.
- */
-import { LuLoaderCircle, LuPlay } from 'react-icons/lu';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import type {
- AgentTeam,
- AgentTeamMember,
- AgentTeamMemberStatus,
-} from '../../services/api/agentTeamApi';
-import { AvatarFallback, AvatarRoot } from '../ui/Avatar';
-import Badge, { type BadgeVariant } from '../ui/Badge';
-import Button from '../ui/Button';
-import { memberColor } from './memberColors';
-
-/** Badge variant (status colour + dot) per member lifecycle state. */
-const MEMBER_STATUS_VARIANT: Record<AgentTeamMemberStatus, BadgeVariant> = {
- active: 'success',
- pending: 'warning',
- idle: 'neutral',
- stopped: 'danger',
-};
-
-const MEMBER_STATUS_KEY: Record<AgentTeamMemberStatus, string> = {
- active: 'intelligence.teams.member.active',
- pending: 'intelligence.teams.member.pending',
- idle: 'intelligence.teams.member.idle',
- stopped: 'intelligence.teams.member.stopped',
-};
-
-interface TeamHeaderProps {
- team: AgentTeam;
- members: AgentTeamMember[];
- taskCount: number;
- /** When provided, renders a "Start" affordance on each non-active member. */
- onStartMember?: (memberId: string) => void;
- /** Id of the member whose live run is currently being dispatched. */
- startingMemberId?: string | null;
-}
-
-export function TeamHeader({
- team,
- members,
- taskCount,
- onStartMember,
- startingMemberId,
-}: TeamHeaderProps) {
- const { t } = useT();
- const title = team.summary?.trim() || team.leadAgentId;
-
- return (
- <div className="rounded-lg border border-line bg-surface px-3 py-2.5">
- <div className="flex flex-wrap items-start justify-between gap-3">
- <div className="min-w-0">
- <div className="wrap-break-word text-sm font-semibold text-content">{title}</div>
- <div className="mt-0.5 text-[11px] text-content-muted">
- {t('intelligence.teams.header.lead')}{' '}
- <span className="font-mono text-primary-600 dark:text-primary-300">
- {team.leadAgentId}
- </span>
- {' · '}
- {t('intelligence.teams.header.taskCount').replace('{count}', String(taskCount))}
- {' · '}
- {t('intelligence.teams.header.memberCount').replace('{count}', String(members.length))}
- </div>
- </div>
-
- <div className="flex flex-wrap items-center gap-1">
- {members.map(member => (
- <Badge
- key={member.id}
- variant={MEMBER_STATUS_VARIANT[member.memberStatus]}
- title={`${member.agentId ?? member.name} · ${t(MEMBER_STATUS_KEY[member.memberStatus])}`}>
- <AvatarRoot className="h-3.5 w-3.5">
- <AvatarFallback
- className="text-[7px] font-semibold text-content-inverted"
- style={{ backgroundColor: memberColor(member.id) }}>
- {member.name.charAt(0).toUpperCase()}
- </AvatarFallback>
- </AvatarRoot>
- <span className="max-w-28 truncate">{member.name}</span>
- {onStartMember && member.memberStatus !== 'active' && (
- <Button
- variant="tertiary"
- iconOnly
- size="xs"
- disabled={startingMemberId === member.id}
- onClick={() => onStartMember(member.id)}
- title={t('intelligence.teams.member.start')}
- aria-label={`${t('intelligence.teams.member.start')} ${member.name}`}
- className="ml-0.5 h-3.5 w-3.5 min-w-0 flex-none text-primary-600 hover:text-primary-700 dark:text-primary-300">
- {startingMemberId === member.id ? (
- <LuLoaderCircle className="h-3 w-3 animate-spin" />
- ) : (
- <LuPlay className="h-3 w-3" />
- )}
- </Button>
- )}
- </Badge>
- ))}
- </div>
- </div>
- </div>
- );
-}
diff --git a/app/src/components/settings/panels/billing/AutoRechargeSection.tsx b/app/src/components/settings/panels/billing/AutoRechargeSection.tsx
deleted file mode 100644
index 8510e4cb39..0000000000
--- a/app/src/components/settings/panels/billing/AutoRechargeSection.tsx
+++ /dev/null
@@ -1,388 +0,0 @@
-import { useT } from '../../../../lib/i18n/I18nContext';
-import type { AutoRechargeSettings, SavedCard } from '../../../../services/api/creditsApi';
-import { Alert, AlertDescription } from '../../../ui/Alert';
-import Badge from '../../../ui/Badge';
-import Button from '../../../ui/Button';
-import Card from '../../../ui/Card';
-import { WarningIcon } from '../../../ui/icons';
-import Switch from '../../../ui/Switch';
-import { ToggleGroupItem, ToggleGroupRoot } from '../../../ui/ToggleGroup';
-
-// ── Constants ────────────────────────────────────────────────────────────────
-const THRESHOLD_OPTIONS = [5, 10, 20] as const;
-const RECHARGE_OPTIONS = [10, 20, 50, 100] as const;
-const WEEKLY_LIMIT_OPTIONS = [25, 50, 100, 200, 500] as const;
-
-const CARD_BRAND_LABELS: Record<string, string> = {
- visa: 'Visa',
- mastercard: 'Mastercard',
- amex: 'Amex',
- discover: 'Discover',
- jcb: 'JCB',
- diners: 'Diners',
- unionpay: 'UnionPay',
-};
-
-function cardBrandLabel(brand: string) {
- return CARD_BRAND_LABELS[brand.toLowerCase()] ?? brand.charAt(0).toUpperCase() + brand.slice(1);
-}
-
-/** A single-select row of dollar-amount pills backed by `ToggleGroup`. */
-function AmountPicker({
- label,
- options,
- value,
- onChange,
-}: {
- label: string;
- options: readonly number[];
- value: number;
- onChange: (v: number) => void;
-}) {
- return (
- <div>
- <p className="text-[11px] text-content-faint mb-1.5">{label}</p>
- <ToggleGroupRoot
- type="single"
- variant="secondary"
- size="xs"
- value={String(value)}
- onValueChange={next => {
- if (next) onChange(Number(next));
- }}
- className="flex-wrap">
- {options.map(v => (
- <ToggleGroupItem key={v} value={String(v)}>
- ${v}
- </ToggleGroupItem>
- ))}
- </ToggleGroupRoot>
- </div>
- );
-}
-
-interface AutoRechargeSectionProps {
- arSettings: AutoRechargeSettings | null;
- arLoading: boolean;
- arError: string | null;
- arSaving: boolean;
- arThreshold: number;
- arAmount: number;
- arWeeklyLimit: number;
- arDirty: boolean;
- setArThreshold: (v: number) => void;
- setArAmount: (v: number) => void;
- setArWeeklyLimit: (v: number) => void;
- onArToggle: () => void;
- onArSave: () => void;
- // Cards
- cards: SavedCard[];
- cardsLoading: boolean;
- confirmDeleteId: string | null;
- deletingCardId: string | null;
- settingDefaultId: string | null;
- setConfirmDeleteId: (v: string | null) => void;
- onSetDefault: (paymentMethodId: string) => void;
- onDeleteCard: (paymentMethodId: string) => void;
- onAddCard: () => void;
-}
-
-const AutoRechargeSection = ({
- arSettings,
- arLoading,
- arError,
- arSaving,
- arThreshold,
- arAmount,
- arWeeklyLimit,
- arDirty,
- setArThreshold,
- setArAmount,
- setArWeeklyLimit,
- onArToggle,
- onArSave,
- cards,
- cardsLoading,
- confirmDeleteId,
- deletingCardId,
- settingDefaultId,
- setConfirmDeleteId,
- onSetDefault,
- onDeleteCard,
- onAddCard,
-}: AutoRechargeSectionProps) => {
- const { t } = useT();
- return (
- <Card className="rounded-2xl">
- {/* Header row */}
- <div className="flex items-center justify-between p-3">
- <div>
- <p className="text-sm font-semibold text-content">
- {t('settings.billing.autoRecharge.title')}
- </p>
- <p className="text-[11px] text-content-faint mt-0.5">
- {t('settings.billing.autoRecharge.subtitle')}
- </p>
- </div>
- {arLoading ? (
- <div className="w-10 h-5 rounded-full bg-surface-strong animate-pulse" />
- ) : (
- <Switch
- id="auto-recharge-toggle"
- checked={arSettings?.enabled ?? false}
- onCheckedChange={onArToggle}
- disabled={arSaving}
- aria-label={t('settings.billing.autoRecharge.toggleAriaLabel')}
- />
- )}
- </div>
-
- {/* Error banner */}
- {arError && (
- <Alert variant="destructive" className="mx-3 mb-2 items-start rounded-lg py-2">
- <WarningIcon className="w-3.5 h-3.5 shrink-0 mt-0.5" />
- <AlertDescription className="text-[12px] leading-relaxed opacity-100">
- {arError}
- </AlertDescription>
- </Alert>
- )}
-
- {/* Settings — only shown when enabled */}
- {!arLoading && arSettings?.enabled && (
- <div className="px-3 pt-3 pb-2 space-y-3">
- {/* Status row */}
- <div className="flex items-center gap-3 flex-wrap">
- {arSettings.inFlight && (
- <Badge variant="warning" dot={false}>
- <svg className="w-2.5 h-2.5 animate-spin" fill="none" viewBox="0 0 24 24">
- <circle
- className="opacity-25"
- cx="12"
- cy="12"
- r="10"
- stroke="currentColor"
- strokeWidth="4"
- />
- <path
- className="opacity-75"
- fill="currentColor"
- d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
- />
- </svg>
- {t('settings.billing.autoRecharge.rechargeInProgress')}
- </Badge>
- )}
- {arSettings.spentThisWeekUsd > 0 && (
- <span className="text-[10px] text-content-faint">
- {t('settings.billing.autoRecharge.spentThisWeek')
- .replace('{spent}', arSettings.spentThisWeekUsd.toFixed(2))
- .replace('{limit}', String(arSettings.weeklyLimitUsd))}
- </span>
- )}
- {arSettings.lastRechargeAt && (
- <span className="text-[10px] text-content-muted">
- {t('settings.billing.autoRecharge.expires').replace(
- '{date}',
- new Date(arSettings.lastRechargeAt).toLocaleDateString('en-US', {
- month: 'short',
- day: 'numeric',
- })
- )}
- </span>
- )}
- </div>
-
- {/* Last error from recharge attempt */}
- {arSettings.lastError && (
- <Alert variant="destructive" className="items-start rounded-lg py-2 gap-1.5">
- <WarningIcon className="w-3 h-3 shrink-0 mt-0.5" />
- <AlertDescription className="text-[10px] opacity-100">
- {t('settings.billing.autoRecharge.lastRechargeFailed')}: {arSettings.lastError}
- </AlertDescription>
- </Alert>
- )}
-
- {/* Trigger threshold / recharge amount / weekly limit — pill selectors */}
- <AmountPicker
- label={t('settings.billing.autoRecharge.rechargeWhen')}
- options={THRESHOLD_OPTIONS}
- value={arThreshold}
- onChange={setArThreshold}
- />
- <AmountPicker
- label={t('settings.billing.autoRecharge.addAmount')}
- options={RECHARGE_OPTIONS}
- value={arAmount}
- onChange={setArAmount}
- />
- <AmountPicker
- label={t('settings.billing.autoRecharge.weeklyLimit')}
- options={WEEKLY_LIMIT_OPTIONS}
- value={arWeeklyLimit}
- onChange={setArWeeklyLimit}
- />
-
- {/* Validation hint */}
- {arAmount <= arThreshold && (
- <p className="text-[10px] text-amber-400">
- {t('settings.billing.autoRecharge.amountHint')}
- </p>
- )}
-
- {/* Save button */}
- {arDirty && (
- <Button
- type="button"
- variant="primary"
- size="sm"
- onClick={onArSave}
- disabled={arSaving || arAmount <= arThreshold}
- className="w-full">
- {arSaving
- ? t('settings.billing.autoRecharge.saving')
- : t('settings.billing.autoRecharge.saveSettings')}
- </Button>
- )}
- </div>
- )}
-
- {/* Payment methods */}
- <div className="px-3 py-2.5">
- <div className="flex items-center justify-between mb-2">
- <p className="text-[11px] font-medium text-content-secondary">
- {t('settings.billing.autoRecharge.paymentMethods')}
- </p>
- <Button
- type="button"
- variant="tertiary"
- size="xs"
- onClick={onAddCard}
- className="text-primary-500 dark:text-primary-400 hover:text-primary-600 dark:hover:text-primary-300">
- {t('settings.billing.autoRecharge.addCard')}
- </Button>
- </div>
-
- {cardsLoading ? (
- <div className="space-y-1.5">
- {[0, 1].map(i => (
- <div key={i} className="h-9 rounded-lg bg-surface-strong/60 animate-pulse" />
- ))}
- </div>
- ) : cards.length === 0 ? (
- <div className="flex items-center gap-2 rounded-lg bg-surface-muted border border-line p-2.5">
- <svg
- className="w-4 h-4 text-content-muted shrink-0"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={1.5}
- d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"
- />
- </svg>
- <p className="text-[11px] text-content-muted">
- {t('settings.billing.autoRecharge.noCards')}
- </p>
- </div>
- ) : (
- <div className="space-y-1.5">
- {cards.map(card => {
- const isDeleting = deletingCardId === card.id;
- const isSettingDefault = settingDefaultId === card.id;
- const isConfirming = confirmDeleteId === card.id;
-
- return (
- <div
- key={card.id}
- className="flex items-center gap-2 rounded-lg bg-surface-muted border border-line px-2.5 py-2">
- {/* Card icon */}
- <svg
- className="w-4 h-4 text-content-faint shrink-0"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={1.5}
- d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"
- />
- </svg>
-
- {/* Card info */}
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-1.5 flex-wrap">
- <span className="text-xs text-content font-medium">
- {cardBrandLabel(card.brand)} ••••{card.last4}
- </span>
- {card.isDefault && (
- <Badge variant="primary">
- {t('settings.billing.autoRecharge.defaultCard')}
- </Badge>
- )}
- </div>
- <p className="text-[10px] text-content-muted mt-0.5">
- {t('settings.billing.autoRecharge.expires').replace(
- '{date}',
- `${String(card.expMonth).padStart(2, '0')}/${String(card.expYear).slice(-2)}`
- )}
- </p>
- </div>
-
- {/* Actions */}
- <div className="flex items-center gap-1 shrink-0">
- {!card.isDefault && (
- <Button
- type="button"
- variant="tertiary"
- size="xs"
- onClick={() => onSetDefault(card.id)}
- disabled={!!settingDefaultId || !!deletingCardId}>
- {isSettingDefault ? '…' : t('settings.billing.autoRecharge.setDefault')}
- </Button>
- )}
-
- {isConfirming ? (
- <div className="flex items-center gap-1">
- <Button
- type="button"
- variant="primary"
- tone="danger"
- size="xs"
- onClick={() => onDeleteCard(card.id)}
- disabled={isDeleting}>
- {isDeleting ? '…' : t('common.confirm')}
- </Button>
- <Button
- type="button"
- variant="tertiary"
- size="xs"
- onClick={() => setConfirmDeleteId(null)}>
- {t('common.cancel')}
- </Button>
- </div>
- ) : (
- <Button
- type="button"
- variant="tertiary"
- size="xs"
- onClick={() => setConfirmDeleteId(card.id)}
- disabled={isDeleting || !!settingDefaultId}
- className="text-content-muted hover:text-coral-600 dark:hover:text-coral-400">
- {t('common.remove')}
- </Button>
- )}
- </div>
- </div>
- );
- })}
- </div>
- )}
- </div>
- </Card>
- );
-};
-
-export default AutoRechargeSection;
diff --git a/app/src/components/settings/panels/billing/SubscriptionPlans.tsx b/app/src/components/settings/panels/billing/SubscriptionPlans.tsx
deleted file mode 100644
index 70c57b6e4a..0000000000
--- a/app/src/components/settings/panels/billing/SubscriptionPlans.tsx
+++ /dev/null
@@ -1,240 +0,0 @@
-import { useT } from '../../../../lib/i18n/I18nContext';
-import type { PlanTier } from '../../../../types/api';
-import Alert from '../../../ui/Alert';
-import Badge from '../../../ui/Badge';
-import Button from '../../../ui/Button';
-import Card from '../../../ui/Card';
-import { CheckIcon, Spinner } from '../../../ui/icons';
-import { SettingsSwitch } from '../../controls';
-import { annualSavings, isUpgrade as checkIsUpgrade, displayPrice, PLANS } from '../billingHelpers';
-
-interface SubscriptionPlansProps {
- currentTier: PlanTier;
- billingInterval: 'monthly' | 'annual';
- setBillingInterval: (v: 'monthly' | 'annual') => void;
- paymentMethod: 'card' | 'crypto';
- setPaymentMethod: (v: 'card' | 'crypto') => void;
- isPurchasing: boolean;
- purchasingTier: PlanTier | null;
- paymentConfirmed: boolean;
- upgradesDisabled?: boolean;
- onUpgrade: (tier: PlanTier) => void;
-}
-
-const SubscriptionPlans = ({
- currentTier,
- billingInterval,
- setBillingInterval,
- paymentMethod,
- setPaymentMethod,
- isPurchasing,
- purchasingTier,
- paymentConfirmed,
- upgradesDisabled = false,
- onUpgrade,
-}: SubscriptionPlansProps) => {
- const { t } = useT();
- return (
- <>
- <Card className="p-4">
- <h3 className="font-headline text-2xl font-bold tracking-tight text-content">
- {t('settings.billing.subscription.chooseTitle')}
- </h3>
- <p className="mt-1 text-sm text-content-muted">
- {t('settings.billing.subscription.chooseSubtitle')}
- </p>
-
- <div className="mt-4 flex items-center justify-between">
- <div>
- <p className="text-sm font-semibold text-content">
- {t('settings.billing.subscription.cryptoQuestion')}
- </p>
- <p className="mt-0.5 text-xs text-content-muted">
- {t('settings.billing.subscription.cryptoDesc')}
- </p>
- </div>
- <SettingsSwitch
- id="subscription-crypto-toggle"
- checked={paymentMethod === 'crypto'}
- onCheckedChange={next => setPaymentMethod(next ? 'crypto' : 'card')}
- />
- </div>
- </Card>
-
- <div className="flex flex-col gap-4">
- <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
- <div className="mx-auto inline-flex w-fit rounded-full bg-surface p-1 shadow-xs ring-1 ring-line lg:mx-0">
- <Button
- variant={billingInterval === 'monthly' ? 'primary' : 'tertiary'}
- size="sm"
- className="rounded-full"
- onClick={() => {
- if (paymentMethod !== 'crypto') setBillingInterval('monthly');
- }}
- disabled={paymentMethod === 'crypto'}>
- {t('settings.billing.subscription.monthly')}
- </Button>
- <Button
- variant={billingInterval === 'annual' ? 'primary' : 'tertiary'}
- size="sm"
- className="rounded-full"
- onClick={() => setBillingInterval('annual')}>
- {t('settings.billing.subscription.annual')}
- </Button>
- </div>
- </div>
-
- {paymentConfirmed && (
- <Alert variant="success">
- <CheckIcon className="h-4 w-4 shrink-0" />
- <p className="text-sm font-medium">
- {t('settings.billing.subscription.paymentConfirmed')}
- </p>
- </Alert>
- )}
-
- {isPurchasing && (
- <Alert variant="warning">
- <Spinner className="h-4 w-4" />
- <p className="text-sm">{t('settings.billing.subscription.waitingPayment')}</p>
- </Alert>
- )}
-
- <div className="space-y-3">
- {PLANS.map(plan => {
- const isCurrent = plan.tier === currentTier;
- const isUpgrade = checkIsUpgrade(plan.tier, currentTier);
- const savings = annualSavings(plan, billingInterval);
- const isThisPurchasing = isPurchasing && purchasingTier === plan.tier;
- const isPopular = plan.recommended && billingInterval === 'annual';
-
- return (
- <div
- key={plan.tier}
- className={`relative flex flex-col gap-5 rounded-[24px] px-5 py-5 transition-all sm:flex-row sm:items-center sm:justify-between ${
- isPopular
- ? 'bg-primary-50 dark:bg-primary-500/10 ring-2 ring-primary-500 shadow-xs'
- : isCurrent
- ? 'bg-surface ring-1 ring-primary-200 shadow-xs'
- : 'bg-surface ring-1 ring-line shadow-xs'
- }`}>
- <div className="flex items-start gap-4">
- <div
- className={`flex h-12 w-12 min-h-12 min-w-12 shrink-0 items-center justify-center rounded-full ${
- plan.recommended
- ? 'bg-primary-600 text-content-inverted'
- : isCurrent
- ? 'bg-primary-100 dark:bg-primary-500/20 text-primary-700 dark:text-primary-300'
- : 'bg-surface-subtle text-content-secondary'
- }`}>
- {plan.tier === 'PRO' ? (
- <svg className="h-5 w-5" fill="currentColor" viewBox="0 0 24 24">
- <path d="M12 2 9.2 8.5 2 9.2l5.4 4.7-1.6 7.1L12 17l6.2 4-1.6-7.1L22 9.2l-7.2-.7z" />
- </svg>
- ) : plan.tier === 'BASIC' ? (
- <svg
- className="h-5 w-5"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M5 12h14M12 5l7 7-7 7"
- />
- </svg>
- ) : (
- <svg
- className="h-5 w-5"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M12 12c2.761 0 5-2.239 5-5S14.761 2 12 2 7 4.239 7 7s2.239 5 5 5Zm0 2c-4.418 0-8 1.79-8 4v2h16v-2c0-2.21-3.582-4-8-4Z"
- />
- </svg>
- )}
- </div>
-
- <div>
- <div className="flex flex-wrap items-center gap-2">
- <h4 className="font-headline text-xl font-bold tracking-tight text-content">
- {plan.name}
- </h4>
- {isPopular && (
- <Badge variant="primary">
- {t('settings.billing.subscription.popular')}
- </Badge>
- )}
- {isCurrent && !plan.recommended && (
- <Badge variant="success">
- {t('settings.billing.subscription.current')}
- </Badge>
- )}
- </div>
- <div className="mt-3 flex flex-wrap gap-2">
- {plan.features.slice(0, 4).map(feature => (
- <Badge key={feature.text} variant="neutral">
- {feature.text}
- </Badge>
- ))}
- </div>
- </div>
- </div>
-
- <div className="flex items-end justify-between gap-2 sm:min-w-[148px] sm:flex-col sm:items-end">
- <div className="text-right">
- <p className="text-2xl font-bold tracking-tight text-content">
- {displayPrice(plan, billingInterval)}
- {plan.tier !== 'FREE' && (
- <span className="text-sm font-medium text-content-faint">
- {t('settings.billing.subscription.perMonth')}
- </span>
- )}
- </p>
- {plan.tier !== 'FREE' && billingInterval === 'annual' && (
- <p className="mt-1 text-xs text-content-muted">
- {t('settings.billing.subscription.billedAnnually').replace(
- '{price}',
- String(plan.annualPrice)
- )}
- </p>
- )}
- {savings && (
- <p className="mt-1 text-xs font-semibold uppercase text-primary-600 dark:text-primary-300">
- {t('settings.billing.subscription.save').replace('{pct}', String(savings))}
- </p>
- )}
- </div>
-
- {isCurrent ? (
- <Badge variant="primary">
- {t('settings.billing.subscription.currentPlan')}
- </Badge>
- ) : isUpgrade ? (
- <Button
- variant="primary"
- size="sm"
- className="rounded-full"
- onClick={() => onUpgrade(plan.tier)}
- disabled={isPurchasing || upgradesDisabled}>
- {isThisPurchasing
- ? t('settings.billing.subscription.waiting')
- : t('settings.billing.subscription.upgrade')}
- </Button>
- ) : null}
- </div>
- </div>
- );
- })}
- </div>
- </div>
- </>
- );
-};
-
-export default SubscriptionPlans;
diff --git a/app/src/components/settings/panels/billing/__tests__/AutoRechargeSection.test.tsx b/app/src/components/settings/panels/billing/__tests__/AutoRechargeSection.test.tsx
deleted file mode 100644
index ce63a262d7..0000000000
--- a/app/src/components/settings/panels/billing/__tests__/AutoRechargeSection.test.tsx
+++ /dev/null
@@ -1,294 +0,0 @@
-/**
- * AutoRechargeSection — unit tests for the auto-recharge UI component.
- *
- * Target lines: 93, 295, 372, 391
- *
- * 93 — SettingsSwitch rendered when not arLoading (the disabled= prop expression)
- * 295 — empty-state "no cards" branch
- * 372 — set-default button rendered for non-default card
- * 391 — confirm/cancel delete flow
- *
- * NOTE: useT is NOT mocked here — the default I18nContext (en.ts) is active,
- * so all text assertions use the actual English strings from en.ts.
- */
-import { fireEvent, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { AutoRechargeSettings, SavedCard } from '../../../../../services/api/creditsApi';
-import AutoRechargeSection from '../AutoRechargeSection';
-
-// ── Helpers ───────────────────────────────────────────────────────────────────
-
-function makeArSettings(overrides: Partial<AutoRechargeSettings> = {}): AutoRechargeSettings {
- return {
- enabled: true,
- thresholdUsd: 10,
- rechargeAmountUsd: 20,
- weeklyLimitUsd: 100,
- inFlight: false,
- spentThisWeekUsd: 0,
- weekStartDate: '2026-01-01',
- hasSavedPaymentMethod: true,
- lastTriggeredAt: null,
- lastRechargeAt: null,
- lastPaymentIntentId: null,
- lastError: null,
- ...overrides,
- };
-}
-
-function makeCard(overrides: Partial<SavedCard> = {}): SavedCard {
- return {
- id: 'card-1',
- brand: 'visa',
- last4: '4242',
- expMonth: 12,
- expYear: 2028,
- isDefault: false,
- billingDetails: {},
- ...overrides,
- };
-}
-
-const defaultProps = {
- arLoading: false,
- arError: null,
- arSaving: false,
- arThreshold: 10,
- arAmount: 20,
- arWeeklyLimit: 100,
- arDirty: false,
- setArThreshold: vi.fn(),
- setArAmount: vi.fn(),
- setArWeeklyLimit: vi.fn(),
- onArToggle: vi.fn(),
- onArSave: vi.fn(),
- cards: [] as SavedCard[],
- cardsLoading: false,
- confirmDeleteId: null,
- deletingCardId: null,
- settingDefaultId: null,
- setConfirmDeleteId: vi.fn(),
- onSetDefault: vi.fn(),
- onDeleteCard: vi.fn(),
- onAddCard: vi.fn(),
-};
-
-// ── Tests ─────────────────────────────────────────────────────────────────────
-
-describe('AutoRechargeSection — toggle switch (line 93)', () => {
- it('renders the toggle switch when not loading (line 93)', () => {
- render(
- <AutoRechargeSection {...defaultProps} arSettings={makeArSettings({ enabled: false })} />
- );
- // en.ts: 'settings.billing.autoRecharge.toggleAriaLabel': 'Toggle auto-recharge'
- const toggle = screen.getByRole('switch', { name: /Toggle auto-recharge/i });
- expect(toggle).toBeInTheDocument();
- });
-
- it('shows loading skeleton instead of switch when arLoading=true', () => {
- render(<AutoRechargeSection {...defaultProps} arSettings={null} arLoading={true} />);
- // No switch rendered while loading (skeleton div shown instead)
- expect(screen.queryByRole('switch')).not.toBeInTheDocument();
- });
-
- it('calls onArToggle when switch is clicked', () => {
- const onArToggle = vi.fn();
- render(
- <AutoRechargeSection
- {...defaultProps}
- arSettings={makeArSettings({ enabled: false })}
- onArToggle={onArToggle}
- />
- );
- fireEvent.click(screen.getByRole('switch'));
- expect(onArToggle).toHaveBeenCalledTimes(1);
- });
-});
-
-describe('AutoRechargeSection — error banner', () => {
- it('renders error banner when arError is set', () => {
- render(
- <AutoRechargeSection
- {...defaultProps}
- arSettings={makeArSettings()}
- arError="Recharge failed: payment declined"
- />
- );
- expect(screen.getByText('Recharge failed: payment declined')).toBeInTheDocument();
- });
-});
-
-describe('AutoRechargeSection — enabled settings panel', () => {
- it('shows the threshold/amount/weeklyLimit selectors when enabled', () => {
- render(
- <AutoRechargeSection {...defaultProps} arSettings={makeArSettings({ enabled: true })} />
- );
- // en.ts: 'settings.billing.autoRecharge.rechargeWhen': 'Recharge when balance drops below'
- expect(screen.getByText('Recharge when balance drops below')).toBeInTheDocument();
- // en.ts: 'settings.billing.autoRecharge.addAmount': 'Add this amount'
- expect(screen.getByText('Add this amount')).toBeInTheDocument();
- // en.ts: 'settings.billing.autoRecharge.weeklyLimit': 'Weekly spending limit'
- expect(screen.getByText('Weekly spending limit')).toBeInTheDocument();
- });
-
- it('shows Save Settings button when dirty', () => {
- render(
- <AutoRechargeSection
- {...defaultProps}
- arSettings={makeArSettings({ enabled: true })}
- arDirty={true}
- arThreshold={5}
- arAmount={20}
- />
- );
- // en.ts: 'settings.billing.autoRecharge.saveSettings': 'Save Settings'
- expect(screen.getByRole('button', { name: 'Save Settings' })).toBeInTheDocument();
- });
-
- it('calls onArSave when Save is clicked', () => {
- const onArSave = vi.fn();
- render(
- <AutoRechargeSection
- {...defaultProps}
- arSettings={makeArSettings({ enabled: true })}
- arDirty={true}
- arThreshold={5}
- arAmount={20}
- onArSave={onArSave}
- />
- );
- fireEvent.click(screen.getByRole('button', { name: 'Save Settings' }));
- expect(onArSave).toHaveBeenCalledTimes(1);
- });
-
- it('shows last error message from arSettings', () => {
- render(
- <AutoRechargeSection
- {...defaultProps}
- arSettings={makeArSettings({ enabled: true, lastError: 'Card declined' })}
- />
- );
- // en.ts: 'settings.billing.autoRecharge.lastRechargeFailed': 'Last recharge failed'
- expect(screen.getByText(/Last recharge failed/)).toBeInTheDocument();
- expect(screen.getByText(/Card declined/)).toBeInTheDocument();
- });
-
- it('shows recharge in-flight indicator', () => {
- render(
- <AutoRechargeSection
- {...defaultProps}
- arSettings={makeArSettings({ enabled: true, inFlight: true })}
- />
- );
- // en.ts: 'settings.billing.autoRecharge.rechargeInProgress': 'Recharge in progress'
- expect(screen.getByText('Recharge in progress')).toBeInTheDocument();
- });
-});
-
-describe('AutoRechargeSection — payment methods (lines 295, 372, 391)', () => {
- it('shows empty-state when no cards on file (line 295)', () => {
- render(<AutoRechargeSection {...defaultProps} arSettings={makeArSettings()} cards={[]} />);
- // en.ts: 'settings.billing.autoRecharge.noCards': 'No cards'
- expect(screen.getByText('No cards')).toBeInTheDocument();
- });
-
- it('renders cards loading skeleton when cardsLoading=true', () => {
- render(
- <AutoRechargeSection
- {...defaultProps}
- arSettings={makeArSettings()}
- cardsLoading={true}
- cards={[]}
- />
- );
- // No "No cards" text while loading
- expect(screen.queryByText('No cards')).not.toBeInTheDocument();
- });
-
- it('renders card with brand + last4', () => {
- render(
- <AutoRechargeSection
- {...defaultProps}
- arSettings={makeArSettings()}
- cards={[makeCard({ brand: 'visa', last4: '9999' })]}
- />
- );
- expect(screen.getByText(/Visa ••••9999/)).toBeInTheDocument();
- });
-
- it('renders "Set as default" button for non-default card (line 372)', () => {
- const onSetDefault = vi.fn();
- render(
- <AutoRechargeSection
- {...defaultProps}
- arSettings={makeArSettings()}
- cards={[makeCard({ isDefault: false })]}
- onSetDefault={onSetDefault}
- />
- );
- // en.ts: 'settings.billing.autoRecharge.setDefault': 'Set as default'
- const setDefaultBtn = screen.getByRole('button', { name: 'Set as default' });
- expect(setDefaultBtn).toBeInTheDocument();
- fireEvent.click(setDefaultBtn);
- expect(onSetDefault).toHaveBeenCalledWith('card-1');
- });
-
- it('does NOT render "Set as default" for default card', () => {
- render(
- <AutoRechargeSection
- {...defaultProps}
- arSettings={makeArSettings()}
- cards={[makeCard({ isDefault: true })]}
- />
- );
- expect(screen.queryByRole('button', { name: 'Set as default' })).not.toBeInTheDocument();
- // en.ts: 'settings.billing.autoRecharge.defaultCard': 'Default card'
- expect(screen.getByText('Default card')).toBeInTheDocument();
- });
-
- it('shows confirm+cancel when card is in confirmDelete state (line 391)', () => {
- const setConfirmDeleteId = vi.fn();
- const onDeleteCard = vi.fn();
- render(
- <AutoRechargeSection
- {...defaultProps}
- arSettings={makeArSettings()}
- cards={[makeCard()]}
- confirmDeleteId="card-1"
- setConfirmDeleteId={setConfirmDeleteId}
- onDeleteCard={onDeleteCard}
- />
- );
- // Confirm + Cancel buttons visible (en.ts: 'common.confirm', 'common.cancel')
- const confirmBtn = screen.getByRole('button', { name: /confirm/i });
- const cancelBtn = screen.getByRole('button', { name: /cancel/i });
- expect(confirmBtn).toBeInTheDocument();
- expect(cancelBtn).toBeInTheDocument();
-
- // Cancel clears confirmDeleteId
- fireEvent.click(cancelBtn);
- expect(setConfirmDeleteId).toHaveBeenCalledWith(null);
-
- // Confirm calls onDeleteCard
- fireEvent.click(confirmBtn);
- expect(onDeleteCard).toHaveBeenCalledWith('card-1');
- });
-
- it('clicking Remove sets the confirm state', () => {
- const setConfirmDeleteId = vi.fn();
- render(
- <AutoRechargeSection
- {...defaultProps}
- arSettings={makeArSettings()}
- cards={[makeCard()]}
- confirmDeleteId={null}
- setConfirmDeleteId={setConfirmDeleteId}
- />
- );
- // en.ts: 'common.remove': should be 'Remove'
- const removeBtn = screen.getByRole('button', { name: /remove/i });
- fireEvent.click(removeBtn);
- expect(setConfirmDeleteId).toHaveBeenCalledWith('card-1');
- });
-});
diff --git a/app/src/components/settings/panels/billing/__tests__/SubscriptionPlans.test.tsx b/app/src/components/settings/panels/billing/__tests__/SubscriptionPlans.test.tsx
deleted file mode 100644
index 060d71e220..0000000000
--- a/app/src/components/settings/panels/billing/__tests__/SubscriptionPlans.test.tsx
+++ /dev/null
@@ -1,97 +0,0 @@
-/**
- * SubscriptionPlans — unit tests for the subscription plan selector.
- *
- * Target line: 53
- *
- * Line 53 — onCheckedChange of the crypto-toggle SettingsSwitch calls
- * setPaymentMethod('crypto') or setPaymentMethod('card').
- *
- * NOTE: useT is NOT mocked here — default I18nContext (en.ts) is active.
- * All text assertions use actual English strings from en.ts.
- */
-import { fireEvent, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { PlanTier } from '../../../../../types/api';
-import SubscriptionPlans from '../SubscriptionPlans';
-
-// ── Helpers ───────────────────────────────────────────────────────────────────
-
-const defaultProps = {
- currentTier: 'FREE' as PlanTier,
- billingInterval: 'monthly' as const,
- setBillingInterval: vi.fn(),
- paymentMethod: 'card' as const,
- setPaymentMethod: vi.fn(),
- isPurchasing: false,
- purchasingTier: null,
- paymentConfirmed: false,
- onUpgrade: vi.fn(),
-};
-
-// ── Tests ─────────────────────────────────────────────────────────────────────
-
-describe('SubscriptionPlans — crypto toggle (line 53)', () => {
- it('renders the crypto toggle switch', () => {
- render(<SubscriptionPlans {...defaultProps} />);
- // en.ts: 'settings.billing.subscription.cryptoQuestion': 'Want to pay with crypto?'
- expect(screen.getByText('Want to pay with crypto?')).toBeInTheDocument();
- // The switch element exists
- expect(screen.getByRole('switch')).toBeInTheDocument();
- });
-
- it('calls setPaymentMethod("crypto") when switch is toggled on (line 53)', () => {
- const setPaymentMethod = vi.fn();
- render(<SubscriptionPlans {...defaultProps} setPaymentMethod={setPaymentMethod} />);
-
- // Switch starts unchecked (paymentMethod='card')
- const toggle = screen.getByRole('switch');
- fireEvent.click(toggle);
-
- expect(setPaymentMethod).toHaveBeenCalledWith('crypto');
- });
-
- it('calls setPaymentMethod("card") when switch is toggled off', () => {
- const setPaymentMethod = vi.fn();
- render(
- <SubscriptionPlans
- {...defaultProps}
- paymentMethod="crypto"
- setPaymentMethod={setPaymentMethod}
- />
- );
-
- const toggle = screen.getByRole('switch');
- fireEvent.click(toggle);
-
- expect(setPaymentMethod).toHaveBeenCalledWith('card');
- });
-
- it('renders the monthly/annual billing interval buttons', () => {
- render(<SubscriptionPlans {...defaultProps} />);
- // en.ts: 'settings.billing.subscription.monthly': 'Monthly'
- // en.ts: 'settings.billing.subscription.annual': 'Annual'
- expect(screen.getByText('Monthly')).toBeInTheDocument();
- expect(screen.getByText('Annual')).toBeInTheDocument();
- });
-
- it('disables monthly button when crypto payment is selected', () => {
- render(<SubscriptionPlans {...defaultProps} paymentMethod="crypto" />);
- const monthlyBtn = screen.getByText('Monthly').closest('button');
- expect(monthlyBtn).toBeDisabled();
- });
-
- it('shows payment-confirmed banner when paymentConfirmed=true', () => {
- render(<SubscriptionPlans {...defaultProps} paymentConfirmed={true} />);
- // en.ts: 'settings.billing.subscription.paymentConfirmed': 'Payment confirmed'
- expect(screen.getByText('Payment confirmed')).toBeInTheDocument();
- });
-
- it('shows waiting-for-payment banner when isPurchasing=true', () => {
- render(
- <SubscriptionPlans {...defaultProps} isPurchasing={true} purchasingTier={'PRO' as PlanTier} />
- );
- // en.ts: 'settings.billing.subscription.waitingPayment': 'Waiting payment'
- expect(screen.getByText('Waiting payment')).toBeInTheDocument();
- });
-});
diff --git a/app/src/features/conversations/aui/RunModeToggle.test.tsx b/app/src/features/conversations/aui/RunModeToggle.test.tsx
deleted file mode 100644
index 52b30037df..0000000000
--- a/app/src/features/conversations/aui/RunModeToggle.test.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import { combineReducers, configureStore } from '@reduxjs/toolkit';
-import { render, screen } from '@testing-library/react';
-import userEvent from '@testing-library/user-event';
-import { Provider } from 'react-redux';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { callCoreRpc } from '../../../services/coreRpcClient';
-import runModeReducer from '../../../store/runModeSlice';
-import { RunModeToggle } from './RunModeToggle';
-
-vi.mock('../../../services/coreRpcClient', () => ({ callCoreRpc: vi.fn() }));
-
-function renderToggle() {
- const store = configureStore({ reducer: combineReducers({ runMode: runModeReducer }) });
- render(
- <Provider store={store}>
- <RunModeToggle threadId="t1" />
- </Provider>
- );
- return store;
-}
-
-describe('RunModeToggle', () => {
- beforeEach(() => vi.mocked(callCoreRpc).mockReset().mockResolvedValue({}));
-
- it('shows the build label by default', () => {
- renderToggle();
- expect(screen.getByTestId('run-mode-toggle')).toHaveAttribute('data-run-mode', 'build');
- });
-
- it('flips to plan mode on click and calls agent_set_run_mode', async () => {
- const store = renderToggle();
- await userEvent.click(screen.getByTestId('run-mode-toggle'));
-
- expect(store.getState().runMode.byThread.t1).toBe('plan');
- expect(callCoreRpc).toHaveBeenCalledWith({
- method: 'openhuman.agent_set_run_mode',
- params: { thread_id: 't1', mode: 'plan' },
- });
- });
-});
diff --git a/app/src/features/conversations/aui/RunModeToggle.tsx b/app/src/features/conversations/aui/RunModeToggle.tsx
deleted file mode 100644
index 40910afb97..0000000000
--- a/app/src/features/conversations/aui/RunModeToggle.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import { LuHammer, LuMap } from 'react-icons/lu';
-
-import { useT } from '../../../lib/i18n/I18nContext';
-import { useRunMode } from './useRunMode';
-
-/**
- * Composer action button showing and flipping the thread's plan/build run
- * mode. Mounted in `Conversations.tsx`'s `assistantComposerFooterExtras` —
- * the same icon-action row that already holds the background-processes
- * button — following that button's exact markup/classes rather than
- * introducing a new styled toggle.
- *
- * `/plan` and `/build` slash commands are a different workstream's job; they
- * import {@link useRunMode} directly rather than going through this button.
- *
- * Not yet backed by real core behavior: `openhuman.agent_set_run_mode` /
- * `agent_get_run_mode` and `run_mode_changed` are coded to the wire contract
- * but unimplemented by the core as of this writing.
- */
-export function RunModeToggle({ threadId }: { threadId: string }) {
- const { t } = useT();
- const { mode, setMode } = useRunMode(threadId);
- const nextMode = mode === 'plan' ? 'build' : 'plan';
- const label =
- mode === 'plan' ? t('conversations.runMode.plan') : t('conversations.runMode.build');
-
- return (
- <button
- type="button"
- data-testid="run-mode-toggle"
- data-analytics-id="chat-composer-run-mode-toggle"
- data-run-mode={mode}
- onClick={() => void setMode(nextMode)}
- aria-label={t('conversations.runMode.toggleLabel')}
- title={t('conversations.runMode.toggleLabel')}
- className="flex h-7 items-center gap-1.5 rounded-lg px-2 text-content-muted transition-colors hover:bg-surface-hover hover:text-content-secondary">
- {mode === 'plan' ? <LuMap className="h-4 w-4" /> : <LuHammer className="h-4 w-4" />}
- <span className="text-xs font-medium">{label}</span>
- </button>
- );
-}
-
-export default RunModeToggle;
diff --git a/app/src/features/human/Mascot/MascotChipAvatar.test.tsx b/app/src/features/human/Mascot/MascotChipAvatar.test.tsx
deleted file mode 100644
index 6fa79bb03c..0000000000
--- a/app/src/features/human/Mascot/MascotChipAvatar.test.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { describe, expect, it } from 'vitest';
-
-import { MascotChipAvatar } from './MascotChipAvatar';
-import { getMascotPalette, shadeHex } from './mascotPalette';
-
-describe('MascotChipAvatar', () => {
- it('renders the custom GIF (decorative) when a gifUrl is provided', () => {
- render(<MascotChipAvatar color="yellow" gifUrl="https://example.com/avatar.gif" />);
-
- const wrapper = screen.getByTestId('mascot-chip-avatar');
- expect(wrapper).toHaveAttribute('data-variant', 'gif');
-
- const img = wrapper.querySelector('img') as HTMLImageElement;
- expect(img).toBeTruthy();
- expect(img).toHaveAttribute('src', 'https://example.com/avatar.gif');
- // Decorative: the chip's <button> already carries the accessible label.
- expect(img).toHaveAttribute('aria-hidden', 'true');
- });
-
- it('falls back to the lightweight Ghosty SVG when no gifUrl is set', () => {
- render(<MascotChipAvatar color="yellow" />);
-
- const wrapper = screen.getByTestId('mascot-chip-avatar');
- expect(wrapper).toHaveAttribute('data-variant', 'ghosty');
- // The static (non-RAF) mascot is an inline SVG, not the heavy WebGL canvas.
- expect(wrapper.querySelector('svg')).toBeTruthy();
- expect(wrapper.querySelector('canvas')).toBeNull();
- });
-
- it('tints the SVG body with the custom primary colour when color is "custom"', () => {
- render(<MascotChipAvatar color="custom" customPrimary="#abcdef" />);
-
- // GhostyDefs paints the body fill from bodyColor; the custom hex must appear
- // somewhere in the rendered SVG markup.
- const wrapper = screen.getByTestId('mascot-chip-avatar');
- expect(wrapper.innerHTML.toLowerCase()).toContain('#abcdef');
- });
-
- it('uses the palette body colour for a named theme', () => {
- const { bodyFill } = getMascotPalette('navy');
- render(<MascotChipAvatar color="navy" />);
-
- const wrapper = screen.getByTestId('mascot-chip-avatar');
- expect(wrapper.innerHTML.toLowerCase()).toContain(bodyFill.toLowerCase());
- });
-
- it('renders the bright "flat" body so the chip matches the Rive mascot stage', () => {
- // The flat variant derives a lightened highlight stop from the body colour;
- // its presence proves we are NOT using the dark, moody body gradient.
- const highlight = shadeHex(getMascotPalette('yellow').bodyFill, 0.32);
- render(<MascotChipAvatar color="yellow" />);
-
- const wrapper = screen.getByTestId('mascot-chip-avatar');
- expect(wrapper.innerHTML.toLowerCase()).toContain(highlight.toLowerCase());
- // The dark-gradient sentinel stop (#050506) must be absent in flat mode.
- expect(wrapper.innerHTML.toLowerCase()).not.toContain('#050506');
- });
-
- it('applies the requested pixel size to the avatar box', () => {
- render(<MascotChipAvatar color="yellow" size={30} />);
-
- const wrapper = screen.getByTestId('mascot-chip-avatar');
- expect(wrapper).toHaveStyle({ width: '30px', height: '30px' });
- });
-});
diff --git a/app/src/features/human/Mascot/MascotChipAvatar.tsx b/app/src/features/human/Mascot/MascotChipAvatar.tsx
deleted file mode 100644
index ef76821c0c..0000000000
--- a/app/src/features/human/Mascot/MascotChipAvatar.tsx
+++ /dev/null
@@ -1,67 +0,0 @@
-// ---------------------------------------------------------------------------
-// MascotChipAvatar
-//
-// A small, on-brand avatar of the user's mascot for compact, always-on UI
-// (e.g. the "Talk to Tiny" face-mode chip). It renders the user's custom GIF
-// when one is set, otherwise the lightweight `Ghosty` SVG tinted with their
-// chosen palette colour.
-//
-// It deliberately never uses the heavy WebGL `RiveMascot`: a corner chip should
-// not spin up a second GPU animation runtime. The SVG path is rendered with
-// `animated={false}` so there is no idle RAF cost — the mascot only comes to
-// life via the parent's hover treatment (e.g. `group-hover:animate-wiggle`).
-// ---------------------------------------------------------------------------
-import { type FC } from 'react';
-
-import { Ghosty } from './Ghosty';
-import { getMascotPalette, type MascotColor } from './mascotPalette';
-
-interface MascotChipAvatarProps {
- /** The user's selected mascot colour theme. */
- color: MascotColor;
- /** Custom primary body colour, used only when `color === 'custom'`. */
- customPrimary?: string | null;
- /** Custom mascot GIF URL — when set, takes precedence over the SVG mascot. */
- gifUrl?: string | null;
- /** Diameter of the avatar in pixels. */
- size?: number;
-}
-
-export const MascotChipAvatar: FC<MascotChipAvatarProps> = ({
- color,
- customPrimary,
- gifUrl,
- size = 22,
-}) => {
- const palette = getMascotPalette(color);
- const bodyColor = color === 'custom' && customPrimary ? customPrimary : palette.bodyFill;
-
- if (gifUrl) {
- return (
- <span
- className="inline-flex shrink-0 items-center justify-center overflow-hidden rounded-full"
- style={{ width: size, height: size }}
- data-testid="mascot-chip-avatar"
- data-variant="gif">
- <img src={gifUrl} alt="" aria-hidden="true" className="h-full w-full object-cover" />
- </span>
- );
- }
-
- return (
- <span
- className="inline-flex shrink-0 items-center justify-center"
- style={{ width: size, height: size }}
- data-testid="mascot-chip-avatar"
- data-variant="ghosty">
- <Ghosty
- bodyColor={bodyColor}
- face="idle"
- arm="none"
- size={size}
- animated={false}
- variant="flat"
- />
- </span>
- );
-};
diff --git a/app/src/features/human/Mascot/backend/BackendRiveMascot.test.tsx b/app/src/features/human/Mascot/backend/BackendRiveMascot.test.tsx
deleted file mode 100644
index 944a0e8aae..0000000000
--- a/app/src/features/human/Mascot/backend/BackendRiveMascot.test.tsx
+++ /dev/null
@@ -1,100 +0,0 @@
-import { render, screen, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { getCachedMascotDetail, loadMascotRivBuffer } from '../../../../services/mascotService';
-import { BackendRiveMascot } from './BackendRiveMascot';
-import type { MascotDetail, RiveMascotDetail } from './types';
-
-// Capture the props useRive receives so we can assert which source (default
-// src vs. custom buffer) the mascot is rendered from.
-const h = vi.hoisted(() => ({ useRiveParams: [] as Record<string, unknown>[] }));
-
-vi.mock('@rive-app/react-webgl2', () => ({
- Fit: { Contain: 'contain' },
- Layout: class {
- constructor(opts: unknown) {
- Object.assign(this, opts as object);
- }
- },
- useRive: (params: Record<string, unknown>) => {
- h.useRiveParams.push(params);
- return { rive: {}, RiveComponent: () => null };
- },
- useViewModel: () => ({}),
- useViewModelInstance: () => ({}),
- useViewModelInstanceEnum: () => ({ setValue: () => {}, value: null, values: [] }),
- useViewModelInstanceColor: () => ({ setValue: () => {} }),
-}));
-
-vi.mock('../../../../services/mascotService', () => ({
- getCachedMascotDetail: vi.fn(),
- loadMascotRivBuffer: vi.fn(),
-}));
-
-const riveDetail: RiveMascotDetail = {
- id: 'toshi',
- name: 'Toshi',
- version: '1.0.0',
- description: '',
- format: 'rive',
- rivFileUrl: '/mascots/toshi/riv?v=1.0.0',
- defaultState: 'idle',
- stateToPose: {},
- viewModelInputs: [],
-};
-
-function lastSource(): Record<string, unknown> {
- return h.useRiveParams.at(-1) ?? {};
-}
-
-describe('BackendRiveMascot', () => {
- beforeEach(() => {
- h.useRiveParams = [];
- vi.clearAllMocks();
- });
-
- it('renders the version-cached buffer once the mascot resolves', async () => {
- const buffer = new ArrayBuffer(8);
- vi.mocked(getCachedMascotDetail).mockResolvedValue(riveDetail);
- vi.mocked(loadMascotRivBuffer).mockResolvedValue(buffer);
-
- render(<BackendRiveMascot mascotId="toshi" face="idle" />);
-
- // Starts on the bundled default while loading...
- expect(lastSource().src).toBe('/tiny_mascot.riv');
-
- // ...then swaps to the custom buffer.
- await waitFor(() => expect(lastSource().buffer).toBe(buffer));
- expect(loadMascotRivBuffer).toHaveBeenCalledWith(riveDetail);
- });
-
- it('falls back to the default mascot when the load fails', async () => {
- vi.mocked(getCachedMascotDetail).mockRejectedValue(new Error('network'));
-
- render(<BackendRiveMascot mascotId="toshi" />);
-
- await waitFor(() => expect(getCachedMascotDetail).toHaveBeenCalled());
- // Never rendered a buffer — stayed on the bundled default.
- expect(h.useRiveParams.every(p => p.buffer === undefined)).toBe(true);
- expect(lastSource().src).toBe('/tiny_mascot.riv');
- });
-
- it('falls back to the default when the selected mascot is an SVG (non-rive)', async () => {
- const svgDetail = { id: 'old', format: 'svg', states: [] } as unknown as MascotDetail;
- vi.mocked(getCachedMascotDetail).mockResolvedValue(svgDetail);
-
- render(<BackendRiveMascot mascotId="old" />);
-
- await waitFor(() => expect(getCachedMascotDetail).toHaveBeenCalled());
- expect(loadMascotRivBuffer).not.toHaveBeenCalled();
- expect(lastSource().src).toBe('/tiny_mascot.riv');
- });
-
- it('renders a canvas container', () => {
- vi.mocked(getCachedMascotDetail).mockResolvedValue(riveDetail);
- vi.mocked(loadMascotRivBuffer).mockResolvedValue(new ArrayBuffer(8));
- const { container } = render(<BackendRiveMascot mascotId="toshi" size={160} />);
- expect(container.querySelector('[data-face]')).not.toBeNull();
- expect(screen).toBeDefined();
- });
-});
diff --git a/app/src/features/human/Mascot/backend/BackendRiveMascot.tsx b/app/src/features/human/Mascot/backend/BackendRiveMascot.tsx
deleted file mode 100644
index e9f396b7d5..0000000000
--- a/app/src/features/human/Mascot/backend/BackendRiveMascot.tsx
+++ /dev/null
@@ -1,67 +0,0 @@
-// Renders a backend-served Rive mascot selected by id.
-//
-// Fetches the manifest (cached), then resolves the .riv binary through the
-// version-keyed cache (`rivCache` → IndexedDB) so the backend is only hit when
-// the mascot's version changes. While the binary loads — or if it fails — we
-// fall back to the bundled default mascot so the Human stage is never blank.
-import debug from 'debug';
-import { type FC, useEffect, useState } from 'react';
-
-import { getCachedMascotDetail, loadMascotRivBuffer } from '../../../../services/mascotService';
-import type { MascotFace } from '../Ghosty';
-import { RiveMascot } from '../RiveMascot';
-import { isRiveMascotDetail } from './types';
-
-const log = debug('human:mascot:backend-rive');
-
-interface BackendRiveMascotProps {
- mascotId: string;
- face?: MascotFace;
- size?: number | string;
- primaryColor?: number;
- secondaryColor?: number;
- visemeCode?: string;
- idlePoseRotation?: boolean;
-}
-
-export const BackendRiveMascot: FC<BackendRiveMascotProps> = ({ mascotId, ...riveProps }) => {
- // Callers key this component by mascotId so a new selection remounts it with
- // fresh state — meaning the effect never has to synchronously reset here, it
- // only resolves the buffer (or marks failure) asynchronously.
- const [buffer, setBuffer] = useState<ArrayBuffer | null>(null);
- const [failed, setFailed] = useState(false);
-
- useEffect(() => {
- let cancelled = false;
-
- (async () => {
- try {
- const detail = await getCachedMascotDetail(mascotId);
- if (cancelled) return;
- if (!isRiveMascotDetail(detail)) {
- // Selected id is an SVG mascot — not renderable here. Fall back.
- log('mascot %s is not a rive mascot; using default', mascotId);
- setFailed(true);
- return;
- }
- const buf = await loadMascotRivBuffer(detail);
- if (!cancelled) setBuffer(buf);
- } catch (err) {
- if (!cancelled) {
- log('failed to load backend rive mascot %s: %o', mascotId, err);
- setFailed(true);
- }
- }
- })();
-
- return () => {
- cancelled = true;
- };
- }, [mascotId]);
-
- // Default mascot while loading or on failure; the custom buffer once ready.
- // Key the instance so the Rive runtime cleanly reinitialises when the buffer
- // arrives (or when switching mascots) rather than mutating a live context.
- if (failed || !buffer) return <RiveMascot key="default" {...riveProps} />;
- return <RiveMascot key={`buf-${mascotId}`} {...riveProps} buffer={buffer} />;
-};
diff --git a/app/src/features/human/SubMascotLayer.test.tsx b/app/src/features/human/SubMascotLayer.test.tsx
deleted file mode 100644
index 7203056dd9..0000000000
--- a/app/src/features/human/SubMascotLayer.test.tsx
+++ /dev/null
@@ -1,202 +0,0 @@
-import { render, screen, within } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { ToolTimelineEntry } from '../../store/chatRuntimeSlice';
-import { SubMascotLayer, subMascotModelsFromTimeline } from './SubMascotLayer';
-
-vi.mock('./Mascot', async importOriginal => {
- const actual = await importOriginal<typeof import('./Mascot')>();
- return {
- ...actual,
- RiveMascot: ({ face }: { face?: string }) => <div data-testid="rive-mascot" data-face={face} />,
- };
-});
-
-function subagentEntry(overrides: Partial<ToolTimelineEntry> = {}): ToolTimelineEntry {
- return {
- id: 'thread-1:subagent:sub-1:researcher',
- name: 'subagent:researcher',
- round: 1,
- seq: 0,
- status: 'running',
- detail: 'Research the relevant docs.',
- subagent: {
- taskId: 'sub-1',
- agentId: 'researcher',
- childIteration: 1,
- childMaxIterations: 4,
- toolCalls: [],
- },
- ...overrides,
- };
-}
-
-describe('subMascotModelsFromTimeline', () => {
- it('builds visible models only from subagent timeline rows', () => {
- const models = subMascotModelsFromTimeline([
- { id: 'thread-1:tool:search', name: 'web_search', round: 1, seq: 0, status: 'running' },
- subagentEntry(),
- ]);
-
- expect(models).toHaveLength(1);
- expect(models[0]).toMatchObject({
- agentId: 'researcher',
- label: 'Researcher',
- status: 'running',
- face: 'thinking',
- activity: 'Iteration 1/4',
- });
- });
-
- it('uses child tool calls as activity for running subagents', () => {
- // subMascotModelsFromTimeline now filters to status === 'running' only,
- // so success/error entries are excluded from the rendered strip.
- const [running] = subMascotModelsFromTimeline([
- subagentEntry({
- id: 'thread-1:subagent:sub-1:code_executor',
- name: 'subagent:code_executor',
- status: 'running',
- subagent: {
- taskId: 'sub-1',
- agentId: 'code_executor',
- toolCalls: [{ callId: 'call-1', toolName: 'read_file', status: 'running' }],
- },
- }),
- // success and error entries are filtered out — only running ones appear.
- subagentEntry({
- id: 'thread-1:subagent:sub-2:researcher',
- status: 'success',
- subagent: { taskId: 'sub-2', agentId: 'researcher', outputChars: 512, toolCalls: [] },
- }),
- subagentEntry({
- id: 'thread-1:subagent:sub-3:critic',
- name: 'subagent:critic',
- status: 'error',
- subagent: { taskId: 'sub-3', agentId: 'critic', toolCalls: [] },
- }),
- ]);
-
- expect(running?.activity).toBe('Reading file');
- expect(running?.face).toBe('thinking');
- // success and error are filtered out — only 1 model returned.
- expect(
- subMascotModelsFromTimeline([
- subagentEntry({
- status: 'success',
- subagent: { taskId: 'sub-2', agentId: 'researcher', outputChars: 512, toolCalls: [] },
- }),
- subagentEntry({
- status: 'error',
- subagent: { taskId: 'sub-3', agentId: 'critic', toolCalls: [] },
- }),
- ])
- ).toHaveLength(0);
- });
-
- it('prefers subagent displayName from registry over humanized agent id', () => {
- const models = subMascotModelsFromTimeline([
- subagentEntry({
- id: 'thread-1:subagent:sub-1:code_executor',
- name: 'subagent:code_executor',
- subagent: {
- taskId: 'sub-1',
- agentId: 'code_executor',
- displayName: 'Code Executor',
- toolCalls: [],
- },
- }),
- ]);
-
- expect(models).toHaveLength(1);
- expect(models[0].label).toBe('Code Executor');
- });
-
- it('prefers entry displayName when subagent displayName is absent', () => {
- const models = subMascotModelsFromTimeline([
- subagentEntry({
- displayName: 'Custom Label',
- subagent: { taskId: 'sub-1', agentId: 'researcher', toolCalls: [] },
- }),
- ]);
-
- expect(models[0].label).toBe('Custom Label');
- });
-
- it('uses formatToolName for running child tool activity', () => {
- const models = subMascotModelsFromTimeline([
- subagentEntry({
- subagent: {
- taskId: 'sub-1',
- agentId: 'researcher',
- toolCalls: [{ callId: 'c1', toolName: 'web_fetch', status: 'running' }],
- },
- }),
- ]);
-
- // The label is already an activity; the old "Using " prefix made this
- // "Using Fetching".
- expect(models[0].activity).toBe('Reading webpage');
- });
-});
-
-describe('<SubMascotLayer />', () => {
- it('renders only running sub-mascots (success/error are filtered out)', () => {
- // The strip now only shows actively-running subagents; completed/failed
- // ones are dropped so they don't crowd the bottom of the mascot stage.
- render(
- <SubMascotLayer
- entries={[
- subagentEntry(),
- subagentEntry({
- id: 'thread-1:subagent:sub-2:planner',
- name: 'subagent:planner',
- status: 'running',
- subagent: { taskId: 'sub-2', agentId: 'planner', toolCalls: [] },
- }),
- subagentEntry({
- id: 'thread-1:subagent:sub-3:critic',
- name: 'subagent:critic',
- status: 'success',
- subagent: { taskId: 'sub-3', agentId: 'critic', outputChars: 90, toolCalls: [] },
- }),
- subagentEntry({
- id: 'thread-1:subagent:sub-4:auditor',
- name: 'subagent:auditor',
- status: 'error',
- subagent: { taskId: 'sub-4', agentId: 'auditor', toolCalls: [] },
- }),
- ]}
- />
- );
-
- // Only the two running entries should render.
- const mascots = screen.getAllByTestId('sub-mascot');
- expect(mascots).toHaveLength(2);
- expect(screen.getByRole('status', { name: /researcher subagent running/i })).toHaveAttribute(
- 'data-status',
- 'running'
- );
- expect(screen.getByRole('status', { name: /planner subagent running/i })).toHaveAttribute(
- 'data-status',
- 'running'
- );
- // success and error mascots are not rendered.
- expect(screen.queryByRole('status', { name: /critic subagent/i })).not.toBeInTheDocument();
- expect(screen.queryByRole('status', { name: /auditor subagent/i })).not.toBeInTheDocument();
-
- // Bubbles show the label text; activity is in the title attribute.
- const bubbles = screen.getAllByTestId('sub-mascot-bubble');
- expect(within(bubbles[0]!).getByText('Researcher')).toBeInTheDocument();
- expect(within(bubbles[1]!).getByText('Planner')).toBeInTheDocument();
- });
-
- it('renders nothing when no subagent rows are present', () => {
- const { container } = render(
- <SubMascotLayer
- entries={[{ id: 'tool-1', name: 'web_search', round: 1, seq: 0, status: 'running' }]}
- />
- );
-
- expect(container).toBeEmptyDOMElement();
- });
-});
diff --git a/app/src/features/human/SubMascotLayer.tsx b/app/src/features/human/SubMascotLayer.tsx
deleted file mode 100644
index 4a18335f8b..0000000000
--- a/app/src/features/human/SubMascotLayer.tsx
+++ /dev/null
@@ -1,180 +0,0 @@
-import debug from 'debug';
-import { type FC, useMemo } from 'react';
-
-import type { ToolTimelineEntry, ToolTimelineEntryStatus } from '../../store/chatRuntimeSlice';
-import { formatToolName } from '../../utils/toolTimelineFormatting';
-import { type MascotFace, RiveMascot } from './Mascot';
-import type { MascotColor } from './Mascot/mascotPalette';
-
-const subMascotLog = debug('human:sub-mascots');
-
-const MAX_SUB_MASCOTS = 5;
-const ACTIVITY_LIMIT = 74;
-
-const SUB_MASCOT_COLORS: readonly MascotColor[] = ['yellow', 'navy', 'burgundy', 'black'] as const;
-
-const POSITIONS = [
- { left: '72%', top: '18%' },
- { left: '24%', top: '20%' },
- { left: '80%', top: '62%' },
- { left: '18%', top: '64%' },
- { left: '50%', top: '10%' },
-] as const;
-
-interface SubMascotModel {
- id: string;
- agentId: string;
- label: string;
- status: ToolTimelineEntryStatus;
- face: MascotFace;
- activity: string;
- color: MascotColor;
- position: (typeof POSITIONS)[number];
-}
-
-interface SubMascotLayerProps {
- entries: ToolTimelineEntry[];
-}
-
-function hashString(value: string): number {
- let hash = 0;
- for (let i = 0; i < value.length; i += 1) {
- hash = (hash * 31 + value.charCodeAt(i)) >>> 0;
- }
- return hash;
-}
-
-function truncateActivity(value: string): string {
- const trimmed = value.trim().replace(/\s+/g, ' ');
- if (trimmed.length <= ACTIVITY_LIMIT) return trimmed;
- return `${trimmed.slice(0, ACTIVITY_LIMIT - 3).trimEnd()}...`;
-}
-
-function humanizeAgentId(value: string): string {
- const cleaned = value
- .replace(/^subagent:/, '')
- .replace(/[_-]+/g, ' ')
- .trim();
- if (!cleaned) return 'Subagent';
- return cleaned.replace(/\b\w/g, ch => ch.toUpperCase());
-}
-
-function faceForStatus(status: ToolTimelineEntryStatus): MascotFace {
- switch (status) {
- case 'success':
- return 'happy';
- case 'error':
- return 'concerned';
- case 'running':
- default:
- return 'thinking';
- }
-}
-
-function activityForEntry(entry: ToolTimelineEntry): string {
- const subagent = entry.subagent;
- if (!subagent) return 'Starting';
-
- if (entry.status === 'success') {
- return subagent.outputChars ? `Completed ${subagent.outputChars} chars` : 'Completed';
- }
-
- if (entry.status === 'error') {
- return 'Needs attention';
- }
-
- const lastRunningTool = [...subagent.toolCalls].reverse().find(call => call.status === 'running');
- if (lastRunningTool) {
- // The label is already a present-tense activity ("Searching the web");
- // prefixing "Using" produced "Using Searching the web".
- return formatToolName(lastRunningTool.toolName);
- }
-
- if (subagent.childIteration) {
- return subagent.childMaxIterations
- ? `Iteration ${subagent.childIteration}/${subagent.childMaxIterations}`
- : `Step ${subagent.childIteration}`;
- }
-
- if (entry.detail?.trim()) {
- return truncateActivity(entry.detail);
- }
-
- return 'Starting';
-}
-
-export function subMascotModelsFromTimeline(entries: ToolTimelineEntry[]): SubMascotModel[] {
- return entries
- .filter(
- entry =>
- entry.subagent &&
- entry.name.startsWith('subagent:') &&
- // Once a subagent's task is done (success or error), drop it from the
- // strip rather than letting completed mascots linger and crowd the
- // bottom. Only actively-running subagents are surfaced.
- entry.status === 'running'
- )
- .slice(-MAX_SUB_MASCOTS)
- .map((entry, index) => {
- const subagent = entry.subagent!;
- const agentId = subagent.agentId || entry.name.replace(/^subagent:/, '') || 'subagent';
- const colorIndex = hashString(`${subagent.taskId}:${agentId}`) % SUB_MASCOT_COLORS.length;
- return {
- id: entry.id,
- agentId,
- label: entry.subagent?.displayName ?? entry.displayName ?? humanizeAgentId(agentId),
- status: entry.status,
- face: faceForStatus(entry.status),
- activity: activityForEntry(entry),
- color: SUB_MASCOT_COLORS[colorIndex],
- position: POSITIONS[index % POSITIONS.length],
- };
- });
-}
-
-export const SubMascotLayer: FC<SubMascotLayerProps> = ({ entries }) => {
- const models = useMemo(() => subMascotModelsFromTimeline(entries), [entries]);
-
- if (models.length === 0) return null;
-
- subMascotLog(
- 'render count=%d states=%o',
- models.length,
- models.map(model => `${model.agentId}:${model.status}`)
- );
-
- return (
- <div
- className="pointer-events-none absolute inset-x-0 bottom-0 z-10 flex justify-center"
- data-testid="sub-mascot-layer"
- aria-live="polite">
- <div className="flex items-end justify-center gap-3 px-3 pb-2 max-w-full overflow-x-auto">
- {models.map(model => (
- <div
- key={model.id}
- role="status"
- aria-label={`${model.label} subagent ${model.status}`}
- data-testid="sub-mascot"
- data-status={model.status}
- className="flex flex-col items-center w-[72px] shrink-0">
- <div
- className={[
- 'relative w-[56px] h-[56px] transition-opacity duration-500',
- model.status === 'running' ? 'opacity-100' : 'opacity-75',
- ].join(' ')}>
- <div className="drop-shadow-[0_6px_12px_rgba(15,23,42,0.18)]">
- <RiveMascot size="100%" face={model.face} />
- </div>
- </div>
- <div
- className="mt-1 max-w-[88px] rounded-md border border-content-inverted/70 bg-surface/85 px-1.5 py-0.5 text-center text-[9px] leading-tight text-content-secondary shadow-soft backdrop-blur dark:border-line-strong dark:bg-surface/85"
- data-testid="sub-mascot-bubble"
- title={`${model.label} — ${model.activity}`}>
- <div className="truncate font-medium">{model.label}</div>
- </div>
- </div>
- ))}
- </div>
- </div>
- );
-};
diff --git a/app/src/features/share/ShareMessageButton.test.tsx b/app/src/features/share/ShareMessageButton.test.tsx
deleted file mode 100644
index 3725865d85..0000000000
--- a/app/src/features/share/ShareMessageButton.test.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import userEvent from '@testing-library/user-event';
-import { describe, expect, test, vi } from 'vitest';
-
-import { ShareMessageButton } from './ShareMessageButton';
-
-vi.mock('./ShareCardModal', () => ({
- ShareCardModal: ({ onClose }: { onClose: () => void }) => (
- <div data-testid="share-modal">
- <button onClick={onClose}>close</button>
- </div>
- ),
-}));
-
-describe('ShareMessageButton', () => {
- test('renders nothing when there is no shareable content', () => {
- const { container } = render(<ShareMessageButton content=" " agentName="Tiny" />);
- expect(container.firstChild).toBeNull();
- });
-
- test('renders a share trigger for agent content', () => {
- render(<ShareMessageButton content="Did the thing" agentName="Tiny" />);
- expect(screen.getByTestId('chat-message-share')).toBeInTheDocument();
- expect(screen.queryByTestId('share-modal')).not.toBeInTheDocument();
- });
-
- test('opens and closes the share modal', async () => {
- const user = userEvent.setup();
- render(<ShareMessageButton content="Did the thing" agentName="Tiny" threadId="t1" />);
-
- await user.click(screen.getByTestId('chat-message-share'));
- expect(screen.getByTestId('share-modal')).toBeInTheDocument();
-
- await user.click(screen.getByText('close'));
- expect(screen.queryByTestId('share-modal')).not.toBeInTheDocument();
- });
-});
diff --git a/app/src/features/share/ShareMessageButton.tsx b/app/src/features/share/ShareMessageButton.tsx
deleted file mode 100644
index 6dafdd3ab6..0000000000
--- a/app/src/features/share/ShareMessageButton.tsx
+++ /dev/null
@@ -1,68 +0,0 @@
-import { useState } from 'react';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import { ShareCardModal } from './ShareCardModal';
-
-interface ShareMessageButtonProps {
- /** Plain-text agent output to turn into a share card. */
- content: string;
- /** Display name of the agent/profile that produced the output. */
- agentName: string;
- /** Optional thread id, forwarded to inference for log grouping. */
- threadId?: string;
- /** Extra classes for positioning within the message row. */
- className?: string;
-}
-
-/**
- * Hover-revealed "Share" affordance rendered under a completed agent message
- * (issue #5006). Opens `ShareCardModal`. Self-contained so the wiring into the
- * large `Conversations.tsx` message list stays a one-liner. Renders nothing when
- * there is no shareable text.
- */
-export function ShareMessageButton({
- content,
- agentName,
- threadId,
- className = '',
-}: ShareMessageButtonProps) {
- const { t } = useT();
- const [open, setOpen] = useState(false);
-
- if (!content.trim()) return null;
-
- return (
- <>
- <button
- type="button"
- data-analytics-id="chat-message-share"
- data-testid="chat-message-share"
- onClick={() => setOpen(true)}
- title={t('share.button')}
- aria-label={t('share.button')}
- className={`p-1 rounded-md opacity-0 group-hover/msg:opacity-100 hover:bg-surface-hover dark:bg-surface-muted dark:hover:bg-surface-muted text-content-faint hover:text-content-secondary transition-all ${className}`}>
- <svg
- className="w-3.5 h-3.5"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24"
- aria-hidden="true">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M8.7 10.7l6.6-3.4M8.7 13.3l6.6 3.4M18 8a3 3 0 100-6 3 3 0 000 6zM6 15a3 3 0 100-6 3 3 0 000 6zm12 7a3 3 0 100-6 3 3 0 000 6z"
- />
- </svg>
- </button>
- {open ? (
- <ShareCardModal
- content={content}
- agentName={agentName}
- threadId={threadId}
- onClose={() => setOpen(false)}
- />
- ) : null}
- </>
- );
-}
diff --git a/app/src/hooks/__tests__/useLatestAsync.test.ts b/app/src/hooks/__tests__/useLatestAsync.test.ts
deleted file mode 100644
index 938e959dd2..0000000000
--- a/app/src/hooks/__tests__/useLatestAsync.test.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { act, renderHook } from '@testing-library/react';
-import { describe, expect, test } from 'vitest';
-
-import { useLatestAsync } from '../useLatestAsync';
-
-describe('useLatestAsync', () => {
- test('returns monotonically increasing generations and accepts only the newest', () => {
- const { result } = renderHook(() => useLatestAsync());
-
- let first!: number;
- let second!: number;
- act(() => {
- first = result.current.begin();
- second = result.current.begin();
- });
-
- expect(second).toBeGreaterThan(first);
- expect(result.current.isLatest(first)).toBe(false);
- expect(result.current.isLatest(second)).toBe(true);
- });
-
- test('invalidate makes every prior generation stale', () => {
- const { result } = renderHook(() => useLatestAsync());
-
- let generation!: number;
- act(() => {
- generation = result.current.begin();
- result.current.invalidate();
- });
-
- expect(result.current.isLatest(generation)).toBe(false);
- });
-
- test('unmount invalidates outstanding work', () => {
- const { result, unmount } = renderHook(() => useLatestAsync());
- const guard = result.current;
-
- let generation!: number;
- act(() => {
- generation = guard.begin();
- });
- unmount();
-
- expect(guard.isLatest(generation)).toBe(false);
- });
-
- test('returns referentially stable methods across renders', () => {
- const { result, rerender } = renderHook(() => useLatestAsync());
- const initial = result.current;
-
- rerender();
-
- expect(result.current.begin).toBe(initial.begin);
- expect(result.current.isLatest).toBe(initial.isLatest);
- expect(result.current.invalidate).toBe(initial.invalidate);
- });
-});
diff --git a/app/src/hooks/useLatestAsync.ts b/app/src/hooks/useLatestAsync.ts
deleted file mode 100644
index 07ee54a931..0000000000
--- a/app/src/hooks/useLatestAsync.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { useCallback, useEffect, useRef } from 'react';
-
-export interface LatestAsyncGuard {
- begin: () => number;
- isLatest: (generation: number) => boolean;
- invalidate: () => void;
-}
-
-export function useLatestAsync(): LatestAsyncGuard {
- const generationRef = useRef(0);
- const mountedRef = useRef(true);
-
- const begin = useCallback(() => {
- generationRef.current += 1;
- return generationRef.current;
- }, []);
-
- const isLatest = useCallback(
- (generation: number) => mountedRef.current && generation === generationRef.current,
- []
- );
-
- const invalidate = useCallback(() => {
- generationRef.current += 1;
- }, []);
-
- useEffect(() => {
- mountedRef.current = true;
- return () => {
- mountedRef.current = false;
- invalidate();
- };
- }, [invalidate]);
-
- return { begin, isLatest, invalidate };
-}
diff --git a/app/src/hooks/useWalletConfigured.test.ts b/app/src/hooks/useWalletConfigured.test.ts
deleted file mode 100644
index 885921362d..0000000000
--- a/app/src/hooks/useWalletConfigured.test.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-import { renderHook, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { resolveWalletConfigured, useWalletConfigured } from './useWalletConfigured';
-
-const fetchWalletStatus = vi.fn();
-vi.mock('../services/walletApi', () => ({ fetchWalletStatus: () => fetchWalletStatus() }));
-
-describe('wallet-configured gate (#5805)', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- describe('resolveWalletConfigured', () => {
- it('reports `yes` when a wallet is configured', async () => {
- fetchWalletStatus.mockResolvedValue({ configured: true });
- await expect(resolveWalletConfigured()).resolves.toBe('yes');
- });
-
- it('reports `no` when wallet_status resolves with no wallet', async () => {
- fetchWalletStatus.mockResolvedValue({ configured: false });
- await expect(resolveWalletConfigured()).resolves.toBe('no');
- });
-
- // The load-bearing case: a failed status fetch must NOT be reported as
- // `no`. Callers skip their wallet-gated call only on a positive `no`, so
- // collapsing this into `no` would let a transport blip hide a wallet that
- // actually exists.
- it('reports `unknown` — never `no` — when the status fetch itself fails', async () => {
- fetchWalletStatus.mockRejectedValue(new Error('rpc transport failed'));
- await expect(resolveWalletConfigured()).resolves.toBe('unknown');
- });
-
- // It is awaited inline before a gated call, so a rejection here would
- // propagate into the caller it was meant to protect.
- it('never rejects', async () => {
- fetchWalletStatus.mockRejectedValue(new Error('boom'));
- await expect(resolveWalletConfigured()).resolves.toBeDefined();
- });
- });
-
- describe('useWalletConfigured', () => {
- it('starts at `resolving` so callers fire nothing before the answer', async () => {
- fetchWalletStatus.mockResolvedValue({ configured: true });
- const { result } = renderHook(() => useWalletConfigured());
-
- // Synchronously after mount, before the promise settles.
- expect(result.current).toBe('resolving');
- await waitFor(() => expect(result.current).toBe('yes'));
- });
-
- it('settles to `no` when no wallet is configured', async () => {
- fetchWalletStatus.mockResolvedValue({ configured: false });
- const { result } = renderHook(() => useWalletConfigured());
-
- await waitFor(() => expect(result.current).toBe('no'));
- });
-
- it('settles to `unknown` when the status fetch fails', async () => {
- fetchWalletStatus.mockRejectedValue(new Error('rpc transport failed'));
- const { result } = renderHook(() => useWalletConfigured());
-
- await waitFor(() => expect(result.current).toBe('unknown'));
- });
-
- // Unmounting before the probe settles must not set state on a dead
- // component — that is what the `cancelled` flag in the effect cleanup is
- // for, and it is only exercised if a test unmounts mid-flight.
- it('does not set state after unmount', async () => {
- let settle: (value: { configured: boolean }) => void = () => {};
- fetchWalletStatus.mockReturnValue(
- new Promise<{ configured: boolean }>(resolve => {
- settle = resolve;
- })
- );
- const errors: unknown[] = [];
- const spy = vi.spyOn(console, 'error').mockImplementation((...args) => errors.push(args));
-
- const { result, unmount } = renderHook(() => useWalletConfigured());
- expect(result.current).toBe('resolving');
- unmount();
- settle({ configured: true });
- await Promise.resolve();
-
- expect(errors).toHaveLength(0);
- spy.mockRestore();
- });
- });
-});
diff --git a/app/src/hooks/useWalletConfigured.ts b/app/src/hooks/useWalletConfigured.ts
deleted file mode 100644
index eec0ce76cd..0000000000
--- a/app/src/hooks/useWalletConfigured.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-/**
- * Shared wallet-configured gate for wallet-requiring RPCs.
- *
- * ## Why this exists
- *
- * Several core RPCs require the local wallet before they can run
- * (EVM signing, balances, deBridge quotes). When no
- * wallet is set up they reject with the core's `WALLET_NOT_CONFIGURED_MESSAGE`.
- * That is an *expected* state — a wallet is optional and most users never
- * create one — but it still travels as an `Err`, so every such call becomes an
- * error the boundary has to classify.
- *
- * The core-side classifier (`ExpectedErrorKind::WalletNotConfigured`) keeps
- * those out of Sentry, and it is deliberately kept as defense-in-depth. This
- * hook is the other half: **do not make the call at all when we have a positive
- * signal that no wallet exists.** `openhuman.wallet_status` answers the same
- * question and resolves normally for a wallet-less user, so the gate costs one
- * non-erroring RPC and removes an erroring one.
- *
- * This pairs prevention-at-source with boundary classification so the next
- * wallet-gated caller inherits the guard instead of re-deriving it.
- *
- * ## The `unknown` state is load-bearing
- *
- * Gate only on a **positive** "no wallet". If `wallet_status` itself fails we
- * cannot prove the wallet is absent, so we return `unknown` and the caller
- * proceeds — a transport blip must not render a configured wallet as missing.
- * Any wallet error that follows is then handled by the boundary classifier.
- *
- * ## Deliberately not cached
- *
- * Resolution runs per mount. A user who sets up a wallet mid-session must be
- * picked up on the next mount, and a cached `no` would strand them until
- * restart. `wallet_status` is a cheap local RPC that does not error, so there
- * is nothing to save by caching it.
- */
-import { useEffect, useState } from 'react';
-
-import { fetchWalletStatus } from '../services/walletApi';
-
-/**
- * - `resolving` — `wallet_status` still in flight. Callers must NOT fire
- * wallet-requiring RPCs yet.
- * - `no` — resolved, and no wallet is configured. The only state that carries a
- * positive lever to skip a wallet-gated call.
- * - `yes` — a wallet is configured; proceed.
- * - `unknown` — the `wallet_status` fetch itself failed. Proceed, and let the
- * boundary classifier handle any wallet error that follows.
- */
-export type WalletConfigured = 'resolving' | 'no' | 'yes' | 'unknown';
-
-/**
- * Resolve the wallet-configured state once, outside React.
- *
- * Exposed for callers that are not components. Never rejects: a failed status
- * fetch becomes `unknown`.
- */
-export async function resolveWalletConfigured(): Promise<Exclude<WalletConfigured, 'resolving'>> {
- try {
- const status = await fetchWalletStatus();
- return status.configured ? 'yes' : 'no';
- } catch {
- // Cannot prove absence — see "The `unknown` state is load-bearing" above.
- return 'unknown';
- }
-}
-
-/** React binding over {@link resolveWalletConfigured}; `resolving` until settled. */
-export function useWalletConfigured(): WalletConfigured {
- const [configured, setConfigured] = useState<WalletConfigured>('resolving');
- useEffect(() => {
- let cancelled = false;
- void resolveWalletConfigured().then(next => {
- if (!cancelled) setConfigured(next);
- });
- return () => {
- cancelled = true;
- };
- }, []);
- return configured;
-}
diff --git a/app/src/lib/commands/__tests__/useHotkey.test.tsx b/app/src/lib/commands/__tests__/useHotkey.test.tsx
deleted file mode 100644
index e2bf29cfb1..0000000000
--- a/app/src/lib/commands/__tests__/useHotkey.test.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-import { act, render } from '@testing-library/react';
-import { StrictMode, useState } from 'react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { hotkeyManager } from '../hotkeyManager';
-import { ScopeContext } from '../ScopeContext';
-import { useHotkey } from '../useHotkey';
-
-beforeEach(() => {
- hotkeyManager.teardown();
- hotkeyManager.init();
-});
-
-function Wrapper({ children, frame }: { children: React.ReactNode; frame: symbol }) {
- return <ScopeContext.Provider value={frame}>{children}</ScopeContext.Provider>;
-}
-
-function TestHotkey({ shortcut, handler }: { shortcut: string; handler: () => void }) {
- useHotkey(shortcut, handler);
- return null;
-}
-
-describe('useHotkey', () => {
- it('binds on mount and unbinds on unmount', () => {
- const frame = hotkeyManager.pushFrame('global', 'root');
- const handler = vi.fn();
- const { unmount } = render(
- <Wrapper frame={frame}>
- <TestHotkey shortcut="k" handler={handler} />
- </Wrapper>
- );
- window.dispatchEvent(new KeyboardEvent('keydown', { key: 'k' }));
- expect(handler).toHaveBeenCalledTimes(1);
- unmount();
- window.dispatchEvent(new KeyboardEvent('keydown', { key: 'k' }));
- expect(handler).toHaveBeenCalledTimes(1);
- hotkeyManager.popFrame(frame);
- });
-
- it('StrictMode double-mount yields net 1 binding', () => {
- const frame = hotkeyManager.pushFrame('global', 'root');
- const handler = vi.fn();
- render(
- <StrictMode>
- <Wrapper frame={frame}>
- <TestHotkey shortcut="k" handler={handler} />
- </Wrapper>
- </StrictMode>
- );
- window.dispatchEvent(new KeyboardEvent('keydown', { key: 'k' }));
- expect(handler).toHaveBeenCalledTimes(1);
- hotkeyManager.popFrame(frame);
- });
-
- it('handler identity updates via ref without re-registration', () => {
- const frame = hotkeyManager.pushFrame('global', 'root');
- const calls: string[] = [];
- function Inner() {
- const [n, setN] = useState(0);
- useHotkey('k', () => calls.push(`v${n}`));
- return <button onClick={() => setN(v => v + 1)}>bump</button>;
- }
- const { getByText } = render(
- <Wrapper frame={frame}>
- <Inner />
- </Wrapper>
- );
- window.dispatchEvent(new KeyboardEvent('keydown', { key: 'k' }));
- act(() => {
- getByText('bump').click();
- });
- window.dispatchEvent(new KeyboardEvent('keydown', { key: 'k' }));
- expect(calls).toEqual(['v0', 'v1']);
- hotkeyManager.popFrame(frame);
- });
-});
diff --git a/app/src/lib/commands/useHotkey.ts b/app/src/lib/commands/useHotkey.ts
deleted file mode 100644
index 7b7eec1b34..0000000000
--- a/app/src/lib/commands/useHotkey.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { useContext, useEffect, useRef } from 'react';
-
-import { hotkeyManager } from './hotkeyManager';
-import { ScopeContext } from './ScopeContext';
-import type { HotkeyBinding } from './types';
-
-type HotkeyOptions = Omit<HotkeyBinding, 'shortcut' | 'handler'>;
-
-export function useHotkey(
- shortcut: string,
- handler: () => void,
- options: HotkeyOptions = {}
-): void {
- const frame = useContext(ScopeContext);
- const handlerRef = useRef(handler);
- const optsRef = useRef(options);
- handlerRef.current = handler;
- optsRef.current = options;
-
- useEffect(() => {
- const stable = () => handlerRef.current();
- // Always route `enabled` through the ref; callers can toggle it at any
- // render without rebinding.
- const stableEnabled = () => optsRef.current.enabled?.() ?? true;
- const sym = hotkeyManager.bind(frame, {
- shortcut,
- handler: stable,
- allowInInput: optsRef.current.allowInInput,
- repeat: optsRef.current.repeat,
- preventDefault: optsRef.current.preventDefault,
- enabled: stableEnabled,
- description: optsRef.current.description,
- id: optsRef.current.id,
- });
- return () => hotkeyManager.unbind(frame, sym);
- }, [shortcut, frame]);
-}
diff --git a/app/src/pages/Channels.tsx b/app/src/pages/Channels.tsx
deleted file mode 100644
index 2b54cf0aaf..0000000000
--- a/app/src/pages/Channels.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import { useState } from 'react';
-
-import ChannelConfigPanel from '../components/channels/ChannelConfigPanel';
-import ChannelSelector from '../components/channels/ChannelSelector';
-import { useChannelDefinitions } from '../hooks/useChannelDefinitions';
-import { useT } from '../lib/i18n/I18nContext';
-import type { ChannelType } from '../types/channels';
-
-const Channels = () => {
- const { t } = useT();
- const { definitions, loading, error } = useChannelDefinitions();
- const [selectedChannel, setSelectedChannel] = useState<ChannelType>('telegram');
-
- return (
- <div className="flex flex-col h-full overflow-hidden">
- <div className="flex-1 overflow-y-auto p-6 space-y-6">
- {error && (
- <div className="rounded-lg border border-coral-200 dark:border-coral-500/30 bg-coral-50 dark:bg-coral-500/10 px-4 py-3 text-sm text-coral-700 dark:text-coral-300">
- {error}
- </div>
- )}
-
- {loading ? (
- <div className="rounded-xl border border-line bg-surface p-6 text-sm text-content-faint">
- {t('common.loading')}
- </div>
- ) : (
- <>
- <ChannelSelector
- definitions={definitions}
- selectedChannel={selectedChannel}
- onSelectChannel={setSelectedChannel}
- />
- <ChannelConfigPanel selectedChannel={selectedChannel} definitions={definitions} />
- </>
- )}
- </div>
- </div>
- );
-};
-
-export default Channels;
diff --git a/app/src/pages/Home.tsx b/app/src/pages/Home.tsx
deleted file mode 100644
index e1e63abb03..0000000000
--- a/app/src/pages/Home.tsx
+++ /dev/null
@@ -1,274 +0,0 @@
-import { useEffect, useMemo, useState } from 'react';
-import { useNavigate } from 'react-router-dom';
-
-import ConnectionIndicator from '../components/ConnectionIndicator';
-import { DiscordBanner, PromotionalCreditsBanner } from '../components/home/HomeBanners';
-import Button from '../components/ui/Button';
-import { useUser } from '../hooks/useUser';
-import { useT } from '../lib/i18n/I18nContext';
-import { restartCoreProcess } from '../services/coreProcessControl';
-import { selectBlockingState } from '../store/connectivitySelectors';
-import { useAppDispatch, useAppSelector } from '../store/hooks';
-import { resolveTheme, setThemeMode, type ThemeMode } from '../store/themeSlice';
-import { APP_VERSION } from '../utils/config';
-import { resolveUserName } from '../utils/userName';
-
-/** @deprecated Use `resolveUserName` from `utils/userName`. Kept for back-compat. */
-export const resolveHomeUserName = resolveUserName;
-
-const Home = () => {
- const { t } = useT();
- const { user } = useUser();
- const navigate = useNavigate();
- const _userName = resolveHomeUserName(user);
- const userName = _userName.split(' ')[0]; // Get first name only
- const promoCredits = user?.usage?.promotionBalanceUsd ?? 0;
- const isFreeTier =
- user?.subscription?.plan === 'FREE' || !user?.subscription?.hasActiveSubscription;
- const showPromoBanner = isFreeTier && promoCredits > 0.01;
-
- const welcomeVariants = useMemo(
- () => [`Welcome, ${userName} 👋`, `Let's cook, ${userName} 🧑‍🍳.`, `Time to Zone In 🧘🏻`],
- [userName]
- );
- const [welcomeVariantIndex, setWelcomeVariantIndex] = useState(0);
- const [typedWelcome, setTypedWelcome] = useState('');
- const [isDeletingWelcome, setIsDeletingWelcome] = useState(false);
- // 3-way blocking state (#1527) — internet > core > backend > ok. Each
- // failure mode now has its own copy so the user knows *which* link is
- // broken instead of seeing a single conflated "device offline" line.
- const blocking = useAppSelector(selectBlockingState);
- const [isRestartingCore, setIsRestartingCore] = useState(false);
- const [restartError, setRestartError] = useState<string | null>(null);
-
- const dispatch = useAppDispatch();
- const themeMode = useAppSelector(state => state.theme.mode) as ThemeMode;
- const resolvedTheme = resolveTheme(themeMode);
- const isDark = resolvedTheme === 'dark';
- const toggleTheme = () => {
- dispatch(setThemeMode(isDark ? 'light' : 'dark'));
- };
-
- const handleRestartCore = async () => {
- setIsRestartingCore(true);
- setRestartError(null);
- try {
- await restartCoreProcess();
- } catch (err) {
- setRestartError(err instanceof Error ? err.message : String(err));
- } finally {
- setIsRestartingCore(false);
- }
- };
-
- const statusCopy = {
- ok: t('home.statusOk'),
- 'backend-only': t('home.statusBackendOnly'),
- 'hosted-degraded': t('home.statusHostedDegraded'),
- 'hosted-stopped': t('home.statusHostedStopped'),
- 'core-unreachable': t('home.statusCoreUnreachable'),
- 'internet-offline': t('home.statusInternetOffline'),
- }[blocking];
-
- // Open in-app chat.
- const handleStartCooking = async () => {
- navigate('/chat');
- };
-
- useEffect(() => {
- const activeVariant = welcomeVariants[welcomeVariantIndex] ?? '';
- const isFullyTyped = typedWelcome === activeVariant;
- const isFullyDeleted = typedWelcome.length === 0;
-
- const delay = isDeletingWelcome
- ? 36
- : isFullyTyped
- ? 1400
- : typedWelcome.length === 0
- ? 250
- : 55;
-
- const timeoutId = window.setTimeout(() => {
- if (!isDeletingWelcome) {
- if (isFullyTyped) {
- setIsDeletingWelcome(true);
- return;
- }
-
- setTypedWelcome(activeVariant.slice(0, typedWelcome.length + 1));
- return;
- }
-
- if (!isFullyDeleted) {
- setTypedWelcome(activeVariant.slice(0, typedWelcome.length - 1));
- return;
- }
-
- setIsDeletingWelcome(false);
- setWelcomeVariantIndex(current => (current + 1) % welcomeVariants.length);
- }, delay);
-
- return () => window.clearTimeout(timeoutId);
- }, [isDeletingWelcome, typedWelcome, welcomeVariantIndex, welcomeVariants]);
-
- return (
- <div className="min-h-full flex flex-col items-center justify-center p-4">
- {/* Welcome title */}
- <h1 className="min-h-14 text-32l font-bold text-content text-center">
- {typedWelcome}
- <span aria-hidden="true" className="ml-0.5 inline-block text-primary-500 animate-pulse">
- |
- </span>
- </h1>
-
- <div className="max-w-md w-full">
- {showPromoBanner && <PromotionalCreditsBanner promoCredits={promoCredits} />}
-
- {/* Main card — data-walkthrough target for step 1 */}
- <div
- data-walkthrough="home-card"
- className="bg-surface rounded-2xl shadow-soft border border-line p-6 animate-fade-up">
- {/* Header row: version centered, theme toggle right-aligned.
- The empty left spacer matches the toggle's width so the version
- stays visually centered. */}
- <div className="flex items-center justify-between mb-4">
- <div className="w-9" aria-hidden="true" />
- <span className="text-xs text-center text-content-faint">v{APP_VERSION}</span>
- <Button
- iconOnly
- variant="tertiary"
- onClick={toggleTheme}
- aria-label={isDark ? t('home.themeToggle.toLight') : t('home.themeToggle.toDark')}
- title={isDark ? t('home.themeToggle.toLight') : t('home.themeToggle.toDark')}
- className="rounded-full">
- {isDark ? (
- <svg
- className="w-5 h-5"
- fill="none"
- stroke="currentColor"
- strokeWidth={2}
- viewBox="0 0 24 24"
- aria-hidden="true">
- <circle cx="12" cy="12" r="4" />
- <path
- strokeLinecap="round"
- d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"
- />
- </svg>
- ) : (
- <svg
- className="w-5 h-5"
- fill="none"
- stroke="currentColor"
- strokeWidth={2}
- viewBox="0 0 24 24"
- aria-hidden="true">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79Z"
- />
- </svg>
- )}
- </Button>
- </div>
-
- {/* Connection status */}
- <div className="flex justify-center mb-3">
- <ConnectionIndicator />
- </div>
-
- {/* Description — copy mirrors the active blocking state so the
- user never sees a "connected" message while the pill shows a
- failure. (#1527) */}
- <p className="text-sm text-content-muted text-center mb-6 leading-relaxed">
- {statusCopy}
- </p>
-
- {/* Recovery action: only shown when the local core sidecar is
- the broken link — internet/backend outages are not actionable
- from here. */}
- {blocking === 'core-unreachable' && (
- <div className="mb-4">
- <button
- onClick={handleRestartCore}
- disabled={isRestartingCore}
- className="w-full py-3 bg-amber-500 hover:bg-amber-600 disabled:opacity-50 text-content-inverted font-medium rounded-xl transition-colors duration-200">
- {isRestartingCore ? t('home.restartingCore') : t('home.restartCore')}
- </button>
- {restartError && (
- <p className="mt-2 text-xs text-coral-500 text-center">{restartError}</p>
- )}
- </div>
- )}
-
- {/* CTA button — data-walkthrough target for step 2 */}
- <Button
- data-walkthrough="home-cta"
- variant="primary"
- size="lg"
- onClick={handleStartCooking}
- disabled={blocking === 'core-unreachable' || blocking === 'internet-offline'}
- className="w-full">
- {t('home.askAssistant')}
- </Button>
- </div>
-
- <DiscordBanner />
-
- {/* Next steps — compact directory of where to go next */}
- {/* <div className="mt-3 bg-surface rounded-2xl shadow-soft border border-line p-4">
- <div className="text-[11px] uppercase tracking-wide text-content-faint mb-2">Next steps</div>
- <div className="divide-y divide-line-subtle">
- <button
- onClick={() => navigate('/connections')}
- className="w-full flex items-center justify-between py-2.5 text-left hover:bg-surface-muted rounded-md px-2 -mx-2 transition-colors">
- <div>
- <div className="text-sm font-medium text-content">Connect your services</div>
- <div className="text-xs text-content-muted">
- Give your assistant access to Gmail, Calendar, and more.
- </div>
- </div>
- <svg
- className="w-4 h-4 text-content-faint"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M9 5l7 7-7 7"
- />
- </svg>
- </button>
- <button
- onClick={() => navigate('/invites')}
- className="w-full flex items-center justify-between py-2.5 text-left hover:bg-surface-muted rounded-md px-2 -mx-2 transition-colors">
- <div>
- <div className="text-sm font-medium text-content">Invite a friend</div>
- <div className="text-xs text-content-muted">
- Share an invite — both of you get credits.
- </div>
- </div>
- <svg
- className="w-4 h-4 text-content-faint"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M9 5l7 7-7 7"
- />
- </svg>
- </button>
- </div>
- </div> */}
- </div>
- </div>
- );
-};
-
-export default Home;
diff --git a/app/src/pages/__tests__/Channels.test.tsx b/app/src/pages/__tests__/Channels.test.tsx
deleted file mode 100644
index 2ed83916a8..0000000000
--- a/app/src/pages/__tests__/Channels.test.tsx
+++ /dev/null
@@ -1,31 +0,0 @@
-import { screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import { FALLBACK_DEFINITIONS } from '../../lib/channels/definitions';
-import { renderWithProviders } from '../../test/test-utils';
-import Channels from '../Channels';
-
-vi.mock('../../hooks/useChannelDefinitions', () => ({
- useChannelDefinitions: () => ({
- definitions: FALLBACK_DEFINITIONS,
- loading: false,
- error: null,
- refreshDefinitions: vi.fn(),
- }),
-}));
-
-describe('Channels page', () => {
- it('renders the channel selector after loading', async () => {
- renderWithProviders(<Channels />);
-
- expect((await screen.findAllByText('Telegram')).length).toBeGreaterThanOrEqual(1);
- expect(screen.getAllByText('Discord').length).toBeGreaterThanOrEqual(1);
- expect(screen.getAllByText('Web').length).toBeGreaterThanOrEqual(1);
- });
-
- it('renders the Telegram config panel by default', async () => {
- renderWithProviders(<Channels />);
-
- expect(await screen.findByText('Login with OpenHuman')).toBeInTheDocument();
- });
-});
diff --git a/app/src/pages/__tests__/Home.test.tsx b/app/src/pages/__tests__/Home.test.tsx
deleted file mode 100644
index ac2b245050..0000000000
--- a/app/src/pages/__tests__/Home.test.tsx
+++ /dev/null
@@ -1,211 +0,0 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import { resolveHomeUserName } from '../Home';
-
-vi.mock('../../components/ConnectionIndicator', () => ({
- default: () => <div>Connection Indicator</div>,
-}));
-
-vi.mock('../../hooks/useUser', () => ({ useUser: () => ({ user: { firstName: 'Shrey' } }) }));
-
-vi.mock('../../utils/config', async importOriginal => {
- const actual = await importOriginal<typeof import('../../utils/config')>();
- return { ...actual, APP_VERSION: '0.0.0-test' };
-});
-
-vi.mock('react-router-dom', () => ({ useNavigate: () => vi.fn() }));
-
-const mockUseUsageState = vi.hoisted(() =>
- vi.fn(() => ({ shouldShowBudgetCompletedMessage: false }))
-);
-vi.mock('../../hooks/useUsageState', () => ({ useUsageState: mockUseUsageState }));
-
-const mockUseOpenRouterFreeModels = vi.hoisted(() => vi.fn());
-vi.mock('../../services/api/openrouterFreeModels', () => ({
- applyOpenRouterFreeModels: () => mockUseOpenRouterFreeModels(),
-}));
-
-// Default: return 'ok' so most tests see the normal state. The
-// blocking-state selector is the only thing this mock is asked to
-// resolve from the live code; Home.tsx also reads `theme.mode`, which
-// must come back as a ThemeMode string (not 'ok'), so the mock
-// inspects the selector callback to pick the right value.
-const useAppSelectorMock = vi.fn(() => 'ok' as string);
-const useAppDispatchMock = vi.fn(() => vi.fn());
-const themeModeProbe = { current: 'system' as 'system' | 'light' | 'dark' };
-/* eslint-disable react-hooks/rules-of-hooks -- mock factories, not real hooks */
-vi.mock('../../store/hooks', () => ({
- useAppSelector: (selector: unknown) => {
- if (typeof selector === 'function') {
- try {
- const probed = (selector as (s: unknown) => unknown)({
- theme: { mode: themeModeProbe.current },
- });
- if (probed === 'system' || probed === 'light' || probed === 'dark') {
- return probed;
- }
- } catch {
- // Selector didn't tolerate the probe — fall through to default.
- }
- }
- return useAppSelectorMock();
- },
- useAppDispatch: () => useAppDispatchMock(),
-}));
-/* eslint-enable react-hooks/rules-of-hooks */
-
-vi.mock('../../store/socketSelectors', () => ({ selectSocketStatus: vi.fn() }));
-vi.mock('../../store/connectivitySelectors', () => ({ selectBlockingState: vi.fn() }));
-
-vi.mock('../../utils/openUrl', () => ({ openUrl: vi.fn() }));
-
-// Mock restartCoreProcess — default resolves; can be overridden per test.
-const restartCoreProcessMock = vi.fn<() => Promise<void>>();
-vi.mock('../../services/coreProcessControl', () => ({
- restartCoreProcess: () => restartCoreProcessMock(),
-}));
-
-describe('resolveHomeUserName', () => {
- it('uses camelCase name fields when present', () => {
- expect(resolveHomeUserName({ firstName: 'Ada', lastName: 'Lovelace' })).toBe('Ada Lovelace');
- });
-
- it('falls back to snake_case name fields from core snapshot payloads', () => {
- expect(resolveHomeUserName({ first_name: 'Ada', last_name: 'Lovelace' })).toBe('Ada Lovelace');
- });
-
- it('falls back to username when no name fields are present', () => {
- expect(resolveHomeUserName({ username: 'openhuman' })).toBe('@openhuman');
- });
-
- it('falls back to the email local-part when no explicit name exists', () => {
- expect(resolveHomeUserName({ email: '[email protected]' })).toBe('ada');
- });
-
- it('returns User when given null', () => {
- expect(resolveHomeUserName(null)).toBe('User');
- });
-
- it('returns User when given undefined', () => {
- expect(resolveHomeUserName(undefined)).toBe('User');
- });
-
- it('returns User when given an empty object', () => {
- expect(resolveHomeUserName({})).toBe('User');
- });
-
- it('prefixes @-less usernames with @', () => {
- expect(resolveHomeUserName({ username: '@already' })).toBe('@already');
- });
-
- it('returns User when email local-part is empty', () => {
- expect(resolveHomeUserName({ email: '@nodomain.com' })).toBe('User');
- });
-});
-
-describe('Home page — handleRestartCore and blocking state rendering', () => {
- it('shows "Restart Core" button when blocking=core-unreachable (lines 194, 200)', async () => {
- useAppSelectorMock.mockReturnValue('core-unreachable');
-
- const { default: Home } = await import('../Home');
- render(<Home />);
-
- expect(screen.getByRole('button', { name: /Restart Core/i })).toBeInTheDocument();
- });
-
- it('does NOT show "Restart Core" button when blocking=ok (line 194)', async () => {
- useAppSelectorMock.mockReturnValue('ok');
-
- const { default: Home } = await import('../Home');
- render(<Home />);
-
- expect(screen.queryByRole('button', { name: /Restart Core/i })).not.toBeInTheDocument();
- });
-
- it('handleRestartCore calls restartCoreProcess and resets state on success (lines 78-81, 85)', async () => {
- useAppSelectorMock.mockReturnValue('core-unreachable');
-
- restartCoreProcessMock.mockResolvedValueOnce(undefined);
-
- const { default: Home } = await import('../Home');
- render(<Home />);
-
- const btn = screen.getByRole('button', { name: /Restart Core/i });
- fireEvent.click(btn);
-
- // While waiting, the button should be in "Restarting core…" state.
- expect(screen.getByRole('button', { name: /Restarting core/i })).toBeInTheDocument();
-
- // After promise resolves the button label reverts.
- await waitFor(() =>
- expect(screen.getByRole('button', { name: /Restart Core$/i })).toBeInTheDocument()
- );
- expect(restartCoreProcessMock).toHaveBeenCalledTimes(1);
- });
-
- it('handleRestartCore shows error message when restartCoreProcess throws (lines 78-83, 202)', async () => {
- useAppSelectorMock.mockReturnValue('core-unreachable');
-
- restartCoreProcessMock.mockRejectedValueOnce(new Error('sidecar not found'));
-
- const { default: Home } = await import('../Home');
- render(<Home />);
-
- const btn = screen.getByRole('button', { name: /Restart Core/i });
- fireEvent.click(btn);
-
- await waitFor(() => expect(screen.getByText(/sidecar not found/i)).toBeInTheDocument());
- });
-
- it('handleRestartCore shows string error when restartCoreProcess throws a non-Error (lines 83)', async () => {
- useAppSelectorMock.mockReturnValue('core-unreachable');
-
- restartCoreProcessMock.mockRejectedValueOnce('raw string error');
-
- const { default: Home } = await import('../Home');
- render(<Home />);
-
- const btn = screen.getByRole('button', { name: /Restart Core/i });
- fireEvent.click(btn);
-
- await waitFor(() => expect(screen.getByText(/raw string error/i)).toBeInTheDocument());
- });
-});
-
-describe('Home page — theme toggle', () => {
- it('renders "Switch to dark mode" in light mode and dispatches setThemeMode("dark") on click', async () => {
- themeModeProbe.current = 'light';
- const dispatch = vi.fn();
- useAppDispatchMock.mockReturnValue(dispatch);
-
- const { default: Home } = await import('../Home');
- render(<Home />);
-
- const toggle = screen.getByRole('button', { name: /switch to dark mode/i });
- expect(toggle).toBeInTheDocument();
-
- fireEvent.click(toggle);
- expect(dispatch).toHaveBeenCalledWith(
- expect.objectContaining({ type: 'theme/setThemeMode', payload: 'dark' })
- );
- });
-
- it('renders "Switch to light mode" in dark mode and dispatches setThemeMode("light") on click', async () => {
- themeModeProbe.current = 'dark';
- const dispatch = vi.fn();
- useAppDispatchMock.mockReturnValue(dispatch);
-
- const { default: Home } = await import('../Home');
- render(<Home />);
-
- const toggle = screen.getByRole('button', { name: /switch to light mode/i });
- expect(toggle).toBeInTheDocument();
-
- fireEvent.click(toggle);
- expect(dispatch).toHaveBeenCalledWith(
- expect.objectContaining({ type: 'theme/setThemeMode', payload: 'light' })
- );
- themeModeProbe.current = 'system';
- });
-});
diff --git a/app/src/pages/onboarding/pages/ContextPage.tsx b/app/src/pages/onboarding/pages/ContextPage.tsx
deleted file mode 100644
index e341e2831a..0000000000
--- a/app/src/pages/onboarding/pages/ContextPage.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-import * as Sentry from '@sentry/react';
-import { useNavigate } from 'react-router-dom';
-
-import { trackEvent } from '../../../services/analytics';
-import { useOnboardingContext } from '../OnboardingContext';
-import ContextGatheringStep from '../steps/ContextGatheringStep';
-
-const ContextPage = () => {
- const navigate = useNavigate();
- const { draft, completeAndExit } = useOnboardingContext();
-
- return (
- <ContextGatheringStep
- connectedSources={draft.connectedSources}
- // Chat-provider step is disabled for now, so context-gathering is
- // the final step when it runs — finish onboarding directly.
- onNext={() => {
- trackEvent('onboarding_step_complete', { step_name: 'context' });
- // The completeAndExit chain awaits four core RPCs
- // (app_state_update_local_state → app_state_snapshot →
- // config_set_onboarding_completed → app_state_snapshot). When any
- // rejects, the user sees a silent dead "Continue to chat" button
- // (#2081). The `.catch` below kept the rejection out of Sentry's
- // global handlers because a handled rejection never fires
- // `unhandledrejection`. Forward to Sentry explicitly so the
- // dashboard can show whether #2179 (snapshot timeout) closed the
- // symptom in practice.
- void completeAndExit().catch(error => {
- console.error('[onboarding:context-page] completeAndExit failed', error);
- Sentry.captureException(error, {
- tags: { flow: 'onboarding-complete', step: 'continue-to-chat' },
- });
- });
- }}
- onBack={() => navigate('/onboarding/skills')}
- />
- );
-};
-
-export default ContextPage;
diff --git a/app/src/pages/onboarding/pages/__tests__/ContextPage.test.tsx b/app/src/pages/onboarding/pages/__tests__/ContextPage.test.tsx
deleted file mode 100644
index e543fa0c8e..0000000000
--- a/app/src/pages/onboarding/pages/__tests__/ContextPage.test.tsx
+++ /dev/null
@@ -1,77 +0,0 @@
-/**
- * Verifies that `ContextPage` forwards a `completeAndExit` rejection into
- * Sentry with the documented tags (#2081). The handled `.catch` would
- * otherwise keep the failure out of `Sentry.globalHandlersIntegration`, so
- * an explicit capture is the only way the dashboard sees it.
- */
-import { fireEvent, screen, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { renderWithProviders } from '../../../../test/test-utils';
-import { OnboardingContext, type OnboardingContextValue } from '../../OnboardingContext';
-import ContextPage from '../ContextPage';
-
-const hoisted = vi.hoisted(() => ({ captureException: vi.fn() }));
-
-vi.mock('@sentry/react', () => ({ captureException: hoisted.captureException }));
-
-// `trackEvent` writes through to analytics → react-ga4 / Sentry. Stub it so
-// the rejection-capture assertion isn't entangled with consent / GA wiring.
-vi.mock('../../../../services/analytics', () => ({ trackEvent: vi.fn() }));
-
-// The page renders `ContextGatheringStep`, which auto-starts a heavy pipeline
-// on mount when `connectedSources` includes a Composio Gmail entry. Stub it
-// to a button that simply invokes `onNext` so the failure path is reachable
-// without simulating the full pipeline.
-vi.mock('../../steps/ContextGatheringStep', () => ({
- default: ({ onNext }: { onNext: () => void | Promise<void> }) => (
- <button data-testid="continue-to-chat" onClick={() => onNext()}>
- Continue to chat
- </button>
- ),
-}));
-
-function renderContextPage(completeAndExit: OnboardingContextValue['completeAndExit']) {
- const value: OnboardingContextValue = {
- draft: { connectedSources: ['composio:gmail'] },
- setDraft: vi.fn(),
- completeAndExit,
- };
- return renderWithProviders(
- <OnboardingContext.Provider value={value}>
- <ContextPage />
- </OnboardingContext.Provider>
- );
-}
-
-describe('ContextPage — onboarding-complete Sentry capture (#2081)', () => {
- beforeEach(() => {
- hoisted.captureException.mockReset();
- });
-
- it('captures a completeAndExit rejection to Sentry with the documented tags', async () => {
- const failure = new Error('app_state_snapshot timed out');
- const completeAndExit = vi.fn().mockRejectedValue(failure);
-
- renderContextPage(completeAndExit);
- fireEvent.click(screen.getByTestId('continue-to-chat'));
-
- await waitFor(() => expect(hoisted.captureException).toHaveBeenCalledTimes(1));
- expect(completeAndExit).toHaveBeenCalledTimes(1);
-
- const [thrown, ctx] = hoisted.captureException.mock.calls[0];
- expect(thrown).toBe(failure);
- expect(ctx).toEqual({ tags: { flow: 'onboarding-complete', step: 'continue-to-chat' } });
- });
-
- it('does not capture anything when completeAndExit resolves', async () => {
- const completeAndExit = vi.fn().mockResolvedValue(undefined);
-
- renderContextPage(completeAndExit);
- fireEvent.click(screen.getByTestId('continue-to-chat'));
-
- // Let the resolved promise settle.
- await waitFor(() => expect(completeAndExit).toHaveBeenCalledTimes(1));
- expect(hoisted.captureException).not.toHaveBeenCalled();
- });
-});
diff --git a/app/src/pages/onboarding/steps/ApiKeysStep.test.tsx b/app/src/pages/onboarding/steps/ApiKeysStep.test.tsx
deleted file mode 100644
index 540da643f9..0000000000
--- a/app/src/pages/onboarding/steps/ApiKeysStep.test.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-import { screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import { renderWithProviders } from '../../../test/test-utils';
-import ApiKeysStep from './ApiKeysStep';
-
-describe('Onboarding ApiKeysStep', () => {
- it('renders the OpenAI/Anthropic key form with an "or" divider between OAuth and manual key entry', () => {
- renderWithProviders(<ApiKeysStep onNext={vi.fn()} onSkip={vi.fn()} />);
-
- expect(screen.getByTestId('onboarding-api-keys-step')).toBeInTheDocument();
- expect(screen.getByTestId('onboarding-api-keys-openai-input')).toBeInTheDocument();
- expect(screen.getByTestId('onboarding-api-keys-anthropic-input')).toBeInTheDocument();
-
- // The hand-rolled divider divs were replaced with the shared Separator
- // primitive — assert its Radix-driven decorative semantics survive.
- const separators = document.querySelectorAll('[data-slot="separator"]');
- expect(separators).toHaveLength(2);
- separators.forEach(separator => {
- // Decorative (the default): Radix renders `role="none"` rather than
- // `role="separator"`, keeping it out of the a11y tree the same way the
- // hand-rolled `aria-hidden` div it replaced did.
- expect(separator).toHaveAttribute('role', 'none');
- });
- });
-});
diff --git a/app/src/pages/onboarding/steps/ApiKeysStep.tsx b/app/src/pages/onboarding/steps/ApiKeysStep.tsx
deleted file mode 100644
index fc012eb378..0000000000
--- a/app/src/pages/onboarding/steps/ApiKeysStep.tsx
+++ /dev/null
@@ -1,268 +0,0 @@
-import { useCallback, useEffect, useState } from 'react';
-
-import Button from '../../../components/ui/Button';
-import Separator from '../../../components/ui/Separator';
-import { useT } from '../../../lib/i18n/I18nContext';
-import { setCloudProviderKey } from '../../../services/api/aiSettingsApi';
-import { callCoreRpc } from '../../../services/coreRpcClient';
-import { openUrl } from '../../../utils/openUrl';
-import OnboardingNextButton from '../components/OnboardingNextButton';
-
-interface ApiKeysStepProps {
- onNext: () => void;
- onSkip: () => void;
-}
-
-type OpenAiOAuthStatus = { connected: boolean; authMethod?: string | null };
-
-// Fixed OpenAI OAuth loopback origin (mirrors `REDIRECT_URI` in
-// crates/openhuman-core/src/inference/openai_oauth/config.rs). Interpolated into the
-// translated callback hint via the `{url}` placeholder so the literal lives in
-// one place instead of inside all 14 locale strings.
-const OPENAI_OAUTH_CALLBACK_ORIGIN = 'http://127.0.0.1:1455/';
-// Non-display technical sentinel (example redirect URL shown as the input
-// placeholder) — exempt from i18n.
-const OPENAI_OAUTH_CALLBACK_PLACEHOLDER = `${OPENAI_OAUTH_CALLBACK_ORIGIN}auth/callback?code=...&state=...`;
-
-const ApiKeysStep = ({ onNext, onSkip }: ApiKeysStepProps) => {
- const { t } = useT();
- const [openai, setOpenai] = useState('');
- const [anthropic, setAnthropic] = useState('');
- const [saving, setSaving] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const [oauthConnected, setOauthConnected] = useState(false);
- const [oauthBusy, setOauthBusy] = useState(false);
- const [oauthAwaitingCallback, setOauthAwaitingCallback] = useState(false);
- const [oauthCallbackUrl, setOauthCallbackUrl] = useState('');
-
- const refreshOAuthStatus = useCallback(async () => {
- try {
- const res = await callCoreRpc<{ result: OpenAiOAuthStatus }>({
- method: 'openhuman.inference_openai_oauth_status',
- params: {},
- });
- setOauthConnected(Boolean(res?.result?.connected));
- } catch (err) {
- console.debug('[onboarding:api-keys] oauth status check failed', err);
- }
- }, []);
-
- useEffect(() => {
- void refreshOAuthStatus();
- }, [refreshOAuthStatus]);
-
- const handleOpenAiOAuthStart = async () => {
- setOauthBusy(true);
- setError(null);
- try {
- const res = await callCoreRpc<{ result: { authUrl: string } }>({
- method: 'openhuman.inference_openai_oauth_start',
- params: {},
- });
- const authUrl = res?.result?.authUrl?.trim();
- if (!authUrl) {
- throw new Error('missing authUrl');
- }
- setOauthAwaitingCallback(true);
- await openUrl(authUrl);
- } catch (err) {
- console.warn('[onboarding:api-keys] oauth start failed', err);
- setError(t('onboarding.apiKeys.oauthStartFailed'));
- } finally {
- setOauthBusy(false);
- }
- };
-
- const handleOpenAiOAuthComplete = async () => {
- const callback = oauthCallbackUrl.trim();
- if (!callback) {
- setError(t('onboarding.apiKeys.oauthPasteRedirect'));
- return;
- }
- setOauthBusy(true);
- setError(null);
- try {
- await callCoreRpc({
- method: 'openhuman.inference_openai_oauth_complete',
- params: { callback_url: callback },
- });
- setOauthCallbackUrl('');
- setOauthAwaitingCallback(false);
- setOauthConnected(true);
- } catch (err) {
- console.warn('[onboarding:api-keys] oauth complete failed', err);
- setError(t('onboarding.apiKeys.oauthCompleteFailed'));
- } finally {
- setOauthBusy(false);
- }
- };
-
- const handleSave = async () => {
- const trimmedOpenai = openai.trim();
- const trimmedAnthropic = anthropic.trim();
- if (!trimmedOpenai && !trimmedAnthropic && !oauthConnected) {
- onSkip();
- return;
- }
-
- setSaving(true);
- setError(null);
- try {
- if (trimmedOpenai) {
- await setCloudProviderKey('openai', trimmedOpenai);
- }
- if (trimmedAnthropic) {
- await setCloudProviderKey('anthropic', trimmedAnthropic);
- }
- onNext();
- } catch (err) {
- console.warn('[onboarding:api-keys] save failed', err);
- setError(t('onboarding.apiKeys.saveError'));
- } finally {
- setSaving(false);
- }
- };
-
- return (
- <div
- data-testid="onboarding-api-keys-step"
- className="rounded-2xl bg-surface p-10 shadow-soft animate-fade-up">
- <div className="text-center">
- <h1 className="text-2xl font-title text-content mb-2 leading-tight">
- {t('onboarding.apiKeys.title')}
- </h1>
- <p className="text-content-muted text-sm leading-relaxed">
- {t('onboarding.apiKeys.subtitle')}
- </p>
- </div>
-
- <div className="mt-6 flex flex-col gap-4">
- <div className="flex flex-col gap-2 rounded-lg border border-line bg-surface-muted p-3">
- <div className="flex flex-wrap items-center justify-between gap-2">
- <span className="text-xs font-medium text-content-secondary">
- {t('onboarding.apiKeys.openaiLabel')}
- </span>
- {oauthConnected ? (
- <span
- data-testid="onboarding-openai-oauth-connected"
- className="text-xs font-medium text-sage-700 dark:text-sage-300">
- {t('onboarding.apiKeys.openaiOauthConnected')}
- </span>
- ) : null}
- </div>
- <p className="text-[11px] text-content-muted">
- {t('onboarding.apiKeys.openaiOauthHint')}
- </p>
- <button
- type="button"
- data-testid="onboarding-openai-oauth-connect"
- disabled={oauthBusy || oauthConnected || saving}
- onClick={() => void handleOpenAiOAuthStart()}
- className="rounded-lg border border-primary-500 bg-primary-50 dark:bg-primary-500/10 px-3 py-2 text-sm font-medium text-primary-700 dark:text-primary-300 hover:bg-primary-100 dark:hover:bg-primary-500/20 disabled:opacity-50">
- {oauthBusy
- ? t('onboarding.apiKeys.openaiOauthOpening')
- : t('onboarding.apiKeys.openaiOauthConnect')}
- </button>
- {oauthAwaitingCallback && !oauthConnected ? (
- <div className="flex flex-col gap-1.5">
- <p className="text-[11px] text-content-muted">
- {t('onboarding.apiKeys.openaiOauthCallbackHint').replace(
- '{url}',
- OPENAI_OAUTH_CALLBACK_ORIGIN
- )}
- </p>
- <input
- data-testid="onboarding-openai-oauth-callback-input"
- type="text"
- autoComplete="off"
- spellCheck={false}
- placeholder={OPENAI_OAUTH_CALLBACK_PLACEHOLDER}
- value={oauthCallbackUrl}
- onChange={e => {
- setOauthCallbackUrl(e.target.value);
- setError(null);
- }}
- className="rounded-lg border border-line-strong bg-surface px-3 py-2 text-xs text-content placeholder-content-faint focus:border-primary-500 focus:outline-hidden focus:ring-1 focus:ring-primary-500"
- />
- <button
- type="button"
- data-testid="onboarding-openai-oauth-complete"
- disabled={oauthBusy || saving}
- onClick={() => void handleOpenAiOAuthComplete()}
- className="self-start text-xs font-medium text-primary-600 dark:text-primary-400 underline disabled:opacity-50">
- {t('onboarding.apiKeys.finishSignIn')}
- </button>
- </div>
- ) : null}
- <div className="relative flex items-center gap-2 py-1">
- <Separator className="flex-1 bg-surface-strong" />
- <span className="text-[10px] uppercase tracking-wide text-content-faint">
- {t('onboarding.apiKeys.orApiKey')}
- </span>
- <Separator className="flex-1 bg-surface-strong" />
- </div>
- <input
- id="onboarding-openai-key"
- data-testid="onboarding-api-keys-openai-input"
- type="password"
- autoComplete="off"
- spellCheck={false}
- placeholder={t('onboarding.apiKeys.openaiPlaceholder')}
- value={openai}
- onChange={e => {
- setOpenai(e.target.value);
- setError(null);
- }}
- className="rounded-lg border border-line-strong bg-surface px-3 py-2 text-sm text-content placeholder-content-faint focus:border-primary-500 focus:outline-hidden focus:ring-1 focus:ring-primary-500"
- />
- </div>
-
- <div className="flex flex-col gap-1.5">
- <label
- htmlFor="onboarding-anthropic-key"
- className="text-xs font-medium text-content-secondary">
- {t('onboarding.apiKeys.anthropicLabel')}
- </label>
- <input
- id="onboarding-anthropic-key"
- data-testid="onboarding-api-keys-anthropic-input"
- type="password"
- autoComplete="off"
- spellCheck={false}
- placeholder={t('onboarding.apiKeys.anthropicPlaceholder')}
- value={anthropic}
- onChange={e => {
- setAnthropic(e.target.value);
- setError(null);
- }}
- className="rounded-lg border border-line-strong bg-surface px-3 py-2 text-sm text-content placeholder-content-faint focus:border-primary-500 focus:outline-hidden focus:ring-1 focus:ring-primary-500"
- />
- </div>
-
- {error ? <p className="text-xs font-medium text-red-600">{error}</p> : null}
- </div>
-
- <div className="mt-8">
- <OnboardingNextButton
- label={t('onboarding.apiKeys.continue')}
- loading={saving}
- loadingLabel={t('onboarding.apiKeys.saving')}
- onClick={() => void handleSave()}
- />
- </div>
-
- <div className="mt-4 flex justify-center">
- <Button
- variant="tertiary"
- size="xs"
- onClick={onSkip}
- disabled={saving}
- className="underline">
- {t('onboarding.apiKeys.skipForNow')}
- </Button>
- </div>
- </div>
- );
-};
-
-export default ApiKeysStep;
diff --git a/app/src/pages/onboarding/steps/ContextGatheringStep.tsx b/app/src/pages/onboarding/steps/ContextGatheringStep.tsx
deleted file mode 100644
index 47e3c098bd..0000000000
--- a/app/src/pages/onboarding/steps/ContextGatheringStep.tsx
+++ /dev/null
@@ -1,487 +0,0 @@
-/**
- * Onboarding step that gathers user context from connected integrations.
- *
- * Orchestrates the LinkedIn-enrichment pipeline directly in TypeScript:
- *
- * 1. Composio Gmail search (`tools_composio_execute` -> `GMAIL_FETCH_EMAILS`)
- * to find a LinkedIn profile URL in the user's recent mail.
- * 2. Apify LinkedIn scrape — disabled (unreliable); stage is skipped.
- * 3. Persist a URL-only markdown via `learning_save_profile` with
- * `summarize=true` so the core LLM compresses it into PROFILE.md.
- *
- * External calls still go through core (auth, proxy, billing). Only the
- * stage-by-stage orchestration lives in the renderer.
- */
-import * as Sentry from '@sentry/react';
-import { useEffect, useRef, useState } from 'react';
-
-import { useT } from '../../../lib/i18n/I18nContext';
-import { callCoreRpc, getCoreRpcUrl, testCoreRpcConnection } from '../../../services/coreRpcClient';
-import OnboardingNextButton from '../components/OnboardingNextButton';
-
-/**
- * Threshold after which the building-profile UI swaps to the "still working"
- * staged copy (#2156). Real first-launch completions on slow M-series Macs
- * can take 30–40s, so users would otherwise see what looks like a stall at
- * the global RPC timeout boundary.
- */
-const STILL_WORKING_THRESHOLD_MS = 30_000;
-
-/** How often we probe `core.ping` after entering the still-working state. */
-const ALIVE_PROBE_INTERVAL_MS = 5_000;
-
-/**
- * Per-probe network budget. `testCoreRpcConnection` uses raw `fetch()` with
- * no built-in timeout, so we have to bound the probe ourselves — otherwise a
- * TCP black-hole (firewall drop, suspended laptop wake) lets the first probe
- * hang forever and the single-flight guard blocks every subsequent tick.
- */
-const PROBE_TIMEOUT_MS = 3_000;
-
-type AliveState = 'unknown' | 'probing' | 'alive' | 'unreachable';
-
-interface ContextGatheringStepProps {
- connectedSources: string[];
- onNext: () => void | Promise<void>;
- onBack?: () => void;
-}
-
-/** Unwrap the Outcome CLI envelope the core wraps around responses. */
-function unwrapCliEnvelope<T>(value: unknown): T {
- if (
- value !== null &&
- typeof value === 'object' &&
- 'result' in (value as Record<string, unknown>) &&
- 'logs' in (value as Record<string, unknown>)
- ) {
- return (value as { result: T }).result;
- }
- return value as T;
-}
-
-interface Stage {
- id: 'gmail-search' | 'linkedin-scrape' | 'build-profile';
- labelKey: string;
-}
-
-const STAGES: Stage[] = [
- { id: 'gmail-search', labelKey: 'onboarding.contextGathering.stageGmail' },
- { id: 'linkedin-scrape', labelKey: 'onboarding.contextGathering.stageLinkedIn' },
- { id: 'build-profile', labelKey: 'onboarding.contextGathering.stageProfile' },
-];
-
-type StageStatus = 'pending' | 'active' | 'done' | 'skipped' | 'error';
-
-// LinkedIn `comm/in/<slug>` (notification-email form) and `in/<slug>`
-// (canonical) — same regex as `crates/openhuman-core/src/agent/learning/linkedin_enrichment.rs`.
-const LINKEDIN_RE =
- /https?:\/\/(?:www\.|[a-z]{2,3}\.)?linkedin\.com\/(?:comm\/)?in\/([a-zA-Z0-9_-]+)/;
-
-function canonicalLinkedInUrl(slug: string): string {
- return `https://www.linkedin.com/in/${slug}`;
-}
-
-function stageNow(): number {
- return globalThis.performance?.now() ?? Date.now();
-}
-
-function durationMs(startedAt: number): number {
- return Math.round(stageNow() - startedAt);
-}
-
-function errorReason(error: unknown): string {
- if (error instanceof Error && error.message.trim()) return error.message;
- if (typeof error === 'string' && error.trim()) return error;
- return 'unknown';
-}
-
-/** URL-safe base64 → utf-8 string (Gmail body parts arrive in this form). */
-function decodeBase64Url(s: string): string {
- try {
- const padded = s.replace(/-/g, '+').replace(/_/g, '/');
- const pad = padded.length % 4 === 0 ? '' : '='.repeat(4 - (padded.length % 4));
- const bin = atob(padded + pad);
- const bytes = new Uint8Array(bin.length);
- for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
- return new TextDecoder('utf-8').decode(bytes);
- } catch {
- return '';
- }
-}
-
-/**
- * Walk a Gmail-API-shaped message payload, decoding any base64 body parts,
- * and concatenate everything into a single searchable string.
- */
-function extractSearchableText(message: unknown): string {
- const parts: string[] = [];
- const visit = (node: unknown) => {
- if (!node || typeof node !== 'object') return;
- const obj = node as Record<string, unknown>;
- if (typeof obj.messageText === 'string') parts.push(obj.messageText);
- if (typeof obj.snippet === 'string') parts.push(obj.snippet);
- const body = obj.body as Record<string, unknown> | undefined;
- if (body && typeof body.data === 'string') parts.push(decodeBase64Url(body.data));
- const subParts = obj.parts;
- if (Array.isArray(subParts)) for (const p of subParts) visit(p);
- const payload = obj.payload;
- if (payload) visit(payload);
- };
- visit(message);
- return parts.join('\n');
-}
-
-interface ComposioExecuteResult {
- successful: boolean;
- data: unknown;
- error?: string | null;
-}
-
-async function findLinkedInUrlViaComposio(): Promise<string | null> {
- console.debug('[onboarding:context] composio GMAIL_FETCH_EMAILS');
- const raw = await callCoreRpc<unknown>({
- method: 'openhuman.tools_composio_execute',
- params: {
- action: 'GMAIL_FETCH_EMAILS',
- params: { query: 'from:linkedin.com', max_results: 10 },
- },
- });
- const result = unwrapCliEnvelope<ComposioExecuteResult>(raw);
- if (!result.successful) {
- throw new Error(result.error ?? 'GMAIL_FETCH_EMAILS failed');
- }
- const data = result.data as { messages?: unknown[] } | null;
- const messages = Array.isArray(data?.messages) ? data!.messages : [];
- for (const msg of messages) {
- const text = extractSearchableText(msg);
- const m = text.match(LINKEDIN_RE);
- if (m) return canonicalLinkedInUrl(m[1]);
- }
- return null;
-}
-
-/**
- * First-launch profile compression on slow hardware (#2156) can run past the
- * global 30s RPC timeout while the core LLM compressor finishes. Use a
- * longer-but-still-bounded budget so users with a slow-but-alive core are
- * not parked on the post-login fallback when the call would otherwise
- * succeed. Real failures still abort within `SAVE_PROFILE_TIMEOUT_MS`.
- */
-const SAVE_PROFILE_TIMEOUT_MS = 90_000;
-
-async function saveProfile(markdown: string): Promise<void> {
- await callCoreRpc<unknown>({
- method: 'openhuman.learning_save_profile',
- params: { markdown, summarize: true },
- timeoutMs: SAVE_PROFILE_TIMEOUT_MS,
- });
-}
-
-const ContextGatheringStep = ({
- connectedSources,
- onNext,
- onBack: _onBack,
-}: ContextGatheringStepProps) => {
- const { t } = useT();
- // Stage statuses are tracked in a ref — they drive pipeline branching only,
- // not rendering, so there is no need to trigger re-renders on each update.
- const stageStatusesRef = useRef<Record<string, StageStatus>>(
- Object.fromEntries(STAGES.map(s => [s.id, 'pending' as StageStatus]))
- );
- const [finished, setFinished] = useState(false);
- const [hasError, setHasError] = useState(false);
- // Staged "still working" mode kicks in after STILL_WORKING_THRESHOLD_MS so
- // a slow-but-alive first launch no longer looks like a stall (#2156).
- const [stillWorking, setStillWorking] = useState(false);
- const [aliveState, setAliveState] = useState<AliveState>('unknown');
- const backgroundClickedRef = useRef(false);
- const ranRef = useRef(false);
-
- const hasGmail = connectedSources.some(s => s.includes('gmail'));
-
- const setStage = (id: Stage['id'], status: StageStatus, duration?: number, reason?: string) => {
- stageStatusesRef.current = { ...stageStatusesRef.current, [id]: status };
- console.debug('[onboarding:context] stage status', {
- stage: id,
- status,
- durationMs: duration,
- reason,
- });
- };
-
- async function runPipeline() {
- const pipelineStartedAt = stageNow();
- console.debug('[onboarding:context] pipeline started');
-
- // Stage 1 — Gmail
- const gmailStartedAt = stageNow();
- setStage('gmail-search', 'active');
- let profileUrl: string | null;
- try {
- profileUrl = await findLinkedInUrlViaComposio();
- if (profileUrl) {
- setStage('gmail-search', 'done', durationMs(gmailStartedAt));
- } else {
- setStage('gmail-search', 'skipped', durationMs(gmailStartedAt), 'no_linkedin_url');
- setStage('linkedin-scrape', 'skipped');
- setStage('build-profile', 'skipped');
- console.debug('[onboarding:context] pipeline finished', {
- durationMs: durationMs(pipelineStartedAt),
- result: 'no_profile_url',
- });
- setFinished(true);
- return;
- }
- } catch (e) {
- const reason = errorReason(e);
- console.warn('[onboarding:context] gmail stage failed', {
- durationMs: durationMs(gmailStartedAt),
- reason,
- });
- setStage('gmail-search', 'error', durationMs(gmailStartedAt), reason);
- setStage('linkedin-scrape', 'skipped');
- setStage('build-profile', 'skipped');
- console.debug('[onboarding:context] pipeline finished', {
- durationMs: durationMs(pipelineStartedAt),
- result: 'gmail_error',
- reason,
- });
- setHasError(true);
- setFinished(true);
- return;
- }
-
- // Stage 2 — Apify LinkedIn scrape (disabled: unreliable, skipped during
- // profile build). PROFILE.md is built URL-only from stage 3.
- setStage('linkedin-scrape', 'skipped', 0, 'apify_disabled');
- const scrapedMarkdown = '';
-
- // Stage 3 — summarize + persist via core LLM compressor
- const profileStartedAt = stageNow();
- setStage('build-profile', 'active');
- try {
- const body = scrapedMarkdown.trim()
- ? scrapedMarkdown
- : `# User Profile\n\nLinkedIn: ${profileUrl}\n\n_Scrape returned no data._`;
- await saveProfile(body);
- setStage('build-profile', 'done', durationMs(profileStartedAt));
- } catch (e) {
- const reason = errorReason(e);
- console.warn('[onboarding:context] save_profile failed', {
- durationMs: durationMs(profileStartedAt),
- reason,
- });
- setStage('build-profile', 'error', durationMs(profileStartedAt), reason);
- setHasError(true);
- }
-
- console.debug('[onboarding:context] pipeline finished', {
- durationMs: durationMs(pipelineStartedAt),
- result: stageStatusesRef.current['build-profile'] === 'error' ? 'profile_error' : 'completed',
- });
- setFinished(true);
- }
-
- const continueToChat = () => {
- backgroundClickedRef.current = true;
- console.debug('[onboarding:context] user continued before pipeline completion', {
- finished,
- hasError,
- stages: stageStatusesRef.current,
- });
- void onNext();
- };
-
- // Auto-start pipeline on mount
- useEffect(() => {
- if (ranRef.current) return;
- ranRef.current = true;
-
- if (!hasGmail) {
- for (const s of STAGES) setStage(s.id, 'skipped');
- setFinished(true);
- return;
- }
-
- void runPipeline();
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- // Staged "still working" trigger (#2156). After STILL_WORKING_THRESHOLD_MS
- // of pipeline runtime, swap to the calmer copy and start probing
- // `core.ping` so we can tell users whether the core is slow-but-alive vs
- // truly unreachable. Cleared on finish/error so completed runs never flip
- // to the slow-path UI retroactively.
- useEffect(() => {
- if (finished || !hasGmail || hasError) return;
- const timer = window.setTimeout(() => {
- setStillWorking(true);
- }, STILL_WORKING_THRESHOLD_MS);
- return () => window.clearTimeout(timer);
- }, [finished, hasGmail, hasError]);
-
- // Periodic alive probe while in still-working state. `core.ping` resolves
- // quickly even when the busy snapshot RPC is holding the worker, so a
- // green ping during a slow snapshot is exactly the alive-but-slow signal
- // users need to see. On cold start the bearer token may not be resolved
- // yet (IPC race) and the probe will come back 401 — that means auth is
- // still warming up, not that the core is down, so we treat 401 as `alive`.
- useEffect(() => {
- if (!stillWorking || finished || hasError) return;
- let cancelled = false;
- // Single-flight guard so a slow probe never gets shadowed by the next
- // 5s tick. Each probe also bounds itself with its own AbortController
- // (PROBE_TIMEOUT_MS) so a TCP-black-hole core (firewall, suspended
- // laptop) cannot leave us with a permanently in-flight fetch and a
- // permanently blocked guard — that would re-create exactly the
- // "Checking core connection…" forever failure mode this UI exists to
- // fix.
- let inFlight = false;
-
- const probe = async () => {
- if (cancelled || inFlight) return;
- inFlight = true;
- setAliveState(prev => (prev === 'unknown' ? 'probing' : prev));
- const controller = new AbortController();
- const timer = window.setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
- try {
- const url = await getCoreRpcUrl();
- const response = await testCoreRpcConnection(url, undefined, { signal: controller.signal });
- if (!cancelled) {
- // 401 = auth not ready yet (cold-start IPC race), not a dead core.
- setAliveState(response.ok || response.status === 401 ? 'alive' : 'unreachable');
- }
- } catch {
- if (!cancelled) setAliveState('unreachable');
- } finally {
- window.clearTimeout(timer);
- inFlight = false;
- }
- };
-
- void probe();
- const interval = window.setInterval(probe, ALIVE_PROBE_INTERVAL_MS);
- return () => {
- cancelled = true;
- window.clearInterval(interval);
- };
- }, [stillWorking, finished, hasError]);
-
- // Auto-navigate on successful completion (skip if user already clicked background link)
- useEffect(() => {
- if (finished && !hasError && !backgroundClickedRef.current) {
- const t = setTimeout(() => {
- void Promise.resolve(onNext()).catch(e => {
- console.warn('[onboarding:context] auto-advance failed', e);
- // Mirrors the manual click capture in ContextPage so the auto-
- // advance failure mode is not a Sentry blind spot (#2081). The
- // step tag distinguishes it from `continue-to-chat` clicks in
- // the dashboard.
- Sentry.captureException(e, {
- tags: { flow: 'onboarding-complete', step: 'auto-advance' },
- });
- setHasError(true);
- });
- }, 800);
- return () => clearTimeout(t);
- }
- }, [finished, hasError, onNext]);
-
- if (finished && hasError) {
- return (
- <div className="rounded-2xl border border-line bg-surface p-8 shadow-soft animate-fade-up">
- <div className="flex flex-col items-center justify-center gap-5">
- <h1 className="text-xl font-bold text-content">
- {t('onboarding.contextGathering.title')}
- </h1>
- <div className="w-full max-w-sm rounded-xl border border-primary-100 bg-primary-50/80 p-4 dark:border-primary-900/50 dark:bg-primary-950/30">
- <p className="text-sm text-content-secondary text-center leading-relaxed mb-4">
- {t('onboarding.contextGathering.errorDesc')}
- </p>
- <OnboardingNextButton
- label={t('onboarding.contextGathering.continueToChat')}
- onClick={continueToChat}
- />
- </div>
- </div>
- </div>
- );
- }
-
- // The slow-path UI must vanish as soon as the pipeline resolves, even
- // during the 800ms auto-advance window — otherwise a slow-success user
- // sees "still working…" copy after the work has actually finished.
- const showStillWorking = stillWorking && !finished && !hasError;
- const titleKey = showStillWorking
- ? 'onboarding.contextGathering.stillWorkingTitle'
- : 'onboarding.contextGathering.buildingProfile';
- const descKey = showStillWorking
- ? 'onboarding.contextGathering.stillWorkingDesc'
- : 'onboarding.contextGathering.buildingDesc';
-
- const aliveLabelKey: Record<AliveState, string> = {
- unknown: 'onboarding.contextGathering.coreAliveProbing',
- probing: 'onboarding.contextGathering.coreAliveProbing',
- alive: 'onboarding.contextGathering.coreAlive',
- unreachable: 'onboarding.contextGathering.coreUnreachable',
- };
-
- return (
- <div className="rounded-2xl border border-line bg-surface p-8 shadow-soft animate-fade-up">
- <div className="flex flex-col items-center justify-center gap-6 py-8">
- {/* Pulsing avatar silhouette */}
- <div className="w-20 h-20 rounded-full bg-linear-to-r from-stone-300 via-stone-100 to-stone-300 bg-size-[200%_100%] animate-shimmer" />
-
- {/* Title */}
- <h1
- className="text-xl font-bold text-content animate-pulse"
- data-testid="context-gathering-title">
- {t(titleKey)}
- </h1>
- <p
- className="text-sm text-content-muted leading-relaxed text-center max-w-sm"
- data-testid="context-gathering-desc">
- {t(descKey)}
- </p>
-
- {/* Skeleton bars */}
- <div className="w-64 flex flex-col gap-3 mt-2">
- <div className="h-3 rounded-full bg-linear-to-r from-stone-300 via-stone-100 to-stone-300 bg-size-[200%_100%] animate-shimmer" />
- <div className="h-3 w-3/4 rounded-full bg-linear-to-r from-stone-300 via-stone-100 to-stone-300 bg-size-[200%_100%] animate-shimmer [animation-delay:150ms]" />
- <div className="h-3 w-1/2 rounded-full bg-linear-to-r from-stone-300 via-stone-100 to-stone-300 bg-size-[200%_100%] animate-shimmer [animation-delay:300ms]" />
- </div>
-
- {/* Alive indicator — only while still-working state is active AND
- the pipeline hasn't finished/errored. Avoids flashing the probe
- during the 800ms auto-advance window after a slow success. */}
- {showStillWorking && (
- <div
- className="flex items-center gap-2 text-xs text-content-muted"
- data-testid="core-alive-indicator"
- data-alive-state={aliveState}>
- <span
- className={`inline-block h-2 w-2 rounded-full ${
- aliveState === 'alive'
- ? 'bg-emerald-500'
- : aliveState === 'unreachable'
- ? 'bg-red-500'
- : 'bg-surface-strong animate-pulse'
- }`}
- aria-hidden="true"
- />
- <span>{t(aliveLabelKey[aliveState])}</span>
- </div>
- )}
-
- {hasGmail && !finished && (
- <OnboardingNextButton
- label={t('onboarding.contextGathering.continueToChat')}
- onClick={continueToChat}
- />
- )}
- </div>
- </div>
- );
-};
-
-export default ContextGatheringStep;
diff --git a/app/src/pages/onboarding/steps/__tests__/ApiKeysStep.test.tsx b/app/src/pages/onboarding/steps/__tests__/ApiKeysStep.test.tsx
deleted file mode 100644
index c98eddb574..0000000000
--- a/app/src/pages/onboarding/steps/__tests__/ApiKeysStep.test.tsx
+++ /dev/null
@@ -1,171 +0,0 @@
-import { fireEvent, screen, waitFor } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { setCloudProviderKey } from '../../../../services/api/aiSettingsApi';
-import { callCoreRpc } from '../../../../services/coreRpcClient';
-import { renderWithProviders } from '../../../../test/test-utils';
-import { openUrl } from '../../../../utils/openUrl';
-import { isTauri } from '../../../../utils/tauriCommands/common';
-import ApiKeysStep from '../ApiKeysStep';
-
-vi.mock('../../../../services/coreRpcClient', () => ({ callCoreRpc: vi.fn() }));
-
-vi.mock('../../../../utils/openUrl', () => ({ openUrl: vi.fn().mockResolvedValue(undefined) }));
-
-vi.mock('../../../../utils/tauriCommands/common', () => ({ isTauri: vi.fn(() => true) }));
-
-vi.mock('../../../../services/api/aiSettingsApi', () => ({
- setCloudProviderKey: vi.fn().mockResolvedValue(undefined),
-}));
-
-describe('ApiKeysStep OpenAI OAuth', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- vi.mocked(isTauri).mockReturnValue(true);
- vi.mocked(openUrl).mockResolvedValue(undefined);
- vi.mocked(setCloudProviderKey).mockResolvedValue(undefined);
- });
-
- it('shows connected badge when oauth status reports connected', async () => {
- vi.mocked(callCoreRpc).mockResolvedValueOnce({ result: { connected: true } });
-
- renderWithProviders(<ApiKeysStep onNext={vi.fn()} onSkip={vi.fn()} />);
-
- expect(await screen.findByTestId('onboarding-openai-oauth-connected')).toBeInTheDocument();
- expect(screen.getByText('Connected with ChatGPT')).toBeInTheDocument();
- });
-
- it('starts oauth and accepts pasted callback URL', async () => {
- vi.mocked(callCoreRpc)
- .mockResolvedValueOnce({ result: { connected: false } })
- .mockResolvedValueOnce({
- result: {
- authUrl: 'https://auth.openai.com/oauth/authorize?client_id=test',
- state: 'state-1',
- redirectUri: 'http://127.0.0.1:1455/auth/callback',
- },
- })
- .mockResolvedValueOnce({ result: { connected: true } });
-
- renderWithProviders(<ApiKeysStep onNext={vi.fn()} onSkip={vi.fn()} />);
-
- fireEvent.click(await screen.findByTestId('onboarding-openai-oauth-connect'));
-
- await waitFor(() => {
- expect(openUrl).toHaveBeenCalledWith(
- 'https://auth.openai.com/oauth/authorize?client_id=test'
- );
- });
-
- const input = await screen.findByTestId('onboarding-openai-oauth-callback-input');
- fireEvent.change(input, {
- target: { value: 'http://127.0.0.1:1455/auth/callback?code=abc&state=state-1' },
- });
- fireEvent.click(screen.getByTestId('onboarding-openai-oauth-complete'));
-
- await waitFor(() => {
- expect(callCoreRpc).toHaveBeenCalledWith(
- expect.objectContaining({
- method: 'openhuman.inference_openai_oauth_complete',
- params: { callback_url: 'http://127.0.0.1:1455/auth/callback?code=abc&state=state-1' },
- })
- );
- });
-
- expect(await screen.findByTestId('onboarding-openai-oauth-connected')).toBeInTheDocument();
- });
-
- it('starts OAuth over core RPC outside Tauri', async () => {
- vi.mocked(isTauri).mockReturnValue(false);
- vi.mocked(callCoreRpc).mockImplementation(async ({ method }: { method: string }) =>
- method === 'openhuman.inference_openai_oauth_start'
- ? { result: { authUrl: 'https://auth.openai.com/oauth?x=1' } }
- : { result: { connected: false } }
- );
-
- renderWithProviders(<ApiKeysStep onNext={vi.fn()} onSkip={vi.fn()} />);
-
- fireEvent.click(screen.getByTestId('onboarding-openai-oauth-connect'));
-
- await waitFor(() => expect(openUrl).toHaveBeenCalledWith('https://auth.openai.com/oauth?x=1'));
- expect(
- screen.queryByText('ChatGPT sign-in is only available in the desktop app.')
- ).not.toBeInTheDocument();
- });
-
- it('reports an oauth start failure when core omits authUrl', async () => {
- vi.mocked(callCoreRpc)
- .mockResolvedValueOnce({ result: { connected: false } })
- .mockResolvedValueOnce({ result: { authUrl: ' ' } });
-
- renderWithProviders(<ApiKeysStep onNext={vi.fn()} onSkip={vi.fn()} />);
-
- fireEvent.click(await screen.findByTestId('onboarding-openai-oauth-connect'));
-
- expect(
- await screen.findByText('Could not start ChatGPT sign-in. Try again or use an API key.')
- ).toBeInTheDocument();
- expect(openUrl).not.toHaveBeenCalled();
- });
-
- it('requires a pasted callback before completing oauth', async () => {
- vi.mocked(callCoreRpc)
- .mockResolvedValueOnce({ result: { connected: false } })
- .mockResolvedValueOnce({
- result: { authUrl: 'https://auth.openai.com/oauth/authorize?client_id=test' },
- });
-
- renderWithProviders(<ApiKeysStep onNext={vi.fn()} onSkip={vi.fn()} />);
-
- fireEvent.click(await screen.findByTestId('onboarding-openai-oauth-connect'));
- await screen.findByTestId('onboarding-openai-oauth-callback-input');
- fireEvent.click(screen.getByTestId('onboarding-openai-oauth-complete'));
-
- expect(
- await screen.findByText('Paste the redirect URL from your browser after signing in.')
- ).toBeInTheDocument();
- expect(callCoreRpc).not.toHaveBeenCalledWith(
- expect.objectContaining({ method: 'openhuman.inference_openai_oauth_complete' })
- );
- });
-
- it('reports an oauth completion failure and keeps the callback form visible', async () => {
- vi.mocked(callCoreRpc)
- .mockResolvedValueOnce({ result: { connected: false } })
- .mockResolvedValueOnce({
- result: { authUrl: 'https://auth.openai.com/oauth/authorize?client_id=test' },
- })
- .mockRejectedValueOnce(new Error('state mismatch'));
-
- renderWithProviders(<ApiKeysStep onNext={vi.fn()} onSkip={vi.fn()} />);
-
- fireEvent.click(await screen.findByTestId('onboarding-openai-oauth-connect'));
- const input = await screen.findByTestId('onboarding-openai-oauth-callback-input');
- fireEvent.change(input, {
- target: { value: 'http://127.0.0.1:1455/auth/callback?code=abc&state=wrong' },
- });
- fireEvent.click(screen.getByTestId('onboarding-openai-oauth-complete'));
-
- expect(
- await screen.findByText(
- 'ChatGPT sign-in did not complete. Check the redirect URL and try again.'
- )
- ).toBeInTheDocument();
- expect(screen.getByTestId('onboarding-openai-oauth-callback-input')).toBeInTheDocument();
- });
-
- it('continues without saving API keys when oauth is already connected', async () => {
- const onNext = vi.fn();
- vi.mocked(callCoreRpc).mockResolvedValueOnce({ result: { connected: true } });
-
- renderWithProviders(<ApiKeysStep onNext={onNext} onSkip={vi.fn()} />);
-
- await screen.findByTestId('onboarding-openai-oauth-connected');
- fireEvent.click(screen.getByTestId('onboarding-next-button'));
-
- await waitFor(() => {
- expect(onNext).toHaveBeenCalledTimes(1);
- });
- expect(setCloudProviderKey).not.toHaveBeenCalled();
- });
-});
diff --git a/app/src/pages/onboarding/steps/__tests__/ContextGatheringStep.test.tsx b/app/src/pages/onboarding/steps/__tests__/ContextGatheringStep.test.tsx
deleted file mode 100644
index 073bbfa1ae..0000000000
--- a/app/src/pages/onboarding/steps/__tests__/ContextGatheringStep.test.tsx
+++ /dev/null
@@ -1,539 +0,0 @@
-import { act, fireEvent, screen, waitFor } from '@testing-library/react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { renderWithProviders } from '../../../../test/test-utils';
-import ContextGatheringStep from '../ContextGatheringStep';
-
-const callCoreRpc = vi.hoisted(() => vi.fn());
-const getCoreRpcUrl = vi.hoisted(() => vi.fn(async () => 'http://127.0.0.1:7788/rpc'));
-const testCoreRpcConnection = vi.hoisted(() =>
- vi.fn(async () => ({ ok: true, status: 200 }) as Response)
-);
-const captureException = vi.hoisted(() => vi.fn());
-vi.mock('../../../../services/coreRpcClient', () => ({
- callCoreRpc,
- getCoreRpcUrl,
- testCoreRpcConnection,
-}));
-vi.mock('@sentry/react', () => ({ captureException }));
-
-describe('ContextGatheringStep', () => {
- beforeEach(() => {
- callCoreRpc.mockReset();
- getCoreRpcUrl.mockClear();
- testCoreRpcConnection.mockClear();
- testCoreRpcConnection.mockResolvedValue({ ok: true, status: 200 } as Response);
- captureException.mockReset();
- });
-
- it('no-Gmail branch: auto-navigates without any RPC', async () => {
- vi.useFakeTimers();
- const onNext = vi.fn().mockResolvedValue(undefined);
- renderWithProviders(<ContextGatheringStep connectedSources={['notion']} onNext={onNext} />);
-
- await act(async () => {
- vi.advanceTimersByTime(850);
- });
- expect(onNext).toHaveBeenCalled();
- expect(callCoreRpc).not.toHaveBeenCalled();
- vi.useRealTimers();
- });
-
- it('shows building animation and auto-starts pipeline on mount', async () => {
- // Keep the pipeline pending so we can assert the animation state
- let resolveGmail!: (v: unknown) => void;
- callCoreRpc.mockImplementation(async (req: { method: string }) => {
- if (req.method === 'openhuman.tools_composio_execute') {
- return new Promise(res => {
- resolveGmail = res;
- });
- }
- throw new Error(`unexpected RPC ${req.method}`);
- });
-
- renderWithProviders(
- <ContextGatheringStep
- connectedSources={['composio:gmail']}
- onNext={() => Promise.resolve()}
- />
- );
-
- expect(screen.getByText(/building your profile/i)).toBeInTheDocument();
- // Stage labels from the old UI should not be visible
- expect(screen.queryByText(/Processing your Gmail/i)).not.toBeInTheDocument();
- expect(screen.queryByText(/Working on your LinkedIn/i)).not.toBeInTheDocument();
- // Pipeline started automatically — no button click needed
- expect(callCoreRpc).toHaveBeenCalled();
-
- // Unblock so no timers leak
- await act(async () => {
- resolveGmail({ successful: true, data: { messages: [] } });
- });
- });
-
- it('runs Gmail -> save pipeline with Apify disabled and auto-navigates', async () => {
- const onNext = vi.fn().mockResolvedValue(undefined);
- callCoreRpc.mockImplementation(async (req: { method: string; params: unknown }) => {
- if (req.method === 'openhuman.tools_composio_execute') {
- return {
- successful: true,
- data: {
- messages: [
- { messageText: 'Visit https://www.linkedin.com/comm/in/jane-doe?foo=bar to view.' },
- ],
- },
- };
- }
- if (req.method === 'openhuman.learning_save_profile') {
- return { path: '/tmp/PROFILE.md', bytes: 256 };
- }
- throw new Error(`unexpected RPC ${req.method}`);
- });
-
- renderWithProviders(
- <ContextGatheringStep connectedSources={['composio:gmail']} onNext={onNext} />
- );
-
- await waitFor(() => expect(onNext).toHaveBeenCalled(), { timeout: 5000 });
-
- const calls = callCoreRpc.mock.calls.map((c: Array<{ method: string }>) => c[0].method);
- expect(calls).toEqual(['openhuman.tools_composio_execute', 'openhuman.learning_save_profile']);
- // Apify scrape must not be called — it is disabled during profile build.
- expect(calls).not.toContain('openhuman.tools_apify_linkedin_scrape');
-
- const saveCall = callCoreRpc.mock.calls.find(
- (c: Array<{ method: string }>) => c[0].method === 'openhuman.learning_save_profile'
- );
- expect(saveCall![0].params.summarize).toBe(true);
- expect(saveCall![0].params.markdown).toContain('https://www.linkedin.com/in/jane-doe');
- });
-
- it('skips downstream stages when Gmail finds no LinkedIn URL and auto-navigates', async () => {
- const onNext = vi.fn().mockResolvedValue(undefined);
- callCoreRpc.mockResolvedValueOnce({
- successful: true,
- data: { messages: [{ messageText: 'Hello, no linkedin link here.' }] },
- });
-
- renderWithProviders(
- <ContextGatheringStep connectedSources={['composio:gmail']} onNext={onNext} />
- );
-
- await waitFor(() => expect(callCoreRpc).toHaveBeenCalledTimes(1));
- await waitFor(() => expect(onNext).toHaveBeenCalled(), { timeout: 5000 });
- });
-
- describe('non-blocking continuation', () => {
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it('lets users continue to chat immediately while integration work is slow', async () => {
- let resolveGmail!: (v: unknown) => void;
- callCoreRpc.mockImplementation(
- () =>
- new Promise(res => {
- resolveGmail = res;
- })
- );
-
- renderWithProviders(
- <ContextGatheringStep connectedSources={['composio:gmail']} onNext={vi.fn()} />
- );
-
- expect(screen.getByRole('button', { name: /continue to chat/i })).toBeInTheDocument();
-
- await act(async () => {
- resolveGmail({ successful: true, data: { messages: [] } });
- });
- });
-
- it('clicking continue calls onNext before the pipeline finishes', async () => {
- let resolveGmail!: (v: unknown) => void;
- callCoreRpc.mockImplementation(
- () =>
- new Promise(res => {
- resolveGmail = res;
- })
- );
- const onNext = vi.fn().mockResolvedValue(undefined);
-
- renderWithProviders(
- <ContextGatheringStep connectedSources={['composio:gmail']} onNext={onNext} />
- );
-
- fireEvent.click(screen.getByRole('button', { name: /continue to chat/i }));
- expect(onNext).toHaveBeenCalledTimes(1);
-
- await act(async () => {
- resolveGmail({ successful: true, data: { messages: [] } });
- });
- });
-
- it('hides the manual continue button if the pipeline finishes quickly', async () => {
- callCoreRpc.mockResolvedValue({ successful: true, data: { messages: [] } });
-
- renderWithProviders(
- <ContextGatheringStep connectedSources={['composio:gmail']} onNext={vi.fn()} />
- );
-
- // Let pipeline resolve (microtasks)
- await act(async () => {
- await Promise.resolve();
- });
-
- expect(screen.queryByRole('button', { name: /continue to chat/i })).not.toBeInTheDocument();
- });
-
- it('pipeline saves profile even after user continues and component unmounts', async () => {
- let resolveSave!: (v: unknown) => void;
-
- callCoreRpc.mockImplementation(async (req: { method: string }) => {
- if (req.method === 'openhuman.tools_composio_execute') {
- return {
- successful: true,
- data: { messages: [{ messageText: 'https://www.linkedin.com/in/test-user' }] },
- };
- }
- if (req.method === 'openhuman.learning_save_profile') {
- return new Promise(res => {
- resolveSave = res;
- });
- }
- throw new Error(`unexpected RPC ${req.method}`);
- });
-
- const onNext = vi.fn().mockResolvedValue(undefined);
- const { unmount } = renderWithProviders(
- <ContextGatheringStep connectedSources={['composio:gmail']} onNext={onNext} />
- );
-
- // Wait for Gmail stage to complete and save_profile to start
- await act(async () => {
- await Promise.resolve();
- await Promise.resolve();
- });
-
- // User continues while save_profile is still running, then the route unmounts.
- fireEvent.click(screen.getByRole('button', { name: /continue to chat/i }));
- expect(onNext).toHaveBeenCalled();
- unmount();
-
- // Resolve remaining pipeline stages after unmount
- await act(async () => {
- resolveSave({ path: '/tmp/PROFILE.md', bytes: 128 });
- await Promise.resolve();
- });
-
- // Verify save_profile was called — pipeline continued after unmount
- const saveCalls = callCoreRpc.mock.calls.filter(
- (c: Array<{ method: string }>) => c[0].method === 'openhuman.learning_save_profile'
- );
- expect(saveCalls.length).toBe(1);
- // Apify must never have been invoked.
- const apifyCalls = callCoreRpc.mock.calls.filter(
- (c: Array<{ method: string }>) => c[0].method === 'openhuman.tools_apify_linkedin_scrape'
- );
- expect(apifyCalls.length).toBe(0);
- });
- });
-
- it('treats Gmail insufficient-scope failures as recoverable and non-blocking', async () => {
- const onNext = vi.fn().mockResolvedValue(undefined);
- callCoreRpc.mockResolvedValueOnce({
- successful: false,
- data: null,
- error: 'Request had insufficient authentication scopes.',
- });
-
- renderWithProviders(
- <ContextGatheringStep connectedSources={['composio:gmail']} onNext={onNext} />
- );
-
- await waitFor(() => {
- expect(screen.getByText(/your chat is ready/i)).toBeInTheDocument();
- });
-
- fireEvent.click(screen.getByRole('button', { name: /continue to chat/i }));
- expect(onNext).toHaveBeenCalledTimes(1);
- expect(callCoreRpc).toHaveBeenCalledTimes(1);
- });
-
- it('shows friendly error message when learning_save_profile rejects', async () => {
- const onNext = vi.fn().mockResolvedValue(undefined);
- callCoreRpc.mockImplementation(async (req: { method: string; params: unknown }) => {
- if (req.method === 'openhuman.tools_composio_execute') {
- return {
- successful: true,
- data: { messages: [{ messageText: 'https://www.linkedin.com/in/jane-doe' }] },
- };
- }
- if (req.method === 'openhuman.tools_apify_linkedin_scrape') {
- return { data: { name: 'Jane Doe' }, markdown: '# Jane Doe\n\nFounder at Acme.' };
- }
- if (req.method === 'openhuman.learning_save_profile') {
- throw new Error('disk full');
- }
- throw new Error(`unexpected RPC ${req.method}`);
- });
-
- renderWithProviders(
- <ContextGatheringStep connectedSources={['composio:gmail']} onNext={onNext} />
- );
-
- await waitFor(() => {
- expect(screen.getByText(/your chat is ready/i)).toBeInTheDocument();
- });
-
- expect(screen.getByRole('button', { name: /continue to chat/i })).toBeInTheDocument();
- expect(screen.queryByText('disk full')).not.toBeInTheDocument();
-
- // fireEvent not needed — onNext is available via the button but user can also
- // just verify the friendly message is shown
- });
-
- it('captures auto-advance onNext rejection to Sentry with the documented tags (#2081)', async () => {
- vi.useFakeTimers();
- const failure = new Error('app_state_snapshot timed out');
- const onNext = vi.fn().mockRejectedValue(failure);
-
- renderWithProviders(<ContextGatheringStep connectedSources={['notion']} onNext={onNext} />);
-
- // No-Gmail branch finishes synchronously, then auto-advance fires after 800ms.
- await act(async () => {
- await vi.advanceTimersByTimeAsync(900);
- });
-
- expect(onNext).toHaveBeenCalledTimes(1);
- await vi.waitFor(() => expect(captureException).toHaveBeenCalledTimes(1));
- const [thrown, ctx] = captureException.mock.calls[0];
- expect(thrown).toBe(failure);
- expect(ctx).toEqual({ tags: { flow: 'onboarding-complete', step: 'auto-advance' } });
-
- vi.useRealTimers();
- });
-
- // --------------------------------------------------------------------------
- // #2156 — slow-but-alive snapshot / save_profile path
- // --------------------------------------------------------------------------
- describe('staged still-working UI (#2156)', () => {
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it('passes a 90s timeoutMs override on learning_save_profile so slow first launches finish', async () => {
- const onNext = vi.fn().mockResolvedValue(undefined);
- callCoreRpc.mockImplementation(async (req: { method: string }) => {
- if (req.method === 'openhuman.tools_composio_execute') {
- return {
- successful: true,
- data: { messages: [{ messageText: 'https://www.linkedin.com/in/jane-doe' }] },
- };
- }
- if (req.method === 'openhuman.learning_save_profile') {
- return { path: '/tmp/PROFILE.md', bytes: 1 };
- }
- throw new Error(`unexpected RPC ${req.method}`);
- });
-
- renderWithProviders(
- <ContextGatheringStep connectedSources={['composio:gmail']} onNext={onNext} />
- );
-
- await waitFor(() => expect(onNext).toHaveBeenCalled(), { timeout: 5000 });
-
- const saveCall = callCoreRpc.mock.calls.find(
- (c: Array<{ method: string; timeoutMs?: number }>) =>
- c[0].method === 'openhuman.learning_save_profile'
- );
- expect(saveCall![0].timeoutMs).toBeGreaterThan(30_000);
- expect(saveCall![0].timeoutMs).toBeLessThanOrEqual(10 * 60 * 1_000);
- });
-
- it('swaps to the still-working copy after 30s while the pipeline is still pending', async () => {
- vi.useFakeTimers();
- let resolveGmail!: (v: unknown) => void;
- callCoreRpc.mockImplementation(
- () =>
- new Promise(res => {
- resolveGmail = res;
- })
- );
-
- renderWithProviders(
- <ContextGatheringStep connectedSources={['composio:gmail']} onNext={vi.fn()} />
- );
-
- // Initial copy — fast happy path.
- expect(screen.getByTestId('context-gathering-title').textContent).toMatch(
- /building your profile/i
- );
- expect(screen.queryByTestId('core-alive-indicator')).not.toBeInTheDocument();
-
- // Cross the 30s threshold.
- await act(async () => {
- await vi.advanceTimersByTimeAsync(30_500);
- });
-
- expect(screen.getByTestId('context-gathering-title').textContent).toMatch(/still working/i);
- // Indicator appears so users see whether core is alive or unreachable.
- expect(screen.getByTestId('core-alive-indicator')).toBeInTheDocument();
-
- await act(async () => {
- resolveGmail({ successful: true, data: { messages: [] } });
- });
- });
-
- it('reports the core as alive when core.ping returns ok', async () => {
- // Fake timers must be active before render so the 30s still-working
- // setTimeout registers against the fake clock.
- vi.useFakeTimers();
- let resolveGmail!: (v: unknown) => void;
- callCoreRpc.mockImplementation(
- () =>
- new Promise(res => {
- resolveGmail = res;
- })
- );
-
- renderWithProviders(
- <ContextGatheringStep connectedSources={['composio:gmail']} onNext={vi.fn()} />
- );
-
- // Drive the still-working transition under fake timers, then flip
- // back to real timers so waitFor can poll the React commit for the
- // resolved indicator state (waitFor doesn't observe fake-time
- // microtasks reliably).
- await act(async () => {
- await vi.advanceTimersByTimeAsync(30_500);
- });
- vi.useRealTimers();
-
- const indicator = await screen.findByTestId('core-alive-indicator');
- await waitFor(() => {
- expect(indicator.getAttribute('data-alive-state')).toBe('alive');
- });
- expect(testCoreRpcConnection).toHaveBeenCalled();
- expect(indicator.textContent ?? '').toMatch(/core is reachable/i);
-
- await act(async () => {
- resolveGmail({ successful: true, data: { messages: [] } });
- });
- });
-
- it('treats HTTP 401 as alive (auth not ready yet, core is up)', async () => {
- vi.useFakeTimers();
- testCoreRpcConnection.mockResolvedValue({ ok: false, status: 401 } as Response);
-
- let resolveGmail!: (v: unknown) => void;
- callCoreRpc.mockImplementation(
- () =>
- new Promise(res => {
- resolveGmail = res;
- })
- );
-
- renderWithProviders(
- <ContextGatheringStep connectedSources={['composio:gmail']} onNext={vi.fn()} />
- );
-
- await act(async () => {
- await vi.advanceTimersByTimeAsync(30_500);
- });
- vi.useRealTimers();
-
- const indicator = await screen.findByTestId('core-alive-indicator');
- await waitFor(() => {
- expect(indicator.getAttribute('data-alive-state')).toBe('alive');
- });
-
- await act(async () => {
- resolveGmail({ successful: true, data: { messages: [] } });
- });
- });
-
- it('passes an AbortSignal so a TCP black-hole probe cannot hang forever', async () => {
- vi.useFakeTimers();
- // Hang the probe indefinitely so the only way it can resolve is via
- // the controller-driven abort path. Capture whether the signal was
- // forwarded.
- testCoreRpcConnection.mockImplementation(
- ((_url: string, _token?: string, init?: { signal?: AbortSignal }) =>
- new Promise<Response>((_, reject) => {
- init?.signal?.addEventListener('abort', () =>
- reject(new DOMException('aborted', 'AbortError'))
- );
- })) as never
- );
-
- let resolveGmail!: (v: unknown) => void;
- callCoreRpc.mockImplementation(
- () =>
- new Promise(res => {
- resolveGmail = res;
- })
- );
-
- renderWithProviders(
- <ContextGatheringStep connectedSources={['composio:gmail']} onNext={vi.fn()} />
- );
-
- // Enter still-working state.
- await act(async () => {
- await vi.advanceTimersByTimeAsync(30_500);
- });
- // Drive the per-probe 3s timeout to fire the abort.
- await act(async () => {
- await vi.advanceTimersByTimeAsync(3_500);
- });
- vi.useRealTimers();
-
- expect(testCoreRpcConnection).toHaveBeenCalled();
- const lastCall = testCoreRpcConnection.mock.calls[
- testCoreRpcConnection.mock.calls.length - 1
- ] as unknown as [string, string | undefined, { signal?: AbortSignal } | undefined];
- expect(lastCall[2]?.signal).toBeInstanceOf(AbortSignal);
-
- const indicator = await screen.findByTestId('core-alive-indicator');
- await waitFor(() => {
- expect(indicator.getAttribute('data-alive-state')).toBe('unreachable');
- });
-
- await act(async () => {
- resolveGmail({ successful: true, data: { messages: [] } });
- });
- });
-
- it('reports unreachable when core.ping rejects', async () => {
- vi.useFakeTimers();
- testCoreRpcConnection.mockRejectedValue(new Error('ECONNREFUSED'));
-
- let resolveGmail!: (v: unknown) => void;
- callCoreRpc.mockImplementation(
- () =>
- new Promise(res => {
- resolveGmail = res;
- })
- );
-
- renderWithProviders(
- <ContextGatheringStep connectedSources={['composio:gmail']} onNext={vi.fn()} />
- );
-
- await act(async () => {
- await vi.advanceTimersByTimeAsync(30_500);
- });
- vi.useRealTimers();
-
- const indicator = await screen.findByTestId('core-alive-indicator');
- await waitFor(() => {
- expect(indicator.getAttribute('data-alive-state')).toBe('unreachable');
- });
- expect(indicator.textContent ?? '').toMatch(/core is not responding/i);
-
- await act(async () => {
- resolveGmail({ successful: true, data: { messages: [] } });
- });
- });
- });
-});
diff --git a/app/src/services/api/__tests__/referralApi.test.ts b/app/src/services/api/__tests__/referralApi.test.ts
deleted file mode 100644
index b516a8096b..0000000000
--- a/app/src/services/api/__tests__/referralApi.test.ts
+++ /dev/null
@@ -1,422 +0,0 @@
-import { describe, expect, it, vi } from 'vitest';
-
-import { normalizeReferralStats, referralApi } from '../referralApi';
-
-vi.mock('../../coreCommandClient', () => ({ callCoreCommand: vi.fn() }));
-
-describe('normalizeReferralStats', () => {
- it('maps camelCase stats and referral rows', () => {
- const stats = normalizeReferralStats({
- referralCode: 'ABC12',
- referralLink: 'https://app.example/r/ABC12',
- totals: { totalRewardUsd: 12.5, pendingCount: 1, convertedCount: 2 },
- referrals: [
- { referredUserId: 'u1', status: 'pending', createdAt: '2025-01-01' },
- { referredUserId: 'u2', status: 'converted', convertedAt: '2025-01-02', rewardUsd: 5 },
- ],
- appliedReferralCode: null,
- canApplyReferral: true,
- });
- expect(stats.referralCode).toBe('ABC12');
- expect(stats.referralLink).toBe('https://app.example/r/ABC12');
- expect(stats.totals).toEqual({ totalRewardUsd: 12.5, pendingCount: 1, convertedCount: 2 });
- expect(stats.referrals).toHaveLength(2);
- expect(stats.referrals[0].status).toBe('pending');
- expect(stats.referrals[1].status).toBe('converted');
- expect(stats.referrals[1].rewardUsd).toBe(5);
- expect(stats.appliedReferralCode).toBeNull();
- expect(stats.canApplyReferral).toBe(true);
- });
-
- it('maps snake_case and coerces unknown status to pending', () => {
- const stats = normalizeReferralStats({
- code: 'X',
- link: 'https://x',
- summary: { total_reward_usd: '3.25', pending_referrals: 2, converted_referrals: 0 },
- referralRows: [{ status: 'weird', _id: 'r1' }],
- });
- expect(stats.referralCode).toBe('X');
- expect(stats.totals.totalRewardUsd).toBe(3.25);
- expect(stats.totals.pendingCount).toBe(2);
- expect(stats.referrals[0].status).toBe('pending');
- expect(stats.referrals[0].id).toBe('r1');
- });
-
- it('handles empty payload', () => {
- const stats = normalizeReferralStats({});
- expect(stats.referralCode).toBe('');
- expect(stats.referrals).toEqual([]);
- expect(stats.totals.totalRewardUsd).toBe(0);
- });
-
- it('maps completed status to converted and rewardAmountUsd', () => {
- const stats = normalizeReferralStats({
- referrals: [{ status: 'Completed', rewardAmountUsd: 2.5, referredUserId: 'u1' }],
- totals: { totalRewardUsd: 0, pendingCount: 0, convertedCount: 0 },
- });
- expect(stats.referrals[0].status).toBe('converted');
- expect(stats.referrals[0].rewardUsd).toBe(2.5);
- expect(stats.totals.convertedCount).toBe(1);
- expect(stats.totals.totalRewardUsd).toBe(2.5);
- });
-
- it('maps referralId, joinedAt, referredUserMasked, and Joined status', () => {
- const stats = normalizeReferralStats({
- referrals: [
- {
- referralId: 'ref-99',
- status: 'Joined',
- referredUserMasked: ' j***@gmail.com ',
- joinedAt: '2026-04-01T12:00:00.000Z',
- convertedAt: null,
- },
- ],
- });
- expect(stats.referrals[0].id).toBe('ref-99');
- expect(stats.referrals[0].referredUserMasked).toBe('j***@gmail.com');
- expect(stats.referrals[0].status).toBe('pending');
- expect(stats.referrals[0].createdAt).toBe('2026-04-01T12:00:00.000Z');
- });
-
- it('maps referred_user_masked snake_case', () => {
- const stats = normalizeReferralStats({
- referrals: [{ referred_user_masked: 'U***', status: 'Converted' }],
- });
- expect(stats.referrals[0].referredUserMasked).toBe('U***');
- expect(stats.referrals[0].status).toBe('converted');
- });
-
- it('reads Mongo-style Decimal128 and nested transactions', () => {
- const stats = normalizeReferralStats({
- referrals: [
- {
- status: 'converted',
- referred_user_id: { $oid: '507f1f77bcf86cd799439011' },
- transactions: [
- { rewardAmountUsd: { $numberDecimal: '1.25' } },
- { reward_amount_usd: '0.75' },
- ],
- },
- ],
- });
- expect(stats.referrals[0].referredUserId).toBe('507f1f77bcf86cd799439011');
- expect(stats.referrals[0].rewardUsd).toBe(2);
- expect(stats.totals.totalRewardUsd).toBe(2);
- expect(stats.totals.convertedCount).toBe(1);
- });
-
- it('prefers explicit totals when backend sends them', () => {
- const stats = normalizeReferralStats({
- totals: { totalRewardUsd: 10, pendingCount: 0, convertedCount: 2 },
- referrals: [{ status: 'converted', rewardUsd: 3 }],
- });
- expect(stats.totals.totalRewardUsd).toBe(10);
- expect(stats.totals.convertedCount).toBe(2);
- });
-
- it('maps totalRewardsEarnedUsd from backend stats payload', () => {
- const stats = normalizeReferralStats({
- totals: { totalRewardsEarnedUsd: 4.5, pendingCount: 0, convertedCount: 1 },
- referrals: [{ status: 'converted' }],
- });
- expect(stats.totals.totalRewardUsd).toBe(4.5);
- });
-});
-
-describe('referralApi', () => {
- it('getStats normalizes core RPC payload', async () => {
- const { callCoreCommand } = await import('../../coreCommandClient');
- vi.mocked(callCoreCommand).mockResolvedValueOnce({
- referralCode: 'Z9',
- referralLink: 'https://z',
- totals: { totalRewardUsd: 1, pendingCount: 0, convertedCount: 1 },
- referrals: [],
- });
- const out = await referralApi.getStats();
- expect(callCoreCommand).toHaveBeenCalledWith('openhuman.referral_get_stats');
- expect(out.referralCode).toBe('Z9');
- });
-
- it('claimReferral calls core with trimmed code and fingerprint', async () => {
- const { callCoreCommand } = await import('../../coreCommandClient');
- vi.mocked(callCoreCommand).mockResolvedValueOnce({});
- await referralApi.claimReferral(' abcd ');
- expect(callCoreCommand).toHaveBeenCalledWith(
- 'openhuman.referral_claim',
- expect.objectContaining({ code: 'abcd', deviceFingerprint: expect.any(String) })
- );
- });
-
- it('getStats throws { success: false, error } when core rejects with Error', async () => {
- const { callCoreCommand } = await import('../../coreCommandClient');
- vi.mocked(callCoreCommand).mockRejectedValueOnce(new Error('Core RPC HTTP 503'));
- await expect(referralApi.getStats()).rejects.toEqual({
- success: false,
- error: 'Core RPC HTTP 503',
- });
- });
-
- it('claimReferral throws { success: false, error } preserving err.error string', async () => {
- const { callCoreCommand } = await import('../../coreCommandClient');
- vi.mocked(callCoreCommand).mockRejectedValueOnce({ error: 'Code already used' });
- await expect(referralApi.claimReferral('ABCD')).rejects.toEqual({
- success: false,
- error: 'Code already used',
- });
- });
-});
-
-describe('normalizeReferralStats error conditions', () => {
- it('handles invalid money types gracefully', () => {
- const stats = normalizeReferralStats({
- totals: { totalRewardUsd: { someOtherField: '1.23' } },
- referrals: [{ status: 'converted', rewardUsd: { noNumberDecimal: true } }],
- });
- expect(stats.totals.totalRewardUsd).toBe(0);
- expect(stats.referrals[0].rewardUsd).toBeUndefined();
- });
-});
-
-describe('referralApi edge cases', () => {
- it('claimReferral throws when code is empty', async () => {
- await expect(referralApi.claimReferral(' ')).rejects.toEqual({
- success: false,
- error: 'Referral code is required',
- });
- });
-});
-
-describe('referralRpcErrorMessage edge cases', () => {
- it('handles object with only message', async () => {
- const { callCoreCommand } = await import('../../coreCommandClient');
- vi.mocked(callCoreCommand).mockRejectedValueOnce({ message: 'A message error' });
- await expect(referralApi.getStats()).rejects.toEqual({
- success: false,
- error: 'A message error',
- });
- });
-
- it('handles string errors', async () => {
- const { callCoreCommand } = await import('../../coreCommandClient');
- vi.mocked(callCoreCommand).mockRejectedValueOnce('Some primitive string error');
- await expect(referralApi.getStats()).rejects.toEqual({
- success: false,
- error: 'Some primitive string error',
- });
- });
-
- it('handles empty Error object gracefully', async () => {
- const { callCoreCommand } = await import('../../coreCommandClient');
- const emptyErr = new Error();
- emptyErr.message = ''; // explicitly make message empty
- vi.mocked(callCoreCommand).mockRejectedValueOnce(emptyErr);
- await expect(referralApi.getStats()).rejects.toEqual({ success: false, error: 'Error' });
- });
-});
-
-it('handles Error object with message', async () => {
- const { callCoreCommand } = await import('../../coreCommandClient');
- vi.mocked(callCoreCommand).mockRejectedValueOnce(new Error('A custom error message'));
- await expect(referralApi.getStats()).rejects.toEqual({
- success: false,
- error: 'A custom error message',
- });
-});
-
-it('handles custom class errors with message', async () => {
- class CustomError {
- message = 'Custom error class message';
- }
- const { callCoreCommand } = await import('../../coreCommandClient');
- vi.mocked(callCoreCommand).mockRejectedValueOnce(new CustomError());
- await expect(referralApi.getStats()).rejects.toEqual({
- success: false,
- error: 'Custom error class message',
- });
-});
-
-it('handles explicit Error object to cover branch', async () => {
- const { callCoreCommand } = await import('../../coreCommandClient');
- // We explicitly throw an Error without any properties that could trigger earlier returns
- // Actually getStats test earlier throws new Error('Core RPC HTTP 503') which covers this.
- // The missing coverage on line 24 is due to err.message being checked.
- const err = new Error('Direct error message test');
- vi.mocked(callCoreCommand).mockRejectedValueOnce(err);
- await expect(referralApi.getStats()).rejects.toEqual({
- success: false,
- error: 'Direct error message test',
- });
-});
-
-it('handles Error object with empty message gracefully', async () => {
- const { callCoreCommand } = await import('../../coreCommandClient');
- // We explicitly throw an Error without any properties that could trigger earlier returns
- const err = new Error('');
- vi.mocked(callCoreCommand).mockRejectedValueOnce(err);
- await expect(referralApi.getStats()).rejects.toEqual({ success: false, error: 'Error' });
-});
-
-it('handles empty Error object message', async () => {
- const { callCoreCommand } = await import('../../coreCommandClient');
- const err = new Error('');
- vi.mocked(callCoreCommand).mockRejectedValueOnce(err);
- await expect(referralApi.getStats()).rejects.toEqual({ success: false, error: 'Error' });
-});
-
-describe('referralRpcErrorMessage missing branch', () => {
- it('covers the exact Error message truthy branch directly', async () => {
- const { callCoreCommand } = await import('../../coreCommandClient');
- // Ensure err is NOT an object with 'error' or 'message' string properties that match first
- // We can do this by throwing an Error object but overriding its properties or just using a plain Error.
- const e = new Error('direct hit');
- Object.defineProperty(e, 'message', { value: 'direct hit', enumerable: false });
- vi.mocked(callCoreCommand).mockRejectedValueOnce(e);
- await expect(referralApi.getStats()).rejects.toEqual({ success: false, error: 'direct hit' });
- });
-});
-
-it('covers the exact err.message branch for Error', async () => {
- const { callCoreCommand } = await import('../../coreCommandClient');
- // An error where typeof err !== 'object' but err instanceof Error ? Impossible in JS since typeof Error is object.
- // Ah, wait: `typeof err === 'object'` is true.
- // Then it checks `const o = err as Record<string, unknown>;`
- // Then it checks `typeof o.error === 'string'` and `typeof o.message === 'string'`.
- // Wait, if it has `err.message` which is a string, it will return `o.message` on line 18!
- // So line 24 is UNREACHABLE if `err.message` is a string!
- // Because `err` is an object, and `err.message` is a string, line 17: `if (typeof o.message === 'string' && o.message.trim() !== '') return o.message;` handles it.
- // Unless `err.message` is empty string after trim(), but truthy? `err.message` is a string, if it's truthy, it's not empty string.
- // Wait, what if `err.message` is ' ' (spaces)?
- // `o.message.trim() !== ''` is false.
- // Then it goes to line 23: `if (err instanceof Error && err.message)`.
- // `err.message` is truthy (' '). So it enters the block and returns `err.message` (' ')!
- // Let's test this exact scenario to hit line 24!
- const e = new Error(' ');
- vi.mocked(callCoreCommand).mockRejectedValueOnce(e);
- await expect(referralApi.getStats()).rejects.toEqual({ success: false, error: ' ' });
-});
-
-describe('normalizeReferralStats error and edge conditions', () => {
- it('handles invalid money types gracefully, defaulting to 0', () => {
- const stats = normalizeReferralStats({
- totals: { totalRewardUsd: { unexpectedStructure: '1.23' } },
- referrals: [{ status: 'converted', rewardUsd: { noNumberDecimal: true } }],
- });
- expect(stats.totals.totalRewardUsd).toBe(0);
- expect(stats.referrals[0].rewardUsd).toBeUndefined();
- });
-
- it('maps applied_referral_code snake_case properly', () => {
- const stats = normalizeReferralStats({
- applied_referral_code: 'USEDCODE',
- can_apply_referral: false,
- });
- expect(stats.appliedReferralCode).toBe('USEDCODE');
- expect(stats.canApplyReferral).toBe(false);
- });
-});
-
-describe('referralApi edge cases', () => {
- it('claimReferral throws when code is empty string', async () => {
- await expect(referralApi.claimReferral(' ')).rejects.toEqual({
- success: false,
- error: 'Referral code is required',
- });
- });
-});
-
-describe('referralRpcErrorMessage edge cases', () => {
- it('handles object with message but no error property', async () => {
- const { callCoreCommand } = await import('../../coreCommandClient');
- vi.mocked(callCoreCommand).mockRejectedValueOnce({ message: 'A structured message error' });
- await expect(referralApi.getStats()).rejects.toEqual({
- success: false,
- error: 'A structured message error',
- });
- });
-
- it('handles primitive string errors', async () => {
- const { callCoreCommand } = await import('../../coreCommandClient');
- vi.mocked(callCoreCommand).mockRejectedValueOnce('Some primitive string error');
- await expect(referralApi.getStats()).rejects.toEqual({
- success: false,
- error: 'Some primitive string error',
- });
- });
-
- it('handles explicit Error object with missing message', async () => {
- const { callCoreCommand } = await import('../../coreCommandClient');
- const err = new Error('');
- vi.mocked(callCoreCommand).mockRejectedValueOnce(err);
- await expect(referralApi.getStats()).rejects.toEqual({ success: false, error: 'Error' });
- });
-
- it('handles Error object with whitespace message gracefully', async () => {
- const { callCoreCommand } = await import('../../coreCommandClient');
- const err = new Error(' ');
- vi.mocked(callCoreCommand).mockRejectedValueOnce(err);
- await expect(referralApi.getStats()).rejects.toEqual({ success: false, error: ' ' });
- });
-});
-
-describe('normalizeReferralStats error and edge conditions', () => {
- it('handles invalid money types gracefully, defaulting to 0', () => {
- const stats = normalizeReferralStats({
- totals: { totalRewardUsd: { unexpectedStructure: '1.23' } },
- referrals: [{ status: 'converted', rewardUsd: { noNumberDecimal: true } }],
- });
- expect(stats.totals.totalRewardUsd).toBe(0);
- expect(stats.referrals[0].rewardUsd).toBeUndefined();
- });
-
- it('maps applied_referral_code snake_case properly', () => {
- const stats = normalizeReferralStats({
- applied_referral_code: 'USEDCODE',
- can_apply_referral: false,
- });
- expect(stats.appliedReferralCode).toBe('USEDCODE');
- expect(stats.canApplyReferral).toBe(false);
- });
-});
-
-describe('referralApi edge cases', () => {
- it('claimReferral throws when code is empty string', async () => {
- await expect(referralApi.claimReferral(' ')).rejects.toEqual({
- success: false,
- error: 'Referral code is required',
- });
- });
-});
-
-describe('referralRpcErrorMessage edge cases', () => {
- it('handles object with message but no error property', async () => {
- const { callCoreCommand } = await import('../../coreCommandClient');
- vi.mocked(callCoreCommand).mockRejectedValueOnce({ message: 'A structured message error' });
- await expect(referralApi.getStats()).rejects.toEqual({
- success: false,
- error: 'A structured message error',
- });
- });
-
- it('handles primitive string errors', async () => {
- const { callCoreCommand } = await import('../../coreCommandClient');
- vi.mocked(callCoreCommand).mockRejectedValueOnce('Some primitive string error');
- await expect(referralApi.getStats()).rejects.toEqual({
- success: false,
- error: 'Some primitive string error',
- });
- });
-
- it('handles explicit Error object with missing message', async () => {
- const { callCoreCommand } = await import('../../coreCommandClient');
- const err = new Error('');
- vi.mocked(callCoreCommand).mockRejectedValueOnce(err);
- await expect(referralApi.getStats()).rejects.toEqual({ success: false, error: 'Error' });
- });
-
- it('handles Error object with whitespace message gracefully', async () => {
- const { callCoreCommand } = await import('../../coreCommandClient');
- const err = new Error(' ');
- vi.mocked(callCoreCommand).mockRejectedValueOnce(err);
- await expect(referralApi.getStats()).rejects.toEqual({ success: false, error: ' ' });
- });
-});
diff --git a/app/src/services/api/agentWorkApi.test.ts b/app/src/services/api/agentWorkApi.test.ts
deleted file mode 100644
index d485dedb0c..0000000000
--- a/app/src/services/api/agentWorkApi.test.ts
+++ /dev/null
@@ -1,158 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { callCoreRpc } from '../coreRpcClient';
-import { agentWorkApi, type AgentWorkResponse } from './agentWorkApi';
-
-vi.mock('../coreRpcClient', () => ({ callCoreRpc: vi.fn() }));
-
-const mockCall = vi.mocked(callCoreRpc);
-
-function response(): AgentWorkResponse {
- return {
- total: 2,
- groups: [
- { bucket: 'needs_input', count: 0, rows: [] },
- {
- bucket: 'working',
- count: 1,
- rows: [
- {
- runId: 'run-1',
- kind: 'subagent',
- agentId: 'agent-a',
- displayName: 'Researcher',
- bucket: 'working',
- status: 'running',
- workerThreadId: 'thread-w',
- startedAt: '2026-01-01T00:00:00Z',
- updatedAt: '2026-01-01T00:01:00Z',
- elapsedMs: 60000,
- inputTokens: 100,
- outputTokens: 50,
- costUsd: 0.01,
- toolCount: 2,
- },
- ],
- },
- { bucket: 'completed', count: 1, rows: [] },
- { bucket: 'failed', count: 0, rows: [] },
- { bucket: 'stopped', count: 0, rows: [] },
- ],
- };
-}
-
-describe('agentWorkApi', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it('list calls the agent_work_list RPC with no params when limit is omitted', async () => {
- mockCall.mockResolvedValueOnce(response());
- await agentWorkApi.list();
- expect(mockCall).toHaveBeenCalledWith({ method: 'openhuman.agent_work_list', params: {} });
- });
-
- it('list forwards an explicit limit', async () => {
- mockCall.mockResolvedValueOnce(response());
- await agentWorkApi.list(25);
- expect(mockCall).toHaveBeenCalledWith({
- method: 'openhuman.agent_work_list',
- params: { limit: 25 },
- });
- });
-
- it('list rejects a non-positive or non-integer limit without calling core', async () => {
- await expect(agentWorkApi.list(0)).rejects.toThrow('positive integer');
- await expect(agentWorkApi.list(-5)).rejects.toThrow('positive integer');
- await expect(agentWorkApi.list(1.5)).rejects.toThrow('positive integer');
- expect(mockCall).not.toHaveBeenCalled();
- });
-
- it('list returns the grouped response unchanged (wire is already camelCase)', async () => {
- mockCall.mockResolvedValueOnce(response());
- const result = await agentWorkApi.list();
- expect(result.total).toBe(2);
- expect(result.groups).toHaveLength(5);
- expect(result.groups.map(g => g.bucket)).toEqual([
- 'needs_input',
- 'working',
- 'completed',
- 'failed',
- 'stopped',
- ]);
- const working = result.groups.find(g => g.bucket === 'working');
- expect(working?.count).toBe(1);
- expect(working?.rows[0].displayName).toBe('Researcher');
- expect(working?.rows[0].workerThreadId).toBe('thread-w');
- });
-});
-
-describe('agentWorkApi.control', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- function controlled(status: string): {
- row: AgentWorkResponse['groups'][number]['rows'][number];
- } {
- return {
- row: {
- runId: 'run-1',
- kind: 'subagent',
- bucket: status === 'cancelled' ? 'stopped' : 'working',
- status,
- startedAt: '2026-01-01T00:00:00Z',
- updatedAt: '2026-01-01T00:02:00Z',
- inputTokens: 0,
- outputTokens: 0,
- costUsd: 0,
- toolCount: 0,
- },
- };
- }
-
- it('stop forwards runId + action and returns the updated row', async () => {
- mockCall.mockResolvedValueOnce(controlled('cancelled'));
- const row = await agentWorkApi.control({ runId: 'run-1', action: 'stop' });
- expect(mockCall).toHaveBeenCalledWith({
- method: 'openhuman.agent_work_control',
- params: { runId: 'run-1', action: 'stop' },
- });
- expect(row.status).toBe('cancelled');
- });
-
- it('stop includes a trimmed reason when given', async () => {
- mockCall.mockResolvedValueOnce(controlled('cancelled'));
- await agentWorkApi.control({ runId: 'run-1', action: 'stop', reason: ' manual ' });
- expect(mockCall).toHaveBeenCalledWith({
- method: 'openhuman.agent_work_control',
- params: { runId: 'run-1', action: 'stop', reason: 'manual' },
- });
- });
-
- it('continue forwards the trimmed message', async () => {
- mockCall.mockResolvedValueOnce(controlled('running'));
- await agentWorkApi.control({ runId: 'run-1', action: 'continue', message: ' go ' });
- expect(mockCall).toHaveBeenCalledWith({
- method: 'openhuman.agent_work_control',
- params: { runId: 'run-1', action: 'continue', message: 'go' },
- });
- });
-
- it('rejects continue / follow_up without a message before calling core', async () => {
- await expect(agentWorkApi.control({ runId: 'run-1', action: 'continue' })).rejects.toThrow(
- 'continue requires a message'
- );
- await expect(
- agentWorkApi.control({ runId: 'run-1', action: 'follow_up', message: ' ' })
- ).rejects.toThrow('follow_up requires a message');
- expect(mockCall).not.toHaveBeenCalled();
- });
-
- it('rejects a missing runId before calling core', async () => {
- await expect(agentWorkApi.control({ runId: ' ', action: 'retry' })).rejects.toThrow(
- 'runId is required'
- );
- expect(mockCall).not.toHaveBeenCalled();
- });
-});
diff --git a/app/src/services/api/agentWorkApi.ts b/app/src/services/api/agentWorkApi.ts
deleted file mode 100644
index eb5510fd01..0000000000
--- a/app/src/services/api/agentWorkApi.ts
+++ /dev/null
@@ -1,124 +0,0 @@
-/**
- * Frontend client for the Background Agent Command Center surface
- * (`openhuman.agent_work_list`). The Rust handler aggregates every tracked
- * background agent run into five lifecycle buckets and returns the rows
- * pre-grouped so the UI renders them in a stable order.
- *
- * The wire payload is already camelCase (the Rust controller serializes with
- * `#[serde(rename_all = "camelCase")]`), so this client only types the shape
- * and forwards the optional `limit`. No snake/camel transform is needed.
- */
-import debug from 'debug';
-
-import { callCoreRpc } from '../coreRpcClient';
-
-const log = debug('agentWorkApi');
-
-/**
- * Lifecycle bucket a run is sorted into. The handler always emits all five,
- * in this display order, even when a bucket has zero rows.
- */
-export type AgentWorkBucket = 'needs_input' | 'working' | 'completed' | 'failed' | 'stopped';
-
-/** A single background agent run. Mirrors the Rust `AgentWorkRow`. */
-export interface AgentWorkRow {
- runId: string;
- kind: string;
- agentId?: string;
- displayName?: string;
- bucket: AgentWorkBucket;
- status: string;
- parentThreadId?: string;
- workerThreadId?: string;
- summary?: string;
- error?: string;
- startedAt: string;
- updatedAt: string;
- elapsedMs?: number;
- inputTokens: number;
- outputTokens: number;
- costUsd: number;
- toolCount: number;
-}
-
-/** A bucket of rows plus its precomputed count. Mirrors the Rust group. */
-export interface AgentWorkGroup {
- bucket: AgentWorkBucket;
- count: number;
- rows: AgentWorkRow[];
-}
-
-/** Full response from `openhuman.agent_work_list`. */
-export interface AgentWorkResponse {
- groups: AgentWorkGroup[];
- total: number;
-}
-
-/**
- * Control verb applied to a single run via `openhuman.agent_work_control`.
- * Mirrors the Rust `ControlVerb`. `continue` / `followUp` require a message.
- */
-type AgentWorkAction = 'stop' | 'retry' | 'continue' | 'follow_up';
-
-/** Arguments for {@link agentWorkApi.control}. */
-interface AgentWorkControlArgs {
- runId: string;
- action: AgentWorkAction;
- /** Required for `continue` and `follow_up`; ignored otherwise. */
- message?: string;
- /** Optional note recorded when `stop`ping. */
- reason?: string;
-}
-
-/** Response from `openhuman.agent_work_control`: the re-projected row. */
-interface AgentWorkControlResponse {
- row: AgentWorkRow;
-}
-
-export const agentWorkApi = {
- /**
- * List all tracked background agent runs, grouped by lifecycle bucket.
- *
- * @param limit Optional cap on the number of rows returned (newest first,
- * applied server-side). Omit to use the handler default.
- */
- list: async (limit?: number): Promise<AgentWorkResponse> => {
- if (limit !== undefined && (!Number.isInteger(limit) || limit <= 0)) {
- throw new Error('agentWorkApi.list: limit must be a positive integer');
- }
- log('list limit=%o', limit);
- const response = await callCoreRpc<AgentWorkResponse>({
- method: 'openhuman.agent_work_list',
- params: limit === undefined ? {} : { limit },
- });
- log('list received groups=%d total=%d', response.groups.length, response.total);
- return response;
- },
-
- /**
- * Apply a control verb to one background agent run, returning the updated row.
- *
- * `continue` and `follow_up` carry the user's message; the client rejects an
- * empty message for those verbs before hitting core (the Rust handler also
- * enforces it). `stop` may carry an optional `reason`.
- */
- control: async (args: AgentWorkControlArgs): Promise<AgentWorkRow> => {
- const runId = args.runId?.trim();
- if (!runId) throw new Error('agentWorkApi.control: runId is required');
- const message = args.message?.trim();
- if ((args.action === 'continue' || args.action === 'follow_up') && !message) {
- throw new Error(`agentWorkApi.control: ${args.action} requires a message`);
- }
- const params: Record<string, unknown> = { runId, action: args.action };
- if (message) params.message = message;
- const reason = args.reason?.trim();
- if (reason) params.reason = reason;
- log('control runId=%s action=%s', runId, args.action);
- const response = await callCoreRpc<AgentWorkControlResponse>({
- method: 'openhuman.agent_work_control',
- params,
- });
- log('control received status=%s', response.row.status);
- return response.row;
- },
-};
diff --git a/app/src/services/api/referralApi.ts b/app/src/services/api/referralApi.ts
deleted file mode 100644
index 6450a2e56d..0000000000
--- a/app/src/services/api/referralApi.ts
+++ /dev/null
@@ -1,322 +0,0 @@
-import type {
- ReferralRelationshipStatus,
- ReferralRow,
- ReferralStats,
- ReferralStatsTotals,
-} from '../../types/referral';
-import { getOrCreateDeviceFingerprint } from '../../utils/deviceFingerprint';
-import { callCoreCommand } from '../coreCommandClient';
-
-/** Shape thrown by {@link referralApi.getStats} / {@link referralApi.claimReferral} on RPC failure. */
-type ReferralRpcFailure = { success: false; error: string };
-
-function referralRpcErrorMessage(err: unknown): string {
- if (err && typeof err === 'object') {
- const o = err as Record<string, unknown>;
- if (typeof o.error === 'string' && o.error.trim() !== '') {
- return o.error;
- }
- if (typeof o.message === 'string' && o.message.trim() !== '') {
- return o.message;
- }
- }
- if (err instanceof Error && err.message) {
- return err.message;
- }
- return String(err);
-}
-
-function throwReferralRpcFailure(err: unknown): never {
- const failure: ReferralRpcFailure = { success: false, error: referralRpcErrorMessage(err) };
- throw failure;
-}
-
-function num(v: unknown): number {
- if (typeof v === 'number' && Number.isFinite(v)) return v;
- if (typeof v === 'string' && v.trim() !== '') {
- const n = Number(v);
- return Number.isFinite(n) ? n : 0;
- }
- return 0;
-}
-
-/** Mongo Decimal128 in JSON (`{ $numberDecimal: "1.23" }`) and similar. */
-function coerceMoney(v: unknown): number {
- if (v === null || v === undefined) return 0;
- if (typeof v === 'number' && Number.isFinite(v)) return v;
- if (typeof v === 'string' && v.trim() !== '') {
- const n = Number(v);
- return Number.isFinite(n) ? n : 0;
- }
- const o = asRecord(v);
- if (o && typeof o.$numberDecimal === 'string') {
- return num(o.$numberDecimal);
- }
- return 0;
-}
-
-function coerceId(v: unknown): string | undefined {
- if (typeof v === 'string' && v.trim()) return v.trim();
- const o = asRecord(v);
- if (o && typeof o.$oid === 'string' && o.$oid.trim()) return o.$oid.trim();
- return undefined;
-}
-
-function asRecord(v: unknown): Record<string, unknown> | null {
- return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : null;
-}
-
-function normalizeStatus(raw: unknown): ReferralRelationshipStatus {
- const s = typeof raw === 'string' ? raw.toLowerCase().trim() : '';
- if (s === 'converted' || s === 'completed' || s === 'complete') return 'converted';
- if (s === 'joined') return 'pending';
- if (s === 'pending' || s === 'expired') return s;
- return 'pending';
-}
-
-function rowRewardUsd(r: Record<string, unknown>): number {
- const direct = coerceMoney(
- r.rewardUsd ??
- r.reward_usd ??
- r.rewardAmountUsd ??
- r.reward_amount_usd ??
- r.totalRewardUsd ??
- r.total_reward_usd
- );
- const cents = num(r.rewardCents ?? r.reward_cents);
- const fromCents = cents > 0 ? cents / 100 : 0;
-
- const txs = r.transactions ?? r.referralTransactions ?? r.referral_transactions;
- let txSum = 0;
- if (Array.isArray(txs)) {
- for (const t of txs) {
- const tr = asRecord(t) ?? {};
- const m = coerceMoney(tr.rewardAmountUsd ?? tr.reward_amount_usd ?? tr.rewardUsd);
- const c = num(tr.rewardCents ?? tr.reward_cents);
- txSum += m > 0 ? m : c > 0 ? c / 100 : 0;
- }
- }
-
- if (txSum > 0) return txSum;
- if (direct > 0) return direct;
- return fromCents;
-}
-
-function normalizeRow(entry: unknown): ReferralRow {
- const r = asRecord(entry) ?? {};
- const refUser = asRecord(r.referredUser ?? r.referred_user ?? r.user);
- const rewardUsd = rowRewardUsd(r);
- const referredUserId =
- (typeof r.referredUserId === 'string' && r.referredUserId) ||
- (typeof r.referred_user_id === 'string' && r.referred_user_id) ||
- (typeof r.refereeId === 'string' && r.refereeId) ||
- (typeof r.referee_id === 'string' && r.referee_id) ||
- coerceId(r.referredUserId) ||
- coerceId(r.referred_user_id) ||
- (refUser
- ? (coerceId(refUser._id) ?? (typeof refUser.id === 'string' ? refUser.id : undefined))
- : undefined);
- const referredDisplayName =
- typeof r.referredDisplayName === 'string'
- ? r.referredDisplayName
- : typeof r.referred_display_name === 'string'
- ? r.referred_display_name
- : typeof r.referredUsername === 'string'
- ? r.referredUsername
- : refUser && typeof refUser.username === 'string'
- ? refUser.username
- : undefined;
-
- const referredUserMaskedRaw =
- typeof r.referredUserMasked === 'string'
- ? r.referredUserMasked
- : typeof r.referred_user_masked === 'string'
- ? r.referred_user_masked
- : undefined;
- const referredUserMasked =
- referredUserMaskedRaw && referredUserMaskedRaw.trim() !== ''
- ? referredUserMaskedRaw.trim()
- : undefined;
-
- return {
- id:
- (typeof r.referralId === 'string' && r.referralId) ||
- (typeof r.referral_id === 'string' && r.referral_id) ||
- (typeof r.id === 'string' && r.id) ||
- (typeof r._id === 'string' && r._id) ||
- coerceId(r._id),
- referredUserId,
- status: normalizeStatus(r.status),
- referralCode:
- typeof r.referralCode === 'string'
- ? r.referralCode
- : typeof r.referral_code === 'string'
- ? r.referral_code
- : undefined,
- createdAt:
- typeof r.joinedAt === 'string'
- ? r.joinedAt
- : typeof r.joined_at === 'string'
- ? r.joined_at
- : typeof r.createdAt === 'string'
- ? r.createdAt
- : typeof r.created_at === 'string'
- ? r.created_at
- : undefined,
- convertedAt:
- r.convertedAt === null
- ? null
- : typeof r.convertedAt === 'string'
- ? r.convertedAt
- : typeof r.converted_at === 'string'
- ? r.converted_at
- : undefined,
- rewardUsd: rewardUsd > 0 ? rewardUsd : undefined,
- referredDisplayName,
- referredUserMasked,
- };
-}
-
-function deriveTotalsFromReferrals(referrals: ReferralRow[]): ReferralStatsTotals {
- let totalRewardUsd = 0;
- let pendingCount = 0;
- let convertedCount = 0;
- for (const row of referrals) {
- if (row.rewardUsd != null && row.rewardUsd > 0) {
- totalRewardUsd += row.rewardUsd;
- }
- if (row.status === 'pending') pendingCount += 1;
- if (row.status === 'converted') convertedCount += 1;
- }
- return { totalRewardUsd, pendingCount, convertedCount };
-}
-
-/**
- * Map backend `/referral/stats` payload (flexible field names) to UI types.
- */
-export function normalizeReferralStats(raw: unknown): ReferralStats {
- const r = asRecord(raw) ?? {};
- const code = String(r.referralCode ?? r.code ?? '').trim();
- const link = String(r.referralLink ?? r.link ?? '').trim();
-
- const totalsRaw = asRecord(r.totals) ?? asRecord(r.summary) ?? {};
- const totalFromApi = Math.max(
- coerceMoney(
- totalsRaw.totalRewardsEarnedUsd ??
- totalsRaw.total_rewards_earned_usd ??
- totalsRaw.totalRewardUsd ??
- totalsRaw.total_reward_usd ??
- totalsRaw.lifetimeRewardUsd ??
- totalsRaw.lifetime_reward_usd
- ),
- coerceMoney(
- r.totalRewardsEarnedUsd ??
- r.total_rewards_earned_usd ??
- r.totalRewardUsd ??
- r.total_reward_usd ??
- r.totalEarningsUsd ??
- r.total_earnings_usd ??
- r.earningsUsd ??
- r.earnings_usd ??
- r.rewardsTotalUsd ??
- r.rewards_total_usd
- )
- );
-
- const pendingFromApi = Math.round(
- num(
- totalsRaw.pendingCount ??
- totalsRaw.pending_count ??
- totalsRaw.pendingReferrals ??
- totalsRaw.pending_referrals ??
- r.pendingCount ??
- r.pending_count
- )
- );
- const convertedFromApi = Math.round(
- num(
- totalsRaw.convertedCount ??
- totalsRaw.converted_count ??
- totalsRaw.convertedReferrals ??
- totalsRaw.converted_referrals ??
- r.convertedCount ??
- r.converted_count
- )
- );
-
- const listRaw = r.referrals ?? r.referralRows ?? r.rows;
- const referrals: ReferralRow[] = Array.isArray(listRaw) ? listRaw.map(normalizeRow) : [];
-
- const derived = deriveTotalsFromReferrals(referrals);
- const totals: ReferralStatsTotals = {
- totalRewardUsd: totalFromApi > 0 ? totalFromApi : derived.totalRewardUsd,
- pendingCount: pendingFromApi || derived.pendingCount,
- convertedCount: convertedFromApi || derived.convertedCount,
- };
-
- const appliedReferralCode =
- r.appliedReferralCode === null
- ? null
- : typeof r.appliedReferralCode === 'string'
- ? r.appliedReferralCode
- : typeof r.applied_referral_code === 'string'
- ? r.applied_referral_code
- : undefined;
-
- const canApplyReferral =
- typeof r.canApplyReferral === 'boolean'
- ? r.canApplyReferral
- : typeof r.can_apply_referral === 'boolean'
- ? r.can_apply_referral
- : undefined;
-
- return {
- referralCode: code,
- referralLink: link,
- totals,
- referrals,
- appliedReferralCode,
- canApplyReferral,
- };
-}
-
-export const referralApi = {
- /**
- * Referral stats via core RPC (`openhuman.referral_get_stats` → backend GET /referral/stats).
- * Uses the sidecar HTTP client so the desktop WebView avoids direct `fetch` (fixes WKWebView "Load failed" / CORS to the API host).
- */
- getStats: async (): Promise<ReferralStats> => {
- try {
- const data = await callCoreCommand<unknown>('openhuman.referral_get_stats');
- console.debug('[referral] stats loaded via core', {
- hasCode: !!(data && typeof data === 'object'),
- });
- return normalizeReferralStats(data);
- } catch (err) {
- console.debug('[referral] getStats RPC failed', referralRpcErrorMessage(err));
- throwReferralRpcFailure(err);
- }
- },
-
- /**
- * Claim a referral link via core RPC (`openhuman.referral_claim` → backend POST /referral/claim).
- * Only users who have not yet subscribed are eligible.
- */
- claimReferral: async (code: string): Promise<void> => {
- const trimmed = code.trim();
- if (!trimmed) {
- throw { success: false as const, error: 'Referral code is required' };
- }
- const deviceFingerprint = getOrCreateDeviceFingerprint();
- try {
- await callCoreCommand<unknown>('openhuman.referral_claim', {
- code: trimmed,
- deviceFingerprint,
- });
- console.debug('[referral] claim succeeded', { codeLength: trimmed.length });
- } catch (err) {
- console.debug('[referral] claim RPC failed', referralRpcErrorMessage(err));
- throwReferralRpcFailure(err);
- }
- },
-};
diff --git a/app/src/utils/__tests__/agentMessageBubbles.test.ts b/app/src/utils/__tests__/agentMessageBubbles.test.ts
deleted file mode 100644
index fa92ee343c..0000000000
--- a/app/src/utils/__tests__/agentMessageBubbles.test.ts
+++ /dev/null
@@ -1,213 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { parseMarkdownTable, splitAgentMessageIntoBubbles } from '../agentMessageBubbles';
-
-describe('splitAgentMessageIntoBubbles', () => {
- it('returns a single bubble when there are no newlines', () => {
- expect(splitAgentMessageIntoBubbles('One line only.')).toEqual(['One line only.']);
- });
-
- it('returns no bubbles for empty or whitespace-only content', () => {
- expect(splitAgentMessageIntoBubbles('')).toEqual([]);
- expect(splitAgentMessageIntoBubbles(' \n\n ')).toEqual([]);
- });
-
- it('keeps single-paragraph newline-separated lines in one bubble', () => {
- expect(splitAgentMessageIntoBubbles('First line\nSecond line\nThird line')).toEqual([
- 'First line\nSecond line\nThird line',
- ]);
- });
-
- it('ignores empty lines between bubbles', () => {
- expect(splitAgentMessageIntoBubbles('First line\n\nSecond line\n\n\nThird line')).toEqual([
- 'First line',
- 'Second line',
- 'Third line',
- ]);
- });
-
- it('keeps fenced code blocks together as one bubble', () => {
- const content = 'Here is code\n```ts\nconst x = 1;\nconst y = 2;\n```\nDone';
- expect(splitAgentMessageIntoBubbles(content)).toEqual([
- 'Here is code',
- '```ts\nconst x = 1;\nconst y = 2;\n```',
- 'Done',
- ]);
- });
-
- it('normalizes windows newlines', () => {
- expect(splitAgentMessageIntoBubbles('First\r\nSecond\r\nThird')).toEqual([
- 'First\nSecond\nThird',
- ]);
- });
-
- it('keeps markdown tables together as one segment', () => {
- const content =
- 'Summary\n| Name | Value |\n| --- | --- |\n| Alpha | 1 |\n| Beta | 2 |\nNext step';
- expect(splitAgentMessageIntoBubbles(content)).toEqual([
- 'Summary',
- '| Name | Value |\n| --- | --- |\n| Alpha | 1 |\n| Beta | 2 |',
- 'Next step',
- ]);
- });
-
- it('does not absorb a following prose line whose pipes give a different column count', () => {
- // The prose line satisfies looksLikeMarkdownTableRow (it contains pipes) but
- // has 3 "cells" vs the table's 2; absorbing it makes parseMarkdownTable
- // reject the block (null), suppressing the table renderer and merging the
- // prose into the table bubble.
- const content =
- '| Plan | Cost |\n| --- | --- |\n| Basic | $10 |\nEither pick Basic | Pro, then run `ps aux | grep node`.';
- expect(splitAgentMessageIntoBubbles(content)).toEqual([
- '| Plan | Cost |\n| --- | --- |\n| Basic | $10 |',
- 'Either pick Basic | Pro, then run `ps aux | grep node`.',
- ]);
- });
-
- it('keeps a table whose first data row carries a code-span pipe as one readable block', () => {
- // splitMarkdownTableCells splits naively on "|", so a genuine first data row
- // with a pipe inside a code span over-counts its cells (3 vs the header's 2).
- // Dropping it would leave a header+separator-only block that renders as an
- // empty-row table and detaches the real row; keeping the first data row makes
- // parseMarkdownTable return null so the block falls back to readable markdown.
- const content = '| Command | Use |\n| --- | --- |\n| `ps aux | grep node` | Find it |';
- expect(splitAgentMessageIntoBubbles(content)).toEqual([content]);
- });
-
- it('keeps double-newline paragraphs in the same bubble', () => {
- const content = 'First line\nSecond line\n\nThird paragraph\nFourth line';
- expect(splitAgentMessageIntoBubbles(content)).toEqual([
- 'First line\nSecond line',
- 'Third paragraph\nFourth line',
- ]);
- });
-
- it('normalizes 3+ newlines down to double before splitting', () => {
- const content = 'One\n\n\n\nTwo\n\n\nThree';
- expect(splitAgentMessageIntoBubbles(content)).toEqual(['One', 'Two', 'Three']);
- });
-
- it('treats <hr> as a bubble break', () => {
- const content = 'First section\n<hr>\nSecond section\n\n<hr />\nThird section';
- expect(splitAgentMessageIntoBubbles(content)).toEqual([
- 'First section',
- 'Second section',
- 'Third section',
- ]);
- });
-
- it('never returns an hr-only bubble', () => {
- expect(splitAgentMessageIntoBubbles('<hr>')).toEqual([]);
- expect(splitAgentMessageIntoBubbles('Before\n\n<hr />\n\nAfter')).toEqual(['Before', 'After']);
- });
-
- it('never returns a markdown thematic-break-only bubble', () => {
- expect(splitAgentMessageIntoBubbles('---')).toEqual([]);
- expect(splitAgentMessageIntoBubbles('***')).toEqual([]);
- expect(splitAgentMessageIntoBubbles('___')).toEqual([]);
- expect(splitAgentMessageIntoBubbles('Before\n\n---\n\nAfter')).toEqual(['Before', 'After']);
- });
-
- // Issue #3807: a heading and its body must never land in separate bubbles.
- it('keeps an ATX heading together with its body in one bubble', () => {
- expect(splitAgentMessageIntoBubbles('## 📅 Calendar\n\n- 9am standup')).toEqual([
- '## 📅 Calendar\n\n- 9am standup',
- ]);
- });
-
- it('keeps a bold-line heading together with its body in one bubble', () => {
- expect(splitAgentMessageIntoBubbles('**Tasks**\n\n- Ship the PR')).toEqual([
- '**Tasks**\n\n- Ship the PR',
- ]);
- });
-
- it('renders a multi-section morning briefing as one bubble per section', () => {
- const briefing = [
- 'Good morning! Here is what today looks like.',
- '## 📅 Calendar',
- '- 9:00 Standup\n- 14:00 Design review',
- '## ✅ Tasks',
- '- Finish the proposal (due today)',
- '## 📧 Emails',
- '2 unread threads from key contacts',
- ].join('\n\n');
-
- const bubbles = splitAgentMessageIntoBubbles(briefing);
-
- expect(bubbles).toEqual([
- 'Good morning! Here is what today looks like.',
- '## 📅 Calendar\n\n- 9:00 Standup\n- 14:00 Design review',
- '## ✅ Tasks\n\n- Finish the proposal (due today)',
- '## 📧 Emails\n\n2 unread threads from key contacts',
- ]);
-
- // No bubble is a heading with no body, and no body bubble lacks its heading.
- for (const bubble of bubbles.slice(1)) {
- const lines = bubble.split('\n').filter(line => line.trim().length > 0);
- expect(lines.length).toBeGreaterThan(1);
- expect(lines[0].startsWith('#')).toBe(true);
- }
- });
-
- it('absorbs trailing closing lines into the final section bubble', () => {
- const briefing = '## 📧 Emails\n\n2 unread threads\n\nHave a great day! ☀️';
- expect(splitAgentMessageIntoBubbles(briefing)).toEqual([
- '## 📧 Emails\n\n2 unread threads\n\nHave a great day! ☀️',
- ]);
- });
-
- it('keeps a table out of the heading bubble so the table renderer still fires', () => {
- // A table folded behind a heading would not sit at the bubble start and
- // would render as raw pipe text, so it stays its own segment.
- const content = '## 📅 Calendar\n\n| Time | Event |\n| --- | --- |\n| 9:00 | Standup |';
- expect(splitAgentMessageIntoBubbles(content)).toEqual([
- '## 📅 Calendar',
- '| Time | Event |\n| --- | --- |\n| 9:00 | Standup |',
- ]);
- });
-
- it('still groups body paragraphs that follow a table under their heading', () => {
- const content =
- '## 📅 Calendar\n\n| Time | Event |\n| --- | --- |\n| 9:00 | Standup |\n\n## ✅ Tasks\n\n- Ship the PR';
- expect(splitAgentMessageIntoBubbles(content)).toEqual([
- '## 📅 Calendar',
- '| Time | Event |\n| --- | --- |\n| 9:00 | Standup |',
- '## ✅ Tasks\n\n- Ship the PR',
- ]);
- });
-
- it('folds a trailing body-less heading into the previous bubble', () => {
- const content = '## 📅 Calendar\n\n- 9:00 Standup\n\n## ✅ Tasks';
- expect(splitAgentMessageIntoBubbles(content)).toEqual([
- '## 📅 Calendar\n\n- 9:00 Standup\n\n## ✅ Tasks',
- ]);
- });
-
- it('does not treat inline bold emphasis with trailing prose as a heading', () => {
- // Only a fully-bold line is a heading; emphasis followed by prose stays a
- // plain paragraph so ordinary content is not misclassified.
- const content = '**Heads up:** the meeting moved\n\nSee you at 3pm';
- expect(splitAgentMessageIntoBubbles(content)).toEqual([
- '**Heads up:** the meeting moved',
- 'See you at 3pm',
- ]);
- });
-});
-
-describe('parseMarkdownTable', () => {
- it('parses a markdown table into headers and rows', () => {
- expect(
- parseMarkdownTable('| Name | Value |\n| --- | --- |\n| Alpha | 1 |\n| Beta | 2 |')
- ).toEqual({
- headers: ['Name', 'Value'],
- rows: [
- ['Alpha', '1'],
- ['Beta', '2'],
- ],
- });
- });
-
- it('returns null for non-table content', () => {
- expect(parseMarkdownTable('Just a normal message')).toBeNull();
- });
-});
diff --git a/app/src/utils/agentMessageBubbles.ts b/app/src/utils/agentMessageBubbles.ts
deleted file mode 100644
index a9a0ab5b4a..0000000000
--- a/app/src/utils/agentMessageBubbles.ts
+++ /dev/null
@@ -1,269 +0,0 @@
-import debugFactory from 'debug';
-
-const debug = debugFactory('agent-message-bubbles');
-
-/**
- * Split an agent message into render-time bubble segments.
- *
- * Normalize excessive vertical whitespace first, then split only on double
- * newlines. Fenced code blocks stay intact as a single segment so
- * Markdown/code rendering does not fragment unexpectedly.
- * Markdown tables also stay grouped so they can render as dedicated table UI.
- *
- * Finally, regroup so a section heading and the body that follows it always
- * share one bubble (issue #3807): structured output such as the morning
- * briefing writes `## Heading\n\n- body…`, and splitting on the blank line
- * would otherwise orphan every heading into its own content-less bubble.
- */
-export function splitAgentMessageIntoBubbles(content: string): string[] {
- const normalized = content
- .replace(/\r\n/g, '\n')
- .replace(/\n{3,}/g, '\n\n')
- .replace(/\n?\s*<hr\s*\/?>\s*\n?/gi, '\n\n');
- const trimmedContent = normalized.trim();
- if (trimmedContent.length === 0) return [];
- if (!normalized.includes('\n')) {
- return isVisualSeparatorOnly(trimmedContent) ? [] : [trimmedContent];
- }
-
- const lines = normalized.split('\n');
- const segments: string[] = [];
- let currentLines: string[] = [];
- let inFence = false;
-
- const flushCurrent = () => {
- const segment = currentLines.join('\n').trim();
- if (segment.length > 0) {
- segments.push(segment);
- }
- currentLines = [];
- };
-
- for (let index = 0; index < lines.length; index += 1) {
- const line = lines[index];
- const trimmedLine = line.trim();
-
- if (!inFence && isMarkdownTableStart(lines, index)) {
- if (currentLines.length > 0) {
- flushCurrent();
- }
- // A prose line that merely contains a pipe (e.g. "pick A | B, then run
- // `ps aux | grep x`") satisfies looksLikeMarkdownTableRow but is not a
- // table row. Require the same column count as the header so it isn't
- // absorbed into the table — otherwise parseMarkdownTable rejects the
- // mismatched block (returns null), suppressing the table UI and merging
- // the prose line into the table bubble.
- //
- // Always keep at least the first data row, though: splitMarkdownTableCells
- // splits naively on "|" and does not honor escaped "\|" or pipes inside
- // code spans, so a genuine first row carrying such a pipe over-counts its
- // cells. Dropping it here would leave a header+separator-only block that
- // parseMarkdownTable renders as an empty-row table (and detaches the real
- // row). Keeping it preserves the count mismatch so parseMarkdownTable
- // returns null and the block falls back to readable raw markdown.
- const headerCellCount = splitMarkdownTableCells(line).length;
- const tableLines = [line, lines[index + 1]];
- index += 2;
- let dataRowsAbsorbed = 0;
- while (index < lines.length && looksLikeMarkdownTableRow(lines[index])) {
- const matches = splitMarkdownTableCells(lines[index]).length === headerCellCount;
- if (!matches && dataRowsAbsorbed > 0) break;
- tableLines.push(lines[index]);
- dataRowsAbsorbed += 1;
- index += 1;
- }
- index -= 1;
- segments.push(tableLines.join('\n').trim());
- continue;
- }
-
- if (trimmedLine.startsWith('```')) {
- if (!inFence && currentLines.length > 0) {
- flushCurrent();
- }
- currentLines.push(line);
- inFence = !inFence;
- if (!inFence) {
- flushCurrent();
- }
- continue;
- }
-
- if (inFence) {
- currentLines.push(line);
- continue;
- }
-
- if (trimmedLine.length === 0) {
- if (currentLines.length > 0) {
- flushCurrent();
- }
- continue;
- }
-
- currentLines.push(line);
- }
-
- flushCurrent();
- const cleaned = segments.filter(segment => !isVisualSeparatorOnly(segment));
- const grouped = groupSectionsUnderHeadings(cleaned);
- debug(
- '[bubbles] %d char message -> %d raw segment(s) -> %d bubble(s) after heading grouping',
- content.length,
- cleaned.length,
- grouped.length
- );
- return grouped;
-}
-
-/**
- * Merge each section heading with the body segments that follow it (up to the
- * next heading) into a single bubble, so a heading is never stranded in a
- * content-less bubble of its own. Segments before the first heading (e.g. a
- * greeting) are left untouched.
- *
- * Tables are deliberately NOT absorbed into a heading bubble: `AgentMessageBubble`
- * only renders the dedicated table UI when the table sits at the start of the
- * bubble (`parseMarkdownTable`), and the Markdown renderer has no GFM-table
- * support, so folding a table behind a heading would render it as raw pipe
- * text. A table therefore stays its own bubble and ends the current section.
- */
-function groupSectionsUnderHeadings(segments: string[]): string[] {
- const grouped: string[] = [];
- let index = 0;
-
- while (index < segments.length) {
- const segment = segments[index];
-
- if (!startsWithHeading(segment)) {
- grouped.push(segment);
- index += 1;
- continue;
- }
-
- // Absorb the body paragraphs below this heading — but stop at the next
- // heading or a table, both of which must begin their own bubble.
- const body: string[] = [];
- index += 1;
- while (
- index < segments.length &&
- !startsWithHeading(segments[index]) &&
- !isTableSegment(segments[index])
- ) {
- body.push(segments[index]);
- index += 1;
- }
-
- if (body.length > 0) {
- grouped.push([segment, ...body].join('\n\n'));
- continue;
- }
-
- // Heading with no inline body. Avoid an orphan heading bubble: when the
- // next segment is a table the heading labels it from the bubble directly
- // above (and must not be folded into the table); otherwise fold the
- // heading into the previous bubble, unless that bubble is itself a table.
- const nextIsTable = index < segments.length && isTableSegment(segments[index]);
- const previous = grouped[grouped.length - 1];
- if (!nextIsTable && previous !== undefined && !isTableSegment(previous)) {
- grouped[grouped.length - 1] = `${previous}\n\n${segment}`;
- } else {
- grouped.push(segment);
- }
- }
-
- return grouped;
-}
-
-/** A segment "starts a section" when its first non-empty line is a heading. */
-function startsWithHeading(segment: string): boolean {
- const firstLine = segment.split('\n').find(line => line.trim().length > 0) ?? '';
- return isHeadingLine(firstLine);
-}
-
-/** A segment is a table when its first non-empty line begins a markdown table. */
-function isTableSegment(segment: string): boolean {
- const lines = segment.split('\n');
- let index = 0;
- while (index < lines.length && lines[index].trim().length === 0) index += 1;
- return isMarkdownTableStart(lines, index);
-}
-
-/**
- * Recognize the heading shapes structured agent output uses to label a
- * section: Markdown ATX headings (`#`..`######`) and a single fully-bold line
- * (`**Calendar**`), optionally with a trailing colon.
- *
- * The bold form deliberately requires the WHOLE line to be bold — inline
- * emphasis with trailing prose (`**Heads up:** the meeting moved`) is NOT a
- * heading, so ordinary emphasized content is not misclassified. The residual
- * heuristic risk is a standalone fully-bold sentence used as content; in that
- * case it is simply merged with the following segment (kept together, never
- * orphaned), which is harmless for the structured briefing shapes this serves.
- */
-function isHeadingLine(line: string): boolean {
- const trimmed = line.trim();
- if (/^#{1,6}\s+\S/.test(trimmed)) return true;
- return /^\*\*[^*]+\*\*:?$/.test(trimmed);
-}
-
-interface ParsedMarkdownTable {
- headers: string[];
- rows: string[][];
-}
-
-export function parseMarkdownTable(content: string): ParsedMarkdownTable | null {
- const normalized = content.replace(/\r\n/g, '\n').trim();
- const lines = normalized
- .split('\n')
- .map(line => line.trim())
- .filter(line => line.length > 0);
-
- if (lines.length < 2) return null;
- if (!isMarkdownTableStart(lines, 0)) return null;
-
- const headers = splitMarkdownTableCells(lines[0]);
- const rows = lines.slice(2).map(splitMarkdownTableCells);
-
- if (headers.length === 0 || rows.some(row => row.length !== headers.length)) {
- return null;
- }
-
- return { headers, rows };
-}
-
-function isMarkdownTableStart(lines: string[], index: number): boolean {
- const header = lines[index];
- const separator = lines[index + 1];
- if (!header || !separator) return false;
- return looksLikeMarkdownTableRow(header) && looksLikeMarkdownTableSeparator(separator);
-}
-
-function looksLikeMarkdownTableRow(line: string): boolean {
- const trimmed = line.trim();
- if (!trimmed.includes('|')) return false;
- const cells = splitMarkdownTableCells(trimmed);
- return cells.length >= 2;
-}
-
-function looksLikeMarkdownTableSeparator(line: string): boolean {
- const cells = splitMarkdownTableCells(line);
- if (cells.length < 2) return false;
- return cells.every(cell => /^:?-{3,}:?$/.test(cell));
-}
-
-function splitMarkdownTableCells(line: string): string[] {
- return line
- .trim()
- .replace(/^\|/, '')
- .replace(/\|$/, '')
- .split('|')
- .map(cell => cell.trim());
-}
-
-function isVisualSeparatorOnly(segment: string): boolean {
- const trimmed = segment.trim();
- if (trimmed.length === 0) return true;
- if (/^<hr\s*\/?>$/i.test(trimmed)) return true;
- return /^(?:-{3,}|\*{3,}|_{3,})$/.test(trimmed.replace(/\s+/g, ''));
-}