Skip to content

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

chore: remove unused components and their tests

Steven Enamakela64d23ed1a47
diff --git a/app/src/components/ConnectionIndicator.tsx b/app/src/components/ConnectionIndicator.tsx
deleted file mode 100644
index 37465ef340..0000000000
--- a/app/src/components/ConnectionIndicator.tsx
+++ /dev/null
@@ -1,142 +0,0 @@
-import { useT } from '../lib/i18n/I18nContext';
-import { selectBlockingState } from '../store/connectivitySelectors';
-import { useAppSelector } from '../store/hooks';
-import { selectSocketStatus } from '../store/socketSelectors';
-
-interface ConnectionIndicatorProps {
- /**
- * Optional override — used by storybook fixtures and a couple of legacy
- * call sites that still drive a single 3-state pill from local state. New
- * code should NOT pass this; let the indicator read connectivitySlice.
- */
- status?: 'connected' | 'disconnected' | 'connecting';
- className?: string;
-}
-
-interface StatusConfig {
- color: string;
- textColor: string;
- text: string;
- pulse: boolean;
-}
-
-/**
- * 4-channel connectivity chip (#1527, #6256).
- *
- * Reads `selectBlockingState`, which encodes the user-visible precedence:
- * internet > core > backend (renderer↔core socket) > hosted (the core's own
- * link to the hosted backend). The legacy `status` prop and
- * `selectSocketStatus` fallback are retained so existing call sites that
- * pre-date the split keep rendering correctly during rollout.
- */
-const ConnectionIndicator = ({
- status: overrideStatus,
- className = '',
-}: ConnectionIndicatorProps) => {
- const { t } = useT();
- const blocking = useAppSelector(selectBlockingState);
- const legacyStatus = useAppSelector(selectSocketStatus);
- const hosted = useAppSelector(state => state.connectivity.hosted);
-
- const config: StatusConfig = (() => {
- if (overrideStatus) {
- return legacyMap(t)[overrideStatus];
- }
- switch (blocking) {
- case 'ok':
- return {
- color: 'bg-sage-500',
- textColor: 'text-sage-500',
- text: t('app.connectionIndicator.connected'),
- pulse: true,
- };
- case 'internet-offline':
- return {
- color: 'bg-coral-500',
- textColor: 'text-coral-500',
- text: t('app.connectionIndicator.offline'),
- pulse: false,
- };
- case 'core-unreachable':
- return {
- color: 'bg-amber-500',
- textColor: 'text-amber-500',
- text: t('app.connectionIndicator.coreOffline'),
- pulse: false,
- };
- case 'backend-only':
- return {
- color: 'bg-amber-500',
- textColor: 'text-amber-500',
- text:
- legacyStatus === 'connecting'
- ? t('app.connectionIndicator.connecting')
- : t('app.connectionIndicator.reconnecting'),
- pulse: false,
- };
- case 'hosted-degraded':
- // Soft state, same treatment as `backend-only`: chat still works, the
- // core is retrying its hosted link and the chip says so (#6256).
- return {
- color: 'bg-amber-500',
- textColor: 'text-amber-500',
- text:
- hosted === 'connecting'
- ? t('app.connectionIndicator.connecting')
- : t('app.connectionIndicator.reconnecting'),
- pulse: false,
- };
- case 'hosted-stopped':
- // The core's loop stopped for good on an unusable session: nothing is
- // retrying, so no "reconnecting" wording — the Home copy says to sign
- // in again (#6270).
- return {
- color: 'bg-amber-500',
- textColor: 'text-amber-500',
- text: t('app.connectionIndicator.disconnected'),
- pulse: false,
- };
- }
- })();
-
- // Simplified two-state label (the dot colour still reflects the nuanced
- // connecting/reconnecting states).
- const isConnected = overrideStatus ? overrideStatus === 'connected' : blocking === 'ok';
- const label = isConnected
- ? t('app.connectionIndicator.connected')
- : t('app.connectionIndicator.disconnected');
-
- return (
- <div className={`inline-flex items-center gap-1.5 ${className}`}>
- <div
- className={`w-2 h-2 ${config.color} rounded-full ${config.pulse ? 'animate-pulse' : ''}`}
- />
- <span className={`text-[10px] font-medium ${config.textColor}`}>{label}</span>
- </div>
- );
-};
-
-const legacyMap = (
- t: (k: string) => string
-): Record<'connected' | 'disconnected' | 'connecting', StatusConfig> => ({
- connected: {
- color: 'bg-sage-500',
- textColor: 'text-sage-500',
- text: t('app.connectionIndicator.connected'),
- pulse: true,
- },
- disconnected: {
- color: 'bg-coral-500',
- textColor: 'text-coral-500',
- text: t('app.connectionIndicator.disconnected'),
- pulse: false,
- },
- connecting: {
- color: 'bg-amber-500',
- textColor: 'text-amber-500',
- text: t('app.connectionIndicator.connecting'),
- pulse: false,
- },
-});
-
-export default ConnectionIndicator;
diff --git a/app/src/components/__tests__/ConnectionIndicator.test.tsx b/app/src/components/__tests__/ConnectionIndicator.test.tsx
deleted file mode 100644
index f5deddc04f..0000000000
--- a/app/src/components/__tests__/ConnectionIndicator.test.tsx
+++ /dev/null
@@ -1,180 +0,0 @@
-import { screen } from '@testing-library/react';
-import { describe, expect, it } from 'vitest';
-
-import { renderWithProviders } from '../../test/test-utils';
-import ConnectionIndicator from '../ConnectionIndicator';
-
-describe('ConnectionIndicator', () => {
- it('renders connected state with override prop', () => {
- renderWithProviders(<ConnectionIndicator status="connected" />);
- expect(screen.getByText('Connected')).toBeInTheDocument();
- });
-
- it('renders disconnected state', () => {
- renderWithProviders(<ConnectionIndicator status="disconnected" />);
- expect(screen.getByText('Disconnected')).toBeInTheDocument();
- });
-
- it('renders connecting state', () => {
- renderWithProviders(<ConnectionIndicator status="connecting" />);
- expect(screen.getByText('Disconnected')).toBeInTheDocument();
- });
-
- it('renders as a pill badge', () => {
- renderWithProviders(<ConnectionIndicator status="connected" />);
- // The indicator renders as an inline pill — status text is visible
- expect(screen.getByText('Connected')).toBeInTheDocument();
- });
-
- it('falls back to connectivity store when no override', () => {
- // Default connectivity state: internet online + core unknown +
- // backend connecting → blocking = backend-only → "Reconnecting…"
- // (#1527: split status; default reflects boot-time pre-socket state.)
- renderWithProviders(<ConnectionIndicator />);
- expect(screen.getByText('Disconnected')).toBeInTheDocument();
- });
-
- // ---- Store-driven branches (lines 43, 50, 57, 67) ----
-
- it('shows "Connected to OpenHuman AI" when blocking=ok (line 43)', () => {
- renderWithProviders(<ConnectionIndicator />, {
- preloadedState: {
- connectivity: {
- internet: 'online',
- core: 'reachable',
- backend: 'connected',
- lastError: {},
- },
- },
- });
- expect(screen.getByText('Connected')).toBeInTheDocument();
- });
-
- it('shows "Offline" when blocking=internet-offline (line 50)', () => {
- renderWithProviders(<ConnectionIndicator />, {
- preloadedState: {
- connectivity: {
- internet: 'offline',
- core: 'reachable',
- backend: 'connected',
- lastError: {},
- },
- },
- });
- expect(screen.getByText('Disconnected')).toBeInTheDocument();
- });
-
- it('shows "Core offline" when blocking=core-unreachable (line 57)', () => {
- renderWithProviders(<ConnectionIndicator />, {
- preloadedState: {
- connectivity: {
- internet: 'online',
- core: 'unreachable',
- backend: 'connected',
- lastError: {},
- },
- },
- });
- expect(screen.getByText('Disconnected')).toBeInTheDocument();
- });
-
- it('shows "Reconnecting…" when blocking=backend-only and socket is disconnected (line 67)', () => {
- renderWithProviders(<ConnectionIndicator />, {
- preloadedState: {
- connectivity: {
- internet: 'online',
- core: 'reachable',
- backend: 'disconnected',
- lastError: {},
- },
- socket: { byUser: {} },
- },
- });
- expect(screen.getByText('Disconnected')).toBeInTheDocument();
- });
-
- it("shows an amber dot and 'Disconnected' while the core's hosted link is retrying (#6256)", () => {
- const { container } = renderWithProviders(<ConnectionIndicator />, {
- preloadedState: {
- connectivity: {
- internet: 'online',
- core: 'reachable',
- backend: 'connected',
- hosted: 'reconnecting',
- lastError: {},
- },
- socket: { byUser: {} },
- },
- });
- expect(screen.getByText('Disconnected')).toBeInTheDocument();
- expect(container.querySelector('.bg-amber-500')).not.toBeNull();
- expect(container.querySelector('.animate-pulse')).toBeNull();
- });
-
- it("shows an amber dot and 'Disconnected' when the core's loop stopped on an unusable session", () => {
- const { container } = renderWithProviders(<ConnectionIndicator />, {
- preloadedState: {
- connectivity: {
- internet: 'online',
- core: 'reachable',
- backend: 'connected',
- hosted: 'stopped',
- lastError: { hosted: 'session expired — please sign in again' },
- },
- socket: { byUser: {} },
- },
- });
- expect(screen.getByText('Disconnected')).toBeInTheDocument();
- expect(container.querySelector('.bg-amber-500')).not.toBeNull();
- });
-
- it('stays green on a server error event, which leaves the hosted link live', () => {
- const { container } = renderWithProviders(<ConnectionIndicator />, {
- preloadedState: {
- connectivity: {
- internet: 'online',
- core: 'reachable',
- backend: 'connected',
- hosted: 'error',
- lastError: { hosted: 'boom' },
- },
- socket: { byUser: {} },
- },
- });
- expect(screen.getByText('Connected')).toBeInTheDocument();
- expect(container.querySelector('.bg-sage-500')).not.toBeNull();
- });
-
- it("stays green when the core's hosted link is simply not running (signed out / local)", () => {
- const { container } = renderWithProviders(<ConnectionIndicator />, {
- preloadedState: {
- connectivity: {
- internet: 'online',
- core: 'reachable',
- backend: 'connected',
- hosted: 'unknown',
- lastError: {},
- },
- socket: { byUser: {} },
- },
- });
- expect(screen.getByText('Connected')).toBeInTheDocument();
- expect(container.querySelector('.bg-sage-500')).not.toBeNull();
- });
-
- it('shows "Connecting" when blocking=backend-only and legacy socket status is connecting (line 67)', () => {
- renderWithProviders(<ConnectionIndicator />, {
- preloadedState: {
- connectivity: {
- internet: 'online',
- core: 'reachable',
- backend: 'connecting',
- lastError: {},
- },
- // Drive selectSocketStatus to return 'connecting'.
- socket: { byUser: { __pending__: { status: 'connecting', socketId: null } } },
- },
- });
- expect(screen.getByText('Disconnected')).toBeInTheDocument();
- });
-});
diff --git a/app/src/components/channels/ChannelCapabilities.tsx b/app/src/components/channels/ChannelCapabilities.tsx
deleted file mode 100644
index c8ef2d905d..0000000000
--- a/app/src/components/channels/ChannelCapabilities.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-import Badge from '../ui/Badge';
-
-interface ChannelCapabilitiesProps {
- capabilities: string[];
-}
-
-const ChannelCapabilities = ({ capabilities }: ChannelCapabilitiesProps) => {
- if (capabilities.length === 0) return null;
- return (
- <div className="flex flex-wrap gap-1.5 mt-2">
- {capabilities.map(cap => (
- <Badge key={cap} dot={false}>
- {cap.replace(/_/g, ' ')}
- </Badge>
- ))}
- </div>
- );
-};
-
-export default ChannelCapabilities;
diff --git a/app/src/components/channels/ChannelConfigPanel.test.tsx b/app/src/components/channels/ChannelConfigPanel.test.tsx
deleted file mode 100644
index d9071e2be5..0000000000
--- a/app/src/components/channels/ChannelConfigPanel.test.tsx
+++ /dev/null
@@ -1,34 +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 ChannelConfigPanel from './ChannelConfigPanel';
-
-// The credential form owns its own RPC/redux wiring (covered by its own suite);
-// stub it so this test isolates the panel's channel→component routing.
-vi.mock('./CredentialChannelConfig', () => ({
- default: ({ definition }: { definition: { id: string } }) => (
- <div data-testid="credential-config">{definition.id}</div>
- ),
-}));
-
-describe('<ChannelConfigPanel />', () => {
- it('routes the email channel to the credential form (#4280)', () => {
- renderWithProviders(
- <ChannelConfigPanel selectedChannel="email" definitions={FALLBACK_DEFINITIONS} />
- );
- const form = screen.getByTestId('credential-config');
- expect(form).toHaveTextContent('email');
- });
-
- it('routes lark and dingtalk to the same credential form', () => {
- for (const channel of ['lark', 'dingtalk'] as const) {
- const { unmount } = renderWithProviders(
- <ChannelConfigPanel selectedChannel={channel} definitions={FALLBACK_DEFINITIONS} />
- );
- expect(screen.getByTestId('credential-config')).toHaveTextContent(channel);
- unmount();
- }
- });
-});
diff --git a/app/src/components/channels/ChannelConfigPanel.tsx b/app/src/components/channels/ChannelConfigPanel.tsx
deleted file mode 100644
index 4720471be5..0000000000
--- a/app/src/components/channels/ChannelConfigPanel.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-import { useT } from '../../lib/i18n/I18nContext';
-import type { ChannelDefinition, ChannelType } from '../../types/channels';
-import ChannelCapabilities from './ChannelCapabilities';
-import CredentialChannelConfig from './CredentialChannelConfig';
-import DiscordConfig from './DiscordConfig';
-import McpServersPage from './mcp/McpServersPage';
-import TelegramConfig from './TelegramConfig';
-import WebChannelConfig from './WebChannelConfig';
-
-interface ChannelConfigPanelProps {
- selectedChannel: ChannelType;
- definitions: ChannelDefinition[];
-}
-
-const ChannelConfigPanel = ({ selectedChannel, definitions }: ChannelConfigPanelProps) => {
- const { t } = useT();
-
- // MCP is a virtual tab — not backed by a ChannelDefinition from the core.
- // The page carries its own header and tab strip.
- if (selectedChannel === 'mcp') {
- return (
- <div className="h-full p-4">
- <McpServersPage />
- </div>
- );
- }
-
- const definition = definitions.find(d => d.id === selectedChannel);
- if (!definition) return null;
-
- return (
- <div className="space-y-4">
- <section className="rounded-xl border border-line bg-surface p-4 space-y-3">
- <div>
- <h3 className="text-base font-semibold text-content">
- {t(`channels.${definition.id}.displayName`, definition.display_name)}
- </h3>
- <p className="text-xs text-content-muted mt-1">
- {t(`channels.${definition.id}.description`, definition.description)}
- </p>
- </div>
- {selectedChannel === 'telegram' && <TelegramConfig definition={definition} />}
- {selectedChannel === 'discord' && <DiscordConfig definition={definition} />}
- {selectedChannel === 'web' && <WebChannelConfig definition={definition} />}
- {(selectedChannel === 'lark' ||
- selectedChannel === 'dingtalk' ||
- selectedChannel === 'email') && <CredentialChannelConfig definition={definition} />}
- </section>
-
- <ChannelCapabilities capabilities={definition.capabilities} />
- </div>
- );
-};
-
-export default ChannelConfigPanel;
diff --git a/app/src/components/channels/ChannelSelector.test.tsx b/app/src/components/channels/ChannelSelector.test.tsx
deleted file mode 100644
index ba5b452ae1..0000000000
--- a/app/src/components/channels/ChannelSelector.test.tsx
+++ /dev/null
@@ -1,38 +0,0 @@
-import { describe, expect, it, vi } from 'vitest';
-
-import { FALLBACK_DEFINITIONS } from '../../lib/channels/definitions';
-import { renderWithProviders } from '../../test/test-utils';
-import ChannelSelector from './ChannelSelector';
-
-function renderSelector() {
- return renderWithProviders(
- <ChannelSelector
- definitions={FALLBACK_DEFINITIONS}
- selectedChannel="telegram"
- onSelectChannel={vi.fn()}
- />
- );
-}
-
-describe('<ChannelSelector /> channel logos (issue #2854)', () => {
- it('renders the Lark / Feishu brand logo on its card', () => {
- const { container } = renderSelector();
- expect(container.querySelector('img[src="/lark.png"]')).not.toBeNull();
- });
-
- it('renders the DingTalk brand logo on its card', () => {
- const { container } = renderSelector();
- expect(container.querySelector('img[src="/dingtalk.png"]')).not.toBeNull();
- });
-
- it('still renders an icon for every channel definition', () => {
- const { getByText } = renderSelector();
- // Every card label is present, and each card carries a visual icon node
- // (img logo, inline svg, or emoji span) — not just label text.
- for (const def of FALLBACK_DEFINITIONS) {
- const card = getByText(def.display_name).closest('button');
- expect(card).not.toBeNull();
- expect(card?.querySelector('img, svg, span.text-base')).not.toBeNull();
- }
- });
-});
diff --git a/app/src/components/channels/ChannelSelector.tsx b/app/src/components/channels/ChannelSelector.tsx
deleted file mode 100644
index 30cc004809..0000000000
--- a/app/src/components/channels/ChannelSelector.tsx
+++ /dev/null
@@ -1,113 +0,0 @@
-import { useMemo } from 'react';
-
-import { resolvePreferredAuthModeForChannel } from '../../lib/channels/routing';
-import { useT } from '../../lib/i18n/I18nContext';
-import { useAppSelector } from '../../store/hooks';
-import type { ChannelConnectionStatus, ChannelDefinition, ChannelType } from '../../types/channels';
-import Button from '../ui/Button';
-import { renderChannelIcon } from './channelIcon';
-import ChannelStatusBadge from './ChannelStatusBadge';
-
-interface ChannelSelectorProps {
- definitions: ChannelDefinition[];
- selectedChannel: ChannelType;
- onSelectChannel: (channel: ChannelType) => void;
-}
-
-/** Virtual (static) tabs that are not backed by a ChannelDefinition from the core. */
-const VIRTUAL_TABS: { id: ChannelType; display_name: string }[] = [
- { id: 'mcp', display_name: 'MCP Servers' },
-];
-
-const CHANNEL_STATUS_PRIORITY: ChannelConnectionStatus[] = [
- 'connected',
- 'connecting',
- 'error',
- 'disconnected',
-];
-
-const ChannelSelector = ({
- definitions,
- selectedChannel,
- onSelectChannel,
-}: ChannelSelectorProps) => {
- const { t } = useT();
- const channelConnections = useAppSelector(state => state.channelConnections);
-
- const activeRoute = useMemo(() => {
- const channel = channelConnections.defaultMessagingChannel;
- const authMode = resolvePreferredAuthModeForChannel(channelConnections, channel);
- return authMode
- ? t('channels.activeRouteValue').replace('{channel}', channel).replace('{authMode}', authMode)
- : t('channels.noActiveRoute');
- }, [channelConnections, t]);
-
- return (
- <section className="rounded-xl border border-line bg-surface p-4 space-y-4">
- <div className="flex items-center justify-between">
- <h2 className="text-sm font-semibold text-content">{t('channels.title')}</h2>
- <p className="text-xs text-content-faint">
- {t('channels.activeRoute')}:{' '}
- <span className="text-primary-600 dark:text-primary-300">{activeRoute}</span>
- </p>
- </div>
-
- <div className="flex gap-2 flex-wrap">
- {definitions.map(def => {
- const channelId = def.id as ChannelType;
- const isSelected = selectedChannel === channelId;
-
- // Determine best connection status for this channel.
- const channelModes = channelConnections.connections[channelId];
- const modeStatuses = channelModes
- ? Object.values(channelModes)
- .map(connection => connection?.status)
- .filter((status): status is ChannelConnectionStatus => Boolean(status))
- : [];
- const bestStatus =
- CHANNEL_STATUS_PRIORITY.find(status => modeStatuses.includes(status)) ?? 'disconnected';
-
- return (
- <Button
- key={channelId}
- variant="tertiary"
- data-testid={`channel-select-${channelId}`}
- onClick={() => onSelectChannel(channelId)}
- className={`flex-1 justify-between gap-2 rounded-lg border px-4 py-3 text-sm font-normal ${
- isSelected
- ? 'border-primary-500/60 bg-primary-50 dark:bg-primary-500/15 text-primary-600 dark:text-primary-300'
- : 'border-line bg-surface-muted text-content-secondary hover:border-line-strong dark:hover:border-line-strong'
- }`}>
- <span className="flex items-center gap-2">
- {renderChannelIcon(def.icon)}
- <span className="font-medium">{def.display_name}</span>
- </span>
- <ChannelStatusBadge status={bestStatus} />
- </Button>
- );
- })}
-
- {/* Virtual tabs — not backed by a ChannelDefinition from the core */}
- {VIRTUAL_TABS.map(tab => {
- const isSelected = selectedChannel === tab.id;
- return (
- <Button
- key={tab.id}
- variant="tertiary"
- onClick={() => onSelectChannel(tab.id)}
- className={`flex-1 justify-start gap-2 rounded-lg border px-4 py-3 text-sm font-normal ${
- isSelected
- ? 'border-primary-500/60 bg-primary-50 dark:bg-primary-500/15 text-primary-600 dark:text-primary-300'
- : 'border-line bg-surface-muted text-content-secondary hover:border-line-strong dark:hover:border-line-strong'
- }`}>
- {renderChannelIcon(tab.id)}
- <span className="font-medium">{tab.display_name}</span>
- </Button>
- );
- })}
- </div>
- </section>
- );
-};
-
-export default ChannelSelector;
diff --git a/app/src/components/channels/WebChannelConfig.tsx b/app/src/components/channels/WebChannelConfig.tsx
deleted file mode 100644
index 7d59224070..0000000000
--- a/app/src/components/channels/WebChannelConfig.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-import { useT } from '../../lib/i18n/I18nContext';
-import type { ChannelDefinition } from '../../types/channels';
-import ChannelStatusBadge from './ChannelStatusBadge';
-
-interface WebChannelConfigProps {
- definition: ChannelDefinition;
-}
-
-const WebChannelConfig = ({ definition: _definition }: WebChannelConfigProps) => {
- const { t } = useT();
- return (
- <div className="space-y-3">
- <div className="flex items-start justify-between">
- <div>
- <ChannelStatusBadge status="connected" />
- </div>
- </div>
- <p className="text-sm text-content-muted">{t('channels.web.alwaysAvailable')}</p>
- </div>
- );
-};
-
-export default WebChannelConfig;
diff --git a/app/src/components/channels/__tests__/ChannelConfigPanel.test.tsx b/app/src/components/channels/__tests__/ChannelConfigPanel.test.tsx
deleted file mode 100644
index 5c7baa15d4..0000000000
--- a/app/src/components/channels/__tests__/ChannelConfigPanel.test.tsx
+++ /dev/null
@@ -1,81 +0,0 @@
-/**
- * Tests for ChannelConfigPanel — covers the MCP virtual tab and the
- * channel-definition-backed tabs (telegram, discord, web) and the null
- * fallback when no matching definition is found.
- */
-import { render, 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 ChannelConfigPanel from '../ChannelConfigPanel';
-
-// McpServersTab is a heavy async component — mock it so ChannelConfigPanel
-// tests stay focused on the routing logic (line 16 branch).
-vi.mock('../mcp/McpServersPage', () => ({
- default: () => <div data-testid="mcp-servers-tab">MCP Servers Tab</div>,
-}));
-
-// Mock channel-specific config panels to keep tests lightweight.
-vi.mock('../TelegramConfig', () => ({
- default: () => <div data-testid="telegram-config">Telegram Config</div>,
-}));
-
-vi.mock('../DiscordConfig', () => ({
- default: () => <div data-testid="discord-config">Discord Config</div>,
-}));
-
-vi.mock('../WebChannelConfig', () => ({
- default: () => <div data-testid="web-config">Web Config</div>,
-}));
-
-vi.mock('../ChannelCapabilities', () => ({
- default: () => <div data-testid="channel-capabilities">Capabilities</div>,
-}));
-
-describe('ChannelConfigPanel', () => {
- it('renders McpServersTab when selectedChannel is "mcp"', () => {
- render(<ChannelConfigPanel selectedChannel="mcp" definitions={FALLBACK_DEFINITIONS} />);
- // The page carries its own header, so the panel adds none of its own.
- expect(screen.getByTestId('mcp-servers-tab')).toBeInTheDocument();
- expect(screen.queryByRole('heading')).not.toBeInTheDocument();
- });
-
- it('does not render definition-based content when channel is "mcp"', () => {
- render(<ChannelConfigPanel selectedChannel="mcp" definitions={FALLBACK_DEFINITIONS} />);
- // No Telegram/Discord/Web-specific config panels
- expect(screen.queryByTestId('telegram-config')).not.toBeInTheDocument();
- expect(screen.queryByTestId('discord-config')).not.toBeInTheDocument();
- });
-
- it('renders TelegramConfig when selectedChannel is "telegram"', () => {
- renderWithProviders(
- <ChannelConfigPanel selectedChannel="telegram" definitions={FALLBACK_DEFINITIONS} />
- );
- expect(screen.getByTestId('telegram-config')).toBeInTheDocument();
- });
-
- it('renders DiscordConfig when selectedChannel is "discord"', () => {
- renderWithProviders(
- <ChannelConfigPanel selectedChannel="discord" definitions={FALLBACK_DEFINITIONS} />
- );
- expect(screen.getByTestId('discord-config')).toBeInTheDocument();
- });
-
- it('renders channel display_name and description for a matched definition', () => {
- renderWithProviders(
- <ChannelConfigPanel selectedChannel="telegram" definitions={FALLBACK_DEFINITIONS} />
- );
- expect(screen.getByText('Telegram')).toBeInTheDocument();
- expect(screen.getByText(/send and receive messages via telegram/i)).toBeInTheDocument();
- });
-
- it('renders nothing when selectedChannel has no matching definition', () => {
- const { container } = renderWithProviders(
- // 'mcp' is handled above; use an unknown channel to hit the null-return
- // branch (definition not found).
- <ChannelConfigPanel selectedChannel={'unknown' as never} definitions={[]} />
- );
- expect(container.firstChild).toBeNull();
- });
-});
diff --git a/app/src/components/channels/__tests__/ChannelSelector.test.tsx b/app/src/components/channels/__tests__/ChannelSelector.test.tsx
deleted file mode 100644
index 8281b91453..0000000000
--- a/app/src/components/channels/__tests__/ChannelSelector.test.tsx
+++ /dev/null
@@ -1,124 +0,0 @@
-import { fireEvent, screen, within } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import { FALLBACK_DEFINITIONS } from '../../../lib/channels/definitions';
-import { setChannelConnectionStatus } from '../../../store/channelConnectionsSlice';
-import { createTestStore, renderWithProviders } from '../../../test/test-utils';
-import ChannelSelector from '../ChannelSelector';
-
-describe('ChannelSelector', () => {
- const onSelect = vi.fn();
-
- it('renders all channel tabs', () => {
- renderWithProviders(
- <ChannelSelector
- definitions={FALLBACK_DEFINITIONS}
- selectedChannel="telegram"
- onSelectChannel={onSelect}
- />
- );
-
- expect(screen.getByText('Telegram')).toBeInTheDocument();
- expect(screen.getByText('Discord')).toBeInTheDocument();
- expect(screen.getByText('Web')).toBeInTheDocument();
- });
-
- it('calls onSelectChannel when a tab is clicked', () => {
- renderWithProviders(
- <ChannelSelector
- definitions={FALLBACK_DEFINITIONS}
- selectedChannel="telegram"
- onSelectChannel={onSelect}
- />
- );
-
- fireEvent.click(screen.getByText('Discord'));
- expect(onSelect).toHaveBeenCalledWith('discord');
- });
-
- it('shows active route summary', () => {
- renderWithProviders(
- <ChannelSelector
- definitions={FALLBACK_DEFINITIONS}
- selectedChannel="telegram"
- onSelectChannel={onSelect}
- />
- );
-
- expect(screen.getByText(/No active route/)).toBeInTheDocument();
- });
-
- it('surfaces channel errors when no mode is connected or connecting', () => {
- const store = createTestStore();
- store.dispatch(
- setChannelConnectionStatus({
- channel: 'telegram',
- authMode: 'bot_token',
- status: 'error',
- lastError: 'Invalid token',
- })
- );
-
- renderWithProviders(
- <ChannelSelector
- definitions={FALLBACK_DEFINITIONS}
- selectedChannel="telegram"
- onSelectChannel={onSelect}
- />,
- { store }
- );
-
- const telegramTab = screen.getByRole('button', { name: /telegram/i });
- expect(within(telegramTab).getByText('Error')).toBeInTheDocument();
- expect(within(telegramTab).queryByText('Disconnected')).not.toBeInTheDocument();
- });
-
- it('renders the MCP virtual tab', () => {
- renderWithProviders(
- <ChannelSelector
- definitions={FALLBACK_DEFINITIONS}
- selectedChannel="telegram"
- onSelectChannel={onSelect}
- />
- );
- expect(screen.getByRole('button', { name: /mcp servers/i })).toBeInTheDocument();
- });
-
- it('calls onSelectChannel with "mcp" when MCP tab is clicked', () => {
- const handleSelect = vi.fn();
- renderWithProviders(
- <ChannelSelector
- definitions={FALLBACK_DEFINITIONS}
- selectedChannel="telegram"
- onSelectChannel={handleSelect}
- />
- );
- fireEvent.click(screen.getByRole('button', { name: /mcp servers/i }));
- expect(handleSelect).toHaveBeenCalledWith('mcp');
- });
-
- it('applies selected styling to MCP tab when it is the active channel', () => {
- renderWithProviders(
- <ChannelSelector
- definitions={FALLBACK_DEFINITIONS}
- selectedChannel="mcp"
- onSelectChannel={onSelect}
- />
- );
- const mcpBtn = screen.getByRole('button', { name: /mcp servers/i });
- expect(mcpBtn.className).toContain('bg-primary-50');
- });
-
- it('applies unselected styling to MCP tab when another channel is active', () => {
- renderWithProviders(
- <ChannelSelector
- definitions={FALLBACK_DEFINITIONS}
- selectedChannel="telegram"
- onSelectChannel={onSelect}
- />
- );
- const mcpBtn = screen.getByRole('button', { name: /mcp servers/i });
- expect(mcpBtn.className).not.toContain('bg-primary-50');
- expect(mcpBtn.className).toContain('bg-surface-muted');
- });
-});
diff --git a/app/src/components/home/HomeBanners.tsx b/app/src/components/home/HomeBanners.tsx
deleted file mode 100644
index 6a64e62f3d..0000000000
--- a/app/src/components/home/HomeBanners.tsx
+++ /dev/null
@@ -1,112 +0,0 @@
-import { useT } from '../../lib/i18n/I18nContext';
-import { DISCORD_INVITE_URL, PRICING_URL } from '../../utils/links';
-import { openUrl } from '../../utils/openUrl';
-
-function formatUsd(amount: number): string {
- return `$${amount.toFixed(amount % 1 === 0 ? 0 : 2)}`;
-}
-
-export function PromotionalCreditsBanner({ promoCredits }: { promoCredits: number }) {
- const { t } = useT();
- return (
- <div className="mb-3 rounded-2xl border border-amber-200 bg-linear-to-r from-amber-50 via-orange-50 to-rose-50 px-4 py-2.5 text-left shadow-soft dark:border-amber-500/30 dark:from-amber-900/30 dark:via-amber-900/20 dark:to-amber-900/10">
- <div className="flex items-start gap-2.5">
- <div className="mt-px flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-amber-100 text-base dark:bg-amber-500/20">
- 🎉
- </div>
- <p className="min-w-0 flex-1 text-sm leading-relaxed text-amber-600 dark:text-amber-300/80">
- {(() => {
- // Single {amount} template; split so the amount renders bold inline.
- const [before, after] = t('home.banners.promoCreditsBody').split('{amount}');
- return (
- <>
- {before}
- <span className="font-semibold text-amber-700 dark:text-amber-300">
- {formatUsd(promoCredits)}
- </span>
- {after}
- </>
- );
- })()}{' '}
- <button
- type="button"
- onClick={() => {
- void openUrl(PRICING_URL);
- }}
- className="cursor-pointer border-b border-dashed border-amber-700 font-bold text-amber-700 hover:text-amber-800 dark:border-amber-300 dark:text-amber-300 dark:hover:text-amber-200">
- {t('home.banners.getSubscription')}
- </button>{' '}
- {t('home.banners.promoCreditsUsage')}
- </p>
- </div>
- </div>
- );
-}
-
-export function EarlyBirdyBanner({ onDismiss }: { onDismiss?: () => void }) {
- const { t } = useT();
- return (
- <div className="relative mb-3 mt-3 rounded-2xl border border-orange-200 bg-linear-to-r from-orange-50 via-amber-50 to-orange-50 px-4 py-4 text-left shadow-soft dark:border-orange-500/30 dark:from-orange-900/30 dark:via-amber-900/20 dark:to-orange-900/10">
- {onDismiss && (
- <button
- type="button"
- onClick={onDismiss}
- aria-label={t('home.banners.earlyBirdDismiss')}
- className="absolute right-3 top-3 rounded-md p-1 text-orange-500 hover:bg-orange-100 hover:text-orange-700 dark:text-orange-300 dark:hover:bg-orange-500/10 dark:hover:text-orange-200">
- ✕
- </button>
- )}
- <div className="flex items-start gap-3">
- <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-orange-100 dark:bg-orange-500/20 text-lg">
- 🐦
- </div>
- <div className="min-w-0 flex-1">
- <p className="text-sm font-semibold text-orange-700 dark:text-orange-300">
- {t('home.banners.earlyBirdTitle')}
- </p>
- <p className="mt-1 text-sm leading-relaxed text-orange-600 dark:text-orange-300/80">
- {t('home.banners.earlyBirdUseCode')}{' '}
- <span className="rounded-md border border-orange-300 bg-surface px-1.5 py-0.5 font-mono text-[12px] font-bold text-orange-700 dark:border-orange-500/40 dark:text-orange-300">
- EARLYBIRDY
- </span>{' '}
- {t('home.banners.earlyBirdOn')}{' '}
- <button
- type="button"
- onClick={() => {
- void openUrl(PRICING_URL);
- }}
- className="cursor-pointer border-b border-amber-700 border-dashed font-bold text-amber-700 hover:text-amber-800 dark:border-amber-300 dark:text-amber-300 dark:hover:text-amber-200">
- {t('home.banners.earlyBirdFirstSub')}
- </button>{' '}
- </p>
- </div>
- </div>
- </div>
- );
-}
-
-export function DiscordBanner() {
- const { t } = useT();
- return (
- <button
- type="button"
- onClick={() => {
- void openUrl(DISCORD_INVITE_URL);
- }}
- className="mb-3 text-left mt-3 block w-full rounded-2xl border border-[#CDD2FF] bg-linear-to-r from-[#F6F7FF] via-[#F1F3FF] to-[#ECEFFF] px-4 py-2.5 text-[#414AAE] shadow-soft transition-transform transition-colors hover:-translate-y-0.5 hover:border-[#BCC3FF] hover:from-[#EEF0FF] hover:to-[#E5E9FF] dark:border-[#5865F2]/30 dark:from-[#5865F2]/10 dark:via-[#5865F2]/15 dark:to-[#5865F2]/10 dark:text-[#A5B0FF] dark:hover:border-[#5865F2]/50 dark:hover:from-[#5865F2]/15 dark:hover:to-[#5865F2]/20">
- <div className="flex items-center gap-2.5">
- <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-[#5865F2]/12 text-[#5865F2]">
- <svg className="h-4 w-4" fill="currentColor" viewBox="0 0 24 24" aria-hidden="true">
- <path d="M20.317 4.37A19.79 19.79 0 0 0 15.885 3c-.191.328-.403.775-.552 1.124a18.27 18.27 0 0 0-5.29 0A11.56 11.56 0 0 0 9.49 3a19.74 19.74 0 0 0-4.433 1.37C2.253 8.51 1.492 12.55 1.872 16.533a19.9 19.9 0 0 0 5.239 2.673c.423-.58.8-1.196 1.123-1.845a12.84 12.84 0 0 1-1.767-.85c.148-.106.292-.217.43-.332c3.408 1.6 7.104 1.6 10.472 0c.14.115.283.226.43.332c-.565.338-1.157.623-1.771.851c.322.648.698 1.264 1.123 1.844a19.84 19.84 0 0 0 5.241-2.673c.446-4.617-.761-8.621-3.787-12.164ZM9.46 14.088c-1.02 0-1.855-.936-1.855-2.084c0-1.148.82-2.084 1.855-2.084c1.044 0 1.87.944 1.855 2.084c0 1.148-.82 2.084-1.855 2.084Zm5.08 0c-1.02 0-1.855-.936-1.855-2.084c0-1.148.82-2.084 1.855-2.084c1.044 0 1.87.944 1.855 2.084c0 1.148-.812 2.084-1.855 2.084Z" />
- </svg>
- </div>
- <div className="min-w-0 flex-1 text-sm">
- <span className="font-semibold">{t('home.banners.discordTitle')}</span>{' '}
- <span className="text-[#5E66BC] dark:text-[#8B95DD]">
- {t('home.banners.discordSubtitle')}
- </span>
- </div>
- </div>
- </button>
- );
-}
diff --git a/app/src/components/home/__tests__/HomeBanners.test.tsx b/app/src/components/home/__tests__/HomeBanners.test.tsx
deleted file mode 100644
index 27753c24b9..0000000000
--- a/app/src/components/home/__tests__/HomeBanners.test.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { DISCORD_INVITE_URL, PRICING_URL } from '../../../utils/links';
-import { openUrl } from '../../../utils/openUrl';
-import { DiscordBanner, EarlyBirdyBanner, PromotionalCreditsBanner } from '../HomeBanners';
-
-vi.mock('../../../utils/openUrl', () => ({ openUrl: vi.fn() }));
-
-describe('HomeBanners', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it('opens the billing dashboard through openUrl from the promotional credits banner', () => {
- render(<PromotionalCreditsBanner promoCredits={12} />);
-
- fireEvent.click(screen.getByRole('button', { name: /get a subscription/i }));
-
- expect(openUrl).toHaveBeenCalledWith('https://tinyhumans.ai/pricing');
- });
-
- it('opens the Discord invite through openUrl from the Discord banner', () => {
- render(<DiscordBanner />);
-
- fireEvent.click(screen.getByRole('button', { name: /join our discord/i }));
-
- expect(openUrl).toHaveBeenCalledWith(DISCORD_INVITE_URL);
- });
-
- describe('EarlyBirdyBanner', () => {
- it('renders the discount code and headline', () => {
- render(<EarlyBirdyBanner />);
-
- expect(screen.getByText('The first 1,000 users get 60% off.')).toBeInTheDocument();
- expect(screen.getByText('EARLYBIRDY')).toBeInTheDocument();
- });
-
- it('opens the billing dashboard when the subscription link is clicked', () => {
- render(<EarlyBirdyBanner />);
-
- fireEvent.click(screen.getByRole('button', { name: /first subscription/i }));
-
- expect(openUrl).toHaveBeenCalledWith(PRICING_URL);
- });
-
- it('does not render a dismiss button when onDismiss is not provided', () => {
- render(<EarlyBirdyBanner />);
-
- expect(
- screen.queryByRole('button', { name: /dismiss early bird banner/i })
- ).not.toBeInTheDocument();
- });
-
- it('renders an accessible dismiss button when onDismiss is provided', () => {
- const onDismiss = vi.fn();
- render(<EarlyBirdyBanner onDismiss={onDismiss} />);
-
- expect(
- screen.getByRole('button', { name: /dismiss early bird banner/i })
- ).toBeInTheDocument();
- });
-
- it('calls onDismiss when the dismiss button is clicked', () => {
- const onDismiss = vi.fn();
- render(<EarlyBirdyBanner onDismiss={onDismiss} />);
-
- fireEvent.click(screen.getByRole('button', { name: /dismiss early bird banner/i }));
-
- expect(onDismiss).toHaveBeenCalledOnce();
- });
-
- it('does not call openUrl when the dismiss button is clicked', () => {
- const onDismiss = vi.fn();
- render(<EarlyBirdyBanner onDismiss={onDismiss} />);
-
- fireEvent.click(screen.getByRole('button', { name: /dismiss early bird banner/i }));
-
- expect(openUrl).not.toHaveBeenCalled();
- });
- });
-});
diff --git a/app/src/components/intelligence/ActionableCard.test.tsx b/app/src/components/intelligence/ActionableCard.test.tsx
deleted file mode 100644
index cd2df0f088..0000000000
--- a/app/src/components/intelligence/ActionableCard.test.tsx
+++ /dev/null
@@ -1,127 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { ActionableItem } from '../../types/intelligence';
-import { ActionableCard } from './ActionableCard';
-
-function makeItem(overrides: Partial<ActionableItem> = {}): ActionableItem {
- const now = new Date();
- return {
- id: 'item-1',
- title: 'Reply to Alice',
- description: 'She asked about Q4 numbers',
- source: 'email',
- priority: 'normal',
- status: 'active',
- createdAt: new Date(now.getTime() - 10 * 60 * 1000), // 10 minutes ago
- updatedAt: now,
- actionable: true,
- ...overrides,
- };
-}
-
-describe('<ActionableCard />', () => {
- it('renders title, description and the relative time meta', () => {
- render(
- <ActionableCard
- item={makeItem()}
- onComplete={() => {}}
- onDismiss={() => {}}
- onSnooze={() => {}}
- />
- );
- expect(screen.getByText('Reply to Alice')).toBeInTheDocument();
- expect(screen.getByText('She asked about Q4 numbers')).toBeInTheDocument();
- expect(screen.getByText(/10 mins ago/i)).toBeInTheDocument();
- });
-
- it('invokes onComplete with the item when the check button is clicked', () => {
- const item = makeItem();
- const onComplete = vi.fn();
- render(
- <ActionableCard
- item={item}
- onComplete={onComplete}
- onDismiss={() => {}}
- onSnooze={() => {}}
- />
- );
- const completeBtn = screen.getByTitle(/actionable\.complete|complete/i);
- fireEvent.click(completeBtn);
- expect(onComplete).toHaveBeenCalledWith(item);
- });
-
- it('invokes onDismiss with the item when the x button is clicked', () => {
- const item = makeItem();
- const onDismiss = vi.fn();
- render(
- <ActionableCard item={item} onComplete={() => {}} onDismiss={onDismiss} onSnooze={() => {}} />
- );
- const dismissBtn = screen.getByTitle(/actionable\.dismiss|dismiss/i);
- fireEvent.click(dismissBtn);
- expect(onDismiss).toHaveBeenCalledWith(item);
- });
-
- it('opens the snooze dropdown on click and surfaces the duration options', () => {
- render(
- <ActionableCard
- item={makeItem()}
- onComplete={() => {}}
- onDismiss={() => {}}
- onSnooze={() => {}}
- />
- );
- fireEvent.click(screen.getByTitle(/actionable\.snooze|snooze/i));
- expect(screen.getByText('1 hour')).toBeInTheDocument();
- expect(screen.getByText('6 hours')).toBeInTheDocument();
- expect(screen.getByText('24 hours')).toBeInTheDocument();
- });
-
- it('invokes onSnooze with the duration after the animation timer fires', () => {
- vi.useFakeTimers();
- try {
- const item = makeItem();
- const onSnooze = vi.fn();
- render(
- <ActionableCard
- item={item}
- onComplete={() => {}}
- onDismiss={() => {}}
- onSnooze={onSnooze}
- />
- );
- fireEvent.click(screen.getByTitle(/actionable\.snooze|snooze/i));
- fireEvent.click(screen.getByText('1 hour'));
- // The 200ms animation-out delay must elapse before onSnooze fires.
- vi.advanceTimersByTime(250);
- expect(onSnooze).toHaveBeenCalledWith(item, 60 * 60 * 1000);
- } finally {
- vi.useRealTimers();
- }
- });
-
- it('renders the "new" badge for items younger than 5 minutes', () => {
- render(
- <ActionableCard
- item={makeItem({ createdAt: new Date(Date.now() - 60_000) })}
- onComplete={() => {}}
- onDismiss={() => {}}
- onSnooze={() => {}}
- />
- );
- // i18n key falls back to "actionable.new" when no provider is mounted.
- expect(screen.getByText(/actionable\.new|new/i)).toBeInTheDocument();
- });
-
- it('honors a custom sourceLabel when provided', () => {
- render(
- <ActionableCard
- item={makeItem({ sourceLabel: 'Gmail' })}
- onComplete={() => {}}
- onDismiss={() => {}}
- onSnooze={() => {}}
- />
- );
- expect(screen.getByText('Gmail')).toBeInTheDocument();
- });
-});
diff --git a/app/src/components/intelligence/ActionableCard.tsx b/app/src/components/intelligence/ActionableCard.tsx
deleted file mode 100644
index ee28c62d58..0000000000
--- a/app/src/components/intelligence/ActionableCard.tsx
+++ /dev/null
@@ -1,396 +0,0 @@
-import { useEffect, useRef, useState } from 'react';
-import { createPortal } from 'react-dom';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import type { ActionableItem, SnoozeOption } from '../../types/intelligence';
-import Badge from '../ui/Badge';
-import Button from '../ui/Button';
-
-interface ActionableCardProps {
- item: ActionableItem;
- onComplete: (item: ActionableItem) => void;
- onDismiss: (item: ActionableItem) => void;
- onSnooze: (item: ActionableItem, duration: number) => void;
- className?: string;
-}
-
-const SNOOZE_OPTIONS: SnoozeOption[] = [
- { label: '1 hour', duration: 60 * 60 * 1000 },
- { label: '6 hours', duration: 6 * 60 * 60 * 1000 },
- { label: '24 hours', duration: 24 * 60 * 60 * 1000 },
-];
-
-// Portal component for snooze dropdown to escape stacking contexts
-interface SnoozeDropdownPortalProps {
- isOpen: boolean;
- buttonRef: React.RefObject<HTMLButtonElement | null>;
- onClose: () => void;
- onSnooze: (duration: number) => void;
-}
-
-function SnoozeDropdownPortal({ isOpen, buttonRef, onClose, onSnooze }: SnoozeDropdownPortalProps) {
- const [position, setPosition] = useState({ top: 0, left: 0 });
- const dropdownRef = useRef<HTMLDivElement>(null);
-
- // Calculate position based on button position
- useEffect(() => {
- if (isOpen && buttonRef.current) {
- const rect = buttonRef.current.getBoundingClientRect();
- const dropdownWidth = 120;
-
- // Position dropdown below and aligned to right edge of button
- const left = Math.max(8, rect.right - dropdownWidth);
- const top = rect.bottom + 4;
-
- setPosition({ top, left });
- }
- }, [isOpen, buttonRef]);
-
- // Handle click outside to close dropdown
- useEffect(() => {
- if (!isOpen) return;
-
- const handleClickOutside = (event: MouseEvent) => {
- const target = event.target as Element;
-
- // Don't close if clicking the button or dropdown itself
- if (
- buttonRef.current?.contains(target) ||
- dropdownRef.current?.contains(target) ||
- target.closest('[data-snooze-dropdown]')
- ) {
- return;
- }
-
- onClose();
- };
-
- // Use capture phase to ensure we handle this before other click handlers
- document.addEventListener('click', handleClickOutside, true);
- return () => document.removeEventListener('click', handleClickOutside, true);
- }, [isOpen, onClose, buttonRef]);
-
- // Handle escape key
- useEffect(() => {
- if (!isOpen) return;
-
- const handleEscape = (event: KeyboardEvent) => {
- if (event.key === 'Escape') {
- onClose();
- }
- };
-
- document.addEventListener('keydown', handleEscape);
- return () => document.removeEventListener('keydown', handleEscape);
- }, [isOpen, onClose]);
-
- if (!isOpen) return null;
-
- return createPortal(
- <div
- ref={dropdownRef}
- data-snooze-dropdown
- className="fixed py-1 bg-surface border border-line rounded-lg shadow-xl min-w-[120px] z-9999 animate-fade-in"
- style={{ top: position.top, left: position.left }}>
- {SNOOZE_OPTIONS.map(option => (
- <Button
- key={option.label}
- variant="tertiary"
- onClick={() => onSnooze(option.duration)}
- className="h-auto w-full justify-start rounded-none px-3 py-1.5 text-xs font-normal dark:bg-surface-muted">
- {option.label}
- </Button>
- ))}
- </div>,
- document.body
- );
-}
-
-// Source icons for different actionable item types
-const SOURCE_ICONS = {
- email: (
- <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M3 8l7.89 4.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"
- />
- </svg>
- ),
- calendar: (
- <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v14a2 2 0 002 2z"
- />
- </svg>
- ),
- telegram: (
- <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
- <path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z" />
- </svg>
- ),
- ai_insight: (
- <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"
- />
- </svg>
- ),
- system: (
- <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"
- />
- </svg>
- ),
- trading: (
- <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"
- />
- </svg>
- ),
- security: (
- <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"
- />
- </svg>
- ),
-};
-
-function formatTimeAgo(date: Date): string {
- const now = new Date();
- const diff = now.getTime() - date.getTime();
-
- const minutes = Math.floor(diff / (1000 * 60));
- const hours = Math.floor(diff / (1000 * 60 * 60));
- const days = Math.floor(diff / (1000 * 60 * 60 * 24));
- const weeks = Math.floor(diff / (1000 * 60 * 60 * 24 * 7));
-
- if (minutes < 1) return 'Just now';
- if (minutes < 60) return `${minutes} min${minutes === 1 ? '' : 's'} ago`;
- if (hours < 24) {
- if (hours === 1) return '1 hour ago';
- if (hours <= 6) return `${hours} hours ago`;
- if (hours <= 12) return 'This morning';
- return 'This afternoon';
- }
- if (days === 1) return 'Yesterday';
- if (days < 7) return `${days} days ago`;
- if (weeks === 1) return '1 week ago';
- return `${weeks} weeks ago`;
-}
-
-function isNewItem(date: Date): boolean {
- const now = new Date();
- const diff = now.getTime() - date.getTime();
- return diff < 5 * 60 * 1000; // Less than 5 minutes old
-}
-
-export function ActionableCard({
- item,
- onComplete,
- onDismiss,
- onSnooze,
- className = '',
-}: ActionableCardProps) {
- const { t } = useT();
- const [showSnoozeMenu, setShowSnoozeMenu] = useState(false);
- const [isAnimatingOut, setIsAnimatingOut] = useState(false);
- const snoozeButtonRef = useRef<HTMLButtonElement>(null);
-
- const handleComplete = () => {
- // Always let the parent handle completion logic
- // The parent (Intelligence.tsx) ALWAYS opens ChatModal for ALL tick actions
- onComplete(item);
- };
-
- const handleDismiss = () => {
- // Always let the parent handle dismiss logic and show confirmation modal
- // The parent (Intelligence.tsx) always shows confirmation for ALL dismiss actions
- onDismiss(item);
- };
-
- const handleSnooze = (duration: number) => {
- setIsAnimatingOut(true);
- setTimeout(() => {
- onSnooze(item, duration);
- setShowSnoozeMenu(false);
- }, 200);
- };
-
- // Priority styling
- const priorityClasses = {
- critical: 'border-coral-500/30 bg-coral-500/5',
- important: 'border-amber-500/30 bg-amber-500/5',
- normal: 'border-line bg-surface-muted',
- };
-
- const priorityDotClasses = {
- critical: 'bg-coral-400',
- important: 'bg-amber-400',
- normal: 'bg-sage-400',
- };
-
- const sourceIcon = item.icon || SOURCE_ICONS[item.source];
- const isNew = isNewItem(item.createdAt);
- const timeAgo = formatTimeAgo(item.createdAt);
-
- return (
- <div
- className={`
- relative group transition-all duration-200 ease-in-out
- ${isAnimatingOut ? 'opacity-0 translate-x-4 scale-95' : 'animate-fade-up'}
- ${className}
- `}>
- <div
- className={`
- relative p-4 rounded-xl border backdrop-blur-sm transition-all duration-200
- hover:bg-surface-hover hover:border-line dark:border-line
- ${priorityClasses[item.priority]}
- `}>
- {/* Main content row */}
- <div className="flex items-start gap-3">
- {/* Icon */}
- <div className="w-8 h-8 flex items-center justify-center text-content-secondary shrink-0 mt-0.5">
- {sourceIcon}
- </div>
-
- {/* Content */}
- <div className="flex-1 min-w-0">
- <div className="flex items-start justify-between gap-3">
- <div className="flex-1 min-w-0">
- <h3 className="text-sm font-medium text-content leading-snug">{item.title}</h3>
- {item.description && (
- <p className="text-xs text-content-faint mt-1 leading-relaxed">
- {item.description}
- </p>
- )}
- </div>
-
- {/* Action buttons */}
- <div className="flex items-center gap-1 shrink-0">
- {/* Complete button */}
- <Button
- variant="tertiary"
- size="sm"
- iconOnly
- onClick={handleComplete}
- className="h-6 w-6 text-content-faint hover:text-sage-400 hover:bg-sage-400/10"
- aria-label={t('actionable.complete')}
- title={t('actionable.complete')}>
- <svg
- className="w-3.5 h-3.5"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M5 13l4 4L19 7"
- />
- </svg>
- </Button>
-
- {/* Dismiss button */}
- <Button
- variant="tertiary"
- size="sm"
- iconOnly
- onClick={handleDismiss}
- className="h-6 w-6 text-content-faint hover:text-coral-400 hover:bg-coral-400/10"
- aria-label={t('actionable.dismiss')}
- title={t('actionable.dismiss')}>
- <svg
- className="w-3.5 h-3.5"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M6 18L18 6M6 6l12 12"
- />
- </svg>
- </Button>
-
- {/* Snooze button */}
- <div className="relative">
- <Button
- ref={snoozeButtonRef}
- variant="tertiary"
- size="sm"
- iconOnly
- onClick={() => setShowSnoozeMenu(!showSnoozeMenu)}
- className="h-6 w-6 text-content-faint hover:text-amber-400 hover:bg-amber-400/10"
- aria-label={t('actionable.snooze')}
- title={t('actionable.snooze')}>
- <svg
- className="w-3.5 h-3.5"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
- />
- </svg>
- </Button>
- </div>
- </div>
- </div>
-
- {/* Meta info */}
- <div className="flex items-center gap-2 mt-2">
- <div className="flex items-center gap-1.5">
- <div className={`w-1.5 h-1.5 rounded-full ${priorityDotClasses[item.priority]}`} />
- <span className="text-xs text-content-muted">
- {item.sourceLabel || item.source}
- </span>
- </div>
- <span className="text-xs text-content-secondary">•</span>
- <span className="text-xs text-content-muted">{timeAgo}</span>
- {isNew && (
- <>
- <span className="text-xs text-content-secondary">•</span>
- <Badge variant="success" dot={false}>
- {t('actionable.new')}
- </Badge>
- </>
- )}
- </div>
- </div>
- </div>
- </div>
-
- {/* Snooze dropdown portal - renders outside of any stacking context */}
- <SnoozeDropdownPortal
- isOpen={showSnoozeMenu}
- buttonRef={snoozeButtonRef}
- onClose={() => setShowSnoozeMenu(false)}
- onSnooze={handleSnooze}
- />
- </div>
- );
-}
diff --git a/app/src/components/intelligence/MemoryChunkLetterhead.tsx b/app/src/components/intelligence/MemoryChunkLetterhead.tsx
deleted file mode 100644
index 4424bf43e9..0000000000
--- a/app/src/components/intelligence/MemoryChunkLetterhead.tsx
+++ /dev/null
@@ -1,78 +0,0 @@
-/**
- * Letterhead: the from / to / date frontmatter of a chunk, rendered
- * as correspondence (dl-style with monospace labels in a fixed column).
- */
-import { useT } from '../../lib/i18n/I18nContext';
-import type { Chunk } from '../../utils/tauriCommands';
-
-interface LetterheadParts {
- fromName: string;
- fromAddress?: string;
- toAddress: string;
-}
-
-function parseSourceParts(chunk: Chunk): LetterheadParts {
- const [senderRaw = '', recipientRaw] = chunk.source_id.split('|');
- const recipient = recipientRaw?.trim() || chunk.owner;
- const normalizedSender = senderRaw.trim();
- const afterColon = normalizedSender.includes(':')
- ? normalizedSender.split(':').slice(1).join(':').trim()
- : normalizedSender;
-
- // Heuristic for known prefixes: prefer the human-readable display when we have one,
- // else fall back to the raw email/handle.
- const isEmailish = /@/.test(afterColon);
- // Try to recover a personalized name from the chunk's tags (first person/* tag)
- const personTag = chunk.tags.find(t => t.startsWith('person/'));
- const personName = personTag
- ? personTag.slice('person/'.length).replace(/[-_]+/g, ' ').trim()
- : null;
-
- if (isEmailish && personName) {
- return { fromName: personName, fromAddress: afterColon, toAddress: recipient };
- }
- if (isEmailish) {
- return { fromName: afterColon, toAddress: recipient };
- }
- if (personName) {
- return { fromName: personName, fromAddress: afterColon, toAddress: recipient };
- }
- return { fromName: afterColon || chunk.source_kind, toAddress: recipient };
-}
-
-function formatLetterDate(ms: number): string {
- const d = new Date(ms);
- const yyyy = d.getFullYear();
- const mm = String(d.getMonth() + 1).padStart(2, '0');
- const dd = String(d.getDate()).padStart(2, '0');
- const hh = String(d.getHours()).padStart(2, '0');
- const mi = String(d.getMinutes()).padStart(2, '0');
- return `${yyyy}·${mm}·${dd} · ${hh}:${mi}`;
-}
-
-export function MemoryChunkLetterhead({ chunk }: { chunk: Chunk }) {
- const { t } = useT();
- const parts = parseSourceParts(chunk);
- return (
- <header className="mw-letterhead" data-testid="memory-chunk-letterhead">
- <dl style={{ margin: 0 }}>
- <div className="mw-letterhead-row">
- <dt className="mw-letterhead-label">{t('intelligence.memoryChunk.letterhead.from')}</dt>
- <dd className="mw-letterhead-value" style={{ margin: 0 }}>
- {parts.fromName}
- {parts.fromAddress && parts.fromAddress !== parts.fromName && (
- <span className="mw-letterhead-value-secondary">{parts.fromAddress}</span>
- )}
- </dd>
- </div>
- <div className="mw-letterhead-row">
- <dt className="mw-letterhead-label">{t('intelligence.memoryChunk.letterhead.to')}</dt>
- <dd className="mw-letterhead-value" style={{ margin: 0 }}>
- {parts.toAddress}
- </dd>
- </div>
- </dl>
- <div className="mw-letterhead-date">{formatLetterDate(chunk.timestamp_ms)}</div>
- </header>
- );
-}
diff --git a/app/src/components/intelligence/MemoryChunkMentioned.tsx b/app/src/components/intelligence/MemoryChunkMentioned.tsx
deleted file mode 100644
index 93fb557732..0000000000
--- a/app/src/components/intelligence/MemoryChunkMentioned.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * "Mentioned" entity list — the marginalia of a chunk's letter view.
- *
- * Each row is `[kind label mono] [surface] [chunk count]`. Clicking a row
- * activates the corresponding entity in the Navigator, filtering the
- * result list to chunks tagged with that entity.
- */
-import { useT } from '../../lib/i18n/I18nContext';
-import type { EntityRef } from '../../utils/tauriCommands';
-import Button from '../ui/Button';
-
-interface MemoryChunkMentionedProps {
- entities: EntityRef[];
- onSelectEntity: (entity: EntityRef) => void;
-}
-
-export function MemoryChunkMentioned({ entities, onSelectEntity }: MemoryChunkMentionedProps) {
- const { t } = useT();
- if (entities.length === 0) return null;
-
- return (
- <section data-testid="memory-chunk-mentioned">
- <h3 className="mw-mentioned-heading">{t('intelligence.memoryChunk.mentioned.heading')}</h3>
- <div className="mw-mentioned-table">
- {entities.map(ent => (
- <Button
- variant="tertiary"
- key={ent.entity_id}
- className="mw-mentioned-row h-auto w-full justify-start rounded-none px-0"
- onClick={() => onSelectEntity(ent)}>
- <span className="mw-mentioned-kind">{ent.kind}</span>
- <span className="mw-mentioned-surface">{ent.surface}</span>
- <span className="mw-mentioned-count">
- {ent.count === 1
- ? t('intelligence.memoryChunk.mentioned.chunkOne')
- : t('intelligence.memoryChunk.mentioned.chunkOther').replace(
- '{count}',
- String(ent.count)
- )}
- </span>
- </Button>
- ))}
- </div>
- </section>
- );
-}
diff --git a/app/src/components/intelligence/MemoryChunkScoreBars.tsx b/app/src/components/intelligence/MemoryChunkScoreBars.tsx
deleted file mode 100644
index 7460331007..0000000000
--- a/app/src/components/intelligence/MemoryChunkScoreBars.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-/**
- * "Why kept" score bars — SVG-rendered (not CSS divs) for crisp pixel
- * alignment regardless of zoom or DPR.
- */
-import { useT } from '../../lib/i18n/I18nContext';
-import type { ScoreBreakdown } from '../../utils/tauriCommands';
-
-interface MemoryChunkScoreBarsProps {
- breakdown: ScoreBreakdown;
-}
-
-const TRACK_WIDTH = 200;
-const TRACK_HEIGHT = 8;
-
-function clamp01(v: number): number {
- if (Number.isNaN(v)) return 0;
- return Math.max(0, Math.min(1, v));
-}
-
-export function MemoryChunkScoreBars({ breakdown }: MemoryChunkScoreBarsProps) {
- const { t } = useT();
- return (
- <section data-testid="memory-chunk-scorebars">
- <h3 className="mw-whykept-heading">{t('intelligence.memoryChunk.scoreBars.heading')}</h3>
- <div>
- {breakdown.signals.map(sig => {
- const pct = clamp01(sig.value);
- return (
- <div key={sig.name} className="mw-scorebar-row">
- <span className="mw-scorebar-label">{sig.name}</span>
- <svg
- width="100%"
- viewBox={`0 0 ${TRACK_WIDTH} ${TRACK_HEIGHT}`}
- preserveAspectRatio="none"
- role="img"
- aria-label={t('intelligence.memoryChunk.scoreBars.ariaScore')
- .replace('{name}', sig.name)
- .replace('{pct}', (pct * 100).toFixed(0))}>
- <rect
- x={0}
- y={0}
- width={TRACK_WIDTH}
- height={TRACK_HEIGHT}
- rx={2}
- fill="var(--paper-recessed)"
- />
- <rect
- x={0}
- y={0}
- width={pct * TRACK_WIDTH}
- height={TRACK_HEIGHT}
- rx={2}
- fill="var(--sage)"
- />
- </svg>
- <span className="mw-scorebar-value">{pct.toFixed(2)}</span>
- </div>
- );
- })}
- </div>
- <div className="mw-scorebar-threshold">
- ───{' '}
- {breakdown.kept
- ? t('intelligence.memoryChunk.scoreBars.kept')
- : t('intelligence.memoryChunk.scoreBars.dropped')}{' '}
- {t('intelligence.memoryChunk.scoreBars.atThreshold').replace(
- '{threshold}',
- breakdown.threshold.toFixed(2)
- )}{' '}
- ───
- </div>
- </section>
- );
-}
diff --git a/app/src/components/intelligence/MemoryEmptyPlaceholder.test.tsx b/app/src/components/intelligence/MemoryEmptyPlaceholder.test.tsx
deleted file mode 100644
index 28b68ceb42..0000000000
--- a/app/src/components/intelligence/MemoryEmptyPlaceholder.test.tsx
+++ /dev/null
@@ -1,18 +0,0 @@
-import { render, screen, within } from '@testing-library/react';
-import { describe, expect, it } from 'vitest';
-
-import { MemoryEmptyPlaceholder } from './MemoryEmptyPlaceholder';
-
-describe('<MemoryEmptyPlaceholder />', () => {
- it('renders the empty title and hint copy inside the testid root', () => {
- render(<MemoryEmptyPlaceholder />);
- const root = screen.getByTestId('memory-empty-placeholder');
- // useT resolves against the bundled English map by default.
- expect(
- within(root).getByRole('heading', { level: 2, name: /No memories yet/i })
- ).toBeInTheDocument();
- expect(
- within(root).getByText(/Start interacting to create your first memories/i)
- ).toBeInTheDocument();
- });
-});
diff --git a/app/src/components/intelligence/MemoryEmptyPlaceholder.tsx b/app/src/components/intelligence/MemoryEmptyPlaceholder.tsx
deleted file mode 100644
index 416a5b4123..0000000000
--- a/app/src/components/intelligence/MemoryEmptyPlaceholder.tsx
+++ /dev/null
@@ -1,18 +0,0 @@
-/**
- * Right-pane placeholder shown to brand-new users (zero chunks).
- *
- * Centered, generous whitespace, no call-to-action buttons — the only path
- * forward is connecting an integration in Settings, so we point there in
- * prose without an explicit link to keep the surface meditative.
- */
-import { useT } from '../../lib/i18n/I18nContext';
-
-export function MemoryEmptyPlaceholder() {
- const { t } = useT();
- return (
- <div className="mw-detail-empty" data-testid="memory-empty-placeholder">
- <h2 className="mw-empty-title">{t('memory.empty')}</h2>
- <p className="mw-empty-body">{t('memory.emptyHint')}</p>
- </div>
- );
-}
diff --git a/app/src/components/intelligence/MemoryHeatmap.test.tsx b/app/src/components/intelligence/MemoryHeatmap.test.tsx
deleted file mode 100644
index 58b0779d3d..0000000000
--- a/app/src/components/intelligence/MemoryHeatmap.test.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-import { fireEvent, render } from '@testing-library/react';
-import { describe, expect, it } from 'vitest';
-
-import { MemoryHeatmap } from './MemoryHeatmap';
-
-function todaySeconds(): number {
- return Math.floor(Date.now() / 1000);
-}
-
-/**
- * MemoryHeatmap's display window ends at midnight-start-of-today. Timestamps
- * later than midnight today are placed on a future cell and NOT counted in
- * the total/peak summary. Use yesterday's epoch-seconds for "should be
- * counted" assertions.
- *
- * Anchored to noon (local time) so callers can subtract small offsets (seconds
- * to a few hours) without crossing the day boundary when the test happens to
- * run near midnight in CI.
- */
-function yesterdaySeconds(): number {
- const noonYesterday = new Date();
- noonYesterday.setHours(12, 0, 0, 0);
- noonYesterday.setDate(noonYesterday.getDate() - 1);
- return Math.floor(noonYesterday.getTime() / 1000);
-}
-
-describe('<MemoryHeatmap />', () => {
- it('renders a skeleton when loading', () => {
- const { container } = render(<MemoryHeatmap timestamps={[]} loading />);
- expect(container.querySelector('.animate-pulse')).not.toBeNull();
- // SVG only renders in the non-loading branch.
- expect(container.querySelector('svg')).toBeNull();
- });
-
- it('renders the SVG grid when not loading', () => {
- const { container } = render(<MemoryHeatmap timestamps={[]} />);
- const svg = container.querySelector('svg');
- expect(svg).not.toBeNull();
- // Many rect cells, at least one per displayed day.
- expect(svg!.querySelectorAll('rect').length).toBeGreaterThan(30);
- });
-
- it('reports total counted events from timestamps inside the display window', () => {
- const y = yesterdaySeconds();
- // 4 events yesterday — all inside the 8-month window.
- const timestamps = [y, y - 30, y - 60, y - 90];
- render(<MemoryHeatmap timestamps={timestamps} />);
- // Total renders as separate text nodes: "<n> events over the last …".
- const summary = document.body.textContent ?? '';
- expect(summary).toMatch(/4 events/);
- // Peak (max daily count) is 4 because all four fall on the same day.
- expect(summary).toMatch(/Peak.*4/);
- });
-
- it('shows a hover tooltip when a cell is mouse-entered', () => {
- const now = todaySeconds();
- const { container } = render(<MemoryHeatmap timestamps={[now]} />);
- const rect = container.querySelector('rect');
- expect(rect).not.toBeNull();
- fireEvent.mouseEnter(rect!);
- // Tooltip is rendered as a fixed-positioned div with z-50.
- expect(container.querySelector('.fixed.z-50')).not.toBeNull();
- fireEvent.mouseLeave(rect!);
- expect(container.querySelector('.fixed.z-50')).toBeNull();
- });
-
- it('accepts millisecond-precision timestamps (>9999999999)', () => {
- // Yesterday in ms so it lands inside the counted window.
- const yMs = Date.now() - 24 * 60 * 60 * 1000;
- render(<MemoryHeatmap timestamps={[yMs]} />);
- const summary = document.body.textContent ?? '';
- expect(summary).toMatch(/1 event/);
- });
-});
diff --git a/app/src/components/intelligence/MemoryHeatmap.tsx b/app/src/components/intelligence/MemoryHeatmap.tsx
deleted file mode 100644
index afceee1007..0000000000
--- a/app/src/components/intelligence/MemoryHeatmap.tsx
+++ /dev/null
@@ -1,253 +0,0 @@
-import { useMemo, useState } from 'react';
-
-import { useT } from '../../lib/i18n/I18nContext';
-
-interface MemoryHeatmapProps {
- /** Array of document/relation timestamps (unix epoch seconds). */
- timestamps: number[];
- loading?: boolean;
-}
-
-const MONTHS = 8;
-const DAYS_PER_WEEK = 7;
-const CELL_GAP = 2;
-function dayLabels(t: (key: string) => string): string[] {
- return ['', t('memory.day.mon'), '', t('memory.day.wed'), '', t('memory.day.fri'), ''];
-}
-
-const INTENSITY_COLORS = [
- 'rgba(255,255,255,0.04)', // 0 events
- 'rgba(74,131,221,0.25)', // 1
- 'rgba(74,131,221,0.45)', // 2-3
- 'rgba(74,131,221,0.65)', // 4-6
- 'rgba(74,131,221,0.85)', // 7+
-];
-
-function getIntensity(count: number): number {
- if (count === 0) return 0;
- if (count === 1) return 1;
- if (count <= 3) return 2;
- if (count <= 6) return 3;
- return 4;
-}
-
-function dateToKey(date: Date): string {
- return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
-}
-
-function formatDate(date: Date): string {
- return date.toLocaleDateString(undefined, {
- weekday: 'short',
- month: 'short',
- day: 'numeric',
- year: 'numeric',
- });
-}
-
-export function MemoryHeatmap({ timestamps, loading }: MemoryHeatmapProps) {
- const { t } = useT();
- const [hoveredCell, setHoveredCell] = useState<{
- date: Date;
- count: number;
- x: number;
- y: number;
- } | null>(null);
-
- const { grid, monthLabels, totalEvents, maxDailyCount, totalWeeks } = useMemo(() => {
- // The window: 6 months ago through today
- const today = new Date();
- today.setHours(0, 0, 0, 0);
-
- const rangeStart = new Date(today);
- rangeStart.setMonth(rangeStart.getMonth() - MONTHS);
- rangeStart.setDate(1); // start of that month
-
- // Align to the Sunday of rangeStart's week
- const startDate = new Date(rangeStart);
- startDate.setDate(startDate.getDate() - startDate.getDay());
-
- // Count timestamps that fall anywhere (not limited to the 6-month window)
- // — this means ingesting old data still lights up that old date.
- const countMap = new Map<string, number>();
- let total = 0;
- let maxCount = 0;
-
- for (const ts of timestamps) {
- const date = new Date(ts > 9999999999 ? ts : ts * 1000);
- const key = dateToKey(date);
- const prev = countMap.get(key) ?? 0;
- const next = prev + 1;
- countMap.set(key, next);
- // Only count towards total/max if inside our display range
- if (date >= startDate && date <= today) {
- total++;
- if (next > maxCount) maxCount = next;
- }
- }
-
- // Build grid
- const cells: { date: Date; count: number; weekIdx: number; dayIdx: number }[] = [];
- const months: { label: string; weekIdx: number }[] = [];
- let lastMonth = -1;
- let weekIdx = 0;
-
- const cursor = new Date(startDate);
- while (cursor <= today) {
- const d = cursor.getDay(); // 0=Sun ... 6=Sat
-
- if (d === 0 && cells.length > 0) weekIdx++;
-
- const cellDate = new Date(cursor);
- const key = dateToKey(cellDate);
- cells.push({ date: cellDate, count: countMap.get(key) ?? 0, weekIdx, dayIdx: d });
-
- // Track month labels (on the first Sunday-row cell of each new month)
- if (cellDate.getMonth() !== lastMonth && d === 0) {
- lastMonth = cellDate.getMonth();
- months.push({ label: cellDate.toLocaleDateString(undefined, { month: 'short' }), weekIdx });
- }
-
- cursor.setDate(cursor.getDate() + 1);
- }
-
- return {
- grid: cells,
- monthLabels: months,
- totalEvents: total,
- maxDailyCount: maxCount,
- totalWeeks: weekIdx + 1,
- };
- }, [timestamps]);
-
- // Dynamic cell size: fill available width (parent is ~100%).
- // We use a viewBox + 100% width so SVG scales to fit container.
- const DAY_LABEL_WIDTH = 28;
- const cellSize = 11;
- const svgWidth = DAY_LABEL_WIDTH + totalWeeks * (cellSize + CELL_GAP) + CELL_GAP;
- const svgHeight = DAYS_PER_WEEK * (cellSize + CELL_GAP) + 22;
-
- if (loading) {
- return (
- <div className="rounded-xl border border-line bg-surface-muted p-5">
- <h3 className="text-sm font-semibold text-content mb-3">{t('memory.ingestionActivity')}</h3>
- <div className="h-28 rounded-lg bg-surface-strong animate-pulse" />
- </div>
- );
- }
-
- return (
- <div className="rounded-xl border border-line bg-surface-muted p-5">
- <div className="flex items-center justify-between mb-3">
- <div>
- <h3 className="text-sm font-semibold text-content">{t('memory.ingestionActivity')}</h3>
- <p className="text-xs text-content-muted mt-0.5">
- {totalEvents} {totalEvents !== 1 ? t('memory.events') : t('memory.event')}{' '}
- {t('memory.overTheLast')} {MONTHS} {t('memory.months')}
- {maxDailyCount > 0 && (
- <>
- {' '}
- · {t('memory.peak')}: {maxDailyCount}
- {t('memory.perDay')}
- </>
- )}
- </p>
- </div>
- <div className="flex items-center gap-1 text-[10px] text-content-muted">
- <span>{t('memory.less')}</span>
- {INTENSITY_COLORS.map((color, i) => (
- <div
- key={i}
- className="w-[10px] h-[10px] rounded-[2px]"
- style={{ backgroundColor: color }}
- />
- ))}
- <span>{t('memory.more')}</span>
- </div>
- </div>
-
- <svg
- width="100%"
- viewBox={`0 0 ${svgWidth} ${svgHeight}`}
- preserveAspectRatio="xMinYMin meet"
- className="block">
- {/* Day labels */}
- {dayLabels(t).map((label, i) =>
- label ? (
- <text
- key={i}
- x={0}
- y={22 + i * (cellSize + CELL_GAP) + cellSize * 0.75}
- fontSize={9}
- fill="rgba(0,0,0,0.4)"
- style={{ userSelect: 'none' }}>
- {label}
- </text>
- ) : null
- )}
-
- {/* Month labels */}
- {monthLabels.map((m, i) => (
- <text
- key={i}
- x={DAY_LABEL_WIDTH + m.weekIdx * (cellSize + CELL_GAP)}
- y={12}
- fontSize={9}
- fill="rgba(0,0,0,0.4)"
- style={{ userSelect: 'none' }}>
- {m.label}
- </text>
- ))}
-
- {/* Cells */}
- {grid.map((cell, i) => {
- const x = DAY_LABEL_WIDTH + cell.weekIdx * (cellSize + CELL_GAP);
- const y = 18 + cell.dayIdx * (cellSize + CELL_GAP);
- const intensity = getIntensity(cell.count);
-
- return (
- <rect
- key={i}
- x={x}
- y={y}
- width={cellSize}
- height={cellSize}
- rx={2}
- fill={INTENSITY_COLORS[intensity]}
- stroke={
- hoveredCell?.date.getTime() === cell.date.getTime()
- ? 'rgba(255,255,255,0.4)'
- : 'transparent'
- }
- strokeWidth={1}
- style={{ cursor: 'pointer', transition: 'fill 0.1s' }}
- onMouseEnter={e => {
- const rect = (e.target as SVGRectElement).getBoundingClientRect();
- setHoveredCell({
- date: cell.date,
- count: cell.count,
- x: rect.left + rect.width / 2,
- y: rect.top,
- });
- }}
- onMouseLeave={() => setHoveredCell(null)}
- />
- );
- })}
- </svg>
-
- {/* Tooltip */}
- {hoveredCell && (
- <div
- className="fixed z-50 px-2 py-1 rounded-md bg-surface border border-line text-[11px] text-content shadow-lg pointer-events-none"
- style={{ left: hoveredCell.x, top: hoveredCell.y - 32, transform: 'translateX(-50%)' }}>
- <span className="font-medium">
- {hoveredCell.count} {hoveredCell.count !== 1 ? t('memory.events') : t('memory.event')}
- </span>{' '}
- <span className="text-content-faint">
- {t('memory.on')} {formatDate(hoveredCell.date)}
- </span>
- </div>
- )}
- </div>
- );
-}
diff --git a/app/src/components/intelligence/MemorySection.test.tsx b/app/src/components/intelligence/MemorySection.test.tsx
deleted file mode 100644
index 32b8bc87d4..0000000000
--- a/app/src/components/intelligence/MemorySection.test.tsx
+++ /dev/null
@@ -1,47 +0,0 @@
-import { screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import { renderWithProviders } from '../../test/test-utils';
-import type { ToastNotification } from '../../types/intelligence';
-import MemorySection from './MemorySection';
-
-const memoryWorkspaceSpy =
- vi.fn<(props: { onToast?: (toast: Omit<ToastNotification, 'id'>) => void }) => void>();
-
-vi.mock('./MemoryWorkspace', () => ({
- MemoryWorkspace: (props: { onToast?: (toast: Omit<ToastNotification, 'id'>) => void }) => {
- memoryWorkspaceSpy(props);
- return <div data-testid="memory-workspace" />;
- },
-}));
-
-describe('<MemorySection />', () => {
- it('renders the core MemoryWorkspace directly with no analysis sub-pill bar', () => {
- const onToast = vi.fn();
- renderWithProviders(<MemorySection onToast={onToast} />);
-
- // Core view is shown.
- expect(screen.getByTestId('memory-workspace')).toBeInTheDocument();
-
- // No sub-pill/tab bar (the analysis pills are gone).
- for (const label of [
- 'Diagram',
- 'Centrality',
- 'Cohesion',
- 'Associations',
- 'Freshness',
- 'Timeline',
- 'Paths',
- 'Namespaces',
- ]) {
- expect(screen.queryByRole('button', { name: label })).not.toBeInTheDocument();
- }
- });
-
- it('forwards onToast to MemoryWorkspace', () => {
- const onToast = vi.fn();
- renderWithProviders(<MemorySection onToast={onToast} />);
-
- expect(memoryWorkspaceSpy).toHaveBeenCalledWith(expect.objectContaining({ onToast }));
- });
-});
diff --git a/app/src/components/intelligence/MemorySection.tsx b/app/src/components/intelligence/MemorySection.tsx
deleted file mode 100644
index 7dd6b20648..0000000000
--- a/app/src/components/intelligence/MemorySection.tsx
+++ /dev/null
@@ -1,22 +0,0 @@
-import type { ToastNotification } from '../../types/intelligence';
-import { MemoryWorkspace } from './MemoryWorkspace';
-
-/**
- * Memory tab body.
- *
- * Renders the core memory experience (`MemoryWorkspace` — sources registry,
- * tree-status panel, and summary graph) directly, with no sub-pill/tab bar.
- *
- * The internal graph/memory-analysis surfaces (Diagram, Centrality, Cohesion,
- * Associations, Freshness, Timeline, Paths, Namespaces) are developer/analysis
- * views that cluttered the experience and are intentionally no longer reachable
- * from this tab. Their components are retained on disk (and still unit-tested)
- * so they can be restored behind a dedicated surface later if needed.
- */
-interface MemorySectionProps {
- onToast: (toast: Omit<ToastNotification, 'id'>) => void;
-}
-
-export default function MemorySection({ onToast }: MemorySectionProps) {
- return <MemoryWorkspace onToast={onToast} />;
-}
diff --git a/app/src/components/intelligence/MemoryStatsBar.test.tsx b/app/src/components/intelligence/MemoryStatsBar.test.tsx
deleted file mode 100644
index fe8fbc8e7b..0000000000
--- a/app/src/components/intelligence/MemoryStatsBar.test.tsx
+++ /dev/null
@@ -1,86 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import { MemoryStatsBar } from './MemoryStatsBar';
-
-const BASE_PROPS = {
- totalDocs: 1234,
- totalFiles: 7,
- totalNamespaces: 3,
- totalRelations: 42,
- totalSessions: 11,
- totalTokens: 9876,
- estimatedStorageBytes: 2 * 1024 * 1024, // 2 MB
- oldestDocTimestamp: null,
- newestDocTimestamp: null,
- docsToday: 0,
-};
-
-describe('<MemoryStatsBar />', () => {
- it('formats large numeric values with thousands separators', () => {
- render(<MemoryStatsBar {...BASE_PROPS} />);
- // totalDocs => 1,234
- expect(screen.getByText('1,234')).toBeInTheDocument();
- // totalTokens => 9,876 lives in a sub-label
- expect(screen.getByText(/9,876/)).toBeInTheDocument();
- });
-
- it('formats the storage cell in human-readable bytes', () => {
- // formatBytes uses .toFixed(1) for values < 10 ("2.0 MB"), Math.round otherwise.
- render(<MemoryStatsBar {...BASE_PROPS} />);
- expect(screen.getByText('2.0 MB')).toBeInTheDocument();
- });
-
- it('rounds storage values >= 10 of a unit', () => {
- render(<MemoryStatsBar {...BASE_PROPS} estimatedStorageBytes={42 * 1024 * 1024} />);
- expect(screen.getByText('42 MB')).toBeInTheDocument();
- });
-
- it('renders "--" placeholders when the corresponding fields are null/zero', () => {
- render(
- <MemoryStatsBar
- {...BASE_PROPS}
- estimatedStorageBytes={0}
- totalSessions={null}
- totalTokens={null}
- />
- );
- // storage and sessions both fall back to '--'
- const placeholders = screen.getAllByText('--');
- expect(placeholders.length).toBeGreaterThanOrEqual(2);
- });
-
- it('renders the docs-today sub-label only when docsToday > 0', () => {
- const { rerender } = render(<MemoryStatsBar {...BASE_PROPS} docsToday={5} />);
- expect(screen.getByText(/\+5/)).toBeInTheDocument();
- rerender(<MemoryStatsBar {...BASE_PROPS} docsToday={0} />);
- expect(screen.queryByText(/^\+/)).not.toBeInTheDocument();
- });
-
- it('renders a relative time-ago when oldest/newest timestamps are provided', () => {
- // Freeze the clock so the relative offsets resolve to exactly "5h ago"
- // and "10m ago" regardless of when the suite runs.
- vi.useFakeTimers();
- vi.setSystemTime(new Date('2026-03-04T12:00:00.000Z'));
- try {
- const now = Math.floor(Date.now() / 1000);
- render(
- <MemoryStatsBar
- {...BASE_PROPS}
- oldestDocTimestamp={now - 3600 * 5} // 5h ago
- newestDocTimestamp={now - 60 * 10} // 10m ago
- />
- );
- expect(screen.getByText('5h ago')).toBeInTheDocument();
- expect(screen.getByText(/10m ago/)).toBeInTheDocument();
- } finally {
- vi.useRealTimers();
- }
- });
-
- it('shows a skeleton placeholder when loading', () => {
- const { container } = render(<MemoryStatsBar {...BASE_PROPS} loading />);
- // 6 stat tiles, each renders an animate-pulse skeleton instead of value.
- expect(container.querySelectorAll('.animate-pulse').length).toBe(6);
- });
-});
diff --git a/app/src/components/intelligence/MemoryStatsBar.tsx b/app/src/components/intelligence/MemoryStatsBar.tsx
deleted file mode 100644
index 2a719685e7..0000000000
--- a/app/src/components/intelligence/MemoryStatsBar.tsx
+++ /dev/null
@@ -1,121 +0,0 @@
-import { useT } from '../../lib/i18n/I18nContext';
-
-interface MemoryStatsBarProps {
- totalDocs: number;
- totalFiles: number;
- totalNamespaces: number;
- totalRelations: number;
- totalSessions: number | null;
- totalTokens: number | null;
- /** Estimated storage in bytes (sum of document content lengths). */
- estimatedStorageBytes: number;
- /** Unix-epoch seconds of the oldest document. */
- oldestDocTimestamp: number | null;
- /** Unix-epoch seconds of the newest document. */
- newestDocTimestamp: number | null;
- docsToday: number;
- loading?: boolean;
-}
-
-function formatBytes(bytes: number): string {
- if (bytes === 0) return '0 B';
- const units = ['B', 'KB', 'MB', 'GB'];
- const i = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
- const value = bytes / Math.pow(1024, i);
- return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[i]}`;
-}
-
-function formatTimeAgo(epochSeconds: number): string {
- const now = Date.now() / 1000;
- const diff = now - epochSeconds;
- if (diff < 60) return 'just now';
- if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
- if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
- if (diff < 2592000) return `${Math.floor(diff / 86400)}d ago`;
- if (diff < 31536000) return `${Math.floor(diff / 2592000)}mo ago`;
- return `${(diff / 31536000).toFixed(1)}y ago`;
-}
-
-function formatNumber(value: number): string {
- return new Intl.NumberFormat().format(value);
-}
-
-export function MemoryStatsBar(props: MemoryStatsBarProps) {
- const { t } = useT();
- const {
- totalDocs,
- totalFiles,
- totalNamespaces,
- totalRelations,
- totalSessions,
- totalTokens,
- estimatedStorageBytes,
- oldestDocTimestamp,
- newestDocTimestamp,
- docsToday,
- loading,
- } = props;
-
- const stats = [
- {
- label: t('stats.storage'),
- value: estimatedStorageBytes > 0 ? formatBytes(estimatedStorageBytes) : '--',
- sub: totalFiles > 0 ? `${formatNumber(totalFiles)} ${t('stats.files')}` : undefined,
- color: 'text-primary-500',
- },
- {
- label: t('stats.documents'),
- value: formatNumber(totalDocs),
- sub: docsToday > 0 ? `+${docsToday} ${t('stats.today')}` : undefined,
- color: 'text-emerald-600 dark:text-emerald-300',
- },
- {
- label: t('stats.namespaces'),
- value: formatNumber(totalNamespaces),
- sub: undefined,
- color: 'text-amber-600 dark:text-amber-300',
- },
- {
- label: t('stats.relations'),
- value: formatNumber(totalRelations),
- sub: undefined,
- color: 'text-violet-600 dark:text-violet-300',
- },
- {
- label: t('stats.firstMemory'),
- value: oldestDocTimestamp ? formatTimeAgo(oldestDocTimestamp) : '--',
- sub: newestDocTimestamp
- ? `${t('stats.latest')}: ${formatTimeAgo(newestDocTimestamp)}`
- : undefined,
- color: 'text-sky-600 dark:text-sky-300',
- },
- {
- label: t('stats.sessions'),
- value: totalSessions !== null ? formatNumber(totalSessions) : '--',
- sub: totalTokens !== null ? `${formatNumber(totalTokens)} ${t('stats.tokens')}` : undefined,
- color: 'text-rose-600 dark:text-rose-300',
- },
- ];
-
- return (
- <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3">
- {stats.map(stat => (
- <div
- key={stat.label}
- className="rounded-xl border border-line bg-surface-muted p-3 transition-colors hover:bg-surface-hover dark:bg-surface-muted">
- <div className="text-[11px] uppercase tracking-wide text-content-muted mb-1">
- {stat.label}
- </div>
- <div className={`text-xl font-semibold ${stat.color}`}>
- {loading ? (
- <div className="h-7 w-16 rounded bg-surface-strong animate-pulse" />
- ) : (
- stat.value
- )}
- </div>
- {stat.sub && <div className="text-[11px] text-content-muted mt-0.5">{stat.sub}</div>}
- </div>
- ))}
- </div>
- );
-}
diff --git a/app/src/components/intelligence/WorkflowRunApprovalCard.test.tsx b/app/src/components/intelligence/WorkflowRunApprovalCard.test.tsx
deleted file mode 100644
index f06789d6b0..0000000000
--- a/app/src/components/intelligence/WorkflowRunApprovalCard.test.tsx
+++ /dev/null
@@ -1,112 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import { type WorkflowDefinition } from '../../services/api/workflowRunsApi';
-import WorkflowRunApprovalCard from './WorkflowRunApprovalCard';
-
-// i18n → echo the key so assertions can target stable strings.
-vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
-
-function def(overrides: Partial<WorkflowDefinition> = {}): WorkflowDefinition {
- return {
- id: 'parallel_research_cross_check',
- name: 'Parallel research',
- description: 'desc',
- phases: [],
- defaultConcurrency: 2,
- maxChildren: 8,
- safetyTier: 'read_only',
- ...overrides,
- };
-}
-
-describe('WorkflowRunApprovalCard', () => {
- it('renders one localized line per reason', () => {
- render(
- <WorkflowRunApprovalCard
- definition={def()}
- reasons={['high_children', 'high_concurrency']}
- onApprove={vi.fn()}
- onCancel={vi.fn()}
- />
- );
- const reasons = screen.getByTestId('workflow-approval-reasons');
- expect(reasons.querySelectorAll('li')).toHaveLength(2);
- expect(screen.getByText('orchestration.approval.reason.children')).toBeInTheDocument();
- expect(screen.getByText('orchestration.approval.reason.concurrency')).toBeInTheDocument();
- });
-
- it('shows the concrete cost facts (tier / concurrency / max children)', () => {
- render(
- <WorkflowRunApprovalCard
- definition={def({ defaultConcurrency: 3, maxChildren: 8 })}
- reasons={['high_children']}
- onApprove={vi.fn()}
- onCancel={vi.fn()}
- />
- );
- expect(screen.getByText('orchestration.tier.readOnly')).toBeInTheDocument();
- expect(screen.getByText('3')).toBeInTheDocument();
- expect(screen.getByText('8')).toBeInTheDocument();
- });
-
- it('fires onApprove when "Approve & start" is clicked', () => {
- const onApprove = vi.fn();
- render(
- <WorkflowRunApprovalCard
- definition={def()}
- reasons={['high_children']}
- onApprove={onApprove}
- onCancel={vi.fn()}
- />
- );
- fireEvent.click(screen.getByTestId('workflow-approval-approve'));
- expect(onApprove).toHaveBeenCalledTimes(1);
- });
-
- it('fires onCancel when "Cancel" is clicked', () => {
- const onCancel = vi.fn();
- render(
- <WorkflowRunApprovalCard
- definition={def()}
- reasons={['high_children']}
- onApprove={vi.fn()}
- onCancel={onCancel}
- />
- );
- fireEvent.click(screen.getByTestId('workflow-approval-cancel'));
- expect(onCancel).toHaveBeenCalledTimes(1);
- });
-
- it('uses an opaque warning surface so thread text does not show through (#3783)', () => {
- render(
- <WorkflowRunApprovalCard
- definition={def()}
- reasons={['high_children']}
- onApprove={vi.fn()}
- onCancel={vi.fn()}
- />
- );
- const card = screen.getByTestId('workflow-approval-card');
- expect(card).toHaveClass('bg-amber-50');
- expect(card).toHaveClass('dark:bg-amber-950');
- // No fractional-opacity background that would let thread text bleed through.
- expect(card.className).not.toMatch(/\bbg-[^\s/]+\/\d+/);
- expect(card.className).not.toMatch(/\bdark:bg-[^\s/]+\/\d+/);
- });
-
- it('disables both buttons and shows the starting label while a start is in flight', () => {
- render(
- <WorkflowRunApprovalCard
- definition={def()}
- reasons={['high_children']}
- starting
- onApprove={vi.fn()}
- onCancel={vi.fn()}
- />
- );
- expect(screen.getByTestId('workflow-approval-approve')).toBeDisabled();
- expect(screen.getByTestId('workflow-approval-cancel')).toBeDisabled();
- expect(screen.getByText('orchestration.approval.starting')).toBeInTheDocument();
- });
-});
diff --git a/app/src/components/intelligence/WorkflowRunApprovalCard.tsx b/app/src/components/intelligence/WorkflowRunApprovalCard.tsx
deleted file mode 100644
index bd51f12f68..0000000000
--- a/app/src/components/intelligence/WorkflowRunApprovalCard.tsx
+++ /dev/null
@@ -1,151 +0,0 @@
-/**
- * WorkflowRunApprovalCard (#3375)
- * --------------------------------
- *
- * Confirmation surface shown before starting a high-cost / high-concurrency
- * workflow run. The acceptance criterion "High-cost/high-concurrency runs
- * require explicit approval" is enforced on the client: the Orchestration tab
- * calls {@link assessWorkflowCost} and, when it returns `requiresApproval`,
- * renders this card instead of starting immediately. The user must press
- * "Approve & start" to proceed; "Cancel" aborts without touching the engine.
- *
- * Styling mirrors the chat ApprovalRequestCard (amber warning chrome) so the
- * approval affordance is visually consistent across the app.
- */
-import debug from 'debug';
-import React from 'react';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import {
- type WorkflowCostReason,
- type WorkflowDefinition,
- type WorkflowSafetyTier,
-} from '../../services/api/workflowRunsApi';
-import Button from '../ui/Button';
-
-const log = debug('intelligence:workflow-approval');
-
-/** i18n key for each cost reason code. */
-const REASON_KEY: Record<WorkflowCostReason, string> = {
- non_read_only_tier: 'orchestration.approval.reason.tier',
- high_concurrency: 'orchestration.approval.reason.concurrency',
- high_children: 'orchestration.approval.reason.children',
-};
-
-/** i18n key for each safety tier label. */
-const SAFETY_TIER_KEY: Record<WorkflowSafetyTier, string> = {
- read_only: 'orchestration.tier.readOnly',
- standard: 'orchestration.tier.standard',
- edit_capable: 'orchestration.tier.editCapable',
-};
-
-interface Props {
- definition: WorkflowDefinition;
- reasons: WorkflowCostReason[];
- /** Whether the start RPC is in flight (disables the buttons). */
- starting?: boolean;
- onApprove: () => void;
- onCancel: () => void;
-}
-
-const WorkflowRunApprovalCard: React.FC<Props> = ({
- definition,
- reasons,
- starting = false,
- onApprove,
- onCancel,
-}) => {
- const { t } = useT();
-
- return (
- // Not `ui/Alert`: this card must render as an opaque solid, never Alert's
- // translucent `dark:bg-amber-500/10`, so background chat thread text
- // never bleeds through underneath it (#3783 — see the regression test).
- <div
- role="alertdialog"
- aria-label={t('orchestration.approval.title')}
- data-testid="workflow-approval-card"
- className="rounded-xl border border-amber-300 bg-amber-50 p-4 text-sm shadow-xs dark:border-amber-700 dark:bg-amber-950">
- <div className="flex items-start gap-2">
- <span aria-hidden className="text-base leading-none">
- ⚠️
- </span>
- <div className="min-w-0 flex-1">
- <p className="font-semibold text-amber-900 dark:text-amber-200">
- {t('orchestration.approval.title')}
- </p>
- <p className="mt-1 wrap-break-word text-amber-800/90 dark:text-amber-200/90">
- {t('orchestration.approval.body')}{' '}
- <span className="font-semibold">{definition.name}</span>
- </p>
-
- {/* Why approval is required — one localized line per reason code. */}
- <ul
- data-testid="workflow-approval-reasons"
- className="mt-2 list-disc space-y-1 pl-5 text-xs text-amber-800/90 dark:text-amber-200/90">
- {reasons.map(reason => (
- <li key={reason}>{t(REASON_KEY[reason])}</li>
- ))}
- </ul>
-
- {/* Concrete cost facts so the user knows what they're approving. */}
- <dl className="mt-3 grid grid-cols-3 gap-2 text-xs">
- <div className="rounded-md bg-amber-100/70 px-2 py-1.5 dark:bg-amber-500/15">
- <dt className="text-amber-700/80 dark:text-amber-300/80">
- {t('orchestration.approval.tier')}
- </dt>
- <dd className="font-medium text-amber-900 dark:text-amber-100">
- {t(SAFETY_TIER_KEY[definition.safetyTier])}
- </dd>
- </div>
- <div className="rounded-md bg-amber-100/70 px-2 py-1.5 dark:bg-amber-500/15">
- <dt className="text-amber-700/80 dark:text-amber-300/80">
- {t('orchestration.approval.concurrency')}
- </dt>
- <dd className="font-medium text-amber-900 dark:text-amber-100">
- {definition.defaultConcurrency}
- </dd>
- </div>
- <div className="rounded-md bg-amber-100/70 px-2 py-1.5 dark:bg-amber-500/15">
- <dt className="text-amber-700/80 dark:text-amber-300/80">
- {t('orchestration.approval.maxChildren')}
- </dt>
- <dd className="font-medium text-amber-900 dark:text-amber-100">
- {definition.maxChildren}
- </dd>
- </div>
- </dl>
-
- <div className="mt-3 flex flex-wrap items-center gap-2">
- <Button
- variant="primary"
- size="sm"
- data-testid="workflow-approval-approve"
- disabled={starting}
- onClick={() => {
- log('approve definitionId=%s', definition.id);
- onApprove();
- }}>
- {starting
- ? t('orchestration.approval.starting')
- : t('orchestration.approval.approve')}
- </Button>
- <Button
- variant="secondary"
- size="sm"
- data-testid="workflow-approval-cancel"
- disabled={starting}
- onClick={() => {
- log('cancel definitionId=%s', definition.id);
- onCancel();
- }}>
- {t('orchestration.approval.cancel')}
- </Button>
- </div>
- </div>
- </div>
- </div>
- );
-};
-
-export default WorkflowRunApprovalCard;
diff --git a/app/src/components/intelligence/WorkflowRunDetail.test.tsx b/app/src/components/intelligence/WorkflowRunDetail.test.tsx
deleted file mode 100644
index 6c42fb18ec..0000000000
--- a/app/src/components/intelligence/WorkflowRunDetail.test.tsx
+++ /dev/null
@@ -1,200 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import { type WorkflowDefinition, type WorkflowRun } from '../../services/api/workflowRunsApi';
-import WorkflowRunDetail from './WorkflowRunDetail';
-
-// i18n → echo the key so assertions can target stable strings.
-vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
-
-function def(): WorkflowDefinition {
- return {
- id: 'parallel_research_cross_check',
- name: 'Parallel research',
- description: 'desc',
- phases: [
- {
- name: 'decompose',
- description: 'Break the question down.',
- agentIds: ['planner'],
- dependsOn: [],
- },
- {
- name: 'research',
- description: 'Research in parallel.',
- agentIds: ['researcher', 'researcher'],
- dependsOn: ['decompose'],
- },
- {
- name: 'synthesize',
- description: 'Synthesize.',
- agentIds: ['summarizer'],
- dependsOn: ['research'],
- },
- ],
- defaultConcurrency: 2,
- maxChildren: 8,
- safetyTier: 'read_only',
- };
-}
-
-function run(overrides: Partial<WorkflowRun> = {}): WorkflowRun {
- return {
- id: 'wfrun-1',
- definitionId: 'parallel_research_cross_check',
- parentThreadId: null,
- input: { question: 'q' },
- phaseStates: {
- decompose: {
- status: 'completed',
- outputs: [{ orchestrationId: 'orch-1', agentId: 'planner', output: 'three angles' }],
- },
- research: { status: 'running', outputs: [] },
- synthesize: { status: 'pending', outputs: [] },
- },
- childRunIds: ['orch-1'],
- status: 'running',
- summary: null,
- startedAt: '2026-01-01T00:00:00Z',
- updatedAt: '2026-01-01T00:01:00Z',
- completedAt: null,
- ...overrides,
- };
-}
-
-describe('WorkflowRunDetail — progress rendering', () => {
- it('renders the run status and every declared phase in order', () => {
- render(
- <WorkflowRunDetail definition={def()} run={run()} onStop={vi.fn()} onResume={vi.fn()} />
- );
-
- expect(screen.getByTestId('workflow-run-status')).toHaveTextContent(
- 'orchestration.runStatus.running'
- );
-
- const phases = screen.getByTestId('workflow-phase-list').querySelectorAll('li');
- expect(phases).toHaveLength(3);
- expect(screen.getByTestId('workflow-phase-decompose')).toBeInTheDocument();
- expect(screen.getByTestId('workflow-phase-research')).toBeInTheDocument();
- expect(screen.getByTestId('workflow-phase-synthesize')).toBeInTheDocument();
- });
-
- it('reflects per-phase status from phaseStates', () => {
- render(
- <WorkflowRunDetail definition={def()} run={run()} onStop={vi.fn()} onResume={vi.fn()} />
- );
- expect(screen.getByTestId('workflow-phase-status-decompose')).toHaveTextContent(
- 'orchestration.phaseStatus.completed'
- );
- expect(screen.getByTestId('workflow-phase-status-research')).toHaveTextContent(
- 'orchestration.phaseStatus.running'
- );
- expect(screen.getByTestId('workflow-phase-status-synthesize')).toHaveTextContent(
- 'orchestration.phaseStatus.pending'
- );
- });
-
- it('shows child agent refs for a phase when expanded', () => {
- render(
- <WorkflowRunDetail definition={def()} run={run()} onStop={vi.fn()} onResume={vi.fn()} />
- );
- // Outputs are collapsed by default; expand the completed phase.
- fireEvent.click(screen.getByTestId('workflow-phase-decompose').querySelector('button')!);
- const outputs = screen.getByTestId('workflow-phase-outputs-decompose');
- expect(outputs).toHaveTextContent('planner');
- expect(outputs).toHaveTextContent('orch-1');
- expect(outputs).toHaveTextContent('three angles');
- });
-
- it('renders the run-level child agent ref count', () => {
- render(
- <WorkflowRunDetail definition={def()} run={run()} onStop={vi.fn()} onResume={vi.fn()} />
- );
- expect(screen.getByTestId('workflow-child-refs')).toBeInTheDocument();
- });
-
- it('shows the final synthesis only once the run is terminal with a summary', () => {
- const { rerender } = render(
- <WorkflowRunDetail definition={def()} run={run()} onStop={vi.fn()} onResume={vi.fn()} />
- );
- expect(screen.queryByTestId('workflow-run-summary')).not.toBeInTheDocument();
-
- rerender(
- <WorkflowRunDetail
- definition={def()}
- run={run({
- status: 'completed',
- summary: 'A cited report.',
- completedAt: '2026-01-01T00:05:00Z',
- })}
- onStop={vi.fn()}
- onResume={vi.fn()}
- />
- );
- expect(screen.getByTestId('workflow-run-summary')).toHaveTextContent('A cited report.');
- });
-
- it('offers Stop while running and wires it to onStop', () => {
- const onStop = vi.fn();
- render(<WorkflowRunDetail definition={def()} run={run()} onStop={onStop} onResume={vi.fn()} />);
- expect(screen.queryByTestId('workflow-run-resume')).not.toBeInTheDocument();
- fireEvent.click(screen.getByTestId('workflow-run-stop'));
- expect(onStop).toHaveBeenCalledWith('wfrun-1');
- });
-
- it('offers Resume when interrupted and wires it to onResume', () => {
- const onResume = vi.fn();
- render(
- <WorkflowRunDetail
- definition={def()}
- run={run({ status: 'interrupted' })}
- onStop={vi.fn()}
- onResume={onResume}
- />
- );
- expect(screen.queryByTestId('workflow-run-stop')).not.toBeInTheDocument();
- fireEvent.click(screen.getByTestId('workflow-run-resume'));
- expect(onResume).toHaveBeenCalledWith('wfrun-1');
- });
-
- it('falls back to phaseStates keys + raw phase name when the definition is missing', () => {
- render(
- <WorkflowRunDetail
- definition={undefined}
- run={run({
- phaseStates: { decompose: { status: 'running', outputs: [] } },
- childRunIds: [],
- })}
- onStop={vi.fn()}
- onResume={vi.fn()}
- />
- );
- // With no definition, the phase order comes from run.phaseStates and the
- // label falls back to the raw phase name (WorkflowRunDetail.tsx:173).
- const phases = screen.getByTestId('workflow-phase-list').querySelectorAll('li');
- expect(phases).toHaveLength(1);
- expect(screen.getByTestId('workflow-phase-decompose')).toHaveTextContent('decompose');
- });
-
- it('renders the failure reason for a failed phase', () => {
- render(
- <WorkflowRunDetail
- definition={def()}
- run={run({
- status: 'failed',
- phaseStates: {
- decompose: { status: 'failed', outputs: [], reason: 'planner agent errored out' },
- research: { status: 'pending', outputs: [] },
- synthesize: { status: 'pending', outputs: [] },
- },
- })}
- onStop={vi.fn()}
- onResume={vi.fn()}
- />
- );
- // The failed-phase reason banner (WorkflowRunDetail.tsx:197).
- expect(screen.getByTestId('workflow-phase-decompose')).toHaveTextContent(
- 'planner agent errored out'
- );
- });
-});
diff --git a/app/src/components/intelligence/WorkflowRunDetail.tsx b/app/src/components/intelligence/WorkflowRunDetail.tsx
deleted file mode 100644
index 0983ca586a..0000000000
--- a/app/src/components/intelligence/WorkflowRunDetail.tsx
+++ /dev/null
@@ -1,267 +0,0 @@
-/**
- * WorkflowRunDetail (#3375)
- * -------------------------
- *
- * Drill-in view for a single workflow run. Given a definition (for phase
- * ordering + labels) and the latest run snapshot, it renders:
- * - the run status header,
- * - an ordered phase timeline driven by `run.phaseStates`,
- * - each phase's child agent refs (orchestration id + agent id + output),
- * - Stop / Resume controls wired to the engine,
- * - the final synthesized report once the run completes.
- *
- * The component is presentational + control-only: the parent (Orchestration
- * tab) owns the polling loop and passes a fresh `run` each tick. Stop / Resume
- * delegate to callbacks so the parent can refresh its run list too.
- */
-import debug from 'debug';
-import React, { useState } from 'react';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import {
- type WorkflowDefinition,
- type WorkflowPhaseState,
- type WorkflowPhaseStatus,
- type WorkflowRun,
- type WorkflowRunStatus,
-} from '../../services/api/workflowRunsApi';
-import { AccordionContent, AccordionItem, AccordionRoot, AccordionTrigger } from '../ui/Accordion';
-import Badge, { type BadgeVariant } from '../ui/Badge';
-import Button from '../ui/Button';
-
-const log = debug('intelligence:workflow-detail');
-
-/** Badge variant per run status. */
-const RUN_STATUS_VARIANT: Record<WorkflowRunStatus, BadgeVariant> = {
- pending: 'neutral',
- running: 'primary',
- completed: 'success',
- failed: 'danger',
- cancelled: 'neutral',
- interrupted: 'warning',
-};
-
-const RUN_STATUS_KEY: Record<WorkflowRunStatus, string> = {
- pending: 'orchestration.runStatus.pending',
- running: 'orchestration.runStatus.running',
- completed: 'orchestration.runStatus.completed',
- failed: 'orchestration.runStatus.failed',
- cancelled: 'orchestration.runStatus.cancelled',
- interrupted: 'orchestration.runStatus.interrupted',
-};
-
-const PHASE_STATUS_KEY: Record<WorkflowPhaseStatus, string> = {
- pending: 'orchestration.phaseStatus.pending',
- running: 'orchestration.phaseStatus.running',
- completed: 'orchestration.phaseStatus.completed',
- failed: 'orchestration.phaseStatus.failed',
-};
-
-/** Badge variant per phase status. */
-const PHASE_STATUS_VARIANT: Record<WorkflowPhaseStatus, BadgeVariant> = {
- pending: 'neutral',
- running: 'primary',
- completed: 'success',
- failed: 'danger',
-};
-
-const TERMINAL_STATUSES: WorkflowRunStatus[] = ['completed', 'failed', 'cancelled', 'interrupted'];
-
-interface Props {
- definition: WorkflowDefinition | undefined;
- run: WorkflowRun;
- /** True while a stop/resume RPC is in flight. */
- busy?: boolean;
- onStop: (id: string) => void;
- onResume: (id: string) => void;
-}
-
-const WorkflowRunDetail: React.FC<Props> = ({
- definition,
- run,
- busy = false,
- onStop,
- onResume,
-}) => {
- const { t } = useT();
- // Every phase is its own independent disclosure — several can be expanded
- // at once, so this is Accordion `type="multiple"` (open phases as an array
- // for Radix's controlled `value`, rather than the old per-name boolean map).
- const [openPhases, setOpenPhases] = useState<string[]>([]);
-
- // Phase order: lead with the definition's declared order, then append any
- // runtime-only phases the run reports but the definition doesn't list (so a
- // run still renders its full progress during definition/version drift).
- const declaredPhaseNames = definition?.phases.map(p => p.name) ?? [];
- const declaredSet = new Set(declaredPhaseNames);
- const runtimeOnlyPhaseNames = Object.keys(run.phaseStates).filter(name => !declaredSet.has(name));
- const phaseNames = [...declaredPhaseNames, ...runtimeOnlyPhaseNames];
-
- const isRunning = run.status === 'running' || run.status === 'pending';
- const canResume = run.status === 'interrupted';
-
- return (
- <div className="space-y-4" data-testid="workflow-run-detail">
- {/* Header: status + controls */}
- <div className="flex flex-wrap items-center justify-between gap-2">
- <div className="flex items-center gap-2">
- <Badge
- variant={RUN_STATUS_VARIANT[run.status]}
- data-testid="workflow-run-status"
- dot={run.status === 'running' ? false : undefined}>
- {run.status === 'running' && (
- <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-primary-500" />
- )}
- {t(RUN_STATUS_KEY[run.status])}
- </Badge>
- <span className="font-mono text-[11px] text-content-faint">{run.id}</span>
- </div>
-
- <div className="flex items-center gap-2">
- {isRunning && (
- <Button
- variant="secondary"
- tone="danger"
- size="sm"
- data-testid="workflow-run-stop"
- disabled={busy}
- onClick={() => {
- log('stop id=%s', run.id);
- onStop(run.id);
- }}>
- {t('orchestration.detail.stop')}
- </Button>
- )}
- {canResume && (
- <Button
- variant="secondary"
- size="sm"
- data-testid="workflow-run-resume"
- disabled={busy}
- onClick={() => {
- log('resume id=%s', run.id);
- onResume(run.id);
- }}
- className="border-primary-300 text-primary-700 hover:bg-primary-50 dark:border-primary-700 dark:text-primary-300 dark:hover:bg-primary-900/40">
- {t('orchestration.detail.resume')}
- </Button>
- )}
- </div>
- </div>
-
- {/* Phase timeline */}
- <AccordionRoot
- type="multiple"
- value={openPhases}
- onValueChange={setOpenPhases}
- asChild
- className="space-y-2">
- <ol data-testid="workflow-phase-list">
- {phaseNames.map(name => {
- const phaseDef = definition?.phases.find(p => p.name === name);
- const state: WorkflowPhaseState = run.phaseStates[name] ?? {
- status: 'pending',
- outputs: [],
- };
- const isOpen = openPhases.includes(name);
- const hasOutputs = state.outputs.length > 0;
- return (
- <AccordionItem
- key={name}
- value={name}
- asChild
- className="rounded-xl border border-line bg-surface">
- <li data-testid={`workflow-phase-${name}`}>
- <AccordionTrigger
- showChevron={false}
- className="h-auto rounded-none px-3 py-2 font-normal hover:bg-transparent">
- <span className="flex min-w-0 items-center gap-2">
- <span className="truncate text-sm font-medium text-content">
- {phaseDef?.name ?? name}
- </span>
- <Badge
- variant={PHASE_STATUS_VARIANT[state.status]}
- data-testid={`workflow-phase-status-${name}`}>
- {t(PHASE_STATUS_KEY[state.status])}
- </Badge>
- </span>
- <span className="flex flex-none items-center gap-2 text-[11px] text-content-faint">
- {hasOutputs && (
- <span data-testid={`workflow-phase-count-${name}`}>
- {state.outputs.length} {t('orchestration.detail.agents')}
- </span>
- )}
- <span aria-hidden>{isOpen ? '▾' : '▸'}</span>
- </span>
- </AccordionTrigger>
-
- {phaseDef?.description && (
- <p className="px-3 pb-1 text-xs text-content-muted">{phaseDef.description}</p>
- )}
-
- {state.status === 'failed' && state.reason && (
- <p className="mx-3 mb-2 rounded-md bg-coral-50 px-2 py-1 text-xs text-coral-700 dark:bg-coral-500/10 dark:text-coral-300">
- {state.reason}
- </p>
- )}
-
- {/* Child agent refs for this phase */}
- {hasOutputs && (
- <AccordionContent
- className="px-0 pb-0"
- data-testid={`workflow-phase-outputs-${name}`}>
- <ul className="space-y-2 px-3 pb-3">
- {state.outputs.map((out, idx) => (
- <li
- key={`${out.orchestrationId}-${idx}`}
- className="rounded-lg border border-line-subtle bg-surface-muted p-2">
- <div className="flex flex-wrap items-center gap-1.5">
- <span className="text-xs font-medium text-content-secondary">
- {out.agentId}
- </span>
- <span className="font-mono text-[10px] text-content-faint">
- {out.orchestrationId}
- </span>
- </div>
- {out.output && (
- <p className="mt-1 whitespace-pre-wrap wrap-break-word text-xs leading-snug text-content-secondary">
- {out.output}
- </p>
- )}
- </li>
- ))}
- </ul>
- </AccordionContent>
- )}
- </li>
- </AccordionItem>
- );
- })}
- </ol>
- </AccordionRoot>
-
- {/* Child agent refs summary (full run-level list) */}
- {run.childRunIds.length > 0 && (
- <div className="text-[11px] text-content-faint" data-testid="workflow-child-refs">
- {t('orchestration.detail.childRefs')}: {run.childRunIds.length}
- </div>
- )}
-
- {/* Final synthesis */}
- {run.summary && TERMINAL_STATUSES.includes(run.status) && (
- <div
- data-testid="workflow-run-summary"
- className="rounded-xl border border-sage-200 bg-sage-50 p-3 dark:border-sage-500/30 dark:bg-sage-500/10">
- <p className="mb-1 text-xs font-semibold text-sage-800 dark:text-sage-200">
- {t('orchestration.detail.synthesis')}
- </p>
- <p className="whitespace-pre-wrap wrap-break-word text-sm leading-snug text-content-secondary">
- {run.summary}
- </p>
- </div>
- )}
- </div>
- );
-};
-
-export default WorkflowRunDetail;
diff --git a/app/src/components/intelligence/__tests__/MemoryChunkLetterhead.test.tsx b/app/src/components/intelligence/__tests__/MemoryChunkLetterhead.test.tsx
deleted file mode 100644
index e34621949d..0000000000
--- a/app/src/components/intelligence/__tests__/MemoryChunkLetterhead.test.tsx
+++ /dev/null
@@ -1,109 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-
-import type { Chunk } from '../../../utils/tauriCommands';
-import { MemoryChunkLetterhead } from '../MemoryChunkLetterhead';
-
-const BASE_CHUNK: Chunk = {
- id: 'chunk-letterhead-01',
- source_kind: 'email',
- source_ref: 'gmail://msg/abc',
- owner: '[email protected]',
- timestamp_ms: Date.UTC(2026, 4, 4, 9, 14, 0),
- token_count: 100,
- lifecycle_status: 'admitted',
- content_preview: 'hello',
- has_embedding: true,
- tags: [],
-};
-
-describe('MemoryChunkLetterhead', () => {
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it('renders the from/to/date frontmatter from a personalized email source', () => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date('2026-05-04T14:30:00'));
-
- const chunk: Chunk = {
- ...BASE_CHUNK,
- timestamp_ms: Date.now(),
- tags: ['person/Steven-Enamakel'],
- };
- render(<MemoryChunkLetterhead chunk={chunk} />);
-
- expect(screen.getByText('from')).toBeInTheDocument();
- expect(screen.getByText('to')).toBeInTheDocument();
- // Person tag wins over the raw email handle as the display name.
- expect(screen.getByText('Steven Enamakel')).toBeInTheDocument();
- // The raw address is rendered as secondary text.
- expect(screen.getByText('[email protected]')).toBeInTheDocument();
- expect(screen.getByText('[email protected]')).toBeInTheDocument();
- expect(screen.getByText('2026·05·04 · 14:30')).toBeInTheDocument();
- });
-
- it('formats the date using local time instead of UTC components', () => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date('2026-05-04T14:44:00'));
-
- const chunk: Chunk = { ...BASE_CHUNK, timestamp_ms: Date.now() };
- render(<MemoryChunkLetterhead chunk={chunk} />);
-
- expect(screen.getByText('2026·05·04 · 14:44')).toBeInTheDocument();
- });
-
- it('trims whitespace around source sender and recipient values', () => {
- const chunk: Chunk = {
- ...BASE_CHUNK,
- source_id: ' gmail:[email protected] | [email protected] ',
- };
- render(<MemoryChunkLetterhead chunk={chunk} />);
-
- expect(screen.getByText('[email protected]')).toBeInTheDocument();
- expect(screen.getByText('[email protected]')).toBeInTheDocument();
- });
-
- it('normalizes underscore-separated person tags for display', () => {
- const chunk: Chunk = { ...BASE_CHUNK, tags: ['person/Steven_Enamakel'] };
- render(<MemoryChunkLetterhead chunk={chunk} />);
-
- expect(screen.getByText('Steven Enamakel')).toBeInTheDocument();
- });
-
- it('falls back to the raw email when no person/* tag is present', () => {
- render(<MemoryChunkLetterhead chunk={BASE_CHUNK} />);
- // Without a person tag, fromName === the raw email.
- expect(screen.getByText('[email protected]')).toBeInTheDocument();
- });
-
- it('uses the owner when the parsed recipient is blank', () => {
- const chunk: Chunk = {
- ...BASE_CHUNK,
- source_id: 'gmail:[email protected]| ',
- owner: '[email protected]',
- };
- render(<MemoryChunkLetterhead chunk={chunk} />);
-
- expect(screen.getByText('[email protected]')).toBeInTheDocument();
- });
-
- it('falls back to the chunk owner when the source_id has no recipient half', () => {
- const chunk: Chunk = {
- ...BASE_CHUNK,
- source_id: 'notion:launch-plan',
- owner: '[email protected]',
- };
- render(<MemoryChunkLetterhead chunk={chunk} />);
- // No `|` → recipient defaults to owner.
- expect(screen.getByText('[email protected]')).toBeInTheDocument();
- });
-
- it('uses source_kind as the display when source_id is bare', () => {
- const chunk: Chunk = { ...BASE_CHUNK, source_kind: 'doc', source_id: '', tags: [] };
- render(<MemoryChunkLetterhead chunk={chunk} />);
- // Empty source_id → fromName falls back to the source_kind label.
- expect(screen.getByText('doc')).toBeInTheDocument();
- });
-});
diff --git a/app/src/components/intelligence/__tests__/MemoryChunkMentioned.test.tsx b/app/src/components/intelligence/__tests__/MemoryChunkMentioned.test.tsx
deleted file mode 100644
index db28ab1f0f..0000000000
--- a/app/src/components/intelligence/__tests__/MemoryChunkMentioned.test.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { EntityRef } from '../../../utils/tauriCommands';
-import { MemoryChunkMentioned } from '../MemoryChunkMentioned';
-
-const ENTITIES: EntityRef[] = [
- { entity_id: 'person:steve', kind: 'person', surface: 'Steven Enamakel', count: 4 },
- { entity_id: 'org:tinyhumans', kind: 'organization', surface: 'TinyHumans', count: 1 },
- { entity_id: 'event:launch', kind: 'event', surface: 'Phoenix launch', count: 7 },
-];
-
-describe('MemoryChunkMentioned', () => {
- it('renders nothing when the entity list is empty', () => {
- const { container } = render(<MemoryChunkMentioned entities={[]} onSelectEntity={vi.fn()} />);
- expect(container.firstChild).toBeNull();
- });
-
- it('renders one row per entity with kind, surface, and a pluralised count', () => {
- render(<MemoryChunkMentioned entities={ENTITIES} onSelectEntity={vi.fn()} />);
- expect(screen.getByText('Steven Enamakel')).toBeInTheDocument();
- expect(screen.getByText('TinyHumans')).toBeInTheDocument();
- expect(screen.getByText('Phoenix launch')).toBeInTheDocument();
-
- // Singular vs plural — the surface display has to switch on count.
- expect(screen.getByText('1 chunk')).toBeInTheDocument();
- expect(screen.getByText('4 chunks')).toBeInTheDocument();
- expect(screen.getByText('7 chunks')).toBeInTheDocument();
- });
-
- it('fires onSelectEntity with the clicked entity', () => {
- const onSelectEntity = vi.fn();
- render(<MemoryChunkMentioned entities={ENTITIES} onSelectEntity={onSelectEntity} />);
-
- fireEvent.click(screen.getByText('TinyHumans').closest('button')!);
- expect(onSelectEntity).toHaveBeenCalledTimes(1);
- expect(onSelectEntity).toHaveBeenCalledWith(ENTITIES[1]);
- });
-});
diff --git a/app/src/components/intelligence/__tests__/MemoryChunkScoreBars.test.tsx b/app/src/components/intelligence/__tests__/MemoryChunkScoreBars.test.tsx
deleted file mode 100644
index 7535dfb648..0000000000
--- a/app/src/components/intelligence/__tests__/MemoryChunkScoreBars.test.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { describe, expect, it } from 'vitest';
-
-import type { ScoreBreakdown } from '../../../utils/tauriCommands';
-import { MemoryChunkScoreBars } from '../MemoryChunkScoreBars';
-
-describe('MemoryChunkScoreBars', () => {
- it('renders one row per signal with a clamped, formatted value', () => {
- const breakdown: ScoreBreakdown = {
- total: 0.65,
- threshold: 0.5,
- kept: true,
- llm_consulted: false,
- signals: [
- { name: 'recency', weight: 0.5, value: 0.83 },
- { name: 'salience', weight: 0.3, value: 0.4 },
- // Out-of-range and NaN both clamp to 0..1 — the bar must not crash
- // or render past the track.
- { name: 'pinned', weight: 0.1, value: 1.7 },
- { name: 'broken', weight: 0.1, value: Number.NaN },
- ],
- };
- render(<MemoryChunkScoreBars breakdown={breakdown} />);
-
- expect(screen.getByText('recency')).toBeInTheDocument();
- expect(screen.getByText('0.83')).toBeInTheDocument();
- expect(screen.getByText('0.40')).toBeInTheDocument();
- // Clamped to 1.00 (over-range) and 0.00 (NaN).
- expect(screen.getByText('1.00')).toBeInTheDocument();
- expect(screen.getByText('0.00')).toBeInTheDocument();
-
- // ARIA labels on the bars are how a screen reader would surface the
- // percentage; check the over-range one collapsed to "100 percent".
- expect(screen.getByLabelText('pinned score 100 percent')).toBeInTheDocument();
- expect(screen.getByLabelText('broken score 0 percent')).toBeInTheDocument();
- });
-
- it('shows the threshold footer with kept/dropped state', () => {
- const breakdown: ScoreBreakdown = {
- total: 0.2,
- threshold: 0.5,
- kept: false,
- llm_consulted: false,
- signals: [{ name: 'recency', weight: 1, value: 0.2 }],
- };
- render(<MemoryChunkScoreBars breakdown={breakdown} />);
- expect(screen.getByText(/dropped at 0\.50/)).toBeInTheDocument();
- });
-});
diff --git a/app/src/components/intelligence/__tests__/MemoryOverview.test.tsx b/app/src/components/intelligence/__tests__/MemoryOverview.test.tsx
deleted file mode 100644
index 7f1de2f696..0000000000
--- a/app/src/components/intelligence/__tests__/MemoryOverview.test.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { MemoryHeatmap } from '../MemoryHeatmap';
-
-function localDayAt(daysAgo: number, hour: number, minute = 0): number {
- const d = new Date(Date.now());
- d.setHours(0, 0, 0, 0);
- d.setDate(d.getDate() - daysAgo);
- d.setHours(hour, minute, 0, 0);
- return d.getTime();
-}
-
-function paragraphMatching(pattern: RegExp) {
- return (_content: string, node: Element | null) =>
- node?.tagName.toLowerCase() === 'p' &&
- pattern.test((node.textContent ?? '').replace(/\s+/g, ' '));
-}
-
-describe('memory overview components', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date('2026-05-16T12:00:00Z'));
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it('renders the heatmap summary and hover tooltip', () => {
- const { container } = render(
- <MemoryHeatmap
- timestamps={[
- Math.floor(localDayAt(0, 0) / 1000),
- Math.floor(localDayAt(0, 0) / 1000),
- Math.floor(localDayAt(1, 0) / 1000),
- ]}
- />
- );
-
- expect(screen.getByRole('heading', { name: 'Ingestion Activity' })).toBeInTheDocument();
- expect(screen.getByText(/3 events over the last 8 months/)).toBeInTheDocument();
- expect(screen.getByText(paragraphMatching(/peak\s*:\s*2\/day/i))).toBeInTheDocument();
-
- const cells = container.querySelectorAll('svg rect[width="11"]');
- expect(cells.length).toBeGreaterThan(0);
- const targetCell = cells[cells.length - 1];
- expect(targetCell).toBeDefined();
- fireEvent.mouseEnter(targetCell);
- expect(screen.getByText(/events?$/)).toBeInTheDocument();
- });
-
- it('renders the heatmap loading skeleton', () => {
- const { container } = render(<MemoryHeatmap timestamps={[]} loading />);
-
- expect(screen.getByRole('heading', { name: 'Ingestion Activity' })).toBeInTheDocument();
- expect(container.querySelector('.animate-pulse')).toBeInTheDocument();
- });
-});
diff --git a/app/src/components/intelligence/__tests__/MemoryPresentation.test.tsx b/app/src/components/intelligence/__tests__/MemoryPresentation.test.tsx
deleted file mode 100644
index 1974e255cc..0000000000
--- a/app/src/components/intelligence/__tests__/MemoryPresentation.test.tsx
+++ /dev/null
@@ -1,120 +0,0 @@
-import { act, fireEvent, render, screen } from '@testing-library/react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import type { ActionableItem } from '../../../types/intelligence';
-import { ActionableCard } from '../ActionableCard';
-import { MemoryEmptyPlaceholder } from '../MemoryEmptyPlaceholder';
-import { MemoryStatsBar } from '../MemoryStatsBar';
-
-function makeActionableItem(overrides: Partial<ActionableItem> = {}): ActionableItem {
- const createdAt = new Date(Date.now() - 2 * 60 * 1000);
- return {
- id: 'action-1',
- title: 'Follow up with Alice',
- description: 'Send the investor update before the meeting.',
- source: 'email',
- sourceLabel: 'Gmail',
- priority: 'important',
- status: 'active',
- createdAt,
- updatedAt: createdAt,
- actionable: true,
- ...overrides,
- };
-}
-
-describe('memory presentation components', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date('2026-05-16T12:00:00Z'));
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it('renders the empty memory placeholder copy', () => {
- render(<MemoryEmptyPlaceholder />);
-
- expect(screen.getByTestId('memory-empty-placeholder')).toBeInTheDocument();
- expect(
- screen.getByRole('heading', { name: /Nothing yet|No memories yet/i })
- ).toBeInTheDocument();
- expect(
- screen.getByText(/Connect an integration in Settings|Start interacting/i)
- ).toBeInTheDocument();
- });
-
- it('formats memory stats and secondary labels', () => {
- render(
- <MemoryStatsBar
- totalDocs={1234}
- totalFiles={2}
- totalNamespaces={5}
- totalRelations={6}
- totalSessions={7}
- totalTokens={2048}
- estimatedStorageBytes={1536}
- oldestDocTimestamp={null}
- newestDocTimestamp={null}
- docsToday={3}
- />
- );
-
- expect(screen.getByText('Storage')).toBeInTheDocument();
- expect(screen.getByText('1.5 KB')).toBeInTheDocument();
- expect(screen.getByText('2 files')).toBeInTheDocument();
- expect(screen.getByText('Documents')).toBeInTheDocument();
- expect(screen.getByText(/^1[,.]234$/)).toBeInTheDocument();
- expect(screen.getByText('+3 today')).toBeInTheDocument();
- expect(screen.getByText('Sessions')).toBeInTheDocument();
- expect(screen.getByText(/^2[,.]048 tokens$/)).toBeInTheDocument();
- });
-
- it('renders actionable item details and fires direct actions', () => {
- const item = makeActionableItem();
- const onComplete = vi.fn();
- const onDismiss = vi.fn();
-
- render(
- <ActionableCard
- item={item}
- onComplete={onComplete}
- onDismiss={onDismiss}
- onSnooze={vi.fn()}
- />
- );
-
- expect(screen.getByText('Follow up with Alice')).toBeInTheDocument();
- expect(screen.getByText('Send the investor update before the meeting.')).toBeInTheDocument();
- expect(screen.getByText('Gmail')).toBeInTheDocument();
- expect(screen.getByText('2 mins ago')).toBeInTheDocument();
- expect(screen.getByText('New')).toBeInTheDocument();
-
- fireEvent.click(screen.getByTitle('Complete'));
- fireEvent.click(screen.getByTitle('Dismiss'));
-
- expect(onComplete).toHaveBeenCalledWith(item);
- expect(onDismiss).toHaveBeenCalledWith(item);
- });
-
- it('snoozes actionable items after the exit animation delay', async () => {
- const item = makeActionableItem();
- const onSnooze = vi.fn();
-
- render(
- <ActionableCard item={item} onComplete={vi.fn()} onDismiss={vi.fn()} onSnooze={onSnooze} />
- );
-
- fireEvent.click(screen.getByTitle('Snooze'));
- fireEvent.click(screen.getByRole('button', { name: '6 hours' }));
-
- expect(onSnooze).not.toHaveBeenCalled();
-
- await act(async () => {
- vi.advanceTimersByTime(200);
- });
-
- expect(onSnooze).toHaveBeenCalledWith(item, 6 * 60 * 60 * 1000);
- });
-});
diff --git a/app/src/components/intelligence/memberColors.test.ts b/app/src/components/intelligence/memberColors.test.ts
deleted file mode 100644
index bdbb5e9a00..0000000000
--- a/app/src/components/intelligence/memberColors.test.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { memberColor, memberTint } from './memberColors';
-
-const PALETTE = ['#4A83DD', '#34C759', '#E8A728', '#EF4444', '#0EA5E9', '#9B8AFB'];
-
-describe('memberColor', () => {
- it('is deterministic for the same id', () => {
- expect(memberColor('member-abc')).toBe(memberColor('member-abc'));
- });
-
- it('always returns a house-palette hue', () => {
- for (const id of ['a', 'bb', 'team-member-1', 'm-42', 'zzz']) {
- expect(PALETTE).toContain(memberColor(id));
- }
- });
-
- it('falls back to the first hue for empty/undefined ids', () => {
- expect(memberColor('')).toBe(PALETTE[0]);
- expect(memberColor(null)).toBe(PALETTE[0]);
- expect(memberColor(undefined)).toBe(PALETTE[0]);
- });
-
- it('spreads distinct ids across more than one hue', () => {
- const colors = new Set(['m1', 'm2', 'm3', 'm4', 'm5', 'm6'].map(memberColor));
- expect(colors.size).toBeGreaterThan(1);
- });
-});
-
-describe('memberTint', () => {
- it('appends the default alpha byte to the colour', () => {
- expect(memberTint('m1')).toBe(`${memberColor('m1')}1f`);
- });
-
- it('honours a custom alpha suffix', () => {
- expect(memberTint('m1', '33')).toBe(`${memberColor('m1')}33`);
- });
-});
diff --git a/app/src/components/intelligence/memberColors.ts b/app/src/components/intelligence/memberColors.ts
deleted file mode 100644
index b01a75a823..0000000000
--- a/app/src/components/intelligence/memberColors.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-/**
- * Deterministic member → colour mapping for the agent-team surface (#3374).
- *
- * A team member should read as the *same* colour everywhere it appears — the
- * owner left-border on a task card, the roster chip in the header, and the
- * avatar in the activity rail. Tailwind can't express a per-member dynamic
- * class (the class names aren't known at build time, so they'd be purged), so
- * the colour is resolved to a house-palette hex here and applied via inline
- * style at the call site — the same approach `memory-workspace.css` already
- * uses for the primary accent.
- *
- * The palette is drawn from the project's semantic tokens (primary / sage / amber
- * / coral / sky / lavender) so the board never introduces an off-brand hue.
- * Assignment is stable per member id: the same id always maps to the same
- * colour, and ids spread across the palette before repeating.
- */
-
-/** House-palette hues used to distinguish team members. Order is the cycle. */
-const MEMBER_PALETTE = [
- '#4A83DD', // primary (brand blue)
- '#34C759', // sage
- '#E8A728', // amber
- '#EF4444', // coral
- '#0EA5E9', // sky (darkened for contrast on white)
- '#9B8AFB', // lavender accent
-] as const;
-
-/** Stable, order-independent hash of a member id → palette bucket. */
-function hashId(id: string): number {
- let hash = 0;
- for (let i = 0; i < id.length; i += 1) {
- // Classic 31-multiplier string hash; `| 0` keeps it in 32-bit int range.
- hash = (hash * 31 + id.charCodeAt(i)) | 0;
- }
- return Math.abs(hash);
-}
-
-/**
- * Resolve a member id to a stable house-palette hex colour.
- *
- * @param memberId The member's durable id. Empty/undefined → first palette hue.
- */
-export function memberColor(memberId: string | null | undefined): string {
- if (!memberId) return MEMBER_PALETTE[0];
- return MEMBER_PALETTE[hashId(memberId) % MEMBER_PALETTE.length];
-}
-
-/**
- * A translucent tint of a member's colour, for chip/badge backgrounds. Appends
- * an alpha byte to the 6-digit hex (e.g. `#4A83DD` + `1f` → ~12% opacity).
- *
- * @param memberId The member's durable id.
- * @param alphaHex Two-hex-digit alpha suffix. Defaults to `1f` (~12%).
- */
-export function memberTint(memberId: string | null | undefined, alphaHex = '1f'): string {
- return `${memberColor(memberId)}${alphaHex}`;
-}
diff --git a/app/src/components/layout/TwoPanelLayout.test.tsx b/app/src/components/layout/TwoPanelLayout.test.tsx
deleted file mode 100644
index 3cd4abe490..0000000000
--- a/app/src/components/layout/TwoPanelLayout.test.tsx
+++ /dev/null
@@ -1,141 +0,0 @@
-import { fireEvent, screen } from '@testing-library/react';
-import { describe, expect, it } from 'vitest';
-
-import { renderWithProviders } from '../../test/test-utils';
-import TwoPanelLayout, { useTwoPanelLayout } from './TwoPanelLayout';
-
-function Sidebar() {
- return <div>sidebar-content</div>;
-}
-function Content() {
- return <div>main-content</div>;
-}
-
-describe('TwoPanelLayout', () => {
- it('renders only the content when the sidebar is hidden', () => {
- renderWithProviders(
- <TwoPanelLayout id="chat" sidebar={<Sidebar />}>
- <Content />
- </TwoPanelLayout>,
- {
- preloadedState: {
- layout: { panels: { chat: { sidebarVisible: false, sidebarWidth: 256 } } },
- },
- }
- );
- expect(screen.getByText('main-content')).toBeInTheDocument();
- expect(screen.queryByText('sidebar-content')).not.toBeInTheDocument();
- expect(screen.queryByTestId('two-panel-divider-chat')).not.toBeInTheDocument();
- });
-
- it('renders sidebar + divider when open and applies the persisted width', () => {
- renderWithProviders(
- <TwoPanelLayout id="chat" sidebar={<Sidebar />}>
- <Content />
- </TwoPanelLayout>,
- {
- preloadedState: {
- layout: { panels: { chat: { sidebarVisible: true, sidebarWidth: 300 } } },
- },
- }
- );
- expect(screen.getByText('sidebar-content')).toBeInTheDocument();
- const pane = screen.getByTestId('two-panel-sidebar-chat');
- expect(pane).toHaveStyle({ width: '300px' });
- expect(screen.getByTestId('two-panel-divider-chat')).toBeInTheDocument();
- });
-
- it('forceSidebarVisible overrides a hidden persisted state without mutating it', () => {
- const { store } = renderWithProviders(
- <TwoPanelLayout id="chat" sidebar={<Sidebar />} forceSidebarVisible>
- <Content />
- </TwoPanelLayout>,
- {
- preloadedState: {
- layout: { panels: { chat: { sidebarVisible: false, sidebarWidth: 256 } } },
- },
- }
- );
- expect(screen.getByText('sidebar-content')).toBeInTheDocument();
- expect(
- (store.getState() as { layout: { panels: Record<string, unknown> } }).layout.panels.chat
- ).toEqual({ sidebarVisible: false, sidebarWidth: 256 });
- });
-
- it('resizes via keyboard and clamps to the configured bounds', () => {
- const { store } = renderWithProviders(
- <TwoPanelLayout id="chat" sidebar={<Sidebar />} minSidebarWidth={180} maxSidebarWidth={480}>
- <Content />
- </TwoPanelLayout>,
- {
- preloadedState: {
- layout: { panels: { chat: { sidebarVisible: true, sidebarWidth: 300 } } },
- },
- }
- );
- const divider = screen.getByTestId('two-panel-divider-chat');
- const widthOf = () =>
- (store.getState() as { layout: { panels: Record<string, { sidebarWidth: number }> } }).layout
- .panels.chat.sidebarWidth;
-
- fireEvent.keyDown(divider, { key: 'ArrowRight' });
- expect(widthOf()).toBe(316);
- fireEvent.keyDown(divider, { key: 'ArrowLeft' });
- expect(widthOf()).toBe(300);
- });
-
- it('seeds default geometry for an unseen panel via ensurePanelLayout', () => {
- const { store } = renderWithProviders(
- <TwoPanelLayout
- id="fresh"
- sidebar={<Sidebar />}
- defaultSidebarVisible
- defaultSidebarWidth={222}>
- <Content />
- </TwoPanelLayout>
- );
- const panel = (store.getState() as { layout: { panels: Record<string, unknown> } }).layout
- .panels.fresh;
- expect(panel).toEqual({ sidebarVisible: true, sidebarWidth: 222 });
- });
-
- it('shows a reopen rail when collapsed and showCollapsedRail is set', () => {
- const { store } = renderWithProviders(
- <TwoPanelLayout id="chat" sidebar={<Sidebar />} showCollapsedRail>
- <Content />
- </TwoPanelLayout>,
- {
- preloadedState: {
- layout: { panels: { chat: { sidebarVisible: false, sidebarWidth: 256 } } },
- },
- }
- );
- const reopen = screen.getByTestId('two-panel-reopen-chat');
- fireEvent.click(reopen);
- expect(
- (store.getState() as { layout: { panels: Record<string, { sidebarVisible: boolean }> } })
- .layout.panels.chat.sidebarVisible
- ).toBe(true);
- });
-});
-
-describe('useTwoPanelLayout', () => {
- function Harness() {
- const { sidebarVisible, toggleSidebar } = useTwoPanelLayout('chat', { sidebarVisible: false });
- return (
- <button type="button" onClick={toggleSidebar}>
- {sidebarVisible ? 'open' : 'closed'}
- </button>
- );
- }
-
- it('reflects and toggles the same persisted state', () => {
- renderWithProviders(<Harness />);
- const btn = screen.getByRole('button');
- expect(btn).toHaveTextContent('closed');
- fireEvent.click(btn);
- expect(btn).toHaveTextContent('open');
- fireEvent.click(btn);
- expect(btn).toHaveTextContent('closed');
- });
-});
diff --git a/app/src/components/layout/TwoPanelLayout.tsx b/app/src/components/layout/TwoPanelLayout.tsx
deleted file mode 100644
index ef0bafbbcf..0000000000
--- a/app/src/components/layout/TwoPanelLayout.tsx
+++ /dev/null
@@ -1,328 +0,0 @@
-import { type ReactNode, useCallback, useEffect } from 'react';
-import { LuChevronRight } from 'react-icons/lu';
-
-import { cn } from '../../lib/cn';
-import { useT } from '../../lib/i18n/I18nContext';
-import { useAppDispatch, useAppSelector } from '../../store/hooks';
-import {
- ensurePanelLayout,
- type PanelLayout,
- selectPanelLayout,
- setSidebarVisible,
- setSidebarWidth,
- toggleSidebar,
-} from '../../store/layoutSlice';
-import { IS_DEV } from '../../utils/config';
-import { Button } from '../ui';
-import { clampWidth, useResizableDivider } from './useResizableDivider';
-
-const namespace = 'two-panel-layout';
-
-function debug(message: string, payload?: Record<string, unknown>) {
- if (IS_DEV) {
- console.debug(`[${namespace}] ${message}`, payload ?? {});
- }
-}
-
-/**
- * Subscribe to a two-pane layout's persisted geometry and get back the
- * helpers external chrome needs to drive it (e.g. a hamburger button living
- * in some other header). Reads the SAME slice state `TwoPanelLayout` renders
- * from, so toggles stay in sync.
- */
-export function useTwoPanelLayout(id: string, defaults?: Partial<PanelLayout>) {
- const dispatch = useAppDispatch();
- const layout = useAppSelector(selectPanelLayout(id, defaults));
-
- const show = useCallback(
- (visible: boolean) => dispatch(setSidebarVisible({ id, visible })),
- [dispatch, id]
- );
- const toggle = useCallback(() => dispatch(toggleSidebar({ id })), [dispatch, id]);
-
- return {
- sidebarVisible: layout.sidebarVisible,
- sidebarWidth: layout.sidebarWidth,
- showSidebar: show,
- toggleSidebar: toggle,
- };
-}
-
-interface TwoPanelLayoutProps {
- /** Stable id used as the persistence key for this layout's geometry. */
- id: string;
- /** Content of the mini sidebar (left pane). */
- sidebar: ReactNode;
- /** Main content (right pane). */
- children: ReactNode;
- /** Sidebar visibility on first ever mount (before any persisted state). */
- defaultSidebarVisible?: boolean;
- /** Sidebar width in px on first ever mount. */
- defaultSidebarWidth?: number;
- /** Minimum sidebar width while dragging. */
- minSidebarWidth?: number;
- /** Maximum sidebar width while dragging. */
- maxSidebarWidth?: number;
- /**
- * Force the sidebar open regardless of persisted state (e.g. an onboarding
- * lockdown where the sidebar must always show). The persisted preference is
- * untouched, so it restores once the force is lifted.
- */
- forceSidebarVisible?: boolean;
- /** Step (px) the keyboard divider moves per arrow press. */
- keyboardStep?: number;
- className?: string;
- sidebarClassName?: string;
- contentClassName?: string;
- /**
- * Shared appearance applied to BOTH panes — the card background, rounded
- * corners, border and shadow live here (not in the panes' own content) so
- * every two-pane screen gets a consistent look for free. Pass `''` to opt
- * out (e.g. a flush, borderless layout).
- */
- paneClassName?: string;
- /**
- * Show a thin rail with a reopen button when the sidebar is hidden. Defaults
- * to false because chat surfaces its own toggle in the header; standalone
- * uses can opt in.
- */
- showCollapsedRail?: boolean;
- /**
- * Show the visible grab handle on the resize divider. When false the divider
- * is still draggable (and shows a faint line on hover/focus) but renders no
- * resting holder — a cleaner look for screens that don't want the affordance
- * front-and-center. Defaults to true.
- */
- showDividerHandle?: boolean;
- /**
- * Join the two panes into a single bordered card with no gap between them: the
- * shared edge becomes a flush, hairline drag divider. This is the default for
- * every two-pane surface; pass `false` for the legacy split-card look with a
- * gutter divider (no current callers).
- */
- seamless?: boolean;
-}
-
-/** Default card look shared by both panes. */
-const DEFAULT_PANE_CLASS = 'bg-surface rounded-2xl shadow-soft border border-line';
-
-const DEFAULT_MIN_WIDTH = 180;
-const DEFAULT_MAX_WIDTH = 480;
-const DEFAULT_KEYBOARD_STEP = 16;
-
-/**
- * A reusable two-pane shell: a resizable mini sidebar on the left and main
- * content on the right. Visibility and the dragged width persist per `id` via
- * the Redux `layout` slice, so the layout is remembered across reloads.
- *
- * Resize: drag the divider between the panes (pointer) or focus it and use the
- * arrow keys. Width is clamped to [minSidebarWidth, maxSidebarWidth] and only
- * committed to the store on drag end to avoid thrashing redux-persist.
- *
- * ---
- *
- * CONVERGENCE DECISION (kept deliberately separate from `ui/Sidebar.tsx`):
- * this stays its own panel system rather than being rebuilt on
- * `SidebarProvider`/`Sidebar`/`SidebarRail`. Both are defensible in the
- * abstract — the shell sidebar is app-level chrome, this is an in-page
- * splitter — but the concrete reason is a real behavioral mismatch, not just
- * "different enough to leave alone":
- *
- * 1. **Persistence cadence is opposite by contract.** `SidebarRail`'s
- * `onWidthChange` fires on every pointermove frame (its own doc comment
- * says so — the shell mirrors width into a live `--sidebar-width` CSS var
- * for chrome reflow). This component commits to Redux **once**, on
- * pointer-up or a keyboard step, specifically to avoid thrashing
- * redux-persist. Building this on `SidebarRail` as-is would mean
- * dispatching on every drag frame; keeping the current commit-on-release
- * contract would mean not using `SidebarRail`'s own callback at all —
- * either way the primitive isn't actually doing the persistence work.
- * 2. **Visual grammar differs.** `Sidebar` assumes a single always-left
- * column composed with `SidebarInset` (a `m-3 rounded-2xl` inset card).
- * This component's default `seamless` mode joins BOTH panes into one
- * bordered card with a flush 1px hairline seam — there's no `Sidebar`
- * equivalent of that, and forcing it would mean reintroducing bespoke
- * layout around the primitive anyway.
- * 3. **Extra affordances with no `Sidebar` counterpart**: `showCollapsedRail`
- * (a reopen button occupying the seam when collapsed) and `seamless`
- * itself aren't expressible through `Sidebar`'s `collapsible` variants.
- *
- * What IS shared: the clamp + pointer-drag + keyboard-step *mechanics* now
- * live in `useResizableDivider` (this directory) rather than inline in this
- * component, specifically so they're one named, independently readable unit
- * instead of hand-rolled logic duplicated alongside `SidebarRail`'s own
- * (different-contract) version. See that hook's doc comment for the full
- * reasoning on why it isn't literally the same code as `SidebarRail`.
- */
-export default function TwoPanelLayout({
- id,
- sidebar,
- children,
- defaultSidebarVisible = false,
- defaultSidebarWidth,
- minSidebarWidth = DEFAULT_MIN_WIDTH,
- maxSidebarWidth = DEFAULT_MAX_WIDTH,
- forceSidebarVisible = false,
- keyboardStep = DEFAULT_KEYBOARD_STEP,
- className = '',
- sidebarClassName = '',
- contentClassName = '',
- paneClassName = DEFAULT_PANE_CLASS,
- showCollapsedRail = false,
- showDividerHandle = true,
- seamless = true,
-}: TwoPanelLayoutProps) {
- const { t } = useT();
- const dispatch = useAppDispatch();
- const layout = useAppSelector(
- selectPanelLayout(id, {
- sidebarVisible: defaultSidebarVisible,
- ...(defaultSidebarWidth != null ? { sidebarWidth: defaultSidebarWidth } : {}),
- })
- );
-
- // Seed persisted geometry from this component's defaults exactly once per id.
- useEffect(() => {
- dispatch(
- ensurePanelLayout({
- id,
- defaults: {
- sidebarVisible: defaultSidebarVisible,
- ...(defaultSidebarWidth != null ? { sidebarWidth: defaultSidebarWidth } : {}),
- },
- })
- );
- // Intentionally only on id change — defaults are a first-mount seed.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [id]);
-
- const isOpen = forceSidebarVisible || layout.sidebarVisible;
-
- const persistedWidth = clampWidth(layout.sidebarWidth, minSidebarWidth, maxSidebarWidth);
-
- const commitWidth = useCallback(
- (clamped: number) => {
- dispatch(setSidebarWidth({ id, width: clamped }));
- debug('commit width', { id, width: clamped });
- },
- [dispatch, id]
- );
-
- // Drag/keyboard mechanics (clamp + commit-on-release) live in a shared hook
- // — see `useResizableDivider` for why this isn't the same code as the shell
- // sidebar's `SidebarRail`.
- const {
- dragWidth,
- onPointerDown,
- onKeyDown: onDividerKeyDown,
- } = useResizableDivider({
- width: persistedWidth,
- minWidth: minSidebarWidth,
- maxWidth: maxSidebarWidth,
- keyboardStep,
- onCommit: commitWidth,
- });
-
- // Live width while dragging is kept local (and applied via inline style) so
- // we don't dispatch — and re-persist — on every pointer move.
- const width = dragWidth ?? persistedWidth;
-
- // In seamless mode the card lives on the wrapper that holds both panes, so the
- // panes themselves carry no border/rounding and sit flush against the divider.
- const paneCard = seamless ? '' : paneClassName;
-
- const panes = (
- <>
- {isOpen && (
- <>
- <div
- className={cn('shrink-0 min-w-0 overflow-hidden', paneCard, sidebarClassName)}
- style={{ width }}
- data-testid={`two-panel-sidebar-${id}`}>
- {sidebar}
- </div>
-
- {/* Drag handle / divider */}
- <div
- role="separator"
- aria-orientation="vertical"
- aria-label={t('layout.resizeSidebar')}
- aria-valuenow={Math.round(width)}
- aria-valuemin={minSidebarWidth}
- aria-valuemax={maxSidebarWidth}
- tabIndex={0}
- data-testid={`two-panel-divider-${id}`}
- data-analytics-id="two-panel-resize-divider"
- onPointerDown={onPointerDown}
- onKeyDown={onDividerKeyDown}
- className={
- seamless
- ? // Flush hairline seam: 1px visible line, wider invisible hit
- // area, highlights on hover/focus.
- 'group relative w-px shrink-0 cursor-col-resize select-none self-stretch bg-surface-strong focus:outline-hidden'
- : cn(
- 'group relative flex shrink-0 cursor-col-resize select-none items-center justify-center self-stretch focus:outline-hidden',
- // Tighter gutter between panes when there's no visible handle.
- showDividerHandle ? 'mx-1 w-3' : 'mx-0 w-1.5'
- )
- }
- title={t('layout.resizeSidebar')}>
- {seamless ? (
- <>
- {/* Wider transparent grab strip straddling the 1px seam; z-10
- keeps it above the adjacent panes so it stays grabbable. */}
- <span className="absolute inset-y-0 -left-1 -right-1 z-10" />
- {/* The seam line itself, brightened on hover/focus. */}
- <span className="absolute inset-0 transition-colors group-hover:bg-primary-400 group-focus:bg-primary-500" />
- </>
- ) : (
- /* Transparent hit area (full height) with a short grab handle
- centered vertically. When the handle is hidden it stays
- transparent at rest and only surfaces on hover/focus. */
- <span
- className={cn(
- 'h-10 w-1 rounded-full transition-colors group-hover:bg-primary-400 group-focus:bg-primary-500',
- // `line-strong` rather than a raw grey pair: the token
- // already carries the per-theme value the two palette classes
- // were hand-picking, so the handle tracks the theme.
- showDividerHandle ? 'bg-line-strong' : 'bg-transparent'
- )}
- />
- )}
- </div>
- </>
- )}
-
- {!isOpen && showCollapsedRail && (
- <Button
- variant="tertiary"
- iconOnly
- data-testid={`two-panel-reopen-${id}`}
- analyticsId="two-panel-reopen-sidebar"
- onClick={() => dispatch(setSidebarVisible({ id, visible: true }))}
- title={t('layout.showSidebar')}
- aria-label={t('layout.showSidebar')}
- // A full-height 24px seam grip rather than a button footprint: the
- // height, width and square corners are overridden, the focus ring and
- // hover fill come from Button.
- className="h-auto w-6 shrink-0 self-stretch rounded-none text-content-faint hover:text-primary-500">
- <LuChevronRight className="w-4 h-4" aria-hidden />
- </Button>
- )}
-
- <div className={cn('flex-1 min-w-0 overflow-hidden', paneCard, contentClassName)}>
- {children}
- </div>
- </>
- );
-
- return (
- <div className={cn('flex min-h-0', className)}>
- {seamless ? (
- <div className={cn('flex min-h-0 flex-1 overflow-hidden', DEFAULT_PANE_CLASS)}>{panes}</div>
- ) : (
- panes
- )}
- </div>
- );
-}
diff --git a/app/src/components/layout/shell/useHomeNav.test.tsx b/app/src/components/layout/shell/useHomeNav.test.tsx
deleted file mode 100644
index 8ce8ee0666..0000000000
--- a/app/src/components/layout/shell/useHomeNav.test.tsx
+++ /dev/null
@@ -1,150 +0,0 @@
-import { renderHook, waitFor } from '@testing-library/react';
-import type { ReactNode } from 'react';
-import { MemoryRouter } from 'react-router-dom';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { AGENT_ACCOUNT_ID } from '../../../utils/accountsFullscreen';
-import { useHomeNav } from './useHomeNav';
-
-// --- Mocks ------------------------------------------------------------------
-// Drive the real hook body while stubbing its router + store dependencies so
-// each branch (off-chat navigate, reuse-empty-thread, create-new-thread) runs
-// deterministically without a live core RPC.
-const mockNavigate = vi.fn();
-let mockPathname = '/home';
-vi.mock('react-router-dom', async importOriginal => {
- const actual = await importOriginal<typeof import('react-router-dom')>();
- return {
- ...actual,
- useNavigate: () => mockNavigate,
- useLocation: () => ({ pathname: mockPathname }),
- };
-});
-
-interface MockThread {
- id: string;
- messageCount: number;
-}
-
-interface MockAction {
- type?: string;
-}
-
-interface WrapperProps {
- children: ReactNode;
-}
-
-const mockDispatch = vi.fn();
-let mockThreads: MockThread[] = [];
-vi.mock('../../../store/hooks', () => ({
- useAppDispatch: () => mockDispatch,
- useAppSelector: (sel: (s: unknown) => unknown) => sel({ thread: { threads: mockThreads } }),
-}));
-
-// Tag each action creator so we can assert what was dispatched.
-vi.mock('../../../store/accountsSlice', () => ({
- setActiveAccount: vi.fn((id: string) => ({ type: 'accounts/setActiveAccount', payload: id })),
-}));
-vi.mock('../../../store/threadSlice', () => ({
- createNewThread: vi.fn(() => ({ type: 'thread/createNewThread' })),
- // The hook normalises a rejected `.unwrap()` (a bare string / SerializedError,
- // never an `Error`) before logging it (#5156).
- formatThreadCreateError: (error: unknown) =>
- error instanceof Error ? error.message : String(error),
- loadThreadMessages: vi.fn((id: string) => ({ type: 'thread/loadThreadMessages', payload: id })),
- setSelectedThread: vi.fn((id: string) => ({ type: 'thread/setSelectedThread', payload: id })),
-}));
-
-function wrapper({ children }: WrapperProps) {
- return <MemoryRouter>{children}</MemoryRouter>;
-}
-
-function dispatchedTypes() {
- return mockDispatch.mock.calls.map(([action]) => action?.type);
-}
-
-describe('useHomeNav', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- mockPathname = '/home';
- mockThreads = [];
- // createNewThread dispatch yields a thunk-style promise with .unwrap().
- mockDispatch.mockImplementation((action: MockAction) => {
- if (action?.type === 'thread/createNewThread') {
- return { unwrap: () => Promise.resolve({ id: 'fresh-thread' }) };
- }
- return undefined;
- });
- });
-
- it('switches to the agent account and navigates to chat when off-chat', () => {
- mockPathname = '/home';
- const { result } = renderHook(() => useHomeNav(), { wrapper });
- result.current();
-
- expect(dispatchedTypes()).toContain('accounts/setActiveAccount');
- expect(mockDispatch).toHaveBeenCalledWith({
- type: 'accounts/setActiveAccount',
- payload: AGENT_ACCOUNT_ID,
- });
- expect(mockNavigate).toHaveBeenCalledWith('/chat');
- // Off-chat path returns before touching threads.
- expect(dispatchedTypes()).not.toContain('thread/createNewThread');
- expect(dispatchedTypes()).not.toContain('thread/setSelectedThread');
- });
-
- it('reuses an existing empty thread when already on chat', () => {
- mockPathname = '/chat';
- mockThreads = [{ id: 'empty-1', messageCount: 0 }];
- const { result } = renderHook(() => useHomeNav(), { wrapper });
- result.current();
-
- expect(mockNavigate).toHaveBeenCalledWith('/chat/empty-1');
- expect(mockDispatch).toHaveBeenCalledWith({
- type: 'thread/setSelectedThread',
- payload: 'empty-1',
- });
- expect(mockDispatch).toHaveBeenCalledWith({
- type: 'thread/loadThreadMessages',
- payload: 'empty-1',
- });
- expect(dispatchedTypes()).not.toContain('thread/createNewThread');
- });
-
- it('creates a new thread when on chat with no empty thread', async () => {
- mockPathname = '/chat/abc';
- mockThreads = [{ id: 't-busy', messageCount: 4 }];
- const { result } = renderHook(() => useHomeNav(), { wrapper });
- result.current();
-
- expect(dispatchedTypes()).toContain('thread/createNewThread');
- // The freshly created thread is selected + loaded once the promise resolves.
- await waitFor(() => {
- expect(mockDispatch).toHaveBeenCalledWith({
- type: 'thread/setSelectedThread',
- payload: 'fresh-thread',
- });
- });
- expect(mockDispatch).toHaveBeenCalledWith({
- type: 'thread/loadThreadMessages',
- payload: 'fresh-thread',
- });
- expect(mockNavigate).toHaveBeenCalledWith('/chat/fresh-thread');
- });
-
- it('swallows a failed thread creation without throwing', async () => {
- mockPathname = '/chat';
- mockThreads = [{ id: 't-busy', messageCount: 2 }];
- mockDispatch.mockImplementation((action: MockAction) => {
- if (action?.type === 'thread/createNewThread') {
- return { unwrap: () => Promise.reject(new Error('boom')) };
- }
- return undefined;
- });
- const { result } = renderHook(() => useHomeNav(), { wrapper });
- expect(() => result.current()).not.toThrow();
- // Give the rejected promise a tick to settle through the .catch().
- await Promise.resolve();
- expect(dispatchedTypes()).toContain('thread/createNewThread');
- });
-});
diff --git a/app/src/components/layout/shell/useHomeNav.ts b/app/src/components/layout/shell/useHomeNav.ts
deleted file mode 100644
index 24c8b7f9d5..0000000000
--- a/app/src/components/layout/shell/useHomeNav.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { useCallback } from 'react';
-import { useLocation, useNavigate } from 'react-router-dom';
-
-import { setActiveAccount } from '../../../store/accountsSlice';
-import { useAppDispatch, useAppSelector } from '../../../store/hooks';
-import {
- createNewThread,
- formatThreadCreateError,
- loadThreadMessages,
- setSelectedThread,
-} from '../../../store/threadSlice';
-import { AGENT_ACCOUNT_ID } from '../../../utils/accountsFullscreen';
-import { chatThreadPath } from '../../../utils/chatRoutes';
-
-/**
- * The shell's "Home" action — shared by the sidebar header (expanded) and the
- * collapsed icon rail so both behave identically.
- *
- * Home → the unified chat on a blank thread. When we're NOT already on chat,
- * just navigate and let the mounting Conversations page own blank-thread landing
- * (avoids a duplicate-create race). When already on chat (no remount), reset to
- * a blank thread here: reuse an existing empty one, else create one.
- */
-export function useHomeNav(): () => void {
- const navigate = useNavigate();
- const location = useLocation();
- const dispatch = useAppDispatch();
- const threads = useAppSelector(state => state.thread.threads);
-
- return useCallback(() => {
- // Switch back to the agent account first — otherwise a selected connected
- // app (WhatsApp/Slack/…) keeps Accounts rendering its webview instead of the
- // blank agent thread.
- dispatch(setActiveAccount(AGENT_ACCOUNT_ID));
- const onChat = location.pathname === '/chat' || location.pathname.startsWith('/chat/');
- if (!onChat) {
- navigate('/chat');
- return;
- }
- const empty = threads.find(thr => (thr.messageCount ?? 0) === 0);
- if (empty) {
- dispatch(setSelectedThread(empty.id));
- void dispatch(loadThreadMessages(empty.id));
- navigate(chatThreadPath(empty.id));
- return;
- }
- void dispatch(createNewThread())
- .unwrap()
- .then(thr => {
- dispatch(setSelectedThread(thr.id));
- void dispatch(loadThreadMessages(thr.id));
- navigate(chatThreadPath(thr.id));
- })
- .catch(err => {
- // The rejection MUST stay consumed here — unconsumed it becomes
- // `UnhandledRejection: Core RPC openhuman.threads_create_new timed out
- // after 30000ms` (#5156). Swallowing it silently was the other half of
- // that bug: Home did nothing and said nothing. The user-visible surface
- // is `thread.createThreadError`, which the chat page renders; this log
- // keeps the cause diagnosable.
- console.error('[home-nav] createNewThread failed', formatThreadCreateError(err));
- });
- }, [navigate, location.pathname, dispatch, threads]);
-}
diff --git a/app/src/components/layout/useResizableDivider.ts b/app/src/components/layout/useResizableDivider.ts
deleted file mode 100644
index 9dd6464d02..0000000000
--- a/app/src/components/layout/useResizableDivider.ts
+++ /dev/null
@@ -1,122 +0,0 @@
-import { useCallback, useLayoutEffect, useRef, useState } from 'react';
-
-/**
- * Pointer-drag + keyboard resize mechanics for a single divider, with the
- * "commit on release" persistence contract `TwoPanelLayout` needs: live drag
- * width is kept in local state (applied via inline style) and only handed to
- * `onCommit` once, on pointer-up or a keyboard step — never on every
- * pointermove frame — so a Redux-persisted store isn't thrashed mid-drag.
- *
- * This is deliberately NOT shared code with `ui/Sidebar.tsx`'s `SidebarRail`:
- * that primitive's `onWidthChange` fires on every drag frame by contract (its
- * own doc comment says so) because the shell mirrors sidebar width into
- * `--sidebar-width` for live layout reflow. `TwoPanelLayout`'s panes don't
- * need that — they resize from local `dragWidth` state — and persisting on
- * every frame is exactly what this hook exists to avoid. Pulled out of the
- * component body into its own hook so the clamp/drag/keyboard logic is one
- * named, independently readable unit rather than duplicated inline should a
- * second two-pane splitter appear in this directory.
- */
-export function clampWidth(width: number, min: number, max: number): number {
- return Math.min(Math.max(width, min), max);
-}
-
-interface UseResizableDividerOptions {
- /** Current persisted width, used as the drag/keyboard starting point. */
- width: number;
- minWidth: number;
- maxWidth: number;
- keyboardStep: number;
- /** Called once per drag (on release) or once per arrow-key press, with the final clamped width. */
- onCommit: (width: number) => void;
-}
-
-interface UseResizableDividerResult {
- /** Live width while dragging (`null` when not dragging) — apply via inline style, falling back to the persisted width. */
- dragWidth: number | null;
- onPointerDown: (e: React.PointerEvent) => void;
- onKeyDown: (e: React.KeyboardEvent) => void;
-}
-
-export function useResizableDivider({
- width,
- minWidth,
- maxWidth,
- keyboardStep,
- onCommit,
-}: UseResizableDividerOptions): UseResizableDividerResult {
- const [dragWidth, setDragWidth] = useState<number | null>(null);
- const dragWidthRef = useRef<number | null>(null);
-
- const commitWidth = useCallback(
- (next: number) => {
- onCommit(clampWidth(Math.round(next), minWidth, maxWidth));
- },
- [onCommit, minWidth, maxWidth]
- );
-
- // Active-drag teardown, stashed so an unmount mid-drag can detach the global
- // listeners. Each drag installs locally-scoped `pointermove`/`pointerup`
- // handlers (hoisted function declarations so they can reference each other),
- // keeping the resize self-contained without inter-callback dependencies.
- const dragCleanupRef = useRef<(() => void) | null>(null);
-
- const onPointerDown = useCallback(
- (e: React.PointerEvent) => {
- e.preventDefault();
- const startX = e.clientX;
- const startWidth = width;
- dragWidthRef.current = startWidth;
- setDragWidth(startWidth);
- document.body.style.cursor = 'col-resize';
- document.body.style.userSelect = 'none';
-
- function handleMove(ev: PointerEvent) {
- const next = clampWidth(startWidth + (ev.clientX - startX), minWidth, maxWidth);
- dragWidthRef.current = next;
- setDragWidth(next);
- }
- function detach() {
- window.removeEventListener('pointermove', handleMove);
- window.removeEventListener('pointerup', stop);
- document.body.style.removeProperty('cursor');
- document.body.style.removeProperty('user-select');
- dragCleanupRef.current = null;
- }
- function stop() {
- detach();
- const finalWidth = dragWidthRef.current;
- dragWidthRef.current = null;
- setDragWidth(null);
- if (finalWidth != null) commitWidth(finalWidth);
- }
-
- dragCleanupRef.current = detach;
- window.addEventListener('pointermove', handleMove);
- window.addEventListener('pointerup', stop);
- },
- [width, minWidth, maxWidth, commitWidth]
- );
-
- // Detach global listeners if we unmount mid-drag.
- useLayoutEffect(() => {
- return () => {
- dragCleanupRef.current?.();
- };
- }, []);
-
- const onKeyDown = useCallback(
- (e: React.KeyboardEvent) => {
- if (e.key === 'ArrowLeft') {
- e.preventDefault();
- commitWidth(width - keyboardStep);
- } else if (e.key === 'ArrowRight') {
- e.preventDefault();
- commitWidth(width + keyboardStep);
- }
- },
- [commitWidth, width, keyboardStep]
- );
-
- return { dragWidth, onPointerDown, onKeyDown };
-}
diff --git a/app/src/components/routines/routineHelpers.test.ts b/app/src/components/routines/routineHelpers.test.ts
deleted file mode 100644
index 66bcaf4daa..0000000000
--- a/app/src/components/routines/routineHelpers.test.ts
+++ /dev/null
@@ -1,148 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { cronToHuman, formatDuration, formatNextRun, formatRoutineName } from './routineHelpers';
-
-describe('cronToHuman', () => {
- it('handles "every" schedule kind', () => {
- expect(cronToHuman({ kind: 'every', every_ms: 30_000 })).toBe('Every 30 seconds');
- expect(cronToHuman({ kind: 'every', every_ms: 1_800_000 })).toBe('Every 30 minutes');
- expect(cronToHuman({ kind: 'every', every_ms: 3_600_000 })).toBe('Every 1 hour');
- expect(cronToHuman({ kind: 'every', every_ms: 7_200_000 })).toBe('Every 2 hours');
- });
-
- it('handles "at" schedule kind', () => {
- const result = cronToHuman({ kind: 'at', at: '2026-05-28T07:00:00Z' });
- expect(result).toMatch(/^Once at /);
- });
-
- it('parses every-minute cron', () => {
- expect(cronToHuman({ kind: 'cron', expr: '* * * * *' })).toBe('Every minute');
- });
-
- it('parses every-N-minutes cron', () => {
- expect(cronToHuman({ kind: 'cron', expr: '*/30 * * * *' })).toBe('Every 30 minutes');
- expect(cronToHuman({ kind: 'cron', expr: '*/5 * * * *' })).toBe('Every 5 minutes');
- });
-
- it('parses every-hour cron', () => {
- expect(cronToHuman({ kind: 'cron', expr: '0 * * * *' })).toBe('Every hour');
- });
-
- it('parses every-N-hours cron', () => {
- expect(cronToHuman({ kind: 'cron', expr: '0 */2 * * *' })).toBe('Every 2 hours');
- });
-
- it('parses daily at specific time', () => {
- expect(cronToHuman({ kind: 'cron', expr: '0 7 * * *' })).toBe('Every day at 7:00 AM');
- expect(cronToHuman({ kind: 'cron', expr: '30 14 * * *' })).toBe('Every day at 2:30 PM');
- expect(cronToHuman({ kind: 'cron', expr: '0 0 * * *' })).toBe('Every day at 12:00 AM');
- expect(cronToHuman({ kind: 'cron', expr: '0 12 * * *' })).toBe('Every day at 12:00 PM');
- });
-
- it('appends timezone when present', () => {
- expect(cronToHuman({ kind: 'cron', expr: '0 9 * * *', tz: 'America/New_York' })).toBe(
- 'Every day at 9:00 AM (America/New_York)'
- );
- });
-
- it('parses weekday schedule', () => {
- expect(cronToHuman({ kind: 'cron', expr: '0 9 * * 1-5' })).toBe('Weekdays at 9:00 AM');
- });
-
- it('parses weekend schedule', () => {
- expect(cronToHuman({ kind: 'cron', expr: '0 10 * * 0,6' })).toBe('Weekends at 10:00 AM');
- expect(cronToHuman({ kind: 'cron', expr: '0 10 * * 6,0' })).toBe('Weekends at 10:00 AM');
- });
-
- it('parses specific day of week', () => {
- expect(cronToHuman({ kind: 'cron', expr: '0 8 * * 1' })).toBe('Every Monday at 8:00 AM');
- expect(cronToHuman({ kind: 'cron', expr: '0 18 * * 5' })).toBe('Every Friday at 6:00 PM');
- });
-
- it('parses specific day of month', () => {
- expect(cronToHuman({ kind: 'cron', expr: '0 9 1 * *' })).toBe(
- 'On the 1st of every month at 9:00 AM'
- );
- expect(cronToHuman({ kind: 'cron', expr: '0 9 15 * *' })).toBe(
- 'On the 15th of every month at 9:00 AM'
- );
- expect(cronToHuman({ kind: 'cron', expr: '0 9 2 * *' })).toBe(
- 'On the 2nd of every month at 9:00 AM'
- );
- expect(cronToHuman({ kind: 'cron', expr: '0 9 3 * *' })).toBe(
- 'On the 3rd of every month at 9:00 AM'
- );
- });
-
- it('falls back to raw expression for complex patterns', () => {
- expect(cronToHuman({ kind: 'cron', expr: '0 9 1,15 * *' })).toBe('0 9 1,15 * *');
- expect(cronToHuman({ kind: 'cron', expr: '*/5 9-17 * * 1-5' })).toBe('*/5 9-17 * * 1-5');
- });
-});
-
-describe('formatRoutineName', () => {
- it('converts snake_case to Title Case', () => {
- expect(formatRoutineName('morning_briefing')).toBe('Morning Briefing');
- });
-
- it('converts kebab-case to Title Case', () => {
- expect(formatRoutineName('daily-standup')).toBe('Daily Standup');
- });
-
- it('returns Untitled Routine for empty/null/undefined', () => {
- expect(formatRoutineName(null)).toBe('Untitled Routine');
- expect(formatRoutineName(undefined)).toBe('Untitled Routine');
- expect(formatRoutineName('')).toBe('Untitled Routine');
- });
-
- it('handles already-formatted names', () => {
- expect(formatRoutineName('Morning Briefing')).toBe('Morning Briefing');
- });
-});
-
-describe('formatNextRun', () => {
- // Offsets are kept well clear of bucket boundaries so the few-ms test
- // execution delay (formatNextRun reads `new Date()` internally) can't flip
- // the result.
- const inMs = (ms: number) => new Date(Date.now() + ms).toISOString();
-
- it('does not render "in 0 hours" just under an hour out (#3757 regression)', () => {
- // 59m 45s away — used to round minutes up to 60, skip the minute branch,
- // then floor hours to 0 → "in 0 hours".
- const out = formatNextRun(inMs(59 * 60_000 + 45_000));
- expect(out).not.toContain('0 hour');
- expect(out).toBe('in 59 minutes');
- });
-
- it('crosses into hours only at/after 60 minutes', () => {
- expect(formatNextRun(inMs(60 * 60_000 + 30_000))).toBe('in 1 hour');
- expect(formatNextRun(inMs(2 * 60 * 60_000 + 30_000))).toBe('in 2 hours');
- });
-
- it('reports sub-minute and minute ranges', () => {
- expect(formatNextRun(inMs(20_000))).toBe('in less than a minute');
- expect(formatNextRun(inMs(60_000 + 30_000))).toBe('in 1 minute');
- expect(formatNextRun(inMs(5 * 60_000 + 30_000))).toBe('in 5 minutes');
- });
-
- it('renders a past timestamp as an absolute locale string, not a relative one', () => {
- const out = formatNextRun(inMs(-60_000));
- expect(out).not.toContain('in ');
- });
-});
-
-describe('formatDuration', () => {
- it('formats milliseconds', () => {
- expect(formatDuration(500)).toBe('500ms');
- });
-
- it('formats seconds', () => {
- expect(formatDuration(3000)).toBe('3s');
- expect(formatDuration(45_000)).toBe('45s');
- });
-
- it('formats minutes and seconds', () => {
- expect(formatDuration(72_000)).toBe('1m 12s');
- expect(formatDuration(120_000)).toBe('2m');
- });
-});
diff --git a/app/src/components/routines/routineHelpers.ts b/app/src/components/routines/routineHelpers.ts
deleted file mode 100644
index aebd609f2b..0000000000
--- a/app/src/components/routines/routineHelpers.ts
+++ /dev/null
@@ -1,169 +0,0 @@
-import type { CoreCronSchedule } from '../../utils/tauriCommands';
-
-/** Day names indexed by cron day-of-week (0 = Sunday). */
-const WEEKDAY_NAMES = [
- 'Sunday',
- 'Monday',
- 'Tuesday',
- 'Wednesday',
- 'Thursday',
- 'Friday',
- 'Saturday',
-];
-
-function formatHour(hour: number, minute: number): string {
- const period = hour >= 12 ? 'PM' : 'AM';
- const h = hour % 12 || 12;
- const m = minute.toString().padStart(2, '0');
- return `${h}:${m} ${period}`;
-}
-
-/**
- * Convert a CoreCronSchedule to a human-readable string.
- *
- * Covers common patterns; falls back to the raw expression for anything exotic.
- */
-export function cronToHuman(schedule: CoreCronSchedule): string {
- if (schedule.kind === 'at') {
- return `Once at ${new Date(schedule.at).toLocaleString()}`;
- }
-
- if (schedule.kind === 'every') {
- const ms = schedule.every_ms;
- if (ms < 60_000) {
- const secs = Math.round(ms / 1000);
- return `Every ${secs} second${secs !== 1 ? 's' : ''}`;
- }
- if (ms < 3_600_000) {
- const mins = Math.round(ms / 60_000);
- return `Every ${mins} minute${mins !== 1 ? 's' : ''}`;
- }
- const hrs = Math.round(ms / 3_600_000);
- return `Every ${hrs} hour${hrs !== 1 ? 's' : ''}`;
- }
-
- // kind === 'cron'
- const expr = schedule.expr.trim();
- const parts = expr.split(/\s+/);
- if (parts.length < 5) return expr;
-
- const [minPart, hourPart, domPart, monPart, dowPart] = parts;
-
- // Every minute: * * * * *
- if (minPart === '*' && hourPart === '*' && domPart === '*' && monPart === '*' && dowPart === '*')
- return 'Every minute';
-
- // Every N minutes: */N * * * *
- const everyMinMatch = minPart.match(/^\*\/(\d+)$/);
- if (everyMinMatch && hourPart === '*' && domPart === '*' && monPart === '*' && dowPart === '*') {
- const n = parseInt(everyMinMatch[1], 10);
- return `Every ${n} minute${n !== 1 ? 's' : ''}`;
- }
-
- // Every hour: 0 * * * *
- if (minPart === '0' && hourPart === '*' && domPart === '*' && monPart === '*' && dowPart === '*')
- return 'Every hour';
-
- // Every N hours: 0 */N * * *
- const everyHourMatch = hourPart.match(/^\*\/(\d+)$/);
- if (minPart === '0' && everyHourMatch && domPart === '*' && monPart === '*' && dowPart === '*') {
- const n = parseInt(everyHourMatch[1], 10);
- return `Every ${n} hour${n !== 1 ? 's' : ''}`;
- }
-
- // Fixed time patterns (minute and hour are numeric)
- const min = parseInt(minPart, 10);
- const hour = parseInt(hourPart, 10);
- if (isNaN(min) || isNaN(hour)) return expr;
-
- const timeStr = formatHour(hour, min);
- const tz = schedule.tz ? ` (${schedule.tz})` : '';
-
- // Every day at H:MM: M H * * *
- if (domPart === '*' && monPart === '*' && dowPart === '*') return `Every day at ${timeStr}${tz}`;
-
- // Weekdays: M H * * 1-5
- if (domPart === '*' && monPart === '*' && dowPart === '1-5') return `Weekdays at ${timeStr}${tz}`;
-
- // Weekends: M H * * 0,6 or 6,0
- if (domPart === '*' && monPart === '*' && (dowPart === '0,6' || dowPart === '6,0'))
- return `Weekends at ${timeStr}${tz}`;
-
- // Specific day of week: M H * * D
- if (domPart === '*' && monPart === '*' && /^\d$/.test(dowPart)) {
- const dayIndex = parseInt(dowPart, 10);
- const dayName = WEEKDAY_NAMES[dayIndex];
- if (dayName) return `Every ${dayName} at ${timeStr}${tz}`;
- }
-
- // Specific day of month: M H D * *
- if (monPart === '*' && dowPart === '*' && /^\d{1,2}$/.test(domPart)) {
- const day = parseInt(domPart, 10);
- const suffix =
- day === 1 || day === 21 || day === 31
- ? 'st'
- : day === 2 || day === 22
- ? 'nd'
- : day === 3 || day === 23
- ? 'rd'
- : 'th';
- return `On the ${day}${suffix} of every month at ${timeStr}${tz}`;
- }
-
- // Fallback
- return expr;
-}
-
-/**
- * Convert a snake_case or kebab-case job name to Title Case.
- */
-export function formatRoutineName(name?: string | null): string {
- if (!name) return 'Untitled Routine';
- return name.replace(/[_-]/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
-}
-
-/**
- * Format a future ISO timestamp as a friendly relative string.
- */
-export function formatNextRun(iso: string): string {
- const target = new Date(iso);
- const now = new Date();
- const diffMs = target.getTime() - now.getTime();
-
- if (diffMs < 0) return target.toLocaleString();
-
- // Floor (not round) so a value just under an hour stays in the minute branch.
- // Rounding pushed [59.5, 60) min up to 60, skipping this branch; the hour
- // branch then floored to 0 and rendered "in 0 hours" (#3757).
- const diffMin = Math.floor(diffMs / 60_000);
- if (diffMin < 1) return 'in less than a minute';
- if (diffMin < 60) return `in ${diffMin} minute${diffMin !== 1 ? 's' : ''}`;
-
- const diffHrs = Math.floor(diffMs / 3_600_000);
- if (diffHrs < 24) return `in ${diffHrs} hour${diffHrs !== 1 ? 's' : ''}`;
-
- // Check if it's tomorrow
- const tomorrow = new Date(now);
- tomorrow.setDate(tomorrow.getDate() + 1);
- if (
- target.getDate() === tomorrow.getDate() &&
- target.getMonth() === tomorrow.getMonth() &&
- target.getFullYear() === tomorrow.getFullYear()
- ) {
- return `Tomorrow at ${formatHour(target.getHours(), target.getMinutes())}`;
- }
-
- return target.toLocaleString();
-}
-
-/**
- * Format duration_ms into a compact string like "3s" or "1m 12s".
- */
-export function formatDuration(ms: number): string {
- if (ms < 1000) return `${ms}ms`;
- const totalSec = Math.round(ms / 1000);
- if (totalSec < 60) return `${totalSec}s`;
- const min = Math.floor(totalSec / 60);
- const sec = totalSec % 60;
- return sec > 0 ? `${min}m ${sec}s` : `${min}m`;
-}
diff --git a/app/src/features/conversations/components/aui/InferenceStatusLine.test.tsx b/app/src/features/conversations/components/aui/InferenceStatusLine.test.tsx
deleted file mode 100644
index 37b5d651a4..0000000000
--- a/app/src/features/conversations/components/aui/InferenceStatusLine.test.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- * `InferenceStatusLine` renders every phase, including `thinking`.
- *
- * On `/chat` (`AssistantUiChat`) assistant-ui paints its own pulsing `●` during
- * the pre-first-token gap, so a `Thinking... (N)` caption there would be a
- * second indicator stacked under the library's. That duplicate is suppressed at
- * the assistant-ui caller (`AssistantUiInferenceStatus` returns null for
- * `thinking`), not by deleting the branch from this component, which stays a
- * complete renderer for any caller that has no indicator of its own.
- */
-import { screen } from '@testing-library/react';
-import { describe, expect, it } from 'vitest';
-
-import { I18nProvider } from '../../../../lib/i18n/I18nContext';
-import { renderWithProviders } from '../../../../test/test-utils';
-import { InferenceStatusLine } from './InferenceStatusLine';
-
-// `I18nProvider` reads `state.locale.current`, so the line needs a store; the
-// shared helper supplies the same reducer set the app mounts.
-function renderLine(status: { phase: string; iteration: number }) {
- return renderWithProviders(
- <I18nProvider>
- <InferenceStatusLine status={status} />
- </I18nProvider>
- );
-}
-
-describe('InferenceStatusLine — the legacy surface still gets a thinking caption', () => {
- it('captions the thinking phase with the iteration count', () => {
- renderLine({ phase: 'thinking', iteration: 3 });
- // The legacy surface has no library dot, so a bare pulse with no words is
- // indistinguishable from a stalled turn.
- expect(screen.getByTestId('inference-status-line').textContent).toContain('3');
- expect(screen.getByTestId('inference-status-line').textContent).toMatch(/Thinking/i);
- });
-
- it('captions the thinking phase without a count before the first iteration', () => {
- renderLine({ phase: 'thinking', iteration: 0 });
- const text = screen.getByTestId('inference-status-line').textContent ?? '';
- expect(text).toMatch(/Thinking/i);
- // `Thinking... (0)` would be worse than no number at all.
- expect(text).not.toContain('(0)');
- });
-
- it('renders the line with a caption, not an empty pulse', () => {
- // The regression this guards is specifically "renders, but says nothing":
- // the element was still present, so a presence assertion would have passed
- // while the user saw a bare dot.
- renderLine({ phase: 'thinking', iteration: 1 });
- const text = (screen.getByTestId('inference-status-line').textContent ?? '').trim();
- expect(text.length).toBeGreaterThan(0);
- });
-});
diff --git a/app/src/features/conversations/components/aui/InferenceStatusLine.tsx b/app/src/features/conversations/components/aui/InferenceStatusLine.tsx
deleted file mode 100644
index 7543a1f7f4..0000000000
--- a/app/src/features/conversations/components/aui/InferenceStatusLine.tsx
+++ /dev/null
@@ -1,86 +0,0 @@
-import { useT } from '../../../../lib/i18n/I18nContext';
-import type { ToolTimelineEntry } from '../../../../store/chatRuntimeSlice';
-import { formatTimelineEntry } from '../../../../utils/toolTimelineFormatting';
-
-export interface InferenceStatusLineProps {
- status: {
- phase: 'thinking' | 'tool_use' | 'subagent' | string;
- iteration: number;
- activeTool?: string;
- activeSubagent?: string;
- };
- /** The newest running non-subagent row, used to title the `tool_use` phase. */
- activeToolEntry?: ToolTimelineEntry;
- /** The running subagent row, used to title the `subagent` phase. */
- activeSubagentEntry?: ToolTimelineEntry;
-}
-
-/**
- * The one-line "what is the model doing right now" indicator.
- *
- * For the `tool_use` / `subagent` phases this only restates the active row the
- * agentic-task-insights timeline already shows, so the caller suppresses it
- * once that timeline is on screen, and keeps it when there is no timeline row
- * to fall back on.
- *
- * The `thinking` branch renders `Thinking... (N)`. On the assistant-ui surface
- * that caption WOULD stack a second indicator under
- * the library's own, and the `(N)` is the harness's iteration counter, internal
- * telemetry a reader cannot act on. That is suppressed one layer up:
- * `AssistantUiInferenceStatus` returns null for `thinking` before reaching this
- * component — see its doc comment for what the library's marker actually is (a
- * message-level synthetic `indicator` part, not a CSS rule on `.aui-md`) and why
- * that is precisely why this surface has no equivalent.
- *
- * So the suppression is per-surface, at the surface-specific caller, and this
- * component stays a complete renderer for every phase.
- */
-export function InferenceStatusLine({
- status,
- activeToolEntry,
- activeSubagentEntry,
-}: InferenceStatusLineProps) {
- // `AssistantUiInferenceStatus` returns null for `thinking` before it ever
- // reaches this component, so the caption below cannot stack under
- // assistant-ui's own `●` (a message-level `indicator` part).
- const { t } = useT();
- return (
- <div
- data-testid="inference-status-line"
- className="flex items-center gap-2 px-1 py-1.5 text-xs text-content-muted">
- <span className="inline-block w-2 h-2 rounded-full bg-primary-400 animate-pulse" />
- <span>
- {status.phase === 'thinking' &&
- (status.iteration > 0
- ? t('chat.thinkingIteration').replace('{n}', String(status.iteration))
- : t('chat.thinkingDots'))}
- {status.phase === 'tool_use' &&
- `${
- formatTimelineEntry(
- activeToolEntry ?? {
- id: 'active-tool',
- name: status.activeTool ?? 'tool',
- round: status.iteration,
- seq: 0,
- status: 'running',
- },
- t
- ).title
- }...`}
- {status.phase === 'subagent' &&
- `${
- formatTimelineEntry(
- activeSubagentEntry ?? {
- id: 'active-subagent',
- name: `subagent:${status.activeSubagent ?? ''}`,
- round: status.iteration,
- seq: 0,
- status: 'running',
- },
- t
- ).title
- }...`}
- </span>
- </div>
- );
-}
diff --git a/app/src/features/human/Mascot/backend/BackendMascot.test.tsx b/app/src/features/human/Mascot/backend/BackendMascot.test.tsx
deleted file mode 100644
index cb11d060aa..0000000000
--- a/app/src/features/human/Mascot/backend/BackendMascot.test.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-import { cleanup, render } from '@testing-library/react';
-import { afterEach, describe, expect, it } from 'vitest';
-
-import { BackendMascot } from './BackendMascot';
-import type { MascotDetail } from './types';
-
-const detail: MascotDetail = {
- id: 'test',
- name: 'Test',
- version: '0.0.0',
- description: '',
- viewBox: '0 0 100 100',
- defaultState: 'idle',
- variables: [],
- visemeSlot: '#m-viseme',
- hidesOnViseme: ['m-smile'],
- states: [
- {
- id: 'idle',
- label: 'Idle',
- description: '',
- svg: `<svg viewBox="0 0 100 100"><g id="m-bob"></g><g id="m-smile" opacity="1"></g><g id="m-viseme" opacity="0"></g></svg>`,
- tween: [{ id: 'm-bob', kind: 'translateY', freq: 1, amp: 10 }],
- },
- ],
- visemes: [
- { label: 'sil', description: '', svg: '' },
- { label: 'aa', description: '', svg: '<path d="MOUTH-AA"/>' },
- ],
-};
-
-describe('BackendMascot', () => {
- afterEach(() => cleanup());
-
- it('renders the chosen state svg', () => {
- const { container } = render(<BackendMascot mascot={detail} />);
- expect(container.querySelector('#m-bob')).toBeTruthy();
- });
-
- it('shows active viseme overlay and hides resting mouth', () => {
- const { container } = render(<BackendMascot mascot={detail} viseme="aa" paused />);
- const slot = container.querySelector('#m-viseme');
- expect(slot?.getAttribute('opacity')).toBe('1');
- expect(slot?.innerHTML).toContain('MOUTH-AA');
- expect(container.querySelector('#m-smile')?.getAttribute('opacity')).toBe('0');
- });
-
- it('clears overlay and restores resting mouth when viseme is sil', () => {
- const { container } = render(<BackendMascot mascot={detail} viseme="sil" paused />);
- const slot = container.querySelector('#m-viseme');
- expect(slot?.getAttribute('opacity')).toBe('0');
- expect(container.querySelector('#m-smile')?.getAttribute('opacity')).toBe('1');
- });
-});
diff --git a/app/src/features/human/Mascot/backend/BackendMascot.tsx b/app/src/features/human/Mascot/backend/BackendMascot.tsx
deleted file mode 100644
index 0fbb0ff937..0000000000
--- a/app/src/features/human/Mascot/backend/BackendMascot.tsx
+++ /dev/null
@@ -1,150 +0,0 @@
-// Animated renderer for a backend-driven mascot manifest.
-//
-// Mount strategy:
-// - Inject the chosen state's `<svg>...</svg>` once via dangerouslySetInnerHTML
-// inside a wrapper <div>.
-// - In a rAF loop, find each tween's target element by id and set its
-// `transform` attribute directly. No SVG re-parse per frame.
-// - When `viseme` changes, run `injectViseme` on the live slot element
-// so the mouth overlay swaps without a full remount.
-//
-// This is the browser-side counterpart of the backend's ffmpeg renderer:
-// same render-core math, same per-state SVG, same viseme map — so the
-// in-app mascot animates in lockstep with the WebRTC video.
-import { useEffect, useMemo, useRef } from 'react';
-
-import { injectViseme, tweenTransform } from './renderCore';
-import { sanitizeSvg } from './sanitizeSvg';
-import type { MascotDetail, MascotState } from './types';
-
-interface BackendMascotProps {
- mascot: MascotDetail;
- /** Active state id. Falls back to `mascot.defaultState` when unknown. */
- stateId?: string;
- /** Active viseme label, or `null` for resting mouth. */
- viseme?: string | null;
- /** CSS variable overrides for the mascot's declared variables. */
- variables?: Record<string, string>;
- /** Override SVG width/height; defaults to filling the parent. */
- size?: number | string;
- /** Pause the rAF loop — used when the mascot is offscreen or in a hidden tab. */
- paused?: boolean;
-}
-
-function pickState(mascot: MascotDetail, stateId?: string): MascotState | null {
- if (mascot.states.length === 0) return null;
- const id = stateId ?? mascot.defaultState;
- return mascot.states.find(s => s.id === id) ?? mascot.states[0];
-}
-
-export function BackendMascot({
- mascot,
- stateId,
- viseme = null,
- variables,
- size = '100%',
- paused = false,
-}: BackendMascotProps) {
- const containerRef = useRef<HTMLDivElement | null>(null);
- const rafRef = useRef<number | null>(null);
-
- const state = useMemo(() => pickState(mascot, stateId), [mascot, stateId]);
-
- // Initial SVG mount — re-runs when the state SVG changes. Viseme is
- // injected once here so the first painted frame is correct; subsequent
- // viseme changes are handled in a separate effect that doesn't tear
- // down the SVG.
- const initialMarkup = useMemo(() => {
- if (!state) return '';
- const active = viseme && viseme !== 'sil' ? viseme : null;
- // Sanitize before injection — backend-supplied SVG reaches a
- // `dangerouslySetInnerHTML` sink in the privileged renderer.
- return sanitizeSvg(injectViseme(state.svg, mascot, active));
- // We intentionally only re-inject on state change here; viseme effect
- // below handles in-place swaps.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [mascot, state]);
-
- // Apply CSS variables to the wrapper so the mascot's color tokens
- // (--body-fill, --eye-color, …) cascade into the inline SVG without
- // requiring per-mascot stylesheets.
- useEffect(() => {
- const el = containerRef.current;
- if (!el || !variables) return;
- for (const [k, v] of Object.entries(variables)) {
- el.style.setProperty(k, v);
- }
- }, [variables]);
-
- // Live viseme swaps without remounting the SVG.
- useEffect(() => {
- const root = containerRef.current?.querySelector('svg');
- if (!root || !mascot.visemeSlot) return;
- const slotId = mascot.visemeSlot.replace(/^#/, '');
- const slot = root.querySelector<SVGGElement>(`#${CSS.escape(slotId)}`);
- if (!slot) return;
- const active = viseme && viseme !== 'sil' ? viseme : null;
- const entry = active ? mascot.visemes.find(v => v.label === active) : null;
- const inner = sanitizeSvg(entry?.svg ?? '');
- const visible = inner.length > 0;
- slot.innerHTML = inner;
- slot.setAttribute('opacity', visible ? '1' : '0');
- // Hide resting-mouth elements while a viseme is active so the
- // overlay reads cleanly. Restore when the viseme clears.
- for (const id of mascot.hidesOnViseme ?? []) {
- const target = root.querySelector<SVGElement>(`#${CSS.escape(id)}`);
- if (!target) continue;
- target.setAttribute('opacity', visible ? '0' : '1');
- }
- // `state` is included so the effect re-runs when the SVG remounts
- // with a different state's structure (slot + hidesOnViseme nodes are
- // queried by id directly on the live DOM, so they're per-state).
- }, [mascot, state, viseme]);
-
- // rAF tween loop. Mutates `transform` attrs in place — no React re-render.
- useEffect(() => {
- if (paused || !state) return;
- const root = containerRef.current?.querySelector('svg');
- if (!root) return;
- const tweens = state.tween ?? [];
- if (tweens.length === 0) return;
-
- // Resolve target elements once; rAF tick just rewrites the attr.
- const targets = tweens
- .map(tw => {
- const node = root.querySelector<SVGElement>(`#${CSS.escape(tw.id)}`);
- return node ? { tw, node } : null;
- })
- .filter((x): x is { tw: (typeof tweens)[number]; node: SVGElement } => x != null);
-
- if (targets.length === 0) return;
-
- const start = window.performance.now();
-
- const tick = (now: number) => {
- const t = (now - start) / 1000;
- for (const { tw, node } of targets) {
- node.setAttribute('transform', tweenTransform(t, tw));
- }
- rafRef.current = window.requestAnimationFrame(tick);
- };
- rafRef.current = window.requestAnimationFrame(tick);
-
- return () => {
- if (rafRef.current != null) window.cancelAnimationFrame(rafRef.current);
- rafRef.current = null;
- };
- }, [state, paused]);
-
- if (!state) return null;
-
- return (
- <div
- ref={containerRef}
- style={{ width: size, height: size, display: 'inline-block' }}
- // Backend-controlled SVG, same source the WebRTC ffmpeg pipeline
- // rasterizes from. Treated as trusted.
- dangerouslySetInnerHTML={{ __html: initialMarkup }}
- />
- );
-}
diff --git a/app/src/features/human/Mascot/backend/renderCore.test.ts b/app/src/features/human/Mascot/backend/renderCore.test.ts
deleted file mode 100644
index 9b8b4ccf2b..0000000000
--- a/app/src/features/human/Mascot/backend/renderCore.test.ts
+++ /dev/null
@@ -1,186 +0,0 @@
-// Behavior parity with backend `src/services/mascots/__tests__/render-core.test.ts`.
-// If this test diverges from the upstream JS file, the WebRTC stream and
-// the in-app render will fall out of lockstep.
-import { describe, expect, it } from 'vitest';
-
-import {
- composeFrameSvg,
- hideRestingMouth,
- injectViseme,
- setTransformOnId,
- tweenTransform,
-} from './renderCore';
-import type { MascotDetail, MascotState, MascotTween } from './types';
-
-const baseSvg = `
-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000">
- <g id="m-bob"><path d="M0 0"/></g>
- <g id="m-left-arm"><path d="M1 1"/></g>
- <g id="m-eye-blink"><path d="M2 2"/></g>
- <g id="m-smile" opacity="1.000"><path d="M3 3"/></g>
- <path id="m-hmm" d="M4 4" stroke="#000" fill="none" opacity="0.5"/>
- <g id="m-viseme" opacity="0"></g>
-</svg>`.trim();
-
-const visemes = [
- { label: 'sil', description: '', svg: '' },
- { label: 'aa', description: '', svg: '<path d="MOUTH-AA"/>' },
-];
-
-const mascot: Pick<MascotDetail, 'visemeSlot' | 'visemes' | 'hidesOnViseme'> = {
- visemeSlot: '#m-viseme',
- visemes,
- hidesOnViseme: ['m-smile', 'm-hmm'],
-};
-
-describe('renderCore', () => {
- describe('tweenTransform', () => {
- it('translateY: amplitude * sin(2π·freq·(t+phase))', () => {
- expect(tweenTransform(0, { id: 'x', kind: 'translateY', amp: 14, freq: 1 })).toBe(
- 'translate(0 0.00)'
- );
- expect(tweenTransform(0.25, { id: 'x', kind: 'translateY', amp: 14, freq: 1 })).toBe(
- 'translate(0 14.00)'
- );
- });
-
- it('rotate: includes pivot in the matrix call', () => {
- expect(
- tweenTransform(0.25, { id: 'x', kind: 'rotate', amp: 30, freq: 1, pivot: [100, 200] })
- ).toBe('rotate(30.00 100 200)');
- });
-
- it('blink: closed during the duration window, open otherwise', () => {
- const tw: MascotTween = { id: 'x', kind: 'blink', period: 2, duration: 0.2, pivot: [10, 20] };
- expect(tweenTransform(0, tw)).toContain('scale(1 1.000)');
- expect(tweenTransform(1, tw)).toContain('scale(1 0.120)');
- });
-
- it('blink respects custom closed value', () => {
- const tw: MascotTween = {
- id: 'x',
- kind: 'blink',
- period: 2,
- duration: 0.2,
- pivot: [0, 0],
- closed: 0.5,
- };
- expect(tweenTransform(1, tw)).toContain('scale(1 0.500)');
- });
-
- it('uses sane defaults when amp/freq/pivot are omitted', () => {
- expect(tweenTransform(1, { id: 'x', kind: 'translateY' })).toBe('translate(0 0.00)');
- expect(tweenTransform(0, { id: 'x', kind: 'rotate' })).toBe('rotate(0.00 0 0)');
- });
- });
-
- describe('injectViseme', () => {
- it('rewrites slot opacity to 1 and injects markup for a known label', () => {
- const out = injectViseme(baseSvg, mascot, 'aa');
- expect(out).toContain('<g id="m-viseme" opacity="1"><path d="MOUTH-AA"/></g>');
- });
-
- it('leaves slot opacity=0 with empty inner for null label', () => {
- const out = injectViseme(baseSvg, mascot, null);
- expect(out).toContain('<g id="m-viseme" opacity="0"></g>');
- });
-
- it('treats "sil" as silence (slot stays hidden)', () => {
- const out = injectViseme(baseSvg, mascot, 'sil');
- expect(out).toContain('<g id="m-viseme" opacity="0"></g>');
- });
-
- it('falls through to no-op for an unknown label', () => {
- const out = injectViseme(baseSvg, mascot, 'unknown');
- expect(out).toContain('<g id="m-viseme" opacity="0"></g>');
- });
-
- it('returns input unchanged when visemeSlot is missing', () => {
- const out = injectViseme(baseSvg, { visemes } as never, 'aa');
- expect(out).toBe(baseSvg);
- });
-
- it('returns input unchanged when slot id is not in the svg', () => {
- const out = injectViseme('<svg></svg>', mascot, 'aa');
- expect(out).toBe('<svg></svg>');
- });
- });
-
- describe('setTransformOnId', () => {
- it('adds a fresh transform attribute', () => {
- const out = setTransformOnId('<g id="x"></g>', 'x', 'rotate(45)');
- expect(out).toBe('<g id="x" transform="rotate(45)"></g>');
- });
-
- it('replaces an existing transform', () => {
- const out = setTransformOnId(
- '<g id="x" transform="translate(0 0)" opacity="1"></g>',
- 'x',
- 'translate(0 5)'
- );
- expect(out).toContain('transform="translate(0 5)"');
- expect(out).not.toContain('translate(0 0)');
- expect(out).toContain('opacity="1"');
- });
-
- it('preserves self-closing slash for void-style elements', () => {
- const out = setTransformOnId('<path id="x" d="M0 0" fill="none"/>', 'x', 'rotate(10)');
- expect(out).toMatch(/transform="rotate\(10\)"\s*\/>/);
- });
-
- it('is a no-op when the id is not present', () => {
- expect(setTransformOnId('<g id="other"></g>', 'x', 'rotate(45)')).toBe('<g id="other"></g>');
- });
- });
-
- describe('hideRestingMouth', () => {
- it('sets opacity=0 on every id in hidesOnViseme', () => {
- const out = hideRestingMouth(baseSvg, mascot);
- expect(out).toContain('<g id="m-smile" opacity="0">');
- expect(out).toMatch(/<path id="m-hmm"[^>]*opacity="0"\s*\/>/);
- });
-
- it('is a no-op when hidesOnViseme is empty', () => {
- expect(hideRestingMouth(baseSvg, { hidesOnViseme: [] })).toBe(baseSvg);
- });
- });
-
- describe('composeFrameSvg', () => {
- const state: MascotState = {
- id: 'idle',
- label: 'Idle',
- description: '',
- svg: baseSvg,
- tween: [
- { id: 'm-bob', kind: 'translateY', freq: 1, amp: 10 },
- { id: 'm-left-arm', kind: 'rotate', freq: 0, amp: 7, pivot: [50, 60] },
- ],
- };
-
- it('applies viseme injection + smile-hiding + tween transforms', () => {
- const out = composeFrameSvg(state, mascot, 0.25, 'aa');
- expect(out).toContain('<path d="MOUTH-AA"/>');
- expect(out).toContain('<g id="m-smile" opacity="0">');
- expect(out).toMatch(/<path id="m-hmm"[^>]*opacity="0"/);
- expect(out).toContain('<g id="m-bob" transform="translate(0 10.00)">');
- expect(out).toContain('rotate(0.00 50 60)');
- });
-
- it('does not hide resting mouth when no viseme is active', () => {
- const out = composeFrameSvg(state, mascot, 0, null);
- expect(out).toContain('<g id="m-smile" opacity="1.000">');
- });
-
- it('treats "sil" as no viseme (resting mouth visible)', () => {
- const out = composeFrameSvg(state, mascot, 0, 'sil');
- expect(out).toContain('<g id="m-smile" opacity="1.000">');
- });
-
- it('handles state without tween gracefully', () => {
- const noTween: MascotState = { ...state, tween: undefined };
- const out = composeFrameSvg(noTween, mascot, 0, null);
- expect(out).toContain('<g id="m-bob">');
- expect(out).not.toContain('transform=');
- });
- });
-});
diff --git a/app/src/features/human/Mascot/backend/renderCore.ts b/app/src/features/human/Mascot/backend/renderCore.ts
deleted file mode 100644
index 956b964267..0000000000
--- a/app/src/features/human/Mascot/backend/renderCore.ts
+++ /dev/null
@@ -1,142 +0,0 @@
-// TS port of backend `src/services/mascots/render-core.js`. Single source
-// of truth for tween math, viseme injection, smile-hiding, and transform
-// substitution. Pure functions — no DOM. The animated `BackendMascot`
-// renderer applies tween transforms directly to live DOM nodes via
-// rAF, but reuses these helpers for viseme injection and tests.
-//
-// MUST stay behavior-equivalent to the backend's JS file — covered by
-// `renderCore.test.ts`, which mirrors the backend's `render-core.test.ts`.
-import type { MascotDetail, MascotState, MascotTween } from './types';
-
-type VisemeCarrier = Pick<MascotDetail, 'visemeSlot' | 'visemes'>;
-type HiderCarrier = Pick<MascotDetail, 'hidesOnViseme'>;
-
-/**
- * Escape regex metacharacters in interpolated id / attribute names so a
- * malformed backend manifest (or a future schema that allows broader id
- * characters) can't inject pattern fragments or throw at RegExp construction.
- */
-function escapeRegExp(value: string): string {
- return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
-}
-
-/**
- * Compute the SVG `transform` value for a tween entry at time t (seconds).
- */
-export function tweenTransform(t: number, tw: MascotTween): string {
- const phase = tw.phase ?? 0;
- if (tw.kind === 'translateY') {
- const amp = tw.amp ?? 0;
- const freq = tw.freq ?? 0;
- const y = amp * Math.sin(2 * Math.PI * freq * (t + phase));
- return `translate(0 ${y.toFixed(2)})`;
- }
- if (tw.kind === 'rotate') {
- const ramp = tw.amp ?? 0;
- const rfreq = tw.freq ?? 0;
- const deg = ramp * Math.sin(2 * Math.PI * rfreq * (t + phase));
- const rp = tw.pivot ?? [0, 0];
- return `rotate(${deg.toFixed(2)} ${rp[0]} ${rp[1]})`;
- }
- if (tw.kind === 'blink') {
- const period = tw.period ?? 2.6;
- const duration = tw.duration ?? 0.2;
- const closed = tw.closed != null ? tw.closed : 0.12;
- // Stagger so the blink doesn't fire on t=0.
- const inBlink = (t + period / 2) % period < duration;
- const sy = inBlink ? closed : 1;
- const bp = tw.pivot ?? [0, 0];
- return `translate(${bp[0]} ${bp[1]}) scale(1 ${sy.toFixed(3)}) translate(${-bp[0]} ${-bp[1]})`;
- }
- return '';
-}
-
-/** Strip `name="..."` from an opening tag string and re-append it with `value`. */
-function setOpeningTagAttr(tag: string, name: string, value: string): string {
- const nameEsc = escapeRegExp(name);
- const stripped = tag.replace(new RegExp(`\\s*\\b${nameEsc}="[^"]*"`, 'g'), '');
- return stripped.replace(/(\/?>)$/, ` ${name}="${value}"$1`);
-}
-
-/**
- * Replace the inner content of <g id="visemeSlotId">…</g> with the viseme's
- * SVG fragment AND force the slot's opacity to 1 so the markup is visible.
- * When label is null/empty, restores opacity="0" and clears the slot so
- * the resting mouth (smile/hmm) shows through.
- */
-export function injectViseme(svg: string, mascot: VisemeCarrier, label: string | null): string {
- if (!mascot.visemeSlot) return svg;
- const slotId = String(mascot.visemeSlot).replace(/^#/, '');
- const slotIdEsc = escapeRegExp(slotId);
- const openRe = new RegExp(`<g\\s[^>]*\\bid="${slotIdEsc}"[^>]*>`);
- const openMatch = svg.match(openRe);
- if (!openMatch) return svg;
- let inner = '';
- let visible = false;
- // 'sil' is the silence sentinel — same as null. Anything else looked
- // up against the viseme map; only non-empty markup counts as visible
- // so the resting mouth still shows when a label has no svg.
- if (label && label !== 'sil') {
- const visemes = mascot.visemes ?? [];
- for (const v of visemes) {
- if (v.label === label) {
- inner = v.svg || '';
- visible = inner.length > 0;
- break;
- }
- }
- }
- const newOpening = setOpeningTagAttr(openMatch[0], 'opacity', visible ? '1' : '0');
- const blockRe = new RegExp(`<g\\s[^>]*\\bid="${slotIdEsc}"[^>]*>[\\s\\S]*?</g>`);
- return svg.replace(blockRe, newOpening + inner + '</g>');
-}
-
-/** Generic single-attribute string set on the element with the given id. */
-function setAttrOnId(svg: string, id: string, name: string, value: string): string {
- // Lazy `[^>]*?` + greedy `\/?>` ordering avoids swallowing the `/` of
- // self-closing tags (`<path .../>`) and emitting malformed
- // `attr"/ transform="...">` output.
- const idEsc = escapeRegExp(id);
- const nameEsc = escapeRegExp(name);
- const re = new RegExp(`(<\\w+\\b[^>]*\\bid="${idEsc}")([^>]*?)(\\s*/?>)`);
- return svg.replace(re, (_full, head: string, rest: string, close: string) => {
- const stripped = rest.replace(new RegExp(`\\s*\\b${nameEsc}="[^"]*"`, 'g'), '');
- return `${head}${stripped} ${name}="${value}"${close}`;
- });
-}
-
-/** Rewrite the opening tag of element `id` to carry a fresh `transform="value"`. */
-export function setTransformOnId(svg: string, id: string, value: string): string {
- return setAttrOnId(svg, id, 'transform', value);
-}
-
-/** Hide resting-mouth ids (smile, hmm, …) while a viseme overlay is active. */
-export function hideRestingMouth(svg: string, mascot: HiderCarrier): string {
- const ids = mascot.hidesOnViseme ?? [];
- let out = svg;
- for (const id of ids) {
- out = setAttrOnId(out, id, 'opacity', '0');
- }
- return out;
-}
-
-/**
- * Compose a full frame SVG for the given state at time t with optional
- * viseme overlay. Pure string-pipeline parity with the backend renderer —
- * used by tests and for the once-on-mount static SVG (no rAF) path.
- */
-export function composeFrameSvg(
- state: MascotState,
- mascot: VisemeCarrier & HiderCarrier,
- t: number,
- viseme: string | null
-): string {
- const active = viseme && viseme !== 'sil' ? viseme : null;
- let svg = injectViseme(state.svg, mascot, active);
- if (active) svg = hideRestingMouth(svg, mascot);
- const tweens = state.tween ?? [];
- for (const tw of tweens) {
- svg = setTransformOnId(svg, tw.id, tweenTransform(t, tw));
- }
- return svg;
-}
diff --git a/app/src/features/human/Mascot/backend/sanitizeSvg.test.ts b/app/src/features/human/Mascot/backend/sanitizeSvg.test.ts
deleted file mode 100644
index 0246c397d0..0000000000
--- a/app/src/features/human/Mascot/backend/sanitizeSvg.test.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { sanitizeSvg } from './sanitizeSvg';
-
-describe('sanitizeSvg', () => {
- it('returns empty string for empty input', () => {
- expect(sanitizeSvg('')).toBe('');
- });
-
- it('preserves benign SVG markup', () => {
- const svg = '<g id="m-bob"><path d="M0 0" fill="red"/></g>';
- expect(sanitizeSvg(svg)).toBe(svg);
- });
-
- it('strips <script> elements and their content', () => {
- const out = sanitizeSvg('<g><script>alert(1)</script><path d="M0 0"/></g>');
- expect(out).not.toContain('script');
- expect(out).toContain('<path d="M0 0"/>');
- });
-
- it('strips <foreignObject> elements (the innerHTML execution sink)', () => {
- const out = sanitizeSvg(
- '<foreignObject><img src="x" onerror="alert(1)"></foreignObject><path/>'
- );
- expect(out.toLowerCase()).not.toContain('foreignobject');
- expect(out).not.toContain('onerror');
- expect(out).toContain('<path/>');
- });
-
- it('strips inline event-handler attributes', () => {
- const out = sanitizeSvg('<circle onload="steal()" onclick=\'x\' r="5"/>');
- expect(out).not.toContain('onload');
- expect(out).not.toContain('onclick');
- expect(out).toContain('r="5"');
- });
-
- it('strips javascript: and data:text/html URLs in href/xlink:href', () => {
- const out = sanitizeSvg(
- '<a href="javascript:alert(1)"><use xlink:href="data:text/html,<x>"/></a>'
- );
- expect(out.toLowerCase()).not.toContain('javascript:');
- expect(out.toLowerCase()).not.toContain('data:text/html');
- });
-
- it('leaves a fragment-only xlink:href intact', () => {
- const svg = '<use xlink:href="#m-mouth"/>';
- expect(sanitizeSvg(svg)).toBe(svg);
- });
-});
diff --git a/app/src/features/human/Mascot/backend/sanitizeSvg.ts b/app/src/features/human/Mascot/backend/sanitizeSvg.ts
deleted file mode 100644
index 568910f36d..0000000000
--- a/app/src/features/human/Mascot/backend/sanitizeSvg.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-// Minimal SVG sanitizer for backend-supplied mascot markup.
-//
-// `BackendMascot` injects per-state SVG via `dangerouslySetInnerHTML` and live
-// `slot.innerHTML` swaps in the privileged Tauri renderer (which can reach the
-// core RPC bearer). `innerHTML` never executes `<svg><script>`, but a
-// `<foreignObject>` with an inline event handler — or an `href`/`xlink:href`
-// pointing at `javascript:` — DOES execute under a CSP that permits inline
-// handlers. We don't have DOMPurify in the dependency tree, so this strips the
-// known SVG-in-HTML execution sinks before injection:
-// - `<script>` and `<foreignObject>` elements (and their content)
-// - inline event-handler attributes (`on*`)
-// - `javascript:`/`data:text/html` URLs in `href` / `xlink:href` / `src`
-//
-// This is intentionally conservative and string-based to match the existing
-// pure-string render pipeline (`renderCore.ts`). It is defense-in-depth: the
-// markup is still expected to come from the trusted backend manifest.
-
-/** Elements whose mere presence in an HTML-parsed SVG can execute script. */
-const FORBIDDEN_ELEMENT_RE = /<\s*(script|foreignObject)\b[\s\S]*?<\s*\/\s*\1\s*>/gi;
-/** Self-closing or unterminated forbidden elements (`<script ... />`, `<foreignObject>`). */
-const FORBIDDEN_ELEMENT_OPEN_RE = /<\s*(script|foreignObject)\b[^>]*>/gi;
-/** Inline event handlers: `onload="…"`, `onerror='…'`, `onclick=…`. */
-const EVENT_HANDLER_ATTR_RE = /\s+on[a-z]+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi;
-/** `href` / `xlink:href` / `src` carrying an executable scheme. */
-const DANGEROUS_URL_ATTR_RE =
- /\s+(?:xlink:)?(?:href|src)\s*=\s*("\s*(?:javascript|data\s*:\s*text\/html)[^"]*"|'\s*(?:javascript|data\s*:\s*text\/html)[^']*'|\s*(?:javascript|data\s*:\s*text\/html)[^\s>]*)/gi;
-
-/**
- * Strip script-execution sinks from an SVG fragment before it is injected via
- * `innerHTML` / `dangerouslySetInnerHTML`. Returns an empty string for empty
- * input. Pure — no DOM access — so it runs identically in tests and renderer.
- */
-export function sanitizeSvg(svg: string): string {
- if (!svg) return '';
- return svg
- .replace(FORBIDDEN_ELEMENT_RE, '')
- .replace(FORBIDDEN_ELEMENT_OPEN_RE, '')
- .replace(EVENT_HANDLER_ATTR_RE, '')
- .replace(DANGEROUS_URL_ATTR_RE, '');
-}
diff --git a/app/src/features/human/Mascot/backend/types.ts b/app/src/features/human/Mascot/backend/types.ts
deleted file mode 100644
index e858e9d333..0000000000
--- a/app/src/features/human/Mascot/backend/types.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-// Mascot library types — mirror the backend models in
-// `tinyhumansai/backend:src/services/mascots/types.ts` and
-// `src/database/models/mascot.ts`. Kept in TS-only form here because
-// the app talks to the backend over HTTP — there is no shared package.
-
-export type MascotVariableType = 'color' | 'number' | 'string';
-
-export interface MascotVariable {
- name: string;
- label: string;
- type: MascotVariableType;
- default: string | number;
- description?: string;
-}
-
-export type MascotTweenKind = 'translateY' | 'rotate' | 'blink';
-
-/**
- * Declarative per-frame tween entry. Interpreted by the renderer's animation
- * loop — there is no per-mascot animation code, just data. `kind` selects
- * the math; the remaining fields parametrize it.
- *
- * translateY transform="translate(0 amp*sin(2π·freq·t + phase))"
- * rotate transform="rotate(amp*sin(2π·freq·t + phase) pivotX pivotY)"
- * blink y-axis squish: pulses to `closed` for `duration`s every
- * `period`s, otherwise scale 1
- */
-export interface MascotTween {
- /** Element id (bare, no '#') to mutate on the mounted SVG. */
- id: string;
- kind: MascotTweenKind;
- /** translateY/rotate: cycles per second. */
- freq?: number;
- /** translateY: pixels. rotate: degrees. */
- amp?: number;
- /** Phase offset in seconds. */
- phase?: number;
- /** rotate/blink: SVG-space pivot point [x, y]. */
- pivot?: [number, number];
- /** blink: full cycle in seconds. */
- period?: number;
- /** blink: how long the eye stays scrunched, in seconds. */
- duration?: number;
- /** blink: scaleY value while closed (default 0.12). */
- closed?: number;
-}
-
-export interface MascotState {
- id: string;
- label: string;
- description: string;
- /** Full <svg>...</svg> for this state, served by the backend per-id endpoint. */
- svg: string;
- /** Optional rAF-driven tween config. Empty/absent => static pose. */
- tween?: MascotTween[];
-}
-
-export interface MascotViseme {
- label: string;
- description: string;
- svg: string;
-}
-
-export type MascotFormat = 'svg' | 'rive';
-
-export interface MascotSummary {
- id: string;
- name: string;
- version: string;
- description: string;
- /** 'svg' (legacy) or 'rive' (current). Absent on old backends => treat as svg. */
- format?: MascotFormat;
- /** SVG-only: state metadata (no SVG bytes or tween) to keep list payload light. */
- states?: Pick<MascotState, 'id' | 'label' | 'description'>[];
- hasVisemes?: boolean;
- /** Rive-only: maps logical state ids to Rive pose enum values. */
- stateToPose?: Record<string, string>;
-}
-
-export interface MascotDetail {
- id: string;
- name: string;
- version: string;
- description: string;
- format?: 'svg';
- viewBox: string;
- defaultState: string;
- variables: MascotVariable[];
- states: MascotState[];
- visemes: MascotViseme[];
- visemeSlot?: string;
- hidesOnViseme?: string[];
-}
-
-export type ViewModelInputType = 'number' | 'boolean' | 'color' | 'string' | 'enum';
-
-export interface ViewModelInput {
- name: string;
- type: ViewModelInputType;
- description?: string;
-}
-
-/** Rive mascot manifest — the binary lives at `rivFileUrl` (version-stamped). */
-export interface RiveMascotDetail {
- id: string;
- name: string;
- version: string;
- description: string;
- format: 'rive';
- /** Backend-relative URL of the .riv binary, e.g. `/mascots/toshi/riv?v=1.0.0`. */
- rivFileUrl: string;
- source?: 'builtin' | 'custom';
- defaultState: string;
- stateToPose: Record<string, string>;
- viewModelInputs: ViewModelInput[];
-}
-
-export type MascotDetailUnion = MascotDetail | RiveMascotDetail;
-
-export function isRiveMascotDetail(d: MascotDetailUnion): d is RiveMascotDetail {
- return d.format === 'rive';
-}
-
-/** Wire shapes for /mascots and /mascots/:id. */
-export interface ListMascotsResponse {
- success: true;
- data: { mascots: MascotSummary[] };
-}
-
-export interface GetMascotResponse {
- success: true;
- data: { mascot: MascotDetailUnion };
-}
diff --git a/app/src/features/share/ShareCardModal.test.tsx b/app/src/features/share/ShareCardModal.test.tsx
deleted file mode 100644
index 0bd874ce1b..0000000000
--- a/app/src/features/share/ShareCardModal.test.tsx
+++ /dev/null
@@ -1,110 +0,0 @@
-import { render, screen, waitFor } from '@testing-library/react';
-import userEvent from '@testing-library/user-event';
-import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
-
-import { ShareCardModal } from './ShareCardModal';
-
-const mocks = vi.hoisted(() => ({
- draftShareHeadline: vi.fn(),
- openUrl: vi.fn(),
- renderShareCardToCanvas: vi.fn(),
- cardToPngBlob: vi.fn(),
- trackAnalyticsEvent: vi.fn(),
-}));
-
-vi.mock('./shareCaption', () => ({ draftShareHeadline: mocks.draftShareHeadline }));
-vi.mock('../../utils/openUrl', () => ({ openUrl: mocks.openUrl }));
-vi.mock('../../components/analytics', () => ({ trackAnalyticsEvent: mocks.trackAnalyticsEvent }));
-vi.mock('./shareCard', async importActual => {
- const actual = await importActual<typeof import('./shareCard')>();
- return {
- ...actual,
- renderShareCardToCanvas: mocks.renderShareCardToCanvas,
- cardToPngBlob: mocks.cardToPngBlob,
- };
-});
-
-let clipboardWriteText: ReturnType<typeof vi.fn>;
-
-beforeEach(() => {
- mocks.draftShareHeadline.mockResolvedValue('My agent cleared my inbox');
- mocks.openUrl.mockResolvedValue(undefined);
- mocks.cardToPngBlob.mockResolvedValue(new Blob(['x'], { type: 'image/png' }));
- clipboardWriteText = vi.fn().mockResolvedValue(undefined);
- vi.stubGlobal('navigator', { ...navigator, clipboard: { writeText: clipboardWriteText } });
-});
-
-afterEach(() => {
- vi.unstubAllGlobals();
- Object.values(mocks).forEach(m => m.mockReset());
-});
-
-describe('ShareCardModal', () => {
- test('drafts a headline and seeds the caption', async () => {
- mocks.draftShareHeadline.mockResolvedValue('My agent cleared my inbox');
- render(<ShareCardModal content="cleared the inbox" agentName="Tiny" onClose={vi.fn()} />);
-
- const textarea = await screen.findByLabelText('Caption');
- await waitFor(() => expect((textarea as HTMLTextAreaElement).value).toContain('cleared'));
- expect(mocks.draftShareHeadline).toHaveBeenCalledWith('cleared the inbox', undefined);
- });
-
- test('opens the X composer with the caption', async () => {
- const user = userEvent.setup();
- render(<ShareCardModal content="cleared the inbox" agentName="Tiny" onClose={vi.fn()} />);
- await screen.findByLabelText('Caption');
-
- await user.click(screen.getByText('Share on X'));
- await waitFor(() => expect(mocks.openUrl).toHaveBeenCalled());
- expect(mocks.openUrl.mock.calls[0][0]).toContain('twitter.com/intent/tweet');
- expect(mocks.trackAnalyticsEvent).toHaveBeenCalledWith('chat_message_shared', {
- destination: 'x',
- });
- });
-
- test('copies the caption to the clipboard and opens LinkedIn', async () => {
- const user = userEvent.setup();
- render(<ShareCardModal content="cleared the inbox" agentName="Tiny" onClose={vi.fn()} />);
- await screen.findByLabelText('Caption');
-
- await user.click(screen.getByText('Share on LinkedIn'));
- await waitFor(() => expect(mocks.openUrl).toHaveBeenCalled());
- expect(mocks.openUrl.mock.calls[0][0]).toContain('linkedin.com/sharing/share-offsite');
- expect(mocks.trackAnalyticsEvent).toHaveBeenCalledWith('chat_message_shared', {
- destination: 'linkedin',
- });
- });
-
- test('copies the image (download fallback when ClipboardItem is absent)', async () => {
- const user = userEvent.setup();
- render(<ShareCardModal content="cleared the inbox" agentName="Tiny" onClose={vi.fn()} />);
- await screen.findByLabelText('Caption');
-
- await user.click(screen.getByText('Copy image'));
- await waitFor(() => expect(mocks.cardToPngBlob).toHaveBeenCalled());
- });
-
- test('falls back to download when the clipboard image write rejects', async () => {
- const user = userEvent.setup();
- const write = vi.fn().mockRejectedValue(new Error('denied'));
- vi.stubGlobal('ClipboardItem', class {} as unknown as typeof ClipboardItem);
- vi.stubGlobal('navigator', {
- ...navigator,
- clipboard: { writeText: clipboardWriteText, write },
- });
- const createObjectURL = vi.fn().mockReturnValue('blob:mock');
- const revokeObjectURL = vi.fn();
- vi.stubGlobal('URL', { ...URL, createObjectURL, revokeObjectURL });
-
- render(<ShareCardModal content="cleared the inbox" agentName="Tiny" onClose={vi.fn()} />);
- await screen.findByLabelText('Caption');
-
- await user.click(screen.getByText('Copy image'));
- await waitFor(() => expect(write).toHaveBeenCalled());
- // Rejected clipboard write should still fall through to the download path
- // (createObjectURL) rather than only surfacing an image error.
- await waitFor(() => expect(createObjectURL).toHaveBeenCalled());
- await waitFor(() => expect(screen.getByText('Image copied')).toBeInTheDocument());
- expect(screen.queryByText("Couldn't generate the image. Try again.")).not.toBeInTheDocument();
- });
-});
diff --git a/app/src/features/share/ShareCardModal.tsx b/app/src/features/share/ShareCardModal.tsx
deleted file mode 100644
index d86de978d1..0000000000
--- a/app/src/features/share/ShareCardModal.tsx
+++ /dev/null
@@ -1,269 +0,0 @@
-import { useCallback, useEffect, useRef, useState } from 'react';
-
-import { trackAnalyticsEvent } from '../../components/analytics';
-import Button from '../../components/ui/Button';
-import { ModalShell } from '../../components/ui/ModalShell';
-import { useT } from '../../lib/i18n/I18nContext';
-import { openUrl } from '../../utils/openUrl';
-import { draftShareHeadline } from './shareCaption';
-import {
- CARD_HEIGHT,
- CARD_WIDTH,
- cardToPngBlob,
- renderShareCardToCanvas,
- type ShareCardFallbacks,
-} from './shareCard';
-import { buildShareCaption, type ShareCaptionTemplates } from './shareContent';
-import { buildLinkedInShareUrl, buildTweetIntentUrl, SHARE_LANDING_URL } from './shareTargets';
-
-const LOG_PREFIX = '[share-modal]';
-
-/** Marketing URL printed on the card footer. */
-const CARD_URL = 'tinyhumans.ai';
-
-interface ShareCardModalProps {
- /** The assistant output being shared (already image-stripped plain text). */
- 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;
- onClose: () => void;
-}
-
-type CopyState = 'idle' | 'image' | 'caption';
-
-/**
- * Preview-and-share modal for the share cards feature (#5006). Drafts a
- * headline (LLM with deterministic fallback), renders a branded PNG card, lets
- * the user edit the caption, and opens the X / LinkedIn composer or copies the
- * image. All rules that could touch inference live in `shareCaption.ts`; this
- * component is presentation + wiring only.
- */
-export function ShareCardModal({ content, agentName, threadId, onClose }: ShareCardModalProps) {
- const { t } = useT();
- const canvasRef = useRef<HTMLCanvasElement>(null);
- const [headline, setHeadline] = useState('');
- const [caption, setCaption] = useState('');
- const [drafting, setDrafting] = useState(true);
- const [copyState, setCopyState] = useState<CopyState>('idle');
- const [imageError, setImageError] = useState(false);
- const [linkedInHint, setLinkedInHint] = useState(false);
-
- // Localized fallback text for the offline/empty-headline paths in
- // shareContent.ts / shareCard.ts. Kept in a ref (refreshed every render) so
- // the drafting effect below can read the latest translation without taking
- // a `t` dependency that would re-trigger the LLM draft RPC on locale change.
- const captionTemplatesRef = useRef<ShareCaptionTemplates>({
- emptyFallback: '',
- withHeadline: '',
- });
- captionTemplatesRef.current = {
- emptyFallback: t('share.defaultCaption'),
- withHeadline: t('share.captionWithHeadline'),
- };
-
- // Draft the headline once on open; degrade to the offline fallback on any
- // failure (draftShareHeadline never rejects).
- useEffect(() => {
- let cancelled = false;
- void draftShareHeadline(content, threadId).then(drafted => {
- if (cancelled) return;
- setHeadline(drafted);
- setCaption(buildShareCaption(drafted, captionTemplatesRef.current));
- setDrafting(false);
- console.debug(`${LOG_PREFIX} headline ready len=${drafted.length}`);
- });
- return () => {
- cancelled = true;
- };
- }, [content, threadId]);
-
- // (Re)paint the card whenever the headline settles, and also on locale
- // change so an empty-headline / empty-agent-name fallback repaints localized.
- useEffect(() => {
- const canvas = canvasRef.current;
- if (!canvas || drafting) return;
- const cardFallbacks: ShareCardFallbacks = {
- headline: t('share.defaultHeadline'),
- agentName: t('share.defaultAgentName'),
- };
- try {
- renderShareCardToCanvas(canvas, { headline, agentName, brandUrl: CARD_URL }, cardFallbacks);
- setImageError(false);
- } catch (err) {
- console.debug(`${LOG_PREFIX} render failed: ${String(err)}`);
- setImageError(true);
- }
- }, [headline, agentName, drafting, t]);
-
- const flashCopy = useCallback((state: Exclude<CopyState, 'idle'>) => {
- setCopyState(state);
- setTimeout(() => setCopyState('idle'), 2000);
- }, []);
-
- const handleShareX = useCallback(() => {
- const url = buildTweetIntentUrl(caption, SHARE_LANDING_URL);
- trackAnalyticsEvent('chat_message_shared', { destination: 'x' });
- void openUrl(url).catch(err => console.debug(`${LOG_PREFIX} openUrl x failed: ${String(err)}`));
- }, [caption]);
-
- const handleShareLinkedIn = useCallback(async () => {
- // LinkedIn's share endpoint ignores caption text, so copy it for pasting.
- try {
- await navigator.clipboard.writeText(caption);
- setLinkedInHint(true);
- } catch {
- // Non-fatal: the composer still opens, the user just retypes the caption.
- }
- trackAnalyticsEvent('chat_message_shared', { destination: 'linkedin' });
- void openUrl(buildLinkedInShareUrl(SHARE_LANDING_URL)).catch(err =>
- console.debug(`${LOG_PREFIX} openUrl linkedin failed: ${String(err)}`)
- );
- }, [caption]);
-
- const handleCopyImage = useCallback(async () => {
- const canvas = canvasRef.current;
- if (!canvas) return;
- try {
- const blob = await cardToPngBlob(canvas);
- const canWriteImage =
- typeof ClipboardItem !== 'undefined' && typeof navigator.clipboard?.write === 'function';
- if (canWriteImage) {
- try {
- await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
- flashCopy('image');
- trackAnalyticsEvent('chat_message_shared', { destination: 'copy_image' });
- return;
- } catch (clipboardErr) {
- // Clipboard write rejected (permission denied, MIME unsupported, or
- // WebView restrictions): fall through to the download fallback below
- // instead of surfacing an image error for a card that rendered fine.
- console.debug(
- `${LOG_PREFIX} clipboard image write rejected; falling back to download err_type=${
- clipboardErr instanceof Error ? clipboardErr.name : typeof clipboardErr
- }`
- );
- }
- }
- // Fallback: trigger a download so the user still gets the PNG.
- downloadBlob(blob, 'openhuman-share.png');
- flashCopy('image');
- trackAnalyticsEvent('chat_message_shared', { destination: 'save_image' });
- } catch (err) {
- console.debug(`${LOG_PREFIX} copy image failed: ${String(err)}`);
- setImageError(true);
- }
- }, [flashCopy]);
-
- const handleCopyCaption = useCallback(async () => {
- try {
- await navigator.clipboard.writeText(caption);
- flashCopy('caption');
- } catch (err) {
- console.debug(`${LOG_PREFIX} copy caption failed: ${String(err)}`);
- }
- }, [caption, flashCopy]);
-
- return (
- <ModalShell
- onClose={onClose}
- titleId="share-card-title"
- title={t('share.modalTitle')}
- subtitle={t('share.modalSubtitle')}
- maxWidthClassName="max-w-lg"
- contentClassName="px-5 py-4 space-y-4">
- <div
- className="relative overflow-hidden rounded-xl border border-line-subtle bg-surface-muted"
- style={{ aspectRatio: `${CARD_WIDTH} / ${CARD_HEIGHT}` }}>
- {drafting ? (
- <div
- className="absolute inset-0 flex items-center justify-center text-sm text-content-muted"
- data-testid="share-card-drafting">
- {t('share.drafting')}
- </div>
- ) : null}
- <canvas
- ref={canvasRef}
- data-testid="share-card-canvas"
- aria-label={t('share.cardAlt')}
- className={`h-full w-full ${drafting ? 'opacity-0' : 'opacity-100'} transition-opacity`}
- />
- {imageError ? (
- <div className="absolute inset-0 flex items-center justify-center px-4 text-center text-sm text-coral-600 dark:text-coral-300">
- {t('share.imageError')}
- </div>
- ) : null}
- </div>
-
- <div className="space-y-1.5">
- <label htmlFor="share-caption" className="text-xs font-medium text-content-secondary">
- {t('share.captionLabel')}
- </label>
- <textarea
- id="share-caption"
- value={caption}
- onChange={e => setCaption(e.target.value)}
- rows={3}
- disabled={drafting}
- placeholder={t('share.captionPlaceholder')}
- className="w-full resize-none rounded-xl border border-line bg-surface px-3 py-2 text-sm text-content placeholder:text-content-faint focus:outline-hidden focus:ring-2 focus:ring-primary-500/40 disabled:opacity-50"
- />
- </div>
-
- <p className="rounded-xl bg-surface-subtle px-3 py-2 text-xs text-content-muted">
- {t('share.privacyNote')}
- </p>
-
- {linkedInHint ? (
- <p className="text-xs text-sage-700 dark:text-sage-300">{t('share.linkedInHint')}</p>
- ) : null}
-
- <div className="flex flex-wrap gap-2">
- <Button
- variant="primary"
- size="sm"
- analyticsId="chat-share-x"
- disabled={drafting}
- onClick={handleShareX}>
- {t('share.shareX')}
- </Button>
- <Button
- variant="secondary"
- size="sm"
- analyticsId="chat-share-linkedin"
- disabled={drafting}
- onClick={() => void handleShareLinkedIn()}>
- {t('share.shareLinkedIn')}
- </Button>
- <Button
- variant="tertiary"
- size="sm"
- analyticsId="chat-share-copy-image"
- disabled={drafting}
- onClick={() => void handleCopyImage()}>
- {copyState === 'image' ? t('share.copiedImage') : t('share.copyImage')}
- </Button>
- <Button
- variant="tertiary"
- size="sm"
- analyticsId="chat-share-copy-caption"
- disabled={drafting}
- onClick={() => void handleCopyCaption()}>
- {copyState === 'caption' ? t('share.copiedCaption') : t('share.copyCaption')}
- </Button>
- </div>
- </ModalShell>
- );
-}
-
-function downloadBlob(blob: Blob, filename: string): void {
- const url = URL.createObjectURL(blob);
- const anchor = document.createElement('a');
- anchor.href = url;
- anchor.download = filename;
- document.body.appendChild(anchor);
- anchor.click();
- anchor.remove();
- URL.revokeObjectURL(url);
-}
diff --git a/app/src/features/share/shareCaption.test.ts b/app/src/features/share/shareCaption.test.ts
deleted file mode 100644
index ff50ad35a7..0000000000
--- a/app/src/features/share/shareCaption.test.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { beforeEach, describe, expect, test, vi } from 'vitest';
-
-import { draftShareHeadline, extractResponseText } from './shareCaption';
-
-const mocks = vi.hoisted(() => ({ callCoreRpc: vi.fn() }));
-
-vi.mock('../../services/coreRpcClient', () => ({ callCoreRpc: mocks.callCoreRpc }));
-
-describe('extractResponseText', () => {
- test('handles a bare string', () => {
- expect(extractResponseText('hello')).toBe('hello');
- });
-
- test('handles the { result } envelope from Outcome', () => {
- expect(extractResponseText({ result: 'hi', logs: ['x'] })).toBe('hi');
- });
-
- test('handles a { response } object', () => {
- expect(extractResponseText({ response: 'yo' })).toBe('yo');
- });
-
- test('returns empty for unknown shapes', () => {
- expect(extractResponseText({ nope: 1 })).toBe('');
- expect(extractResponseText(null)).toBe('');
- });
-});
-
-describe('draftShareHeadline', () => {
- beforeEach(() => {
- mocks.callCoreRpc.mockReset();
- });
-
- test('uses the sanitized LLM response on success', async () => {
- mocks.callCoreRpc.mockResolvedValue({ result: '"My agent cleared my inbox."' });
- const out = await draftShareHeadline('cleared the whole inbox in seconds', 't1');
- expect(out).toBe('My agent cleared my inbox');
- expect(mocks.callCoreRpc).toHaveBeenCalledTimes(1);
- const arg = mocks.callCoreRpc.mock.calls[0][0];
- expect(arg.method).toBe('openhuman.inference_agent_chat_simple');
- expect(arg.params.thread_id).toBe('t1');
- });
-
- test('falls back to a deterministic headline on RPC error', async () => {
- mocks.callCoreRpc.mockRejectedValue(new Error('no model'));
- const out = await draftShareHeadline('Summarised the quarterly report today.');
- expect(out).toBe('Summarised the quarterly report today');
- });
-
- test('falls back when the LLM returns empty text', async () => {
- mocks.callCoreRpc.mockResolvedValue({ result: ' ' });
- const out = await draftShareHeadline('Booked the flights and hotel.');
- expect(out).toBe('Booked the flights and hotel');
- });
-
- test('returns the fallback without calling RPC for empty output', async () => {
- const out = await draftShareHeadline(' ');
- expect(out).toBe('');
- expect(mocks.callCoreRpc).not.toHaveBeenCalled();
- });
-
- test('omits thread_id when not provided', async () => {
- mocks.callCoreRpc.mockResolvedValue({ result: 'Did a thing well' });
- await draftShareHeadline('did a thing');
- expect(mocks.callCoreRpc.mock.calls[0][0].params.thread_id).toBeUndefined();
- });
-});
diff --git a/app/src/features/share/shareCaption.ts b/app/src/features/share/shareCaption.ts
deleted file mode 100644
index 381872f2c2..0000000000
--- a/app/src/features/share/shareCaption.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-/**
- * LLM-backed headline drafting for the share cards feature (#5006).
- *
- * Reuses the existing one-shot completion RPC (`openhuman.inference_agent_chat_simple`)
- * to turn an agent's chat output into a short, punchy, first-person headline for
- * the card. Every failure mode (RPC error, empty/garbage response, no model
- * configured) degrades gracefully to the deterministic `buildFallbackHeadline`
- * so the Share flow never blocks on inference.
- *
- * PRIVACY: the prompt is built from the assistant message the user is already
- * looking at, and the response is scrubbed by `sanitizeHeadline` before use.
- */
-import { callCoreRpc } from '../../services/coreRpcClient';
-import { CORE_RPC_METHODS } from '../../services/rpcMethods';
-import { buildFallbackHeadline, redactSensitive, sanitizeHeadline } from './shareContent';
-
-const LOG_PREFIX = '[share-caption]';
-
-/** How much of the agent output we feed the model. Keeps the prompt cheap. */
-const MAX_CONTEXT_CHARS = 1200;
-
-function buildPrompt(agentOutput: string): string {
- const context = redactSensitive(agentOutput).slice(0, MAX_CONTEXT_CHARS);
- return [
- 'You write short, punchy social-media headlines.',
- 'Read the AI assistant output below and write ONE first-person headline',
- '(max 90 characters) describing what the AI agent just accomplished for its user.',
- 'No hashtags, no quotation marks, no emoji, no trailing period. Reply with only the headline.',
- '',
- 'Assistant output:',
- context,
- ].join('\n');
-}
-
-/**
- * Extracts the response text from whatever envelope shape the core returns for
- * `inference_agent_chat_simple`. The op wraps its `String` result via
- * `Outcome::single_log`, which serialises to `{ result, logs }`; older/other
- * transports may hand back a bare string or a `{ response }` object. We accept
- * all three defensively.
- */
-export function extractResponseText(raw: unknown): string {
- if (typeof raw === 'string') return raw;
- if (raw && typeof raw === 'object') {
- const obj = raw as Record<string, unknown>;
- for (const key of ['result', 'response', 'data', 'text']) {
- if (typeof obj[key] === 'string') return obj[key] as string;
- }
- }
- return '';
-}
-
-/**
- * Drafts a card headline for `agentOutput`. Resolves to an LLM headline when
- * available, otherwise the deterministic fallback. Never rejects.
- *
- * @param agentOutput the assistant message text the user is sharing.
- * @param threadId optional thread id, forwarded for inference-log grouping.
- */
-export async function draftShareHeadline(agentOutput: string, threadId?: string): Promise<string> {
- const fallback = buildFallbackHeadline(agentOutput);
- const trimmed = agentOutput.trim();
- if (!trimmed) return fallback;
-
- try {
- console.debug(`${LOG_PREFIX} requesting draft len=${trimmed.length} thread=${threadId ?? '-'}`);
- const raw = await callCoreRpc<unknown>({
- method: CORE_RPC_METHODS.inferenceAgentChatSimple,
- params: {
- message: buildPrompt(trimmed),
- temperature: 0.6,
- ...(threadId ? { thread_id: threadId } : {}),
- },
- });
- const headline = sanitizeHeadline(extractResponseText(raw));
- if (headline) {
- console.debug(`${LOG_PREFIX} draft ok len=${headline.length}`);
- return headline;
- }
- console.debug(`${LOG_PREFIX} draft empty after sanitize; using fallback`);
- return fallback;
- } catch (err) {
- console.debug(
- `${LOG_PREFIX} draft failed; using fallback err_type=${
- err instanceof Error ? err.name : typeof err
- }`
- );
- return fallback;
- }
-}
diff --git a/app/src/features/share/shareCard.test.ts b/app/src/features/share/shareCard.test.ts
deleted file mode 100644
index 0ccde235cf..0000000000
--- a/app/src/features/share/shareCard.test.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-import { describe, expect, test, vi } from 'vitest';
-
-import {
- CARD_HEIGHT,
- CARD_WIDTH,
- type CardPaintContext,
- computeCardModel,
- paintShareCard,
- wrapLines,
-} from './shareCard';
-
-describe('wrapLines', () => {
- test('wraps on word boundaries within the char budget', () => {
- const lines = wrapLines('the quick brown fox jumps', 10, 5);
- expect(lines.every(l => l.length <= 10)).toBe(true);
- expect(lines.join(' ')).toBe('the quick brown fox jumps');
- });
-
- test('hard-splits an over-long token', () => {
- const lines = wrapLines('supercalifragilisticexpialidocious', 8, 6);
- expect(lines[0].length).toBe(8);
- });
-
- test('caps at maxLines and ellipsises the overflow', () => {
- const lines = wrapLines('a b c d e f g h i j k', 3, 2);
- expect(lines.length).toBe(2);
- expect(lines[1].endsWith('…')).toBe(true);
- });
-});
-
-describe('computeCardModel', () => {
- test('wraps the headline and normalises fields', () => {
- const model = computeCardModel({
- headline: 'My agent summarised three months of emails in twelve seconds',
- agentName: 'Tiny',
- stat: '12s',
- brandUrl: 'tinyhumans.ai',
- });
- expect(model.headlineLines.length).toBeGreaterThan(0);
- expect(model.agentName).toBe('Tiny');
- expect(model.stat).toBe('12s');
- });
-
- test('supplies defaults for empty headline / agent / stat', () => {
- const model = computeCardModel({ headline: ' ', agentName: '', brandUrl: '' });
- expect(model.headlineLines.join(' ')).toContain('OpenHuman');
- expect(model.agentName).toBe('My agent');
- expect(model.stat).toBeNull();
- });
-
- test('uses caller-supplied localized fallbacks instead of English', () => {
- const model = computeCardModel(
- { headline: ' ', agentName: '', brandUrl: '' },
- { headline: 'Mira lo que hizo mi agente', agentName: 'Mi agente' }
- );
- expect(model.headlineLines.join(' ')).toContain('Mira lo que hizo mi agente');
- expect(model.agentName).toBe('Mi agente');
- });
-});
-
-function makeMockCtx(): CardPaintContext & { texts: string[] } {
- const texts: string[] = [];
- return {
- texts,
- fillStyle: '',
- strokeStyle: '',
- lineWidth: 0,
- font: '',
- textBaseline: '',
- textAlign: '',
- globalAlpha: 1,
- fillRect: vi.fn(),
- fillText: (t: string) => {
- texts.push(t);
- },
- beginPath: vi.fn(),
- arc: vi.fn(),
- fill: vi.fn(),
- rect: vi.fn(),
- roundRect: vi.fn(),
- createLinearGradient: () => ({ addColorStop: vi.fn() }) as unknown as CanvasGradient,
- };
-}
-
-describe('paintShareCard', () => {
- test('draws the brand, headline, stat, and footer', () => {
- const ctx = makeMockCtx();
- paintShareCard(ctx, {
- headline: 'Cleared my inbox',
- agentName: 'Tiny',
- stat: '12s',
- brandUrl: 'tinyhumans.ai',
- });
- const joined = ctx.texts.join('\n');
- expect(joined).toContain('OpenHuman');
- expect(joined).toContain('Cleared my inbox');
- expect(joined).toContain('12s');
- expect(joined).toContain('Tiny');
- expect(joined).toContain('tinyhumans.ai');
- });
-
- test('omits the stat chip when no stat given', () => {
- const ctx = makeMockCtx();
- paintShareCard(ctx, { headline: 'Did a thing', agentName: 'Tiny', brandUrl: 'tinyhumans.ai' });
- // With no roundRect stat chip, roundRect is never called.
- expect(ctx.roundRect).not.toHaveBeenCalled();
- });
-
- test('card dimensions are 16:9', () => {
- expect(CARD_WIDTH / CARD_HEIGHT).toBeCloseTo(16 / 9, 1);
- });
-});
diff --git a/app/src/features/share/shareCard.ts b/app/src/features/share/shareCard.ts
deleted file mode 100644
index 0d3c480081..0000000000
--- a/app/src/features/share/shareCard.ts
+++ /dev/null
@@ -1,284 +0,0 @@
-/**
- * Branded share-card rendering for issue #5006.
- *
- * The card is drawn with the raw Canvas 2D API (no html2canvas / screenshot) so
- * the output is deterministic, dependency-free, and on-brand. Layout maths that
- * doesn't need a live canvas (word wrap, which elements show) is factored into
- * pure functions so it can be unit-tested; `paintShareCard` issues the actual
- * draw calls and is exercised against a mock context in tests.
- *
- * Brand tokens mirror app/tailwind.config.js: ocean primary #4A83DD, Inter for
- * body copy, Cabinet Grotesk for the wordmark (falls back to Inter/sans if the
- * font is not yet loaded in the webview).
- */
-
-/** 16:9 — the aspect ratio both X and LinkedIn preview cleanly. */
-export const CARD_WIDTH = 1200;
-export const CARD_HEIGHT = 675;
-
-const OCEAN = '#4A83DD';
-const OCEAN_DEEP = '#2C5AA8';
-const INK = '#0E1726';
-
-const LOG_PREFIX = '[share-card]';
-
-interface ShareCardData {
- /** Punchy headline describing what the agent did. */
- headline: string;
- /** Agent / profile name shown in the footer. */
- agentName: string;
- /** Optional stat chip, e.g. "12s" or "3 files". */
- stat?: string;
- /** Marketing URL printed in the footer. */
- brandUrl: string;
-}
-
-interface ShareCardModel {
- headlineLines: string[];
- agentName: string;
- stat: string | null;
- brandUrl: string;
-}
-
-/**
- * Greedy word-wrap by character budget. Deterministic and canvas-free so the
- * layout is unit-testable. Words longer than `maxChars` are hard-split. Caps at
- * `maxLines`, ellipsising the final line when content overflows.
- */
-export function wrapLines(text: string, maxChars: number, maxLines: number): string[] {
- const words = text.trim().split(/\s+/).filter(Boolean);
- const lines: string[] = [];
- let current = '';
-
- const pushWord = (word: string) => {
- if (!current) {
- current = word;
- } else if (current.length + 1 + word.length <= maxChars) {
- current += ` ${word}`;
- } else {
- lines.push(current);
- current = word;
- }
- };
-
- for (let word of words) {
- while (word.length > maxChars) {
- // Hard-split an over-long token (e.g. a URL slug).
- if (current) {
- lines.push(current);
- current = '';
- }
- lines.push(word.slice(0, maxChars));
- word = word.slice(maxChars);
- }
- pushWord(word);
- }
- if (current) lines.push(current);
-
- if (lines.length <= maxLines) return lines;
- const clipped = lines.slice(0, maxLines);
- const last = clipped[maxLines - 1];
- clipped[maxLines - 1] =
- last.length > maxChars - 1 ? `${last.slice(0, maxChars - 1)}…` : `${last}…`;
- return clipped;
-}
-
-/** Roughly how many headline characters fit one line at the card's title size. */
-const HEADLINE_CHARS_PER_LINE = 26;
-const HEADLINE_MAX_LINES = 4;
-
-/** Localized fallbacks for {@link computeCardModel}. See `share.default*` in `en.ts`. */
-export interface ShareCardFallbacks {
- /** Shown when `data.headline` is empty/blank. */
- headline: string;
- /** Shown when `data.agentName` is empty/blank. */
- agentName: string;
-}
-
-/** English defaults, used when a caller doesn't pass locale-aware fallbacks (e.g. tests). */
-const DEFAULT_CARD_FALLBACKS: ShareCardFallbacks = {
- headline: 'Look what my OpenHuman agent just did',
- agentName: 'My agent',
-};
-
-/**
- * Builds the pure layout model for a card: wrapped headline lines plus the
- * normalised footer/stat fields. No canvas required.
- *
- * `fallbacks` should be sourced from `useT()` at the UI boundary so non-English
- * users don't get English text on the card; it defaults to English for callers
- * that don't have a locale (tests, non-UI callers).
- */
-export function computeCardModel(
- data: ShareCardData,
- fallbacks: ShareCardFallbacks = DEFAULT_CARD_FALLBACKS
-): ShareCardModel {
- const headline = data.headline.trim() || fallbacks.headline;
- return {
- headlineLines: wrapLines(headline, HEADLINE_CHARS_PER_LINE, HEADLINE_MAX_LINES),
- agentName: data.agentName.trim() || fallbacks.agentName,
- stat: data.stat?.trim() ? data.stat.trim() : null,
- brandUrl: data.brandUrl.trim(),
- };
-}
-
-/**
- * Minimal structural subset of `CanvasRenderingContext2D` that `paintShareCard`
- * uses. Declaring it lets tests pass a lightweight mock and lets us paint
- * without depending on a real DOM canvas.
- */
-export interface CardPaintContext {
- fillStyle: string | CanvasGradient;
- strokeStyle: string | CanvasGradient;
- lineWidth: number;
- font: string;
- textBaseline: string;
- textAlign: string;
- globalAlpha: number;
- fillRect(x: number, y: number, w: number, h: number): void;
- fillText(text: string, x: number, y: number): void;
- beginPath(): void;
- arc(x: number, y: number, r: number, start: number, end: number): void;
- fill(): void;
- roundRect?(x: number, y: number, w: number, h: number, radius: number): void;
- rect(x: number, y: number, w: number, h: number): void;
- createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient;
-}
-
-const FONT_SANS =
- 'Inter, "Cabinet Grotesk", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
-const FONT_DISPLAY = '"Cabinet Grotesk", Inter, sans-serif';
-
-/**
- * Paints the full card onto a 2D context sized `CARD_WIDTH`×`CARD_HEIGHT`.
- * Pure with respect to `data` — same input paints the same pixels.
- */
-export function paintShareCard(
- ctx: CardPaintContext,
- data: ShareCardData,
- fallbacks: ShareCardFallbacks = DEFAULT_CARD_FALLBACKS
-): void {
- const model = computeCardModel(data, fallbacks);
-
- // Background: ocean vertical gradient.
- const bg = ctx.createLinearGradient(0, 0, 0, CARD_HEIGHT);
- bg.addColorStop(0, OCEAN);
- bg.addColorStop(1, OCEAN_DEEP);
- ctx.fillStyle = bg;
- ctx.fillRect(0, 0, CARD_WIDTH, CARD_HEIGHT);
-
- const pad = 72;
-
- // Brand wordmark: a dot + "OpenHuman".
- ctx.beginPath();
- ctx.fillStyle = '#FFFFFF';
- ctx.arc(pad + 12, pad + 6, 12, 0, Math.PI * 2);
- ctx.fill();
- ctx.textBaseline = 'alphabetic';
- ctx.textAlign = 'left';
- ctx.font = `700 34px ${FONT_DISPLAY}`;
- ctx.fillStyle = '#FFFFFF';
- ctx.fillText('OpenHuman', pad + 36, pad + 18);
-
- // Headline block.
- ctx.font = `700 62px ${FONT_SANS}`;
- ctx.fillStyle = '#FFFFFF';
- const lineHeight = 74;
- const blockHeight = model.headlineLines.length * lineHeight;
- let y = Math.max(pad + 150, (CARD_HEIGHT - blockHeight) / 2);
- for (const line of model.headlineLines) {
- ctx.fillText(line, pad, y);
- y += lineHeight;
- }
-
- // Optional stat chip below the headline.
- if (model.stat) {
- const chipY = y + 8;
- ctx.globalAlpha = 0.18;
- ctx.fillStyle = '#FFFFFF';
- drawRoundedRect(ctx, pad, chipY, 260, 56, 28);
- ctx.globalAlpha = 1;
- ctx.fillStyle = '#FFFFFF';
- ctx.font = `600 30px ${FONT_SANS}`;
- ctx.fillText(model.stat, pad + 28, chipY + 38);
- }
-
- // Footer: agent name + marketing URL.
- ctx.font = `600 30px ${FONT_SANS}`;
- ctx.fillStyle = 'rgba(255,255,255,0.92)';
- ctx.fillText(model.agentName, pad, CARD_HEIGHT - pad + 6);
- if (model.brandUrl) {
- ctx.textAlign = 'right';
- ctx.font = `500 28px ${FONT_SANS}`;
- ctx.fillStyle = 'rgba(255,255,255,0.82)';
- ctx.fillText(model.brandUrl, CARD_WIDTH - pad, CARD_HEIGHT - pad + 6);
- ctx.textAlign = 'left';
- }
-
- // Faint ink vignette in the bottom-right for depth (kept subtle).
- ctx.globalAlpha = 0.06;
- ctx.fillStyle = INK;
- ctx.fillRect(CARD_WIDTH - 4, 0, 4, CARD_HEIGHT);
- ctx.globalAlpha = 1;
-}
-
-function drawRoundedRect(
- ctx: CardPaintContext,
- x: number,
- y: number,
- w: number,
- h: number,
- radius: number
-): void {
- ctx.beginPath();
- if (typeof ctx.roundRect === 'function') {
- ctx.roundRect(x, y, w, h, radius);
- } else {
- ctx.rect(x, y, w, h);
- }
- ctx.fill();
-}
-
-/**
- * Renders the card into a real DOM canvas (sizing it and acquiring the 2D
- * context). Throws if the context can't be acquired. Browser/Tauri only.
- */
-export function renderShareCardToCanvas(
- canvas: HTMLCanvasElement,
- data: ShareCardData,
- fallbacks: ShareCardFallbacks = DEFAULT_CARD_FALLBACKS
-): void {
- console.debug(`${LOG_PREFIX} render start w=${CARD_WIDTH} h=${CARD_HEIGHT}`);
- canvas.width = CARD_WIDTH;
- canvas.height = CARD_HEIGHT;
- const ctx = canvas.getContext('2d');
- if (!ctx) {
- console.debug(`${LOG_PREFIX} render failed: no 2d context`);
- throw new Error('2d canvas context unavailable');
- }
- try {
- paintShareCard(ctx as unknown as CardPaintContext, data, fallbacks);
- console.debug(`${LOG_PREFIX} render ok`);
- } catch (err) {
- console.debug(
- `${LOG_PREFIX} render failed err_type=${err instanceof Error ? err.name : typeof err}`
- );
- throw err;
- }
-}
-
-/** Serialises a canvas to a PNG blob. Rejects if encoding fails. */
-export function cardToPngBlob(canvas: HTMLCanvasElement): Promise<Blob> {
- console.debug(`${LOG_PREFIX} png export start`);
- return new Promise((resolve, reject) => {
- canvas.toBlob(blob => {
- if (blob) {
- console.debug(`${LOG_PREFIX} png export ok bytes=${blob.size}`);
- resolve(blob);
- } else {
- console.debug(`${LOG_PREFIX} png export failed: toBlob returned null`);
- reject(new Error('canvas.toBlob returned null'));
- }
- }, 'image/png');
- });
-}
diff --git a/app/src/features/share/shareContent.test.ts b/app/src/features/share/shareContent.test.ts
deleted file mode 100644
index e202d0cdb2..0000000000
--- a/app/src/features/share/shareContent.test.ts
+++ /dev/null
@@ -1,208 +0,0 @@
-import { describe, expect, test } from 'vitest';
-
-import {
- buildFallbackHeadline,
- buildShareCaption,
- redactSensitive,
- sanitizeHeadline,
- SHARE_HEADLINE_MAX,
- stripMarkdown,
- truncateAtWord,
- TWEET_MAX,
-} from './shareContent';
-
-describe('redactSensitive', () => {
- test('scrubs API keys', () => {
- expect(redactSensitive('key sk-abcdef0123456789ABCDEF here')).toContain('[redacted]');
- expect(redactSensitive('key sk-abcdef0123456789ABCDEF here')).not.toContain('sk-abcdef');
- });
-
- test('scrubs POSIX and Windows paths', () => {
- expect(redactSensitive('saved to /Users/jane/secret.txt')).toContain('[path]');
- expect(redactSensitive('at C:\\Users\\jane\\notes.md')).toContain('[path]');
- expect(redactSensitive('saved to /Users/jane/secret.txt')).not.toContain('jane');
- });
-
- test('scrubs workspace/application-root paths, including a spaced filename', () => {
- const out = redactSensitive('open /workspace/acme/private plan.txt now');
- expect(out).toContain('[path]');
- expect(out).not.toContain('acme');
- expect(out).not.toContain('private plan');
- // Prose after the path is left alone - the redaction shouldn't eat the sentence.
- expect(out).toContain('now');
- });
-
- test('scrubs an unlabelled opaque base64-like secret', () => {
- const secret = 'aA1bB2cC3dD4eE5fF6gG7hH8iI9jJ0kK1lL2';
- const out = redactSensitive(`token=${secret} saved`);
- expect(out).toContain('[redacted]');
- expect(out).not.toContain(secret);
- });
-
- test('leaves plain prose and short tokens alone', () => {
- const clean = 'Summarised three months of emails in twelve seconds';
- expect(redactSensitive(clean)).toBe(clean);
- });
-
- test('scrubs email addresses', () => {
- expect(redactSensitive('mail [email protected] now')).toContain('[email]');
- });
-
- // The last-resort rule requires an upper-case character so it does not fire on
- // prose. Everything below is lower-case + digits, so it reached the card intact
- // until these patterns were added. Each value is a shape-accurate dummy, not a
- // real credential.
- //
- // Every vendor-prefixed value is assembled from parts on purpose: written as a
- // single literal it carries the vendor's exact token shape, which is what a
- // secret scanner keys on. GitHub push protection already rejects the Slack form
- // outright, and that would block this file for anyone pushing it.
- const assembled = (separator: string, ...parts: string[]) => parts.join(separator);
-
- test.each([
- ['slack bot token', assembled('-', 'xoxb', '123456789012', '987654321098', 'abcdefghijklmnop')],
- [
- 'slack user token',
- assembled('-', 'xoxp', '987654321098', '123456789012', 'zyxwvutsrqponmlk'),
- ],
- ['gitlab personal access token', assembled('-', 'glpat', 'abcdefghij1234567890')],
- ['huggingface token', assembled('_', 'hf', 'abcdefghijklmnopqrstuvwxyz1234')],
- ])('scrubs an all-lower-case %s', (_label, secret) => {
- const out = redactSensitive(`saved ${secret} for you`);
- expect(out).toContain('[redacted]');
- expect(out).not.toContain(secret);
- });
-
- test.each([
- ['slack', 'https://hooks.slack.com/services/T00000000/B00000000/abcdefghijklmnopqrst'],
- [
- 'discord',
- 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz012345',
- ],
- ])('scrubs a %s webhook URL, which carries its secret in the path', (_label, url) => {
- expect(redactSensitive(`posting to ${url} now`)).not.toContain(url);
- });
-
- test('survives stripMarkdown running first, as buildFallbackHeadline runs it', () => {
- // stripMarkdown removes `_`, so a pattern that insisted on it would never match.
- const hfToken = assembled('_', 'hf', 'abcdefghijklmnopqrstuvwxyz1234');
- const head = buildFallbackHeadline(`Done. Saved ${hfToken} for you.`);
- expect(head).not.toContain('abcdefghijklmnopqrstuvwxyz');
- expect(head).toContain('[redacted]');
- });
-
- test('does not fire on ordinary lower-case prose', () => {
- const clean = 'renamed the folder to archive and moved twelve files into it';
- expect(redactSensitive(clean)).toBe(clean);
- });
-
- test('is idempotent and leaves clean prose untouched', () => {
- const clean = 'Summarised three months of emails in twelve seconds';
- expect(redactSensitive(clean)).toBe(clean);
- expect(redactSensitive(redactSensitive(clean))).toBe(clean);
- });
-});
-
-describe('stripMarkdown', () => {
- test('removes fences, emphasis, headings, and links', () => {
- const md = '# Title\n\n**Bold** and _italic_ with [a link](http://x.io)\n```\ncode\n```';
- const out = stripMarkdown(md);
- expect(out).not.toContain('#');
- expect(out).not.toContain('**');
- expect(out).not.toContain('```');
- expect(out).toContain('a link');
- expect(out).not.toContain('http://x.io');
- });
-});
-
-describe('truncateAtWord', () => {
- test('leaves short text unchanged', () => {
- expect(truncateAtWord('hello world', 50)).toBe('hello world');
- });
-
- test('never exceeds max and ends with an ellipsis when cut', () => {
- const out = truncateAtWord('the quick brown fox jumps over the lazy dog', 20);
- expect(out.length).toBeLessThanOrEqual(20);
- expect(out.endsWith('…')).toBe(true);
- });
-});
-
-describe('buildFallbackHeadline', () => {
- test('takes the first sentence and caps length', () => {
- const out = buildFallbackHeadline('Summarised the report. Then did more.');
- expect(out).toBe('Summarised the report');
- expect(out.length).toBeLessThanOrEqual(SHARE_HEADLINE_MAX);
- });
-
- test('returns empty for empty input', () => {
- expect(buildFallbackHeadline(' ')).toBe('');
- });
-
- test('redacts secrets that appear in output', () => {
- expect(buildFallbackHeadline('Wrote key to /Users/jane/.env file')).not.toContain('jane');
- });
-
- // First-sentence extraction was rewritten off a RegExp lookbehind (WebKit
- // 16.4+, unavailable on the macOS 12 system WebView) onto a lookahead
- // (#5571). These pin the equivalence across terminators and boundaries.
- test('splits the first sentence on ! and ? terminators', () => {
- expect(buildFallbackHeadline('Shipped the feature! Then celebrated.')).toBe(
- 'Shipped the feature'
- );
- expect(buildFallbackHeadline('Did the build work? I think so.')).toBe('Did the build work');
- });
-
- test('splits on the first terminator even with extra whitespace', () => {
- expect(buildFallbackHeadline('First thing here. Second thing.')).toBe('First thing here');
- });
-
- test('keeps the whole string when no terminator is followed by whitespace', () => {
- // Periods inside a version string are not followed by whitespace → no boundary.
- expect(buildFallbackHeadline('Bumped to v1.2.3 today')).toBe('Bumped to v1.2.3 today');
- // Terminator at end of input with no trailing whitespace → whole string.
- expect(buildFallbackHeadline('All done here.')).toBe('All done here');
- });
-});
-
-describe('sanitizeHeadline', () => {
- test('strips wrapping quotes and trailing punctuation', () => {
- expect(sanitizeHeadline('"My agent shipped a feature!"')).toBe('My agent shipped a feature');
- });
-
- test('returns empty for too-short garbage', () => {
- expect(sanitizeHeadline('.')).toBe('');
- });
-
- test('caps at the headline max', () => {
- const long = 'word '.repeat(80);
- expect(sanitizeHeadline(long).length).toBeLessThanOrEqual(SHARE_HEADLINE_MAX);
- });
-});
-
-describe('buildShareCaption', () => {
- test('embeds the headline and brand', () => {
- const out = buildShareCaption('My agent summarised my inbox');
- expect(out).toContain('My agent summarised my inbox');
- expect(out).toContain('OpenHuman');
- });
-
- test('falls back to a generic caption for empty headline', () => {
- expect(buildShareCaption('')).toContain('OpenHuman');
- });
-
- test('leaves headroom under the tweet limit', () => {
- const out = buildShareCaption('x'.repeat(400));
- expect(out.length).toBeLessThanOrEqual(TWEET_MAX - 30);
- });
-
- test('uses caller-supplied localized templates instead of English', () => {
- const templates = {
- emptyFallback: 'Mira lo que hizo mi agente.',
- withHeadline: '{headline}. Hecho con mi agente OpenHuman.',
- };
- expect(buildShareCaption('Resumió mi bandeja', templates)).toBe(
- 'Resumió mi bandeja. Hecho con mi agente OpenHuman.'
- );
- expect(buildShareCaption('', templates)).toBe('Mira lo que hizo mi agente.');
- });
-});
diff --git a/app/src/features/share/shareContent.ts b/app/src/features/share/shareContent.ts
deleted file mode 100644
index 63c6f144e0..0000000000
--- a/app/src/features/share/shareContent.ts
+++ /dev/null
@@ -1,200 +0,0 @@
-/**
- * Pure content helpers for the in-app share cards feature (#5006).
- *
- * These functions turn an agent's chat output into the short, on-brand text
- * that appears on the share card and in the pre-filled social caption. They are
- * deliberately dependency-free and synchronous so they can be unit-tested
- * without a running core, a canvas, or the network — the async LLM draft lives
- * in `shareCaption.ts` and delegates its fallback here.
- *
- * PRIVACY (issue #5006 acceptance criterion): nothing private must leak into a
- * shared card. The source text is the assistant message the user already sees,
- * but the agent may have echoed a file path, an API key, or an email address
- * into that reply. `redactSensitive` scrubs those classes before any text is
- * placed on the card or in the caption. Callers must run derived text through
- * it (both `buildFallbackHeadline` and `sanitizeHeadline` already do).
- */
-
-/** Max characters for the headline rendered on the card / seeded into the caption. */
-export const SHARE_HEADLINE_MAX = 90;
-
-/** X (Twitter) hard limit for the tweet body. */
-export const TWEET_MAX = 280;
-
-const LOG_PREFIX = '[share-content]';
-
-/**
- * Patterns for text that must never appear on a public card. Order matters:
- * broad secret tokens first, then paths, then emails. Each is replaced with a
- * neutral placeholder rather than removed so the surrounding sentence still
- * reads naturally.
- */
-const REDACTIONS: ReadonlyArray<{ re: RegExp; with: string }> = [
- // OpenAI / Anthropic / generic provider keys: sk-..., sk-ant-..., etc.
- { re: /\bsk-[a-zA-Z0-9-]{16,}\b/g, with: '[redacted]' },
- // Bearer / auth tokens explicitly labelled.
- { re: /\bBearer\s+[A-Za-z0-9._-]{12,}\b/gi, with: '[redacted]' },
- // AWS access key ids.
- { re: /\bAKIA[0-9A-Z]{16}\b/g, with: '[redacted]' },
- // Vendor-prefixed credentials whose body is lower-case and digits only. The
- // last-resort rule below cannot reach these: it requires an upper-case letter so
- // it does not fire on prose, and an all-lower-case token slips straight past it.
- // The `_` is optional because `stripMarkdown` strips emphasis characters before
- // this runs, so `hf_abc…` arrives here as `hfabc…`.
- { re: /\b(?:xox[abeprs]|xapp)-[A-Za-z0-9-]{10,}/g, with: '[redacted]' },
- { re: /\bglpat-[A-Za-z0-9_-]{16,}/g, with: '[redacted]' },
- { re: /\bhf_?[a-z0-9]{20,}\b/g, with: '[redacted]' },
- // Webhook URLs carry the secret in the path, so the whole URL has to go.
- {
- re: /\bhttps?:\/\/(?:hooks\.slack\.com|discord(?:app)?\.com\/api\/webhooks)\/[^\s"'`)]+/gi,
- with: '[redacted]',
- },
- // Long opaque hex runs (>= 32 chars) that look like secrets, not prose.
- { re: /\b[A-Fa-f0-9]{32,}\b/g, with: '[redacted]' },
- // Long opaque base64/base64url runs (>= 24 chars) that mix upper/lower/digit,
- // e.g. an unlabelled webhook secret, JWT-like value, or provider key. This is
- // intentionally last-resort and biased toward over-redaction: a stray
- // camelCase identifier can trip it, but leaking a real secret onto a public
- // card is the worse outcome. Requiring all three character classes keeps it
- // from firing on plain hex (already caught above) or all-caps constants.
- {
- re: /\b(?=[A-Za-z0-9+/_-]{24,}={0,2}\b)(?=[A-Za-z0-9+/_-]*[A-Z])(?=[A-Za-z0-9+/_-]*[a-z])(?=[A-Za-z0-9+/_-]*[0-9])[A-Za-z0-9+/_-]{24,}={0,2}\b/g,
- with: '[redacted]',
- },
- // POSIX absolute paths under common home/system/workspace/application roots.
- // The optional trailing group covers a single space-separated filename token
- // (e.g. "private plan.txt") without swallowing the rest of the sentence: it
- // only fires when that token itself looks like a filename (has a dot
- // extension), so normal prose following the path is left untouched.
- {
- re: /\/(?:Users|home|root|var|etc|tmp|private|workspace|opt|srv|app|data|mnt|Applications|Volumes)\/(?:[^\s"'`)/]+\/)*[^\s"'`)]+(?:[ \t][^\s"'`)]*\.[A-Za-z0-9]{1,8})?/g,
- with: '[path]',
- },
- // Windows absolute paths and UNC shares.
- { re: /[A-Za-z]:\\[^\s"'`)]+/g, with: '[path]' },
- { re: /\\\\[^\s"'`)]+/g, with: '[path]' },
- // Email addresses (PII).
- { re: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, with: '[email]' },
-];
-
-/**
- * Removes secrets, absolute file paths, and emails from `text`. Idempotent and
- * safe to call on already-clean text. See the module-level PRIVACY note.
- */
-export function redactSensitive(text: string): string {
- let out = text;
- for (const { re, with: replacement } of REDACTIONS) {
- out = out.replace(re, replacement);
- }
- return out;
-}
-
-/**
- * Strips the common markdown syntax an agent reply carries so the card shows
- * clean prose, not raw `**bold**` / `# headings` / ``` fences. Not a full
- * markdown parser — just enough to make a one-line headline readable.
- */
-export function stripMarkdown(text: string): string {
- return (
- text
- // Fenced code blocks -> drop entirely (never headline-worthy).
- .replace(/```[\s\S]*?```/g, ' ')
- // Inline code -> keep the inner text.
- .replace(/`([^`]+)`/g, '$1')
- // Images -> alt text.
- .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')
- // Links -> label only.
- .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
- // Headings / blockquote / list markers at line start.
- .replace(/^\s{0,3}(?:#{1,6}|>|[-*+]|\d+\.)\s+/gm, '')
- // Emphasis markers.
- .replace(/(\*\*|__|\*|_|~~)/g, '')
- // Collapse whitespace.
- .replace(/\s+/g, ' ')
- .trim()
- );
-}
-
-/**
- * Truncates `text` to at most `max` characters on a word boundary, appending an
- * ellipsis when it had to cut. Never returns a string longer than `max`.
- */
-export function truncateAtWord(text: string, max: number): string {
- const trimmed = text.trim();
- if (trimmed.length <= max) return trimmed;
- // Reserve one character for the ellipsis.
- const slice = trimmed.slice(0, max - 1);
- const lastSpace = slice.lastIndexOf(' ');
- const body = lastSpace > max * 0.5 ? slice.slice(0, lastSpace) : slice;
- return `${body.trimEnd()}…`;
-}
-
-/**
- * Builds a deterministic card headline from raw agent output. Used both as the
- * offline fallback when the LLM draft is unavailable and as the input the LLM
- * draft is sanitised against. Returns an empty string if nothing usable remains
- * after cleaning.
- */
-export function buildFallbackHeadline(agentOutput: string): string {
- const cleaned = redactSensitive(stripMarkdown(agentOutput));
- if (!cleaned) return '';
- // Prefer the first sentence; fall back to the whole cleaned string.
- // Match up to and including the first sentence terminator that is followed
- // by whitespace. A lookahead (not a lookbehind) is used deliberately: RegExp
- // lookbehind needs WebKit 16.4, which no macOS 12 (Monterey) system WebView
- // ships, so it would throw before the module loads (#5571).
- const firstSentence = cleaned.match(/^[\s\S]*?[.!?](?=\s)/)?.[0] ?? cleaned;
- const candidate = firstSentence.length >= 12 ? firstSentence : cleaned;
- return truncateAtWord(candidate.replace(/[.!?]+$/, ''), SHARE_HEADLINE_MAX);
-}
-
-/**
- * Normalises a headline that may have come from an LLM: strips wrapping quotes,
- * surrounding markdown, secrets/paths/emails, collapses whitespace, and caps
- * length. Returns an empty string when the result is unusable so the caller can
- * fall back.
- */
-export function sanitizeHeadline(raw: string): string {
- const unquoted = raw.trim().replace(/^["'`]+|["'`]+$/g, '');
- const cleaned = redactSensitive(stripMarkdown(unquoted));
- if (cleaned.length < 3) return '';
- return truncateAtWord(cleaned.replace(/[.!?]+$/, ''), SHARE_HEADLINE_MAX);
-}
-
-/** Localized templates for {@link buildShareCaption}. See `share.default*` / `share.captionWithHeadline` in `en.ts`. */
-export interface ShareCaptionTemplates {
- /** Shown when there's no usable headline. */
- emptyFallback: string;
- /** Template used when a headline is available; must contain a `{headline}` placeholder. */
- withHeadline: string;
-}
-
-/** English defaults, used when a caller doesn't pass locale-aware templates (e.g. tests). */
-const DEFAULT_CAPTION_TEMPLATES: ShareCaptionTemplates = {
- emptyFallback: 'Look what my OpenHuman agent just did.',
- withHeadline: '{headline}. Made with my OpenHuman agent.',
-};
-
-/**
- * Builds the default social caption seeded from a headline. The card carries
- * the branding, so the caption stays short and leaves room for the link the
- * share-intent appends. The user can edit this before posting.
- *
- * `templates` should be sourced from `useT()` at the UI boundary so non-English
- * users don't get an English caption; it defaults to English for callers that
- * don't have a locale (tests, non-UI callers).
- */
-export function buildShareCaption(
- headline: string,
- templates: ShareCaptionTemplates = DEFAULT_CAPTION_TEMPLATES
-): string {
- const clean = headline.trim();
- const base = clean
- ? templates.withHeadline.replace('{headline}', clean)
- : templates.emptyFallback;
- const capped = truncateAtWord(base, TWEET_MAX - 30); // headroom for the link.
- if (capped !== base) {
- console.debug(`${LOG_PREFIX} caption truncated len=${base.length}`);
- }
- return capped;
-}
diff --git a/app/src/features/share/shareTargets.test.ts b/app/src/features/share/shareTargets.test.ts
deleted file mode 100644
index 646278cc14..0000000000
--- a/app/src/features/share/shareTargets.test.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { describe, expect, test } from 'vitest';
-
-import { buildLinkedInShareUrl, buildTweetIntentUrl, SHARE_LANDING_URL } from './shareTargets';
-
-describe('buildTweetIntentUrl', () => {
- test('encodes caption and url as query params', () => {
- const url = buildTweetIntentUrl('Look what my agent did!', SHARE_LANDING_URL);
- expect(url.startsWith('https://twitter.com/intent/tweet?')).toBe(true);
- const parsed = new URL(url);
- expect(parsed.searchParams.get('text')).toBe('Look what my agent did!');
- expect(parsed.searchParams.get('url')).toBe(SHARE_LANDING_URL);
- });
-
- test('defaults to the landing url', () => {
- const parsed = new URL(buildTweetIntentUrl('hi'));
- expect(parsed.searchParams.get('url')).toBe(SHARE_LANDING_URL);
- });
-
- test('trims an over-long caption to leave room for the link', () => {
- const parsed = new URL(buildTweetIntentUrl('a'.repeat(400)));
- const text = parsed.searchParams.get('text') ?? '';
- expect(text.length).toBeLessThanOrEqual(280 - 24);
- expect(text.endsWith('…')).toBe(true);
- });
-});
-
-describe('buildLinkedInShareUrl', () => {
- test('builds a share-offsite url with the target url', () => {
- const url = buildLinkedInShareUrl('https://tinyhumans.ai');
- expect(url.startsWith('https://www.linkedin.com/sharing/share-offsite/?')).toBe(true);
- expect(new URL(url).searchParams.get('url')).toBe('https://tinyhumans.ai');
- });
-
- test('defaults to the landing url', () => {
- expect(new URL(buildLinkedInShareUrl()).searchParams.get('url')).toBe(SHARE_LANDING_URL);
- });
-});
diff --git a/app/src/features/share/shareTargets.ts b/app/src/features/share/shareTargets.ts
deleted file mode 100644
index 3752809abe..0000000000
--- a/app/src/features/share/shareTargets.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * Pure builders for the social share-intent URLs used by the share cards
- * feature (#5006). Kept dependency-free so they can be unit-tested and reused
- * from the modal without pulling in React or Tauri.
- *
- * Neither X nor LinkedIn lets a web intent attach a raw image blob, so the flow
- * is: the user copies/saves the generated PNG, then the intent opens a
- * pre-filled composer they drop the image into. The URL carries the caption and
- * a link back to tinyhumans.ai.
- */
-import { TWEET_MAX } from './shareContent';
-
-/** Canonical marketing URL shared on every card. */
-export const SHARE_LANDING_URL = 'https://tinyhumans.ai';
-
-/**
- * Builds an X (Twitter) web-intent URL that opens the composer pre-filled with
- * `text` and a link to `url`. X counts the (shortened) URL against the 280-char
- * limit as a fixed ~23 chars, so we trim the caption to leave room.
- */
-export function buildTweetIntentUrl(text: string, url: string = SHARE_LANDING_URL): string {
- const URL_WEIGHT = 24; // t.co shortener length + a space.
- const room = Math.max(0, TWEET_MAX - URL_WEIGHT);
- const body = text.length > room ? `${text.slice(0, room - 1).trimEnd()}…` : text;
- const params = new URLSearchParams({ text: body, url });
- return `https://twitter.com/intent/tweet?${params.toString()}`;
-}
-
-/**
- * Builds a LinkedIn share URL. LinkedIn's public share endpoint
- * (`share-offsite`) only accepts a `url`; it ignores any caption/summary
- * parameter (the old `mini`/`summary` params were removed). The caller is
- * therefore expected to copy the caption to the clipboard and prompt the user
- * to paste it — see `ShareCardModal`.
- */
-export function buildLinkedInShareUrl(url: string = SHARE_LANDING_URL): string {
- const params = new URLSearchParams({ url });
- return `https://www.linkedin.com/sharing/share-offsite/?${params.toString()}`;
-}
diff --git a/app/src/hooks/__tests__/useMemoryIngestionStatus.test.ts b/app/src/hooks/__tests__/useMemoryIngestionStatus.test.ts
deleted file mode 100644
index 61dc2f3ca4..0000000000
--- a/app/src/hooks/__tests__/useMemoryIngestionStatus.test.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { act, renderHook, waitFor } from '@testing-library/react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { useMemoryIngestionStatus } from '../useMemoryIngestionStatus';
-
-const mockCallCoreRpc = vi.fn();
-
-vi.mock('../../services/coreRpcClient', () => ({
- callCoreRpc: (args: unknown) => mockCallCoreRpc(args),
-}));
-
-describe('useMemoryIngestionStatus', () => {
- beforeEach(() => {
- mockCallCoreRpc.mockReset();
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it('maps the snake_case RPC envelope into camelCase status', async () => {
- mockCallCoreRpc.mockResolvedValue({
- running: true,
- current_document_id: 'doc-1',
- current_title: 'Notes',
- current_namespace: 'global',
- queue_depth: 2,
- last_completed_at: 1700000000000,
- last_document_id: 'doc-0',
- last_success: true,
- });
-
- const { result } = renderHook(() => useMemoryIngestionStatus());
-
- await waitFor(() => expect(result.current.loading).toBe(false));
-
- expect(result.current.status).toEqual({
- running: true,
- currentDocumentId: 'doc-1',
- currentTitle: 'Notes',
- currentNamespace: 'global',
- queueDepth: 2,
- lastCompletedAt: 1700000000000,
- lastDocumentId: 'doc-0',
- lastSuccess: true,
- });
- expect(result.current.error).toBeNull();
- expect(mockCallCoreRpc).toHaveBeenCalledWith({ method: 'openhuman.memory_ingestion_status' });
- });
-
- it('reports an error when the RPC fails and keeps idle defaults', async () => {
- mockCallCoreRpc.mockRejectedValue(new Error('boom'));
-
- const { result } = renderHook(() => useMemoryIngestionStatus());
-
- await waitFor(() => expect(result.current.loading).toBe(false));
-
- expect(result.current.status.running).toBe(false);
- expect(result.current.status.queueDepth).toBe(0);
- expect(result.current.error).toBe('boom');
- });
-
- it('refresh() re-issues the RPC and updates status', async () => {
- mockCallCoreRpc
- .mockResolvedValueOnce({ running: false, queue_depth: 0 })
- .mockResolvedValueOnce({ running: true, queue_depth: 1, current_document_id: 'doc-2' });
-
- const { result } = renderHook(() => useMemoryIngestionStatus());
- await waitFor(() => expect(result.current.loading).toBe(false));
- expect(result.current.status.running).toBe(false);
-
- await act(async () => {
- await result.current.refresh();
- });
-
- expect(result.current.status.running).toBe(true);
- expect(result.current.status.queueDepth).toBe(1);
- expect(result.current.status.currentDocumentId).toBe('doc-2');
- });
-});
diff --git a/app/src/hooks/useConsciousItems.test.tsx b/app/src/hooks/useConsciousItems.test.tsx
deleted file mode 100644
index 3e56568112..0000000000
--- a/app/src/hooks/useConsciousItems.test.tsx
+++ /dev/null
@@ -1,80 +0,0 @@
-import { act, renderHook } from '@testing-library/react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { useConsciousItems } from './useConsciousItems';
-
-const mockConsciousLoopRun = vi.fn();
-const mockMemoryQueryNamespace = vi.fn();
-
-vi.mock('../utils/tauriCommands', async importOriginal => {
- const actual = await importOriginal<typeof import('../utils/tauriCommands')>();
- return {
- ...actual,
- isTauri: () => true,
- consciousLoopRun: (...args: unknown[]) => mockConsciousLoopRun(...args),
- memoryQueryNamespace: (...args: unknown[]) => mockMemoryQueryNamespace(...args),
- };
-});
-
-// `listen` resolves an unlisten fn but never fires events, so `isRunning` stays
-// false — modelling the window before the backend `conscious_loop:started`
-// event arrives, which is exactly where the duplicate-run race lived.
-vi.mock('@tauri-apps/api/event', () => ({ listen: vi.fn(() => Promise.resolve(() => {})) }));
-
-vi.mock('../lib/coreState/store', () => ({
- getCoreStateSnapshot: () => ({ snapshot: { sessionToken: 'test-token' } }),
-}));
-
-vi.mock('../services/backendUrl', () => ({
- getBackendUrl: () => Promise.resolve('http://localhost:9999'),
-}));
-
-describe('useConsciousItems · triggerAnalysis re-entry guard', () => {
- beforeEach(() => {
- mockConsciousLoopRun.mockReset();
- mockMemoryQueryNamespace.mockReset();
- mockMemoryQueryNamespace.mockResolvedValue({ text: '' });
- });
-
- it('does not start a second run while the first is in flight (before isRunning flips)', async () => {
- let resolveRun: () => void = () => {};
- mockConsciousLoopRun.mockImplementation(
- () =>
- new Promise<void>(resolve => {
- resolveRun = resolve;
- })
- );
-
- const { result } = renderHook(() => useConsciousItems());
-
- // Two synchronous triggers within the pre-`started`-event window: the
- // backend has not yet flipped `isRunning`, so only the synchronous ref
- // guard can stop the duplicate.
- await act(async () => {
- void result.current.triggerAnalysis();
- void result.current.triggerAnalysis();
- });
-
- expect(mockConsciousLoopRun).toHaveBeenCalledTimes(1);
-
- // Settle the in-flight run so the ref releases for the next assertion.
- await act(async () => {
- resolveRun();
- });
- });
-
- it('releases the guard after a run settles so a later run can start', async () => {
- mockConsciousLoopRun.mockResolvedValue(undefined);
-
- const { result } = renderHook(() => useConsciousItems());
-
- await act(async () => {
- await result.current.triggerAnalysis();
- });
- await act(async () => {
- await result.current.triggerAnalysis();
- });
-
- expect(mockConsciousLoopRun).toHaveBeenCalledTimes(2);
- });
-});
diff --git a/app/src/hooks/useConsciousItems.ts b/app/src/hooks/useConsciousItems.ts
deleted file mode 100644
index 33aae86454..0000000000
--- a/app/src/hooks/useConsciousItems.ts
+++ /dev/null
@@ -1,233 +0,0 @@
-/**
- * useConsciousItems
- *
- * Reads actionable items from the `conscious` memory namespace (populated by
- * the Rust conscious loop) and exposes a trigger to kick off a new analysis run.
- *
- * Data flow:
- * conscious_loop_run_inner (Rust)
- * → stores ExtractedActionable JSON docs in `conscious` namespace
- * → emits `conscious_loop:started` / `conscious_loop:completed`
- * useConsciousItems (here)
- * → fetches via memoryQueryNamespace on mount + on completed event
- * → parses JSON objects out of the formatted context string
- * → maps to ActionableItem[]
- */
-import { listen } from '@tauri-apps/api/event';
-import { useCallback, useEffect, useRef, useState } from 'react';
-
-import { getCoreStateSnapshot } from '../lib/coreState/store';
-import { getBackendUrl } from '../services/backendUrl';
-import type {
- ActionableItem,
- ActionableItemPriority,
- ActionableItemSource,
-} from '../types/intelligence';
-import { consciousLoopRun, isTauri, memoryQueryNamespace } from '../utils/tauriCommands';
-
-// ─── Types from conscious_loop.rs (mirrored) ────────────────────────────────
-
-interface ExtractedActionable {
- title: string;
- description?: string;
- source: string;
- priority: string;
- actionable: boolean;
- requires_confirmation: boolean;
- has_complex_action: boolean;
- source_label: string;
-}
-
-// ─── JSON extraction ─────────────────────────────────────────────────────────
-
-/**
- * Walk the context string and extract all valid JSON objects that look like
- * ExtractedActionable items. Uses brace-depth tracking to handle the full
- * object regardless of whitespace or newlines.
- */
-function extractActionablesFromContext(context: string): ExtractedActionable[] {
- const results: ExtractedActionable[] = [];
- const seen = new Set<string>();
- let i = 0;
-
- while (i < context.length) {
- if (context[i] === '{') {
- let depth = 0;
- let j = i;
- while (j < context.length) {
- if (context[j] === '{') depth++;
- else if (context[j] === '}') {
- depth--;
- if (depth === 0) break;
- }
- j++;
- }
- if (depth === 0) {
- try {
- const candidate = context.slice(i, j + 1);
- const parsed = JSON.parse(candidate) as Record<string, unknown>;
- if (
- typeof parsed.title === 'string' &&
- typeof parsed.source === 'string' &&
- typeof parsed.priority === 'string' &&
- !seen.has(parsed.title)
- ) {
- seen.add(parsed.title);
- results.push(parsed as unknown as ExtractedActionable);
- }
- } catch {
- // not valid JSON — skip
- }
- i = j + 1;
- } else {
- i++;
- }
- } else {
- i++;
- }
- }
-
- return results;
-}
-
-// ─── Mapping ─────────────────────────────────────────────────────────────────
-
-const VALID_SOURCES: ActionableItemSource[] = [
- 'email',
- 'calendar',
- 'telegram',
- 'ai_insight',
- 'system',
- 'trading',
- 'security',
-];
-const VALID_PRIORITIES: ActionableItemPriority[] = ['critical', 'important', 'normal'];
-
-function mapToActionableItem(item: ExtractedActionable, index: number): ActionableItem {
- const source: ActionableItemSource = VALID_SOURCES.includes(item.source as ActionableItemSource)
- ? (item.source as ActionableItemSource)
- : 'ai_insight';
-
- const priority: ActionableItemPriority = VALID_PRIORITIES.includes(
- item.priority as ActionableItemPriority
- )
- ? (item.priority as ActionableItemPriority)
- : 'normal';
-
- return {
- id: `conscious-${index}-${item.title.slice(0, 20).replace(/\s+/g, '-')}`,
- title: item.title,
- description: item.description,
- source,
- priority,
- status: 'active',
- createdAt: new Date(),
- updatedAt: new Date(),
- actionable: item.actionable,
- requiresConfirmation: item.requires_confirmation,
- hasComplexAction: item.has_complex_action,
- sourceLabel: item.source_label,
- };
-}
-
-// ─── Hook ─────────────────────────────────────────────────────────────────────
-
-interface UseConsciousItemsResult {
- items: ActionableItem[];
- loading: boolean;
- isRunning: boolean;
- error: string | null;
- refresh: () => Promise<void>;
- triggerAnalysis: () => Promise<void>;
-}
-
-export function useConsciousItems(): UseConsciousItemsResult {
- const [items, setItems] = useState<ActionableItem[]>([]);
- const [loading, setLoading] = useState(false);
- const [isRunning, setIsRunning] = useState(false);
- const [error, setError] = useState<string | null>(null);
-
- // Prevent double-fetch on StrictMode double-mount
- const fetchingRef = useRef(false);
- // Synchronous guard for triggerAnalysis: `isRunning` only flips true once the
- // backend round-trips the `conscious_loop:started` event, leaving a window
- // where a second synchronous call would pass the `isRunning` guard and fire a
- // duplicate run. This ref closes that window immediately (mirrors fetchingRef).
- const runningRef = useRef(false);
-
- const refresh = useCallback(async () => {
- if (fetchingRef.current) return;
- fetchingRef.current = true;
- setLoading(true);
- setError(null);
- try {
- const queryResult = await memoryQueryNamespace(
- 'conscious',
- 'actionable items priority source title description',
- 20
- );
- const extracted = extractActionablesFromContext(queryResult.text);
- setItems(extracted.map(mapToActionableItem));
- } catch (err) {
- const msg = err instanceof Error ? err.message : 'Failed to load conscious items';
- setError(msg);
- } finally {
- setLoading(false);
- fetchingRef.current = false;
- }
- }, []);
-
- const triggerAnalysis = useCallback(async () => {
- const authToken = getCoreStateSnapshot().snapshot.sessionToken;
- if (!isTauri() || !authToken || isRunning || runningRef.current) return;
- runningRef.current = true;
- try {
- await consciousLoopRun(authToken, await getBackendUrl());
- } catch (err) {
- console.warn('[conscious] Failed to trigger analysis:', err);
- } finally {
- runningRef.current = false;
- }
- }, [isRunning]);
-
- // Initial fetch
- useEffect(() => {
- refresh();
- }, [refresh]);
-
- // Listen to conscious loop events
- useEffect(() => {
- if (!isTauri()) return;
-
- let unlistenStarted: (() => void) | undefined;
- let unlistenCompleted: (() => void) | undefined;
-
- listen('conscious_loop:started', () => {
- setIsRunning(true);
- })
- .then(fn => {
- unlistenStarted = fn;
- })
- .catch(console.warn);
-
- listen('conscious_loop:completed', () => {
- setIsRunning(false);
- refresh();
- })
- .then(fn => {
- unlistenCompleted = fn;
- })
- .catch(console.warn);
-
- listen('conscious_loop:error', () => {
- setIsRunning(false);
- }).catch(console.warn);
-
- return () => {
- unlistenStarted?.();
- unlistenCompleted?.();
- };
- }, [refresh]);
-
- return { items, loading, isRunning, error, refresh, triggerAnalysis };
-}
diff --git a/app/src/hooks/useMemoryIngestionStatus.ts b/app/src/hooks/useMemoryIngestionStatus.ts
deleted file mode 100644
index 1ff27a7c80..0000000000
--- a/app/src/hooks/useMemoryIngestionStatus.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-import { useCallback, useEffect, useRef, useState } from 'react';
-
-import { callCoreRpc } from '../services/coreRpcClient';
-
-interface MemoryIngestionStatus {
- running: boolean;
- currentDocumentId?: string;
- currentTitle?: string;
- currentNamespace?: string;
- queueDepth: number;
- lastCompletedAt?: number;
- lastDocumentId?: string;
- lastSuccess?: boolean;
-}
-
-interface IngestionStatusEnvelope {
- running: boolean;
- current_document_id?: string;
- current_title?: string;
- current_namespace?: string;
- queue_depth: number;
- last_completed_at?: number;
- last_document_id?: string;
- last_success?: boolean;
-}
-
-const DEFAULT_POLL_MS = 4000;
-const FAST_POLL_MS = 1500;
-
-const EMPTY_STATUS: MemoryIngestionStatus = { running: false, queueDepth: 0 };
-
-/**
- * Polls `openhuman.memory_ingestion_status`. Polls faster while a job is
- * running or queued so the UI reacts quickly when ingestion finishes;
- * relaxes to a slower cadence at idle.
- */
-export function useMemoryIngestionStatus(): {
- status: MemoryIngestionStatus;
- loading: boolean;
- error: string | null;
- refresh: () => void;
-} {
- const [status, setStatus] = useState<MemoryIngestionStatus>(EMPTY_STATUS);
- const [loading, setLoading] = useState(true);
- const [error, setError] = useState<string | null>(null);
- const cancelledRef = useRef(false);
-
- const fetchOnce = useCallback(async () => {
- try {
- const env = await callCoreRpc<IngestionStatusEnvelope>({
- method: 'openhuman.memory_ingestion_status',
- });
- if (cancelledRef.current) return;
- setStatus({
- running: env.running,
- currentDocumentId: env.current_document_id,
- currentTitle: env.current_title,
- currentNamespace: env.current_namespace,
- queueDepth: env.queue_depth ?? 0,
- lastCompletedAt: env.last_completed_at,
- lastDocumentId: env.last_document_id,
- lastSuccess: env.last_success,
- });
- setError(null);
- } catch (err) {
- if (cancelledRef.current) return;
- setError(err instanceof Error ? err.message : String(err));
- } finally {
- if (!cancelledRef.current) setLoading(false);
- }
- }, []);
-
- const statusRef = useRef(status);
- statusRef.current = status;
-
- useEffect(() => {
- cancelledRef.current = false;
- let timer: ReturnType<typeof setTimeout> | null = null;
-
- const tick = async () => {
- await fetchOnce();
- if (cancelledRef.current) return;
- const live = statusRef.current;
- const delay = live.running || live.queueDepth > 0 ? FAST_POLL_MS : DEFAULT_POLL_MS;
- timer = setTimeout(tick, delay);
- };
-
- void tick();
-
- return () => {
- cancelledRef.current = true;
- if (timer) clearTimeout(timer);
- };
- }, [fetchOnce]);
-
- return { status, loading, error, refresh: fetchOnce };
-}
diff --git a/app/src/lib/errorMessage.test.ts b/app/src/lib/errorMessage.test.ts
deleted file mode 100644
index 12f85db2fa..0000000000
--- a/app/src/lib/errorMessage.test.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { errorMessage } from './errorMessage';
-
-const FALLBACK = 'Something went wrong';
-
-describe('errorMessage', () => {
- it('reads the message off a real Error', () => {
- expect(errorMessage(new Error('boom'), FALLBACK)).toBe('boom');
- });
-
- // The case the helper exists for (#5900). `dispatch(thunk).unwrap()` rethrows
- // Redux Toolkit's SerializedError — a plain object, NOT an Error — so an
- // `instanceof` guard falls through to `String(value)`, which is
- // "[object Object]".
- it('reads the message off a SerializedError-shaped object', () => {
- const serialized = { name: 'Error', message: 'backend refused the profile', stack: '…' };
-
- expect(errorMessage(serialized, FALLBACK)).toBe('backend refused the profile');
- expect(errorMessage(serialized, FALLBACK)).not.toBe('[object Object]');
- });
-
- it('accepts a bare string, which is what rejectWithValue often carries', () => {
- expect(errorMessage('plain failure', FALLBACK)).toBe('plain failure');
- });
-
- it('trims surrounding whitespace', () => {
- expect(errorMessage(new Error(' padded '), FALLBACK)).toBe('padded');
- expect(errorMessage(' bare ', FALLBACK)).toBe('bare');
- expect(errorMessage({ message: ' object ' }, FALLBACK)).toBe('object');
- });
-
- // An empty message is no more useful than none, and rendering it would put a
- // blank alert on screen — worse than the fallback, because it reads as "no
- // error". Same reasoning as `formatThreadCreateError` (threadSlice.ts:117-121).
- it.each([
- ['an Error with an empty message', new Error('')],
- ['an Error with a whitespace message', new Error(' ')],
- ['an object with an empty message', { message: '' }],
- ['an object with a whitespace message', { message: ' ' }],
- ['an empty string', ''],
- ['a whitespace string', ' '],
- ])('falls back for %s', (_label, value) => {
- expect(errorMessage(value, FALLBACK)).toBe(FALLBACK);
- });
-
- it.each([
- ['null', null],
- ['undefined', undefined],
- ['a number', 42],
- ['an object with no message', { code: 500 }],
- ['an object whose message is not a string', { message: { nested: true } }],
- ['an array', ['a', 'b']],
- ])('falls back for %s', (_label, value) => {
- expect(errorMessage(value, FALLBACK)).toBe(FALLBACK);
- });
-
- it('never returns the literal [object Object]', () => {
- for (const value of [{}, { message: {} }, { code: 1 }, Object.create(null)]) {
- expect(errorMessage(value, FALLBACK)).toBe(FALLBACK);
- }
- });
-});
diff --git a/app/src/lib/errorMessage.ts b/app/src/lib/errorMessage.ts
deleted file mode 100644
index 1ba973e133..0000000000
--- a/app/src/lib/errorMessage.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-/**
- * Turn an unknown thrown/rejected value into something worth showing a user.
- *
- * The case this exists for: `dispatch(someThunk()).unwrap()` does NOT reject
- * with an `Error`. For a `createAsyncThunk` that threw, Redux Toolkit rethrows
- * its `SerializedError` — a plain object `{ name, message, stack }` — and for
- * one that used `rejectWithValue`, it rethrows the payload, often a bare
- * string. Neither is an `instanceof Error`.
- *
- * So the common guard
- *
- * err instanceof Error ? err.message : String(err)
- *
- * takes its `String(err)` branch on exactly the shape it was written to
- * handle, and `String({ message: '…' })` is `"[object Object]"`. The user loses
- * the only diagnostic the failure path gives them (#5900), and the same shape
- * caused the "Non-Error promise rejection captured with value" reports in
- * #5156.
- *
- * Read `message` off the value instead of testing its prototype.
- *
- * Two existing helpers already solve this for their own domains —
- * `formatThreadCreateError` (`store/threadSlice.ts`) and `formatThreadLoadError`
- * (`features/conversations/Conversations.tsx`). Both predate this and carry
- * domain-specific fallbacks and, in the thread case, an extra empty-message
- * rule that #5156 depends on; they are deliberately left alone. New call sites
- * should use this.
- *
- * @param error the caught value, of unknown shape
- * @param fallback shown when nothing usable can be recovered
- */
-export function errorMessage(error: unknown, fallback: string): string {
- if (typeof error === 'string' && error.trim().length > 0) return error.trim();
-
- // An `Error` with an empty message is no more useful than no error at all —
- // fall through to the fallback rather than rendering a blank alert.
- if (error instanceof Error && error.message.trim().length > 0) {
- return error.message.trim();
- }
-
- // The SerializedError / rejectWithValue-object case: duck-type `message`
- // rather than testing the prototype, which is the whole bug.
- if (error && typeof error === 'object' && 'message' in error) {
- const message = (error as { message?: unknown }).message;
- if (typeof message === 'string' && message.trim().length > 0) {
- return message.trim();
- }
- }
-
- return fallback;
-}
diff --git a/app/src/pages/onboarding/pages/SkillsPage.test.tsx b/app/src/pages/onboarding/pages/SkillsPage.test.tsx
deleted file mode 100644
index e6289be9d9..0000000000
--- a/app/src/pages/onboarding/pages/SkillsPage.test.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-import { fireEvent, screen, waitFor } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import { renderWithProviders } from '../../../test/test-utils';
-import SkillsPage from './SkillsPage';
-
-const navigateMock = vi.hoisted(() => vi.fn());
-const setDraftMock = vi.hoisted(() => vi.fn());
-const completeAndExitMock = vi.hoisted(() => vi.fn());
-
-vi.mock('react-router-dom', async importOriginal => {
- const actual = await importOriginal<typeof import('react-router-dom')>();
- return { ...actual, useNavigate: () => navigateMock };
-});
-
-vi.mock('../OnboardingContext', () => ({
- useOnboardingContext: () => ({ setDraft: setDraftMock, completeAndExit: completeAndExitMock }),
-}));
-
-vi.mock('../steps/SkillsStep', () => ({
- default: (props: { onNext: (payload: { sources: string[] }) => void | Promise<void> }) => (
- <div>
- <button onClick={() => void props.onNext({ sources: ['composio:gmail'] })}>
- Next with composio
- </button>
- <button onClick={() => void props.onNext({ sources: [] })}>Next without composio</button>
- </div>
- ),
-}));
-
-describe('SkillsPage', () => {
- it('routes to context when a composio source is selected', async () => {
- renderWithProviders(<SkillsPage />);
-
- fireEvent.click(screen.getByRole('button', { name: 'Next with composio' }));
-
- await waitFor(() => {
- expect(navigateMock).toHaveBeenCalledWith('/onboarding/context');
- });
- expect(setDraftMock).toHaveBeenCalledTimes(1);
- const updater = setDraftMock.mock.calls[0][0] as (prev: { connectedSources?: string[] }) => {
- connectedSources: string[];
- };
- expect(updater({ connectedSources: [] }).connectedSources).toEqual(['composio:gmail']);
- expect(completeAndExitMock).not.toHaveBeenCalled();
- });
-
- it('completes onboarding immediately when no composio source is selected', async () => {
- completeAndExitMock.mockResolvedValue(undefined);
- renderWithProviders(<SkillsPage />);
-
- fireEvent.click(screen.getByRole('button', { name: 'Next without composio' }));
-
- await waitFor(() => {
- expect(completeAndExitMock).toHaveBeenCalledTimes(1);
- });
- expect(navigateMock).not.toHaveBeenCalledWith('/onboarding/context');
- expect(setDraftMock).toHaveBeenCalledTimes(1);
- const updater = setDraftMock.mock.calls[0][0] as (prev: { connectedSources?: string[] }) => {
- connectedSources: string[];
- };
- expect(updater({ connectedSources: ['old'] }).connectedSources).toEqual([]);
- });
-});
diff --git a/app/src/pages/onboarding/pages/SkillsPage.tsx b/app/src/pages/onboarding/pages/SkillsPage.tsx
deleted file mode 100644
index 72ffa4bb45..0000000000
--- a/app/src/pages/onboarding/pages/SkillsPage.tsx
+++ /dev/null
@@ -1,29 +0,0 @@
-import { useNavigate } from 'react-router-dom';
-
-import { trackEvent } from '../../../services/analytics';
-import { useOnboardingContext } from '../OnboardingContext';
-import SkillsStep, { type SkillsConnections } from '../steps/SkillsStep';
-
-const SkillsPage = () => {
- const navigate = useNavigate();
- const { setDraft, completeAndExit } = useOnboardingContext();
-
- const handleNext = async ({ sources }: SkillsConnections) => {
- console.debug('[onboarding:skills-page] next', { sources });
- setDraft(prev => ({ ...prev, connectedSources: sources }));
- trackEvent('onboarding_step_complete', { step_name: 'skills' });
-
- // Route to ContextGatheringStep when there's a Composio source the
- // pipeline can drive. Otherwise jump straight to onboarding completion.
- const hasComposioSource = sources.some(s => s.startsWith('composio:'));
- if (hasComposioSource) {
- navigate('/onboarding/context');
- } else {
- await completeAndExit();
- }
- };
-
- return <SkillsStep onNext={handleNext} onBack={() => navigate('/onboarding/welcome')} />;
-};
-
-export default SkillsPage;
diff --git a/app/src/pages/onboarding/steps/SkillsStep.test.tsx b/app/src/pages/onboarding/steps/SkillsStep.test.tsx
deleted file mode 100644
index 1ade91f839..0000000000
--- a/app/src/pages/onboarding/steps/SkillsStep.test.tsx
+++ /dev/null
@@ -1,86 +0,0 @@
-import { fireEvent, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import '../../../test/mockDefaultSkillStatusHooks';
-import { renderWithProviders } from '../../../test/test-utils';
-import SkillsStep from './SkillsStep';
-
-const useComposioIntegrationsMock = vi.hoisted(() => vi.fn());
-vi.mock('../../../lib/composio/hooks', () => ({
- useComposioIntegrations: useComposioIntegrationsMock,
-}));
-
-vi.mock('../../../components/composio/ComposioConnectModal', () => ({
- default: ({
- toolkit,
- onClose,
- onChanged,
- }: {
- toolkit: { name: string };
- onClose: () => void;
- onChanged: () => void;
- }) => (
- <div role="dialog">
- <p>Sign in to {toolkit.name}</p>
- <button
- onClick={() => {
- onChanged();
- onClose();
- }}>
- Mark connected
- </button>
- <button onClick={onClose}>Cancel</button>
- </div>
- ),
-}));
-
-function setComposioState(opts: { connected?: boolean; error?: string | null }): void {
- const { connected = false, error = null } = opts;
- const map = new Map();
- if (connected) {
- map.set('gmail', { toolkit: 'gmail', status: 'ACTIVE', composioState: 'connected' });
- }
- const connectionsMap = new Map(Array.from(map.entries()).map(([k, v]) => [k, [v]]));
- useComposioIntegrationsMock.mockReturnValue({
- toolkits: ['gmail'],
- connectionByToolkit: map,
- connectionsByToolkit: connectionsMap,
- loading: false,
- error,
- refresh: vi.fn(),
- });
-}
-
-describe('Onboarding SkillsStep', () => {
- it('shows the Composio gmail card and skips when nothing is connected', async () => {
- setComposioState({});
- const onNext = vi.fn().mockResolvedValue(undefined);
- renderWithProviders(<SkillsStep onNext={onNext} />);
-
- expect(screen.getByText('Gmail')).toBeInTheDocument();
- expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
-
- fireEvent.click(screen.getByRole('button', { name: 'Skip for Now' }));
- expect(onNext).toHaveBeenCalledWith({ sources: [] });
- });
-
- it('opens the Composio connect modal when the gmail card is clicked', () => {
- setComposioState({});
- renderWithProviders(<SkillsStep onNext={vi.fn()} />);
-
- fireEvent.click(screen.getByTestId('onboarding-skills-gmail-button'));
- expect(screen.getByRole('dialog')).toBeInTheDocument();
- expect(screen.getByText('Sign in to Gmail')).toBeInTheDocument();
- });
-
- it('forwards composio:gmail on continue when gmail is connected', async () => {
- setComposioState({ connected: true });
- const onNext = vi.fn().mockResolvedValue(undefined);
- renderWithProviders(<SkillsStep onNext={onNext} />);
-
- expect(screen.getByText('Connected')).toBeInTheDocument();
-
- fireEvent.click(screen.getByRole('button', { name: 'Continue' }));
- expect(onNext).toHaveBeenCalledWith({ sources: ['composio:gmail'] });
- });
-});
diff --git a/app/src/pages/onboarding/steps/SkillsStep.tsx b/app/src/pages/onboarding/steps/SkillsStep.tsx
deleted file mode 100644
index 7b2e567f8d..0000000000
--- a/app/src/pages/onboarding/steps/SkillsStep.tsx
+++ /dev/null
@@ -1,196 +0,0 @@
-import { useState } from 'react';
-
-import ComposioConnectModal from '../../../components/composio/ComposioConnectModal';
-import {
- composioToolkitMeta,
- type ComposioToolkitMeta,
-} from '../../../components/composio/toolkitMeta';
-import { useComposioIntegrations } from '../../../lib/composio/hooks';
-import { type ComposioConnection, deriveComposioState } from '../../../lib/composio/types';
-import { useT } from '../../../lib/i18n/I18nContext';
-import OnboardingNextButton from '../components/OnboardingNextButton';
-
-export interface SkillsConnections {
- /** Wire-format source ids (e.g. `composio:gmail`). */
- sources: string[];
-}
-
-interface SkillsStepProps {
- onNext: (connections: SkillsConnections) => void | Promise<void>;
- onBack?: () => void;
-}
-
-function statusDotClass(connection: ComposioConnection | undefined): string {
- switch (deriveComposioState(connection)) {
- case 'connected':
- return 'bg-sage-500';
- case 'pending':
- return 'bg-amber-500 animate-pulse';
- case 'expired':
- return 'bg-coral-500';
- case 'error':
- return 'bg-coral-500';
- default:
- return 'bg-content-faint';
- }
-}
-
-function statusLabel(
- state: ReturnType<typeof deriveComposioState>,
- t: (key: string) => string
-): string {
- switch (state) {
- case 'connected':
- return t('skills.connected');
- case 'pending':
- return t('channels.status.connecting');
- case 'expired':
- return t('composio.authExpired');
- case 'error':
- return t('common.error');
- default:
- return '';
- }
-}
-
-function statusColor(state: ReturnType<typeof deriveComposioState>): string {
- switch (state) {
- case 'connected':
- return 'text-sage-600 dark:text-sage-300';
- case 'pending':
- return 'text-amber-600 dark:text-amber-300';
- case 'expired':
- return 'text-coral-600 dark:text-coral-300';
- case 'error':
- return 'text-coral-600 dark:text-coral-300';
- default:
- return 'text-content-faint';
- }
-}
-
-const SkillsStep = ({ onNext, onBack: _onBack }: SkillsStepProps) => {
- const { t } = useT();
- const [submitting, setSubmitting] = useState(false);
- const [error, setError] = useState<string | null>(null);
- const [activeToolkit, setActiveToolkit] = useState<ComposioToolkitMeta | null>(null);
-
- const {
- connectionByToolkit,
- connectionsByToolkit,
- error: composioError,
- refresh: refreshComposio,
- } = useComposioIntegrations();
-
- const gmailMeta = composioToolkitMeta('gmail');
- const gmailConnection = connectionByToolkit.get('gmail');
- const gmailState = deriveComposioState(gmailConnection);
- const gmailConnected = gmailState === 'connected';
-
- const handleContinue = async () => {
- setError(null);
- setSubmitting(true);
- try {
- const sources = gmailConnected ? ['composio:gmail'] : [];
- await onNext({ sources });
- } catch (e) {
- setError(e instanceof Error ? e.message : t('bootCheck.actionFailed'));
- } finally {
- setSubmitting(false);
- }
- };
-
- return (
- <div className="rounded-2xl border border-line bg-surface p-8 shadow-soft animate-fade-up">
- <div className="text-center mb-4">
- <h1 className="text-xl font-bold mb-2 text-content">{t('skills.connect')}</h1>
- <p className="text-content-secondary text-sm">{t('skills.available')}</p>
- </div>
-
- <div className="mb-4 space-y-2">
- {composioError ? (
- <div className="rounded-xl border border-amber-200 dark:border-amber-500/30 bg-amber-50 dark:bg-amber-500/10 p-4 text-center">
- <p className="text-sm text-amber-700 dark:text-amber-300 mb-2">{t('common.error')}</p>
- <button
- type="button"
- onClick={() => void refreshComposio()}
- className="text-xs font-medium text-amber-800 border border-amber-300 rounded-lg px-3 py-1 hover:bg-amber-100 dark:bg-amber-500/20 transition-colors">
- {t('common.retry')}
- </button>
- </div>
- ) : (
- <button
- type="button"
- onClick={() => setActiveToolkit(gmailMeta)}
- data-testid="onboarding-skills-gmail-button"
- className="w-full flex items-center gap-3 rounded-xl border border-line-subtle bg-surface p-3 transition-colors hover:bg-surface-hover text-left">
- <div className="flex h-8 w-8 shrink-0 items-center justify-center text-lg">
- {gmailMeta.icon}
- </div>
-
- <div className="min-w-0 flex-1">
- <div className="flex items-center gap-2">
- <span className="truncate text-sm font-semibold text-content">
- {gmailMeta.name}
- </span>
- {statusLabel(gmailState, t) && (
- <>
- <div
- className={`h-1.5 w-1.5 shrink-0 rounded-full ${statusDotClass(gmailConnection)}`}
- />
- <span className={`shrink-0 text-xs ${statusColor(gmailState)}`}>
- {statusLabel(gmailState, t)}
- </span>
- </>
- )}
- </div>
- <p className="mt-0.5 line-clamp-1 text-xs leading-relaxed text-content-muted">
- {gmailMeta.description}
- </p>
- </div>
-
- <span
- className={`shrink-0 rounded-lg border px-3 py-1.5 text-[11px] font-medium transition-colors ${
- gmailConnected
- ? 'border-sage-200 dark:border-sage-500/30 bg-sage-50 dark:bg-sage-500/10 text-sage-700 dark:text-sage-300'
- : gmailState === 'pending'
- ? 'border-amber-200 dark:border-amber-500/30 bg-amber-50 dark:bg-amber-500/10 text-amber-700 dark:text-amber-300'
- : gmailState === 'expired'
- ? 'border-coral-200 dark:border-coral-500/30 bg-coral-50 dark:bg-coral-500/10 text-coral-700 dark:text-coral-300'
- : 'border-primary-200 dark:border-primary-500/30 bg-primary-50 dark:bg-primary-500/15 text-primary-700 dark:text-primary-300'
- }`}>
- {gmailConnected
- ? t('skills.configure')
- : gmailState === 'expired'
- ? t('composio.reconnect')
- : t('skills.connect')}
- </span>
- </button>
- )}
-
- <div className="rounded-xl border border-line-subtle bg-surface-muted px-3 py-2.5 text-center">
- <p className="text-xs text-content-faint">{t('skills.available')}</p>
- </div>
- </div>
-
- {error && <p className="text-coral-400 text-sm mb-3 text-center">{error}</p>}
-
- <OnboardingNextButton
- onClick={handleContinue}
- loading={submitting}
- loadingLabel={t('common.loading')}
- label={gmailConnected ? t('common.continue') : t('onboarding.skipForNow')}
- />
-
- {activeToolkit && (
- <ComposioConnectModal
- toolkit={activeToolkit}
- connections={connectionsByToolkit?.get(activeToolkit.slug)}
- onChanged={() => void refreshComposio()}
- onClose={() => setActiveToolkit(null)}
- />
- )}
- </div>
- );
-};
-
-export default SkillsStep;
diff --git a/app/src/services/__tests__/mascotService.test.ts b/app/src/services/__tests__/mascotService.test.ts
deleted file mode 100644
index 3151086b05..0000000000
--- a/app/src/services/__tests__/mascotService.test.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import {
- clearMascotDetailCache,
- fetchMascotDetail,
- fetchMascotList,
- getCachedMascotDetail,
-} from '../mascotService';
-
-const getMock = vi.fn();
-
-vi.mock('../apiClient', () => ({ apiClient: { get: (...args: unknown[]) => getMock(...args) } }));
-
-const summary = {
- id: 'yellow',
- name: 'Yellow',
- version: '1.0.0',
- description: '',
- states: [{ id: 'idle', label: 'Idle', description: '' }],
- hasVisemes: true,
-};
-
-const detail = {
- id: 'yellow',
- name: 'Yellow',
- version: '1.0.0',
- description: '',
- viewBox: '0 0 1 1',
- defaultState: 'idle',
- variables: [],
- states: [{ id: 'idle', label: 'Idle', description: '', svg: '<svg/>' }],
- visemes: [],
-};
-
-describe('mascotService', () => {
- beforeEach(() => {
- getMock.mockReset();
- clearMascotDetailCache();
- });
-
- it('fetchMascotList hits /mascots and unwraps the response', async () => {
- getMock.mockResolvedValueOnce({ success: true, data: { mascots: [summary] } });
- const list = await fetchMascotList();
- expect(list).toEqual([summary]);
- expect(getMock).toHaveBeenCalledWith('/mascots', { requireAuth: false });
- });
-
- it('fetchMascotDetail encodes the id and unwraps the manifest', async () => {
- getMock.mockResolvedValueOnce({ success: true, data: { mascot: detail } });
- const d = await fetchMascotDetail('yellow bob');
- expect(d).toEqual(detail);
- expect(getMock).toHaveBeenCalledWith('/mascots/yellow%20bob', { requireAuth: false });
- });
-
- it('rejects an empty id without hitting the network', async () => {
- await expect(fetchMascotDetail(' ')).rejects.toThrow(/empty/i);
- expect(getMock).not.toHaveBeenCalled();
- });
-
- it('getCachedMascotDetail memoizes per id', async () => {
- getMock.mockResolvedValue({ success: true, data: { mascot: detail } });
- const a = await getCachedMascotDetail('yellow');
- const b = await getCachedMascotDetail('yellow');
- expect(a).toBe(b);
- expect(getMock).toHaveBeenCalledTimes(1);
- });
-
- it('clearMascotDetailCache forces a refetch', async () => {
- getMock.mockResolvedValue({ success: true, data: { mascot: detail } });
- await getCachedMascotDetail('yellow');
- clearMascotDetailCache();
- await getCachedMascotDetail('yellow');
- expect(getMock).toHaveBeenCalledTimes(2);
- });
-});
diff --git a/app/src/services/api/agentLibraryApi.test.ts b/app/src/services/api/agentLibraryApi.test.ts
deleted file mode 100644
index a2ec9dd8ec..0000000000
--- a/app/src/services/api/agentLibraryApi.test.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { callCoreRpc } from '../coreRpcClient';
-import { agentLibraryApi } from './agentLibraryApi';
-
-vi.mock('../coreRpcClient', () => ({ callCoreRpc: vi.fn() }));
-
-const mockCall = vi.mocked(callCoreRpc);
-
-describe('agentLibraryApi', () => {
- beforeEach(() => vi.clearAllMocks());
-
- it('lists safe agent definitions through the agent controller', async () => {
- mockCall.mockResolvedValueOnce({
- definitions: [
- {
- id: 'researcher',
- display_name: 'Researcher',
- when_to_use: 'Use for 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',
- },
- ],
- });
-
- await expect(agentLibraryApi.listDefinitions()).resolves.toMatchObject([
- { id: 'researcher', write_capable: false },
- ]);
- expect(mockCall).toHaveBeenCalledWith({
- method: 'openhuman.agent_list_definitions',
- params: {},
- });
- });
-
- it('tolerates a missing definitions field', async () => {
- mockCall.mockResolvedValueOnce({});
- await expect(agentLibraryApi.listDefinitions()).resolves.toEqual([]);
- });
-
- it('tolerates a non-array definitions field', async () => {
- mockCall.mockResolvedValueOnce({ definitions: { id: 'bad-shape' } });
- await expect(agentLibraryApi.listDefinitions()).resolves.toEqual([]);
- });
-});
diff --git a/app/src/services/api/agentLibraryApi.ts b/app/src/services/api/agentLibraryApi.ts
deleted file mode 100644
index 339ad1fb9e..0000000000
--- a/app/src/services/api/agentLibraryApi.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import debug from 'debug';
-
-import { callCoreRpc } from '../coreRpcClient';
-
-const log = debug('agentLibraryApi');
-
-export type AgentDefinitionSource = 'builtin' | 'custom';
-
-export interface AgentDefinitionModel {
- kind: 'inherit' | 'exact' | 'hint' | string;
- value?: string | null;
-}
-
-export interface AgentDefinitionDisplay {
- id: string;
- display_name: string;
- when_to_use: string;
- tier: 'chat' | 'reasoning' | 'worker' | string;
- model: AgentDefinitionModel;
- direct_tool_count: number;
- direct_tool_names: string[];
- uses_wildcard_tools: boolean;
- subagent_ids: string[];
- includes_profile: boolean;
- includes_memory_md: boolean;
- includes_memory_context: boolean;
- can_run_as_user_facing_worker: boolean;
- write_capable: boolean;
- source: AgentDefinitionSource;
-}
-
-export const agentLibraryApi = {
- listDefinitions: async (): Promise<AgentDefinitionDisplay[]> => {
- log('[agent-library] listDefinitions entry');
- const response = await callCoreRpc<{ definitions?: AgentDefinitionDisplay[] }>({
- method: 'openhuman.agent_list_definitions',
- params: {},
- });
- const definitions = Array.isArray(response?.definitions) ? response.definitions : [];
- log('[agent-library] listDefinitions exit count=%d', definitions.length);
- return definitions;
- },
-};
diff --git a/app/src/services/api/agentTeamApi.test.ts b/app/src/services/api/agentTeamApi.test.ts
deleted file mode 100644
index e73e97b9c1..0000000000
--- a/app/src/services/api/agentTeamApi.test.ts
+++ /dev/null
@@ -1,295 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { callCoreRpc } from '../coreRpcClient';
-import { agentTeamApi } from './agentTeamApi';
-
-vi.mock('../coreRpcClient', () => ({ callCoreRpc: vi.fn() }));
-
-const mockCall = vi.mocked(callCoreRpc);
-
-beforeEach(() => {
- vi.clearAllMocks();
-});
-
-describe('agentTeamApi.list', () => {
- it('unwraps the { teams, count } envelope to an array', async () => {
- mockCall.mockResolvedValueOnce({ teams: [{ id: 't1' }, { id: 't2' }], count: 2 });
- const teams = await agentTeamApi.list();
- expect(teams).toHaveLength(2);
- expect(teams[0].id).toBe('t1');
- expect(mockCall).toHaveBeenCalledWith({ method: 'openhuman.agent_team_list', params: {} });
- });
-
- it('returns [] when the envelope omits teams', async () => {
- mockCall.mockResolvedValueOnce({ count: 0 });
- expect(await agentTeamApi.list()).toEqual([]);
- });
-
- it('forwards filters as params', async () => {
- mockCall.mockResolvedValueOnce({ teams: [], count: 0 });
- await agentTeamApi.list({ parentThreadId: 'thread-1', status: 'active', limit: 10 });
- expect(mockCall).toHaveBeenCalledWith({
- method: 'openhuman.agent_team_list',
- params: { parentThreadId: 'thread-1', status: 'active', limit: 10 },
- });
- });
-
- it('rejects a non-positive limit without calling core', async () => {
- await expect(agentTeamApi.list({ limit: 0 })).rejects.toThrow('positive integer');
- await expect(agentTeamApi.list({ limit: 1.5 })).rejects.toThrow('positive integer');
- expect(mockCall).not.toHaveBeenCalled();
- });
-});
-
-describe('agentTeamApi.get', () => {
- it('unwraps { team } to the TeamView', async () => {
- const view = { team: { id: 't1' }, members: [], tasks: [] };
- mockCall.mockResolvedValueOnce({ team: view });
- const result = await agentTeamApi.get('t1');
- expect(result).toBe(view);
- expect(mockCall).toHaveBeenCalledWith({
- method: 'openhuman.agent_team_get',
- params: { teamId: 't1' },
- });
- });
-
- it('returns null when the team is unknown ({ team: null })', async () => {
- mockCall.mockResolvedValueOnce({ team: null });
- expect(await agentTeamApi.get('missing')).toBeNull();
- });
-
- it('throws when teamId is empty, without calling core', async () => {
- await expect(agentTeamApi.get('')).rejects.toThrow('teamId is required');
- expect(mockCall).not.toHaveBeenCalled();
- });
-});
-
-describe('agentTeamApi.listMessages', () => {
- it('unwraps { messages } and narrows each run-event payload', async () => {
- mockCall.mockResolvedValueOnce({
- messages: [
- {
- runId: 'team-1',
- sequence: 1,
- eventType: 'team_message',
- payload: { from: 'm1', to: 'm2', content: 'hi', visibility: 'team' },
- timestamp: '2026-01-01T00:00:00Z',
- },
- ],
- });
- const messages = await agentTeamApi.listMessages('team-1');
- expect(messages).toHaveLength(1);
- expect(messages[0].payload).toEqual({
- from: 'm1',
- to: 'm2',
- content: 'hi',
- visibility: 'team',
- });
- });
-
- it('defends against a malformed payload (missing fields → safe defaults)', async () => {
- mockCall.mockResolvedValueOnce({
- messages: [
- {
- runId: 'team-1',
- sequence: 2,
- eventType: 'team_message',
- payload: { from: 'm1' },
- timestamp: '2026-01-01T00:00:00Z',
- },
- ],
- });
- const [msg] = await agentTeamApi.listMessages('team-1');
- expect(msg.payload).toEqual({ from: 'm1', to: null, content: '', visibility: 'team' });
- });
-
- it('returns [] when the envelope omits messages', async () => {
- mockCall.mockResolvedValueOnce({});
- expect(await agentTeamApi.listMessages('team-1')).toEqual([]);
- });
-
- it('forwards an explicit limit, omits it otherwise', async () => {
- mockCall.mockResolvedValueOnce({ messages: [] });
- await agentTeamApi.listMessages('team-1', 50);
- expect(mockCall).toHaveBeenCalledWith({
- method: 'openhuman.agent_team_list_messages',
- params: { teamId: 'team-1', limit: 50 },
- });
- mockCall.mockResolvedValueOnce({ messages: [] });
- await agentTeamApi.listMessages('team-1');
- expect(mockCall).toHaveBeenLastCalledWith({
- method: 'openhuman.agent_team_list_messages',
- params: { teamId: 'team-1' },
- });
- });
-});
-
-describe('agentTeamApi.completeTask', () => {
- it('unwraps { result } and defaults evidence + requireEvidence', async () => {
- mockCall.mockResolvedValueOnce({ result: { kind: 'completed', id: 'task-1', status: 'done' } });
- const outcome = await agentTeamApi.completeTask({
- teamId: 'team-1',
- taskId: 'task-1',
- memberId: 'm1',
- });
- expect(outcome.kind).toBe('completed');
- expect(mockCall).toHaveBeenCalledWith({
- method: 'openhuman.agent_team_complete_task',
- params: {
- teamId: 'team-1',
- taskId: 'task-1',
- memberId: 'm1',
- evidence: [],
- requireEvidence: false,
- },
- });
- });
-
- it('forwards evidence + requireEvidence and surfaces a gateFailed outcome', async () => {
- mockCall.mockResolvedValueOnce({
- result: { kind: 'gateFailed', reasons: ['completion requires at least one evidence link'] },
- });
- const outcome = await agentTeamApi.completeTask({
- teamId: 'team-1',
- taskId: 'task-1',
- memberId: 'm1',
- evidence: ['proof'],
- requireEvidence: true,
- });
- expect(outcome).toEqual({
- kind: 'gateFailed',
- reasons: ['completion requires at least one evidence link'],
- });
- expect(mockCall).toHaveBeenCalledWith({
- method: 'openhuman.agent_team_complete_task',
- params: {
- teamId: 'team-1',
- taskId: 'task-1',
- memberId: 'm1',
- evidence: ['proof'],
- requireEvidence: true,
- },
- });
- });
-
- it('throws when a required id is missing, without calling core', async () => {
- await expect(
- agentTeamApi.completeTask({ teamId: '', taskId: 't', memberId: 'm' })
- ).rejects.toThrow('required');
- expect(mockCall).not.toHaveBeenCalled();
- });
-});
-
-describe('agentTeamApi.shutdownMember', () => {
- it('unwraps { result } to the MemberShutdown', async () => {
- const result = { member: { id: 'm1', memberStatus: 'stopped' }, releasedTaskIds: ['task-1'] };
- mockCall.mockResolvedValueOnce({ result });
- const outcome = await agentTeamApi.shutdownMember('team-1', 'm1');
- expect(outcome).toBe(result);
- expect(mockCall).toHaveBeenCalledWith({
- method: 'openhuman.agent_team_shutdown_member',
- params: { teamId: 'team-1', memberId: 'm1' },
- });
- });
-
- it('throws when teamId or memberId is empty, without calling core', async () => {
- await expect(agentTeamApi.shutdownMember('', 'm1')).rejects.toThrow('required');
- await expect(agentTeamApi.shutdownMember('team-1', '')).rejects.toThrow('required');
- expect(mockCall).not.toHaveBeenCalled();
- });
-});
-
-describe('agentTeamApi.messageMember', () => {
- it('narrows the { message } event and omits absent optional fields', async () => {
- mockCall.mockResolvedValueOnce({
- message: {
- runId: 'team-1',
- sequence: 5,
- eventType: 'team_message',
- payload: { from: 'lead', to: 'm1', content: 'go', visibility: 'team' },
- timestamp: '2026-01-01T00:00:00Z',
- },
- });
- const msg = await agentTeamApi.messageMember({
- teamId: 'team-1',
- toMemberId: 'm1',
- content: 'go',
- });
- expect(msg.payload).toEqual({ from: 'lead', to: 'm1', content: 'go', visibility: 'team' });
- // fromMemberId omitted → lead origin; no empty keys forwarded.
- expect(mockCall).toHaveBeenCalledWith({
- method: 'openhuman.agent_team_message_member',
- params: { teamId: 'team-1', content: 'go', toMemberId: 'm1' },
- });
- });
-
- it('forwards fromMemberId for teammate-to-teammate messages', async () => {
- mockCall.mockResolvedValueOnce({
- message: {
- runId: 'team-1',
- sequence: 6,
- eventType: 'team_message',
- payload: { from: 'm1', to: 'm2', content: 'hi', visibility: 'team' },
- timestamp: '2026-01-01T00:00:00Z',
- },
- });
- await agentTeamApi.messageMember({
- teamId: 'team-1',
- fromMemberId: 'm1',
- toMemberId: 'm2',
- content: 'hi',
- });
- expect(mockCall).toHaveBeenCalledWith({
- method: 'openhuman.agent_team_message_member',
- params: { teamId: 'team-1', content: 'hi', fromMemberId: 'm1', toMemberId: 'm2' },
- });
- });
-
- it('throws on empty content or teamId, without calling core', async () => {
- await expect(agentTeamApi.messageMember({ teamId: '', content: 'x' })).rejects.toThrow(
- 'teamId is required'
- );
- await expect(agentTeamApi.messageMember({ teamId: 'team-1', content: ' ' })).rejects.toThrow(
- 'content is required'
- );
- expect(mockCall).not.toHaveBeenCalled();
- });
-});
-
-describe('agentTeamApi.startMember', () => {
- it('unwraps { result } and forwards an explicit taskId', async () => {
- mockCall.mockResolvedValueOnce({
- result: { kind: 'started', runId: 'teamrun-1', task: { id: 'task-1' } },
- });
- const outcome = await agentTeamApi.startMember({
- teamId: 'team-1',
- memberId: 'm1',
- taskId: 'task-1',
- });
- expect(outcome).toEqual({ kind: 'started', runId: 'teamrun-1', task: { id: 'task-1' } });
- expect(mockCall).toHaveBeenCalledWith({
- method: 'openhuman.agent_team_start_member',
- params: { teamId: 'team-1', memberId: 'm1', taskId: 'task-1' },
- });
- });
-
- it('omits taskId when auto-picking and surfaces a blocked outcome', async () => {
- mockCall.mockResolvedValueOnce({ result: { kind: 'blocked', unmet: ['task-a'] } });
- const outcome = await agentTeamApi.startMember({ teamId: 'team-1', memberId: 'm1' });
- expect(outcome).toEqual({ kind: 'blocked', unmet: ['task-a'] });
- expect(mockCall).toHaveBeenCalledWith({
- method: 'openhuman.agent_team_start_member',
- params: { teamId: 'team-1', memberId: 'm1' },
- });
- });
-
- it('throws when teamId or memberId is empty, without calling core', async () => {
- await expect(agentTeamApi.startMember({ teamId: '', memberId: 'm1' })).rejects.toThrow(
- 'required'
- );
- await expect(agentTeamApi.startMember({ teamId: 'team-1', memberId: '' })).rejects.toThrow(
- 'required'
- );
- expect(mockCall).not.toHaveBeenCalled();
- });
-});
diff --git a/app/src/services/api/agentTeamApi.ts b/app/src/services/api/agentTeamApi.ts
deleted file mode 100644
index c96726ea1c..0000000000
--- a/app/src/services/api/agentTeamApi.ts
+++ /dev/null
@@ -1,336 +0,0 @@
-/**
- * Frontend client for the durable agent-team coordination surface (#3374).
- *
- * Wraps the `openhuman.agent_team_*` controller family from the durable team
- * ledger (PR1, #3546): the read paths `agent_team_list`, `agent_team_get`, and
- * `agent_team_list_messages`, plus two lifecycle writes added with quality-gated
- * completion — `agent_team_complete_task` and `agent_team_shutdown_member`.
- * PR4 adds the two user-driven writes the Teams UI needs: `messageMember`
- * (address a named teammate / broadcast) and `startMember` (spawn a live worker
- * on a task). Creating teams, assigning, and claiming tasks stay the agents'
- * job (driven over the same controllers from the run loop), so those write
- * methods are deliberately absent here.
- *
- * The Rust controllers serialize their row types with
- * `#[serde(rename_all = "camelCase")]`, so the wire payload is already camelCase
- * and no snake/camel transform is needed. What this client DOES own is
- * normalizing the controllers' inconsistent response envelopes — `get` returns
- * `{ team }`, `list` returns `{ teams, count }`, `list_messages` returns
- * `{ messages }` — into the clean shapes the UI consumes. Quarantining that
- * here means components never see the wrapper objects, and if the backend later
- * normalizes its envelopes only this file changes.
- */
-import debug from 'debug';
-
-import { callCoreRpc } from '../coreRpcClient';
-
-const log = debug('agentTeamApi');
-
-/** Lifecycle of a team. Mirrors Rust `AgentTeamStatus`. */
-export type AgentTeamStatus = 'active' | 'closed';
-
-/** Lifecycle of a single member. Mirrors Rust `AgentTeamMemberStatus`. */
-export type AgentTeamMemberStatus = 'pending' | 'active' | 'idle' | 'stopped';
-
-/** Lifecycle of a coordination task. Mirrors Rust `AgentTeamTaskStatus`. */
-type AgentTeamTaskStatus = 'todo' | 'ready' | 'in_progress' | 'blocked' | 'done';
-
-/** A team header row. Mirrors Rust `AgentTeam`. */
-export interface AgentTeam {
- id: string;
- parentThreadId?: string | null;
- leadAgentId: string;
- status: AgentTeamStatus;
- summary?: string | null;
- createdAt: string;
- updatedAt: string;
- closedAt?: string | null;
-}
-
-/** A member of a team. Mirrors Rust `AgentTeamMember`. */
-export interface AgentTeamMember {
- id: string;
- teamId: string;
- name: string;
- agentId?: string | null;
- memberStatus: AgentTeamMemberStatus;
- currentTaskId?: string | null;
- workerThreadId?: string | null;
- runId?: string | null;
- createdAt: string;
- updatedAt: string;
-}
-
-/** A coordination task within a team. Mirrors Rust `AgentTeamTask`. */
-interface AgentTeamTask {
- id: string;
- teamId: string;
- title: string;
- objective?: string | null;
- status: AgentTeamTaskStatus;
- ownerMemberId?: string | null;
- claimedByMemberId?: string | null;
- claimToken?: string | null;
- /** Task ids this task depends on. Unmet (non-`done`) deps block a claim. */
- dependsOn: string[];
- /** Free-form gate status. Known: `pending` / `passed` / `failed`; default `pending`. */
- gateStatus: string;
- gateReason?: string | null;
- evidence: string[];
- sourceRunId?: string | null;
- orderIndex: number;
- createdAt: string;
- updatedAt: string;
-}
-
-/** A team plus its members and tasks. Mirrors Rust `TeamView` (the `get` shape). */
-interface TeamView {
- team: AgentTeam;
- members: AgentTeamMember[];
- tasks: AgentTeamTask[];
-}
-
-/**
- * Outcome of a completion attempt. Mirrors Rust `CompletionOutcome`, which is an
- * internally-tagged enum on `kind`: `completed` flattens the resulting task onto
- * the object; `gateFailed` carries the unmet-invariant reasons; the rest are
- * bare tags.
- */
-type CompletionOutcome =
- | ({ kind: 'completed' } & AgentTeamTask)
- | { kind: 'gateFailed'; reasons: string[] }
- | { kind: 'notClaimed' }
- | { kind: 'unknownTask' };
-
-/** Result of stopping a member. Mirrors Rust `MemberShutdown`. */
-interface MemberShutdown {
- member: AgentTeamMember;
- releasedTaskIds: string[];
-}
-
-/**
- * Outcome of starting a live run for a member. Mirrors Rust `StartMemberOutcome`
- * (internally-tagged on `kind`): `started` carries the dispatched `runId` and the
- * claimed task; the rest explain why no worker was spawned.
- */
-type StartMemberOutcome =
- | { kind: 'started'; runId: string; task: AgentTeamTask }
- | { kind: 'blocked'; unmet: string[] }
- | { kind: 'alreadyClaimed' }
- | { kind: 'alreadyActive' }
- | { kind: 'noClaimableTask' }
- | { kind: 'unknownTask' };
-
-/** Parsed payload of a `team_message` run event. Mirrors the Rust `json!` body. */
-export interface TeamMessagePayload {
- from: string;
- to: string | null;
- content: string;
- visibility: string;
-}
-
-/** A teammate message. A `team_message` run event with its payload typed. */
-export interface TeamMessage {
- runId: string;
- sequence: number;
- eventType: string;
- payload: TeamMessagePayload;
- timestamp: string;
-}
-
-/** Raw `RunEvent` wire shape before the payload is narrowed to a message. */
-interface RawRunEvent {
- runId: string;
- sequence: number;
- eventType: string;
- payload: unknown;
- timestamp: string;
-}
-
-/** Optional filters for {@link agentTeamApi.list}. Mirrors `AgentTeamListRequest`. */
-interface AgentTeamListParams {
- parentThreadId?: string;
- status?: AgentTeamStatus;
- limit?: number;
- offset?: number;
-}
-
-function assertPositiveInt(value: number | undefined, label: string): void {
- if (value !== undefined && (!Number.isInteger(value) || value <= 0)) {
- throw new Error(`agentTeamApi: ${label} must be a positive integer`);
- }
-}
-
-/** Coerce a raw run-event payload into a typed message payload, defensively. */
-function readMessagePayload(payload: unknown): TeamMessagePayload {
- const p = (payload ?? {}) as Record<string, unknown>;
- return {
- from: typeof p.from === 'string' ? p.from : '',
- to: typeof p.to === 'string' ? p.to : null,
- content: typeof p.content === 'string' ? p.content : '',
- visibility: typeof p.visibility === 'string' ? p.visibility : 'team',
- };
-}
-
-export const agentTeamApi = {
- /**
- * List team headers, newest first. Filters are optional; `parentThreadId`
- * scopes to one conversation, `status` to active/closed.
- *
- * Unwraps the controller's `{ teams, count }` envelope down to `AgentTeam[]`.
- */
- list: async (params: AgentTeamListParams = {}): Promise<AgentTeam[]> => {
- assertPositiveInt(params.limit, 'limit');
- log('list params=%o', params);
- const response = await callCoreRpc<{ teams?: AgentTeam[]; count?: number }>({
- method: 'openhuman.agent_team_list',
- params,
- });
- const teams = response.teams ?? [];
- log('list received teams=%d count=%o', teams.length, response.count);
- return teams;
- },
-
- /**
- * Fetch one team plus its members and tasks. Returns `null` when the id is
- * unknown (the controller answers `{ team: null }`).
- */
- get: async (teamId: string): Promise<TeamView | null> => {
- if (!teamId) throw new Error('agentTeamApi.get: teamId is required');
- log('get teamId=%s', teamId);
- const response = await callCoreRpc<{ team: TeamView | null }>({
- method: 'openhuman.agent_team_get',
- params: { teamId },
- });
- log('get found=%o', response.team != null);
- return response.team ?? null;
- },
-
- /**
- * List a team's teammate messages in sequence order. Unwraps the
- * `{ messages }` envelope and narrows each run-event payload to a typed
- * {@link TeamMessagePayload}.
- */
- listMessages: async (teamId: string, limit?: number): Promise<TeamMessage[]> => {
- if (!teamId) throw new Error('agentTeamApi.listMessages: teamId is required');
- assertPositiveInt(limit, 'limit');
- log('listMessages teamId=%s limit=%o', teamId, limit);
- const response = await callCoreRpc<{ messages?: RawRunEvent[] }>({
- method: 'openhuman.agent_team_list_messages',
- params: limit === undefined ? { teamId } : { teamId, limit },
- });
- const messages = (response.messages ?? []).map(event => ({
- runId: event.runId,
- sequence: event.sequence,
- eventType: event.eventType,
- payload: readMessagePayload(event.payload),
- timestamp: event.timestamp,
- }));
- log('listMessages received=%d', messages.length);
- return messages;
- },
-
- /**
- * Complete a claimed task, gating its transition to `done`. The core checks
- * the quality invariants (dependencies done, the completer is the claimant and
- * any pre-assigned owner, evidence present when `requireEvidence`) and returns
- * a {@link CompletionOutcome}: `completed`, `gateFailed` (with reasons),
- * `notClaimed`, or `unknownTask`. Evidence links accumulate across retries.
- */
- completeTask: async (params: {
- teamId: string;
- taskId: string;
- memberId: string;
- evidence?: string[];
- requireEvidence?: boolean;
- }): Promise<CompletionOutcome> => {
- const { teamId, taskId, memberId, evidence = [], requireEvidence = false } = params;
- if (!teamId || !taskId || !memberId) {
- throw new Error('agentTeamApi.completeTask: teamId, taskId and memberId are required');
- }
- log('completeTask teamId=%s taskId=%s requireEvidence=%o', teamId, taskId, requireEvidence);
- const response = await callCoreRpc<{ result: CompletionOutcome }>({
- method: 'openhuman.agent_team_complete_task',
- params: { teamId, taskId, memberId, evidence, requireEvidence },
- });
- log('completeTask kind=%s', response.result.kind);
- return response.result;
- },
-
- /**
- * Stop a member and release any task it is actively working on back to `todo`.
- * Returns the stopped member plus the ids that were released.
- */
- shutdownMember: async (teamId: string, memberId: string): Promise<MemberShutdown> => {
- if (!teamId || !memberId) {
- throw new Error('agentTeamApi.shutdownMember: teamId and memberId are required');
- }
- log('shutdownMember teamId=%s memberId=%s', teamId, memberId);
- const response = await callCoreRpc<{ result: MemberShutdown }>({
- method: 'openhuman.agent_team_shutdown_member',
- params: { teamId, memberId },
- });
- log('shutdownMember released=%d', response.result.releasedTaskIds.length);
- return response.result;
- },
-
- /**
- * Send a message to a named teammate (or broadcast when `toMemberId` is
- * omitted). `fromMemberId` is omitted for a lead/user-originated message — the
- * core stores it with `from = "lead"`. Returns the appended message event.
- */
- messageMember: async (params: {
- teamId: string;
- toMemberId?: string;
- fromMemberId?: string;
- content: string;
- visibility?: string;
- }): Promise<TeamMessage> => {
- const { teamId, toMemberId, fromMemberId, content, visibility } = params;
- if (!teamId) throw new Error('agentTeamApi.messageMember: teamId is required');
- if (!content.trim()) throw new Error('agentTeamApi.messageMember: content is required');
- log('messageMember teamId=%s to=%o from=%o', teamId, toMemberId, fromMemberId);
- const response = await callCoreRpc<{ message: RawRunEvent }>({
- method: 'openhuman.agent_team_message_member',
- params: {
- teamId,
- content,
- ...(fromMemberId ? { fromMemberId } : {}),
- ...(toMemberId ? { toMemberId } : {}),
- ...(visibility ? { visibility } : {}),
- },
- });
- const event = response.message;
- return {
- runId: event.runId,
- sequence: event.sequence,
- eventType: event.eventType,
- payload: readMessagePayload(event.payload),
- timestamp: event.timestamp,
- };
- },
-
- /**
- * Start a live run for a member: the core claims a task (the explicit `taskId`,
- * else the member's next claimable one) and spawns a worker that runs it to
- * completion. Returns a {@link StartMemberOutcome} — `started` (worker
- * dispatched) or a reason no work began.
- */
- startMember: async (params: {
- teamId: string;
- memberId: string;
- taskId?: string;
- }): Promise<StartMemberOutcome> => {
- const { teamId, memberId, taskId } = params;
- if (!teamId || !memberId) {
- throw new Error('agentTeamApi.startMember: teamId and memberId are required');
- }
- log('startMember teamId=%s memberId=%s taskId=%o', teamId, memberId, taskId);
- const response = await callCoreRpc<{ result: StartMemberOutcome }>({
- method: 'openhuman.agent_team_start_member',
- params: { teamId, memberId, ...(taskId ? { taskId } : {}) },
- });
- log('startMember kind=%s', response.result.kind);
- return response.result;
- },
-};
diff --git a/app/src/services/api/workflowRunsApi.test.ts b/app/src/services/api/workflowRunsApi.test.ts
deleted file mode 100644
index 28e3900b94..0000000000
--- a/app/src/services/api/workflowRunsApi.test.ts
+++ /dev/null
@@ -1,166 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { callCoreRpc } from '../coreRpcClient';
-import {
- assessWorkflowCost,
- type WorkflowDefinition,
- type WorkflowRun,
- workflowRunsApi,
-} from './workflowRunsApi';
-
-vi.mock('../coreRpcClient', () => ({ callCoreRpc: vi.fn() }));
-
-const mockRpc = vi.mocked(callCoreRpc);
-
-function def(overrides: Partial<WorkflowDefinition> = {}): WorkflowDefinition {
- return {
- id: 'parallel_research_cross_check',
- name: 'Parallel research with cross-checking',
- description: 'Decompose, research in parallel, cross-check, synthesize.',
- phases: [
- { name: 'decompose', description: '', agentIds: ['planner'], dependsOn: [] },
- {
- name: 'research',
- description: '',
- agentIds: ['researcher', 'researcher'],
- dependsOn: ['decompose'],
- },
- ],
- defaultConcurrency: 2,
- maxChildren: 8,
- safetyTier: 'read_only',
- ...overrides,
- };
-}
-
-function run(overrides: Partial<WorkflowRun> = {}): WorkflowRun {
- return {
- id: 'wfrun-1',
- definitionId: 'parallel_research_cross_check',
- parentThreadId: null,
- input: { question: 'why is the sky blue?' },
- phaseStates: {},
- childRunIds: [],
- status: 'running',
- summary: null,
- startedAt: '2026-01-01T00:00:00Z',
- updatedAt: '2026-01-01T00:00:00Z',
- completedAt: null,
- ...overrides,
- };
-}
-
-describe('assessWorkflowCost', () => {
- it('requires approval for the builtin (maxChildren >= 8)', () => {
- const result = assessWorkflowCost(def({ maxChildren: 8, defaultConcurrency: 2 }));
- expect(result.requiresApproval).toBe(true);
- expect(result.reasons).toContain('high_children');
- });
-
- it('does not require approval for a small read-only fan-out', () => {
- const result = assessWorkflowCost(
- def({ maxChildren: 4, defaultConcurrency: 2, safetyTier: 'read_only' })
- );
- expect(result.requiresApproval).toBe(false);
- expect(result.reasons).toHaveLength(0);
- });
-
- it('flags non-read-only tiers', () => {
- const result = assessWorkflowCost(
- def({ maxChildren: 2, defaultConcurrency: 1, safetyTier: 'edit_capable' })
- );
- expect(result.requiresApproval).toBe(true);
- expect(result.reasons).toContain('non_read_only_tier');
- });
-
- it('flags high concurrency', () => {
- const result = assessWorkflowCost(
- def({ maxChildren: 2, defaultConcurrency: 4, safetyTier: 'read_only' })
- );
- expect(result.requiresApproval).toBe(true);
- expect(result.reasons).toContain('high_concurrency');
- });
-});
-
-describe('workflowRunsApi', () => {
- beforeEach(() => mockRpc.mockReset());
-
- it('listDefinitions calls the RPC and returns the array', async () => {
- mockRpc.mockResolvedValueOnce({ definitions: [def()], count: 1 });
- const defs = await workflowRunsApi.listDefinitions();
- expect(mockRpc).toHaveBeenCalledWith({ method: 'openhuman.workflow_run_list_definitions' });
- expect(defs).toHaveLength(1);
- expect(defs[0].id).toBe('parallel_research_cross_check');
- });
-
- it('listDefinitions tolerates a missing array', async () => {
- mockRpc.mockResolvedValueOnce({});
- expect(await workflowRunsApi.listDefinitions()).toEqual([]);
- });
-
- it('listRuns forwards filters and returns the runs array', async () => {
- mockRpc.mockResolvedValueOnce({ runs: [run()], count: 1 });
- const runs = await workflowRunsApi.listRuns({ limit: 50, status: 'running' });
- expect(mockRpc).toHaveBeenCalledWith({
- method: 'openhuman.workflow_run_list',
- params: { limit: 50, status: 'running' },
- });
- expect(runs).toHaveLength(1);
- expect(runs[0].id).toBe('wfrun-1');
- });
-
- it('listRuns defaults params and tolerates a missing array', async () => {
- mockRpc.mockResolvedValueOnce({});
- const runs = await workflowRunsApi.listRuns();
- expect(mockRpc).toHaveBeenCalledWith({ method: 'openhuman.workflow_run_list', params: {} });
- expect(runs).toEqual([]);
- });
-
- it('getRun returns the run when present', async () => {
- mockRpc.mockResolvedValueOnce({ workflowRun: run() });
- const fetched = await workflowRunsApi.getRun('wfrun-1');
- expect(mockRpc).toHaveBeenCalledWith({
- method: 'openhuman.workflow_run_get',
- params: { id: 'wfrun-1' },
- });
- expect(fetched?.id).toBe('wfrun-1');
- });
-
- it('startRun forwards definitionId + input and returns the run', async () => {
- mockRpc.mockResolvedValueOnce({ workflowRun: run() });
- const started = await workflowRunsApi.startRun({
- definitionId: 'parallel_research_cross_check',
- input: { question: 'q' },
- });
- expect(mockRpc).toHaveBeenCalledWith({
- method: 'openhuman.workflow_run_start',
- params: { definitionId: 'parallel_research_cross_check', input: { question: 'q' } },
- });
- expect(started.id).toBe('wfrun-1');
- });
-
- it('getRun returns null when the run is absent', async () => {
- mockRpc.mockResolvedValueOnce({ workflowRun: null });
- expect(await workflowRunsApi.getRun('nope')).toBeNull();
- });
-
- it('stopRun returns the updated run', async () => {
- mockRpc.mockResolvedValueOnce({ workflowRun: run({ status: 'interrupted' }) });
- const stopped = await workflowRunsApi.stopRun('wfrun-1');
- expect(mockRpc).toHaveBeenCalledWith({
- method: 'openhuman.workflow_run_stop',
- params: { id: 'wfrun-1' },
- });
- expect(stopped?.status).toBe('interrupted');
- });
-
- it('resumeRun returns the resumed run', async () => {
- mockRpc.mockResolvedValueOnce({ workflowRun: run({ status: 'running' }) });
- const resumed = await workflowRunsApi.resumeRun('wfrun-1');
- expect(mockRpc).toHaveBeenCalledWith({
- method: 'openhuman.workflow_run_resume',
- params: { id: 'wfrun-1' },
- });
- expect(resumed.status).toBe('running');
- });
-});
diff --git a/app/src/services/api/workflowRunsApi.ts b/app/src/services/api/workflowRunsApi.ts
deleted file mode 100644
index 7d3879d21e..0000000000
--- a/app/src/services/api/workflowRunsApi.ts
+++ /dev/null
@@ -1,266 +0,0 @@
-/**
- * Frontend client for the declarative workflow-runs engine (#3375).
- *
- * Wraps the six `openhuman.workflow_run_*` JSON-RPC controllers exposed by the
- * Rust `workflow_runs` domain:
- * - `workflow_run_list_definitions` — catalog of runnable workflow definitions
- * - `workflow_run_list` — durable runs (with filters / paging)
- * - `workflow_run_get` — single run (poll target for progress)
- * - `workflow_run_start` — start a run from a definition id
- * - `workflow_run_stop` — interrupt a running workflow
- * - `workflow_run_resume` — resume an interrupted workflow
- *
- * The Rust controllers serialize structs with `rename_all = "camelCase"` and
- * the status / safety-tier enums with `rename_all = "snake_case"`, so the wire
- * payload already matches these TypeScript shapes — no snake/camel transform is
- * needed. Progress is poll-based in this engine (no socket events yet): start a
- * run, then poll `getRun(id)` until `status` is terminal.
- */
-import debug from 'debug';
-
-import { trackAnalyticsEvent } from '../analytics';
-import { callCoreRpc } from '../coreRpcClient';
-
-const log = debug('workflowRunsApi');
-
-// ---------------------------------------------------------------------------
-// Wire types — mirror `crates/openhuman-core/src/workflow_runs/types.rs`.
-// ---------------------------------------------------------------------------
-
-/** What a workflow's child agents are permitted to do. (`snake_case` on wire.) */
-export type WorkflowSafetyTier = 'read_only' | 'standard' | 'edit_capable';
-
-/** Lifecycle status of a durable run. (`snake_case` on wire.) */
-export type WorkflowRunStatus =
- | 'pending'
- | 'running'
- | 'completed'
- | 'failed'
- | 'cancelled'
- | 'interrupted';
-
-/** Per-phase progress status inside `WorkflowRun.phaseStates`. */
-export type WorkflowPhaseStatus = 'pending' | 'running' | 'completed' | 'failed';
-
-/** One ordered phase of a workflow definition. */
-export interface WorkflowPhase {
- /** Unique within the definition (e.g. "decompose", "research"). */
- name: string;
- /** Human-readable purpose. */
- description: string;
- /** Agent definition ids fanned out (in parallel) for this phase. */
- agentIds: string[];
- /** Phase names that must complete before this one runs. */
- dependsOn: string[];
-}
-
-/** A runnable workflow definition (builtin or, later, user-authored). */
-export interface WorkflowDefinition {
- id: string;
- name: string;
- description: string;
- phases: WorkflowPhase[];
- /** Max agents run concurrently within a single phase. */
- defaultConcurrency: number;
- /** Hard cap on child agents spawned across the whole run. */
- maxChildren: number;
- safetyTier: WorkflowSafetyTier;
-}
-
-/** One child agent's result within a phase. */
-export interface WorkflowPhaseOutput {
- /** Orchestration id of the spawned child agent. */
- orchestrationId: string;
- /** Agent definition id (e.g. "code_executor"). */
- agentId: string;
- /** The child's result summary. */
- output: string;
-}
-
-/** Progress record for a single phase, keyed by phase name in `phaseStates`. */
-export interface WorkflowPhaseState {
- status: WorkflowPhaseStatus;
- outputs: WorkflowPhaseOutput[];
- /** Present only when `status === 'failed'`. */
- reason?: string;
-}
-
-/** A durable workflow run. Mirrors the Rust `WorkflowRun`. */
-export interface WorkflowRun {
- id: string;
- definitionId: string;
- parentThreadId: string | null;
- /** Run input object (e.g. `{ question: "..." }`). */
- input: unknown;
- /** Per-phase progress, keyed by phase name. */
- phaseStates: Record<string, WorkflowPhaseState>;
- /** Orchestration ids of every spawned child agent. */
- childRunIds: string[];
- status: WorkflowRunStatus;
- /** Final synthesized output — present once `status === 'completed'`. */
- summary: string | null;
- startedAt: string;
- updatedAt: string;
- completedAt: string | null;
-}
-
-interface ListDefinitionsResult {
- definitions: WorkflowDefinition[];
- count: number;
-}
-
-interface ListRunsResult {
- runs: WorkflowRun[];
- count: number;
-}
-
-interface RunResult {
- workflowRun: WorkflowRun;
-}
-
-interface MaybeRunResult {
- workflowRun: WorkflowRun | null;
-}
-
-/** Filters accepted by `workflow_run_list`. */
-interface ListRunsParams {
- definitionId?: string;
- status?: WorkflowRunStatus;
- parentThreadId?: string;
- limit?: number;
- offset?: number;
-}
-
-/** Parameters accepted by `workflow_run_start`. */
-interface StartRunParams {
- definitionId: string;
- /** Run input, e.g. `{ question: "..." }` or `{ modelOverride: "..." }`. */
- input?: Record<string, unknown>;
- /** Originating thread id, for lineage. */
- parentThreadId?: string;
-}
-
-// ---------------------------------------------------------------------------
-// Cost / concurrency safety gate (#3375 AC: high-cost runs require approval).
-// ---------------------------------------------------------------------------
-
-/**
- * Why a run is considered high-cost / high-concurrency and therefore gated
- * behind explicit approval. Stable codes — the UI maps each to a localized
- * sentence so the user understands what they're approving.
- */
-export type WorkflowCostReason = 'non_read_only_tier' | 'high_concurrency' | 'high_children';
-
-interface WorkflowCostAssessment {
- /** True when the definition must be explicitly approved before starting. */
- requiresApproval: boolean;
- /** Machine-readable reasons (empty when no approval required). */
- reasons: WorkflowCostReason[];
-}
-
-/**
- * Per-phase concurrency at or above this is treated as high-concurrency.
- * The builtin parallel-research workflow runs at 2, so routine read-only
- * fan-outs stay frictionless; only unusually wide phases trip the gate.
- */
-const HIGH_CONCURRENCY_THRESHOLD = 4;
-
-/**
- * Total child-agent budget at or above this is treated as high-cost — every
- * child is a full agent turn (tokens + wall-clock), so a large cap is the
- * clearest proxy for spend in the absence of an explicit cost field.
- */
-const HIGH_CHILDREN_THRESHOLD = 8;
-
-/**
- * Decide whether starting `def` needs explicit user approval.
- *
- * The Rust safety tiers exist on the definition but the engine does not yet
- * gate on them, so the approval decision lives here on the client: any
- * non-`read_only` tier (child agents may take actions / edit files), or a
- * wide/expensive fan-out, requires the user to confirm before we call
- * `startRun`. Read-only, low-fan-out definitions start immediately.
- */
-export function assessWorkflowCost(def: WorkflowDefinition): WorkflowCostAssessment {
- const reasons: WorkflowCostReason[] = [];
- if (def.safetyTier !== 'read_only') reasons.push('non_read_only_tier');
- if (def.defaultConcurrency >= HIGH_CONCURRENCY_THRESHOLD) reasons.push('high_concurrency');
- if (def.maxChildren >= HIGH_CHILDREN_THRESHOLD) reasons.push('high_children');
- return { requiresApproval: reasons.length > 0, reasons };
-}
-
-// ---------------------------------------------------------------------------
-// RPC client.
-// ---------------------------------------------------------------------------
-
-export const workflowRunsApi = {
- /** List available declarative workflow definitions (builtins, currently). */
- listDefinitions: async (): Promise<WorkflowDefinition[]> => {
- log('listDefinitions: request');
- const result = await callCoreRpc<ListDefinitionsResult>({
- method: 'openhuman.workflow_run_list_definitions',
- });
- const definitions = result?.definitions ?? [];
- log('listDefinitions: count=%d', definitions.length);
- return definitions;
- },
-
- /** List durable workflow runs, newest first, with optional filters. */
- listRuns: async (params: ListRunsParams = {}): Promise<WorkflowRun[]> => {
- log('listRuns: request %o', params);
- const result = await callCoreRpc<ListRunsResult>({
- method: 'openhuman.workflow_run_list',
- params,
- });
- const runs = result?.runs ?? [];
- log('listRuns: count=%d', runs.length);
- return runs;
- },
-
- /** Fetch a single run by id. Returns null when no such run exists. */
- getRun: async (id: string): Promise<WorkflowRun | null> => {
- log('getRun: request id=%s', id);
- const result = await callCoreRpc<MaybeRunResult>({
- method: 'openhuman.workflow_run_get',
- params: { id },
- });
- const run = result?.workflowRun ?? null;
- log('getRun: status=%s', run?.status ?? 'null');
- return run;
- },
-
- /** Start a run from a definition id; returns the created Running run. */
- startRun: async (params: StartRunParams): Promise<WorkflowRun> => {
- log('startRun: request definitionId=%s', params.definitionId);
- const result = await callCoreRpc<RunResult>({ method: 'openhuman.workflow_run_start', params });
- log('startRun: id=%s status=%s', result.workflowRun.id, result.workflowRun.status);
- trackAnalyticsEvent('automation_run_started', { automation_kind: 'orchestration' });
- return result.workflowRun;
- },
-
- /** Stop a running workflow after its current phase. Null if id unknown. */
- stopRun: async (id: string): Promise<WorkflowRun | null> => {
- log('stopRun: request id=%s', id);
- const result = await callCoreRpc<MaybeRunResult>({
- method: 'openhuman.workflow_run_stop',
- params: { id },
- });
- log('stopRun: status=%s', result?.workflowRun?.status ?? 'null');
- if (result?.workflowRun) {
- trackAnalyticsEvent('automation_run_cancelled', { automation_kind: 'orchestration' });
- }
- return result?.workflowRun ?? null;
- },
-
- /** Resume an interrupted workflow from the first incomplete phase. */
- resumeRun: async (id: string): Promise<WorkflowRun> => {
- log('resumeRun: request id=%s', id);
- const result = await callCoreRpc<RunResult>({
- method: 'openhuman.workflow_run_resume',
- params: { id },
- });
- log('resumeRun: status=%s', result.workflowRun.status);
- trackAnalyticsEvent('automation_run_resumed', { automation_kind: 'orchestration' });
- return result.workflowRun;
- },
-};
diff --git a/app/src/services/mascotService.test.ts b/app/src/services/mascotService.test.ts
deleted file mode 100644
index 58913ba22c..0000000000
--- a/app/src/services/mascotService.test.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import type { RiveMascotDetail } from '../features/human/Mascot/backend/types';
-import { loadRivBuffer } from '../features/human/Mascot/rivCache';
-import { getBackendUrl } from './backendUrl';
-import { loadMascotRivBuffer } from './mascotService';
-
-vi.mock('../features/human/Mascot/rivCache', () => ({ loadRivBuffer: vi.fn() }));
-vi.mock('./backendUrl', () => ({ getBackendUrl: vi.fn() }));
-vi.mock('./apiClient', () => ({ apiClient: { get: vi.fn() } }));
-
-const rive: RiveMascotDetail = {
- id: 'toshi',
- name: 'Toshi',
- version: '1.0.0',
- description: '',
- format: 'rive',
- rivFileUrl: '/mascots/toshi/riv?v=1.0.0',
- defaultState: 'idle',
- stateToPose: {},
- viewModelInputs: [],
-};
-
-describe('loadMascotRivBuffer', () => {
- beforeEach(() => {
- vi.mocked(getBackendUrl).mockResolvedValue('https://api.example.test');
- vi.mocked(loadRivBuffer).mockResolvedValue(new ArrayBuffer(8));
- });
-
- it('composes the absolute, version-stamped URL and delegates to the cache', async () => {
- const buf = await loadMascotRivBuffer(rive);
- expect(buf).toBeInstanceOf(ArrayBuffer);
- expect(loadRivBuffer).toHaveBeenCalledWith(
- 'toshi',
- '1.0.0',
- 'https://api.example.test/mascots/toshi/riv?v=1.0.0'
- );
- });
-});
diff --git a/app/src/services/mascotService.ts b/app/src/services/mascotService.ts
deleted file mode 100644
index 184d106a3d..0000000000
--- a/app/src/services/mascotService.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-// Client for the backend mascot library — GET /mascots (summaries) and
-// GET /mascots/:id (full manifest with per-state SVGs + visemes).
-//
-// Backend: tinyhumansai/backend PR #770. Both endpoints are public
-// (manifests only, no compute) so we skip auth.
-import type {
- GetMascotResponse,
- ListMascotsResponse,
- MascotDetailUnion,
- MascotSummary,
- RiveMascotDetail,
-} from '../features/human/Mascot/backend/types';
-import { loadRivBuffer } from '../features/human/Mascot/rivCache';
-import { apiClient } from './apiClient';
-import { getBackendUrl } from './backendUrl';
-
-export async function fetchMascotList(): Promise<MascotSummary[]> {
- const res = await apiClient.get<ListMascotsResponse>('/mascots', { requireAuth: false });
- return res.data.mascots;
-}
-
-export async function fetchMascotDetail(id: string): Promise<MascotDetailUnion> {
- const safe = encodeURIComponent(id.trim());
- if (!safe) throw new Error('mascot id is empty');
- const res = await apiClient.get<GetMascotResponse>(`/mascots/${safe}`, { requireAuth: false });
- return res.data.mascot;
-}
-
-/**
- * Resolve a Rive mascot's binary, version-cached in IndexedDB. The backend
- * stamps `version` into both the manifest and the `rivFileUrl` (`?v=`), so the
- * binary is only re-downloaded when that version changes.
- */
-export async function loadMascotRivBuffer(detail: RiveMascotDetail): Promise<ArrayBuffer> {
- const base = await getBackendUrl();
- // rivFileUrl is backend-relative (e.g. "/mascots/toshi/riv?v=1.0.0").
- const url = `${base}${detail.rivFileUrl}`;
- return loadRivBuffer(detail.id, detail.version, url);
-}
-
-/**
- * Lightweight in-memory cache for manifest fetches. Manifests carry the
- * full SVG bytes for every state (~ tens of KB per mascot) — the WebRTC
- * pipeline keeps them in mongo and the picker UI revisits selections,
- * so a per-id memoization keeps the picker snappy without hammering the
- * backend.
- */
-const detailCache = new Map<string, MascotDetailUnion>();
-
-export async function getCachedMascotDetail(id: string): Promise<MascotDetailUnion> {
- const existing = detailCache.get(id);
- if (existing) return existing;
- const detail = await fetchMascotDetail(id);
- detailCache.set(id, detail);
- return detail;
-}
-
-export function clearMascotDetailCache(): void {
- detailCache.clear();
-}
diff --git a/app/src/utils/userName.ts b/app/src/utils/userName.ts
deleted file mode 100644
index e93bab2cfd..0000000000
--- a/app/src/utils/userName.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- * Resolve a human-friendly display name from a core-owned user snapshot,
- * tolerating both camelCase and snake_case identity fields. Returns the
- * literal `'User'` when nothing usable is present.
- *
- * Shared by the Home greeting and the bottom-bar avatar so both derive the
- * same name from the same source.
- */
-export function resolveUserName(user: unknown): string {
- if (!user || typeof user !== 'object') return 'User';
-
- const record = user as Record<string, unknown>;
- const firstName =
- (typeof record.firstName === 'string' && record.firstName.trim()) ||
- (typeof record.first_name === 'string' && record.first_name.trim()) ||
- '';
- const lastName =
- (typeof record.lastName === 'string' && record.lastName.trim()) ||
- (typeof record.last_name === 'string' && record.last_name.trim()) ||
- '';
- const username = typeof record.username === 'string' ? record.username.trim() : '';
- const email = typeof record.email === 'string' ? record.email.trim() : '';
-
- const fullName = [firstName, lastName].filter(Boolean).join(' ').trim();
- if (fullName) return fullName;
- if (firstName) return firstName;
- if (username) return username.startsWith('@') ? username : `@${username}`;
- if (email) return email.split('@')[0] || 'User';
- return 'User';
-}
diff --git a/app/src/utils/withTimeout.test.ts b/app/src/utils/withTimeout.test.ts
deleted file mode 100644
index d3b5578a22..0000000000
--- a/app/src/utils/withTimeout.test.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { toolExecutionTimeoutMsFromEnv, withTimeout } from './withTimeout';
-
-// Provide TOOL_TIMEOUT_SECS that the global setup mock omits.
-vi.mock('./config', async importOriginal => {
- const actual = await importOriginal<typeof import('./config')>();
- return { ...actual, TOOL_TIMEOUT_SECS: 120 };
-});
-
-describe('withTimeout', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it('resolves with the promise value when it settles before the timeout', async () => {
- const promise = Promise.resolve('ok');
- const result = await withTimeout(promise, 5000, 'fast-op');
- expect(result).toBe('ok');
- });
-
- it('rejects with a timeout error when the timeout elapses first', async () => {
- // withTimeout creates an internal timeoutPromise that rejects. When
- // Promise.race settles via that rejection, the internal promise itself
- // has no handler yet — Node surfaces it as an unhandled rejection warning.
- // We suppress it by attaching a catch to the overall race before advancing
- // the timer, then asserting on the stored error.
- let capturedError: unknown;
- const never = new Promise<never>(() => {});
-
- const racePromise = withTimeout(never, 3000, 'slow-op').catch((e: unknown) => {
- capturedError = e;
- // Swallow here — we assert manually below.
- });
-
- await vi.advanceTimersByTimeAsync(3001);
- await racePromise; // wait for the catch branch to complete
-
- expect(capturedError).toBeInstanceOf(Error);
- expect((capturedError as Error).message).toBe('slow-op timed out after 3s');
- });
-
- it('error message rounds timeout to seconds', async () => {
- let capturedError: unknown;
- const never = new Promise<never>(() => {});
-
- const racePromise = withTimeout(never, 2500, 'half-sec').catch((e: unknown) => {
- capturedError = e;
- });
-
- await vi.advanceTimersByTimeAsync(3000);
- await racePromise;
-
- expect(capturedError).toBeInstanceOf(Error);
- // Math.round(2500 / 1000) === 3
- expect((capturedError as Error).message).toBe('half-sec timed out after 3s');
- });
-
- it('passes through a rejection from the underlying promise', async () => {
- const failing = Promise.reject(new Error('upstream failure'));
- failing.catch(() => {}); // suppress premature unhandled warning
- await expect(withTimeout(failing, 5000, 'fail-op')).rejects.toThrow('upstream failure');
- });
-
- it('does not fire the timeout when the promise rejects quickly', async () => {
- const err = new Error('quick rejection');
- const failing = Promise.reject(err);
- failing.catch(() => {}); // suppress premature unhandled warning
- const racePromise = withTimeout(failing, 5000, 'quick-fail');
-
- await expect(racePromise).rejects.toThrow('quick rejection');
-
- // Advance well past the timeout — timer should already be cleared.
- await vi.advanceTimersByTimeAsync(10000);
- });
-
- it('bypasses the timeout when timeoutMs <= 0 and returns the raw promise', async () => {
- const promise = Promise.resolve(42);
- const result = await withTimeout(promise, 0, 'zero-timeout');
- expect(result).toBe(42);
- });
-
- it('bypasses the timeout for negative timeoutMs', async () => {
- const promise = Promise.resolve('neg');
- const result = await withTimeout(promise, -1, 'negative-timeout');
- expect(result).toBe('neg');
- });
-
- it('resolves with complex return types', async () => {
- const payload = { id: 1, data: [true, 'hello'] };
- const result = await withTimeout(Promise.resolve(payload), 1000, 'complex');
- expect(result).toEqual(payload);
- });
-
- it('clears the timer when the promise resolves (no dangling timer)', async () => {
- const clearSpy = vi.spyOn(globalThis, 'clearTimeout');
- await withTimeout(Promise.resolve('done'), 5000, 'cleanup-check');
- expect(clearSpy).toHaveBeenCalled();
- });
-});
-
-describe('toolExecutionTimeoutMsFromEnv', () => {
- it('returns a positive number of milliseconds', () => {
- const ms = toolExecutionTimeoutMsFromEnv();
- expect(ms).toBeGreaterThan(0);
- expect(Number.isFinite(ms)).toBe(true);
- });
-
- it('returns 120 000 ms matching the mocked TOOL_TIMEOUT_SECS of 120', () => {
- const ms = toolExecutionTimeoutMsFromEnv();
- // TOOL_TIMEOUT_SECS is mocked to 120 by this file's vi.mock above.
- expect(ms).toBe(120_000);
- });
-});
diff --git a/app/src/utils/withTimeout.ts b/app/src/utils/withTimeout.ts
deleted file mode 100644
index 069f3160aa..0000000000
--- a/app/src/utils/withTimeout.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { TOOL_TIMEOUT_SECS } from './config';
-
-/**
- * Reject with a clear error if `promise` does not settle within `timeoutMs`.
- * Clears the timer when the promise completes.
- */
-export async function withTimeout<T>(
- promise: Promise<T>,
- timeoutMs: number,
- label: string
-): Promise<T> {
- if (timeoutMs <= 0) return promise;
-
- let timer: ReturnType<typeof setTimeout> | undefined;
- const timeoutPromise = new Promise<never>((_, reject) => {
- timer = setTimeout(() => {
- reject(new Error(`${label} timed out after ${Math.round(timeoutMs / 1000)}s`));
- }, timeoutMs);
- });
-
- try {
- return await Promise.race([promise, timeoutPromise]);
- } finally {
- if (timer !== undefined) clearTimeout(timer);
- }
-}
-
-/** Default matches core `OPENHUMAN_TOOL_TIMEOUT_SECS` (120). */
-export function toolExecutionTimeoutMsFromEnv(): number {
- return Math.round(TOOL_TIMEOUT_SECS * 1000);
-}