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
fix(memory-sources): keep a sync's live state when the Sources screen goes away
Shanu2c58b588dda9
diff --git a/app/src/components/intelligence/MemorySourcesRegistry.tsx b/app/src/components/intelligence/MemorySourcesRegistry.tsxindex 6d7906690d..6a89e18ebd 100644--- a/app/src/components/intelligence/MemorySourcesRegistry.tsx+++ b/app/src/components/intelligence/MemorySourcesRegistry.tsx@@ -40,55 +40,23 @@ import { MemorySourceRow } from './MemorySourceRow';import { AllInIcon, PlusIcon } from './memorySourcesIcons';import { sourceTreeScope } from './memorySourcesRowHelpers';import {- STAGE_FALLBACK_PERCENT,- 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';+interface MemorySourcesRegistryProps {onToast?: (toast: Omit<ToastNotification, 'id'>) => void;pollIntervalMs?: number;}-/**- * 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;-}-export function MemorySourcesRegistry({onToast,pollIntervalMs = 5000,@@ -110,13 +78,14 @@ export function MemorySourcesRegistry({const [pipeline, setPipeline] = useState<MemoryTreePipelineStatus | null>(null);const [loading, setLoading] = useState(true);const [dialogOpen, setDialogOpen] = useState(false);- // RC#1 (#3295): use a Set so multiple sources can show "syncing" concurrently.- // Set state is always replaced with a new Set to trigger re-renders.- const [syncingIds, setSyncingIds] = useState<Set<string>>(new Set());+ // 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 [syncProgress, setSyncProgress] = useState<Map<string, SyncProgress>>(new Map());- // Terminal per-source result (success/failure) shown after a sync ends (#3295).- const [syncResults, setSyncResults] = useState<Map<string, SyncResult>>(new Map());const [allInModalOpen, setAllInModalOpen] = useState(false);const [applyingAllIn, setApplyingAllIn] = useState(false);const allInInFlightRef = useRef(false);@@ -134,54 +103,18 @@ 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') {- // 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);- setSyncResults(prev => {- const next = new Map(prev);- next.set(rowId, { kind: 'success', items, reason: null });- return next;- });+ // The item count parsed from the detail ("ingested N item(s)");+ // 0 new items → "up to date" (#3295).+ const items = result.items;onToastRef.current?.({type: 'success',title: `${tt('memorySources.sync.completeTitle')} ${label}`,@@ -191,56 +124,17 @@ export function MemorySourcesRegistry({: tt('memorySources.sync.upToDate'),});} 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 });- 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}`,- message: reason ?? tt('memorySources.sync.failedLabel'),+ message: detail ?? tt('memorySources.sync.failedLabel'),});}- 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.- setSyncResults(prev => {- if (!prev.has(rowId)) return prev;- const next = new Map(prev);- next.delete(rowId);- return next;- });- const percent = parseSyncProgress(data?.detail ?? null, stage);- setSyncProgress(prev => {- const next = new Map(prev);- next.set(rowId, { stage, detail: data?.detail ?? null, percent });- return next;- });- // RC#1: ADD this source id to the set (immutable update).- if (- stage === 'requested' ||- stage === 'fetching' ||- stage === 'stored' ||- stage === 'queued' ||- stage === 'ingesting'- ) {- setSyncingIds(prev => {- if (prev.has(rowId)) return prev; // no change — avoid re-render- const next = new Set(prev);- next.add(rowId);- return next;- });- }- };- window.addEventListener('openhuman:memory-sync-stage', handler);- return () => window.removeEventListener('openhuman:memory-sync-stage', handler);- }, []);+ }),+ []+ );const refresh = useCallback(async () => {try {@@ -264,11 +158,13 @@ export function MemorySourcesRegistry({setSources(list);setStatuses(stats);setPipeline(health);- // RC#5 (#3295): The 5s poll is the safety net for missed completed/failed events.- // If a source is in syncingIds but the poll shows it's no longer active (no- // in-progress status indicator from the server), we clear it here. In practice- // the event stream covers this; on remount the state rehydrates within ~5s via poll.- // No new RPC needed — reconciliation is best-effort and relies on the existing poll.+ // 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 {setLoading(false);}@@ -347,20 +243,10 @@ export function MemorySourcesRegistry({const handleSync = useCallback(async (source: MemorySourceEntry) => {- // RC#1 (#3295): add immediately on click — event will also fire, but this- // ensures the row lights up before the first sync-stage event arrives.- setSyncingIds(prev => {- const next = new Set(prev);- next.add(source.id);- return next;- });- // A fresh sync is starting — drop any prior terminal result chip (#3295).- setSyncResults(prev => {- if (!prev.has(source.id)) return prev;- const next = new Map(prev);- next.delete(source.id);- return next;- });+ // 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);@@ -374,16 +260,7 @@ export function MemorySourcesRegistry({// 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);- setSyncingIds(prev => {- const next = new Set(prev);- next.delete(source.id);- return next;- });- setSyncResults(prev => {- const next = new Map(prev);- next.set(source.id, { kind: 'failed', items: null, reason });- return next;- });+ noteSyncRejected(source.id, reason);onToast?.({type: 'error',title: `${t('memorySources.sync.failedLabel')} · ${source.label}`,diff --git a/app/src/components/intelligence/__tests__/MemorySourcesRegistry.sync.test.tsx b/app/src/components/intelligence/__tests__/MemorySourcesRegistry.sync.test.tsxindex 95f6290484..137a1e3fe4 100644--- a/app/src/components/intelligence/__tests__/MemorySourcesRegistry.sync.test.tsx+++ b/app/src/components/intelligence/__tests__/MemorySourcesRegistry.sync.test.tsx@@ -16,6 +16,7 @@ import {parseIngestedCount,parseSyncProgress,} from '../MemorySourcesRegistry';+import { resetMemorySyncActivityForTests } from '../memorySyncActivityStore';// ── i18n mock (returns key as the translation) ────────────────────────────────vi.mock('../../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (key: string) => key }) }));@@ -138,6 +139,12 @@ describe('parseIngestedCount', () => {// ── 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>;@@ -485,4 +492,68 @@ describe('MemorySourcesRegistry', () => {// The optimistic syncing state is cleared after the RPC rejection.expect(screen.queryByText('sync.syncing')).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 --git a/app/src/components/intelligence/__tests__/memorySyncActivityStore.test.ts b/app/src/components/intelligence/__tests__/memorySyncActivityStore.test.tsnew file mode 100644index 0000000000..3a4956bb47--- /dev/null+++ b/app/src/components/intelligence/__tests__/memorySyncActivityStore.test.ts@@ -0,0 +1,114 @@+/**+ * @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(ended).toHaveBeenCalledWith(+ expect.objectContaining({+ rowId: 'src-a',+ stage: 'completed',+ result: { kind: 'success', items: 7, reason: 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',+ });+ });++ 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('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 --git a/app/src/components/intelligence/memorySyncActivityStore.ts b/app/src/components/intelligence/memorySyncActivityStore.tsnew file mode 100644index 0000000000..6410c2ff79--- /dev/null+++ b/app/src/components/intelligence/memorySyncActivityStore.ts@@ -0,0 +1,282 @@+/**+ * 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 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;+}++/** 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.+ const result: SyncResult =+ stage === 'completed'+ ? { kind: 'success', items: parseIngestedCount(detail), reason: null }+ : { kind: 'failed', items: null, reason: detail };+ 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 });+ 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;+ 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);+ });+}diff --git a/app/src/services/memorySourcesService.ts b/app/src/services/memorySourcesService.tsindex 55310b8b8c..a756d53b7c 100644--- a/app/src/services/memorySourcesService.ts+++ b/app/src/services/memorySourcesService.ts@@ -148,6 +148,14 @@ export interface SourceStatus {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[]> {diff --git a/src/openhuman/memory/mod.rs b/src/openhuman/memory/mod.rsindex c1a68508a7..5d6515e7d5 100644--- a/src/openhuman/memory/mod.rs+++ b/src/openhuman/memory/mod.rs@@ -60,6 +60,7 @@ pub mod host_impls;pub mod obsidian_registry;pub mod ops;pub mod preferences;+pub mod sync_activity;pub mod sync_events_bridge;// The consolidated `memory_query` agent tool and its six retrieval modes. Came// back from `tinymemory-core` with the rest of the agent tools — it is a `Tool`diff --git a/src/openhuman/memory/sources/status.rs b/src/openhuman/memory/sources/status.rsindex 3563927c3a..bffb223e98 100644--- a/src/openhuman/memory/sources/status.rs+++ b/src/openhuman/memory/sources/status.rs@@ -75,7 +75,8 @@ impl FreshnessLabel {/// RPC has always returned it.////// Field for field and name for name the engine's `SourceStatus`, so the-/// response JSON is unchanged by the move.+/// response JSON is unchanged by the move — plus the two in-flight fields the+/// host adds from its own memory of the stage stream (openhuman#6019).#[derive(Clone, Debug, Serialize)]pub struct SourceStatus {pub source_id: String,@@ -83,6 +84,14 @@ pub struct SourceStatus {pub chunks_pending: u64,pub last_chunk_at_ms: Option<i64>,pub freshness: FreshnessLabel,+ /// The stage of a sync in flight for this source, as the stage stream last+ /// reported it; `None` when nothing is running. The chunk counts cannot+ /// say this — a connector still paging has written nothing — and without+ /// it a Sources screen mounting mid-run showed the row idle, as if the+ /// sync had stopped (openhuman#6019).+ pub sync_stage: Option<String>,+ /// The free-text detail that came with [`Self::sync_stage`], if any.+ pub sync_detail: Option<String>,}impl SourceStatus {@@ -97,8 +106,28 @@ impl SourceStatus {chunks_pending: 0,last_chunk_at_ms: None,freshness: FreshnessLabel::Idle,+ sync_stage: None,+ sync_detail: None,}}++ /// The row with the run in flight written onto it, when there is one.+ pub(crate) fn with_live_sync(+ mut self,+ live: Option<crate::openhuman::memory::sync_activity::LiveSync>,+ ) -> Self {+ match live {+ Some(live) => {+ self.sync_stage = Some(live.stage);+ self.sync_detail = live.detail;+ }+ None => {+ self.sync_stage = None;+ self.sync_detail = None;+ }+ }+ self+ }}/// The literal prefix of the chunk-ingest key a source's rows carry.@@ -187,20 +216,27 @@ pub async fn status_list(config: &Config) -> Result<Vec<SourceStatus>, String> {Ok(sources.into_iter().map(|source| {+ // The run in flight, from the process's memory of the stage+ // stream rather than from the store: the store only learns of a+ // run once something is written (openhuman#6019).+ let live = crate::openhuman::memory::sync_activity::live_sync(&source.id);// Paired by `source_id`, not by position: the member echoes the id// precisely so a caller need not trust the order, and a mis-indexed// row here would report one connector's progress under another's// name.- match rows.iter().find(|row| row.source_id == source.id) {+ let status = match rows.iter().find(|row| row.source_id == source.id) {Some(row) => SourceStatus {source_id: source.id,chunks_synced: row.chunks_synced,chunks_pending: row.chunks_pending,last_chunk_at_ms: row.last_chunk_at_ms,freshness: FreshnessLabel::from_age_ms(row.last_chunk_at_ms, now_ms),+ sync_stage: None,+ sync_detail: None,},None => SourceStatus::idle(source.id),- }+ };+ status.with_live_sync(live)}).collect())}diff --git a/src/openhuman/memory/sources/status_tests.rs b/src/openhuman/memory/sources/status_tests.rsindex 6842ac29cb..5146b3c65c 100644--- a/src/openhuman/memory/sources/status_tests.rs+++ b/src/openhuman/memory/sources/status_tests.rs@@ -114,10 +114,12 @@ fn freshness_serialises_snake_case() {);}-/// The five fields, their names, and the fact that `last_chunk_at_ms` is-/// carried as `null` rather than omitted — the engine's `SourceStatus` had no-/// `skip_serializing_if`, and a field that disappears is a field a client-/// reading `row.last_chunk_at_ms` sees as `undefined`.+/// The engine's five fields, their names, and the fact that the optional+/// ones are carried as `null` rather than omitted — the engine's `SourceStatus`+/// had no `skip_serializing_if`, and a field that disappears is a field a+/// client reading `row.last_chunk_at_ms` sees as `undefined`. The host's two+/// in-flight fields (openhuman#6019) follow the same rule, so a client can+/// tell "nothing running" from "a core that does not report it".#[test]fn source_status_serde_shape_is_unchanged() {let json = serde_json::to_value(SourceStatus::idle("src_a".into())).unwrap();@@ -129,6 +131,26 @@ fn source_status_serde_shape_is_unchanged() {"chunks_pending": 0,"last_chunk_at_ms": null,"freshness": "idle",+ "sync_stage": null,+ "sync_detail": null,}));}++/// A run the stage stream remembers rides on the row; none leaves both+/// fields `null` rather than stale.+#[test]+fn the_run_in_flight_rides_on_the_status_row() {+ use crate::openhuman::memory::sync_activity::LiveSync;+ let live = SourceStatus::idle("src_a".into()).with_live_sync(Some(LiveSync {+ stage: "running".into(),+ detail: Some("pass 1".into()),+ updated_at_ms: 1,+ }));+ assert_eq!(live.sync_stage.as_deref(), Some("running"));+ assert_eq!(live.sync_detail.as_deref(), Some("pass 1"));++ let idle = live.with_live_sync(None);+ assert_eq!(idle.sync_stage, None);+ assert_eq!(idle.sync_detail, None);+}diff --git a/src/openhuman/memory/sync_activity.rs b/src/openhuman/memory/sync_activity.rsnew file mode 100644index 0000000000..881c9554de--- /dev/null+++ b/src/openhuman/memory/sync_activity.rs@@ -0,0 +1,143 @@+//! What is syncing right now, remembered from the stage stream.+//!+//! `memory_sources.status_list` answers "how far has this source got" from the+//! chunk store, and the store knows nothing about a run in flight: a connector+//! still paging Gmail in its detached task has written nothing yet, and the+//! row reads idle. The Sources screen kept the live state for itself, in+//! component state fed by the socket — and lost it the moment the screen+//! unmounted, so a tab change mid-sync looked like the sync had stopped+//! (openhuman#6019).+//!+//! This is the process's own memory of that stream. A bus subscriber beside+//! [`super::sync_events_bridge`] records every `MemorySyncStageChanged` that+//! names a source: a non-terminal stage puts the source in flight, `completed`+//! or `failed` takes it out. The status list reads it, so a screen that mounts+//! mid-run, or an app that reloads, is told where the run is instead of+//! guessing from a chunk count.++use std::collections::HashMap;+use std::sync::{Arc, Mutex, OnceLock, PoisonError};++use async_trait::async_trait;+use tinybus::{EventHandler, SubscriptionHandle};++use crate::core::bus::BUS;+use crate::core::events::DomainEvent;++/// One source's run in flight, as the stream last described it.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct LiveSync {+ /// The last non-terminal stage seen — `running` for a connector sync,+ /// the per-item stages for a reader-backed one.+ pub stage: String,+ /// The stage's free-text detail, when it carried one.+ pub detail: Option<String>,+ /// When the entry was last written, epoch milliseconds.+ pub updated_at_ms: i64,+}++/// An entry older than this without a terminal stage is no run at all.+///+/// The bus delivers locally over a broadcast channel that drops under lag, so+/// a `completed` can go missing; a connector run is bounded well inside this+/// by its pass cap and per-call deadline. Without a ceiling a lost terminal+/// stage would pin a "running" bar to the row for the life of the process.+const STALE_AFTER_MS: i64 = 30 * 60 * 1_000;++static LIVE: OnceLock<Mutex<HashMap<String, LiveSync>>> = OnceLock::new();+static HANDLE: OnceLock<SubscriptionHandle> = OnceLock::new();++fn live() -> &'static Mutex<HashMap<String, LiveSync>> {+ LIVE.get_or_init(Default::default)+}++fn now_ms() -> i64 {+ chrono::Utc::now().timestamp_millis()+}++/// The two stages after which a source is no longer in flight.+pub(crate) fn is_terminal(stage: &str) -> bool {+ matches!(stage, "completed" | "failed")+}++/// Record one stage for `source_id`.+pub(crate) fn note_stage(source_id: &str, stage: &str, detail: Option<&str>) {+ note_stage_at(source_id, stage, detail, now_ms());+}++fn note_stage_at(source_id: &str, stage: &str, detail: Option<&str>, at_ms: i64) {+ let mut map = live().lock().unwrap_or_else(PoisonError::into_inner);+ if is_terminal(stage) {+ map.remove(source_id);+ } else {+ map.insert(+ source_id.to_string(),+ LiveSync {+ stage: stage.to_string(),+ detail: detail.map(str::to_string),+ updated_at_ms: at_ms,+ },+ );+ }+}++/// The run in flight for `source_id`, if the stream has one that is not stale.+pub fn live_sync(source_id: &str) -> Option<LiveSync> {+ live_sync_at(source_id, now_ms())+}++fn live_sync_at(source_id: &str, now_ms: i64) -> Option<LiveSync> {+ let map = live().lock().unwrap_or_else(PoisonError::into_inner);+ map.get(source_id)+ .filter(|entry| now_ms.saturating_sub(entry.updated_at_ms) <= STALE_AFTER_MS)+ .cloned()+}++/// Subscribe the tracker to the bus, once. Registered beside the sync-stage+/// bridge so every host that serves the stream also remembers it.+pub fn register() {+ if HANDLE.get().is_some() {+ return;+ }+ match BUS.subscribe(Arc::new(SyncActivityTracker)) {+ Some(handle) => {+ let _ = HANDLE.set(handle);+ log::debug!("[event_bus] memory sync activity tracker registered");+ }+ None => log::warn!(+ "[event_bus] failed to register memory sync activity tracker — bus not initialized"+ ),+ }+}++struct SyncActivityTracker;++#[async_trait]+impl EventHandler<DomainEvent> for SyncActivityTracker {+ fn name(&self) -> &str {+ "memory::sync_activity_tracker"+ }++ fn domains(&self) -> Option<&[&str]> {+ Some(&["memory"])+ }++ async fn handle(&self, event: &DomainEvent) {+ // Only a stage that names its memory-source row can be shown on that+ // row; an unattributed one (a connection bootstrapped before its entry+ // exists) has nowhere to go and is left alone.+ if let DomainEvent::MemorySyncStageChanged {+ stage,+ detail,+ source_id: Some(source_id),+ ..+ } = event+ {+ note_stage(source_id, stage, detail.as_deref());+ }+ }+}++#[cfg(test)]+#[path = "sync_activity_tests.rs"]+mod tests;diff --git a/src/openhuman/memory/sync_activity_tests.rs b/src/openhuman/memory/sync_activity_tests.rsnew file mode 100644index 0000000000..3430b30c41--- /dev/null+++ b/src/openhuman/memory/sync_activity_tests.rs@@ -0,0 +1,83 @@+//! Tests for the sync activity tracker. The map is process-global, so every+//! test uses its own source ids rather than resetting it under the others.++use super::*;++fn stage_event(source_id: Option<&str>, stage: &str, detail: Option<&str>) -> DomainEvent {+ DomainEvent::MemorySyncStageChanged {+ trigger: "manual".into(),+ stage: stage.into(),+ provider: Some("gmail".into()),+ connection_id: Some("conn-1".into()),+ detail: detail.map(str::to_string),+ source_id: source_id.map(str::to_string),+ }+}++#[tokio::test]+async fn a_running_stage_puts_the_source_in_flight_until_its_terminal_stage() {+ let tracker = SyncActivityTracker;+ tracker+ .handle(&stage_event(Some("src-live"), "running", None))+ .await;+ let live = live_sync("src-live").expect("in flight after `running`");+ assert_eq!(live.stage, "running");+ assert_eq!(live.detail, None);++ tracker+ .handle(&stage_event(+ Some("src-live"),+ "completed",+ Some("ingested 3 item(s)"),+ ))+ .await;+ assert_eq!(live_sync("src-live"), None, "`completed` takes it out");+}++#[tokio::test]+async fn a_failed_stage_takes_the_source_out_too() {+ let tracker = SyncActivityTracker;+ tracker+ .handle(&stage_event(+ Some("src-fail"),+ "fetching",+ Some("1/4 pages"),+ ))+ .await;+ assert_eq!(+ live_sync("src-fail").map(|live| live.detail),+ Some(Some("1/4 pages".to_string()))+ );+ tracker+ .handle(&stage_event(Some("src-fail"), "failed", Some("boom")))+ .await;+ assert_eq!(live_sync("src-fail"), None);+}++#[tokio::test]+async fn a_stage_without_a_source_id_is_not_remembered() {+ SyncActivityTracker+ .handle(&stage_event(None, "running", None))+ .await;+ assert_eq!(live_sync("conn-1"), None, "the connection id is not a row");+}++#[test]+fn a_run_with_no_terminal_stage_goes_stale_after_the_ceiling() {+ note_stage_at("src-stale", "running", None, 1_000);+ assert!(live_sync_at("src-stale", 1_000 + STALE_AFTER_MS).is_some());+ assert_eq!(+ live_sync_at("src-stale", 1_000 + STALE_AFTER_MS + 1),+ None,+ "a lost `completed` must not pin the row forever"+ );+}++#[test]+fn the_latest_stage_wins() {+ note_stage_at("src-latest", "requested", None, 10);+ note_stage_at("src-latest", "ingesting", Some("queue_depth=2"), 20);+ let live = live_sync_at("src-latest", 25).expect("still in flight");+ assert_eq!(live.stage, "ingesting");+ assert_eq!(live.updated_at_ms, 20);+}diff --git a/src/openhuman/memory/sync_events_bridge.rs b/src/openhuman/memory/sync_events_bridge.rsindex a26f644286..e6e29ff58d 100644--- a/src/openhuman/memory/sync_events_bridge.rs+++ b/src/openhuman/memory/sync_events_bridge.rs@@ -46,6 +46,10 @@ pub fn register_sync_stage_bridge(config: &Config) {}}+ // The process's memory of the stream the bridge feeds: which sources are+ // in flight right now, for the status list (openhuman#6019).+ super::sync_activity::register();+// Trigger batch embedding when a sync completes. Extract no longer embeds// inline — the backfill pass picks up all un-embedded chunks in large// batches (up to 1000 items per API call).