The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(intelligence): migrate memory components to new engine architecture
Steven Enamakel874262b22e70
diff --git a/app/src/components/intelligence/AddMemorySourceDialog.test.tsx b/app/src/components/intelligence/AddMemorySourceDialog.test.tsxdeleted file mode 100644index f5b3ea1fe5..0000000000--- a/app/src/components/intelligence/AddMemorySourceDialog.test.tsx+++ /dev/null@@ -1,489 +0,0 @@-/**- * Tests for the AddMemorySourceDialog — focused on the Composio connection- * picker: deduplication, readable labels, and no raw connection IDs in the- * rendered dropdown (issue #3356).- */-import { fireEvent, screen, waitFor } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { listConnections } from '../../lib/composio/composioApi';-import { getSupportedToolkits } from '../../services/memorySourcesService';-import { renderWithProviders } from '../../test/test-utils';-import { AddMemorySourceDialog, deduplicateConnections } from './AddMemorySourceDialog';--// ----------------------------------------------------------------------------// Module mocks-// -----------------------------------------------------------------------------vi.mock('../../lib/composio/composioApi', () => ({ listConnections: vi.fn() }));--vi.mock('../../services/memorySourcesService', () => ({- addMemorySource: vi.fn(),- getSupportedToolkits: vi.fn(),- SOURCE_KIND_ICONS: {- folder: '📁',- composio: '🔗',- conversation: '💬',- github_repo: '🐙',- rss_feed: '📡',- web_page: '🌐',- twitter_query: '🐦',- },- SOURCE_KIND_LABEL_KEYS: {- folder: 'memorySources.kind.folder',- composio: 'memorySources.kind.composio',- conversation: 'memorySources.kind.conversation',- github_repo: 'memorySources.kind.github_repo',- rss_feed: 'memorySources.kind.rss_feed',- web_page: 'memorySources.kind.web_page',- twitter_query: 'memorySources.kind.twitter_query',- },-}));--const mockListConnections = listConnections as ReturnType<typeof vi.fn>;-const mockGetSupportedToolkits = getSupportedToolkits as ReturnType<typeof vi.fn>;--/** Every toolkit used across the picker component tests is syncable by default,- * so existing assertions keep passing. Tests that exercise the disabled /- * "Coming soon" path override this with a narrower set. */-const DEFAULT_SUPPORTED = ['gmail', 'slack', 'notion', 'github', 'linear', 'clickup'];--// ----------------------------------------------------------------------------// Helper-// -----------------------------------------------------------------------------function renderDialog() {- const onClose = vi.fn();- const onAdded = vi.fn();- renderWithProviders(<AddMemorySourceDialog open onClose={onClose} onAdded={onAdded} />);- return { onClose, onAdded };-}--async function openComposioStep() {- renderDialog();- // The i18n context renders the real English string from en.ts- const integrationBtn = screen.getByText('Integration');- fireEvent.click(integrationBtn);- // Wait for async connection fetch- await waitFor(() => expect(mockListConnections).toHaveBeenCalledTimes(1));-}--/** Open the custom connection dropdown so its option rows render. */-async function openListbox() {- const trigger = await screen.findByTestId('composio-connection-picker');- fireEvent.click(trigger);- await screen.findByTestId('composio-connection-listbox');-}--// ----------------------------------------------------------------------------// Unit tests: deduplicateConnections helper-// -----------------------------------------------------------------------------describe('deduplicateConnections', () => {- it('returns an empty array for empty input', () => {- expect(deduplicateConnections([])).toEqual([]);- });-- it('uses accountEmail as the identity label', () => {- const conn = {- id: 'conn-1',- toolkit: 'Gmail',- status: 'ACTIVE',- accountEmail: '[email protected]',- };- const result = deduplicateConnections([conn]);- expect(result).toHaveLength(1);- expect(result[0].label).toBe('Gmail · [email protected]');- expect(result[0].conn.id).toBe('conn-1');- });-- it('falls back to workspace when accountEmail is absent', () => {- const conn = { id: 'conn-2', toolkit: 'Slack', status: 'ACTIVE', workspace: 'my-workspace' };- const result = deduplicateConnections([conn]);- expect(result[0].label).toBe('Slack · my-workspace');- });-- it('falls back to username when neither email nor workspace is present', () => {- const conn = { id: 'conn-3', toolkit: 'GitHub', status: 'ACTIVE', username: 'octocat' };- const result = deduplicateConnections([conn]);- expect(result[0].label).toBe('GitHub · octocat');- });-- it('uses connection ID as label when no identity field is available', () => {- const conn = { id: 'conn-x', toolkit: 'Notion', status: 'ACTIVE' };- const result = deduplicateConnections([conn]);- expect(result[0].label).toBe('Notion · conn-x');- });-- it('shows each connection ID for multiple no-identity connections', () => {- const conns = [- { id: 'conn-a', toolkit: 'Notion', status: 'ACTIVE' },- { id: 'conn-b', toolkit: 'Notion', status: 'ACTIVE' },- ];- const result = deduplicateConnections(conns);- expect(result).toHaveLength(2);- expect(result[0].label).toBe('Notion · conn-a');- expect(result[1].label).toBe('Notion · conn-b');- });-- it('deduplicates connections with the same toolkit and identity', () => {- const conns = [- { id: 'conn-1', toolkit: 'Gmail', status: 'ACTIVE', accountEmail: '[email protected]' },- { id: 'conn-2', toolkit: 'Gmail', status: 'ACTIVE', accountEmail: '[email protected]' },- ];- const result = deduplicateConnections(conns);- expect(result).toHaveLength(1);- expect(result[0].conn.id).toBe('conn-1');- expect(result[0].label).toBe('Gmail · [email protected]');- });-- it('keeps connections with the same toolkit but different identities', () => {- const conns = [- { id: 'conn-1', toolkit: 'Gmail', status: 'ACTIVE', accountEmail: '[email protected]' },- { id: 'conn-2', toolkit: 'Gmail', status: 'ACTIVE', accountEmail: '[email protected]' },- ];- const result = deduplicateConnections(conns);- expect(result).toHaveLength(2);- });-- it('uses the connection ID in the label when no identity is available', () => {- const conns = [- { id: 'raw-uuid-abc123', toolkit: 'Linear', status: 'ACTIVE' },- { id: 'raw-uuid-def456', toolkit: 'Linear', status: 'ACTIVE' },- ];- const result = deduplicateConnections(conns);- expect(result[0].label).toBe('Linear · raw-uuid-abc123');- expect(result[1].label).toBe('Linear · raw-uuid-def456');- });-- it('shows connection IDs for no-identity connections across toolkits', () => {- const conns = [- { id: 'n-1', toolkit: 'Notion', status: 'ACTIVE' },- { id: 's-1', toolkit: 'Slack', status: 'ACTIVE' },- { id: 'n-2', toolkit: 'Notion', status: 'ACTIVE' },- ];- const result = deduplicateConnections(conns);- expect(result).toHaveLength(3);- expect(result.find(r => r.conn.id === 'n-1')?.label).toBe('Notion · n-1');- expect(result.find(r => r.conn.id === 'n-2')?.label).toBe('Notion · n-2');- expect(result.find(r => r.conn.id === 's-1')?.label).toBe('Slack · s-1');- });-- it('prefers ACTIVE over EXPIRED when deduplicating same toolkit+identity', () => {- // Backend returns EXPIRED first — the ACTIVE one should win- const conns = [- { id: 'conn-expired', toolkit: 'Gmail', status: 'EXPIRED', accountEmail: '[email protected]' },- { id: 'conn-active', toolkit: 'Gmail', status: 'ACTIVE', accountEmail: '[email protected]' },- ];- const result = deduplicateConnections(conns);- expect(result).toHaveLength(1);- expect(result[0].conn.id).toBe('conn-active');- });-- it('deduplicates identity-less connections with the same conn.id', () => {- // Same connection returned twice with no identity — must not produce duplicate React keys- const conns = [- { id: 'conn-same', toolkit: 'Notion', status: 'ACTIVE' },- { id: 'conn-same', toolkit: 'Notion', status: 'ACTIVE' },- ];- const result = deduplicateConnections(conns);- expect(result).toHaveLength(1);- expect(result[0].conn.id).toBe('conn-same');- });-- it('sorts CONNECTED equal to ACTIVE above PENDING and EXPIRED', () => {- const conns = [- { id: 'exp', toolkit: 'Linear', status: 'EXPIRED', accountEmail: '[email protected]' },- { id: 'pending', toolkit: 'Linear', status: 'PENDING', accountEmail: '[email protected]' },- { id: 'connected', toolkit: 'Linear', status: 'CONNECTED', accountEmail: '[email protected]' },- ];- const result = deduplicateConnections(conns);- expect(result).toHaveLength(1);- // CONNECTED ranks same as ACTIVE — must win over EXPIRED and PENDING- expect(result[0].conn.id).toBe('connected');- });-});--// ----------------------------------------------------------------------------// Component tests: Conversation kind-// -----------------------------------------------------------------------------describe('AddMemorySourceDialog — Conversation kind', () => {- beforeEach(() => {- mockListConnections.mockReset();- mockGetSupportedToolkits.mockReset();- mockGetSupportedToolkits.mockResolvedValue(DEFAULT_SUPPORTED);- });-- it('shows no extra fields and submits with just a label', async () => {- const { addMemorySource } = await import('../../services/memorySourcesService');- const mockAdd = addMemorySource as ReturnType<typeof vi.fn>;- mockAdd.mockResolvedValue({- id: 'src_conv',- kind: 'conversation',- label: 'Chats',- enabled: true,- });-- const { onAdded } = renderDialog();-- const conversationBtn = screen.getByText('Conversation');- fireEvent.click(conversationBtn);-- const labelInput = screen.getByPlaceholderText('My research notes');- fireEvent.change(labelInput, { target: { value: 'Chats' } });-- const submitBtn = screen.getByRole('button', { name: 'Add' });- fireEvent.click(submitBtn);-- await waitFor(() => {- expect(mockAdd).toHaveBeenCalledWith(- expect.objectContaining({ kind: 'conversation', label: 'Chats', enabled: true })- );- });- await waitFor(() => expect(onAdded).toHaveBeenCalled());- });-});--// ----------------------------------------------------------------------------// Component tests: ComposioPicker inside the dialog-// -----------------------------------------------------------------------------describe('AddMemorySourceDialog — Composio picker', () => {- beforeEach(() => {- mockListConnections.mockReset();- mockGetSupportedToolkits.mockReset();- mockGetSupportedToolkits.mockResolvedValue(DEFAULT_SUPPORTED);- });-- it('shows loading state while fetching connections', async () => {- // Never resolves during this test- mockListConnections.mockReturnValue(new Promise(() => {}));- renderDialog();- fireEvent.click(screen.getByText('Integration'));- await waitFor(() => expect(screen.queryByText('Loading connections…')).toBeTruthy());- });-- it('shows no-connections message when list is empty', async () => {- mockListConnections.mockResolvedValue({ connections: [] });- await openComposioStep();- await waitFor(() =>- expect(- screen.queryByText('No active Composio connections found. Connect an integration first.')- ).toBeTruthy()- );- });-- it('renders readable labels — toolkit · identity — not raw IDs', async () => {- mockListConnections.mockResolvedValue({- connections: [- { id: 'raw-id-xyz', toolkit: 'Gmail', status: 'ACTIVE', accountEmail: '[email protected]' },- ],- });- await openComposioStep();- await openListbox();- await waitFor(() => expect(screen.queryByText('Gmail · [email protected]')).toBeTruthy());- expect(screen.queryByText('raw-id-xyz')).toBeNull();- });-- it('deduplicates same toolkit+identity connections in the dropdown', async () => {- mockListConnections.mockResolvedValue({- connections: [- { id: 'conn-1', toolkit: 'Gmail', status: 'ACTIVE', accountEmail: '[email protected]' },- { id: 'conn-2', toolkit: 'Gmail', status: 'ACTIVE', accountEmail: '[email protected]' },- ],- });- await openComposioStep();- await openListbox();- await waitFor(() => {- const options = screen.getAllByRole('option');- const gmailOptions = options.filter(o => o.textContent?.includes('Gmail · [email protected]'));- expect(gmailOptions).toHaveLength(1);- });- });-- it('shows connection IDs for connections without identity fields', async () => {- mockListConnections.mockResolvedValue({- connections: [- { id: 'conn-a', toolkit: 'Notion', status: 'ACTIVE' },- { id: 'conn-b', toolkit: 'Notion', status: 'ACTIVE' },- ],- });- await openComposioStep();- await openListbox();- await waitFor(() => {- expect(screen.queryByText('Notion · conn-a')).toBeTruthy();- expect(screen.queryByText('Notion · conn-b')).toBeTruthy();- });- });-- it('auto-fills the source label when a connection is selected', async () => {- mockListConnections.mockResolvedValue({- connections: [- { id: 'conn-1', toolkit: 'Slack', status: 'ACTIVE', workspace: 'my-workspace' },- ],- });- await openComposioStep();- await openListbox();- const option = await screen.findByTestId('composio-option-conn-1');- fireEvent.click(option);-- // The label field should be auto-filled, and the dropdown collapses to- // show the chosen connection on the trigger.- await waitFor(() => {- const labelInput = screen.getByPlaceholderText('My research notes');- expect((labelInput as HTMLInputElement).value).toBe('Slack · my-workspace');- });- });-- it('disables unsupported toolkits with a "Coming soon" tag and keeps them unselectable', async () => {- // Slack is syncable; Google Calendar is not in the supported set.- mockGetSupportedToolkits.mockResolvedValue(['slack']);- mockListConnections.mockResolvedValue({- connections: [- { id: 'conn-slack', toolkit: 'slack', status: 'ACTIVE', workspace: 'acme' },- { id: 'conn-gcal', toolkit: 'googlecalendar', status: 'ACTIVE', accountEmail: '[email protected]' },- ],- });- await openComposioStep();- await openListbox();-- const supported = await screen.findByTestId('composio-option-conn-slack');- const unsupported = await screen.findByTestId('composio-option-conn-gcal');-- expect(supported.getAttribute('aria-disabled')).toBe('false');- expect(unsupported.getAttribute('aria-disabled')).toBe('true');- expect(screen.getByTestId('composio-option-coming-soon-conn-gcal')).toBeInTheDocument();- // No "Coming soon" chip on the supported row.- expect(screen.queryByTestId('composio-option-coming-soon-conn-slack')).toBeNull();-- // Clicking the unsupported row must NOT select it (label stays empty).- fireEvent.click(unsupported);- const labelInput = screen.getByPlaceholderText('My research notes');- expect((labelInput as HTMLInputElement).value).toBe('');-- // Clicking the supported row selects it.- fireEvent.click(supported);- await waitFor(() => expect((labelInput as HTMLInputElement).value).toBe('slack · acme'));- });-- it('treats every connection as supported when the supported-toolkit RPC fails', async () => {- // Fallback path: getSupportedToolkits rejects → null set → nothing disabled.- mockGetSupportedToolkits.mockRejectedValue(new Error('rpc down'));- mockListConnections.mockResolvedValue({- connections: [{ id: 'conn-x', toolkit: 'sentry', status: 'ACTIVE', accountEmail: '[email protected]' }],- });- await openComposioStep();- await openListbox();- const option = await screen.findByTestId('composio-option-conn-x');- expect(option.getAttribute('aria-disabled')).toBe('false');- expect(screen.queryByTestId('composio-option-coming-soon-conn-x')).toBeNull();- });-- it('closes the dropdown when Escape is pressed', async () => {- mockListConnections.mockResolvedValue({- connections: [{ id: 'conn-1', toolkit: 'Slack', status: 'ACTIVE', workspace: 'acme' }],- });- await openComposioStep();- await openListbox();- expect(screen.queryByTestId('composio-connection-listbox')).toBeInTheDocument();-- fireEvent.keyDown(document, { key: 'Escape' });- await waitFor(() => expect(screen.queryByTestId('composio-connection-listbox')).toBeNull());- });-- it('closes the dropdown on an outside click', async () => {- mockListConnections.mockResolvedValue({- connections: [{ id: 'conn-1', toolkit: 'Slack', status: 'ACTIVE', workspace: 'acme' }],- });- await openComposioStep();- await openListbox();- expect(screen.queryByTestId('composio-connection-listbox')).toBeInTheDocument();-- // A mousedown outside the picker container collapses the listbox.- fireEvent.mouseDown(document.body);- await waitFor(() => expect(screen.queryByTestId('composio-connection-listbox')).toBeNull());- });-- it('opens the listbox with ArrowDown on the trigger button', async () => {- mockListConnections.mockResolvedValue({- connections: [{ id: 'conn-1', toolkit: 'Slack', status: 'ACTIVE', workspace: 'acme' }],- });- await openComposioStep();- const trigger = await screen.findByTestId('composio-connection-picker');- fireEvent.keyDown(trigger, { key: 'ArrowDown' });- await screen.findByTestId('composio-connection-listbox');- });-- it('navigates options with the arrow keys and selects with Enter', async () => {- mockListConnections.mockResolvedValue({- connections: [- { id: 'conn-gmail', toolkit: 'Gmail', status: 'ACTIVE', accountEmail: '[email protected]' },- { id: 'conn-slack', toolkit: 'Slack', status: 'ACTIVE', workspace: 'acme' },- ],- });- await openComposioStep();- await openListbox();- const listbox = screen.getByTestId('composio-connection-listbox');-- // Opens highlighting the first selectable option; ArrowDown moves to the next.- expect(listbox).toHaveAttribute('aria-activedescendant', 'composio-opt-conn-gmail');- fireEvent.keyDown(listbox, { key: 'ArrowDown' });- expect(listbox).toHaveAttribute('aria-activedescendant', 'composio-opt-conn-slack');-- // Enter selects the highlighted option and closes the dropdown.- fireEvent.keyDown(listbox, { key: 'Enter' });- await waitFor(() => {- const labelInput = screen.getByPlaceholderText('My research notes');- expect((labelInput as HTMLInputElement).value).toBe('Slack · acme');- });- expect(screen.queryByTestId('composio-connection-listbox')).toBeNull();- });-- it('skips unsupported options during keyboard navigation', async () => {- mockGetSupportedToolkits.mockResolvedValue(['slack']);- mockListConnections.mockResolvedValue({- connections: [- { id: 'conn-slack', toolkit: 'slack', status: 'ACTIVE', workspace: 'acme' },- { id: 'conn-gcal', toolkit: 'googlecalendar', status: 'ACTIVE', accountEmail: '[email protected]' },- ],- });- await openComposioStep();- await openListbox();- const listbox = screen.getByTestId('composio-connection-listbox');-- // Only the supported option is reachable; wrapping keeps it on slack.- expect(listbox).toHaveAttribute('aria-activedescendant', 'composio-opt-conn-slack');- fireEvent.keyDown(listbox, { key: 'ArrowDown' });- expect(listbox).toHaveAttribute('aria-activedescendant', 'composio-opt-conn-slack');- fireEvent.keyDown(listbox, { key: 'ArrowUp' });- expect(listbox).toHaveAttribute('aria-activedescendant', 'composio-opt-conn-slack');- });-});--// ----------------------------------------------------------------------------// Component tests: the surface is a real modal (Radix Dialog), not a-// hand-rolled `fixed inset-0` div — focus trap, aria-modal, Escape-to-close.-// -----------------------------------------------------------------------------describe('AddMemorySourceDialog — dialog surface', () => {- beforeEach(() => {- mockListConnections.mockReset();- mockGetSupportedToolkits.mockReset();- mockGetSupportedToolkits.mockResolvedValue(DEFAULT_SUPPORTED);- });-- it('renders as a real dialog and traps focus inside it on mount', () => {- renderDialog();- const dialog = screen.getByRole('dialog');- // Radix's FocusScope moves focus into the content on mount — it must not- // be left on the document body, which is what the old plain div left.- expect(dialog.contains(document.activeElement)).toBe(true);- });-- it('closes (via onClose) when Escape is pressed', async () => {- const { onClose } = renderDialog();- fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' });- await waitFor(() => expect(onClose).toHaveBeenCalled());- });-});diff --git a/app/src/components/intelligence/AddMemorySourceDialog.tsx b/app/src/components/intelligence/AddMemorySourceDialog.tsxdeleted file mode 100644index d276fba2ce..0000000000--- a/app/src/components/intelligence/AddMemorySourceDialog.tsx+++ /dev/null@@ -1,301 +0,0 @@-/**- * Dialog for adding a new memory source.- *- * Step 1: pick a source kind (Composio / Folder / GitHub / RSS / Web / Twitter).- * Step 2: fill in kind-specific fields and submit.- *- * For Composio, the dialog fetches the user's active connections and- * presents them as a dropdown — the user picks an existing OAuth- * connection rather than typing toolkit + connection_id.- */-import debug from 'debug';-import { useCallback, useEffect, useState } from 'react';--import { listConnections } from '../../lib/composio/composioApi';-import type { ComposioConnection } from '../../lib/composio/types';-import { useT } from '../../lib/i18n/I18nContext';-import {- addMemorySource,- getSupportedToolkits,- type MemorySourceEntry,- SOURCE_KIND_ICONS,- SOURCE_KIND_LABEL_KEYS,- type SourceKind,-} from '../../services/memorySourcesService';-import Button from '../ui/Button';-import { DialogContent, DialogRoot, DialogTitle } from '../ui/Dialog';-import { Field, isKindFieldsValid, KindFields } from './AddMemorySourceFields';--const log = debug('intelligence:add-memory-source-dialog');--/** Safe, PII-free string for an unknown error — message/name only, no stack. */-function errMessage(err: unknown): string {- return err instanceof Error ? err.message : String(err);-}--interface AddMemorySourceDialogProps {- open: boolean;- onClose: () => void;- onAdded: (source: MemorySourceEntry) => void;-}--const ALL_KINDS: SourceKind[] = [- 'composio',- 'conversation',- 'folder',- 'github_repo',- 'rss_feed',- 'web_page',- 'twitter_query',-];--export function AddMemorySourceDialog({ open, onClose, onAdded }: AddMemorySourceDialogProps) {- const { t } = useT();- const [kind, setKind] = useState<SourceKind | null>(null);- const [label, setLabel] = useState('');- const [submitting, setSubmitting] = useState(false);- const [error, setError] = useState<string | null>(null);-- // Kind-specific fields- const [path, setPath] = useState('');- const [glob, setGlob] = useState('**/*.md');- const [url, setUrl] = useState('');- const [branch, setBranch] = useState('main');- const [query, setQuery] = useState('');- const [selector, setSelector] = useState('');- const [connectionId, setConnectionId] = useState('');- const [toolkit, setToolkit] = useState('');-- // Composio connection picker state- const [connections, setConnections] = useState<ComposioConnection[]>([]);- const [loadingConnections, setLoadingConnections] = useState(false);- // Toolkit slugs that can actually sync (backend registry). `null` means the- // set hasn't loaded (or the RPC failed) — in that case we treat every- // connection as supported rather than locking the user out of all of them.- const [supportedToolkits, setSupportedToolkits] = useState<string[] | null>(null);-- // Fetch composio connections + the supported-toolkit set when the user picks- // the composio kind. setState calls live inside the spawned async closure- // (not the synchronous effect body) to satisfy `react-hooks/set-state-in-effect`.- useEffect(() => {- if (kind !== 'composio') return undefined;- let cancelled = false;- void (async () => {- if (cancelled) return;- setLoadingConnections(true);- try {- const [resp, toolkits] = await Promise.all([- listConnections(),- getSupportedToolkits().catch((err: unknown) => {- // Non-fatal: fall back to "everything supported" so the picker- // still works if the supported-toolkit RPC is unavailable.- log('[composio-picker] getSupportedToolkits failed: %s', errMessage(err));- return null;- }),- ]);- if (cancelled) return;- setConnections(resp.connections);- setSupportedToolkits(toolkits);- } catch (err) {- if (cancelled) return;- log('[add-memory-source] listConnections failed: %s', errMessage(err));- setError(t('memorySources.composioListFailed'));- } finally {- if (!cancelled) setLoadingConnections(false);- }- })();- return () => {- cancelled = true;- };- }, [kind, t]);-- const reset = useCallback(() => {- setKind(null);- setLabel('');- setPath('');- setGlob('**/*.md');- setUrl('');- setBranch('main');- setQuery('');- setSelector('');- setConnectionId('');- setToolkit('');- setError(null);- }, []);-- const handleClose = useCallback(() => {- reset();- onClose();- }, [onClose, reset]);-- const handleSubmit = useCallback(async () => {- if (!kind || !label.trim()) return;- setSubmitting(true);- setError(null);-- try {- const params: Record<string, unknown> = { kind, label: label.trim(), enabled: true };-- switch (kind) {- case 'composio':- params.toolkit = toolkit;- params.connection_id = connectionId;- break;- case 'conversation':- break;- case 'folder':- params.path = path.trim();- params.glob = glob.trim() || '**/*.md';- break;- case 'github_repo':- params.url = url.trim();- params.branch = branch.trim() || 'main';- break;- case 'rss_feed':- params.url = url.trim();- break;- case 'web_page':- params.url = url.trim();- if (selector.trim()) params.selector = selector.trim();- break;- case 'twitter_query':- params.query = query.trim();- break;- }-- const source = await addMemorySource(params as Omit<MemorySourceEntry, 'id'>);- onAdded(source);- handleClose();- } catch (err) {- setError(err instanceof Error ? err.message : String(err));- } finally {- setSubmitting(false);- }- }, [- kind,- label,- path,- glob,- url,- branch,- query,- selector,- connectionId,- toolkit,- onAdded,- handleClose,- ]);-- const isValid =- kind && label.trim() && isKindFieldsValid(kind, { path, url, query, connectionId });-- return (- <DialogRoot- open={open}- onOpenChange={next => {- if (!next) handleClose();- }}>- <DialogContent className="max-w-lg p-6">- <DialogTitle className="text-lg">{t('memorySources.addSource')}</DialogTitle>-- {!kind ? (- <>- <p className="mt-2 text-sm text-content-muted">{t('memorySources.pickKind')}</p>- <div className="mt-4 grid grid-cols-2 gap-3">- {ALL_KINDS.map(k => (- <Button- key={k}- variant="secondary"- onClick={() => setKind(k)}- className="h-auto items-center justify-start gap-3 p-3 text-left font-normal- hover:border-primary-400 hover:bg-primary-50- dark:hover:border-primary-500 dark:hover:bg-primary-500/10">- <span className="text-xl">{SOURCE_KIND_ICONS[k]}</span>- <span className="text-sm font-medium text-content">- {t(SOURCE_KIND_LABEL_KEYS[k])}- </span>- </Button>- ))}- </div>- <div className="mt-4 flex justify-end">- <Button variant="tertiary" size="md" onClick={handleClose}>- {t('common.cancel')}- </Button>- </div>- </>- ) : (- <>- <p className="mt-1 text-sm text-content-muted">- {SOURCE_KIND_ICONS[kind]} {t(SOURCE_KIND_LABEL_KEYS[kind])}- </p>-- <div className="mt-4 space-y-3">- <Field- label={t('memorySources.label')}- value={label}- onChange={setLabel}- placeholder={t('memorySources.labelPlaceholder')}- />- <KindFields- kind={kind}- path={path}- setPath={setPath}- glob={glob}- setGlob={setGlob}- url={url}- setUrl={setUrl}- branch={branch}- setBranch={setBranch}- query={query}- setQuery={setQuery}- selector={selector}- setSelector={setSelector}- connections={connections}- loadingConnections={loadingConnections}- supportedToolkits={supportedToolkits}- connectionId={connectionId}- setConnection={(connId, tk, identityLabel) => {- setConnectionId(connId);- setToolkit(tk);- if (!label) setLabel(identityLabel);- }}- />- </div>-- {error && (- <p className="mt-3 rounded-md bg-coral-50 p-2 text-xs text-coral-800 dark:bg-coral-500/10 dark:text-coral-300">- {error}- </p>- )}-- <div className="mt-5 flex items-center justify-between">- <Button- variant="tertiary"- size="sm"- onClick={() => {- setKind(null);- setError(null);- }}>- ← {t('memorySources.backToKinds')}- </Button>- <div className="flex gap-2">- <Button variant="tertiary" size="md" onClick={handleClose}>- {t('common.cancel')}- </Button>- <Button- variant="primary"- size="md"- onClick={handleSubmit}- disabled={!isValid || submitting}>- {submitting ? t('memorySources.adding') : t('memorySources.add')}- </Button>- </div>- </div>- </>- )}- </DialogContent>- </DialogRoot>- );-}--export { deduplicateConnections } from './AddMemorySourceFields';diff --git a/app/src/components/intelligence/AddMemorySourceFields.tsx b/app/src/components/intelligence/AddMemorySourceFields.tsxdeleted file mode 100644index acbea8574c..0000000000--- a/app/src/components/intelligence/AddMemorySourceFields.tsx+++ /dev/null@@ -1,495 +0,0 @@-/**- * Step-2 field renderers + the Composio connection picker for- * `AddMemorySourceDialog`.- *- * Split out of the dialog file to keep it under the ~500-line budget —- * everything here is pure presentation/validation for "fill in kind-specific- * fields", independent of the dialog's open/close/submit orchestration.- */-import debug from 'debug';-import {- type KeyboardEvent as ReactKeyboardEvent,- useEffect,- useMemo,- useRef,- useState,-} from 'react';--import type { ComposioConnection } from '../../lib/composio/types';-import { useT } from '../../lib/i18n/I18nContext';-import type { SourceKind } from '../../services/memorySourcesService';-import Badge from '../ui/Badge';-import TextField from '../ui/TextField';-import { FolderField } from './FolderField';--const log = debug('intelligence:add-memory-source-dialog');--export function isKindFieldsValid(- kind: SourceKind,- fields: { path: string; url: string; query: string; connectionId: string }-): boolean {- switch (kind) {- case 'composio':- return fields.connectionId.length > 0;- case 'conversation':- return true;- case 'folder':- return fields.path.trim().length > 0;- case 'github_repo':- case 'rss_feed':- case 'web_page':- return fields.url.trim().length > 0;- case 'twitter_query':- return fields.query.trim().length > 0;- default:- return true;- }-}--interface FieldProps {- label: string;- value: string;- onChange: (v: string) => void;- placeholder?: string;- type?: string;-}--export function Field({ label, value, onChange, placeholder, type = 'text' }: FieldProps) {- return (- <label className="block">- <span className="text-xs font-medium text-content-secondary">{label}</span>- <TextField- type={type}- value={value}- onChange={e => onChange(e.target.value)}- placeholder={placeholder}- className="mt-1"- />- </label>- );-}--interface KindFieldsProps {- kind: SourceKind;- path: string;- setPath: (v: string) => void;- glob: string;- setGlob: (v: string) => void;- url: string;- setUrl: (v: string) => void;- branch: string;- setBranch: (v: string) => void;- query: string;- setQuery: (v: string) => void;- selector: string;- setSelector: (v: string) => void;- connections: ComposioConnection[];- loadingConnections: boolean;- /** Syncable toolkit slugs; `null` while unknown (treat all as supported). */- supportedToolkits: string[] | null;- connectionId: string;- setConnection: (connectionId: string, toolkit: string, identityLabel: string) => void;-}--export function KindFields(props: KindFieldsProps) {- const { t } = useT();- switch (props.kind) {- case 'composio':- return <ComposioPicker {...props} />;- case 'conversation':- return null;- case 'folder':- return (- <>- <FolderField- label={t('memorySources.folderPath')}- value={props.path}- onChange={props.setPath}- />- <Field- label={t('memorySources.globPattern')}- value={props.glob}- onChange={props.setGlob}- placeholder={t('memorySources.globPatternPlaceholder')}- />- </>- );- case 'github_repo':- return (- <>- <Field- label={t('memorySources.repoUrl')}- value={props.url}- onChange={props.setUrl}- placeholder={t('memorySources.repoUrlPlaceholder')}- />- <Field- label={t('memorySources.branch')}- value={props.branch}- onChange={props.setBranch}- placeholder={t('memorySources.branchPlaceholder')}- />- </>- );- case 'rss_feed':- return (- <Field- label={t('memorySources.feedUrl')}- value={props.url}- onChange={props.setUrl}- placeholder={t('memorySources.feedUrlPlaceholder')}- />- );- case 'web_page':- return (- <>- <Field- label={t('memorySources.pageUrl')}- value={props.url}- onChange={props.setUrl}- placeholder={t('memorySources.pageUrlPlaceholder')}- />- <Field- label={t('memorySources.cssSelector')}- value={props.selector}- onChange={props.setSelector}- placeholder={t('memorySources.cssSelectorPlaceholder')}- />- </>- );- case 'twitter_query':- return (- <Field- label={t('memorySources.searchQuery')}- value={props.query}- onChange={props.setQuery}- placeholder={t('memorySources.searchQueryPlaceholder')}- />- );- default:- return null;- }-}--/** Active-first status rank — lower is better. */-const STATUS_RANK: Record<string, number> = {- ACTIVE: 0,- CONNECTED: 0,- PENDING: 1,- INITIATED: 1,- INITIALIZING: 1,- EXPIRED: 2,- FAILED: 3,- ERROR: 3,-};--function statusRank(conn: ComposioConnection): number {- return STATUS_RANK[conn.status.toUpperCase()] ?? 2;-}--/**- * Deduplicates and labels connections for display in the picker.- *- * - Sorts by status rank first (ACTIVE/CONNECTED before EXPIRED/FAILED) so- * that when two connections share the same toolkit + identity, the healthier- * one wins rather than the first-returned one.- * - Connections sharing the same toolkit + identity (accountEmail / workspace /- * username) OR the same raw connection id are collapsed to the first- * occurrence, preventing both labeled and identity-less duplicates.- * - Connections with no identity field fall back to showing the raw connection ID- * so users can unambiguously distinguish accounts.- */-export function deduplicateConnections(- connections: ComposioConnection[]-): Array<{ conn: ComposioConnection; label: string }> {- const sorted = [...connections].sort((a, b) => statusRank(a) - statusRank(b));- const seen = new Set<string>();- const result: Array<{ conn: ComposioConnection; label: string }> = [];-- for (const conn of sorted) {- // Always dedup by raw connection id to guard against identity-less dupes.- if (seen.has(conn.id)) {- log('[composio-picker] dropping duplicate connection toolkit=%s', conn.toolkit);- continue;- }- seen.add(conn.id);-- const identity = conn.accountEmail ?? conn.workspace ?? conn.username;- if (identity) {- const key = `${conn.toolkit}:${identity}`;- if (seen.has(key)) {- log('[composio-picker] dropping duplicate connection toolkit=%s', conn.toolkit);- continue;- }- seen.add(key);- result.push({ conn, label: `${conn.toolkit} · ${identity}` });- } else {- // Fall back to the raw connection ID so the user can unambiguously- // distinguish accounts when no identity data is available.- result.push({ conn, label: `${conn.toolkit} · ${conn.id}` });- }- }- return result;-}--/** A connection is syncable when its toolkit ships a provider. A `null`- * supported-set means "unknown" — treat everything as supported so a failed- * lookup never disables the whole picker. */-function isToolkitSupported(toolkit: string, supportedToolkits: string[] | null): boolean {- if (supportedToolkits === null) return true;- return supportedToolkits.includes(toolkit.trim().toLowerCase());-}--interface PickerEntry {- conn: ComposioConnection;- label: string;- supported: boolean;-}--function ComposioPicker({- connections,- loadingConnections,- supportedToolkits,- connectionId,- setConnection,-}: KindFieldsProps) {- const { t } = useT();- const [open, setOpen] = useState(false);- // Index (into `entries`) of the keyboard-highlighted option; -1 when none.- const [activeIndex, setActiveIndex] = useState(-1);- const containerRef = useRef<HTMLDivElement>(null);- const buttonRef = useRef<HTMLButtonElement>(null);- const listboxRef = useRef<HTMLUListElement>(null);-- // useMemo must be declared before any early returns (Rules of Hooks).- const entries = useMemo<PickerEntry[]>(() => {- const deduped = deduplicateConnections(connections).map(({ conn, label }) => ({- conn,- label,- supported: isToolkitSupported(conn.toolkit, supportedToolkits),- }));- // Supported connections first so the actionable ones surface at the top;- // stable within each partition (dedup already ranked by health/status).- return [...deduped.filter(e => e.supported), ...deduped.filter(e => !e.supported)];- }, [connections, supportedToolkits]);-- // Indexes of keyboard-selectable (supported) options — unsupported rows are- // skipped during arrow navigation, mirroring a native <select>'s disabled opts.- const selectableIndexes = useMemo(- () => entries.map((e, i) => (e.supported ? i : -1)).filter(i => i >= 0),- [entries]- );-- const selected = entries.find(e => e.conn.id === connectionId) ?? null;-- // Close the popover on outside click or Escape.- useEffect(() => {- if (!open) return undefined;- const onPointerDown = (event: MouseEvent) => {- if (containerRef.current && !containerRef.current.contains(event.target as Node)) {- setOpen(false);- }- };- const onKeyDown = (event: KeyboardEvent) => {- if (event.key === 'Escape') setOpen(false);- };- document.addEventListener('mousedown', onPointerDown);- document.addEventListener('keydown', onKeyDown);- return () => {- document.removeEventListener('mousedown', onPointerDown);- document.removeEventListener('keydown', onKeyDown);- };- }, [open]);-- // Move keyboard focus into the listbox when it opens so arrow keys work- // immediately. This is a DOM side-effect only — the highlighted index is set- // in the open/close handlers, not here, to avoid setState-in-effect churn.- useEffect(() => {- if (open) listboxRef.current?.focus();- }, [open]);-- if (loadingConnections) {- return <p className="text-xs text-content-muted">{t('memorySources.loadingConnections')}</p>;- }-- if (connections.length === 0) {- return (- <p className="rounded-md bg-amber-50 p-3 text-xs text-amber-800 dark:bg-amber-500/10 dark:text-amber-300">- {t('memorySources.noConnections')}- </p>- );- }-- // Highlight the current selection (or first selectable option) and open.- const openListbox = () => {- const selIdx = entries.findIndex(e => e.conn.id === connectionId && e.supported);- setActiveIndex(selIdx >= 0 ? selIdx : (selectableIndexes[0] ?? -1));- setOpen(true);- };-- const close = (returnFocus = true) => {- setActiveIndex(-1);- setOpen(false);- if (returnFocus) buttonRef.current?.focus();- };-- const select = (entry: PickerEntry) => {- if (!entry.supported) {- log('[composio-picker] ignoring selection of unsupported toolkit=%s', entry.conn.toolkit);- return;- }- setConnection(entry.conn.id, entry.conn.toolkit, entry.label);- close();- };-- // Move the highlight to the next/previous selectable option, wrapping around.- const moveActive = (dir: 1 | -1) => {- if (selectableIndexes.length === 0) return;- const pos = selectableIndexes.indexOf(activeIndex);- const nextPos =- pos === -1- ? dir === 1- ? 0- : selectableIndexes.length - 1- : (pos + dir + selectableIndexes.length) % selectableIndexes.length;- setActiveIndex(selectableIndexes[nextPos]);- };-- const onButtonKeyDown = (event: ReactKeyboardEvent<HTMLButtonElement>) => {- // Open with the arrow keys; Enter/Space already toggle via onClick.- if (!open && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) {- event.preventDefault();- openListbox();- }- };-- const onListKeyDown = (event: ReactKeyboardEvent<HTMLUListElement>) => {- switch (event.key) {- case 'ArrowDown':- event.preventDefault();- moveActive(1);- break;- case 'ArrowUp':- event.preventDefault();- moveActive(-1);- break;- case 'Home':- event.preventDefault();- if (selectableIndexes.length) setActiveIndex(selectableIndexes[0]);- break;- case 'End':- event.preventDefault();- if (selectableIndexes.length)- setActiveIndex(selectableIndexes[selectableIndexes.length - 1]);- break;- case 'Enter':- case ' ':- event.preventDefault();- if (activeIndex >= 0 && entries[activeIndex]) select(entries[activeIndex]);- break;- case 'Escape':- event.preventDefault();- close();- break;- case 'Tab':- // Let focus leave naturally, but collapse the popover.- setOpen(false);- break;- default:- break;- }- };-- const LISTBOX_ID = 'composio-connection-listbox';- const optionId = (entry: PickerEntry) => `composio-opt-${entry.conn.id}`;- const activeOptionId =- activeIndex >= 0 && entries[activeIndex] ? optionId(entries[activeIndex]) : undefined;-- return (- <div className="block" ref={containerRef}>- <span className="text-xs font-medium text-content-secondary">- {t('memorySources.pickConnection')}- </span>- <div className="relative mt-1">- <button- ref={buttonRef}- type="button"- data-testid="composio-connection-picker"- aria-haspopup="listbox"- aria-expanded={open}- aria-controls={open ? LISTBOX_ID : undefined}- onClick={() => (open ? close(false) : openListbox())}- onKeyDown={onButtonKeyDown}- className="flex w-full items-center justify-between rounded-md border border-line-strong- bg-surface px-3 py-2 text-left text-sm text-content- focus:border-primary-400 focus:outline-hidden focus:ring-1 focus:ring-primary-400- dark:bg-surface-muted dark:text-content- dark:focus:border-primary-500">- <span className={selected ? '' : 'text-content-faint'}>- {selected ? selected.label : t('memorySources.selectConnection')}- </span>- <span aria-hidden className="ml-2 text-content-faint">- ▾- </span>- </button>-- {open && (- <ul- ref={listboxRef}- id={LISTBOX_ID}- role="listbox"- tabIndex={-1}- aria-label={t('memorySources.pickConnection')}- aria-activedescendant={activeOptionId}- onKeyDown={onListKeyDown}- data-testid="composio-connection-listbox"- className="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md border- border-line bg-surface py-1 shadow-lg focus:outline-hidden- dark:border-line-strong dark:bg-surface-muted">- {entries.map((entry, index) => {- const isSelected = entry.conn.id === connectionId;- const isActive = index === activeIndex;- return (- <li- key={entry.conn.id}- id={optionId(entry)}- role="option"- aria-selected={isSelected}- aria-disabled={!entry.supported}- data-testid={`composio-option-${entry.conn.id}`}- data-supported={entry.supported}- data-active={isActive}- onClick={() => select(entry)}- onMouseEnter={() => entry.supported && setActiveIndex(index)}- className={[- 'flex items-center justify-between gap-2 px-3 py-2 text-sm',- entry.supported- ? 'cursor-pointer text-content'- : 'cursor-not-allowed text-content-faint',- isActive && entry.supported ? 'bg-primary-50 dark:bg-primary-500/10' : '',- ].join(' ')}>- <span className="flex items-center gap-2 truncate">- {isSelected && entry.supported && (- <span aria-hidden className="text-primary-500">- ✓- </span>- )}- <span className="truncate">{entry.label}</span>- </span>- {!entry.supported && (- <Badge- variant="neutral"- className="shrink-0"- data-testid={`composio-option-coming-soon-${entry.conn.id}`}>- {t('memorySources.comingSoon')}- </Badge>- )}- </li>- );- })}- </ul>- )}- </div>- </div>- );-}diff --git a/app/src/components/intelligence/CodingSessionsCard.tsx b/app/src/components/intelligence/CodingSessionsCard.tsxdeleted file mode 100644index 28829762c2..0000000000--- a/app/src/components/intelligence/CodingSessionsCard.tsx+++ /dev/null@@ -1,238 +0,0 @@-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';--import { useT } from '../../lib/i18n/I18nContext';-import {- type CodingSessionDrainProgress,- type CodingSessionSourceStatus,- drainCodingSessions,- getCodingSessionStatus,-} from '../../services/memorySourcesService';-import type { ToastNotification } from '../../types/intelligence';-import { Card } from '../ui';-import Button from '../ui/Button';--interface CodingSessionsCardProps {- onToast?: (toast: Omit<ToastNotification, 'id'>) => void;-}--const SOURCE_LABEL_KEYS: Record<CodingSessionSourceStatus['kind'], string> = {- claude_code: 'memorySources.codingSessions.claude',- codex: 'memorySources.codingSessions.codex',-};--export function CodingSessionsCard({ onToast }: CodingSessionsCardProps) {- const { t } = useT();- const [sources, setSources] = useState<CodingSessionSourceStatus[]>([]);- const [loading, setLoading] = useState(true);- const [ingesting, setIngesting] = useState(false);- const [progress, setProgress] = useState<CodingSessionDrainProgress | null>(null);- const [error, setError] = useState<string | null>(null);- // The ref keeps the synchronous `shouldStop` poll contract for the drain loop;- // the state mirror drives an immediate re-render so the Stop button disables on- // click instead of waiting for the next pass to fire `onProgress`.- const stopRequestedRef = useRef(false);- const [stopRequested, setStopRequested] = useState(false);-- const load = useCallback(async () => {- console.debug('[coding-sessions] status: entry');- setError(null);- try {- const next = await getCodingSessionStatus();- setSources(next);- console.debug('[coding-sessions] status: exit sources=%d', next.length);- } catch (cause) {- console.error('[coding-sessions] status failed', cause);- setError(cause instanceof Error ? cause.message : String(cause));- } finally {- setLoading(false);- }- }, []);-- useEffect(() => {- void load();- }, [load]);-- const totals = useMemo(- () => ({- files: sources.reduce((sum, source) => sum + source.session_files, 0),- evidence: sources.reduce((sum, source) => sum + source.evidence_units, 0),- }),- [sources]- );- const hasImportableHistory =- totals.files > 0 || sources.some(source => source.scan_truncated === true);-- const ingest = useCallback(async () => {- console.debug('[coding-sessions] drain: entry');- stopRequestedRef.current = false;- setStopRequested(false);- setIngesting(true);- setProgress(null);- setError(null);- try {- const result = await drainCodingSessions({- onProgress: setProgress,- shouldStop: () => stopRequestedRef.current,- });- console.debug(- '[coding-sessions] drain: exit passes=%d processed=%d failed=%d more=%s timed_out=%s',- result.passes,- result.sessionsProcessed,- result.sessionsFailed,- result.moreRemaining,- result.timedOut- );- // Any leftover backlog is incomplete, regardless of why the loop exited —- // a user Stop, the pass cap, or a stalled pass. Only a fully drained run- // (no more budget) is reported as complete success.- const incomplete = result.moreRemaining;- // A deadline outranks a stale failure count. `sessionsFailed` is assigned- // from the last *completed* pass, so when a later pass times out it- // describes work that is already superseded — while `timedOut` describes- // a run that is still going. Leading with the failure would tell the user- // to retry something that has not finished, which is the whole defect- // this branch exists to stop (#5802).- const message = result.timedOut- ? t('memorySources.codingSessions.stillRunningMessage').replace(- '{processed}',- String(result.sessionsProcessed)- )- : result.sessionsFailed > 0- ? t('memorySources.codingSessions.partialFailure')- .replace('{failed}', String(result.sessionsFailed))- .replace('{processed}', String(result.sessionsProcessed))- : incomplete- ? t('memorySources.codingSessions.stoppedMessage')- .replace('{processed}', String(result.sessionsProcessed))- .replace('{remaining}', String(result.remaining))- : t('memorySources.codingSessions.completeMessage')- .replace('{processed}', String(result.sessionsProcessed))- .replace('{observations}', String(result.observations));- const title = result.timedOut- ? t('memorySources.codingSessions.stillRunning')- : incomplete- ? t('memorySources.codingSessions.stopped')- : t('memorySources.codingSessions.complete');- onToast?.({- type: result.timedOut- ? 'info'- : result.sessionsFailed > 0- ? 'warning'- : incomplete- ? 'info'- : 'success',- title,- message,- });- await load();- } catch (cause) {- console.error('[coding-sessions] drain failed', cause);- const message = cause instanceof Error ? cause.message : String(cause);- setError(message);- onToast?.({ type: 'error', title: t('memorySources.codingSessions.failed'), message });- } finally {- setIngesting(false);- setProgress(null);- }- }, [load, onToast, t]);-- const stopDrain = useCallback(() => {- console.debug('[coding-sessions] drain: stop requested');- stopRequestedRef.current = true;- setStopRequested(true);- }, []);-- return (- <Card padded divided={false} data-testid="coding-sessions-card">- <div className="flex flex-wrap items-start justify-between gap-3">- <div>- <h3 className="text-sm font-semibold text-content">- {t('memorySources.codingSessions.title')}- </h3>- <p className="mt-1 text-xs text-content-secondary">- {t('memorySources.codingSessions.description')}- </p>- </div>- <div className="flex items-center gap-2">- {ingesting && (- <Button- analyticsId="brain-sources-coding-sessions-stop"- size="sm"- variant="secondary"- onClick={stopDrain}- disabled={stopRequested}- data-testid="coding-sessions-stop">- {t('memorySources.codingSessions.stop')}- </Button>- )}- <Button- analyticsId="brain-sources-coding-sessions-ingest"- size="sm"- onClick={() => void ingest()}- disabled={loading || ingesting || !hasImportableHistory}- data-testid="coding-sessions-ingest">- {ingesting- ? t('memorySources.codingSessions.draining').replace(- '{passes}',- String(progress?.passes ?? 0)- )- : t('memorySources.codingSessions.importAll')}- </Button>- </div>- </div>-- {ingesting && progress && (- <p- className="mt-3 text-xs text-content-secondary"- data-testid="coding-sessions-progress"- role="status">- {t('memorySources.codingSessions.progress')- .replace('{processed}', String(progress.sessionsProcessed))- .replace('{observations}', String(progress.observations))}- {progress.moreRemaining- ? ` · ${t('memorySources.codingSessions.remaining').replace(- '{remaining}',- String(progress.remaining)- )}`- : ''}- </p>- )}-- <div className="mt-3 grid gap-2 sm:grid-cols-2">- {sources.map(source => (- <div- key={source.kind}- className="rounded-md border border-line-subtle bg-surface-muted px-3 py-2"- data-testid={`coding-session-source-${source.kind}`}>- <div className="text-xs font-medium text-content">- {t(SOURCE_LABEL_KEYS[source.kind])}- </div>- <div className="mt-1 text-xs text-content-secondary">- {source.available- ? t('memorySources.codingSessions.counts')- .replace('{files}', String(source.session_files))- .replace('{evidence}', String(source.evidence_units))- : t('memorySources.codingSessions.notFound')}- </div>- {source.available && source.scan_truncated && (- <div className="mt-1 text-xs text-amber-600 dark:text-amber-400">- {t('memorySources.codingSessions.truncated')}- </div>- )}- </div>- ))}- </div>-- {loading && (- <p className="mt-3 text-xs text-content-secondary">- {t('memorySources.codingSessions.scanning')}- </p>- )}- {error && (- <p className="mt-3 text-xs text-coral-600 dark:text-coral-400" role="alert">- {error}- </p>- )}- </Card>- );-}diff --git a/app/src/components/intelligence/FolderField.test.tsx b/app/src/components/intelligence/FolderField.test.tsxdeleted file mode 100644index f186fe94c7..0000000000--- a/app/src/components/intelligence/FolderField.test.tsx+++ /dev/null@@ -1,153 +0,0 @@-/**- * Tests for the folder memory-source path field (#5831).- *- * The defect these guard against: Browse used to be an- * `<input type="file" webkitdirectory>`, whose handler stored- * `webkitRelativePath.split('/')[0]` when the non-standard `File.path` was- * absent. That is the chosen directory's bare *name*, and no renderer Wry- * ships (WKWebView, WebView2, WebKitGTK) provides `File.path`, so it was the- * value stored every time. The source then looked configured and failed once- * per sync cycle, forever, with `folder does not exist: docs`.- *- * The invariant asserted here is therefore not "Browse works" but the- * stronger "Browse never writes a value that cannot resolve".- */-import { fireEvent, screen, waitFor } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { renderWithProviders } from '../../test/test-utils';-import { pickDirectoryNatively } from '../../utils/tauriCommands/directoryPicker';-import { KindFields } from './AddMemorySourceFields';--vi.mock('../../utils/tauriCommands/directoryPicker', () => ({ pickDirectoryNatively: vi.fn() }));--const mockPick = vi.mocked(pickDirectoryNatively);--function renderFolderFields(path = '') {- const setPath = vi.fn();- renderWithProviders(- <KindFields- kind="folder"- path={path}- setPath={setPath}- glob=""- setGlob={vi.fn()}- url=""- setUrl={vi.fn()}- branch=""- setBranch={vi.fn()}- query=""- setQuery={vi.fn()}- selector=""- setSelector={vi.fn()}- connections={[]}- loadingConnections={false}- supportedToolkits={null}- connectionId=""- setConnection={vi.fn()}- />- );- return { setPath };-}--const UNAVAILABLE_COPY = 'Could not determine where that folder is. Type its full path instead.';--describe('FolderField (folder memory source)', () => {- beforeEach(() => {- mockPick.mockReset();- });-- it('stores the absolute path the native chooser returned', async () => {- mockPick.mockResolvedValue({ ok: true, path: '/Users/you/notes' });- const { setPath } = renderFolderFields();-- fireEvent.click(screen.getByRole('button', { name: /browse/i }));-- await waitFor(() => expect(setPath).toHaveBeenCalledWith('/Users/you/notes'));- expect(screen.queryByRole('alert')).toBeNull();- });-- it('stores nothing and explains itself when no path can be obtained', async () => {- mockPick.mockResolvedValue({ ok: false, reason: 'unavailable' });- const { setPath } = renderFolderFields();-- fireEvent.click(screen.getByRole('button', { name: /browse/i }));-- expect(await screen.findByRole('alert')).toHaveTextContent(UNAVAILABLE_COPY);- expect(setPath).not.toHaveBeenCalled();- });-- it('stores nothing when the host chooser tried and failed', async () => {- mockPick.mockResolvedValue({ ok: false, reason: 'failed', message: 'no portal' });- const { setPath } = renderFolderFields();-- fireEvent.click(screen.getByRole('button', { name: /browse/i }));-- expect(await screen.findByRole('alert')).toHaveTextContent(UNAVAILABLE_COPY);- expect(setPath).not.toHaveBeenCalled();- });-- it('leaves the field untouched and silent when the user cancels', async () => {- mockPick.mockResolvedValue({ ok: false, reason: 'cancelled' });- const { setPath } = renderFolderFields();-- fireEvent.click(screen.getByRole('button', { name: /browse/i }));-- await waitFor(() => expect(mockPick).toHaveBeenCalled());- expect(setPath).not.toHaveBeenCalled();- expect(screen.queryByRole('alert')).toBeNull();- });-- it('clears a previous error once the user types a path by hand', async () => {- mockPick.mockResolvedValue({ ok: false, reason: 'unavailable' });- const { setPath } = renderFolderFields();-- fireEvent.click(screen.getByRole('button', { name: /browse/i }));- expect(await screen.findByRole('alert')).toBeInTheDocument();-- fireEvent.change(screen.getByPlaceholderText('/Users/you/notes'), {- target: { value: '/Users/you/docs' },- });-- expect(screen.queryByRole('alert')).toBeNull();- expect(setPath).toHaveBeenCalledWith('/Users/you/docs');- });-- it('no longer renders a directory input that cannot report a path', () => {- const { container } = renderWithProviders(- <KindFields- kind="folder"- path=""- setPath={vi.fn()}- glob=""- setGlob={vi.fn()}- url=""- setUrl={vi.fn()}- branch=""- setBranch={vi.fn()}- query=""- setQuery={vi.fn()}- selector=""- setSelector={vi.fn()}- connections={[]}- loadingConnections={false}- supportedToolkits={null}- connectionId=""- setConnection={vi.fn()}- />- );-- expect(container.querySelector('input[type="file"]')).toBeNull();- expect(container.querySelector('[webkitdirectory]')).toBeNull();- });-- it('gives Browse a stable analytics id rather than a DOM-order fallback', () => {- mockPick.mockResolvedValue({ ok: false, reason: 'cancelled' });- renderFolderFields();-- expect(screen.getByRole('button', { name: /browse/i })).toHaveAttribute(- 'data-analytics-id',- 'brain-sources-folder-browse'- );- });-});diff --git a/app/src/components/intelligence/FolderField.tsx b/app/src/components/intelligence/FolderField.tsxdeleted file mode 100644index 87ece21ccd..0000000000--- a/app/src/components/intelligence/FolderField.tsx+++ /dev/null@@ -1,93 +0,0 @@-/**- * Path field for the `folder` memory-source kind, with a Browse button backed- * by the OS-native directory chooser.- *- * Split out of `AddMemorySourceFields` for the same reason that file was split- * out of the dialog: it is the only field with behaviour of its own, and the- * reasoning below is most of what there is to say about it.- *- * Browse used to be an `<input type="file" webkitdirectory>`. That element- * cannot report where the directory it returned actually lives - `File.path`- * is an Electron extension no web engine implements, Wry's WKWebView,- * WebView2 and WebKitGTK included - so its handler fell through to- * `webkitRelativePath.split('/')[0]` and stored the directory's bare *name*.- * The source then looked configured and failed every sync cycle, forever,- * with `folder does not exist: docs` (#5831).- *- * The rule that replaces it: **never store a value that cannot resolve.**- * When no absolute path can be obtained the field says so and stays as it- * was, because a visible error is recoverable and a silently stored name is- * not. Typing a path by hand is untouched, including a relative one - the- * reader anchors those on the workspace at read time (tinymemory#113), which- * is deliberately not something this field second-guesses.- */-import debug from 'debug';-import { useState } from 'react';--import { useT } from '../../lib/i18n/I18nContext';-import { pickDirectoryNatively } from '../../utils/tauriCommands/directoryPicker';-import Button from '../ui/Button';-import TextField from '../ui/TextField';--const log = debug('intelligence:folder-field');--export interface FolderFieldProps {- label: string;- value: string;- onChange: (v: string) => void;-}--export function FolderField({ label, value, onChange }: FolderFieldProps) {- const { t } = useT();- const [pickError, setPickError] = useState<string | null>(null);-- const handleBrowse = async () => {- const result = await pickDirectoryNatively();- if (result.ok) {- setPickError(null);- onChange(result.path);- return;- }- if (result.reason === 'cancelled') {- // Dismissing the dialog is not a failure. Leave the field untouched and- // clear any error from an earlier attempt.- setPickError(null);- return;- }- log('folder picker produced no absolute path (%s); refusing to store a name', result.reason);- setPickError(t('memorySources.folderPathUnavailable'));- };-- return (- <label className="block">- <span className="text-xs font-medium text-content-secondary">{label}</span>- <div className="mt-1 flex gap-2">- <TextField- type="text"- value={value}- onChange={e => {- setPickError(null);- onChange(e.target.value);- }}- placeholder={t('memorySources.folderPathPlaceholder')}- />- <Button- type="button"- variant="secondary"- size="sm"- className="shrink-0"- analyticsId="brain-sources-folder-browse"- onClick={handleBrowse}>- {t('memorySources.browse')}- </Button>- </div>- {pickError && (- <p role="alert" className="mt-1 text-xs leading-5 text-red-600 dark:text-red-300">- {pickError}- </p>- )}- </label>- );-}--export default FolderField;diff --git a/app/src/components/intelligence/GoalsPanel.test.tsx b/app/src/components/intelligence/GoalsPanel.test.tsxdeleted file mode 100644index 47e6140481..0000000000--- a/app/src/components/intelligence/GoalsPanel.test.tsx+++ /dev/null@@ -1,169 +0,0 @@-import { fireEvent, render, screen, waitFor } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { goalsApi } from '../../services/api/goalsApi';-import GoalsPanel from './GoalsPanel';--vi.mock('../../services/api/goalsApi', () => ({- goalsApi: { list: vi.fn(), add: vi.fn(), edit: vi.fn(), remove: vi.fn(), reflect: vi.fn() },-}));--const api = vi.mocked(goalsApi);--describe('<GoalsPanel />', () => {- beforeEach(() => vi.clearAllMocks());-- it('renders the empty state once loading resolves', async () => {- api.list.mockResolvedValueOnce([]);- render(<GoalsPanel />);- expect(await screen.findByText(/No goals yet/)).toBeInTheDocument();- expect(screen.getByText('Long-term Goals')).toBeInTheDocument();- });-- it('renders loaded goals', async () => {- api.list.mockResolvedValueOnce([- { id: 'g1', text: 'Ship the desktop app' },- { id: 'g2', text: 'Keep the Rust core authoritative' },- ]);- render(<GoalsPanel />);- expect(await screen.findByText('Ship the desktop app')).toBeInTheDocument();- expect(screen.getByText('Keep the Rust core authoritative')).toBeInTheDocument();- });-- it('adds a goal from the input and renders the updated list', async () => {- api.list.mockResolvedValueOnce([]);- api.add.mockResolvedValueOnce([{ id: 'g1', text: 'New goal' }]);- render(<GoalsPanel />);- await screen.findByText(/No goals yet/);-- fireEvent.change(screen.getByPlaceholderText('Add a long-term goal…'), {- target: { value: 'New goal' },- });- fireEvent.click(screen.getByRole('button', { name: /Add/ }));-- await waitFor(() => expect(api.add).toHaveBeenCalledWith('New goal'));- expect(await screen.findByText('New goal')).toBeInTheDocument();- });-- it('deletes a goal', async () => {- api.list.mockResolvedValueOnce([{ id: 'g1', text: 'Doomed goal' }]);- api.remove.mockResolvedValueOnce([]);- render(<GoalsPanel />);- await screen.findByText('Doomed goal');-- fireEvent.click(screen.getByRole('button', { name: 'Delete goal' }));- await waitFor(() => expect(api.remove).toHaveBeenCalledWith('g1'));- });-- it('runs reflect and shows the agent summary', async () => {- api.list.mockResolvedValueOnce([]);- api.reflect.mockResolvedValueOnce({- ran: true,- summary: 'Added 2 goals from context',- items: [- { id: 'g1', text: 'A' },- { id: 'g2', text: 'B' },- ],- });- render(<GoalsPanel />);- await screen.findByText(/No goals yet/);-- fireEvent.click(screen.getByRole('button', { name: /Reflect/ }));- await waitFor(() => expect(api.reflect).toHaveBeenCalled());- expect(await screen.findByText('Added 2 goals from context')).toBeInTheDocument();- expect(screen.getByText('A')).toBeInTheDocument();- });-- it('surfaces an action error when add fails', async () => {- api.list.mockResolvedValueOnce([]);- api.add.mockRejectedValueOnce(new Error('boom'));- render(<GoalsPanel />);- await screen.findByText(/No goals yet/);-- fireEvent.change(screen.getByPlaceholderText('Add a long-term goal…'), {- target: { value: 'x' },- });- fireEvent.click(screen.getByRole('button', { name: /Add/ }));- expect(await screen.findByRole('alert')).toHaveTextContent('boom');- });-- it('edits a goal inline and saves', async () => {- api.list.mockResolvedValueOnce([{ id: 'g1', text: 'old text' }]);- api.edit.mockResolvedValueOnce([{ id: 'g1', text: 'new text' }]);- render(<GoalsPanel />);- await screen.findByText('old text');-- fireEvent.click(screen.getByRole('button', { name: 'Edit goal' }));- const input = screen.getByDisplayValue('old text');- fireEvent.change(input, { target: { value: 'new text' } });- fireEvent.click(screen.getByRole('button', { name: 'Save' }));-- await waitFor(() => expect(api.edit).toHaveBeenCalledWith('g1', 'new text'));- expect(await screen.findByText('new text')).toBeInTheDocument();- });-- it('cancels an inline edit without saving', async () => {- api.list.mockResolvedValueOnce([{ id: 'g1', text: 'keep me' }]);- render(<GoalsPanel />);- await screen.findByText('keep me');-- fireEvent.click(screen.getByRole('button', { name: 'Edit goal' }));- fireEvent.change(screen.getByDisplayValue('keep me'), { target: { value: 'discarded' } });- fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));-- expect(api.edit).not.toHaveBeenCalled();- expect(screen.getByText('keep me')).toBeInTheDocument();- });-- it('surfaces an action error when edit fails', async () => {- api.list.mockResolvedValueOnce([{ id: 'g1', text: 'x' }]);- api.edit.mockRejectedValueOnce(new Error('edit blew up'));- render(<GoalsPanel />);- await screen.findByText('x');-- fireEvent.click(screen.getByRole('button', { name: 'Edit goal' }));- fireEvent.change(screen.getByDisplayValue('x'), { target: { value: 'y' } });- fireEvent.click(screen.getByRole('button', { name: 'Save' }));- expect(await screen.findByRole('alert')).toHaveTextContent('edit blew up');- });-- it('surfaces an action error when delete fails', async () => {- api.list.mockResolvedValueOnce([{ id: 'g1', text: 'x' }]);- api.remove.mockRejectedValueOnce(new Error('delete failed'));- render(<GoalsPanel />);- await screen.findByText('x');-- fireEvent.click(screen.getByRole('button', { name: 'Delete goal' }));- expect(await screen.findByRole('alert')).toHaveTextContent('delete failed');- });-- it('renders the load error branch when list rejects', async () => {- api.list.mockRejectedValueOnce(new Error('cannot load goals'));- render(<GoalsPanel />);- expect(await screen.findByText('cannot load goals')).toBeInTheDocument();- });-- it('shows the summary when reflect reports ran=false', async () => {- api.list.mockResolvedValueOnce([]);- api.reflect.mockResolvedValueOnce({- ran: false,- summary: 'enrichment failed: no model',- items: [],- });- render(<GoalsPanel />);- await screen.findByText(/No goals yet/);-- fireEvent.click(screen.getByRole('button', { name: /Reflect/ }));- expect(await screen.findByText('enrichment failed: no model')).toBeInTheDocument();- });-- it('surfaces an action error when reflect throws', async () => {- api.list.mockResolvedValueOnce([]);- api.reflect.mockRejectedValueOnce(new Error('reflect crashed'));- render(<GoalsPanel />);- await screen.findByText(/No goals yet/);-- fireEvent.click(screen.getByRole('button', { name: /Reflect/ }));- expect(await screen.findByRole('alert')).toHaveTextContent('reflect crashed');- });-});diff --git a/app/src/components/intelligence/GoalsPanel.tsx b/app/src/components/intelligence/GoalsPanel.tsxdeleted file mode 100644index 1e4bd9c1f8..0000000000--- a/app/src/components/intelligence/GoalsPanel.tsx+++ /dev/null@@ -1,293 +0,0 @@-/**- * GoalsPanel — Brain > Goals.- *- * Views and edits the agent's long-term goals list (`openhuman.memory_goals_*`)- * and triggers the turn-based enrichment agent ("Reflect"). The same list is- * curated automatically by the background goals agent when context is- * summarized; this panel is the manual surface.- */-import { useCallback, useEffect, useRef, useState } from 'react';-import { LuCheck, LuPencil, LuPlus, LuSparkles, LuTrash2, LuX } from 'react-icons/lu';--import { useT } from '../../lib/i18n/I18nContext';-import { type GoalItem, goalsApi } from '../../services/api/goalsApi';-import { Card } from '../ui';-import Button from '../ui/Button';-import Input from '../ui/Input';--export default function GoalsPanel() {- const { t } = useT();- const [goals, setGoals] = useState<GoalItem[]>([]);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);- const [actionError, setActionError] = useState<string | null>(null);-- const [newText, setNewText] = useState('');- const [adding, setAdding] = useState(false);- const [reflecting, setReflecting] = useState(false);- const [reflectSummary, setReflectSummary] = useState<string | null>(null);-- const [editingId, setEditingId] = useState<string | null>(null);- const [editText, setEditText] = useState('');- const [busyId, setBusyId] = useState<string | null>(null);-- const mountedRef = useRef(true);-- const load = useCallback(async () => {- setError(null);- try {- const list = await goalsApi.list();- if (mountedRef.current) setGoals(list);- } catch (err) {- if (mountedRef.current) setError(err instanceof Error ? err.message : String(err));- } finally {- if (mountedRef.current) setLoading(false);- }- }, []);-- useEffect(() => {- mountedRef.current = true;- void load();- return () => {- mountedRef.current = false;- };- }, [load]);-- const handleAdd = useCallback(async () => {- const text = newText.trim();- if (!text) return;- setActionError(null);- setAdding(true);- try {- const list = await goalsApi.add(text);- if (mountedRef.current) {- setError(null);- setGoals(list);- setNewText('');- }- } catch (err) {- if (mountedRef.current)- setActionError(err instanceof Error ? err.message : t('brain.goals.actionError'));- } finally {- if (mountedRef.current) setAdding(false);- }- }, [newText, t]);-- const startEdit = useCallback((goal: GoalItem) => {- setActionError(null);- setEditingId(goal.id);- setEditText(goal.text);- }, []);-- const cancelEdit = useCallback(() => {- setEditingId(null);- setEditText('');- }, []);-- const saveEdit = useCallback(- async (id: string) => {- const text = editText.trim();- if (!text) return;- setActionError(null);- setBusyId(id);- try {- const list = await goalsApi.edit(id, text);- if (mountedRef.current) {- setError(null);- setGoals(list);- setEditingId(null);- setEditText('');- }- } catch (err) {- if (mountedRef.current)- setActionError(err instanceof Error ? err.message : t('brain.goals.actionError'));- } finally {- if (mountedRef.current) setBusyId(null);- }- },- [editText, t]- );-- const handleDelete = useCallback(- async (id: string) => {- setActionError(null);- setBusyId(id);- try {- const list = await goalsApi.remove(id);- if (mountedRef.current) {- setError(null);- setGoals(list);- }- } catch (err) {- if (mountedRef.current)- setActionError(err instanceof Error ? err.message : t('brain.goals.actionError'));- } finally {- if (mountedRef.current) setBusyId(null);- }- },- [t]- );-- const handleReflect = useCallback(async () => {- setActionError(null);- setReflectSummary(null);- setReflecting(true);- try {- const res = await goalsApi.reflect();- if (mountedRef.current) {- setError(null);- setGoals(res.items);- setReflectSummary(- res.ran- ? res.summary || t('brain.goals.reflectDone')- : res.summary || t('brain.goals.actionError')- );- }- } catch (err) {- if (mountedRef.current)- setActionError(err instanceof Error ? err.message : t('brain.goals.actionError'));- } finally {- if (mountedRef.current) setReflecting(false);- }- }, [t]);-- return (- <div className="space-y-3 animate-fade-up">- <Card padded divided={false}>- {/* Header */}- <div className="flex items-start justify-between gap-3">- <div className="min-w-0">- <h2 className="text-sm font-semibold text-content">{t('brain.goals.title')}</h2>- <p className="mt-0.5 text-xs text-content-muted">{t('brain.goals.description')}</p>- </div>- <Button- type="button"- variant="secondary"- size="sm"- onClick={handleReflect}- disabled={reflecting}>- <LuSparkles className="mr-1.5 h-3.5 w-3.5" />- {reflecting ? t('brain.goals.reflecting') : t('brain.goals.reflect')}- </Button>- </div>-- {/* Add row */}- <div className="mt-4 flex items-center gap-2">- <Input- inputSize="sm"- value={newText}- placeholder={t('brain.goals.addPlaceholder')}- onChange={e => setNewText(e.target.value)}- onKeyDown={e => {- if (e.key === 'Enter') void handleAdd();- }}- />- <Button- type="button"- variant="primary"- size="sm"- onClick={handleAdd}- disabled={adding || !newText.trim()}>- <LuPlus className="mr-1 h-3.5 w-3.5" />- {t('brain.goals.add')}- </Button>- </div>-- {/* Errors / reflect summary */}- {actionError && (- <div- className="mt-3 rounded-lg border border-coral-200 bg-coral-50 px-3 py-2 text-xs text-coral-700 dark:border-coral-500/30 dark:bg-coral-500/10 dark:text-coral-300"- role="alert">- {actionError}- </div>- )}- {reflectSummary && (- <div className="mt-3 whitespace-pre-wrap rounded-lg border border-sage-200 bg-sage-50 px-3 py-2 text-xs text-sage-800 dark:border-sage-500/30 dark:bg-sage-500/10 dark:text-sage-200">- {reflectSummary}- </div>- )}-- {/* List */}- <div className="mt-4">- {loading ? (- <div className="flex items-center justify-center py-8 text-content-faint">- <div className="mr-2 h-4 w-4 animate-spin rounded-full border-2 border-primary-500 border-t-transparent" />- <span className="text-sm">{t('common.loading')}</span>- </div>- ) : error ? (- <div className="rounded-lg border border-coral-200 bg-coral-50 px-3 py-2 text-sm text-coral-700 dark:border-coral-500/30 dark:bg-coral-500/10 dark:text-coral-300">- {error}- </div>- ) : goals.length === 0 ? (- <p className="py-6 text-center text-sm text-content-faint">{t('brain.goals.empty')}</p>- ) : (- <ul className="divide-y divide-line overflow-hidden rounded-xl border border-line">- {goals.map(goal => (- <li key={goal.id} className="bg-surface px-3 py-2.5">- {editingId === goal.id ? (- <div className="flex items-center gap-2">- <Input- inputSize="sm"- value={editText}- onChange={e => setEditText(e.target.value)}- onKeyDown={e => {- if (e.key === 'Enter') void saveEdit(goal.id);- if (e.key === 'Escape') cancelEdit();- }}- autoFocus- />- <Button- type="button"- variant="tertiary"- size="xs"- onClick={() => void saveEdit(goal.id)}- disabled={busyId === goal.id || !editText.trim()}- aria-label={t('common.save')}>- <LuCheck className="h-3.5 w-3.5" />- </Button>- <Button- type="button"- variant="tertiary"- size="xs"- onClick={cancelEdit}- aria-label={t('common.cancel')}>- <LuX className="h-3.5 w-3.5" />- </Button>- </div>- ) : (- <div className="flex items-center justify-between gap-3">- <span className="min-w-0 flex-1 text-sm text-content-secondary">- {goal.text}- </span>- <div className="flex shrink-0 items-center gap-1">- <Button- type="button"- variant="tertiary"- size="xs"- onClick={() => startEdit(goal)}- disabled={busyId === goal.id}- aria-label={t('brain.goals.editGoal')}>- <LuPencil className="h-3.5 w-3.5" />- </Button>- <Button- type="button"- variant="secondary"- tone="danger"- size="xs"- onClick={() => void handleDelete(goal.id)}- disabled={busyId === goal.id}- aria-label={t('brain.goals.deleteGoal')}>- <LuTrash2 className="h-3.5 w-3.5" />- </Button>- </div>- </div>- )}- </li>- ))}- </ul>- )}- </div>- </Card>- </div>- );-}diff --git a/app/src/components/intelligence/MemoryControls.test.tsx b/app/src/components/intelligence/MemoryControls.test.tsxdeleted file mode 100644index 3c4ab279fd..0000000000--- a/app/src/components/intelligence/MemoryControls.test.tsx+++ /dev/null@@ -1,102 +0,0 @@-import { act, fireEvent, render, screen } from '@testing-library/react';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { MemoryControls } from './MemoryControls';--// Stub i18n and the vault sub-section so we render just the control bar.-vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));-vi.mock('./ObsidianVaultSection', () => ({ ObsidianVaultSection: () => null }));-vi.mock('../../utils/tauriCommands', () => ({- memoryTreeFlushNow: vi.fn().mockResolvedValue({ enqueued: true, stale_buffers: 0 }),- memoryTreeResetTree: vi.fn().mockResolvedValue(undefined),- memoryTreeWipeAll: vi.fn().mockResolvedValue(undefined),-}));-// The bound engine's families; `null` is "not known yet", which fails open.-const engine = vi.hoisted(() => ({ capabilities: null as ReadonlySet<string> | null }));-vi.mock('./useMemoryEngineCapabilities', () => ({- useMemoryEngine: () => ({ capabilities: engine.capabilities }),-}));--const noop = () => {};--describe('<MemoryControls /> refresh feedback', () => {- beforeEach(() => {- vi.useFakeTimers();- });- afterEach(() => {- vi.useRealTimers();- });-- it('calls onRefresh and shows a busy spinner immediately on click', async () => {- const onRefresh = vi.fn();- render(<MemoryControls mode="tree" onModeChange={noop} onRefresh={onRefresh} />);-- const btn = screen.getByTestId('memory-graph-refresh');- expect(btn).not.toBeDisabled();-- fireEvent.click(btn);-- // The parent re-pull fires right away…- expect(onRefresh).toHaveBeenCalledTimes(1);- // …and the button reports a busy state so the click is visibly acknowledged.- expect(btn).toBeDisabled();- expect(btn.getAttribute('aria-busy')).toBe('true');- expect(btn.querySelector('.animate-spin')).not.toBeNull();- });-- it('clears the busy state after the minimum spin window', async () => {- const onRefresh = vi.fn();- render(<MemoryControls mode="tree" onModeChange={noop} onRefresh={onRefresh} />);-- const btn = screen.getByTestId('memory-graph-refresh');- fireEvent.click(btn);- expect(btn).toBeDisabled();-- // Advance past the 600ms minimum spin window; the button re-enables.- await act(async () => {- await vi.advanceTimersByTimeAsync(600);- });- expect(btn).not.toBeDisabled();- expect(btn.getAttribute('aria-busy')).toBe('false');- });-- it('ignores re-clicks while already refreshing', async () => {- const onRefresh = vi.fn();- render(<MemoryControls mode="tree" onModeChange={noop} onRefresh={onRefresh} />);-- const btn = screen.getByTestId('memory-graph-refresh');- fireEvent.click(btn);- // A disabled button shouldn't re-fire, but guard against programmatic clicks too.- fireEvent.click(btn);- expect(onRefresh).toHaveBeenCalledTimes(1);- });-});--describe('<MemoryControls /> per engine', () => {- afterEach(() => {- engine.capabilities = null;- });-- it('offers the local store controls for an engine that keeps one', () => {- engine.capabilities = new Set(['tree', 'chunks']);- render(<MemoryControls mode="tree" onModeChange={noop} onRefresh={noop} />);- expect(screen.getByTestId('memory-wipe-all')).toBeInTheDocument();- expect(screen.getByTestId('memory-reset-tree')).toBeInTheDocument();- expect(screen.getByTestId('memory-build-trees')).toBeInTheDocument();- expect(screen.getByTestId('memory-graph-refresh')).toBeInTheDocument();- });-- it('offers only Refresh for hosted memory, which keeps no local store', () => {- engine.capabilities = new Set(['tree', 'retrieval', 'sources']);- render(<MemoryControls mode="tree" onModeChange={noop} onRefresh={noop} />);- expect(screen.queryByTestId('memory-wipe-all')).toBeNull();- expect(screen.queryByTestId('memory-reset-tree')).toBeNull();- expect(screen.queryByTestId('memory-build-trees')).toBeNull();- expect(screen.getByTestId('memory-graph-refresh')).toBeInTheDocument();- });-- it('shows every control while the engine is not known', () => {- render(<MemoryControls mode="tree" onModeChange={noop} onRefresh={noop} />);- expect(screen.getByTestId('memory-wipe-all')).toBeInTheDocument();- });-});diff --git a/app/src/components/intelligence/MemoryControls.tsx b/app/src/components/intelligence/MemoryControls.tsxdeleted file mode 100644index 6ee8d6ca06..0000000000--- a/app/src/components/intelligence/MemoryControls.tsx+++ /dev/null@@ -1,342 +0,0 @@-/**- * MemoryControls — the unified action toolbar for the memory surface.- *- * Extracted from `MemoryWorkspace` so the Brain page and Settings → Memory- * share one elegant, consistent control bar instead of a row of mismatched,- * differently-coloured buttons.- *- * Visual language (deliberate hierarchy, not a rainbow):- * - Trees / Contacts — a segmented graph-mode toggle on the left.- * - Build summary trees — the single primary (filled) action.- * - Refresh · View vault — quiet ghost buttons.- * - Reset memory · Reset memory tree — destructive, intentionally muted and- * set apart behind a divider; they only reveal their warning tint on hover.- *- * The parent owns the graph fetch: every mutation (and Refresh) calls- * `onRefresh()` so the caller re-pulls the graph on its own cadence.- *- * Everything but Refresh works on the engine's local chunk store and summary- * tree, so it shows only for an engine with `chunks`. Hosted memory draws its- * graph from the server's understanding and keeps no such store: it gets- * Refresh alone.- */-import { useCallback, useState } from 'react';--import { useT } from '../../lib/i18n/I18nContext';-import type { ToastNotification } from '../../types/intelligence';-import {- type GraphMode,- memoryTreeFlushNow,- memoryTreeResetTree,- memoryTreeWipeAll,-} from '../../utils/tauriCommands';-import ChipTabs from '../layout/ChipTabs';-import Button from '../ui/Button';-import Separator from '../ui/Separator';-import { ObsidianVaultSection } from './ObsidianVaultSection';-import { useMemoryEngine } from './useMemoryEngineCapabilities';--interface MemoryControlsProps {- mode: GraphMode;- onModeChange: (next: GraphMode) => void;- /** Re-pull the graph — parent owns the fetch. Called after every mutation. */- onRefresh: () => void;- onToast?: (toast: Omit<ToastNotification, 'id'>) => void;- /** Absolute content root (from graph export); enables the View vault button. */- contentRootAbs?: string | null;-}--export function MemoryControls({- mode,- onModeChange,- onRefresh,- onToast,- contentRootAbs,-}: MemoryControlsProps) {- const { t } = useT();- // Fails open, like the family gate: while the engine is unknown, every- // control shows.- const { capabilities } = useMemoryEngine();- const localStore = !capabilities || capabilities.has('chunks');- const [building, setBuilding] = useState(false);- const [wiping, setWiping] = useState(false);- const [resetting, setResetting] = useState(false);- const [refreshing, setRefreshing] = useState(false);- const busy = building || wiping || resetting;-- const handleWipe = useCallback(async () => {- // Two-step confirm so accidental clicks can't nuke a workspace.- if (!window.confirm(t('workspace.wipeConfirm'))) return;- setWiping(true);- try {- const resp = await memoryTreeWipeAll();- onToast?.({- type: 'success',- title: t('workspace.wipeSuccessTitle'),- message: t('workspace.wipeSuccessMessage')- .replace('{rows}', resp.rows_deleted.toLocaleString())- .replace('{dirs}', String(resp.dirs_removed.length))- .replace('{cursors}', resp.sync_state_cleared.toLocaleString()),- });- // Re-pull immediately so the canvas reflects the wipe.- onRefresh();- } catch (err) {- console.error('[ui-flow][memory-controls] wipe_all failed', err);- onToast?.({- type: 'error',- title: t('workspace.wipeFailedTitle'),- message: err instanceof Error ? err.message : String(err),- });- } finally {- setWiping(false);- }- }, [onToast, onRefresh, t]);-- const handleResetTree = useCallback(async () => {- if (!window.confirm(t('workspace.resetTreeConfirm'))) return;- setResetting(true);- try {- const resp = await memoryTreeResetTree();- onToast?.({- type: 'success',- title: t('workspace.resetTreeSuccessTitle'),- message: t('workspace.resetTreeSuccessMessage')- .replace('{treeRows}', resp.tree_rows_deleted.toLocaleString())- .replace('{chunks}', resp.chunks_requeued.toLocaleString())- .replace('{jobs}', resp.jobs_enqueued.toLocaleString()),- });- // reset_tree restarts from extract jobs (slower than seal-only) — give the- // worker a longer head start than build does before re-pulling.- setTimeout(() => onRefresh(), 8000);- } catch (err) {- console.error('[ui-flow][memory-controls] reset_tree failed', err);- onToast?.({- type: 'error',- title: t('workspace.resetTreeFailedTitle'),- message: err instanceof Error ? err.message : String(err),- });- } finally {- setResetting(false);- }- }, [onToast, onRefresh, t]);-- const handleBuildTrees = useCallback(async () => {- setBuilding(true);- try {- const resp = await memoryTreeFlushNow();- onToast?.({- type: resp.enqueued ? 'success' : 'info',- title: resp.enqueued- ? `Building summary trees · ${resp.stale_buffers} buffer(s)`- : 'Build already in progress',- message: resp.enqueued- ? 'Force-sealing every L0 buffer through the configured AI summariser. The graph will refresh once the worker drains.'- : 'A flush job for today is already queued — no new work needed.',- });- // The seal cascade runs async on the worker pool; 4s covers the typical- // case without making the UI feel stuck.- setTimeout(() => onRefresh(), 4000);- } catch (err) {- console.error('[ui-flow][memory-controls] flush_now failed', err);- onToast?.({- type: 'error',- title: t('workspace.buildTreesFailedTitle'),- message: err instanceof Error ? err.message : String(err),- });- } finally {- setBuilding(false);- }- }, [onToast, onRefresh, t]);-- const handleRefresh = useCallback(async () => {- if (refreshing) return;- console.debug('[ui-flow][memory-controls] manual refresh: entry');- setRefreshing(true);- try {- // `onRefresh` re-pulls the graph; the parent owns the fetch and may- // resolve synchronously (it just bumps a version key today). Run it- // alongside a short minimum spin window so the click always produces- // perceptible feedback instead of an instant, invisible no-op.- await Promise.all([- Promise.resolve(onRefresh()),- new Promise(resolve => setTimeout(resolve, 600)),- ]);- } catch (err) {- console.error('[ui-flow][memory-controls] manual refresh failed', err);- } finally {- setRefreshing(false);- console.debug('[ui-flow][memory-controls] manual refresh: exit');- }- }, [onRefresh, refreshing]);-- return (- <div className="flex flex-wrap items-center justify-between gap-3" data-testid="memory-actions">- {localStore ? <ModeToggle mode={mode} onChange={onModeChange} /> : <span />}-- <div className="flex flex-wrap items-center gap-2">- {localStore ? (- <>- {/* Destructive actions — muted, set apart behind a divider. */}- <Button- variant="secondary"- tone="danger"- size="sm"- onClick={handleWipe}- disabled={busy}- data-testid="memory-wipe-all"- className="text-content-muted border-line"- leadingIcon={wiping ? <Spinner /> : <TrashIcon />}- title={t('workspace.wipeTitle')}>- {wiping ? t('workspace.resetting') : t('workspace.resetMemory')}- </Button>- <Button- variant="secondary"- size="sm"- onClick={handleResetTree}- disabled={busy}- data-testid="memory-reset-tree"- className="text-content-muted border-line hover:border-amber-300 hover:bg-amber-50 hover:text-amber-700 dark:hover:border-amber-500/30 dark:hover:bg-amber-500/10 dark:hover:text-amber-300"- leadingIcon={resetting ? <Spinner /> : <RefreshIcon />}- title={t('workspace.resetTreeTitle')}>- {resetting ? t('workspace.rebuilding') : t('workspace.resetMemoryTree')}- </Button>-- <Separator orientation="vertical" className="mx-1 h-5 self-center bg-surface-strong" />- </>- ) : null}-- {/* Secondary actions — quiet ghost buttons. */}- <Button- variant="secondary"- size="sm"- onClick={handleRefresh}- disabled={refreshing}- aria-busy={refreshing}- data-testid="memory-graph-refresh"- leadingIcon={refreshing ? <Spinner /> : <RefreshIcon />}- title={t('common.refresh')}>- {t('common.refresh')}- </Button>- {localStore && contentRootAbs ? (- <ObsidianVaultSection contentRootAbs={contentRootAbs} onToast={onToast} />- ) : null}-- {/* Primary action. */}- {localStore ? (- <Button- variant="primary"- size="sm"- onClick={handleBuildTrees}- disabled={building}- data-testid="memory-build-trees"- leadingIcon={building ? <Spinner /> : <BrainIcon />}>- {building ? t('workspace.building') : t('workspace.buildSummaryTrees')}- </Button>- ) : null}- </div>- </div>- );-}--// ── Mode toggle ───────────────────────────────────────────────────────────────--interface ModeToggleProps {- mode: GraphMode;- onChange: (next: GraphMode) => void;-}--function ModeToggle({ mode, onChange }: ModeToggleProps) {- const { t } = useT();- return (- <ChipTabs<GraphMode>- items={[- { id: 'tree', label: t('workspace.trees'), testId: 'memory-graph-mode-tree' },- { id: 'contacts', label: t('workspace.contacts'), testId: 'memory-graph-mode-contacts' },- ]}- value={mode}- onChange={onChange}- as="tab"- ariaLabel={t('workspace.graphViewMode')}- testId="memory-graph-mode-toggle"- className="inline-flex items-center gap-1.5"- />- );-}--// ── Tiny inline icons (no extra dep) ──────────────────────────────────────────--function RefreshIcon() {- return (- <svg- width="14"- height="14"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="1.8"- strokeLinecap="round"- strokeLinejoin="round"- aria-hidden="true">- <path d="M21 12a9 9 0 11-3-6.7" />- <path d="M21 4v5h-5" />- <path d="M3 12a9 9 0 003 6.7" />- <path d="M3 20v-5h5" />- </svg>- );-}--function TrashIcon() {- return (- <svg- width="14"- height="14"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="1.8"- strokeLinecap="round"- strokeLinejoin="round"- aria-hidden="true">- <path d="M3 6h18" />- <path d="M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2" />- <path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6" />- <path d="M10 11v6" />- <path d="M14 11v6" />- </svg>- );-}--function BrainIcon() {- return (- <svg- width="14"- height="14"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="1.8"- strokeLinecap="round"- strokeLinejoin="round"- aria-hidden="true">- <path d="M9.5 2A2.5 2.5 0 0112 4.5v15a2.5 2.5 0 01-4.96.44 2.5 2.5 0 01-2.96-3.08 3 3 0 01-.34-5.58 2.5 2.5 0 011.32-4.24 2.5 2.5 0 011.98-3A2.5 2.5 0 019.5 2z" />- <path d="M14.5 2A2.5 2.5 0 0012 4.5v15a2.5 2.5 0 004.96.44 2.5 2.5 0 002.96-3.08 3 3 0 00.34-5.58 2.5 2.5 0 00-1.32-4.24 2.5 2.5 0 00-1.98-3A2.5 2.5 0 0014.5 2z" />- </svg>- );-}--function Spinner() {- return (- <svg- className="animate-spin"- width="14"- height="14"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- aria-hidden="true">- <circle cx="12" cy="12" r="9" opacity="0.25" />- <path d="M21 12a9 9 0 00-9-9" />- </svg>- );-}diff --git a/app/src/components/intelligence/MemoryEngineRow.tsx b/app/src/components/intelligence/MemoryEngineRow.tsxdeleted file mode 100644index 1cbe72509f..0000000000--- a/app/src/components/intelligence/MemoryEngineRow.tsx+++ /dev/null@@ -1,39 +0,0 @@-import { useNavigate } from 'react-router-dom';--import { useT } from '../../lib/i18n/I18nContext';-import { Button } from '../ui';-import { useMemoryEngine } from './useMemoryEngineCapabilities';--/**- * "Memory engine: <label> · Change" — a one-line summary on the Brain page that- * links to Settings → memory engine. Renders nothing until the core answers (or- * if it does not support memory engines), so it never blocks the page.- */-export default function MemoryEngineRow() {- const { t } = useT();- const navigate = useNavigate();- const { id, label } = useMemoryEngine();- const engine = id ? { id, label: label ?? id } : null;-- if (!engine) return null;- return (- <div- data-testid="brain-memory-engine-row"- className="flex items-center justify-between gap-3 rounded-lg border border-line px-4 py-2.5 text-sm">- <span className="text-content-secondary">- {t('memoryEngine.row.label')}{' '}- <span className="font-medium text-content">- {t(`memoryEngine.engine.${engine.id}.label`, engine.label)}- </span>- </span>- <Button- variant="tertiary"- size="xs"- analyticsId="brain-memory-engine-change"- data-testid="brain-memory-engine-change"- onClick={() => navigate('/settings/memory-engine')}>- {t('memoryEngine.row.change')}- </Button>- </div>- );-}diff --git a/app/src/components/intelligence/MemoryFamilyGate.test.tsx b/app/src/components/intelligence/MemoryFamilyGate.test.tsxdeleted file mode 100644index 02f225f9d4..0000000000--- a/app/src/components/intelligence/MemoryFamilyGate.test.tsx+++ /dev/null@@ -1,103 +0,0 @@-/**- * MemoryFamilyGate: shows children when the bound engine has the family (or- * when that is unknown), and a friendly "Not available" state when it does not.- */-import { screen, waitFor } from '@testing-library/react';-import { beforeEach, describe, expect, test, vi } from 'vitest';--import { renderWithProviders } from '../../test/test-utils';-import MemoryFamilyGate from './MemoryFamilyGate';-import { resetMemoryEngineCacheForTests } from './useMemoryEngineCapabilities';--const hoisted = vi.hoisted(() => ({ list: vi.fn(), get: vi.fn() }));--vi.mock('../../utils/tauriCommands/memoryEngine', () => ({- memoryEnginesList: (...a: unknown[]) => hoisted.list(...a),- memoryEngineGet: (...a: unknown[]) => hoisted.get(...a),-}));--function bind(driver: string, label: string, capabilities: string[]) {- hoisted.get.mockResolvedValue({ driver });- hoisted.list.mockResolvedValue({- active: driver,- engines: [{ id: driver, label, capabilities }],- });-}--describe('MemoryFamilyGate', () => {- beforeEach(() => {- hoisted.list.mockReset();- hoisted.get.mockReset();- resetMemoryEngineCacheForTests();- });-- test('shows the empty state naming the engine when the family is missing', async () => {- bind('mem0', 'Mem0', ['core', 'recall', 'portability']);- renderWithProviders(- <MemoryFamilyGate family="goals">- <div>goals body</div>- </MemoryFamilyGate>- );- await waitFor(() => expect(screen.getByTestId('memory-family-unavailable')).toBeTruthy());- expect(screen.getByText(/Not available with/)).toBeTruthy();- expect(screen.queryByText('goals body')).toBeNull();- });-- test('renders children when the engine has the family', async () => {- bind('tinymemory', 'Local', ['core', 'recall', 'goals']);- renderWithProviders(- <MemoryFamilyGate family="goals">- <div>goals body</div>- </MemoryFamilyGate>- );- await waitFor(() => expect(hoisted.list).toHaveBeenCalled());- expect(screen.getByText('goals body')).toBeTruthy();- expect(screen.queryByTestId('memory-family-unavailable')).toBeNull();- });-- test('fails open when the core cannot report the engine', async () => {- hoisted.get.mockRejectedValue(new Error('offline'));- hoisted.list.mockRejectedValue(new Error('offline'));- renderWithProviders(- <MemoryFamilyGate family="goals">- <div>goals body</div>- </MemoryFamilyGate>- );- await waitFor(() => expect(hoisted.get).toHaveBeenCalled());- expect(screen.getByText('goals body')).toBeTruthy();- expect(screen.queryByTestId('memory-family-unavailable')).toBeNull();- });-- test('shows a skeleton, not the children, while the engine is loading', async () => {- let release: (v: unknown) => void = () => {};- hoisted.get.mockReturnValue(new Promise(r => (release = r)));- hoisted.list.mockResolvedValue({ active: 'mem0', engines: [] });- renderWithProviders(- <MemoryFamilyGate family="goals">- <div>goals body</div>- </MemoryFamilyGate>- );- expect(screen.getByTestId('memory-family-loading')).toBeTruthy();- expect(screen.queryByText('goals body')).toBeNull();- release({ driver: 'tinymemory' });- await waitFor(() => expect(screen.queryByTestId('memory-family-loading')).toBeNull());- });-- test('gates every family when memory is paused on the null driver', async () => {- hoisted.get.mockResolvedValue({- driver: 'null',- fell_back_from: 'mem0',- last_error: 'engine credential unavailable',- });- hoisted.list.mockResolvedValue({ active: 'null', engines: [] });- renderWithProviders(- <MemoryFamilyGate family="core">- <div>core body</div>- </MemoryFamilyGate>- );- await waitFor(() => expect(screen.getByTestId('memory-family-unavailable')).toBeTruthy());- expect(screen.getByText('Memory is paused')).toBeTruthy();- expect(screen.getByText('engine credential unavailable')).toBeTruthy();- expect(screen.queryByText('core body')).toBeNull();- });-});diff --git a/app/src/components/intelligence/MemoryFamilyGate.tsx b/app/src/components/intelligence/MemoryFamilyGate.tsxdeleted file mode 100644index 7ef719bbf2..0000000000--- a/app/src/components/intelligence/MemoryFamilyGate.tsx+++ /dev/null@@ -1,67 +0,0 @@-import type { ReactNode } from 'react';--import { useT } from '../../lib/i18n/I18nContext';-import { useMemoryEngine } from './useMemoryEngineCapabilities';--interface MemoryFamilyGateProps {- /** Capability family the wrapped content needs (e.g. `tree`, `goals`). */- family: string;- children: ReactNode;-}--/**- * Renders `children` when the bound memory engine has `family`, otherwise a- * friendly "Not available with <engine>" state in place of an error. While the- * engine is still loading it shows a skeleton instead of the children (so a- * feature the engine lacks never flashes an error first). When the core cannot- * answer at all it fails open. Memory paused on the `null` driver (a failed- * engine bind) gates every family.- */-export default function MemoryFamilyGate({ family, children }: MemoryFamilyGateProps) {- const { t } = useT();- const { loading, id, label, capabilities, current, error } = useMemoryEngine();-- if (loading) {- return (- <div- data-testid="memory-family-loading"- aria-busy="true"- className="animate-pulse space-y-2 rounded-lg border border-line px-4 py-6">- <div className="h-3 w-1/3 rounded bg-line" />- <div className="h-3 w-2/3 rounded bg-line" />- </div>- );- }-- if (id === 'null') {- return (- <div- data-testid="memory-family-unavailable"- data-family={family}- className="rounded-lg border border-line px-4 py-6 text-center">- <p className="text-sm font-medium text-content">{t('memoryEngine.paused')}</p>- {current?.last_error ? (- <p className="mt-1 text-xs text-content-muted">{current.last_error}</p>- ) : null}- <p className="mt-1 text-xs text-content-muted">{t('memoryEngine.unavailableHint')}</p>- </div>- );- }-- if (error !== null || !id || !capabilities || capabilities.has(family)) {- return <>{children}</>;- }-- const engine = t(`memoryEngine.engine.${id}.label`, label ?? id);- return (- <div- data-testid="memory-family-unavailable"- data-family={family}- className="rounded-lg border border-line px-4 py-6 text-center">- <p className="text-sm font-medium text-content">- {t('memoryEngine.unavailable').replace('{engine}', engine)}- </p>- <p className="mt-1 text-xs text-content-muted">{t('memoryEngine.unavailableHint')}</p>- </div>- );-}diff --git a/app/src/components/intelligence/MemoryGraph.test.tsx b/app/src/components/intelligence/MemoryGraph.test.tsxdeleted file mode 100644index d3ebbb24e8..0000000000--- a/app/src/components/intelligence/MemoryGraph.test.tsx+++ /dev/null@@ -1,323 +0,0 @@-import { configureStore } from '@reduxjs/toolkit';-import { fireEvent, render, screen, waitFor } from '@testing-library/react';-import type { PropsWithChildren } from 'react';-import { Provider } from 'react-redux';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import themeReducer from '../../store/themeSlice';-import type { GraphEdge, GraphNode } from '../../utils/tauriCommands';-import { MemoryGraph } from './MemoryGraph';--function ReduxWrapper({ children }: PropsWithChildren) {- const store = configureStore({ reducer: { theme: themeReducer } });- return <Provider store={store}>{children}</Provider>;-}--const mocks = vi.hoisted(() => ({- openUrl: vi.fn(),- openWorkspacePath: vi.fn(),- previewWorkspaceText: vi.fn(),-}));--vi.mock('../../utils/openUrl', () => ({ openUrl: (...args: unknown[]) => mocks.openUrl(...args) }));-vi.mock('../../utils/tauriCommands/workspacePaths', () => ({- openWorkspacePath: (...args: unknown[]) => mocks.openWorkspacePath(...args),- previewWorkspaceText: (...args: unknown[]) => mocks.previewWorkspaceText(...args),-}));--function makeSummaryNode(overrides: Partial<GraphNode> = {}): GraphNode {- return {- kind: 'summary',- id: 'sum-1',- label: 'Summary 1',- tree_id: 't-1',- tree_kind: 'topic',- tree_scope: 'work',- level: 0,- parent_id: null,- child_count: 2,- file_basename: 'summary-1',- ...overrides,- };-}--function makeChunkNode(overrides: Partial<GraphNode> = {}): GraphNode {- return { kind: 'chunk', id: 'chunk-1', label: 'A chunk', ...overrides };-}--function makeContactNode(overrides: Partial<GraphNode> = {}): GraphNode {- return {- kind: 'contact',- id: 'person:alice',- label: 'Alice',- entity_kind: 'person',- ...overrides,- };-}--describe('<MemoryGraph />', () => {- beforeEach(() => {- mocks.openUrl.mockReset();- mocks.openUrl.mockResolvedValue(undefined);- mocks.openWorkspacePath.mockReset();- mocks.openWorkspacePath.mockResolvedValue(undefined);- mocks.previewWorkspaceText.mockReset();- mocks.previewWorkspaceText.mockResolvedValue({- path: 'memory_tree/content/wiki/summaries/topic-workspace-one/L2/summary-A.md',- absolutePath:- '/Users/me/openhuman/memory_tree/content/wiki/summaries/topic-workspace-one/L2/summary-A.md',- contents: '# Summary\n\nWorkspace one notes',- truncated: false,- sizeBytes: 30,- });- });-- it('renders the empty state when there are no nodes', () => {- render(<MemoryGraph nodes={[]} edges={[]} mode="tree" />, { wrapper: ReduxWrapper });- expect(screen.getByTestId('memory-graph-empty')).toBeInTheDocument();- });-- it('fires onReady once the layout settles (synchronous SVG path under jsdom)', async () => {- const onReady = vi.fn();- const nodes = [- makeSummaryNode({ id: 'root', level: 0, parent_id: null }),- makeSummaryNode({ id: 'child', level: 1, parent_id: 'root' }),- ];- render(<MemoryGraph nodes={nodes} edges={[]} mode="tree" onReady={onReady} />, {- wrapper: ReduxWrapper,- });- await waitFor(() => expect(onReady).toHaveBeenCalledTimes(1));- });-- it('does not fire onReady for an empty graph (nothing to lay out)', () => {- const onReady = vi.fn();- render(<MemoryGraph nodes={[]} edges={[]} mode="tree" onReady={onReady} />, {- wrapper: ReduxWrapper,- });- expect(onReady).not.toHaveBeenCalled();- });-- it('renders an SVG with one circle per node in tree mode', () => {- const nodes = [- makeSummaryNode({ id: 'root', level: 0, parent_id: null }),- makeSummaryNode({ id: 'child', level: 1, parent_id: 'root' }),- ];- const { container } = render(<MemoryGraph nodes={nodes} edges={[]} mode="tree" />, {- wrapper: ReduxWrapper,- });- expect(screen.getByTestId('memory-graph-svg')).toBeInTheDocument();- expect(container.querySelectorAll('circle').length).toBe(2);- expect(screen.getByTestId('memory-graph-node-root')).toBeInTheDocument();- expect(screen.getByTestId('memory-graph-node-child')).toBeInTheDocument();- });-- it('renders contacts-mode legend rows for chunk and contact', () => {- const nodes = [- makeChunkNode({ id: 'd1' }),- makeContactNode({ id: 'person:alice', label: 'Alice' }),- ];- const edges: GraphEdge[] = [{ from: 'd1', to: 'person:alice' }];- render(<MemoryGraph nodes={nodes} edges={edges} mode="contacts" />, { wrapper: ReduxWrapper });- // Two legend rows render with i18n keys as fallback (graph.document/contact)- // — assert via the rendered nodes count instead, which is deterministic.- expect(screen.getAllByTestId(/memory-graph-node-/).length).toBe(2);- });-- it('opens a summary node through the shared workspace path command', async () => {- const nodes = [- makeSummaryNode({- id: 'sum-A',- tree_kind: 'topic',- tree_scope: 'workspace one',- level: 2,- file_basename: 'summary-A',- }),- ];- render(<MemoryGraph nodes={nodes} edges={[]} mode="tree" />, { wrapper: ReduxWrapper });- fireEvent.click(screen.getByTestId('memory-graph-node-sum-A'));- await waitFor(() => {- expect(mocks.openWorkspacePath).toHaveBeenCalledWith(- 'memory_tree/content/wiki/summaries/topic-workspace-one/L2/summary-A.md'- );- });- expect(mocks.openUrl).not.toHaveBeenCalled();- });-- it('logs workspace open failures without falling back to raw URL opens', async () => {- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});- mocks.openWorkspacePath.mockRejectedValueOnce(new Error('open failed'));- const nodes = [- makeSummaryNode({- id: 'sum-open-fails',- tree_kind: 'topic',- tree_scope: 'workspace one',- level: 2,- file_basename: 'summary-A',- }),- ];-- render(<MemoryGraph nodes={nodes} edges={[]} mode="tree" />, { wrapper: ReduxWrapper });- fireEvent.click(screen.getByTestId('memory-graph-node-sum-open-fails'));-- await waitFor(() => {- expect(errorSpy).toHaveBeenCalledWith(- '[memory-graph] openWorkspacePath failed',- expect.any(Error)- );- });- expect(mocks.openUrl).not.toHaveBeenCalled();- errorSpy.mockRestore();- });-- it('keeps non-Gmail source prefixes in summary workspace paths', async () => {- const nodes = [- makeSummaryNode({- id: 'sum-slack',- tree_kind: 'source',- tree_scope: 'slack:#eng',- level: 2,- file_basename: 'summary-slack',- }),- ];- render(<MemoryGraph nodes={nodes} edges={[]} mode="tree" />, { wrapper: ReduxWrapper });- fireEvent.click(screen.getByTestId('memory-graph-node-sum-slack'));- await waitFor(() => {- expect(mocks.openWorkspacePath).toHaveBeenCalledWith(- 'memory_tree/content/wiki/summaries/source-slack-eng/L2/summary-slack.md'- );- });- });-- it('previews a hovered summary through the shared workspace preview command', async () => {- const nodes = [- makeSummaryNode({- id: 'sum-A',- tree_kind: 'topic',- tree_scope: 'workspace one',- level: 2,- file_basename: 'summary-A',- }),- ];- render(<MemoryGraph nodes={nodes} edges={[]} mode="tree" />, { wrapper: ReduxWrapper });-- fireEvent.mouseEnter(screen.getByTestId('memory-graph-node-sum-A'));- fireEvent.click(screen.getByTestId('memory-graph-preview-sum-A'));-- await waitFor(() => {- expect(mocks.previewWorkspaceText).toHaveBeenCalledWith(- 'memory_tree/content/wiki/summaries/topic-workspace-one/L2/summary-A.md'- );- });- expect(await screen.findByTestId('memory-graph-preview')).toHaveTextContent(- 'Workspace one notes'- );- });-- it('shows preview errors from the shared workspace preview command', async () => {- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});- mocks.previewWorkspaceText.mockRejectedValueOnce(new Error('preview failed'));- const nodes = [- makeSummaryNode({- id: 'sum-preview-fails',- tree_kind: 'topic',- tree_scope: 'workspace one',- level: 2,- file_basename: 'summary-A',- }),- ];-- render(<MemoryGraph nodes={nodes} edges={[]} mode="tree" />, { wrapper: ReduxWrapper });- fireEvent.mouseEnter(screen.getByTestId('memory-graph-node-sum-preview-fails'));- fireEvent.click(screen.getByTestId('memory-graph-preview-sum-preview-fails'));-- expect(await screen.findByTestId('memory-graph-preview')).toHaveTextContent('preview failed');- expect(errorSpy).toHaveBeenCalledWith(- '[memory-graph] previewWorkspaceText failed',- expect.any(Error)- );- errorSpy.mockRestore();- });-- it('marks truncated summary previews in the preview panel', async () => {- mocks.previewWorkspaceText.mockResolvedValueOnce({- path: 'memory_tree/content/wiki/summaries/topic-workspace-one/L2/summary-A.md',- absolutePath:- '/Users/me/openhuman/memory_tree/content/wiki/summaries/topic-workspace-one/L2/summary-A.md',- contents: '# Summary',- truncated: true,- sizeBytes: 100_000,- });- const nodes = [- makeSummaryNode({- id: 'sum-truncated',- tree_kind: 'topic',- tree_scope: 'workspace one',- level: 2,- file_basename: 'summary-A',- }),- ];-- render(<MemoryGraph nodes={nodes} edges={[]} mode="tree" />, { wrapper: ReduxWrapper });- fireEvent.mouseEnter(screen.getByTestId('memory-graph-node-sum-truncated'));- fireEvent.click(screen.getByTestId('memory-graph-preview-sum-truncated'));-- expect(await screen.findByTestId('memory-graph-preview')).toHaveTextContent('# Summary');- expect(screen.getByTestId('memory-graph-preview')).toHaveTextContent('…');- });-- it('keeps the summary preview action reachable after leaving the SVG node', () => {- const nodes = [- makeSummaryNode({- id: 'sum-A',- tree_kind: 'topic',- tree_scope: 'workspace one',- level: 2,- file_basename: 'summary-A',- }),- ];- render(<MemoryGraph nodes={nodes} edges={[]} mode="tree" />, { wrapper: ReduxWrapper });-- const node = screen.getByTestId('memory-graph-node-sum-A');- fireEvent.mouseEnter(node);- fireEvent.mouseLeave(node, { relatedTarget: screen.getByTestId('memory-graph-tooltip') });-- expect(screen.getByTestId('memory-graph-preview-sum-A')).toBeInTheDocument();- });-- it('clears the hovered node when the pointer leaves the graph', () => {- const nodes = [- makeSummaryNode({- id: 'sum-A',- tree_kind: 'topic',- tree_scope: 'workspace one',- level: 2,- file_basename: 'summary-A',- }),- ];- const { container } = render(<MemoryGraph nodes={nodes} edges={[]} mode="tree" />, {- wrapper: ReduxWrapper,- });-- fireEvent.mouseEnter(screen.getByTestId('memory-graph-node-sum-A'));- expect(screen.getByTestId('memory-graph-tooltip')).toBeInTheDocument();- fireEvent.mouseLeave(container.querySelector('.memory-graph') as Element);-- expect(screen.queryByTestId('memory-graph-tooltip')).not.toBeInTheDocument();- });-- it('does NOT call workspace open when a non-summary node is clicked', async () => {- const nodes = [makeChunkNode({ id: 'doc-1' })];- render(<MemoryGraph nodes={nodes} edges={[]} mode="contacts" />, { wrapper: ReduxWrapper });- fireEvent.click(screen.getByTestId('memory-graph-node-doc-1'));- await Promise.resolve();- expect(mocks.openWorkspacePath).not.toHaveBeenCalled();- });-- it('shows a tooltip footer when a node is hovered', () => {- const nodes = [makeContactNode({ id: 'person:bob', label: 'Bob' })];- render(<MemoryGraph nodes={nodes} edges={[]} mode="contacts" />, { wrapper: ReduxWrapper });- fireEvent.mouseEnter(screen.getByTestId('memory-graph-node-person:bob'));- expect(screen.getByTestId('memory-graph-tooltip')).toBeInTheDocument();- expect(screen.getByTestId('memory-graph-tooltip').textContent).toContain('Bob');- });-});diff --git a/app/src/components/intelligence/MemoryGraph.tsx b/app/src/components/intelligence/MemoryGraph.tsxdeleted file mode 100644index d036e3f6d1..0000000000--- a/app/src/components/intelligence/MemoryGraph.tsx+++ /dev/null@@ -1,873 +0,0 @@-/**- * Obsidian-style force-directed graph view for the memory tree.- *- * Two modes:- * - `tree` — sealed summary nodes connected by parent→child- * - `contacts` — raw chunks linked to person entities they mention- *- * Layout: a tiny barycentric force simulation- * - parent → child links pull connected nodes together- * - all-pairs Coulomb repulsion pushes overlapping nodes apart- * - centring force keeps the cloud anchored in the viewport- *- * Colour: in tree mode each level lights up in its own hue (mirroring the- * Obsidian `path:L{n}` groups) with a soft glow on summary nodes; leaves- * stay a quiet slate.- *- * Interaction: drag a node to reposition it, drag the background to pan,- * scroll to zoom, and "Reset view" recentres. Click a summary node →- * opens the matching `.md` file through the shared workspace path- * command (skipped when the pointer was dragging). This keeps Memory- * graph file actions on the same guarded contract as chat workspace links.- *- * Rendering: where WebGL is available we use a Pixi.js + d3-force canvas- * ({@link PixiGraph}) — the same stack Obsidian's graph runs on, smooth- * well past the 1000-node cap. Without WebGL (e.g. jsdom under test) it- * falls back to a deterministic pure-SVG renderer with the same colours,- * interactions and click/preview behaviour.- */-import {- type PointerEvent as ReactPointerEvent,- type WheelEvent as ReactWheelEvent,- useCallback,- useEffect,- useMemo,- useReducer,- useRef,- useState,-} from 'react';--import { useT } from '../../lib/i18n/I18nContext';-import { useAppSelector } from '../../store/hooks';-import { resolveTheme, type ThemeMode } from '../../store/themeSlice';-import { type GraphEdge, type GraphMode, type GraphNode } from '../../utils/tauriCommands';-import { openWorkspacePath, previewWorkspaceText } from '../../utils/tauriCommands/workspacePaths';-import Button from '../ui/Button';-import {- CONTACT_COLOR,- LEAF_COLOR,- levelColor,- nodeColor,- nodeRadius,- type SimTuning,- SOURCE_COLOR,- VIEWPORT_H,- VIEWPORT_W,- ZOOM_MAX,- ZOOM_MIN,-} from './memoryGraphLayout';-import { summaryWorkspacePath } from './memoryWorkspacePaths';-import { PixiGraph } from './PixiGraph';-import { seedSvgLayout } from './seedSvgLayout';-import { useSvgForceLayout, WORKER_SUPPORTED } from './useSvgForceLayout';--/** Use WebGL (Pixi) in production; fall back to SVG in test (jsdom). */-const HAS_WEBGL =- typeof document !== 'undefined' &&- typeof document.createElement === 'function' &&- (() => {- try {- const c = document.createElement('canvas');- return !!(c.getContext('webgl2') || c.getContext('webgl'));- } catch {- return false;- }- })();--interface SimNode extends GraphNode {- x: number;- y: number;- vx: number;- vy: number;-}--interface SimState {- sim: SimNode[];- edges: Array<[number, number]>;- radii: number[];- alpha: number;-}--// Stable empties so the worker-layout effect's deps don't change every render-// when there's no graph yet.-const NO_NODES: SimNode[] = [];-const NO_RADII: number[] = [];-const NO_EDGES: Array<[number, number]> = [];-// Stable centre the SVG worker layout settles around (matches the viewBox).-const SVG_CENTER: readonly [number, number] = [VIEWPORT_W / 2, VIEWPORT_H / 2];--interface MemoryGraphProps {- /** Pre-fetched summary / chunk / contact nodes. */- nodes: GraphNode[];- /** Explicit edges (only used in contacts mode). */- edges: GraphEdge[];- /** Which graph this is — drives colour palette + click behaviour. */- mode: GraphMode;- /** Optional override for the empty-state message. */- emptyHint?: string;- /** Optional label for the central hub node (WebGL path). Defaults to "Memory". */- rootLabel?: string;- /** Fill the parent's height (full-screen) instead of the fixed 640px card. */- fill?: boolean;- /** Initial auto-fit zoom. Lower = more zoomed out. Defaults to 0.17. */- fitScale?: number;- /** Fit the whole graph tightly to the viewport instead of a fixed zoom. */- fitToBounds?: boolean;- /** Draw an always-on text label under each node. */- showLabels?: boolean;- /**- * Optional force-simulation tuning applied on the WebGL (Pixi) path. Every- * field defaults to identity, so omitting it preserves the standard layout;- * the orchestration scale showcase passes higher repulsion / link length for- * a wide fan-out.- */- tuning?: SimTuning;- /**- * Fired exactly once when the graph's force layout first settles (SVG- * worker `end`, the synchronous relax fallback, or the Pixi sim cooling).- * A loading overlay (e.g. the Brain page) waits on this to reveal the graph.- */- onReady?: () => void;-}--interface SummaryPreviewState {- path: string;- contents: string;- truncated: boolean;- error: string | null;-}--/**- * Map a pointer's client coords into the SVG's viewBox coordinate space- * (SVG fallback only). Returns null without a live CTM (e.g. jsdom) so the- * pan/zoom handlers degrade to no-ops under test.- */-function clientToViewBox(- svg: SVGSVGElement | null,- clientX: number,- clientY: number-): { x: number; y: number } | null {- if (!svg || typeof svg.getScreenCTM !== 'function') return null;- const ctm = svg.getScreenCTM();- if (!ctm) return null;- const inv = ctm.inverse();- return {- x: inv.a * clientX + inv.c * clientY + inv.e,- y: inv.b * clientX + inv.d * clientY + inv.f,- };-}--/**- * Run the force simulation for `iterations` ticks. Mutates positions in- * place so we can re-use the same buffer across renders.- */-function relaxLayout(nodes: SimNode[], edges: Array<[number, number]>, iterations = 220): void {- const REPULSION = 1800;- const SPRING_K = 0.04;- const SPRING_LEN = 60;- const CENTER_K = 0.0025;- const FRICTION = 0.85;- const cx = VIEWPORT_W / 2;- const cy = VIEWPORT_H / 2;-- for (let iter = 0; iter < iterations; iter++) {- for (let i = 0; i < nodes.length; i++) {- for (let j = i + 1; j < nodes.length; j++) {- const a = nodes[i];- const b = nodes[j];- const dx = a.x - b.x;- const dy = a.y - b.y;- const dist2 = dx * dx + dy * dy + 0.01;- const force = REPULSION / dist2;- const dist = Math.sqrt(dist2);- const fx = (dx / dist) * force;- const fy = (dy / dist) * force;- a.vx += fx;- a.vy += fy;- b.vx -= fx;- b.vy -= fy;- }- }- for (const [ai, bi] of edges) {- const a = nodes[ai];- const b = nodes[bi];- const dx = b.x - a.x;- const dy = b.y - a.y;- const dist = Math.sqrt(dx * dx + dy * dy) + 0.01;- const delta = dist - SPRING_LEN;- const fx = (dx / dist) * delta * SPRING_K;- const fy = (dy / dist) * delta * SPRING_K;- a.vx += fx;- a.vy += fy;- b.vx -= fx;- b.vy -= fy;- }- for (const n of nodes) {- n.vx += (cx - n.x) * CENTER_K;- n.vy += (cy - n.y) * CENTER_K;- n.vx *= FRICTION;- n.vy *= FRICTION;- n.x += n.vx;- n.y += n.vy;- }- }-}--export function MemoryGraph({- nodes,- edges,- mode,- emptyHint,- rootLabel,- fill,- fitScale,- fitToBounds,- showLabels,- tuning,- onReady,-}: MemoryGraphProps) {- const { t } = useT();- const themeMode = useAppSelector(state => state.theme?.mode ?? 'system') as ThemeMode;- const isDark = resolveTheme(themeMode) === 'dark';- const [hovered, setHovered] = useState<GraphNode | null>(null);-- // Fire `onReady` at most once across this component's lifetime. The latest- // callback is held in a ref so `fireReady` stays stable (the SVG layout hook- // depends on a stable `onSettled`, and the guard prevents refires on reheat).- const onReadyRef = useRef(onReady);- onReadyRef.current = onReady;- const readyFiredRef = useRef(false);- const fireReady = useCallback(() => {- if (readyFiredRef.current) return;- readyFiredRef.current = true;- console.debug('[memory-graph] layout settled → onReady');- onReadyRef.current?.();- }, []);- const [preview, setPreview] = useState<SummaryPreviewState | null>(null);- const [previewingPath, setPreviewingPath] = useState<string | null>(null);- const svgRef = useRef<SVGSVGElement | null>(null);-- // Pan / zoom transform applied to the graph group, plus the live drag- // state. Node positions live in the memoised `sim` buffer and are- // mutated in place during a node drag; `bumpTick` forces a re-render so- // the moved node repaints without re-running the physics.- const [view, setView] = useState({ tx: 0, ty: 0, scale: 1 });- const [, bumpTick] = useReducer((c: number) => c + 1, 0);- const [grabbing, setGrabbing] = useState(false);- // Bumped by "Reset view" — the Pixi renderer watches it to recentre.- const [resetSignal, bumpReset] = useReducer((c: number) => c + 1, 0);- // Flips true if Pixi fails to init at runtime → fall back to SVG even- // though supportsWebGL() was true at module load.- const [pixiFailed, setPixiFailed] = useState(false);- const useWebGL = HAS_WEBGL && !pixiFailed;- const dragRef = useRef<- | { kind: 'node'; node: SimNode; dx: number; dy: number }- | { kind: 'pan'; vbStartX: number; vbStartY: number; tx0: number; ty0: number }- | null- >(null);- // True once the pointer moved during the current gesture — guards the- // node click so a drag doesn't also open the summary file.- const movedRef = useRef(false);- // Halts the SVG layout worker once the user grabs a node/background, so its- // streamed positions stop fighting the manual drag. Set after the hook below.- const stopLayoutRef = useRef<() => void>(() => {});- // Set once the user grabs the camera, so the settle-time auto-fit doesn't- // yank the view out from under them.- const userInteractedRef = useRef(false);- // Re-frame the SVG graph from "Reset view" (set after fitToView below).- const fitRef = useRef<() => void>(() => {});- // Holds the current sim across renders; during the next build it still points- // at the OUTGOING sim, whose nodes carry the latest live coordinates (the- // worker / a drag mutate them in place) — read for position carry-over.- const liveSimRef = useRef<SimState | null>(null);-- const clientToGraph = useCallback(- (clientX: number, clientY: number) => {- const vb = clientToViewBox(svgRef.current, clientX, clientY);- if (!vb) return null;- return { x: (vb.x - view.tx) / view.scale, y: (vb.y - view.ty) / view.scale };- },- [view]- );-- const onNodePointerDown = useCallback(- (e: ReactPointerEvent, n: SimNode) => {- // Stop the background pan from also starting on this pointer down.- e.stopPropagation();- movedRef.current = false;- const g = clientToGraph(e.clientX, e.clientY);- if (!g) return;- (e.currentTarget as Element).setPointerCapture?.(e.pointerId);- dragRef.current = { kind: 'node', node: n, dx: g.x - n.x, dy: g.y - n.y };- setGrabbing(true);- },- [clientToGraph]- );-- const onBackgroundPointerDown = useCallback(- (e: ReactPointerEvent) => {- movedRef.current = false;- const vb = clientToViewBox(svgRef.current, e.clientX, e.clientY);- if (!vb) return;- (e.currentTarget as Element).setPointerCapture?.(e.pointerId);- dragRef.current = { kind: 'pan', vbStartX: vb.x, vbStartY: vb.y, tx0: view.tx, ty0: view.ty };- setGrabbing(true);- },- [view]- );-- const onPointerMove = useCallback(- (e: ReactPointerEvent) => {- const d = dragRef.current;- if (!d) return;- // On the first real movement (not a plain click), hand the camera to the- // user: freeze the worker layout and suppress the settle-time auto-fit.- if (!movedRef.current) {- stopLayoutRef.current();- userInteractedRef.current = true;- }- if (d.kind === 'node') {- const g = clientToGraph(e.clientX, e.clientY);- if (!g) return;- d.node.x = g.x - d.dx;- d.node.y = g.y - d.dy;- movedRef.current = true;- bumpTick();- } else {- const vb = clientToViewBox(svgRef.current, e.clientX, e.clientY);- if (!vb) return;- movedRef.current = true;- setView(v => ({ ...v, tx: d.tx0 + (vb.x - d.vbStartX), ty: d.ty0 + (vb.y - d.vbStartY) }));- }- },- [clientToGraph]- );-- const endDrag = useCallback(() => {- dragRef.current = null;- setGrabbing(false);- }, []);-- const onWheelZoom = useCallback((e: ReactWheelEvent) => {- const vb = clientToViewBox(svgRef.current, e.clientX, e.clientY);- if (!vb) return;- userInteractedRef.current = true;- setView(v => {- const factor = Math.exp(-e.deltaY * 0.0015);- const scale = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, v.scale * factor));- // Keep the graph point under the cursor fixed while zooming.- const gx = (vb.x - v.tx) / v.scale;- const gy = (vb.y - v.ty) / v.scale;- return { scale, tx: vb.x - gx * scale, ty: vb.y - gy * scale };- });- }, []);-- const resetView = useCallback(() => {- // SVG re-frames the whole graph; the Pixi canvas listens on the reset- // signal. Both are triggered so the button works in either path.- userInteractedRef.current = false;- fitRef.current();- bumpReset();- }, []);-- const openSummary = useCallback(async (node: GraphNode) => {- const path = summaryWorkspacePath(node);- if (!path) return;- console.debug('[memory-graph] open workspace path=%s', path);- try {- await openWorkspacePath(path);- } catch (err) {- console.error('[memory-graph] openWorkspacePath failed', err);- }- }, []);-- const previewSummary = useCallback(async (node: GraphNode) => {- const path = summaryWorkspacePath(node);- if (!path) return;- setPreviewingPath(path);- try {- const next = await previewWorkspaceText(path);- setPreview({ path, contents: next.contents, truncated: next.truncated, error: null });- } catch (err) {- console.error('[memory-graph] previewWorkspaceText failed', err);- setPreview({- path,- contents: '',- truncated: false,- error: err instanceof Error ? err.message : String(err),- });- } finally {- setPreviewingPath(null);- }- }, []);-- // Build edges + seed positions, carrying over the last positions of any- // surviving node so a live data update doesn't reshuffle the whole graph- // (seedSvgLayout). The O(n²) relax only runs as the no-worker fallback (test- // env); the worker settles otherwise; the Pixi path runs its own sim.- const sim = useMemo<SimState | null>(() => {- if (!nodes || nodes.length === 0) return null;- // Snapshot the OUTGOING graph's live coordinates so survivors carry over- // from where they actually are now — not a stale init/settle snapshot —- // even mid-settle or after a drag.- const prev = liveSimRef.current;- const prevPos = new Map<string, { x: number; y: number }>();- if (prev) for (const n of prev.sim) prevPos.set(n.id, { x: n.x, y: n.y });- const seed = seedSvgLayout(nodes, edges, mode, prevPos);- const sim: SimNode[] = nodes.map((n, i) => ({- ...n,- x: seed.positions[i].x,- y: seed.positions[i].y,- vx: 0,- vy: 0,- }));- const radii = sim.map(n => nodeRadius(n));- if (!useWebGL && !WORKER_SUPPORTED) relaxLayout(sim, seed.edges);- return { sim, edges: seed.edges, radii, alpha: seed.reheatAlpha };- }, [nodes, edges, mode, useWebGL]);- // Becomes the "previous" sim on the next build (above).- liveSimRef.current = sim;-- // Element refs for imperative position updates: while the worker streams- // positions we write cx/cy (and line endpoints) straight to the DOM instead- // of re-rendering up to 10k elements through React every frame.- const circleEls = useRef<(SVGCircleElement | null)[]>([]);- const lineEls = useRef<(SVGLineElement | null)[]>([]);- const textEls = useRef<(SVGTextElement | null)[]>([]);-- // Progressive DOM mount for the SVG path: reveal nodes in per-frame batches- // so a large graph never blocks building thousands of elements in one commit.- // WebGL draws to one canvas, so it shows everything at once.- const FIRST_BATCH = 800;- const [svgVisible, setSvgVisible] = useState(() =>- sim ? Math.min(sim.sim.length, FIRST_BATCH) : 0- );- // Reset the reveal window + element refs during render when the graph data- // changes (the recommended alternative to setState-in-effect).- const simIdRef = useRef(sim);- if (simIdRef.current !== sim) {- simIdRef.current = sim;- circleEls.current = [];- lineEls.current = [];- textEls.current = [];- setSvgVisible(sim ? Math.min(sim.sim.length, FIRST_BATCH) : 0);- }-- // Latest visible count read by the stable imperative applier without- // re-subscribing the worker every render.- const latestVisibleRef = useRef(svgVisible);- latestVisibleRef.current = svgVisible;-- // Write current positions straight to the mounted SVG elements.- const applyPositions = useCallback(() => {- const s = liveSimRef.current;- if (!s) return;- const vis = latestVisibleRef.current;- const ns = s.sim;- for (let i = 0; i < vis && i < ns.length; i++) {- const el = circleEls.current[i];- if (el) {- el.setAttribute('cx', String(ns[i].x));- el.setAttribute('cy', String(ns[i].y));- }- const tel = textEls.current[i];- if (tel) {- tel.setAttribute('x', String(ns[i].x));- tel.setAttribute('y', String(ns[i].y + nodeRadius(ns[i]) + 12));- }- }- for (let e = 0; e < s.edges.length; e++) {- const [ai, bi] = s.edges[e];- if (ai >= vis || bi >= vis) continue;- const el = lineEls.current[e];- if (el) {- el.setAttribute('x1', String(ns[ai].x));- el.setAttribute('y1', String(ns[ai].y));- el.setAttribute('x2', String(ns[bi].x));- el.setAttribute('y2', String(ns[bi].y));- }- }- }, []);-- // Frame the whole cloud in the viewport. d3-force spreads a large graph far- // past the viewBox, so without this most nodes sit off-screen. Committed to- // `view` state (single source) so pan/zoom keep working; called once the- // worker settles, unless the user already grabbed the camera.- const fitToView = useCallback(() => {- const s = liveSimRef.current;- if (!s || userInteractedRef.current) return;- const ns = s.sim;- if (ns.length === 0) return;- // Center on the root node at a fixed comfortable zoom.- if (fitToBounds) {- let minX = Infinity;- let minY = Infinity;- let maxX = -Infinity;- let maxY = -Infinity;- for (const n of ns) {- const r = nodeRadius(n) + 8;- minX = Math.min(minX, n.x - r);- minY = Math.min(minY, n.y - r);- maxX = Math.max(maxX, n.x + r);- maxY = Math.max(maxY, n.y + r);- }- const w = Math.max(1, maxX - minX);- const h = Math.max(1, maxY - minY);- const scale = Math.min(- ZOOM_MAX,- Math.max(ZOOM_MIN, Math.min(VIEWPORT_W / w, VIEWPORT_H / h) * 0.92)- );- const bx = (minX + maxX) / 2;- const by = (minY + maxY) / 2;- setView({ scale, tx: VIEWPORT_W / 2 - bx * scale, ty: VIEWPORT_H / 2 - by * scale });- return;- }- const root = ns.find(n => n.kind === 'root');- const cx = root?.x ?? 0;- const cy = root?.y ?? 0;- const scale = fitScale ?? 0.17;- setView({ scale, tx: VIEWPORT_W / 2 - cx * scale, ty: VIEWPORT_H / 2 - cy * scale });- }, [fitScale, fitToBounds]);- fitRef.current = fitToView;-- // Coalesce worker ticks to one DOM write per frame.- const applyPendingRef = useRef(false);- const scheduleApply = useCallback(() => {- if (applyPendingRef.current) return;- applyPendingRef.current = true;- const run = () => {- applyPendingRef.current = false;- applyPositions();- };- if (typeof window.requestAnimationFrame === 'function') window.requestAnimationFrame(run);- else run();- }, [applyPositions]);-- // Frame the graph then signal readiness once the worker layout cools.- const onSvgSettled = useCallback(() => {- fitToView();- fireReady();- }, [fitToView, fireReady]);-- // SVG fallback layout runs in a worker (off the main thread); positions- // stream back and are applied imperatively. No-op on WebGL and where workers- // are unavailable (the synchronous relaxLayout above covers that case).- const svgLayout = useSvgForceLayout(- !useWebGL && !!sim,- sim?.sim ?? NO_NODES,- sim?.radii ?? NO_RADII,- sim?.edges ?? NO_EDGES,- SVG_CENTER,- sim?.alpha ?? 1,- scheduleApply,- onSvgSettled- );- stopLayoutRef.current = svgLayout.stop;-- // Synchronous-layout path (no WebGL, no Worker — e.g. jsdom under test):- // `relaxLayout` already ran inside the `sim` memo, so the graph is laid out- // as soon as `sim` exists. Signal readiness on the next tick.- useEffect(() => {- if (useWebGL || WORKER_SUPPORTED || !sim) return;- fireReady();- }, [useWebGL, sim, fireReady]);-- // Ramp the rest in per-frame batches (setState only inside the rAF callback).- useEffect(() => {- if (useWebGL || !sim) return;- const total = sim.sim.length;- if (total <= FIRST_BATCH || typeof window.requestAnimationFrame !== 'function') return;- let raf = 0;- const step = () => {- setSvgVisible(c => {- const next = Math.min(total, c + 1200);- if (next < total) raf = window.requestAnimationFrame(step);- return next;- });- };- raf = window.requestAnimationFrame(step);- return () => window.cancelAnimationFrame(raf);- }, [useWebGL, sim]);-- if (nodes.length === 0) {- return (- <div- className="flex h-[640px] items-center justify-center rounded-lg border border-line-subtle bg-surface-muted/40 text-sm text-content-muted"- data-testid="memory-graph-empty">- {emptyHint ?? (mode === 'contacts' ? t('graph.noContactMentions') : t('graph.noMemory'))}- </div>- );- }-- if (!sim) return null;-- // Distinct legend rows for the active mode. Tree mode lists the levels- // actually present (each lit in its own colour) plus a leaf row when- // chunks are shown.- const legend =- mode === 'tree'- ? [- ...(nodes.some(n => n.kind === 'source')- ? [{ label: t('graph.source', 'Source'), color: SOURCE_COLOR }]- : []),- ...Array.from(new Set(nodes.filter(n => n.kind === 'summary').map(n => n.level ?? 0)))- .sort((a, b) => a - b)- .map(lvl => ({ label: `L${lvl}`, color: levelColor(lvl) })),- ...(nodes.some(n => n.kind === 'chunk')- ? [{ label: t('graph.document'), color: LEAF_COLOR }]- : []),- ]- : [- { label: t('graph.document'), color: LEAF_COLOR },- { label: t('graph.contact'), color: CONTACT_COLOR },- ];- const hoveredSummaryPath = hovered?.kind === 'summary' ? summaryWorkspacePath(hovered) : null;-- return (- <div- className={`memory-graph rounded-lg border border-line-subtle bg-surface ${- fill ? 'flex h-full flex-col overflow-hidden' : ''- }`}- onMouseLeave={() => setHovered(null)}>- <div className="flex flex-none items-center justify-between gap-4 border-b border-line-subtle px-4 py-2">- <div className="flex items-center gap-3 text-xs text-content-muted">- <span>- {nodes.length} {t('graph.nodes')}- </span>- <span className="text-content-faint">·</span>- <span>- {sim.edges.length}{' '}- {mode === 'tree' ? t('graph.parentChild') : t('graph.documentContact')}{' '}- {sim.edges.length === 1 ? t('graph.link') : t('graph.links')}- </span>- </div>- <div className="flex items-center gap-3">- {legend.map(item => (- <span- key={item.label}- className="flex items-center gap-1.5 text-xs text-content-secondary">- <span- className="inline-block h-2.5 w-2.5 rounded-full"- style={{ backgroundColor: item.color }}- />- {item.label}- </span>- ))}- <Button- variant="secondary"- size="xs"- onClick={resetView}- data-testid="memory-graph-reset-view"- className="text-[11px] shadow-xs">- {t('graph.resetView')}- </Button>- </div>- </div>- {useWebGL ? (- <PixiGraph- nodes={nodes}- edges={edges}- mode={mode}- rootLabel={rootLabel}- fill={fill}- fitScale={fitScale}- fitToBounds={fitToBounds}- showLabels={showLabels}- tuning={tuning}- dark={- typeof document !== 'undefined' && document.documentElement.classList.contains('dark')- }- resetSignal={resetSignal}- onHover={setHovered}- onOpen={n => {- if (n.kind === 'summary') void openSummary(n);- }}- onError={() => setPixiFailed(true)}- onReady={fireReady}- />- ) : (- <svg- ref={svgRef}- viewBox={`0 0 ${VIEWPORT_W} ${VIEWPORT_H}`}- className={`block w-full touch-none select-none ${fill ? 'min-h-0 flex-1' : ''}`}- style={{- height: fill ? '100%' : 'min(640px, calc(100vh - 22rem))',- cursor: grabbing ? 'grabbing' : 'grab',- }}- onPointerDown={onBackgroundPointerDown}- onPointerMove={onPointerMove}- onPointerUp={endDrag}- onPointerLeave={endDrag}- onWheel={onWheelZoom}- data-testid="memory-graph-svg">- {/* Pan / zoom group — drag the background to pan, scroll to zoom. */}- <g transform={`translate(${view.tx} ${view.ty}) scale(${view.scale})`}>- <g- stroke={isDark ? '#cbd5e1' : '#475569'}- strokeWidth={isDark ? 0.6 : 1.2}- opacity={isDark ? 0.7 : 0.7}>- {sim.edges.map(([ai, bi], idx) => {- // Only draw edges whose endpoints are both mounted yet.- if (ai >= svgVisible || bi >= svgVisible) return null;- const a = sim.sim[ai];- const b = sim.sim[bi];- return (- <line- key={idx}- ref={el => {- lineEls.current[idx] = el;- }}- x1={a.x}- y1={a.y}- x2={b.x}- y2={b.y}- />- );- })}- </g>- <g>- {sim.sim.slice(0, svgVisible).map((n, i) => {- const r = nodeRadius(n);- const fill = nodeColor(n);- const isHover = hovered?.id === n.id;- // Leaves stay flat; summary / contact nodes glow in their- // own colour so the tree levels "light up".- const glow =- n.kind === 'chunk' ? undefined : `drop-shadow(0 0 ${isHover ? 7 : 4}px ${fill})`;- return (- <circle- key={n.id}- ref={el => {- circleEls.current[i] = el;- }}- cx={n.x}- cy={n.y}- r={isHover ? r + 2 : r}- fill={fill}- stroke={- isHover ? (isDark ? '#0f172a' : '#1e293b') : isDark ? '#ffffff' : '#e2e8f0'- }- strokeWidth={isHover ? 1.4 : 0.8}- style={{ cursor: grabbing ? 'grabbing' : 'pointer', filter: glow }}- onPointerDown={e => onNodePointerDown(e, n)}- onMouseEnter={() => setHovered(n)}- onClick={() => {- // A drag ends with a click event too — skip the open- // when the pointer actually moved.- if (movedRef.current) return;- if (n.kind === 'summary') void openSummary(n);- }}- data-testid={`memory-graph-node-${n.id}`}>- <title>{tooltipFor(n, t)}</title>- </circle>- );- })}- </g>- {showLabels && (- <g>- {sim.sim.slice(0, svgVisible).map((n, i) => {- const label = (n.label ?? '').trim();- const text = label.length > 22 ? `${label.slice(0, 21)}…` : label;- return (- <text- key={n.id}- ref={el => {- textEls.current[i] = el;- }}- x={n.x}- y={n.y + nodeRadius(n) + 12}- textAnchor="middle"- fontSize={13}- fill={isDark ? '#e2e8f0' : '#334155'}- style={{ pointerEvents: 'none', userSelect: 'none' }}>- {text}- </text>- );- })}- </g>- )}- </g>- </svg>- )}- {hovered && (- <div- className="border-t border-line-subtle bg-surface-muted/70 dark:bg-surface/70 px-4 py-2 text-xs text-content-secondary"- data-testid="memory-graph-tooltip">- {hovered.kind === 'root' ? (- <span className="font-medium text-violet-600 dark:text-violet-400">- {hovered.label}- </span>- ) : hovered.kind === 'source' ? (- <span className="font-medium text-orange-600 dark:text-orange-400">- {hovered.label}- </span>- ) : hovered.kind === 'summary' ? (- <>- <span className="font-mono">L{hovered.level ?? '?'}</span>- <span className="text-content-faint"> · </span>- <span className="capitalize">{hovered.tree_kind}</span>- <span className="text-content-faint"> · </span>- <span>{hovered.tree_scope}</span>- <span className="text-content-faint"> · </span>- <span>- {hovered.child_count ?? 0} {t('graph.children')}- </span>- {hoveredSummaryPath && (- <>- <span className="ml-3 break-all font-mono text-content-faint">- {t('graph.workspacePath').replace('{path}', hoveredSummaryPath)}- </span>- <Button- variant="secondary"- size="xs"- data-testid={`memory-graph-preview-${hovered.id}`}- disabled={previewingPath === hoveredSummaryPath}- onClick={() => void previewSummary(hovered)}- className="ml-3 text-[11px] shadow-xs">- {previewingPath === hoveredSummaryPath- ? t('migration.previewRunning')- : t('migration.previewAction')}- </Button>- </>- )}- </>- ) : hovered.kind === 'contact' ? (- <>- <span className="font-medium text-violet-700 dark:text-violet-300">- {hovered.label}- </span>- <span className="ml-3 text-content-faint">- {t('graph.person')} · canonical id {hovered.id.slice(0, 12)}…- </span>- </>- ) : (- <>- <span className="font-medium">{hovered.label || 'chunk'}</span>- <span className="ml-3 text-content-faint">{t('graph.document')}</span>- </>- )}- </div>- )}- {preview && (- <div- className="border-t border-line-subtle bg-surface px-4 py-3 dark:bg-surface-canvas"- data-testid="memory-graph-preview">- <div className="mb-2 break-all font-mono text-[11px] text-content-faint">- {t('graph.workspacePath').replace('{path}', preview.path)}- </div>- <pre className="max-h-40 overflow-auto whitespace-pre-wrap rounded-md bg-surface-muted p-3 text-xs text-content-secondary">- {preview.error || preview.contents}- {preview.truncated ? '\n…' : ''}- </pre>- </div>- )}- </div>- );-}--function tooltipFor(n: GraphNode, t: (key: string, fallback?: string) => string): string {- if (n.kind === 'root') return n.label;- if (n.kind === 'summary') return t('graph.tooltip.summary');- if (n.kind === 'contact') return t('graph.tooltip.contact');- return n.label || t('graph.document');-}diff --git a/app/src/components/intelligence/MemoryGraph.worker.test.tsx b/app/src/components/intelligence/MemoryGraph.worker.test.tsxdeleted file mode 100644index e4f422bae4..0000000000--- a/app/src/components/intelligence/MemoryGraph.worker.test.tsx+++ /dev/null@@ -1,192 +0,0 @@-/**- * Exercises the worker-backed SVG path of MemoryGraph, which can't run under- * the default test env (no real Worker). A mocked Worker lets us drive the- * streamed-position apply, settle-time fit, drag-freeze, and progressive mount.- *- * `WORKER_SUPPORTED` is captured at module load, so Worker must be stubbed- * before MemoryGraph is imported — hence the dynamic import in beforeAll.- */-import { configureStore } from '@reduxjs/toolkit';-import { act, fireEvent, render } from '@testing-library/react';-import type { PropsWithChildren } from 'react';-import { Provider } from 'react-redux';-import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';--import themeReducer from '../../store/themeSlice';-import type { GraphNode } from '../../utils/tauriCommands';--function ReduxWrapper({ children }: PropsWithChildren) {- const store = configureStore({ reducer: { theme: themeReducer } });- return <Provider store={store}>{children}</Provider>;-}--vi.mock('../../utils/openUrl', () => ({ openUrl: vi.fn() }));-vi.mock('../../utils/tauriCommands/workspacePaths', () => ({- openWorkspacePath: vi.fn(),- previewWorkspaceText: vi.fn(),-}));--class MockWorker {- static instances: MockWorker[] = [];- onmessage: ((e: { data: unknown }) => void) | null = null;- posted: Array<Record<string, unknown>> = [];- terminated = false;- constructor() {- MockWorker.instances.push(this);- }- postMessage(m: Record<string, unknown>) {- this.posted.push(m);- }- terminate() {- this.terminated = true;- }- emit(data: unknown) {- this.onmessage?.({ data });- }-}--const last = () => MockWorker.instances[MockWorker.instances.length - 1];--let MemoryGraph: typeof import('./MemoryGraph').MemoryGraph;--beforeAll(async () => {- vi.stubGlobal('Worker', MockWorker as unknown as typeof Worker);- // Run rAF synchronously so imperative position writes + the mount ramp are- // deterministic within a test tick.- vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {- cb(0);- return 1;- });- vi.stubGlobal('cancelAnimationFrame', () => {});- ({ MemoryGraph } = await import('./MemoryGraph'));-});--function treeNodes(leaves: number): GraphNode[] {- const nodes: GraphNode[] = [{ kind: 'source', id: 's', label: 's', parent_id: null }];- for (let i = 0; i < leaves; i++) {- nodes.push({ kind: 'chunk', id: `c${i}`, label: `c${i}`, parent_id: 's' });- }- return nodes;-}--/** Give the SVG a usable CTM so pan/drag math doesn't no-op under jsdom. */-function withCTM(svg: Element) {- (svg as unknown as { getScreenCTM: () => unknown }).getScreenCTM = () => ({- inverse: () => ({ a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 }),- });-}--describe('<MemoryGraph /> worker-backed SVG path', () => {- beforeEach(() => {- MockWorker.instances = [];- });-- it('spins up a worker and applies streamed positions imperatively', () => {- const { container } = render(<MemoryGraph nodes={treeNodes(3)} edges={[]} mode="tree" />, {- wrapper: ReduxWrapper,- });- const w = last();- expect(w).toBeTruthy();- expect(w.posted[0].type).toBe('init');- expect(w.posted[0].alpha).toBe(1); // fresh graph → full reheat-- act(() =>- w.emit({- type: 'tick',- positions: new Float32Array([11, 22, 33, 44, 55, 66, 77, 88]),- alpha: 0.5,- })- );- const circles = container.querySelectorAll('circle');- expect(circles.length).toBeGreaterThan(0);- expect(circles[0].getAttribute('cx')).toBe('11');- expect(circles[0].getAttribute('cy')).toBe('22');- });-- it('frames the graph on settle (end → fit transform)', () => {- const { container } = render(<MemoryGraph nodes={treeNodes(3)} edges={[]} mode="tree" />, {- wrapper: ReduxWrapper,- });- const w = last();- act(() =>- w.emit({- type: 'tick',- positions: new Float32Array([0, 0, 200, 0, 0, 200, 200, 200]),- alpha: 0.1,- })- );- act(() => w.emit({ type: 'end' }));- const g = container.querySelector('[data-testid="memory-graph-svg"] g');- expect(g?.getAttribute('transform')).toMatch(/translate\(.*\) scale\(/);- });-- it('freezes the worker on a drag, but NOT on a plain click', () => {- const { container } = render(<MemoryGraph nodes={treeNodes(3)} edges={[]} mode="tree" />, {- wrapper: ReduxWrapper,- });- const svg = container.querySelector('[data-testid="memory-graph-svg"]') as Element;- withCTM(svg);- const w = last();-- // Plain click (down + up, no move) must not stop layout.- fireEvent.pointerDown(svg, { clientX: 10, clientY: 10 });- fireEvent.pointerUp(svg, { clientX: 10, clientY: 10 });- expect(w.terminated).toBe(false);-- // Drag (down + move) hands the camera over → stop().- fireEvent.pointerDown(svg, { clientX: 10, clientY: 10 });- fireEvent.pointerMove(svg, { clientX: 80, clientY: 80 });- expect(w.terminated).toBe(true);- });-- it('reheats gently and carries positions over on an incremental update', () => {- const { rerender } = render(<MemoryGraph nodes={treeNodes(3)} edges={[]} mode="tree" />, {- wrapper: ReduxWrapper,- });- const first = last();- act(() =>- first.emit({- type: 'tick',- positions: new Float32Array([1, 1, 2, 2, 3, 3, 4, 4]),- alpha: 0.5,- })- );- // Add a node → same instance, new props → new worker session.- rerender(<MemoryGraph nodes={treeNodes(4)} edges={[]} mode="tree" />);- const second = last();- expect(second).not.toBe(first);- expect(second.posted[0].type).toBe('init');- expect(second.posted[0].alpha).toBe(0.3); // survivors present → gentle reheat- });-- it('mounts a large graph progressively without throwing', () => {- expect(() =>- render(<MemoryGraph nodes={treeNodes(900)} edges={[]} mode="tree" />, {- wrapper: ReduxWrapper,- })- ).not.toThrow();- });-- it('handles node drag, wheel zoom, and reset view', () => {- const { container, getByTestId } = render(- <MemoryGraph nodes={treeNodes(3)} edges={[]} mode="tree" />,- { wrapper: ReduxWrapper }- );- const svg = container.querySelector('[data-testid="memory-graph-svg"]') as Element;- withCTM(svg);- const w = last();-- // Drag a node → freezes layout and repositions the node.- const node = container.querySelector('[data-testid="memory-graph-node-c0"]') as Element;- fireEvent.pointerDown(node, { clientX: 20, clientY: 20 });- fireEvent.pointerMove(svg, { clientX: 90, clientY: 90 });- fireEvent.pointerUp(svg, { clientX: 90, clientY: 90 });- expect(w.terminated).toBe(true);-- // Wheel zoom is a real interaction (no throw).- expect(() => fireEvent.wheel(svg, { deltaY: -120, clientX: 50, clientY: 50 })).not.toThrow();-- // Reset view re-frames.- expect(() => fireEvent.click(getByTestId('memory-graph-reset-view'))).not.toThrow();- });-});diff --git a/app/src/components/intelligence/MemorySourceRow.pipelineWarning.test.tsx b/app/src/components/intelligence/MemorySourceRow.pipelineWarning.test.tsxdeleted file mode 100644index e5c06d8410..0000000000--- a/app/src/components/intelligence/MemorySourceRow.pipelineWarning.test.tsx+++ /dev/null@@ -1,288 +0,0 @@-/**- * The "stored without vectors" warning must actually reach the screen.- *- * Motivating incident: a workspace sat with 2,581 chunks synced and 0 embedded,- * and no degraded indicator appeared anywhere in the UI. The user's semantic- * search was silently returning nothing findable, while every surface reported- * a healthy sync.- *- * The *verdict* behind that warning — `deriveSourcePipelineHealth` — is already- * exhaustively covered by `sourcePipelineStatus.test.ts` (14 cases, every- * branch). What was NOT covered is whether the verdict is ever rendered:- * `MemorySourceRow.test.tsx` only exercises the settings disclosure. Deleting- * the whole `{ingestedOnly && …}` block from `MemorySourceRow.tsx` leaves every- * other test in the repo green — a correct verdict computed into a void, which- * is exactly the shape of the reported incident.- *- * These tests therefore assert the *rendered* contract, not the derivation:- * the warning appears when chunks are stored without vectors, it carries the- * message the user needs, and — the easy thing to get wrong — it is suppressed- * only while a sync is genuinely in flight.- */-import { render, screen } from '@testing-library/react';-import { describe, expect, it, vi } from 'vitest';--import type { MemorySourceEntry, SourceStatus } from '../../services/memorySourcesService';-import { MemorySourceRow } from './MemorySourceRow';--// Keys come back verbatim, except the one with a placeholder: it comes back as-// its English shape so the count interpolation is asserted, not just the key.-vi.mock('../../lib/i18n/I18nContext', () => ({- useT: () => ({- t: (k: string) =>- k === 'sync.pipeline.vectorsPending' ? 'Chunks waiting for vectors: {count}' : k,- }),-}));--const SOURCE_ID = 'src_brain_1';--function makeSource(overrides: Partial<MemorySourceEntry> = {}): MemorySourceEntry {- return {- id: SOURCE_ID,- kind: 'github_repo',- label: 'My Repo',- enabled: true,- url: 'https://github.com/org/repo',- ...overrides,- };-}--/**- * The incident's shape: everything ingested, nothing embedded, and nothing- * moving — the newest chunk is long past the core's five-minute `recent`- * window and no backfill snapshot says a chain is draining it. (A backlog- * that IS moving is the neutral "waiting for vectors" note, pinned at the- * bottom of this file — openhuman#6025.)- */-function storedWithoutVectors(overrides: Partial<SourceStatus> = {}): SourceStatus {- return {- source_id: SOURCE_ID,- chunks_synced: 2581,- chunks_pending: 2581,- last_chunk_at_ms: Date.now() - 60 * 60_000,- freshness: 'idle',- ...overrides,- } as SourceStatus;-}--function renderRow(overrides: Partial<React.ComponentProps<typeof MemorySourceRow>> = {}) {- const props: React.ComponentProps<typeof MemorySourceRow> = {- source: makeSource(),- status: null,- pipeline: null,- backfill: null,- isAuthenticated: true,- isSyncing: false,- isBuilding: false,- progress: null,- result: null,- settingsExpanded: false,- onToggle: vi.fn(),- onRemove: vi.fn(),- onSync: vi.fn(),- onBuild: vi.fn(),- onToggleSettings: vi.fn(),- onSettingsSaved: vi.fn(),- onViewHealth: vi.fn(),- onSignIn: vi.fn(),- ...overrides,- };- render(- <ul>- <MemorySourceRow {...props} />- </ul>- );-}--const warning = () => screen.queryByTestId(`memory-source-pipeline-warning-${SOURCE_ID}`);--describe('MemorySourceRow — the row tells the truth about embedding state', () => {- it('shows the pipeline warning when every synced chunk is unembedded', () => {- renderRow({ status: storedWithoutVectors() });-- const banner = warning();- expect(banner).toBeInTheDocument();- expect(banner).toHaveTextContent('sync.pipeline.storedWithoutVectors');- });-- it('shows the warning for a single unembedded chunk, not just a large backlog', () => {- // There is no threshold in the contract: one chunk that semantic search- // cannot reach is still a source that is not retrieval-ready.- renderRow({ status: storedWithoutVectors({ chunks_synced: 10, chunks_pending: 1 }) });-- expect(warning()).toBeInTheDocument();- });-- it('stays silent when every chunk is embedded', () => {- renderRow({ status: storedWithoutVectors({ chunks_pending: 0 }) });-- expect(warning()).not.toBeInTheDocument();- });-- it('stays silent before anything has been ingested', () => {- // A brand-new source has no chunks and therefore nothing to warn about;- // warning here would train users to ignore the banner.- renderRow({ status: storedWithoutVectors({ chunks_synced: 0, chunks_pending: 0 }) });-- expect(warning()).not.toBeInTheDocument();- });-- it('surfaces the warning from the global semantic-recall latch with no pending chunks', () => {- // The per-source count can be 0 while the process-wide embeddings provider- // is down; the row still is not retrieval-ready.- renderRow({- status: storedWithoutVectors({ chunks_pending: 0 }),- pipeline: {- status: 'degraded',- degraded: { semantic_recall: true },- } as unknown as React.ComponentProps<typeof MemorySourceRow>['pipeline'],- });-- expect(warning()).toBeInTheDocument();- expect(warning()).toHaveTextContent('sync.pipeline.storedWithoutVectors');- });-});--describe('MemorySourceRow — what suppresses the warning', () => {- // `settled = !progress` in MemorySourceRow.tsx (openhuman#6025 dropped the- // `!result` half). Suppressing while progress streams is correct (mid-sync- // `chunks_pending` is legitimately transient) and is also the most plausible- // way for the indicator to never appear: a source wedged in a progress state- // would warn about nothing forever. Both directions are pinned.- it('hides the warning while a sync is actively reporting progress', () => {- renderRow({- status: storedWithoutVectors(),- progress: { processed: 10, total: 2581 } as unknown as React.ComponentProps<- typeof MemorySourceRow- >['progress'],- });-- expect(warning()).not.toBeInTheDocument();- });-- // A terminal result chip no longer suppresses the verdict (openhuman#6025):- // the chip sits on the row until the NEXT sync starts, so `!result` hid a- // real hole in recall indefinitely — exactly the incident this file exists- // for. The verdict now tells a draining backlog from a stuck one itself,- // so the chip is not needed as a proxy. This case was written, and skipped,- // as the spec for that fix; it went green the moment the fix landed.- it('still warns after a sync finishes while chunks remain unembedded', () => {- renderRow({- status: storedWithoutVectors(),- progress: null,- result: { kind: 'success', items: 2581, note: null } as unknown as React.ComponentProps<- typeof MemorySourceRow- >['result'],- });-- expect(warning()).toBeInTheDocument();- });-- it('reports the truth again once the sync has settled', () => {- renderRow({ status: storedWithoutVectors(), progress: null, result: null });-- expect(warning()).toBeInTheDocument();- });-- it('offers sign-in only when the failure is a missing backend session', () => {- renderRow({- isAuthenticated: false,- status: storedWithoutVectors(),- pipeline: {- status: 'degraded',- first_blocking_cause: { code: 'auth_missing' },- } as unknown as React.ComponentProps<typeof MemorySourceRow>['pipeline'],- });-- expect(screen.getByTestId(`memory-source-signin-${SOURCE_ID}`)).toBeInTheDocument();- });-- it('does not offer sign-in for a non-auth embeddings failure', () => {- renderRow({- isAuthenticated: false,- status: storedWithoutVectors(),- pipeline: {- status: 'degraded',- first_blocking_cause: { code: 'provider_unreachable' },- } as unknown as React.ComponentProps<typeof MemorySourceRow>['pipeline'],- });-- expect(warning()).toBeInTheDocument();- expect(screen.queryByTestId(`memory-source-signin-${SOURCE_ID}`)).not.toBeInTheDocument();- });-});--describe('MemorySourceRow — a backlog that is still draining is pending, not failed (openhuman#6025)', () => {- const pendingNote = () => screen.queryByTestId(`memory-source-vectors-pending-${SOURCE_ID}`);-- it('shows the neutral waiting note, not the warning, while a re-embed chain has rows to process', () => {- // The report: 676 chunks, 322 pending, ten minutes after a Gmail sync, and- // the row went amber for a backlog the engine was already draining.- renderRow({- status: storedWithoutVectors({ chunks_synced: 676, chunks_pending: 322 }),- backfill: { in_progress: true, pending_jobs: 1 },- });-- expect(warning()).not.toBeInTheDocument();- const note = pendingNote();- expect(note).toBeInTheDocument();- expect(note).toHaveTextContent('Chunks waiting for vectors: 322');- // The freshness pill stays; the amber "Ingested only" pill does not appear.- expect(screen.getByText('sync.idle')).toBeInTheDocument();- expect(- screen.queryByTestId(`memory-source-ingested-only-${SOURCE_ID}`)- ).not.toBeInTheDocument();- });-- it('shows the waiting note while the newest chunk is recent, even with no backfill snapshot', () => {- renderRow({- status: storedWithoutVectors({- chunks_pending: 4,- freshness: 'recent',- last_chunk_at_ms: Date.now(),- }),- backfill: null,- });-- expect(warning()).not.toBeInTheDocument();- expect(pendingNote()).toBeInTheDocument();- });-- it('keeps the waiting note beside a fresh result chip', () => {- // The minutes right after `completed` are exactly when the backlog is- // visible; the chip must hide neither the note nor (above) the warning.- renderRow({- status: storedWithoutVectors({ chunks_pending: 322, freshness: 'active' }),- backfill: { in_progress: true, pending_jobs: 1 },- result: { kind: 'success', items: 500, note: null } as unknown as React.ComponentProps<- typeof MemorySourceRow- >['result'],- });-- expect(screen.getByTestId(`memory-source-result-${SOURCE_ID}`)).toBeInTheDocument();- expect(pendingNote()).toBeInTheDocument();- expect(warning()).not.toBeInTheDocument();- });-- it('turns amber once the backlog is idle with no chain queued', () => {- renderRow({- status: storedWithoutVectors({ chunks_pending: 322 }),- backfill: { in_progress: false, pending_jobs: 0 },- });-- expect(pendingNote()).not.toBeInTheDocument();- expect(warning()).toBeInTheDocument();- });-- it('hides the note while a sync is actively reporting progress', () => {- renderRow({- status: storedWithoutVectors({ chunks_pending: 322, freshness: 'active' }),- backfill: { in_progress: true, pending_jobs: 1 },- progress: { processed: 10, total: 2581 } as unknown as React.ComponentProps<- typeof MemorySourceRow- >['progress'],- });-- expect(pendingNote()).not.toBeInTheDocument();- });-});diff --git a/app/src/components/intelligence/MemorySourceRow.test.tsx b/app/src/components/intelligence/MemorySourceRow.test.tsxdeleted file mode 100644index 8f450299fd..0000000000--- a/app/src/components/intelligence/MemorySourceRow.test.tsx+++ /dev/null@@ -1,121 +0,0 @@-/**- * Small render test for the settings-panel disclosure in `MemorySourceRow`- * (#radix-ui-foundation). The gear button is a `CollapsibleTrigger` wrapping- * a `Button` via `asChild`, and the panel is a `CollapsibleContent` — Radix- * unmounts it from the DOM while collapsed, which is a genuine behavior- * change from the old `{settingsExpanded && <SourceSettingsPanel />}` (which- * only ever rendered it conditionally too, so the unmount contract is- * unchanged in practice; this test pins that both states still work).- *- * Full interaction coverage (per-kind fields, Save, etc.) lives in- * `__tests__/MemorySourcesRegistry.test.tsx`, which renders this row through- * its real parent.- */-import { fireEvent, render, screen } from '@testing-library/react';-import { describe, expect, it, vi } from 'vitest';--import type { MemorySourceEntry } from '../../services/memorySourcesService';-import { MemorySourceRow } from './MemorySourceRow';--vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));--function makeSource(overrides: Partial<MemorySourceEntry> = {}): MemorySourceEntry {- return {- id: 'src_1',- kind: 'github_repo',- label: 'My Repo',- enabled: true,- url: 'https://github.com/org/repo',- ...overrides,- };-}--function renderRow(overrides: Partial<React.ComponentProps<typeof MemorySourceRow>> = {}) {- const onToggleSettings = vi.fn();- const props: React.ComponentProps<typeof MemorySourceRow> = {- source: makeSource(),- status: null,- pipeline: null,- backfill: null,- isAuthenticated: true,- isSyncing: false,- isBuilding: false,- progress: null,- result: null,- settingsExpanded: false,- onToggle: vi.fn(),- onRemove: vi.fn(),- onSync: vi.fn(),- onBuild: vi.fn(),- onToggleSettings,- onSettingsSaved: vi.fn(),- onViewHealth: vi.fn(),- onSignIn: vi.fn(),- ...overrides,- };- render(- <ul>- <MemorySourceRow {...props} />- </ul>- );- return { onToggleSettings };-}--describe('MemorySourceRow — settings disclosure', () => {- it('keeps the settings panel unmounted while collapsed', () => {- renderRow({ settingsExpanded: false });- expect(screen.queryByTestId('source-settings-panel-src_1')).not.toBeInTheDocument();- expect(screen.getByTestId('memory-source-settings-src_1')).toHaveAttribute(- 'aria-expanded',- 'false'- );- });-- it('renders the settings panel when the parent marks it expanded', () => {- renderRow({ settingsExpanded: true });- expect(screen.getByTestId('source-settings-panel-src_1')).toBeInTheDocument();- expect(screen.getByTestId('memory-source-settings-src_1')).toHaveAttribute(- 'aria-expanded',- 'true'- );- });-- it('delegates the toggle to onToggleSettings rather than owning its own open state', () => {- const { onToggleSettings } = renderRow({ settingsExpanded: false });- fireEvent.click(screen.getByTestId('memory-source-settings-src_1'));- expect(onToggleSettings).toHaveBeenCalledWith('src_1');- });-});--describe('MemorySourceRow — live sync stage (openhuman#6257)', () => {- it('names a per-item stage in plain language and hides its internal detail', () => {- renderRow({- isSyncing: true,- progress: {- stage: 'queued',- detail: 'queued chunk extraction for mem_src:src_1:a.md',- percent: 25,- },- });- const bar = screen.getByTestId('memory-source-progress-src_1');- expect(bar).toHaveTextContent('memorySources.stage.queued');- expect(bar).not.toHaveTextContent('mem_src:');- });-- it('keeps a progress detail a person can read', () => {- renderRow({- isSyncing: true,- progress: { stage: 'running', detail: 'pass 2 done, 400 item(s) so far', percent: null },- });- const bar = screen.getByTestId('memory-source-progress-src_1');- expect(bar).toHaveTextContent('memorySources.stage.running');- expect(bar).toHaveTextContent('pass 2 done, 400 item(s) so far');- });-- it('falls back to a generic label for a stage it does not know', () => {- renderRow({ isSyncing: true, progress: { stage: 'mystery', detail: null, percent: null } });- expect(screen.getByTestId('memory-source-progress-src_1')).toHaveTextContent(- 'memorySources.stage.unknown'- );- });-});diff --git a/app/src/components/intelligence/MemorySourceRow.tsx b/app/src/components/intelligence/MemorySourceRow.tsxdeleted file mode 100644index 5abd4f8f59..0000000000--- a/app/src/components/intelligence/MemorySourceRow.tsx+++ /dev/null@@ -1,392 +0,0 @@-/**- * A single row in `MemorySourcesRegistry`'s source list: label + kind badge +- * freshness pill, live sync progress / terminal result, the GH-4690 pipeline- * warning banner, and the settings/sync/build/enable/remove controls.- *- * Split out of `MemorySourcesRegistry.tsx` to keep that file under the size- * budget.- */-import { useT } from '../../lib/i18n/I18nContext';-import {- type FreshnessLabel,- type MemorySourceEntry,- SOURCE_KIND_ICONS,- SOURCE_KIND_LABEL_KEYS,- type SourceStatus,-} from '../../services/memorySourcesService';-import type { ToastNotification } from '../../types/intelligence';-import type {- BackfillStatus,- MemoryTreePipelineStatus,-} from '../../utils/tauriCommands/memoryTree';-import Badge, { type BadgeVariant } from '../ui/Badge';-import Button from '../ui/Button';-import { CollapsibleContent, CollapsibleRoot, CollapsibleTrigger } from '../ui/Collapsible';-import Switch from '../ui/Switch';-import {- BuildIcon,- CheckIcon,- GearIcon,- Spinner,- SyncIcon,- TrashIcon,- WarnIcon,-} from './memorySourcesIcons';-import { relativeTimestamp, sourceDetail } from './memorySourcesRowHelpers';-import {- showsStageDetail,- STAGE_FALLBACK_PERCENT,- stageLabelKey,- type SyncProgress,- type SyncResult,-} from './memorySourcesSyncTypes';-import {- deriveSourcePipelineHealth,- pipelineIssueMessageKey,- type SourcePipelineHealth,- VECTORS_PENDING_MESSAGE_KEY,-} from './sourcePipelineStatus';-import { SourceSettingsPanel } from './SourceSettingsPanel';--interface SourceRowProps {- source: MemorySourceEntry;- status: SourceStatus | null;- /** Global downstream pipeline health (GH-4690); `null` before first poll. */- pipeline: MemoryTreePipelineStatus | null;- /**- * Global embed-backfill snapshot (openhuman#6025); `null` before the first- * poll or when that RPC failed. Tells a backlog that is being drained from- * one nothing is working on.- */- backfill: BackfillStatus | null;- /** Whether a backend session exists — gates the "Sign in to enable" prompt. */- isAuthenticated: boolean;- isSyncing: boolean;- isBuilding: boolean;- progress: SyncProgress | null;- result: SyncResult | null;- settingsExpanded: boolean;- onToggle: (source: MemorySourceEntry) => void;- onRemove: (source: MemorySourceEntry) => void;- onSync: (source: MemorySourceEntry) => void;- onBuild: (source: MemorySourceEntry) => void;- onToggleSettings: (sourceId: string) => void;- onSettingsSaved: (updated: MemorySourceEntry) => void;- onToast?: (toast: Omit<ToastNotification, 'id'>) => void;- /** Navigate to Brain > Memory > Sync (the full memory-health panel). */- onViewHealth: () => void;- /** Navigate to sign-in (embeddings need a backend session). */- onSignIn: () => void;-}--/**- * The line shown beside a successful count when the run stopped short. With a- * zero count the chip itself says why the run stopped (there is no count to- * show instead), so the note is never repeated beside it.- */-function syncNoteKey(result: SyncResult): string | null {- if (!(result.items && result.items > 0)) return null;- if (result.note === 'more_pending') return 'memorySources.sync.morePending';- if (result.note === 'budget_spent') return 'memorySources.sync.budgetSpent';- return null;-}--export function MemorySourceRow({- source,- status,- pipeline,- backfill,- isAuthenticated,- isSyncing,- isBuilding,- progress,- result,- settingsExpanded,- onToggle,- onRemove,- onSync,- onBuild,- onToggleSettings,- onSettingsSaved,- onToast,- onViewHealth,- onSignIn,-}: SourceRowProps) {- const { t } = useT();- const icon = SOURCE_KIND_ICONS[source.kind] ?? '📄';- const kindLabel = t(SOURCE_KIND_LABEL_KEYS[source.kind] ?? source.kind);- const detail = sourceDetail(source);- const lastSync = status ? relativeTimestamp(status.last_chunk_at_ms, t) : null;-- // GH-4690: layered pipeline verdict. Only meaningful once no sync is- // reporting live progress — mid-run the row renders the progress bar- // instead. A terminal result chip does NOT suppress it (openhuman#6025):- // the chip sits on the row until the next sync starts, and the minutes- // right after `completed` are exactly when the embed backlog is visible.- // The verdict itself tells a draining backlog (neutral note) from a stuck- // one (amber warning), so it no longer needs the chip as a proxy.- const settled = !progress;- const noteKey = result ? syncNoteKey(result) : null;- const health: SourcePipelineHealth = settled- ? deriveSourcePipelineHealth(status, pipeline, backfill)- : { state: 'none', issues: [], authRelated: false, vectorsPending: false };- const ingestedOnly = health.state === 'ingested_only';- if (ingestedOnly) {- console.debug(- `[ui-flow][memory-sources] source=${source.id} ingested-only issues=${health.issues.join(',')}`- );- }- if (health.vectorsPending) {- console.debug(- `[ui-flow][memory-sources] source=${source.id} vectors-pending chunks=${status?.chunks_pending ?? 0}`- );- }-- return (- <li className="py-3" data-testid={`memory-source-row-${source.kind}`}>- {/* Per-row settings panel is a single disclosure region controlled by- the registry (`settingsExpanded` + `onToggleSettings`) — Collapsible,- not Accordion: there is no sibling exclusivity to coordinate here. */}- <CollapsibleRoot- open={settingsExpanded}- onOpenChange={() => onToggleSettings(source.id)}- className="flex flex-col gap-2">- <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">- <div className="min-w-0 flex-1">- <div className="flex flex-wrap items-center gap-2">- <span className="text-base">{icon}</span>- <span- className={`truncate text-sm font-medium ${- source.enabled ? 'text-content' : 'text-content-faint line-through'- }`}>- {source.label}- </span>- <Badge variant="neutral">{kindLabel}</Badge>- {status &&- status.chunks_synced > 0 &&- (ingestedOnly ? (- <IngestedOnlyPill sourceId={source.id} />- ) : (- <FreshnessPill freshness={status.freshness} />- ))}- </div>- {detail && <p className="mt-0.5 truncate pl-7 text-xs text-content-faint">{detail}</p>}- {progress && (- <div className="mt-2 pl-7" data-testid={`memory-source-progress-${source.id}`}>- <div className="flex items-center gap-2 text-xs text-content-muted">- {/* openhuman#6257: a readable label, not the raw pipeline stage- ("Queued" beside "queued chunk extraction for mem_src:…"). */}- <span>{t(stageLabelKey(progress.stage))}</span>- {progress.percent !== null && (- <span className="font-medium text-primary-600 dark:text-primary-400">- {progress.percent}%- </span>- )}- {progress.detail && showsStageDetail(progress.stage) && (- <span className="truncate text-content-faint">{progress.detail}</span>- )}- </div>- <div className="mt-1 h-1.5 w-full overflow-hidden rounded-full bg-surface-strong">- <div- className="h-full rounded-full bg-primary-500 transition-all duration-300"- style={{- width: `${progress.percent ?? STAGE_FALLBACK_PERCENT[progress.stage] ?? 2}%`,- }}- />- </div>- </div>- )}- {!progress && result && (- <div className="mt-2 pl-7" data-testid={`memory-source-result-${source.id}`}>- {result.kind === 'success' ? (- <>- <Badge variant="success" dot={false}>- <CheckIcon />- {result.items && result.items > 0- ? `${result.items.toLocaleString()} ${t('memorySources.sync.itemsSynced')}`- : result.note === 'budget_spent'- ? t('memorySources.sync.budgetSpent')- : result.note === 'more_pending'- ? t('memorySources.sync.morePending')- : t('memorySources.sync.upToDate')}- </Badge>- {noteKey && (- <span- className="ml-2 text-xs text-content-muted"- data-testid={`memory-source-note-${source.id}`}>- {t(noteKey)}- </span>- )}- </>- ) : (- <Badge variant="danger" dot={false} title={result.reason ?? undefined}>- <WarnIcon />- <span className="wrap-break-word">- {t('memorySources.sync.failedLabel')}- {result.reason ? `: ${result.reason}` : ''}- </span>- </Badge>- )}- </div>- )}- {!progress &&- !result &&- status &&- (status.chunks_synced > 0 || status.chunks_pending > 0) && (- <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-0.5 pl-7 text-xs text-content-muted">- <span>- {status.chunks_synced.toLocaleString()} {t('sync.chunks')}- </span>- {lastSync && (- <span>- {t('sync.lastChunk')} {lastSync}- </span>- )}- {status.chunks_pending > 0 && (- <span>- {status.chunks_pending.toLocaleString()} {t('sync.pending')}- </span>- )}- </div>- )}- {health.vectorsPending && status && (- <p- className="mt-1 pl-7 text-xs text-content-muted"- data-testid={`memory-source-vectors-pending-${source.id}`}- role="status">- {t(VECTORS_PENDING_MESSAGE_KEY).replace(- '{count}',- status.chunks_pending.toLocaleString()- )}- </p>- )}- {ingestedOnly && (- <div- className="mt-2 flex flex-col gap-1 rounded-md border border-amber-200 bg-amber-50 px-2.5 py-1.5 pl-7 text-xs text-amber-800 dark:border-amber-500/30 dark:bg-amber-500/10 dark:text-amber-200"- data-testid={`memory-source-pipeline-warning-${source.id}`}- role="status">- {health.issues.map(issue => (- <div key={issue} className="flex items-start gap-1.5">- <WarnIcon />- <span className="wrap-break-word">{t(pipelineIssueMessageKey(issue))}</span>- </div>- ))}- <div className="mt-0.5 flex flex-wrap items-center gap-x-3 gap-y-1 pl-[18px]">- {health.authRelated && !isAuthenticated && (- <Button- variant="tertiary"- size="xs"- onClick={onSignIn}- data-testid={`memory-source-signin-${source.id}`}- className="h-auto px-0 font-medium text-amber-900 underline underline-offset-2 hover:bg-transparent hover:text-amber-950 dark:text-amber-100 dark:hover:text-content-inverted">- {t('sync.pipeline.signInToEnable')}- </Button>- )}- <Button- variant="tertiary"- size="xs"- onClick={onViewHealth}- data-testid={`memory-source-view-health-${source.id}`}- className="h-auto px-0 font-medium text-amber-900 underline underline-offset-2 hover:bg-transparent hover:text-amber-950 dark:text-amber-100 dark:hover:text-content-inverted">- {t('sync.pipeline.viewHealth')}- </Button>- </div>- </div>- )}- </div>- <div className="flex shrink-0 items-center gap-2">- <CollapsibleTrigger asChild>- <Button- iconOnly- variant="tertiary"- size="xs"- title={t('memorySources.settings.button')}- aria-label={t('memorySources.settings.button')}- data-testid={`memory-source-settings-${source.id}`}- className={- settingsExpanded- ? 'bg-primary-100 text-primary-600 dark:bg-primary-500/20 dark:text-primary-400'- : 'text-content-faint hover:text-content-secondary'- }>- <GearIcon />- </Button>- </CollapsibleTrigger>- <Button- variant="primary"- size="sm"- onClick={() => onSync(source)}- disabled={!source.enabled || isSyncing}- title={t('sync.sync')}- data-testid={`memory-source-sync-${source.toolkit ?? source.kind}`}- leadingIcon={isSyncing ? <Spinner /> : <SyncIcon />}>- {isSyncing ? t('sync.syncing') : t('sync.sync')}- </Button>- <Button- variant="secondary"- size="sm"- onClick={() => onBuild(source)}- disabled={!source.enabled || isBuilding || isSyncing}- title={t('memorySources.build.title')}- leadingIcon={isBuilding ? <Spinner /> : <BuildIcon />}- className="border-primary-300 text-primary-600 hover:bg-primary-50- dark:border-primary-500/30 dark:text-primary-400 dark:hover:bg-primary-500/10">- {isBuilding ? t('memorySources.build.building') : t('memorySources.build.title')}- </Button>- <Switch- id={`memory-source-toggle-${source.id}`}- checked={source.enabled}- onCheckedChange={() => onToggle(source)}- aria-label={source.enabled ? t('memorySources.disable') : t('memorySources.enable')}- />- <Button- iconOnly- variant="tertiary"- tone="danger"- size="xs"- onClick={() => onRemove(source)}- title={t('memorySources.remove')}- aria-label={t('memorySources.remove')}>- <TrashIcon />- </Button>- </div>- </div>- <CollapsibleContent>- <SourceSettingsPanel source={source} onSaved={onSettingsSaved} onToast={onToast} />- </CollapsibleContent>- </CollapsibleRoot>- </li>- );-}--const FRESHNESS_VARIANT: Record<FreshnessLabel, BadgeVariant> = {- active: 'primary',- recent: 'success',- idle: 'neutral',-};--function FreshnessPill({ freshness }: { freshness: FreshnessLabel }) {- const { t } = useT();- const label =- freshness === 'active'- ? t('sync.active')- : freshness === 'recent'- ? t('sync.recent')- : t('sync.idle');- return <Badge variant={FRESHNESS_VARIANT[freshness]}>{label}</Badge>;-}--/**- * GH-4690: the "Ingested only" warning pill. Replaces the clean freshness pill- * when a source ingested chunks but the downstream retrieval pipeline failed- * (no vectors / extraction / degraded tree). Amber, matching the degraded- * badges in the Brain > Memory > Sync panel, so raw sync ≠ retrieval-ready is- * unmistakable at a glance.- */-function IngestedOnlyPill({ sourceId }: { sourceId: string }) {- const { t } = useT();- return (- <Badge variant="warning" data-testid={`memory-source-ingested-only-${sourceId}`}>- {t('sync.pipeline.ingestedOnly')}- </Badge>- );-}diff --git a/app/src/components/intelligence/MemorySourcesRegistry.tsx b/app/src/components/intelligence/MemorySourcesRegistry.tsxdeleted file mode 100644index f4cb010f04..0000000000--- a/app/src/components/intelligence/MemorySourcesRegistry.tsx+++ /dev/null@@ -1,612 +0,0 @@-/**- * Unified memory sources panel.- *- * Single source of truth for **what feeds memory**: folders, GitHub- * repos, RSS feeds, web pages, Twitter queries, and Composio- * integrations. Polls `openhuman.memory_sources_status_list` every 5s- * for per-source chunk counts and freshness. The Sync button on each- * row dispatches `openhuman.memory_sources_sync` which runs in the- * background and emits MemorySyncStageChanged events.- */-import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';-import { useNavigate } from 'react-router-dom';--import { useT } from '../../lib/i18n/I18nContext';-import { CoreStateContext } from '../../providers/coreStateContext';-import {- applyAllIn,- listMemorySources,- type MemorySourceEntry,- memorySourcesStatusList,- removeMemorySource,- type SourceStatus,- syncMemorySource,- updateMemorySource,-} from '../../services/memorySourcesService';-import type {- ConfirmationModal as ConfirmationModalType,- ToastNotification,-} from '../../types/intelligence';-import {- type BackfillConnectorTreesResponse,- type BackfillStatus,- memoryTreeBackfillConnectorTrees,- memoryTreeBackfillStatus,- memoryTreeFlushSource,- memoryTreePipelineStatus,- type MemoryTreePipelineStatus,-} from '../../utils/tauriCommands/memoryTree';-import { trackAnalyticsEvent } from '../analytics';-import { Card } from '../ui';-import Button from '../ui/Button';-import { AddMemorySourceDialog } from './AddMemorySourceDialog';-import { ConfirmationModal } from './ConfirmationModal';-import { MemorySourceRow } from './MemorySourceRow';-import { AllInIcon, PlusIcon } from './memorySourcesIcons';-import { sourceTreeScope } from './memorySourcesRowHelpers';-import {- noteSyncRejected,- noteSyncRequested,- reconcileWithStatuses,- subscribeTerminalSyncEvents,- useMemorySyncActivity,-} from './memorySyncActivityStore';-import { MemorySyncSchedule } from './MemorySyncSchedule';--// The parsers moved to the store with the state they feed (openhuman#6019);-// re-exported so their tests and any other reader keep one import path.-export { parseIngestedCount, parseSyncNote, parseSyncProgress } from './memorySyncActivityStore';--interface MemorySourcesRegistryProps {- onToast?: (toast: Omit<ToastNotification, 'id'>) => void;- pollIntervalMs?: number;-}--export function MemorySourcesRegistry({- onToast,- pollIntervalMs = 5000,-}: MemorySourcesRegistryProps) {- const { t } = useT();- const navigate = useNavigate();- // Read the core snapshot directly (not via the throwing `useCoreState`- // hook) so this component still renders in unit tests that mount it- // without a CoreStateProvider — there `ctx` is null and `isAuthenticated`- // stays a stable `false`, so the load effect behaves exactly as before.- const coreState = useContext(CoreStateContext);- const isAuthenticated = coreState?.snapshot.auth.isAuthenticated ?? false;- const [sources, setSources] = useState<MemorySourceEntry[]>([]);- const [statuses, setStatuses] = useState<SourceStatus[]>([]);- // Global downstream pipeline health (GH-4690) — the same snapshot the- // Brain > Memory > Sync panel renders. Folded into each row so a source that- // ingested but failed embeddings/extraction/tree-build shows a warning rather- // than a clean synced badge. `null` until the first poll resolves.- const [pipeline, setPipeline] = useState<MemoryTreePipelineStatus | null>(null);- // Global embed-backfill snapshot (openhuman#6025): whether a re-embed chain- // still has rows to process. Rows use it to tell a backlog that is being- // drained (neutral note) from one nothing is working on (amber warning).- const [backfill, setBackfill] = useState<BackfillStatus | null>(null);- const [loading, setLoading] = useState(true);- const [dialogOpen, setDialogOpen] = useState(false);- // The live sync state — which rows are syncing, their bar, their last- // result — lives in `memorySyncActivityStore`, which outlives this screen- // (openhuman#6019): a tab or route change mid-sync used to drop it all and- // miss the terminal event, so the row came back idle as if the sync had- // stopped. The store's listener is installed once for the page; this screen- // only reads.- const { syncingIds, progress: syncProgress, results: syncResults } = useMemorySyncActivity();- const [buildingId, setBuildingId] = useState<string | null>(null);- const [allInModalOpen, setAllInModalOpen] = useState(false);- const [applyingAllIn, setApplyingAllIn] = useState(false);- const allInInFlightRef = useRef(false);- const isMountedRef = useRef(true);- // "Repair older memories" (openhuman#6012): the backfill RPC has no other- // entry point in the app. Two steps — a dry run that only counts, then the- // real pass behind a confirmation — because the real pass embeds every- // document it files, and that spends credits.- const [repairModalOpen, setRepairModalOpen] = useState(false);- const [repairPreview, setRepairPreview] = useState<BackfillConnectorTreesResponse | null>(null);- const [repairing, setRepairing] = useState(false);- const repairInFlightRef = useRef(false);- const [expandedSettingsId, setExpandedSettingsId] = useState<string | null>(null);-- // Refs let the (intentionally dep-free) sync-stage listener fire accurate- // toasts on the *terminal* event without re-subscribing on every render or- // 5s poll. The handler must read the latest onToast/sources/t (#3295).- const onToastRef = useRef(onToast);- const sourcesRef = useRef(sources);- const tRef = useRef(t);- useEffect(() => {- onToastRef.current = onToast;- sourcesRef.current = sources;- tRef.current = t;- });-- useEffect(() => {- isMountedRef.current = true;- return () => {- isMountedRef.current = false;- };- }, []);-- // The toast for a run that ends while this screen is mounted. The state- // itself is the store's; a run that ends while no screen is showing still- // lands as the row's result chip on the next mount, it just goes untoasted.- useEffect(- () =>- subscribeTerminalSyncEvents(({ rowId, stage, detail, result }) => {- const tt = tRef.current;- const label = sourcesRef.current.find(s => s.id === rowId)?.label ?? rowId;- if (stage === 'completed') {- // The item count parsed from the detail ("ingested N item(s)") and- // why the run stopped short, both already on the result. A zero- // count is not "up to date" when the run stopped short: the reason- // it stopped is the whole message then, not a suffix (#3295).- const { items, note } = result;- const hasItems = Boolean(items && items > 0);- const counted = hasItems- ? `${items} ${tt('memorySources.sync.itemsSynced')}`- : note === 'budget_spent'- ? tt('memorySources.sync.budgetSpent')- : note === 'more_pending'- ? tt('memorySources.sync.morePending')- : tt('memorySources.sync.upToDate');- // Beside a count, the note says why the run stopped short — the- // budget as much as the cap. A pass that filed some mail and then- // ran out for the day is the common partial case this exists to- // explain; "N items synced" alone would read as a finished sync.- const noteKey =- note === 'budget_spent'- ? 'memorySources.sync.budgetSpent'- : note === 'more_pending'- ? 'memorySources.sync.morePending'- : null;- onToastRef.current?.({- type: note === 'budget_spent' ? 'warning' : 'success',- title: `${tt('memorySources.sync.completeTitle')} ${label}`,- message: hasItems && noteKey ? `${counted} — ${tt(noteKey)}` : counted,- });- } else {- // The core already reported internal bugs to Sentry via- // report_error_or_expected; here the reason reaches the user.- onToastRef.current?.({- type: 'error',- title: `${tt('memorySources.sync.failedLabel')} · ${label}`,- message: detail ?? tt('memorySources.sync.failedLabel'),- });- }- }),- []- );-- const refresh = useCallback(async () => {- try {- const [list, stats, health, backfillStatus] = await Promise.all([- listMemorySources().catch(err => {- console.warn('[ui-flow][memory-sources] list failed', err);- return [] as MemorySourceEntry[];- }),- memorySourcesStatusList().catch(err => {- console.warn('[ui-flow][memory-sources] status_list failed', err);- return [] as SourceStatus[];- }),- // GH-4690: downstream pipeline health. Best-effort — a failure here- // must never hide the source list, so we fall back to `null` (rows then- // rely on the precise per-source pending-chunk signal alone).- memoryTreePipelineStatus().catch(err => {- console.warn('[ui-flow][memory-sources] pipeline_status failed', err);- return null;- }),- // openhuman#6025: embed work in flight. Best-effort like the pipeline- // snapshot — `null` makes rows fall back to their own freshness.- memoryTreeBackfillStatus().catch(err => {- console.warn('[ui-flow][memory-sources] backfill_status failed', err);- return null;- }),- ]);- if (!isMountedRef.current) return;- setSources(list);- setStatuses(stats);- setPipeline(health);- setBackfill(backfillStatus);- // The core's own account of what is in flight (`sync_stage`,- // openhuman#6019): seeds the bar for a run this page never saw start —- // a cold mount, an app reload mid-sync — and takes down a bar whose- // terminal event was lost, once the core has reported the row idle for- // longer than the grace. RC#5's "rehydrates via poll" promise (#3295)- // finally has the field it needed.- reconcileWithStatuses(stats);- } finally {- if (isMountedRef.current) setLoading(false);- }- }, []);-- // Load on mount AND whenever the session transitions to authenticated.- // After a page reload the registry can mount (e.g. via a persisted- // `?tab=memory` deep link) *before* CoreStateProvider has restored the- // session, so the initial fetch runs against a not-yet-ready core and- // surfaces nothing. Re-running when `isAuthenticated` flips true picks up- // sources immediately instead of waiting for the next 5s poll — which- // under CI load was racing the E2E visibility timeout (#3449).- useEffect(() => {- void refresh();- }, [refresh, isAuthenticated]);-- useEffect(() => {- if (!pollIntervalMs) return undefined;- const id = setInterval(() => {- void refresh();- }, pollIntervalMs);- return () => clearInterval(id);- }, [pollIntervalMs, refresh]);-- const statusById = useMemo(() => {- const m = new Map<string, SourceStatus>();- for (const s of statuses) m.set(s.source_id, s);- return m;- }, [statuses]);-- // Newest chunk timestamp across every source — the "Last synced …" anchor- // for the global schedule header. Derived from persisted chunk data, so it- // survives restarts.- const overallLastSyncMs = useMemo(() => {- let newest: number | null = null;- for (const s of statuses) {- if (s.last_chunk_at_ms != null && (newest === null || s.last_chunk_at_ms > newest)) {- newest = s.last_chunk_at_ms;- }- }- return newest;- }, [statuses]);-- const handleToggle = useCallback(- async (source: MemorySourceEntry) => {- try {- const updated = await updateMemorySource(source.id, { enabled: !source.enabled });- setSources(prev => prev.map(s => (s.id === updated.id ? updated : s)));- } catch (err) {- onToast?.({- type: 'error',- title: t('memorySources.toggleFailed'),- message: err instanceof Error ? err.message : String(err),- });- }- },- [onToast, t]- );-- const handleRemove = useCallback(- async (source: MemorySourceEntry) => {- try {- await removeMemorySource(source.id);- setSources(prev => prev.filter(s => s.id !== source.id));- onToast?.({ type: 'success', title: t('memorySources.removed'), message: source.label });- } catch (err) {- onToast?.({- type: 'error',- title: t('memorySources.removeFailed'),- message: err instanceof Error ? err.message : String(err),- });- }- },- [onToast, t]- );-- const handleSync = useCallback(- async (source: MemorySourceEntry) => {- // RC#1 (#3295): light the row on click — the event will also fire, but- // this way it lights before the first sync-stage event arrives — and- // drop the prior run's result chip.- noteSyncRequested(source.id);- console.debug(`[ui-flow][memory-sync] manual sync triggered source_id=${source.id}`);- try {- await syncMemorySource(source.id);- // NOTE: success/failure feedback is intentionally NOT fired here. This- // RPC returns in ~4ms after merely *spawning* the background sync; the- // real outcome arrives via the terminal `completed`/`failed` stage event- // (handled above), which carries the item count / failure reason (#3295).- void refresh();- } catch (err) {- // The RPC call itself failed (transport/validation) — the background- // sync never started, so no stage event will arrive. Surface it here:- // clear the syncing flag and record a failed result on the row.- const reason = err instanceof Error ? err.message : String(err);- noteSyncRejected(source.id, reason);- onToast?.({- type: 'error',- title: `${t('memorySources.sync.failedLabel')} · ${source.label}`,- message: reason,- });- }- // No `finally` clear: on success the row stays "syncing" until the- // terminal stage event arrives (the sync is still running in the- // background). Clearing here is what made the indicator vanish in ~4ms.- },- [onToast, refresh, t]- );-- const handleBuild = useCallback(- async (source: MemorySourceEntry) => {- const scope = sourceTreeScope(source);- if (!scope) return;- setBuildingId(source.id);- try {- const resp = await memoryTreeFlushSource(scope);- onToast?.({- type: 'success',- title: t('memorySources.build.successTitle'),- message: `${resp.seals_fired} ${t('memorySources.build.sealsMessage')}`,- });- } catch (err) {- onToast?.({- type: 'error',- title: t('memorySources.build.failedTitle'),- message: err instanceof Error ? err.message : String(err),- });- } finally {- setBuildingId(prev => (prev === source.id ? null : prev));- }- },- [onToast, t]- );-- const handleAdded = useCallback(- (source: MemorySourceEntry) => {- setSources(prev => [...prev, source]);- onToast?.({ type: 'success', title: t('memorySources.added'), message: source.label });- void refresh();- },- [onToast, refresh, t]- );-- const handleConfirmAllIn = useCallback(async () => {- if (allInInFlightRef.current) return;- allInInFlightRef.current = true;- setApplyingAllIn(true);- try {- const result = await applyAllIn();- setSources(result.sources);- // openhuman#5820: the RPC resolves even when triggers failed, so the- // verdict comes from the counts, not from "the call did not throw".- // Every trigger failing (the incident: `no memory source registered`- // x4) is an error; a partial start is a warning that names both- // counts. Only a clean sweep is a success.- if (result.sync_failed > 0 && result.sync_triggered === 0) {- onToast?.({- type: 'error',- title: t('memorySources.allIn.allFailed'),- message: result.sync_errors[0],- });- } else if (result.sync_failed > 0) {- onToast?.({- type: 'warning',- title: t('memorySources.allIn.partial')- .replace('{triggered}', String(result.sync_triggered))- .replace('{failed}', String(result.sync_failed)),- message: result.sync_errors[0],- });- } else {- onToast?.({ type: 'success', title: t('memorySources.allIn.success') });- }- } catch (err) {- onToast?.({- type: 'error',- title: t('memorySources.allIn.failed'),- message: err instanceof Error ? err.message : String(err),- });- } finally {- allInInFlightRef.current = false;- setApplyingAllIn(false);- setAllInModalOpen(false);- }- }, [onToast, t]);-- const handleRepairClick = useCallback(async () => {- if (repairInFlightRef.current) return;- repairInFlightRef.current = true;- setRepairing(true);- try {- // Preview first: the dry run counts what a pass would examine and- // writes nothing, so the confirmation can name a number before any- // credit is spent.- const preview = await memoryTreeBackfillConnectorTrees({ dryRun: true });- setRepairPreview(preview);- if (preview.scanned === 0) {- onToast?.({ type: 'success', title: t('memorySources.repair.nothing') });- return;- }- setRepairModalOpen(true);- } catch (err) {- onToast?.({- type: 'error',- title: t('memorySources.repair.failed'),- message: err instanceof Error ? err.message : String(err),- });- } finally {- repairInFlightRef.current = false;- setRepairing(false);- }- }, [onToast, t]);-- const handleConfirmRepair = useCallback(async () => {- if (repairInFlightRef.current) return;- repairInFlightRef.current = true;- setRepairing(true);- setRepairModalOpen(false);- try {- const result = await memoryTreeBackfillConnectorTrees({ dryRun: false });- // The successful domain outcome, not the click: a privacy-safe count- // only — no ids, no user text.- trackAnalyticsEvent('memory_repair_succeeded', { count: result.ingested });- const summary = t('memorySources.repair.success')- .replace('{ingested}', String(result.ingested))- .replace('{already}', String(result.already_present))- .replace('{skipped}', String(result.skipped));- // The driver files up to its per-call limit and says when documents- // remain; the pass is idempotent, so "run it again" is the whole- // resume story.- if (result.more_pending) {- onToast?.({- type: 'warning',- title: summary,- message: t('memorySources.repair.morePending'),- });- } else {- onToast?.({ type: 'success', title: summary });- }- void refresh();- } catch (err) {- onToast?.({- type: 'error',- title: t('memorySources.repair.failed'),- message: err instanceof Error ? err.message : String(err),- });- } finally {- repairInFlightRef.current = false;- setRepairing(false);- setRepairPreview(null);- }- }, [onToast, refresh, t]);-- const handleSettingsSaved = useCallback((updated: MemorySourceEntry) => {- setSources(prev => prev.map(s => (s.id === updated.id ? updated : s)));- }, []);-- const handleToggleSettings = useCallback((sourceId: string) => {- setExpandedSettingsId(prev => (prev === sourceId ? null : sourceId));- }, []);-- const allInModal: ConfirmationModalType = {- isOpen: allInModalOpen,- title: t('memorySources.allIn.title'),- message: t('memorySources.allIn.message'),- confirmText: t('memorySources.allIn.confirm'),- cancelText: t('memorySources.allIn.cancel'),- destructive: false,- onConfirm: () => {- void handleConfirmAllIn();- },- onCancel: () => {- setAllInModalOpen(false);- },- };-- const repairModal: ConfirmationModalType = {- isOpen: repairModalOpen,- title: t('memorySources.repair.title'),- message: t('memorySources.repair.message').replace(- '{scanned}',- String(repairPreview?.scanned ?? 0)- ),- confirmText: t('memorySources.repair.confirm'),- cancelText: t('memorySources.repair.cancel'),- destructive: false,- onConfirm: () => {- void handleConfirmRepair();- },- onCancel: () => {- setRepairModalOpen(false);- setRepairPreview(null);- },- };-- return (- <Card padded divided={false} data-testid="memory-sources">- <header className="mb-3 flex items-center justify-between gap-2">- <h3 className="text-sm font-semibold text-content-secondary">{t('memorySources.title')}</h3>- <div className="flex items-center gap-2">- <Button- variant="secondary"- size="sm"- onClick={() => void handleRepairClick()}- disabled={repairing}- analyticsId="memory-sources-repair"- data-testid="repair-memories-button"- title={t('memorySources.repair.title')}>- {t('memorySources.repair.button')}- </Button>- <Button- variant="secondary"- size="sm"- onClick={() => setAllInModalOpen(true)}- disabled={applyingAllIn}- data-testid="all-in-button"- leadingIcon={<AllInIcon />}- className="border-primary-300 text-primary-600 hover:bg-primary-50- dark:border-primary-500/30 dark:text-primary-400 dark:hover:bg-primary-500/10">- {t('memorySources.allIn.button')}- </Button>- <Button- variant="primary"- size="sm"- onClick={() => setDialogOpen(true)}- leadingIcon={<PlusIcon />}>- {t('memorySources.addSource')}- </Button>- </div>- </header>-- <MemorySyncSchedule lastSyncMs={overallLastSyncMs} onToast={onToast} />-- {loading ? (- <p className="text-xs text-content-muted">{t('common.loading')}</p>- ) : sources.length === 0 ? (- <p className="text-xs text-content-muted">{t('memorySources.empty')}</p>- ) : (- <ul className="divide-y divide-line-subtle">- {sources.map(source => (- <MemorySourceRow- key={source.id}- source={source}- status={statusById.get(source.id) ?? null}- pipeline={pipeline}- backfill={backfill}- isAuthenticated={isAuthenticated}- isSyncing={syncingIds.has(source.id) || syncProgress.has(source.id)}- isBuilding={buildingId === source.id}- progress={syncProgress.get(source.id) ?? null}- result={syncResults.get(source.id) ?? null}- settingsExpanded={expandedSettingsId === source.id}- onToggle={handleToggle}- onRemove={handleRemove}- onSync={handleSync}- onBuild={handleBuild}- onToggleSettings={handleToggleSettings}- onSettingsSaved={handleSettingsSaved}- onToast={onToast}- onViewHealth={() => {- console.debug('[ui-flow][memory-sources] view memory health from source row');- navigate('/connections?tab=brain&brain=sync');- }}- onSignIn={() => {- console.debug(- '[ui-flow][memory-sources] sign-in prompt from stored-without-vectors'- );- navigate('/auth');- }}- />- ))}- </ul>- )}-- <AddMemorySourceDialog- open={dialogOpen}- onClose={() => setDialogOpen(false)}- onAdded={handleAdded}- />-- {allInModalOpen && (- <ConfirmationModal modal={allInModal} onClose={() => setAllInModalOpen(false)} />- )}-- {repairModalOpen && (- <ConfirmationModal- modal={repairModal}- onClose={() => {- setRepairModalOpen(false);- setRepairPreview(null);- }}- />- )}- </Card>- );-}diff --git a/app/src/components/intelligence/MemorySyncSchedule.tsx b/app/src/components/intelligence/MemorySyncSchedule.tsxdeleted file mode 100644index 3b4d1eb747..0000000000--- a/app/src/components/intelligence/MemorySyncSchedule.tsx+++ /dev/null@@ -1,141 +0,0 @@-/**- * Global memory-sync schedule control (#3302). Presented like a backup- * schedule: "Last synced … · Sync every …", with preset cadences (4h / 12h /- * 24h) plus "Manual only". Reads/writes `config_*_memory_sync_settings`.- *- * Split out of `MemorySourcesRegistry.tsx` to keep that file under the size- * budget.- */-import debug from 'debug';-import { useCallback, useEffect, useState } from 'react';--import { useT } from '../../lib/i18n/I18nContext';-import type { ToastNotification } from '../../types/intelligence';-import {- type MemorySyncSettings,- openhumanGetMemorySyncSettings,- openhumanUpdateMemorySyncSettings,-} from '../../utils/tauriCommands/config';-import Button from '../ui/Button';-import { relativeTimestamp } from './memorySourcesRowHelpers';--const log = debug('intelligence:memory-sync');--/** Manual-only sentinel — stored as `sync_interval_secs = 0`. */-const MANUAL_INTERVAL_SECS = 0;-/** Preset cadences offered in the UI (seconds): 4h / 12h / 24h. */-const SYNC_INTERVAL_PRESETS_SECS = [14_400, 43_200, 86_400];--/** Human label for a cadence ("Every 4h" / "Every 30m" / "Manual only"). */-function intervalChipLabel(secs: number, t: (k: string) => string): string {- if (secs === MANUAL_INTERVAL_SECS) return t('memorySyncInterval.manual');- if (secs % 3600 === 0) {- return t('memorySyncInterval.everyHours').replace('{h}', String(secs / 3600));- }- return t('memorySyncInterval.everyMinutes').replace('{m}', String(Math.round(secs / 60)));-}--interface MemorySyncScheduleProps {- lastSyncMs: number | null;- onToast?: (toast: Omit<ToastNotification, 'id'>) => void;-}--export function MemorySyncSchedule({ lastSyncMs, onToast }: MemorySyncScheduleProps) {- const { t } = useT();- const [settings, setSettings] = useState<MemorySyncSettings | null>(null);- const [saving, setSaving] = useState(false);-- useEffect(() => {- let active = true;- const loadSettings = async () => {- try {- const resp = await openhumanGetMemorySyncSettings();- if (active) setSettings(resp.result);- } catch (err) {- log('get settings failed: %O', err);- }- };- void loadSettings();- return () => {- active = false;- };- }, []);-- const handleSelect = useCallback(- async (secs: number) => {- setSaving(true);- try {- const resp = await openhumanUpdateMemorySyncSettings({ sync_interval_secs: secs });- setSettings(resp.result);- } catch (err) {- onToast?.({- type: 'error',- title: t('memorySyncInterval.saveFailed'),- message: err instanceof Error ? err.message : String(err),- });- } finally {- setSaving(false);- }- },- [onToast, t]- );-- if (!settings) return null;-- const lastSync = relativeTimestamp(lastSyncMs, t);- const currentLabel = settings.is_manual- ? t('memorySyncInterval.manual')- : intervalChipLabel(settings.selected_secs, t);- // Option list: backend presets (fall back to the local defaults) + Manual.- const presetSecs =- settings.presets && settings.presets.length > 0 ? settings.presets : SYNC_INTERVAL_PRESETS_SECS;- const options = [...presetSecs, MANUAL_INTERVAL_SECS];- const selectedSecs = settings.is_manual ? MANUAL_INTERVAL_SECS : settings.selected_secs;-- return (- <div- className="mb-3 rounded-md border border-line bg-surface-muted p-3"- data-testid="memory-sync-schedule">- <div className="flex flex-wrap items-center justify-between gap-2">- <div className="min-w-0">- <p className="text-xs font-semibold text-content-secondary">- {t('memorySyncInterval.title')}- </p>- <p className="mt-0.5 text-xs text-content-muted">- <span>- {t('memorySyncInterval.lastSynced')} {lastSync ?? t('memorySyncInterval.never')}- </span>- <span aria-hidden="true"> · </span>- <span data-testid="memory-sync-current">{currentLabel}</span>- </p>- </div>- <div- role="radiogroup"- aria-label={t('memorySyncInterval.title')}- className="flex flex-wrap items-center gap-1.5">- {options.map(secs => {- const isSelected = secs === selectedSecs;- return (- <Button- key={secs}- variant="secondary"- size="xs"- role="radio"- aria-checked={isSelected}- disabled={saving}- onClick={() => void handleSelect(secs)}- data-testid={`memory-sync-preset-${secs}`}- className={- isSelected- ? 'border-primary-500 bg-primary-50 text-primary-700 dark:border-primary-500/50 dark:bg-primary-500/10 dark:text-primary-300'- : 'text-content-secondary'- }>- {intervalChipLabel(secs, t)}- </Button>- );- })}- </div>- </div>- </div>- );-}diff --git a/app/src/components/intelligence/MemoryTextWithEntities.tsx b/app/src/components/intelligence/MemoryTextWithEntities.tsxdeleted file mode 100644index de0b48333e..0000000000--- a/app/src/components/intelligence/MemoryTextWithEntities.tsx+++ /dev/null@@ -1,131 +0,0 @@-/**- * Renders memory query/recall text with highlighted entity type annotations,- * plus an optional structured entity list when the backend returns entities- * in the `context.entities[]` field.- *- * The backend surfaces entity types in text like:- * "Alice (PERSON) -[OWNS]-> Atlas (PROJECT)"- *- * This component parses those `(TYPE)` annotations and renders them as- * small styled badges inline, keeping the rest as plain text. When a- * structured `entities` array is provided, it also renders a compact- * entity chip bar above the text.- */-import { useT } from '../../lib/i18n/I18nContext';-import type { MemoryRetrievalEntity } from '../../utils/tauriCommands';--interface MemoryTextWithEntitiesProps {- text: string;- /** Structured entities from `context.entities[]` — shown as chips when present. */- entities?: MemoryRetrievalEntity[];- className?: string;-}--/** Matches parenthesized entity type annotations like (PERSON), (PROJECT), (ORG). */-const ENTITY_TYPE_RE = /\(([A-Z][A-Z0-9_]{1,30})\)/g;--/** Deterministic colour palette for entity type badges (hue-shifted). */-const TYPE_COLORS: Record<string, { bg: string; text: string; border: string }> = {- PERSON: { bg: 'bg-sky-500/15', text: 'text-sky-300', border: 'border-sky-500/20' },- PROJECT: { bg: 'bg-emerald-500/15', text: 'text-emerald-300', border: 'border-emerald-500/20' },- ORG: { bg: 'bg-amber-500/15', text: 'text-amber-300', border: 'border-amber-500/20' },- ORGANIZATION: { bg: 'bg-amber-500/15', text: 'text-amber-300', border: 'border-amber-500/20' },- TECHNOLOGY: { bg: 'bg-violet-500/15', text: 'text-violet-300', border: 'border-violet-500/20' },- TOOL: { bg: 'bg-violet-500/15', text: 'text-violet-300', border: 'border-violet-500/20' },- LOCATION: { bg: 'bg-rose-500/15', text: 'text-rose-300', border: 'border-rose-500/20' },- EVENT: { bg: 'bg-pink-500/15', text: 'text-pink-300', border: 'border-pink-500/20' },- CONCEPT: { bg: 'bg-teal-500/15', text: 'text-teal-300', border: 'border-teal-500/20' },-};--const DEFAULT_TYPE_COLOR = {- bg: 'bg-primary-500/15',- text: 'text-primary-300',- border: 'border-primary-500/20',-};--function colorForType(entityType: string): { bg: string; text: string; border: string } {- return TYPE_COLORS[entityType.toUpperCase()] ?? DEFAULT_TYPE_COLOR;-}--interface TextSegment {- kind: 'text' | 'entity-type';- value: string;-}--function parseEntityAnnotations(text: string): TextSegment[] {- const segments: TextSegment[] = [];- let lastIndex = 0;-- for (const match of text.matchAll(ENTITY_TYPE_RE)) {- const matchStart = match.index;- if (matchStart > lastIndex) {- segments.push({ kind: 'text', value: text.slice(lastIndex, matchStart) });- }- segments.push({ kind: 'entity-type', value: match[1] });- lastIndex = matchStart + match[0].length;- }-- if (lastIndex < text.length) {- segments.push({ kind: 'text', value: text.slice(lastIndex) });- }-- return segments;-}--/** Compact chip for a structured entity, showing name + optional type badge. */-function EntityChip({ entity }: { entity: MemoryRetrievalEntity }) {- const color = entity.entity_type ? colorForType(entity.entity_type) : DEFAULT_TYPE_COLOR;- return (- <span- className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded ${color.bg} border ${color.border}`}- title={entity.entity_type ? `${entity.name} (${entity.entity_type})` : entity.name}>- <span className={`text-[10px] leading-tight font-medium ${color.text}`}>{entity.name}</span>- {entity.entity_type && (- <span className="text-[8px] leading-tight font-semibold uppercase tracking-wide opacity-70">- {entity.entity_type}- </span>- )}- </span>- );-}--export function MemoryTextWithEntities({ text, entities, className }: MemoryTextWithEntitiesProps) {- const { t } = useT();- if (!text && (!entities || entities.length === 0)) return null;-- const hasStructuredEntities = entities && entities.length > 0;- const hasInlineAnnotations = /\([A-Z][A-Z0-9_]{1,30}\)/.test(text);-- return (- <div className={className}>- {/* Structured entity chips */}- {hasStructuredEntities && (- <div className="flex flex-wrap gap-1 mb-2 pb-2 border-b border-line">- {entities.map((entity, i) => (- <EntityChip key={entity.id ?? `${entity.name}-${i}`} entity={entity} />- ))}- </div>- )}-- {/* Text content with inline entity type annotations */}- {text && (- <pre className="whitespace-pre-wrap m-0 p-0 font-inherit text-inherit leading-inherit">- {hasInlineAnnotations- ? parseEntityAnnotations(text).map((seg, i) =>- seg.kind === 'entity-type' ? (- <span- key={i}- className={`inline-block mx-0.5 px-1 py-px rounded text-[9px] leading-tight font-semibold ${colorForType(seg.value).bg} ${colorForType(seg.value).text} border ${colorForType(seg.value).border} uppercase tracking-wide align-baseline`}- title={`${t('intelligence.memoryText.entityTypePrefix')}: ${seg.value}`}>- {seg.value}- </span>- ) : (- <span key={i}>{seg.value}</span>- )- )- : text}- </pre>- )}- </div>- );-}diff --git a/app/src/components/intelligence/MemoryTreeStatusPanel.test.tsx b/app/src/components/intelligence/MemoryTreeStatusPanel.test.tsxdeleted file mode 100644index 9fd432e309..0000000000--- a/app/src/components/intelligence/MemoryTreeStatusPanel.test.tsx+++ /dev/null@@ -1,764 +0,0 @@-/**- * Vitest for `<MemoryTreeStatusPanel />`. Covers the four-tile dashboard,- * the toggle round-trip (calls `memoryTreeSetEnabled` and re-fetches),- * paused/error rendering branches, and the failure → retry path.- *- * Fake timers are pinned in `beforeEach` so `Date.now()` (in- * `formatRelativeMs` and the `payload()` helper) yields the same value on- * every assertion, and the polling `setTimeout` cannot race CI runners.- * The first `fetchOnce()` still resolves as a microtask via `waitFor`, so- * the suite never needs to advance timers manually.- */-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import type { MemoryTreePipelineStatus } from '../../utils/tauriCommands';-import {- classifyIntegration,- MemoryTreeStatusPanel,- providerIconChar,-} from './MemoryTreeStatusPanel';--const mockPipelineStatus = vi.fn();-const mockSetEnabled = vi.fn();-const mockSyncStatusList = vi.fn();-const mockRetryFailed = vi.fn();-const mockNamespaceSummaries = vi.fn();-// #5324: the panel now navigates (budget CTA) and dispatches (escalating the-// blocking cause to the shell-mounted UserErrorCenter). Stub both so the-// suite keeps rendering the panel bare, without a Router or a Redux store.-const mockNavigate = vi.fn();-const mockDispatch = vi.fn();-// Analytics is a consent-gated side effect that reaches into the core-state-// snapshot; stub it so the panel renders bare and the retry-success path can be-// asserted without a real analytics pipeline.-const mockTrackAnalyticsEvent = vi.fn();--vi.mock('react-router-dom', () => ({ useNavigate: () => mockNavigate }));-vi.mock('../../store/hooks', () => ({ useAppDispatch: () => mockDispatch }));-vi.mock('../analytics', () => ({- trackAnalyticsEvent: (...args: unknown[]) => mockTrackAnalyticsEvent(...args),-}));--vi.mock('../../utils/tauriCommands', async importOriginal => {- // Inherit everything else (types, sibling wrappers) verbatim so the panel- // sees the same module shape as production — only the two new helpers- // under test get swapped for spies.- const actual = await importOriginal<typeof import('../../utils/tauriCommands')>();- return {- ...actual,- memoryTreePipelineStatus: (...args: unknown[]) => mockPipelineStatus(...args),- memoryTreeSetEnabled: (...args: unknown[]) => mockSetEnabled(...args),- memorySyncStatusList: (...args: unknown[]) => mockSyncStatusList(...args),- memoryTreeRetryFailed: (...args: unknown[]) => mockRetryFailed(...args),- memoryNamespaceSummaries: (...args: unknown[]) => mockNamespaceSummaries(...args),- };-});--/** Stable wall-clock used by every test in this file. */-const FIXED_NOW_MS = new Date('2026-01-01T12:00:00.000Z').getTime();--function payload(overrides: Partial<MemoryTreePipelineStatus> = {}): MemoryTreePipelineStatus {- return {- status: 'running',- reason: null,- last_sync_ms: FIXED_NOW_MS - 5 * 60 * 1000, // 5 minutes ago (stable under fake timers)- total_chunks: 1234,- wiki_size_bytes: 2 * 1024 * 1024, // 2 MiB- pipeline_jobs: { ready: 0, running: 0, failed: 0 },- is_syncing: false,- is_paused: false,- ...overrides,- };-}--describe('<MemoryTreeStatusPanel />', () => {- beforeEach(() => {- // `shouldAdvanceTime` lets fake `setTimeout`/`setInterval` tick at the- // real-time cadence so RTL's `waitFor` (and the panel's polling loop)- // make progress without each test having to call- // `vi.advanceTimersByTime` manually — while `setSystemTime` still- // freezes `Date.now()` so `formatRelativeMs` resolves deterministically.- vi.useFakeTimers({ shouldAdvanceTime: true });- vi.setSystemTime(new Date(FIXED_NOW_MS));- mockPipelineStatus.mockReset();- mockSetEnabled.mockReset();- mockSyncStatusList.mockReset();- mockRetryFailed.mockReset();- mockNamespaceSummaries.mockReset();- mockTrackAnalyticsEvent.mockReset();- mockSyncStatusList.mockResolvedValue([]); // default: empty, harmless to existing tests- // Same default the inline stub used to hard-code, now re-programmable- // per test so the failure branch can be driven.- mockNamespaceSummaries.mockResolvedValue({ namespaces: [], total_documents: 0 });- });-- afterEach(() => {- vi.useRealTimers();- vi.restoreAllMocks();- });-- it('renders the four tiles with formatted values once the status loads', async () => {- mockPipelineStatus.mockResolvedValueOnce(payload());- render(<MemoryTreeStatusPanel />);-- // Status label flows in from the wire status.- await waitFor(() => {- expect(screen.getByTestId('memory-tree-status-label')).toHaveTextContent(/running/i);- });-- // Number is thousands-separated via Intl.NumberFormat.- expect(screen.getByTestId('memory-tree-total-chunks')).toHaveTextContent('1,234');- // 2 MiB formatter renders "2.0 MiB".- expect(screen.getByTestId('memory-tree-wiki-size')).toHaveTextContent(/2\.0 MiB/);- // last_sync_ms ~5 min ago bucketed to "5 min ago".- expect(screen.getByTestId('memory-tree-last-sync')).toHaveTextContent(/min ago/);- });-- it('shows the memory-tree job queue a sync feeds (openhuman#6257)', async () => {- mockPipelineStatus.mockResolvedValue(- payload({ pipeline_jobs: { ready: 1234, running: 1, failed: 2 } })- );- render(<MemoryTreeStatusPanel />);-- await waitFor(() => {- expect(screen.getByTestId('memory-tree-job-queue')).toHaveTextContent(- 'Memory jobs: 1,234 waiting, 1 running, 2 failed'- );- });- });-- it('fetches integration list and pipeline status in parallel on the same tick', async () => {- mockPipelineStatus.mockResolvedValue(payload());- mockSyncStatusList.mockResolvedValue([- {- provider: 'slack',- chunks_synced: 5231,- chunks_pending: 0,- batch_total: 0,- batch_processed: 0,- last_chunk_at_ms: FIXED_NOW_MS - 3 * 60 * 1000,- freshness: 'active',- },- ]);-- render(<MemoryTreeStatusPanel />);-- await waitFor(() => {- expect(mockPipelineStatus).toHaveBeenCalledTimes(1);- expect(mockSyncStatusList).toHaveBeenCalledTimes(1);- });- });-- it('shows skeleton placeholders before the first status payload resolves', async () => {- // Suspend the promise so the panel paints its loading state.- let resolve: (v: MemoryTreePipelineStatus) => void = () => {};- mockPipelineStatus.mockReturnValueOnce(- new Promise<MemoryTreePipelineStatus>(r => {- resolve = r;- })- );- render(<MemoryTreeStatusPanel />);- // Tiles container is on-screen; status-label has not been written yet.- expect(screen.getByTestId('memory-tree-status-tiles')).toBeInTheDocument();- expect(screen.queryByTestId('memory-tree-status-label')).toBeNull();- // Resolve to unblock the cleanup path.- await act(async () => {- resolve(payload());- });- });-- it('toggles auto-sync by calling memoryTreeSetEnabled and re-fetching', async () => {- mockPipelineStatus- .mockResolvedValueOnce(payload({ status: 'running', is_paused: false }))- .mockResolvedValueOnce(- payload({ status: 'paused', is_paused: true, reason: 'scheduler gate mode = off' })- );- mockSetEnabled.mockResolvedValueOnce({ enabled: false, changed: true, mode: 'off' });-- render(<MemoryTreeStatusPanel />);- await waitFor(() => {- expect(screen.getByTestId('memory-tree-status-label')).toHaveTextContent(/running/i);- });-- const toggle = screen.getByTestId('memory-tree-status-toggle');- expect(toggle.getAttribute('aria-checked')).toBe('true');-- fireEvent.click(toggle);-- await waitFor(() => {- expect(mockSetEnabled).toHaveBeenCalledWith(false);- });- await waitFor(() => {- expect(screen.getByTestId('memory-tree-status-label')).toHaveTextContent(/paused/i);- });- expect(toggle.getAttribute('aria-checked')).toBe('false');- });-- it('renders a paused pill with the reason from the wire payload', async () => {- mockPipelineStatus.mockResolvedValueOnce(- payload({ status: 'paused', is_paused: true, reason: 'scheduler gate mode = off' })- );- render(<MemoryTreeStatusPanel />);-- await waitFor(() => {- expect(screen.getByTestId('memory-tree-status-label')).toHaveTextContent(/paused/i);- });- expect(screen.getByText(/scheduler gate mode = off/i)).toBeInTheDocument();- expect(screen.getByTestId('memory-tree-status-toggle').getAttribute('aria-checked')).toBe(- 'false'- );- });-- it('shows an error banner with retry button when the fetch rejects', async () => {- mockPipelineStatus.mockRejectedValueOnce(new Error('rpc went boom'));- mockPipelineStatus.mockResolvedValueOnce(payload({ status: 'idle', total_chunks: 0 }));- render(<MemoryTreeStatusPanel />);-- await waitFor(() => {- expect(screen.getByTestId('memory-tree-status-error')).toBeInTheDocument();- });-- const retry = screen.getByRole('button', { name: /retry/i });- fireEvent.click(retry);-- await waitFor(() => {- expect(screen.getByTestId('memory-tree-status-label')).toHaveTextContent(/idle/i);- });- });-- it('renders a row per integration with provider name, chunk count, freshness pill', async () => {- mockPipelineStatus.mockResolvedValue(payload());- mockSyncStatusList.mockResolvedValue([- {- provider: 'slack',- chunks_synced: 5231,- chunks_pending: 0,- batch_total: 0,- batch_processed: 0,- last_chunk_at_ms: FIXED_NOW_MS - 3 * 60 * 1000,- freshness: 'active',- },- {- provider: 'gmail',- chunks_synced: 842,- chunks_pending: 0,- batch_total: 0,- batch_processed: 0,- last_chunk_at_ms: FIXED_NOW_MS - 2 * 60 * 60 * 1000,- freshness: 'idle',- },- ]);-- render(<MemoryTreeStatusPanel />);-- await waitFor(() => {- expect(screen.getByTestId('memory-tree-integrations')).toBeInTheDocument();- });-- const rows = screen.getAllByTestId(/^memory-tree-integration-row-/);- expect(rows).toHaveLength(2);-- const slackRow = screen.getByTestId('memory-tree-integration-row-slack');- expect(slackRow).toHaveTextContent(/slack/i);- expect(slackRow).toHaveTextContent(/Chunks: 5,231/);- expect(slackRow).toHaveTextContent(/Active/);-- const gmailRow = screen.getByTestId('memory-tree-integration-row-gmail');- expect(gmailRow).toHaveTextContent(/gmail/i);- expect(gmailRow).toHaveTextContent(/Stale/);- });-- it('falls back to the never label when last_chunk_at_ms is null', async () => {- mockPipelineStatus.mockResolvedValue(payload());- mockSyncStatusList.mockResolvedValue([- {- provider: 'slack',- chunks_synced: 0,- chunks_pending: 0,- batch_total: 0,- batch_processed: 0,- last_chunk_at_ms: null,- freshness: 'idle',- },- ]);-- render(<MemoryTreeStatusPanel />);-- await waitFor(() => {- expect(screen.getByTestId('memory-tree-integration-row-slack')).toBeInTheDocument();- });- expect(screen.getByTestId('memory-tree-integration-row-slack')).toHaveTextContent(/Never/);- });-- it('renders an empty list and logs a warn when memorySyncStatusList rejects', async () => {- mockPipelineStatus.mockResolvedValue(payload());- mockSyncStatusList.mockRejectedValue(new Error('boom'));- const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);-- render(<MemoryTreeStatusPanel />);-- // Tiles still render (pipeline succeeded) and the strip shows the empty state.- await waitFor(() => {- expect(screen.getByTestId('memory-tree-status-label')).toBeInTheDocument();- expect(screen.getByTestId('memory-tree-integrations-empty')).toBeInTheDocument();- });- expect(warn).toHaveBeenCalled();- warn.mockRestore();- });-- it('shows the empty state when there are no integrations', async () => {- mockPipelineStatus.mockResolvedValue(payload());- mockSyncStatusList.mockResolvedValue([]);-- render(<MemoryTreeStatusPanel />);-- await waitFor(() => {- expect(screen.getByTestId('memory-tree-integrations-empty')).toBeInTheDocument();- });- expect(screen.getByTestId('memory-tree-integrations-empty')).toHaveTextContent(- /no integrations connected/i- );- });-- it('renders the integration strip between the tile grid and the toggle row', async () => {- mockPipelineStatus.mockResolvedValue(payload());- mockSyncStatusList.mockResolvedValue([- {- provider: 'slack',- chunks_synced: 1,- chunks_pending: 0,- batch_total: 0,- batch_processed: 0,- last_chunk_at_ms: FIXED_NOW_MS - 1000,- freshness: 'active',- },- ]);-- render(<MemoryTreeStatusPanel />);-- await waitFor(() => {- expect(screen.getByTestId('memory-tree-integrations')).toBeInTheDocument();- });-- const panel = screen.getByTestId('memory-tree-status-panel');- const tiles = screen.getByTestId('memory-tree-status-tiles');- const strip = screen.getByTestId('memory-tree-integrations');- const toggle = screen.getByTestId('memory-tree-status-toggle-row');-- const order = Array.from(panel.querySelectorAll('[data-testid]'))- .map(el => el.getAttribute('data-testid'))- .filter(id =>- [- 'memory-tree-status-tiles',- 'memory-tree-integrations',- 'memory-tree-status-toggle-row',- ].includes(id ?? '')- );-- expect(order).toEqual([- 'memory-tree-status-tiles',- 'memory-tree-integrations',- 'memory-tree-status-toggle-row',- ]);- expect(tiles).toBeInTheDocument();- expect(strip).toBeInTheDocument();- expect(toggle).toBeInTheDocument();- });-- it('reports toggle errors via the onToast callback', async () => {- mockPipelineStatus.mockResolvedValueOnce(payload({ status: 'running', is_paused: false }));- mockSetEnabled.mockRejectedValueOnce(new Error('disk write failed'));- const onToast = vi.fn();-- render(<MemoryTreeStatusPanel onToast={onToast} />);- await waitFor(() => {- expect(screen.getByTestId('memory-tree-status-label')).toHaveTextContent(/running/i);- });-- fireEvent.click(screen.getByTestId('memory-tree-status-toggle'));- await waitFor(() => {- expect(onToast).toHaveBeenCalledWith(- expect.objectContaining({ type: 'error', message: 'disk write failed' })- );- });- });-- // ── #002 (T018): degraded status + first-blocking-cause banner ──────────-- it('renders the first-blocking-cause remediation banner with a degraded recall badge', async () => {- mockPipelineStatus.mockResolvedValueOnce(- payload({- status: 'degraded',- reason: 'semantic recall disabled',- first_blocking_cause: {- code: 'embeddings_unconfigured',- class: 'unrecoverable',- remediation_key: 'memory.health.remediation.embeddings_unconfigured',- },- degraded: { semantic_recall: true, structure: false },- })- );- render(<MemoryTreeStatusPanel />);-- await waitFor(() => {- expect(screen.getByTestId('memory-tree-status-label')).toHaveTextContent(/degraded/i);- });-- // The remediation text comes from the i18n key the core supplied.- const remediation = screen.getByTestId('memory-tree-blocking-cause-remediation');- expect(remediation).toHaveTextContent(/embeddings provider is configured/i);- // Recall badge present, structure badge absent.- expect(screen.getByTestId('memory-tree-badge-recall')).toBeInTheDocument();- expect(screen.queryByTestId('memory-tree-badge-structure')).not.toBeInTheDocument();- });-- it('shows the structure badge when only extraction is degraded', async () => {- mockPipelineStatus.mockResolvedValueOnce(- payload({- status: 'degraded',- first_blocking_cause: {- code: 'extraction_timeout',- class: 'unrecoverable',- remediation_key: 'memory.health.remediation.extraction_timeout',- },- degraded: { semantic_recall: false, structure: true },- })- );- render(<MemoryTreeStatusPanel />);-- await waitFor(() => {- expect(screen.getByTestId('memory-tree-blocking-cause')).toBeInTheDocument();- });- expect(screen.getByTestId('memory-tree-badge-structure')).toBeInTheDocument();- expect(screen.queryByTestId('memory-tree-badge-recall')).not.toBeInTheDocument();- expect(screen.getByTestId('memory-tree-blocking-cause-remediation')).toHaveTextContent(- /extraction model is timing out/i- );- });-- it('does not render the blocking-cause banner on a healthy pipeline', async () => {- mockPipelineStatus.mockResolvedValueOnce(payload({ status: 'running' }));- render(<MemoryTreeStatusPanel />);-- await waitFor(() => {- expect(screen.getByTestId('memory-tree-status-label')).toHaveTextContent(/running/i);- });- expect(screen.queryByTestId('memory-tree-blocking-cause')).not.toBeInTheDocument();- });-- // ── #5324: budget-exhausted state ───────────────────────────────────────-- /** A pipeline parked on a spent managed embedding budget. */- function budgetExhaustedPayload() {- return payload({- status: 'error',- reason: '936 unrecoverable failure(s) need action',- pipeline_jobs: { ready: 12, running: 0, failed: 936 },- first_blocking_cause: {- code: 'budget_exhausted',- class: 'unrecoverable',- remediation_key: 'memory.health.remediation.budget_exhausted',- },- });- }-- it('names the budget-exhausted state instead of a generic error', async () => {- mockPipelineStatus.mockResolvedValueOnce(budgetExhaustedPayload());- render(<MemoryTreeStatusPanel />);-- await waitFor(() => {- expect(screen.getByTestId('memory-tree-status-label')).toHaveTextContent(- /embedding budget reached/i- );- });- // "Error" alone told the user nothing they could act on.- expect(screen.getByTestId('memory-tree-status-label')).not.toHaveTextContent(/^Error$/);- });-- it('offers a one-click CTA to the embeddings configuration screen', async () => {- mockPipelineStatus.mockResolvedValueOnce(budgetExhaustedPayload());- render(<MemoryTreeStatusPanel />);-- const cta = await screen.findByTestId('memory-tree-budget-cta');- fireEvent.click(cta);- expect(mockNavigate).toHaveBeenCalledWith('/connections?tab=embeddings');- });-- it('escalates the budget cause out of this panel into the global error center', async () => {- // The whole point of the issue: a warning only visible inside this panel- // is a warning nobody sees.- mockPipelineStatus.mockResolvedValueOnce(budgetExhaustedPayload());- render(<MemoryTreeStatusPanel />);-- await waitFor(() => {- expect(mockDispatch).toHaveBeenCalled();- });- });-- it('keeps the paused label when the user paused a tree carrying an old budget failure', async () => {- // `first_blocking_cause` reports the most recent failed job regardless of- // why the pipeline is currently stopped. Relabelling a manually-paused- // tree would hide the real reason it is not running.- mockPipelineStatus.mockResolvedValueOnce(- payload({- status: 'paused',- is_paused: true,- reason: 'scheduler gate mode = off',- first_blocking_cause: {- code: 'budget_exhausted',- class: 'unrecoverable',- remediation_key: 'memory.health.remediation.budget_exhausted',- },- })- );- render(<MemoryTreeStatusPanel />);-- await waitFor(() => {- expect(screen.getByTestId('memory-tree-status-label')).toHaveTextContent(/paused/i);- });- expect(screen.getByTestId('memory-tree-status-label')).not.toHaveTextContent(- /embedding budget reached/i- );- });-- it('does not show the budget CTA for other blocking causes', async () => {- mockPipelineStatus.mockResolvedValueOnce(- payload({- status: 'error',- first_blocking_cause: {- code: 'embedding_dim_mismatch',- class: 'unrecoverable',- remediation_key: 'memory.health.remediation.embedding_dim_mismatch',- },- })- );- render(<MemoryTreeStatusPanel />);-- await waitFor(() => {- expect(screen.getByTestId('memory-tree-blocking-cause')).toBeInTheDocument();- });- expect(screen.queryByTestId('memory-tree-budget-cta')).not.toBeInTheDocument();- expect(screen.getByTestId('memory-tree-status-label')).toHaveTextContent(/error/i);- });-- it('handles the legacy degraded.cause payload shape (no first_blocking_cause)', async () => {- // Older/degraded-only payloads carry the cause on `degraded.cause` and omit- // `first_blocking_cause`. The label, CTA, and escalation must all key off- // the same resolved cause, so this shape must behave exactly like the- // `first_blocking_cause` one — not render the banner while silently- // dropping the budget label, CTA, and the global escalation.- mockPipelineStatus.mockResolvedValueOnce(- payload({- status: 'degraded',- reason: 'queue has not completed any job in 8h — memory is not growing',- degraded: {- semantic_recall: false,- structure: false,- cause: {- code: 'budget_exhausted',- class: 'unrecoverable',- remediation_key: 'memory.health.remediation.budget_exhausted',- },- },- })- );- render(<MemoryTreeStatusPanel />);-- // Named budget state, not a bare "degraded".- await waitFor(() => {- expect(screen.getByTestId('memory-tree-status-label')).toHaveTextContent(- /embedding budget reached/i- );- });- // CTA present…- expect(screen.getByTestId('memory-tree-budget-cta')).toBeInTheDocument();- // …and the cause still escalates out of this panel. Escalation runs from an- // effect after the status resolves, so wait for it rather than asserting- // synchronously (matches the `first_blocking_cause` escalation test above).- await waitFor(() => {- expect(mockDispatch).toHaveBeenCalled();- });- });-- // ── Retry-failed affordance ─────────────────────────────────────────────-- it('offers a retry when jobs are parked in failed', async () => {- mockPipelineStatus.mockResolvedValue(- payload({- status: 'error',- reason: '29 unrecoverable failure(s) need action',- pipeline_jobs: { ready: 0, running: 0, failed: 29 },- })- );- render(<MemoryTreeStatusPanel />);-- await waitFor(() => {- expect(screen.getByTestId('memory-tree-retry-failed')).toBeInTheDocument();- });- });-- /**- * The affordance keys off the failed-job counter, not off the blocking-cause- * banner. A failure the pipeline has already worked past no longer surfaces a- * remediation (the core withholds a superseded cause), but its rows still sit- * in `failed` and still need clearing — so the button must be reachable with- * no banner on screen. Without this the user is left in a permanent `error`- * state with no way out, which is the bug.- */- it('offers the retry even when no blocking cause is surfaced', async () => {- mockPipelineStatus.mockResolvedValue(- payload({- status: 'error',- reason: '29 unrecoverable failure(s) need action',- pipeline_jobs: { ready: 0, running: 0, failed: 29 },- first_blocking_cause: null,- })- );- render(<MemoryTreeStatusPanel />);-- await waitFor(() => {- expect(screen.getByTestId('memory-tree-retry-failed')).toBeInTheDocument();- });- expect(screen.queryByTestId('memory-tree-blocking-cause')).not.toBeInTheDocument();- });-- it('hides the retry when nothing has failed', async () => {- mockPipelineStatus.mockResolvedValue(payload({ status: 'running' }));- render(<MemoryTreeStatusPanel />);-- await waitFor(() => {- expect(screen.getByTestId('memory-tree-status-label')).toHaveTextContent(/running/i);- });- expect(screen.queryByTestId('memory-tree-retry-failed')).not.toBeInTheDocument();- });-- it('requeues the failed jobs, reports the count, and re-fetches', async () => {- mockPipelineStatus.mockResolvedValue(- payload({- status: 'error',- reason: '29 unrecoverable failure(s) need action',- pipeline_jobs: { ready: 0, running: 0, failed: 29 },- })- );- mockRetryFailed.mockResolvedValue({ requeued: 29 });- const onToast = vi.fn();- render(<MemoryTreeStatusPanel onToast={onToast} />);-- await waitFor(() => {- expect(screen.getByTestId('memory-tree-retry-failed')).toBeInTheDocument();- });- const callsBefore = mockPipelineStatus.mock.calls.length;- await act(async () => {- fireEvent.click(screen.getByTestId('memory-tree-retry-failed'));- });-- expect(mockRetryFailed).toHaveBeenCalledTimes(1);- // Successful domain outcome is tracked with the privacy-safe count only.- expect(mockTrackAnalyticsEvent).toHaveBeenCalledWith('memory_tree_retry_succeeded', {- count: 29,- });- await waitFor(() => {- expect(onToast).toHaveBeenCalledWith(- expect.objectContaining({ type: 'success', message: expect.stringContaining('29') })- );- });- // Successful domain outcome is tracked with a privacy-safe count only.- expect(mockTrackAnalyticsEvent).toHaveBeenCalledWith('memory_tree_retry_succeeded', {- count: 29,- });- await waitFor(() => {- expect(mockPipelineStatus.mock.calls.length).toBeGreaterThan(callsBefore);- });- });-- it('surfaces an error toast when the requeue fails', async () => {- mockPipelineStatus.mockResolvedValue(- payload({- status: 'error',- reason: '29 unrecoverable failure(s) need action',- pipeline_jobs: { ready: 0, running: 0, failed: 29 },- })- );- mockRetryFailed.mockRejectedValue(new Error('UNIQUE constraint failed'));- const onToast = vi.fn();- render(<MemoryTreeStatusPanel onToast={onToast} />);-- await waitFor(() => {- expect(screen.getByTestId('memory-tree-retry-failed')).toBeInTheDocument();- });- await act(async () => {- fireEvent.click(screen.getByTestId('memory-tree-retry-failed'));- });-- await waitFor(() => {- expect(onToast).toHaveBeenCalledWith(- expect.objectContaining({ type: 'error', message: 'UNIQUE constraint failed' })- );- });- // The button must stay usable so a transient failure is not a dead end.- expect(screen.getByTestId('memory-tree-retry-failed')).not.toBeDisabled();- });-- // -- stored-items tile ----------------------------------------------------- // The stored-document total rides the same poll as the pipeline status but- // comes from a different store, and it is fetched on a detached promise so a- // failure there must NOT wipe the panel. These pin both halves of that.-- it('renders the stored-items total from the namespace summaries', async () => {- mockPipelineStatus.mockResolvedValue(payload());- mockNamespaceSummaries.mockResolvedValue({- namespaces: [{ namespace: 'slack', count: 1500, last_updated: null }],- total_documents: 1500,- });-- render(<MemoryTreeStatusPanel />);-- await waitFor(() => {- expect(screen.getByTestId('memory-stored-items')).toHaveTextContent('1,500');- });- });-- it('keeps the panel alive and shows the placeholder when the summaries call fails', async () => {- // Detached-promise failure path: `storedItems` falls back to null, which- // renders the skeleton rather than a number. The pipeline status still- // resolved, so nothing else on the panel may degrade — in particular the- // panel-wide error must stay clear, because only a pipeline failure owns it.- mockPipelineStatus.mockResolvedValue(payload());- mockNamespaceSummaries.mockRejectedValue(new Error('namespace summaries down'));-- render(<MemoryTreeStatusPanel />);-- await waitFor(() => {- expect(screen.getByTestId('memory-tree-total-chunks')).toHaveTextContent('1,234');- });- expect(screen.queryByTestId('memory-stored-items')).not.toBeInTheDocument();- expect(screen.getByTestId('memory-tree-status-label')).toHaveTextContent(/running/i);- });-});--describe('integration health helpers', () => {- describe('classifyIntegration', () => {- it('maps active freshness to active', () => {- expect(classifyIntegration('active')).toBe('active');- });- it('maps recent freshness to stale', () => {- expect(classifyIntegration('recent')).toBe('stale');- });- it('maps idle freshness to stale', () => {- expect(classifyIntegration('idle')).toBe('stale');- });- });-- describe('providerIconChar', () => {- it('returns a known glyph for slack', () => {- expect(providerIconChar('slack')).toBe('💬');- });- it('returns a known glyph for gmail', () => {- expect(providerIconChar('gmail')).toBe('📧');- });- it('falls back to the plug glyph for unknown providers', () => {- expect(providerIconChar('definitely-not-a-real-provider')).toBe('🔌');- });- });-});diff --git a/app/src/components/intelligence/MemoryTreeStatusPanel.tsx b/app/src/components/intelligence/MemoryTreeStatusPanel.tsxdeleted file mode 100644index 986c102937..0000000000--- a/app/src/components/intelligence/MemoryTreeStatusPanel.tsx+++ /dev/null@@ -1,421 +0,0 @@-/**- * Memory Tree status panel — 4 stat tiles + on/off toggle.- *- * Replaces the temporary `useConsciousItems`-driven pill in- * `Intelligence.tsx`; addresses issue #1856 Part 1.- *- * The toggle writes `config.scheduler_gate.mode = "off"` via the- * `memory_tree_set_enabled` RPC and relies on the scheduler-gate- * hot-reload to pause all LLM-bound background work cooperatively.- * It does NOT pause the 20-min Composio fetch loop yet (#1856 Part 2- * follow-up).- *- * Polling cadence mirrors `useMemoryIngestionStatus`: 1.5s while- * syncing/active jobs, 4s otherwise — the same heuristic we use- * elsewhere so the dashboard feels lively without thrashing the- * core.- *- * Layout & color conventions copied verbatim from- * `MemoryStatsBar.tsx` (tiles) and the inline `ToggleRow` in- * `settings/panels/AIPanel.tsx` (switch markup).- */-import { useCallback, useEffect, useState } from 'react';-import { useNavigate } from 'react-router-dom';--import { useT } from '../../lib/i18n/I18nContext';-import { reportMemoryPipelineFailure, reportMemoryQuarantine } from '../../lib/userErrors/report';-import { useAppDispatch } from '../../store/hooks';-import type { ToastNotification } from '../../types/intelligence';-import { memoryTreeRetryFailed, memoryTreeSetEnabled } from '../../utils/tauriCommands';-import { trackAnalyticsEvent } from '../analytics';-import { Badge, Card } from '../ui';-import Button from '../ui/Button';-import Switch from '../ui/Switch';-import {- classifyIntegration,- formatBytes,- formatRelativeMs,- IntegrationHealthStrip,- providerIconChar,- statusDotClass,- useMemoryTreeStatus,-} from './memoryTreeStatusHelpers';--export { classifyIntegration, providerIconChar };--interface MemoryTreeStatusPanelProps {- onToast?: (toast: Omit<ToastNotification, 'id'>) => void;-}--/**- * Memory Tree status panel — render the four-tile dashboard plus the- * auto-sync toggle. Designed to mount above `<MemorySources>` in- * `MemoryWorkspace` so it surfaces in both the Intelligence page and- * Settings → Memory data without extra wiring.- */-export function MemoryTreeStatusPanel({ onToast }: MemoryTreeStatusPanelProps) {- const { t } = useT();- const navigate = useNavigate();- const dispatch = useAppDispatch();- const { status, storedItems, integrations, loading, error, refresh } = useMemoryTreeStatus();- const [toggleBusy, setToggleBusy] = useState(false);- const [retryBusy, setRetryBusy] = useState(false);-- // #002 (FR-004): the single first blocking cause. Prefer the explicit- // `first_blocking_cause`; fall back to the active degradation cause so older- // payload shapes still surface something actionable. Derived ONCE here so the- // escalation, the status label, the CTA, and the banner all key off the same- // cause — a payload that carries only `degraded.cause` (and no- // `first_blocking_cause`) must not render the banner one way while the- // escalation and budget label read a different, empty cause.- const blockingCause = status?.first_blocking_cause ?? status?.degraded?.cause ?? null;-- // #5324: this panel was the ONLY place a budget-exhausted memory pipeline- // was ever surfaced, so users who never opened it experienced weeks of- // silently broken memory. Escalate the typed cause into the shell-mounted- // UserErrorCenter, which stays visible across routes and after the panel- // unmounts. The store dedupes on descriptor id, so polling re-reports bump- // the recurrence count rather than stacking entries.- const blockingCauseCode = blockingCause?.code ?? null;- useEffect(() => {- reportMemoryPipelineFailure(dispatch, blockingCauseCode);- }, [dispatch, blockingCauseCode]);- // openhuman#5820: this panel polls faster than the shell, so a re-sync- // retires the quarantine notice as soon as the first chunk lands.- const quarantine = status?.quarantine ?? null;- const quarantineKey = quarantine- ? `${quarantine.quarantined_at_ms}:${quarantine.resynced}`- : null;- useEffect(() => {- reportMemoryQuarantine(dispatch, quarantine);- // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed on the fields that matter- }, [dispatch, quarantineKey]);-- const handleToggle = useCallback(async () => {- if (!status || toggleBusy) return;- const nextEnabled = status.is_paused; // currently paused ⇒ enable- console.debug('[ui-flow][memory-tree-status] toggle: entry next_enabled=%s', nextEnabled);- setToggleBusy(true);- try {- await memoryTreeSetEnabled(nextEnabled);- await refresh();- } catch (err) {- const message = err instanceof Error ? err.message : String(err);- console.warn('[ui-flow][memory-tree-status] toggle: error %s', message);- onToast?.({ type: 'error', title: t('memoryTree.status.toggleFailed'), message });- } finally {- setToggleBusy(false);- }- }, [status, toggleBusy, refresh, onToast, t]);-- /**- * Requeue every terminally-failed job.- *- * An unrecoverable failure (auth, budget, dimension mismatch) is terminal by- * design — the worker never retries it — so a batch that failed under a- * since-fixed config stays parked forever and pins this panel on `error`.- * The `memory_tree_retry_failed` RPC existed for exactly this, but had no- * caller anywhere in the app, leaving the user with a permanent error state- * and no way to clear it.- */- const handleRetryFailed = useCallback(async () => {- if (retryBusy) {- console.debug('[ui-flow][memory-tree-status] retryFailed: skipped busy=true');- return;- }- console.debug('[ui-flow][memory-tree-status] retryFailed: entry');- setRetryBusy(true);- console.debug('[ui-flow][memory-tree-status] retryFailed: busy=true rpc:start');- try {- const { requeued } = await memoryTreeRetryFailed();- console.debug('[ui-flow][memory-tree-status] retryFailed: rpc:ok requeued=%d', requeued);- // Record the successful domain outcome (not just the click). Privacy-safe:- // a non-identifying count only, no ids or user text.- trackAnalyticsEvent('memory_tree_retry_succeeded', { count: requeued });- onToast?.({- type: 'success',- title: t('memoryTree.status.retryFailedDone'),- message: t('memoryTree.status.retryFailedCount').replace('{count}', String(requeued)),- });- await refresh();- } catch (err) {- const message = err instanceof Error ? err.message : String(err);- console.warn('[ui-flow][memory-tree-status] retryFailed: error %s', message);- onToast?.({ type: 'error', title: t('memoryTree.status.retryFailedError'), message });- } finally {- console.debug('[ui-flow][memory-tree-status] retryFailed: busy=false exit');- setRetryBusy(false);- }- }, [retryBusy, refresh, onToast, t]);-- const statusKind = status?.status ?? 'idle';- // #5324: "Error — 936 unrecoverable failures need action" told the user- // nothing they could act on. When the blocking cause is a spent embedding- // budget, name that state exactly. Derived here rather than as a new wire- // status so older clients keep deserialising the payload unchanged and the- // existing `status` precedence rules stay untouched.- //- // Scoped to the states the budget actually explains. `first_blocking_cause`- // reports the most recent failed job even when the user has since paused the- // tree themselves, so without this guard a manually-paused tree carrying an- // old budget failure would be relabelled and hide the real reason it stopped.- const isBudgetExhausted =- blockingCause?.code === 'budget_exhausted' &&- (statusKind === 'error' || statusKind === 'degraded');- const statusLabel: string = (() => {- if (isBudgetExhausted) return t('memoryTree.status.statusBudgetExhausted');- switch (statusKind) {- case 'running':- return t('memoryTree.status.statusRunning');- case 'paused':- return t('memoryTree.status.statusPaused');- case 'syncing':- return t('memoryTree.status.statusSyncing');- case 'error':- return t('memoryTree.status.statusError');- case 'degraded':- return t('memoryTree.status.statusDegraded');- case 'idle':- default:- return t('memoryTree.status.statusIdle');- }- })();-- // `blockingCause` (derived above) is rendered verbatim in the banner below- // with a localized remediation.- const degraded = status?.degraded;-- // Parked failures are the one panel state the user can act on directly, and- // the affordance is keyed off the counter rather than off the blocking-cause- // banner: a failure the pipeline has already worked past no longer surfaces a- // remediation, but its rows still sit in `failed` and still need clearing.- const failedJobs = status?.pipeline_jobs.failed ?? 0;-- const checked = !(status?.is_paused ?? false);-- const labelClass = 'text-[11px] uppercase tracking-wide text-content-muted mb-1';- const valueClass = 'text-xl font-semibold text-content';- const skeletonClass = 'h-7 w-16 rounded bg-surface-strong animate-pulse';-- return (- <div className="space-y-3" data-testid="memory-tree-status-panel">- <div className="flex items-center justify-between">- <h2 className="text-sm font-semibold text-content">{t('memoryTree.status.title')}</h2>- </div>-- {error && !loading ? (- <div- role="alert"- className="flex items-center justify-between gap-3 rounded-lg border border-coral-200 dark:border-coral-500/30 bg-coral-50 dark:bg-coral-500/10 px-3 py-2 text-sm text-coral-700 dark:text-coral-300"- data-testid="memory-tree-status-error">- <span>{t('memoryTree.status.fetchError')}</span>- <Button- variant="secondary"- tone="danger"- size="xs"- onClick={() => {- void refresh();- }}>- {t('memoryTree.status.retry')}- </Button>- </div>- ) : null}-- {/* #002 (FR-004): actionable first-blocking-cause banner. Shown when the- core reports a typed cause — names the problem + the fix instead of a- generic "error". Degraded badges below distinguish recall vs structure. */}- {!loading && blockingCause ? (- <div- className="rounded-lg border border-amber-200 dark:border-amber-500/30 bg-amber-50 dark:bg-amber-500/10 px-3 py-2 text-sm text-amber-800 dark:text-amber-200"- data-testid="memory-tree-blocking-cause">- <div className="font-medium" data-testid="memory-tree-blocking-cause-remediation">- {t(blockingCause.remediation_key, t('memory.health.remediation.unknown'))}- </div>- {/* #5324: the remediation text names the fix ("set up local Ollama- embeddings or add your own key") but left the user to find that- screen themselves. One click, no embeddings knowledge required. */}- {isBudgetExhausted ? (- <div className="mt-2">- <Button- variant="secondary"- size="xs"- data-testid="memory-tree-budget-cta"- analyticsId="memory-tree-budget-configure-embeddings"- onClick={() => {- navigate('/connections?tab=embeddings');- }}>- {t('userErrors.action.openEmbeddingsSettings')}- </Button>- </div>- ) : null}- {degraded?.semantic_recall || degraded?.structure ? (- <div className="mt-1 flex flex-wrap gap-1.5" data-testid="memory-tree-degraded-badges">- {degraded?.semantic_recall ? (- <Badge variant="warning" data-testid="memory-tree-badge-recall">- {t('memoryTree.status.degradedRecall')}- </Badge>- ) : null}- {degraded?.structure ? (- <Badge variant="warning" data-testid="memory-tree-badge-structure">- {t('memoryTree.status.degradedStructure')}- </Badge>- ) : null}- </div>- ) : null}- </div>- ) : null}-- <div className="grid grid-cols-2 sm:grid-cols-4 gap-3" data-testid="memory-tree-status-tiles">- {/* Status tile ── color-coded pill */}- <Card- divided={false}- className="bg-surface-muted p-3 transition-colors hover:bg-surface-hover">- <div className={labelClass}>{t('memoryTree.status.statusTile')}</div>- {loading || !status ? (- <div className={skeletonClass} />- ) : (- <>- <div className="flex items-center gap-2">- <span- aria-hidden- className={`inline-block h-2 w-2 rounded-full ${statusDotClass(statusKind)}`}- />- <span className={valueClass} data-testid="memory-tree-status-label">- {statusLabel}- </span>- </div>- {status.reason ? (- <div className="mt-0.5 text-[11px] text-content-muted">{status.reason}</div>- ) : null}- {failedJobs > 0 ? (- <div className="mt-2">- <Button- variant="secondary"- size="xs"- disabled={retryBusy}- data-testid="memory-tree-retry-failed"- analyticsId="memory-tree-retry-failed-jobs"- onClick={() => {- void handleRetryFailed();- }}>- {retryBusy- ? t('memoryTree.status.retryFailedBusy')- : t('memoryTree.status.retryFailed')}- </Button>- </div>- ) : null}- </>- )}- </Card>-- {/* Last-sync tile */}- <Card- divided={false}- className="bg-surface-muted p-3 transition-colors hover:bg-surface-hover">- <div className={labelClass}>{t('memoryTree.status.lastSyncTile')}</div>- {loading || !status ? (- <div className={skeletonClass} />- ) : (- <div className={valueClass} data-testid="memory-tree-last-sync">- {formatRelativeMs(status.last_sync_ms, t, t('memoryTree.status.never'))}- </div>- )}- </Card>-- {/* Stored items tile — the document/search-index store, the number a- user checks after a sync. Distinct from the summary-tree leaves- tile beside it, which counts a different, much smaller store. */}- <Card- divided={false}- className="bg-surface-muted p-3 transition-colors hover:bg-surface-hover">- <div className={labelClass}>{t('memoryTree.status.storedItemsTile')}</div>- {storedItems === null ? (- <div className={skeletonClass} />- ) : (- <div className={valueClass} data-testid="memory-stored-items">- {new Intl.NumberFormat().format(storedItems)}- </div>- )}- </Card>-- {/* Total chunks tile */}- <Card- divided={false}- className="bg-surface-muted p-3 transition-colors hover:bg-surface-hover">- <div className={labelClass}>{t('memoryTree.status.totalChunksTile')}</div>- {loading || !status ? (- <div className={skeletonClass} />- ) : (- <div className={valueClass} data-testid="memory-tree-total-chunks">- {new Intl.NumberFormat().format(status.total_chunks)}- </div>- )}- </Card>-- {/* Wiki size tile */}- <Card- divided={false}- className="bg-surface-muted p-3 transition-colors hover:bg-surface-hover">- <div className={labelClass}>{t('memoryTree.status.wikiSizeTile')}</div>- {loading || !status ? (- <div className={skeletonClass} />- ) : (- <div className={valueClass} data-testid="memory-tree-wiki-size">- {formatBytes(status.wiki_size_bytes)}- </div>- )}- </Card>- </div>-- {/* #002 (FR-010 / US5): extraction coverage. Only meaningful once chunks- exist; near-0% with chunks present means the wiki is built but has no- structure (the extraction model is failing). */}- {!loading && status && status.total_chunks > 0 && status.extraction_coverage != null ? (- <div className="text-xs text-content-muted" data-testid="memory-tree-extraction-coverage">- {t('memoryTree.status.extractionCoverage').replace(- '{pct}',- String(Math.round((status.extraction_coverage ?? 0) * 100))- )}- </div>- ) : null}-- {/* openhuman#6257: the memory-tree job queue a sync feeds. `ready` is the- queue the Sources rows' "Processing into memory" stage and the retry- toast refer to; nothing on this tab showed it before. */}- {!loading && status ? (- <div className="text-xs text-content-muted" data-testid="memory-tree-job-queue">- {t('memoryTree.status.jobQueue')- .replace('{ready}', new Intl.NumberFormat().format(status.pipeline_jobs.ready))- .replace('{running}', new Intl.NumberFormat().format(status.pipeline_jobs.running))- .replace('{failed}', new Intl.NumberFormat().format(status.pipeline_jobs.failed))}- </div>- ) : null}-- <IntegrationHealthStrip integrations={integrations} loading={loading} t={t} />-- {/* Auto-sync toggle row — markup mirrors AIPanel's inline ToggleRow */}- <div- className="flex items-center justify-between gap-3 rounded-lg border border-line bg-surface px-3 py-2"- data-testid="memory-tree-status-toggle-row">- <div className="min-w-0">- <div className="text-sm font-medium text-content">- {t('memoryTree.status.autoSyncLabel')}- </div>- <div className="text-xs text-content-muted">- {t('memoryTree.status.autoSyncDescription')}- </div>- </div>- <Switch- id="memory-tree-status-toggle"- aria-label={t('memoryTree.status.autoSyncLabel')}- checked={checked}- disabled={toggleBusy || loading || !status}- onCheckedChange={() => {- void handleToggle();- }}- data-testid="memory-tree-status-toggle"- />- </div>- </div>- );-}diff --git a/app/src/components/intelligence/MemoryWorkspace.test.tsx b/app/src/components/intelligence/MemoryWorkspace.test.tsxdeleted file mode 100644index 45b4fa331e..0000000000--- a/app/src/components/intelligence/MemoryWorkspace.test.tsx+++ /dev/null@@ -1,67 +0,0 @@-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { memoryTreeGraphExport } from '../../utils/tauriCommands';-import { MemoryWorkspace } from './MemoryWorkspace';--// Stub the i18n hook and the heavy child panels so the test renders just the-// MemoryWorkspace shell (graph fetch effect + the refresh control + poll).-vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));-vi.mock('./MemoryGraph', () => ({ MemoryGraph: () => null }));-vi.mock('./MemorySourcesRegistry', () => ({ MemorySourcesRegistry: () => null }));-vi.mock('./MemoryTreeStatusPanel', () => ({ MemoryTreeStatusPanel: () => null }));-vi.mock('./ObsidianVaultSection', () => ({ ObsidianVaultSection: () => null }));-vi.mock('../../utils/tauriCommands', () => ({- memoryTreeGraphExport: vi.fn().mockResolvedValue({ nodes: [], edges: [] }),- memoryTreeFlushNow: vi.fn().mockResolvedValue(undefined),- memoryTreeResetTree: vi.fn().mockResolvedValue(undefined),- memoryTreeWipeAll: vi.fn().mockResolvedValue(undefined),-}));--const graphExportMock = vi.mocked(memoryTreeGraphExport);--describe('<MemoryWorkspace />', () => {- beforeEach(() => {- graphExportMock.mockClear();- });- afterEach(() => {- vi.useRealTimers();- });-- it('re-exports the graph when the refresh button is clicked', async () => {- render(<MemoryWorkspace />);- // Mount runs the initial graph load.- await waitFor(() => expect(graphExportMock).toHaveBeenCalledTimes(1));-- fireEvent.click(screen.getByTestId('memory-graph-refresh'));-- // Bumping graphVersion re-runs the load effect.- await waitFor(() => expect(graphExportMock).toHaveBeenCalledTimes(2));- });-- it('polls the graph on a 30s tick, and skips the tick while the tab is hidden', async () => {- vi.useFakeTimers();- render(<MemoryWorkspace />);- // Flush the mount-time async load under fake timers.- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- const afterMount = graphExportMock.mock.calls.length;-- // Visible tab → the 30s tick re-pulls the graph.- await act(async () => {- await vi.advanceTimersByTimeAsync(30_000);- });- expect(graphExportMock.mock.calls.length).toBeGreaterThan(afterMount);-- // Backgrounded tab → the tick is skipped (no extra RPC churn).- const hiddenSpy = vi.spyOn(document, 'hidden', 'get').mockReturnValue(true);- const afterVisible = graphExportMock.mock.calls.length;- await act(async () => {- await vi.advanceTimersByTimeAsync(30_000);- });- expect(graphExportMock.mock.calls.length).toBe(afterVisible);-- hiddenSpy.mockRestore();- });-});diff --git a/app/src/components/intelligence/MemoryWorkspace.tsx b/app/src/components/intelligence/MemoryWorkspace.tsxdeleted file mode 100644index 299871eba6..0000000000--- a/app/src/components/intelligence/MemoryWorkspace.tsx+++ /dev/null@@ -1,145 +0,0 @@-/**- * Obsidian-style graph view for the memory tree, plus controls to drive- * the ingestion pipeline manually.- *- * ┌───────────────────────────────────────────────────────┐- * │ MemoryTreeStatusPanel (chunk counts + freshness) │- * └───────────────────────────────────────────────────────┘- * ┌───────────────────────────────────────────────────────┐- * │ MemorySourcesRegistry — unified source list │- * │ (Composio + folder + GitHub + RSS + web · per-row │- * │ Sync button, status chip, chunk count, freshness) │- * └───────────────────────────────────────────────────────┘- * ┌───────────────────────────────────────────────────────┐- * │ ModeToggle · Reset Memory · Reset Tree · Build Trees │- * │ [ View vault in Obsidian ] (shown when vault set) │- * └───────────────────────────────────────────────────────┘- * ┌───────────────────────────────────────────────────────┐- * │ Force-directed summary graph (SVG) │- * └───────────────────────────────────────────────────────┘- *- * `MemorySourcesRegistry` replaces the old Composio-only `MemorySources`- * panel. It auto-seeds active Composio connections as sources and lets- * users add folder, GitHub repo, RSS, and web-page sources via the- * Add Source dialog.- *- * `Build summary trees` calls `memory_tree.flush_now` which enqueues a- * `flush_stale` job with `max_age_secs=0` so every L0 buffer- * force-seals immediately. The seal worker runs each through the- * configured cloud or local LLM and the new summary nodes appear in- * the graph after the worker drains.- */-import { useEffect, useState } from 'react';--import { useT } from '../../lib/i18n/I18nContext';-import type { ToastNotification } from '../../types/intelligence';-import {- type GraphExportResponse,- type GraphMode,- memoryTreeGraphExport,-} from '../../utils/tauriCommands';-import { MemoryControls } from './MemoryControls';-import { MemoryGraph } from './MemoryGraph';-import { MemorySourcesRegistry } from './MemorySourcesRegistry';-import { MemoryTreeStatusPanel } from './MemoryTreeStatusPanel';--interface MemoryWorkspaceProps {- onToast?: (toast: Omit<ToastNotification, 'id'>) => void;-}--export function MemoryWorkspace({ onToast }: MemoryWorkspaceProps) {- const { t } = useT();- const [graph, setGraph] = useState<GraphExportResponse | null>(null);- const [error, setError] = useState<string | null>(null);- const [mode, setMode] = useState<GraphMode>('tree');-- const [graphVersion, setGraphVersion] = useState(0);-- // (Re)load the graph whenever the mode toggle flips or tree events arrive.- useEffect(() => {- console.debug('[ui-flow][memory-workspace] graph load: entry mode=%s v=%d', mode, graphVersion);- let cancelled = false;- setError(null);- void (async () => {- try {- const resp = await memoryTreeGraphExport(mode);- if (cancelled) return;- console.debug(- '[ui-flow][memory-workspace] graph load: exit mode=%s n=%d edges=%d',- mode,- resp.nodes.length,- resp.edges.length- );- setGraph(resp);- } catch (err) {- if (cancelled) return;- console.error('[ui-flow][memory-workspace] graph load failed', err);- setError(err instanceof Error ? err.message : String(err));- }- })();- return () => {- cancelled = true;- };- }, [mode, graphVersion]);-- useEffect(() => {- const onTreeDone = () => {- setTimeout(() => setGraphVersion(v => v + 1), 2000);- };- const onSyncDone = (e: Event) => {- const data = (e as CustomEvent).detail as { stage?: string } | null;- if (data?.stage === 'completed') {- setTimeout(() => setGraphVersion(v => v + 1), 3000);- }- };- window.addEventListener('openhuman:memory-tree-completed', onTreeDone);- window.addEventListener('openhuman:memory-sync-stage', onSyncDone);- return () => {- window.removeEventListener('openhuman:memory-tree-completed', onTreeDone);- window.removeEventListener('openhuman:memory-sync-stage', onSyncDone);- };- }, []);-- // Live refresh: re-pull the graph every 30s while this tab is mounted so it- // reflects background tree growth (e.g. seal_document jobs draining as- // Notion syncs) without a manual refresh. The Memory tab unmounts this- // component when inactive, which clears the interval — so the poll only runs- // while the tab is actually open. Ticks are skipped while the window is- // backgrounded to avoid needless RPC churn; the next visible tick catches up.- useEffect(() => {- const GRAPH_POLL_MS = 30_000;- const id = setInterval(() => {- if (typeof document !== 'undefined' && document.hidden) return;- console.debug('[ui-flow][memory-workspace] graph poll tick → bump version');- setGraphVersion(v => v + 1);- }, GRAPH_POLL_MS);- return () => clearInterval(id);- }, []);-- return (- <div className="space-y-4" data-testid="memory-workspace">- <MemoryTreeStatusPanel onToast={onToast} />- <MemorySourcesRegistry onToast={onToast} />-- <MemoryControls- mode={mode}- onModeChange={setMode}- onRefresh={() => setGraphVersion(v => v + 1)}- onToast={onToast}- contentRootAbs={graph?.content_root_abs}- />-- {error ? (- <div className="rounded-lg border border-coral-200 dark:border-coral-500/30 bg-coral-50 dark:bg-coral-500/10 px-4 py-3 text-sm text-coral-800">- {t('workspace.graphLoadFailed')}: {error}- </div>- ) : !graph ? (- <div className="flex h-[640px] items-center justify-center rounded-lg border border-line-subtle bg-surface-muted/40 text-sm text-content-muted">- {t('workspace.loadingGraph')}- </div>- ) : (- <MemoryGraph nodes={graph.nodes} edges={graph.edges} mode={mode} />- )}- </div>- );-}diff --git a/app/src/components/intelligence/ObsidianVaultSection.test.tsx b/app/src/components/intelligence/ObsidianVaultSection.test.tsxdeleted file mode 100644index c08aba6935..0000000000--- a/app/src/components/intelligence/ObsidianVaultSection.test.tsx+++ /dev/null@@ -1,77 +0,0 @@-/**- * Tests for the cross-host guard (#4278) in ObsidianVaultSection: when the- * vault lives on a different-OS core host, "View Vault" must surface guidance- * and disable the local-FS actions instead of firing a doomed deep link.- */-import { fireEvent, screen, waitFor } from '@testing-library/react';-import { describe, expect, it, type Mock, vi } from 'vitest';--import { renderWithProviders } from '../../test/test-utils';-import { ObsidianVaultSection } from './ObsidianVaultSection';--vi.mock('../../utils/tauriCommands', () => ({ memoryTreeObsidianVaultStatus: vi.fn() }));--vi.mock('../../utils/tauriCommands/workspacePaths', () => ({- resolveWorkspaceAbsolutePath: vi.fn().mockResolvedValue('/home/leigh/OHvault'),- revealWorkspacePath: vi.fn().mockResolvedValue(undefined),-}));--vi.mock('../../utils/openUrl', () => ({ openUrl: vi.fn().mockResolvedValue(undefined) }));--vi.mock('./vaultHostMatch', () => ({- resolveVaultHostMatch: vi.fn().mockResolvedValue({ local: true }),-}));--const { memoryTreeObsidianVaultStatus } =- (await import('../../utils/tauriCommands')) as unknown as { memoryTreeObsidianVaultStatus: Mock };--const { openUrl } = (await import('../../utils/openUrl')) as unknown as { openUrl: Mock };--const { resolveVaultHostMatch } = (await import('./vaultHostMatch')) as unknown as {- resolveVaultHostMatch: Mock;-};--const CONTENT_ROOT = '/home/leigh/OHvault';--describe('<ObsidianVaultSection /> cross-host (#4278)', () => {- it('surfaces guidance and disables local actions when the vault is on a different-OS core host', async () => {- memoryTreeObsidianVaultStatus.mockResolvedValueOnce({- registered: true,- config_found: true,- content_root_abs: CONTENT_ROOT,- host_os: 'linux',- });- resolveVaultHostMatch.mockResolvedValueOnce({ local: false, hostOs: 'linux' });-- renderWithProviders(<ObsidianVaultSection contentRootAbs={CONTENT_ROOT} />);- fireEvent.click(screen.getByTestId('memory-open-in-obsidian'));-- await waitFor(() => {- expect(screen.getByTestId('obsidian-vault-guidance')).toBeInTheDocument();- });- expect(screen.getByTestId('obsidian-vault-guidance')).toHaveTextContent('linux');- expect(screen.getByTestId('obsidian-reveal')).toBeDisabled();- expect(screen.getByTestId('obsidian-open-anyway')).toBeDisabled();- // Registered=true would normally fire the deep link; cross-host must NOT.- expect(openUrl).not.toHaveBeenCalled();- });-- it('fires the deep link normally for a same-host registered vault (regression)', async () => {- memoryTreeObsidianVaultStatus.mockResolvedValueOnce({- registered: true,- config_found: true,- content_root_abs: CONTENT_ROOT,- host_os: 'macos',- });- resolveVaultHostMatch.mockResolvedValueOnce({ local: true, hostOs: 'macos' });-- renderWithProviders(<ObsidianVaultSection contentRootAbs={CONTENT_ROOT} />);- fireEvent.click(screen.getByTestId('memory-open-in-obsidian'));-- await waitFor(() => {- expect(openUrl).toHaveBeenCalledWith(- 'obsidian://open?path=' + encodeURIComponent(CONTENT_ROOT)- );- });- });-});diff --git a/app/src/components/intelligence/ObsidianVaultSection.tsx b/app/src/components/intelligence/ObsidianVaultSection.tsxdeleted file mode 100644index 7379fe3d28..0000000000--- a/app/src/components/intelligence/ObsidianVaultSection.tsx+++ /dev/null@@ -1,404 +0,0 @@-/**- * Inline "open your memory vault in Obsidian" control for the Memory tab.- *- * The vault is the on-disk `<workspace>/memory_tree/content/` folder. Opening- * it uses an `obsidian://open?path=…` deep link — but that scheme only- * resolves folders Obsidian has already registered as a vault (it cannot- * register one, and a `.obsidian/` folder on disk is not enough). So a- * first-time click would otherwise land on Obsidian's *"Unable to find a vault- * for the URL"* error.- *- * Flow (progressive disclosure):- * - Click → check registration via `memory_tree_obsidian_vault_status`.- * - Registered → fire the deep link (success toast). Done.- * - Not registered → expand inline guidance instead of firing a doomed link:- * Reveal Folder · Open anyway · Install Obsidian · Advanced ▸ config-dir- * override.- *- * Detection is best-effort — Obsidian can live somewhere we can't probe- * (Flatpak/Snap/portable). "Open anyway" and the config-dir override are the- * escape hatches for that case; a false "not registered" never blocks the user.- */-import { useCallback, useRef, useState } from 'react';--import { useT } from '../../lib/i18n/I18nContext';-import type { ToastNotification } from '../../types/intelligence';-import { openUrl } from '../../utils/openUrl';-import { memoryTreeObsidianVaultStatus } from '../../utils/tauriCommands';-import {- resolveWorkspaceAbsolutePath,- revealWorkspacePath,-} from '../../utils/tauriCommands/workspacePaths';-import Button from '../ui/Button';-import { PopoverAnchor, PopoverClose, PopoverContent, PopoverRoot } from '../ui/Popover';-import TextField from '../ui/TextField';-import { MEMORY_CONTENT_WORKSPACE_PATH } from './memoryWorkspacePaths';-import { resolveVaultHostMatch } from './vaultHostMatch';--/** localStorage key for the optional Obsidian config-dir override. */-const CONFIG_DIR_KEY = 'openhuman.obsidian.configDir';-const OBSIDIAN_DOWNLOAD_URL = 'https://obsidian.md/download';--interface ObsidianVaultSectionProps {- /** Absolute path to `<workspace>/memory_tree/content/` (from graph export). */- contentRootAbs: string;- onToast?: (toast: Omit<ToastNotification, 'id'>) => void;-}--function readConfigDirOverride(): string {- try {- return localStorage.getItem(CONFIG_DIR_KEY) ?? '';- } catch {- return '';- }-}--export function ObsidianVaultSection({ contentRootAbs, onToast }: ObsidianVaultSectionProps) {- const { t } = useT();- const [checking, setChecking] = useState(false);- const [expanded, setExpanded] = useState(false);- // null = not probed yet / probe failed; otherwise last `config_found`.- const [configFound, setConfigFound] = useState<boolean | null>(null);- const [showAdvanced, setShowAdvanced] = useState(false);- const [configDir, setConfigDir] = useState<string>(readConfigDirOverride);- // #4278: set to the core host OS when the vault lives on a different-OS core- // host, so local actions (Reveal / Open in Obsidian) are disabled + explained.- const [crossHostOs, setCrossHostOs] = useState<string | null>(null);- // Anchors the popover to the View Vault button. The outside-click guard- // (onPointerDownOutside below) uses this to recognize a re-click on the- // trigger as "inside" rather than "outside" — see the PopoverAnchor comment- // near the render for why a plain PopoverTrigger doesn't work here.- const anchorRef = useRef<HTMLButtonElement>(null);-- /**- * Build + fire the `obsidian://` deep link.- *- * The absolute path is resolved through the shared workspace-link layer- * (`resolve_workspace_absolute_path` Tauri command) rather than reused from- * the `contentRootAbs` prop — this routes Obsidian deep links through the- * same canonicalize + workspace-containment guard as `open_workspace_path`- * and `preview_workspace_text` (see issue #2492 / #2476).- *- * Resolves to an error or null.- */- const fireDeepLink = useCallback(async (): Promise<unknown | null> => {- console.debug('[ui-flow][obsidian-vault] firing deep link');- try {- const absolutePath = await resolveWorkspaceAbsolutePath(MEMORY_CONTENT_WORKSPACE_PATH);- const url = `obsidian://open?path=${encodeURIComponent(absolutePath)}`;- await openUrl(url);- return null;- } catch (err) {- console.error('[ui-flow][obsidian-vault] resolve/open failed', err);- return err;- }- }, []);-- const reveal = useCallback(() => {- void (async () => {- try {- await revealWorkspacePath(MEMORY_CONTENT_WORKSPACE_PATH);- } catch (err) {- console.error('[ui-flow][obsidian-vault] revealWorkspacePath failed', err);- onToast?.({- type: 'error',- title: t('workspace.revealVaultFailed'),- message: err instanceof Error ? err.message : String(err),- });- }- })();- }, [onToast, t]);-- const toastOpenOutcome = useCallback(- (err: unknown | null) => {- onToast?.(- err === null- ? {- type: 'info',- title: t('workspace.openingVaultTitle'),- message: `${t('workspace.openingVaultMessage')} ${contentRootAbs}`,- action: { label: t('workspace.revealFolder'), handler: reveal },- }- : {- type: 'error',- title: t('workspace.openVaultFailedTitle'),- message: `${t('workspace.openVaultFailedMessage')} ${contentRootAbs}`,- action: { label: t('workspace.revealFolder'), handler: reveal },- }- );- },- [onToast, t, contentRootAbs, reveal]- );-- /** Fire the deep link unconditionally — the "Open anyway" escape hatch. */- const openAnyway = useCallback(() => {- void (async () => {- toastOpenOutcome(await fireDeepLink());- })();- }, [fireDeepLink, toastOpenOutcome]);-- const installObsidian = useCallback(() => {- // https URL → openUrl falls back to window.open if the IPC bridge isn't- // ready, so this normally reaches the download page. Swallow + log any- // rejection so it can't surface as an unhandled promise rejection.- void (async () => {- try {- await openUrl(OBSIDIAN_DOWNLOAD_URL);- } catch (err) {- console.error('[ui-flow][obsidian-vault] openUrl(download) failed', err);- }- })();- }, []);-- const handleViewVault = useCallback(() => {- void (async () => {- setChecking(true);- try {- const override = configDir.trim();- const status = await memoryTreeObsidianVaultStatus(override || undefined);- console.debug(- '[ui-flow][obsidian-vault] status registered=%s config_found=%s host_os=%s',- status.registered,- status.config_found,- status.host_os- );-- // #4278: when the vault lives on a core host running a different OS, the- // path is not local — guide instead of firing a doomed deep link / reveal.- const match = await resolveVaultHostMatch(status.host_os);- if (!match.local) {- console.debug('[ui-flow][obsidian-vault] cross-host vault host_os=%s', match.hostOs);- setCrossHostOs(match.hostOs ?? status.host_os ?? '');- setConfigFound(status.config_found);- setExpanded(true);- return;- }- setCrossHostOs(null);- setConfigFound(status.config_found);-- if (status.registered) {- // Known vault — open it directly.- const err = await fireDeepLink();- toastOpenOutcome(err);- // Registered but the IPC/scheme still failed → surface guidance;- // on success collapse any stale panel from a prior failed check.- setExpanded(err !== null);- return;- }-- // Not registered — guide the user instead of firing a doomed link.- setExpanded(true);- } catch (err) {- // Detection itself failed — degrade gracefully to the guidance panel.- console.error('[ui-flow][obsidian-vault] status check failed', err);- setConfigFound(null);- setExpanded(true);- } finally {- setChecking(false);- }- })();- }, [configDir, fireDeepLink, toastOpenOutcome]);-- const saveConfigDir = useCallback(() => {- const trimmed = configDir.trim();- try {- if (trimmed) localStorage.setItem(CONFIG_DIR_KEY, trimmed);- else localStorage.removeItem(CONFIG_DIR_KEY);- } catch (err) {- console.warn('[ui-flow][obsidian-vault] persist config dir failed', err);- }- // Re-run the check with the new override applied.- handleViewVault();- }, [configDir, handleViewVault]);-- const helpText = crossHostOs- ? `${t('crossHostVault.title')} ${t('crossHostVault.message').replace('{os}', crossHostOs)}`- : configFound === false- ? t('workspace.obsidianNotFoundHelp')- : t('workspace.vaultNotRegisteredHelp');-- // The guidance panel is a Radix Popover anchored to the button (out of- // normal flow) rather than an inline sibling. This component lives inside- // the horizontal MemoryControls toolbar; an in-flow `w-full`/wide panel- // would grow this flex item and force the whole toolbar to wrap/misalign- // (issue #4266). Taking the panel out of flow keeps the toolbar row stable- // regardless of the panel's visibility.- //- // `PopoverAnchor` (not `PopoverTrigger`) is deliberate: Radix's Trigger- // toggles the popover closed on a second click, which would contradict the- // on-screen "click View Vault again" copy above — a re-click on the button- // must always re-run `handleViewVault`'s check, never just dismiss. Driving- // `open`/`onOpenChange` ourselves keeps that behavior while still getting- // Radix's outside-click, Escape, focus-return and viewport-collision- // handling for free.- return (- <div className="relative inline-flex" data-testid="obsidian-vault-section">- <PopoverRoot open={expanded} onOpenChange={setExpanded}>- <PopoverAnchor asChild>- <Button- ref={anchorRef}- variant="secondary"- size="sm"- onClick={handleViewVault}- disabled={checking}- data-testid="memory-open-in-obsidian"- title={`obsidian://open?path=${contentRootAbs}`}- leadingIcon={<ExternalLinkIcon />}>- {checking ? t('workspace.checkingVault') : t('workspace.viewVault')}- </Button>- </PopoverAnchor>-- <PopoverContent- data-testid="obsidian-vault-guidance"- align="end"- sideOffset={8}- onEscapeKeyDown={() => {- console.debug('[ui-flow][obsidian-vault] dismiss: escape');- }}- onPointerDownOutside={event => {- // A click back on the trigger button re-runs handleViewVault's- // check (see the anchor comment above) rather than dismissing —- // without this guard Radix would treat that click as "outside"- // and close the panel in the same tick handleViewVault reopens- // it, causing a flicker or a stuck-closed panel.- if (anchorRef.current && anchorRef.current.contains(event.target as Node)) {- event.preventDefault();- return;- }- console.debug('[ui-flow][obsidian-vault] dismiss: outside click');- }}- className="absolute right-0 top-full z-20 mt-2 w-xl max-w-[calc(100vw-2rem)]- rounded-lg border border-primary-200 bg-primary-50 p-4 pr-10 text-sm shadow-xl- dark:border-primary-500/30 dark:bg-primary-950">- <PopoverClose asChild>- <Button- variant="tertiary"- size="sm"- iconOnly- data-testid="obsidian-vault-close"- aria-label={t('common.close')}- className="absolute right-2 top-2 h-auto w-auto p-1 hover:bg-primary-100- dark:hover:bg-primary-500/20">- <CloseIcon />- </Button>- </PopoverClose>- <p className="text-content-secondary">{helpText}</p>-- <code- className="mt-2 block break-all rounded bg-surface/70 px-2 py-1 font-mono text-xs- text-content-secondary dark:bg-surface/60"- data-testid="obsidian-vault-path">- {contentRootAbs}- </code>-- <div className="mt-3 flex flex-wrap gap-2">- <Button- variant="secondary"- size="sm"- onClick={reveal}- disabled={crossHostOs !== null}- data-testid="obsidian-reveal">- {t('workspace.revealFolder')}- </Button>- <Button- variant="secondary"- size="sm"- onClick={openAnyway}- disabled={crossHostOs !== null}- data-testid="obsidian-open-anyway"- className="border-primary-300 text-primary-700 hover:bg-primary-100 dark:border-primary-500/40- dark:text-primary-300">- {t('workspace.openAnyway')}- </Button>- <Button- variant="secondary"- size="sm"- onClick={installObsidian}- data-testid="obsidian-install">- {t('workspace.installObsidian')}- </Button>- </div>-- <Button- variant="tertiary"- size="sm"- onClick={() => setShowAdvanced(v => !v)}- data-testid="obsidian-advanced-toggle"- className="mt-3 h-auto p-0 font-medium text-primary-600 hover:underline hover:bg-transparent dark:text-primary-300">- {t('workspace.obsidianAdvanced')}- </Button>-- {showAdvanced && (- <div className="mt-2 space-y-1.5">- <label- htmlFor="obsidian-config-dir"- className="block text-xs font-medium text-content-secondary">- {t('workspace.obsidianConfigDirLabel')}- </label>- <div className="flex flex-wrap items-center gap-2">- <TextField- id="obsidian-config-dir"- type="text"- inputSize="sm"- mono- value={configDir}- onChange={e => setConfigDir(e.target.value)}- placeholder={t('workspace.obsidianConfigDirPlaceholder')}- spellCheck={false}- data-testid="obsidian-config-dir-input"- className="flex-1"- />- <Button- variant="primary"- size="sm"- onClick={saveConfigDir}- disabled={checking}- data-testid="obsidian-config-dir-save">- {t('common.save')}- </Button>- </div>- <p className="text-xs text-content-muted">{t('workspace.obsidianConfigDirHint')}</p>- </div>- )}- </PopoverContent>- </PopoverRoot>- </div>- );-}--function CloseIcon() {- return (- <svg- width="14"- height="14"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- strokeLinecap="round"- strokeLinejoin="round"- aria-hidden="true">- <path d="M18 6L6 18" />- <path d="M6 6l12 12" />- </svg>- );-}--function ExternalLinkIcon() {- return (- <svg- width="14"- height="14"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="1.8"- strokeLinecap="round"- strokeLinejoin="round"- aria-hidden="true">- <path d="M14 3h7v7" />- <path d="M10 14L21 3" />- <path d="M21 14v7H3V3h7" />- </svg>- );-}diff --git a/app/src/components/intelligence/PixiGraph.test.tsx b/app/src/components/intelligence/PixiGraph.test.tsxdeleted file mode 100644index cf838dc86a..0000000000--- a/app/src/components/intelligence/PixiGraph.test.tsx+++ /dev/null@@ -1,94 +0,0 @@-import { act, render, waitFor } from '@testing-library/react';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import type { GraphNode } from '../../utils/tauriCommands';-import { PixiGraph } from './PixiGraph';--const mocks = vi.hoisted(() => ({ mountPixiGraph: vi.fn() }));--vi.mock('./pixiGraphRenderer', () => ({- mountPixiGraph: (...args: unknown[]) => mocks.mountPixiGraph(...args),-}));--const NODES: GraphNode[] = [- { kind: 'summary', id: 'root', label: 'R', level: 0, parent_id: null },- { kind: 'chunk', id: 'leaf', label: 'L', parent_id: 'root' },-];--describe('<PixiGraph />', () => {- beforeEach(() => mocks.mountPixiGraph.mockReset());- afterEach(() => vi.restoreAllMocks());-- it('mounts the renderer with built graph data', async () => {- const handle = { resetView: vi.fn(), setTheme: vi.fn(), destroy: vi.fn() };- mocks.mountPixiGraph.mockResolvedValue(handle);- const { getByTestId } = render(- <PixiGraph- nodes={NODES}- edges={[]}- mode="tree"- dark={false}- resetSignal={0}- onHover={vi.fn()}- onOpen={vi.fn()}- />- );- const host = getByTestId('memory-graph-canvas');- expect(host).toHaveAttribute('data-render-ready', 'false');- await waitFor(() => expect(mocks.mountPixiGraph).toHaveBeenCalledTimes(1));- const [, opts] = mocks.mountPixiGraph.mock.calls[0] as [- HTMLElement,- { simNodes: unknown[]; links: unknown[]; onReady: () => void },- ];- expect(opts.simNodes).toHaveLength(3); // 2 data nodes + synthetic root hub- expect(opts.links).toHaveLength(1); // leaf -> root- act(() => opts.onReady());- expect(host).toHaveAttribute('data-render-ready', 'true');- });-- it('destroys the renderer on unmount', async () => {- const handle = { resetView: vi.fn(), setTheme: vi.fn(), destroy: vi.fn() };- mocks.mountPixiGraph.mockResolvedValue(handle);- const { unmount } = render(- <PixiGraph- nodes={NODES}- edges={[]}- mode="tree"- dark={false}- resetSignal={0}- onHover={vi.fn()}- onOpen={vi.fn()}- />- );- await waitFor(() => expect(mocks.mountPixiGraph).toHaveBeenCalled());- unmount();- await waitFor(() => expect(handle.destroy).toHaveBeenCalled());- });-- it('ignores renderer readiness after cleanup', async () => {- const handle = { resetView: vi.fn(), setTheme: vi.fn(), destroy: vi.fn() };- const onReady = vi.fn();- mocks.mountPixiGraph.mockResolvedValue(handle);- const { getByTestId, unmount } = render(- <PixiGraph- nodes={NODES}- edges={[]}- mode="tree"- dark={false}- resetSignal={0}- onHover={vi.fn()}- onOpen={vi.fn()}- onReady={onReady}- />- );- const host = getByTestId('memory-graph-canvas');- await waitFor(() => expect(mocks.mountPixiGraph).toHaveBeenCalledTimes(1));- const [, opts] = mocks.mountPixiGraph.mock.calls[0] as [HTMLElement, { onReady: () => void }];-- unmount();- act(() => opts.onReady());-- expect(host).toHaveAttribute('data-render-ready', 'false');- expect(onReady).not.toHaveBeenCalled();- });-});diff --git a/app/src/components/intelligence/PixiGraph.tsx b/app/src/components/intelligence/PixiGraph.tsxdeleted file mode 100644index 16ef07ac77..0000000000--- a/app/src/components/intelligence/PixiGraph.tsx+++ /dev/null@@ -1,148 +0,0 @@-/**- * Thin React host for the imperative Pixi + d3-force renderer.- *- * Mounts the WebGL graph into a div and forwards hover/open back to the- * parent `MemoryGraph` chrome (footer + preview). Pixi owns all canvas- * interaction; React only manages the lifecycle. Callbacks are held in- * refs so changing them never tears down and re-creates the GPU context.- */-import { useEffect, useRef } from 'react';--import { type GraphEdge, type GraphMode, type GraphNode } from '../../utils/tauriCommands';-import { buildGraph, type SimTuning } from './memoryGraphLayout';-import { mountPixiGraph, type PixiGraphHandle } from './pixiGraphRenderer';--interface PixiGraphProps {- nodes: GraphNode[];- edges: GraphEdge[];- mode: GraphMode;- dark: boolean;- /** Optional label for the synthetic hub node (defaults to "Memory"). */- rootLabel?: string;- /** Fill the parent's height instead of the fixed 640px cap. */- fill?: boolean;- /** Initial auto-fit zoom (world scale). Defaults to 0.17. */- fitScale?: number;- /** Fit the whole node cloud tightly to the viewport instead of a fixed zoom. */- fitToBounds?: boolean;- /** Draw an always-on text label under each node. */- showLabels?: boolean;- /** Optional force-simulation tuning (defaults preserve the standard layout). */- tuning?: SimTuning;- /** Bump to recentre the view (Reset view button). */- resetSignal: number;- onHover: (node: GraphNode | null) => void;- onOpen: (node: GraphNode) => void;- /** Called if Pixi fails to initialise at runtime so the parent can- * fall back to the SVG renderer. */- onError?: () => void;- /** Fired once the layout settles (graph is ready to reveal). */- onReady?: () => void;-}--export function PixiGraph({- nodes,- edges,- mode,- dark,- rootLabel,- fill,- fitScale,- fitToBounds,- showLabels,- tuning,- resetSignal,- onHover,- onOpen,- onError,- onReady,-}: PixiGraphProps) {- const hostRef = useRef<HTMLDivElement | null>(null);- const handleRef = useRef<PixiGraphHandle | null>(null);- const onHoverRef = useRef(onHover);- const onOpenRef = useRef(onOpen);- const onErrorRef = useRef(onError);- const onReadyRef = useRef(onReady);- const darkRef = useRef(dark);- onHoverRef.current = onHover;- onOpenRef.current = onOpen;- onErrorRef.current = onError;- onReadyRef.current = onReady;- darkRef.current = dark;-- // Mount the renderer once; update in-place when graph data changes.- const mountedModeRef = useRef<GraphMode | null>(null);-- useEffect(() => {- const host = hostRef.current;- if (!host) return;-- // Mode change requires full remount (different edge semantics).- if (handleRef.current && mountedModeRef.current === mode) {- const { simNodes, links } = buildGraph(nodes, edges, mode, rootLabel);- handleRef.current.updateGraph(simNodes, links);- return;- }-- // First mount or mode flip — full init.- host.dataset.renderReady = 'false';- let cancelled = false;- handleRef.current?.destroy();- handleRef.current = null;- const { simNodes, links } = buildGraph(nodes, edges, mode, rootLabel);- const pending = mountPixiGraph(host, {- simNodes,- links,- dark: darkRef.current,- fitScale,- fitToBounds,- showLabels,- tuning,- onHover: n => onHoverRef.current(n),- onOpen: n => onOpenRef.current(n),- onReady: () => {- if (cancelled) return;- host.dataset.renderReady = 'true';- onReadyRef.current?.();- },- })- .then(handle => {- if (cancelled) {- handle.destroy();- return null;- }- handleRef.current = handle;- mountedModeRef.current = mode;- return handle;- })- .catch(err => {- console.error('[memory-graph] Pixi init failed; falling back to SVG', err);- if (!cancelled) onErrorRef.current?.();- return null;- });- return () => {- cancelled = true;- handleRef.current = null;- mountedModeRef.current = null;- void pending.then(handle => handle?.destroy());- };- }, [nodes, edges, mode, rootLabel, fitScale, fitToBounds, showLabels, tuning]);-- useEffect(() => {- handleRef.current?.setTheme(dark);- }, [dark]);-- useEffect(() => {- if (resetSignal > 0) handleRef.current?.resetView();- }, [resetSignal]);-- return (- <div- ref={hostRef}- data-testid="memory-graph-canvas"- data-render-ready="false"- className={`block w-full ${fill ? 'min-h-0 flex-1' : ''}`}- style={{ height: fill ? '100%' : 'min(640px, calc(100vh - 22rem))' }}- />- );-}diff --git a/app/src/components/intelligence/SourceSettingsPanel.test.tsx b/app/src/components/intelligence/SourceSettingsPanel.test.tsxdeleted file mode 100644index 8d9baaf6f6..0000000000--- a/app/src/components/intelligence/SourceSettingsPanel.test.tsx+++ /dev/null@@ -1,65 +0,0 @@-import { render, screen } from '@testing-library/react';-import userEvent from '@testing-library/user-event';-import { afterEach, describe, expect, it, vi } from 'vitest';--import { type MemorySourceEntry, updateMemorySource } from '../../services/memorySourcesService';-import { SourceSettingsPanel } from './SourceSettingsPanel';--vi.mock('../../services/memorySourcesService', async () => {- const actual = await vi.importActual<typeof import('../../services/memorySourcesService')>(- '../../services/memorySourcesService'- );- return { ...actual, updateMemorySource: vi.fn() };-});--const source: MemorySourceEntry = {- id: 'src-1',- kind: 'rss_feed',- label: 'My Feed',- enabled: true,- max_items: 50,-};--describe('<SourceSettingsPanel />', () => {- afterEach(() => {- vi.mocked(updateMemorySource).mockReset();- });-- it('renders a labelled numeric field per relevant limit and a save button', () => {- render(<SourceSettingsPanel source={source} onSaved={vi.fn()} />);- const field = screen.getByLabelText(/Max Items/i) as HTMLInputElement;- expect(field).toBeInTheDocument();- expect(field.value).toBe('50');- expect(screen.getByRole('button', { name: /Save/i })).toBeInTheDocument();- });-- it('saves the edited value and reports the updated entry', async () => {- const updated = { ...source, max_items: 75 };- vi.mocked(updateMemorySource).mockResolvedValue(updated);- const onSaved = vi.fn();- const user = userEvent.setup();-- render(<SourceSettingsPanel source={source} onSaved={onSaved} />);- const field = screen.getByLabelText(/Max Items/i);- await user.clear(field);- await user.type(field, '75');- await user.click(screen.getByRole('button', { name: /Save/i }));-- expect(updateMemorySource).toHaveBeenCalledWith('src-1', { max_items: 75 });- expect(onSaved).toHaveBeenCalledWith(updated);- });-- it('rejects a negative value and reports the failure via onToast without saving', async () => {- const onToast = vi.fn();- const user = userEvent.setup();-- render(<SourceSettingsPanel source={source} onSaved={vi.fn()} onToast={onToast} />);- const field = screen.getByLabelText(/Max Items/i);- await user.clear(field);- await user.type(field, '-5');- await user.click(screen.getByRole('button', { name: /Save/i }));-- expect(updateMemorySource).not.toHaveBeenCalled();- expect(onToast).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }));- });-});diff --git a/app/src/components/intelligence/SourceSettingsPanel.tsx b/app/src/components/intelligence/SourceSettingsPanel.tsxdeleted file mode 100644index fe604c0b82..0000000000--- a/app/src/components/intelligence/SourceSettingsPanel.tsx+++ /dev/null@@ -1,196 +0,0 @@-/**- * Expandable per-source sync-settings panel.- *- * Rendered inline below a SourceRow when the gear icon is clicked.- * Shows only the limit fields relevant to the source's kind, seeded from- * the current entry values. Empty input = omit the field on save (meaning- * "use backend default / unlimited").- *- * On Save calls `updateMemorySource` and notifies the parent via- * `onSaved` with the updated entry.- */-import { useCallback, useState } from 'react';--import { useT } from '../../lib/i18n/I18nContext';-import {- type MemorySourceEntry,- type SourceKind,- updateMemorySource,-} from '../../services/memorySourcesService';-import Button from '../ui/Button';-import Input from '../ui/Input';--// Which limit fields are relevant per kind. Order determines display order.-// Only caps that are actually enforced at sync time are surfaced — the-// per-sync token/cost budgets are not yet wired into the sync loop, so they-// are intentionally omitted here.-const KIND_FIELDS: Record<SourceKind, Array<keyof LimitFields>> = {- composio: ['sync_depth_days', 'max_items'],- conversation: ['sync_depth_days'],- github_repo: ['max_prs', 'max_issues', 'max_commits', 'sync_depth_days'],- rss_feed: ['max_items', 'sync_depth_days'],- twitter_query: ['since_days'],- web_page: ['sync_depth_days'],- folder: ['sync_depth_days'],-};--// i18n key for each field label-const FIELD_LABEL_KEYS: Record<keyof LimitFields, string> = {- max_prs: 'memorySources.settings.maxPrs',- max_issues: 'memorySources.settings.maxIssues',- max_commits: 'memorySources.settings.maxCommits',- max_items: 'memorySources.settings.maxItems',- since_days: 'memorySources.settings.sinceDays',- sync_depth_days: 'memorySources.settings.syncDepthDays',-};--type LimitFields = Pick<- MemorySourceEntry,- 'max_prs' | 'max_issues' | 'max_commits' | 'max_items' | 'since_days' | 'sync_depth_days'->;--// Item-count caps where a "Maxed" badge is meaningful (synced count vs cap).-// Time-window (sync_depth_days/since_days) and budget (tokens/cost) caps don't-// map to a chunk count, so they never show "Maxed".-interface SourceSettingsPanelProps {- source: MemorySourceEntry;- onSaved: (updated: MemorySourceEntry) => void;- onToast?: (toast: { type: 'success' | 'error'; title: string; message?: string }) => void;-}--export function SourceSettingsPanel({ source, onSaved, onToast }: SourceSettingsPanelProps) {- const { t } = useT();- const fields = KIND_FIELDS[source.kind] ?? [];-- // Hold each field as a string so inputs can be freely edited. Seeded from the- // entry's stored cap (fetched from the backend — the single source of truth;- // the caps migration writes conservative defaults onto the entry). An empty- // field genuinely means "no cap / unlimited".- const [values, setValues] = useState<Record<string, string>>(() => {- const init: Record<string, string> = {};- for (const f of fields) {- const stored = source[f as keyof MemorySourceEntry];- init[f] = stored != null ? String(stored) : '';- }- return init;- });-- const [saving, setSaving] = useState(false);-- const handleChange = useCallback((field: string, value: string) => {- setValues(prev => ({ ...prev, [field]: value }));- }, []);-- const handleSave = useCallback(async () => {- setSaving(true);- try {- const patch: Partial<LimitFields> = {};- for (const f of fields) {- const raw = values[f];- if (raw !== '' && raw !== undefined) {- const parsed = Number(raw);- if (!Number.isFinite(parsed) || !Number.isInteger(parsed) || parsed < 0) {- onToast?.({ type: 'error', title: t('memorySources.settings.saveFailed') });- return;- }- (patch as Record<string, number>)[f] = parsed;- }- // Empty string → omit from patch (backend treats absence as "default")- }- const updated = await updateMemorySource(source.id, patch);- onSaved(updated);- onToast?.({ type: 'success', title: t('memorySources.settings.saved') });- } catch (err) {- onToast?.({- type: 'error',- title: t('memorySources.settings.saveFailed'),- message: err instanceof Error ? err.message : String(err),- });- } finally {- setSaving(false);- }- }, [fields, source.id, values, onSaved, onToast, t]);-- if (fields.length === 0) return null;-- // Display name for the tooltip — the toolkit slug (title-cased) for Composio- // sources, else the source label.- const toolkitName = source.toolkit- ? source.toolkit.charAt(0).toUpperCase() + source.toolkit.slice(1)- : source.label;- const unlimitedTooltip = t('memorySources.settings.unlimitedTooltip').replace(- '{toolkit}',- toolkitName- );-- return (- <div- className="mt-2 ml-7 rounded-lg border border-line bg-surface-muted p-3"- data-testid={`source-settings-panel-${source.id}`}>- <p className="mb-2 text-xs font-semibold text-content-secondary">- {t('memorySources.settings.title')}- </p>- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">- {fields.map(field => {- const isUnlimited = (values[field] ?? '') === '';- // No "Maxed" badge. The only count a row has is *chunks*, and a cap- // is *items* (emails, issues, commits); one email is several- // chunks, so the badge lit long before the cap was reached. It- // comes back when the status carries an item count (openhuman#6012).- return (- <div key={field}>- <label- htmlFor={`src-setting-${source.id}-${field}`}- className="mb-0.5 flex items-center gap-1.5 text-xs font-medium text-content-secondary">- {t(FIELD_LABEL_KEYS[field])}- {isUnlimited && (- <span- className="inline-flex cursor-help text-content-faint"- title={unlimitedTooltip}- aria-label={unlimitedTooltip}>- <InfoIcon />- </span>- )}- </label>- <Input- id={`src-setting-${source.id}-${field}`}- type="number"- inputSize="sm"- monospace- min={0}- step={1}- value={values[field] ?? ''}- onChange={e => handleChange(field, e.target.value)}- placeholder={`∞ ${t('memorySources.settings.unlimited')}`}- className="text-xs"- />- </div>- );- })}- </div>- <div className="mt-3 flex justify-end">- <Button variant="primary" size="sm" onClick={() => void handleSave()} disabled={saving}>- {saving ? t('memorySources.settings.saving') : t('memorySources.settings.save')}- </Button>- </div>- </div>- );-}--function InfoIcon() {- return (- <svg- width="13"- height="13"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- strokeLinecap="round"- strokeLinejoin="round"- aria-hidden="true">- <circle cx="12" cy="12" r="10" />- <path d="M12 16v-4M12 8h.01" />- </svg>- );-}diff --git a/app/src/components/intelligence/SyncActivityCard.test.tsx b/app/src/components/intelligence/SyncActivityCard.test.tsxdeleted file mode 100644index b07fd51c32..0000000000--- a/app/src/components/intelligence/SyncActivityCard.test.tsx+++ /dev/null@@ -1,237 +0,0 @@-/**- * Vitest for `<SyncActivityCard />` (openhuman#6257): the sources with a sync- * in flight on Brain › Sync, named and staged in plain language.- *- * The card reads the real sync store, fed here the way the socket feeds it- * (`applyStageEvent`); only the status-list RPC is swapped for a spy.- */-import { act, render, screen, waitFor } from '@testing-library/react';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import type { SourceStatus } from '../../services/memorySourcesService';-import {- applyStageEvent,- getMemorySyncActivity,- noteSyncRequested,- resetMemorySyncActivityForTests,-} from './memorySyncActivityStore';-import { STATUS_POLL_MS, SyncActivityCard } from './SyncActivityCard';--const mockStatusList = vi.fn();--vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));--vi.mock('../../services/memorySourcesService', async importOriginal => {- const actual = await importOriginal<typeof import('../../services/memorySourcesService')>();- return { ...actual, memorySourcesStatusList: (...args: unknown[]) => mockStatusList(...args) };-});--function status(source_id: string, extra: Partial<SourceStatus> = {}): SourceStatus {- return {- source_id,- chunks_synced: 0,- chunks_pending: 0,- last_chunk_at_ms: null,- freshness: 'idle',- ...extra,- };-}--describe('<SyncActivityCard />', () => {- beforeEach(() => {- resetMemorySyncActivityForTests();- mockStatusList.mockReset();- mockStatusList.mockResolvedValue([]);- });-- afterEach(() => {- vi.useRealTimers();- });-- it('says nothing is syncing when no run is in flight', async () => {- render(<SyncActivityCard />);- expect(await screen.findByTestId('sync-activity-empty')).toHaveTextContent(- 'sync.nowSyncing.empty'- );- });-- it('lists a syncing source by its label with a plain-language stage', async () => {- mockStatusList.mockResolvedValue([status('src-a', { label: 'Notes', sync_stage: null })]);- render(<SyncActivityCard />);- act(() => {- applyStageEvent({- stage: 'queued',- source_id: 'src-a',- detail: 'queued chunk extraction for mem_src:src-a:x.md',- });- });-- const row = await screen.findByTestId('sync-activity-row-src-a');- await waitFor(() => expect(row).toHaveTextContent('Notes'));- expect(row).toHaveTextContent('memorySources.stage.queued');- expect(row).not.toHaveTextContent('mem_src:');- });-- it('shows a progress detail a person can read, under the id when no label is known', async () => {- mockStatusList.mockResolvedValue([status('src-b')]);- render(<SyncActivityCard />);- act(() => {- applyStageEvent({- stage: 'running',- source_id: 'src-b',- detail: 'pass 1 done, 200 item(s) so far',- });- });-- const row = await screen.findByTestId('sync-activity-row-src-b');- expect(row).toHaveTextContent('src-b');- expect(row).toHaveTextContent('memorySources.stage.running');- expect(row).toHaveTextContent('pass 1 done, 200 item(s) so far');- });-- it('shows a row the Sync button lit before any stage as starting', async () => {- mockStatusList.mockResolvedValue([status('src-e')]);- render(<SyncActivityCard />);- act(() => {- noteSyncRequested('src-e');- });- expect(await screen.findByTestId('sync-activity-row-src-e')).toHaveTextContent(- 'memorySources.stage.requested'- );- });-- it('seeds a run the core reports in flight when the card mounts', async () => {- mockStatusList.mockResolvedValue([- status('src-c', { label: 'Gmail', sync_stage: 'running', sync_detail: null }),- ]);- render(<SyncActivityCard />);-- const row = await screen.findByTestId('sync-activity-row-src-c');- await waitFor(() => expect(row).toHaveTextContent('Gmail'));- expect(getMemorySyncActivity().syncingIds.has('src-c')).toBe(true);- });-- it('drops a row once its run ends', async () => {- mockStatusList.mockResolvedValue([status('src-f')]);- render(<SyncActivityCard />);- act(() => {- applyStageEvent({ stage: 'running', source_id: 'src-f', detail: null });- });- expect(await screen.findByTestId('sync-activity-row-src-f')).toBeInTheDocument();-- act(() => {- applyStageEvent({ stage: 'completed', source_id: 'src-f', detail: 'ingested 1 item(s)' });- });- await waitFor(() =>- expect(screen.queryByTestId('sync-activity-row-src-f')).not.toBeInTheDocument()- );- expect(screen.getByTestId('sync-activity-empty')).toBeInTheDocument();- });-- it('polls the status list while mounted and stops on unmount', async () => {- vi.useFakeTimers({ shouldAdvanceTime: true });- const view = render(<SyncActivityCard />);- await waitFor(() => expect(mockStatusList).toHaveBeenCalledTimes(1));-- await act(async () => {- vi.advanceTimersByTime(STATUS_POLL_MS);- });- await waitFor(() => expect(mockStatusList).toHaveBeenCalledTimes(2));-- view.unmount();- await act(async () => {- vi.advanceTimersByTime(STATUS_POLL_MS * 2);- });- expect(mockStatusList).toHaveBeenCalledTimes(2);- });-- it('keeps the last known sources when a later status read fails', async () => {- vi.useFakeTimers({ shouldAdvanceTime: true });- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});- mockStatusList- .mockResolvedValueOnce([status('src-d', { label: 'Drive' })])- .mockRejectedValue(new Error('core down'));- render(<SyncActivityCard />);- await waitFor(() => expect(mockStatusList).toHaveBeenCalledTimes(1));- act(() => {- applyStageEvent({ stage: 'running', source_id: 'src-d', detail: null });- });- const row = await screen.findByTestId('sync-activity-row-src-d');- await waitFor(() => expect(row).toHaveTextContent('Drive'));-- await act(async () => {- vi.advanceTimersByTime(STATUS_POLL_MS);- });- await waitFor(() => expect(warn).toHaveBeenCalled());- expect(screen.getByTestId('sync-activity-row-src-d')).toHaveTextContent('Drive');- warn.mockRestore();- });-- it('lists only sources the registry knows, never a per-document row', async () => {- mockStatusList.mockResolvedValue([status('src-g', { label: 'Gmail' })]);- render(<SyncActivityCard />);- await waitFor(() => expect(mockStatusList).toHaveBeenCalled());- act(() => {- // The bridge's per-document stage for a document outside the registry- // arrives keyed by the document id, and no run ever ends it.- applyStageEvent({- stage: 'ingesting',- connection_id: 'gmail:ca_1:msg-42',- detail: 'queue_depth=3',- });- applyStageEvent({ stage: 'running', source_id: 'src-g', detail: null });- });-- const row = await screen.findByTestId('sync-activity-row-src-g');- await waitFor(() => expect(row).toHaveTextContent('Gmail'));- expect(getMemorySyncActivity().syncingIds.has('gmail:ca_1:msg-42')).toBe(true);- expect(screen.getByTestId('sync-activity-card')).not.toHaveTextContent('msg-42');- });-- it('ignores a status read that answers after a newer one', async () => {- vi.useFakeTimers({ shouldAdvanceTime: true });- let answerFirst: (rows: SourceStatus[]) => void = () => {};- mockStatusList- .mockImplementationOnce(- () =>- new Promise<SourceStatus[]>(resolve => {- answerFirst = resolve;- })- )- .mockResolvedValue([status('src-h', { label: 'Newer', sync_stage: null })]);- render(<SyncActivityCard />);- await act(async () => {- vi.advanceTimersByTime(STATUS_POLL_MS);- });- await waitFor(() => expect(mockStatusList).toHaveBeenCalledTimes(2));- act(() => {- applyStageEvent({ stage: 'running', source_id: 'src-h', detail: null });- });- const row = await screen.findByTestId('sync-activity-row-src-h');- await waitFor(() => expect(row).toHaveTextContent('Newer'));-- // The first read answers last, with an older label.- await act(async () => {- answerFirst([status('src-h', { label: 'Older', sync_stage: null })]);- });- expect(screen.getByTestId('sync-activity-row-src-h')).toHaveTextContent('Newer');- });-- it('hides the detail of a stage it does not know', async () => {- mockStatusList.mockResolvedValue([status('src-u', { label: 'Feed' })]);- render(<SyncActivityCard />);- await waitFor(() => expect(mockStatusList).toHaveBeenCalled());- act(() => {- noteSyncRequested('src-u');- applyStageEvent({- stage: 'embedding',- source_id: 'src-u',- detail: 'batch for mem_src:src-u:7',- });- });-- const row = await screen.findByTestId('sync-activity-row-src-u');- expect(row).toHaveTextContent('memorySources.stage.unknown');- expect(row).not.toHaveTextContent('mem_src:');- });-});diff --git a/app/src/components/intelligence/SyncActivityCard.tsx b/app/src/components/intelligence/SyncActivityCard.tsxdeleted file mode 100644index 934997d05c..0000000000--- a/app/src/components/intelligence/SyncActivityCard.tsx+++ /dev/null@@ -1,113 +0,0 @@-/**- * "Now syncing" on Brain › Sync — the sources with a sync in flight, and where- * each one is (openhuman#6257).- *- * The tab showed the history of finished runs and the job counters, but- * nothing about a run still going, so a source whose Sources row said "Queued"- * had no counterpart here. This lists them from the same store the Sources- * rows read, so the two tabs agree.- *- * The status list is polled while the card is mounted for three things: each- * source's label (the store keys runs by id); the registry's source ids, since- * the store also lights rows keyed by a document outside the registry, which- * never end and are not listed here; and the core's own account of what is in- * flight, which seeds a run this page never saw start (an app reload mid-sync).- */-import { useEffect, useState } from 'react';--import { useT } from '../../lib/i18n/I18nContext';-import { memorySourcesStatusList } from '../../services/memorySourcesService';-import {- registrySyncingIds,- showsStageDetail,- sourceLabelsById,- stageLabelKey,-} from './memorySourcesSyncTypes';-import { reconcileWithStatuses, useMemorySyncActivity } from './memorySyncActivityStore';--/** How often the card re-reads the status list while mounted. */-export const STATUS_POLL_MS = 10_000;--export function SyncActivityCard() {- const { t } = useT();- const { syncingIds, progress } = useMemorySyncActivity();- const [labels, setLabels] = useState<Record<string, string>>({});- const [sourceIds, setSourceIds] = useState<ReadonlySet<string>>(() => new Set());-- useEffect(() => {- let cancelled = false;- // Polls can answer out of order: a read slower than the poll interval must- // not put an older account back over a newer one.- let requested = 0;- let applied = 0;- const refresh = async () => {- const seq = ++requested;- try {- const statuses = await memorySourcesStatusList();- if (cancelled) return;- if (seq < applied) {- console.debug(- '[sync-activity] dropped an older status read seq=%d applied=%d',- seq,- applied- );- return;- }- applied = seq;- setLabels(sourceLabelsById(statuses));- setSourceIds(new Set(statuses.map(status => status.source_id)));- reconcileWithStatuses(statuses);- console.debug('[sync-activity] status list ok sources=%d', statuses.length);- } catch (err) {- // A failed read keeps the labels and source ids of the last read that- // answered, so runs the socket reports for those sources still show.- if (!cancelled) console.warn('[sync-activity] status list failed', err);- }- };- void refresh();- const id = setInterval(() => {- void refresh();- }, STATUS_POLL_MS);- return () => {- cancelled = true;- clearInterval(id);- };- }, []);-- const rows = registrySyncingIds(syncingIds, sourceIds);-- return (- <div className="space-y-2" data-testid="sync-activity-card">- <h3 className="text-sm font-medium text-content-secondary">- {t('sync.nowSyncing.title', 'Now syncing')}- </h3>- {rows.length === 0 ? (- <div className="text-xs text-content-faint" data-testid="sync-activity-empty">- {t('sync.nowSyncing.empty', 'Nothing is syncing right now.')}- </div>- ) : (- <ul className="space-y-1.5">- {rows.map(id => {- const live = progress.get(id);- // A row the Sync button lit before the core's first stage has no- // bar yet: it is starting.- const stage = live?.stage ?? 'requested';- const detail = live && showsStageDetail(live.stage) ? live.detail : null;- return (- <li- key={id}- data-testid={`sync-activity-row-${id}`}- className="flex items-center justify-between gap-3 rounded-md border border-line-subtle px-3 py-2 text-xs">- <span className="truncate font-medium text-content">{labels[id] ?? id}</span>- <span className="flex min-w-0 items-center gap-2 text-content-muted">- <span className="shrink-0">{t(stageLabelKey(stage))}</span>- {detail ? <span className="truncate text-content-faint">{detail}</span> : null}- </span>- </li>- );- })}- </ul>- )}- </div>- );-}diff --git a/app/src/components/intelligence/SyncAuditPanel.test.tsx b/app/src/components/intelligence/SyncAuditPanel.test.tsxdeleted file mode 100644index cbbb7e6d0b..0000000000--- a/app/src/components/intelligence/SyncAuditPanel.test.tsx+++ /dev/null@@ -1,389 +0,0 @@-/**- * Vitest for `<SyncAuditPanel />` (issue #3116 — coverage for the sync-audit- * history surface shipped in PR #3113; openhuman#6257 — the panel keeps- * itself current).- *- * Covers:- * - loading → loaded transition (renders rows once the audit log resolves)- * - formatting of tokens (k/M), cost ($x.xxxx), and duration (ms / s / m s)- * - the scope label mapping for github / gmail / rebuild scopes- * - success / partial / failed status badges- * - the empty state when no runs are recorded- * - registry labels from the status list, with the scope label as fallback- * - re-reading after a run ends, polling while one runs, and manual Refresh- * - an older read that answers last never replacing a newer history- *- * Only the `memorySyncAuditLog` and `memorySourcesStatusList` wrappers are- * swapped for spies; everything else in those modules is inherited verbatim.- * The sync store is the real one, fed through `applyStageEvent` the way the- * socket feeds it.- */-import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import type { SourceStatus } from '../../services/memorySourcesService';-import type { SyncAuditEntry } from '../../utils/tauriCommands';-import { applyStageEvent, resetMemorySyncActivityForTests } from './memorySyncActivityStore';-import {- POLL_WHILE_SYNCING_MS,- REFETCH_AFTER_RUN_ENDS_MS,- SyncAuditPanel,- timeAgo,-} from './SyncAuditPanel';--const mockAuditLog = vi.fn();-const mockStatusList = vi.fn();--vi.mock('../../utils/tauriCommands', async importOriginal => {- const actual = await importOriginal<typeof import('../../utils/tauriCommands')>();- return { ...actual, memorySyncAuditLog: (...args: unknown[]) => mockAuditLog(...args) };-});--vi.mock('../../services/memorySourcesService', async importOriginal => {- const actual = await importOriginal<typeof import('../../services/memorySourcesService')>();- return { ...actual, memorySourcesStatusList: (...args: unknown[]) => mockStatusList(...args) };-});--function entry(overrides: Partial<SyncAuditEntry> = {}): SyncAuditEntry {- return {- timestamp: new Date().toISOString(),- source_id: 'src-1',- source_kind: 'github_repo',- scope: 'github:tinyhumansai/openhuman',- items_fetched: 12,- batches: 1,- input_tokens: 1500,- output_tokens: 500,- estimated_cost_usd: 0.0123,- duration_ms: 4200,- success: true,- ...overrides,- };-}--function status(source_id: string, extra: Partial<SourceStatus> = {}): SourceStatus {- return {- source_id,- chunks_synced: 0,- chunks_pending: 0,- last_chunk_at_ms: null,- freshness: 'idle',- ...extra,- };-}--describe('<SyncAuditPanel />', () => {- beforeEach(() => {- resetMemorySyncActivityForTests();- mockAuditLog.mockReset();- mockStatusList.mockReset();- mockStatusList.mockResolvedValue([]);- });-- afterEach(() => {- vi.useRealTimers();- });-- it('renders the empty state when there are no runs', async () => {- mockAuditLog.mockResolvedValue([]);- render(<SyncAuditPanel />);- expect(await screen.findByText('No sync runs recorded yet.')).toBeInTheDocument();- });-- it('renders entries once the audit log resolves', async () => {- mockAuditLog.mockResolvedValue([entry()]);- render(<SyncAuditPanel />);-- // Summary line: "1 sync runs" (count + label render as sibling text nodes- // inside one span, so match the span's normalized text content).- expect(await screen.findByText(/^\s*1\s+sync runs\s*$/)).toBeInTheDocument();- // The github scope is rendered through scopeLabel().- expect(screen.getByText('GitHub · tinyhumansai/openhuman')).toBeInTheDocument();- // Item count cell.- expect(screen.getByText('12')).toBeInTheDocument();- });-- it('formats tokens, cost, and duration for each row', async () => {- mockAuditLog.mockResolvedValue([- entry({- input_tokens: 1_500, // 1.5k in- output_tokens: 500, // combined 2.0k displayed- estimated_cost_usd: 0.0123,- duration_ms: 4200, // 4.2s- }),- ]);- render(<SyncAuditPanel />);-- // formatTokens(input+output) → 2.0k- expect(await screen.findByText('2.0k')).toBeInTheDocument();- // cost → $0.0123 (4 dp)- expect(screen.getByText('$0.0123')).toBeInTheDocument();- // duration → 4.2s- expect(screen.getByText('4.2s')).toBeInTheDocument();- });-- it('formats sub-second, minute, and millions correctly', async () => {- mockAuditLog.mockResolvedValue([- entry({- source_id: 'big',- scope: 'gmail:test-at-example-dot-com',- input_tokens: 1_500_000, // 1.5M in- output_tokens: 500_000, // combined 2.0M- duration_ms: 125_000, // 2m 5s- estimated_cost_usd: 1.5,- }),- ]);- render(<SyncAuditPanel />);-- expect(await screen.findByText('2.0M')).toBeInTheDocument();- expect(screen.getByText('2m 5s')).toBeInTheDocument();- // gmail scope label de-slugifies the email.- expect(screen.getByText('Gmail · [email protected]')).toBeInTheDocument();- });-- it('aggregates totals across multiple runs', async () => {- mockAuditLog.mockResolvedValue([- entry({ source_id: 'a', estimated_cost_usd: 0.01, input_tokens: 1000, output_tokens: 0 }),- entry({ source_id: 'b', estimated_cost_usd: 0.02, input_tokens: 1000, output_tokens: 0 }),- ]);- render(<SyncAuditPanel />);-- // "2 sync runs"- expect(await screen.findByText(/^\s*2\s+sync runs\s*$/)).toBeInTheDocument();- // Total cost = 0.03 rendered with the "total" suffix in the summary span.- expect(screen.getByText(/\$0\.0300\s+total/)).toBeInTheDocument();- });-- it('renders the failure badge for unsuccessful runs', async () => {- mockAuditLog.mockResolvedValue([- entry({ success: false, error: 'rate limited', source_id: 'fail' }),- ]);- render(<SyncAuditPanel />);-- const failBadge = await screen.findByTitle('rate limited');- expect(failBadge).toHaveTextContent('Failed');- });-- it('renders the partial badge when the fetch succeeded but tree ingest failed', async () => {- // openhuman#5820: fetched items with a failed memory-tree half must not- // read as plain failure (nothing fetched) and MUST not read as success.- mockAuditLog.mockResolvedValue([- entry({- success: false,- items_fetched: 250,- tree_ingest_failures: 250,- tree_error: '250 item(s) fetched but not ingested into the memory tree',- source_id: 'partial',- }),- ]);- render(<SyncAuditPanel />);-- const partialBadge = await screen.findByTitle(- '250 item(s) fetched but not ingested into the memory tree'- );- expect(partialBadge).toHaveTextContent('Partial');- });-- it('falls back to the partial label when the row has no tree_error text', async () => {- mockAuditLog.mockResolvedValue([- entry({ success: false, tree_ingest_failures: 3, source_id: 'partial-no-text' }),- ]);- render(<SyncAuditPanel />);-- const partialBadge = await screen.findByTitle('Fetched, memory ingest failed');- expect(partialBadge).toHaveTextContent('Partial');- });-- it('renders the success badge for successful runs', async () => {- mockAuditLog.mockResolvedValue([entry({ success: true })]);- render(<SyncAuditPanel />);-- const okBadge = await screen.findByTitle('Success');- expect(okBadge).toHaveTextContent('Success');- });-- it('maps a rebuild scope through its label', async () => {- mockAuditLog.mockResolvedValue([- entry({ source_kind: 'rebuild', scope: 'rebuild:gmail:x-at-y-dot-com', source_id: 'r' }),- ]);- render(<SyncAuditPanel />);-- expect(await screen.findByText('Rebuild · gmail:x-at-y-dot-com')).toBeInTheDocument();- });-- it('survives a fetch failure by leaving the empty state', async () => {- const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});- mockAuditLog.mockRejectedValue(new Error('boom'));- render(<SyncAuditPanel />);-- // After the rejected fetch, loading clears and the empty state shows.- await waitFor(() => expect(screen.getByText('No sync runs recorded yet.')).toBeInTheDocument());- expect(consoleError).toHaveBeenCalled();- consoleError.mockRestore();- });-- it('renders a full table with headers when entries exist', async () => {- mockAuditLog.mockResolvedValue([entry()]);- render(<SyncAuditPanel />);-- // Wait for the loaded table (real row data), not the loading skeleton- // table that briefly renders first with the same column headers — the- // skeleton node gets swapped out for the real one once the audit log- // resolves, so grabbing "table" before that would hold a detached node.- await screen.findByText('GitHub · tinyhumansai/openhuman');- const table = screen.getByRole('table');- expect(within(table).getByText('When')).toBeInTheDocument();- expect(within(table).getByText('Source')).toBeInTheDocument();- expect(within(table).getByText('Cost')).toBeInTheDocument();- });-- it('names a row by its registry label and keeps the scope as the title', async () => {- mockAuditLog.mockResolvedValue([- entry({ source_id: 'src-gmail', source_kind: 'composio', scope: 'gmail:ca_1' }),- ]);- mockStatusList.mockResolvedValue([status('src-gmail', { label: 'Gmail · work' })]);- render(<SyncAuditPanel />);-- const cell = await screen.findByText('Gmail · work');- expect(cell).toHaveAttribute('title', 'gmail:ca_1');- });-- it('falls back to the scope label when the status list fails', async () => {- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});- mockAuditLog.mockResolvedValue([entry()]);- mockStatusList.mockRejectedValue(new Error('core down'));- render(<SyncAuditPanel />);-- expect(await screen.findByText('GitHub · tinyhumansai/openhuman')).toBeInTheDocument();- expect(warn).toHaveBeenCalled();- warn.mockRestore();- });-- it('re-reads the history shortly after a sync run ends', async () => {- vi.useFakeTimers({ shouldAdvanceTime: true });- mockAuditLog- .mockResolvedValueOnce([])- .mockResolvedValue([entry({ source_id: 'src-new', scope: 'github:org/new' })]);- render(<SyncAuditPanel />);- await screen.findByText('No sync runs recorded yet.');-- act(() => {- applyStageEvent({ stage: 'completed', source_id: 'src-new', detail: 'ingested 3 item(s)' });- });- expect(mockAuditLog).toHaveBeenCalledTimes(1);-- await act(async () => {- vi.advanceTimersByTime(REFETCH_AFTER_RUN_ENDS_MS);- });- expect(await screen.findByText('GitHub · org/new')).toBeInTheDocument();- expect(mockAuditLog).toHaveBeenCalledTimes(2);- });-- it('polls while a sync is running and stops once it ends', async () => {- vi.useFakeTimers({ shouldAdvanceTime: true });- mockAuditLog.mockResolvedValue([]);- mockStatusList.mockResolvedValue([status('src-live')]);- render(<SyncAuditPanel />);- await screen.findByText('No sync runs recorded yet.');- expect(mockAuditLog).toHaveBeenCalledTimes(1);-- act(() => {- applyStageEvent({ stage: 'running', source_id: 'src-live', detail: null });- });- await act(async () => {- vi.advanceTimersByTime(POLL_WHILE_SYNCING_MS);- });- await waitFor(() => expect(mockAuditLog).toHaveBeenCalledTimes(2));-- act(() => {- applyStageEvent({ stage: 'completed', source_id: 'src-live', detail: 'ingested 1 item(s)' });- });- await act(async () => {- vi.advanceTimersByTime(REFETCH_AFTER_RUN_ENDS_MS);- });- await waitFor(() => expect(mockAuditLog).toHaveBeenCalledTimes(3));-- await act(async () => {- vi.advanceTimersByTime(POLL_WHILE_SYNCING_MS * 2);- });- expect(mockAuditLog).toHaveBeenCalledTimes(3);- });-- it('does not keep polling for a per-document row the registry does not know', async () => {- vi.useFakeTimers({ shouldAdvanceTime: true });- mockAuditLog.mockResolvedValue([]);- mockStatusList.mockResolvedValue([status('src-known')]);- render(<SyncAuditPanel />);- await screen.findByText('No sync runs recorded yet.');-- act(() => {- applyStageEvent({- stage: 'ingesting',- connection_id: 'slack:workspace-1:msg',- detail: 'queue_depth=1',- });- });- await act(async () => {- vi.advanceTimersByTime(POLL_WHILE_SYNCING_MS * 2);- });- expect(mockAuditLog).toHaveBeenCalledTimes(1);- });-- it('shows the history without waiting for the status list', async () => {- mockAuditLog.mockResolvedValue([entry({ source_id: 'src-slow', scope: 'github:org/slow' })]);- mockStatusList.mockImplementation(() => new Promise<SourceStatus[]>(() => {}));- render(<SyncAuditPanel />);-- expect(await screen.findByText('GitHub · org/slow')).toBeInTheDocument();- expect(screen.getByTestId('sync-history-refresh')).not.toBeDisabled();- });-- it('re-reads the history when Refresh is pressed', async () => {- mockAuditLog.mockResolvedValue([]);- render(<SyncAuditPanel />);-- fireEvent.click(await screen.findByTestId('sync-history-refresh'));- await waitFor(() => expect(mockAuditLog).toHaveBeenCalledTimes(2));- });-- it('keeps the newer history when an older read answers last', async () => {- vi.useFakeTimers({ shouldAdvanceTime: true });- let resolveFirst: (rows: SyncAuditEntry[]) => void = () => {};- mockAuditLog- .mockImplementationOnce(- () =>- new Promise<SyncAuditEntry[]>(resolve => {- resolveFirst = resolve;- })- )- .mockResolvedValueOnce([entry({ source_id: 'newer', scope: 'github:org/newer' })]);- render(<SyncAuditPanel />);-- act(() => {- applyStageEvent({ stage: 'completed', source_id: 'newer', detail: 'ingested 1 item(s)' });- });- await act(async () => {- vi.advanceTimersByTime(REFETCH_AFTER_RUN_ENDS_MS);- });- expect(await screen.findByText('GitHub · org/newer')).toBeInTheDocument();-- await act(async () => {- resolveFirst([entry({ source_id: 'older', scope: 'github:org/older' })]);- });- expect(screen.queryByText('GitHub · org/older')).not.toBeInTheDocument();- expect(screen.getByText('GitHub · org/newer')).toBeInTheDocument();- });-});--describe('timeAgo', () => {- // Resolve to the fallback English so the `{n}` interpolation is exercised.- const t = (_key: string, fallback?: string) => fallback ?? _key;- const isoAgo = (ms: number) => new Date(Date.now() - ms).toISOString();-- it('covers every relative-time bucket and substitutes the {n} placeholder', () => {- expect(timeAgo(isoAgo(0), t)).toBe('just now');- expect(timeAgo(isoAgo(5 * 60_000), t)).toBe('5m ago');- expect(timeAgo(isoAgo(3 * 60 * 60_000), t)).toBe('3h ago');- expect(timeAgo(isoAgo(2 * 24 * 60 * 60_000), t)).toBe('2d ago');- });-});diff --git a/app/src/components/intelligence/SyncAuditPanel.tsx b/app/src/components/intelligence/SyncAuditPanel.tsxdeleted file mode 100644index 4ed5867447..0000000000--- a/app/src/components/intelligence/SyncAuditPanel.tsx+++ /dev/null@@ -1,384 +0,0 @@-/**- * Sync audit history panel — shows when syncs happened, tokens consumed,- * cost, and duration. Fetches from `openhuman.memory_sources_sync_audit_log`.- *- * Keeps itself current (openhuman#6257). It re-reads the history shortly after- * any sync ends, polls while one is still running, and has a manual Refresh.- * It used to fetch once on mount, so a run that finished while the tab was- * open never appeared until the tab was left and re-entered.- */-import { RefreshCw } from 'lucide-react';-import { useCallback, useEffect, useState } from 'react';--import { useT } from '../../lib/i18n/I18nContext';-import { memorySourcesStatusList } from '../../services/memorySourcesService';-import { memorySyncAuditLog, type SyncAuditEntry } from '../../utils/tauriCommands';-import Badge from '../ui/Badge';-import Button from '../ui/Button';-import DataTable, { type DataTableColumn } from '../ui/DataTable';-import EmptyState from '../ui/EmptyState';-import { registrySyncingIds, sourceLabelsById } from './memorySourcesSyncTypes';-import { subscribeTerminalSyncEvents, useMemorySyncActivity } from './memorySyncActivityStore';--/**- * How long after a run ends before the history is re-read. The core writes- * the row for a run it drove before publishing the run's end, but the memory- * driver's own periodic writer appends after its stage, so the read waits a- * beat.- */-export const REFETCH_AFTER_RUN_ENDS_MS = 1_000;--/** How often the history is re-read while any sync is still running. */-export const POLL_WHILE_SYNCING_MS = 10_000;--function formatDuration(ms: number): string {- if (ms < 1000) return `${ms}ms`;- const secs = ms / 1000;- if (secs < 60) return `${secs.toFixed(1)}s`;- const mins = Math.floor(secs / 60);- const remSecs = Math.round(secs % 60);- return `${mins}m ${remSecs}s`;-}--function formatTokens(n: number): string {- if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;- if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;- return String(n);-}--function scopeLabel(scope: string): string {- if (scope.startsWith('github:')) {- return `GitHub · ${scope.slice(7)}`;- }- if (scope.startsWith('gmail:')) {- return `Gmail · ${scope.slice(6).replace(/-at-/g, '@').replace(/-dot-/g, '.')}`;- }- if (scope.startsWith('rebuild:')) {- return `Rebuild · ${scope.slice(8)}`;- }- return scope;-}--// `t` is threaded in because this is a module-level helper with no hook scope.-// The `{n}` placeholder follows the codebase's interpolation convention-// (t(...).replace('{n}', value)) — `t()` itself does not interpolate params.-export function timeAgo(iso: string, t: (key: string, fallback?: string) => string): string {- const diff = Date.now() - new Date(iso).getTime();- const mins = Math.floor(diff / 60_000);- if (mins < 1) return t('sync.timeAgo.justNow', 'just now');- if (mins < 60) return t('sync.timeAgo.minutes', '{n}m ago').replace('{n}', String(mins));- const hours = Math.floor(mins / 60);- if (hours < 24) return t('sync.timeAgo.hours', '{n}h ago').replace('{n}', String(hours));- const days = Math.floor(hours / 24);- return t('sync.timeAgo.days', '{n}d ago').replace('{n}', String(days));-}--type SyncStatus = 'success' | 'partial' | 'failed';--const STATUS_VARIANT: Record<SyncStatus, 'success' | 'warning' | 'danger'> = {- success: 'success',- partial: 'warning',- failed: 'danger',-};--const STATUS_LABEL_KEY: Record<SyncStatus, string> = {- success: 'sync.status.success',- partial: 'sync.status.partialShort',- failed: 'sync.status.failed',-};--/** Date over time, with the relative age as the tooltip. */-function WhenCell({ iso, ago }: { iso: string; ago: string }) {- const ts = Date.parse(iso);- if (Number.isNaN(ts)) return <span title={iso}>{ago}</span>;- const date = new Date(ts);- return (- <span className="flex flex-col leading-tight" title={`${date.toLocaleString()} · ${ago}`}>- <span className="text-content">{date.toLocaleDateString()}</span>- <span className="text-xs text-content-muted">{date.toLocaleTimeString()}</span>- </span>- );-}--interface SyncAuditPanelProps {- /** Fill a height-bounded parent (only rows scroll) instead of a capped card. */- fill?: boolean;-}--export function SyncAuditPanel({ fill = false }: SyncAuditPanelProps = {}) {- const { t } = useT();- const { syncingIds } = useMemorySyncActivity();- const [entries, setEntries] = useState<SyncAuditEntry[]>([]);- // Registry labels by source id. A row whose source has no label (removed- // since, or a core that predates the field) keeps its scope label.- const [labels, setLabels] = useState<Record<string, string>>({});- // The registry's source ids. Only a run of one of them keeps the history- // polling: the store also lights rows keyed by a document outside the- // registry, and those never end (see `registrySyncingIds`).- const [sourceIds, setSourceIds] = useState<ReadonlySet<string>>(() => new Set());- const anySyncing = registrySyncingIds(syncingIds, sourceIds).length > 0;- const [loading, setLoading] = useState(true);- const [refreshing, setRefreshing] = useState(false);- // Every read — mount, a run ending, a poll, a Refresh press — is one bump of- // this token, and the read effect below is keyed on it. A newer bump cancels- // the read still in flight, so an older read that answers last cannot put an- // older history back on screen.- const [reloadToken, setReloadToken] = useState(0);- const [query, setQuery] = useState('');- const [statusFilter, setStatusFilter] = useState<ReadonlySet<string>>(() => new Set());-- const reload = useCallback((reason: string) => {- console.debug('[sync-audit] reload requested reason=%s', reason);- setReloadToken(token => token + 1);- }, []);-- useEffect(() => {- let cancelled = false;- // The history and the labels are read side by side, not together: a slow- // status list must not hold back the rows or the Refresh button.- void (async () => {- console.debug('[sync-audit] load: entry token=%d', reloadToken);- try {- const data = await memorySyncAuditLog();- if (cancelled) {- console.debug('[sync-audit] load: dropped superseded token=%d', reloadToken);- return;- }- setEntries(data);- console.debug('[sync-audit] load: ok token=%d entries=%d', reloadToken, data.length);- } catch (err) {- console.error('[sync-audit] fetch failed', err);- } finally {- if (!cancelled) {- setLoading(false);- setRefreshing(false);- }- }- })();- // Labels and source ids only. A failed or superseded read keeps what the- // last read that answered said, and a row with no label names itself by- // its scope.- void (async () => {- try {- const statuses = await memorySourcesStatusList();- if (cancelled) return;- setLabels(sourceLabelsById(statuses));- setSourceIds(new Set(statuses.map(status => status.source_id)));- } catch (err) {- if (!cancelled) {- console.warn('[sync-audit] status list failed; keeping the last labels', err);- }- }- })();- return () => {- cancelled = true;- };- }, [reloadToken]);-- // A run ending is when the history changes, whichever tab started the run.- useEffect(() => {- let timer: ReturnType<typeof setTimeout> | undefined;- const unsubscribe = subscribeTerminalSyncEvents(({ rowId, stage }) => {- console.debug('[sync-audit] run ended rowId=%s stage=%s', rowId, stage);- if (timer !== undefined) clearTimeout(timer);- timer = setTimeout(() => {- timer = undefined;- reload('run-ended');- }, REFETCH_AFTER_RUN_ENDS_MS);- });- return () => {- unsubscribe();- if (timer !== undefined) clearTimeout(timer);- };- }, [reload]);-- // While anything is syncing, keep reading: a run whose end the socket never- // delivered still reaches the history on the next tick.- useEffect(() => {- if (!anySyncing) return undefined;- const id = setInterval(() => {- reload('poll');- }, POLL_WHILE_SYNCING_MS);- return () => clearInterval(id);- }, [anySyncing, reload]);-- const statusOf = (e: SyncAuditEntry): SyncStatus =>- e.success- ? 'success'- : (e.tree_ingest_failures ?? 0) > 0 || e.tree_error- ? 'partial'- : 'failed';- const sourceName = (e: SyncAuditEntry) => labels[e.source_id] ?? scopeLabel(e.scope);-- const needle = query.trim().toLowerCase();- const visible = entries.filter(e => {- if (statusFilter.size > 0 && !statusFilter.has(statusOf(e))) return false;- if (!needle) return true;- return sourceName(e).toLowerCase().includes(needle) || e.scope.toLowerCase().includes(needle);- });-- const totalCost = entries.reduce((s, e) => s + e.estimated_cost_usd, 0);- const totalInput = entries.reduce((s, e) => s + e.input_tokens, 0);- const totalOutput = entries.reduce((s, e) => s + e.output_tokens, 0);- const summary =- entries.length > 0 ? (- <span className="inline-flex flex-wrap items-center gap-x-2">- <span>- {entries.length} {t('sync.runs', 'sync runs')}- </span>- <span aria-hidden>·</span>- <span>- {t('sync.tokensInOut', '{in} in / {out} out')- .replace('{in}', formatTokens(totalInput))- .replace('{out}', formatTokens(totalOutput))}- </span>- <span aria-hidden>·</span>- <span className="font-medium text-content-secondary">- ${totalCost.toFixed(4)} {t('sync.totalCost', 'total')}- </span>- </span>- ) : undefined;-- const columns: DataTableColumn<SyncAuditEntry>[] = [- {- id: 'when',- header: t('sync.when', 'When'),- className: 'w-px whitespace-nowrap tabular-nums',- cell: e => <WhenCell iso={e.timestamp} ago={timeAgo(e.timestamp, t)} />,- },- {- id: 'source',- header: t('sync.source', 'Source'),- className: 'w-full max-w-0',- cell: e => (- <span className="block truncate" title={e.scope}>- {sourceName(e)}- </span>- ),- },- {- id: 'items',- header: t('sync.items', 'Items'),- align: 'right',- className: 'w-px whitespace-nowrap tabular-nums',- cell: e => e.items_fetched,- },- {- id: 'tokens',- header: t('sync.tokens', 'Tokens'),- align: 'right',- className: 'w-px whitespace-nowrap tabular-nums',- cell: e => (- <span title={`${e.input_tokens} in / ${e.output_tokens} out`}>- {formatTokens(e.input_tokens + e.output_tokens)}- </span>- ),- },- {- id: 'cost',- header: t('sync.cost', 'Cost'),- align: 'right',- className: 'w-px whitespace-nowrap tabular-nums font-medium',- cell: e => `$${e.estimated_cost_usd.toFixed(4)}`,- },- {- id: 'duration',- header: t('sync.duration', 'Duration'),- align: 'right',- className: 'w-px whitespace-nowrap tabular-nums text-content-muted',- cell: e => formatDuration(e.duration_ms),- },- {- id: 'status',- header: t('sync.statusColumn', 'Status'),- align: 'right',- className: 'w-px whitespace-nowrap',- cell: e => {- const status = statusOf(e);- // openhuman#5820: a fetch that committed while the memory-tree half- // dropped items is its own "partial" verdict, not a plain failure. The- // tooltip carries the core's error so the row explains itself.- const title =- status === 'success'- ? t('sync.status.success', 'Success')- : status === 'partial'- ? (e.tree_error ?? t('sync.status.partial', 'Fetched, memory ingest failed'))- : (e.error ?? t('sync.status.failed', 'Failed'));- return (- <Badge variant={STATUS_VARIANT[status]} title={title} data-status={status}>- {t(STATUS_LABEL_KEY[status])}- </Badge>- );- },- },- ];-- return (- <DataTable<SyncAuditEntry>- // Sits among other cards on the scrolling Sync tab: capped, scrolls inside.- fill={fill}- maxHeight="24rem"- testId="sync-history-table"- title={t('sync.auditTitle', 'Sync History')}- description={summary}- actions={- <Button- variant="secondary"- size="sm"- analyticsId="sync-history-refresh"- data-testid="sync-history-refresh"- leadingIcon={<RefreshCw className="h-3.5 w-3.5" aria-hidden />}- disabled={refreshing}- onClick={() => {- setRefreshing(true);- reload('manual');- }}>- {t('common.refresh', 'Refresh')}- </Button>- }- search={- entries.length > 0- ? {- value: query,- onChange: setQuery,- placeholder: t('sync.searchPlaceholder', 'Search sources…'),- testId: 'sync-history-search',- }- : undefined- }- filters={- entries.length > 0- ? [- {- id: 'status',- label: t('sync.statusColumn', 'Status'),- options: (['success', 'partial', 'failed'] as const).map(value => ({- value,- label: t(STATUS_LABEL_KEY[value]),- })),- selected: statusFilter,- onChange: setStatusFilter,- testId: 'sync-history-status-filter',- },- ]- : undefined- }- columns={columns}- rows={visible}- rowKey={(e, i) => `${e.timestamp}-${i}`}- pagination={{ pageSize: fill ? 25 : 10 }}- loading={loading}- loadingRows={4}- empty={- <EmptyState- label={- entries.length === 0- ? t('sync.noAuditEntries', 'No sync runs recorded yet.')- : t('common.noResults', 'No results')- }- />- }- ariaLabel={t('sync.auditTitle', 'Sync History')}- />- );-}diff --git a/app/src/components/intelligence/VaultHealthChecklist.test.tsx b/app/src/components/intelligence/VaultHealthChecklist.test.tsxdeleted file mode 100644index f54d2fe240..0000000000--- a/app/src/components/intelligence/VaultHealthChecklist.test.tsx+++ /dev/null@@ -1,132 +0,0 @@-import { fireEvent, screen, waitFor } from '@testing-library/react';-import { describe, expect, it, type Mock, vi } from 'vitest';--import { renderWithProviders } from '../../test/test-utils';-import type { VaultHealthCheck } from '../../utils/tauriCommands';-import { VaultHealthChecklist } from './VaultHealthChecklist';--vi.mock('../../utils/tauriCommands', () => ({ memoryTreeVaultHealthCheck: vi.fn() }));--vi.mock('../../utils/openUrl', () => ({- openUrl: vi.fn().mockResolvedValue(undefined),- revealPath: vi.fn().mockResolvedValue(undefined),-}));--vi.mock('./vaultHostMatch', () => ({- resolveVaultHostMatch: vi.fn().mockResolvedValue({ local: true }),-}));--const { memoryTreeVaultHealthCheck } = (await import('../../utils/tauriCommands')) as unknown as {- memoryTreeVaultHealthCheck: Mock;-};--const { openUrl, revealPath } = (await import('../../utils/openUrl')) as unknown as {- openUrl: Mock;- revealPath: Mock;-};--const { resolveVaultHostMatch } = (await import('./vaultHostMatch')) as unknown as {- resolveVaultHostMatch: Mock;-};--function health(overrides: Partial<VaultHealthCheck> = {}): VaultHealthCheck {- return {- content_root_abs: '/tmp/workspace/memory_tree/content',- exists: true,- readable: true,- writable: true,- obsidian_registered: true,- pipeline_healthy: true,- last_sync_ms: Date.now() - 60_000,- ...overrides,- };-}--describe('<VaultHealthChecklist />', () => {- it('shows all checks as passed when the health RPC is fully healthy', async () => {- memoryTreeVaultHealthCheck.mockResolvedValueOnce(health());- renderWithProviders(<VaultHealthChecklist />);-- await waitFor(() => {- expect(screen.getByTestId('vault-health-item-exists')).toBeInTheDocument();- });- expect(screen.getByText(/Passed · Workspace vault path exists/)).toBeInTheDocument();- expect(screen.getByText(/Passed · Vault is writable by OpenHuman/)).toBeInTheDocument();- expect(screen.getByText(/Passed · Vault is registered in Obsidian/)).toBeInTheDocument();- expect(screen.getByText(/Passed · Memory pipeline is healthy/)).toBeInTheDocument();- });-- it('surfaces a recovery hint when the vault folder is missing', async () => {- memoryTreeVaultHealthCheck.mockResolvedValueOnce(health({ exists: false, readable: false }));- renderWithProviders(<VaultHealthChecklist />);-- await waitFor(() => {- expect(screen.getByTestId('vault-health-item-exists')).toBeInTheDocument();- });- expect(screen.getByText(/Vault folder is missing/)).toBeInTheDocument();- });-- it('surfaces a recovery hint when the vault is not writable', async () => {- memoryTreeVaultHealthCheck.mockResolvedValueOnce(health({ writable: false }));- renderWithProviders(<VaultHealthChecklist />);-- await waitFor(() => {- expect(screen.getByTestId('vault-health-item-writable')).toBeInTheDocument();- });- expect(screen.getByText(/cannot write to this vault yet/i)).toBeInTheDocument();- });-- it('surfaces Obsidian registration guidance and action buttons', async () => {- memoryTreeVaultHealthCheck.mockResolvedValueOnce(health({ obsidian_registered: false }));- renderWithProviders(<VaultHealthChecklist />);-- await waitFor(() => {- expect(screen.getByTestId('vault-health-item-obsidian')).toBeInTheDocument();- });- expect(screen.getByText(/Open folder as vault/)).toBeInTheDocument();-- fireEvent.click(screen.getByTestId('vault-health-open-obsidian'));- await waitFor(() => {- expect(openUrl).toHaveBeenCalledWith(- 'obsidian://open?path=' + encodeURIComponent('/tmp/workspace/memory_tree/content')- );- });-- fireEvent.click(screen.getByTestId('vault-health-reveal'));- await waitFor(() => {- expect(revealPath).toHaveBeenCalledWith('/tmp/workspace/memory_tree/content');- });- });-- // #4278: vault on a different-OS core host — surface a banner and disable the- // local-FS actions instead of letting them act on a foreign path.- it('warns and disables local actions when the vault is on a different-OS core host', async () => {- memoryTreeVaultHealthCheck.mockResolvedValueOnce(health({ host_os: 'linux' }));- resolveVaultHostMatch.mockResolvedValueOnce({ local: false, hostOs: 'linux' });- renderWithProviders(<VaultHealthChecklist />);-- await waitFor(() => {- expect(screen.getByTestId('vault-health-cross-host')).toBeInTheDocument();- });- expect(screen.getByTestId('vault-health-cross-host')).toHaveTextContent('linux');- expect(screen.getByTestId('vault-health-reveal')).toBeDisabled();- expect(screen.getByTestId('vault-health-open-obsidian')).toBeDisabled();-- fireEvent.click(screen.getByTestId('vault-health-reveal'));- fireEvent.click(screen.getByTestId('vault-health-open-obsidian'));- expect(revealPath).not.toHaveBeenCalled();- expect(openUrl).not.toHaveBeenCalled();- });-- it('keeps local actions enabled for a same-host vault (regression)', async () => {- memoryTreeVaultHealthCheck.mockResolvedValueOnce(health({ host_os: 'macos' }));- resolveVaultHostMatch.mockResolvedValueOnce({ local: true, hostOs: 'macos' });- renderWithProviders(<VaultHealthChecklist />);-- await waitFor(() => {- expect(screen.getByTestId('vault-health-reveal')).toBeInTheDocument();- });- expect(screen.queryByTestId('vault-health-cross-host')).not.toBeInTheDocument();- expect(screen.getByTestId('vault-health-reveal')).not.toBeDisabled();- });-});diff --git a/app/src/components/intelligence/VaultHealthChecklist.tsx b/app/src/components/intelligence/VaultHealthChecklist.tsxdeleted file mode 100644index 249069ae55..0000000000--- a/app/src/components/intelligence/VaultHealthChecklist.tsx+++ /dev/null@@ -1,245 +0,0 @@-import { useCallback, useEffect, useMemo, useState } from 'react';--import { useT } from '../../lib/i18n/I18nContext';-import type { ToastNotification } from '../../types/intelligence';-import { openUrl, revealPath } from '../../utils/openUrl';-import { memoryTreeVaultHealthCheck, type VaultHealthCheck } from '../../utils/tauriCommands';-import Button from '../ui/Button';-import { resolveVaultHostMatch, type VaultHostMatch } from './vaultHostMatch';--const OBSIDIAN_DOWNLOAD_URL = 'https://obsidian.md/download';--interface VaultHealthChecklistProps {- onToast?: (toast: Omit<ToastNotification, 'id'>) => void;- title?: string;-}--function formatRelativeTime(ms: number, t: (key: string, fallback?: string) => string): string {- if (!ms || ms <= 0) return t('vaultHealth.timeNever');- const diff = Date.now() - ms;- if (diff < 0) return t('vaultHealth.timeNever');- const sec = Math.floor(diff / 1000);- if (sec < 45) return t('vaultHealth.timeJustNow');- const min = Math.floor(sec / 60);- if (min < 60) return t('vaultHealth.timeMinAgo').replace('{n}', String(min));- const hr = Math.floor(min / 60);- if (hr < 24) return t('vaultHealth.timeHrAgo').replace('{n}', String(hr));- const day = Math.floor(hr / 24);- return (day === 1 ? t('vaultHealth.timeDayAgo') : t('vaultHealth.timeDaysAgo')).replace(- '{n}',- String(day)- );-}--function dirname(path: string): string {- const normalized = path.replace(/[\\/]+$/, '');- const slash = Math.max(normalized.lastIndexOf('/'), normalized.lastIndexOf('\\'));- if (slash <= 0) return normalized;- return normalized.slice(0, slash);-}--export function VaultHealthChecklist({ onToast, title }: VaultHealthChecklistProps) {- const { t } = useT();- const resolvedTitle = title ?? t('vaultHealth.title');- const [health, setHealth] = useState<VaultHealthCheck | null>(null);- const [hostMatch, setHostMatch] = useState<VaultHostMatch | null>(null);- const [loading, setLoading] = useState(true);- const [refreshing, setRefreshing] = useState(false);- const [error, setError] = useState<string | null>(null);-- const runCheck = useCallback(async () => {- setRefreshing(true);- try {- const next = await memoryTreeVaultHealthCheck();- setHealth(next);- setHostMatch(await resolveVaultHostMatch(next.host_os));- setError(null);- } catch (err) {- const message = err instanceof Error ? err.message : String(err);- setError(message);- } finally {- setRefreshing(false);- setLoading(false);- }- }, []);-- useEffect(() => {- void runCheck();- }, [runCheck]);-- const revealTarget = useMemo(() => {- if (!health?.content_root_abs) return '';- return health.exists ? health.content_root_abs : dirname(health.content_root_abs);- }, [health]);-- // #4278: the vault lives on the core host's filesystem. When this frontend- // runs on a different OS than the core, the path can't be opened/registered- // locally — disable the local-FS actions and explain why instead of firing a- // doomed reveal / deep link.- const crossHost = hostMatch ? !hostMatch.local : false;-- const openObsidian = useCallback(() => {- if (!health?.content_root_abs) return;- void (async () => {- try {- await openUrl(`obsidian://open?path=${encodeURIComponent(health.content_root_abs)}`);- } catch (err) {- const message = err instanceof Error ? err.message : String(err);- onToast?.({ type: 'error', title: t('vaultHealth.openObsidianError'), message });- }- })();- }, [health, onToast, t]);-- const revealVault = useCallback(() => {- if (!revealTarget) return;- void (async () => {- try {- await revealPath(revealTarget);- } catch (err) {- const message = err instanceof Error ? err.message : String(err);- onToast?.({ type: 'error', title: t('vaultHealth.revealError'), message });- }- })();- }, [onToast, revealTarget, t]);-- const installObsidian = useCallback(() => {- void (async () => {- try {- await openUrl(OBSIDIAN_DOWNLOAD_URL);- } catch (err) {- const message = err instanceof Error ? err.message : String(err);- onToast?.({ type: 'error', title: t('vaultHealth.downloadError'), message });- }- })();- }, [onToast, t]);-- const checklist = health- ? [- {- key: 'exists',- label: t('vaultHealth.existsLabel'),- ok: health.exists,- recovery: t('vaultHealth.existsRecovery'),- },- {- key: 'writable',- label: t('vaultHealth.writableLabel'),- ok: health.writable,- recovery: t('vaultHealth.writableRecovery'),- },- {- key: 'obsidian',- label: t('vaultHealth.obsidianLabel'),- ok: health.obsidian_registered,- recovery: t('vaultHealth.obsidianRecovery'),- },- {- key: 'pipeline',- label: t('vaultHealth.pipelineLabel'),- ok: health.pipeline_healthy,- recovery: t('vaultHealth.pipelineRecovery'),- },- ]- : [];-- return (- <div- className="rounded-xl border border-line bg-surface p-4 space-y-3"- data-testid="vault-health-checklist">- <div className="flex items-start justify-between gap-2">- <div>- <h3 className="text-sm font-semibold text-content">{resolvedTitle}</h3>- <p className="mt-1 text-xs text-content-secondary">- {t('vaultHealth.workspaceVault')} <code className="font-mono">memory_tree/content</code>- </p>- </div>- <Button- variant="secondary"- size="xs"- onClick={() => {- void runCheck();- }}- disabled={refreshing}- data-testid="vault-health-refresh">- {refreshing ? t('vaultHealth.refreshing') : t('vaultHealth.refresh')}- </Button>- </div>-- {health?.content_root_abs ? (- <code- className="block break-all rounded-md bg-surface-subtle px-2 py-1 text-[11px] text-content-secondary"- data-testid="vault-health-path">- {health.content_root_abs}- </code>- ) : null}-- {crossHost ? (- <div- className="rounded-md border border-amber-200 dark:border-amber-500/30 bg-amber-50 dark:bg-amber-500/10 px-3 py-2 text-xs text-amber-800 dark:text-amber-200"- data-testid="vault-health-cross-host">- <span className="font-semibold">{t('crossHostVault.title')}</span>{' '}- {t('crossHostVault.message').replace('{os}', hostMatch?.hostOs ?? '')}- </div>- ) : null}-- <div className="flex flex-wrap gap-2">- <Button- variant="secondary"- size="sm"- onClick={revealVault}- disabled={!health?.content_root_abs || crossHost}- data-testid="vault-health-reveal">- {t('vaultHealth.revealFolder')}- </Button>- <Button- type="button"- variant="secondary"- size="sm"- onClick={openObsidian}- disabled={!health?.content_root_abs || crossHost}- className="border-violet-300 dark:border-violet-500/40 text-violet-700 dark:text-violet-300"- data-testid="vault-health-open-obsidian">- {t('vaultHealth.openInObsidian')}- </Button>- <Button- variant="secondary"- size="sm"- onClick={installObsidian}- data-testid="vault-health-install-obsidian">- {t('vaultHealth.installObsidian')}- </Button>- </div>-- {loading ? (- <div className="h-16 rounded-md bg-surface-subtle animate-pulse" />- ) : error ? (- <div- className="rounded-md border border-coral-200 dark:border-coral-500/30 bg-coral-50 dark:bg-coral-500/10 px-3 py-2 text-xs text-coral-700 dark:text-coral-300"- data-testid="vault-health-error">- {t('vaultHealth.loadError')} {error}- </div>- ) : (- <div className="space-y-2">- {checklist.map(item => (- <div- key={item.key}- data-testid={`vault-health-item-${item.key}`}- className={`rounded-md border px-3 py-2 text-xs ${- item.ok- ? 'border-sage-200 dark:border-sage-500/30 bg-sage-50 dark:bg-sage-500/10 text-sage-800 dark:text-sage-200'- : 'border-amber-200 dark:border-amber-500/30 bg-amber-50 dark:bg-amber-500/10 text-amber-800 dark:text-amber-200'- }`}>- <div className="font-semibold">- {item.ok ? t('vaultHealth.passed') : t('vaultHealth.needsAttention')} · {item.label}- </div>- {!item.ok ? <p className="mt-1 leading-relaxed">{item.recovery}</p> : null}- </div>- ))}- <p className="text-[11px] text-content-secondary" data-testid="vault-health-last-sync">- {t('vaultHealth.lastSync')} {formatRelativeTime(health?.last_sync_ms ?? 0, t)}- </p>- </div>- )}- </div>- );-}diff --git a/app/src/components/intelligence/__tests__/CodingSessionsCard.test.tsx b/app/src/components/intelligence/__tests__/CodingSessionsCard.test.tsxdeleted file mode 100644index 9ba2be2c9d..0000000000--- a/app/src/components/intelligence/__tests__/CodingSessionsCard.test.tsx+++ /dev/null@@ -1,309 +0,0 @@-import { fireEvent, screen, waitFor } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import * as service from '../../../services/memorySourcesService';-import { renderWithProviders } from '../../../test/test-utils';-import { CodingSessionsCard } from '../CodingSessionsCard';--vi.mock('../../../services/memorySourcesService', async () => {- const actual = await vi.importActual<typeof import('../../../services/memorySourcesService')>(- '../../../services/memorySourcesService'- );- return { ...actual, getCodingSessionStatus: vi.fn(), drainCodingSessions: vi.fn() };-});--const mockedStatus = vi.mocked(service.getCodingSessionStatus);-const mockedDrain = vi.mocked(service.drainCodingSessions);--describe('CodingSessionsCard', () => {- beforeEach(() => {- vi.clearAllMocks();- mockedStatus.mockResolvedValue([- {- kind: 'claude_code',- available: true,- session_files: 2,- evidence_units: 4,- invalid_files: 0,- },- { kind: 'codex', available: true, session_files: 3, evidence_units: 7, invalid_files: 0 },- ]);- });-- it('shows discovered local session counts', async () => {- renderWithProviders(<CodingSessionsCard />);-- expect(await screen.findByTestId('coding-session-source-claude_code')).toHaveTextContent(- '2 sessions · 4 human turns'- );- expect(screen.getByTestId('coding-session-source-codex')).toHaveTextContent(- '3 sessions · 7 human turns'- );- expect(screen.getByTestId('coding-sessions-ingest')).toBeEnabled();- expect(screen.getByTestId('coding-sessions-ingest')).toHaveAttribute(- 'data-analytics-id',- 'brain-sources-coding-sessions-ingest'- );- });-- it('drains the whole backlog and reports the distilled observations', async () => {- mockedDrain.mockResolvedValue({- passes: 2,- sessionsProcessed: 4,- sessionsFailed: 0,- observations: 6,- remaining: 0,- moreRemaining: false,- timedOut: false,- });- const onToast = vi.fn();- renderWithProviders(<CodingSessionsCard onToast={onToast} />);-- fireEvent.click(await screen.findByTestId('coding-sessions-ingest'));-- await waitFor(() =>- expect(mockedDrain).toHaveBeenCalledWith(- expect.objectContaining({- onProgress: expect.any(Function),- shouldStop: expect.any(Function),- })- )- );- await waitFor(() =>- expect(onToast).toHaveBeenCalledWith(- expect.objectContaining({- type: 'success',- message: '4 sessions produced 6 persona observations.',- })- )- );- });-- it('keeps ingestion disabled when no human-authored evidence exists', async () => {- mockedStatus.mockResolvedValue([- { kind: 'codex', available: false, session_files: 0, evidence_units: 0, invalid_files: 0 },- ]);- renderWithProviders(<CodingSessionsCard />);-- expect(await screen.findByText('No local history found')).toBeInTheDocument();- expect(screen.getByTestId('coding-sessions-ingest')).toBeDisabled();- });-- it('shows live progress and pauses the drain when the user stops', async () => {- let finishDrain!: () => void;- mockedDrain.mockImplementation(({ onProgress } = {}) => {- onProgress?.({- passes: 1,- sessionsProcessed: 5,- sessionsFailed: 0,- observations: 3,- remaining: 25,- moreRemaining: true,- timedOut: false,- });- return new Promise(resolve => {- finishDrain = () =>- resolve({- passes: 1,- sessionsProcessed: 5,- sessionsFailed: 0,- observations: 3,- remaining: 25,- moreRemaining: true,- timedOut: false,- });- });- });- const onToast = vi.fn();- renderWithProviders(<CodingSessionsCard onToast={onToast} />);-- fireEvent.click(await screen.findByTestId('coding-sessions-ingest'));-- // Live progress renders mid-drain.- expect(await screen.findByTestId('coding-sessions-progress')).toHaveTextContent(- '5 sessions imported · 3 observations · about 25 left'- );-- // Stopping mid-drain reports a paused import with the remaining estimate.- fireEvent.click(await screen.findByTestId('coding-sessions-stop'));- finishDrain();-- await waitFor(() =>- expect(onToast).toHaveBeenCalledWith(- expect.objectContaining({- type: 'info',- title: 'Import paused',- message: 'Imported 5 sessions. Run import again to continue the remaining 25.',- })- )- );- });-- it('reports a paused import when the backlog remains without a user stop (cap/stall)', async () => {- // moreRemaining=true with no Stop click — the drain hit the pass cap or- // stalled. This must NOT be reported as a complete success.- mockedDrain.mockResolvedValue({- passes: 2000,- sessionsProcessed: 30000,- sessionsFailed: 0,- observations: 12000,- remaining: 300,- moreRemaining: true,- timedOut: false,- });- const onToast = vi.fn();- renderWithProviders(<CodingSessionsCard onToast={onToast} />);-- fireEvent.click(await screen.findByTestId('coding-sessions-ingest'));-- await waitFor(() =>- expect(onToast).toHaveBeenCalledWith(- expect.objectContaining({- type: 'info',- title: 'Import paused',- message: 'Imported 30000 sessions. Run import again to continue the remaining 300.',- })- )- );- });-- it('reports partial session failures in the warning toast', async () => {- mockedDrain.mockResolvedValue({- passes: 1,- sessionsProcessed: 3,- sessionsFailed: 2,- observations: 4,- remaining: 0,- moreRemaining: false,- timedOut: false,- });- const onToast = vi.fn();- renderWithProviders(<CodingSessionsCard onToast={onToast} />);-- fireEvent.click(await screen.findByTestId('coding-sessions-ingest'));-- await waitFor(() =>- expect(onToast).toHaveBeenCalledWith(- expect.objectContaining({- type: 'warning',- message: '2 sessions failed while 3 were processed. Run ingestion again to retry them.',- })- )- );- });-- it('shows status failures as an alert', async () => {- mockedStatus.mockRejectedValue(new Error('session scan failed'));- renderWithProviders(<CodingSessionsCard />);-- expect(await screen.findByRole('alert')).toHaveTextContent('session scan failed');- });-- it('does not report a deadline as a failure banner', async () => {- // The defect this test exists for (#5802): the import completes seconds- // after the caller stops waiting, and the user was shown a red "ingestion- // failed" banner over work that had succeeded — then invited to redo a- // 35-60s job. A deadline must read as "still running", never as a failure.- mockedDrain.mockResolvedValue({- passes: 1,- sessionsProcessed: 3,- sessionsFailed: 0,- observations: 15,- remaining: 419,- moreRemaining: true,- timedOut: true,- });- const onToast = vi.fn();- renderWithProviders(<CodingSessionsCard onToast={onToast} />);-- fireEvent.click(await screen.findByTestId('coding-sessions-ingest'));-- await waitFor(() =>- expect(onToast).toHaveBeenCalledWith(- expect.objectContaining({- type: 'info',- title: 'Import still running',- message: expect.stringContaining('Sessions imported so far: 3'),- })- )- );- // No error toast and no inline alert — both would tell the user the import- // is over when it is not.- expect(onToast).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }));- expect(screen.queryByRole('alert')).toBeNull();- });-- it('leads with the deadline when a stale failure count is also present', async () => {- // `sessionsFailed` carries the last *completed* pass's count, so on a- // timeout it describes superseded work. Reporting it would tell the user to- // retry a run that has not finished.- mockedDrain.mockResolvedValue({- passes: 2,- sessionsProcessed: 4,- sessionsFailed: 2,- observations: 9,- remaining: 100,- moreRemaining: true,- timedOut: true,- });- const onToast = vi.fn();- renderWithProviders(<CodingSessionsCard onToast={onToast} />);-- fireEvent.click(await screen.findByTestId('coding-sessions-ingest'));-- await waitFor(() =>- expect(onToast).toHaveBeenCalledWith(- expect.objectContaining({ type: 'info', title: 'Import still running' })- )- );- expect(onToast).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'warning' }));- });-- it('reports ingestion failures through the error toast', async () => {- mockedDrain.mockRejectedValue(new Error('persona pipeline failed'));- const onToast = vi.fn();- renderWithProviders(<CodingSessionsCard onToast={onToast} />);-- fireEvent.click(await screen.findByTestId('coding-sessions-ingest'));-- await waitFor(() =>- expect(onToast).toHaveBeenCalledWith({- type: 'error',- title: 'Coding-session ingestion failed',- message: 'persona pipeline failed',- })- );- });-- it('warns when a source scan reaches its file cap', async () => {- mockedStatus.mockResolvedValue([- {- kind: 'codex',- available: true,- session_files: 1000,- evidence_units: 1200,- invalid_files: 0,- scan_truncated: true,- },- ]);- renderWithProviders(<CodingSessionsCard />);-- expect(await screen.findByText('Scan limited to the first 1,000 session files.')).toBeVisible();- });-- it('keeps ingestion enabled when a capped scan has not found evidence yet', async () => {- mockedStatus.mockResolvedValue([- {- kind: 'codex',- available: true,- session_files: 1000,- evidence_units: 0,- invalid_files: 1000,- scan_truncated: true,- },- ]);- renderWithProviders(<CodingSessionsCard />);-- expect(await screen.findByTestId('coding-sessions-ingest')).toBeEnabled();- });-});diff --git a/app/src/components/intelligence/__tests__/MemorySourcesRegistry.sync.test.tsx b/app/src/components/intelligence/__tests__/MemorySourcesRegistry.sync.test.tsxdeleted file mode 100644index 188a2406bf..0000000000--- a/app/src/components/intelligence/__tests__/MemorySourcesRegistry.sync.test.tsx+++ /dev/null@@ -1,802 +0,0 @@-/**- * Tests for MemorySourcesRegistry (issue #3295):- *- * RC#1 — concurrent syncs: multiple sources can show "syncing" simultaneously.- * RC#2 — source_id matching: events matched by source_id (preferred) or- * connection_id (fallback) for backward compat.- * RC#4 — tolerant parseSyncProgress: numeric ratio, stage fallback, and- * indeterminate (null) cases.- */-import { act, fireEvent, screen, waitFor } from '@testing-library/react';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { renderWithProviders } from '../../../test/test-utils';-import {- MemorySourcesRegistry,- parseIngestedCount,- parseSyncNote,- parseSyncProgress,-} from '../MemorySourcesRegistry';-import { resetMemorySyncActivityForTests } from '../memorySyncActivityStore';--// ── i18n mock (returns key as the translation) ────────────────────────────────-vi.mock('../../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (key: string) => key }) }));--// ── memorySourcesService mock ─────────────────────────────────────────────────-vi.mock('../../../services/memorySourcesService', () => ({- listMemorySources: vi.fn().mockResolvedValue([]),- memorySourcesStatusList: vi.fn().mockResolvedValue([]),- syncMemorySource: vi.fn().mockResolvedValue(undefined),- removeMemorySource: vi.fn().mockResolvedValue(undefined),- updateMemorySource: vi- .fn()- .mockImplementation((id: string, patch: Record<string, unknown>) =>- Promise.resolve({ id, kind: 'folder', label: 'Test', enabled: true, ...patch })- ),- SOURCE_KIND_ICONS: {- folder: 'F',- composio: 'C',- github_repo: 'G',- rss_feed: 'R',- web_page: 'W',- twitter_query: 'T',- },- SOURCE_KIND_LABEL_KEYS: {- folder: 'memorySources.kind.folder',- composio: 'memorySources.kind.composio',- github_repo: 'memorySources.kind.github_repo',- rss_feed: 'memorySources.kind.rss_feed',- web_page: 'memorySources.kind.web_page',- twitter_query: 'memorySources.kind.twitter_query',- },-}));--// ── tauriCommands mock ────────────────────────────────────────────────────────-// memoryTreePipelineStatus is polled for downstream pipeline health (GH-4690);-// default to a healthy running snapshot so rows keep their clean synced state.-const mockTrackAnalyticsEvent = vi.fn();-vi.mock('../../analytics', () => ({- trackAnalyticsEvent: (...args: unknown[]) => mockTrackAnalyticsEvent(...args),-}));--vi.mock('../../../utils/tauriCommands/memoryTree', () => ({- memoryTreeBackfillConnectorTrees: vi.fn(),- memoryTreeBackfillStatus: vi.fn().mockResolvedValue({ in_progress: false, pending_jobs: 0 }),- memoryTreeFlushSource: vi.fn().mockResolvedValue({ seals_fired: 0 }),- memoryTreePipelineStatus: vi- .fn()- .mockResolvedValue({- status: 'running',- reason: null,- last_sync_ms: 0,- total_chunks: 0,- wiki_size_bytes: 0,- pipeline_jobs: { ready: 0, running: 0, failed: 0 },- is_syncing: false,- is_paused: false,- }),-}));--// ── helpers ───────────────────────────────────────────────────────────────────--function makeSyncStageEvent(detail: {- stage: string;- source_id?: string | null;- connection_id?: string | null;- detail?: string;-}): CustomEvent {- return new CustomEvent('openhuman:memory-sync-stage', { detail });-}--function makeSource(id: string) {- return { id, kind: 'folder' as const, label: `Source ${id}`, enabled: true };-}--// ── parseSyncProgress unit tests ──────────────────────────────────────────────--describe('parseSyncProgress', () => {- it('returns ratio for "N/M ..." numeric pattern', () => {- expect(parseSyncProgress('5/10 processed', 'ingesting')).toBe(50);- expect(parseSyncProgress('3/12 docs', 'fetching')).toBe(25);- expect(parseSyncProgress('1/1 done', 'ingesting')).toBe(100);- });-- it('returns stage fallback when no numeric ratio is present', () => {- expect(parseSyncProgress('queue_depth=3', 'ingesting')).toBe(40);- expect(parseSyncProgress('listing items', 'fetching')).toBe(5);- expect(parseSyncProgress(null, 'requested')).toBe(2);- expect(parseSyncProgress('canonicalized 3 chunks', 'stored')).toBe(15);- expect(parseSyncProgress('queued chunk extraction', 'queued')).toBe(25);- });-- it('returns 100 for completed stage', () => {- expect(parseSyncProgress(null, 'completed')).toBe(100);- expect(parseSyncProgress('ingested 5 item(s)', 'completed')).toBe(100);- });-- it('returns null when no ratio and no recognized stage', () => {- expect(parseSyncProgress('some detail', 'unknown_stage')).toBeNull();- expect(parseSyncProgress(null, undefined)).toBeNull();- expect(parseSyncProgress(null)).toBeNull();- });-- it('handles non-ratio numeric strings gracefully', () => {- // "N discovered" — no slash — should use stage fallback, not parse as ratio- expect(parseSyncProgress('3 discovered', 'stored')).toBe(15);- // "N/0 ..." — divide by zero guard- expect(parseSyncProgress('5/0 items', 'fetching')).toBe(5); // falls through to stage fallback- });-});--// ── parseIngestedCount unit tests ─────────────────────────────────────────────--describe('parseIngestedCount', () => {- it('parses the count from "ingested N item(s)"', () => {- expect(parseIngestedCount('ingested 5 item(s)')).toBe(5);- expect(parseIngestedCount('ingested 0 item(s)')).toBe(0);- expect(parseIngestedCount('ingested 123 items')).toBe(123);- });-- it('returns null when no count is present', () => {- expect(parseIngestedCount(null)).toBeNull();- expect(parseIngestedCount('done')).toBeNull();- expect(parseIngestedCount('delegating to composio sync')).toBeNull();- });-});--// ── parseSyncNote unit tests ──────────────────────────────────────────────────--describe('parseSyncNote', () => {- it('reads "more pending" from the remainder after the count', () => {- expect(parseSyncNote('ingested 100 item(s), more pending — Sync again to continue')).toBe(- 'more_pending'- );- });-- it('reads a spent budget, and prefers it when both appear', () => {- expect(parseSyncNote("ingested 0 item(s); today's provider request budget is spent")).toBe(- 'budget_spent'- );- expect(- parseSyncNote(- "ingested 0 item(s), more pending — Sync again to continue; today's provider request budget is spent"- )- ).toBe('budget_spent');- });-- it('returns null for a plain count or no detail', () => {- expect(parseSyncNote('ingested 5 item(s)')).toBeNull();- expect(parseSyncNote(null)).toBeNull();- });-});--// ── MemorySourcesRegistry integration tests ───────────────────────────────────--describe('MemorySourcesRegistry', () => {- // The live sync state is a page-wide store now (openhuman#6019); each test- // starts from nothing in flight.- beforeEach(() => {- resetMemorySyncActivityForTests();- });-- // Expose mock so tests can control what listMemorySources returns.- let listMemorySources: ReturnType<typeof vi.fn>;- let memorySourcesStatusList: ReturnType<typeof vi.fn>;- let syncMemorySource: ReturnType<typeof vi.fn>;-- beforeEach(async () => {- const svc = await import('../../../services/memorySourcesService');- listMemorySources = svc.listMemorySources as ReturnType<typeof vi.fn>;- memorySourcesStatusList = svc.memorySourcesStatusList as ReturnType<typeof vi.fn>;- syncMemorySource = svc.syncMemorySource as ReturnType<typeof vi.fn>;- });-- afterEach(() => {- vi.clearAllMocks();- });-- it('shows two sources as syncing when two concurrent sync-stage events arrive (RC#1)', async () => {- const sources = [makeSource('src-alpha'), makeSource('src-beta')];- listMemorySources.mockResolvedValue(sources);- memorySourcesStatusList.mockResolvedValue([]);-- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);-- // Wait for sources to render.- await waitFor(() => {- expect(screen.getByText('Source src-alpha')).toBeInTheDocument();- expect(screen.getByText('Source src-beta')).toBeInTheDocument();- });-- // Dispatch two concurrent "requested" events with different source_ids.- act(() => {- window.dispatchEvent(- makeSyncStageEvent({- stage: 'requested',- source_id: 'src-alpha',- connection_id: 'src-alpha',- })- );- window.dispatchEvent(- makeSyncStageEvent({ stage: 'requested', source_id: 'src-beta', connection_id: 'src-beta' })- );- });-- // Both rows should show the syncing spinner/text (sync.syncing key → "sync.syncing").- await waitFor(() => {- const syncingButtons = screen.getAllByText('sync.syncing');- expect(syncingButtons).toHaveLength(2);- });- });-- it('clears only one source when completed, leaving the other syncing (RC#1)', async () => {- const sources = [makeSource('src-alpha'), makeSource('src-beta')];- listMemorySources.mockResolvedValue(sources);- memorySourcesStatusList.mockResolvedValue([]);-- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);-- await waitFor(() => {- expect(screen.getByText('Source src-alpha')).toBeInTheDocument();- });-- // Both start syncing.- act(() => {- window.dispatchEvent(- makeSyncStageEvent({- stage: 'requested',- source_id: 'src-alpha',- connection_id: 'src-alpha',- })- );- window.dispatchEvent(- makeSyncStageEvent({ stage: 'requested', source_id: 'src-beta', connection_id: 'src-beta' })- );- });-- await waitFor(() => {- expect(screen.getAllByText('sync.syncing')).toHaveLength(2);- });-- // Complete src-alpha — only src-beta should remain syncing.- act(() => {- window.dispatchEvent(- makeSyncStageEvent({- stage: 'completed',- source_id: 'src-alpha',- connection_id: 'src-alpha',- })- );- });-- await waitFor(() => {- const syncingButtons = screen.getAllByText('sync.syncing');- expect(syncingButtons).toHaveLength(1);- });-- // The one remaining syncing button should be for src-beta.- // The sync button for src-alpha should now show "sync.sync".- const syncButtons = screen.getAllByText('sync.sync');- expect(syncButtons).toHaveLength(1); // src-alpha back to idle- });-- it('failed event also clears the syncing source (RC#1)', async () => {- const sources = [makeSource('src-gamma')];- listMemorySources.mockResolvedValue(sources);- memorySourcesStatusList.mockResolvedValue([]);-- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);-- await waitFor(() => {- expect(screen.getByText('Source src-gamma')).toBeInTheDocument();- });-- act(() => {- window.dispatchEvent(makeSyncStageEvent({ stage: 'fetching', source_id: 'src-gamma' }));- });-- await waitFor(() => {- expect(screen.getByText('sync.syncing')).toBeInTheDocument();- });-- act(() => {- window.dispatchEvent(makeSyncStageEvent({ stage: 'failed', source_id: 'src-gamma' }));- });-- await waitFor(() => {- expect(screen.queryByText('sync.syncing')).not.toBeInTheDocument();- expect(screen.getByText('sync.sync')).toBeInTheDocument();- });- });-- it('matches events by source_id when present, ignoring connection_id (RC#2)', async () => {- const sources = [makeSource('src-new')];- listMemorySources.mockResolvedValue(sources);- memorySourcesStatusList.mockResolvedValue([]);-- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);-- await waitFor(() => {- expect(screen.getByText('Source src-new')).toBeInTheDocument();- });-- // Event with source_id matching the row but a different connection_id- // (e.g. an intermediate stage from the bridge where connection_id = document_id).- act(() => {- window.dispatchEvent(- makeSyncStageEvent({- stage: 'ingesting',- source_id: 'src-new', // matches the row- connection_id: 'mem_src:src-new:doc-123', // ingest-pipeline id, NOT the row id- })- );- });-- // Row should light up because source_id matches.- await waitFor(() => {- expect(screen.getByText('sync.syncing')).toBeInTheDocument();- });- });-- it('falls back to connection_id when source_id is absent (RC#2 backward compat)', async () => {- const sources = [makeSource('src-legacy')];- listMemorySources.mockResolvedValue(sources);- memorySourcesStatusList.mockResolvedValue([]);-- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);-- await waitFor(() => {- expect(screen.getByText('Source src-legacy')).toBeInTheDocument();- });-- // Old-style event: no source_id, connection_id is the row id.- act(() => {- window.dispatchEvent(- makeSyncStageEvent({- stage: 'fetching',- // source_id absent- connection_id: 'src-legacy',- })- );- });-- await waitFor(() => {- expect(screen.getByText('sync.syncing')).toBeInTheDocument();- });- });-- it('ignores events with neither source_id nor connection_id', async () => {- const sources = [makeSource('src-quiet')];- listMemorySources.mockResolvedValue(sources);- memorySourcesStatusList.mockResolvedValue([]);-- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);-- await waitFor(() => {- expect(screen.getByText('Source src-quiet')).toBeInTheDocument();- });-- act(() => {- window.dispatchEvent(- new CustomEvent('openhuman:memory-sync-stage', {- detail: { stage: 'fetching' }, // no source_id, no connection_id- })- );- });-- // Row should remain idle.- await waitFor(() => {- expect(screen.queryByText('sync.syncing')).not.toBeInTheDocument();- });- });-- // ── Terminal result chips (#3295) ──────────────────────────────────────────-- it('shows "N items synced" after a completed event with a non-zero count', async () => {- const sources = [makeSource('src-done')];- listMemorySources.mockResolvedValue(sources);- memorySourcesStatusList.mockResolvedValue([]);-- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);- await waitFor(() => expect(screen.getByText('Source src-done')).toBeInTheDocument());-- act(() => {- window.dispatchEvent(makeSyncStageEvent({ stage: 'fetching', source_id: 'src-done' }));- });- await waitFor(() => expect(screen.getByText('sync.syncing')).toBeInTheDocument());-- act(() => {- window.dispatchEvent(- makeSyncStageEvent({- stage: 'completed',- source_id: 'src-done',- detail: 'ingested 5 item(s)',- })- );- });-- // The result chip persists and shows the parsed count + the (mocked) i18n key.- await waitFor(() => {- const chip = screen.getByTestId('memory-source-result-src-done');- expect(chip).toHaveTextContent('5');- expect(chip).toHaveTextContent('memorySources.sync.itemsSynced');- });- // The progress bar / syncing state is gone.- expect(screen.queryByText('sync.syncing')).not.toBeInTheDocument();- });-- it('shows "Up to date" after a completed event with zero new items', async () => {- const sources = [makeSource('src-noop')];- listMemorySources.mockResolvedValue(sources);- memorySourcesStatusList.mockResolvedValue([]);-- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);- await waitFor(() => expect(screen.getByText('Source src-noop')).toBeInTheDocument());-- act(() => {- window.dispatchEvent(- makeSyncStageEvent({- stage: 'completed',- source_id: 'src-noop',- detail: 'ingested 0 item(s)',- })- );- });-- await waitFor(() => {- const chip = screen.getByTestId('memory-source-result-src-noop');- expect(chip).toHaveTextContent('memorySources.sync.upToDate');- });- });-- it('shows the failure reason after a failed event', async () => {- const sources = [makeSource('src-bad')];- listMemorySources.mockResolvedValue(sources);- memorySourcesStatusList.mockResolvedValue([]);-- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);- await waitFor(() => expect(screen.getByText('Source src-bad')).toBeInTheDocument());-- act(() => {- window.dispatchEvent(- makeSyncStageEvent({- stage: 'failed',- source_id: 'src-bad',- detail: 'composio sync failed: rate limit exceeded',- })- );- });-- await waitFor(() => {- const chip = screen.getByTestId('memory-source-result-src-bad');- expect(chip).toHaveTextContent('memorySources.sync.failedLabel');- expect(chip).toHaveTextContent('rate limit exceeded');- });- });-- it('clears a prior result chip when a new sync starts for that row', async () => {- const sources = [makeSource('src-redo')];- listMemorySources.mockResolvedValue(sources);- memorySourcesStatusList.mockResolvedValue([]);-- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);- await waitFor(() => expect(screen.getByText('Source src-redo')).toBeInTheDocument());-- // First sync completes → chip shown.- act(() => {- window.dispatchEvent(- makeSyncStageEvent({- stage: 'completed',- source_id: 'src-redo',- detail: 'ingested 2 item(s)',- })- );- });- await waitFor(() =>- expect(screen.getByTestId('memory-source-result-src-redo')).toBeInTheDocument()- );-- // A new sync starts (non-terminal event) → chip cleared, progress shown.- act(() => {- window.dispatchEvent(makeSyncStageEvent({ stage: 'fetching', source_id: 'src-redo' }));- });- await waitFor(() => {- expect(screen.queryByTestId('memory-source-result-src-redo')).not.toBeInTheDocument();- expect(screen.getByText('sync.syncing')).toBeInTheDocument();- });- });-- it('shows a failed chip when the sync RPC itself rejects (no stage event arrives)', async () => {- const sources = [makeSource('src-rpcfail')];- listMemorySources.mockResolvedValue(sources);- memorySourcesStatusList.mockResolvedValue([]);- syncMemorySource.mockRejectedValueOnce(new Error('core unreachable'));-- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);- await waitFor(() => expect(screen.getByText('Source src-rpcfail')).toBeInTheDocument());-- // Click the row's sync button (folder kind → testid suffix "folder").- fireEvent.click(screen.getByTestId('memory-source-sync-folder'));-- await waitFor(() => {- const chip = screen.getByTestId('memory-source-result-src-rpcfail');- expect(chip).toHaveTextContent('memorySources.sync.failedLabel');- expect(chip).toHaveTextContent('core unreachable');- });- // The optimistic syncing state is cleared after the RPC rejection.- expect(screen.queryByText('sync.syncing')).not.toBeInTheDocument();- });- it('says the budget is spent instead of "Up to date" when zero items arrive for that reason', async () => {- // The core writes why a run stopped after the count; a spent budget with- // zero new items used to read as "Up to date" — the opposite of what- // happened (openhuman#6012 follow-up).- const sources = [makeSource('src-budget')];- listMemorySources.mockResolvedValue(sources);- memorySourcesStatusList.mockResolvedValue([]);- const onToast = vi.fn();-- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} onToast={onToast} />);- await waitFor(() => expect(screen.getByText('Source src-budget')).toBeInTheDocument());-- act(() => {- window.dispatchEvent(- makeSyncStageEvent({- stage: 'completed',- source_id: 'src-budget',- detail:- "ingested 0 item(s), more pending — Sync again to continue; today's provider request budget is spent",- })- );- });-- await waitFor(() => {- const chip = screen.getByTestId('memory-source-result-src-budget');- expect(chip).toHaveTextContent('memorySources.sync.budgetSpent');- expect(chip).not.toHaveTextContent('memorySources.sync.upToDate');- });- expect(onToast).toHaveBeenCalledWith(- expect.objectContaining({ type: 'warning', message: 'memorySources.sync.budgetSpent' })- );- });-- it('keeps the budget note beside a nonzero count in the toast', async () => {- // A pass that filed some mail and then ran out for the day is the common- // partial case; "N items synced" alone read as a finished sync.- const sources = [makeSource('src-partial')];- listMemorySources.mockResolvedValue(sources);- memorySourcesStatusList.mockResolvedValue([]);- const onToast = vi.fn();-- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} onToast={onToast} />);- await waitFor(() => expect(screen.getByText('Source src-partial')).toBeInTheDocument());-- act(() => {- window.dispatchEvent(- makeSyncStageEvent({- stage: 'completed',- source_id: 'src-partial',- detail: "ingested 3 item(s); today's provider request budget is spent",- })- );- });-- await waitFor(() =>- expect(onToast).toHaveBeenCalledWith(- expect.objectContaining({- type: 'warning',- message: '3 memorySources.sync.itemsSynced — memorySources.sync.budgetSpent',- })- )- );- });-- it('shows the "more to sync" note beside a count when the run stopped at its cap', async () => {- const sources = [makeSource('src-more')];- listMemorySources.mockResolvedValue(sources);- memorySourcesStatusList.mockResolvedValue([]);-- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);- await waitFor(() => expect(screen.getByText('Source src-more')).toBeInTheDocument());-- act(() => {- window.dispatchEvent(- makeSyncStageEvent({- stage: 'completed',- source_id: 'src-more',- detail: 'ingested 100 item(s), more pending — Sync again to continue',- })- );- });-- await waitFor(() => {- expect(screen.getByTestId('memory-source-result-src-more')).toHaveTextContent(- '100 memorySources.sync.itemsSynced'- );- expect(screen.getByTestId('memory-source-note-src-more')).toHaveTextContent(- 'memorySources.sync.morePending'- );- });- });-- it('repairs older memories only after a preview and a confirmation', async () => {- // Backfill has no other entry point in the app (openhuman#6012). The real- // pass embeds every document it files, so the button previews (dry run)- // and asks before it writes anything.- const memoryTree = await import('../../../utils/tauriCommands/memoryTree');- const backfill = memoryTree.memoryTreeBackfillConnectorTrees as ReturnType<typeof vi.fn>;- backfill- .mockResolvedValueOnce({- executed: false,- scanned: 42,- ingested: 0,- already_present: 0,- skipped: 0,- more_pending: false,- notes: [],- })- .mockResolvedValueOnce({- executed: true,- scanned: 42,- ingested: 40,- already_present: 1,- skipped: 1,- more_pending: false,- notes: [],- });- listMemorySources.mockResolvedValue([makeSource('src-a')]);- memorySourcesStatusList.mockResolvedValue([]);- const onToast = vi.fn();-- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} onToast={onToast} />);- await waitFor(() => expect(screen.getByText('Source src-a')).toBeInTheDocument());-- fireEvent.click(screen.getByTestId('repair-memories-button'));- await waitFor(() => expect(backfill).toHaveBeenCalledWith({ dryRun: true }));- // The confirmation names the preview count and nothing has been written.- await waitFor(() =>- expect(screen.getByText('memorySources.repair.confirm')).toBeInTheDocument()- );- expect(backfill).toHaveBeenCalledTimes(1);-- fireEvent.click(screen.getByText('memorySources.repair.confirm'));- await waitFor(() => expect(backfill).toHaveBeenCalledWith({ dryRun: false }));- // The successful domain outcome is tracked with the privacy-safe count only.- await waitFor(() =>- expect(mockTrackAnalyticsEvent).toHaveBeenCalledWith('memory_repair_succeeded', { count: 40 })- );- // The i18n mock returns keys, so the placeholders in the summary are- // not substituted here; the counts are covered by the wrapper's tests.- await waitFor(() =>- expect(onToast).toHaveBeenCalledWith(- expect.objectContaining({ type: 'success', title: 'memorySources.repair.success' })- )- );- });-- it('does not ask when the preview finds nothing to repair', async () => {- const memoryTree = await import('../../../utils/tauriCommands/memoryTree');- const backfill = memoryTree.memoryTreeBackfillConnectorTrees as ReturnType<typeof vi.fn>;- backfill.mockReset();- backfill.mockResolvedValueOnce({- executed: false,- scanned: 0,- ingested: 0,- already_present: 0,- skipped: 0,- more_pending: false,- notes: [],- });- listMemorySources.mockResolvedValue([makeSource('src-b')]);- memorySourcesStatusList.mockResolvedValue([]);- const onToast = vi.fn();-- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} onToast={onToast} />);- await waitFor(() => expect(screen.getByText('Source src-b')).toBeInTheDocument());-- fireEvent.click(screen.getByTestId('repair-memories-button'));- await waitFor(() =>- expect(onToast).toHaveBeenCalledWith(- expect.objectContaining({ title: 'memorySources.repair.nothing' })- )- );- expect(screen.queryByText('memorySources.repair.confirm')).not.toBeInTheDocument();- expect(backfill).toHaveBeenCalledTimes(1);- });- it('says "more to sync" — not "Up to date" — when zero items arrived because the run stopped at its cap', async () => {- // A capped run can write nothing (everything on the page was already- // ingested) and still have more to read. Zero + more-pending used to- // render as "Up to date" beside a "more to sync" note — contradictory.- const sources = [makeSource('src-zero-more')];- listMemorySources.mockResolvedValue(sources);- memorySourcesStatusList.mockResolvedValue([]);-- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);- await waitFor(() => expect(screen.getByText('Source src-zero-more')).toBeInTheDocument());-- act(() => {- window.dispatchEvent(- makeSyncStageEvent({- stage: 'completed',- source_id: 'src-zero-more',- detail: 'ingested 0 item(s), more pending — Sync again to continue',- })- );- });-- await waitFor(() => {- const chip = screen.getByTestId('memory-source-result-src-zero-more');- expect(chip).toHaveTextContent('memorySources.sync.morePending');- expect(chip).not.toHaveTextContent('memorySources.sync.upToDate');- });- expect(screen.queryByTestId('memory-source-note-src-zero-more')).not.toBeInTheDocument();- });-- it('keeps the live bar and then the result across an unmount and remount (openhuman#6019)', async () => {- // Leaving Brain › Sources mid-sync used to drop the bar and miss the- // terminal event: the sync kept running in the core, the screen said idle.- listMemorySources.mockResolvedValue([makeSource('src-persist')]);- memorySourcesStatusList.mockResolvedValue([]);-- const first = renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);- await waitFor(() => expect(screen.getByText('Source src-persist')).toBeInTheDocument());- act(() => {- window.dispatchEvent(makeSyncStageEvent({ stage: 'running', source_id: 'src-persist' }));- });- // openhuman#6257: the row names the stage in plain language.- await waitFor(() =>- expect(screen.getByText('memorySources.stage.running')).toBeInTheDocument()- );-- first.unmount();- // The run goes on with no screen listening.- act(() => {- window.dispatchEvent(- makeSyncStageEvent({ stage: 'fetching', source_id: 'src-persist', detail: '1/3 pages' })- );- });-- const second = renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);- await waitFor(() => expect(screen.getByText('Source src-persist')).toBeInTheDocument());- expect(screen.getByText('memorySources.stage.fetching')).toBeInTheDocument();-- second.unmount();- act(() => {- window.dispatchEvent(- makeSyncStageEvent({- stage: 'completed',- source_id: 'src-persist',- detail: 'ingested 12 item(s)',- })- );- });- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);- await waitFor(() =>- expect(screen.getByTestId('memory-source-result-src-persist')).toHaveTextContent(- '12 memorySources.sync.itemsSynced'- )- );- });-- it('shows a run the core reports in flight on a cold mount (openhuman#6019)', async () => {- // An app reload mid-sync: no stage event ever reached this page, but the- // status list says the core is still running the source.- listMemorySources.mockResolvedValue([makeSource('src-cold')]);- memorySourcesStatusList.mockResolvedValue([- {- source_id: 'src-cold',- chunks_synced: 0,- chunks_pending: 0,- last_chunk_at_ms: null,- freshness: 'idle',- sync_stage: 'running',- sync_detail: null,- },- ]);-- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);- await waitFor(() =>- expect(screen.getByText('memorySources.stage.running')).toBeInTheDocument()- );- expect(screen.getByText('sync.syncing')).toBeInTheDocument();- });-});diff --git a/app/src/components/intelligence/__tests__/MemorySourcesRegistry.test.tsx b/app/src/components/intelligence/__tests__/MemorySourcesRegistry.test.tsxdeleted file mode 100644index 11ee5b4678..0000000000--- a/app/src/components/intelligence/__tests__/MemorySourcesRegistry.test.tsx+++ /dev/null@@ -1,760 +0,0 @@-/**- * Unit tests for MemorySourcesRegistry — All In button, gear/settings panel,- * per-kind field visibility, Save, and existing toggle behaviour.- */-import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';-import { Provider } from 'react-redux';-import { MemoryRouter } from 'react-router-dom';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import * as service from '../../../services/memorySourcesService';-import { getCoreStateSnapshot } from '../../../lib/coreState/store';-import { CoreStateContext, type CoreStateContextValue } from '../../../providers/coreStateContext';-import type { MemorySourceEntry } from '../../../services/memorySourcesService';-import { createTestStore, renderWithProviders } from '../../../test/test-utils';-import {- openhumanGetMemorySyncSettings,- openhumanUpdateMemorySyncSettings,-} from '../../../utils/tauriCommands/config';-import {- memoryTreeBackfillStatus,- memoryTreePipelineStatus,- type MemoryTreePipelineStatus,-} from '../../../utils/tauriCommands/memoryTree';-import { MemorySourcesRegistry } from '../MemorySourcesRegistry';--// Mock the entire service so we don't hit RPC-vi.mock('../../../services/memorySourcesService', async () => {- const actual = await vi.importActual<typeof import('../../../services/memorySourcesService')>(- '../../../services/memorySourcesService'- );- return {- ...actual,- listMemorySources: vi.fn(),- memorySourcesStatusList: vi.fn(),- updateMemorySource: vi.fn(),- removeMemorySource: vi.fn(),- syncMemorySource: vi.fn(),- applyAllIn: vi.fn(),- };-});--// Mock tauriCommands/memoryTree. The registry now also polls-// memoryTreePipelineStatus for downstream health (GH-4690) and-// memoryTreeBackfillStatus for embed work in flight (openhuman#6025); default-// both to a healthy, idle snapshot so no source row shows a spurious warning.-vi.mock('../../../utils/tauriCommands/memoryTree', () => ({- memoryTreeBackfillStatus: vi.fn().mockResolvedValue({ in_progress: false, pending_jobs: 0 }),- memoryTreeFlushSource: vi.fn().mockResolvedValue({ seals_fired: 0 }),- memoryTreePipelineStatus: vi- .fn()- .mockResolvedValue({- status: 'running',- reason: null,- last_sync_ms: 0,- total_chunks: 0,- wiki_size_bytes: 0,- pipeline_jobs: { ready: 0, running: 0, failed: 0 },- is_syncing: false,- is_paused: false,- }),-}));--// Mock the memory-sync schedule config RPCs (#3302).-vi.mock('../../../utils/tauriCommands/config', () => ({- openhumanGetMemorySyncSettings: vi.fn(),- openhumanUpdateMemorySyncSettings: vi.fn(),-}));--const mockedList = vi.mocked(service.listMemorySources);-const mockedStatus = vi.mocked(service.memorySourcesStatusList);-const mockedUpdate = vi.mocked(service.updateMemorySource);-const mockedApplyAllIn = vi.mocked(service.applyAllIn);-const mockedGetSync = vi.mocked(openhumanGetMemorySyncSettings);-const mockedUpdateSync = vi.mocked(openhumanUpdateMemorySyncSettings);-const mockedPipeline = vi.mocked(memoryTreePipelineStatus);-const mockedBackfill = vi.mocked(memoryTreeBackfillStatus);--/** A healthy `memory_tree_pipeline_status` snapshot (no degradation). */-function healthyPipeline(- overrides: Partial<MemoryTreePipelineStatus> = {}-): MemoryTreePipelineStatus {- return {- status: 'running',- reason: null,- last_sync_ms: 0,- total_chunks: 0,- wiki_size_bytes: 0,- pipeline_jobs: { ready: 0, running: 0, failed: 0 },- is_syncing: false,- is_paused: false,- ...overrides,- };-}--function syncSettings(overrides: Record<string, unknown> = {}) {- return {- result: {- sync_interval_secs: null,- selected_secs: 86_400,- is_manual: false,- is_default: true,- default_secs: 86_400,- presets: [14_400, 43_200, 86_400],- ...overrides,- },- logs: [],- };-}--function makeSource(overrides: Partial<MemorySourceEntry> = {}): MemorySourceEntry {- return {- id: 'src_1',- kind: 'github_repo',- label: 'My Repo',- enabled: true,- url: 'https://github.com/org/repo',- ...overrides,- };-}--function setup(sources: MemorySourceEntry[] = [makeSource()]) {- mockedList.mockResolvedValue(sources);- mockedStatus.mockResolvedValue([]);- const onToast = vi.fn();- const result = renderWithProviders(- <MemorySourcesRegistry onToast={onToast} pollIntervalMs={0} />,- {}- );- return { ...result, onToast };-}--describe('MemorySourcesRegistry', () => {- beforeEach(() => {- vi.clearAllMocks();- // Default: schedule RPCs succeed with the unset/default 24h view.- mockedGetSync.mockResolvedValue(syncSettings());- mockedUpdateSync.mockResolvedValue(syncSettings());- mockedBackfill.mockResolvedValue({ in_progress: false, pending_jobs: 0 });- });-- // -------------------------------------------------------------------------- // Basic render- // -------------------------------------------------------------------------- it('renders loaded sources list', async () => {- setup([makeSource({ label: 'Work Repo' })]);- await screen.findByText('Work Repo');- expect(screen.getByTestId('memory-sources')).toBeInTheDocument();- });-- it('renders empty state when no sources', async () => {- mockedList.mockResolvedValue([]);- mockedStatus.mockResolvedValue([]);- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);- await screen.findByText(/no memory sources/i);- });-- // -------------------------------------------------------------------------- // Embed backlog: pending vs stuck (openhuman#6025)- // -------------------------------------------------------------------------- it('hands the backfill snapshot to rows so a draining backlog reads as pending, not failed', async () => {- // Nothing about this source alone says "still moving" (idle freshness);- // only the registry's backfill poll does. If the poll were not wired- // through to the row, this would render the amber warning.- mockedStatus.mockResolvedValue([- {- source_id: 'src_1',- chunks_synced: 10,- chunks_pending: 4,- last_chunk_at_ms: 0,- freshness: 'idle',- },- ]);- mockedBackfill.mockResolvedValue({ in_progress: true, pending_jobs: 1 });- mockedList.mockResolvedValue([makeSource()]);- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);-- const note = await screen.findByTestId('memory-source-vectors-pending-src_1');- expect(note).toHaveTextContent('Chunks waiting for vectors: 4');- expect(screen.queryByTestId('memory-source-pipeline-warning-src_1')).not.toBeInTheDocument();- expect(mockedBackfill).toHaveBeenCalled();- });-- it('falls back to the amber warning when the backfill poll fails and nothing is fresh', async () => {- // Best-effort: a failed backfill RPC must neither hide the source list- // nor invent a "draining" state. With the source idle, the truthful- // verdict is the warning.- mockedStatus.mockResolvedValue([- {- source_id: 'src_1',- chunks_synced: 10,- chunks_pending: 4,- last_chunk_at_ms: 0,- freshness: 'idle',- },- ]);- mockedBackfill.mockRejectedValue(new Error('backfill_status unavailable'));- mockedList.mockResolvedValue([makeSource()]);- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);-- await screen.findByTestId('memory-source-pipeline-warning-src_1');- expect(screen.queryByTestId('memory-source-vectors-pending-src_1')).not.toBeInTheDocument();- });-- // -------------------------------------------------------------------------- // Toggle (existing behaviour)- // -------------------------------------------------------------------------- it('toggle calls updateMemorySource and flips state', async () => {- const source = makeSource({ enabled: true });- mockedUpdate.mockResolvedValue({ ...source, enabled: false });- setup([source]);- await screen.findByText('My Repo');-- const toggle = screen.getByRole('switch', { name: /disable/i });- fireEvent.click(toggle);-- await waitFor(() => {- expect(mockedUpdate).toHaveBeenCalledWith('src_1', { enabled: false });- });- });-- // -------------------------------------------------------------------------- // All In button- // -------------------------------------------------------------------------- it('All In button is rendered in the header', async () => {- setup();- await screen.findByText('My Repo');- expect(screen.getByTestId('all-in-button')).toBeInTheDocument();- });-- it('clicking All In opens a confirmation modal', async () => {- setup();- await screen.findByText('My Repo');-- fireEvent.click(screen.getByTestId('all-in-button'));-- // The modal should appear- await screen.findByText('Go All In?');- expect(- screen.getByText(/This enables every memory source and removes all sync limits/i)- ).toBeInTheDocument();- });-- it('cancelling All In modal closes it without calling applyAllIn', async () => {- setup();- await screen.findByText('My Repo');-- fireEvent.click(screen.getByTestId('all-in-button'));- await screen.findByText('Go All In?');-- // Click the No / cancel button- fireEvent.click(screen.getByText('No'));-- await waitFor(() => {- expect(screen.queryByText('Go All In?')).not.toBeInTheDocument();- });- expect(mockedApplyAllIn).not.toHaveBeenCalled();- });-- it('confirming All In calls applyAllIn, updates sources, and shows success toast', async () => {- const updatedSrc = makeSource({ id: 'src_2', label: 'New Repo', enabled: true });- mockedApplyAllIn.mockResolvedValue({- sources: [updatedSrc],- sync_triggered: 1,- sync_failed: 0,- sync_errors: [],- });-- const { onToast } = setup();- await screen.findByText('My Repo');-- fireEvent.click(screen.getByTestId('all-in-button'));- await screen.findByText('Go All In?');-- fireEvent.click(screen.getByText('Yes'));-- await waitFor(() => {- expect(mockedApplyAllIn).toHaveBeenCalledOnce();- });-- await waitFor(() => {- expect(onToast).toHaveBeenCalledWith(expect.objectContaining({ type: 'success' }));- });-- // Modal should close- await waitFor(() => {- expect(screen.queryByText('Go All In?')).not.toBeInTheDocument();- });- });-- it('All In with every trigger failing shows an error toast, not success (openhuman#5820)', async () => {- const updatedSrc = makeSource({ id: 'src_2', label: 'New Repo', enabled: true });- mockedApplyAllIn.mockResolvedValue({- sources: [updatedSrc],- sync_triggered: 0,- sync_failed: 1,- sync_errors: ['src_2: not found: no memory source registered as src_2'],- });-- const { onToast } = setup();- await screen.findByText('My Repo');- fireEvent.click(screen.getByTestId('all-in-button'));- await screen.findByText('Go All In?');- fireEvent.click(screen.getByText('Yes'));-- await waitFor(() => {- expect(onToast).toHaveBeenCalledWith(- expect.objectContaining({- type: 'error',- message: 'src_2: not found: no memory source registered as src_2',- })- );- });- expect(onToast).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'success' }));- });-- it('All In with a partial start shows a warning naming both counts', async () => {- const updatedSrc = makeSource({ id: 'src_2', label: 'New Repo', enabled: true });- mockedApplyAllIn.mockResolvedValue({- sources: [updatedSrc],- sync_triggered: 2,- sync_failed: 1,- sync_errors: ['src_3: boom'],- });-- const { onToast } = setup();- await screen.findByText('My Repo');- fireEvent.click(screen.getByTestId('all-in-button'));- await screen.findByText('Go All In?');- fireEvent.click(screen.getByText('Yes'));-- await waitFor(() => {- expect(onToast).toHaveBeenCalledWith(- expect.objectContaining({- type: 'warning',- title: 'Syncs started: 2. Could not start: 1.',- message: 'src_3: boom',- })- );- });- });-- it('All In failure shows error toast', async () => {- mockedApplyAllIn.mockRejectedValue(new Error('RPC error'));-- const { onToast } = setup();- await screen.findByText('My Repo');-- fireEvent.click(screen.getByTestId('all-in-button'));- await screen.findByText('Go All In?');-- fireEvent.click(screen.getByText('Yes'));-- await waitFor(() => {- expect(onToast).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }));- });- });-- // -------------------------------------------------------------------------- // Gear / settings panel — toggling- // -------------------------------------------------------------------------- it('gear button renders for each source row', async () => {- setup([makeSource({ id: 'src_1' }), makeSource({ id: 'src_2', label: 'Second' })]);- await screen.findByText('My Repo');-- expect(screen.getByTestId('memory-source-settings-src_1')).toBeInTheDocument();- expect(screen.getByTestId('memory-source-settings-src_2')).toBeInTheDocument();- });-- it('clicking gear expands the settings panel for that source', async () => {- setup([makeSource({ id: 'src_1', kind: 'github_repo' })]);- await screen.findByText('My Repo');-- expect(screen.queryByTestId('source-settings-panel-src_1')).not.toBeInTheDocument();-- fireEvent.click(screen.getByTestId('memory-source-settings-src_1'));-- expect(screen.getByTestId('source-settings-panel-src_1')).toBeInTheDocument();- });-- it('clicking gear again collapses the settings panel', async () => {- setup([makeSource({ id: 'src_1', kind: 'github_repo' })]);- await screen.findByText('My Repo');-- const gearBtn = screen.getByTestId('memory-source-settings-src_1');- fireEvent.click(gearBtn);- expect(screen.getByTestId('source-settings-panel-src_1')).toBeInTheDocument();-- fireEvent.click(gearBtn);- expect(screen.queryByTestId('source-settings-panel-src_1')).not.toBeInTheDocument();- });-- // -------------------------------------------------------------------------- // Settings panel — field visibility per kind- // -------------------------------------------------------------------------- it('github_repo settings panel shows max_prs, max_issues, max_commits, sync_depth_days', async () => {- setup([makeSource({ id: 'src_1', kind: 'github_repo' })]);- await screen.findByText('My Repo');-- fireEvent.click(screen.getByTestId('memory-source-settings-src_1'));-- const panel = screen.getByTestId('source-settings-panel-src_1');- expect(within(panel).getByLabelText(/max pull requests/i)).toBeInTheDocument();- expect(within(panel).getByLabelText(/max issues/i)).toBeInTheDocument();- expect(within(panel).getByLabelText(/max commits/i)).toBeInTheDocument();- expect(within(panel).getByLabelText(/sync depth/i)).toBeInTheDocument();- });-- it('composio settings panel shows sync_depth_days and max_items but NOT max_prs', async () => {- setup([makeSource({ id: 'src_1', kind: 'composio', toolkit: 'github' })]);- await screen.findByText('My Repo');-- fireEvent.click(screen.getByTestId('memory-source-settings-src_1'));-- const panel = screen.getByTestId('source-settings-panel-src_1');- expect(within(panel).getByLabelText(/max items/i)).toBeInTheDocument();- expect(within(panel).getByLabelText(/sync depth/i)).toBeInTheDocument();- expect(within(panel).queryByLabelText(/max pull requests/i)).not.toBeInTheDocument();- });-- it('rss_feed settings panel shows max_items and sync_depth_days but NOT max_prs', async () => {- setup([makeSource({ id: 'src_1', kind: 'rss_feed', url: 'https://example.com/feed.xml' })]);- await screen.findByText('My Repo');-- fireEvent.click(screen.getByTestId('memory-source-settings-src_1'));-- const panel = screen.getByTestId('source-settings-panel-src_1');- expect(within(panel).getByLabelText(/max items/i)).toBeInTheDocument();- expect(within(panel).getByLabelText(/sync depth/i)).toBeInTheDocument();- expect(within(panel).queryByLabelText(/max pull requests/i)).not.toBeInTheDocument();- expect(within(panel).queryByLabelText(/max commits/i)).not.toBeInTheDocument();- });-- // -------------------------------------------------------------------------- // Settings panel — Save- // -------------------------------------------------------------------------- it('Save in settings panel calls updateMemorySource with numeric patch', async () => {- const source = makeSource({ id: 'src_1', kind: 'github_repo' });- const updated = { ...source, max_prs: 50 };- mockedUpdate.mockResolvedValue(updated);-- const { onToast } = setup([source]);- await screen.findByText('My Repo');-- fireEvent.click(screen.getByTestId('memory-source-settings-src_1'));-- const panel = screen.getByTestId('source-settings-panel-src_1');- const maxPrsInput = within(panel).getByLabelText(/max pull requests/i);- fireEvent.change(maxPrsInput, { target: { value: '50' } });-- const saveBtn = within(panel).getByText('Save');- fireEvent.click(saveBtn);-- await waitFor(() => {- expect(mockedUpdate).toHaveBeenCalledWith('src_1', expect.objectContaining({ max_prs: 50 }));- });-- await waitFor(() => {- expect(onToast).toHaveBeenCalledWith(expect.objectContaining({ type: 'success' }));- });- });-- it('empty input is omitted from the save patch (not sent as 0)', async () => {- const source = makeSource({ id: 'src_1', kind: 'github_repo', max_prs: 10 });- mockedUpdate.mockResolvedValue(source);-- setup([source]);- await screen.findByText('My Repo');-- fireEvent.click(screen.getByTestId('memory-source-settings-src_1'));-- const panel = screen.getByTestId('source-settings-panel-src_1');- const maxPrsInput = within(panel).getByLabelText(/max pull requests/i);-- // Clear the field- fireEvent.change(maxPrsInput, { target: { value: '' } });-- fireEvent.click(within(panel).getByText('Save'));-- await waitFor(() => {- expect(mockedUpdate).toHaveBeenCalledWith(- 'src_1',- expect.not.objectContaining({ max_prs: expect.anything() })- );- });- });-- it('Save failure shows error toast', async () => {- mockedUpdate.mockRejectedValue(new Error('Save failed'));-- const { onToast } = setup([makeSource({ kind: 'github_repo' })]);- await screen.findByText('My Repo');-- fireEvent.click(screen.getByTestId('memory-source-settings-src_1'));- const panel = screen.getByTestId('source-settings-panel-src_1');- fireEvent.click(within(panel).getByText('Save'));-- await waitFor(() => {- expect(onToast).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }));- });- });-- // -------------------------------------------------------------------------- // Memory sync schedule (#3302)- // -------------------------------------------------------------------------- it('renders the sync schedule with the default 24h cadence highlighted', async () => {- setup();- const schedule = await screen.findByTestId('memory-sync-schedule');- // Default view highlights the 24h preset.- const preset24h = within(schedule).getByTestId('memory-sync-preset-86400');- expect(preset24h).toHaveAttribute('aria-checked', 'true');- // Manual is offered and not selected.- const manual = within(schedule).getByTestId('memory-sync-preset-0');- expect(manual).toHaveAttribute('aria-checked', 'false');- // The summary shows the current cadence.- expect(within(schedule).getByTestId('memory-sync-current')).toHaveTextContent('Every 24h');- });-- it('shows "Last synced …" from the newest source chunk timestamp', async () => {- mockedList.mockResolvedValue([makeSource()]);- mockedStatus.mockResolvedValue([- {- source_id: 'src_1',- chunks_synced: 5,- chunks_pending: 0,- last_chunk_at_ms: Date.now() - 2 * 60 * 60 * 1000,- freshness: 'recent',- },- ]);- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);- const schedule = await screen.findByTestId('memory-sync-schedule');- await waitFor(() => {- expect(schedule).toHaveTextContent(/Last synced/i);- expect(schedule).toHaveTextContent(/2h ago/i);- });- });-- it('selecting a preset calls update with the cadence in seconds', async () => {- setup();- const schedule = await screen.findByTestId('memory-sync-schedule');-- mockedUpdateSync.mockResolvedValue(- syncSettings({ sync_interval_secs: 14_400, selected_secs: 14_400, is_default: false })- );- fireEvent.click(within(schedule).getByTestId('memory-sync-preset-14400'));-- await waitFor(() => {- expect(mockedUpdateSync).toHaveBeenCalledWith({ sync_interval_secs: 14_400 });- });- await waitFor(() => {- expect(within(schedule).getByTestId('memory-sync-current')).toHaveTextContent('Every 4h');- });- });-- it('selecting Manual sends sync_interval_secs = 0 and shows Manual only', async () => {- setup();- const schedule = await screen.findByTestId('memory-sync-schedule');-- mockedUpdateSync.mockResolvedValue(- syncSettings({ sync_interval_secs: 0, selected_secs: 0, is_manual: true, is_default: false })- );- fireEvent.click(within(schedule).getByTestId('memory-sync-preset-0'));-- await waitFor(() => {- expect(mockedUpdateSync).toHaveBeenCalledWith({ sync_interval_secs: 0 });- });- await waitFor(() => {- expect(within(schedule).getByTestId('memory-sync-current')).toHaveTextContent('Manual only');- });- });-- it('schedule update failure shows an error toast', async () => {- const { onToast } = setup();- const schedule = await screen.findByTestId('memory-sync-schedule');-- mockedUpdateSync.mockRejectedValue(new Error('RPC down'));- fireEvent.click(within(schedule).getByTestId('memory-sync-preset-14400'));-- await waitFor(() => {- expect(onToast).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }));- });- });-- // -------------------------------------------------------------------------- // Refetch when the session becomes authenticated (#3449)- //- // After a page reload the registry can mount before CoreStateProvider has- // restored the session. The first fetch then runs against a not-yet-ready- // core; sources must reappear as soon as auth flips true, without waiting- // for the next background poll.- // -------------------------------------------------------------------------- it('refetches sources when the session transitions to authenticated', async () => {- mockedList.mockResolvedValue([makeSource({ label: 'Reloaded Repo' })]);- mockedStatus.mockResolvedValue([]);-- const coreState = (isAuthenticated: boolean): CoreStateContextValue =>- ({- ...getCoreStateSnapshot(),- snapshot: {- ...getCoreStateSnapshot().snapshot,- auth: {- isAuthenticated,- userId: isAuthenticated ? 'u1' : null,- user: null,- profileId: null,- },- },- refresh: async () => {},- refreshTeams: async () => {},- refreshTeamMembers: async () => {},- refreshTeamInvites: async () => {},- setAnalyticsEnabled: async () => {},- setMeetAutoOrchestratorHandoff: async () => {},- setOnboardingCompletedFlag: async () => {},- setEncryptionKey: async () => {},- patchSnapshot: () => {},- setOnboardingTasks: async () => {},- storeSessionToken: async () => {},- clearSession: async () => {},- }) as CoreStateContextValue;-- const store = createTestStore();- const tree = (isAuthenticated: boolean) => (- <Provider store={store}>- <CoreStateContext.Provider value={coreState(isAuthenticated)}>- <MemoryRouter>- {/* pollIntervalMs=0 disables the background poll, so the only way- the second fetch can fire is the auth transition. */}- <MemorySourcesRegistry pollIntervalMs={0} />- </MemoryRouter>- </CoreStateContext.Provider>- </Provider>- );-- const { rerender } = render(tree(false));- await waitFor(() => expect(mockedList).toHaveBeenCalledTimes(1));-- rerender(tree(true));- await waitFor(() => expect(mockedList).toHaveBeenCalledTimes(2));- expect(await screen.findByText('Reloaded Repo')).toBeInTheDocument();- });-- // -------------------------------------------------------------------------- // Layered pipeline status — Data Sync must not show a clean "synced" badge- // when the downstream retrieval pipeline failed (GH-4690).- // -------------------------------------------------------------------------- describe('layered pipeline warnings (GH-4690)', () => {- it('no regression: a fully healthy sync keeps the clean freshness badge', async () => {- mockedList.mockResolvedValue([makeSource({ id: 'src_1', label: 'Healthy Repo' })]);- mockedStatus.mockResolvedValue([- {- source_id: 'src_1',- chunks_synced: 5,- chunks_pending: 0,- last_chunk_at_ms: Date.now(),- freshness: 'recent',- },- ]);- mockedPipeline.mockResolvedValue(healthyPipeline());-- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);- await screen.findByText('Healthy Repo');- // Clean state: freshness pill shows, no "Ingested only" warning surfaces.- await waitFor(() => {- expect(screen.getByText('Recent')).toBeInTheDocument();- });- expect(screen.queryByTestId('memory-source-ingested-only-src_1')).not.toBeInTheDocument();- expect(screen.queryByTestId('memory-source-pipeline-warning-src_1')).not.toBeInTheDocument();- });-- it('flags "Stored without vectors" from per-source pending chunks', async () => {- mockedList.mockResolvedValue([makeSource({ id: 'src_1', label: 'Notes' })]);- mockedStatus.mockResolvedValue([- {- source_id: 'src_1',- chunks_synced: 1,- chunks_pending: 1,- // Long idle: nothing is draining this backlog (openhuman#6025 —- // a recent chunk or a running backfill would read as "pending").- last_chunk_at_ms: Date.now() - 60 * 60_000,- freshness: 'idle',- },- ]);- // Even with a "healthy" global snapshot, the per-source pending chunks- // are the precise signal that this source has no vectors.- mockedPipeline.mockResolvedValue(healthyPipeline());-- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);- await screen.findByText('Notes');- expect(await screen.findByTestId('memory-source-ingested-only-src_1')).toBeInTheDocument();- expect(screen.getByTestId('memory-source-pipeline-warning-src_1')).toHaveTextContent(- /Stored without vectors/i- );- // Clean freshness badge must be gone.- expect(screen.queryByText('Idle')).not.toBeInTheDocument();- // A link to the full memory-health panel is offered.- expect(screen.getByTestId('memory-source-view-health-src_1')).toBeInTheDocument();- });-- it('offers "Sign in to enable" when embeddings fail for lack of a backend session', async () => {- mockedList.mockResolvedValue([makeSource({ id: 'src_1', label: 'Notes' })]);- mockedStatus.mockResolvedValue([- {- source_id: 'src_1',- chunks_synced: 2,- chunks_pending: 2,- last_chunk_at_ms: Date.now(),- freshness: 'idle',- },- ]);- mockedPipeline.mockResolvedValue(- healthyPipeline({- status: 'error',- first_blocking_cause: {- code: 'auth_missing',- class: 'unrecoverable',- remediation_key: 'memory.health.remediation.auth_missing',- },- })- );-- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);- await screen.findByText('Notes');- // Unauthenticated (no CoreStateProvider ⇒ isAuthenticated false), auth-related.- const signIn = await screen.findByTestId('memory-source-signin-src_1');- expect(signIn).toBeInTheDocument();- // Clicking must not throw (navigates within the MemoryRouter).- fireEvent.click(signIn);- });-- it('surfaces extraction failure from the global pipeline health', async () => {- mockedList.mockResolvedValue([makeSource({ id: 'src_1', label: 'Notes' })]);- mockedStatus.mockResolvedValue([- {- source_id: 'src_1',- chunks_synced: 5,- chunks_pending: 0,- last_chunk_at_ms: Date.now(),- freshness: 'recent',- },- ]);- mockedPipeline.mockResolvedValue(- healthyPipeline({- status: 'degraded',- first_blocking_cause: {- code: 'extraction_timeout',- class: 'transient',- remediation_key: 'memory.health.remediation.extraction_timeout',- },- })- );-- renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);- await screen.findByText('Notes');- expect(await screen.findByTestId('memory-source-ingested-only-src_1')).toBeInTheDocument();- expect(screen.getByTestId('memory-source-pipeline-warning-src_1')).toHaveTextContent(- /extraction failed/i- );- });- });-});diff --git a/app/src/components/intelligence/__tests__/MemoryTextAndDetail.test.tsx b/app/src/components/intelligence/__tests__/MemoryTextAndDetail.test.tsxdeleted file mode 100644index 0887009f7a..0000000000--- a/app/src/components/intelligence/__tests__/MemoryTextAndDetail.test.tsx+++ /dev/null@@ -1,51 +0,0 @@-import { render, screen } from '@testing-library/react';-import { describe, expect, it, vi } from 'vitest';--import type { MemoryRetrievalEntity } from '../../../utils/tauriCommands';-import { MemoryTextWithEntities } from '../MemoryTextWithEntities';--const rpcMocks = vi.hoisted(() => ({- memoryTreeEntityIndexFor: vi.fn(),- memoryTreeChunkScore: vi.fn(),-}));--vi.mock('../../../utils/tauriCommands', async () => {- const actual = await vi.importActual<typeof import('../../../utils/tauriCommands')>(- '../../../utils/tauriCommands'- );- return {- ...actual,- memoryTreeEntityIndexFor: rpcMocks.memoryTreeEntityIndexFor,- memoryTreeChunkScore: rpcMocks.memoryTreeChunkScore,- };-});--describe('MemoryTextWithEntities', () => {- it('renders nothing when there is no text or entity chip data', () => {- const { container } = render(<MemoryTextWithEntities text="" />);-- expect(container).toBeEmptyDOMElement();- });-- it('renders structured entity chips with type titles', () => {- const entities: MemoryRetrievalEntity[] = [- { id: 'e1', name: 'Alice', entity_type: 'PERSON' },- { id: 'e2', name: 'Atlas', entity_type: 'PROJECT' },- ];-- render(<MemoryTextWithEntities text="Relevant context" entities={entities} />);-- expect(screen.getByTitle('Alice (PERSON)')).toBeInTheDocument();- expect(screen.getByTitle('Atlas (PROJECT)')).toBeInTheDocument();- expect(screen.getByText('Relevant context')).toBeInTheDocument();- });-- it('turns inline entity annotations into accessible badges', () => {- render(<MemoryTextWithEntities text="Alice (PERSON) owns Atlas (PROJECT)." />);-- expect(screen.getByTitle('Entity type: PERSON')).toHaveTextContent('PERSON');- expect(screen.getByTitle('Entity type: PROJECT')).toHaveTextContent('PROJECT');- expect(screen.getByText(/Alice/)).toBeInTheDocument();- expect(screen.getByText(/owns Atlas/)).toBeInTheDocument();- });-});diff --git a/app/src/components/intelligence/__tests__/MemoryWorkspace.test.tsx b/app/src/components/intelligence/__tests__/MemoryWorkspace.test.tsxdeleted file mode 100644index 085c18c723..0000000000--- a/app/src/components/intelligence/__tests__/MemoryWorkspace.test.tsx+++ /dev/null@@ -1,429 +0,0 @@-import { act, fireEvent, screen, waitFor } from '@testing-library/react';-import { beforeEach, describe, expect, it, type Mock, vi } from 'vitest';--import { renderWithProviders } from '../../../test/test-utils';-import type { GraphExportResponse, GraphNode } from '../../../utils/tauriCommands';-import { MemoryWorkspace } from '../MemoryWorkspace';--// The graph workspace pulls every sealed summary through one RPC call —-// `memory_tree_graph_export`. The MemorySyncConnections poll is mocked-// out separately so the workspace mounts cleanly without hitting the-// network.-vi.mock('../../../utils/tauriCommands', () => ({- // The status hook polls this alongside pipeline status; a factory mock- // without it turns every render into an unhandled rejection.- memoryNamespaceSummaries: vi.fn(async () => ({ namespaces: [], total_documents: 0 })),- isTauri: vi.fn(() => true),- memoryTreeGraphExport: vi.fn(),- memoryTreeFlushNow: vi.fn(),- memoryTreeWipeAll: vi.fn(),- memoryTreeResetTree: vi.fn(),- memoryTreeObsidianVaultStatus: vi.fn(),-}));--vi.mock('../../../services/memorySourcesService', () => ({- listMemorySources: vi.fn().mockResolvedValue([]),- memorySourcesStatusList: vi.fn().mockResolvedValue([]),- syncMemorySource: vi.fn(),- removeMemorySource: vi.fn(),- updateMemorySource: vi.fn(),- addMemorySource: vi.fn(),- getSupportedToolkits: vi.fn().mockResolvedValue([]),- SOURCE_KIND_ICONS: {- folder: '📁',- composio: '🔗',- github_repo: '🐙',- rss_feed: '📡',- web_page: '🌐',- twitter_query: '🐦',- },- SOURCE_KIND_LABEL_KEYS: {- folder: 'memorySources.kind.folder',- composio: 'memorySources.kind.composio',- github_repo: 'memorySources.kind.github_repo',- rss_feed: 'memorySources.kind.rss_feed',- web_page: 'memorySources.kind.web_page',- twitter_query: 'memorySources.kind.twitter_query',- },-}));--vi.mock('../../../lib/composio/composioApi', () => ({- listConnections: vi.fn().mockResolvedValue({ connections: [] }),- syncConnection: vi.fn(),-}));--// Stub `openUrl` so deep-link clicks land in a mock instead of routing-// through `tauri-plugin-opener` (which isn't loaded in the test env).-vi.mock('../../../utils/openUrl', () => ({ openUrl: vi.fn().mockResolvedValue(undefined) }));--vi.mock('../../../utils/tauriCommands/workspacePaths', () => ({- openWorkspacePath: vi.fn().mockResolvedValue(undefined),- revealWorkspacePath: vi.fn().mockResolvedValue(undefined),- // #2492: the Obsidian deep link now resolves the vault's absolute path- // through the shared workspace-link layer instead of trusting the- // `content_root_abs` field returned from the graph export RPC. Return the- // same path the prop carries so the existing `openUrl` assertion is stable.- resolveWorkspaceAbsolutePath: vi.fn().mockResolvedValue('/tmp/workspace/memory_tree/content'),- previewWorkspaceText: vi- .fn()- .mockResolvedValue({- path: 'memory_tree/content/wiki/summaries/source-alice-x-com/L1/summary-L1-abc.md',- absolutePath:- '/tmp/workspace/memory_tree/content/wiki/summaries/source-alice-x-com/L1/summary-L1-abc.md',- contents: '# Gmail summary',- truncated: false,- sizeBytes: 15,- }),-}));--const {- memoryTreeGraphExport,- memoryTreeFlushNow,- memoryTreeWipeAll,- memoryTreeResetTree,- memoryTreeObsidianVaultStatus,-} = (await import('../../../utils/tauriCommands')) as unknown as {- memoryTreeGraphExport: Mock;- memoryTreeFlushNow: Mock;- memoryTreeWipeAll: Mock;- memoryTreeResetTree: Mock;- memoryTreeObsidianVaultStatus: Mock;-};--const { listConnections, syncConnection } =- (await import('../../../lib/composio/composioApi')) as unknown as {- listConnections: Mock;- syncConnection: Mock;- };--const { listMemorySources, syncMemorySource } =- (await import('../../../services/memorySourcesService')) as unknown as {- listMemorySources: Mock;- syncMemorySource: Mock;- };--const { openUrl } = (await import('../../../utils/openUrl')) as unknown as { openUrl: Mock };--const { openWorkspacePath, revealWorkspacePath } =- (await import('../../../utils/tauriCommands/workspacePaths')) as unknown as {- openWorkspacePath: Mock;- revealWorkspacePath: Mock;- };--function makeSummary(partial: Partial<GraphNode>): GraphNode {- return {- kind: 'summary',- id: 'summary:L1:abc',- label: 'L1 · gmail',- tree_id: 'tree-1',- tree_kind: 'source',- tree_scope: 'gmail:[email protected]',- level: 1,- parent_id: null,- child_count: 4,- time_range_start_ms: 0,- time_range_end_ms: 0,- file_basename: 'summary-L1-abc',- ...partial,- };-}--const SAMPLE_RESPONSE: GraphExportResponse = {- content_root_abs: '/tmp/workspace/memory_tree/content',- edges: [],- nodes: [- makeSummary({ id: 'root', level: 2, parent_id: null, child_count: 2 }),- makeSummary({ id: 'child-1', level: 1, parent_id: 'root' }),- makeSummary({ id: 'child-2', level: 1, parent_id: 'root' }),- ],-};--describe('MemoryWorkspace (graph view)', () => {- beforeEach(() => {- vi.clearAllMocks();- memoryTreeGraphExport.mockResolvedValue(SAMPLE_RESPONSE);- memoryTreeFlushNow.mockResolvedValue({ enqueued: true, stale_buffers: 3 });- memoryTreeWipeAll.mockResolvedValue({- rows_deleted: 42,- dirs_removed: ['raw', 'wiki', 'email'],- sync_state_cleared: 1,- });- memoryTreeResetTree.mockResolvedValue({- tree_rows_deleted: 12,- chunks_requeued: 7,- jobs_enqueued: 7,- });- listConnections.mockResolvedValue({ connections: [] });- syncConnection.mockResolvedValue({ ok: true });- openUrl.mockResolvedValue(undefined);- openWorkspacePath.mockResolvedValue(undefined);- revealWorkspacePath.mockResolvedValue(undefined);- // Default: the content root is already a registered Obsidian vault, so a- // View-Vault click opens it directly (the not-registered guidance branch- // is covered in ObsidianVaultSection.test.tsx).- memoryTreeObsidianVaultStatus.mockResolvedValue({- registered: true,- config_found: true,- content_root_abs: '/tmp/workspace/memory_tree/content',- });- });-- it('renders the SVG graph once the export RPC resolves', async () => {- renderWithProviders(<MemoryWorkspace />);- await waitFor(() => {- expect(screen.getByTestId('memory-graph-svg')).toBeInTheDocument();- });- // Three nodes → three circle elements with stable testids.- expect(screen.getByTestId('memory-graph-node-root')).toBeInTheDocument();- expect(screen.getByTestId('memory-graph-node-child-1')).toBeInTheDocument();- expect(screen.getByTestId('memory-graph-node-child-2')).toBeInTheDocument();- });-- it('shows an empty state when the tree has no sealed summaries', async () => {- memoryTreeGraphExport.mockResolvedValueOnce({- content_root_abs: '/tmp/workspace/memory_tree/content',- edges: [],- nodes: [],- });- renderWithProviders(<MemoryWorkspace />);- await waitFor(() => {- expect(screen.getByTestId('memory-graph-empty')).toBeInTheDocument();- });- });-- it('"View vault in Obsidian" triggers the deep link via the OS opener (not the webview)', async () => {- renderWithProviders(<MemoryWorkspace />);- const button = await screen.findByTestId('memory-open-in-obsidian');- fireEvent.click(button);- await waitFor(() => {- expect(openUrl).toHaveBeenCalledWith(- 'obsidian://open?path=' + encodeURIComponent('/tmp/workspace/memory_tree/content')- );- });- });-- // #2281: every click must produce a visible result. We emit an info- // toast naming the vault path AND offering a "Reveal Folder" action- // so users without Obsidian still get feedback + a working escape- // hatch.- it('"View vault" click emits an info toast with the vault path and a Reveal Folder action', async () => {- const onToast = vi.fn();- renderWithProviders(<MemoryWorkspace onToast={onToast} />);- const button = await screen.findByTestId('memory-open-in-obsidian');- fireEvent.click(button);- await waitFor(() => {- expect(onToast).toHaveBeenCalled();- });- const toast = onToast.mock.calls[0][0];- expect(toast.type).toBe('info');- expect(toast.message).toContain('/tmp/workspace/memory_tree/content');- expect(toast.action?.label).toBeTruthy();- expect(typeof toast.action?.handler).toBe('function');- });-- it('Reveal Folder action on the success toast uses the shared workspace reveal command', async () => {- const onToast = vi.fn();- renderWithProviders(<MemoryWorkspace onToast={onToast} />);- fireEvent.click(await screen.findByTestId('memory-open-in-obsidian'));- await waitFor(() => expect(onToast).toHaveBeenCalled());- const toast = onToast.mock.calls[0][0];- toast.action.handler();- await waitFor(() => {- expect(revealWorkspacePath).toHaveBeenCalledWith('memory_tree/content');- });- });-- it('"View vault" surfaces an error toast (still with Reveal Folder) when openUrl rejects', async () => {- openUrl.mockRejectedValueOnce(new Error('boom'));- const onToast = vi.fn();- renderWithProviders(<MemoryWorkspace onToast={onToast} />);- fireEvent.click(await screen.findByTestId('memory-open-in-obsidian'));- await waitFor(() => expect(onToast).toHaveBeenCalled());- const toast = onToast.mock.calls[0][0];- expect(toast.type).toBe('error');- expect(toast.message).toContain('/tmp/workspace/memory_tree/content');- expect(toast.action?.label).toBeTruthy();- });-- it('Reveal Folder fallback surfaces an error toast when workspace reveal itself fails', async () => {- revealWorkspacePath.mockRejectedValueOnce(new Error('reveal failed'));- const onToast = vi.fn();- renderWithProviders(<MemoryWorkspace onToast={onToast} />);- fireEvent.click(await screen.findByTestId('memory-open-in-obsidian'));- await waitFor(() => expect(onToast).toHaveBeenCalled());- const firstToast = onToast.mock.calls[0][0];- firstToast.action.handler();- await waitFor(() => {- expect(onToast.mock.calls.length).toBeGreaterThanOrEqual(2);- });- const errorToast = onToast.mock.calls[onToast.mock.calls.length - 1][0];- expect(errorToast.type).toBe('error');- expect(errorToast.message).toContain('reveal failed');- });-- it('clicking a summary node opens that file through the shared workspace path command', async () => {- renderWithProviders(<MemoryWorkspace />);- const node = await screen.findByTestId('memory-graph-node-child-1');- fireEvent.click(node);- const expectedRel = 'wiki/summaries/source-alice-x-com/L1/summary-L1-abc.md';- await waitFor(() => {- expect(openWorkspacePath).toHaveBeenCalledWith(`memory_tree/content/${expectedRel}`);- });- });-- it('shows sync rows for provider-backed toolkits and hides non-syncable ones', async () => {- // The new MemorySourcesRegistry reads from listMemorySources (not listConnections).- // Composio connections are auto-seeded into the registry as MemorySourceEntry records.- listMemorySources.mockResolvedValue([- { id: 'src-gmail', kind: 'composio', toolkit: 'gmail', label: 'Gmail · a@x', enabled: true },- { id: 'src-slack', kind: 'composio', toolkit: 'slack', label: 'Slack · acme', enabled: true },- { id: 'src-notion', kind: 'composio', toolkit: 'notion', label: 'Notion', enabled: true },- ]);- renderWithProviders(<MemoryWorkspace />);- // Provider-backed toolkits should render actionable Sync rows- expect(await screen.findByTestId('memory-source-sync-gmail')).toBeInTheDocument();- expect(screen.getByTestId('memory-source-sync-slack')).toBeInTheDocument();- expect(screen.getByTestId('memory-source-sync-notion')).toBeInTheDocument();- // Discord was not added as a source, so no row exists for it.- expect(screen.queryAllByTestId('memory-source-row-composio').length).toBeGreaterThan(0); // some composio rows exist- expect(screen.queryByTestId('memory-source-sync-discord')).toBeNull();- });-- it('toggling to Contacts mode re-fetches the graph with mode=contacts', async () => {- renderWithProviders(<MemoryWorkspace />);- await screen.findByTestId('memory-graph-svg');- expect(memoryTreeGraphExport).toHaveBeenLastCalledWith('tree');- const contactsTab = screen.getByTestId('memory-graph-mode-contacts');- fireEvent.click(contactsTab);- await waitFor(() => {- expect(memoryTreeGraphExport).toHaveBeenLastCalledWith('contacts');- });- });-- it('"Reset memory" requires a confirm and then dispatches memory_tree_wipe_all', async () => {- const onToast = vi.fn();- const confirmSpy = vi.spyOn(window, 'confirm');- // First click — user cancels the confirm dialog → no RPC call.- confirmSpy.mockReturnValueOnce(false);- renderWithProviders(<MemoryWorkspace onToast={onToast} />);- const button = await screen.findByTestId('memory-wipe-all');- fireEvent.click(button);- await waitFor(() => {- expect(confirmSpy).toHaveBeenCalledTimes(1);- });- expect(memoryTreeWipeAll).not.toHaveBeenCalled();-- // Second click — user accepts. RPC fires, success toast carries- // the rows count, and the graph re-fetches.- confirmSpy.mockReturnValueOnce(true);- fireEvent.click(button);- await waitFor(() => {- expect(memoryTreeWipeAll).toHaveBeenCalledTimes(1);- });- await waitFor(() => {- expect(onToast).toHaveBeenCalledWith(- expect.objectContaining({- type: 'success',- title: 'Memory wiped',- message: expect.stringContaining('42'),- })- );- });- confirmSpy.mockRestore();- });-- it('"Reset memory tree" requires a confirm and dispatches memory_tree_reset_tree', async () => {- const onToast = vi.fn();- const confirmSpy = vi.spyOn(window, 'confirm');-- // Cancel first → no RPC call.- confirmSpy.mockReturnValueOnce(false);- renderWithProviders(<MemoryWorkspace onToast={onToast} />);- const button = await screen.findByTestId('memory-reset-tree');- fireEvent.click(button);- await waitFor(() => {- expect(confirmSpy).toHaveBeenCalledTimes(1);- });- expect(memoryTreeResetTree).not.toHaveBeenCalled();-- // Accept → RPC fires, success toast carries the chunk + job counts.- confirmSpy.mockReturnValueOnce(true);- fireEvent.click(button);- await waitFor(() => {- expect(memoryTreeResetTree).toHaveBeenCalledTimes(1);- });- await waitFor(() => {- expect(onToast).toHaveBeenCalledWith(- expect.objectContaining({- type: 'success',- title: 'Memory tree rebuilding',- message: expect.stringContaining('7'),- })- );- });- confirmSpy.mockRestore();- });-- it('"Build summary trees" calls memory_tree_flush_now and toasts the buffer count', async () => {- const onToast = vi.fn();- renderWithProviders(<MemoryWorkspace onToast={onToast} />);- const button = await screen.findByTestId('memory-build-trees');- fireEvent.click(button);- await waitFor(() => {- expect(memoryTreeFlushNow).toHaveBeenCalledTimes(1);- });- await waitFor(() => {- expect(onToast).toHaveBeenCalledWith(- expect.objectContaining({ type: 'success', title: expect.stringContaining('3 buffer') })- );- });- });-- it('per-source Sync button dispatches memory_sources_sync with the source id', async () => {- listMemorySources.mockResolvedValue([- {- id: 'src-gmail-001',- kind: 'composio',- toolkit: 'gmail',- label: 'Gmail · [email protected]',- enabled: true,- },- ]);- syncMemorySource.mockResolvedValue(undefined);- const onToast = vi.fn();- renderWithProviders(<MemoryWorkspace onToast={onToast} />);- const button = await screen.findByTestId('memory-source-sync-gmail');- // Source row title surfaces the account identity.- expect(button.closest('li')).toHaveTextContent(/Gmail · alice@example\.com/);- fireEvent.click(button);- await waitFor(() => {- expect(syncMemorySource).toHaveBeenCalledWith('src-gmail-001');- });- // Success feedback now fires on the terminal `completed` stage event, not- // the RPC ack — which only spawns the background sync and returns in ~4ms- // (#3295). Simulate the core emitting completion for this source.- act(() => {- window.dispatchEvent(- new CustomEvent('openhuman:memory-sync-stage', {- detail: { stage: 'completed', source_id: 'src-gmail-001', detail: 'ingested 4 item(s)' },- })- );- });- await waitFor(() => {- expect(onToast).toHaveBeenCalledWith(- expect.objectContaining({- type: 'success',- title: expect.stringContaining('[email protected]'),- })- );- });- });-- it('surfaces an error message when the export RPC rejects', async () => {- memoryTreeGraphExport.mockRejectedValueOnce(new Error('boom'));- renderWithProviders(<MemoryWorkspace />);- await waitFor(() => {- expect(screen.getByText(/Failed to load memory graph/)).toBeInTheDocument();- });- });-});diff --git a/app/src/components/intelligence/__tests__/ObsidianVaultSection.test.tsx b/app/src/components/intelligence/__tests__/ObsidianVaultSection.test.tsxdeleted file mode 100644index ca31344eba..0000000000--- a/app/src/components/intelligence/__tests__/ObsidianVaultSection.test.tsx+++ /dev/null@@ -1,240 +0,0 @@-import { fireEvent, screen, waitFor } from '@testing-library/react';-import userEvent from '@testing-library/user-event';-import { beforeEach, describe, expect, it, type Mock, vi } from 'vitest';--import { renderWithProviders } from '../../../test/test-utils';-import { ObsidianVaultSection } from '../ObsidianVaultSection';--vi.mock('../../../utils/tauriCommands', () => ({ memoryTreeObsidianVaultStatus: vi.fn() }));--vi.mock('../../../utils/openUrl', () => ({ openUrl: vi.fn().mockResolvedValue(undefined) }));--vi.mock('../../../utils/tauriCommands/workspacePaths', () => ({- revealWorkspacePath: vi.fn().mockResolvedValue(undefined),- resolveWorkspaceAbsolutePath: vi.fn().mockResolvedValue('/tmp/workspace/memory_tree/content'),-}));--const { memoryTreeObsidianVaultStatus } =- (await import('../../../utils/tauriCommands')) as unknown as {- memoryTreeObsidianVaultStatus: Mock;- };--const { openUrl } = (await import('../../../utils/openUrl')) as unknown as { openUrl: Mock };--const { revealWorkspacePath, resolveWorkspaceAbsolutePath } =- (await import('../../../utils/tauriCommands/workspacePaths')) as unknown as {- revealWorkspacePath: Mock;- resolveWorkspaceAbsolutePath: Mock;- };--const ROOT = '/tmp/workspace/memory_tree/content';-const DEEP_LINK = 'obsidian://open?path=' + encodeURIComponent(ROOT);--function status(over: Partial<{ registered: boolean; config_found: boolean }> = {}) {- return { registered: false, config_found: true, content_root_abs: ROOT, ...over };-}--describe('ObsidianVaultSection', () => {- beforeEach(() => {- vi.clearAllMocks();- localStorage.clear();- openUrl.mockResolvedValue(undefined);- revealWorkspacePath.mockResolvedValue(undefined);- resolveWorkspaceAbsolutePath.mockResolvedValue(ROOT);- });-- it('registered vault → opens the deep link directly, no guidance shown', async () => {- memoryTreeObsidianVaultStatus.mockResolvedValue(status({ registered: true }));- const onToast = vi.fn();- renderWithProviders(<ObsidianVaultSection contentRootAbs={ROOT} onToast={onToast} />);-- fireEvent.click(screen.getByTestId('memory-open-in-obsidian'));-- await waitFor(() => expect(openUrl).toHaveBeenCalledWith(DEEP_LINK));- expect(screen.queryByTestId('obsidian-vault-guidance')).toBeNull();- await waitFor(() => expect(onToast).toHaveBeenCalled());- expect(onToast.mock.calls[0][0].type).toBe('info');- });-- it('unregistered vault → no deep link, shows guidance with the vault path', async () => {- memoryTreeObsidianVaultStatus.mockResolvedValue(status());- renderWithProviders(<ObsidianVaultSection contentRootAbs={ROOT} />);-- fireEvent.click(screen.getByTestId('memory-open-in-obsidian'));-- await waitFor(() => expect(screen.getByTestId('obsidian-vault-guidance')).toBeInTheDocument());- expect(openUrl).not.toHaveBeenCalled();- expect(screen.getByTestId('obsidian-vault-path')).toHaveTextContent(ROOT);- });-- // #4266: the section lives inside the horizontal MemoryControls toolbar, so- // the guidance panel must render out of normal flow (absolute popover) — an- // in-flow/`w-full` panel grows the flex item and reflows the whole toolbar.- it('guidance panel renders out of flow so the toolbar never reflows', async () => {- memoryTreeObsidianVaultStatus.mockResolvedValue(status());- renderWithProviders(<ObsidianVaultSection contentRootAbs={ROOT} />);-- fireEvent.click(screen.getByTestId('memory-open-in-obsidian'));-- const panel = await screen.findByTestId('obsidian-vault-guidance');- expect(panel).toHaveClass('absolute');- expect(panel).not.toHaveClass('w-full');- // The section itself stays inline (sized to the button), not a full-width column.- expect(screen.getByTestId('obsidian-vault-section')).toHaveClass('inline-flex');- });-- // #4266: as a floating popover the panel overlays the graph, so its background- // must be opaque — the old translucent `dark:bg-*-500/10` let content bleed- // through and made the text unreadable. (The panel moved from the stock- // violet ramp to the themeable `primary` one; the opacity contract is- // unchanged.)- it('guidance panel has an opaque background (does not bleed through)', async () => {- memoryTreeObsidianVaultStatus.mockResolvedValue(status());- renderWithProviders(<ObsidianVaultSection contentRootAbs={ROOT} />);-- fireEvent.click(screen.getByTestId('memory-open-in-obsidian'));-- const panel = await screen.findByTestId('obsidian-vault-guidance');- expect(panel).toHaveClass('bg-primary-50');- expect(panel).toHaveClass('dark:bg-primary-950');- expect(panel).not.toHaveClass('dark:bg-primary-500/10');- });-- // #4266: the floating panel needs explicit dismissal — close button, Escape,- // and click-outside all collapse it.- it('close button dismisses the guidance panel', async () => {- memoryTreeObsidianVaultStatus.mockResolvedValue(status());- renderWithProviders(<ObsidianVaultSection contentRootAbs={ROOT} />);-- fireEvent.click(screen.getByTestId('memory-open-in-obsidian'));- fireEvent.click(await screen.findByTestId('obsidian-vault-close'));-- await waitFor(() => expect(screen.queryByTestId('obsidian-vault-guidance')).toBeNull());- });-- it('Escape key dismisses the guidance panel', async () => {- memoryTreeObsidianVaultStatus.mockResolvedValue(status());- renderWithProviders(<ObsidianVaultSection contentRootAbs={ROOT} />);-- fireEvent.click(screen.getByTestId('memory-open-in-obsidian'));- await screen.findByTestId('obsidian-vault-guidance');- fireEvent.keyDown(document.body, { key: 'Escape' });-- await waitFor(() => expect(screen.queryByTestId('obsidian-vault-guidance')).toBeNull());- });-- it('clicking outside the section dismisses the guidance panel', async () => {- memoryTreeObsidianVaultStatus.mockResolvedValue(status());- renderWithProviders(<ObsidianVaultSection contentRootAbs={ROOT} />);-- fireEvent.click(screen.getByTestId('memory-open-in-obsidian'));- await screen.findByTestId('obsidian-vault-guidance');- // Radix's dismissable layer listens for `pointerdown`, not `mousedown` —- // `userEvent.click` drives the full native pointerdown/pointerup/click- // sequence (and, unlike a bare `fireEvent.pointerDown`, waits out Radix's- // internal `setTimeout(0)` that defers attaching the outside-pointerdown- // listener — otherwise a synchronous dispatch fires before Radix is- // listening at all).- const user = userEvent.setup();- await user.click(document.body);-- await waitFor(() => expect(screen.queryByTestId('obsidian-vault-guidance')).toBeNull());- });-- it('"Open anyway" fires the deep link even when unregistered', async () => {- memoryTreeObsidianVaultStatus.mockResolvedValue(status());- const onToast = vi.fn();- renderWithProviders(<ObsidianVaultSection contentRootAbs={ROOT} onToast={onToast} />);-- fireEvent.click(screen.getByTestId('memory-open-in-obsidian'));- const openAnyway = await screen.findByTestId('obsidian-open-anyway');- fireEvent.click(openAnyway);-- await waitFor(() => expect(openUrl).toHaveBeenCalledWith(DEEP_LINK));- });-- it('"Reveal Folder" in the guidance panel reveals the content root', async () => {- memoryTreeObsidianVaultStatus.mockResolvedValue(status());- renderWithProviders(<ObsidianVaultSection contentRootAbs={ROOT} />);-- fireEvent.click(screen.getByTestId('memory-open-in-obsidian'));- fireEvent.click(await screen.findByTestId('obsidian-reveal'));-- await waitFor(() => expect(revealWorkspacePath).toHaveBeenCalledWith('memory_tree/content'));- });-- it('config not found → Install Obsidian opens the download page', async () => {- memoryTreeObsidianVaultStatus.mockResolvedValue(status({ config_found: false }));- renderWithProviders(<ObsidianVaultSection contentRootAbs={ROOT} />);-- fireEvent.click(screen.getByTestId('memory-open-in-obsidian'));- fireEvent.click(await screen.findByTestId('obsidian-install'));-- await waitFor(() => expect(openUrl).toHaveBeenCalledWith('https://obsidian.md/download'));- });-- it('Advanced config-dir override persists to localStorage and re-checks with it', async () => {- memoryTreeObsidianVaultStatus.mockResolvedValue(status());- renderWithProviders(<ObsidianVaultSection contentRootAbs={ROOT} />);-- // First click → not registered → guidance.- fireEvent.click(screen.getByTestId('memory-open-in-obsidian'));- fireEvent.click(await screen.findByTestId('obsidian-advanced-toggle'));-- const input = await screen.findByTestId('obsidian-config-dir-input');- fireEvent.change(input, { target: { value: '/custom/obsidian' } });- fireEvent.click(screen.getByTestId('obsidian-config-dir-save'));-- await waitFor(() =>- expect(memoryTreeObsidianVaultStatus).toHaveBeenLastCalledWith('/custom/obsidian')- );- expect(localStorage.getItem('openhuman.obsidian.configDir')).toBe('/custom/obsidian');- });-- it('detection failure degrades gracefully to the guidance panel', async () => {- memoryTreeObsidianVaultStatus.mockRejectedValue(new Error('rpc down'));- renderWithProviders(<ObsidianVaultSection contentRootAbs={ROOT} />);-- fireEvent.click(screen.getByTestId('memory-open-in-obsidian'));-- await waitFor(() => expect(screen.getByTestId('obsidian-vault-guidance')).toBeInTheDocument());- expect(openUrl).not.toHaveBeenCalled();- });-- // #2492: the absolute path that feeds the `obsidian://open?path=…` URL must- // come from the shared workspace-link layer (the Rust-side resolver), not- // from the `contentRootAbs` prop. The prop stays around for display, but- // the deep link URL is composed with whatever the resolver returns.- it('deep link uses the workspace-link resolver, not the contentRootAbs prop', async () => {- const resolved = '/private/var/folders/canonical/memory_tree/content';- resolveWorkspaceAbsolutePath.mockResolvedValue(resolved);- memoryTreeObsidianVaultStatus.mockResolvedValue(status({ registered: true }));- renderWithProviders(<ObsidianVaultSection contentRootAbs={ROOT} />);-- fireEvent.click(screen.getByTestId('memory-open-in-obsidian'));-- await waitFor(() =>- expect(resolveWorkspaceAbsolutePath).toHaveBeenCalledWith('memory_tree/content')- );- await waitFor(() =>- expect(openUrl).toHaveBeenCalledWith('obsidian://open?path=' + encodeURIComponent(resolved))- );- });-- // #2492: when the Rust-side resolver rejects (e.g. workspace path missing- // on disk), the click must not silently no-op — it surfaces an error toast- // and keeps the guidance panel expanded so the user has an escape hatch.- it('resolver failure surfaces an error toast and keeps guidance expanded', async () => {- resolveWorkspaceAbsolutePath.mockRejectedValue(new Error('workspace path does not exist'));- memoryTreeObsidianVaultStatus.mockResolvedValue(status({ registered: true }));- const onToast = vi.fn();- renderWithProviders(<ObsidianVaultSection contentRootAbs={ROOT} onToast={onToast} />);-- fireEvent.click(screen.getByTestId('memory-open-in-obsidian'));-- await waitFor(() => expect(onToast).toHaveBeenCalled());- expect(onToast.mock.calls[0][0].type).toBe('error');- expect(openUrl).not.toHaveBeenCalled();- expect(screen.getByTestId('obsidian-vault-guidance')).toBeInTheDocument();- });-});diff --git a/app/src/components/intelligence/__tests__/memorySyncActivityStore.test.ts b/app/src/components/intelligence/__tests__/memorySyncActivityStore.test.tsdeleted file mode 100644index b34f882ca5..0000000000--- a/app/src/components/intelligence/__tests__/memorySyncActivityStore.test.ts+++ /dev/null@@ -1,205 +0,0 @@-/**- * @vitest-environment jsdom- */-import { beforeEach, describe, expect, it, vi } from 'vitest';--import type { SourceStatus } from '../../../services/memorySourcesService';-import {- applyStageEvent,- getMemorySyncActivity,- LATE_ITEM_STAGE_WINDOW_MS,- noteSyncRejected,- noteSyncRequested,- RECONCILE_GRACE_MS,- reconcileWithStatuses,- resetMemorySyncActivityForTests,- subscribeTerminalSyncEvents,-} from '../memorySyncActivityStore';--function status(source_id: string, extra: Partial<SourceStatus> = {}): SourceStatus {- return {- source_id,- chunks_synced: 0,- chunks_pending: 0,- last_chunk_at_ms: null,- freshness: 'idle',- ...extra,- };-}--describe('memorySyncActivityStore', () => {- beforeEach(() => {- resetMemorySyncActivityForTests();- });-- it('keeps a live bar per row from the stage stream until the run ends', () => {- applyStageEvent({ stage: 'running', source_id: 'src-a', detail: null });- let s = getMemorySyncActivity();- expect(s.progress.get('src-a')).toEqual({ stage: 'running', detail: null, percent: null });-- const ended = vi.fn();- const unsubscribe = subscribeTerminalSyncEvents(ended);- applyStageEvent({ stage: 'completed', source_id: 'src-a', detail: 'ingested 7 item(s)' });- s = getMemorySyncActivity();- expect(s.progress.has('src-a')).toBe(false);- expect(s.syncingIds.has('src-a')).toBe(false);- expect(s.results.get('src-a')).toEqual({ kind: 'success', items: 7, reason: null, note: null });- expect(ended).toHaveBeenCalledWith(- expect.objectContaining({- rowId: 'src-a',- stage: 'completed',- result: { kind: 'success', items: 7, reason: null, note: null },- })- );- unsubscribe();- });-- it('is fed by the window event without any screen mounted', () => {- window.dispatchEvent(- new CustomEvent('openhuman:memory-sync-stage', {- detail: { stage: 'fetching', source_id: 'src-b', detail: '2/4 pages' },- })- );- const s = getMemorySyncActivity();- expect(s.progress.get('src-b')).toEqual({- stage: 'fetching',- detail: '2/4 pages',- percent: 50,- });- expect(s.syncingIds.has('src-b')).toBe(true);- });-- it('lights the row on request and records a rejected request as a failed result', () => {- applyStageEvent({ stage: 'completed', source_id: 'src-c', detail: 'ingested 1 item(s)' });- noteSyncRequested('src-c');- let s = getMemorySyncActivity();- expect(s.syncingIds.has('src-c')).toBe(true);- expect(s.results.has('src-c')).toBe(false);-- noteSyncRejected('src-c', 'transport down');- s = getMemorySyncActivity();- expect(s.syncingIds.has('src-c')).toBe(false);- expect(s.results.get('src-c')).toEqual({- kind: 'failed',- items: null,- reason: 'transport down',- note: null,- });- });-- it('seeds a run the core reports that the store did not see start', () => {- reconcileWithStatuses([status('src-d', { sync_stage: 'running', sync_detail: 'pass 2' })]);- const s = getMemorySyncActivity();- expect(s.progress.get('src-d')).toEqual({ stage: 'running', detail: 'pass 2', percent: null });- // The flag follows the bar on a cold mount: the button must read as- // syncing, not only the row.- expect(s.syncingIds.has('src-d')).toBe(true);- });-- it("marks the connector's `running` stage as syncing like the reader stages", () => {- applyStageEvent({ stage: 'running', source_id: 'src-h', detail: null });- expect(getMemorySyncActivity().syncingIds.has('src-h')).toBe(true);- });-- it('leaves a fresh local entry alone when the core says idle, and clears a stale one', () => {- const t0 = 1_000_000;- applyStageEvent({ stage: 'running', source_id: 'src-e', detail: null });- // The store stamps Date.now(); reconcile with a "now" inside the grace.- reconcileWithStatuses([status('src-e', { sync_stage: null, sync_detail: null })], Date.now());- expect(getMemorySyncActivity().progress.has('src-e')).toBe(true);-- reconcileWithStatuses(- [status('src-e', { sync_stage: null, sync_detail: null })],- Date.now() + RECONCILE_GRACE_MS + t0- );- expect(getMemorySyncActivity().progress.has('src-e')).toBe(false);- expect(getMemorySyncActivity().syncingIds.has('src-e')).toBe(false);- });-- it('seeds the bar for a row the button lit when the poll reports it live', () => {- // The optimistic flag has no stage; if the first socket event was missed,- // the poll carries it.- noteSyncRequested('src-g');- reconcileWithStatuses([status('src-g', { sync_stage: 'running', sync_detail: null })]);- const s = getMemorySyncActivity();- expect(s.progress.get('src-g')).toEqual({ stage: 'running', detail: null, percent: null });- expect(s.syncingIds.has('src-g')).toBe(true);- });-- it('changes nothing for a core that does not report the field', () => {- applyStageEvent({ stage: 'running', source_id: 'src-f', detail: null });- reconcileWithStatuses([status('src-f')], Date.now() + RECONCILE_GRACE_MS * 10);- expect(getMemorySyncActivity().progress.has('src-f')).toBe(true);- });-- // openhuman#6257: the core's bridge re-emits per-document stages, and they- // can trail the run's terminal event.- it('keeps the result when a per-item stage trails the terminal event', () => {- applyStageEvent({ stage: 'running', source_id: 'src-i', detail: null });- applyStageEvent({ stage: 'completed', source_id: 'src-i', detail: 'ingested 2 item(s)' });- for (const stage of ['stored', 'queued', 'ingesting']) {- applyStageEvent({ stage, source_id: 'src-i', detail: 'queued chunk extraction' });- }- const s = getMemorySyncActivity();- expect(s.progress.has('src-i')).toBe(false);- expect(s.syncingIds.has('src-i')).toBe(false);- expect(s.results.get('src-i')).toEqual({ kind: 'success', items: 2, reason: null, note: null });- });-- it('tracks a new run after a finished one', () => {- applyStageEvent({ stage: 'failed', source_id: 'src-j', detail: 'boom' });- applyStageEvent({ stage: 'requested', source_id: 'src-j', detail: null });- applyStageEvent({ stage: 'queued', source_id: 'src-j', detail: null });- const s = getMemorySyncActivity();- expect(s.progress.get('src-j')?.stage).toBe('queued');- expect(s.syncingIds.has('src-j')).toBe(true);- expect(s.results.has('src-j')).toBe(false);- });-- it('lets a Sync press start a new run whose item stages count again', () => {- applyStageEvent({ stage: 'completed', source_id: 'src-k', detail: 'ingested 0 item(s)' });- noteSyncRequested('src-k');- applyStageEvent({ stage: 'stored', source_id: 'src-k', detail: null });- expect(getMemorySyncActivity().progress.get('src-k')?.stage).toBe('stored');- });-- it('does not seed a per-item stage the poll reports for a finished run', () => {- applyStageEvent({ stage: 'completed', source_id: 'src-l', detail: 'ingested 1 item(s)' });- reconcileWithStatuses([status('src-l', { sync_stage: 'queued', sync_detail: null })]);- const s = getMemorySyncActivity();- expect(s.progress.has('src-l')).toBe(false);- expect(s.syncingIds.has('src-l')).toBe(false);- });-- // A run whose start the app never saw shows up as per-item stages only, so- // once the window the core applies too has passed, those stages count.- it('counts per-item stages again once the finished run is past the window', () => {- const now = vi.spyOn(Date, 'now');- const finishedAt = 5_000_000;- now.mockReturnValue(finishedAt);- applyStageEvent({ stage: 'completed', source_id: 'src-m', detail: 'ingested 1 item(s)' });-- now.mockReturnValue(finishedAt + LATE_ITEM_STAGE_WINDOW_MS);- applyStageEvent({ stage: 'queued', source_id: 'src-m', detail: null });- expect(getMemorySyncActivity().progress.has('src-m')).toBe(false);-- now.mockReturnValue(finishedAt + LATE_ITEM_STAGE_WINDOW_MS + 1);- applyStageEvent({ stage: 'queued', source_id: 'src-m', detail: null });- expect(getMemorySyncActivity().progress.get('src-m')?.stage).toBe('queued');- expect(getMemorySyncActivity().syncingIds.has('src-m')).toBe(true);- now.mockRestore();- });-- it('lets the poll seed a per-item stage once the finished run is past the window', () => {- const finishedAt = 7_000_000;- const now = vi.spyOn(Date, 'now').mockReturnValue(finishedAt);- applyStageEvent({ stage: 'completed', source_id: 'src-n', detail: 'ingested 1 item(s)' });- now.mockRestore();-- const live = [status('src-n', { sync_stage: 'ingesting', sync_detail: null })];- reconcileWithStatuses(live, finishedAt + LATE_ITEM_STAGE_WINDOW_MS);- expect(getMemorySyncActivity().syncingIds.has('src-n')).toBe(false);- reconcileWithStatuses(live, finishedAt + LATE_ITEM_STAGE_WINDOW_MS + 1);- expect(getMemorySyncActivity().syncingIds.has('src-n')).toBe(true);- });-});diff --git a/app/src/components/intelligence/memory-workspace.css b/app/src/components/intelligence/memory-workspace.cssdeleted file mode 100644index 694cd50c2d..0000000000--- a/app/src/components/intelligence/memory-workspace.css+++ /dev/null@@ -1,617 +0,0 @@-/**- * Locked design tokens for the three-pane MemoryWorkspace browser.- *- * Scoped under `.memory-workspace-root` so the rest of the app's surfaces- * (which use the global stone/primary palette) are unaffected.- */-.memory-workspace-root {- /* Match the rest of the app's stone palette — dropped the cream tones- (#faf7f2 / #f4f0e9) that read yellowish next to the bottom nav bar. */- --paper: #fafaf9; /* stone-50 — base surface */- --paper-elevated: #ffffff; /* white — active/selected/list */- --paper-recessed: #f5f5f4; /* stone-100 — hover */- --paper-recessed-darker: #e7e5e4; /* stone-200 — pressed */- --hairline: #e7e5e4; /* stone-200 — borders */- --ink: #1c1917;- --ink-soft: #44403c;- --ink-whisper: #78716c;- --ocean: #4a83dd;- --ocean-deep: #2e5baa;- --ocean-mist: rgba(74, 131, 221, 0.08);- --sage: #7a9b7e;- --amber: #c8954d;- --coral: #c26b5c;- --shadow-rest: 0 1px 2px rgba(26, 31, 46, 0.04);- --r-tight: 4px;- --r-card: 8px;- --r-room: 12px;-}--.memory-workspace-root,-.memory-workspace-root * {- box-sizing: border-box;-}--.memory-workspace-root {- background: var(--paper);- color: var(--ink);- border-radius: var(--r-room);- border: 1px solid var(--hairline);- box-shadow: var(--shadow-rest);- overflow: hidden;- font-family:- Inter,- -apple-system,- BlinkMacSystemFont,- system-ui,- sans-serif;-}--.memory-workspace-grid {- display: grid;- grid-template-columns: 280px 380px 1fr;- min-height: 640px;- height: calc(100vh - 240px);- max-height: 900px;-}--.memory-workspace-grid > * + * {- border-left: 1px solid var(--hairline);-}--@media (max-width: 1100px) {- .memory-workspace-grid {- grid-template-columns: 1fr 1fr;- }- .memory-workspace-grid .mw-pane-detail {- display: none;- }- .memory-workspace-grid.mw-show-detail {- grid-template-columns: 1fr;- }- .memory-workspace-grid.mw-show-detail .mw-pane-navigator,- .memory-workspace-grid.mw-show-detail .mw-pane-results {- display: none;- }- .memory-workspace-grid.mw-show-detail .mw-pane-detail {- display: flex;- }-}--.mw-pane-navigator {- background: var(--paper-recessed);- display: flex;- flex-direction: column;- overflow: hidden;-}-.mw-pane-results {- background: var(--paper);- display: flex;- flex-direction: column;- overflow: hidden;-}-.mw-pane-detail {- background: var(--paper-elevated);- display: flex;- flex-direction: column;- overflow: hidden;-}--.mw-pane-scroll {- flex: 1 1 auto;- overflow-y: auto;- overflow-x: hidden;-}--/* Section headings — Inter uppercase, modern app-rail style. Replaces- the Cabinet Grotesk lowercase tracked treatment which read like a- magazine masthead in a left-rail context. */-.mw-section-heading {- font-family: Inter, system-ui, sans-serif;- font-size: 11px;- font-weight: 600;- letter-spacing: 0.06em;- text-transform: uppercase;- color: var(--ink-whisper);- padding: 10px 16px 6px;- display: flex;- align-items: center;- gap: 8px;- cursor: pointer;- user-select: none;- background: transparent;- border: none;- width: 100%;- text-align: left;- transition: color 120ms ease;-}-.mw-section-heading:hover {- color: var(--ink-soft);-}-.mw-section-chev {- margin-left: auto;- font-size: 11px;- opacity: 0.5;- transition: transform 120ms ease;-}-.mw-section-chev.open {- transform: rotate(90deg);-}--.mw-section {- border-bottom: 1px solid var(--hairline);-}-.mw-section:last-child {- border-bottom: none;-}--/* Nested sections — sources expanded shows Email/Slack/etc. as- sub-collapsibles. Indent + tone-shift the nested level so the- hierarchy reads visually. */-.mw-section .mw-section {- border-bottom: 1px solid var(--hairline);- border-left: 2px solid var(--hairline);- margin: 0 0 0 12px;- background: var(--paper-recessed);-}-.mw-section .mw-section:last-child {- border-bottom: none;-}-.mw-section .mw-section .mw-section-heading {- font-size: 10px;- letter-spacing: 0.04em;- padding: 6px 12px 4px;- color: var(--ink-soft);-}-.mw-section .mw-section .mw-section-heading:hover {- color: var(--ink);-}-.mw-section .mw-section .mw-list-item {- /* Source rows under a kind heading need a stronger indent so the- hierarchy is unambiguous: kind heading at one level, individual- senders deeper. Bump left padding so each row sits visibly under- the kind's chevron, with a sub-rail line to continue the nesting. */- padding: 5px 12px 5px 26px;- position: relative;-}-.mw-section .mw-section .mw-list-item::before {- content: '';- position: absolute;- left: 14px;- top: 0;- bottom: 0;- width: 1px;- background: var(--hairline);- opacity: 0.7;-}-.mw-section .mw-section .mw-list-item.is-active::before {- background: var(--ocean);- opacity: 1;-}--.mw-search-row {- padding: 12px 16px;- border-bottom: 1px solid var(--hairline);-}-.mw-search-input {- width: 100%;- background: transparent;- border: none;- border-bottom: 1px solid var(--hairline);- padding: 6px 0;- font-size: 14px;- color: var(--ink);- outline: none;- font-style: italic;-}-.mw-search-input:focus {- border-bottom-color: var(--ocean);-}-.mw-search-input::placeholder {- color: var(--ink-whisper);- font-style: italic;-}--.mw-heatmap-host {- padding: 8px 12px 12px;- border-bottom: 1px solid var(--hairline);-}-.mw-heatmap-host > div {- background: transparent !important;- border: none !important;- padding: 0 !important;-}-.mw-heatmap-host h3 {- display: none;-}-.mw-heatmap-host p {- font-size: 10px !important;- color: var(--ink-whisper) !important;- margin: 0 !important;-}--.mw-recent-summary {- padding: 8px 16px 14px;- font-size: 12px;- color: var(--ink-soft);- font-family: 'JetBrains Mono', 'SF Mono', Consolas, monospace;-}-.mw-recent-summary span + span {- margin-left: 8px;- color: var(--ink-whisper);-}--.mw-list {- list-style: none;- margin: 0;- padding: 0 0 8px;-}-.mw-list-item {- display: grid;- grid-template-columns: 8px 1fr auto;- gap: 10px;- align-items: center;- padding: 6px 16px;- cursor: pointer;- border-left: 2px solid transparent;- transition:- background 80ms,- border-color 80ms;- background: transparent;- border-top: none;- border-right: none;- border-bottom: none;- width: 100%;- text-align: left;-}-.mw-list-item:hover {- background: var(--paper-recessed-darker);-}-.mw-list-item.is-active {- background: var(--paper-elevated); /* white — matches bottom nav active state */- border-left-color: var(--ocean);- box-shadow: 0 1px 2px rgba(28, 25, 23, 0.04);-}-.mw-list-item.is-active .mw-list-name {- font-weight: 600;- color: var(--ink);-}-.mw-dot {- width: 8px;- height: 8px;- border-radius: 999px;- background: var(--ink-whisper);-}-.mw-dot.dot-admitted {- background: var(--sage);-}-.mw-dot.dot-pending {- background: var(--amber);-}-.mw-dot.dot-buffered {- background: var(--ocean);-}-.mw-dot.dot-dropped {- background: var(--coral);-}-.mw-list-name {- font-size: 14px;- color: var(--ink-soft);- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- font-weight: 500;-}-.mw-list-count {- font-family: 'JetBrains Mono', 'SF Mono', Consolas, monospace;- font-size: 11px;- color: var(--ink-whisper);-}--/* Result list */-.mw-results-empty,-.mw-detail-empty {- flex: 1;- display: flex;- flex-direction: column;- align-items: center;- justify-content: center;- text-align: center;- padding: 32px;- color: var(--ink-soft);-}-.mw-results-empty {- font-size: 13px;- color: var(--ink-whisper);-}-.mw-detail-empty {- font-family: 'Cabinet Grotesk', Inter, system-ui, sans-serif;-}-.mw-detail-empty .mw-empty-title {- font-size: 22px;- margin: 0 0 12px;- color: var(--ink-soft);-}-.mw-detail-empty .mw-empty-body {- font-size: 14px;- color: var(--ink-whisper);- max-width: 320px;- line-height: 1.6;-}--.mw-results-section {- border-bottom: 1px solid var(--hairline);-}-.mw-results-section-header {- position: sticky;- top: 0;- z-index: 1;- background: var(--paper);- font-family: 'Cabinet Grotesk', Inter, sans-serif;- font-size: 11px;- letter-spacing: 0.2em;- text-transform: uppercase;- color: var(--ink-whisper);- padding: 10px 16px 8px;- border-bottom: 1px solid var(--hairline);-}-.mw-result-row {- display: grid;- grid-template-columns: 56px 1fr;- gap: 12px;- padding: 12px 16px;- cursor: pointer;- border-left: 2px solid transparent;- border-bottom: 1px solid var(--hairline);- transition: background 80ms;- background: transparent;- border-right: none;- border-top: none;- width: 100%;- text-align: left;-}-.mw-result-row:last-child {- border-bottom: none;-}-.mw-result-row:hover {- background: var(--paper-recessed);-}-.mw-result-row.is-active {- background: var(--ocean-mist);- border-left-color: var(--ocean);-}-.mw-result-row.is-active .mw-result-subject {- font-weight: 600;- color: var(--ink);-}-.mw-result-time {- font-family: 'JetBrains Mono', 'SF Mono', Consolas, monospace;- font-size: 12px;- color: var(--ink-whisper);- padding-top: 1px;-}-.mw-result-content {- min-width: 0;-}-.mw-result-subject {- font-size: 14px;- font-weight: 500;- color: var(--ink);- display: -webkit-box;- -webkit-line-clamp: 2;- line-clamp: 2;- -webkit-box-orient: vertical;- overflow: hidden;- line-height: 1.4;-}-.mw-result-meta {- font-size: 12px;- color: var(--ink-soft);- margin-top: 2px;- white-space: nowrap;- overflow: hidden;- text-overflow: ellipsis;-}-.mw-result-kind {- font-family: 'JetBrains Mono', monospace;- font-size: 10px;- text-transform: uppercase;- letter-spacing: 0.08em;- color: var(--ink-whisper);- padding: 1px 6px;- border: 1px solid var(--hairline);- border-radius: 999px;- background: var(--paper);- margin-right: 2px;-}--/* Chunk detail letter */-.mw-detail-scroll {- padding: 40px 48px;-}-.mw-letter {- max-width: 720px;- margin: 0 auto;-}-.mw-letterhead {- margin-bottom: 24px;-}-.mw-letterhead-row {- display: grid;- grid-template-columns: 80px 1fr;- gap: 8px;- margin-bottom: 8px;- align-items: baseline;-}-.mw-letterhead-label {- font-family: 'JetBrains Mono', 'SF Mono', Consolas, monospace;- font-size: 11px;- text-transform: lowercase;- color: var(--ink-whisper);- letter-spacing: 0.05em;-}-.mw-letterhead-label::after {- content: '';- display: block;- border-bottom: 1px solid var(--hairline);- width: 40px;- margin-top: 2px;-}-.mw-letterhead-value {- font-size: 14px;- color: var(--ink);- line-height: 1.5;-}-.mw-letterhead-value-secondary {- font-size: 12px;- color: var(--ink-soft);- display: block;- margin-top: 2px;-}-.mw-letterhead-date {- margin-top: 12px;- font-family: 'JetBrains Mono', 'SF Mono', Consolas, monospace;- font-size: 12px;- color: var(--ink-soft);- letter-spacing: 0.05em;-}--.mw-rule {- border: none;- border-top: 1px solid var(--hairline);- margin: 24px 0;-}--.mw-letter-subject {- font-family: 'Cabinet Grotesk', Inter, system-ui, sans-serif;- font-size: 22px;- font-weight: 500;- letter-spacing: -0.01em;- color: var(--ink);- margin: 0 0 16px;- line-height: 1.35;-}--.mw-letter-body {- font-size: 15px;- line-height: 1.7;- color: var(--ink);- white-space: pre-wrap;- /* `word-wrap` is the legacy alias of `overflow-wrap`; modern engines- respect `overflow-wrap` directly without the legacy fallback. */- overflow-wrap: break-word;-}-.mw-letter-body p {- margin: 0 0 12px;-}--/* Mentioned section */-.mw-mentioned-heading,-.mw-whykept-heading {- font-family: 'Cabinet Grotesk', Inter, sans-serif;- font-size: 12px;- letter-spacing: 0.3em;- color: var(--ink-whisper);- text-transform: lowercase;- margin: 16px 0 12px;- font-weight: 500;-}--.mw-mentioned-table {- width: 100%;- border-collapse: collapse;-}-.mw-mentioned-row {- cursor: pointer;- background: transparent;- border: none;- /* Single padding declaration — was duplicated (`padding: 0` then- `padding: 6px 0` later in the block). Combined into the right- value below. */- padding: 6px 0;- width: 100%;- display: grid;- grid-template-columns: 110px 1fr auto;- gap: 12px;- font-size: 13px;- color: var(--ink);- align-items: baseline;- text-align: left;- border-bottom: 1px dotted var(--hairline);-}-.mw-mentioned-row:last-child {- border-bottom: none;-}-.mw-mentioned-row:hover {- background: var(--paper-recessed);-}-.mw-mentioned-kind {- font-family: 'JetBrains Mono', 'SF Mono', Consolas, monospace;- font-size: 11px;- color: var(--ink-whisper);- text-transform: lowercase;-}-.mw-mentioned-surface {- color: var(--ink);- font-size: 13px;-}-.mw-mentioned-count {- font-family: 'JetBrains Mono', 'SF Mono', Consolas, monospace;- font-size: 11px;- color: var(--ink-whisper);-}--/* Score bars */-.mw-scorebar-row {- display: grid;- grid-template-columns: 110px 1fr 60px;- gap: 12px;- align-items: center;- padding: 6px 0;- font-size: 13px;-}-.mw-scorebar-label {- font-size: 13px;- color: var(--ink-soft);-}-.mw-scorebar-value {- font-family: 'JetBrains Mono', 'SF Mono', Consolas, monospace;- font-size: 12px;- color: var(--ink);- text-align: right;-}-.mw-scorebar-threshold {- font-family: 'JetBrains Mono', 'SF Mono', Consolas, monospace;- font-size: 11px;- color: var(--ink-whisper);- text-align: center;- margin-top: 12px;- letter-spacing: 0.05em;-}--/* Footer */-.mw-letter-footer {- margin-top: 32px;- padding-top: 16px;- border-top: 1px solid var(--hairline);- font-family: 'JetBrains Mono', 'SF Mono', Consolas, monospace;- font-size: 11px;- color: var(--ink-whisper);- display: flex;- flex-wrap: wrap;- gap: 6px 12px;-}-.mw-letter-footer button {- background: transparent;- border: none;- padding: 0;- font-family: inherit;- font-size: inherit;- color: inherit;- cursor: pointer;- text-decoration: underline dotted;- text-underline-offset: 2px;-}-.mw-letter-footer button:hover {- color: var(--ocean);-}diff --git a/app/src/components/intelligence/memoryGraphLayout.test.ts b/app/src/components/intelligence/memoryGraphLayout.test.tsdeleted file mode 100644index be94409ff9..0000000000--- a/app/src/components/intelligence/memoryGraphLayout.test.ts+++ /dev/null@@ -1,114 +0,0 @@-import { describe, expect, it } from 'vitest';--import type { GraphEdge, GraphNode } from '../../utils/tauriCommands';-import {- buildGraph,- CONTACT_COLOR,- createSimulation,- LEAF_COLOR,- LEVEL_COLOR,- levelColor,- nodeColor,- nodeGlows,- nodeRadius,- pickNode,- type SimNode,- supportsWebGL,-} from './memoryGraphLayout';--function summary(overrides: Partial<GraphNode> = {}): GraphNode {- return { kind: 'summary', id: 's', label: 'S', level: 0, parent_id: null, ...overrides };-}-function chunk(overrides: Partial<GraphNode> = {}): GraphNode {- return { kind: 'chunk', id: 'c', label: 'C', ...overrides };-}-function contact(overrides: Partial<GraphNode> = {}): GraphNode {- return { kind: 'contact', id: 'p', label: 'P', entity_kind: 'person', ...overrides };-}--describe('memoryGraphLayout', () => {- it('colours summaries by level, wrapping the palette', () => {- expect(levelColor(0)).toBe(LEVEL_COLOR[0]);- expect(levelColor(2)).toBe(LEVEL_COLOR[2]);- expect(levelColor(LEVEL_COLOR.length)).toBe(LEVEL_COLOR[0]); // wraps- expect(levelColor(null)).toBe(LEAF_COLOR);- expect(levelColor(-5)).toBe(LEVEL_COLOR[0]); // clamped to 0- });-- it('nodeColor branches on kind', () => {- expect(nodeColor(summary({ level: 1 }))).toBe(LEVEL_COLOR[1]);- expect(nodeColor(chunk())).toBe(LEAF_COLOR);- expect(nodeColor(contact())).toBe(CONTACT_COLOR);- });-- it('nodeRadius grows with level (capped) and is fixed for chunk/contact', () => {- expect(nodeRadius(summary({ level: 0 }))).toBe(5);- expect(nodeRadius(summary({ level: 3 }))).toBe(12.5);- // Capped at 14: document merge-tier nodes live at a large synthetic level- // (MERGE_LEVEL_BASE = 1000+), so the raw `5 + level*2.5` is clamped to keep- // the d3 layout/collision sane instead of rendering giant discs.- expect(nodeRadius(summary({ level: 4 }))).toBe(14); // 5 + 4*2.5 = 15 → capped- expect(nodeRadius(summary({ level: 99 }))).toBe(14);- expect(nodeRadius(summary({ level: 1001 }))).toBe(14);- expect(nodeRadius(contact())).toBe(9);- expect(nodeRadius(chunk())).toBe(3);- });-- it('only summary/contact nodes glow', () => {- expect(nodeGlows(summary())).toBe(true);- expect(nodeGlows(contact())).toBe(true);- expect(nodeGlows(chunk())).toBe(false);- });-- it('buildGraph derives parent_id edges in tree mode and drops danglers', () => {- const nodes = [- summary({ id: 'root', parent_id: null }),- summary({ id: 'child', level: 1, parent_id: 'root' }),- chunk({ id: 'leaf', parent_id: 'child' }),- chunk({ id: 'orphan', parent_id: 'missing' }), // dangling → dropped- ];- const { simNodes, links } = buildGraph(nodes, [], 'tree');- expect(simNodes).toHaveLength(5); // 4 data nodes + synthetic root hub- expect(simNodes.every(n => typeof n.x === 'number' && typeof n.y === 'number')).toBe(true);- const pairs = links.map(l => `${String(l.source)}->${String(l.target)}`);- expect(pairs).toContain('child->root');- expect(pairs).toContain('leaf->child');- expect(pairs).not.toContain('orphan->missing');- });-- it('buildGraph uses explicit edges in contacts mode and drops danglers', () => {- const nodes = [chunk({ id: 'c1' }), contact({ id: 'p1' })];- const edges: GraphEdge[] = [- { from: 'c1', to: 'p1' },- { from: 'c1', to: 'ghost' }, // dangling endpoint → dropped- ];- const { links } = buildGraph(nodes, edges, 'contacts');- expect(links).toHaveLength(1); // no source nodes → no root links- expect(String(links[0].source)).toBe('c1');- expect(String(links[0].target)).toBe('p1');- });-- it('createSimulation resolves link ids to node objects and converges', () => {- const nodes = [summary({ id: 'root' }), summary({ id: 'child', parent_id: 'root' })];- const { simNodes, links } = buildGraph(nodes, [], 'tree');- const sim = createSimulation(simNodes, links);- for (let i = 0; i < 50; i++) sim.tick();- // forceLink replaces string ids with the actual node objects.- expect((links[0].source as SimNode).id).toBe('child');- expect((links[0].target as SimNode).id).toBe('root');- expect(Number.isFinite(simNodes[0].x)).toBe(true);- sim.stop();- });-- it('pickNode returns the nearest node within its disc, else null', () => {- const a: SimNode = { ...summary({ id: 'a', level: 0 }), x: 0, y: 0 };- const b: SimNode = { ...summary({ id: 'b', level: 0 }), x: 100, y: 0 };- expect(pickNode([a, b], 1, 1)?.id).toBe('a');- expect(pickNode([a, b], 99, 0)?.id).toBe('b');- expect(pickNode([a, b], 50, 50)).toBeNull(); // outside both discs- });-- it('supportsWebGL is false under jsdom (no GL context)', () => {- expect(supportsWebGL()).toBe(false);- });-});diff --git a/app/src/components/intelligence/memoryGraphLayout.ts b/app/src/components/intelligence/memoryGraphLayout.tsdeleted file mode 100644index bfb7016743..0000000000--- a/app/src/components/intelligence/memoryGraphLayout.ts+++ /dev/null@@ -1,251 +0,0 @@-/**- * Shared, render-agnostic layout + palette helpers for the memory graph.- *- * Physics is d3-force (Barnes–Hut quadtree charge, O(n log n)) so the- * 1000-node cap settles smoothly — the same model Obsidian's graph is- * built on. Both the WebGL (Pixi) renderer and the SVG fallback consume- * these helpers so colours, radii, edge derivation and hit-testing stay- * identical across paths.- */-import {- forceCenter,- forceCollide,- forceLink,- forceManyBody,- forceSimulation,- type Simulation,- type SimulationLinkDatum,- type SimulationNodeDatum,-} from 'd3-force';--import { type GraphEdge, type GraphMode, type GraphNode } from '../../utils/tauriCommands';--/**- * Per-level palette — each tree level "lights up" in its own hue- * (mirrors the Obsidian `path:L{n}` colour groups).- */-export const LEVEL_COLOR = [- '#7C3AED', // L0- '#4A83DD', // L1- '#1FB6C7', // L2- '#34C77B', // L3- '#E8A653', // L4- '#E0654A', // L5- '#C026D3', // L6+-];-export const LEAF_COLOR = '#94A3B8'; // raw chunks / leaves (no level)-export const CONTACT_COLOR = '#A78BFA'; // person entities (contacts mode)-export const SOURCE_COLOR = '#F97316'; // synthetic source root nodes-const ROOT_COLOR = '#8B5CF6'; // master root hub (purple)--/** Layout is computed in this fixed coordinate space; the renderer pans/zooms it. */-export const VIEWPORT_W = 1100;-export const VIEWPORT_H = 640;-// Lower bound shared by auto-fit framing and manual wheel zoom-out. Kept very-// small (20× zoom-out) so large clouds — e.g. a Notion connection's hundreds-// of page-chunk leaves — can be framed in full. At 0.3 the auto-fit was-// clamped above the scale needed to show every node, so big graphs rendered-// "too zoomed in" with the outer nodes spilling off-screen. Using one shared-// floor (rather than a separate, lower auto-fit floor) avoids a zoom-snap-// where the first wheel tick would jump back up to the manual floor.-export const ZOOM_MIN = 0.05;-export const ZOOM_MAX = 4;--export function levelColor(level: number | null | undefined): string {- if (level == null) return LEAF_COLOR;- return LEVEL_COLOR[Math.max(0, level) % LEVEL_COLOR.length];-}--export function nodeColor(node: GraphNode): string {- if (node.color) return node.color; // UI override (e.g. dimmed offline agents)- if (node.kind === 'root') return ROOT_COLOR;- if (node.kind === 'source') return SOURCE_COLOR;- if (node.kind === 'summary') return levelColor(node.level);- if (node.kind === 'contact') return CONTACT_COLOR;- return LEAF_COLOR; // chunk-}--export function nodeRadius(node: GraphNode): number {- if (node.kind === 'root') return 20;- if (node.kind === 'source') return 16;- if (node.kind === 'summary') {- // Higher levels render slightly larger, but the size MUST be capped:- // document source trees place their cross-document merge tier at a large- // synthetic level (MERGE_LEVEL_BASE = 1000+), so the raw `level * 2.5`- // would explode to thousands of px — rendering giant discs and, via the- // `forceCollide(nodeRadius + 2)` term, blowing the whole layout apart.- // The cap keeps merge nodes the largest summaries without distorting it.- const level = node.level ?? 0;- return Math.min(5 + level * 2.5, 14);- }- if (node.kind === 'contact') return 9;- return 3; // chunk / document leaf-}--/** Source / summary / contact nodes glow; leaves stay flat so the structure pops. */-export function nodeGlows(node: GraphNode): boolean {- return node.kind !== 'chunk';-}--/** A graph node carrying mutable physics state (x/y/vx/vy populated by d3-force). */-export interface SimNode extends GraphNode, SimulationNodeDatum {- x: number;- y: number;-}--export type SimLink = SimulationLinkDatum<SimNode>;--/**- * Seed node positions on a ring centred on the origin and derive links.- * Tree mode draws an edge from each node to its `parent_id`; contacts mode- * uses the explicit `edges`. Dangling endpoints are dropped.- */-const ROOT_NODE_ID = '__root__';--export function buildGraph(- nodes: GraphNode[],- edges: GraphEdge[],- mode: GraphMode,- rootLabel = 'Memory'-): { simNodes: SimNode[]; links: SimLink[] } {- const ids = new Set(nodes.map(n => n.id));-- // Synthetic master root at the origin — all source nodes fan out from it.- // `rootLabel` lets non-memory reuses (e.g. the orchestration overview) name- // the hub; defaults to "Memory".- const rootNode: SimNode = { kind: 'root', id: ROOT_NODE_ID, label: rootLabel, x: 0, y: 0 };-- const simNodes: SimNode[] = [rootNode];- for (let i = 0; i < nodes.length; i++) {- const n = nodes[i];- const angle = (i / Math.max(1, nodes.length)) * Math.PI * 2;- const r = 180 + (i % 7) * 14;- simNodes.push({ ...n, x: Math.cos(angle) * r, y: Math.sin(angle) * r });- }-- const links: SimLink[] = [];-- // Link every source node to the master root.- for (const n of nodes) {- if (n.kind === 'source') {- links.push({ source: n.id, target: ROOT_NODE_ID });- }- }-- if (mode === 'tree') {- for (const n of nodes) {- if (!n.parent_id || !ids.has(n.parent_id) || !ids.has(n.id)) continue;- links.push({ source: n.id, target: n.parent_id });- }- } else {- for (const e of edges) {- if (!ids.has(e.from) || !ids.has(e.to)) continue;- links.push({ source: e.from, target: e.to });- }- }- return { simNodes, links };-}--/**- * Optional per-graph tuning of the force simulation. Every field defaults to- * `1` (identity), so callers that omit it — including the Brain memory graph —- * get exactly the previous physics. Reuses that want a wider/looser layout- * (e.g. the orchestration scale showcase, which fans ~120 agents out from a- * core) scale the repulsion and link length up.- */-export interface SimTuning {- /** Multiplies the Coulomb repulsion (bigger → nodes push apart harder). */- chargeScale?: number;- /** Multiplies rest link length (bigger → longer springs, wider fan-out). */- linkDistanceScale?: number;- /** Multiplies the `distanceMax` cutoff so far-apart nodes still repel. */- distanceMaxScale?: number;- /** Multiplies the centring pull (smaller → nodes drift out from centre). */- centerScale?: number;-}--/**- * A cooled d3-force simulation (call `.tick()` from the render loop). Charge- * = Coulomb repulsion (Barnes–Hut), link = Hooke spring, plus centring and- * a soft collide so nodes don't stack.- */-export function createSimulation(- simNodes: SimNode[],- links: SimLink[],- tuning: SimTuning = {}-): Simulation<SimNode, SimLink> {- const charge = tuning.chargeScale ?? 1;- const linkDist = tuning.linkDistanceScale ?? 1;- const distMax = tuning.distanceMaxScale ?? 1;- const center = tuning.centerScale ?? 1;- return forceSimulation(simNodes)- .force(- 'charge',- forceManyBody<SimNode>()- .strength(n => {- if (n.kind === 'root') return -650 * charge;- if (n.kind === 'source') return -280 * charge;- return -140 * charge;- })- .distanceMax(300 * distMax)- )- .force(- 'link',- forceLink<SimNode, SimLink>(links)- .id(d => d.id)- .distance(link => {- const src = link.source as SimNode;- const tgt = link.target as SimNode;- if (src.kind === 'root' || tgt.kind === 'root') return 90 * linkDist;- if (src.kind === 'source' || tgt.kind === 'source') return 40 * linkDist;- return 22 * linkDist;- })- .strength(0.7)- )- .force('center', forceCenter(0, 0).strength(0.12 * center))- .force(- 'collide',- forceCollide<SimNode>().radius(n => {- if (n.kind === 'root') return 80;- if (n.kind === 'source') return 40;- return nodeRadius(n) + 2;- })- )- .stop();-}--/**- * Nearest node whose disc (radius + slop) contains the point, or null.- * Linear scan — trivial at the 1000-node cap and only runs on pointer- * events, never per frame.- */-export function pickNode(simNodes: SimNode[], x: number, y: number, slop = 4): SimNode | null {- let best: SimNode | null = null;- let bestD = Infinity;- for (const n of simNodes) {- const r = nodeRadius(n) + slop;- const dx = n.x - x;- const dy = n.y - y;- const d = dx * dx + dy * dy;- if (d <= r * r && d < bestD) {- bestD = d;- best = n;- }- }- return best;-}--/** Does the renderer have a usable WebGL context? Drives Pixi-vs-SVG. */-export function supportsWebGL(): boolean {- if (typeof document === 'undefined') return false;- try {- const canvas = document.createElement('canvas');- return !!(- canvas.getContext('webgl2') ||- canvas.getContext('webgl') ||- canvas.getContext('experimental-webgl')- );- } catch {- return false;- }-}diff --git a/app/src/components/intelligence/memorySourcesIcons.tsx b/app/src/components/intelligence/memorySourcesIcons.tsxdeleted file mode 100644index 076a4159d6..0000000000--- a/app/src/components/intelligence/memorySourcesIcons.tsx+++ /dev/null@@ -1,162 +0,0 @@-/**- * Small inline SVG icons used by MemorySourcesRegistry and its row/schedule- * subcomponents. Split out to keep the parent files under the size budget.- */--export function PlusIcon() {- return (- <svg- width="14"- height="14"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- strokeLinecap="round"- strokeLinejoin="round"- aria-hidden="true">- <path d="M12 5v14M5 12h14" />- </svg>- );-}--export function TrashIcon() {- return (- <svg- width="14"- height="14"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="1.8"- strokeLinecap="round"- strokeLinejoin="round"- aria-hidden="true">- <path d="M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6" />- </svg>- );-}--export function BuildIcon() {- return (- <svg- width="12"- height="12"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="1.8"- strokeLinecap="round"- strokeLinejoin="round"- aria-hidden="true">- <path d="M22 11.08V12a10 10 0 11-5.93-9.14" />- <path d="M22 4L12 14.01l-3-3" />- </svg>- );-}--export function SyncIcon() {- return (- <svg- width="12"- height="12"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="1.8"- strokeLinecap="round"- strokeLinejoin="round"- aria-hidden="true">- <path d="M21 12a9 9 0 11-3-6.7" />- <path d="M21 4v5h-5" />- </svg>- );-}--export function Spinner() {- return (- <svg- className="animate-spin"- width="12"- height="12"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- aria-hidden="true">- <circle cx="12" cy="12" r="9" opacity="0.25" />- <path d="M21 12a9 9 0 00-9-9" />- </svg>- );-}--export function GearIcon() {- return (- <svg- width="14"- height="14"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="1.8"- strokeLinecap="round"- strokeLinejoin="round"- aria-hidden="true">- <circle cx="12" cy="12" r="3" />- <path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83-2.83l.06-.06A1.65 1.65 0 004.68 15a1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 012.83-2.83l.06.06A1.65 1.65 0 009 4.68a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 2.83l-.06.06A1.65 1.65 0 0019.4 9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z" />- </svg>- );-}--export function CheckIcon() {- return (- <svg- width="12"- height="12"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2.5"- strokeLinecap="round"- strokeLinejoin="round"- aria-hidden="true">- <path d="M20 6L9 17l-5-5" />- </svg>- );-}--export function WarnIcon() {- return (- <svg- width="12"- height="12"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- strokeLinecap="round"- strokeLinejoin="round"- aria-hidden="true"- className="mt-0.5 shrink-0">- <path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />- <path d="M12 9v4M12 17h.01" />- </svg>- );-}--export function AllInIcon() {- return (- <svg- width="12"- height="12"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2"- strokeLinecap="round"- strokeLinejoin="round"- aria-hidden="true">- <path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z" />- </svg>- );-}diff --git a/app/src/components/intelligence/memorySourcesRowHelpers.ts b/app/src/components/intelligence/memorySourcesRowHelpers.tsdeleted file mode 100644index 7236dd7420..0000000000--- a/app/src/components/intelligence/memorySourcesRowHelpers.ts+++ /dev/null@@ -1,48 +0,0 @@-/**- * Pure formatting helpers shared by `MemorySourcesRegistry`, `MemorySyncSchedule`,- * and `MemorySourceRow`.- */-import type { MemorySourceEntry } from '../../services/memorySourcesService';--export function relativeTimestamp(epochMs: number | null, t: (k: string) => string): string | null {- if (epochMs === null) return null;- const delta = Date.now() - epochMs;- if (delta < 1000) return t('time.justNow');- const seconds = Math.floor(delta / 1000);- if (seconds < 60) return `${seconds}${t('time.secondsAgoSuffix')}`;- const minutes = Math.floor(seconds / 60);- if (minutes < 60) return `${minutes}${t('time.minutesAgoSuffix')}`;- const hours = Math.floor(minutes / 60);- if (hours < 24) return `${hours}${t('time.hoursAgoSuffix')}`;- const days = Math.floor(hours / 24);- return `${days}${t('time.daysAgoSuffix')}`;-}--export function sourceTreeScope(source: MemorySourceEntry): string | null {- if (source.kind === 'github_repo' && source.url) {- const m = source.url.match(/github\.com\/([^/]+)\/([^/.]+)/);- if (m) return `github:${m[1]}/${m[2]}`;- }- return source.id;-}--export function sourceDetail(source: MemorySourceEntry): string | null {- switch (source.kind) {- case 'composio': {- const parts = [source.toolkit, source.connection_id].filter(Boolean);- return parts.length ? parts.join(' · ') : null;- }- case 'folder':- return source.path ?? null;- case 'github_repo':- return source.url ?? null;- case 'rss_feed':- return source.url ?? null;- case 'web_page':- return source.url ?? null;- case 'twitter_query':- return source.query ?? null;- default:- return null;- }-}diff --git a/app/src/components/intelligence/memorySourcesSyncTypes.ts b/app/src/components/intelligence/memorySourcesSyncTypes.tsdeleted file mode 100644index eb59c9e7eb..0000000000--- a/app/src/components/intelligence/memorySourcesSyncTypes.ts+++ /dev/null@@ -1,129 +0,0 @@-/**- * Sync-progress types shared between `MemorySourcesRegistry` (which owns the- * in-flight state) and `MemorySourceRow` (which renders it). Split out so- * neither file needs to import the other for a type.- */--/** Live progress for a sync in flight, driven by MemorySyncStageChanged events. */-export interface SyncProgress {- stage: string;- detail: string | null;- percent: number | null;-}--/**- * Terminal outcome of a sync run, shown on the row after the `completed` or- * `failed` stage event arrives (#3295). Persists until the next sync starts,- * so a no-op ("0 new items") or failed sync leaves visible confirmation- * instead of the indicator silently vanishing.- */-/**- * Why a completed run stopped short, parsed from the remainder the core writes- * after the item count. `more_pending`: the per-run cap or the day's budget- * left more to read — click Sync again. `budget_spent`: the day's provider- * request budget is gone, so nothing more arrives until tomorrow; with a zero- * count that is the opposite of "Up to date", which is what the row used to- * say.- */-export type SyncNote = 'more_pending' | 'budget_spent';--export interface SyncResult {- kind: 'success' | 'failed';- /** New items ingested (success only); null when the count is unknown. */- items: number | null;- /** Human-readable failure reason (failed only). */- reason: string | null;- /** Why the run stopped short (success only); null when it did not. */- note: SyncNote | null;-}--/**- * Per-stage fallback percentages so the progress bar always advances even- * when no numeric "N/M" ratio is present in the detail string (RC#4, #3295).- */-export const STAGE_FALLBACK_PERCENT: Record<string, number> = {- requested: 2,- fetching: 5,- stored: 15,- queued: 25,- ingesting: 40,- completed: 100,-};--/**- * The stages that describe one item inside a run rather than the run itself.- * The core's sync-stage bridge emits them per stored document, and their- * details name internal ids (`mem_src:…`, `queue_depth=…`).- */-const ITEM_STAGES = new Set(['stored', 'queued', 'ingesting']);--/** Whether `stage` describes one item inside a run (see `ITEM_STAGES`). */-export function isItemStage(stage: string): boolean {- return ITEM_STAGES.has(stage);-}--/**- * The i18n key for each stage's plain-language label (openhuman#6257). The- * rows used to print the raw stage name, so the reader path's per-item stage- * surfaced as "Queued" beside "queued chunk extraction for mem_src:…" —- * pipeline vocabulary with no queue anywhere to look at. Spelled out literally- * so each key is visible to the i18n scanner.- */-const STAGE_LABEL_KEYS: Record<string, string> = {- requested: 'memorySources.stage.requested',- running: 'memorySources.stage.running',- fetching: 'memorySources.stage.fetching',- stored: 'memorySources.stage.stored',- queued: 'memorySources.stage.queued',- ingesting: 'memorySources.stage.ingesting',-};--/** The label key for `stage`, with a generic "Syncing" for one it does not know. */-export function stageLabelKey(stage: string): string {- return STAGE_LABEL_KEYS[stage] ?? 'memorySources.stage.unknown';-}--/**- * The stages whose detail a person can read: the connector's `running` detail- * ("pass 2 done, 400 item(s) so far"), a reader's `fetching` ratio, and the- * request itself. Listed rather than inferred, so a per-item stage's detail- * (`mem_src:…`, `queue_depth=…`) and a stage this app does not know yet stay- * hidden.- */-const DETAIL_STAGES = new Set(['requested', 'running', 'fetching']);--/** Whether a stage's detail is worth showing (see `DETAIL_STAGES`). */-export function showsStageDetail(stage: string): boolean {- return DETAIL_STAGES.has(stage);-}--/**- * Display labels keyed by source id, from the rows of- * `memory_sources.status_list` that carry one — a core that predates the- * `label` field sends none, and callers fall back to the id or the scope.- */-export function sourceLabelsById(- statuses: ReadonlyArray<{ source_id: string; label?: string }>-): Record<string, string> {- const labels: Record<string, string> = {};- for (const status of statuses) {- if (status.label) labels[status.source_id] = status.label;- }- return labels;-}--/**- * The syncing rows that name a registry source, sorted (openhuman#6257).- *- * The store lights a row for any stage event it can key, and the core's bridge- * keys its per-document `ingesting` stage for a document outside the registry- * (a Composio message, a note) by that document's id. Such a row never ends and- * names no source, so a screen that lists or counts runs keeps to the ids the- * status list reports.- */-export function registrySyncingIds(- syncingIds: ReadonlySet<string>,- sourceIds: ReadonlySet<string>-): string[] {- return [...syncingIds].filter(id => sourceIds.has(id)).sort();-}diff --git a/app/src/components/intelligence/memorySyncActivityStore.ts b/app/src/components/intelligence/memorySyncActivityStore.tsdeleted file mode 100644index 476539f6af..0000000000--- a/app/src/components/intelligence/memorySyncActivityStore.ts+++ /dev/null@@ -1,368 +0,0 @@-/**- * Live per-source sync state that outlives the Sources screen (openhuman#6019).- *- * The core runs a sync in a detached task and narrates it over the socket- * (`memory:sync_stage` → `openhuman:memory-sync-stage` on `window`). The- * Sources screen used to keep the resulting state — which rows are syncing,- * their live bar, their last result — in component state, with the window- * listener registered in an effect. Both went away with the component: a tab- * or route change mid-sync dropped the bar, the terminal event landed on- * nobody, and the row came back idle as if the sync had stopped. It had not.- *- * This module is the state's home instead. The listener is installed once,- * for the life of the page, and screens read the store; a screen that mounts- * mid-run finds the run where it is. What a screen still owns is the toast- * for a run that ends while it is mounted — see `subscribeTerminalSyncEvents`.- *- * The store is also fed from the other direction: `memory_sources.status_list`- * now says which sources the core has in flight, so a cold mount (or an app- * reload mid-run) seeds the bar from the poll, and a bar whose terminal event- * was lost is taken down once the core reports the row idle.- */-import { useSyncExternalStore } from 'react';--import type { SourceStatus } from '../../services/memorySourcesService';-import {- isItemStage,- STAGE_FALLBACK_PERCENT,- type SyncNote,- type SyncProgress,- type SyncResult,-} from './memorySourcesSyncTypes';--/**- * Parse a sync progress detail string into a 0–100 percent.- *- * - Recognises "N/M ..." numeric patterns and returns N/M as a ratio.- * - Falls back to the per-stage baseline when no ratio is present rather- * than returning a bogus number (RC#4, issue #3295).- * - Returns `null` when both approaches are unavailable (no stage either).- */-export function parseSyncProgress(detail: string | null, stage?: string): number | null {- // Try the numeric "N/M ..." ratio first.- if (detail) {- const match = detail.match(/^(\d+)\/(\d+)[\s/]/);- if (match) {- const current = parseInt(match[1], 10);- const total = parseInt(match[2], 10);- if (total > 0) return Math.round((current / total) * 100);- }- }- // Fall back to the per-stage baseline percentage.- if (stage && stage in STAGE_FALLBACK_PERCENT) {- return STAGE_FALLBACK_PERCENT[stage];- }- return null;-}--/**- * Parse the number of newly-ingested items from a `completed` stage detail- * string. The backend formats this as `"ingested N item(s)"`- * (`memory_sources/sync.rs`). Returns `null` when no count is present so the- * UI can fall back to a generic "synced" confirmation (#3295).- */-export function parseIngestedCount(detail: string | null): number | null {- if (!detail) return null;- const match = detail.match(/ingested\s+(\d+)\s+item/i);- if (match) return parseInt(match[1], 10);- return null;-}--/**- * Why a completed run stopped short, from the remainder the core writes after- * the count: `", more pending — Sync again to continue"` when the per-run cap- * left more to read, `"; today's provider request budget is spent"` when the- * day's budget did. The number alone made both read as a finished sync, and a- * spent budget with zero new items read as "Up to date" — the opposite of what- * happened. The budget wins when both appear: it is the reason nothing more- * will arrive today.- */-export function parseSyncNote(detail: string | null): SyncNote | null {- if (!detail) return null;- const lower = detail.toLowerCase();- if (lower.includes('budget')) return 'budget_spent';- if (lower.includes('more pending')) return 'more_pending';- return null;-}--/** The store's snapshot: one immutable object, replaced on every change. */-export interface MemorySyncActivity {- /** Rows a sync is running for — the button's spinner and disabled state. */- syncingIds: ReadonlySet<string>;- /** Live bar per row while a run is in flight. */- progress: ReadonlyMap<string, SyncProgress>;- /** Terminal chip per row after a run ended, until the next run starts. */- results: ReadonlyMap<string, SyncResult>;-}--/** The `openhuman:memory-sync-stage` event's `detail` payload. */-export interface SyncStageEventDetail {- stage?: string;- /** Originating memory-source id (RC#2, #3295). Preferred over connection_id. */- source_id?: string | null;- /** Legacy: document/connection id. Still present for backward compat. */- connection_id?: string | null;- detail?: string | null;-}--/** A run ending, for the screen that wants to say so. */-export interface TerminalSyncEvent {- rowId: string;- stage: 'completed' | 'failed';- detail: string | null;- result: SyncResult;-}--type TerminalListener = (event: TerminalSyncEvent) => void;--/**- * A local live entry younger than this is not overruled by a poll that says- * idle: the poll's answer may predate the `running` stage, and the button's- * optimistic flag always predates the core's first stage.- */-export const RECONCILE_GRACE_MS = 10_000;--/**- * Stages that mean a run is in progress for the button's sake (RC#1, #3295).- * `running` is the connector's one live stage; the reader path narrates the- * rest.- */-const SYNCING_STAGES = new Set([- 'running',- 'requested',- 'fetching',- 'stored',- 'queued',- 'ingesting',-]);--const EMPTY: MemorySyncActivity = {- syncingIds: new Set(),- progress: new Map(),- results: new Map(),-};--let state: MemorySyncActivity = EMPTY;-/** When each row's live entry was last written — the reconcile grace clock. */-const liveSince = new Map<string, number>();-/**- * How long a finished row ignores per-item stages: the core tracker's own- * ceiling (`STALE_AFTER_MS` in `memory/sync_activity.rs`). A new run normally- * announces itself first (the Sync button, or a `requested`, `fetching` or- * `running` stage), which clears the mark at once. Past the window, a per-item- * stage is taken as a later run whose start this app never saw, as the core's- * status list takes it.- */-export const LATE_ITEM_STAGE_WINDOW_MS = 30 * 60 * 1_000;--/**- * When each row's last run ended (openhuman#6257). The core's bridge re-emits- * the module's per-document events as `stored`, `queued` and `ingesting`, and- * they can arrive after the run's `completed`: without this the row went back- * to a live "Queued" bar and lost its result chip for a run that was over. A- * row leaves the map when a new run starts (any other stage, or the Sync- * button) or once its window has passed.- */-const finishedRows = new Map<string, number>();--/** Whether `stage` is a late per-item report of `rowId`'s finished run, as of `now`. */-function isLateItemStage(rowId: string, stage: string, now: number): boolean {- const finishedAt = finishedRows.get(rowId);- if (finishedAt === undefined || !isItemStage(stage)) return false;- if (now - finishedAt <= LATE_ITEM_STAGE_WINDOW_MS) return true;- finishedRows.delete(rowId);- return false;-}-const listeners = new Set<() => void>();-const terminalListeners = new Set<TerminalListener>();--function commit(next: MemorySyncActivity): void {- state = next;- for (const listener of listeners) listener();-}--function subscribe(listener: () => void): () => void {- listeners.add(listener);- return () => {- listeners.delete(listener);- };-}--function getSnapshot(): MemorySyncActivity {- return state;-}--/** The live state, re-rendering on every change. */-export function useMemorySyncActivity(): MemorySyncActivity {- return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);-}--/** The live state, once. */-export function getMemorySyncActivity(): MemorySyncActivity {- return state;-}--/**- * Be told when a run ends. The store records the result either way; this is- * for the screen-level courtesy of a toast, which only makes sense while a- * screen is there to show it.- */-export function subscribeTerminalSyncEvents(listener: TerminalListener): () => void {- terminalListeners.add(listener);- return () => {- terminalListeners.delete(listener);- };-}--/** Apply one stage event. Exported for tests; the window listener below is the caller. */-export function applyStageEvent(data: SyncStageEventDetail | null | undefined): void {- // RC#2 (#3295): prefer source_id when present; fall back to connection_id for- // backward compat with older core versions that don't emit source_id yet.- const rowId = data?.source_id ?? data?.connection_id;- if (!rowId) return;- const stage = data?.stage ?? '';- const detail = data?.detail ?? null;-- console.debug(- `[ui-flow][memory-sync] stage=${stage} rowId=${rowId} source_id=${data?.source_id ?? 'absent'} connection_id=${data?.connection_id ?? 'absent'}`- );-- if (stage === 'completed' || stage === 'failed') {- // Success: the item count parsed from the detail ("ingested N item(s)")- // and why the run stopped short, if it did; 0 new items → "up to date"- // (#3295). Failure: the reason, verbatim.- const result: SyncResult =- stage === 'completed'- ? {- kind: 'success',- items: parseIngestedCount(detail),- reason: null,- note: parseSyncNote(detail),- }- : { kind: 'failed', items: null, reason: detail, note: null };- const progress = new Map(state.progress);- progress.delete(rowId);- liveSince.delete(rowId);- const syncingIds = new Set(state.syncingIds);- syncingIds.delete(rowId);- const results = new Map(state.results);- results.set(rowId, result);- finishedRows.set(rowId, Date.now());- commit({ syncingIds, progress, results });- for (const listener of terminalListeners) listener({ rowId, stage, detail, result });- return;- }-- // A per-item stage for a run that already ended is a late report of that- // run, not a new one: keep the result chip (openhuman#6257).- if (isLateItemStage(rowId, stage, Date.now())) {- console.debug(`[ui-flow][memory-sync] ignored late stage=${stage} for finished rowId=${rowId}`);- return;- }- finishedRows.delete(rowId);-- // Non-terminal stage: a sync is genuinely in progress. Drop any stale- // terminal result for this row so the live bar replaces the old chip.- const results = new Map(state.results);- results.delete(rowId);- const progress = new Map(state.progress);- progress.set(rowId, { stage, detail, percent: parseSyncProgress(detail, stage) });- liveSince.set(rowId, Date.now());- const syncingIds = new Set(state.syncingIds);- if (SYNCING_STAGES.has(stage)) syncingIds.add(rowId);- commit({ syncingIds, progress, results });-}--/**- * The Sync button was pressed: light the row before the first stage arrives- * (RC#1, #3295) and drop the previous run's chip.- */-export function noteSyncRequested(rowId: string): void {- finishedRows.delete(rowId);- const syncingIds = new Set(state.syncingIds);- syncingIds.add(rowId);- const results = new Map(state.results);- results.delete(rowId);- liveSince.set(rowId, Date.now());- commit({ syncingIds, progress: state.progress, results });-}--/**- * The sync RPC itself was rejected, so no run started and no stage event will- * come: take the row down and record the reason as its result.- */-export function noteSyncRejected(rowId: string, reason: string): void {- const syncingIds = new Set(state.syncingIds);- syncingIds.delete(rowId);- const progress = new Map(state.progress);- progress.delete(rowId);- liveSince.delete(rowId);- const results = new Map(state.results);- results.set(rowId, { kind: 'failed', items: null, reason, note: null });- commit({ syncingIds, progress, results });-}--/**- * Fold the core's own account of what is in flight into the store.- *- * A row the core reports running that the store knows nothing about gets its- * bar (a cold mount, an app reload mid-run). A row the store has live that the- * core reports idle is taken down once its entry is older than the grace —- * the terminal event was lost, or never named the row. Rows from a core that- * does not report the field (`sync_stage` absent, not `null`) say nothing- * and change nothing.- */-export function reconcileWithStatuses(statuses: SourceStatus[], now = Date.now()): void {- const syncingIds = new Set(state.syncingIds);- const progress = new Map(state.progress);- const results = new Map(state.results);- let changed = false;- for (const status of statuses) {- if (status.sync_stage === undefined) continue;- const rowId = status.source_id;- const live = status.sync_stage;- const knownLive = progress.has(rowId) || syncingIds.has(rowId);- if (live) {- // A per-item stage for a run that already ended is a late report of- // that run, not a new one (openhuman#6257).- if (isLateItemStage(rowId, live, now)) continue;- // The core has the row running: the flag follows, whether the store- // learns of the run here (a cold mount) or already had the bar.- if (!syncingIds.has(rowId)) {- syncingIds.add(rowId);- changed = true;- }- // A row the button lit optimistically has no bar yet; if its first- // stage event was missed, the poll is what carries the stage.- if (progress.has(rowId)) continue;- const detail = status.sync_detail ?? null;- progress.set(rowId, { stage: live, detail, percent: parseSyncProgress(detail, live) });- liveSince.set(rowId, now);- results.delete(rowId);- changed = true;- } else if (knownLive) {- if (now - (liveSince.get(rowId) ?? 0) < RECONCILE_GRACE_MS) continue;- progress.delete(rowId);- liveSince.delete(rowId);- syncingIds.delete(rowId);- changed = true;- }- }- if (changed) commit({ syncingIds, progress, results });-}--/** Back to nothing in flight. Tests only. */-export function resetMemorySyncActivityForTests(): void {- liveSince.clear();- finishedRows.clear();- commit(EMPTY);-}--// Installed once, for the life of the page, and never removed: the socket-// service dispatches the event globally whether or not any screen is showing,-// and the whole point is to be listening while none is.-if (typeof window !== 'undefined') {- window.addEventListener('openhuman:memory-sync-stage', event => {- applyStageEvent((event as CustomEvent<SyncStageEventDetail | null>).detail);- });-}diff --git a/app/src/components/intelligence/memoryTreeStatusHelpers.tsx b/app/src/components/intelligence/memoryTreeStatusHelpers.tsxdeleted file mode 100644index 21ecd1f65e..0000000000--- a/app/src/components/intelligence/memoryTreeStatusHelpers.tsx+++ /dev/null@@ -1,311 +0,0 @@-/**- * Shared polling hook + presentational helpers for `MemoryTreeStatusPanel`.- * Extracted so the panel component itself stays under the file-size budget —- * behavior is unchanged, this is a pure move.- */-import { useCallback, useEffect, useRef, useState } from 'react';--import {- memoryNamespaceSummaries,- memorySyncStatusList,- type MemorySyncStatusRow,- memoryTreePipelineStatus,- type MemoryTreePipelineStatus,-} from '../../utils/tauriCommands';-import { Badge } from '../ui';--/** Translator function shape exposed by `useT()`. */-export type TFn = (key: string, fallback?: string) => string;--/**- * Adaptive polling cadence — match the existing memory ingestion- * panel so the two surfaces feel like one.- */-const FAST_POLL_MS = 1500;-const DEFAULT_POLL_MS = 4000;--/**- * Public hook so unit tests (and any future caller) can subscribe to the- * pipeline-status stream without re-implementing the polling dance.- */-export function useMemoryTreeStatus(): {- status: MemoryTreePipelineStatus | null;- /** Stored-document grand total from the mandatory namespaces surface. */- storedItems: number | null;- integrations: MemorySyncStatusRow[];- loading: boolean;- error: string | null;- refresh: () => Promise<void>;-} {- const [status, setStatus] = useState<MemoryTreePipelineStatus | null>(null);- const [storedItems, setStoredItems] = useState<number | null>(null);- const [integrations, setIntegrations] = useState<MemorySyncStatusRow[]>([]);- const [loading, setLoading] = useState(true);- const [error, setError] = useState<string | null>(null);- const cancelledRef = useRef(false);- const statusRef = useRef<MemoryTreePipelineStatus | null>(null);- statusRef.current = status;-- const fetchOnce = useCallback(async () => {- console.debug('[ui-flow][memory-tree-status] fetchOnce: entry');- // Stored-document total rides the same poll: it is the sync-verification- // number, from a different store than every tree tile (#5932 field- // finding — a user watched 100 items land while the tree figure sat at 2).- void memoryNamespaceSummaries()- .then(r => {- if (!cancelledRef.current) setStoredItems(r.total_documents);- })- .catch(() => {- if (!cancelledRef.current) setStoredItems(null);- });- try {- // Fetch pipeline + per-integration health in parallel so the strip- // and the tiles share a single 1.5s / 4s adaptive tick (#2763).- const [next, rows] = await Promise.all([- memoryTreePipelineStatus(),- memorySyncStatusList().catch(err => {- // Per-integration list is best-effort: surface an empty strip- // rather than wiping the panel when only the secondary endpoint- // fails. Pipeline failure still flips the panel-wide error.- console.warn(- '[ui-flow][memory-tree-status] memorySyncStatusList failed: %s',- err instanceof Error ? err.message : String(err)- );- return [] as MemorySyncStatusRow[];- }),- ]);- if (cancelledRef.current) return;- setStatus(next);- setIntegrations(rows);- setError(null);- console.debug(- '[ui-flow][memory-tree-status] fetchOnce: ok status=%s total=%d integrations=%d',- next.status,- next.total_chunks,- rows.length- );- } catch (err) {- if (cancelledRef.current) return;- const message = err instanceof Error ? err.message : String(err);- console.warn('[ui-flow][memory-tree-status] fetchOnce: error %s', message);- setError(message);- } finally {- if (!cancelledRef.current) setLoading(false);- }- }, []);-- 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 fast = live?.is_syncing || (live?.pipeline_jobs?.running ?? 0) > 0;- timer = setTimeout(tick, fast ? FAST_POLL_MS : DEFAULT_POLL_MS);- };-- void tick();-- return () => {- cancelledRef.current = true;- if (timer) clearTimeout(timer);- };- }, [fetchOnce]);-- return { status, storedItems, integrations, loading, error, refresh: fetchOnce };-}--/**- * Format a millisecond timestamp as a coarse "5 min ago" style label.- * Returns the localized `Never` placeholder when `ms` is 0/falsy.- *- * Intentionally light — no dayjs dependency, no plural rules. Buckets- * (just-now / seconds / minutes / hours / days) are enough for the status- * tile; the precise timestamp is one level deeper in the workspace UI.- *- * Strings flow through `t()` from `useT()` so the panel localizes- * cleanly. `{count}` placeholders are substituted client-side because- * `t()` does not interpolate (see `I18nContext.tsx`).- */-export function formatRelativeMs(ms: number, t: TFn, neverLabel: string): string {- if (!ms || ms <= 0) return neverLabel;- const diffMs = Date.now() - ms;- if (diffMs < 0) return neverLabel; // clock skew safety- const sec = Math.floor(diffMs / 1000);- if (sec < 30) return t('memoryTree.status.justNow');- if (sec < 60) return t('memoryTree.status.secondsAgo').replace('{count}', String(sec));- const min = Math.floor(sec / 60);- if (min < 60) {- if (min === 1) return t('memoryTree.status.minuteAgo');- return t('memoryTree.status.minutesAgo').replace('{count}', String(min));- }- const hr = Math.floor(min / 60);- if (hr < 24) {- if (hr === 1) return t('memoryTree.status.hourAgo');- return t('memoryTree.status.hoursAgo').replace('{count}', String(hr));- }- const day = Math.floor(hr / 24);- if (day === 1) return t('memoryTree.status.dayAgo');- return t('memoryTree.status.daysAgo').replace('{count}', String(day));-}--/**- * Format a raw byte count as KiB / MiB / GiB — sized to the order of- * magnitude. Negative / zero ⇒ `0 B`.- */-export function formatBytes(n: number): string {- if (!n || n <= 0) return '0 B';- const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];- let v = n;- let i = 0;- while (v >= 1024 && i < units.length - 1) {- v /= 1024;- i += 1;- }- // 1 decimal place once we're past bytes, integer for plain bytes.- return `${i === 0 ? Math.round(v) : v.toFixed(1)} ${units[i]}`;-}--/** Map the wire status to a dot color token + animation flag. */-export function statusDotClass(kind: MemoryTreePipelineStatus['status']): string {- switch (kind) {- case 'running':- return 'bg-sage-400';- case 'syncing':- return 'bg-sage-500 animate-pulse';- case 'paused':- return 'bg-content-faint';- case 'error':- return 'bg-coral-500';- case 'degraded':- // Amber: the pipeline is running but recall/structure is reduced.- return 'bg-amber-500';- case 'idle':- default:- return 'bg-content-faint';- }-}--/**- * UI health classification for a single provider row in the integration- * health strip (#2763). The wire shape's three-state `freshness` collapses- * to two states here — `Active` (currently producing chunks) vs `Stale`- * (anything older). An `Error` state is intentionally NOT derived from the- * current data; per-provider failure attribution needs new core work and- * is filed as a follow-up to issue #2763.- */-type IntegrationHealth = 'active' | 'stale';--/** Map the wire `freshness` enum to the two-state UI classification. */-export function classifyIntegration(- freshness: MemorySyncStatusRow['freshness']-): IntegrationHealth {- return freshness === 'active' ? 'active' : 'stale';-}--/**- * Built-in glyph for each known provider key from `memory_sync_status_list`.- * Source: `MemorySyncStatus.provider` in `crates/openhuman-core/src/memory/sync/sync_status/types.rs`- * — that file's doc comment enumerates the providers ("slack", "gmail",- * "discord", "telegram", "whatsapp", "notion", "meeting_notes",- * "drive_docs", etc.). Anything not in this map falls back to a generic- * plug glyph so unknown providers still render cleanly.- *- * Kept inline (rather than re-using `SOURCE_KIND_ICONS` from- * `memorySourcesService`) because that map is keyed by `SourceKind`- * (`composio` / `folder` / `github_repo` / …) — a different taxonomy.- */-const PROVIDER_ICONS: Record<string, string> = {- slack: '💬',- gmail: '📧',- discord: '🎮',- telegram: '✈️',- whatsapp: '🟢',- notion: '📝',- meeting_notes: '🎙️',- drive_docs: '📄',- github: '🐙',-};--/** Look up a provider glyph; fall back to a generic plug for unknowns. */-export function providerIconChar(provider: string): string {- return PROVIDER_ICONS[provider] ?? '🔌';-}--/**- * Per-integration health strip (#2763). Rendered between the four pipeline- * tiles and the auto-sync toggle inside `MemoryTreeStatusPanel`. Consumes- * the `integrations` slice returned by `useMemoryTreeStatus` — no- * additional fetch, no second timer.- */-export function IntegrationHealthStrip({- integrations,- loading,- t,-}: {- integrations: MemorySyncStatusRow[];- loading: boolean;- t: TFn;-}) {- return (- <div className="space-y-2" data-testid="memory-tree-integrations">- <div className="text-[11px] uppercase tracking-wide text-content-muted">- {t('memoryTree.status.integrationsTitle')}- </div>- {loading && integrations.length === 0 ? (- // First-mount: suppress "no integrations" copy until the initial poll- // resolves, otherwise the strip falsely implies nothing is connected- // before data arrives (CodeRabbit feedback on #2763).- <div- data-testid="memory-tree-integrations-skeleton"- className="h-9 animate-pulse rounded-lg bg-surface-strong"- />- ) : integrations.length === 0 ? (- <div- data-testid="memory-tree-integrations-empty"- className="rounded-lg border border-dashed border-line px-3 py-2 text-xs text-content-muted">- {t('memoryTree.status.integrationsEmpty')}- </div>- ) : (- <ul- className="max-h-48 space-y-1 overflow-y-auto rounded-lg border border-line bg-surface-muted/40 dark:bg-surface-muted/30 p-2"- aria-label={t('memoryTree.status.integrationsTitle')}>- {integrations.map(row => {- const health = classifyIntegration(row.freshness);- const healthLabel =- health === 'active'- ? t('memoryTree.status.integrationActive')- : t('memoryTree.status.integrationStale');- return (- <li- key={row.provider}- data-testid={`memory-tree-integration-row-${row.provider}`}- className="flex items-center justify-between gap-2 rounded-md px-2 py-1.5 hover:bg-surface-subtle/60 dark:hover:bg-surface-muted/60">- <div className="flex min-w-0 items-center gap-2">- <span aria-hidden className="text-base leading-none">- {providerIconChar(row.provider)}- </span>- <span className="truncate text-sm font-medium text-content">{row.provider}</span>- </div>- <div className="flex shrink-0 items-center gap-3 text-xs text-content-muted">- <span>- {t('memoryTree.status.integrationChunks').replace(- '{count}',- new Intl.NumberFormat().format(row.chunks_synced)- )}- </span>- <span>- {formatRelativeMs(row.last_chunk_at_ms ?? 0, t, t('memoryTree.status.never'))}- </span>- <Badge variant={health === 'active' ? 'success' : 'neutral'}>{healthLabel}</Badge>- </div>- </li>- );- })}- </ul>- )}- </div>- );-}diff --git a/app/src/components/intelligence/memoryWorkspacePaths.test.ts b/app/src/components/intelligence/memoryWorkspacePaths.test.tsdeleted file mode 100644index 7440e7fd68..0000000000--- a/app/src/components/intelligence/memoryWorkspacePaths.test.ts+++ /dev/null@@ -1,74 +0,0 @@-import { describe, expect, it } from 'vitest';--import type { GraphNode } from '../../utils/tauriCommands';-import { MEMORY_CONTENT_WORKSPACE_PATH, summaryWorkspacePath } from './memoryWorkspacePaths';--function summaryNode(overrides: Partial<GraphNode> = {}): GraphNode {- return {- kind: 'summary',- id: 'summary-1',- label: 'Summary',- tree_id: 'tree-1',- tree_kind: 'topic',- tree_scope: 'Team_Name',- level: 1,- parent_id: null,- child_count: 0,- file_basename: 'summary-file',- ...overrides,- };-}--describe('memoryWorkspacePaths', () => {- it('returns null for graph nodes that cannot resolve to a summary file', () => {- expect(summaryWorkspacePath({ kind: 'chunk', id: 'c1', label: 'Chunk' })).toBeNull();- expect(summaryWorkspacePath(summaryNode({ file_basename: undefined }))).toBeNull();- expect(summaryWorkspacePath(summaryNode({ tree_kind: undefined }))).toBeNull();- expect(- summaryWorkspacePath(summaryNode({ tree_kind: null as unknown as GraphNode['tree_kind'] }))- ).toBeNull();- expect(summaryWorkspacePath(summaryNode({ level: undefined }))).toBeNull();- expect(- summaryWorkspacePath(summaryNode({ level: null as unknown as GraphNode['level'] }))- ).toBeNull();- });-- it('preserves internal underscores while trimming leading/trailing separators', () => {- expect(- summaryWorkspacePath(summaryNode({ tree_kind: 'source', tree_scope: '__Team_Name__' }))- ).toBe(`${MEMORY_CONTENT_WORKSPACE_PATH}/wiki/summaries/source-team_name/L1/summary-file.md`);- });-- it('strips gmail prefixes from source scopes before slugifying', () => {- expect(- summaryWorkspacePath(- summaryNode({ tree_kind: 'source', tree_scope: 'gmail:[email protected]' })- )- ).toBe(- `${MEMORY_CONTENT_WORKSPACE_PATH}/wiki/summaries/source-user-example-com/L1/summary-file.md`- );- });-- it('formats valid timestamps as ISO dates for global summaries', () => {- const ms = new Date('2024-06-15T12:00:00Z').getTime();-- expect(- summaryWorkspacePath(summaryNode({ tree_kind: 'global', time_range_start_ms: ms }))- ).toBe(`${MEMORY_CONTENT_WORKSPACE_PATH}/wiki/summaries/global-2024-06-15/L1/summary-file.md`);- });-- it('uses unknown-date for global summaries with missing or invalid timestamps', () => {- expect(- summaryWorkspacePath(summaryNode({ tree_kind: 'global', time_range_start_ms: undefined }))- ).toBe(- `${MEMORY_CONTENT_WORKSPACE_PATH}/wiki/summaries/global-unknown-date/L1/summary-file.md`- );- expect(- summaryWorkspacePath(- summaryNode({ tree_kind: 'global', time_range_start_ms: Number.MAX_SAFE_INTEGER })- )- ).toBe(- `${MEMORY_CONTENT_WORKSPACE_PATH}/wiki/summaries/global-unknown-date/L1/summary-file.md`- );- });-});diff --git a/app/src/components/intelligence/memoryWorkspacePaths.ts b/app/src/components/intelligence/memoryWorkspacePaths.tsdeleted file mode 100644index ca362c791b..0000000000--- a/app/src/components/intelligence/memoryWorkspacePaths.ts+++ /dev/null@@ -1,63 +0,0 @@-import type { GraphNode } from '../../utils/tauriCommands';--export const MEMORY_CONTENT_WORKSPACE_PATH = 'memory_tree/content';--/** Mirror of `paths::slugify_source_id` (Rust). */-function slugify(s: string): string {- const lower = s.toLowerCase();- let out = '';- let lastDash = true;- let pendingUnderscore = false;- for (const ch of lower) {- if (ch === '_') {- if (!lastDash) pendingUnderscore = true;- } else if (/[a-z0-9]/.test(ch)) {- if (pendingUnderscore) {- out += '_';- pendingUnderscore = false;- }- out += ch;- lastDash = false;- } else {- pendingUnderscore = false;- if (!lastDash) {- out += '-';- lastDash = true;- }- }- }- return out.replace(/[-_]+$/, '').slice(0, 120) || 'unknown';-}--function dateFromMs(ms?: number): string {- if (typeof ms !== 'number' || !Number.isFinite(ms)) return 'unknown-date';- const date = new Date(ms);- if (Number.isNaN(date.getTime())) return 'unknown-date';- return date.toISOString().slice(0, 10);-}--function joinWorkspaceContentPath(relPath: string): string {- const rel = relPath.replace(/^\/+/, '');- return rel ? `${MEMORY_CONTENT_WORKSPACE_PATH}/${rel}` : MEMORY_CONTENT_WORKSPACE_PATH;-}--function summaryScopeSlug(node: GraphNode): string {- const scope = node.tree_scope ?? '';- if (node.tree_kind === 'source' && scope.startsWith('gmail:')) {- return slugify(scope.slice('gmail:'.length));- }- return slugify(scope);-}--export function summaryWorkspacePath(node: GraphNode): string | null {- if (node.kind !== 'summary' || !node.tree_kind || node.level == null || !node.file_basename) {- return null;- }-- const rel =- node.tree_kind === 'global'- ? `wiki/summaries/global-${dateFromMs(node.time_range_start_ms)}/L${node.level}/${node.file_basename}.md`- : `wiki/summaries/${node.tree_kind}-${summaryScopeSlug(node)}/L${node.level}/${node.file_basename}.md`;-- return joinWorkspaceContentPath(rel);-}diff --git a/app/src/components/intelligence/pixiGraphRenderer.test.ts b/app/src/components/intelligence/pixiGraphRenderer.test.tsdeleted file mode 100644index 6d22c8c22d..0000000000--- a/app/src/components/intelligence/pixiGraphRenderer.test.ts+++ /dev/null@@ -1,206 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';--import type { SimLink, SimNode } from './memoryGraphLayout';-import { mountPixiGraph } from './pixiGraphRenderer';--// Minimal Pixi stubs that record the handlers the renderer wires up so we-// can drive them from the test. Shared with the mock via vi.hoisted.-const h = vi.hoisted(() => {- const state: {- stageHandlers: Record<string, (e: unknown) => void>;- canvasListeners: Record<string, (e: unknown) => void>;- rendererHandlers: Record<string, () => void>;- tickerCb: (() => void) | null;- destroyed: boolean;- } = {- stageHandlers: {},- canvasListeners: {},- rendererHandlers: {},- tickerCb: null,- destroyed: false,- };- class Graphics {- clear() {- return this;- }- circle() {- return this;- }- fill() {- return this;- }- moveTo() {- return this;- }- lineTo() {- return this;- }- stroke() {- return this;- }- }- class Container {- position = {- x: 0,- y: 0,- set(x: number, y: number) {- this.x = x;- this.y = y;- },- };- scale = {- x: 1,- y: 1,- set(s: number) {- this.x = s;- this.y = s;- },- };- children: unknown[] = [];- eventMode = '';- hitArea: unknown = null;- addChild(c: unknown) {- this.children.push(c);- }- removeChildren() {- this.children = [];- }- toLocal(p: { x: number; y: number }) {- return {- x: (p.x - this.position.x) / this.scale.x,- y: (p.y - this.position.y) / this.scale.y,- };- }- on(ev: string, cb: (e: unknown) => void) {- state.stageHandlers[ev] = cb;- }- }- class Application {- canvas = {- style: {} as Record<string, string>,- addEventListener: (ev: string, cb: (e: unknown) => void) => {- state.canvasListeners[ev] = cb;- },- removeEventListener: vi.fn(),- };- stage = new Container();- screen = { width: 800, height: 600 };- ticker = {- add: (cb: () => void) => {- state.tickerCb = cb;- },- };- renderer = {- on: (ev: string, cb: () => void) => {- state.rendererHandlers[ev] = cb;- },- };- init = vi.fn().mockResolvedValue(undefined);- destroy = vi.fn(() => {- state.destroyed = true;- });- }- return { state, Graphics, Container, Application };-});--vi.mock('pixi.js', () => ({- Application: h.Application,- Container: h.Container,- Graphics: h.Graphics,-}));-vi.mock('pixi.js/unsafe-eval', () => ({}));--function makeNodes(): SimNode[] {- return [- { kind: 'summary', id: 'root', label: 'R', level: 0, parent_id: null, x: 0, y: 0 },- { kind: 'chunk', id: 'leaf', label: 'L', x: 200, y: 0 },- ];-}--describe('mountPixiGraph', () => {- beforeEach(() => {- h.state.stageHandlers = {};- h.state.canvasListeners = {};- h.state.rendererHandlers = {};- h.state.tickerCb = null;- h.state.destroyed = false;- });-- async function mount() {- const simNodes = makeNodes();- const links: SimLink[] = [{ source: simNodes[1], target: simNodes[0] }];- const onHover = vi.fn();- const onOpen = vi.fn();- const host = { appendChild: vi.fn() } as unknown as HTMLElement;- const handle = await mountPixiGraph(host, { simNodes, links, dark: false, onHover, onOpen });- return { handle, simNodes, onHover, onOpen, host };- }-- it('wires interaction handlers and a render loop', async () => {- const { host } = await mount();- expect(host.appendChild).toHaveBeenCalled();- expect(h.state.tickerCb).toBeTypeOf('function');- expect(h.state.stageHandlers.pointerdown).toBeTypeOf('function');- // Render loop draws while the simulation is warm.- expect(() => h.state.tickerCb?.()).not.toThrow();- });-- it('opens a node on a click without movement', async () => {- const { onOpen } = await mount();- // World is centred at (400,300); a click there maps to graph (0,0) = "root".- h.state.stageHandlers.pointerdown({ global: { x: 400, y: 300 } });- h.state.stageHandlers.pointerup({});- expect(onOpen).toHaveBeenCalledWith(expect.objectContaining({ id: 'root' }));- });-- it('drags a node instead of opening it once the pointer moves', async () => {- const { onOpen, simNodes } = await mount();- h.state.stageHandlers.pointerdown({ global: { x: 400, y: 300 } });- h.state.stageHandlers.pointermove({ global: { x: 450, y: 320 } });- h.state.stageHandlers.pointerup({});- expect(onOpen).not.toHaveBeenCalled();- // Pin released after the drag so physics can resume.- expect(simNodes[0].fx ?? null).toBeNull();- });-- it('emits hover when the pointer is over a node and clears it off-node', async () => {- const { onHover } = await mount();- h.state.stageHandlers.pointermove({ global: { x: 400, y: 300 } }); // over root- expect(onHover).toHaveBeenLastCalledWith(expect.objectContaining({ id: 'root' }));- h.state.stageHandlers.pointermove({ global: { x: 10, y: 10 } }); // empty space- expect(onHover).toHaveBeenLastCalledWith(null);- });-- it('pans on background drag', async () => {- await mount();- // Pointer down on empty space starts a pan, not a node drag.- expect(() => {- h.state.stageHandlers.pointerdown({ global: { x: 10, y: 10 } });- h.state.stageHandlers.pointermove({ global: { x: 60, y: 40 } });- h.state.stageHandlers.pointerup({});- }).not.toThrow();- });-- it('zooms on wheel without throwing and prevents default scroll', async () => {- await mount();- const preventDefault = vi.fn();- h.state.canvasListeners.wheel({ offsetX: 400, offsetY: 300, deltaY: -120, preventDefault });- expect(preventDefault).toHaveBeenCalled();- });-- it('resetView, setTheme and resize redraw without error', async () => {- const { handle } = await mount();- expect(() => {- handle.setTheme(true);- handle.resetView();- h.state.rendererHandlers.resize?.();- h.state.tickerCb?.();- }).not.toThrow();- });-- it('destroy tears down the Pixi application', async () => {- const { handle } = await mount();- handle.destroy();- expect(h.state.destroyed).toBe(true);- });-});diff --git a/app/src/components/intelligence/pixiGraphRenderer.ts b/app/src/components/intelligence/pixiGraphRenderer.tsdeleted file mode 100644index 7f393e4ccc..0000000000--- a/app/src/components/intelligence/pixiGraphRenderer.ts+++ /dev/null@@ -1,395 +0,0 @@-/**- * WebGL memory-graph renderer — Pixi.js draw loop driven by a d3-force- * simulation. This is the same stack Obsidian's graph view uses (Pixi for- * GPU rendering, force-directed physics) so it stays smooth well past the- * 1000-node cap.- *- * The renderer is fully imperative: a React wrapper mounts it into a host- * element and feeds hover/open back through callbacks. All interaction- * (drag a node, drag the background to pan, wheel to zoom) is hit-tested- * against the simulation positions in `memoryGraphLayout`, so there are no- * per-node DOM objects — the whole graph is a single canvas.- *- * Drawing is dirty-flagged: while the simulation is warm (or the user is- * interacting) we redraw each frame; once it cools the loop idles.- */-import { Application, Container, type FederatedPointerEvent, Graphics, Text } from 'pixi.js';-import 'pixi.js/unsafe-eval';--import {- createSimulation,- nodeColor,- nodeGlows,- nodeRadius,- pickNode,- type SimLink,- type SimNode,- type SimTuning,- ZOOM_MAX,- ZOOM_MIN,-} from './memoryGraphLayout';--interface PixiGraphOptions {- simNodes: SimNode[];- links: SimLink[];- dark: boolean;- onHover: (node: SimNode | null) => void;- onOpen: (node: SimNode) => void;- /** Fired once the force simulation first cools (graph is laid out). */- onReady?: () => void;- /** Initial auto-fit zoom (world scale). Defaults to 0.17. */- fitScale?: number;- /** Fit the whole node cloud tightly to the viewport instead of a fixed zoom. */- fitToBounds?: boolean;- /** Draw an always-on text label under each node (off by default). */- showLabels?: boolean;- /** Optional force-simulation tuning (defaults preserve the standard layout). */- tuning?: SimTuning;-}--export interface PixiGraphHandle {- resetView(): void;- setTheme(dark: boolean): void;- updateGraph(simNodes: SimNode[], links: SimLink[]): void;- destroy(): void;-}--function colorNum(hex: string): number {- return parseInt(hex.replace('#', ''), 16);-}--/**- * Mount a Pixi graph into `host`. Resolves once the WebGL context is live;- * rejects/throws if Pixi can't initialise (caller falls back to SVG).- */-export async function mountPixiGraph(- host: HTMLElement,- opts: PixiGraphOptions-): Promise<PixiGraphHandle> {- const app = new Application();- await app.init({- resizeTo: host,- backgroundAlpha: 0,- antialias: true,- autoDensity: true,- resolution: typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1,- // Match Obsidian — force the WebGL backend rather than letting Pixi- // probe WebGPU, which is uneven across the CEF runtime.- preference: 'webgl',- });- host.appendChild(app.canvas);- app.canvas.style.width = '100%';- app.canvas.style.height = '100%';- app.canvas.style.display = 'block';-- const world = new Container();- const edgeG = new Graphics();- const nodeG = new Graphics();- const labelG = new Container();- world.addChild(edgeG);- world.addChild(nodeG);- world.addChild(labelG); // labels paint above the discs- app.stage.addChild(world);-- const recenter = () => world.position.set(app.screen.width / 2, app.screen.height / 2);- recenter();-- const sim = createSimulation(opts.simNodes, opts.links, opts.tuning);- sim.alpha(1);-- let dark = opts.dark;- let dirty = true;- let hoveredId: string | null = null;- // Fires `onReady` exactly once when the sim first cools — the signal a- // loading overlay (e.g. the Brain page) waits on before revealing the graph.- let readyFired = false;- // Auto-fit the whole graph into view until the user pans/zooms/drags,- // so the initial frame is zoomed out to show as much as possible.- let userInteracted = false;-- /**- * Frame the graph. With `fitToBounds`, scale so the whole node cloud fits the- * viewport as tightly as possible (a little margin for node radii/labels);- * otherwise centre on the root at a fixed comfortable zoom (`fitScale`).- */- const fitToView = () => {- if (opts.simNodes.length === 0) return;-- if (opts.fitToBounds) {- let minX = Infinity;- let minY = Infinity;- let maxX = -Infinity;- let maxY = -Infinity;- for (const n of opts.simNodes) {- const r = nodeRadius(n) + 8; // pad for the node radius + a little label room- minX = Math.min(minX, n.x - r);- minY = Math.min(minY, n.y - r);- maxX = Math.max(maxX, n.x + r);- maxY = Math.max(maxY, n.y + r);- }- const w = Math.max(1, maxX - minX);- const h = Math.max(1, maxY - minY);- const margin = 0.92; // leave ~8% breathing room around the content- const scale = Math.min(- ZOOM_MAX,- Math.max(ZOOM_MIN, Math.min(app.screen.width / w, app.screen.height / h) * margin)- );- const cx = (minX + maxX) / 2;- const cy = (minY + maxY) / 2;- world.scale.set(scale);- world.position.set(app.screen.width / 2 - cx * scale, app.screen.height / 2 - cy * scale);- return;- }-- const root = opts.simNodes.find(n => n.kind === 'root');- const cx = root?.x ?? 0;- const cy = root?.y ?? 0;- const scale = opts.fitScale ?? 0.17;- world.scale.set(scale);- world.position.set(app.screen.width / 2 - cx * scale, app.screen.height / 2 - cy * scale);- };-- // Always-on node labels (opt-in via `showLabels`). Parallel to `opts.simNodes`- // and repositioned each frame in `draw()` so they track the simulation.- const labelColor = () => (dark ? 0xe2e8f0 : 0x334155);- const labelText = (n: SimNode): string => {- const s = (n.label ?? '').trim();- return s.length > 22 ? `${s.slice(0, 21)}…` : s;- };- let labels: Text[] = [];- const rebuildLabels = () => {- for (const label of labels) label.destroy();- labels = [];- labelG.removeChildren();- if (!opts.showLabels) return;- for (const n of opts.simNodes) {- const text = new Text({- text: labelText(n),- style: { fontFamily: 'sans-serif', fontSize: 13, fill: labelColor(), align: 'center' },- });- text.anchor.set(0.5, 0);- text.resolution = 2; // crisp when the world is scaled up- labelG.addChild(text);- labels.push(text);- }- };- rebuildLabels();-- const draw = () => {- edgeG.clear();- for (const l of opts.links) {- const s = l.source as SimNode;- const t = l.target as SimNode;- if (!s || !t || typeof s.x !== 'number' || typeof t.x !== 'number') continue;- edgeG.moveTo(s.x, s.y);- edgeG.lineTo(t.x, t.y);- }- edgeG.stroke({ width: 0.8, color: dark ? 0x475569 : 0xcbd5e1, alpha: 0.7 });-- nodeG.clear();- // Halos first so the structural levels "light up" beneath the discs.- for (const n of opts.simNodes) {- if (!nodeGlows(n)) continue;- nodeG- .circle(n.x, n.y, nodeRadius(n) + 5)- .fill({ color: colorNum(nodeColor(n)), alpha: 0.18 });- }- for (const n of opts.simNodes) {- const hover = n.id === hoveredId;- const r = nodeRadius(n) + (hover ? 2 : 0);- nodeG.circle(n.x, n.y, r).fill({ color: colorNum(nodeColor(n)), alpha: 1 });- if (hover) nodeG.circle(n.x, n.y, r).stroke({ width: 1.4, color: 0x0f172a, alpha: 0.9 });- }-- // Node labels follow the discs; recolour to the live theme.- if (opts.showLabels) {- const fill = labelColor();- for (let i = 0; i < labels.length; i++) {- const n = opts.simNodes[i];- const label = labels[i];- if (!n || !label) continue;- label.position.set(n.x, n.y + nodeRadius(n) + 3);- label.style.fill = fill;- }- }- };-- app.ticker.add(() => {- let changed = dirty;- if (sim.alpha() > sim.alphaMin()) {- sim.tick();- changed = true;- } else if (!readyFired) {- // Simulation has cooled → the layout has settled. Signal readiness once.- readyFired = true;- opts.onReady?.();- }- if (changed) {- // Keep the whole graph framed while it settles, until the user- // takes over the camera.- if (!userInteracted) fitToView();- draw();- dirty = false;- }- });-- // ── interaction ────────────────────────────────────────────────────- app.stage.eventMode = 'static';- app.stage.hitArea = app.screen;- let drag:- | { node: SimNode; moved: boolean }- | { panX: number; panY: number; px: number; py: number; moved: boolean }- | null = null;-- const setCursor = (c: string) => {- app.canvas.style.cursor = c;- };-- app.stage.on('pointerdown', (e: FederatedPointerEvent) => {- userInteracted = true; // hand the camera to the user- const p = world.toLocal(e.global);- const node = pickNode(opts.simNodes, p.x, p.y);- if (node) {- sim.alpha(0.3);- node.fx = node.x;- node.fy = node.y;- drag = { node, moved: false };- setCursor('grabbing');- } else {- drag = {- panX: world.position.x,- panY: world.position.y,- px: e.global.x,- py: e.global.y,- moved: false,- };- setCursor('grabbing');- }- });-- app.stage.on('pointermove', (e: FederatedPointerEvent) => {- if (drag) {- if ('node' in drag) {- const p = world.toLocal(e.global);- drag.node.fx = p.x;- drag.node.fy = p.y;- drag.moved = true;- if (sim.alpha() < 0.1) sim.alpha(0.1);- } else {- world.position.set(drag.panX + (e.global.x - drag.px), drag.panY + (e.global.y - drag.py));- drag.moved = true;- }- dirty = true;- return;- }- const p = world.toLocal(e.global);- const node = pickNode(opts.simNodes, p.x, p.y);- const id = node ? node.id : null;- setCursor(node ? 'pointer' : 'grab');- if (id !== hoveredId) {- hoveredId = id;- dirty = true;- opts.onHover(node ?? null);- }- });-- const endDrag = (open: boolean) => {- const d = drag;- if (d && 'node' in d) {- // Release the pin so physics resumes for that node.- d.node.fx = null;- d.node.fy = null;- if (open && !d.moved) opts.onOpen(d.node);- }- drag = null;- setCursor('grab');- };- app.stage.on('pointerup', () => endDrag(true));- app.stage.on('pointerupoutside', () => endDrag(false));-- const onWheel = (e: WheelEvent) => {- e.preventDefault();- userInteracted = true;- const gx = e.offsetX;- const gy = e.offsetY;- // Graph point under the cursor, kept fixed across the zoom.- const lx = (gx - world.position.x) / world.scale.x;- const ly = (gy - world.position.y) / world.scale.y;- const next = Math.min(- ZOOM_MAX,- Math.max(ZOOM_MIN, world.scale.x * Math.exp(-e.deltaY * 0.0015))- );- world.scale.set(next);- world.position.set(gx - lx * next, gy - ly * next);- dirty = true;- };- app.canvas.addEventListener('wheel', onWheel, { passive: false });-- app.renderer.on('resize', () => {- dirty = true;- });-- return {- resetView() {- userInteracted = false;- sim.alpha(0.3);- dirty = true;- },- setTheme(next: boolean) {- dark = next;- dirty = true;- },- updateGraph(nextNodes: SimNode[], nextLinks: SimLink[]) {- const oldById = new Map(opts.simNodes.map(n => [n.id, n]));-- for (const n of nextNodes) {- const old = oldById.get(n.id);- if (old) {- n.x = old.x;- n.y = old.y;- n.vx = old.vx ?? 0;- n.vy = old.vy ?? 0;- n.fx = old.fx ?? undefined;- n.fy = old.fy ?? undefined;- } else {- // New node — seed near its parent or at a small random offset- // from the centroid so it animates into place.- const parentLink = nextLinks.find(- l => (typeof l.source === 'string' ? l.source : (l.source as SimNode).id) === n.id- );- const parentId =- parentLink &&- (typeof parentLink.target === 'string'- ? parentLink.target- : (parentLink.target as SimNode).id);- const parent = parentId ? oldById.get(parentId) : undefined;- if (parent) {- n.x = parent.x + (Math.random() - 0.5) * 40;- n.y = parent.y + (Math.random() - 0.5) * 40;- } else {- n.x = (Math.random() - 0.5) * 100;- n.y = (Math.random() - 0.5) * 100;- }- }- }-- // Hot-swap the simulation's node and link arrays.- opts.simNodes = nextNodes;- opts.links = nextLinks;- rebuildLabels();- sim.nodes(nextNodes);- const linkForce = sim.force('link') as ReturnType<typeof import('d3-force').forceLink>;- if (linkForce && typeof linkForce.links === 'function') {- linkForce.links(nextLinks);- }- // Gentle reheat so new nodes settle without disrupting existing ones.- sim.alpha(0.3);- dirty = true;- },- destroy() {- sim.stop();- app.canvas.removeEventListener('wheel', onWheel);- app.destroy(true, { children: true });- },- };-}diff --git a/app/src/components/intelligence/seedSvgLayout.test.ts b/app/src/components/intelligence/seedSvgLayout.test.tsdeleted file mode 100644index 698130a75a..0000000000--- a/app/src/components/intelligence/seedSvgLayout.test.ts+++ /dev/null@@ -1,172 +0,0 @@-import { describe, expect, it } from 'vitest';--import { type GraphEdge, type GraphNode } from '../../utils/tauriCommands';-import { seedSvgLayout } from './seedSvgLayout';--const src = (id: string): GraphNode => ({ kind: 'source', id, label: id, parent_id: null });-const sum = (id: string, parent: string): GraphNode => ({- kind: 'summary',- id,- label: id,- level: 1,- parent_id: parent,-});-const chunk = (id: string, parent: string): GraphNode => ({- kind: 'chunk',- id,- label: id,- parent_id: parent,-});-const contact = (id: string): GraphNode => ({- kind: 'contact',- id,- label: id,- entity_kind: 'person',-});--const NO_PREV = new Map<string, { x: number; y: number }>();-const finite = (p: { x: number; y: number }) => Number.isFinite(p.x) && Number.isFinite(p.y);--describe('seedSvgLayout — first load (no previous positions)', () => {- it('marks every node new, reheats fully, and produces finite positions', () => {- const nodes = [src('s'), sum('a', 's'), chunk('c1', 'a'), chunk('c2', 'a')];- const r = seedSvgLayout(nodes, [], 'tree', NO_PREV);- expect(r.positions).toHaveLength(4);- expect(r.positions.every(p => p.isNew)).toBe(true);- expect(r.newCount).toBe(4);- expect(r.reheatAlpha).toBe(1);- expect(r.positions.every(finite)).toBe(true);- });-- it('handles an empty graph', () => {- const r = seedSvgLayout([], [], 'tree', NO_PREV);- expect(r.positions).toEqual([]);- expect(r.edges).toEqual([]);- expect(r.newCount).toBe(0);- expect(r.reheatAlpha).toBe(1);- });-});--describe('seedSvgLayout — carry-over', () => {- it('preserves the exact previous position of surviving nodes', () => {- const nodes = [src('s'), sum('a', 's')];- const prev = new Map([- ['s', { x: 100, y: 120 }],- ['a', { x: 300, y: 340 }],- ]);- const r = seedSvgLayout(nodes, [], 'tree', prev);- expect(r.positions[0]).toEqual({ x: 100, y: 120, isNew: false });- expect(r.positions[1]).toEqual({ x: 300, y: 340, isNew: false });- expect(r.newCount).toBe(0);- expect(r.reheatAlpha).toBe(0.3); // all survived → gentle reheat- });-- it('drops removed nodes — result length tracks the current node set', () => {- const nodes = [src('s')];- const prev = new Map([- ['s', { x: 10, y: 10 }],- ['gone-1', { x: 1, y: 1 }],- ['gone-2', { x: 2, y: 2 }],- ]);- const r = seedSvgLayout(nodes, [], 'tree', prev);- expect(r.positions).toHaveLength(1);- expect(r.positions[0]).toEqual({ x: 10, y: 10, isNew: false });- });-});--describe('seedSvgLayout — new nodes', () => {- it('seeds a new child near its parent’s previous position', () => {- const nodes = [sum('a', 's'), chunk('c', 'a')];- const prev = new Map([['a', { x: 500, y: 250 }]]); // parent survived, child is new- const r = seedSvgLayout(nodes, [], 'tree', prev);- const childPos = r.positions[1];- expect(childPos.isNew).toBe(true);- const dist = Math.hypot(childPos.x - 500, childPos.y - 250);- expect(dist).toBeGreaterThan(0);- expect(dist).toBeLessThanOrEqual(25); // within the small offset of the parent- });-- it('falls back to the ring-3 when a new node’s parent is also new (not in prev)', () => {- const nodes = [sum('a', 's'), chunk('c', 'a')]; // neither in prev- const r = seedSvgLayout(nodes, [], 'tree', NO_PREV);- expect(r.positions[1].isNew).toBe(true);- expect(finite(r.positions[1])).toBe(true);- // not clustered at the parent (parent has no known position)- expect(r.positions[1]).not.toEqual(r.positions[0]);- });-- it('falls back to the ring-3 for a parent-less new node', () => {- const nodes = [src('s')];- const r = seedSvgLayout(nodes, [], 'tree', NO_PREV);- expect(r.positions[0].isNew).toBe(true);- expect(finite(r.positions[0])).toBe(true);- });-- it('reheats fully when the graph is entirely replaced (no survivors)', () => {- const nodes = [src('x'), sum('y', 'x')];- const prev = new Map([['old', { x: 1, y: 2 }]]); // stale ids, none match- const r = seedSvgLayout(nodes, [], 'tree', prev);- expect(r.newCount).toBe(2);- expect(r.reheatAlpha).toBe(1);- });-- it('reheats gently when at least one node survives a mixed update', () => {- const nodes = [sum('a', 's'), chunk('c1', 'a'), chunk('c2', 'a')];- const prev = new Map([['a', { x: 400, y: 300 }]]); // a survives, c1/c2 new- const r = seedSvgLayout(nodes, [], 'tree', prev);- expect(r.newCount).toBe(2);- expect(r.positions[0].isNew).toBe(false);- expect(r.reheatAlpha).toBe(0.3);- });-});--describe('seedSvgLayout — edges', () => {- it('derives tree edges from parent_id', () => {- const nodes = [src('s'), sum('a', 's'), chunk('c', 'a')];- const r = seedSvgLayout(nodes, [], 'tree', NO_PREV);- // [child, parent] index pairs: a→s (1,0), c→a (2,1)- expect(r.edges).toEqual([- [1, 0],- [2, 1],- ]);- });-- it('skips tree edges whose parent_id is missing from the node set', () => {- const nodes = [sum('a', 'ghost-parent'), chunk('c', 'a')];- const r = seedSvgLayout(nodes, [], 'tree', NO_PREV);- expect(r.edges).toEqual([[1, 0]]); // a→ghost dropped; c→a kept- expect(r.edges.every(([x, y]) => x < nodes.length && y < nodes.length)).toBe(true);- });-- it('uses explicit edges in contacts mode and skips dangling endpoints', () => {- const nodes = [chunk('c', 'whatever'), contact('p')];- const edges: GraphEdge[] = [- { from: 'c', to: 'p' },- { from: 'c', to: 'missing' }, // dangling → skipped- ];- const r = seedSvgLayout(nodes, edges, 'contacts', NO_PREV);- expect(r.edges).toEqual([[0, 1]]);- expect(r.edges.every(([x, y]) => x < nodes.length && y < nodes.length)).toBe(true);- });-- it('seeds new contact-mode nodes on the ring (no parent_id seeding)', () => {- const nodes = [chunk('c', 'x'), contact('p')];- const r = seedSvgLayout(nodes, [{ from: 'c', to: 'p' }], 'contacts', NO_PREV);- expect(r.positions.every(p => p.isNew && finite(p))).toBe(true);- });-});--describe('seedSvgLayout — invariants', () => {- it('is deterministic for identical inputs', () => {- const nodes = [src('s'), sum('a', 's'), chunk('c1', 'a'), chunk('c2', 'a')];- const a = seedSvgLayout(nodes, [], 'tree', NO_PREV);- const b = seedSvgLayout(nodes, [], 'tree', NO_PREV);- expect(a).toEqual(b);- });-- it('keeps positions index-aligned with the node array', () => {- const nodes = [src('s'), sum('a', 's'), chunk('c', 'a')];- const r = seedSvgLayout(nodes, [], 'tree', new Map([['a', { x: 9, y: 9 }]]));- expect(r.positions).toHaveLength(nodes.length);- });-});diff --git a/app/src/components/intelligence/seedSvgLayout.ts b/app/src/components/intelligence/seedSvgLayout.tsdeleted file mode 100644index 46bf0a3b79..0000000000--- a/app/src/components/intelligence/seedSvgLayout.ts+++ /dev/null@@ -1,103 +0,0 @@-/**- * Position seeding for the SVG force layout, with incremental carry-over.- *- * When the graph data changes (a background sync completes, a rebuild, a mode- * toggle) the component re-derives its node array. Re-seeding every node from- * scratch makes the whole graph reshuffle and re-settle — jarring on a live- * update. Instead this:- * - keeps each surviving node (same `id`) at its previous position,- * - seeds a genuinely-new node near its parent's previous position (tree- * mode) so it eases in next to where it belongs, falling back to a- * deterministic ring around the viewport centre,- * - reports a `reheatAlpha`: a gentle 0.3 when anything carried over (so the- * sim nudges rather than explodes), or a full 1 for a first / fully-new- * graph.- *- * Pure and deterministic (no RNG / clock) so it is straightforward to test.- */-import { type GraphEdge, type GraphMode, type GraphNode } from '../../utils/tauriCommands';-import { VIEWPORT_H, VIEWPORT_W } from './memoryGraphLayout';--interface SeededPosition {- x: number;- y: number;- /** True when the node had no carried-over position (newly arrived). */- isNew: boolean;-}--interface SeedResult {- /** Index-aligned with the input `nodes`. */- positions: SeededPosition[];- /** Edge index pairs [childIdx, parentIdx] (tree) or [fromIdx, toIdx] (contacts). */- edges: Array<[number, number]>;- /** How many nodes had no previous position. */- newCount: number;- /** Initial simulation alpha: gentle (0.3) on an incremental update, full (1) otherwise. */- reheatAlpha: number;-}--const CX = VIEWPORT_W / 2;-const CY = VIEWPORT_H / 2;-const NEW_NODE_OFFSET = 24;--/** Deterministic ring position around the viewport centre for index `i`. */-function ringPosition(i: number, total: number): { x: number; y: number } {- const angle = (i / Math.max(1, total)) * Math.PI * 2;- const r = 200 + (i % 7) * 12;- return { x: CX + Math.cos(angle) * r, y: CY + Math.sin(angle) * r };-}--export function seedSvgLayout(- nodes: GraphNode[],- edges: GraphEdge[],- mode: GraphMode,- prev: ReadonlyMap<string, { x: number; y: number }>-): SeedResult {- const idIndex = new Map<string, number>();- nodes.forEach((n, i) => idIndex.set(n.id, i));-- const positions: SeededPosition[] = nodes.map((n, i) => {- const carried = prev.get(n.id);- if (carried) return { x: carried.x, y: carried.y, isNew: false };-- // New node — seed near its parent's previous position if we know it.- if (mode === 'tree' && n.parent_id) {- const parent = prev.get(n.parent_id);- if (parent) {- const a = (i % 12) * (Math.PI / 6);- return {- x: parent.x + Math.cos(a) * NEW_NODE_OFFSET,- y: parent.y + Math.sin(a) * NEW_NODE_OFFSET,- isNew: true,- };- }- }- const ring = ringPosition(i, nodes.length);- return { x: ring.x, y: ring.y, isNew: true };- });-- const edgeIndices: Array<[number, number]> = [];- if (mode === 'tree') {- for (const n of nodes) {- if (!n.parent_id) continue;- const child = idIndex.get(n.id);- const parent = idIndex.get(n.parent_id);- if (child == null || parent == null) continue;- edgeIndices.push([child, parent]);- }- } else {- for (const e of edges) {- const a = idIndex.get(e.from);- const b = idIndex.get(e.to);- if (a == null || b == null) continue;- edgeIndices.push([a, b]);- }- }-- const newCount = positions.reduce((acc, p) => acc + (p.isNew ? 1 : 0), 0);- // Gentle reheat only when at least one node survived (an incremental update);- // a first load or a fully-replaced graph gets a full settle.- const reheatAlpha = nodes.length > 0 && newCount < nodes.length ? 0.3 : 1;-- return { positions, edges: edgeIndices, newCount, reheatAlpha };-}diff --git a/app/src/components/intelligence/sourcePipelineStatus.test.ts b/app/src/components/intelligence/sourcePipelineStatus.test.tsdeleted file mode 100644index d20ff6a195..0000000000--- a/app/src/components/intelligence/sourcePipelineStatus.test.ts+++ /dev/null@@ -1,370 +0,0 @@-/**- * Unit tests for the layered Data Sync pipeline-health derivation (GH-4690).- * Covers each warning layer plus the healthy no-regression case.- */-import { describe, expect, it } from 'vitest';--import type { SourceStatus } from '../../services/memorySourcesService';-import type {- BackfillStatus,- MemoryTreePipelineStatus,-} from '../../utils/tauriCommands/memoryTree';-import {- deriveSourcePipelineHealth,- pipelineIssueMessageKey,- type SourcePipelineIssueKind,-} from './sourcePipelineStatus';--function makeStatus(overrides: Partial<SourceStatus> = {}): SourceStatus {- return {- source_id: 'src_1',- chunks_synced: 5,- chunks_pending: 0,- last_chunk_at_ms: 1_000,- freshness: 'recent',- ...overrides,- };-}--function makePipeline(overrides: Partial<MemoryTreePipelineStatus> = {}): MemoryTreePipelineStatus {- return {- status: 'running',- reason: null,- last_sync_ms: 1_000,- total_chunks: 5,- wiki_size_bytes: 0,- pipeline_jobs: { ready: 0, running: 0, failed: 0 },- is_syncing: false,- is_paused: false,- ...overrides,- };-}--/** The global embed-backfill snapshot (`memory_tree_memory_backfill_status`). */-function makeBackfill(overrides: Partial<BackfillStatus> = {}): BackfillStatus {- return { in_progress: false, pending_jobs: 0, ...overrides };-}--describe('deriveSourcePipelineHealth', () => {- it('returns none when nothing has been ingested yet', () => {- const h = deriveSourcePipelineHealth(makeStatus({ chunks_synced: 0 }), makePipeline());- expect(h.state).toBe('none');- expect(h.issues).toEqual([]);- });-- it('returns none when status is null (pre-load)', () => {- const h = deriveSourcePipelineHealth(null, makePipeline());- expect(h.state).toBe('none');- });-- // -- No regression: fully healthy sync stays clean -------------------------- it('reports retrieval_ready when everything is healthy', () => {- const h = deriveSourcePipelineHealth(- makeStatus({ chunks_synced: 5, chunks_pending: 0 }),- makePipeline({ status: 'running' })- );- expect(h.state).toBe('retrieval_ready');- expect(h.issues).toEqual([]);- expect(h.authRelated).toBe(false);- });-- it('stays retrieval_ready when the pipeline snapshot is missing but chunks are embedded', () => {- const h = deriveSourcePipelineHealth(makeStatus({ chunks_pending: 0 }), null);- expect(h.state).toBe('retrieval_ready');- expect(h.issues).toEqual([]);- });-- // -- Layer 1: embeddings ---------------------------------------------------- it('flags stored_without_vectors from per-source pending chunks alone', () => {- // The exact issue repro: "1 chunk / 1 pending" with no pipeline snapshot,- // and nothing draining it: no backfill snapshot, newest chunk long idle.- const h = deriveSourcePipelineHealth(- makeStatus({ chunks_synced: 1, chunks_pending: 1, freshness: 'idle' }),- null- );- expect(h.state).toBe('ingested_only');- expect(h.issues).toContain('stored_without_vectors');- });-- it('flags stored_without_vectors from the global semantic_recall latch', () => {- const h = deriveSourcePipelineHealth(- makeStatus({ chunks_pending: 0 }),- makePipeline({ status: 'degraded', degraded: { semantic_recall: true, structure: false } })- );- expect(h.issues).toContain('stored_without_vectors');- // A recall-degraded state must NOT also add the generic tree_degraded noise.- expect(h.issues).not.toContain('tree_degraded');- });-- it('marks authRelated when the blocking cause is a missing backend session', () => {- const h = deriveSourcePipelineHealth(- makeStatus({ chunks_pending: 3 }),- makePipeline({- status: 'error',- first_blocking_cause: {- code: 'auth_missing',- class: 'unrecoverable',- remediation_key: 'memory.health.remediation.auth_missing',- },- })- );- expect(h.issues).toContain('stored_without_vectors');- expect(h.authRelated).toBe(true);- });-- it('does not mark authRelated for a non-auth embeddings cause', () => {- const h = deriveSourcePipelineHealth(- makeStatus({ chunks_pending: 3 }),- makePipeline({- status: 'error',- first_blocking_cause: {- code: 'embeddings_unconfigured',- class: 'unrecoverable',- remediation_key: 'memory.health.remediation.embeddings_unconfigured',- },- })- );- expect(h.authRelated).toBe(false);- });-- // -- Layer 2: extraction ---------------------------------------------------- it('flags extraction_failed from an extraction_timeout blocking cause', () => {- const h = deriveSourcePipelineHealth(- makeStatus({ chunks_pending: 0 }),- makePipeline({- status: 'degraded',- first_blocking_cause: {- code: 'extraction_timeout',- class: 'transient',- remediation_key: 'memory.health.remediation.extraction_timeout',- },- })- );- expect(h.state).toBe('ingested_only');- expect(h.issues).toContain('extraction_failed');- });-- it('flags extraction_failed from the structure degraded flag', () => {- const h = deriveSourcePipelineHealth(- makeStatus({ chunks_pending: 0 }),- makePipeline({ status: 'degraded', degraded: { semantic_recall: false, structure: true } })- );- expect(h.issues).toContain('extraction_failed');- });-- // -- Layer 3: memory tree --------------------------------------------------- it('flags tree_degraded for a generic degraded status with no specific layer', () => {- const h = deriveSourcePipelineHealth(- makeStatus({ chunks_pending: 0 }),- makePipeline({ status: 'degraded' })- );- expect(h.state).toBe('ingested_only');- expect(h.issues).toEqual(['tree_degraded']);- });-- it('flags tree_degraded for an error status too', () => {- const h = deriveSourcePipelineHealth(- makeStatus({ chunks_pending: 0 }),- makePipeline({ status: 'error' })- );- expect(h.issues).toContain('tree_degraded');- });-- // -- Multiple layers at once (the full-failure scenario) -------------------- it('surfaces every failed layer together, embeddings first', () => {- const h = deriveSourcePipelineHealth(- makeStatus({ chunks_synced: 1, chunks_pending: 1 }),- makePipeline({ status: 'degraded', degraded: { semantic_recall: true, structure: true } })- );- expect(h.state).toBe('ingested_only');- // Embeddings + extraction; the generic tree layer is suppressed because- // more specific layers already explain the degradation.- expect(h.issues).toEqual(['stored_without_vectors', 'extraction_failed']);- });-});--// -- Layer 1, the soft half: a backlog that is being drained (openhuman#6025)-describe('deriveSourcePipelineHealth — vectors pending vs stored without vectors', () => {- it('reads pending chunks as vectors_pending while a re-embed chain has rows to process', () => {- // The incident's numbers: 676 synced, 322 waiting, the backfill row queued- // behind extraction. Nothing failed; the row must not say it did.- const h = deriveSourcePipelineHealth(- makeStatus({ chunks_synced: 676, chunks_pending: 322, freshness: 'idle' }),- makePipeline(),- makeBackfill({ in_progress: true, pending_jobs: 1 })- );- expect(h.state).toBe('vectors_pending');- expect(h.vectorsPending).toBe(true);- expect(h.issues).toEqual([]);- expect(h.authRelated).toBe(false);- });-- it('reads pending chunks as vectors_pending while the newest chunk is active, with no backfill snapshot', () => {- // The backfill RPC failed (or predates this build): the source's own- // freshness carries the "still moving" judgement on its own.- const h = deriveSourcePipelineHealth(- makeStatus({ chunks_synced: 10, chunks_pending: 4, freshness: 'active' }),- null- );- expect(h.state).toBe('vectors_pending');- });-- it('reads pending chunks as vectors_pending while the newest chunk is recent, with no backfill snapshot', () => {- const h = deriveSourcePipelineHealth(- makeStatus({ chunks_synced: 10, chunks_pending: 4, freshness: 'recent' }),- null,- null- );- expect(h.state).toBe('vectors_pending');- });-- it('lets an explicit "no chain queued" snapshot outrank a fresh chunk', () => {- // `last_chunk_at_ms` is the content's own time (an email's sent date,- // a file's mtime), not proof that a worker is alive; a future-dated item- // reads `active` forever. When the engine says no chain is queued, the- // backlog is stuck whatever the freshness pill shows.- const h = deriveSourcePipelineHealth(- makeStatus({ chunks_synced: 10, chunks_pending: 4, freshness: 'active' }),- makePipeline(),- makeBackfill({ in_progress: false })- );- expect(h.state).toBe('ingested_only');- expect(h.issues).toEqual(['stored_without_vectors']);- expect(h.vectorsPending).toBe(false);- });-- it('flags stored_without_vectors once the backlog is idle with no chain queued', () => {- const h = deriveSourcePipelineHealth(- makeStatus({ chunks_synced: 10, chunks_pending: 4, freshness: 'idle' }),- makePipeline(),- makeBackfill({ in_progress: false })- );- expect(h.state).toBe('ingested_only');- expect(h.issues).toEqual(['stored_without_vectors']);- expect(h.vectorsPending).toBe(false);- });-- it('lets the global recall latch win over a draining backfill', () => {- const h = deriveSourcePipelineHealth(- makeStatus({ chunks_pending: 4, freshness: 'active' }),- makePipeline({ status: 'degraded', degraded: { semantic_recall: true, structure: false } }),- makeBackfill({ in_progress: true })- );- expect(h.state).toBe('ingested_only');- expect(h.issues).toContain('stored_without_vectors');- expect(h.vectorsPending).toBe(false);- });-- it.each([- 'budget_exhausted',- 'auth_missing',- 'auth_invalid',- 'embeddings_unconfigured',- 'embedding_dim_mismatch',- 'local_model_unavailable',- ] as const)(- 'lets an embeddings-family blocking cause (%s) win over a draining backfill',- code => {- // The provider cannot write vectors, so the backlog is not going to drain- // whatever the chain flag says; that is the hard state, sign-in CTA and all.- const h = deriveSourcePipelineHealth(- makeStatus({ chunks_pending: 4, freshness: 'active' }),- makePipeline({- status: 'error',- first_blocking_cause: {- code,- class: 'unrecoverable',- remediation_key: `memory.health.remediation.${code}`,- },- }),- makeBackfill({ in_progress: true })- );- expect(h.issues).toContain('stored_without_vectors');- expect(h.vectorsPending).toBe(false);- expect(h.authRelated).toBe(code === 'auth_missing');- }- );-- it('keeps a non-embeddings blocking cause from turning a draining backlog amber', () => {- // Extraction timing out says nothing about the embedder; the vectors are- // still coming. Both truths are carried: the extraction warning AND the- // neutral pending note.- const h = deriveSourcePipelineHealth(- makeStatus({ chunks_pending: 4, freshness: 'active' }),- makePipeline({- status: 'degraded',- first_blocking_cause: {- code: 'extraction_timeout',- class: 'transient',- remediation_key: 'memory.health.remediation.extraction_timeout',- },- })- );- expect(h.state).toBe('ingested_only');- expect(h.issues).toEqual(['extraction_failed']);- expect(h.vectorsPending).toBe(true);- });-- it.each([- { label: 'is_paused', pipeline: makePipeline({ is_paused: true }) },- { label: "status 'paused'", pipeline: makePipeline({ status: 'paused', reason: 'gate off' }) },- {- label: 'gate_paused (live policy, mode still auto)',- pipeline: makePipeline({ gate_paused: true, gate_pause_reason: 'on_battery' }),- },- ])(- 'reads a paused scheduler ($label) as stuck even while a chain is armed and ingest is fresh',- ({ pipeline }) => {- // Pausing the memory-tree scheduler stops every LLM-bound job, the embed- // chain included, while leaving its `in_progress` flag armed and letting- // ingest keep writing. Nothing will drain the backlog until the user- // resumes, so "shortly" would be a promise nobody is keeping.- const h = deriveSourcePipelineHealth(- makeStatus({ chunks_synced: 10, chunks_pending: 4, freshness: 'active' }),- pipeline,- makeBackfill({ in_progress: true, pending_jobs: 1 })- );- expect(h.state).toBe('ingested_only');- expect(h.issues).toEqual(['stored_without_vectors']);- expect(h.vectorsPending).toBe(false);- }- );-- it('reads a stalled queue as stuck even while the backfill snapshot says in progress', () => {- // The #5324 verdict: eligible work waiting six hours with nothing- // settling. A stalled `reembed_backfill` row still keeps `in_progress`- // up, but the core has ruled that nothing is draining, so the row must- // not promise "shortly" beside a degraded status.- const h = deriveSourcePipelineHealth(- makeStatus({ chunks_synced: 10, chunks_pending: 4, freshness: 'active' }),- makePipeline({ status: 'degraded', reason: 'queue stalled for 7h', queue_stalled: true }),- makeBackfill({ in_progress: true, pending_jobs: 1 })- );- expect(h.state).toBe('ingested_only');- expect(h.issues).toEqual(['stored_without_vectors']);- expect(h.vectorsPending).toBe(false);- });-- it('stays retrieval_ready when a backfill runs but this source has nothing pending', () => {- const h = deriveSourcePipelineHealth(- makeStatus({ chunks_pending: 0 }),- makePipeline(),- makeBackfill({ in_progress: true, pending_jobs: 1 })- );- expect(h.state).toBe('retrieval_ready');- expect(h.vectorsPending).toBe(false);- });-});--describe('pipelineIssueMessageKey', () => {- it('maps every issue kind to a stable i18n key', () => {- const kinds: SourcePipelineIssueKind[] = [- 'stored_without_vectors',- 'extraction_failed',- 'tree_degraded',- ];- for (const k of kinds) {- expect(pipelineIssueMessageKey(k)).toMatch(/^sync\.pipeline\./);- }- });-});diff --git a/app/src/components/intelligence/sourcePipelineStatus.ts b/app/src/components/intelligence/sourcePipelineStatus.tsdeleted file mode 100644index 35e864440b..0000000000--- a/app/src/components/intelligence/sourcePipelineStatus.ts+++ /dev/null@@ -1,212 +0,0 @@-/**- * Layered pipeline-health derivation for Data Sync source rows (GH-4690).- *- * Raw sync ≠ retrieval-ready. A source can be "synced" (its documents were- * ingested into `mem_tree_chunks`) while the downstream retrieval pipeline- * silently failed underneath it: embeddings were never created, spaCy/LLM- * extraction failed, or the memory tree is degraded. Before this, Data Sync- * showed a clean freshness badge in all those cases and the user only learned- * the truth in Brain > Memory > Sync or the raw logs.- *- * This module folds three signals the core already exposes into one per-row- * verdict so the row can honestly say "Ingested only" instead of "synced":- *- * 1. **Per-source, precise** — `SourceStatus.chunks_pending` is the SQL count- * of this source's chunks with no vector at the active embedding signature- * (see `memory_sources/status.rs`). `> 0` means semantic search cannot- * reach those chunks *yet*.- * 2. **Global pipeline health** — `memory_tree_pipeline_status` (the same RPC- * that drives the Brain > Memory > Sync "Degraded" panel) carries the- * process-wide `degraded` snapshot + `first_blocking_cause`. Embedding /- * extraction / tree-degraded causes there are attributed to the whole- * pipeline, so we surface them on rows that actually contributed chunks.- * 3. **Embed work in flight** — `memory_tree_memory_backfill_status` says- * whether a re-embed chain still has rows to process. Since tinymemory- * 1.14 chunks get their vectors from that chain, not inline at ingest, so- * every sizeable sync leaves a backlog for a few minutes- * (openhuman#6025). A backlog that is being drained is *pending*, not- * *failed*: the row shows a neutral note and keeps its freshness pill. The- * amber warning is reserved for a backlog nothing will drain: the global- * recall latch, an embeddings-family blocking cause, a paused scheduler- * gate, or pending chunks with no chain queued. The source's freshness- * stands in only when that snapshot is unavailable.- *- * The function is pure so it can be unit-tested exhaustively without a DOM.- */-import type { SourceStatus } from '../../services/memorySourcesService';-import type {- BackfillStatus,- MemoryTreePipelineStatus,-} from '../../utils/tauriCommands/memoryTree';--/** One failed layer of the post-ingest pipeline, in severity-display order. */-export type SourcePipelineIssueKind =- | 'stored_without_vectors'- | 'extraction_failed'- | 'tree_degraded';--/** Coarse retrieval-readiness state for a single source row. */-export type SourcePipelineState = 'none' | 'retrieval_ready' | 'vectors_pending' | 'ingested_only';--export interface SourcePipelineHealth {- /**- * `none` — nothing ingested yet (no badge changes; row renders as before).- * `retrieval_ready` — chunks synced AND no downstream failure (clean state).- * `vectors_pending` — chunks synced, some still waiting for an embed- * backfill that is provably working on them (neutral note, no warning).- * `ingested_only` — chunks synced but ≥1 downstream layer failed (warn).- */- state: SourcePipelineState;- /** The failed layers, deduped, in display order. Empty unless `ingested_only`. */- issues: SourcePipelineIssueKind[];- /**- * True when the embeddings failure is attributable to a missing backend- * session / auth (the "No backend session for cloud embeddings" case). Drives- * the "Sign in to enable" affordance — only meaningful with- * `stored_without_vectors`.- */- authRelated: boolean;- /**- * True when this source has chunks waiting for vectors AND the backlog is- * being drained (the soft state). Carried separately from `state` so the- * row can still show the neutral note beside another layer's warning.- */- vectorsPending: boolean;-}--/**- * Blocking causes that mean the embeddings provider itself cannot write- * vectors, so a pending backlog is not going to drain on its own. Anything- * else (`transient`, `extraction_timeout`, …) leaves the backfill able to- * finish, and the row must not read the backlog as a failure.- */-const EMBEDDINGS_BLOCKING_CAUSES: ReadonlySet<string> = new Set([- 'budget_exhausted',- 'auth_missing',- 'auth_invalid',- 'embeddings_unconfigured',- 'embedding_dim_mismatch',- 'local_model_unavailable',-]);--/**- * Compute the layered pipeline verdict for one source row.- *- * `status` is this source's `memory_sources_status_list` entry; `pipeline` is- * the global `memory_tree_pipeline_status` snapshot (may be `null` when that- * RPC hasn't resolved / failed — the per-source signal still stands on its- * own); `backfill` is the global `memory_tree_memory_backfill_status` snapshot- * (`null` when unavailable — the row then falls back to the source's own- * freshness to decide whether a backlog is still moving).- */-export function deriveSourcePipelineHealth(- status: SourceStatus | null,- pipeline: MemoryTreePipelineStatus | null,- backfill: BackfillStatus | null = null-): SourcePipelineHealth {- const synced = status?.chunks_synced ?? 0;-- // Nothing ingested yet → don't invent a warning. The row keeps its existing- // (empty / mid-sync) rendering.- if (synced <= 0) {- return { state: 'none', issues: [], authRelated: false, vectorsPending: false };- }-- const degraded = pipeline?.degraded;- const causeCode = pipeline?.first_blocking_cause?.code ?? degraded?.cause?.code ?? null;-- const issues: SourcePipelineIssueKind[] = [];-- // Layer 1 — embeddings. `chunks_pending` alone is ambiguous: right after a- // sync it is the backfill's to-do list, minutes later with nothing queued- // it is a hole in recall. Three signals settle which (openhuman#6025):- //- // - the global "semantic recall degraded" latch (no usable provider): hard;- // - an embeddings-family blocking cause: the provider cannot write vectors,- // so the backlog will not drain: hard;- // - a paused scheduler: the configured `off` mode (`is_paused` /- // `status === 'paused'`) or the gate's live policy (`gate_paused`: on- // battery, CPU pressure, signed out). The chain may be armed and ingest- // may still be writing, but no worker will embed anything until the gate- // lifts, so "shortly" would be a promise nobody is keeping. Pending- // chunks are hard until then;- // - a stalled queue (`queue_stalled`: eligible work waiting six hours with- // nothing settling, the #5324 verdict): a stalled `reembed_backfill` row- // still keeps the snapshot `in_progress`, but the core has ruled that- // nothing is draining. Hard;- // - otherwise the engine's own word decides: pending chunks are soft while- // `backfill.in_progress` reports a re-embed chain with rows to process,- // and hard when that snapshot says no chain is queued. Only when the- // snapshot is unavailable (RPC failed, older core) does the source's- // freshness stand in: a chunk inside the core's `recent` window (≤ 5 min)- // suggests ingest is still writing and the chain arms on the next extract- // admit. A fallback, not evidence of a worker — `last_chunk_at_ms` is the- // content's own time (an email's sent date), which is why it never- // outranks an explicit "no chain queued".- //- // `backfill.in_progress` is process-wide on purpose, not a per-source- // signal to be narrowed: the chain it reports is signature-wide — each- // batch takes any chunk lacking a vector at the active signature, whoever- // ingested it — so a running chain is draining THIS source's backlog too.- // (A chunk the chain skipped for good is tombstoned and no longer counts as- // pending, so it cannot hide behind the flag.)- const pending = status?.chunks_pending ?? 0;- const recallLatched = degraded?.semantic_recall === true;- const embeddingsBlocked = causeCode !== null && EMBEDDINGS_BLOCKING_CAUSES.has(causeCode);- const paused =- pipeline?.is_paused === true || pipeline?.status === 'paused' || pipeline?.gate_paused === true;- const stalled = pipeline?.queue_stalled === true;- const draining =- !paused &&- !stalled &&- (backfill- ? backfill.in_progress === true- : status?.freshness === 'active' || status?.freshness === 'recent');- const storedWithoutVectors = recallLatched || (pending > 0 && (embeddingsBlocked || !draining));- if (storedWithoutVectors) {- issues.push('stored_without_vectors');- }- const vectorsPending = !storedWithoutVectors && pending > 0;-- // Layer 2 — extraction. `degraded.structure` exists but has no production- // producer today (test-only), so the live signal is the typed- // `extraction_timeout` blocking cause ("the memory extraction model is- // timing out"). Honour both.- const extractionFailed = degraded?.structure === true || causeCode === 'extraction_timeout';- if (extractionFailed) {- issues.push('extraction_failed');- }-- // Layer 3 — memory tree. A global degraded/error status that isn't already- // explained by a more specific layer above (e.g. storage-degraded, a failed- // job). Retrieval for every synced source may return stale results.- const treeDegraded =- (pipeline?.status === 'degraded' || pipeline?.status === 'error') &&- !storedWithoutVectors &&- !extractionFailed;- if (treeDegraded) {- issues.push('tree_degraded');- }-- const authRelated = storedWithoutVectors && causeCode === 'auth_missing';-- const state: SourcePipelineState =- issues.length > 0 ? 'ingested_only' : vectorsPending ? 'vectors_pending' : 'retrieval_ready';-- return { state, issues, authRelated, vectorsPending };-}--/** i18n key for a given issue's row warning message. */-export function pipelineIssueMessageKey(kind: SourcePipelineIssueKind): string {- switch (kind) {- case 'stored_without_vectors':- return 'sync.pipeline.storedWithoutVectors';- case 'extraction_failed':- return 'sync.pipeline.extractionFailed';- case 'tree_degraded':- return 'sync.pipeline.treeDegraded';- }-}--/** i18n key for the neutral "waiting for vectors" note (`{count}` placeholder). */-export const VECTORS_PENDING_MESSAGE_KEY = 'sync.pipeline.vectorsPending';diff --git a/app/src/components/intelligence/svgForceLayout.worker.test.ts b/app/src/components/intelligence/svgForceLayout.worker.test.tsdeleted file mode 100644index 8c26b1ee1a..0000000000--- a/app/src/components/intelligence/svgForceLayout.worker.test.ts+++ /dev/null@@ -1,90 +0,0 @@-/**- * Drives the worker module directly with a stubbed `self`, since a real- * Worker context can't run under the test env. Verifies it streams tick frames,- * cools to an end, pins on drag, and halts on stop.- */-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--interface FakeSelf {- onmessage: ((e: { data: unknown }) => void) | null;- postMessage: ReturnType<typeof vi.fn>;-}--let workerSelf: FakeSelf;--async function loadWorker() {- workerSelf = { onmessage: null, postMessage: vi.fn() };- vi.stubGlobal('self', workerSelf);- vi.resetModules();- await import('./svgForceLayout.worker');-}--function send(msg: unknown) {- workerSelf.onmessage?.({ data: msg });-}--function initMsg(n: number) {- return {- type: 'init',- nodes: Array.from({ length: n }, (_, i) => ({ x: i * 10, y: i * 10, r: 6 })),- links: n > 1 ? [{ source: 1, target: 0 }] : [],- cx: 550,- cy: 320,- alpha: 1,- };-}--const ticks = () => workerSelf.postMessage.mock.calls.filter(c => c[0]?.type === 'tick');-const ended = () => workerSelf.postMessage.mock.calls.some(c => c[0]?.type === 'end');--describe('svgForceLayout.worker', () => {- beforeEach(async () => {- vi.useFakeTimers();- await loadWorker();- });- afterEach(() => {- vi.useRealTimers();- vi.unstubAllGlobals();- });-- it('streams a tick frame with a transferable positions buffer on init', () => {- send(initMsg(3));- const tick = ticks()[0];- expect(tick).toBeTruthy();- expect(tick[0].positions).toBeInstanceOf(Float32Array);- expect(tick[0].positions.length).toBe(6); // 3 nodes × (x,y)- expect(Array.isArray(tick[1])).toBe(true); // transfer list- });-- it('cools to an end message and then stops ticking', () => {- send(initMsg(2));- vi.advanceTimersByTime(20000); // run the tick loop down to alphaMin- expect(ended()).toBe(true);- const afterEnd = workerSelf.postMessage.mock.calls.length;- vi.advanceTimersByTime(5000);- expect(workerSelf.postMessage.mock.calls.length).toBe(afterEnd); // no more ticks- });-- it('halts the loop on stop (no further frames)', () => {- send(initMsg(2));- send({ type: 'stop' });- const before = workerSelf.postMessage.mock.calls.length;- vi.advanceTimersByTime(5000);- expect(workerSelf.postMessage.mock.calls.length).toBe(before);- });-- it('pins/unpins a node on drag and resumes ticking after it settles', () => {- send(initMsg(2));- vi.advanceTimersByTime(20000); // settle (loop idle)- const before = workerSelf.postMessage.mock.calls.length;- send({ type: 'drag', index: 0, x: 100, y: 100, fixed: true });- vi.advanceTimersByTime(64); // a few frames- expect(workerSelf.postMessage.mock.calls.length).toBeGreaterThan(before);- send({ type: 'drag', index: 0, x: 0, y: 0, fixed: false }); // unpin — no throw- });-- it('ignores a drag for an out-of-range index without throwing', () => {- send(initMsg(2));- expect(() => send({ type: 'drag', index: 99, x: 0, y: 0, fixed: true })).not.toThrow();- });-});diff --git a/app/src/components/intelligence/svgForceLayout.worker.ts b/app/src/components/intelligence/svgForceLayout.worker.tsdeleted file mode 100644index 15c6e78400..0000000000--- a/app/src/components/intelligence/svgForceLayout.worker.ts+++ /dev/null@@ -1,146 +0,0 @@-/**- * Off-main-thread force layout for the SVG fallback renderer.- *- * The SVG path used to settle its graph with a synchronous O(n²) all-pairs- * relaxation (`relaxLayout` in MemoryGraph.tsx) that ran 220 iterations in one- * blocking call — fine at a few hundred nodes, a multi-second freeze at ~1k,- * and a renderer-killing hang at ~10k. This worker moves that work off the UI- * thread: it runs the same d3-force simulation the WebGL path uses (Barnes–Hut- * charge, link springs, centring, collision) and streams node positions back- * as a transferable Float32Array each tick. The main thread only applies- * positions and repaints, so it never blocks regardless of graph size.- *- * Protocol (main → worker):- * { type: 'init', nodes: {x,y,r}[], links: {source,target}[] } // source/target = node indices- * { type: 'drag', index, x, y, fixed } // pin/unpin a node during drag- * { type: 'stop' } // halt + tear down the sim- * Worker → main:- * { type: 'tick', positions: Float32Array([x0,y0,x1,y1,…]), alpha }- * { type: 'end' } // sim cooled below alphaMin- */-import {- forceCenter,- forceCollide,- forceLink,- forceManyBody,- forceSimulation,- type Simulation,- type SimulationNodeDatum,-} from 'd3-force';--interface WNode extends SimulationNodeDatum {- r: number;-}-interface WLink {- source: number;- target: number;-}--// Local worker-global type so we don't pull the `webworker` lib (which would-// clash with the DOM lib across the whole tsc program). `self` is the worker's-// global scope at runtime.-const ctx = self as unknown as {- onmessage: ((e: MessageEvent) => void) | null;- postMessage: (message: unknown, transfer?: Transferable[]) => void;-};--let sim: Simulation<WNode, WLink> | null = null;-let nodes: WNode[] = [];-let timer: ReturnType<typeof setTimeout> | 0 = 0;--// d3 charge/link/collide params mirror createSimulation() in-// memoryGraphLayout.ts so the worker layout matches the WebGL path. `cx`/`cy`-// centre the cloud on the SVG viewport (the WebGL path recentres its own-// camera, but the SVG path renders in fixed viewBox coordinates).-function build(- initNodes: { x: number; y: number; r: number }[],- links: WLink[],- cx: number,- cy: number,- alpha: number-) {- nodes = initNodes.map(n => ({ x: n.x, y: n.y, r: n.r }));- sim = forceSimulation<WNode, WLink>(nodes)- .force('charge', forceManyBody<WNode>().strength(-140).distanceMax(420))- .force(- 'link',- forceLink<WNode, WLink>(links)- .id((_d, i) => i)- .distance(58)- .strength(0.35)- )- .force('center', forceCenter(cx, cy).strength(0.04))- .force(- 'collide',- forceCollide<WNode>().radius(d => d.r + 2)- )- .stop();- // 1 on a fresh graph (full settle); ~0.3 on an incremental update so carried- // positions barely move and only new nodes ease into place.- sim.alpha(alpha > 0 ? alpha : 1);-}--function postPositions() {- const buf = new Float32Array(nodes.length * 2);- for (let i = 0; i < nodes.length; i++) {- buf[i * 2] = nodes[i].x ?? 0;- buf[i * 2 + 1] = nodes[i].y ?? 0;- }- ctx.postMessage({ type: 'tick', positions: buf, alpha: sim?.alpha() ?? 0 }, [buf.buffer]);-}--function loop() {- if (!sim) return;- sim.tick(); // one integration step per frame- postPositions();- if (sim.alpha() > sim.alphaMin()) {- timer = setTimeout(loop, 16); // ~60fps; workers have no requestAnimationFrame- } else {- timer = 0;- ctx.postMessage({ type: 'end' });- }-}--function stop() {- if (timer) {- clearTimeout(timer);- timer = 0;- }- sim?.stop();- sim = null;-}--ctx.onmessage = (e: MessageEvent) => {- const msg = e.data as- | {- type: 'init';- nodes: { x: number; y: number; r: number }[];- links: WLink[];- cx: number;- cy: number;- alpha: number;- }- | { type: 'drag'; index: number; x: number; y: number; fixed: boolean }- | { type: 'stop' };-- if (msg.type === 'init') {- stop();- build(msg.nodes, msg.links, msg.cx, msg.cy, msg.alpha);- loop();- } else if (msg.type === 'drag') {- const n = nodes[msg.index];- if (n) {- if (msg.fixed) {- n.fx = msg.x;- n.fy = msg.y;- } else {- n.fx = null;- n.fy = null;- }- }- if (sim) sim.alpha(Math.max(sim.alpha(), 0.2));- if (!timer) loop();- } else if (msg.type === 'stop') {- stop();- }-};diff --git a/app/src/components/intelligence/useMemoryEngineCapabilities.test.tsx b/app/src/components/intelligence/useMemoryEngineCapabilities.test.tsxdeleted file mode 100644index 88405d42df..0000000000--- a/app/src/components/intelligence/useMemoryEngineCapabilities.test.tsx+++ /dev/null@@ -1,67 +0,0 @@-/**- * The shared engine cache: every reader in one view shares one- * `engines_list` + `engine_get`, and a forced refresh re-fetches.- */-import { act, renderHook, waitFor } from '@testing-library/react';-import { beforeEach, describe, expect, test, vi } from 'vitest';--import { resetMemoryEngineCacheForTests, useMemoryEngine } from './useMemoryEngineCapabilities';--const hoisted = vi.hoisted(() => ({ list: vi.fn(), get: vi.fn() }));--vi.mock('../../utils/tauriCommands/memoryEngine', () => ({- memoryEnginesList: (...a: unknown[]) => hoisted.list(...a),- memoryEngineGet: (...a: unknown[]) => hoisted.get(...a),-}));--beforeEach(() => {- hoisted.list.mockReset();- hoisted.get.mockReset();- resetMemoryEngineCacheForTests();- hoisted.get.mockResolvedValue({ driver: 'mem0' });- hoisted.list.mockResolvedValue({- active: 'mem0',- engines: [{ id: 'mem0', label: 'Mem0', capabilities: ['core'] }],- });-});--describe('useMemoryEngine', () => {- test('several readers in one view share a single list + get', async () => {- const a = renderHook(() => useMemoryEngine());- const b = renderHook(() => useMemoryEngine());- const c = renderHook(() => useMemoryEngine());- await waitFor(() => expect(a.result.current.id).toBe('mem0'));- await waitFor(() => expect(b.result.current.id).toBe('mem0'));- await waitFor(() => expect(c.result.current.label).toBe('Mem0'));- expect(hoisted.list).toHaveBeenCalledTimes(1);- expect(hoisted.get).toHaveBeenCalledTimes(1);- });-- test('a reader mounting within the TTL reuses the result', async () => {- const first = renderHook(() => useMemoryEngine());- await waitFor(() => expect(first.result.current.id).toBe('mem0'));- const later = renderHook(() => useMemoryEngine());- expect(later.result.current.id).toBe('mem0');- expect(hoisted.get).toHaveBeenCalledTimes(1);- });-- test('refresh forces a new fetch and fans out to every reader', async () => {- const a = renderHook(() => useMemoryEngine());- const b = renderHook(() => useMemoryEngine());- await waitFor(() => expect(a.result.current.id).toBe('mem0'));- hoisted.get.mockResolvedValue({ driver: 'null' });- await act(async () => {- await a.result.current.refresh();- });- await waitFor(() => expect(b.result.current.id).toBe('null'));- expect(hoisted.get).toHaveBeenCalledTimes(2);- });-- test('a failed fetch leaves capabilities unknown (fail open) and reports the error', async () => {- hoisted.get.mockRejectedValue(new Error('offline'));- const a = renderHook(() => useMemoryEngine());- await waitFor(() => expect(a.result.current.loading).toBe(false));- expect(a.result.current.capabilities).toBeNull();- expect(a.result.current.error).toBeTruthy();- });-});diff --git a/app/src/components/intelligence/useMemoryEngineCapabilities.ts b/app/src/components/intelligence/useMemoryEngineCapabilities.tsdeleted file mode 100644index 394e7c12d3..0000000000--- a/app/src/components/intelligence/useMemoryEngineCapabilities.ts+++ /dev/null@@ -1,150 +0,0 @@-import debug from 'debug';-import { useCallback, useEffect, useState } from 'react';--import {- type MemoryEngineDescriptor,- memoryEngineGet,- memoryEnginesList,- type MemoryEngineState,-} from '../../utils/tauriCommands/memoryEngine';--const log = debug('brain:memory-engine');--/** How long a fetched engine snapshot is reused by views mounting close together. */-export const MEMORY_ENGINE_CACHE_TTL_MS = 5000;-const MEMORY_ENGINE_REQUEST_TIMEOUT_MS = 10_000;--export interface MemoryEngineView {- /** True until the first answer (or failure) arrives. */- loading: boolean;- /** Id of the bound engine; null until the core answers or if it cannot. */- id: string | null;- /** Human label of the bound engine (falls back to the id). */- label: string | null;- /** Capability families the bound engine advertises; null while unknown. */- capabilities: ReadonlySet<string> | null;- /** Every selectable engine (empty until known). */- engines: MemoryEngineDescriptor[];- /** The raw `engine_get` state (fell_back_from, last_error, ...); null until known. */- current: MemoryEngineState | null;- /** Error from the last fetch, when it failed. */- error: unknown;- /** Re-fetch now (deduplicated with any fetch already in flight). */- refresh: () => Promise<void>;-}--interface Snapshot {- loading: boolean;- engines: MemoryEngineDescriptor[];- current: MemoryEngineState | null;- error: unknown;- fetchedAt: number;-}--const INITIAL: Snapshot = { loading: true, engines: [], current: null, error: null, fetchedAt: 0 };--let snapshot: Snapshot = INITIAL;-let inflight: Promise<void> | null = null;-let revision = 0;-const listeners = new Set<(s: Snapshot) => void>();--function publish(next: Snapshot) {- snapshot = next;- listeners.forEach(fn => fn(next));-}--/**- * One `engines_list` + `engine_get` per view: concurrent callers share the- * in-flight request and callers within the TTL share its result.- */-function fetchSnapshot(force: boolean): Promise<void> {- if (inflight) {- return inflight.then(() =>- force && snapshot.fetchedAt === 0 ? fetchSnapshot(true) : undefined- );- }- const fresh =- snapshot.fetchedAt > 0 && Date.now() - snapshot.fetchedAt < MEMORY_ENGINE_CACHE_TTL_MS;- if (!force && fresh && snapshot.error === null) return Promise.resolve();- const requestedRevision = revision;- inflight = (async () => {- try {- const [list, current] = await Promise.race([- Promise.all([memoryEnginesList(), memoryEngineGet()]),- new Promise<never>((_, reject) =>- setTimeout(- () => reject(new Error('Memory engine status request timed out')),- MEMORY_ENGINE_REQUEST_TIMEOUT_MS- )- ),- ]);- if (requestedRevision !== revision) return;- log('loaded engines=%d active=%s', list.engines.length, current.driver);- publish({- loading: false,- engines: list.engines,- current,- error: null,- fetchedAt: Date.now(),- });- } catch (err) {- log('unavailable: %o', err);- if (requestedRevision === revision) {- publish({ ...snapshot, loading: false, error: err, fetchedAt: Date.now() });- }- } finally {- inflight = null;- }- })();- return inflight;-}--/** Drop the cached snapshot (after a switch) so the next reader re-fetches. */-export function invalidateMemoryEngine(): void {- revision += 1;- publish({ ...snapshot, fetchedAt: 0 });-}--/** Test seam: forget everything, including subscribers' last value. */-export function resetMemoryEngineCacheForTests(): void {- snapshot = INITIAL;- inflight = null;- revision = 0;-}--/**- * The active memory engine, its capability families and the engine list — one- * shared cache behind the Brain row, the family gates and the settings panel.- *- * Fails open: while loading, or if the core does not answer, `capabilities` is- * null and callers must treat every family as available. Hiding a working- * feature because a status probe failed would be worse than showing an error.- */-export function useMemoryEngine(): MemoryEngineView {- const [snap, setSnap] = useState<Snapshot>(snapshot);-- useEffect(() => {- listeners.add(setSnap);- setSnap(snapshot);- void fetchSnapshot(false);- return () => {- listeners.delete(setSnap);- };- }, []);-- const refresh = useCallback(() => fetchSnapshot(true), []);- const entry = snap.current ? snap.engines.find(e => e.id === snap.current?.driver) : undefined;- return {- loading: snap.loading,- id: snap.current?.driver ?? null,- label: snap.current ? (entry?.label ?? snap.current.driver) : null,- capabilities: entry ? new Set(entry.capabilities) : null,- engines: snap.engines,- current: snap.current,- error: snap.error,- refresh,- };-}--/** Back-compat alias for callers that only need the id / label / capabilities. */-export const useMemoryEngineCapabilities = useMemoryEngine;diff --git a/app/src/components/intelligence/useSvgForceLayout.ts b/app/src/components/intelligence/useSvgForceLayout.tsdeleted file mode 100644index 03060aba73..0000000000--- a/app/src/components/intelligence/useSvgForceLayout.ts+++ /dev/null@@ -1,109 +0,0 @@-/**- * React hook that drives the SVG fallback's layout from a Web Worker.- *- * When enabled, it spins up {@link svgForceLayout.worker} with the seeded node- * positions + edges, applies each streamed position frame back onto the same- * `nodes` array (mutated in place, by index), and calls `onTick` so the SVG- * repaints — the graph visibly settles instead of freezing. The worker is torn- * down on data change / unmount / `stop()`.- *- * If `Worker` is unavailable (jsdom under test, or a runtime without workers),- * the hook is a no-op and the caller's synchronous `relaxLayout` fallback runs- * instead — so behaviour and tests are unchanged off the worker path.- */-import { useCallback, useEffect, useRef } from 'react';--interface SvgLayoutNode {- x: number;- y: number;-}--interface WorkerTickMessage {- type: 'tick';- positions: Float32Array;- alpha: number;-}--export const WORKER_SUPPORTED = typeof Worker !== 'undefined';--/**- * @param enabled only true on the SVG path with worker support- * @param nodes the live SimNode array (mutated in place with streamed x/y)- * @param radii per-node collision radius, index-aligned with `nodes`- * @param edges index pairs [childIdx, parentIdx]- * @param center [cx, cy] viewport centre the layout settles around- * @param alpha initial sim energy: 1 fresh graph, ~0.3 incremental update- * @param onTick stable callback to trigger a repaint (e.g. an imperative apply)- * @param onSettled stable callback fired once the sim cools (good time to fit)- */-export function useSvgForceLayout(- enabled: boolean,- nodes: SvgLayoutNode[],- radii: number[],- edges: Array<[number, number]>,- center: readonly [number, number],- alpha: number,- onTick: () => void,- onSettled: () => void-): { drag: (index: number, x: number, y: number, fixed: boolean) => void; stop: () => void } {- const workerRef = useRef<Worker | null>(null);- // Session-alive guard, shared by the message handler, the effect cleanup, and- // stop(); flipping it false makes any in-flight tick/end a no-op.- const aliveRef = useRef(false);-- useEffect(() => {- if (!enabled || !WORKER_SUPPORTED || nodes.length === 0) return;-- const worker = new Worker(new URL('./svgForceLayout.worker.ts', import.meta.url), {- type: 'module',- });- workerRef.current = worker;- aliveRef.current = true;-- worker.onmessage = (e: MessageEvent) => {- // aliveRef is flipped false by the cleanup AND by stop(), so a late- // tick/end from a just-stopped worker can't mutate nodes or fit.- if (!aliveRef.current) return;- const msg = e.data as WorkerTickMessage | { type: 'end' };- if (msg.type === 'tick') {- const pos = msg.positions;- const n = Math.min(nodes.length, pos.length >> 1);- for (let i = 0; i < n; i++) {- nodes[i].x = pos[i * 2];- nodes[i].y = pos[i * 2 + 1];- }- onTick();- } else if (msg.type === 'end') {- onSettled();- }- };-- worker.postMessage({- type: 'init',- nodes: nodes.map((node, i) => ({ x: node.x, y: node.y, r: radii[i] ?? 6 })),- links: edges.map(([a, b]) => ({ source: a, target: b })),- cx: center[0],- cy: center[1],- alpha,- });-- return () => {- aliveRef.current = false;- worker.postMessage({ type: 'stop' });- worker.terminate();- workerRef.current = null;- };- }, [enabled, nodes, radii, edges, center, alpha, onTick, onSettled]);-- const drag = useCallback((index: number, x: number, y: number, fixed: boolean) => {- workerRef.current?.postMessage({ type: 'drag', index, x, y, fixed });- }, []);- const stop = useCallback(() => {- aliveRef.current = false; // ignore any in-flight tick/end from this worker- workerRef.current?.postMessage({ type: 'stop' });- workerRef.current?.terminate();- workerRef.current = null;- }, []);-- return { drag, stop };-}diff --git a/app/src/components/intelligence/vaultHostMatch.test.ts b/app/src/components/intelligence/vaultHostMatch.test.tsdeleted file mode 100644index ba230a35e3..0000000000--- a/app/src/components/intelligence/vaultHostMatch.test.ts+++ /dev/null@@ -1,88 +0,0 @@-/**- * Unit tests for cross-host vault detection (#4278).- */-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { isVaultLocalToThisDevice, normalizeOs, resolveVaultHostMatch } from './vaultHostMatch';--const isTauriMock = vi.fn();-const platformMock = vi.fn();--vi.mock('../../utils/tauriCommands/common', () => ({ isTauri: () => isTauriMock() }));-vi.mock('@tauri-apps/plugin-os', () => ({ platform: () => platformMock() }));--describe('normalizeOs', () => {- it('folds known aliases to canonical tokens', () => {- expect(normalizeOs('macos')).toBe('macos');- expect(normalizeOs('Darwin')).toBe('macos');- expect(normalizeOs('win32')).toBe('windows');- expect(normalizeOs('Windows')).toBe('windows');- expect(normalizeOs('linux')).toBe('linux');- });-- it('returns undefined for empty / unknown values', () => {- expect(normalizeOs(undefined)).toBeUndefined();- expect(normalizeOs(null)).toBeUndefined();- expect(normalizeOs('')).toBeUndefined();- expect(normalizeOs('plan9')).toBeUndefined();- });-});--describe('isVaultLocalToThisDevice', () => {- it('is true only when both OSes are known and equal', () => {- expect(isVaultLocalToThisDevice('macos', 'macos')).toBe(true);- expect(isVaultLocalToThisDevice('linux', 'linux')).toBe(true);- });-- it('is false when the OSes differ', () => {- expect(isVaultLocalToThisDevice('macos', 'linux')).toBe(false);- expect(isVaultLocalToThisDevice('linux', 'windows')).toBe(false);- });-- it('defaults to local (true) when either OS is unknown — never block on missing signal', () => {- expect(isVaultLocalToThisDevice(undefined, 'macos')).toBe(true);- expect(isVaultLocalToThisDevice('macos', undefined)).toBe(true);- expect(isVaultLocalToThisDevice(undefined, undefined)).toBe(true);- });-});--describe('resolveVaultHostMatch', () => {- beforeEach(() => {- vi.clearAllMocks();- });-- it('treats a vault as local when the core reports no host_os (older core)', async () => {- isTauriMock.mockReturnValue(true);- const m = await resolveVaultHostMatch(undefined);- expect(m).toEqual({ local: true });- expect(platformMock).not.toHaveBeenCalled();- });-- it('treats a vault as local outside Tauri', async () => {- isTauriMock.mockReturnValue(false);- const m = await resolveVaultHostMatch('linux');- expect(m).toEqual({ local: true, hostOs: 'linux' });- expect(platformMock).not.toHaveBeenCalled();- });-- it('flags cross-host when the core OS differs from this device', async () => {- isTauriMock.mockReturnValue(true);- platformMock.mockResolvedValue('macos');- const m = await resolveVaultHostMatch('linux');- expect(m).toEqual({ local: false, hostOs: 'linux' });- });-- it('reports local when the core OS matches this device', async () => {- isTauriMock.mockReturnValue(true);- platformMock.mockResolvedValue('linux');- const m = await resolveVaultHostMatch('linux');- expect(m).toEqual({ local: true, hostOs: 'linux' });- });-- it('falls back to local when the platform probe throws', async () => {- isTauriMock.mockReturnValue(true);- platformMock.mockRejectedValue(new Error('no os'));- const m = await resolveVaultHostMatch('windows');- expect(m).toEqual({ local: true, hostOs: 'windows' });- });-});diff --git a/app/src/components/intelligence/vaultHostMatch.ts b/app/src/components/intelligence/vaultHostMatch.tsdeleted file mode 100644index 9bd4508a77..0000000000--- a/app/src/components/intelligence/vaultHostMatch.ts+++ /dev/null@@ -1,86 +0,0 @@-/**- * Cross-host vault awareness (issue #4278).- *- * `openhuman-core` owns a single local filesystem. The memory-tree / Obsidian- * vault physically lives under the CORE host's filesystem, and the vault RPCs- * return that host's absolute path (`content_root_abs`) plus the core's OS- * (`host_os`). When a frontend attaches from a DIFFERENT OS than the core, that- * path cannot be opened or registered locally — "Reveal Folder" / "Open in- * Obsidian" would act on a path that does not exist on this machine.- *- * These helpers compare the core's OS against this frontend's OS so the local- * file integrations can be disabled with a clear message instead of silently- * firing a doomed deep link or a cryptic opener failure.- *- * Backward compatibility: when `host_os` is absent (older core) or this- * frontend's OS cannot be determined, treat the vault as local — never block a- * single-host user on missing signal.- */-import { platform } from '@tauri-apps/plugin-os';--import { isTauri } from '../../utils/tauriCommands/common';--/** Canonical OS tokens shared by Rust `std::env::consts::OS` and plugin-os. */-export type OsToken = 'macos' | 'linux' | 'windows';--/**- * Normalize an OS string to a canonical token. Rust's `std::env::consts::OS`- * and `@tauri-apps/plugin-os` both emit `"macos"`/`"linux"`/`"windows"`, but we- * defensively fold common aliases (`darwin`, `win32`, …) so a future source- * change can't silently break the comparison.- */-export function normalizeOs(os: string | undefined | null): OsToken | undefined {- if (!os) return undefined;- const v = os.trim().toLowerCase();- if (v === 'macos' || v === 'darwin' || v === 'mac' || v === 'osx') return 'macos';- if (v === 'windows' || v === 'win' || v === 'win32') return 'windows';- if (v === 'linux') return 'linux';- return undefined;-}--/**- * Pure decision: is a vault whose path lives on `hostOs` local to a frontend- * running on `clientOs`?- *- * Returns `true` (local — safe to open) when either OS is unknown, so a missing- * signal never disables local actions for a genuine single-host setup.- */-export function isVaultLocalToThisDevice(- hostOs: string | undefined | null,- clientOs: string | undefined | null-): boolean {- const host = normalizeOs(hostOs);- const client = normalizeOs(clientOs);- if (!host || !client) return true;- return host === client;-}--/** Resolved cross-host state for a vault response. */-export interface VaultHostMatch {- /** True when the vault path is openable on this device (same OS, or unknown). */- local: boolean;- /** Normalized core host OS, when known. */- hostOs?: OsToken;-}--/**- * Resolve the cross-host state for a vault response carrying `host_os`.- *- * Reads this frontend's OS via `@tauri-apps/plugin-os`. Outside Tauri, or if- * the platform probe throws, falls back to "local" so non-desktop / preview- * contexts are never blocked.- */-export async function resolveVaultHostMatch(- hostOs: string | undefined | null-): Promise<VaultHostMatch> {- const normalizedHost = normalizeOs(hostOs);- if (!normalizedHost) return { local: true };- if (!isTauri()) return { local: true, hostOs: normalizedHost };- try {- const clientOs = await platform();- return { local: isVaultLocalToThisDevice(normalizedHost, clientOs), hostOs: normalizedHost };- } catch {- // Can't determine this device's OS — don't block local actions.- return { local: true, hostOs: normalizedHost };- }-}diff --git a/app/src/components/settings/components/MemoryWindowControl.tsx b/app/src/components/settings/components/MemoryWindowControl.tsxdeleted file mode 100644index 6c103d5c34..0000000000--- a/app/src/components/settings/components/MemoryWindowControl.tsx+++ /dev/null@@ -1,167 +0,0 @@-import { useEffect, useState } from 'react';--import { cn } from '../../../lib/cn';-import { useT } from '../../../lib/i18n/I18nContext';-import {- MEMORY_CONTEXT_WINDOWS,- type MemoryContextWindow,- openhumanGetConfig,- openhumanUpdateMemorySettings,-} from '../../../utils/tauriCommands';-import Card from '../../ui/Card';-import { RadioGroupItem, RadioGroupRoot } from '../../ui/RadioGroup';--interface PresetMeta {- label: string;- badge: string;- hint: string;-}--const isMemoryContextWindow = (value: unknown): value is MemoryContextWindow =>- typeof value === 'string' && (MEMORY_CONTEXT_WINDOWS as readonly string[]).includes(value);--const extractCurrentWindow = (snapshot: unknown): MemoryContextWindow => {- if (!snapshot || typeof snapshot !== 'object') return 'balanced';- const root = snapshot as Record<string, unknown>;- const config = (root.config as Record<string, unknown> | undefined) ?? root;- const agent = config.agent as Record<string, unknown> | undefined;- const candidate = agent?.memory_window;- return isMemoryContextWindow(candidate) ? candidate : 'balanced';-};--interface Props {- onError?: (message: string) => void;- onSaved?: (window: MemoryContextWindow) => void;-}--/**- * Stepped memory-context window selector.- *- * - Reads the persisted preference from the core via `openhuman.get_config`.- * - Writes it back via `openhuman.update_memory_settings` (the core- * owns the actual char-budget mapping).- * - Renders four options with plain-language hints so users understand- * the cost / continuity tradeoff.- */-const MemoryWindowControl = ({ onError, onSaved }: Props) => {- const { t } = useT();- const [current, setCurrent] = useState<MemoryContextWindow>('balanced');- const [pending, setPending] = useState<MemoryContextWindow | null>(null);- const [loaded, setLoaded] = useState(false);- const [saving, setSaving] = useState<MemoryContextWindow | null>(null);-- const localizedMeta: Record<MemoryContextWindow, PresetMeta> = {- minimal: {- label: t('settings.memoryWindow.minimal.label'),- badge: t('settings.memoryWindow.minimal.badge'),- hint: t('settings.memoryWindow.minimal.hint'),- },- balanced: {- label: t('settings.memoryWindow.balanced.label'),- badge: t('settings.memoryWindow.balanced.badge'),- hint: t('settings.memoryWindow.balanced.hint'),- },- extended: {- label: t('settings.memoryWindow.extended.label'),- badge: t('settings.memoryWindow.extended.badge'),- hint: t('settings.memoryWindow.extended.hint'),- },- maximum: {- label: t('settings.memoryWindow.maximum.label'),- badge: t('settings.memoryWindow.maximum.badge'),- hint: t('settings.memoryWindow.maximum.hint'),- },- };-- useEffect(() => {- let cancelled = false;- const load = async () => {- try {- const response = await openhumanGetConfig();- if (cancelled) return;- setCurrent(extractCurrentWindow(response.result));- } catch (err) {- if (cancelled) return;- onError?.(err instanceof Error ? err.message : 'Failed to load memory settings');- } finally {- if (!cancelled) setLoaded(true);- }- };- void load();- return () => {- cancelled = true;- };- }, [onError]);-- const select = async (next: MemoryContextWindow) => {- if (next === current || saving) return;- setPending(next);- setSaving(next);- try {- await openhumanUpdateMemorySettings({ memory_window: next });- setCurrent(next);- onSaved?.(next);- } catch (err) {- onError?.(err instanceof Error ? err.message : 'Failed to save memory window');- } finally {- setSaving(null);- setPending(null);- }- };-- const activeForUi = pending ?? current;- const meta = localizedMeta[activeForUi];-- return (- <Card- title={t('settings.memoryWindow.title')}- description={t('settings.memoryWindow.description')}- data-testid="memory-window-control">- <div className="space-y-3 p-4">- <RadioGroupRoot- value={activeForUi}- onValueChange={next => void select(next as MemoryContextWindow)}- aria-label={t('settings.memoryWindow.title')}- className="grid grid-cols-2 gap-2">- {MEMORY_CONTEXT_WINDOWS.map(option => {- const optionMeta = localizedMeta[option];- const isActive = activeForUi === option;- const isSaving = saving === option;- const inputId = `memory-window-option-${option}-input`;- return (- <label- key={option}- htmlFor={inputId}- className={cn(- 'flex min-w-0 items-center justify-between gap-2 rounded-md border px-3 py-2 transition-colors',- isActive- ? 'border-primary-500 bg-primary-500/10'- : 'border-line-strong hover:bg-surface-hover',- (!loaded || (saving !== null && !isSaving)) && 'opacity-60 pointer-events-none'- )}>- <RadioGroupItem- id={inputId}- value={option}- data-testid={`memory-window-option-${option}`}- disabled={!loaded || (saving !== null && !isSaving)}- className="sr-only"- />- <span className="min-w-0 flex-1 truncate font-medium text-content">- {optionMeta.label}- </span>- <span className="shrink-0 whitespace-nowrap text-[10px] uppercase tracking-wide text-content-muted">- {optionMeta.badge}- </span>- </label>- );- })}- </RadioGroupRoot>- <p className="text-xs text-content-muted" data-testid="memory-window-hint">- {meta.hint}- </p>- </div>- </Card>- );-};--export default MemoryWindowControl;diff --git a/app/src/components/settings/panels/MemoryDataPanel.tsx b/app/src/components/settings/panels/MemoryDataPanel.tsxdeleted file mode 100644index 7f2872fa63..0000000000--- a/app/src/components/settings/panels/MemoryDataPanel.tsx+++ /dev/null@@ -1,118 +0,0 @@-import { useCallback, useState } from 'react';--import { useT } from '../../../lib/i18n/I18nContext';-import type { ToastNotification } from '../../../types/intelligence';-import MemoryFamilyGate from '../../intelligence/MemoryFamilyGate';-import { MemoryWorkspace } from '../../intelligence/MemoryWorkspace';-import { ToastContainer } from '../../intelligence/Toast';-import { VaultHealthChecklist } from '../../intelligence/VaultHealthChecklist';-import PanelPage from '../../layout/PanelPage';-import MemoryWindowControl from '../components/MemoryWindowControl';-import { SettingsSection } from '../controls';-import SettingsPanel from '../layout/SettingsPanel';-import { useMemoryEngineErrorText } from './MemoryEngineErrorAlert';-import { classifyMemoryEngineError } from './memoryEngineUtils';--interface MemoryDataPanelProps {- /** When true, render without the SettingsHeader chrome (used when embedded- * inside the onboarding custom wizard). */- embedded?: boolean;-}--const MemoryDataPanel = ({ embedded = false }: MemoryDataPanelProps = {}) => {- const { t } = useT();- const [toasts, setToasts] = useState<ToastNotification[]>([]);-- const addToast = useCallback((toast: Omit<ToastNotification, 'id'>) => {- const newToast: ToastNotification = { ...toast, id: `toast-${Date.now()}-${Math.random()}` };- setToasts(prev => [...prev, newToast]);- }, []);-- const removeToast = (id: string) => {- setToasts(prev => prev.filter(t => t.id !== id));- };-- const engineErrorText = useMemoryEngineErrorText();- const handleWindowError = useCallback(- (message: string) => {- // A hosted engine's 402 / expired session reads as a top-up / sign-in hint.- const kind = classifyMemoryEngineError(message);- addToast({- type: 'error',- title: t('memoryData.windowError'),- message: kind === 'other' ? message : engineErrorText(kind),- });- },- [addToast, t, engineErrorText]- );-- const handleWindowSaved = useCallback(- (window: string) => {- addToast({- type: 'success',- title: t('memoryData.windowUpdated'),- message: t('memoryData.windowUpdatedMsg').replace('{window}', window),- });- },- [addToast, t]- );-- const body = (- <>- <div className="space-y-5">- <SettingsSection title={t('memoryData.howItWorks')}>- <dl className="space-y-2.5 px-4 py-3">- <div>- <dt className="text-xs font-semibold text-content">- {t('memoryData.workspaceVault')}- </dt>- <dd className="text-xs leading-relaxed text-content-muted">- {t('memoryData.workspaceVaultDesc')}- </dd>- </div>- <div>- <dt className="text-xs font-semibold text-content">- {t('memoryData.connectedSources')}- </dt>- <dd className="text-xs leading-relaxed text-content-muted">- {t('memoryData.connectedSourcesDesc')}- </dd>- </div>- <div>- <dt className="text-xs font-semibold text-content">- {t('memoryData.internalFiles')}- </dt>- <dd className="text-xs leading-relaxed text-content-muted">- {t('memoryData.internalFilesDesc')}- </dd>- </div>- </dl>- </SettingsSection>- {/* The vault is the local chunk store's files: hosted memory has none. */}- <MemoryFamilyGate family="chunks">- <VaultHealthChecklist onToast={addToast} title={t('vaultHealth.setupTitle')} />- </MemoryFamilyGate>- <MemoryWindowControl onError={handleWindowError} onSaved={handleWindowSaved} />- <MemoryFamilyGate family="tree">- <MemoryWorkspace onToast={addToast} />- </MemoryFamilyGate>- </div>- <ToastContainer notifications={toasts} onRemove={removeToast} />- </>- );-- // Embedded (the onboarding custom wizard) keeps the headerless PanelPage- // branch — that host draws its own step chrome, so a settings page header- // here would be a second one.- if (embedded) {- return (- <PanelPage className="z-10" contentClassName="">- {body}- </PanelPage>- );- }-- return <SettingsPanel description={t('devOptions.memoryInspectionDesc')}>{body}</SettingsPanel>;-};--export default MemoryDataPanel;diff --git a/app/src/components/settings/panels/MemoryDebugPanel.tsx b/app/src/components/settings/panels/MemoryDebugPanel.tsxdeleted file mode 100644index 844b741b34..0000000000--- a/app/src/components/settings/panels/MemoryDebugPanel.tsx+++ /dev/null@@ -1,481 +0,0 @@-import { RefreshCw, Trash2 } from 'lucide-react';-import { useCallback, useEffect, useMemo, useState } from 'react';--import { useT } from '../../../lib/i18n/I18nContext';-import {- memoryClearNamespace,- type MemoryDebugDocument,- memoryDeleteDocument,- memoryListDocuments,- memoryListNamespaces,- memoryQueryNamespace,- type MemoryQueryResult,- memoryRecallNamespace,-} from '../../../utils/tauriCommands';-import { MemoryTextWithEntities } from '../../intelligence/MemoryTextWithEntities';-import { Badge, Spinner } from '../../ui';-import Button from '../../ui/Button';-import DataTable, { type DataTableColumn } from '../../ui/DataTable';-import {- SettingsEmptyState,- SettingsSection,- SettingsSelect,- SettingsStatusLine,- SettingsTextArea,- SettingsTextField,-} from '../controls';-import SettingsPanel from '../layout/SettingsPanel';-import { normalizeMemoryDocuments } from './memoryDebugUtils';--const MemoryDebugPanel = () => {- const { t } = useT();- const [documents, setDocuments] = useState<MemoryDebugDocument[]>([]);- const [documentsRaw, setDocumentsRaw] = useState<unknown>(null);- const [documentsNamespaceFilter, setDocumentsNamespaceFilter] = useState('');- const [namespaces, setNamespaces] = useState<string[]>([]);- const [documentsLoading, setDocumentsLoading] = useState(false);- const [namespacesLoading, setNamespacesLoading] = useState(false);- const [deleteLoadingId, setDeleteLoadingId] = useState<string | null>(null);- const [documentsError, setDocumentsError] = useState<string | null>(null);- const [namespacesError, setNamespacesError] = useState<string | null>(null);-- const [namespaceInput, setNamespaceInput] = useState('');- const [queryInput, setQueryInput] = useState('');- const [maxChunksInput, setMaxChunksInput] = useState('10');- const [queryResult, setQueryResult] = useState<MemoryQueryResult | null>(null);- const [recallResult, setRecallResult] = useState<MemoryQueryResult | null>(null);- const [queryError, setQueryError] = useState<string | null>(null);- const [recallError, setRecallError] = useState<string | null>(null);- const [queryLoading, setQueryLoading] = useState(false);- const [recallLoading, setRecallLoading] = useState(false);-- const [clearNamespaceInput, setClearNamespaceInput] = useState('');- const [clearLoading, setClearLoading] = useState(false);- const [clearSuccess, setClearSuccess] = useState<string | null>(null);- const [clearError, setClearError] = useState<string | null>(null);-- const maxChunks = useMemo(() => {- const parsed = Number(maxChunksInput);- if (!Number.isFinite(parsed) || parsed <= 0) return 10;- return Math.floor(parsed);- }, [maxChunksInput]);-- const loadDocuments = useCallback(async () => {- setDocumentsLoading(true);- setDocumentsError(null);- try {- const namespace = documentsNamespaceFilter.trim();- const payload = await memoryListDocuments(namespace || undefined);- setDocumentsRaw(payload);- setDocuments(normalizeMemoryDocuments(payload));- } catch (error) {- setDocumentsError(error instanceof Error ? error.message : String(error));- setDocuments([]);- setDocumentsRaw(null);- } finally {- setDocumentsLoading(false);- }- }, [documentsNamespaceFilter]);-- const loadNamespaces = useCallback(async () => {- setNamespacesLoading(true);- setNamespacesError(null);- try {- const result = await memoryListNamespaces();- setNamespaces(result);- if (!namespaceInput && result.length > 0) {- setNamespaceInput(result[0]);- }- } catch (error) {- setNamespacesError(error instanceof Error ? error.message : String(error));- setNamespaces([]);- } finally {- setNamespacesLoading(false);- }- }, [namespaceInput]);-- const refreshAll = useCallback(async () => {- await Promise.all([loadDocuments(), loadNamespaces()]);- }, [loadDocuments, loadNamespaces]);-- useEffect(() => {- void refreshAll();- }, [refreshAll]);-- const handleDelete = useCallback(- async (doc: MemoryDebugDocument) => {- const confirmed = window.confirm(- t('memory.deleteConfirm', 'Delete document "{documentId}" in namespace "{namespace}"?')- .replace('{documentId}', doc.documentId)- .replace('{namespace}', doc.namespace)- );- if (!confirmed) return;-- setDeleteLoadingId(doc.documentId);- try {- await memoryDeleteDocument(doc.documentId, doc.namespace);- await refreshAll();- } catch (error) {- setDocumentsError(error instanceof Error ? error.message : String(error));- } finally {- setDeleteLoadingId(null);- }- },- [refreshAll, t]- );-- const handleQuery = useCallback(async () => {- setQueryLoading(true);- setQueryError(null);- setQueryResult(null);- try {- const result = await memoryQueryNamespace(- namespaceInput.trim(),- queryInput.trim(),- maxChunks- );- setQueryResult(result);- } catch (error) {- setQueryError(error instanceof Error ? error.message : String(error));- } finally {- setQueryLoading(false);- }- }, [maxChunks, namespaceInput, queryInput]);-- const handleRecall = useCallback(async () => {- setRecallLoading(true);- setRecallError(null);- setRecallResult(null);- try {- const result = await memoryRecallNamespace(namespaceInput.trim(), maxChunks);- setRecallResult(result);- } catch (error) {- setRecallError(error instanceof Error ? error.message : String(error));- } finally {- setRecallLoading(false);- }- }, [maxChunks, namespaceInput]);-- const handleClearNamespace = useCallback(async () => {- const ns = clearNamespaceInput.trim();- if (!ns) return;-- const confirmed = window.confirm(- t(- 'memory.clearNamespaceConfirm',- 'This will permanently delete ALL documents in namespace "{namespace}". Continue?'- ).replace('{namespace}', ns)- );- if (!confirmed) return;-- setClearLoading(true);- setClearError(null);- setClearSuccess(null);- try {- const result = await memoryClearNamespace(ns);- if (result.cleared) {- setClearSuccess(- t('memory.clearNamespaceSuccess', 'Namespace "{namespace}" cleared.').replace(- '{namespace}',- result.namespace- )- );- } else {- setClearSuccess(- t('memory.clearNamespaceEmpty', 'Nothing to clear in "{namespace}".').replace(- '{namespace}',- result.namespace- )- );- }- await refreshAll();- } catch (error) {- setClearError(error instanceof Error ? error.message : String(error));- } finally {- setClearLoading(false);- }- }, [clearNamespaceInput, refreshAll, t]);-- const documentColumns: DataTableColumn<MemoryDebugDocument>[] = [- {- id: 'document',- header: t('memory.column.document'),- className: 'w-full max-w-0',- cell: doc => (- <div className="min-w-0 space-y-0.5">- <p className="truncate text-xs font-medium text-content" title={doc.documentId}>- {doc.documentId}- </p>- {doc.title && (- <p className="truncate text-[11px] text-content-muted" title={doc.title}>- {doc.title}- </p>- )}- </div>- ),- },- {- id: 'namespace',- header: t('memory.namespace'),- className: 'w-px whitespace-nowrap',- cell: doc => <Badge variant="neutral">{doc.namespace}</Badge>,- },- {- id: 'actions',- header: <span className="sr-only">{t('memory.delete')}</span>,- align: 'right',- className: 'w-px whitespace-nowrap',- cell: doc => (- <Button- type="button"- variant="tertiary"- tone="danger"- size="xs"- disabled={Boolean(deleteLoadingId)}- onClick={() => void handleDelete(doc)}- leadingIcon={- deleteLoadingId === doc.documentId ? (- <Spinner className="h-3 w-3" />- ) : (- <Trash2 className="h-3.5 w-3.5" aria-hidden />- )- }>- {t('memory.delete')}- </Button>- ),- },- ];-- return (- <SettingsPanel testId="memory-debug-panel" description={t('devOptions.debugPanelsDesc')}>- <div className="space-y-5">- {/* Documents — the standard table, capped in height because this- page also carries the namespace / query / clear sections below. */}- <DataTable<MemoryDebugDocument>- fill={false}- testId="memory-debug-documents"- title={t('memory.documents')}- actions={- <Button- type="button"- variant="secondary"- size="sm"- onClick={() => void loadDocuments()}- disabled={documentsLoading}- leadingIcon={- documentsLoading ? (- <Spinner className="h-3 w-3" />- ) : (- <RefreshCw className="h-3.5 w-3.5" aria-hidden />- )- }>- {t('memory.refresh')}- </Button>- }- search={{- value: documentsNamespaceFilter,- onChange: setDocumentsNamespaceFilter,- placeholder: t('memory.filterByNamespace'),- ariaLabel: t('memory.filterByNamespace'),- }}- error={- documentsError ? (- <SettingsStatusLine saving={false} error={documentsError} savingLabel="" />- ) : undefined- }- columns={documentColumns}- rows={documents}- rowKey={doc => `${doc.namespace}:${doc.documentId}`}- // Paging only once there is more than a page: a short list needs no- // footer.- pagination={documents.length > 25 ? { pageSize: 25 } : undefined}- loading={documentsLoading && documents.length === 0}- empty={<SettingsEmptyState label={t('memory.noDocumentsFound')} />}- ariaLabel={t('memory.documents')}- />- <details className="text-xs">- <summary className="cursor-pointer text-content-muted">{t('memory.rawResponse')}</summary>- {/* Intentionally non-themeable: a fixed dark terminal surface- for raw JSON, inverted between light/dark mode so the dump- always reads as a code/terminal pane rather than following- the user's theme. Arbitrary hex values (not the `neutral`- palette scale) so this isn't a themeable-surface regression- masquerading as a fixed one. */}- <pre className="mt-1 max-h-32 overflow-auto rounded-lg border border-line bg-[#0a0a0a] dark:bg-[#fafafa] p-2 text-[11px] text-[#f5f5f5] dark:text-[#171717] whitespace-pre-wrap wrap-break-word">- {JSON.stringify(documentsRaw, null, 2)}- </pre>- </details>-- {/* Namespaces */}- <SettingsSection title={t('memory.namespaces')}>- <div className="px-4 py-3 space-y-2">- <div className="flex items-center justify-between">- <Button- type="button"- variant="secondary"- size="xs"- onClick={() => void loadNamespaces()}- disabled={namespacesLoading}- leadingIcon={namespacesLoading ? <Spinner className="h-3 w-3" /> : undefined}>- {t('memory.refresh')}- </Button>- </div>- <SettingsStatusLine saving={false} error={namespacesError} savingLabel="" />- {namespaces.length > 0 ? (- <div className="flex flex-wrap gap-1">- {namespaces.map(ns => (- <Badge key={ns} variant="neutral">- {ns}- </Badge>- ))}- </div>- ) : (- <SettingsEmptyState label={t('memory.noNamespacesFound')} />- )}- </div>- </SettingsSection>-- {/* Query & Recall */}- <SettingsSection title={t('memory.queryRecall')}>- <div className="px-4 py-3 space-y-2">- <SettingsTextField- value={namespaceInput}- onChange={e => setNamespaceInput(e.target.value)}- placeholder={t('memory.namespace')}- aria-label={t('memory.namespace')}- inputSize="sm"- />- <SettingsTextArea- value={queryInput}- onChange={e => setQueryInput(e.target.value)}- rows={2}- placeholder={t('memory.queryText')}- aria-label={t('memory.queryText')}- />- <div className="flex items-center gap-2">- <SettingsTextField- className="w-16"- value={maxChunksInput}- onChange={e => setMaxChunksInput(e.target.value)}- placeholder={t('memory.defaultMaxChunks')}- aria-label={t('memory.maxChunks')}- inputSize="sm"- />- <span className="text-[11px] text-content-muted">{t('memory.maxChunks')}</span>- <div className="flex-1" />- <Button- type="button"- variant="secondary"- size="xs"- onClick={() => void handleQuery()}- disabled={queryLoading || !namespaceInput.trim() || !queryInput.trim()}- leadingIcon={queryLoading ? <Spinner className="h-3 w-3" /> : undefined}>- {t('memory.query')}- </Button>- <Button- type="button"- variant="secondary"- size="xs"- onClick={() => void handleRecall()}- disabled={recallLoading || !namespaceInput.trim()}- leadingIcon={recallLoading ? <Spinner className="h-3 w-3" /> : undefined}>- {t('memory.recall')}- </Button>- </div>- <SettingsStatusLine- saving={false}- error={- queryError- ? `${t('memory.queryLabel')}: ${queryError}`- : recallError- ? `${t('memory.recallLabel')}: ${recallError}`- : null- }- savingLabel=""- />- {(queryResult || recallResult) && (- <div className="space-y-2">- {queryResult && (- <div>- <div className="text-[11px] font-medium text-content-muted mb-1">- {t('memory.queryResult')}- </div>- <MemoryTextWithEntities- text={queryResult.text ?? ''}- entities={queryResult.entities}- className="rounded-lg border border-line bg-surface-muted p-2 text-[11px] leading-5 min-h-12 whitespace-pre-wrap"- />- </div>- )}- {recallResult && (- <div>- <div className="text-[11px] font-medium text-content-muted mb-1">- {t('memory.recallResult')}- </div>- <MemoryTextWithEntities- text={recallResult.text ?? ''}- entities={recallResult.entities}- className="rounded-lg border border-line bg-surface-muted p-2 text-[11px] leading-5 min-h-12 whitespace-pre-wrap"- />- </div>- )}- </div>- )}- </div>- </SettingsSection>-- {/* Clear Namespace */}- <SettingsSection- title={t('memory.clearNamespace')}- description={t('memory.clearNamespaceDescription')}>- <div className="px-4 py-3 space-y-2">- <div className="flex gap-2">- {namespaces.length > 0 ? (- <SettingsSelect- className="flex-1"- value={clearNamespaceInput}- onChange={e => setClearNamespaceInput(e.target.value)}- aria-label={t('memory.selectNamespace')}- inputSize="sm">- <option value="">{t('memory.selectNamespace')}</option>- {namespaces.map(ns => (- <option key={ns} value={ns}>- {ns}- </option>- ))}- </SettingsSelect>- ) : (- <SettingsTextField- className="flex-1"- value={clearNamespaceInput}- onChange={e => setClearNamespaceInput(e.target.value)}- placeholder={t('memory.exampleNamespace')}- aria-label={t('memory.exampleNamespace')}- inputSize="sm"- />- )}- <Button- type="button"- variant="secondary"- tone="danger"- size="xs"- onClick={() => void handleClearNamespace()}- disabled={clearLoading || !clearNamespaceInput.trim()}- leadingIcon={clearLoading ? <Spinner className="h-3 w-3" /> : undefined}>- {t('memory.clear')}- </Button>- </div>- <SettingsStatusLine- saving={false}- savedNote={clearSuccess}- error={clearError}- savingLabel=""- />- </div>- </SettingsSection>- </div>- </SettingsPanel>- );-};--export default MemoryDebugPanel;diff --git a/app/src/components/settings/panels/MemoryEngineErrorAlert.test.tsx b/app/src/components/settings/panels/MemoryEngineErrorAlert.test.tsxdeleted file mode 100644index a77a31f528..0000000000--- a/app/src/components/settings/panels/MemoryEngineErrorAlert.test.tsx+++ /dev/null@@ -1,49 +0,0 @@-/**- * MemoryEngineErrorAlert: the shared top-up / sign-in / unavailable states that- * the engine panel, Brain and the memory data panel reuse.- */-import { screen } from '@testing-library/react';-import { describe, expect, test } from 'vitest';--import { renderWithProviders } from '../../../test/test-utils';-import MemoryEngineErrorAlert from './MemoryEngineErrorAlert';--describe('MemoryEngineErrorAlert', () => {- test('a hosted 402 shows the top-up state with a billing link', () => {- renderWithProviders(- <MemoryEngineErrorAlert error="INSUFFICIENT_CREDITS: the memory engine is out of credits" />- );- expect(screen.getByTestId('memory-engine-error-insufficient_credits')).toBeInTheDocument();- expect(screen.getByTestId('memory-engine-open-billing')).toBeInTheDocument();- });-- test('an expired session shows the sign-in state', () => {- renderWithProviders(- <MemoryEngineErrorAlert error={new Error('SESSION_EXPIRED: no TinyHumans session')} />- );- expect(screen.getByTestId('memory-engine-error-session_expired')).toBeInTheDocument();- expect(screen.getByTestId('memory-engine-sign-in')).toBeInTheDocument();- });-- test('a refused credential is its own state, never a sign-in prompt', () => {- renderWithProviders(- <MemoryEngineErrorAlert error="MEMORY_FORBIDDEN: the memory engine refused this credential" />- );- expect(screen.getByTestId('memory-engine-error-memory_forbidden')).toBeInTheDocument();- expect(screen.queryByTestId('memory-engine-sign-in')).toBeNull();- });-- test('an unreachable engine shows the unavailable state', () => {- renderWithProviders(- <MemoryEngineErrorAlert error="MEMORY_UNREACHABLE: the memory engine is not available right now" />- );- expect(screen.getByTestId('memory-engine-error-backend_unavailable')).toBeInTheDocument();- });-- test('any other error shows the caller fallback text and no action', () => {- renderWithProviders(<MemoryEngineErrorAlert error="boom" fallbackText="Graph failed" />);- expect(screen.getByTestId('memory-engine-error-other')).toHaveTextContent('Graph failed');- expect(screen.queryByTestId('memory-engine-open-billing')).toBeNull();- expect(screen.queryByTestId('memory-engine-sign-in')).toBeNull();- });-});diff --git a/app/src/components/settings/panels/MemoryEngineErrorAlert.tsx b/app/src/components/settings/panels/MemoryEngineErrorAlert.tsxdeleted file mode 100644index 8fe0a406aa..0000000000--- a/app/src/components/settings/panels/MemoryEngineErrorAlert.tsx+++ /dev/null@@ -1,74 +0,0 @@-import { useNavigate } from 'react-router-dom';--import { useT } from '../../../lib/i18n/I18nContext';-import { Alert, AlertDescription, Button } from '../../ui';-import { classifyMemoryEngineError, type MemoryEngineErrorKind } from './memoryEngineUtils';--/** Friendly text for a classified engine error; generic otherwise. */-export function useMemoryEngineErrorText(): (kind: MemoryEngineErrorKind) => string {- const { t } = useT();- return kind =>- kind === 'insufficient_credits'- ? t('memoryEngine.error.insufficientCredits')- : kind === 'session_expired'- ? t('memoryEngine.error.sessionExpired')- : kind === 'memory_forbidden'- ? t('memoryEngine.error.forbidden')- : kind === 'backend_unavailable'- ? t('memoryEngine.error.backendUnavailable')- : t('memoryEngine.error.generic');-}--interface MemoryEngineErrorAlertProps {- /** The raw error (Error, string or core message). */- error: unknown;- /** Kind already classified by the caller; derived from `error` when omitted. */- kind?: MemoryEngineErrorKind;- /** Shown instead of the generic text when the error is not an engine error. */- fallbackText?: string;-}--/**- * The top-up / sign-in / backend-unavailable states for a memory-engine error,- * shared by the engine panel and every memory view that surfaces core errors.- */-export default function MemoryEngineErrorAlert({- error,- kind,- fallbackText,-}: MemoryEngineErrorAlertProps) {- const { t } = useT();- const navigate = useNavigate();- const errorText = useMemoryEngineErrorText();- const resolved = kind ?? classifyMemoryEngineError(error);-- return (- <Alert variant="destructive" data-testid={`memory-engine-error-${resolved}`}>- <AlertDescription>- <span>{resolved === 'other' && fallbackText ? fallbackText : errorText(resolved)}</span>- {resolved === 'insufficient_credits' ? (- <Button- variant="tertiary"- size="xs"- className="ml-2"- analyticsId="memory-engine-open-billing"- data-testid="memory-engine-open-billing"- onClick={() => navigate('/settings/account')}>- {t('memoryEngine.error.openBilling')}- </Button>- ) : null}- {resolved === 'session_expired' ? (- <Button- variant="tertiary"- size="xs"- className="ml-2"- analyticsId="memory-engine-sign-in"- data-testid="memory-engine-sign-in"- onClick={() => navigate('/')}>- {t('memoryEngine.error.signIn')}- </Button>- ) : null}- </AlertDescription>- </Alert>- );-}diff --git a/app/src/components/settings/panels/MemoryEngineOption.tsx b/app/src/components/settings/panels/MemoryEngineOption.tsxdeleted file mode 100644index e349261676..0000000000--- a/app/src/components/settings/panels/MemoryEngineOption.tsx+++ /dev/null@@ -1,136 +0,0 @@-import { useT } from '../../../lib/i18n/I18nContext';-import type { MemoryEngineDescriptor } from '../../../utils/tauriCommands/memoryEngine';-import { Badge, NativeSelect, TextField } from '../../ui';-import { RadioGroupItem } from '../../ui/RadioGroup';--export interface EngineFormValues {- endpoint: string;- deployment: string;- apiKey: string;-}--interface MemoryEngineOptionProps {- engine: MemoryEngineDescriptor;- isActive: boolean;- isSelected: boolean;- /** A key is already stored for this engine (only ever true for the active one). */- keySaved: boolean;- /** Hosted engine while signed out: not selectable. */- disabledReason: 'signed_out' | null;- form: EngineFormValues;- onFormChange: (patch: Partial<EngineFormValues>) => void;-}--/** One radio row; the configuration form opens under the selected engine. */-export default function MemoryEngineOption({- engine,- isActive,- isSelected,- keySaved,- disabledReason,- form,- onFormChange,-}: MemoryEngineOptionProps) {- const { t } = useT();- const label = t(`memoryEngine.engine.${engine.id}.label`, engine.label);- const description = t(`memoryEngine.engine.${engine.id}.description`, engine.description);- const inputId = `memory-engine-${engine.id}`;- const showKey = engine.needs_key || engine.key_optional;-- return (- <div- data-testid={`memory-engine-option-${engine.id}`}- className="rounded-lg border border-line px-4 py-3">- <div className="flex items-start gap-3">- <RadioGroupItem- id={inputId}- value={engine.id}- data-testid={`memory-engine-radio-${engine.id}`}- disabled={disabledReason !== null}- className="mt-0.5"- />- <div className="min-w-0 flex-1">- <div className="flex flex-wrap items-center gap-2">- <label htmlFor={inputId} className="text-sm font-medium text-content">- {label}- </label>- {isActive ? <Badge variant="success">{t('memoryEngine.active')}</Badge> : null}- </div>- <p className="mt-0.5 text-xs leading-relaxed text-content-muted">{description}</p>- {engine.hosted ? (- <p className="mt-1 text-xs text-content-muted">- {t('memoryEngine.hostedNote')}- {disabledReason === 'signed_out' ? (- <span className="ml-1 font-medium text-coral-600" role="note">- {t('memoryEngine.signInRequired')}- </span>- ) : null}- </p>- ) : null}-- {isSelected && disabledReason === null ? (- <div className="mt-3 space-y-3" data-testid={`memory-engine-form-${engine.id}`}>- {engine.needs_endpoint ? (- <div>- <label- htmlFor={`${inputId}-endpoint`}- className="mb-1 block text-xs font-medium text-content-secondary">- {t('memoryEngine.endpoint')}- </label>- <TextField- id={`${inputId}-endpoint`}- mono- value={form.endpoint}- placeholder={engine.default_endpoint ?? 'https://'}- onChange={e => onFormChange({ endpoint: e.target.value })}- />- </div>- ) : null}- {engine.deployments.length > 0 ? (- <div>- <label- htmlFor={`${inputId}-deployment`}- className="mb-1 block text-xs font-medium text-content-secondary">- {t('memoryEngine.deployment')}- </label>- <NativeSelect- id={`${inputId}-deployment`}- value={form.deployment}- onChange={e => onFormChange({ deployment: e.target.value })}>- {engine.deployments.map(d => (- <option key={d} value={d}>- {t(`memoryEngine.deployment.${d}`, d)}- </option>- ))}- </NativeSelect>- </div>- ) : null}- {showKey ? (- <div>- <label- htmlFor={`${inputId}-key`}- className="mb-1 block text-xs font-medium text-content-secondary">- {engine.key_optional- ? t('memoryEngine.apiKeyOptional')- : t('memoryEngine.apiKey')}- </label>- <TextField- id={`${inputId}-key`}- type="password"- autoComplete="off"- value={form.apiKey}- placeholder={keySaved ? t('memoryEngine.keySavedPlaceholder') : ''}- onChange={e => onFormChange({ apiKey: e.target.value })}- />- {keySaved ? (- <p className="mt-1 text-xs text-content-muted">{t('memoryEngine.keySaved')}</p>- ) : null}- </div>- ) : null}- </div>- ) : null}- </div>- </div>- </div>- );-}diff --git a/app/src/components/settings/panels/MemoryEnginePanel.test.tsx b/app/src/components/settings/panels/MemoryEnginePanel.test.tsxdeleted file mode 100644index 204d905f1b..0000000000--- a/app/src/components/settings/panels/MemoryEnginePanel.test.tsx+++ /dev/null@@ -1,570 +0,0 @@-/**- * MemoryEnginePanel: engine list from the core, switching with and without- * copying memories (migration polling), error mapping, and signed-out gating- * of hosted engines.- */-import { act, fireEvent, screen, waitFor } from '@testing-library/react';-import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';--import { renderWithProviders } from '../../../test/test-utils';-import type {- MemoryEngineDescriptor,- MemoryEngineState,-} from '../../../utils/tauriCommands/memoryEngine';-import { resetMemoryEngineCacheForTests } from '../../intelligence/useMemoryEngineCapabilities';-import MemoryEnginePanel, {- copyCompletion,- MIGRATE_JOB_STORAGE_KEY,- MIGRATE_POLL_INTERVAL_MS,-} from './MemoryEnginePanel';--const hoisted = vi.hoisted(() => ({- list: vi.fn(),- get: vi.fn(),- set: vi.fn(),- migrate: vi.fn(),- status: vi.fn(),- cancel: vi.fn(),- storage: new Map<string, string>(),- track: vi.fn(),- auth: { isAuthenticated: true },-}));--vi.mock('../../../utils/tauriCommands/memoryEngine', () => ({- memoryEnginesList: (...a: unknown[]) => hoisted.list(...a),- memoryEngineGet: (...a: unknown[]) => hoisted.get(...a),- memoryEngineSet: (...a: unknown[]) => hoisted.set(...a),- memoryEngineMigrate: (...a: unknown[]) => hoisted.migrate(...a),- memoryEngineMigrateStatus: (...a: unknown[]) => hoisted.status(...a),- memoryEngineMigrateCancel: (...a: unknown[]) => hoisted.cancel(...a),-}));--vi.mock('../../../store/userScopedStorage', () => ({- userScopedStorage: {- getItem: async (k: string) => hoisted.storage.get(k) ?? null,- setItem: async (k: string, v: string) => {- hoisted.storage.set(k, v);- },- removeItem: async (k: string) => {- hoisted.storage.delete(k);- },- },-}));--vi.mock('../../../services/analytics', () => ({- trackAnalyticsEvent: (...a: unknown[]) => hoisted.track(...a),-}));--vi.mock('../../../providers/CoreStateProvider', () => ({- useCoreState: () => ({ snapshot: { auth: hoisted.auth, sessionToken: 'jwt' } }),-}));--vi.mock('../../../utils/localSession', () => ({ isLocalSessionToken: () => false }));--vi.mock('../hooks/useSettingsNavigation', () => ({- useSettingsNavigation: () => ({ navigateBack: vi.fn(), breadcrumbs: [] }),-}));--function engine(- id: string,- overrides: Partial<MemoryEngineDescriptor> = {}-): MemoryEngineDescriptor {- return {- id,- label: id,- description: `${id} description`,- needs_endpoint: false,- needs_key: false,- key_optional: false,- deployments: [],- default_endpoint: null,- hosted: false,- capabilities: ['recall', 'graph'],- ...overrides,- };-}--const ENGINES: MemoryEngineDescriptor[] = [- engine('tinymemory'),- engine('tinyhumans', { hosted: true, capabilities: ['recall'] }),- engine('supermemory', { needs_key: true }),- engine('mem0', {- needs_endpoint: true,- needs_key: true,- key_optional: true,- deployments: ['cloud', 'self_hosted'],- default_endpoint: 'https://api.mem0.ai',- capabilities: ['recall'],- }),-];--function state(overrides: Partial<MemoryEngineState> = {}): MemoryEngineState {- return {- driver: 'tinymemory',- endpoint: null,- deployment: null,- has_credential: false,- class: 'local',- fell_back_from: null,- last_error: null,- ...overrides,- };-}--async function renderPanel() {- renderWithProviders(<MemoryEnginePanel />);- await screen.findByTestId('memory-engine-option-tinymemory');-}--const pick = (id: string) =>- fireEvent.click(screen.getByRole('radio', { name: new RegExp(id, 'i') }));--beforeEach(() => {- vi.clearAllMocks();- resetMemoryEngineCacheForTests();- hoisted.storage.clear();- hoisted.auth = { isAuthenticated: true };- hoisted.list.mockResolvedValue({ engines: ENGINES, active: 'tinymemory' });- hoisted.get.mockResolvedValue(state());-});--afterEach(() => {- vi.useRealTimers();-});--describe('MemoryEnginePanel', () => {- test('renders the engines returned by the core and marks the active one', async () => {- await renderPanel();- for (const e of ENGINES) {- expect(screen.getByTestId(`memory-engine-option-${e.id}`)).toBeInTheDocument();- }- const active = screen.getByTestId('memory-engine-option-tinymemory');- expect(active).toHaveTextContent('Active');- expect(screen.getByTestId('memory-engine-option-mem0')).not.toHaveTextContent('Active');- // Nothing to switch to until another engine is picked.- expect(screen.getByTestId('memory-engine-switch')).toBeDisabled();- });-- test('switch without copying calls engine_set and tracks only the engine id', async () => {- hoisted.set.mockResolvedValue(state({ driver: 'supermemory', has_credential: true }));- await renderPanel();- pick('supermemory');-- const keyInput = screen.getByLabelText('API key');- expect(keyInput).toHaveAttribute('type', 'password');- expect(screen.getByTestId('memory-engine-switch')).toBeDisabled();- fireEvent.change(keyInput, { target: { value: 'sk-secret' } });- fireEvent.click(screen.getByTestId('memory-engine-switch'));-- expect(await screen.findByTestId('memory-engine-switch-dialog')).toBeInTheDocument();- expect(screen.getByText('Copy my existing memories to the new engine?')).toBeInTheDocument();- // Brain features the target lacks are listed.- hoisted.get.mockResolvedValue(state({ driver: 'supermemory', has_credential: true }));- fireEvent.click(screen.getByTestId('memory-engine-switch-only'));-- await waitFor(() =>- expect(hoisted.set).toHaveBeenCalledWith({ driver: 'supermemory', api_key: 'sk-secret' })- );- expect(hoisted.migrate).not.toHaveBeenCalled();- await waitFor(() =>- expect(hoisted.track).toHaveBeenCalledWith('memory_engine_switched', {- engine: 'supermemory',- })- );- await waitFor(() =>- expect(screen.queryByTestId('memory-engine-switch-dialog')).not.toBeInTheDocument()- );- // The stored key is never echoed back into the field.- expect(screen.getByLabelText('API key')).toHaveValue('');- expect(screen.getByText('A key is saved. Leave blank to keep it.')).toBeInTheDocument();- });-- test('prefills the endpoint and offers deployments for engines that need them', async () => {- await renderPanel();- pick('mem0');- expect(screen.getByLabelText('Endpoint')).toHaveValue('https://api.mem0.ai');- expect(screen.getByLabelText('Deployment')).toHaveValue('cloud');- // Key is optional for this engine, so switching is allowed without one.- expect(screen.getByTestId('memory-engine-switch')).toBeEnabled();- });-- test('copy & switch polls migration progress, then refreshes', async () => {- vi.useFakeTimers();- hoisted.migrate.mockResolvedValue({ job_id: 'job-1' });- hoisted.status- .mockResolvedValueOnce({ state: 'running', copied: 2, total: 4, error: null })- .mockResolvedValueOnce({ state: 'done', copied: 4, total: 4, error: null });- renderWithProviders(<MemoryEnginePanel />);- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- pick('mem0');- fireEvent.click(screen.getByTestId('memory-engine-switch'));- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- expect(screen.getByTestId('memory-engine-lacking')).toHaveTextContent('graph');-- hoisted.get.mockResolvedValue(state({ driver: 'mem0', endpoint: 'https://api.mem0.ai' }));- fireEvent.click(screen.getByTestId('memory-engine-copy-switch'));- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- expect(hoisted.migrate).toHaveBeenCalledWith(- { driver: 'mem0', endpoint: 'https://api.mem0.ai', deployment: 'cloud' },- { replayContent: true }- );- expect(screen.getByTestId('memory-engine-progress')).toBeInTheDocument();-- await act(async () => {- await vi.advanceTimersByTimeAsync(MIGRATE_POLL_INTERVAL_MS);- });- expect(hoisted.status).toHaveBeenCalledWith('job-1');- expect(screen.getByTestId('memory-engine-progress')).toHaveTextContent('Copied 2 of 4');-- await act(async () => {- await vi.advanceTimersByTimeAsync(MIGRATE_POLL_INTERVAL_MS);- });- expect(hoisted.track).toHaveBeenCalledWith('memory_engine_switched', { engine: 'mem0' });- expect(screen.queryByTestId('memory-engine-switch-dialog')).not.toBeInTheDocument();- expect(hoisted.get).toHaveBeenCalledTimes(2);- });-- test('a failed migration shows an error and keeps the previous engine', async () => {- vi.useFakeTimers();- hoisted.migrate.mockResolvedValue({ job_id: 'job-2' });- hoisted.status.mockResolvedValue({ state: 'failed', copied: 1, total: 4, error: 'boom' });- renderWithProviders(<MemoryEnginePanel />);- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- pick('mem0');- fireEvent.click(screen.getByTestId('memory-engine-switch'));- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- fireEvent.click(screen.getByTestId('memory-engine-copy-switch'));- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- await act(async () => {- await vi.advanceTimersByTimeAsync(MIGRATE_POLL_INTERVAL_MS);- });- expect(screen.getByTestId('memory-engine-error-other')).toBeInTheDocument();- expect(hoisted.track).not.toHaveBeenCalled();- });-- test('insufficient credits maps to a friendly state with a billing link', async () => {- hoisted.set.mockRejectedValue(new Error('INSUFFICIENT_CREDITS: balance is zero'));- await renderPanel();- pick('tinyhumans');- fireEvent.click(screen.getByTestId('memory-engine-switch'));- fireEvent.click(await screen.findByTestId('memory-engine-switch-only'));-- const alert = await screen.findByTestId('memory-engine-error-insufficient_credits');- expect(alert).toHaveTextContent('out of OpenHuman credits');- expect(screen.getByTestId('memory-engine-open-billing')).toBeInTheDocument();- expect(hoisted.track).not.toHaveBeenCalled();- });-- test('session expired prompts to sign in', async () => {- hoisted.set.mockRejectedValue(new Error('SESSION_EXPIRED: token rejected'));- await renderPanel();- pick('tinyhumans');- fireEvent.click(screen.getByTestId('memory-engine-switch'));- fireEvent.click(await screen.findByTestId('memory-engine-switch-only'));- expect(await screen.findByTestId('memory-engine-error-session_expired')).toBeInTheDocument();- expect(screen.getByTestId('memory-engine-sign-in')).toBeInTheDocument();- });-- test('hosted engines are disabled when signed out', async () => {- hoisted.auth = { isAuthenticated: false };- await renderPanel();- const hosted = screen.getByTestId('memory-engine-option-tinyhumans');- expect(hosted).toHaveTextContent('Billed through your OpenHuman plan or credits.');- expect(hosted).toHaveTextContent('Sign in to use this engine.');- expect(screen.getByRole('radio', { name: /tinyhumans/i })).toBeDisabled();- // Non-hosted engines stay selectable.- expect(screen.getByRole('radio', { name: /supermemory/i })).toBeEnabled();- });-- test('a failed bind says memory is paused (not local) and shows the reason', async () => {- hoisted.get.mockResolvedValue(- state({ driver: 'null', fell_back_from: 'mem0', last_error: 'engine credential unavailable' })- );- await renderPanel();- const warning = screen.getByTestId('memory-engine-fallback');- expect(warning).toHaveTextContent('Memory is paused');- expect(warning).toHaveTextContent('mem0');- expect(warning).toHaveTextContent('engine credential unavailable');- expect(warning).not.toHaveTextContent(/local memory/i);- });-- test('cancel stops a running copy and leaves the panel on the previous engine', async () => {- vi.useFakeTimers();- hoisted.migrate.mockResolvedValue({ job_id: 'job-c' });- hoisted.cancel.mockResolvedValue({ cancelled: true });- hoisted.status- .mockResolvedValueOnce({ state: 'running', copied: 1, total: null, error: null })- .mockResolvedValue({ state: 'cancelled', copied: 1, total: null, error: null });- renderWithProviders(<MemoryEnginePanel />);- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- pick('mem0');- fireEvent.click(screen.getByTestId('memory-engine-switch'));- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- fireEvent.click(screen.getByTestId('memory-engine-copy-switch'));- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- fireEvent.click(screen.getByTestId('memory-engine-cancel-migration'));- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- expect(hoisted.cancel).toHaveBeenCalledWith('job-c');-- for (let i = 0; i < 2; i += 1) {- await act(async () => {- await vi.advanceTimersByTimeAsync(MIGRATE_POLL_INTERVAL_MS);- });- }- expect(screen.queryByTestId('memory-engine-switch-dialog')).not.toBeInTheDocument();- expect(hoisted.track).not.toHaveBeenCalled();- expect(hoisted.storage.has(MIGRATE_JOB_STORAGE_KEY)).toBe(false);- });-- test('the running migration job id is persisted and resumed on return', async () => {- vi.useFakeTimers();- hoisted.storage.set(- MIGRATE_JOB_STORAGE_KEY,- JSON.stringify({ jobId: 'job-r', driver: 'mem0' })- );- hoisted.status.mockResolvedValue({ state: 'running', copied: 3, total: null, error: null });- renderWithProviders(<MemoryEnginePanel />);- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- expect(hoisted.status).toHaveBeenCalledWith('job-r');- expect(screen.getByTestId('memory-engine-progress')).toHaveTextContent('Copied 3 memories');- });-- test('a stored job that already finished is cleared without a dialog', async () => {- hoisted.storage.set(- MIGRATE_JOB_STORAGE_KEY,- JSON.stringify({ jobId: 'job-x', driver: 'mem0' })- );- hoisted.status.mockResolvedValue({ state: 'failed', copied: 0, total: null, error: 'x' });- await renderPanel();- await waitFor(() => expect(hoisted.storage.has(MIGRATE_JOB_STORAGE_KEY)).toBe(false));- expect(screen.queryByTestId('memory-engine-switch-dialog')).not.toBeInTheDocument();- });-- test('starting a copy persists the job id', async () => {- hoisted.migrate.mockResolvedValue({ job_id: 'job-p' });- hoisted.status.mockResolvedValue({ state: 'running', copied: 0, total: null, error: null });- await renderPanel();- pick('mem0');- fireEvent.click(screen.getByTestId('memory-engine-switch'));- fireEvent.click(await screen.findByTestId('memory-engine-copy-switch'));- await waitFor(() => expect(hoisted.storage.get(MIGRATE_JOB_STORAGE_KEY)).toContain('job-p'));- expect(JSON.parse(hoisted.storage.get(MIGRATE_JOB_STORAGE_KEY) ?? '{}')).toEqual({- jobId: 'job-p',- driver: 'mem0',- replayContent: true,- });- });-- test('a resumed migration keeps the replay choice it was started with', async () => {- vi.useFakeTimers();- hoisted.storage.set(- MIGRATE_JOB_STORAGE_KEY,- JSON.stringify({ jobId: 'job-o', driver: 'mem0', replayContent: false })- );- const skippedContent = {- step: 'content',- skipped_because: 'the caller chose not to re-send content',- read: 0,- written: 0,- unchanged: 0,- failed: 0,- errors: [],- };- hoisted.status- .mockResolvedValueOnce({ state: 'running', copied: 1, total: null, error: null })- .mockResolvedValue({- state: 'done',- copied: 1,- total: null,- error: null,- steps: [skippedContent],- });- renderWithProviders(<MemoryEnginePanel />);- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- expect(screen.getByTestId('memory-engine-progress')).toBeInTheDocument();- hoisted.get.mockResolvedValue(state({ driver: 'mem0', endpoint: 'https://api.mem0.ai' }));- await act(async () => {- await vi.advanceTimersByTimeAsync(MIGRATE_POLL_INTERVAL_MS);- });- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- expect(- screen.queryByTestId('memory-engine-left-behind'),- 'content the user chose not to re-send is not reported as left behind'- ).not.toBeInTheDocument();- });-- test('the copy can leave synced content behind, and the hint shows for hosted engines', async () => {- vi.useFakeTimers();- hoisted.migrate.mockResolvedValue({ job_id: 'job-h' });- hoisted.status.mockResolvedValue({ state: 'running', copied: 0, total: null, error: null });- renderWithProviders(<MemoryEnginePanel />);- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- pick('tinyhumans');- fireEvent.click(screen.getByTestId('memory-engine-switch'));- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- const dialog = screen.getByTestId('memory-engine-switch-dialog');- expect(dialog).toHaveTextContent('conversation history');- expect(dialog).toHaveTextContent('OpenHuman credits');- const replay = screen.getByTestId('memory-engine-replay-content');- expect(replay).toBeChecked();- fireEvent.click(replay);- expect(replay).not.toBeChecked();- fireEvent.click(screen.getByTestId('memory-engine-copy-switch'));- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- expect(hoisted.migrate).toHaveBeenCalledWith(- { driver: 'tinyhumans' },- { replayContent: false }- );- });-- test('the progress line names the step under way', async () => {- vi.useFakeTimers();- hoisted.migrate.mockResolvedValue({ job_id: 'job-s' });- hoisted.status.mockResolvedValue({- state: 'running',- copied: 12,- total: null,- error: null,- step: 'episodic',- step_read: 40,- step_written: 38,- steps: [],- });- renderWithProviders(<MemoryEnginePanel />);- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- pick('mem0');- fireEvent.click(screen.getByTestId('memory-engine-switch'));- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- fireEvent.click(screen.getByTestId('memory-engine-copy-switch'));- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- await act(async () => {- await vi.advanceTimersByTimeAsync(MIGRATE_POLL_INTERVAL_MS);- });- expect(screen.getByTestId('memory-engine-progress-line')).toHaveTextContent(- 'Copying conversation history… 40 copied so far'- );- });-- test('after the switch, what the new engine could not take is named', async () => {- vi.useFakeTimers();- hoisted.migrate.mockResolvedValue({ job_id: 'job-l' });- const skipped = (step: string) => ({- step,- skipped_because: 'the target does not serve it',- read: 0,- written: 0,- unchanged: 0,- failed: 0,- errors: [],- });- hoisted.status.mockResolvedValue({- state: 'done',- copied: 4,- total: null,- error: null,- steps: [- skipped('goals'),- skipped('profile'),- { ...skipped('content'), skipped_because: null, read: 5, written: 3, failed: 2 },- ],- });- renderWithProviders(<MemoryEnginePanel />);- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- pick('mem0');- fireEvent.click(screen.getByTestId('memory-engine-switch'));- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- hoisted.get.mockResolvedValue(state({ driver: 'mem0', endpoint: 'https://api.mem0.ai' }));- fireEvent.click(screen.getByTestId('memory-engine-copy-switch'));- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- await act(async () => {- await vi.advanceTimersByTimeAsync(MIGRATE_POLL_INTERVAL_MS);- });- await act(async () => {- await vi.advanceTimersByTimeAsync(0);- });- expect(screen.getByTestId('memory-engine-left-behind')).toHaveTextContent(- 'goals, learned profile'- );- expect(screen.getByTestId('memory-engine-content-refused')).toHaveTextContent('(2)');- });-});--describe('copyCompletion', () => {- const step = (name: 'content' | 'goals', skipped: string | null, failed = 0) => ({- step: name,- skipped_because: skipped,- read: 0,- written: 0,- unchanged: 0,- failed,- errors: [],- });- const done = (steps: ReturnType<typeof step>[]) => ({- state: 'done' as const,- copied: 0,- total: null,- error: null,- steps,- });-- test('content the user chose not to re-send is not left behind', () => {- const status = done([- step('content', 'the caller chose not to re-send content'),- step('goals', null),- ]);- expect(copyCompletion(status, false)).toEqual({ leftBehind: [], refused: 0 });- expect(copyCompletion(status, true)).toEqual({ leftBehind: ['content'], refused: 0 });- });-- test('content the new engine refused is counted', () => {- const status = done([- step('goals', 'the target does not serve goals'),- step('content', null, 3),- ]);- expect(copyCompletion(status, true)).toEqual({ leftBehind: ['goals'], refused: 3 });- });-});diff --git a/app/src/components/settings/panels/MemoryEnginePanel.tsx b/app/src/components/settings/panels/MemoryEnginePanel.tsxdeleted file mode 100644index b4b28fa1b0..0000000000--- a/app/src/components/settings/panels/MemoryEnginePanel.tsx+++ /dev/null@@ -1,504 +0,0 @@-/**- * Memory engine settings: pick exactly one active memory engine.- *- * The engine list comes from `openhuman.memory_engines_list`; the panel only- * carries fallback labels keyed by engine id (i18n). Switching either copies- * the existing memories first (`memory_engine_migrate`, polled) or just flips- * the driver (`memory_engine_set`).- *- * debug logging: DEBUG=settings:memory-engine- */-import debug from 'debug';-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';--import { useT } from '../../../lib/i18n/I18nContext';-import { useCoreState } from '../../../providers/CoreStateProvider';-import { trackAnalyticsEvent } from '../../../services/analytics';-import { userScopedStorage } from '../../../store/userScopedStorage';-import { isLocalSessionToken } from '../../../utils/localSession';-import {- type MemoryEngineDescriptor,- memoryEngineMigrate,- memoryEngineMigrateCancel,- memoryEngineMigrateStatus,- type MemoryEngineMigrateStatus,- type MemoryEngineMigrateStep,- memoryEngineSet,- type MemoryEngineState,- type MemoryEngineTarget,-} from '../../../utils/tauriCommands/memoryEngine';-import {- invalidateMemoryEngine,- useMemoryEngine,-} from '../../intelligence/useMemoryEngineCapabilities';-import { Alert, AlertDescription, Button, CenteredLoadingState } from '../../ui';-import { RadioGroupRoot } from '../../ui/RadioGroup';-import SettingsPanel from '../layout/SettingsPanel';-import MemoryEngineErrorAlert from './MemoryEngineErrorAlert';-import MemoryEngineOption, { type EngineFormValues } from './MemoryEngineOption';-import MemoryEngineSwitchDialog from './MemoryEngineSwitchDialog';-import {- classifyMemoryEngineError,- humanizeCapability,- type MemoryEngineErrorKind,- missingCapabilities,-} from './memoryEngineUtils';--const log = debug('settings:memory-engine');--/**- * What a finished copy could not carry: the steps it skipped because an engine- * does not serve them, and the content the new engine refused. Content the- * user chose not to re-send is not left behind: they asked for that.- */-export interface CopyCompletion {- leftBehind: MemoryEngineMigrateStep[];- refused: number;-}--export function copyCompletion(- status: MemoryEngineMigrateStatus,- replayContent: boolean-): CopyCompletion {- const steps = status.steps ?? [];- return {- leftBehind: steps- .filter(step => step.skipped_because !== null)- .filter(step => replayContent || step.step !== 'content')- .map(step => step.step),- // Only re-sent content may fail without holding the switch back, so on a- // finished job this is the content the new engine refused.- refused: steps.reduce((sum, step) => sum + step.failed, 0),- };-}--/** How often a running migration is polled. */-export const MIGRATE_POLL_INTERVAL_MS = 1000;--/** userScopedStorage key of the running migration `{ jobId, driver, replayContent }`. */-export const MIGRATE_JOB_STORAGE_KEY = 'memoryEngine.migrateJob';--interface StoredJob {- jobId: string;- driver: string;- /** The content re-send choice the job was started with. */- replayContent: boolean;-}--async function storeJob(job: StoredJob): Promise<void> {- await userScopedStorage.setItem(MIGRATE_JOB_STORAGE_KEY, JSON.stringify(job));-}--async function clearStoredJob(): Promise<void> {- await userScopedStorage.removeItem(MIGRATE_JOB_STORAGE_KEY);-}--async function readStoredJob(): Promise<StoredJob | null> {- try {- const raw = await userScopedStorage.getItem(MIGRATE_JOB_STORAGE_KEY);- if (!raw) return null;- const parsed = JSON.parse(raw) as {- jobId?: unknown;- driver?: unknown;- replayContent?: unknown;- };- return typeof parsed.jobId === 'string' && typeof parsed.driver === 'string'- ? {- jobId: parsed.jobId,- driver: parsed.driver,- // A job stored before the choice existed re-sent content.- replayContent: parsed.replayContent !== false,- }- : null;- } catch {- return null;- }-}--interface PanelError {- kind: MemoryEngineErrorKind;- message: string;-}--function toPanelError(err: unknown): PanelError {- return {- kind: classifyMemoryEngineError(err),- message: err instanceof Error ? err.message : String(err ?? ''),- };-}--function formFor(- engine: MemoryEngineDescriptor,- current: MemoryEngineState | null-): EngineFormValues {- const same = current?.driver === engine.id;- return {- endpoint: (same ? current?.endpoint : null) ?? engine.default_endpoint ?? '',- deployment: (same ? current?.deployment : null) ?? engine.deployments[0] ?? '',- apiKey: '',- };-}--export default function MemoryEnginePanel() {- const { t } = useT();- const { snapshot } = useCoreState();- const signedIn = snapshot.auth.isAuthenticated && !isLocalSessionToken(snapshot.sessionToken);-- // One shared engines_list + engine_get for this view (and the Brain row / gates).- const { engines, current, loading, error: loadError, refresh } = useMemoryEngine();- const [selectedId, setSelectedId] = useState<string | null>(null);- const [forms, setForms] = useState<Record<string, EngineFormValues>>({});- const [error, setError] = useState<PanelError | null>(null);- const [saving, setSaving] = useState(false);- const [confirming, setConfirming] = useState(false);- const [jobId, setJobId] = useState<string | null>(null);- const [migration, setMigration] = useState<MemoryEngineMigrateStatus | null>(null);- // Re-send synced content with the copy (the content step); on unless the user opts out.- const [replayContent, setReplayContent] = useState(true);- // What a finished copy could not carry, shown once the switch is done.- const [completion, setCompletion] = useState<CopyCompletion | null>(null);- // The replay choice the running job was started with (polling outlives the toggle).- const replayRequestedRef = useRef(true);- const mounted = useRef(true);- // Driver the running migration is copying into (finishSwitch needs it after polling).- const targetDriverRef = useRef<string>('');-- useEffect(() => {- mounted.current = true;- return () => {- mounted.current = false;- };- }, []);-- const load = useCallback(async () => {- await refresh();- }, [refresh]);-- // Always show fresh data on entry, then pick the active engine once known.- useEffect(() => {- void refresh();- }, [refresh]);-- useEffect(() => {- if (current) setSelectedId(prev => prev ?? current.driver);- }, [current]);-- // Resume a migration that was running when the panel was left.- useEffect(() => {- let cancelled = false;- void (async () => {- const stored = await readStoredJob();- if (!stored || cancelled) return;- try {- const status = await memoryEngineMigrateStatus(stored.jobId);- if (cancelled || !mounted.current) return;- if (status.state === 'running') {- log(- 'resuming migration job=%s driver=%s replay_content=%s',- stored.jobId,- stored.driver,- stored.replayContent- );- targetDriverRef.current = stored.driver;- replayRequestedRef.current = stored.replayContent;- setReplayContent(stored.replayContent);- setSelectedId(stored.driver);- setMigration(status);- setSaving(true);- setConfirming(true);- setJobId(stored.jobId);- return;- }- await clearStoredJob();- if (status.state === 'done') await load();- } catch {- await clearStoredJob();- }- })();- return () => {- cancelled = true;- };- }, [load]);-- const activeId = current?.driver ?? null;- const activeEngine = engines.find(e => e.id === activeId);- const selected = engines.find(e => e.id === selectedId);- const form = selected ? (forms[selected.id] ?? formFor(selected, current)) : null;- const isSameDriver = selected?.id === activeId;- const keySaved = Boolean(isSameDriver && current?.has_credential);-- const patchForm = (patch: Partial<EngineFormValues>) => {- if (!selected || !form) return;- setForms(prev => ({ ...prev, [selected.id]: { ...form, ...patch } }));- };-- const hostedBlocked = Boolean(selected?.hosted && !signedIn);- const missingRequired = useMemo(() => {- if (!selected || !form) return false;- if (selected.needs_endpoint && !form.endpoint.trim()) return true;- if (selected.needs_key && !selected.key_optional && !form.apiKey.trim() && !keySaved) {- return true;- }- return false;- }, [selected, form, keySaved]);-- const dirty = useMemo(() => {- if (!isSameDriver || !form || !current) return false;- const endpointChanged =- selected?.needs_endpoint === true && form.endpoint !== (current.endpoint ?? '');- const deploymentChanged =- (selected?.deployments.length ?? 0) > 0 && form.deployment !== (current.deployment ?? '');- return form.apiKey.trim() !== '' || endpointChanged || deploymentChanged;- }, [isSameDriver, form, current, selected]);-- const buildTarget = (): MemoryEngineTarget | null => {- if (!selected || !form) return null;- const target: MemoryEngineTarget = { driver: selected.id };- if (selected.needs_endpoint && form.endpoint.trim()) target.endpoint = form.endpoint.trim();- if (selected.deployments.length > 0 && form.deployment) target.deployment = form.deployment;- if ((selected.needs_key || selected.key_optional) && form.apiKey.trim()) {- target.api_key = form.apiKey.trim();- }- return target;- };-- const finishSwitch = useCallback(- async (driver: string) => {- trackAnalyticsEvent('memory_engine_switched', { engine: driver });- setConfirming(false);- setJobId(null);- setMigration(null);- void clearStoredJob();- setForms({});- setSelectedId(driver);- await load();- },- [load]- );-- const doSet = async () => {- const target = buildTarget();- if (!target) return;- setSaving(true);- setError(null);- try {- await memoryEngineSet(target);- log('engine set driver=%s', target.driver);- invalidateMemoryEngine();- await refresh();- if (!mounted.current) return;- await finishSwitch(target.driver);- } catch (err) {- log('engine set failed: %o', err);- if (mounted.current) {- setConfirming(false);- setError(toPanelError(err));- }- } finally {- if (mounted.current) setSaving(false);- }- };-- const doMigrate = async () => {- const target = buildTarget();- if (!target) return;- setSaving(true);- setError(null);- try {- targetDriverRef.current = target.driver;- setCompletion(null);- replayRequestedRef.current = replayContent;- const { job_id } = await memoryEngineMigrate(target, { replayContent });- log(- 'migrate started job=%s driver=%s replay_content=%s',- job_id,- target.driver,- replayContent- );- if (!mounted.current) return;- setMigration({ state: 'running', copied: 0, total: null, error: null });- setJobId(job_id);- void storeJob({ jobId: job_id, driver: target.driver, replayContent });- } catch (err) {- log('migrate start failed: %o', err);- if (mounted.current) {- setConfirming(false);- setError(toPanelError(err));- setSaving(false);- }- }- };-- // Poll the migration job until it settles.- useEffect(() => {- if (!jobId) return;- let cancelled = false;- let timer: ReturnType<typeof setTimeout> | undefined;- const tick = async () => {- try {- const status = await memoryEngineMigrateStatus(jobId);- if (cancelled) return;- setMigration(status);- if (status.state === 'running') {- timer = setTimeout(() => void tick(), MIGRATE_POLL_INTERVAL_MS);- return;- }- setSaving(false);- if (status.state === 'done') {- log('migrate done job=%s copied=%d', jobId, status.copied);- invalidateMemoryEngine();- await finishSwitch(targetDriverRef.current);- if (mounted.current) setCompletion(copyCompletion(status, replayRequestedRef.current));- } else if (status.state === 'cancelled') {- log('migrate cancelled job=%s', jobId);- void clearStoredJob();- setJobId(null);- setConfirming(false);- setMigration(null);- } else {- log('migrate failed job=%s', jobId);- void clearStoredJob();- setJobId(null);- setConfirming(false);- setMigration(null);- setError(toPanelError(status.error ?? 'migration failed'));- }- } catch (err) {- if (cancelled) return;- log('migrate status failed: %o', err);- void clearStoredJob();- setSaving(false);- setJobId(null);- setConfirming(false);- setMigration(null);- setError(toPanelError(err));- }- };- timer = setTimeout(() => void tick(), MIGRATE_POLL_INTERVAL_MS);- return () => {- cancelled = true;- if (timer) clearTimeout(timer);- };- }, [jobId, finishSwitch]);-- const doCancelMigration = async () => {- if (!jobId) return;- try {- await memoryEngineMigrateCancel(jobId);- log('cancel requested job=%s', jobId);- } catch (err) {- log('cancel failed: %o', err);- if (mounted.current) setError(toPanelError(err));- }- };-- const onSwitchClick = () => {- if (isSameDriver) {- void doSet();- } else {- setConfirming(true);- }- };-- const lacking = missingCapabilities(activeEngine, selected).map(humanizeCapability);- const switchDisabled =- saving || !selected || hostedBlocked || missingRequired || (isSameDriver && !dirty);-- return (- <SettingsPanel description={t('memoryEngine.description')}>- <div className="space-y-4" data-testid="memory-engine-panel">- {current?.fell_back_from || current?.last_error ? (- <Alert variant="warning" data-testid="memory-engine-fallback">- <AlertDescription>- {current.fell_back_from- ? t('memoryEngine.fallback')- .replace('{engine}', current.fell_back_from)- .replace('{reason}', current.last_error ?? '')- : t('memoryEngine.lastError')}- </AlertDescription>- </Alert>- ) : null}-- {completion && (completion.leftBehind.length > 0 || completion.refused > 0) ? (- <Alert variant="info" data-testid="memory-engine-left-behind">- <AlertDescription>- {completion.leftBehind.length > 0 ? (- <p>- {t('memoryEngine.notCopied').replace(- '{items}',- completion.leftBehind.map(step => t(`memoryEngine.step.${step}`)).join(', ')- )}- </p>- ) : null}- {completion.refused > 0 ? (- <p data-testid="memory-engine-content-refused">- {t('memoryEngine.contentRefused').replace('{count}', String(completion.refused))}- </p>- ) : null}- </AlertDescription>- </Alert>- ) : null}-- {error ? (- <MemoryEngineErrorAlert error={error.message} kind={error.kind} />- ) : loadError ? (- <MemoryEngineErrorAlert error={loadError} />- ) : null}-- {loading ? (- <CenteredLoadingState />- ) : (- <>- <RadioGroupRoot- aria-label={t('memoryEngine.title')}- value={selectedId ?? ''}- onValueChange={id => {- setSelectedId(id);- setError(null);- }}>- {engines.map(engine => (- <MemoryEngineOption- key={engine.id}- engine={engine}- isActive={engine.id === activeId}- isSelected={engine.id === selectedId}- keySaved={engine.id === activeId && Boolean(current?.has_credential)}- disabledReason={engine.hosted && !signedIn ? 'signed_out' : null}- form={engine.id === selectedId && form ? form : formFor(engine, current)}- onFormChange={patchForm}- />- ))}- </RadioGroupRoot>- <div className="flex justify-end">- <Button- variant="primary"- size="sm"- analyticsId="memory-engine-switch"- data-testid="memory-engine-switch"- disabled={switchDisabled}- onClick={onSwitchClick}>- {isSameDriver ? t('memoryEngine.save') : t('memoryEngine.switch')}- </Button>- </div>- </>- )}-- {confirming && selected ? (- <MemoryEngineSwitchDialog- targetLabel={t(`memoryEngine.engine.${selected.id}.label`, selected.label)}- lacking={lacking}- migration={migration}- busy={saving}- hosted={Boolean(selected.hosted)}- replayContent={replayContent}- onReplayContentChange={setReplayContent}- onCopy={() => void doMigrate()}- onSkipCopy={() => void doSet()}- onCancel={() => setConfirming(false)}- onCancelMigration={() => void doCancelMigration()}- />- ) : null}- </div>- </SettingsPanel>- );-}diff --git a/app/src/components/settings/panels/MemoryEngineSwitchDialog.tsx b/app/src/components/settings/panels/MemoryEngineSwitchDialog.tsxdeleted file mode 100644index 92a8e2a8e6..0000000000--- a/app/src/components/settings/panels/MemoryEngineSwitchDialog.tsx+++ /dev/null@@ -1,154 +0,0 @@-import { useT } from '../../../lib/i18n/I18nContext';-import type { MemoryEngineMigrateStatus } from '../../../utils/tauriCommands/memoryEngine';-import { Button, Checkbox, ModalShell, Progress } from '../../ui';--interface MemoryEngineSwitchDialogProps {- targetLabel: string;- /** Capabilities of the current engine that the target lacks (humanized). */- lacking: string[];- /** Set once "Copy & switch" started; swaps the choices for a progress view. */- migration: MemoryEngineMigrateStatus | null;- busy: boolean;- /** Whether the target bills for what it reads (TinyHumans memory). */- hosted: boolean;- /** Re-send synced content with the copy, so the new engine rebuilds its summaries. */- replayContent: boolean;- onReplayContentChange: (next: boolean) => void;- onCopy: () => void;- onSkipCopy: () => void;- onCancel: () => void;- /** Stops the running copy (the active engine is left unchanged). */- onCancelMigration: () => void;-}--/** "Copy my existing memories?" confirmation, then migration progress. */-export default function MemoryEngineSwitchDialog({- targetLabel,- lacking,- migration,- busy,- hosted,- replayContent,- onReplayContentChange,- onCopy,- onSkipCopy,- onCancel,- onCancelMigration,-}: MemoryEngineSwitchDialogProps) {- const { t } = useT();- const migrating = migration !== null && migration.state === 'running';- const percent =- migration && migration.total && migration.total > 0- ? Math.min(100, Math.round((migration.copied / migration.total) * 100))- : null;-- return (- <ModalShell- title={t('memoryEngine.dialog.title').replace('{engine}', targetLabel)}- titleId="memory-engine-switch-title"- testId="memory-engine-switch-dialog"- onClose={onCancel}- maxWidthClassName="max-w-md"- closePolicy={busy ? { escape: false, backdrop: false, button: false } : undefined}- footer={- migrating ? (- <div className="flex justify-end">- <Button- variant="tertiary"- size="sm"- analyticsId="memory-engine-cancel-migration"- data-testid="memory-engine-cancel-migration"- onClick={onCancelMigration}>- {t('memoryEngine.dialog.cancelMigration')}- </Button>- </div>- ) : (- <div className="flex flex-wrap justify-end gap-2">- <Button- variant="tertiary"- size="sm"- analyticsId="memory-engine-cancel"- data-testid="memory-engine-cancel"- disabled={busy}- onClick={onCancel}>- {t('common.cancel')}- </Button>- <Button- variant="secondary"- size="sm"- analyticsId="memory-engine-switch-only"- data-testid="memory-engine-switch-only"- disabled={busy}- onClick={onSkipCopy}>- {t('memoryEngine.dialog.switchOnly')}- </Button>- <Button- variant="primary"- size="sm"- analyticsId="memory-engine-copy-switch"- data-testid="memory-engine-copy-switch"- disabled={busy}- onClick={onCopy}>- {t('memoryEngine.dialog.copySwitch')}- </Button>- </div>- )- }>- <div className="space-y-3 text-sm text-content-secondary">- {migrating ? (- <div data-testid="memory-engine-progress" className="space-y-2">- <p>{t('memoryEngine.dialog.copying')}</p>- <Progress value={percent} aria-label={t('memoryEngine.dialog.copying')} />- <p className="text-xs text-content-muted" data-testid="memory-engine-progress-line">- {migration.step && migration.step !== 'records'- ? t('memoryEngine.dialog.stepProgress')- .replace('{step}', t(`memoryEngine.step.${migration.step}`))- .replace('{count}', String(migration.step_read ?? 0))- : migration.total !== null- ? t('memoryEngine.dialog.progress')- .replace('{copied}', String(migration.copied))- .replace('{total}', String(migration.total))- : t('memoryEngine.dialog.progressUnknown').replace(- '{copied}',- String(migration.copied)- )}- </p>- </div>- ) : (- <>- <p>{t('memoryEngine.dialog.body')}</p>- <p className="text-xs text-content-muted">{t('memoryEngine.dialog.copies')}</p>- <label className="flex items-start gap-2" htmlFor="memory-engine-replay-content">- <Checkbox- id="memory-engine-replay-content"- data-testid="memory-engine-replay-content"- checked={replayContent}- disabled={busy}- onCheckedChange={onReplayContentChange}- className="mt-0.5"- />- <span>- <span className="text-content">{t('memoryEngine.dialog.replayContent')}</span>- {hosted ? (- <span className="block text-xs text-content-muted">- {t('memoryEngine.dialog.replayContentHint')}- </span>- ) : null}- </span>- </label>- {lacking.length > 0 ? (- <div data-testid="memory-engine-lacking">- <p className="font-medium text-content">{t('memoryEngine.dialog.lacking')}</p>- <ul className="mt-1 list-disc pl-5 text-xs text-content-muted">- {lacking.map(cap => (- <li key={cap}>{cap}</li>- ))}- </ul>- </div>- ) : null}- </>- )}- </div>- </ModalShell>- );-}diff --git a/app/src/components/settings/panels/__tests__/MemoryDataPanel.test.tsx b/app/src/components/settings/panels/__tests__/MemoryDataPanel.test.tsxdeleted file mode 100644index 4026c440e0..0000000000--- a/app/src/components/settings/panels/__tests__/MemoryDataPanel.test.tsx+++ /dev/null@@ -1,126 +0,0 @@-/**- * Tests for the Settings → Memory Data panel.- *- * Verifies that all four memory-window preset buttons render, the memory- * sources section is present, and that a sync-connection error does not- * hide or disable the memory-window controls.- */-import { screen, waitFor } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { renderWithProviders } from '../../../../test/test-utils';-import MemoryDataPanel from '../MemoryDataPanel';--// ── Mocks ────────────────────────────────────────────────────────────────────--const hoisted = vi.hoisted(() => ({- mockGetConfig: vi.fn(),- mockUpdateMemorySettings: vi.fn(),- mockIsTauri: vi.fn(() => false),- mockMemoryTreeListChunks: vi.fn(),- mockMemoryTreeListSources: vi.fn(),- mockMemoryTreeTopEntities: vi.fn(),- mockMemoryTreeEntityIndexFor: vi.fn(),- mockMemoryTreeChunkScore: vi.fn(),- mockMemoryTreeChunksForEntity: vi.fn(),-}));--vi.mock('../../../../utils/tauriCommands', () => ({- // The status hook polls this alongside pipeline status; a factory mock- // without it turns every render into an unhandled rejection.- memoryNamespaceSummaries: vi.fn(async () => ({ namespaces: [], total_documents: 0 })),- isTauri: hoisted.mockIsTauri,- openhumanGetConfig: hoisted.mockGetConfig,- openhumanUpdateMemorySettings: hoisted.mockUpdateMemorySettings,- MEMORY_CONTEXT_WINDOWS: ['minimal', 'balanced', 'extended', 'maximum'],- memoryTreeListChunks: hoisted.mockMemoryTreeListChunks,- memoryTreeListSources: hoisted.mockMemoryTreeListSources,- memoryTreeTopEntities: hoisted.mockMemoryTreeTopEntities,- memoryTreeEntityIndexFor: hoisted.mockMemoryTreeEntityIndexFor,- memoryTreeChunkScore: hoisted.mockMemoryTreeChunkScore,- memoryTreeChunksForEntity: hoisted.mockMemoryTreeChunksForEntity,-}));--vi.mock('../../hooks/useSettingsNavigation', () => ({- useSettingsNavigation: () => ({ navigateBack: vi.fn(), breadcrumbs: [] }),-}));--// ── Helpers ───────────────────────────────────────────────────────────────────--const resolveConfigWith = (memory_window = 'balanced') => {- hoisted.mockGetConfig.mockResolvedValue({- result: {- config: { agent: { memory_window } },- workspace_dir: '/tmp/ws',- config_path: '/tmp/cfg.toml',- },- });-};--// ── Tests ─────────────────────────────────────────────────────────────────────--describe('MemoryDataPanel', () => {- beforeEach(() => {- hoisted.mockGetConfig.mockReset();- hoisted.mockUpdateMemorySettings.mockReset();- hoisted.mockIsTauri.mockReturnValue(false);- hoisted.mockMemoryTreeListChunks.mockReset();- hoisted.mockMemoryTreeListSources.mockReset();- hoisted.mockMemoryTreeTopEntities.mockReset();- hoisted.mockMemoryTreeEntityIndexFor.mockReset();- hoisted.mockMemoryTreeChunkScore.mockReset();- hoisted.mockMemoryTreeChunksForEntity.mockReset();-- // Default: no sources yet, no errors- hoisted.mockMemoryTreeListChunks.mockResolvedValue({ chunks: [], total: 0, cursor: null });- hoisted.mockMemoryTreeListSources.mockResolvedValue([]);- hoisted.mockMemoryTreeTopEntities.mockResolvedValue([]);- });-- it('renders all four preset buttons', async () => {- resolveConfigWith('balanced');- renderWithProviders(<MemoryDataPanel />);-- for (const label of ['Minimal', 'Balanced', 'Extended', 'Maximum']) {- expect(screen.getByText(label)).toBeInTheDocument();- }- });-- it('renders the memory sources section', async () => {- resolveConfigWith('balanced');- renderWithProviders(<MemoryDataPanel />);-- await waitFor(() => {- expect(screen.getByTestId('memory-sources')).toBeInTheDocument();- });- });-- it('renders in embedded mode (embedded padding branch)', async () => {- resolveConfigWith('balanced');- renderWithProviders(<MemoryDataPanel embedded />);-- // Body sections still render when embedded (exercises the embedded layout- // branch of the root container).- await waitFor(() => {- expect(screen.getByTestId('memory-sources')).toBeInTheDocument();- });- });-- it.skip('keeps all preset buttons accessible when sync connections returns an error', async () => {- resolveConfigWith('balanced');-- renderWithProviders(<MemoryDataPanel />);-- // Wait for the error state to appear in the sync connections section- await waitFor(() => {- expect(screen.getByText(/network timeout/i)).toBeInTheDocument();- });-- // All four preset buttons must still be in the DOM and not disabled- for (const preset of ['minimal', 'balanced', 'extended', 'maximum']) {- const btn = screen.getByTestId(`memory-window-option-${preset}`);- expect(btn).toBeInTheDocument();- expect(btn).not.toBeDisabled();- }- });-});diff --git a/app/src/components/settings/panels/__tests__/MemoryDebugPanel.test.tsx b/app/src/components/settings/panels/__tests__/MemoryDebugPanel.test.tsxdeleted file mode 100644index edd001e746..0000000000--- a/app/src/components/settings/panels/__tests__/MemoryDebugPanel.test.tsx+++ /dev/null@@ -1,359 +0,0 @@-/**- * MemoryDebugPanel coverage tests.- *- * Target uncovered lines (from diff-cover report):- * 215,224,234-235,245,256-257,282,288,290-291,309,316,325,338-340,346,348,354,- * 356,362,364,370,376,382,399,403,407-408,417,427,429- *- * These cover:- * - Documents section: list rendering, doc row (with/without title), delete btn- * - Namespaces section: list rendering, empty state- * - Query & Recall: query button, recall button, queryResult/recallResult rendering- * - Clear Namespace section: select when namespaces exist, text field fallback,- * clear success/failure paths- */-import { fireEvent, render, screen, waitFor } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';--vi.mock('../../../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (key: string) => key }) }));--vi.mock('../../hooks/useSettingsNavigation', () => ({- useSettingsNavigation: () => ({ navigateBack: vi.fn(), breadcrumbs: [] }),-}));--vi.mock('../../components/SettingsBackButton', () => ({ default: () => null }));--vi.mock('../../../intelligence/MemoryTextWithEntities', () => ({- MemoryTextWithEntities: ({ text }: { text: string }) => (- <span data-testid="mem-text">{text}</span>- ),-}));--const {- mockListDocuments,- mockListNamespaces,- mockDeleteDocument,- mockQueryNamespace,- mockRecallNamespace,- mockClearNamespace,-} = vi.hoisted(() => ({- mockListDocuments: vi.fn(),- mockListNamespaces: vi.fn(),- mockDeleteDocument: vi.fn(),- mockQueryNamespace: vi.fn(),- mockRecallNamespace: vi.fn(),- mockClearNamespace: vi.fn(),-}));--vi.mock('../../../../utils/tauriCommands', () => ({- memoryClearNamespace: (...args: unknown[]) => mockClearNamespace(...args),- memoryDeleteDocument: (...args: unknown[]) => mockDeleteDocument(...args),- memoryListDocuments: (...args: unknown[]) => mockListDocuments(...args),- memoryListNamespaces: (...args: unknown[]) => mockListNamespaces(...args),- memoryQueryNamespace: (...args: unknown[]) => mockQueryNamespace(...args),- memoryRecallNamespace: (...args: unknown[]) => mockRecallNamespace(...args),-}));--// normalizeMemoryDocuments returns MemoryDebugDocument[] from raw response.-// Mock it to pass through the data we supply.-vi.mock('../memoryDebugUtils', () => ({- normalizeMemoryDocuments: (raw: unknown) => {- if (!raw || typeof raw !== 'object') return [];- const r = raw as { documents?: unknown[] };- if (!Array.isArray(r.documents)) return [];- return r.documents;- },-}));--// -------------------------------------------------------------------// Factory helpers-// --------------------------------------------------------------------const makeDoc = (overrides: Record<string, unknown> = {}) => ({- documentId: 'doc-alpha',- namespace: 'ns-test',- title: null,- ...overrides,-});--const makeRawPayload = (docs: unknown[] = []) => ({ documents: docs });--const queryResult = { text: 'query result text here', entities: [] };--const recallResult = { text: 'recall result text here', entities: [] };--describe('MemoryDebugPanel', () => {- beforeEach(() => {- vi.clearAllMocks();- // Default: empty state- mockListDocuments.mockResolvedValue(makeRawPayload());- mockListNamespaces.mockResolvedValue([]);- mockDeleteDocument.mockResolvedValue({});- mockQueryNamespace.mockResolvedValue(queryResult);- mockRecallNamespace.mockResolvedValue(recallResult);- mockClearNamespace.mockResolvedValue({ cleared: true, namespace: 'ns-test' });- });-- async function renderPanel() {- const { default: MemoryDebugPanel } = await import('../MemoryDebugPanel');- return render(<MemoryDebugPanel />);- }-- // ── Documents section ──────────────────────────────────────────────────────-- it('renders the panel root test-id (smoke test)', async () => {- await renderPanel();- expect(screen.getByTestId('memory-debug-panel')).toBeInTheDocument();- });-- it('renders empty state when no documents (line 234)', async () => {- mockListDocuments.mockResolvedValue(makeRawPayload([]));- await renderPanel();- await waitFor(() => expect(screen.getByText('memory.noDocumentsFound')).toBeInTheDocument());- });-- it('renders document rows with id and namespace (lines 234-235, 239, 242)', async () => {- const doc = makeDoc({ documentId: 'doc-beta', namespace: 'ns-alpha', title: null });- mockListDocuments.mockResolvedValue(makeRawPayload([doc]));- await renderPanel();-- await waitFor(() => expect(screen.getByText('doc-beta')).toBeInTheDocument());- expect(screen.getByText('ns-alpha')).toBeInTheDocument();- });-- it('renders optional title when doc has one (line 245-248)', async () => {- const doc = makeDoc({- documentId: 'doc-gamma',- namespace: 'ns-beta',- title: 'My document title',- });- mockListDocuments.mockResolvedValue(makeRawPayload([doc]));- await renderPanel();-- await waitFor(() => expect(screen.getByText('My document title')).toBeInTheDocument());- });-- it('calls memoryDeleteDocument after confirm dialog (lines 256-257, 282)', async () => {- const doc = makeDoc({ documentId: 'doc-delta', namespace: 'ns-gamma' });- mockListDocuments.mockResolvedValue(makeRawPayload([doc]));- // Mock window.confirm to auto-accept- vi.spyOn(window, 'confirm').mockReturnValue(true);-- await renderPanel();- await waitFor(() => expect(screen.getByText('doc-delta')).toBeInTheDocument());-- fireEvent.click(screen.getByRole('button', { name: 'memory.delete' }));-- await waitFor(() => expect(mockDeleteDocument).toHaveBeenCalledWith('doc-delta', 'ns-gamma'));- });-- it('does not delete when confirm is cancelled (line 282)', async () => {- const doc = makeDoc({ documentId: 'doc-epsilon', namespace: 'ns-delta' });- mockListDocuments.mockResolvedValue(makeRawPayload([doc]));- vi.spyOn(window, 'confirm').mockReturnValue(false);-- await renderPanel();- await waitFor(() => screen.getByRole('button', { name: 'memory.delete' }));- fireEvent.click(screen.getByRole('button', { name: 'memory.delete' }));-- expect(mockDeleteDocument).not.toHaveBeenCalled();- });-- // ── Namespaces section ─────────────────────────────────────────────────────-- it('renders empty state when no namespaces (line 299)', async () => {- mockListNamespaces.mockResolvedValue([]);- await renderPanel();- await waitFor(() => expect(screen.getByText('memory.noNamespacesFound')).toBeInTheDocument());- });-- it('renders namespace chips when namespaces exist (lines 288, 290-291)', async () => {- mockListNamespaces.mockResolvedValue(['ns-workspace', 'ns-channel']);- await renderPanel();-- // Namespace chips in the namespaces section (may also appear in Clear Namespace select)- await waitFor(() =>- expect(screen.getAllByText('ns-workspace').length).toBeGreaterThanOrEqual(1)- );- expect(screen.getAllByText('ns-channel').length).toBeGreaterThanOrEqual(1);- });-- // ── Query & Recall section ─────────────────────────────────────────────────-- it('calls memoryQueryNamespace and renders result (lines 309, 316, 325, 362, 364)', async () => {- mockListNamespaces.mockResolvedValue(['ns-workspace']);- mockQueryNamespace.mockResolvedValue(queryResult);- await renderPanel();-- // Fill namespace input- const nsInput = screen.getByPlaceholderText('memory.namespace');- fireEvent.change(nsInput, { target: { value: 'ns-workspace' } });-- // Fill query text- const queryTextarea = screen.getByPlaceholderText('memory.queryText');- fireEvent.change(queryTextarea, { target: { value: 'what did I learn?' } });-- // Click Query button- fireEvent.click(screen.getByText('memory.query'));-- await waitFor(() =>- expect(mockQueryNamespace).toHaveBeenCalledWith(- 'ns-workspace',- 'what did I learn?',- expect.any(Number)- )- );-- // Result label and text rendered (lines 362, 364, 370)- await waitFor(() => expect(screen.getByText('memory.queryResult')).toBeInTheDocument());- expect(screen.getByText('query result text here')).toBeInTheDocument();- });-- it('calls memoryRecallNamespace and renders result (lines 338-340, 346, 348, 376, 382)', async () => {- mockRecallNamespace.mockResolvedValue(recallResult);- await renderPanel();-- const nsInput = screen.getByPlaceholderText('memory.namespace');- fireEvent.change(nsInput, { target: { value: 'ns-workspace' } });-- // Query textarea can remain empty for recall- fireEvent.click(screen.getByText('memory.recall'));-- await waitFor(() =>- expect(mockRecallNamespace).toHaveBeenCalledWith('ns-workspace', expect.any(Number))- );-- await waitFor(() => expect(screen.getByText('memory.recallResult')).toBeInTheDocument());- expect(screen.getByText('recall result text here')).toBeInTheDocument();- });-- it('shows query error when queryNamespace rejects (lines 354, 356)', async () => {- mockQueryNamespace.mockRejectedValue(new Error('query failed due to timeout'));- await renderPanel();-- const nsInput = screen.getByPlaceholderText('memory.namespace');- fireEvent.change(nsInput, { target: { value: 'ns-test' } });- const queryTextarea = screen.getByPlaceholderText('memory.queryText');- fireEvent.change(queryTextarea, { target: { value: 'search term' } });-- fireEvent.click(screen.getByText('memory.query'));-- await waitFor(() =>- expect(screen.getByText(/query failed due to timeout/)).toBeInTheDocument()- );- });-- it('shows recall error when recallNamespace rejects (lines 346, 348)', async () => {- mockRecallNamespace.mockRejectedValue(new Error('recall timed out'));- await renderPanel();-- const nsInput = screen.getByPlaceholderText('memory.namespace');- fireEvent.change(nsInput, { target: { value: 'ns-test' } });-- fireEvent.click(screen.getByText('memory.recall'));-- await waitFor(() => expect(screen.getByText(/recall timed out/)).toBeInTheDocument());- });-- // ── Clear Namespace section ────────────────────────────────────────────────-- it('renders SettingsSelect when namespaces exist (lines 399, 403)', async () => {- mockListNamespaces.mockResolvedValue(['ns-workspace', 'ns-channel']);- await renderPanel();-- await waitFor(() => expect(screen.getByRole('combobox')).toBeInTheDocument());- // Options should include each namespace (lines 407-408)- const select = screen.getByRole('combobox') as HTMLSelectElement;- const optionValues = Array.from(select.options).map(o => o.value);- expect(optionValues).toContain('ns-workspace');- expect(optionValues).toContain('ns-channel');- });-- it('renders text input fallback when no namespaces exist (line 417)', async () => {- mockListNamespaces.mockResolvedValue([]);- await renderPanel();-- await waitFor(() => expect(screen.queryByRole('combobox')).not.toBeInTheDocument());- // The namespace text field has aria-label from t()- expect(screen.getByPlaceholderText('memory.exampleNamespace')).toBeInTheDocument();- });-- it('shows success message after clear (line 427)', async () => {- mockListNamespaces.mockResolvedValue(['ns-workspace']);- mockClearNamespace.mockResolvedValue({ cleared: true, namespace: 'ns-workspace' });- vi.spyOn(window, 'confirm').mockReturnValue(true);- await renderPanel();-- await waitFor(() => expect(screen.getByRole('combobox')).toBeInTheDocument());-- const select = screen.getByRole('combobox') as HTMLSelectElement;- fireEvent.change(select, { target: { value: 'ns-workspace' } });-- fireEvent.click(screen.getByText('memory.clear'));-- await waitFor(() => expect(mockClearNamespace).toHaveBeenCalledWith('ns-workspace'));- await waitFor(() =>- expect(screen.getByText('memory.clearNamespaceSuccess')).toBeInTheDocument()- );- });-- it('shows empty/nothing message when cleared=false (line 429)', async () => {- mockListNamespaces.mockResolvedValue(['ns-empty']);- mockClearNamespace.mockResolvedValue({ cleared: false, namespace: 'ns-empty' });- vi.spyOn(window, 'confirm').mockReturnValue(true);- await renderPanel();-- await waitFor(() => expect(screen.getByRole('combobox')).toBeInTheDocument());-- const select = screen.getByRole('combobox') as HTMLSelectElement;- fireEvent.change(select, { target: { value: 'ns-empty' } });-- fireEvent.click(screen.getByText('memory.clear'));-- await waitFor(() => expect(screen.getByText('memory.clearNamespaceEmpty')).toBeInTheDocument());- });-- it('shows error when clearNamespace rejects', async () => {- mockListNamespaces.mockResolvedValue(['ns-bad']);- mockClearNamespace.mockRejectedValue(new Error('clear failed'));- vi.spyOn(window, 'confirm').mockReturnValue(true);- await renderPanel();-- await waitFor(() => expect(screen.getByRole('combobox')).toBeInTheDocument());-- const select = screen.getByRole('combobox') as HTMLSelectElement;- fireEvent.change(select, { target: { value: 'ns-bad' } });-- fireEvent.click(screen.getByText('memory.clear'));-- await waitFor(() => expect(screen.getByText(/clear failed/)).toBeInTheDocument());- });-- it('does not call clearNamespace when confirm is cancelled', async () => {- mockListNamespaces.mockResolvedValue(['ns-test']);- vi.spyOn(window, 'confirm').mockReturnValue(false);- await renderPanel();-- await waitFor(() => expect(screen.getByRole('combobox')).toBeInTheDocument());-- const select = screen.getByRole('combobox') as HTMLSelectElement;- fireEvent.change(select, { target: { value: 'ns-test' } });-- fireEvent.click(screen.getByText('memory.clear'));-- expect(mockClearNamespace).not.toHaveBeenCalled();- });-- it('refresh documents button re-loads (line 215, 224)', async () => {- await renderPanel();- // Two refresh buttons: documents section + namespaces section- await waitFor(() =>- expect(screen.getAllByText('memory.refresh').length).toBeGreaterThanOrEqual(1)- );-- const refreshBtns = screen.getAllByText('memory.refresh');- fireEvent.click(refreshBtns[0]);-- await waitFor(() => expect(mockListDocuments).toHaveBeenCalledTimes(2));- });-});diff --git a/app/src/components/settings/panels/__tests__/memoryDebugUtils.test.ts b/app/src/components/settings/panels/__tests__/memoryDebugUtils.test.tsdeleted file mode 100644index e1fc935ae8..0000000000--- a/app/src/components/settings/panels/__tests__/memoryDebugUtils.test.ts+++ /dev/null@@ -1,37 +0,0 @@-import { describe, expect, it } from 'vitest';--import { normalizeMemoryDocuments } from '../memoryDebugUtils';--describe('normalizeMemoryDocuments', () => {- it('reads documents from data.documents', () => {- const payload = {- success: true,- data: {- documents: [- { documentId: 'doc-1', namespace: 'conversations', title: 'First' },- { id: 'doc-2', namespace: 'skills', name: 'Second' },- ],- },- };-- expect(normalizeMemoryDocuments(payload)).toEqual([- {- documentId: 'doc-1',- namespace: 'conversations',- title: 'First',- raw: { documentId: 'doc-1', namespace: 'conversations', title: 'First' },- },- {- documentId: 'doc-2',- namespace: 'skills',- title: 'Second',- raw: { id: 'doc-2', namespace: 'skills', name: 'Second' },- },- ]);- });-- it('returns empty for unsupported shapes', () => {- expect(normalizeMemoryDocuments({ data: { foo: [] } })).toEqual([]);- expect(normalizeMemoryDocuments(null)).toEqual([]);- });-});diff --git a/app/src/components/settings/panels/memoryDebugUtils.ts b/app/src/components/settings/panels/memoryDebugUtils.tsdeleted file mode 100644index 974e228a79..0000000000--- a/app/src/components/settings/panels/memoryDebugUtils.ts+++ /dev/null@@ -1,68 +0,0 @@-import type { MemoryDebugDocument } from '../../../utils/tauriCommands';--function asArray(value: unknown): unknown[] {- return Array.isArray(value) ? value : [];-}--function asRecord(value: unknown): Record<string, unknown> | null {- if (!value || typeof value !== 'object' || Array.isArray(value)) {- return null;- }- return value as Record<string, unknown>;-}--function pickFirstString(record: Record<string, unknown>, keys: string[]): string | undefined {- for (const key of keys) {- const value = record[key];- if (typeof value === 'string' && value.trim()) {- return value;- }- }- return undefined;-}--function findDocumentsArray(payload: unknown): unknown[] {- if (Array.isArray(payload)) {- return payload;- }-- const root = asRecord(payload);- if (!root) return [];-- const rootCandidates = ['documents', 'items', 'results'];- for (const key of rootCandidates) {- const value = root[key];- if (Array.isArray(value)) return value;- }-- const data = asRecord(root.data);- if (!data) return [];-- const dataCandidates = ['documents', 'items', 'results'];- for (const key of dataCandidates) {- const value = data[key];- if (Array.isArray(value)) return value;- }-- return [];-}--export function normalizeMemoryDocuments(payload: unknown): MemoryDebugDocument[] {- const items = findDocumentsArray(payload);- const normalized: MemoryDebugDocument[] = [];-- for (const item of asArray(items)) {- const record = asRecord(item);- if (!record) continue;-- const documentId = pickFirstString(record, ['documentId', 'document_id', 'id']);- const namespace = pickFirstString(record, ['namespace']);- const title = pickFirstString(record, ['title', 'name']);-- if (!documentId || !namespace) continue;-- normalized.push({ documentId, namespace, title, raw: item });- }-- return normalized;-}diff --git a/app/src/components/settings/panels/memoryEngineUtils.ts b/app/src/components/settings/panels/memoryEngineUtils.tsdeleted file mode 100644index 621417a6d6..0000000000--- a/app/src/components/settings/panels/memoryEngineUtils.ts+++ /dev/null@@ -1,42 +0,0 @@-import type { MemoryEngineDescriptor } from '../../../utils/tauriCommands/memoryEngine';--export type MemoryEngineErrorKind =- | 'insufficient_credits'- | 'session_expired'- | 'memory_forbidden'- | 'backend_unavailable'- | 'other';--/** Maps the core's prefixed error strings onto a friendly state. */-export function classifyMemoryEngineError(err: unknown): MemoryEngineErrorKind {- const message = err instanceof Error ? err.message : String(err ?? '');- if (message.includes('INSUFFICIENT_CREDITS:')) return 'insufficient_credits';- if (message.includes('SESSION_EXPIRED:')) return 'session_expired';- // A refused credential (an API key without the memory scope): not a lapsed- // session, so it must never read as one and sign the user out.- if (message.includes('MEMORY_FORBIDDEN:')) return 'memory_forbidden';- if (message.includes('BACKEND_UNAVAILABLE:') || message.includes('MEMORY_UNREACHABLE:')) {- return 'backend_unavailable';- }- return 'other';-}--/** Capabilities the active engine offers that the target lacks. */-export function missingCapabilities(- active: MemoryEngineDescriptor | undefined,- target: MemoryEngineDescriptor | undefined-): string[] {- if (!active || !target || active.id === target.id) return [];- const have = new Set(target.capabilities);- return active.capabilities.filter(cap => !have.has(cap));-}--/** `graph_export` -> `graph export`; capability ids are core-defined. */-export function humanizeCapability(cap: string): string {- return cap.replace(/[_-]+/g, ' ');-}--/** Fallback label for an engine id the RPC did not describe. */-export function engineLabel(engines: MemoryEngineDescriptor[], id: string): string {- return engines.find(e => e.id === id)?.label ?? id;-}diff --git a/app/src/pages/Brain.tsx b/app/src/pages/Brain.tsxdeleted file mode 100644index 2da9c5f4b1..0000000000--- a/app/src/pages/Brain.tsx+++ /dev/null@@ -1,404 +0,0 @@-/**- * Brain — the centerpiece memory surface.- *- * Sub-tabs: Graph, Goals, Sources, and Sync.- *- * Rendered as the Brain sub-page of Connections → Integrations (it has no- * route of its own). Connections owns `?tab=brain` and the sidebar; this page- * keeps its sub-tab in `?brain=` and switches between them with chip tabs.- */-import { useCallback, useEffect, useMemo, useState } from 'react';-import { useLocation, useNavigate } from 'react-router-dom';--import { CodingSessionsCard } from '../components/intelligence/CodingSessionsCard';-import GoalsPanel from '../components/intelligence/GoalsPanel';-import { MemoryControls } from '../components/intelligence/MemoryControls';-import MemoryEngineRow from '../components/intelligence/MemoryEngineRow';-import MemoryFamilyGate from '../components/intelligence/MemoryFamilyGate';-import { MemoryGraph } from '../components/intelligence/MemoryGraph';-import { MemorySourcesRegistry } from '../components/intelligence/MemorySourcesRegistry';-import { MemoryTreeStatusPanel } from '../components/intelligence/MemoryTreeStatusPanel';-import { SyncActivityCard } from '../components/intelligence/SyncActivityCard';-import { SyncAuditPanel } from '../components/intelligence/SyncAuditPanel';-import { ToastContainer } from '../components/intelligence/Toast';-import SettingsTabbedPage from '../components/settings/layout/SettingsTabbedPage';-import MemoryEngineErrorAlert from '../components/settings/panels/MemoryEngineErrorAlert';-import { classifyMemoryEngineError } from '../components/settings/panels/memoryEngineUtils';-import { Alert, AlertDescription, Card } from '../components/ui';-import { CenteredLoadingState } from '../components/ui/LoadingState';-import { useT } from '../lib/i18n/I18nContext';-import { useCoreState } from '../providers/CoreStateProvider';-import type { ToastNotification } from '../types/intelligence';-import {- type GraphExportResponse,- type GraphMode,- memoryTreeGraphExport,-} from '../utils/tauriCommands';--type BrainTab = 'graph' | 'goals' | 'sources' | 'sync';--const BRAIN_TABS: readonly BrainTab[] = ['graph', 'goals', 'sources', 'sync'];--/** Sub-tabs of Sync, reflected in `?view=`: live status, or the run history. */-type SyncView = 'status' | 'history';--/** Chip-tab ids: the functional tabs, with Sync's history view as its own chip. */-type BrainChip = BrainTab | 'history';--/**- * Backoff ladder for automatically retrying a failed graph load.- *- * Written out rather than computed from an exponent because the two things a- * reader needs — how long the wait is, and that there are exactly three of- * them — are then both visible. The last element is the bound: once the ladder- * is spent the error stays on screen and manual Refresh is the way back.- */-const RETRY_DELAYS_MS: readonly number[] = [2_000, 4_000, 8_000];--/**- * Canonical text header (title + one-line description) per functional tab.- */-const BRAIN_HEADERS: Record<BrainTab, { titleKey: string; descKey: string }> = {- graph: { titleKey: 'brain.tabs.graph', descKey: 'brain.header.graph' },- goals: { titleKey: 'brain.tabs.goals', descKey: 'brain.header.goals' },- sources: { titleKey: 'brain.tabs.sources', descKey: 'brain.header.sources' },- sync: { titleKey: 'brain.tabs.sync', descKey: 'brain.header.sync' },-};--export default function Brain() {- const { t } = useT();- const location = useLocation();- const navigate = useNavigate();- // Tab is reflected in `?brain=` (`?tab=` belongs to Connections) so deep- // links (and the redirected old `/brain` and settings routes) land on the- // right sub-page.- const activeTab = useMemo<BrainTab>(() => {- const raw = new URLSearchParams(location.search).get('brain');- return (BRAIN_TABS as readonly string[]).includes(raw ?? '') ? (raw as BrainTab) : 'graph';- }, [location.search]);- const syncView: SyncView =- new URLSearchParams(location.search).get('view') === 'history' ? 'history' : 'status';- const setChip = useCallback(- (chip: BrainChip) => {- const params = new URLSearchParams(location.search);- params.set('brain', chip === 'history' ? 'sync' : chip);- if (chip === 'history') params.set('view', 'history');- else params.delete('view');- navigate({ pathname: location.pathname, search: `?${params.toString()}` });- },- [location.pathname, location.search, navigate]- );- const chipValue: BrainChip =- activeTab === 'sync' && syncView === 'history' ? 'history' : activeTab;- const [graph, setGraph] = useState<GraphExportResponse | null>(null);- const [error, setError] = useState<string | null>(null);- const [mode, setMode] = useState<GraphMode>('tree');- const [refreshKey, setRefreshKey] = useState(0);- const [toasts, setToasts] = useState<ToastNotification[]>([]);-- // The memory graph is read from the on-disk store, but the read only fired on- // mount — so after a logout→login cycle the page kept whatever (empty) state- // it had when the core was signed-out / mid identity-flip and never refetched- // once auth was restored, showing an empty graph for an account whose data is- // still on disk (#4149). Key the load on the authenticated identity so a- // re-auth (null→user, or A→B) re-pulls the persisted graph, mirroring the- // thread-cache reload CoreStateProvider already does on identity change.- const { snapshot } = useCoreState();- const authUserId = snapshot.auth.userId;-- const addToast = useCallback((toast: Omit<ToastNotification, 'id'>) => {- setToasts(prev => [...prev, { ...toast, id: `toast-${Date.now()}-${Math.random()}` }]);- }, []);- const removeToast = useCallback((id: string) => {- setToasts(prev => prev.filter(toast => toast.id !== id));- }, []);- const refresh = useCallback(() => setRefreshKey(k => k + 1), []);-- useEffect(() => {- let cancelled = false;- // The pending automatic retry, if one is scheduled. Effect-scoped, so a- // dependency change or an unmount cancels it in the cleanup below.- let retryTimer: ReturnType<typeof setTimeout> | undefined;- // Index into RETRY_DELAYS_MS. Effect-scoped too, which is what makes a- // manual Refresh (a `refreshKey` change re-runs this effect) start the- // ladder over rather than inheriting a spent one.- let attempt = 0;- // Monotonic request generation. Two `load()` calls can be in flight at once- // (the initial one and a `memory-tree-completed` event, or an automatic- // retry overtaken by an event), and they share `graph`, `error` and the- // retry ladder. Without this, a SUPERSEDED call's late result still writes:- // an obsolete rejection sets an error and schedules another retry even- // though a newer call has already succeeded, and an obsolete success can- // overwrite a newer graph. `cancelled` does not cover this — it only- // distinguishes this effect run from the next one, never two loads within- // the same run.- let generation = 0;- // Generation of the response currently ON SCREEN, which is NOT the same as- // the newest request. That difference is the whole point: `generation` says- // which request is newest, `renderedGeneration` says which one produced the- // data the user is looking at. They diverge exactly when a newer request- // FAILED — and that is the case where a superseded success must still be- // allowed through, because there is no newer data for it to clobber.- let renderedGeneration = 0;-- const load = async (isAutomaticRetry = false) => {- const myGeneration = ++generation;- // Any load supersedes a retry still waiting, so a manual Refresh or a- // `memory-tree-completed` event cannot race a timer into a double fetch.- if (retryTimer !== undefined) {- clearTimeout(retryTimer);- retryTimer = undefined;- }- console.debug(- '[brain] graph fetch: entry mode=%s attempt=%d retry=%s',- mode,- attempt,- isAutomaticRetry- );- // An AUTOMATIC retry must not clear the error while it is in flight.- // Clearing it here is right for a load the user or the app asked for —- // mount, Refresh, `memory-tree-completed` — because the previous failure- // is no longer what is being reported. A timer-driven retry is different:- // nothing has changed from the user's point of view, so blanking the- // alert (or the stale-data warning) for the duration of the request makes- // the failure flicker out and back for no reason they can perceive. The- // success path clears it on an accepted success, which is when the error- // has actually stopped being true.- if (!isAutomaticRetry) setError(null);- try {- const resp = await memoryTreeGraphExport(mode);- // Discard this success only if NEWER DATA already rendered — not merely- // because a newer request exists. Testing `myGeneration !== generation`- // here also dropped the older success when the newer request had- // failed, which leaves the user with an error and no graph: strictly- // worse than either behaviour this guard was meant to produce.- if (cancelled || myGeneration < renderedGeneration) {- console.debug('[brain] graph fetch: dropping success behind newer data');- return;- }- console.debug(- '[brain] graph fetch: exit n=%d edges=%d',- resp.nodes.length,- resp.edges.length- );- setGraph(resp);- renderedGeneration = myGeneration;- // Clear the error on an ACCEPTED SUCCESS, not only when a load starts.- // Two `load()` calls can overlap (the initial one and a- // `memory-tree-completed` event, or two events in quick succession),- // and they share this state with no request-generation guard. If the- // newer call fails and the older then succeeds, `error` stays set from- // the newer one while a perfectly good graph renders — which before- // this PR was invisible, and with the warning below would be a FALSE- // "your data is stale" on data that is not.- setError(null);- // Success resets the ladder: the NEXT transient failure gets the full- // set of retries rather than resuming where an old failure left off.- attempt = 0;- } catch (err) {- if (cancelled || myGeneration !== generation) {- // A newer load has taken over. Dropping this rejection is what stops- // an obsolete failure from scheduling a retry against a graph that- // has already refreshed successfully.- console.debug('[brain] graph fetch: dropping superseded failure');- return;- }- console.error('[brain] graph fetch failed', err);- setError(err instanceof Error ? err.message : String(err));-- const delay = RETRY_DELAYS_MS[attempt];- if (delay === undefined) {- // Bounded on purpose. Past this point the failure is very unlikely to- // be transient, and retrying forever would hammer the core and hide a- // real outage behind a spinner. The error stays on screen and the- // manual Refresh in `MemoryControls` remains the way back.- console.warn('[brain] graph fetch: retries exhausted after %d attempts', attempt);- return;- }- console.debug('[brain] graph fetch: scheduling retry %d in %dms', attempt + 1, delay);- attempt += 1;- retryTimer = setTimeout(() => {- void load(true);- }, delay);- }- };- void load();- const onTreeDone = () => {- console.debug('[brain] memory-tree-completed → refetch');- void load();- };- window.addEventListener('openhuman:memory-tree-completed', onTreeDone);- return () => {- cancelled = true;- if (retryTimer !== undefined) clearTimeout(retryTimer);- window.removeEventListener('openhuman:memory-tree-completed', onTreeDone);- };- // `authUserId` is a dependency so a logout→login (identity becomes- // available again) re-pulls the persisted graph instead of leaving the- // signed-out empty state on screen (#4149).- }, [mode, refreshKey, authUserId]);-- return (- <div className="h-full">- {- // Full width on purpose: the header band has to run edge to edge across- // the content card, so the width cap cannot live above it. Each tab's- // body carries its own `mx-auto max-w-3xl`, which is what the old- // `max-w-5xl` here was really constraining.- <div className="h-full w-full">- {/* All tabs share the standard scaffold: a single scrolling body,- all custom controls live inside it. The title/description go through- PanelPage so every page opens with the same flush header band, rather- than a bordered card floating in the content column. */}- <div className="h-full">- <SettingsTabbedPage<BrainChip>- title={t(BRAIN_HEADERS[activeTab].titleKey)}- description={t(BRAIN_HEADERS[activeTab].descKey)}- tabs={[- { id: 'graph', label: t('brain.tabs.graph') },- { id: 'goals', label: t('brain.tabs.goals') },- { id: 'sources', label: t('brain.tabs.sources') },- { id: 'sync', label: t('brain.tabs.sync') },- { id: 'history', label: t('brain.sync.viewHistory') },- ]}- value={chipValue}- onChange={setChip}- tabsAriaLabel={t('nav.brain')}- tabsTestIdPrefix="brain-tab"- // History is a full-height table: only its rows scroll.- scrollable={!(activeTab === 'sync' && syncView === 'history')}>- <div- className={- activeTab === 'sync' && syncView === 'history'- ? 'flex h-full min-h-0 flex-col'- : 'w-full space-y-5'- }>- {activeTab === 'graph' && (- <MemoryFamilyGate family="tree">- <div className="space-y-5 animate-fade-up">- <MemoryControls- mode={mode}- onModeChange={setMode}- onRefresh={refresh}- onToast={addToast}- contentRootAbs={graph?.content_root_abs}- />-- {/*- A failed refresh AFTER a good load keeps the graph on- screen and warns, rather than replacing it with an- error. The graph is expensive to rebuild and stays- useful when a refresh blips, so destroying it would- turn a transient failure into total data loss on- screen. What is not acceptable is the third option —- showing stale data with no indication at all, which is- what this did before: the error branch below is- reachable only while `graph` is null, and the catch in- `load()` never clears `graph`, so a later failure was- invisible.-- The two states are deliberately different components:- this one means "what you see is old", the one below- means "there is nothing to see".- */}- {/*- `error !== null`, not truthiness: `load()`'s catch does- `setError(err.message)`, and an Error carrying an empty- message yields `''`, which is falsy. Under a truthiness- test that failure suppresses BOTH alerts and is silent- again — the exact defect this PR exists to remove.- */}- {error !== null && graph ? (- classifyMemoryEngineError(error) !== 'other' ? (- <MemoryEngineErrorAlert error={error} />- ) : (- <Alert variant="warning">- <AlertDescription>{t('brain.refreshError')}</AlertDescription>- </Alert>- )- ) : null}-- {graph ? (- <MemoryGraph- nodes={graph.nodes}- edges={graph.edges}- mode={mode}- emptyHint={t('brain.empty')}- />- ) : error !== null ? (- <MemoryEngineErrorAlert error={error} fallbackText={t('brain.error')} />- ) : (- // The first load can take seconds — a hosted engine- // builds the graph from its derived layers — and an- // empty canvas meanwhile reads as a broken page.- <div role="status" data-testid="brain-graph-loading">- <CenteredLoadingState- label={t('workspace.loadingGraph')}- className="h-[640px] rounded-lg border border-line-subtle bg-surface-muted/40"- />- </div>- )}- </div>- </MemoryFamilyGate>- )}-- {activeTab === 'goals' && (- <MemoryFamilyGate family="goals">- <GoalsPanel />- </MemoryFamilyGate>- )}-- {activeTab === 'sources' && (- <div className="space-y-5 animate-fade-up">- <MemoryEngineRow />- {/* Coding sessions are a family of their own: an engine- can accept synced items without reading local agent- transcripts (hosted memory does exactly that). */}- <MemoryFamilyGate family="coding_sessions">- <CodingSessionsCard onToast={addToast} />- </MemoryFamilyGate>- <MemoryFamilyGate family="sources">- <MemorySourcesRegistry onToast={addToast} />- </MemoryFamilyGate>- </div>- )}-- {activeTab === 'sync' && syncView === 'status' && (- <div className="space-y-5 animate-fade-up">- {/* The ingest pipeline's status is the local chunk store's:- hosted memory draws a tree but keeps no such store. */}- <MemoryFamilyGate family="tree">- <MemoryFamilyGate family="chunks">- <Card padded divided={false}>- <MemoryTreeStatusPanel onToast={addToast} />- </Card>- </MemoryFamilyGate>- </MemoryFamilyGate>- {/* openhuman#6257: what is syncing right now, beside the- history of what already ran. */}- <MemoryFamilyGate family="sources">- <Card padded divided={false} data-testid="brain-sync-activity">- <SyncActivityCard />- </Card>- </MemoryFamilyGate>- </div>- )}-- {/* Sync → History: the run history as a full-height table. */}- {activeTab === 'sync' && syncView === 'history' && (- <div className="flex min-h-0 flex-1 flex-col" data-testid="brain-sync-history">- <MemoryFamilyGate family="sources">- <SyncAuditPanel fill />- </MemoryFamilyGate>- </div>- )}- </div>- </SettingsTabbedPage>- </div>- </div>- }-- <ToastContainer notifications={toasts} onRemove={removeToast} />- </div>- );-}diff --git a/app/src/pages/__tests__/Brain.autoRetry.test.tsx b/app/src/pages/__tests__/Brain.autoRetry.test.tsxdeleted file mode 100644index b9e16b4614..0000000000--- a/app/src/pages/__tests__/Brain.autoRetry.test.tsx+++ /dev/null@@ -1,364 +0,0 @@-/**- * Brain graph — AUTOMATIC recovery from a transient failure (#5904).- *- * `Brain.errorRecovery.test.tsx` covers recovery that a user or an in-product- * event triggers: manual Refresh, and the `openhuman:memory-tree-completed`- * listener. Neither is automatic — before #5904 a failed load simply stayed- * failed until something else happened, so a blip during a background refresh- * left the panel stuck until the user noticed and pressed a button.- *- * What is pinned here is the ladder in `Brain.tsx` (`RETRY_DELAYS_MS`):- * retries fire on their own, they are BOUNDED, a success resets them, and a- * pending one is cancelled on unmount.- *- * Timers are faked because the delays are seconds long; `advanceTimersByTimeAsync`- * is used rather than `advanceTimersByTime` so the promise inside each retry- * settles before the assertion reads the call count.- */-import { act, screen } from '@testing-library/react';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { renderWithProviders } from '../../test/test-utils';-import Brain from '../Brain';--const graphExportMock = vi.hoisted(() => vi.fn());-// Controllable authenticated identity so we can simulate a logout→login cycle-// (userId null → set) and assert the graph reloads (#4149).-const coreAuthRef = vi.hoisted(() => ({ current: 'user-A' as string | null }));-const navigateSpy = vi.hoisted(() => vi.fn());--vi.mock('react-router-dom', async importOriginal => {- const actual = await importOriginal<typeof import('react-router-dom')>();- return { ...actual, useNavigate: () => navigateSpy };-});--vi.mock('../../utils/tauriCommands', () => ({- memoryTreeGraphExport: graphExportMock,- isTauri: () => false,-}));--vi.mock('../../providers/CoreStateProvider', () => ({- useCoreState: () => ({- snapshot: {- auth: { userId: coreAuthRef.current, isAuthenticated: coreAuthRef.current != null },- },- }),-}));--vi.mock('../../components/intelligence/MemoryGraph', async () => {- const React = await import('react');- return {- MemoryGraph: ({ nodes }: { nodes: unknown[] }) =>- React.createElement('div', { 'data-testid': 'memory-graph' }, `nodes:${nodes.length}`),- };-});--vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));--vi.mock('../../components/layout/ChipTabs', async () => {- const React = await import('react');- return {- default: ({ children }: { children?: React.ReactNode }) =>- React.createElement('div', null, children),- };-});-vi.mock('../../components/ui/BetaBanner', () => ({ default: () => null }));-vi.mock('../../components/intelligence/MemoryControls', () => ({ MemoryControls: () => null }));-vi.mock('../../components/intelligence/MemoryTreeStatusPanel', async () => {- const React = await import('react');- return {- MemoryTreeStatusPanel: () => React.createElement('div', { 'data-testid': 'brain-sync' }),- };-});-vi.mock('../../components/intelligence/MemorySourcesRegistry', async () => {- const React = await import('react');- return {- MemorySourcesRegistry: () => React.createElement('div', { 'data-testid': 'brain-sources' }),- };-});-vi.mock('../../components/intelligence/Toast', () => ({ ToastContainer: () => null }));-vi.mock('../../components/intelligence/SyncAuditPanel', async () => {- const React = await import('react');- return {- SyncAuditPanel: () => React.createElement('div', { 'data-testid': 'brain-sync-audit' }),- };-});--const makeGraph = (n: number) => ({- nodes: Array.from({ length: n }, (_, i) => ({ id: `n${i}`, kind: 'summary', label: `N${i}` })),- edges: [],- content_root_abs: '/tmp/content',-});--/** Mirrors `RETRY_DELAYS_MS` in `Brain.tsx`. */-const RETRY_DELAYS_MS = [2_000, 4_000, 8_000];-const TOTAL_LADDER_MS = RETRY_DELAYS_MS.reduce((a, b) => a + b, 0);--const renderBrain = async () => {- await act(async () => {- renderWithProviders(<Brain />, { initialEntries: ['/?tab=graph'] });- });-};--describe('Brain graph — automatic retry', () => {- beforeEach(() => {- vi.clearAllMocks();- // `clearAllMocks` clears CALLS but not implementations, and several tests- // here set a persistent `mockRejectedValue`. Without an explicit reset that- // rejection leaks into the next test and silently changes its call counts.- graphExportMock.mockReset();- coreAuthRef.current = 'user-A';- vi.useFakeTimers();- });-- afterEach(() => {- vi.useRealTimers();- vi.restoreAllMocks();- });-- it('retries a failed load on its own, with no user action', async () => {- graphExportMock- .mockRejectedValueOnce(new Error('transient blip'))- .mockResolvedValue(makeGraph(2));-- await renderBrain();- // One attempt so far, and it failed.- expect(graphExportMock).toHaveBeenCalledTimes(1);- expect(screen.queryByTestId('memory-graph')).not.toBeInTheDocument();-- // Nothing is dispatched and nothing is clicked — only time passes.- await act(async () => {- await vi.advanceTimersByTimeAsync(RETRY_DELAYS_MS[0]);- });-- expect(graphExportMock).toHaveBeenCalledTimes(2);- expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:2');- });-- it('does not fire the retry before its delay has elapsed', async () => {- // Otherwise "it retried" could be satisfied by an immediate re-fetch loop,- // which is the thing a backoff exists to prevent.- graphExportMock.mockRejectedValue(new Error('down'));-- await renderBrain();- expect(graphExportMock).toHaveBeenCalledTimes(1);-- await act(async () => {- await vi.advanceTimersByTimeAsync(RETRY_DELAYS_MS[0] - 1);- });- expect(graphExportMock).toHaveBeenCalledTimes(1);- });-- it('stops after the ladder is exhausted rather than retrying forever', async () => {- graphExportMock.mockRejectedValue(new Error('backend is down'));-- await renderBrain();-- // Walk the whole ladder: 1 initial attempt + one per delay.- await act(async () => {- await vi.advanceTimersByTimeAsync(TOTAL_LADDER_MS);- });- expect(graphExportMock).toHaveBeenCalledTimes(1 + RETRY_DELAYS_MS.length);-- // Far beyond it, the count must not move. This is the assertion that- // distinguishes a bounded ladder from an infinite one.- await act(async () => {- await vi.advanceTimersByTimeAsync(TOTAL_LADDER_MS * 10);- });- expect(graphExportMock).toHaveBeenCalledTimes(1 + RETRY_DELAYS_MS.length);- });-- it('resets the ladder after a success, so a later failure retries again', async () => {- // Fail, recover on the first retry, then fail again. If `attempt` were not- // reset on success the second failure would resume mid-ladder and this- // would come out one call short.- graphExportMock- .mockRejectedValueOnce(new Error('blip one'))- .mockResolvedValueOnce(makeGraph(2))- .mockRejectedValue(new Error('blip two'));-- await renderBrain();- await act(async () => {- await vi.advanceTimersByTimeAsync(RETRY_DELAYS_MS[0]);- });- expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:2');- expect(graphExportMock).toHaveBeenCalledTimes(2);-- // A second failure, triggered the in-product way.- await act(async () => {- window.dispatchEvent(new Event('openhuman:memory-tree-completed'));- });- expect(graphExportMock).toHaveBeenCalledTimes(3);- // Prove the CATCH ran before advancing timers, not merely that the call was- // made. The retry timer is armed inside the catch, so without this the- // advance below could race the rejection's microtask and the ladder- // assertion would be measuring an arming that had not happened yet.- //- // Asserted directly rather than through `waitFor`: this file runs on fake- // timers, and `waitFor` polls on real timers that never advance, so it hangs- // to the 30s test timeout instead of retrying. The enclosing `act` above has- // already flushed the rejection's microtask, which is what makes the direct- // read sound here.- expect(document.querySelector('[data-slot="alert"]')).not.toBeNull();-- // The full ladder is available again: 3 more retries on top of that call.- await act(async () => {- await vi.advanceTimersByTimeAsync(TOTAL_LADDER_MS);- });- expect(graphExportMock).toHaveBeenCalledTimes(3 + RETRY_DELAYS_MS.length);- });-- it('keeps the failure visible while an automatic retry is in flight', async () => {- // A timer-driven retry must not blank the alert for the duration of its- // request. Nothing has changed from the user's point of view, so the- // failure flickering out and back is noise they cannot account for. The- // error is cleared on an accepted SUCCESS, which is when it stops being- // true, rather than at the top of every retry.- let resolveRetry!: (value: unknown) => void;- const retryCall = new Promise(resolve => {- resolveRetry = resolve;- });- graphExportMock- .mockImplementationOnce(() => Promise.reject(new Error('down')))- .mockImplementationOnce(() => retryCall);-- await renderBrain();- // Direct, not `waitFor` — see the note in the ladder test: `waitFor` polls- // on real timers and this file fakes them.- expect(document.querySelector('[data-slot="alert"]')).not.toBeNull();-- // The automatic retry starts and stays pending.- await act(async () => {- await vi.advanceTimersByTimeAsync(RETRY_DELAYS_MS[0]);- });- expect(graphExportMock).toHaveBeenCalledTimes(2);-- // Still on screen while that request is outstanding.- expect(document.querySelector('[data-slot="alert"]')).not.toBeNull();-- // And it goes away only once the retry actually succeeds.- await act(async () => {- resolveRetry(makeGraph(2));- });- expect(document.querySelector('[data-slot="alert"]')).toBeNull();- expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:2');- });-- it('cancels a pending retry when the panel unmounts', async () => {- // A timer that outlives the component would fetch (and setState) against an- // unmounted tree.- graphExportMock.mockRejectedValue(new Error('down'));-- let unmount!: () => void;- await act(async () => {- ({ unmount } = renderWithProviders(<Brain />, { initialEntries: ['/?tab=graph'] }));- });- expect(graphExportMock).toHaveBeenCalledTimes(1);-- unmount();-- await act(async () => {- await vi.advanceTimersByTimeAsync(TOTAL_LADDER_MS * 2);- });- expect(graphExportMock).toHaveBeenCalledTimes(1);- });-- it('ignores a superseded FAILURE instead of retrying from it', async () => {- // Two loads overlap: the initial one is still in flight when a- // `memory-tree-completed` event starts a newer one that SUCCEEDS. When the- // older call then rejects, that obsolete failure must not set an error or- // schedule a retry against a graph that has already refreshed.- let rejectFirst!: (reason: unknown) => void;- const firstCall = new Promise((_resolve, reject) => {- rejectFirst = reject;- });- graphExportMock- .mockImplementationOnce(() => firstCall)- .mockImplementationOnce(() => Promise.resolve(makeGraph(7)));-- await renderBrain();- await act(async () => {- window.dispatchEvent(new Event('openhuman:memory-tree-completed'));- });- expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:7');- expect(graphExportMock).toHaveBeenCalledTimes(2);-- // The superseded call finally fails.- await act(async () => {- rejectFirst(new Error('older load failed'));- });-- // No retry may come from it, however long we wait.- await act(async () => {- await vi.advanceTimersByTimeAsync(TOTAL_LADDER_MS * 2);- });- expect(graphExportMock).toHaveBeenCalledTimes(2);- expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:7');- });-- it('renders an older success when the newer load FAILED, and still retries', async () => {- // The collision between this PR's guard and #5942's "clear the error on an- // accepted success". The guard's job is to stop a stale response clobbering- // NEWER DATA — but when the newer request failed there is no newer data,- // and dropping the older success leaves the user with an error and no- // graph, which is worse than anything either PR intends.- //- // Both halves are asserted, because they are in tension and a fix that got- // only one would look right:- // - the older success renders (the guard let it through), AND- // - the ladder is still armed, because the NEWEST thing we know about the- // backend is that it failed. Showing data and continuing to retry is- // the correct combination, not a leftover.- let resolveFirst!: (value: unknown) => void;- const firstCall = new Promise(resolve => {- resolveFirst = resolve;- });- graphExportMock- .mockImplementationOnce(() => firstCall)- .mockImplementationOnce(() => Promise.reject(new Error('newer load failed')))- .mockResolvedValue(makeGraph(6));-- await renderBrain();- await act(async () => {- window.dispatchEvent(new Event('openhuman:memory-tree-completed'));- });- expect(graphExportMock).toHaveBeenCalledTimes(2);-- // The superseded call succeeds. Nothing newer has rendered, so it must show.- await act(async () => {- resolveFirst(makeGraph(3));- });- expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:3');-- // And the retry the failure armed still fires.- await act(async () => {- await vi.advanceTimersByTimeAsync(RETRY_DELAYS_MS[0]);- });- expect(graphExportMock).toHaveBeenCalledTimes(3);- expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:6');- });-- it('ignores a superseded SUCCESS instead of overwriting a newer graph', async () => {- // The other direction of the same race: a slow older call resolving after a- // newer one must not roll the graph back to its stale payload.- let resolveFirst!: (value: unknown) => void;- const firstCall = new Promise(resolve => {- resolveFirst = resolve;- });- graphExportMock- .mockImplementationOnce(() => firstCall)- .mockImplementationOnce(() => Promise.resolve(makeGraph(9)));-- await renderBrain();- await act(async () => {- window.dispatchEvent(new Event('openhuman:memory-tree-completed'));- });- expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:9');-- await act(async () => {- resolveFirst(makeGraph(1));- });-- expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:9');- });-});diff --git a/app/src/pages/__tests__/Brain.errorRecovery.test.tsx b/app/src/pages/__tests__/Brain.errorRecovery.test.tsxdeleted file mode 100644index 11c83d1979..0000000000--- a/app/src/pages/__tests__/Brain.errorRecovery.test.tsx+++ /dev/null@@ -1,327 +0,0 @@-/**- * Brain graph — transient-failure recovery, and what a failed refresh shows.- *- * `Brain.test.tsx` already covers "an alert appears when the fetch fails".- * None of the behaviours here is covered anywhere:- *- * 1. A transient failure must CLEAR on the next successful load. This is the- * accurate half of the "Couldn't load your brain" report — the panel is- * recoverable (`Brain.tsx:97` calls `setError(null)` at the top of every- * `load()`, and `MemoryControls` renders above the error branch so Refresh- * stays reachable), but nothing pinned that, so deleting that one line- * would have turned a recoverable error into a permanent one silently.- *- * 2. A refresh that fails AFTER a successful load keeps the stale graph and- * warns. This was BUG-W4-3 (#5895): the alert branch was reachable only- * while `graph` was null, and the catch in `load()` never clears `graph`,- * so a failed refresh left stale data on screen with no indication. The- * second test used to CHARACTERISE that swallow; it now asserts the- * warning, which is the same test inverted by the fix.- *- * 3. A FIRST load that fails still shows the destructive "couldn't load"- * alert and no graph — the branch that must not be swallowed by (2).- *- * 4. A failure whose message is EMPTY still surfaces. `load()` stores- * `err.message`, so `new Error('')` becomes `''`; a truthiness test would- * swallow it silently, which is (2) again through a different door.- *- * 5. An older load succeeding after a newer one failed must NOT leave a- * stale-data warning on data that is not stale. The two overlap and share- * state; the warning is what turns that pre-existing race into a visible- * false alarm, so the success path clears the error.- *- * These drive the refetch through the `openhuman:memory-tree-completed` window- * event, which is the in-product refetch trigger and needs no DOM control.- */-import { act, screen, waitFor } from '@testing-library/react';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { renderWithProviders } from '../../test/test-utils';-import Brain from '../Brain';--const graphExportMock = vi.hoisted(() => vi.fn());-// Controllable authenticated identity so we can simulate a logout→login cycle-// (userId null → set) and assert the graph reloads (#4149).-const coreAuthRef = vi.hoisted(() => ({ current: 'user-A' as string | null }));-const navigateSpy = vi.hoisted(() => vi.fn());--vi.mock('react-router-dom', async importOriginal => {- const actual = await importOriginal<typeof import('react-router-dom')>();- return { ...actual, useNavigate: () => navigateSpy };-});--vi.mock('../../utils/tauriCommands', () => ({- memoryTreeGraphExport: graphExportMock,- isTauri: () => false,-}));--vi.mock('../../providers/CoreStateProvider', () => ({- useCoreState: () => ({- snapshot: {- auth: { userId: coreAuthRef.current, isAuthenticated: coreAuthRef.current != null },- },- }),-}));--vi.mock('../../components/intelligence/MemoryGraph', async () => {- const React = await import('react');- return {- MemoryGraph: ({ nodes }: { nodes: unknown[] }) =>- React.createElement('div', { 'data-testid': 'memory-graph' }, `nodes:${nodes.length}`),- };-});--vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));--vi.mock('../../components/layout/ChipTabs', async () => {- const React = await import('react');- return {- default: ({ children }: { children?: React.ReactNode }) =>- React.createElement('div', null, children),- };-});-vi.mock('../../components/ui/BetaBanner', () => ({ default: () => null }));-vi.mock('../../components/intelligence/MemoryControls', () => ({ MemoryControls: () => null }));-vi.mock('../../components/intelligence/MemoryTreeStatusPanel', async () => {- const React = await import('react');- return {- MemoryTreeStatusPanel: () => React.createElement('div', { 'data-testid': 'brain-sync' }),- };-});-vi.mock('../../components/intelligence/MemorySourcesRegistry', async () => {- const React = await import('react');- return {- MemorySourcesRegistry: () => React.createElement('div', { 'data-testid': 'brain-sources' }),- };-});-vi.mock('../../components/intelligence/Toast', () => ({ ToastContainer: () => null }));-vi.mock('../../components/intelligence/SyncAuditPanel', async () => {- const React = await import('react');- return {- SyncAuditPanel: () => React.createElement('div', { 'data-testid': 'brain-sync-audit' }),- };-});--const makeGraph = (n: number) => ({- nodes: Array.from({ length: n }, (_, i) => ({ id: `n${i}`, kind: 'summary', label: `N${i}` })),- edges: [],- content_root_abs: '/tmp/content',-});--describe('Brain graph — transient failure recovery', () => {- beforeEach(() => {- vi.clearAllMocks();- coreAuthRef.current = 'user-A';- });-- afterEach(() => {- vi.restoreAllMocks();- });-- it('clears the error when a retry succeeds after a transient failure', async () => {- // Fail once, then succeed — a transient blip, not a broken backend.- graphExportMock- .mockRejectedValueOnce(new Error('transient blip'))- .mockResolvedValue(makeGraph(2));-- await act(async () => {- renderWithProviders(<Brain />, { initialEntries: ['/?tab=graph'] });- });-- // The failure is visible first — otherwise the clearing below proves nothing.- await waitFor(() => {- expect(screen.getByRole('alert')).toBeInTheDocument();- });- expect(screen.queryByTestId('memory-graph')).not.toBeInTheDocument();-- // The in-product refetch trigger.- await act(async () => {- window.dispatchEvent(new Event('openhuman:memory-tree-completed'));- });-- // The panel RECOVERS: the retry runs and its data renders.- //- // This comment used to say the test could not prove `error` itself was- // cleared — once `graph` was truthy, a still-set `error` was simply not in- // the DOM, so deleting `setError(null)` from `Brain.tsx` left both tests in- // this file passing. That was true, and it was a consequence of BUG-W4-3.- //- // Fixing #5895 makes the state reset OBSERVABLE, which is a second benefit- // of the fix worth naming: a stale `error` alongside a loaded graph now- // renders the warning variant. So the absence of that warning after a- // successful reload is real evidence that `setError(null)` ran, and the- // assertion below can fail if it is removed.- //- // Revert-checked by disabling the `openhuman:memory-tree-completed`- // listener (`Brain.tsx:113-117`): both tests then fail on the call-count- // assertion below.- await waitFor(() => {- expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:2');- });- expect(graphExportMock).toHaveBeenCalledTimes(2);- // The error state was genuinely cleared, not merely hidden: a surviving- // `error` beside a loaded graph would render the stale-data warning.- expect(document.querySelector('[data-variant="warning"]')).toBeNull();- });-- it('warns and keeps the stale graph when a refresh fails after a good load', async () => {- // Succeed first, then fail — the opposite order to the test above.- graphExportMock- .mockResolvedValueOnce(makeGraph(3))- .mockRejectedValue(new Error('refresh blew up'));-- await act(async () => {- renderWithProviders(<Brain />, { initialEntries: ['/?tab=graph'] });- });- await waitFor(() => {- expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:3');- });-- await act(async () => {- window.dispatchEvent(new Event('openhuman:memory-tree-completed'));- });- await waitFor(() => {- expect(graphExportMock).toHaveBeenCalledTimes(2);- });-- // This test previously asserted the OPPOSITE — `queryByRole('alert')` was- // expected to be absent — as a deliberate characterisation of BUG-W4-3,- // with a note saying it must be rewritten "to assert whichever was chosen"- // once the bug was fixed. #5895 chose: warn and keep the stale graph. So- // this is that rewrite, and the test that used to prove the swallow now- // proves the notification.- //- // Both halves matter and neither alone is the fix:- // - the warning appears, so the failure is no longer silent;- // - the graph is still there, so a transient blip does not wipe data the- // user can still read. Clearing `graph` on error would also have made- // the alert appear, and would have been the worse product choice.- // Asserted on `data-variant` (emitted by `Alert` at `Alert.tsx:85`) rather- // than on `role="alert"`: BOTH the warning and the destructive variant are- // in `ASSERTIVE_VARIANTS` (`Alert.tsx:62`) and so both carry that role, and- // an assertion that cannot tell the two apart would pass on either branch.- // Inside `waitFor`: the `toHaveBeenCalledTimes(2)` above only waits until- // the mock is CALLED, not until React has committed the state its rejection- // sets. Querying synchronously after it can read the DOM one commit early- // and fail intermittently.- await waitFor(() => {- const alert = document.querySelector('[data-slot="alert"]');- expect(alert).not.toBeNull();- expect(alert).toHaveAttribute('data-variant', 'warning');- });- expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:3');- });-- it('shows the load error, and no graph, when the FIRST load fails', async () => {- // The other side of the branch: with no previously loaded graph there is- // nothing stale to keep, so the destructive "couldn't load" alert is- // correct and the warning must not be what renders. This guards against a- // fix that routes every failure through the stale-data warning.- graphExportMock.mockRejectedValue(new Error('cold load blew up'));-- await act(async () => {- renderWithProviders(<Brain />, { initialEntries: ['/?tab=graph'] });- });-- await waitFor(() => {- expect(document.querySelector('[data-slot="alert"]')).not.toBeNull();- });- expect(document.querySelector('[data-slot="alert"]')).toHaveAttribute(- 'data-variant',- 'destructive'- );- expect(document.querySelector('[data-variant="warning"]')).toBeNull();- expect(screen.queryByTestId('memory-graph')).not.toBeInTheDocument();- });-- it('still surfaces a failure whose message is empty', async () => {- // `load()` stores `err.message`, so `new Error('')` lands as `''`. Under a- // truthiness test (`error ? ...`) that failure renders NOTHING and is- // silently swallowed — the very defect this PR exists to remove, reachable- // through a different door. Hence `error !== null` in both branches.- graphExportMock.mockRejectedValue(new Error(''));-- await act(async () => {- renderWithProviders(<Brain />, { initialEntries: ['/?tab=graph'] });- });-- await waitFor(() => {- const alert = document.querySelector('[data-slot="alert"]');- expect(alert).not.toBeNull();- expect(alert).toHaveAttribute('data-variant', 'destructive');- });- });-- it('still warns when a REFRESH failure carries an empty message', async () => {- // The sibling test covers an empty message on the FIRST load, which is the- // destructive branch. This covers the warning branch, and the two need- // separate cases: a truthiness regression in only one of them would- // otherwise slip through on the strength of the other.- graphExportMock.mockResolvedValueOnce(makeGraph(5)).mockRejectedValue(new Error(''));-- await act(async () => {- renderWithProviders(<Brain />, { initialEntries: ['/?tab=graph'] });- });- await waitFor(() => {- expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:5');- });-- await act(async () => {- window.dispatchEvent(new Event('openhuman:memory-tree-completed'));- });-- await waitFor(() => {- const alert = document.querySelector('[data-slot="alert"]');- expect(alert).not.toBeNull();- expect(alert).toHaveAttribute('data-variant', 'warning');- });- // And the stale graph is still there, as in the non-empty case.- expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:5');- });-- it('does not warn when an older load succeeds after a newer one failed', async () => {- // Two `load()` calls overlap and share `graph`/`error`: the initial one and- // one started by `memory-tree-completed`. If the NEWER fails while the- // OLDER is still in flight, and the older then succeeds, the success- // renders a good graph — and must not leave a "your data is stale" warning- // attached to data that is not stale.- //- // Before this PR the leftover error was invisible, so the race was- // harmless; the warning is what would have made it a visible false alarm.- let resolveFirst!: (value: unknown) => void;- const firstCall = new Promise(resolve => {- resolveFirst = resolve;- });- graphExportMock- .mockImplementationOnce(() => firstCall)- .mockImplementationOnce(() => Promise.reject(new Error('newer load failed')));-- await act(async () => {- renderWithProviders(<Brain />, { initialEntries: ['/?tab=graph'] });- });-- // The newer load starts and fails while the first is still pending.- await act(async () => {- window.dispatchEvent(new Event('openhuman:memory-tree-completed'));- });-- // Assert the PRECONDITION before resolving anything. Without this the test- // passes vacuously: if the event never started a second load, resolving the- // first would render a graph with no warning and the final assertions would- // be satisfied for entirely the wrong reason.- await waitFor(() => {- expect(graphExportMock).toHaveBeenCalledTimes(2);- expect(document.querySelector('[data-slot="alert"]')).not.toBeNull();- });-- // Now the older, superseded call finally succeeds.- await act(async () => {- resolveFirst(makeGraph(4));- });-- await waitFor(() => {- expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:4');- });- expect(document.querySelector('[data-variant="warning"]')).toBeNull();- });-});diff --git a/app/src/pages/__tests__/Brain.test.tsx b/app/src/pages/__tests__/Brain.test.tsxdeleted file mode 100644index 90b4e7f1c0..0000000000--- a/app/src/pages/__tests__/Brain.test.tsx+++ /dev/null@@ -1,321 +0,0 @@-import { act, screen, waitFor } from '@testing-library/react';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { resetMemoryEngineCacheForTests } from '../../components/intelligence/useMemoryEngineCapabilities';-import { renderWithProviders } from '../../test/test-utils';-import Brain from '../Brain';--const graphExportMock = vi.hoisted(() => vi.fn());-// The bound memory engine, as `MemoryFamilyGate` reads it. Rejected by default,-// so every gate fails open and the tabs render as they always have.-const engineMock = vi.hoisted(() => ({ list: vi.fn(), get: vi.fn() }));-vi.mock('../../utils/tauriCommands/memoryEngine', () => ({- memoryEnginesList: (...a: unknown[]) => engineMock.list(...a),- memoryEngineGet: (...a: unknown[]) => engineMock.get(...a),-}));-// Controllable authenticated identity so we can simulate a logout→login cycle-// (userId null → set) and assert the graph reloads (#4149).-const coreAuthRef = vi.hoisted(() => ({ current: 'user-A' as string | null }));-const navigateSpy = vi.hoisted(() => vi.fn());--vi.mock('react-router-dom', async importOriginal => {- const actual = await importOriginal<typeof import('react-router-dom')>();- return { ...actual, useNavigate: () => navigateSpy };-});--vi.mock('../../utils/tauriCommands', () => ({- memoryTreeGraphExport: graphExportMock,- isTauri: () => false,-}));--vi.mock('../../providers/CoreStateProvider', () => ({- useCoreState: () => ({- snapshot: {- auth: { userId: coreAuthRef.current, isAuthenticated: coreAuthRef.current != null },- },- }),-}));--vi.mock('../../components/intelligence/MemoryGraph', async () => {- const React = await import('react');- return {- MemoryGraph: ({ nodes }: { nodes: unknown[] }) =>- React.createElement('div', { 'data-testid': 'memory-graph' }, `nodes:${nodes.length}`),- };-});--vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));--vi.mock('../../components/layout/ChipTabs', async () => {- const React = await import('react');- return {- default: ({ children }: { children?: React.ReactNode }) =>- React.createElement('div', null, children),- };-});-vi.mock('../../components/ui/BetaBanner', () => ({ default: () => null }));-vi.mock('../../components/intelligence/MemoryControls', () => ({ MemoryControls: () => null }));-vi.mock('../../components/intelligence/MemoryTreeStatusPanel', async () => {- const React = await import('react');- return {- MemoryTreeStatusPanel: () => React.createElement('div', { 'data-testid': 'brain-sync' }),- };-});-vi.mock('../../components/intelligence/MemorySourcesRegistry', async () => {- const React = await import('react');- return {- MemorySourcesRegistry: () => React.createElement('div', { 'data-testid': 'brain-sources' }),- };-});-vi.mock('../../components/intelligence/Toast', () => ({ ToastContainer: () => null }));-vi.mock('../../components/intelligence/SyncAuditPanel', async () => {- const React = await import('react');- return {- SyncAuditPanel: () => React.createElement('div', { 'data-testid': 'brain-sync-audit' }),- };-});-vi.mock('../../components/intelligence/SyncActivityCard', async () => {- const React = await import('react');- return {- SyncActivityCard: () =>- React.createElement('div', { 'data-testid': 'brain-sync-activity-card' }),- };-});--const makeGraph = (n: number) => ({- nodes: Array.from({ length: n }, (_, i) => ({ id: `n${i}`, kind: 'summary', label: `N${i}` })),- edges: [],- content_root_abs: '/tmp/content',-});--describe('Brain page', () => {- beforeEach(() => {- vi.clearAllMocks();- coreAuthRef.current = 'user-A';- resetMemoryEngineCacheForTests();- engineMock.get.mockRejectedValue(new Error('no engine rpc in this test'));- engineMock.list.mockRejectedValue(new Error('no engine rpc in this test'));- });-- afterEach(() => {- vi.restoreAllMocks();- });-- it('renders the graph once data is fetched', async () => {- graphExportMock.mockResolvedValue(makeGraph(3));- await act(async () => {- renderWithProviders(<Brain />, { initialEntries: ['/?brain=graph'] });- });- await waitFor(() => {- expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:3');- });- });-- it('shows a loading state, not an empty canvas, until the graph arrives', async () => {- let resolveGraph!: (graph: ReturnType<typeof makeGraph>) => void;- graphExportMock.mockReturnValue(- new Promise(resolve => {- resolveGraph = resolve;- })- );- await act(async () => {- renderWithProviders(<Brain />, { initialEntries: ['/?brain=graph'] });- });- expect(screen.getByTestId('brain-graph-loading')).toHaveTextContent('workspace.loadingGraph');- expect(screen.queryByTestId('memory-graph')).not.toBeInTheDocument();-- await act(async () => {- resolveGraph(makeGraph(2));- });- await waitFor(() => {- expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:2');- });- expect(screen.queryByTestId('brain-graph-loading')).not.toBeInTheDocument();- });-- it('renders empty-state graph when there are no nodes', async () => {- graphExportMock.mockResolvedValue(makeGraph(0));- await act(async () => {- renderWithProviders(<Brain />, { initialEntries: ['/?brain=graph'] });- });- await waitFor(() => {- expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:0');- });- });-- it('reloads the memory graph from the store when the user re-authenticates (#4149)', async () => {- // Start signed-out / mid identity-flip: the first fetch resolves empty.- coreAuthRef.current = null;- graphExportMock.mockResolvedValue(makeGraph(0));- let view!: ReturnType<typeof renderWithProviders>;- await act(async () => {- view = renderWithProviders(<Brain />, { initialEntries: ['/?brain=graph'] });- });- await waitFor(() => expect(graphExportMock).toHaveBeenCalledTimes(1));- expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:0');-- // Re-login: identity becomes available — the graph must re-pull from the- // persistent store rather than keep the signed-out empty state.- coreAuthRef.current = 'user-A';- graphExportMock.mockResolvedValue(makeGraph(5));- await act(async () => {- view.rerender(<Brain />);- });- await waitFor(() => expect(graphExportMock).toHaveBeenCalledTimes(2));- await waitFor(() => {- expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:5');- });- });-- it('surfaces an error alert when the fetch fails', async () => {- graphExportMock.mockRejectedValue(new Error('boom'));- await act(async () => {- renderWithProviders(<Brain />, { initialEntries: ['/?brain=graph'] });- });- await waitFor(() => {- expect(screen.getByRole('alert')).toBeInTheDocument();- });- });-- // All tabs share the standard scaffold. Drive each via the `?brain=` query- // param so every per-tab branch is exercised.- it.each([- ['sources', 'brain-sources'],- ['sync', 'brain-sync'],- ])('renders the %s tab', async (tab, testId) => {- graphExportMock.mockResolvedValue(makeGraph(0));- await act(async () => {- renderWithProviders(<Brain />, { initialEntries: [`/?brain=${tab}`] });- });- await waitFor(() => {- expect(screen.getByTestId(testId)).toBeInTheDocument();- });- });-- // Sync has two sub-views reflected in `?view=`: the default "status" view- // (live status panel + activity card) and "history" (the full-height run- // history table). They're mutually exclusive panes, not stacked together.- it('shows the live status and activity panels on the Sync status sub-view (default)', async () => {- graphExportMock.mockResolvedValue(makeGraph(0));- await act(async () => {- renderWithProviders(<Brain />, { initialEntries: ['/?brain=sync'] });- });- await waitFor(() => {- expect(screen.getByTestId('brain-sync')).toBeInTheDocument();- expect(screen.getByTestId('brain-sync-activity')).toBeInTheDocument();- expect(screen.getByTestId('brain-sync-activity-card')).toBeInTheDocument();- });- expect(screen.queryByTestId('brain-sync-history')).toBeNull();- expect(screen.queryByTestId('brain-sync-audit')).toBeNull();- });-- it('shows the sync history panel on the Sync history sub-view', async () => {- graphExportMock.mockResolvedValue(makeGraph(0));- await act(async () => {- renderWithProviders(<Brain />, { initialEntries: ['/?brain=sync&view=history'] });- });- await waitFor(() => {- expect(screen.getByTestId('brain-sync-history')).toBeInTheDocument();- expect(screen.getByTestId('brain-sync-audit')).toBeInTheDocument();- });- expect(screen.queryByTestId('brain-sync-activity')).toBeNull();- expect(screen.queryByTestId('brain-sync-activity-card')).toBeNull();- });-- // A remote engine without the Sources family (a direct CortexDB) has no- // `memory_sources.*` RPCs at all: the sync panels must say so rather than- // render and fail.- it('shows the sync panels as unavailable on an engine without sources', async () => {- graphExportMock.mockResolvedValue(makeGraph(0));- engineMock.get.mockResolvedValue({ driver: 'cortex' });- engineMock.list.mockResolvedValue({- active: 'cortex',- engines: [- {- id: 'cortex',- label: 'CortexDB',- capabilities: ['core', 'recall', 'portability', 'answer'],- },- ],- });- await act(async () => {- renderWithProviders(<Brain />, { initialEntries: ['/?brain=sync'] });- });- await waitFor(() => {- expect(screen.getAllByTestId('memory-family-unavailable').length).toBeGreaterThan(0);- });- expect(screen.queryByTestId('brain-sync-activity')).toBeNull();- expect(screen.queryByTestId('brain-sync-activity-card')).toBeNull();- });-- // Hosted memory serves a tree — the server's understanding — but keeps no- // local chunk store: the graph draws, and the ingest pipeline's status panel- // says it is not available rather than reading a store that is not there.- const hostedWithTree = () => {- engineMock.get.mockResolvedValue({ driver: 'tinyhumans' });- engineMock.list.mockResolvedValue({- active: 'tinyhumans',- engines: [- {- id: 'tinyhumans',- label: 'CortexDB (via TinyHumans)',- capabilities: ['core', 'recall', 'portability', 'sources', 'retrieval', 'tree'],- },- ],- });- };-- it('draws the graph on hosted memory', async () => {- graphExportMock.mockResolvedValue(makeGraph(2));- hostedWithTree();- await act(async () => {- renderWithProviders(<Brain />, { initialEntries: ['/?brain=graph'] });- });- await waitFor(() => {- expect(screen.getByTestId('memory-graph')).toHaveTextContent('nodes:2');- });- });-- it('gates the local pipeline status on hosted memory', async () => {- graphExportMock.mockResolvedValue(makeGraph(0));- hostedWithTree();- await act(async () => {- renderWithProviders(<Brain />, { initialEntries: ['/?brain=sync'] });- });- await waitFor(() => {- const gated = screen- .getAllByTestId('memory-family-unavailable')- .map(node => node.getAttribute('data-family'));- expect(gated).toContain('chunks');- });- expect(screen.queryByTestId('brain-sync')).toBeNull();- });-- // Hosted memory accepts synced items but reads no local agent transcripts:- // the sources registry renders, the coding-sessions card says it is not- // available instead of calling an RPC the engine refuses.- it('gates the coding sessions card on its own family', async () => {- graphExportMock.mockResolvedValue(makeGraph(0));- engineMock.get.mockResolvedValue({ driver: 'tinyhumans' });- engineMock.list.mockResolvedValue({- active: 'tinyhumans',- engines: [- {- id: 'tinyhumans',- label: 'CortexDB (via TinyHumans)',- capabilities: ['core', 'recall', 'portability', 'answer', 'sources', 'documents'],- },- ],- });- await act(async () => {- renderWithProviders(<Brain />, { initialEntries: ['/?brain=sources'] });- });- await waitFor(() => {- const gated = screen- .getAllByTestId('memory-family-unavailable')- .map(node => node.getAttribute('data-family'));- expect(gated).toContain('coding_sessions');- expect(gated).not.toContain('sources');- });- });-});diff --git a/app/src/services/api/goalsApi.ts b/app/src/services/api/goalsApi.tsdeleted file mode 100644index 57e9752e40..0000000000--- a/app/src/services/api/goalsApi.ts+++ /dev/null@@ -1,114 +0,0 @@-/**- * Frontend client for the long-term goals surface (`openhuman.memory_goals_*`).- *- * The Rust handlers persist an editable list of the agent's durable long-term- * goals to `<workspace>/MEMORY_GOALS.md`. The same list is curated by the- * background `goals_agent` (enrichment) — user edits here and agent edits stay- * in lock-step on the same file.- *- * Wire shapes: `list` returns the bare `GoalsDoc` ({ items }); the mutation- * methods wrap their value in `{ result, logs }` when logs are present. The- * {@link extractItems} helper normalises both shapes so callers always get a- * `GoalItem[]`.- */-import debug from 'debug';--import { callCoreRpc } from '../coreRpcClient';--const log = debug('openhuman:goalsApi');--/** A single long-term goal item. */-export interface GoalItem {- id: string;- text: string;-}--/** Outcome of an enrichment (reflect) pass. */-interface ReflectResult {- ran: boolean;- summary: string;- items: GoalItem[];-}--/** Drop `undefined` params so the wire payload stays clean. */-function pruneParams<T extends Record<string, unknown>>(params: T): Partial<T> {- const out: Partial<T> = {};- for (const [k, v] of Object.entries(params)) {- if (v !== undefined) (out as Record<string, unknown>)[k] = v;- }- return out;-}--/** Pull the goal items out of any of the handler response shapes. */-function extractItems(res: unknown): GoalItem[] {- if (!res || typeof res !== 'object') return [];- // Unwrap the Outcome `{ result, logs }` envelope when present.- const value =- 'result' in (res as Record<string, unknown>) ? (res as { result: unknown }).result : res;- if (!value || typeof value !== 'object') return [];- const v = value as Record<string, unknown>;- // Direct GoalsDoc ({ items }) or AddResult/ReflectResult ({ goals: { items } }).- const items = Array.isArray(v.items)- ? v.items- : Array.isArray((v.goals as { items?: unknown })?.items)- ? (v.goals as { items: unknown[] }).items- : [];- return items.filter(- (i): i is GoalItem =>- !!i && typeof (i as GoalItem).id === 'string' && typeof (i as GoalItem).text === 'string'- );-}--export const goalsApi = {- list: async (): Promise<GoalItem[]> => {- log('list');- const res = await callCoreRpc<unknown>({ method: 'openhuman.memory_goals_list', params: {} });- return extractItems(res);- },-- add: async (text: string): Promise<GoalItem[]> => {- log('add');- const res = await callCoreRpc<unknown>({- method: 'openhuman.memory_goals_add',- params: { text },- });- return extractItems(res);- },-- edit: async (id: string, text: string): Promise<GoalItem[]> => {- log('edit id=%s', id);- const res = await callCoreRpc<unknown>({- method: 'openhuman.memory_goals_edit',- params: { id, text },- });- return extractItems(res);- },-- remove: async (id: string): Promise<GoalItem[]> => {- log('delete id=%s', id);- const res = await callCoreRpc<unknown>({- method: 'openhuman.memory_goals_delete',- params: { id },- });- return extractItems(res);- },-- reflect: async (context?: string): Promise<ReflectResult> => {- log('reflect hasContext=%s', Boolean(context));- const res = await callCoreRpc<unknown>({- method: 'openhuman.memory_goals_reflect',- params: pruneParams({ context }),- // Enrichment runs a full agent turn — give it room beyond the default.- timeoutMs: 180_000,- });- const envelope =- res && typeof res === 'object' && 'result' in (res as Record<string, unknown>)- ? (res as { result: Record<string, unknown> }).result- : ((res as Record<string, unknown>) ?? {});- return {- ran: Boolean(envelope?.ran),- summary: typeof envelope?.summary === 'string' ? envelope.summary : '',- items: extractItems(res),- };- },-};diff --git a/app/src/services/memorySourcesService.test.ts b/app/src/services/memorySourcesService.test.tsdeleted file mode 100644index 4a590403bf..0000000000--- a/app/src/services/memorySourcesService.test.ts+++ /dev/null@@ -1,417 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { callCoreRpc } from './coreRpcClient';-import {- addMemorySource,- applyAllIn,- type CodingSessionDrainProgress,- drainCodingSessions,- getCodingSessionStatus,- ingestCodingSessions,- isIngestTimeout,- listMemorySources,- MEMORY_SYNC_RPC_TIMEOUT_MS,- type MemorySourceEntry,- removeMemorySource,- SOURCE_KIND_ICONS,- SOURCE_KIND_LABEL_KEYS,- updateMemorySource,-} from './memorySourcesService';--vi.mock('./coreRpcClient', () => ({ callCoreRpc: vi.fn() }));--const mockedCall = vi.mocked(callCoreRpc);--describe('memorySourcesService', () => {- beforeEach(() => {- mockedCall.mockReset();- });-- it('listMemorySources returns sources from envelope-wrapped response', async () => {- mockedCall.mockResolvedValue({- result: {- sources: [{ id: 'src_1', kind: 'folder', label: 'Notes', enabled: true, path: '/tmp' }],- },- logs: [],- } as never);-- const sources = await listMemorySources();-- expect(mockedCall).toHaveBeenCalledWith({ method: 'openhuman.memory_sources_list' });- expect(sources).toHaveLength(1);- expect(sources[0].kind).toBe('folder');- });-- it('listMemorySources handles flat (un-wrapped) response', async () => {- mockedCall.mockResolvedValue({ sources: [] } as never);- const sources = await listMemorySources();- expect(sources).toEqual([]);- });-- it('addMemorySource sends kind-specific flat fields', async () => {- mockedCall.mockResolvedValue({- result: {- source: { id: 'src_new', kind: 'folder', label: 'Test', enabled: true, path: '/x' },- },- logs: [],- } as never);-- const result = await addMemorySource({- kind: 'folder',- label: 'Test',- enabled: true,- path: '/x',- });-- expect(mockedCall).toHaveBeenCalledWith({- method: 'openhuman.memory_sources_add',- params: { kind: 'folder', label: 'Test', enabled: true, path: '/x' },- });- expect(result.id).toBe('src_new');- });-- it('updateMemorySource sends id + patch fields', async () => {- mockedCall.mockResolvedValue({- result: { source: { id: 'src_1', kind: 'folder', label: 'X', enabled: false } },- logs: [],- } as never);-- await updateMemorySource('src_1', { enabled: false, label: 'X' });-- expect(mockedCall).toHaveBeenCalledWith({- method: 'openhuman.memory_sources_update',- params: { id: 'src_1', enabled: false, label: 'X' },- });- });-- it('removeMemorySource returns boolean', async () => {- mockedCall.mockResolvedValue({ result: { removed: true }, logs: [] } as never);- const removed = await removeMemorySource('src_1');- expect(removed).toBe(true);- });-- it('exposes labels and icons for every source kind', () => {- const kinds = [- 'composio',- 'conversation',- 'folder',- 'github_repo',- 'twitter_query',- 'rss_feed',- 'web_page',- ] as const;- for (const kind of kinds) {- expect(SOURCE_KIND_LABEL_KEYS[kind]).toBeTruthy();- expect(SOURCE_KIND_ICONS[kind]).toBeTruthy();- }- });-- it('addMemorySource sends conversation source with no extra fields', async () => {- mockedCall.mockResolvedValue({- result: {- source: { id: 'src_conv', kind: 'conversation', label: 'Conversations', enabled: true },- },- logs: [],- } as never);-- const result = await addMemorySource({- kind: 'conversation',- label: 'Conversations',- enabled: true,- });-- expect(mockedCall).toHaveBeenCalledWith({- method: 'openhuman.memory_sources_add',- params: { kind: 'conversation', label: 'Conversations', enabled: true },- });- expect(result.id).toBe('src_conv');- expect(result.kind).toBe('conversation');- });-- // ---------------------------------------------------------------------------- // applyAllIn- // ----------------------------------------------------------------------------- it('applyAllIn calls the correct RPC method', async () => {- mockedCall.mockResolvedValue({- result: {- sources: [{ id: 'src_1', kind: 'github_repo', label: 'All Repos', enabled: true }],- sync_triggered: 1,- },- logs: [],- } as never);-- const result = await applyAllIn();-- expect(mockedCall).toHaveBeenCalledWith({- method: 'openhuman.memory_sources_apply_all_in',- timeoutMs: MEMORY_SYNC_RPC_TIMEOUT_MS,- });- expect(result.sync_triggered).toBe(1);- expect(result.sources).toHaveLength(1);- expect(result.sources[0].id).toBe('src_1');- });-- it('applyAllIn normalises the #5820 failure fields for cores that omit them', async () => {- mockedCall.mockResolvedValueOnce({- result: { sources: [], sync_triggered: 0 },- logs: [],- } as never);- const legacy = await applyAllIn();- expect(legacy.sync_failed).toBe(0);- expect(legacy.sync_errors).toEqual([]);-- mockedCall.mockResolvedValueOnce({- result: { sources: [], sync_triggered: 0, sync_failed: 2, sync_errors: ['a: x', 'b: y'] },- logs: [],- } as never);- const failed = await applyAllIn();- expect(failed.sync_failed).toBe(2);- expect(failed.sync_errors).toEqual(['a: x', 'b: y']);- });-- it('applyAllIn handles envelope-wrapped response', async () => {- mockedCall.mockResolvedValue({ result: { sources: [], sync_triggered: 0 }, logs: [] } as never);-- const result = await applyAllIn();- expect(result.sources).toEqual([]);- expect(result.sync_triggered).toBe(0);- });-- it('applyAllIn handles flat (un-wrapped) response', async () => {- mockedCall.mockResolvedValue({- sources: [{ id: 'src_2', kind: 'folder', label: 'Docs', enabled: true }],- sync_triggered: 1,- } as never);-- const result = await applyAllIn();- expect(result.sources).toHaveLength(1);- });-- // ---------------------------------------------------------------------------- // MemorySourceEntry interface includes all limit fields- // ----------------------------------------------------------------------------- it('MemorySourceEntry interface accepts all limit fields at compile-time', () => {- // This test is a type-level assertion: if the fields are missing from the- // interface the assignment below would fail TypeScript compilation.- const entry: MemorySourceEntry = {- id: 'src_1',- kind: 'github_repo',- label: 'Test',- enabled: true,- max_commits: 100,- max_issues: 200,- max_prs: 50,- max_items: 500,- since_days: 30,- sync_depth_days: 90,- max_tokens_per_sync: 100_000,- max_cost_per_sync_usd: 1.5,- };- expect(entry.max_commits).toBe(100);- expect(entry.max_issues).toBe(200);- expect(entry.max_prs).toBe(50);- expect(entry.since_days).toBe(30);- expect(entry.sync_depth_days).toBe(90);- expect(entry.max_tokens_per_sync).toBe(100_000);- expect(entry.max_cost_per_sync_usd).toBe(1.5);- });-- it('discovers Codex and Claude Code session sources', async () => {- mockedCall.mockResolvedValue({- result: {- sources: [- { kind: 'codex', available: true, session_files: 2, evidence_units: 5, invalid_files: 0 },- ],- },- logs: [],- } as never);-- const sources = await getCodingSessionStatus();-- expect(mockedCall).toHaveBeenCalledWith({- method: 'openhuman.memory_sources_coding_session_status',- });- expect(sources[0]).toMatchObject({ kind: 'codex', evidence_units: 5 });- });-- it('requests a timeout-aligned incremental coding-session batch', async () => {- mockedCall.mockResolvedValue({- result: {- mode: 'incremental',- files_seen: 2,- sessions_processed: 2,- sessions_skipped: 0,- sessions_failed: 0,- evidence_units: 5,- observations: 3,- budget_hit: false,- },- logs: [],- } as never);-- const result = await ingestCodingSessions(false, 25);-- // Clamped to the batch max (5), and the per-call timeout stays under the RPC- // client's hard 600s ceiling: 120s + 5*90s + 15s = 585s.- expect(mockedCall).toHaveBeenCalledWith({- method: 'openhuman.memory_sources_ingest_coding_sessions',- params: { backfill: false, max_sessions: 5 },- timeoutMs: 585_000,- });- // Guard the cross-wire contract: the per-call timeout must stay under- // coreRpcClient's PER_CALL_TIMEOUT_MAX_MS (600s), or the override is clamped- // and silently unreachable (the #5509 gap). Raising BATCH_MAX / per-session- // past this must fail here.- const CORE_RPC_PER_CALL_TIMEOUT_MAX_MS = 10 * 60 * 1_000;- expect(585_000).toBeLessThanOrEqual(CORE_RPC_PER_CALL_TIMEOUT_MAX_MS);- expect(result.sessions_processed).toBe(2);- });-- const ingestResult = (over: Partial<Record<string, number | boolean>> = {}) =>- ({- result: {- mode: 'incremental',- files_seen: 40,- sessions_processed: 15,- sessions_skipped: 0,- sessions_failed: 0,- evidence_units: 30,- observations: 20,- budget_hit: true,- ...over,- },- logs: [],- }) as never;-- it('drains across bounded passes until the backlog reports no more budget', async () => {- // Two budget-hit passes, then a final pass that clears the backlog.- mockedCall- .mockResolvedValueOnce(ingestResult({ sessions_skipped: 0, budget_hit: true }))- .mockResolvedValueOnce(ingestResult({ sessions_skipped: 15, budget_hit: true }))- .mockResolvedValueOnce(- ingestResult({ sessions_processed: 10, sessions_skipped: 30, budget_hit: false })- );-- const seen: CodingSessionDrainProgress[] = [];- const result = await drainCodingSessions({ onProgress: p => seen.push(p) });-- expect(mockedCall).toHaveBeenCalledTimes(3);- // Every pass stays bounded to the timeout-safe per-call maximum.- expect(mockedCall).toHaveBeenLastCalledWith(- expect.objectContaining({ params: { backfill: false, max_sessions: 5 } })- );- expect(result.passes).toBe(3);- expect(result.sessionsProcessed).toBe(40); // 15 + 15 + 10- expect(result.observations).toBe(60); // 20 * 3- expect(result.moreRemaining).toBe(false);- expect(seen).toHaveLength(3);- });-- it('stops before a pass when shouldStop is asserted', async () => {- mockedCall.mockResolvedValue(ingestResult({ budget_hit: true }));- let calls = 0;-- const result = await drainCodingSessions({- // Allow one pass, then request a stop before the next.- shouldStop: () => calls++ >= 1,- });-- expect(mockedCall).toHaveBeenCalledTimes(1);- expect(result.passes).toBe(1);- expect(result.moreRemaining).toBe(true);- });-- it('reports a deadline as still-running, not as a thrown failure', async () => {- // The #5802 shape: a pass completes, the next one trips a deadline. No- // deadline in this stack cancels the import, so the run is still going —- // rejecting here is what put a red "failed" banner over work that- // succeeded seconds later.- mockedCall- .mockResolvedValueOnce(ingestResult({ sessions_processed: 3, budget_hit: true }))- .mockRejectedValueOnce(- new Error('ingest coding sessions: call to `IngestCodingSessions` timed out after 30000ms')- );-- const result = await drainCodingSessions();-- expect(result.timedOut).toBe(true);- // The completed pass's work is kept: those sessions really were imported.- expect(result.sessionsProcessed).toBe(3);- expect(result.passes).toBe(1);- });-- it('reports the core budget deadline too, which is spelled in seconds', async () => {- // `ingest_budget` renders "timed out after 570s". The seconds form does not- // match coreRpcClient's `\d+ms` timeout classifier, so a check that keyed- // only on CoreRpcError.kind would let this one through as a failure.- mockedCall.mockRejectedValueOnce(new Error('ingest coding sessions: timed out after 570s'));-- const result = await drainCodingSessions();-- expect(result.timedOut).toBe(true);- expect(result.sessionsProcessed).toBe(0);- });-- it('still rejects a genuine ingest failure', async () => {- // The other half of the contract: making a deadline non-fatal must not make- // everything non-fatal.- mockedCall.mockRejectedValueOnce(new Error('persona pipeline failed'));-- await expect(drainCodingSessions()).rejects.toThrow('persona pipeline failed');- });-- it('rejects a renderer-side abort instead of calling it still-running', async () => {- // The client's own AbortController proves the renderer stopped waiting and- // nothing else — a wedged, overloaded or absent core produces exactly the- // same signal as one happily distilling sessions. Suppressing it would show- // a false success over work that may never have started, which is #5802- // with the sign flipped. Only the core's own prefix is evidence.- const abort = Object.assign(- new Error(- 'Core RPC openhuman.memory_sources_ingest_coding_sessions timed out after 585000ms'- ),- { kind: 'timeout' }- );- mockedCall.mockRejectedValueOnce(abort);-- await expect(drainCodingSessions()).rejects.toThrow('timed out after 585000ms');- });-- it('isIngestTimeout suppresses only deadlines the core reported', () => {- // Suppressed: both shapes carry `ingest coding sessions: `, which only- // `ingest_coding_sessions_rpc` adds — proof the handler ran.- expect(- isIngestTimeout(- new Error('ingest coding sessions: call to `IngestCodingSessions` timed out after 30000ms')- )- ).toBe(true);- expect(isIngestTimeout(new Error('ingest coding sessions: timed out after 570s'))).toBe(true);-- // Not suppressed. A bare timeout phrase carries no evidence that anything- // was dispatched, and an unprefixed pattern would have swallowed an- // ordinary provider failure.- expect(isIngestTimeout(new Error('timed out after 30000ms'))).toBe(false);- expect(isIngestTimeout(new Error('request timed out after 30s'))).toBe(false);- expect(isIngestTimeout(new Error('Core RPC x timed out after 585000ms'))).toBe(false);- expect(isIngestTimeout(new Error('the request timed out'))).toBe(false);- expect(isIngestTimeout(new Error('session scan failed'))).toBe(false);- // A kind field alone is not evidence either.- expect(isIngestTimeout({ kind: 'timeout' })).toBe(false);- });-- it('stops when a budget-hit pass makes no forward progress', async () => {- // Backlog still reports budget_hit, but nothing new is distilled — avoid an- // infinite loop on sessions that only ever fail.- mockedCall.mockResolvedValue(- ingestResult({ sessions_processed: 0, sessions_failed: 3, budget_hit: true })- );-- const result = await drainCodingSessions();-- expect(mockedCall).toHaveBeenCalledTimes(1);- expect(result.sessionsFailed).toBe(3);- expect(result.moreRemaining).toBe(true);- });-});diff --git a/app/src/services/memorySourcesService.ts b/app/src/services/memorySourcesService.tsdeleted file mode 100644index d032126cd4..0000000000--- a/app/src/services/memorySourcesService.ts+++ /dev/null@@ -1,534 +0,0 @@-/**- * RPC client for the memory_sources domain.- *- * Wraps `openhuman.memory_sources_*` RPCs so UI components get typed- * responses without knowing the wire shape.- */-import debug from 'debug';--import { callCoreRpc } from './coreRpcClient';--const log = debug('memory-sources');--export type SourceKind =- | 'composio'- | 'conversation'- | 'folder'- | 'github_repo'- | 'twitter_query'- | 'rss_feed'- | 'web_page';--export interface MemorySourceEntry {- id: string;- kind: SourceKind;- label: string;- enabled: boolean;- toolkit?: string;- connection_id?: string;- path?: string;- glob?: string;- url?: string;- branch?: string;- paths?: string[];- query?: string;- selector?: string;- // Sync limit fields (all optional; omit = use backend default / unlimited)- since_days?: number;- max_items?: number;- max_commits?: number;- max_issues?: number;- max_prs?: number;- sync_depth_days?: number;- max_tokens_per_sync?: number;- max_cost_per_sync_usd?: number;-}--export interface SourceItem {- id: string;- title: string;- updated_at_ms?: number | null;-}--export interface SourceContent {- id: string;- title: string;- body: string;- content_type: 'markdown' | 'html' | 'plaintext';- metadata: Record<string, unknown>;-}--function unwrap<T>(raw: unknown): T {- const obj = raw as Record<string, unknown>;- if (obj && typeof obj === 'object' && 'result' in obj) {- return obj.result as T;- }- return raw as T;-}--export async function listMemorySources(): Promise<MemorySourceEntry[]> {- log('list');- const resp = await callCoreRpc<{ sources: MemorySourceEntry[] }>({- method: 'openhuman.memory_sources_list',- });- const data = unwrap<{ sources: MemorySourceEntry[] }>(resp);- return data.sources ?? [];-}--export async function getMemorySource(id: string): Promise<MemorySourceEntry | null> {- log('get id=%s', id);- const resp = await callCoreRpc<{ source: MemorySourceEntry | null }>({- method: 'openhuman.memory_sources_get',- params: { id },- });- const data = unwrap<{ source: MemorySourceEntry | null }>(resp);- return data.source ?? null;-}--export async function addMemorySource(- params: Omit<MemorySourceEntry, 'id'>-): Promise<MemorySourceEntry> {- log('add kind=%s label=%s', params.kind, params.label);- const resp = await callCoreRpc<{ source: MemorySourceEntry }>({- method: 'openhuman.memory_sources_add',- params,- });- const data = unwrap<{ source: MemorySourceEntry }>(resp);- return data.source;-}--export async function updateMemorySource(- id: string,- patch: Partial<Omit<MemorySourceEntry, 'id' | 'kind'>>-): Promise<MemorySourceEntry> {- log('update id=%s', id);- const resp = await callCoreRpc<{ source: MemorySourceEntry }>({- method: 'openhuman.memory_sources_update',- params: { id, ...patch },- });- const data = unwrap<{ source: MemorySourceEntry }>(resp);- return data.source;-}--export async function removeMemorySource(id: string): Promise<boolean> {- log('remove id=%s', id);- const resp = await callCoreRpc<{ removed: boolean }>({- method: 'openhuman.memory_sources_remove',- params: { id },- });- const data = unwrap<{ removed: boolean }>(resp);- return data.removed;-}--export async function listSourceItems(sourceId: string): Promise<SourceItem[]> {- log('list_items source_id=%s', sourceId);- const resp = await callCoreRpc<{ items: SourceItem[] }>({- method: 'openhuman.memory_sources_list_items',- params: { source_id: sourceId },- });- const data = unwrap<{ items: SourceItem[] }>(resp);- return data.items ?? [];-}--export async function readSourceItem(sourceId: string, itemId: string): Promise<SourceContent> {- log('read_item source_id=%s item_id=%s', sourceId, itemId);- const resp = await callCoreRpc<{ content: SourceContent }>({- method: 'openhuman.memory_sources_read_item',- params: { source_id: sourceId, item_id: itemId },- });- const data = unwrap<{ content: SourceContent }>(resp);- return data.content;-}--export type FreshnessLabel = 'active' | 'recent' | 'idle';--export interface SourceStatus {- source_id: string;- /**- * The source's display label (openhuman#6257), so a screen that reads only- * the status list can name the row. Absent from a core that predates it.- */- label?: string;- chunks_synced: number;- chunks_pending: number;- last_chunk_at_ms: number | null;- freshness: FreshnessLabel;- /**- * The stage of a sync the core has in flight for this source, `null` when- * none (openhuman#6019). Absent altogether from a core that predates the- * field — callers treat absent as "unknown", not as idle.- */- sync_stage?: string | null;- /** The detail that came with `sync_stage`, if any. */- sync_detail?: string | null;-}--export async function memorySourcesStatusList(): Promise<SourceStatus[]> {- log('status_list');- const resp = await callCoreRpc<{ statuses: SourceStatus[] }>({- method: 'openhuman.memory_sources_status_list',- });- const data = unwrap<{ statuses: SourceStatus[] }>(resp);- return data.statuses ?? [];-}--/**- * Per-call budget for the RPCs that run a whole source sync before answering- * (`memory_sources_sync`, `memory_sources_apply_all_in`).- *- * The client's default per-call timeout is 30 s and one Gmail page alone takes- * ~31 s end to end, so the default aborted the fetch while the core kept- * syncing: the row flipped to "failed" for work that then completed, and the- * run never showed as done (#5820). This is the client's own clamp ceiling- * (`PER_CALL_TIMEOUT_MAX_MS`); the core's bus deadline is sized to outlast it- * so this abort, with its clean message, is the one that fires if a run wedges.- */-export const MEMORY_SYNC_RPC_TIMEOUT_MS = 10 * 60 * 1_000;--export async function syncMemorySource(sourceId: string): Promise<void> {- log('sync source_id=%s', sourceId);- await callCoreRpc<{ requested: boolean }>({- method: 'openhuman.memory_sources_sync',- params: { source_id: sourceId },- timeoutMs: MEMORY_SYNC_RPC_TIMEOUT_MS,- });-}--/**- * Toolkit slugs that ship a native memory-sync provider (backend registry —- * `all_providers()`). The Add Source connection picker uses this to disable- * connections whose toolkit can never sync. Maps to- * `openhuman.memory_sources_supported_toolkits`. See issue #3352.- */-export async function getSupportedToolkits(): Promise<string[]> {- log('supported_toolkits');- const resp = await callCoreRpc<{ toolkits: string[] }>({- method: 'openhuman.memory_sources_supported_toolkits',- });- const data = unwrap<{ toolkits: string[] }>(resp);- return data.toolkits ?? [];-}--export interface ApplyAllInResult {- sources: MemorySourceEntry[];- sync_triggered: number;- /**- * Enabled sources whose sync trigger failed (openhuman#5820). Older cores- * omit it; the service normalises absence to `0`, so a caller can always- * read it. `sync_triggered === 0 && sync_failed > 0` is the "nothing- * started" outcome the toast must not report as success.- */- sync_failed: number;- /** One `<source_id>: <error>` line per failed trigger. */- sync_errors: string[];-}--/**- * Enables every memory source, clears all per-source sync caps, and- * triggers a background sync for each. Equivalent to the UI "All In"- * action. Maps to `openhuman.memory_sources_apply_all_in`.- */-export async function applyAllIn(): Promise<ApplyAllInResult> {- log('apply_all_in');- // All In runs every enabled source's sync to completion, one after another,- // before it answers; the budget has to cover the whole sweep.- const resp = await callCoreRpc<ApplyAllInResult>({- method: 'openhuman.memory_sources_apply_all_in',- timeoutMs: MEMORY_SYNC_RPC_TIMEOUT_MS,- });- const data = unwrap<ApplyAllInResult>(resp);- return {- sources: data.sources ?? [],- sync_triggered: data.sync_triggered ?? 0,- sync_failed: data.sync_failed ?? 0,- sync_errors: data.sync_errors ?? [],- };-}--export interface CodingSessionSourceStatus {- kind: 'claude_code' | 'codex';- available: boolean;- session_files: number;- evidence_units: number;- invalid_files: number;- scan_truncated?: boolean;-}--export interface CodingSessionIngestResult {- mode: 'backfill' | 'incremental';- files_seen: number;- sessions_processed: number;- sessions_skipped: number;- sessions_failed: number;- evidence_units: number;- observations: number;- budget_hit: boolean;- pack_path?: string | null;-}--// A single ingest RPC is bounded so it fits under the core RPC client's hard-// per-call ceiling (`PER_CALL_TIMEOUT_MAX_MS` = 600s in `coreRpcClient.ts`, which-// clamps every override — a larger request timeout is silently unreachable).-// The bound mirrors the core's `ingest_budget` (`memory/sources/rpc.rs`): the-// server sizes the same call at `120s + N*90s` and the client adds a 15s grace-// so the server's structured timeout fires first. Each multi-window session-// drives several sequential LLM calls (~90s/session), so the batch is kept small-// (`120s + 5*90s + 15s = 585s < 600s`) and large histories drain across repeated-// bounded passes via `drainCodingSessions`, driven by the response `budget_hit`-// flag — never by widening a single call past the reachable ceiling.-const CODING_SESSION_BATCH_MAX = 5;-const CODING_SESSION_BASE_TIMEOUT_MS = 120_000;-const CODING_SESSION_PER_SESSION_TIMEOUT_MS = 90_000;-const CODING_SESSION_RPC_GRACE_MS = 15_000;-// Hard safety cap on drain passes so a stuck backlog can never spin forever.-// Sized well above the largest realistic history: at 5 sessions/pass this covers-// ~10k sessions in a single run, so the target ~7,800-file case drains fully-// rather than exiting capped. The `moreRemaining` flag still lets the UI report-// an honest "paused" state if the cap is ever reached.-const CODING_SESSION_MAX_DRAIN_PASSES = 2000;--export async function getCodingSessionStatus(): Promise<CodingSessionSourceStatus[]> {- log('coding_session_status: entry');- const resp = await callCoreRpc<{ sources: CodingSessionSourceStatus[] }>({- method: 'openhuman.memory_sources_coding_session_status',- });- const data = unwrap<{ sources: CodingSessionSourceStatus[] }>(resp);- log('coding_session_status: exit sources=%d', data.sources?.length ?? 0);- return data.sources ?? [];-}--export async function ingestCodingSessions(- backfill = false,- maxSessions = CODING_SESSION_BATCH_MAX-): Promise<CodingSessionIngestResult> {- const boundedMaxSessions = Number.isFinite(maxSessions)- ? Math.min(Math.max(Math.trunc(maxSessions), 1), CODING_SESSION_BATCH_MAX)- : CODING_SESSION_BATCH_MAX;- const timeoutMs =- CODING_SESSION_BASE_TIMEOUT_MS +- boundedMaxSessions * CODING_SESSION_PER_SESSION_TIMEOUT_MS +- CODING_SESSION_RPC_GRACE_MS;- log(- 'ingest_coding_sessions: entry backfill=%s max_sessions=%d requested=%d timeout_ms=%d',- backfill,- boundedMaxSessions,- maxSessions,- timeoutMs- );- const resp = await callCoreRpc<CodingSessionIngestResult>({- method: 'openhuman.memory_sources_ingest_coding_sessions',- params: { backfill, max_sessions: boundedMaxSessions },- timeoutMs,- });- const data = unwrap<CodingSessionIngestResult>(resp);- log(- 'ingest_coding_sessions: exit processed=%d failed=%d budget_hit=%s',- data.sessions_processed,- data.sessions_failed,- data.budget_hit- );- return data;-}--export interface CodingSessionDrainProgress {- /** Bounded ingest RPC passes completed so far in this drain. */- passes: number;- /** Sessions distilled across every pass in this drain. */- sessionsProcessed: number;- /** Sessions retained for retry after a provider failure (latest pass). */- sessionsFailed: number;- /** Persona observations distilled across this drain. */- observations: number;- /** Best-effort backlog estimate reported by the latest pass. */- remaining: number;- /** True while the backlog still reported more work after the latest pass. */- moreRemaining: boolean;- /**- * True when a pass stopped waiting on a deadline rather than failing.- *- * The distinction is the whole point: no deadline in this stack cancels the- * work it bounds. The core's `ingest_budget` and tinybus' call deadline both- * only release the *caller* — tinybus says so in as many words: *"A timeout- * does not cancel the remote work."* So the import is still running, its- * result is simply not going to arrive on this call, and reporting it as a- * failure is both wrong and harmful: it invites a retry of a 35-60 s job- * that already succeeded (#5802).- */- timedOut: boolean;-}--/**- * Whether a rejected ingest pass is a deadline the **core itself** reported.- *- * Suppressing a timeout is only defensible when the work is genuinely still- * running, and that needs proof — not merely the absence of a reply. The proof- * used here is the message prefix: `ingest coding sessions: ` is added by- * `ingest_coding_sessions_rpc` (`crates/openhuman-core/src/memory/sources/rpc.rs`) around- * both of its deadline paths, so a message carrying it can only have been- * produced *inside* that handler. The core received the request, resolved the- * binding and started the call. Two shapes qualify:- *- * - `ingest coding sessions: timed out after 570s` — the RPC's own- * `ingest_budget` ceiling. Note the unit: **seconds**.- * - ``ingest coding sessions: call to `IngestCodingSessions` timed out after- * 30000ms`` — the tinybus call deadline, wrapped by the same handler.- * **Milliseconds.**- *- * Everything else is a failure, and two near-misses are deliberately excluded:- *- * - **The renderer's own `AbortController`** (`CoreRpcError` with- * `kind === 'timeout'`, message `Core RPC <method> timed out after <n>ms`).- * It proves the client stopped waiting and nothing more. A core that is- * wedged, overloaded, or not running produces exactly the same signal as one- * that is happily distilling sessions, so treating it as "still running"- * would show a false success and discourage a retry that is actually needed- * — the same false-reporting defect as #5802 with the sign flipped.- * - **A bare timeout phrase.** A provider failure surfacing as- * `request timed out after 30s` would have matched an unprefixed pattern.- *- * That asymmetry is the point: a *false negative* here costs a banner that- * says "failed" when the work continues — annoying, and recoverable, because- * the next status poll shows what landed. A *false positive* costs a banner- * that says "still running" over work that stopped, which is unrecoverable- * without the user noticing on their own. So the predicate is deliberately- * narrow and keyed on evidence rather than on symptom.- */-export function isIngestTimeout(cause: unknown): boolean {- const message = cause instanceof Error ? cause.message : String(cause);- return /ingest coding sessions:[\s\S]*timed out after \d+\s*(ms|s)\b/i.test(message);-}--export interface CodingSessionDrainOptions {- /** Called after each pass so the UI can render live progress. */- onProgress?: (progress: CodingSessionDrainProgress) => void;- /** Polled before each pass; return true to pause the drain cleanly. */- shouldStop?: () => boolean;- /** Per-pass batch bound; defaults to the RPC-timeout-safe maximum. */- maxSessionsPerPass?: number;- /** Hard cap on passes as a runaway guard. */- maxPasses?: number;-}--/**- * Drain the coding-session backlog across repeated bounded passes until it is- * empty, the caller stops it, or a pass makes no forward progress.- *- * Incremental mode only, by design: each pass skips already-distilled sessions- * by cursor, so the backlog strictly shrinks and the loop converges. Backfill- * re-reads every file regardless of cursor, so looping it under the per-call- * budget would re-process the same oldest slice forever and never drain — and- * because evidence ids are content-addressed, an incremental drain reproduces- * the same persona anyway.- */-export async function drainCodingSessions(- options: CodingSessionDrainOptions = {}-): Promise<CodingSessionDrainProgress> {- const { onProgress, shouldStop } = options;- const maxSessionsPerPass = options.maxSessionsPerPass ?? CODING_SESSION_BATCH_MAX;- // Normalize the safety cap: a non-finite or non-positive override would defeat- // the runaway guard, so fall back to the default in that case.- const maxPasses =- Number.isFinite(options.maxPasses) && (options.maxPasses as number) > 0- ? Math.trunc(options.maxPasses as number)- : CODING_SESSION_MAX_DRAIN_PASSES;-- const progress: CodingSessionDrainProgress = {- passes: 0,- sessionsProcessed: 0,- sessionsFailed: 0,- observations: 0,- remaining: 0,- moreRemaining: false,- timedOut: false,- };- log('drain_coding_sessions: entry max_per_pass=%d max_passes=%d', maxSessionsPerPass, maxPasses);-- while (progress.passes < maxPasses) {- if (shouldStop?.()) {- log('drain_coding_sessions: stop requested after pass=%d', progress.passes);- break;- }- let result: CodingSessionIngestResult;- try {- result = await ingestCodingSessions(false, maxSessionsPerPass);- } catch (cause) {- // A deadline is not a failure. Nothing in this stack cancels the import- // when a caller stops waiting for it, so the pass is still running and- // will still write its observations — it just has no report to hand back- // on this call. Rethrowing here is what put a red "ingestion failed"- // banner over a run that went on to succeed, and invited the user to- // redo 35-60 s of work (#5802).- //- // Returning rather than rethrowing keeps every completed pass's counts,- // which is the honest answer: those passes really did import what they- // report, and only the last one is unresolved.- if (!isIngestTimeout(cause)) throw cause;- progress.timedOut = true;- log('drain_coding_sessions: pass=%d timed out; work continues', progress.passes + 1);- onProgress?.({ ...progress });- break;- }- progress.passes += 1;- progress.sessionsProcessed += result.sessions_processed;- progress.sessionsFailed = result.sessions_failed;- progress.observations += result.observations;- // files_seen is the discovered total for this scan; skipped + processed is- // what this pass accounted for, so the remainder is the honest backlog.- progress.remaining = Math.max(- 0,- result.files_seen - result.sessions_skipped - result.sessions_processed- );- progress.moreRemaining = result.budget_hit;- onProgress?.({ ...progress });-- if (!result.budget_hit) {- log(- 'drain_coding_sessions: drained after pass=%d processed=%d',- progress.passes,- progress.sessionsProcessed- );- break;- }- if (result.sessions_processed === 0) {- // The backlog still reports more work, but this pass distilled nothing- // new — every remaining candidate failed or could not advance. Stop- // rather than spin; the caller surfaces the retained failures.- log('drain_coding_sessions: no forward progress on pass=%d — stopping', progress.passes);- break;- }- }-- log(- 'drain_coding_sessions: exit passes=%d processed=%d failed=%d remaining=%d more=%s',- progress.passes,- progress.sessionsProcessed,- progress.sessionsFailed,- progress.remaining,- progress.moreRemaining- );- return progress;-}--/// i18n keys for each source kind's user-visible label. Resolve via-/// `t(SOURCE_KIND_LABEL_KEYS[kind])` in components — keeping the keys-/// as a constant lets the dialog kind-picker render the same labels-/// without each call site duplicating the switch.-export const SOURCE_KIND_LABEL_KEYS: Record<SourceKind, string> = {- composio: 'memorySources.kind.composio',- conversation: 'memorySources.kind.conversation',- folder: 'memorySources.kind.folder',- github_repo: 'memorySources.kind.github_repo',- twitter_query: 'memorySources.kind.twitter_query',- rss_feed: 'memorySources.kind.rss_feed',- web_page: 'memorySources.kind.web_page',-};--export const SOURCE_KIND_ICONS: Record<SourceKind, string> = {- composio: '🔗',- conversation: '💬',- folder: '📁',- github_repo: '🐙',- twitter_query: '🐦',- rss_feed: '📡',- web_page: '🌐',-};diff --git a/app/src/utils/tauriCommands/memoryEngine.ts b/app/src/utils/tauriCommands/memoryEngine.tsdeleted file mode 100644index 1497b8ef0c..0000000000--- a/app/src/utils/tauriCommands/memoryEngine.ts+++ /dev/null@@ -1,131 +0,0 @@-/**- * Typed wrappers for the memory-engine RPCs (`openhuman.memory_engine*`).- *- * The core owns engine selection, credentials and migration; these wrappers- * only carry the wire shapes. Errors may be prefixed `INSUFFICIENT_CREDITS:`,- * `SESSION_EXPIRED:` or `BACKEND_UNAVAILABLE:` — see `memoryEngineErrors`.- */-import { callCoreRpc } from '../../services/coreRpcClient';-import { CORE_RPC_METHODS } from '../../services/rpcMethods';--export interface MemoryEngineDescriptor {- id: string;- label: string;- description: string;- needs_endpoint: boolean;- needs_key: boolean;- key_optional: boolean;- /** e.g. `["cloud", "self_hosted"]`, or empty when the engine has one shape. */- deployments: string[];- default_endpoint: string | null;- /** True when billed through OpenHuman credits and the signed-in session. */- hosted: boolean;- capabilities: string[];-}--export interface MemoryEnginesList {- engines: MemoryEngineDescriptor[];- active: string;-}--export interface MemoryEngineState {- driver: string;- endpoint: string | null;- deployment: string | null;- has_credential: boolean;- class: string;- fell_back_from: string | null;- last_error: string | null;-}--export interface MemoryEngineTarget {- driver: string;- endpoint?: string;- deployment?: string;- api_key?: string;-}--export type MemoryEngineMigrateState = 'running' | 'done' | 'failed' | 'cancelled';--/** What a migration copies, in the order it copies it. */-export type MemoryEngineMigrateStep =- | 'records'- | 'documents'- | 'goals'- | 'profile'- | 'episodic'- | 'content';--/** What one step after the stored memories did, once the copy finished. */-export interface MemoryEngineMigrateStepStatus {- step: Exclude<MemoryEngineMigrateStep, 'records'>;- /** Why the step did not run; null when it ran. */- skipped_because: string | null;- read: number;- written: number;- unchanged: number;- failed: number;- errors: string[];-}--export interface MemoryEngineMigrateStatus {- state: MemoryEngineMigrateState;- copied: number;- total: number | null;- error: string | null;- /** Caveat on a finished job (writes made while the copy ran); absent otherwise. */- note?: string | null;- /** The step under way, or the last one once the copy ended. */- step?: MemoryEngineMigrateStep | null;- /** Items the step under way has read so far. */- step_read?: number;- /** Items the step under way has written so far. */- step_written?: number;- /** What each step after the stored memories did, once the copy finished. */- steps?: MemoryEngineMigrateStepStatus[];-}--export async function memoryEnginesList(): Promise<MemoryEnginesList> {- return await callCoreRpc<MemoryEnginesList>({ method: CORE_RPC_METHODS.memoryEnginesList });-}--export async function memoryEngineGet(): Promise<MemoryEngineState> {- return await callCoreRpc<MemoryEngineState>({ method: CORE_RPC_METHODS.memoryEngineGet });-}--export async function memoryEngineSet(target: MemoryEngineTarget): Promise<MemoryEngineState> {- return await callCoreRpc<MemoryEngineState>({- method: CORE_RPC_METHODS.memoryEngineSet,- params: target,- });-}--/**- * Copies every memory from the active engine into `to`, then switches to it.- * `replayContent` re-sends ingested content so the new engine rebuilds its- * summaries; it defaults to true.- */-export async function memoryEngineMigrate(- to: MemoryEngineTarget,- options: { replayContent?: boolean } = {}-): Promise<{ job_id: string }> {- return await callCoreRpc<{ job_id: string }>({- method: CORE_RPC_METHODS.memoryEngineMigrate,- params: { to, replay_content: options.replayContent ?? true },- });-}--export async function memoryEngineMigrateStatus(jobId: string): Promise<MemoryEngineMigrateStatus> {- return await callCoreRpc<MemoryEngineMigrateStatus>({- method: CORE_RPC_METHODS.memoryEngineMigrateStatus,- params: { job_id: jobId },- });-}--/** Stops a running migration; the active engine is left unchanged. */-export async function memoryEngineMigrateCancel(jobId: string): Promise<{ cancelled: boolean }> {- return await callCoreRpc<{ cancelled: boolean }>({- method: CORE_RPC_METHODS.memoryEngineMigrateCancel,- params: { job_id: jobId },- });-}diff --git a/app/src/utils/tauriCommands/memoryTree.test.ts b/app/src/utils/tauriCommands/memoryTree.test.tsdeleted file mode 100644index b18fbb6698..0000000000--- a/app/src/utils/tauriCommands/memoryTree.test.ts+++ /dev/null@@ -1,576 +0,0 @@-/**- * Unit tests for memory_tree RPC wrappers. Mirror the pattern used by- * `memory.test.ts` — mock the underlying `callCoreRpc` and assert that- * each helper dispatches the right method name + params and unwraps- * `Outcome`'s `{ result, logs }` envelope correctly.- */-import { beforeEach, describe, expect, type Mock, test, vi } from 'vitest';--import { callCoreRpc } from '../../services/coreRpcClient';-import {- memoryNamespaceSummaries,- memorySyncStatusList,- memoryTreeBackfillConnectorTrees,- memoryTreeBackfillStatus,- memoryTreeChunkScore,- memoryTreeDeleteChunk,- memoryTreeEntityIndexFor,- memoryTreeFlushNow,- memoryTreeGetLlm,- memoryTreeGraphExport,- memoryTreeListChunks,- memoryTreeListSources,- memoryTreeObsidianVaultStatus,- memoryTreeRecall,- memoryTreeResetTree,- memoryTreeRetryFailed,- memoryTreeSearch,- memoryTreeSetLlm,- memoryTreeTopEntities,- memoryTreeWipeAll,-} from './memoryTree';--vi.mock('../../services/coreRpcClient', () => ({ callCoreRpc: vi.fn() }));--const mockCallCoreRpc = callCoreRpc as Mock;--beforeEach(() => {- vi.clearAllMocks();-});--describe('memoryTreeListChunks', () => {- test('dispatches openhuman.memory_tree_list_chunks with the filter as params', async () => {- mockCallCoreRpc.mockResolvedValueOnce({- result: { chunks: [], total: 0 },- logs: ['memory_tree::read: list_chunks n=0 total=0'],- });-- const out = await memoryTreeListChunks({ limit: 50 });-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_tree_list_chunks',- params: { limit: 50 },- });- expect(out).toEqual({ chunks: [], total: 0 });- });-- test('handles bare-value responses (no logs envelope)', async () => {- mockCallCoreRpc.mockResolvedValueOnce({ chunks: [{ id: 'c1' }], total: 1 });- const out = await memoryTreeListChunks({});- expect(out.total).toBe(1);- expect(out.chunks[0]?.id).toBe('c1');- });-});--describe('memoryTreeListSources', () => {- test('omits user_email_hint when not provided', async () => {- mockCallCoreRpc.mockResolvedValueOnce({ result: [], logs: ['stub'] });-- await memoryTreeListSources();-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_tree_list_sources',- params: {},- });- });-- test('forwards user_email_hint when provided', async () => {- mockCallCoreRpc.mockResolvedValueOnce({ result: [], logs: ['stub'] });-- await memoryTreeListSources('[email protected]');-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_tree_list_sources',- params: { user_email_hint: '[email protected]' },- });- });-- test('returns the unwrapped Source array', async () => {- const sources = [- {- source_id: 'gmail:x|y',- display_name: 'X',- source_kind: 'email',- chunk_count: 2,- most_recent_ms: 1,- },- ];- mockCallCoreRpc.mockResolvedValueOnce({ result: sources, logs: ['stub'] });- const out = await memoryTreeListSources();- expect(out).toEqual(sources);- });-});--describe('memoryTreeSearch', () => {- test('dispatches with query + k', async () => {- mockCallCoreRpc.mockResolvedValueOnce({ result: [], logs: ['stub'] });-- await memoryTreeSearch('phoenix', 25);-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_tree_search',- params: { query: 'phoenix', k: 25 },- });- });-});--describe('memoryTreeRecall', () => {- test('dispatches with query + k and unwraps the recall envelope', async () => {- mockCallCoreRpc.mockResolvedValueOnce({- result: { chunks: [{ id: 'c1' }], scores: [0.9] },- logs: ['stub'],- });-- const out = await memoryTreeRecall('design sync', 10);-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_tree_recall',- params: { query: 'design sync', k: 10 },- });- expect(out.chunks).toHaveLength(1);- expect(out.scores[0]).toBe(0.9);- });-});--describe('memoryTreeEntityIndexFor', () => {- test('dispatches with chunk_id', async () => {- mockCallCoreRpc.mockResolvedValueOnce({ result: [], logs: ['stub'] });-- await memoryTreeEntityIndexFor('chunk-abc');-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_tree_entity_index_for',- params: { chunk_id: 'chunk-abc' },- });- });-});--describe('memoryTreeTopEntities', () => {- test('omits kind when not provided and defaults limit to 50', async () => {- mockCallCoreRpc.mockResolvedValueOnce({ result: [], logs: ['stub'] });-- await memoryTreeTopEntities();-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_tree_top_entities',- params: { limit: 50 },- });- });-- test('forwards kind + custom limit when provided', async () => {- mockCallCoreRpc.mockResolvedValueOnce({ result: [], logs: ['stub'] });-- await memoryTreeTopEntities('person', 12);-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_tree_top_entities',- params: { limit: 12, kind: 'person' },- });- });-});--describe('memoryTreeChunkScore', () => {- test('returns null when the core reports no score row', async () => {- mockCallCoreRpc.mockResolvedValueOnce({ result: null, logs: ['stub'] });-- const out = await memoryTreeChunkScore('chunk-missing');-- expect(out).toBeNull();- });-- test('unwraps the breakdown when present', async () => {- const breakdown = {- signals: [{ name: 'token_count', weight: 1, value: 0.5 }],- total: 0.5,- threshold: 0.85,- kept: false,- llm_consulted: false,- };- mockCallCoreRpc.mockResolvedValueOnce({ result: breakdown, logs: ['stub'] });-- const out = await memoryTreeChunkScore('chunk-real');-- expect(out).toEqual(breakdown);- });-});--describe('memoryTreeDeleteChunk', () => {- test('dispatches with chunk_id and surfaces the full DeleteChunkResponse', async () => {- mockCallCoreRpc.mockResolvedValueOnce({- result: { deleted: true, score_rows_removed: 1, entity_index_rows_removed: 3 },- logs: ['stub'],- });-- const out = await memoryTreeDeleteChunk('chunk-xyz');-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_tree_delete_chunk',- params: { chunk_id: 'chunk-xyz' },- });- expect(out).toEqual({ deleted: true, score_rows_removed: 1, entity_index_rows_removed: 3 });- });-});--describe('memoryTreeGetLlm / memoryTreeSetLlm', () => {- test('get_llm dispatches without params', async () => {- mockCallCoreRpc.mockResolvedValueOnce({ result: { current: 'cloud' }, logs: ['stub'] });-- const out = await memoryTreeGetLlm();-- expect(mockCallCoreRpc).toHaveBeenCalledWith({ method: 'openhuman.memory_tree_get_llm' });- expect(out.current).toBe('cloud');- });-- test('set_llm dispatches with backend param and returns the effective value', async () => {- mockCallCoreRpc.mockResolvedValueOnce({ result: { current: 'local' }, logs: ['stub'] });-- const out = await memoryTreeSetLlm('local');-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_tree_set_llm',- params: { backend: 'local' },- });- expect(out.current).toBe('local');- });-- test('set_llm forwards optional per-role model fields verbatim as snake_case', async () => {- // The wrapper takes either a bare backend string (legacy) or the full- // request object. When the caller passes a request, the snake_case- // field names must reach the wire untouched — no camelCase- // translation lives in this layer.- mockCallCoreRpc.mockResolvedValueOnce({ result: { current: 'local' }, logs: ['stub'] });-- const out = await memoryTreeSetLlm({- backend: 'local',- extract_model: 'qwen2.5:0.5b',- summariser_model: 'gemma3:1b-it-qat',- });-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_tree_set_llm',- params: {- backend: 'local',- extract_model: 'qwen2.5:0.5b',- summariser_model: 'gemma3:1b-it-qat',- },- });- expect(out.current).toBe('local');- });-- test('set_llm with cloud_model only flips backend + cloud model', async () => {- mockCallCoreRpc.mockResolvedValueOnce({ result: { current: 'cloud' }, logs: ['stub'] });-- await memoryTreeSetLlm({ backend: 'cloud', cloud_model: 'summarizer-v2' });-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_tree_set_llm',- params: { backend: 'cloud', cloud_model: 'summarizer-v2' },- });- });-});--describe('memoryTreeFlushNow', () => {- test('dispatches flush_now and returns the unwrapped envelope', async () => {- mockCallCoreRpc.mockResolvedValueOnce({- result: { enqueued: true, stale_buffers: 4 },- logs: ['stub'],- });-- const out = await memoryTreeFlushNow();-- expect(mockCallCoreRpc).toHaveBeenCalledWith({ method: 'openhuman.memory_tree_flush_now' });- expect(out).toEqual({ enqueued: true, stale_buffers: 4 });- });-- test('passes through bare-shape responses (no envelope) unchanged', async () => {- // Defensive path: if a future Rust handler stops emitting logs the- // bare value flows through `unwrapResult` unchanged.- mockCallCoreRpc.mockResolvedValueOnce({ enqueued: false, stale_buffers: 0 });-- const out = await memoryTreeFlushNow();-- expect(out).toEqual({ enqueued: false, stale_buffers: 0 });- });-});--describe('memoryTreeWipeAll', () => {- test('dispatches wipe_all and returns the unwrapped envelope', async () => {- mockCallCoreRpc.mockResolvedValueOnce({- result: { rows_deleted: 12, dirs_removed: ['raw', 'wiki'], sync_state_cleared: 1 },- logs: ['stub'],- });-- const out = await memoryTreeWipeAll();-- expect(mockCallCoreRpc).toHaveBeenCalledWith({ method: 'openhuman.memory_tree_wipe_all' });- expect(out.rows_deleted).toBe(12);- expect(out.dirs_removed).toEqual(['raw', 'wiki']);- expect(out.sync_state_cleared).toBe(1);- });-});--describe('memoryTreeResetTree', () => {- test('dispatches reset_tree and returns the unwrapped envelope', async () => {- mockCallCoreRpc.mockResolvedValueOnce({- result: { tree_rows_deleted: 8, chunks_requeued: 5, jobs_enqueued: 5 },- logs: ['stub'],- });-- const out = await memoryTreeResetTree();-- expect(mockCallCoreRpc).toHaveBeenCalledWith({ method: 'openhuman.memory_tree_reset_tree' });- expect(out).toEqual({ tree_rows_deleted: 8, chunks_requeued: 5, jobs_enqueued: 5 });- });-});--describe('memoryTreeGraphExport', () => {- test('defaults to mode=tree and returns the unwrapped envelope', async () => {- mockCallCoreRpc.mockResolvedValueOnce({- result: { nodes: [], edges: [], content_root_abs: '/tmp/workspace/memory_tree/content' },- logs: ['stub'],- });-- const out = await memoryTreeGraphExport();-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_tree_graph_export',- params: { mode: 'tree' },- });- expect(out.nodes).toEqual([]);- expect(out.edges).toEqual([]);- expect(out.content_root_abs).toBe('/tmp/workspace/memory_tree/content');- });-- test('forwards explicit mode=contacts to the wire params', async () => {- mockCallCoreRpc.mockResolvedValueOnce({- result: {- nodes: [{ kind: 'chunk', id: 'c1', label: 'one' }],- edges: [{ from: 'c1', to: 'p1' }],- content_root_abs: '/tmp/x',- },- logs: ['stub'],- });-- const out = await memoryTreeGraphExport('contacts');-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_tree_graph_export',- params: { mode: 'contacts' },- });- expect(out.nodes).toHaveLength(1);- expect(out.edges).toHaveLength(1);- });-});--describe('memoryTreeBackfillStatus', () => {- test('dispatches openhuman.memory_tree_memory_backfill_status and unwraps', async () => {- mockCallCoreRpc.mockResolvedValueOnce({- result: { in_progress: true, pending_jobs: 3 },- logs: ['memory_tree: backfill_status in_progress=true pending=3'],- });-- const out = await memoryTreeBackfillStatus();-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_tree_memory_backfill_status',- });- expect(out.in_progress).toBe(true);- expect(out.pending_jobs).toBe(3);- });-- test('handles bare-value responses (no logs envelope)', async () => {- mockCallCoreRpc.mockResolvedValueOnce({ in_progress: false, pending_jobs: 0 });- const out = await memoryTreeBackfillStatus();- expect(out.in_progress).toBe(false);- expect(out.pending_jobs).toBe(0);- });-});--describe('memoryTreeObsidianVaultStatus', () => {- test('dispatches with the config-dir override when one is provided', async () => {- mockCallCoreRpc.mockResolvedValueOnce({- result: {- registered: false,- config_found: true,- content_root_abs: '/ws/memory_tree/content',- },- logs: ['memory_tree::read: obsidian_vault_status registered=false config_found=true'],- });-- const out = await memoryTreeObsidianVaultStatus('/custom/obsidian');-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_tree_obsidian_vault_status',- params: { obsidian_config_dir: '/custom/obsidian' },- });- expect(out.registered).toBe(false);- expect(out.config_found).toBe(true);- });-- test('omits the override param and unwraps a bare-value response', async () => {- mockCallCoreRpc.mockResolvedValueOnce({- registered: true,- config_found: true,- content_root_abs: '/ws/memory_tree/content',- });-- const out = await memoryTreeObsidianVaultStatus();-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_tree_obsidian_vault_status',- params: {},- });- expect(out.registered).toBe(true);- });-});--describe('memorySyncStatusList', () => {- test('dispatches openhuman.memory_sync_status_list and returns the rows from a result envelope', async () => {- mockCallCoreRpc.mockResolvedValueOnce({- result: {- statuses: [- {- provider: 'slack',- chunks_synced: 5,- chunks_pending: 0,- batch_total: 0,- batch_processed: 0,- last_chunk_at_ms: 1_700_000_000_000,- freshness: 'active',- },- ],- },- });-- const rows = await memorySyncStatusList();-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_sync_status_list',- params: {},- });- expect(rows).toHaveLength(1);- expect(rows[0].provider).toBe('slack');- expect(rows[0].freshness).toBe('active');- });-- test('handles bare-value responses (no logs envelope)', async () => {- mockCallCoreRpc.mockResolvedValueOnce({ statuses: [] });- const rows = await memorySyncStatusList();- expect(rows).toEqual([]);- });-- test('falls back to empty array when statuses is missing', async () => {- mockCallCoreRpc.mockResolvedValueOnce({});- const rows = await memorySyncStatusList();- expect(rows).toEqual([]);- });-});--describe('memoryTreeRetryFailed', () => {- test('dispatches memory_tree_retry_failed with empty params and returns the count', async () => {- mockCallCoreRpc.mockResolvedValueOnce({ result: { requeued: 5 }, logs: ['stub'] });-- const out = await memoryTreeRetryFailed();-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_tree_retry_failed',- params: {},- });- expect(out).toEqual({ requeued: 5 });- });-- test('passes through bare-shape responses (no envelope) unchanged', async () => {- // Defensive path: a handler that stops emitting logs returns the bare- // value, which flows through `unwrapResult` untouched.- mockCallCoreRpc.mockResolvedValueOnce({ requeued: 0 });-- const out = await memoryTreeRetryFailed();-- expect(out).toEqual({ requeued: 0 });- });-});--describe('memoryNamespaceSummaries', () => {- // The stored-document total is the sync-verification number the tree tiles- // cannot answer (#5932: a user watched 100 items land while the tree figure- // sat at 2), so both the dispatch and the envelope unwrap are pinned here.- test('dispatches openhuman.memory_namespace_summaries and returns the rows plus total', async () => {- mockCallCoreRpc.mockResolvedValueOnce({- result: {- namespaces: [- { namespace: 'slack', count: 80, last_updated: '2026-09-01T12:00:00Z' },- { namespace: 'gmail', count: 20, last_updated: null },- ],- total_documents: 100,- },- logs: ['memory::namespaces: summaries n=2 total=100'],- });-- const out = await memoryNamespaceSummaries();-- expect(mockCallCoreRpc).toHaveBeenCalledWith({- method: 'openhuman.memory_namespace_summaries',- params: {},- });- expect(out.total_documents).toBe(100);- expect(out.namespaces).toHaveLength(2);- expect(out.namespaces[0].namespace).toBe('slack');- expect(out.namespaces[0].count).toBe(80);- });-- test('passes through bare-shape responses (no logs envelope) unchanged', async () => {- mockCallCoreRpc.mockResolvedValueOnce({ namespaces: [], total_documents: 0 });-- const out = await memoryNamespaceSummaries();-- expect(out).toEqual({ namespaces: [], total_documents: 0 });- });-});--describe('memoryTreeBackfillConnectorTrees', () => {- test('sends dry_run and omits limit when none is given', async () => {- mockCallCoreRpc.mockResolvedValueOnce({- result: {- executed: false,- scanned: 12,- ingested: 0,- already_present: 0,- skipped: 0,- more_pending: false,- notes: [],- },- logs: ['stub'],- });-- const out = await memoryTreeBackfillConnectorTrees({ dryRun: true });-- expect(mockCallCoreRpc).toHaveBeenCalledWith(- expect.objectContaining({- method: 'openhuman.memory_tree_backfill_connector_trees',- params: { dry_run: true },- })- );- expect(out.executed).toBe(false);- expect(out.scanned).toBe(12);- });-- test('forwards a limit and unwraps a bare (non-envelope) reply', async () => {- mockCallCoreRpc.mockResolvedValueOnce({- executed: true,- scanned: 5,- ingested: 4,- already_present: 1,- skipped: 0,- more_pending: true,- notes: [],- });-- const out = await memoryTreeBackfillConnectorTrees({ dryRun: false, limit: 5 });-- expect(mockCallCoreRpc).toHaveBeenCalledWith(- expect.objectContaining({ params: { dry_run: false, limit: 5 } })- );- expect(out.ingested).toBe(4);- expect(out.more_pending).toBe(true);- });-});diff --git a/app/src/utils/tauriCommands/memoryTree.ts b/app/src/utils/tauriCommands/memoryTree.tsdeleted file mode 100644index 0dad16785f..0000000000--- a/app/src/utils/tauriCommands/memoryTree.ts+++ /dev/null@@ -1,1182 +0,0 @@-/**- * memory_tree subsystem commands.- *- * Thin wrappers over the `openhuman.memory_tree_*` JSON-RPC surface that- * powers the Memory tab and the Settings → AI backend chooser. Method- * shapes mirror the Rust handlers in `crates/openhuman-core/src/memory/tree/read_rpc.rs`- * and `schemas.rs`.- *- * Responses come back wrapped by `Outcome::single_log` as- * `{ result: <T>, logs: string[] }` (single-log envelope). Each helper- * unwraps `result` so callers see the bare value the Rust handler- * returned, falling back gracefully if a future handler stops emitting- * logs and the bare value flows through.- *- * Logging convention: `[memory-tree-rpc]` prefix for grep-friendly tracing- * per the project debug-logging rule.- */-import { callCoreRpc } from '../../services/coreRpcClient';--// ── Public types — match the memory_tree RPC contract ────────────────────--/**- * Source kind values the Rust core uses for canonical chunk metadata.- * The list is closed for the surfaces the Memory tab cares about, but- * the wire type is `string` so any future kind round-trips through the- * UI without a recompile.- */-export type SourceKind = 'email' | 'chat' | 'screen' | 'voice' | 'doc';--/** Chunk lifecycle phase as emitted by the admission gate. */-export type LifecycleStatus = 'admitted' | 'buffered' | 'pending_extraction' | 'dropped';--/**- * Canonical entity-kind strings emitted by the entity index. Kept- * permissive (`string`) on the Rust side; the TS union is the curated- * subset the UI knows how to render.- */-export type EntityKind =- | 'person'- | 'organization'- | 'location'- | 'event'- | 'product'- | 'datetime'- | 'technology'- | 'artifact'- | 'quantity'- | 'misc';--/**- * A single chunk in the memory tree — one user-visible message-sized unit- * (an email, a chat turn, a doc page, a transcribed voice clip).- *- * Wire shape mirrors Rust's [`ChunkRow`](crates/openhuman-core/src/memory/tree/read_rpc.rs)- * — body is replaced with a `≤500-char preview` plus a flag indicating- * whether the row has an embedding.- */-export interface Chunk {- id: string;- source_kind: SourceKind;- source_id: string;- source_ref?: string;- owner: string;- timestamp_ms: number;- token_count: number;- lifecycle_status: LifecycleStatus;- content_path?: string;- /** Up to 500 chars; used as the result-list subject preview. */- content_preview?: string;- has_embedding: boolean;- /** Hierarchical: ["person/Steve-Enamakel", "organization/TinyHumans"]. */- tags: string[];-}--export interface ChunkFilter {- source_kinds?: string[];- source_ids?: string[];- entity_ids?: string[];- since_ms?: number;- until_ms?: number;- query?: string;- limit?: number;- offset?: number;-}--export interface ListChunksResponse {- chunks: Chunk[];- total: number;-}--/**- * Distinct ingest source as returned by `memory_tree_list_sources`.- *- * `lifecycle_status` is **optional** — the Rust handler does not emit it- * (it's a UI-derived aggregate), but the navigator pane wants a per-source- * dot color. Consumers compute it from chunk-level state and pass it in,- * or omit it and the UI falls back to a neutral dot.- */-export interface Source {- source_id: string;- /** Un-slugged readable; user-email stripped when `user_email_hint` matched. */- display_name: string;- source_kind: string;- chunk_count: number;- most_recent_ms: number;- lifecycle_status?: LifecycleStatus;-}--export interface EntityRef {- /** Canonical id (e.g. `person:Steven Enamakel`, `email:[email protected]`). */- entity_id: string;- kind: string;- surface: string;- count: number;-}--export interface ScoreSignal {- name: string;- weight: number;- value: number;-}--export interface ScoreBreakdown {- signals: ScoreSignal[];- total: number;- threshold: number;- kept: boolean;- llm_consulted: boolean;-}--export interface RecallResponse {- chunks: Chunk[];- scores: number[];-}--/**- * Response shape for `memory_tree_delete_chunk`. The Rust handler also- * surfaces the number of dependent rows removed so UIs can render a- * detailed "purged X / Y / Z" toast.- */-export interface DeleteChunkResponse {- deleted: boolean;- score_rows_removed: number;- entity_index_rows_removed: number;-}--/** Backend selector value. */-export type LlmBackend = 'cloud' | 'local';--export interface LlmResponse {- current: LlmBackend;-}--/**- * Wire shape for `openhuman.memory_tree_set_llm`.- *- * `backend` is required and always overwrites `memory_tree.llm_backend`.- *- * The three model fields are optional; absent means "leave the- * corresponding `memory_tree.*_model` config key untouched", present- * means "overwrite it". This lets the UI flip the backend without- * touching models, or persist a per-role model selection without having- * to re-supply every other model id. Field names are snake_case to match- * the Rust `SetLlmRequest` struct verbatim — the wrapper does not- * translate.- */-export interface SetLlmRequest {- backend: LlmBackend;- cloud_model?: string;- extract_model?: string;- summariser_model?: string;-}--// ── Envelope unwrap helper ────────────────────────────────────────────────--/**- * Internal envelope shape produced by `Outcome::single_log` on the- * Rust side. Every read_rpc handler emits at least one log line, so the- * shape will be `{ result, logs }` in practice — but we keep the- * fallback path for defensive parsing.- */-interface ResultEnvelope<T> {- result?: T;- logs?: string[];-}--function unwrapResult<T>(resp: T | ResultEnvelope<T>): T {- if (resp && typeof resp === 'object' && 'result' in resp) {- return (resp as ResultEnvelope<T>).result as T;- }- return resp as T;-}--// ── memory_tree_list_chunks ──────────────────────────────────────────────--/**- * Paginated chunk listing with optional filters. Backed by- * `openhuman.memory_tree_list_chunks`.- */-export async function memoryTreeListChunks(filter: ChunkFilter): Promise<ListChunksResponse> {- console.debug('[memory-tree-rpc] memoryTreeListChunks: entry filter=%o', filter);- const resp = await callCoreRpc<ListChunksResponse | ResultEnvelope<ListChunksResponse>>({- method: 'openhuman.memory_tree_list_chunks',- params: filter,- });- const out = unwrapResult(resp);- console.debug(- '[memory-tree-rpc] memoryTreeListChunks: exit n=%d total=%d',- out.chunks?.length ?? 0,- out.total ?? 0- );- return out;-}--// ── memory_tree_list_sources ─────────────────────────────────────────────--/**- * Distinct (source_kind, source_id) pairs with chunk counts and most-recent- * timestamps. `user_email_hint` (when supplied) tells the Rust handler to- * strip that address from email-thread display names.- */-export async function memoryTreeListSources(userEmailHint?: string): Promise<Source[]> {- console.debug(- '[memory-tree-rpc] memoryTreeListSources: entry hint=%s',- userEmailHint ?? '<none>'- );- const params = userEmailHint ? { user_email_hint: userEmailHint } : {};- const resp = await callCoreRpc<Source[] | ResultEnvelope<Source[]>>({- method: 'openhuman.memory_tree_list_sources',- params,- });- const out = unwrapResult(resp);- console.debug('[memory-tree-rpc] memoryTreeListSources: exit n=%d', out?.length ?? 0);- return out ?? [];-}--// ── memory_tree_search ───────────────────────────────────────────────────--/**- * Keyword `LIKE`-search over chunk bodies. Cheap, deterministic; useful- * as a fallback when semantic recall is unavailable.- */-export async function memoryTreeSearch(query: string, k: number): Promise<Chunk[]> {- console.debug('[memory-tree-rpc] memoryTreeSearch: entry query_len=%d k=%d', query.length, k);- const resp = await callCoreRpc<Chunk[] | ResultEnvelope<Chunk[]>>({- method: 'openhuman.memory_tree_search',- params: { query, k },- });- const out = unwrapResult(resp);- console.debug('[memory-tree-rpc] memoryTreeSearch: exit n=%d', out?.length ?? 0);- return out ?? [];-}--// ── memory_tree_recall ───────────────────────────────────────────────────--/**- * Semantic recall via the Phase 4 cosine rerank path. Returns leaf chunks- * and a parallel `scores` array.- */-export async function memoryTreeRecall(query: string, k: number): Promise<RecallResponse> {- console.debug('[memory-tree-rpc] memoryTreeRecall: entry query_len=%d k=%d', query.length, k);- const resp = await callCoreRpc<RecallResponse | ResultEnvelope<RecallResponse>>({- method: 'openhuman.memory_tree_recall',- params: { query, k },- });- const out = unwrapResult(resp);- console.debug('[memory-tree-rpc] memoryTreeRecall: exit n=%d', out?.chunks?.length ?? 0);- return out ?? { chunks: [], scores: [] };-}--// ── memory_tree_entity_index_for ─────────────────────────────────────────--/**- * All canonical entities indexed against a single chunk (or summary node) id.- */-export async function memoryTreeEntityIndexFor(chunkId: string): Promise<EntityRef[]> {- console.debug('[memory-tree-rpc] memoryTreeEntityIndexFor: entry chunk_id=%s', chunkId);- const resp = await callCoreRpc<EntityRef[] | ResultEnvelope<EntityRef[]>>({- method: 'openhuman.memory_tree_entity_index_for',- params: { chunk_id: chunkId },- });- const out = unwrapResult(resp);- console.debug('[memory-tree-rpc] memoryTreeEntityIndexFor: exit n=%d', out?.length ?? 0);- return out ?? [];-}--// ── memory_tree_chunks_for_entity ────────────────────────────────────────--/**- * Inverse of `memoryTreeEntityIndexFor` — return chunk IDs that reference- * the given entity. Used by the Memory tab's People/Topics lenses to- * filter the chunk list to those mentioning a selected entity.- */-export async function memoryTreeChunksForEntity(entityId: string): Promise<string[]> {- console.debug('[memory-tree-rpc] memoryTreeChunksForEntity: entry entity_id=%s', entityId);- const resp = await callCoreRpc<string[] | ResultEnvelope<string[]>>({- method: 'openhuman.memory_tree_chunks_for_entity',- params: { entity_id: entityId },- });- const out = unwrapResult(resp);- console.debug('[memory-tree-rpc] memoryTreeChunksForEntity: exit n=%d', out?.length ?? 0);- return out ?? [];-}--// ── memory_tree_top_entities ─────────────────────────────────────────────--/**- * Most-frequent canonical entities across the workspace, optionally narrowed- * by `kind`. The Rust handler treats `limit` as required; we default to 50- * to match the navigator's lens cardinality.- */-export async function memoryTreeTopEntities(kind?: string, limit = 50): Promise<EntityRef[]> {- console.debug(- '[memory-tree-rpc] memoryTreeTopEntities: entry kind=%s limit=%d',- kind ?? '<all>',- limit- );- const params: Record<string, unknown> = { limit };- if (kind) params.kind = kind;- const resp = await callCoreRpc<EntityRef[] | ResultEnvelope<EntityRef[]>>({- method: 'openhuman.memory_tree_top_entities',- params,- });- const out = unwrapResult(resp);- console.debug('[memory-tree-rpc] memoryTreeTopEntities: exit n=%d', out?.length ?? 0);- return out ?? [];-}--// ── memory_tree_chunk_score ──────────────────────────────────────────────--/**- * Score breakdown stored in `mem_tree_score` for one chunk. Returns- * `null` when the chunk has no score row (e.g. it was admitted before- * scoring was enabled, or it is a synthesized fixture in tests).- */-export async function memoryTreeChunkScore(chunkId: string): Promise<ScoreBreakdown | null> {- console.debug('[memory-tree-rpc] memoryTreeChunkScore: entry chunk_id=%s', chunkId);- const resp = await callCoreRpc<ScoreBreakdown | null | ResultEnvelope<ScoreBreakdown | null>>({- method: 'openhuman.memory_tree_chunk_score',- params: { chunk_id: chunkId },- });- const out = unwrapResult(resp);- console.debug('[memory-tree-rpc] memoryTreeChunkScore: exit kept=%o', out?.kept);- return out ?? null;-}--// ── memory_tree_delete_chunk ─────────────────────────────────────────────--/**- * Purge one chunk plus its score row, entity-index rows, and on-disk .md- * file. Idempotent — missing chunk returns `deleted=false`.- */-export async function memoryTreeDeleteChunk(chunkId: string): Promise<DeleteChunkResponse> {- console.debug('[memory-tree-rpc] memoryTreeDeleteChunk: entry chunk_id=%s', chunkId);- const resp = await callCoreRpc<DeleteChunkResponse | ResultEnvelope<DeleteChunkResponse>>({- method: 'openhuman.memory_tree_delete_chunk',- params: { chunk_id: chunkId },- });- const out = unwrapResult(resp);- console.debug(- '[memory-tree-rpc] memoryTreeDeleteChunk: exit deleted=%o score_rows=%d entity_rows=%d',- out?.deleted,- out?.score_rows_removed,- out?.entity_index_rows_removed- );- return out;-}--// ── memory_tree_get_llm / memory_tree_set_llm ────────────────────────────--/**- * Read the currently configured LLM backend (`cloud` or `local`).- */-export async function memoryTreeGetLlm(): Promise<LlmResponse> {- console.debug('[memory-tree-rpc] memoryTreeGetLlm: entry');- const resp = await callCoreRpc<LlmResponse | ResultEnvelope<LlmResponse>>({- method: 'openhuman.memory_tree_get_llm',- });- const out = unwrapResult(resp);- console.debug('[memory-tree-rpc] memoryTreeGetLlm: exit current=%s', out?.current);- return out;-}--/**- * Update the LLM backend selector — and, optionally, per-role model- * choices (`cloud_model`, `extract_model`, `summariser_model`) — and- * persist the result to `config.toml` in a single atomic write. Survives- * sidecar restart.- *- * Returns the effective backend after the call (the core may downgrade- * `local` → `cloud` if the host can't satisfy the local minimums; today- * the handler accepts the value verbatim).- *- * Accepts either a bare backend string (legacy callers) or the full- * {@link SetLlmRequest} object, so call-sites that only flip the mode- * stay terse while sites that want to persist model picks pass the- * extended shape.- */-export async function memoryTreeSetLlm(- reqOrBackend: LlmBackend | SetLlmRequest-): Promise<LlmResponse> {- const params: SetLlmRequest =- typeof reqOrBackend === 'string' ? { backend: reqOrBackend } : reqOrBackend;- console.debug(- '[memory-tree-rpc] memoryTreeSetLlm: entry backend=%s cloud_model=%s extract_model=%s summariser_model=%s',- params.backend,- params.cloud_model ?? '<none>',- params.extract_model ?? '<none>',- params.summariser_model ?? '<none>'- );- const resp = await callCoreRpc<LlmResponse | ResultEnvelope<LlmResponse>>({- method: 'openhuman.memory_tree_set_llm',- params,- });- const out = unwrapResult(resp);- console.debug('[memory-tree-rpc] memoryTreeSetLlm: exit current=%s', out?.current);- return out;-}--// ── memory_tree_graph_export ────────────────────────────────────────────--/**- * Discriminator for graph nodes. `"summary"` is a sealed summary tree- * node (Tree mode); `"chunk"` is a raw memory chunk and `"contact"`- * is a person entity (Contacts mode).- */-export type GraphNodeKind = 'root' | 'source' | 'summary' | 'chunk' | 'contact';--/**- * One node in the graph export. Optional fields are populated only- * when relevant to the node's `kind`; the UI branches on `kind` and- * ignores the rest.- */-export interface GraphNode {- kind: GraphNodeKind;- id: string;- /** Display-friendly label (scope, preview snippet, or surface form). */- label: string;- /**- * Optional UI-only fill override (hex). The backend never sets this; reuses- * of the graph (e.g. the orchestration overview dimming offline agents) use- * it to colour a node independent of its `kind`.- */- color?: string;-- // Summary-only ──- tree_id?: string;- tree_kind?: 'source' | 'topic' | 'global';- tree_scope?: string;- level?: number;- parent_id?: string | null;- child_count?: number;- /** Filesystem-safe basename (no `.md`); used to build Obsidian deep links. */- file_basename?: string;-- // Summary or chunk ──- time_range_start_ms?: number;- time_range_end_ms?: number;-- // Contact-only ──- /** `"person" | "organization" | …`. */- entity_kind?: string;-}--/** One explicit edge — used in Contacts mode to link chunks to contacts. */-export interface GraphEdge {- from: string;- to: string;-}--export type GraphMode = 'tree' | 'contacts';--export interface GraphExportResponse {- nodes: GraphNode[];- /**- * Explicit edges. Empty in `tree` mode (each summary node's- * `parent_id` carries the edge); chunk→contact mention edges in- * `contacts` mode.- */- edges: GraphEdge[];- /** Absolute filesystem path to `<workspace>/memory_tree/content/`. */- content_root_abs: string;-}--/** Response shape for `memory_tree_wipe_all`. */-export interface WipeAllResponse {- rows_deleted: number;- dirs_removed: string[];- /**- * Composio sync-state KV rows deleted. Clearing these (per-connection- * cursors + synced-id dedup sets) is what lets the next sync re-fetch- * every upstream item instead of skipping ones it's already seen.- */- sync_state_cleared: number;-}--/**- * Destructive reset: truncate every `mem_tree_*` table, remove the- * on-disk chunk-store directories under the workspace content root,- * **and** clear the `composio-sync-state` KV namespace so the next- * sync re-fetches every upstream item from scratch (no- * synced-id-dedup carry-over). Backed by- * `openhuman.memory_tree_wipe_all`.- *- * Callers can rely on `sync_state_cleared` in the response — a- * positive count means the next sync will be a full re-fetch; `0`- * means there were no live cursors to drop (e.g. fresh workspace).- */-export async function memoryTreeWipeAll(): Promise<WipeAllResponse> {- console.debug('[memory-tree-rpc] memoryTreeWipeAll: entry');- const resp = await callCoreRpc<WipeAllResponse | ResultEnvelope<WipeAllResponse>>({- method: 'openhuman.memory_tree_wipe_all',- });- const out = unwrapResult(resp);- console.debug(- '[memory-tree-rpc] memoryTreeWipeAll: exit rows=%d dirs=%o',- out.rows_deleted,- out.dirs_removed- );- return out;-}--/** Response shape for `memory_tree_reset_tree`. */-export interface ResetTreeResponse {- /** Tree-state SQLite rows deleted (summaries + trees + buffers + jobs). */- tree_rows_deleted: number;- /** Chunks reset to lifecycle_status = 'pending_extraction'. */- chunks_requeued: number;- /** `extract_chunk` jobs enqueued (one per chunk). */- jobs_enqueued: number;-}--/**- * Wipe summary-tree state but keep chunks, raw archive, and sync- * state — then re-enqueue every chunk through extraction so the- * tree rebuilds without a fresh upstream sync. Backed by- * `openhuman.memory_tree_reset_tree`.- *- * Use after changing the summariser backend (e.g. flipping inert- * → real local LLM) to re-summarise existing data on the new- * model.- */-export async function memoryTreeResetTree(): Promise<ResetTreeResponse> {- console.debug('[memory-tree-rpc] memoryTreeResetTree: entry');- const resp = await callCoreRpc<ResetTreeResponse | ResultEnvelope<ResetTreeResponse>>({- method: 'openhuman.memory_tree_reset_tree',- });- const out = unwrapResult(resp);- console.debug(- '[memory-tree-rpc] memoryTreeResetTree: exit tree_rows=%d chunks=%d jobs=%d',- out.tree_rows_deleted,- out.chunks_requeued,- out.jobs_enqueued- );- return out;-}--/** Response shape for `memory_tree_backfill_connector_trees`. */-export interface BackfillConnectorTreesResponse {- /** False for the dry-run preview: it counted and wrote nothing. */- executed: boolean;- /** Documents examined. */- scanned: number;- /** Documents that produced new memory-tree rows. */- ingested: number;- /** Documents the tree already held. */- already_present: number;- /** Documents left alone rather than filed under a guess. */- skipped: number;- /** The pass stopped on its limit with documents unexamined — run again. */- more_pending: boolean;- /** Bounded, human-readable reasons behind `skipped`. */- notes: string[];-}--/**- * A real pass reads and embeds up to the driver's per-call limit of documents- * (500) before it answers; the budget has to cover the whole pass.- */-const BACKFILL_RPC_TIMEOUT_MS = 10 * 60 * 1_000;--/**- * Re-file connector documents stored before the memory-tree routing fix- * (openhuman#6007) into the tree. Backed by- * `openhuman.memory_tree_backfill_connector_trees` (openhuman#6012).- *- * `dryRun: true` counts what a pass would examine and writes nothing; the real- * pass embeds every document it files, which spends credits, so the UI always- * previews first and asks. Idempotent: documents already in the tree come- * back as `already_present`, never filed twice.- */-export async function memoryTreeBackfillConnectorTrees(opts: {- dryRun: boolean;- limit?: number;-}): Promise<BackfillConnectorTreesResponse> {- console.debug(- '[memory-tree-rpc] memoryTreeBackfillConnectorTrees: entry dry_run=%s',- opts.dryRun- );- const resp = await callCoreRpc<- BackfillConnectorTreesResponse | ResultEnvelope<BackfillConnectorTreesResponse>- >({- method: 'openhuman.memory_tree_backfill_connector_trees',- params: { dry_run: opts.dryRun, ...(opts.limit ? { limit: opts.limit } : {}) },- timeoutMs: BACKFILL_RPC_TIMEOUT_MS,- });- const out = unwrapResult(resp);- console.debug(- '[memory-tree-rpc] memoryTreeBackfillConnectorTrees: exit executed=%s scanned=%d ingested=%d already=%d skipped=%d more=%s',- out.executed,- out.scanned,- out.ingested,- out.already_present,- out.skipped,- out.more_pending- );- return out;-}--/** Response shape for `memory_tree_flush_now`. */-export interface FlushNowResponse {- enqueued: boolean;- stale_buffers: number;-}--/**- * Manually trigger the summary-tree build. Enqueues a `flush_stale` job- * with `max_age_secs=0` so every L0 buffer force-seals immediately; the- * seal worker runs each through the configured cloud or local- * summariser. Backed by `openhuman.memory_tree_flush_now`.- *- * Safe to spam — same UTC-day dedupe key as the scheduled flush, so- * duplicate clicks return `enqueued=false` rather than queuing twice.- */-interface FlushSourceResponse {- tree_scope: string;- seals_fired: number;-}--export async function memoryTreeFlushSource(sourceScope: string): Promise<FlushSourceResponse> {- console.debug('[memory-tree-rpc] memoryTreeFlushSource: entry scope=%s', sourceScope);- const resp = await callCoreRpc<FlushSourceResponse | ResultEnvelope<FlushSourceResponse>>({- method: 'openhuman.memory_tree_flush_source',- params: { source_scope: sourceScope },- });- const out = unwrapResult(resp);- console.debug(- '[memory-tree-rpc] memoryTreeFlushSource: exit scope=%s seals=%d',- out.tree_scope,- out.seals_fired- );- return out;-}--export async function memoryTreeFlushNow(): Promise<FlushNowResponse> {- console.debug('[memory-tree-rpc] memoryTreeFlushNow: entry');- const resp = await callCoreRpc<FlushNowResponse | ResultEnvelope<FlushNowResponse>>({- method: 'openhuman.memory_tree_flush_now',- });- const out = unwrapResult(resp);- console.debug(- '[memory-tree-rpc] memoryTreeFlushNow: exit enqueued=%s stale_buffers=%d',- out.enqueued,- out.stale_buffers- );- return out;-}--/**- * Return either the summary tree (parent→child links between sealed- * summaries) or the document↔contact graph (chunks linked to person- * entities they mention). Backed by `openhuman.memory_tree_graph_export`.- */-export async function memoryTreeGraphExport(- mode: GraphMode = 'tree'-): Promise<GraphExportResponse> {- console.debug('[memory-tree-rpc] memoryTreeGraphExport: entry mode=%s', mode);- const resp = await callCoreRpc<GraphExportResponse | ResultEnvelope<GraphExportResponse>>({- method: 'openhuman.memory_tree_graph_export',- params: { mode },- });- const out = unwrapResult(resp);- console.debug(- // Don't log the absolute content root — it embeds the user's- // home directory + username and shows up in console logs / bug- // reports. The path is still returned to the caller.- '[memory-tree-rpc] memoryTreeGraphExport: exit mode=%s n=%d edges=%d',- mode,- out.nodes?.length ?? 0,- out.edges?.length ?? 0- );- return out;-}--/** Response shape for `memory_tree_obsidian_vault_status`. */-export interface ObsidianVaultStatus {- /**- * True when the content root (or an ancestor) is already a registered- * Obsidian vault, so `obsidian://open?path=` will actually resolve.- */- registered: boolean;- /**- * True when an `obsidian.json` was found and parsed (Obsidian is set up).- * Lets the UI offer "Open folder as vault" vs. "Install Obsidian".- */- config_found: boolean;- /** Absolute filesystem path to `<workspace>/memory_tree/content/`. */- content_root_abs: string;- /**- * OS of the core host (`"macos"` / `"linux"` / `"windows"`). `content_root_abs`- * is a path on that host; when the frontend runs on a different OS the vault- * cannot be opened/registered locally (issue #4278). Optional for backward- * compatibility with cores that predate this field.- */- host_os?: string;-}--/**- * Best-effort check of whether the memory-tree content root is a registered- * Obsidian vault. Called before firing the `obsidian://open?path=` deep link,- * which only resolves vaults already in Obsidian's `obsidian.json` registry —- * it cannot register a new vault on its own.- *- * `obsidianConfigDir` optionally overrides where the core looks for- * `obsidian.json` (non-standard installs: Flatpak / Snap / portable). Backed- * by `openhuman.memory_tree_obsidian_vault_status`.- */-export async function memoryTreeObsidianVaultStatus(- obsidianConfigDir?: string-): Promise<ObsidianVaultStatus> {- console.debug(- '[memory-tree-rpc] memoryTreeObsidianVaultStatus: entry override=%s',- obsidianConfigDir ? 'set' : 'none'- );- const resp = await callCoreRpc<ObsidianVaultStatus | ResultEnvelope<ObsidianVaultStatus>>({- method: 'openhuman.memory_tree_obsidian_vault_status',- // Only send the override when present so the core uses its default probe.- params: obsidianConfigDir ? { obsidian_config_dir: obsidianConfigDir } : {},- });- const out = unwrapResult(resp);- console.debug(- '[memory-tree-rpc] memoryTreeObsidianVaultStatus: exit registered=%s config_found=%s',- out.registered,- out.config_found- );- return out;-}--/** Response shape for `memory_tree_vault_health_check`. */-export interface VaultHealthCheck {- /** Absolute filesystem path to `<workspace>/memory_tree/content/`. */- content_root_abs: string;- /** True when the vault directory exists on disk. */- exists: boolean;- /** True when the vault directory is readable. */- readable: boolean;- /** True when a temp-file create+delete probe succeeds in the vault. */- writable: boolean;- /** True when Obsidian has this folder (or an ancestor) registered as a vault. */- obsidian_registered: boolean;- /** True when pipeline status is not paused and not in error. */- pipeline_healthy: boolean;- /** Epoch ms of newest chunk timestamp; zero when no chunks exist yet. */- last_sync_ms: number;- /**- * OS of the core host (`"macos"` / `"linux"` / `"windows"`). `exists` /- * `readable` / `writable` describe that host's filesystem; a frontend on a- * different OS cannot open `content_root_abs` locally even when they report- * healthy (issue #4278). Optional for backward compatibility.- */- host_os?: string;-}--/**- * Consolidated onboarding/settings health snapshot for the workspace memory- * vault (`<workspace>/memory_tree/content/`).- *- * Backed by `openhuman.memory_tree_vault_health_check`.- */-export async function memoryTreeVaultHealthCheck(- obsidianConfigDir?: string-): Promise<VaultHealthCheck> {- console.debug(- '[memory-tree-rpc] memoryTreeVaultHealthCheck: entry override=%s',- obsidianConfigDir ? 'set' : 'none'- );- const resp = await callCoreRpc<VaultHealthCheck | ResultEnvelope<VaultHealthCheck>>({- method: 'openhuman.memory_tree_vault_health_check',- params: obsidianConfigDir ? { obsidian_config_dir: obsidianConfigDir } : {},- });- const out = unwrapResult(resp);- console.debug(- '[memory-tree-rpc] memoryTreeVaultHealthCheck: exit exists=%s readable=%s writable=%s obsidian_registered=%s pipeline_healthy=%s',- out.exists,- out.readable,- out.writable,- out.obsidian_registered,- out.pipeline_healthy- );- return out;-}--/**- * #1574 §4b: per-model embedding re-embed backfill status. The AI settings- * panel polls this after an embedder change to warn that semantic recall- * is reduced until the new embedding space is fully re-embedded, and to- * dismiss the warning once the chain drains. Backed by- * `openhuman.memory_tree_memory_backfill_status`.- */-export interface BackfillStatus {- /** True while a re-embed backfill still has work pending. */- in_progress: boolean;- /** Count of `reembed_backfill` jobs in ready/running state. */- pending_jobs: number;-}--export async function memoryTreeBackfillStatus(): Promise<BackfillStatus> {- console.debug('[memory-tree-rpc] memoryTreeBackfillStatus: entry');- const resp = await callCoreRpc<BackfillStatus | ResultEnvelope<BackfillStatus>>({- method: 'openhuman.memory_tree_memory_backfill_status',- });- const out = unwrapResult(resp);- console.debug(- '[memory-tree-rpc] memoryTreeBackfillStatus: exit in_progress=%s pending=%d',- out.in_progress,- out.pending_jobs- );- return out;-}--// ── memory_tree_pipeline_status (#1856 Part 1) ───────────────────────────--/**- * Coarse status string emitted by `memory_tree_pipeline_status`. Mapped- * verbatim to a colored pill in the status panel — `paused` is the only- * state the toggle directly influences.- */-export type MemoryTreePipelineStatusKind =- | 'running'- | 'paused'- | 'syncing'- | 'error'- | 'idle'- | 'degraded';--/**- * Stable typed failure codes the Rust `health::FailureCode` emits (#002). The- * UI maps each to a localized remediation string; `remediation_key` carries- * the i18n key directly so the panel renders the core's guidance verbatim.- */-export type MemoryTreeFailureCode =- | 'budget_exhausted'- | 'auth_missing'- | 'auth_invalid'- | 'embeddings_unconfigured'- | 'embedding_dim_mismatch'- | 'local_model_unavailable'- | 'extraction_timeout'- | 'summarizer_unavailable'- | 'transient';--/**- * Typed pipeline failure (#002 FR-004). Mirrors Rust `health::PipelineFailure`.- * `remediation_key` is an i18n key (e.g. `memory.health.remediation.*`); the UI- * resolves it via `useT()`. `detail` is a short non-localized diagnostic- * string (never a secret) for logs/tooltips.- */-export interface MemoryTreePipelineFailure {- code: MemoryTreeFailureCode;- class: 'transient' | 'unrecoverable';- remediation_key: string;- detail?: string;-}--/**- * "The pipeline ran but output quality is reduced" (#002 FR-002/FR-005).- * Mirrors Rust `health::DegradedState`. `semantic_recall` true when embeddings- * were skipped (no usable provider → recall falls back to recency);- * `structure` true when extraction yielded nothing across the board.- */-export interface MemoryTreeDegradedState {- semantic_recall: boolean;- structure: boolean;- cause?: MemoryTreePipelineFailure | null;-}--/**- * Per-state job counters returned in {@link MemoryTreePipelineStatus}. Mirrors- * the Rust `PipelineJobCounts` struct exactly — snake_case carried through.- */-export interface MemoryTreePipelineJobCounts {- /** Jobs queued and waiting for a worker. */- ready: number;- /** Jobs currently being processed by a worker. */- running: number;- /** Jobs that exhausted retries and remain in the table for diagnosis. */- failed: number;-}--/**- * Aggregated Memory Tree health snapshot returned by- * `openhuman.memory_tree_pipeline_status`. The UI status panel polls this- * (every ~1.5s while syncing, ~4s otherwise) and renders the four tiles- * directly from the payload — no client-side derivation required.- */-export interface MemoryTreePipelineStatus {- /** UI status pill — one of `running` / `paused` / `syncing` / `error` / `idle`. */- status: MemoryTreePipelineStatusKind;- /**- * Optional human-readable reason. Present when `status` is `paused`- * (carries the gate mode) or `error` (carries the failed-job count);- * `null` otherwise.- */- reason: string | null;- /** Epoch ms of the most-recent chunk timestamp. Zero when the store is empty. */- last_sync_ms: number;- /** Total `mem_tree_chunks` rows across all sources. */- total_chunks: number;- /** Recursive on-disk size of the `wiki/` sub-tree under the memory_tree content root, in bytes. */- wiki_size_bytes: number;- /** Snapshot of `mem_tree_jobs` by status. */- pipeline_jobs: MemoryTreePipelineJobCounts;- /** Convenience flag: at least one job is currently `running`. */- is_syncing: boolean;- /** Convenience flag: scheduler-gate mode is `off`. */- is_paused: boolean;- /**- * The scheduler gate's live verdict (openhuman#6025 review): `true` while- * its policy is `paused` whichever mode is configured — in `auto` that is- * on battery with `require_ac_power`, under CPU pressure, or signed out —- * so every LLM-bound worker, the embed backfill included, is blocked right- * now. `is_paused` stays the configured `off` mode (the panel's toggle).- * Absent from a core that predates the field.- */- gate_paused?: boolean;- /** Why the gate is paused: `user_disabled` | `on_battery` | `cpu_pressure` | `signed_out` | `unknown`. */- gate_pause_reason?: string | null;- /**- * The #5324 stall verdict as a flag: eligible queue work has waited at- * least six hours without any job settling. `status` reads `degraded` for- * it; the flag tells that stall apart from the other degradations, because- * a stalled `reembed_backfill` row still keeps the backfill snapshot- * `in_progress` (openhuman#6025 review). Absent from an older core.- */- queue_stalled?: boolean;- /**- * #002 (FR-002/FR-005): degradation snapshot. Optional for back-compat with- * older cores that don't emit it (the Rust field is `#[serde(default)]`);- * absent ⇒ treat as not degraded.- */- degraded?: MemoryTreeDegradedState;- /**- * #002 (FR-004): the single first blocking/most-significant cause, rendered- * verbatim by the panel (resolving `remediation_key`). `null`/absent when- * the pipeline is healthy.- */- first_blocking_cause?: MemoryTreePipelineFailure | null;- /**- * #002 (FR-010 / US5): fraction of chunks with ≥1 indexed entity, in- * `[0.0, 1.0]`. Near 0 with `total_chunks > 0` ⇒ extraction is producing no- * structure ("empty-but-built wiki"). Optional for back-compat.- */- extraction_coverage?: number | null;- /**- * openhuman#5820: the most recent corrupt-store quarantine, derived from- * disk by the core so it survives restarts and reaches a renderer that was- * not connected when it happened. Absent when nothing was quarantined.- */- quarantine?: MemoryTreeQuarantine | null;-}--/** A corrupt-store quarantine as `memory_tree_pipeline_status` reports it. */-export interface MemoryTreeQuarantine {- /** Epoch ms of the quarantine (from the `.corrupt-<ts>` file name). */- quarantined_at_ms: number;- /** Local path of the preserved damaged database. */- quarantined_path: string;- /** The rebuilt (initially empty) store holds a chunk again: the user re-synced. */- resynced: boolean;-}--/**- * Fetch the Memory Tree pipeline status snapshot. Cheap and idempotent —- * the handler runs three SQL counters + one recursive dir walk. Safe to- * poll at ~1.5s intervals while the panel is mounted.- *- * Backed by `openhuman.memory_tree_pipeline_status` (#1856 Part 1).- */-export async function memoryTreePipelineStatus(): Promise<MemoryTreePipelineStatus> {- console.debug('[memory-tree-rpc] memoryTreePipelineStatus: entry');- const resp = await callCoreRpc<- MemoryTreePipelineStatus | ResultEnvelope<MemoryTreePipelineStatus>- >({ method: 'openhuman.memory_tree_pipeline_status', params: {} });- const out = unwrapResult(resp);- console.debug(- '[memory-tree-rpc] memoryTreePipelineStatus: exit status=%s total=%d syncing=%s paused=%s',- out.status,- out.total_chunks,- out.is_syncing,- out.is_paused- );- return out;-}--// ── memory_tree_retry_failed (#002 FR-011) ───────────────────────────────--/** Response shape for `openhuman.memory_tree_retry_failed`. */-export interface MemoryTreeRetryFailedResponse {- /** Number of terminally-failed jobs flipped back to `ready`. */- requeued: number;-}--/**- * Requeue every terminally-failed Memory Tree job.- *- * Unrecoverable failures (auth, budget, dimension mismatch) are terminal by- * design — the worker never retries them — so once the user fixes the- * underlying cause this is the only thing that unparks the work. Without it a- * single bad batch pins the panel on `error` permanently.- *- * Backed by `openhuman.memory_tree_retry_failed`.- */-export async function memoryTreeRetryFailed(): Promise<MemoryTreeRetryFailedResponse> {- console.debug('[memory-tree-rpc] memoryTreeRetryFailed: entry');- const resp = await callCoreRpc<- MemoryTreeRetryFailedResponse | ResultEnvelope<MemoryTreeRetryFailedResponse>- >({ method: 'openhuman.memory_tree_retry_failed', params: {} });- const out = unwrapResult(resp);- console.debug('[memory-tree-rpc] memoryTreeRetryFailed: exit requeued=%d', out.requeued);- return out;-}--// ── memory_tree_set_enabled (#1856 Part 1) ───────────────────────────────--/**- * Wire shape returned by `openhuman.memory_tree_set_enabled`. `changed=false`- * means the persisted mode already matched the request (idempotent toggle).- */-export interface MemoryTreeSetEnabledResponse {- /** Echo of the requested enabled state (post-write). */- enabled: boolean;- /** True when the persisted mode flipped; false when the call was a no-op. */- changed: boolean;- /** New scheduler-gate mode as wire string (`auto` / `off`). */- mode: string;-}--/**- * Toggle Memory Tree auto-sync. `enabled=true` flips the scheduler-gate to- * `auto`; `enabled=false` flips it to `off`, which pauses every LLM-bound- * background worker cooperatively at their next `wait_for_capacity()`- * await on the Rust side.- *- * Backed by `openhuman.memory_tree_set_enabled` (#1856 Part 1). The 20-min- * Composio fetch loop is *not* paused by this toggle yet — that lands in- * #1856 Part 2.- */-export async function memoryTreeSetEnabled(- enabled: boolean-): Promise<MemoryTreeSetEnabledResponse> {- console.debug('[memory-tree-rpc] memoryTreeSetEnabled: entry enabled=%s', enabled);- const resp = await callCoreRpc<- MemoryTreeSetEnabledResponse | ResultEnvelope<MemoryTreeSetEnabledResponse>- >({ method: 'openhuman.memory_tree_set_enabled', params: { enabled } });- const out = unwrapResult(resp);- console.debug(- '[memory-tree-rpc] memoryTreeSetEnabled: exit enabled=%s changed=%s mode=%s',- out.enabled,- out.changed,- out.mode- );- return out;-}--// ── Sync Audit Log ─────────────────────────────────────────────────--export interface SyncAuditEntry {- timestamp: string;- source_id: string;- source_kind: string;- scope: string;- items_fetched: number;- batches: number;- input_tokens: number;- output_tokens: number;- estimated_cost_usd: number;- duration_ms: number;- success: boolean;- error?: string;- /**- * Items fetched-and-stored whose memory-tree ingest failed- * (openhuman#5820). Absent on rows written before the field existed and on- * fully-healthy rows; a non-zero count with `success: false` is the- * "fetched, not tree-ingested" partial verdict the panel renders as ⚠.- */- tree_ingest_failures?: number;- /** Why the tree half failed, when it did. Never memory content. */- tree_error?: string;-}--export async function memorySyncAuditLog(): Promise<SyncAuditEntry[]> {- const resp = await callCoreRpc<- { entries: SyncAuditEntry[] } | ResultEnvelope<{ entries: SyncAuditEntry[] }>- >({ method: 'openhuman.memory_sources_sync_audit_log', params: {} });- return unwrapResult(resp).entries ?? [];-}--// ── memory_sync_status_list (#2763 — per-integration health strip) ───────--/**- * Freshness label emitted by `openhuman.memory_sync_status_list`. Snake-case- * mirrors the Rust `FreshnessLabel` serde rename. Derived from- * `now - last_chunk_at_ms` at RPC time, not stored.- */-export type MemorySyncFreshness = 'active' | 'recent' | 'idle';--/**- * One row per provider that has produced chunks. Mirrors the Rust- * `MemorySyncStatus` struct exactly — snake_case carried through so the- * wire payload deserialises without a remap layer.- */-export interface MemorySyncStatusRow {- /** Provider key — `slack`, `gmail`, `notion`, `discord`, `telegram`, etc. */- provider: string;- /** Total chunks in `mem_tree_chunks` for this provider. */- chunks_synced: number;- /** Chunks fetched but not yet extracted/embedded. Lifetime metric. */- chunks_pending: number;- /** Total chunks in the current sync wave. Zero when no wave is active. */- batch_total: number;- /** Of `batch_total`, how many have been processed. */- batch_processed: number;- /** Epoch ms of the most-recent chunk for this provider; null if none yet. */- last_chunk_at_ms: number | null;- /** Coarse activity label — derived at RPC time. */- freshness: MemorySyncFreshness;-}--/**- * Fetch the per-provider sync-status list. Single SQL query against- * `mem_tree_chunks` (GROUP BY source_kind); safe to poll alongside- * `memoryTreePipelineStatus` on the same 1.5s / 4s adaptive cadence.- *- * Backed by `openhuman.memory_sync_status_list` (#1136). Surfaced by the- * per-integration health strip in `MemoryTreeStatusPanel` (#2763).- */-export async function memorySyncStatusList(): Promise<MemorySyncStatusRow[]> {- console.debug('[memory-tree-rpc] memorySyncStatusList: entry');- const resp = await callCoreRpc<- { statuses: MemorySyncStatusRow[] } | ResultEnvelope<{ statuses: MemorySyncStatusRow[] }>- >({ method: 'openhuman.memory_sync_status_list', params: {} });- const out = unwrapResult(resp);- const rows = out.statuses ?? [];- console.debug('[memory-tree-rpc] memorySyncStatusList: exit rows=%d', rows.length);- return rows;-}--// ── memory_namespace_summaries (#5932 — sync-verification counts) ────────────--/** One namespace's stored-document count, from the mandatory driver surface. */-export interface NamespaceSummaryRow {- namespace: string;- count: number;- last_updated?: string | null;-}--export interface NamespaceSummariesResponse {- namespaces: NamespaceSummaryRow[];- total_documents: number;-}--/**- * Per-namespace stored-document counts plus the grand total — the number a- * user checks to verify a sync's items actually landed (`list_namespaces`- * answers names alone).- */-export async function memoryNamespaceSummaries(): Promise<NamespaceSummariesResponse> {- const resp = await callCoreRpc<- NamespaceSummariesResponse | ResultEnvelope<NamespaceSummariesResponse>- >({ method: 'openhuman.memory_namespace_summaries', params: {} });- return unwrapResult(resp);-}diff --git a/vendor/tinymemory b/vendor/tinymemoryindex a98dfdbf41..0924669dfa 160000--- a/vendor/tinymemory+++ b/vendor/tinymemory@@ -1 +1 @@-Subproject commit a98dfdbf4192245f4570b1e3c8d111d505efcd1c+Subproject commit 0924669dfa86d6c565569ef8461744fee580e248