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
Merge main into fix/memory-sources-sync-progress-persist\n\nTakes #6017 (main 69843f159). Its Sources-screen changes land on the same\nhandler this branch moved into the store, so the resolution re-applies the\nstore rewiring on top of main's text: `parseSyncNote` moves into the store\nwith the other two parsers and is re-exported from the registry, every\n`SyncResult` the store writes carries #6017's `note`, and the terminal-toast\nsubscription keeps #6017's wording for a run that stopped short.\n\nAlso folds in a review finding on the store: a row the button lit\noptimistically has no bar yet, so a poll that reports it live now seeds the\nbar instead of being skipped (it was skipped whenever the row was known\nlive at all).\n
Shanuddb0ed2ccece
diff --cc app/src/components/intelligence/MemorySourcesRegistry.tsxindex 6a89e18ebd,0bd76163ff..d1bef91041--- a/app/src/components/intelligence/MemorySourcesRegistry.tsx+++ b/app/src/components/intelligence/MemorySourcesRegistry.tsx@@@ -40,18 -43,13 +43,18 @@@ import { MemorySourceRow } from './Memoimport { AllInIcon, PlusIcon } from './memorySourcesIcons';import { sourceTreeScope } from './memorySourcesRowHelpers';import {- STAGE_FALLBACK_PERCENT,- type SyncNote,- type SyncProgress,- type SyncResult,-} from './memorySourcesSyncTypes';+ 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, parseSyncProgress } from './memorySyncActivityStore';++export { parseIngestedCount, parseSyncNote, parseSyncProgress } from './memorySyncActivityStore';+interface MemorySourcesRegistryProps {onToast?: (toast: Omit<ToastNotification, 'id'>) => void;pollIntervalMs?: number;@@@ -103,29 -163,89 +114,46 @@@ export function MemorySourcesRegistry(tRef.current = t;});- useEffect(() => {- const handler = (e: Event) => {- const data = (e as CustomEvent).detail as {- 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;-- // 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 ?? '';-- 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') {- // Clear the live progress bar + syncing flag for this row.- setSyncProgress(prev => {- const next = new Map(prev);- next.delete(rowId);- return next;- });- // RC#1: immutable Set update — remove just this source, keep others syncing.- setSyncingIds(prev => {- const next = new Set(prev);- next.delete(rowId);- return next;- });-+ // 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)");- // 0 new items → "up to date" (#3295).- const items = result.items;- // Success: record + toast the item count parsed from the detail- // ("ingested N item(s)"). 0 new items → "up to date" (#3295).- const items = parseIngestedCount(data?.detail ?? null);- const note = parseSyncNote(data?.detail ?? null);- setSyncResults(prev => {- const next = new Map(prev);- next.set(rowId, { kind: 'success', items, reason: null, note });- return next;- });- // 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.++ // 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: 'success',+ type: note === 'budget_spent' ? 'warning' : 'success',title: `${tt('memorySources.sync.completeTitle')} ${label}`,- message:- items && items > 0- ? `${items} ${tt('memorySources.sync.itemsSynced')}`- : tt('memorySources.sync.upToDate'),+ message: hasItems && noteKey ? `${counted} — ${tt(noteKey)}` : counted,});} else {- // Failure: surface the reason on the row + a toast. The core already- // reported internal bugs to Sentry via report_error_or_expected.- const reason = data?.detail ?? null;- setSyncResults(prev => {- const next = new Map(prev);- next.set(rowId, { kind: 'failed', items: null, reason, note: null });- return next;- });+ // 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}`,diff --cc app/src/components/intelligence/__tests__/MemorySourcesRegistry.sync.test.tsxindex 137a1e3fe4,9fc6dd4e6a..12dab59797--- a/app/src/components/intelligence/__tests__/MemorySourcesRegistry.sync.test.tsx+++ b/app/src/components/intelligence/__tests__/MemorySourcesRegistry.sync.test.tsx@@@ -14,9 -14,9 +14,10 @@@ import { renderWithProviders } from '..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 }) }));@@@ -492,68 -518,208 +525,272 @@@ describe('MemorySourcesRegistry', () =// 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' }));+ });+ await waitFor(() => expect(screen.getByText('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('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('running')).toBeInTheDocument());+ expect(screen.getByText('sync.syncing')).toBeInTheDocument();+ });});diff --cc app/src/components/intelligence/__tests__/memorySyncActivityStore.test.tsindex 3a4956bb47,0000000000..874d070118mode 100644,000000..100644--- a/app/src/components/intelligence/__tests__/memorySyncActivityStore.test.ts+++ b/app/src/components/intelligence/__tests__/memorySyncActivityStore.test.ts@@@ -1,114 -1,0 +1,125 @@@+/**+ * @vitest-environment jsdom+ */+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { SourceStatus } from '../../../services/memorySourcesService';+import {+ applyStageEvent,+ getMemorySyncActivity,+ 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 });++ 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 },++ 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 });+ });++ 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);+ });+});diff --cc app/src/components/intelligence/memorySyncActivityStore.tsindex 6410c2ff79,0000000000..4ba99de720mode 100644,000000..100644--- a/app/src/components/intelligence/memorySyncActivityStore.ts+++ b/app/src/components/intelligence/memorySyncActivityStore.ts@@@ -1,282 -1,0 +1,308 @@@+/**+ * 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 {+ 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). */+const SYNCING_STAGES = new Set(['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>();+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)");- // 0 new items → "up to date" (#3295). Failure: the reason, verbatim.++ // 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 }- : { kind: 'failed', items: null, reason: detail };++ ? {++ 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);+ commit({ syncingIds, progress, results });+ for (const listener of terminalListeners) listener({ rowId, stage, detail, result });+ return;+ }++ // 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 {+ 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 });++ 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) {- if (knownLive) continue;++ // 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();+ 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);+ });+}