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): record every sync run in Sync History and show live sync activity
Shanucb4dc2d5a85a
diff --git a/app/src/components/intelligence/MemorySourceRow.test.tsx b/app/src/components/intelligence/MemorySourceRow.test.tsxindex d744f8c025..8f450299fd 100644--- a/app/src/components/intelligence/MemorySourceRow.test.tsx+++ b/app/src/components/intelligence/MemorySourceRow.test.tsx@@ -86,3 +86,36 @@ describe('MemorySourceRow — settings disclosure', () => {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.tsxindex 54c0686bc6..914b948d79 100644--- a/app/src/components/intelligence/MemorySourceRow.tsx+++ b/app/src/components/intelligence/MemorySourceRow.tsx@@ -33,7 +33,9 @@ import {} from './memorySourcesIcons';import { relativeTimestamp, sourceDetail } from './memorySourcesRowHelpers';import {+ showsStageDetail,STAGE_FALLBACK_PERCENT,+ stageLabelKey,type SyncProgress,type SyncResult,} from './memorySourcesSyncTypes';@@ -173,13 +175,15 @@ export function MemorySourceRow({{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">- <span className="capitalize">{progress.stage}</span>+ {/* 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 && (+ {progress.detail && showsStageDetail(progress.stage) && (<span className="truncate text-content-faint">{progress.detail}</span>)}</div>diff --git a/app/src/components/intelligence/MemoryTreeStatusPanel.test.tsx b/app/src/components/intelligence/MemoryTreeStatusPanel.test.tsxindex a13e13d76d..9fd432e309 100644--- a/app/src/components/intelligence/MemoryTreeStatusPanel.test.tsx+++ b/app/src/components/intelligence/MemoryTreeStatusPanel.test.tsx@@ -115,6 +115,19 @@ describe('<MemoryTreeStatusPanel />', () => {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([diff --git a/app/src/components/intelligence/MemoryTreeStatusPanel.tsx b/app/src/components/intelligence/MemoryTreeStatusPanel.tsxindex e6214dbd3d..07a2011426 100644--- a/app/src/components/intelligence/MemoryTreeStatusPanel.tsx+++ b/app/src/components/intelligence/MemoryTreeStatusPanel.tsx@@ -383,6 +383,18 @@ export function MemoryTreeStatusPanel({ onToast }: MemoryTreeStatusPanelProps) {</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 */}diff --git a/app/src/components/intelligence/SyncActivityCard.test.tsx b/app/src/components/intelligence/SyncActivityCard.test.tsxnew file mode 100644index 0000000000..3478a96c36--- /dev/null+++ b/app/src/components/intelligence/SyncActivityCard.test.tsx@@ -0,0 +1,190 @@+/**+ * 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');+ });+});diff --git a/app/src/components/intelligence/SyncActivityCard.tsx b/app/src/components/intelligence/SyncActivityCard.tsxnew file mode 100644index 0000000000..852b22d18b--- /dev/null+++ b/app/src/components/intelligence/SyncActivityCard.tsx@@ -0,0 +1,99 @@+/**+ * "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;+ const refresh = async () => {+ try {+ const statuses = await memorySourcesStatusList();+ if (cancelled) return;+ 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.tsxindex 1b7bec3ca6..abf7dbe010 100644--- a/app/src/components/intelligence/SyncAuditPanel.test.tsx+++ b/app/src/components/intelligence/SyncAuditPanel.test.tsx@@ -1,6 +1,7 @@/*** Vitest for `<SyncAuditPanel />` (issue #3116 — coverage for the sync-audit- * history surface shipped in PR #3113).+ * history surface shipped in PR #3113; openhuman#6257 — the panel keeps+ * itself current).** Covers:* - loading → loaded transition (renders rows once the audit log resolves)@@ -8,24 +9,41 @@* - the scope label mapping for github / gmail / rebuild scopes* - success ✓ vs failure ✗ status glyphs* - 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` wrapper is swapped for a spy; everything- * else in the `tauriCommands` barrel (types, sibling wrappers) is inherited- * verbatim so the panel sees the production module shape.+ * 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 { render, screen, waitFor, within } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';+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 { SyncAuditPanel, timeAgo } from './SyncAuditPanel';+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(),@@ -43,9 +61,27 @@ function entry(overrides: Partial<SyncAuditEntry> = {}): SyncAuditEntry {};}+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 () => {@@ -195,6 +231,134 @@ describe('<SyncAuditPanel />', () => {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('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', () => {diff --git a/app/src/components/intelligence/SyncAuditPanel.tsx b/app/src/components/intelligence/SyncAuditPanel.tsxindex 2141fa0fc8..61e896e194 100644--- a/app/src/components/intelligence/SyncAuditPanel.tsx+++ b/app/src/components/intelligence/SyncAuditPanel.tsx@@ -1,12 +1,32 @@/*** 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 { useEffect, useState } from '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 Button from '../ui/Button';import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/Table';+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`;@@ -52,25 +72,109 @@ export function timeAgo(iso: string, t: (key: string, fallback?: string) => striexport function SyncAuditPanel() {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 reload = useCallback((reason: string) => {+ console.debug('[sync-audit] reload requested reason=%s', reason);+ setReloadToken(token => token + 1);+ }, []);useEffect(() => {let cancelled = false;void (async () => {+ console.debug('[sync-audit] load: entry token=%d', reloadToken);try {- const data = await memorySyncAuditLog();- if (!cancelled) setEntries(data);+ const [data, statuses] = await Promise.all([+ memorySyncAuditLog(),+ // Labels and source ids only: a failed status read must not hide+ // the history. What the last read that answered said stays, and a+ // row with no label names itself by its scope.+ memorySourcesStatusList().catch((err: unknown) => {+ console.warn('[sync-audit] status list failed; keeping the last labels', err);+ return null;+ }),+ ]);+ if (cancelled) {+ console.debug('[sync-audit] load: dropped superseded token=%d', reloadToken);+ return;+ }+ setEntries(data);+ if (statuses) {+ setLabels(sourceLabelsById(statuses));+ setSourceIds(new Set(statuses.map(status => status.source_id)));+ }+ 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);+ if (!cancelled) {+ setLoading(false);+ setRefreshing(false);+ }}})();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 refreshButton = (+ <Button+ variant="secondary"+ size="xs"+ analyticsId="sync-history-refresh"+ data-testid="sync-history-refresh"+ disabled={refreshing}+ onClick={() => {+ setRefreshing(true);+ reload('manual');+ }}>+ {t('common.refresh', 'Refresh')}+ </Button>+ );if (loading) {return (@@ -80,8 +184,11 @@ export function SyncAuditPanel() {if (entries.length === 0) {return (- <div className="text-xs text-content-faint py-2">- {t('sync.noAuditEntries', 'No sync runs recorded yet.')}+ <div className="flex items-center justify-between gap-3 py-2">+ <span className="text-xs text-content-faint">+ {t('sync.noAuditEntries', 'No sync runs recorded yet.')}+ </span>+ {refreshButton}</div>);}@@ -104,6 +211,7 @@ export function SyncAuditPanel() {<span className="font-medium">${totalCost.toFixed(4)} {t('sync.totalCost', 'total')}</span>+ <span className="ml-auto">{refreshButton}</span></div><div className="max-h-48 overflow-y-auto rounded-md border border-line-subtle"><Table className="text-xs">@@ -141,7 +249,7 @@ export function SyncAuditPanel() {<TableCellclassName="px-3 py-1.5 text-content-secondary truncate max-w-[180px]"title={e.scope}>- {scopeLabel(e.scope)}+ {labels[e.source_id] ?? scopeLabel(e.scope)}</TableCell><TableCell className="px-3 py-1.5 text-right tabular-nums text-content-secondary">{e.items_fetched}diff --git a/app/src/components/intelligence/__tests__/MemorySourcesRegistry.sync.test.tsx b/app/src/components/intelligence/__tests__/MemorySourcesRegistry.sync.test.tsxindex b97fcac381..188a2406bf 100644--- a/app/src/components/intelligence/__tests__/MemorySourcesRegistry.sync.test.tsx+++ b/app/src/components/intelligence/__tests__/MemorySourcesRegistry.sync.test.tsx@@ -742,7 +742,10 @@ describe('MemorySourcesRegistry', () => {act(() => {window.dispatchEvent(makeSyncStageEvent({ stage: 'running', source_id: 'src-persist' }));});- await waitFor(() => expect(screen.getByText('running')).toBeInTheDocument());+ // 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.@@ -754,7 +757,7 @@ describe('MemorySourcesRegistry', () => {const second = renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);await waitFor(() => expect(screen.getByText('Source src-persist')).toBeInTheDocument());- expect(screen.getByText('fetching')).toBeInTheDocument();+ expect(screen.getByText('memorySources.stage.fetching')).toBeInTheDocument();second.unmount();act(() => {@@ -791,7 +794,9 @@ describe('MemorySourcesRegistry', () => {]);renderWithProviders(<MemorySourcesRegistry pollIntervalMs={0} />);- await waitFor(() => expect(screen.getByText('running')).toBeInTheDocument());+ await waitFor(() =>+ expect(screen.getByText('memorySources.stage.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.tsindex 31dbe43080..042fa2de1b 100644--- a/app/src/components/intelligence/__tests__/memorySyncActivityStore.test.ts+++ b/app/src/components/intelligence/__tests__/memorySyncActivityStore.test.ts@@ -7,6 +7,7 @@ import type { SourceStatus } from '../../../services/memorySourcesService';import {applyStageEvent,getMemorySyncActivity,+ LATE_ITEM_STAGE_WINDOW_MS,noteSyncRejected,noteSyncRequested,RECONCILE_GRACE_MS,@@ -130,4 +131,75 @@ describe('memorySyncActivityStore', () => {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 background run reports nothing but per-item stages, so once the window+ // the core applies too has passed, those stages are a later run's.+ 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/memorySourcesSyncTypes.ts b/app/src/components/intelligence/memorySourcesSyncTypes.tsindex 1d3206aeba..c2a98b7ce7 100644--- a/app/src/components/intelligence/memorySourcesSyncTypes.ts+++ b/app/src/components/intelligence/memorySourcesSyncTypes.ts@@ -49,3 +49,76 @@ export const STAGE_FALLBACK_PERCENT: Record<string, number> = {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';+}++/**+ * Whether a stage's detail is worth showing. The connector's `running` detail+ * ("pass 2 done, 400 item(s) so far") and a reader's `fetching` ratio are+ * progress a person can read; a per-item stage's detail is not.+ */+export function showsStageDetail(stage: string): boolean {+ return !isItemStage(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.tsindex 17307ed25a..70391d89fb 100644--- a/app/src/components/intelligence/memorySyncActivityStore.ts+++ b/app/src/components/intelligence/memorySyncActivityStore.ts@@ -23,6 +23,7 @@ import { useSyncExternalStore } from 'react';import type { SourceStatus } from '../../services/memorySourcesService';import {+ isItemStage,STAGE_FALLBACK_PERCENT,type SyncNote,type SyncProgress,@@ -144,6 +145,32 @@ const EMPTY: MemorySyncActivity = {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`). Past it, a per-item+ * stage belongs to a later run (a background sync reports nothing but per-item+ * stages), and the row shows it again, as the core's status list does.+ */+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>();@@ -218,11 +245,20 @@ export function applyStageEvent(data: SyncStageEventDetail | null | undefined):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);@@ -240,6 +276,7 @@ export function applyStageEvent(data: SyncStageEventDetail | null | undefined):* (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);@@ -284,6 +321,9 @@ export function reconcileWithStatuses(statuses: SourceStatus[], now = Date.now()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)) {@@ -312,6 +352,7 @@ export function reconcileWithStatuses(statuses: SourceStatus[], now = Date.now()/** Back to nothing in flight. Tests only. */export function resetMemorySyncActivityForTests(): void {liveSince.clear();+ finishedRows.clear();commit(EMPTY);}diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.tsindex b093286139..394fc5b76f 100644--- a/app/src/lib/i18n/ar.ts+++ b/app/src/lib/i18n/ar.ts@@ -366,6 +366,8 @@ const messages: TranslationMap = {'sync.status.success': 'نجاح','sync.status.failed': 'فشل','sync.status.partial': 'تم الجلب، وفشل الإدراج في الذاكرة',+ 'sync.nowSyncing.title': 'قيد المزامنة الآن',+ 'sync.nowSyncing.empty': 'لا تجري أي مزامنة الآن.','common.error': 'خطأ','common.success': 'نجاح','common.back': 'رجوع',@@ -945,6 +947,8 @@ const messages: TranslationMap = {'memoryTree.status.retryFailedDone': 'تمت إعادة إدراج المهام الفاشلة','memoryTree.status.retryFailedCount': 'تمت جدولة {count} مهمة للتشغيل من جديد.','memoryTree.status.retryFailedError': 'تعذّرت إعادة إدراج المهام الفاشلة',+ 'memoryTree.status.jobQueue':+ 'مهام الذاكرة: {ready} قيد الانتظار، {running} قيد التشغيل، {failed} فاشلة','memoryTree.status.toggleFailed': 'لا يمكن أن نهز السيرة الذاتية','memoryTree.status.justNow': 'الآن','memoryTree.status.secondsAgo': 'اكساكسوكس قبل',@@ -2576,8 +2580,6 @@ const messages: TranslationMap = {'memorySources.kind.twitter_query': 'Xqx0x','memorySources.kind.rss_feed': 'Xqx0xq','memorySources.kind.web_page': 'الصفحة',- 'memorySources.sync.successTitle': 'الموسم',- 'memorySources.sync.successMessage': 'وسيظهر التقدم قريبا.','memorySources.sync.failedTitle': 'لقد فشل (سينك)','memorySources.sync.completeTitle': 'تمت المزامنة','memorySources.sync.itemsSynced': 'عناصر تمت مزامنتها',@@ -2585,6 +2587,13 @@ const messages: TranslationMap = {'memorySources.sync.failedLabel': 'فشل','memorySources.sync.morePending': 'يوجد المزيد للمزامنة. انقر على «مزامنة» مرة أخرى','memorySources.sync.budgetSpent': 'استُنفدت ميزانية الطلبات لليوم. حاول مرة أخرى غدًا',+ 'memorySources.stage.requested': 'جارٍ البدء',+ 'memorySources.stage.running': 'جارٍ المزامنة',+ 'memorySources.stage.fetching': 'جارٍ الجلب',+ 'memorySources.stage.stored': 'جارٍ الحفظ',+ 'memorySources.stage.queued': 'جارٍ المعالجة في الذاكرة',+ 'memorySources.stage.ingesting': 'جارٍ المعالجة في الذاكرة',+ 'memorySources.stage.unknown': 'جارٍ المزامنة','time.justNow': 'للتو','time.secondsAgoSuffix': 'ثانية مضت','time.minutesAgoSuffix': 'دقيقة مضت',diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.tsindex 46ef31f09e..c2658761c0 100644--- a/app/src/lib/i18n/bn.ts+++ b/app/src/lib/i18n/bn.ts@@ -378,6 +378,8 @@ const messages: TranslationMap = {'sync.status.success': 'সফল','sync.status.failed': 'ব্যর্থ','sync.status.partial': 'আনা হয়েছে, মেমোরিতে যুক্ত হয়নি',+ 'sync.nowSyncing.title': 'এখন সিঙ্ক হচ্ছে',+ 'sync.nowSyncing.empty': 'এই মুহূর্তে কিছুই সিঙ্ক হচ্ছে না।','common.error': 'ত্রুটি','common.success': 'সফল','common.back': 'পেছনে',@@ -972,6 +974,8 @@ const messages: TranslationMap = {'memoryTree.status.retryFailedDone': 'ব্যর্থ কাজগুলো আবার সারিতে দেওয়া হয়েছে','memoryTree.status.retryFailedCount': '{count}টি কাজ আবার চালানোর জন্য সারিতে রাখা হয়েছে।','memoryTree.status.retryFailedError': 'ব্যর্থ কাজগুলো আবার সারিতে দেওয়া যায়নি',+ 'memoryTree.status.jobQueue':+ 'মেমোরির কাজ: {ready}টি অপেক্ষমাণ, {running}টি চলছে, {failed}টি ব্যর্থ','memoryTree.status.toggleFailed': 'স্বয়ংক্রিয়ভাবে সনাক্ত করা সম্ভব হয়নি','memoryTree.status.justNow': 'এখন','memoryTree.status.secondsAgo': 'xqxqx পূর্বে',@@ -2638,8 +2642,6 @@ const messages: TranslationMap = {'memorySources.kind.twitter_query': 'Xqxqx অনুসন্ধান','memorySources.kind.rss_feed': 'xqxqx ফিড','memorySources.kind.web_page': 'ওয়েব পেজ',- 'memorySources.sync.successTitle': 'সুসংগতি',- 'memorySources.sync.successMessage': 'অগ্রগতি শীঘ্রই দেখা যাবে।','memorySources.sync.failedTitle': 'সুসংগত করতে ব্যর্থ:','memorySources.sync.completeTitle': 'সিঙ্ক হয়েছে','memorySources.sync.itemsSynced': 'আইটেম সিঙ্ক হয়েছে',@@ -2647,6 +2649,13 @@ const messages: TranslationMap = {'memorySources.sync.failedLabel': 'ব্যর্থ','memorySources.sync.morePending': 'আরও সিঙ্ক বাকি আছে। আবার Sync-এ ক্লিক করুন','memorySources.sync.budgetSpent': 'আজকের অনুরোধের বাজেট শেষ। আগামীকাল আবার চেষ্টা করুন',+ 'memorySources.stage.requested': 'শুরু হচ্ছে',+ 'memorySources.stage.running': 'সিঙ্ক হচ্ছে',+ 'memorySources.stage.fetching': 'আনা হচ্ছে',+ 'memorySources.stage.stored': 'সংরক্ষণ করা হচ্ছে',+ 'memorySources.stage.queued': 'মেমোরিতে যোগ করা হচ্ছে',+ 'memorySources.stage.ingesting': 'মেমোরিতে যোগ করা হচ্ছে',+ 'memorySources.stage.unknown': 'সিঙ্ক হচ্ছে','time.justNow': 'এইমাত্র','time.secondsAgoSuffix': 'সেকেন্ড আগে','time.minutesAgoSuffix': 'মিনিট আগে',diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.tsindex 4ed788ef74..2769180950 100644--- a/app/src/lib/i18n/de.ts+++ b/app/src/lib/i18n/de.ts@@ -397,6 +397,8 @@ const messages: TranslationMap = {'sync.status.success': 'Erfolg','sync.status.failed': 'Fehlgeschlagen','sync.status.partial': 'Abgerufen, Speicherung im Gedächtnis fehlgeschlagen',+ 'sync.nowSyncing.title': 'Wird gerade synchronisiert',+ 'sync.nowSyncing.empty': 'Gerade wird nichts synchronisiert.','common.error': 'Fehler','common.success': 'Erfolg','common.back': 'Zurück',@@ -1007,6 +1009,8 @@ const messages: TranslationMap = {'memoryTree.status.retryFailedCount': 'Erneut eingereihte Jobs: {count}.','memoryTree.status.retryFailedError':'Die fehlgeschlagenen Jobs konnten nicht neu eingereiht werden',+ 'memoryTree.status.jobQueue':+ 'Gedächtnisaufgaben: {ready} wartend, {running} laufend, {failed} fehlgeschlagen','memoryTree.status.toggleFailed':'Automatische Synchronisierung konnte nicht umgeschaltet werden','memoryTree.status.justNow': 'gerade eben',@@ -2713,8 +2717,6 @@ const messages: TranslationMap = {'memorySources.kind.twitter_query': 'Twitter-Suche','memorySources.kind.rss_feed': 'RSS-Feed','memorySources.kind.web_page': 'Webseite',- 'memorySources.sync.successTitle': 'Synchronisierung läuft',- 'memorySources.sync.successMessage': 'Der Fortschritt wird in Kürze angezeigt.','memorySources.sync.failedTitle': 'Synchronisierung ist fehlgeschlagen','memorySources.sync.completeTitle': 'Synchronisiert','memorySources.sync.itemsSynced': 'Elemente synchronisiert',@@ -2723,6 +2725,13 @@ const messages: TranslationMap = {'memorySources.sync.morePending': 'Mehr zu synchronisieren. Erneut auf Synchronisieren klicken','memorySources.sync.budgetSpent':'Das heutige Anfragebudget ist aufgebraucht. Morgen erneut versuchen',+ 'memorySources.stage.requested': 'Wird gestartet',+ 'memorySources.stage.running': 'Synchronisierung läuft',+ 'memorySources.stage.fetching': 'Wird abgerufen',+ 'memorySources.stage.stored': 'Wird gespeichert',+ 'memorySources.stage.queued': 'Wird ins Gedächtnis übernommen',+ 'memorySources.stage.ingesting': 'Wird ins Gedächtnis übernommen',+ 'memorySources.stage.unknown': 'Synchronisierung läuft','time.justNow': 'gerade eben','time.secondsAgoSuffix': 'vor {count} Sek.','time.minutesAgoSuffix': 'vor {count} Min.',diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.tsindex 94683cb8ab..b2b4c84b2a 100644--- a/app/src/lib/i18n/en.ts+++ b/app/src/lib/i18n/en.ts@@ -172,6 +172,8 @@ const en: TranslationMap = {'sync.status.success': 'Success','sync.status.failed': 'Failed','sync.status.partial': 'Fetched, memory ingest failed',+ 'sync.nowSyncing.title': 'Now syncing',+ 'sync.nowSyncing.empty': 'Nothing is syncing right now.','common.error': 'Error','common.success': 'Success','common.back': 'Back',@@ -964,6 +966,7 @@ const en: TranslationMap = {'memoryTree.status.retryFailedDone': 'Failed jobs requeued','memoryTree.status.retryFailedCount': 'Jobs queued to run again: {count}.','memoryTree.status.retryFailedError': 'Could not requeue the failed jobs',+ 'memoryTree.status.jobQueue': 'Memory jobs: {ready} waiting, {running} running, {failed} failed','memoryTree.status.toggleFailed': "Couldn't toggle auto-sync",// Relative-time buckets surfaced by the last-sync tile. `{count}` is// replaced client-side at the call site (the runtime `t()` does not@@ -3008,8 +3011,6 @@ const en: TranslationMap = {'memorySources.kind.twitter_query': 'Twitter Search','memorySources.kind.rss_feed': 'RSS Feed','memorySources.kind.web_page': 'Web Page',- 'memorySources.sync.successTitle': 'Syncing',- 'memorySources.sync.successMessage': 'Progress will appear shortly.','memorySources.sync.failedTitle': 'Sync failed:','memorySources.sync.completeTitle': 'Synced','memorySources.sync.itemsSynced': 'items synced',@@ -3017,6 +3018,13 @@ const en: TranslationMap = {'memorySources.sync.failedLabel': 'Failed','memorySources.sync.morePending': 'More to sync. Click Sync again','memorySources.sync.budgetSpent': "Today's request budget is spent. Try again tomorrow",+ 'memorySources.stage.requested': 'Starting',+ 'memorySources.stage.running': 'Syncing',+ 'memorySources.stage.fetching': 'Fetching',+ 'memorySources.stage.stored': 'Saving',+ 'memorySources.stage.queued': 'Processing into memory',+ 'memorySources.stage.ingesting': 'Processing into memory',+ 'memorySources.stage.unknown': 'Syncing','time.justNow': 'just now','time.secondsAgoSuffix': 's ago','time.minutesAgoSuffix': 'm ago',diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.tsindex 0b17424dba..c4c8d65f9d 100644--- a/app/src/lib/i18n/es.ts+++ b/app/src/lib/i18n/es.ts@@ -387,6 +387,8 @@ const messages: TranslationMap = {'sync.status.success': 'Correcto','sync.status.failed': 'Fallido','sync.status.partial': 'Obtenido, pero no se pudo indexar en memoria',+ 'sync.nowSyncing.title': 'Sincronizando ahora',+ 'sync.nowSyncing.empty': 'No se está sincronizando nada en este momento.','common.error': 'error','common.success': 'Éxito','common.back': 'Atrás',@@ -994,6 +996,8 @@ const messages: TranslationMap = {'memoryTree.status.retryFailedCount': 'Trabajos en cola para ejecutarse de nuevo: {count}.','memoryTree.status.retryFailedError':'No se pudieron volver a poner en cola los trabajos fallidos',+ 'memoryTree.status.jobQueue':+ 'Tareas de memoria: {ready} en espera, {running} en curso, {failed} fallidas','memoryTree.status.toggleFailed': 'No se pudo activar la sincronización automática','memoryTree.status.justNow': 'justo ahora','memoryTree.status.secondsAgo': '{count}s hace',@@ -2690,8 +2694,6 @@ const messages: TranslationMap = {'memorySources.kind.twitter_query': 'Búsqueda en Twitter','memorySources.kind.rss_feed': 'RSS Alimentar','memorySources.kind.web_page': 'Página web',- 'memorySources.sync.successTitle': 'Sincronizando',- 'memorySources.sync.successMessage': 'El progreso aparecerá en breve.','memorySources.sync.failedTitle': 'Sincronización fallida:','memorySources.sync.completeTitle': 'Sincronizado','memorySources.sync.itemsSynced': 'elementos sincronizados',@@ -2700,6 +2702,13 @@ const messages: TranslationMap = {'memorySources.sync.morePending': 'Queda más por sincronizar. Pulsa Sincronizar de nuevo','memorySources.sync.budgetSpent':'El presupuesto de solicitudes de hoy se ha agotado. Inténtalo mañana',+ 'memorySources.stage.requested': 'Iniciando',+ 'memorySources.stage.running': 'Sincronizando',+ 'memorySources.stage.fetching': 'Obteniendo',+ 'memorySources.stage.stored': 'Guardando',+ 'memorySources.stage.queued': 'Procesando en la memoria',+ 'memorySources.stage.ingesting': 'Procesando en la memoria',+ 'memorySources.stage.unknown': 'Sincronizando','time.justNow': 'ahora mismo','time.secondsAgoSuffix': 's','time.minutesAgoSuffix': 'min',diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.tsindex c02a28feac..bb53561e16 100644--- a/app/src/lib/i18n/fr.ts+++ b/app/src/lib/i18n/fr.ts@@ -395,6 +395,8 @@ const messages: TranslationMap = {'sync.status.success': 'Réussi','sync.status.failed': 'Échec','sync.status.partial': 'Récupéré, échec d’indexation mémoire',+ 'sync.nowSyncing.title': 'Synchronisation en cours',+ 'sync.nowSyncing.empty': 'Aucune synchronisation en cours.','common.error': 'Erreur','common.success': 'Succès','common.back': 'Retour',@@ -1005,6 +1007,8 @@ const messages: TranslationMap = {'memoryTree.status.retryFailedDone': 'Tâches en échec remises en file','memoryTree.status.retryFailedCount': "Tâches remises en file d'attente : {count}.",'memoryTree.status.retryFailedError': 'Impossible de remettre en file les tâches en échec',+ 'memoryTree.status.jobQueue':+ 'Tâches de mémoire : {ready} en attente, {running} en cours, {failed} en échec','memoryTree.status.toggleFailed':"Impossible d'activer/désactiver la synchronisation automatique",'memoryTree.status.justNow': "à l'instant",@@ -2712,8 +2716,6 @@ const messages: TranslationMap = {'memorySources.kind.twitter_query': 'Recherche Twitter','memorySources.kind.rss_feed': 'RSS Flux','memorySources.kind.web_page': 'Page Web',- 'memorySources.sync.successTitle': 'Synchronisation',- 'memorySources.sync.successMessage': 'Le progrès apparaîtra bientôt.','memorySources.sync.failedTitle': 'Échec de la synchronisation:','memorySources.sync.completeTitle': 'Synchronisé','memorySources.sync.itemsSynced': 'éléments synchronisés',@@ -2722,6 +2724,13 @@ const messages: TranslationMap = {'memorySources.sync.morePending':'Il reste des éléments à synchroniser. Cliquez à nouveau sur Synchroniser','memorySources.sync.budgetSpent': 'Le budget de requêtes du jour est épuisé. Réessayez demain',+ 'memorySources.stage.requested': 'Démarrage',+ 'memorySources.stage.running': 'Synchronisation',+ 'memorySources.stage.fetching': 'Récupération',+ 'memorySources.stage.stored': 'Enregistrement',+ 'memorySources.stage.queued': 'Traitement dans la mémoire',+ 'memorySources.stage.ingesting': 'Traitement dans la mémoire',+ 'memorySources.stage.unknown': 'Synchronisation','time.justNow': "à l'instant",'time.secondsAgoSuffix': 's','time.minutesAgoSuffix': 'min',diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.tsindex 5491cd8420..a9fcebbec1 100644--- a/app/src/lib/i18n/hi.ts+++ b/app/src/lib/i18n/hi.ts@@ -380,6 +380,8 @@ const messages: TranslationMap = {'sync.status.success': 'सफल','sync.status.failed': 'विफल','sync.status.partial': 'प्राप्त हुआ, मेमोरी में दर्ज नहीं हुआ',+ 'sync.nowSyncing.title': 'अभी सिंक हो रहा है',+ 'sync.nowSyncing.empty': 'अभी कुछ भी सिंक नहीं हो रहा है।','common.error': 'एरर','common.success': 'सफल','common.back': 'वापस',@@ -971,6 +973,8 @@ const messages: TranslationMap = {'memoryTree.status.retryFailedDone': 'विफल कार्य फिर से कतार में डाले गए','memoryTree.status.retryFailedCount': '{count} कार्य दोबारा चलने के लिए कतार में हैं।','memoryTree.status.retryFailedError': 'विफल कार्यों को फिर से कतार में नहीं डाला जा सका',+ 'memoryTree.status.jobQueue':+ 'मेमोरी कार्य: {ready} प्रतीक्षा में, {running} चल रहे हैं, {failed} विफल','memoryTree.status.toggleFailed': 'ऑटो सिंक को टॉगल नहीं कर सका','memoryTree.status.justNow': 'अभी','memoryTree.status.secondsAgo': '{count} पहले',@@ -2638,8 +2642,6 @@ const messages: TranslationMap = {'memorySources.kind.twitter_query': 'Twitter खोज','memorySources.kind.rss_feed': 'RSS फ़ीड','memorySources.kind.web_page': 'वेब पेज',- 'memorySources.sync.successTitle': 'सिंक करना',- 'memorySources.sync.successMessage': 'प्रगति शीघ्र ही दिखाई देगी।','memorySources.sync.failedTitle': 'सिंक विफल:','memorySources.sync.completeTitle': 'सिंक हो गया','memorySources.sync.itemsSynced': 'आइटम सिंक हुए',@@ -2647,6 +2649,13 @@ const messages: TranslationMap = {'memorySources.sync.failedLabel': 'विफल','memorySources.sync.morePending': 'और सिंक बाकी है। फिर से Sync पर क्लिक करें','memorySources.sync.budgetSpent': 'आज का अनुरोध बजट खत्म हो गया है। कल फिर कोशिश करें',+ 'memorySources.stage.requested': 'शुरू हो रहा है',+ 'memorySources.stage.running': 'सिंक हो रहा है',+ 'memorySources.stage.fetching': 'प्राप्त किया जा रहा है',+ 'memorySources.stage.stored': 'सहेजा जा रहा है',+ 'memorySources.stage.queued': 'मेमोरी में जोड़ा जा रहा है',+ 'memorySources.stage.ingesting': 'मेमोरी में जोड़ा जा रहा है',+ 'memorySources.stage.unknown': 'सिंक हो रहा है','time.justNow': 'अभी','time.secondsAgoSuffix': 'सेकंड पहले','time.minutesAgoSuffix': 'मिनट पहले',diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.tsindex be61314dd6..abfa68d0ce 100644--- a/app/src/lib/i18n/id.ts+++ b/app/src/lib/i18n/id.ts@@ -384,6 +384,8 @@ const messages: TranslationMap = {'sync.status.success': 'Berhasil','sync.status.failed': 'Gagal','sync.status.partial': 'Terambil, gagal masuk ke memori',+ 'sync.nowSyncing.title': 'Sedang disinkronkan',+ 'sync.nowSyncing.empty': 'Tidak ada yang sedang disinkronkan saat ini.','common.error': 'Kesalahan','common.success': 'Berhasil','common.back': 'Kembali',@@ -982,6 +984,8 @@ const messages: TranslationMap = {'memoryTree.status.retryFailedDone': 'Tugas yang gagal masuk antrean lagi','memoryTree.status.retryFailedCount': '{count} tugas diantrekan untuk dijalankan ulang.','memoryTree.status.retryFailedError': 'Tidak dapat mengantrekan ulang tugas yang gagal',+ 'memoryTree.status.jobQueue':+ 'Tugas memori: {ready} menunggu, {running} berjalan, {failed} gagal','memoryTree.status.toggleFailed': 'Gagal mengalihkan sinkronisasi otomatis','memoryTree.status.justNow': 'baru saja','memoryTree.status.secondsAgo': '{count} dtk lalu',@@ -2650,8 +2654,6 @@ const messages: TranslationMap = {'memorySources.kind.twitter_query': 'Pencarian Twitter','memorySources.kind.rss_feed': 'Feed RSS','memorySources.kind.web_page': 'Halaman Web',- 'memorySources.sync.successTitle': 'Menyinkronkan',- 'memorySources.sync.successMessage': 'Kemajuan akan segera muncul.','memorySources.sync.failedTitle': 'Sinkronisasi gagal:','memorySources.sync.completeTitle': 'Tersinkron','memorySources.sync.itemsSynced': 'item tersinkron',@@ -2659,6 +2661,13 @@ const messages: TranslationMap = {'memorySources.sync.failedLabel': 'Gagal','memorySources.sync.morePending': 'Masih ada yang perlu disinkronkan. Klik Sinkronkan lagi','memorySources.sync.budgetSpent': 'Anggaran permintaan hari ini sudah habis. Coba lagi besok',+ 'memorySources.stage.requested': 'Memulai',+ 'memorySources.stage.running': 'Menyinkronkan',+ 'memorySources.stage.fetching': 'Mengambil',+ 'memorySources.stage.stored': 'Menyimpan',+ 'memorySources.stage.queued': 'Memproses ke memori',+ 'memorySources.stage.ingesting': 'Memproses ke memori',+ 'memorySources.stage.unknown': 'Menyinkronkan','time.justNow': 'baru saja','time.secondsAgoSuffix': 'd lalu','time.minutesAgoSuffix': 'm lalu',diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.tsindex b1e888c849..7dc9eb6fdd 100644--- a/app/src/lib/i18n/it.ts+++ b/app/src/lib/i18n/it.ts@@ -390,6 +390,8 @@ const messages: TranslationMap = {'sync.status.success': 'Riuscito','sync.status.failed': 'Non riuscito','sync.status.partial': 'Recuperato, indicizzazione in memoria non riuscita',+ 'sync.nowSyncing.title': 'Sincronizzazione in corso',+ 'sync.nowSyncing.empty': 'Nessuna sincronizzazione in corso.','common.error': 'Errore','common.success': 'Successo','common.back': 'Indietro',@@ -997,6 +999,8 @@ const messages: TranslationMap = {'memoryTree.status.retryFailedDone': 'Lavori non riusciti rimessi in coda','memoryTree.status.retryFailedCount': 'Lavori in coda per una nuova esecuzione: {count}.','memoryTree.status.retryFailedError': 'Impossibile rimettere in coda i lavori non riusciti',+ 'memoryTree.status.jobQueue':+ 'Attività di memoria: {ready} in attesa, {running} in corso, {failed} non riuscite','memoryTree.status.toggleFailed':'Impossibile attivare/disattivare la sincronizzazione automatica','memoryTree.status.justNow': 'proprio adesso',@@ -2688,8 +2692,6 @@ const messages: TranslationMap = {'memorySources.kind.twitter_query': 'Ricerca su Twitter','memorySources.kind.rss_feed': 'Feed RSS','memorySources.kind.web_page': 'Pagina web',- 'memorySources.sync.successTitle': 'Sincronizzazione',- 'memorySources.sync.successMessage': 'Il progresso apparirà a breve.','memorySources.sync.failedTitle': 'Sincronizzazione fallita:','memorySources.sync.completeTitle': 'Sincronizzato','memorySources.sync.itemsSynced': 'elementi sincronizzati',@@ -2697,6 +2699,13 @@ const messages: TranslationMap = {'memorySources.sync.failedLabel': 'Non riuscito','memorySources.sync.morePending': 'Altro da sincronizzare. Fai di nuovo clic su Sincronizza','memorySources.sync.budgetSpent': 'Il budget di richieste di oggi è esaurito. Riprova domani',+ 'memorySources.stage.requested': 'Avvio',+ 'memorySources.stage.running': 'Sincronizzazione',+ 'memorySources.stage.fetching': 'Recupero',+ 'memorySources.stage.stored': 'Salvataggio',+ 'memorySources.stage.queued': 'Elaborazione nella memoria',+ 'memorySources.stage.ingesting': 'Elaborazione nella memoria',+ 'memorySources.stage.unknown': 'Sincronizzazione','time.justNow': 'proprio ora','time.secondsAgoSuffix': 's fa','time.minutesAgoSuffix': 'min fa',diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.tsindex d153bfdad5..b27104b79d 100644--- a/app/src/lib/i18n/ko.ts+++ b/app/src/lib/i18n/ko.ts@@ -374,6 +374,8 @@ const messages: TranslationMap = {'sync.status.success': '성공','sync.status.failed': '실패','sync.status.partial': '가져왔지만 메모리 기록 실패',+ 'sync.nowSyncing.title': '지금 동기화 중',+ 'sync.nowSyncing.empty': '지금 동기화 중인 항목이 없습니다.','common.error': '오류','common.success': '성공','common.back': '뒤로',@@ -961,6 +963,7 @@ const messages: TranslationMap = {'memoryTree.status.retryFailedDone': '실패한 작업을 다시 대기열에 넣었습니다','memoryTree.status.retryFailedCount': '{count}개 작업이 다시 실행되도록 대기열에 있습니다.','memoryTree.status.retryFailedError': '실패한 작업을 다시 대기열에 넣지 못했습니다',+ 'memoryTree.status.jobQueue': '메모리 작업: 대기 {ready}개, 실행 중 {running}개, 실패 {failed}개','memoryTree.status.toggleFailed': '자동 동기화를 전환할 수 없습니다.','memoryTree.status.justNow': '방금 전','memoryTree.status.secondsAgo': '{count}초 전',@@ -2605,8 +2608,6 @@ const messages: TranslationMap = {'memorySources.kind.twitter_query': 'Twitter 검색','memorySources.kind.rss_feed': 'RSS 피드','memorySources.kind.web_page': '웹 페이지',- 'memorySources.sync.successTitle': '동기화 중',- 'memorySources.sync.successMessage': '진행 상황이 곧 표시됩니다.','memorySources.sync.failedTitle': '동기화 실패:','memorySources.sync.completeTitle': '동기화됨','memorySources.sync.itemsSynced': '항목 동기화됨',@@ -2614,6 +2615,13 @@ const messages: TranslationMap = {'memorySources.sync.failedLabel': '실패','memorySources.sync.morePending': '동기화할 항목이 더 있습니다. 동기화를 다시 클릭하세요','memorySources.sync.budgetSpent': '오늘의 요청 한도를 모두 사용했습니다. 내일 다시 시도하세요',+ 'memorySources.stage.requested': '시작하는 중',+ 'memorySources.stage.running': '동기화 중',+ 'memorySources.stage.fetching': '가져오는 중',+ 'memorySources.stage.stored': '저장하는 중',+ 'memorySources.stage.queued': '메모리에 반영하는 중',+ 'memorySources.stage.ingesting': '메모리에 반영하는 중',+ 'memorySources.stage.unknown': '동기화 중','time.justNow': '방금 전','time.secondsAgoSuffix': '초 전','time.minutesAgoSuffix': '분 전',diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.tsindex e04c88a3b4..2fb9ba7a22 100644--- a/app/src/lib/i18n/pl.ts+++ b/app/src/lib/i18n/pl.ts@@ -389,6 +389,8 @@ const messages: TranslationMap = {'sync.status.success': 'Sukces','sync.status.failed': 'Niepowodzenie','sync.status.partial': 'Pobrano, zapis do pamięci nie powiódł się',+ 'sync.nowSyncing.title': 'Trwa synchronizacja',+ 'sync.nowSyncing.empty': 'Obecnie nic nie jest synchronizowane.','common.error': 'Błąd','common.success': 'Sukces','common.back': 'Wstecz',@@ -987,6 +989,8 @@ const messages: TranslationMap = {'memoryTree.status.retryFailedDone': 'Nieudane zadania wróciły do kolejki','memoryTree.status.retryFailedCount': 'W kolejce do ponownego uruchomienia: {count}.','memoryTree.status.retryFailedError': 'Nie udało się ponowić nieudanych zadań',+ 'memoryTree.status.jobQueue':+ 'Zadania pamięci: {ready} oczekujących, {running} w toku, {failed} nieudanych','memoryTree.status.toggleFailed': 'Nie udało się przełączyć automatycznej synchronizacji','memoryTree.status.justNow': 'przed chwilą','memoryTree.status.secondsAgo': '{count} s temu',@@ -2669,8 +2673,6 @@ const messages: TranslationMap = {'memorySources.kind.twitter_query': 'Wyszukiwanie Twittera','memorySources.kind.rss_feed': 'Kanał RSS','memorySources.kind.web_page': 'Strona internetowa',- 'memorySources.sync.successTitle': 'Synchronizowanie',- 'memorySources.sync.successMessage': 'Postęp pojawi się za chwilę.','memorySources.sync.failedTitle': 'Synchronizacja nie powiodła się:','memorySources.sync.completeTitle': 'Zsynchronizowano','memorySources.sync.itemsSynced': 'zsynchronizowanych elementów',@@ -2678,6 +2680,13 @@ const messages: TranslationMap = {'memorySources.sync.failedLabel': 'Niepowodzenie','memorySources.sync.morePending': 'Jest więcej do synchronizacji. Kliknij Synchronizuj ponownie','memorySources.sync.budgetSpent': 'Dzisiejszy limit zapytań został wyczerpany. Spróbuj jutro',+ 'memorySources.stage.requested': 'Uruchamianie',+ 'memorySources.stage.running': 'Synchronizowanie',+ 'memorySources.stage.fetching': 'Pobieranie',+ 'memorySources.stage.stored': 'Zapisywanie',+ 'memorySources.stage.queued': 'Przetwarzanie do pamięci',+ 'memorySources.stage.ingesting': 'Przetwarzanie do pamięci',+ 'memorySources.stage.unknown': 'Synchronizowanie','time.justNow': 'przed chwilą','time.secondsAgoSuffix': 's temu','time.minutesAgoSuffix': 'min temu',diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.tsindex a087052ba9..2b7d74c97d 100644--- a/app/src/lib/i18n/pt.ts+++ b/app/src/lib/i18n/pt.ts@@ -384,6 +384,8 @@ const messages: TranslationMap = {'sync.status.success': 'Sucesso','sync.status.failed': 'Falhou','sync.status.partial': 'Conteúdo obtido, mas falhou ao indexar na memória',+ 'sync.nowSyncing.title': 'Sincronizando agora',+ 'sync.nowSyncing.empty': 'Nada está sendo sincronizado agora.','common.error': 'Erro','common.success': 'Sucesso','common.back': 'Voltar',@@ -992,6 +994,8 @@ const messages: TranslationMap = {'memoryTree.status.retryFailedDone': 'Tarefas com falha recolocadas na fila','memoryTree.status.retryFailedCount': 'Tarefas na fila para executar de novo: {count}.','memoryTree.status.retryFailedError': 'Não foi possível recolocar as tarefas com falha na fila',+ 'memoryTree.status.jobQueue':+ 'Tarefas de memória: {ready} aguardando, {running} em execução, {failed} com falha','memoryTree.status.toggleFailed': 'Não foi possível ativar/desativar a sincronização automática','memoryTree.status.justNow': 'agora mesmo','memoryTree.status.secondsAgo': '{count}s atrás',@@ -2686,8 +2690,6 @@ const messages: TranslationMap = {'memorySources.kind.twitter_query': 'Busca no Twitter','memorySources.kind.rss_feed': 'Feed RSS','memorySources.kind.web_page': 'Página da Web',- 'memorySources.sync.successTitle': 'Sincronizando',- 'memorySources.sync.successMessage': 'O progresso aparecerá em breve.','memorySources.sync.failedTitle': 'Falha na sincronização:','memorySources.sync.completeTitle': 'Sincronizado','memorySources.sync.itemsSynced': 'itens sincronizados',@@ -2696,6 +2698,13 @@ const messages: TranslationMap = {'memorySources.sync.morePending': 'Há mais para sincronizar. Clique em Sincronizar novamente','memorySources.sync.budgetSpent':'O orçamento de solicitações de hoje acabou. Tente novamente amanhã',+ 'memorySources.stage.requested': 'Iniciando',+ 'memorySources.stage.running': 'Sincronizando',+ 'memorySources.stage.fetching': 'Buscando',+ 'memorySources.stage.stored': 'Salvando',+ 'memorySources.stage.queued': 'Processando na memória',+ 'memorySources.stage.ingesting': 'Processando na memória',+ 'memorySources.stage.unknown': 'Sincronizando','time.justNow': 'agora mesmo','time.secondsAgoSuffix': 's atrás','time.minutesAgoSuffix': 'min atrás',diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.tsindex a9967fce18..9b72918eb2 100644--- a/app/src/lib/i18n/ru.ts+++ b/app/src/lib/i18n/ru.ts@@ -383,6 +383,8 @@ const messages: TranslationMap = {'sync.status.success': 'Успешно','sync.status.failed': 'Сбой','sync.status.partial': 'Получено, но не записано в память',+ 'sync.nowSyncing.title': 'Сейчас синхронизируется',+ 'sync.nowSyncing.empty': 'Сейчас ничего не синхронизируется.','common.error': 'Ошибка','common.success': 'Готово','common.back': 'Назад',@@ -981,6 +983,8 @@ const messages: TranslationMap = {'memoryTree.status.retryFailedDone': 'Неудавшиеся задачи снова в очереди','memoryTree.status.retryFailedCount': 'Задач в очереди на повторный запуск: {count}.','memoryTree.status.retryFailedError': 'Не удалось вернуть неудавшиеся задачи в очередь',+ 'memoryTree.status.jobQueue':+ 'Задачи памяти: {ready} ожидают, {running} выполняются, {failed} с ошибкой','memoryTree.status.toggleFailed': 'Не удалось включить автосинхронизацию.','memoryTree.status.justNow': 'прямо сейчас','memoryTree.status.secondsAgo': '{count} сек. назад',@@ -2657,8 +2661,6 @@ const messages: TranslationMap = {'memorySources.kind.twitter_query': 'Поиск в Твиттере','memorySources.kind.rss_feed': 'RSS Лента','memorySources.kind.web_page': 'Веб-страница',- 'memorySources.sync.successTitle': 'Синхронизация',- 'memorySources.sync.successMessage': 'Прогресс появится в ближайшее время.','memorySources.sync.failedTitle': 'Синхронизация не удалась:','memorySources.sync.completeTitle': 'Синхронизировано','memorySources.sync.itemsSynced': 'элементов синхронизировано',@@ -2666,6 +2668,13 @@ const messages: TranslationMap = {'memorySources.sync.failedLabel': 'Не удалось','memorySources.sync.morePending': 'Есть что синхронизировать. Нажмите «Синхронизировать» ещё раз','memorySources.sync.budgetSpent': 'Дневной лимит запросов исчерпан. Попробуйте завтра',+ 'memorySources.stage.requested': 'Запуск',+ 'memorySources.stage.running': 'Синхронизация',+ 'memorySources.stage.fetching': 'Получение',+ 'memorySources.stage.stored': 'Сохранение',+ 'memorySources.stage.queued': 'Обработка в памяти',+ 'memorySources.stage.ingesting': 'Обработка в памяти',+ 'memorySources.stage.unknown': 'Синхронизация','time.justNow': 'только что','time.secondsAgoSuffix': 'с назад','time.minutesAgoSuffix': 'мин назад',diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.tsindex 2d7bf33316..29a965d07e 100644--- a/app/src/lib/i18n/zh-CN.ts+++ b/app/src/lib/i18n/zh-CN.ts@@ -351,6 +351,8 @@ const messages: TranslationMap = {'sync.status.success': '成功','sync.status.failed': '失败','sync.status.partial': '已获取,但记忆摄取失败',+ 'sync.nowSyncing.title': '当前同步',+ 'sync.nowSyncing.empty': '目前没有正在进行的同步。','common.error': '错误','common.success': '成功','common.back': '返回',@@ -913,6 +915,7 @@ const messages: TranslationMap = {'memoryTree.status.retryFailedDone': '失败的任务已重新排队','memoryTree.status.retryFailedCount': '已有 {count} 个任务重新排队等待运行。','memoryTree.status.retryFailedError': '无法将失败的任务重新排队',+ 'memoryTree.status.jobQueue': '记忆任务:{ready} 个等待中,{running} 个运行中,{failed} 个失败','memoryTree.status.toggleFailed': '无法切换自动同步','memoryTree.status.justNow': '刚刚','memoryTree.status.secondsAgo': '{count} 秒前',@@ -2488,8 +2491,6 @@ const messages: TranslationMap = {'memorySources.kind.twitter_query': 'Twitter 搜索','memorySources.kind.rss_feed': 'RSS 订阅','memorySources.kind.web_page': '网页',- 'memorySources.sync.successTitle': '正在同步',- 'memorySources.sync.successMessage': '进度很快会显示。','memorySources.sync.failedTitle': '同步失败:','memorySources.sync.completeTitle': '已同步','memorySources.sync.itemsSynced': '项已同步',@@ -2497,6 +2498,13 @@ const messages: TranslationMap = {'memorySources.sync.failedLabel': '失败','memorySources.sync.morePending': '还有更多待同步。请再次点击“同步”','memorySources.sync.budgetSpent': '今日请求额度已用完。请明天再试',+ 'memorySources.stage.requested': '正在开始',+ 'memorySources.stage.running': '正在同步',+ 'memorySources.stage.fetching': '正在获取',+ 'memorySources.stage.stored': '正在保存',+ 'memorySources.stage.queued': '正在存入记忆',+ 'memorySources.stage.ingesting': '正在存入记忆',+ 'memorySources.stage.unknown': '正在同步','time.justNow': '刚刚','time.secondsAgoSuffix': '秒前','time.minutesAgoSuffix': '分钟前',diff --git a/app/src/pages/Brain.tsx b/app/src/pages/Brain.tsxindex f580eeacfc..a93dbaedec 100644--- a/app/src/pages/Brain.tsx+++ b/app/src/pages/Brain.tsx@@ -12,6 +12,7 @@ import { MemoryControls } from '../components/intelligence/MemoryControls';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 PageWelcome from '../components/layout/PageWelcome';@@ -399,6 +400,11 @@ export default function Brain() {<Card padded divided={false}><MemoryTreeStatusPanel onToast={addToast} /></Card>+ {/* openhuman#6257: what is syncing right now, beside the+ history of what already ran. */}+ <Card padded divided={false} data-testid="brain-sync-activity">+ <SyncActivityCard />+ </Card>{/* Sync history relocated from the Memory Inspection panel sothe Sync tab is the single sync surface. */}<Card padded divided={false} data-testid="brain-sync-history">diff --git a/app/src/pages/__tests__/Brain.test.tsx b/app/src/pages/__tests__/Brain.test.tsxindex 65e6548f67..b7d1ca8ffe 100644--- a/app/src/pages/__tests__/Brain.test.tsx+++ b/app/src/pages/__tests__/Brain.test.tsx@@ -66,6 +66,13 @@ vi.mock('../../components/intelligence/SyncAuditPanel', async () => {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}` })),@@ -160,6 +167,8 @@ describe('Brain page', () => {await waitFor(() => {expect(screen.getByTestId('brain-sync-history')).toBeInTheDocument();expect(screen.getByTestId('brain-sync-audit')).toBeInTheDocument();+ expect(screen.getByTestId('brain-sync-activity')).toBeInTheDocument();+ expect(screen.getByTestId('brain-sync-activity-card')).toBeInTheDocument();});});});diff --git a/app/src/services/memorySourcesService.ts b/app/src/services/memorySourcesService.tsindex 0a03eb6a71..d032126cd4 100644--- a/app/src/services/memorySourcesService.ts+++ b/app/src/services/memorySourcesService.ts@@ -144,6 +144,11 @@ 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;diff --git a/crates/openhuman-core/src/integrations/composio/ops/connector_runs.rs b/crates/openhuman-core/src/integrations/composio/ops/connector_runs.rsnew file mode 100644index 0000000000..1a30d6cce0--- /dev/null+++ b/crates/openhuman-core/src/integrations/composio/ops/connector_runs.rs@@ -0,0 +1,102 @@+//! Sync History rows for Composio runs (openhuman#6257).+//!+//! Every Composio run is read by the connector module and ingested by this+//! host, so the memory driver's audit log never sees one — the engine loop that+//! used to write those rows left with tinymemory v1.13.4. They are recorded in+//! the host's run log instead, at the two places a run ends: the Sources row's+//! budgeted loop in `providers_ops`, and the single-call drain in `pass_budget`+//! that every other entry point shares.++use std::time::Instant;++use chrono::{DateTime, Utc};++use crate::config::Config;+use crate::memory::api::provider::sync::SyncAuditEntry;+use crate::memory::sources::run_history::{self, HostRun};++use super::providers_ops::SOURCE_KIND;+use super::source_rows::source_id_for_connection;++/// The reason the periodic loop syncs under.+const PERIODIC: &str = "periodic";++/// Whether a finished run earns a Sync History row.+///+/// A run someone started always does — the Sync button, Apply all, the first+/// sync after connecting, a provider sync, Slack's own RPC — because "did my+/// sync happen" is the question the history answers. The periodic loop polls+/// every connection on a short interval, and a poll that found nothing new is+/// not a sync anyone asked about; recorded, it would bury the runs that were.+/// So a periodic run earns a row only when it wrote something or failed.+pub(crate) fn should_record(reason: &str, written: u64, failed: bool) -> bool {+ reason != PERIODIC || failed || written > 0+}++/// The scope a connector run files under: `{toolkit}:{connection_id}`, toolkit+/// lowercased, both trimmed — the ingest funnel's `path_scope`, so the history+/// row and the sealed tree name the same thing.+pub(crate) fn connector_scope(toolkit: &str, connection_id: &str) -> String {+ format!(+ "{}:{}",+ toolkit.trim().to_ascii_lowercase(),+ connection_id.trim()+ )+}++/// One finished connector run.+pub(crate) struct ConnectorRun<'a> {+ pub toolkit: &'a str,+ pub connection_id: &'a str,+ /// The Sources row that started the run, when one did; otherwise the row is+ /// looked up by connection.+ pub source_id: Option<&'a str>,+ pub reason: &'a str,+ pub started: Instant,+ /// Items the run wrote before it ended.+ pub written: u64,+ /// Why the run failed; `None` for a run that completed.+ pub error: Option<&'a str>,+}++/// The history row for `run`, naming `source_id` when the registry has one and+/// the connection's scope otherwise.+pub(crate) fn connector_run_entry(+ run: &ConnectorRun<'_>,+ source_id: Option<String>,+ finished_at: DateTime<Utc>,+) -> SyncAuditEntry {+ let scope = connector_scope(run.toolkit, run.connection_id);+ HostRun {+ source_id: source_id.unwrap_or_else(|| scope.clone()),+ source_kind: SOURCE_KIND.to_string(),+ scope,+ items: run.written,+ duration_ms: run_history::elapsed_ms(run.started),+ error: run.error.map(str::to_string),+ ..HostRun::default()+ }+ .into_entry(finished_at)+}++/// Record `run` in the host's run log, when [`should_record`] says it earns a+/// row.+pub(crate) fn record(config: &Config, run: &ConnectorRun<'_>) {+ if !should_record(run.reason, run.written, run.error.is_some()) {+ tracing::debug!(+ toolkit = %run.toolkit,+ connection_id = %run.connection_id,+ "[composio] periodic run found nothing new; no history row"+ );+ return;+ }+ let source_id = run+ .source_id+ .map(str::to_string)+ .or_else(|| source_id_for_connection(config, run.toolkit, run.connection_id));+ run_history::record_run(config, connector_run_entry(run, source_id, Utc::now()));+}++#[cfg(test)]+#[path = "connector_runs_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/integrations/composio/ops/connector_runs_tests.rs b/crates/openhuman-core/src/integrations/composio/ops/connector_runs_tests.rsnew file mode 100644index 0000000000..e5349c0ef8--- /dev/null+++ b/crates/openhuman-core/src/integrations/composio/ops/connector_runs_tests.rs@@ -0,0 +1,122 @@+//! Which connector runs earn a history row, and the row they write+//! (openhuman#6257).++use chrono::TimeZone;++use super::*;+use crate::memory::sources::run_history::{read_runs, KEEP_ROWS};++fn finished_at() -> DateTime<Utc> {+ Utc.timestamp_opt(1_789_000_000, 0)+ .single()+ .expect("a valid instant")+}++fn gmail_run(+ reason: &'static str,+ written: u64,+ error: Option<&'static str>,+) -> ConnectorRun<'static> {+ ConnectorRun {+ toolkit: "gmail",+ connection_id: "ca_1",+ source_id: None,+ reason,+ started: Instant::now(),+ written,+ error,+ }+}++#[test]+fn a_run_someone_started_always_earns_a_row() {+ for reason in ["manual", "connection_created"] {+ assert!(+ should_record(reason, 0, false),+ "{reason} with nothing written"+ );+ assert!(should_record(reason, 3, false), "{reason} with items");+ assert!(should_record(reason, 0, true), "{reason} that failed");+ }+}++#[test]+fn a_periodic_run_earns_a_row_only_when_it_wrote_or_failed() {+ assert!(+ !should_record("periodic", 0, false),+ "a quiet poll adds no row"+ );+ assert!(should_record("periodic", 1, false));+ assert!(should_record("periodic", 0, true));+}++#[test]+fn the_scope_is_the_ingest_funnels_path_scope() {+ assert_eq!(connector_scope(" GMAIL ", " ca_1 "), "gmail:ca_1");+}++#[test]+fn the_row_names_the_source_when_one_is_known_and_the_scope_otherwise() {+ let run = gmail_run("manual", 12, None);++ let known = connector_run_entry(&run, Some("src_gmail".to_string()), finished_at());+ assert_eq!(known.source_id, "src_gmail");+ assert_eq!(known.source_kind, "composio");+ assert_eq!(known.scope, "gmail:ca_1");+ assert!(known.success);+ assert_eq!(known.items_fetched, 12);+ assert_eq!(known.timestamp, finished_at());++ let unknown = connector_run_entry(&run, None, finished_at());+ assert_eq!(unknown.source_id, "gmail:ca_1");+}++#[test]+fn a_failed_run_row_carries_the_error_and_what_it_wrote() {+ let row = connector_run_entry(+ &gmail_run("manual", 4, Some("module unavailable")),+ None,+ finished_at(),+ );+ assert!(!row.success);+ assert_eq!(row.error.as_deref(), Some("module unavailable"));+ assert_eq!(+ row.items_fetched, 4,+ "items written before the failure are committed"+ );+}++#[test]+fn record_skips_a_quiet_periodic_poll_and_writes_the_rest() {+ let dir = tempfile::tempdir().expect("tempdir");+ let config = Config {+ workspace_dir: dir.path().join("workspace"),+ config_path: dir.path().join("config.toml"),+ ..Config::default()+ };++ record(&config, &gmail_run("periodic", 0, None));+ assert!(+ read_runs(&config.workspace_dir, KEEP_ROWS)+ .expect("read the run log")+ .is_empty(),+ "a periodic poll that wrote nothing is not recorded"+ );++ let mut started_by_a_row = gmail_run("manual", 2, None);+ started_by_a_row.source_id = Some("src_gmail");+ record(&config, &started_by_a_row);+ record(+ &config,+ &gmail_run("periodic", 0, Some("module unavailable")),+ );++ let rows = read_runs(&config.workspace_dir, KEEP_ROWS).expect("read the run log");+ assert_eq!(rows.len(), 2);+ assert_eq!(rows[0].error.as_deref(), Some("module unavailable"));+ assert_eq!(+ rows[0].source_id, "gmail:ca_1",+ "no registry row for the connection, so the row names its scope"+ );+ assert_eq!(rows[1].source_id, "src_gmail");+}diff --git a/crates/openhuman-core/src/integrations/composio/ops/mod.rs b/crates/openhuman-core/src/integrations/composio/ops/mod.rsindex a17e71664d..edb4e22f2a 100644--- a/crates/openhuman-core/src/integrations/composio/ops/mod.rs+++ b/crates/openhuman-core/src/integrations/composio/ops/mod.rs@@ -22,14 +22,18 @@//! | `providers_ops` | `composio_get_user_profile`, `_refresh_...`, `composio_sync` |//! | `direct_mode` | `composio_get_mode`, `composio_set_api_key`, `_clear_...` |//! | `user_scopes` | per-toolkit agent scope prefs, over the bound memory driver |+//! | `connector_runs` | Sync History rows for Composio runs (openhuman#6257) |+//! | `source_rows` | which memory-sources row a Composio connection belongs to |mod connections;+mod connector_runs;mod direct_mode;mod error_utils;mod execute;mod memory_cleanup;mod pass_budget;mod providers_ops;+mod source_rows;mod toolkits;mod tools_ops;mod triggers;@@ -37,19 +41,20 @@ mod user_scopes;// ── Public re-exports (match original ops.rs public surface) ───────────────+#[cfg(test)]+pub(crate) use crate::memory::sources::run_history::completed_sync_detail;pub use connections::{composio_authorize, composio_delete_connection, composio_list_connections};pub use direct_mode::{composio_clear_api_key, composio_get_mode, composio_set_api_key};pub(crate) use error_utils::{report_composio_op_error, should_forward_tags};pub use execute::composio_execute;#[cfg(test)]-pub(crate) use providers_ops::{- completed_sync_detail, completed_sync_detail_for_test, next_pass_budget,- pick_source_sync_depth_days,-};+pub(crate) use providers_ops::{completed_sync_detail_for_test, next_pass_budget};pub use providers_ops::{composio_get_user_profile, composio_refresh_all_identities, composio_sync,composio_sync_budgeted, composio_sync_for_source, RefreshIdentitiesReport, SYNC_PASS_MAX_ITEMS,};+#[cfg(test)]+pub(crate) use source_rows::pick_source_sync_depth_days;// The tinyconnectors-mediated sync pass, repeated within one call's item// budget for the entry points that sync once per invocation (periodic tick,// manual provider sync, `connection_created`, the Slack ingest RPC) — seediff --git a/crates/openhuman-core/src/integrations/composio/ops/pass_budget.rs b/crates/openhuman-core/src/integrations/composio/ops/pass_budget.rsindex 495d1dd42a..cefdf36ad3 100644--- a/crates/openhuman-core/src/integrations/composio/ops/pass_budget.rs+++ b/crates/openhuman-core/src/integrations/composio/ops/pass_budget.rs@@ -84,16 +84,36 @@ where/// [`run_sync_pass`] for the single-call entry points: the same/// tinyconnectors-mediated pass, repeated within [`SINGLE_CALL_ITEM_BUDGET`].+///+/// Also where each of those runs gets its Sync History row (openhuman#6257):+/// the periodic tick, the first sync after connecting, a provider sync and the+/// Slack RPC all end here, so recording at the callers would be four copies of+/// one rule. A drain that fails records no item count — the passes before the+/// failure are committed, but the error carries no total.pub(crate) async fn run_sync_within_budget(config: &Config,toolkit: &str,connection_id: &str,reason: &str,) -> Result<SyncPassOutcome, String> {- run_passes_within_budget(SINGLE_CALL_ITEM_BUDGET, |pass_budget| {+ let started = std::time::Instant::now();+ let result = run_passes_within_budget(SINGLE_CALL_ITEM_BUDGET, |pass_budget| {run_sync_pass(config, toolkit, connection_id, reason, pass_budget)})- .await+ .await;+ super::connector_runs::record(+ config,+ &super::connector_runs::ConnectorRun {+ toolkit,+ connection_id,+ source_id: None,+ reason,+ started,+ written: result.as_ref().map_or(0, |pass| u64::from(pass.written)),+ error: result.as_ref().err().map(String::as_str),+ },+ );+ result}#[cfg(test)]diff --git a/crates/openhuman-core/src/integrations/composio/ops/providers_ops.rs b/crates/openhuman-core/src/integrations/composio/ops/providers_ops.rsindex 3930dfd062..d896d42ab7 100644--- a/crates/openhuman-core/src/integrations/composio/ops/providers_ops.rs+++ b/crates/openhuman-core/src/integrations/composio/ops/providers_ops.rs@@ -21,9 +21,12 @@ use super::super::types::{reencode, ComposioRefreshIdentitiesResponse, ComposioUserProfile, ComposioUserProfileRequest,};use super::connections::resolve_toolkit_for_connection;+use super::connector_runs::{self, ConnectorRun};use super::error_utils::{report_composio_op_error, OpResult};+use super::source_rows::source_sync_depth_days;use crate::memory::api::provider::types::SourceItem;use crate::memory::api::types::MemoryTaint;+use crate::memory::sources::run_history::completed_sync_detail;use tinyconnectors_bus::records::{ConnectorSyncRequest, ConnectorSyncResponse};/// The source kind every connector record is ingested under.@@ -32,7 +35,7 @@ use tinyconnectors_bus::records::{ConnectorSyncRequest, ConnectorSyncResponse};/// and answers `Invalid` for a kind it does not know, so it is a literal here/// rather than something derived from the toolkit. Records from Gmail and from/// Slack are both Composio records; the *toolkit* lives in the source id.-const SOURCE_KIND: &str = "composio";+pub(super) const SOURCE_KIND: &str = "composio";/// Per-pass item budget handed to the connector's `Sync` member.///@@ -67,34 +70,6 @@ pub(crate) fn next_pass_budget(source_max_items: Option<u32>, total_written: u64}}-/// The `completed` stage's detail string.-///-/// A parse contract, not prose: the Sources UI extracts the count with-/// `/ingested\s+(\d+)\s+item/i` and falls back to a generic "up to date"-/// when it cannot (#3295). Pinned by a unit test against that exact pattern.-///-/// `note` is what the module said about a run that stopped short — today's-/// request budget being spent, above all. It rides *after* the count, never-/// inside it, so the regex keeps matching and everything past the count is-/// free text the UI can show. Without it a spent budget wrote zero items and-/// read back as "Up to date", the opposite of what happened.-pub(crate) fn completed_sync_detail(- total_written: u64,- more_pending: bool,- note: Option<&str>,-) -> String {- let mut detail = if more_pending {- format!("ingested {total_written} item(s), more pending — Sync again to continue")- } else {- format!("ingested {total_written} item(s)")- };- if let Some(note) = note.map(str::trim).filter(|note| !note.is_empty()) {- detail.push_str("; ");- detail.push_str(note);- }- detail-}-/// Aggregate result of [`composio_refresh_all_identities`].#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]pub struct RefreshIdentitiesReport {@@ -306,6 +281,8 @@ pub async fn composio_sync_budgeted(let connection_for_task = connection_id.to_string();let reason_for_task = reason.as_str().to_string();let source_for_task = source_id.clone();+ let source_for_record = source_id.clone();+ let started = std::time::Instant::now();let trigger_for_task = reason.as_str().to_string();let publish_stage = move |stage: &str, detail: Option<String>| {@@ -412,8 +389,22 @@ pub async fn composio_sync_budgeted(Err(error) => break Err(error),}};+ // The history row goes down before the terminal stage goes out: the+ // Sync History panel refetches when that stage arrives (openhuman#6257).match outcome {Ok(()) => {+ connector_runs::record(+ &config_for_run,+ &ConnectorRun {+ toolkit: &toolkit_for_log,+ connection_id: &connection_for_log,+ source_id: source_for_record.as_deref(),+ reason: &reason_for_task,+ started,+ written: total_written,+ error: None,+ },+ );// The detail is a parse contract, not prose: the Sources UI// extracts the count with `/ingested\s+(\d+)\s+item/i` and// falls back to a generic "up to date" when it cannot (#3295).@@ -434,6 +425,18 @@ pub async fn composio_sync_budgeted(error = %error,"[composio] background sync failed");+ connector_runs::record(+ &config_for_run,+ &ConnectorRun {+ toolkit: &toolkit_for_log,+ connection_id: &connection_for_log,+ source_id: source_for_record.as_deref(),+ reason: &reason_for_task,+ started,+ written: total_written,+ error: Some(error.as_str()),+ },+ );publish_stage("failed", Some(error.clone()));}}@@ -601,11 +604,7 @@ pub(crate) async fn run_sync_pass(// into a failed one. Safe to call unconditionally, too: the contract makes// an empty scope `Ok(0)` rather than an error.if outcome.written > 0 {- let scope = format!(- "{}:{}",- toolkit.trim().to_ascii_lowercase(),- connection_id.trim()- );+ let scope = connector_runs::connector_scope(toolkit, connection_id);match binding.provider().as_tree() {Some(tree) => match tree.flush_source_tree(&scope).await {Ok(seals) => tracing::debug!(@@ -655,76 +654,6 @@ pub(crate) async fn run_sync_pass(})}-/// The per-source "Sync depth (days)" cap for one connection, from the-/// memory-sources registry the pass's own `config` names.-///-/// Resolved here rather than threaded through every caller because there are-/// five of them (the row button, All In, the periodic loop, the connection-/// bootstrap, Slack's own RPC), and `max_items` already showed what happens-/// when each open-codes the same rule: two of the five disagreed-/// (openhuman#6007). Read through `config`, not the process environment: a-/// pass is bound to one workspace, and the global registry path would answer a-/// caller bound to workspace B with workspace A's rows — the cross-workspace-/// leak the registry's `_in` variants exist to prevent. `None` when the row is-/// missing, carries no cap, or the registry cannot be read — each means "no-/// lower bound", which is what every release before the field existed did, so-/// a registry hiccup degrades to the old behaviour rather than to a failed-/// sync.-fn source_sync_depth_days(config: &Config, toolkit: &str, connection_id: &str) -> Option<u32> {- let sources = match crate::memory::sources::registry::list_sources_in(config) {- Ok(sources) => sources,- Err(error) => {- tracing::warn!(- toolkit = %toolkit,- connection_id = %connection_id,- error = %error,- "[composio] memory-sources registry unreadable for the sync depth; \- syncing without a lower bound"- );- return None;- }- };- pick_source_sync_depth_days(- sources- .iter()- .filter(|source| source.kind == crate::memory::sources::SourceKind::Composio)- .map(|source| {- (- source.toolkit.as_deref(),- source.connection_id.as_deref(),- source.sync_depth_days,- )- }),- toolkit,- connection_id,- )-}--/// The cap of the row matching `toolkit` and `connection_id`, if any.-///-/// Matched the way the engine keys the rows — toolkit case-insensitively and-/// trimmed, connection trimmed — and a cap of zero reads as none: the settings-/// field stores "unlimited" as an empty value, and a zero typed by hand would-/// otherwise ask Gmail for mail newer than today.-pub(crate) fn pick_source_sync_depth_days<'a>(- rows: impl IntoIterator<Item = (Option<&'a str>, Option<&'a str>, Option<u32>)>,- toolkit: &str,- connection_id: &str,-) -> Option<u32> {- let toolkit = toolkit.trim();- let connection_id = connection_id.trim();- rows.into_iter()- .find_map(|(row_toolkit, row_connection, depth)| {- let same_toolkit =- row_toolkit.is_some_and(|slug| slug.trim().eq_ignore_ascii_case(toolkit));- let same_connection = row_connection.is_some_and(|id| id.trim() == connection_id);- (same_toolkit && same_connection)- .then_some(depth)- .flatten()- .filter(|days| *days > 0)- })-}-/// Parse the optional `reason` parameter into a [`SyncReason`].////// `None` and the explicit `"manual"` value both map todiff --git a/crates/openhuman-core/src/integrations/composio/ops/source_rows.rs b/crates/openhuman-core/src/integrations/composio/ops/source_rows.rsnew file mode 100644index 0000000000..f629d24a94--- /dev/null+++ b/crates/openhuman-core/src/integrations/composio/ops/source_rows.rs@@ -0,0 +1,133 @@+//! Which memory-sources registry row a Composio connection belongs to.+//!+//! One matching rule with more than one reader: the pass's sync-depth cap and+//! the history row's source id both find the row this way (openhuman#6257).+//! Call sites that each open-code one row rule are how two of them came to+//! disagree before (openhuman#6007).++use crate::config::Config;+use crate::memory::sources::SourceKind;++/// Whether a registry row's toolkit and connection name this connection.+///+/// Matched the way the engine keys the rows: toolkit case-insensitively and+/// trimmed, connection trimmed.+fn names_connection(+ row_toolkit: Option<&str>,+ row_connection: Option<&str>,+ toolkit: &str,+ connection_id: &str,+) -> bool {+ row_toolkit.is_some_and(|slug| slug.trim().eq_ignore_ascii_case(toolkit.trim()))+ && row_connection.is_some_and(|id| id.trim() == connection_id.trim())+}++/// The per-source "Sync depth (days)" cap for one connection, from the+/// memory-sources registry the pass's own `config` names.+///+/// Resolved here rather than threaded through every caller because there are+/// five of them (the row button, All In, the periodic loop, the connection+/// bootstrap, Slack's own RPC), and `max_items` already showed what happens+/// when each open-codes the same rule: two of the five disagreed+/// (openhuman#6007). Read through `config`, not the process environment: a+/// pass is bound to one workspace, and the global registry path would answer a+/// caller bound to workspace B with workspace A's rows — the cross-workspace+/// leak the registry's `_in` variants exist to prevent. `None` when the row is+/// missing, carries no cap, or the registry cannot be read — each means "no+/// lower bound", which is what every release before the field existed did, so+/// a registry hiccup degrades to the old behaviour rather than to a failed+/// sync.+pub(super) fn source_sync_depth_days(+ config: &Config,+ toolkit: &str,+ connection_id: &str,+) -> Option<u32> {+ let sources = match crate::memory::sources::registry::list_sources_in(config) {+ Ok(sources) => sources,+ Err(error) => {+ tracing::warn!(+ toolkit = %toolkit,+ connection_id = %connection_id,+ error = %error,+ "[composio] memory-sources registry unreadable for the sync depth; \+ syncing without a lower bound"+ );+ return None;+ }+ };+ pick_source_sync_depth_days(+ sources+ .iter()+ .filter(|source| source.kind == SourceKind::Composio)+ .map(|source| {+ (+ source.toolkit.as_deref(),+ source.connection_id.as_deref(),+ source.sync_depth_days,+ )+ }),+ toolkit,+ connection_id,+ )+}++/// The cap of the row matching `toolkit` and `connection_id`, if any.+///+/// Matched by [`names_connection`], and a cap of zero reads as none: the+/// settings field stores "unlimited" as an empty value, and a zero typed by+/// hand would otherwise ask Gmail for mail newer than today.+pub(crate) fn pick_source_sync_depth_days<'a>(+ rows: impl IntoIterator<Item = (Option<&'a str>, Option<&'a str>, Option<u32>)>,+ toolkit: &str,+ connection_id: &str,+) -> Option<u32> {+ rows.into_iter()+ .find_map(|(row_toolkit, row_connection, depth)| {+ names_connection(row_toolkit, row_connection, toolkit, connection_id)+ .then_some(depth)+ .flatten()+ .filter(|days| *days > 0)+ })+}++/// The registry id of the Composio row for this connection, if the pass's+/// workspace has one.+///+/// `None` when no row matches or the registry cannot be read. A history row+/// then names the connection's scope instead, which still identifies the run+/// it describes, so neither case is worth failing a recording over.+pub(super) fn source_id_for_connection(+ config: &Config,+ toolkit: &str,+ connection_id: &str,+) -> Option<String> {+ let sources = match crate::memory::sources::registry::list_sources_in(config) {+ Ok(sources) => sources,+ Err(error) => {+ tracing::warn!(+ toolkit = %toolkit,+ connection_id = %connection_id,+ error = %error,+ "[composio] memory-sources registry unreadable; the run's history row \+ names its scope instead of a source"+ );+ return None;+ }+ };+ sources+ .into_iter()+ .find(|source| {+ source.kind == SourceKind::Composio+ && names_connection(+ source.toolkit.as_deref(),+ source.connection_id.as_deref(),+ toolkit,+ connection_id,+ )+ })+ .map(|source| source.id)+}++#[cfg(test)]+#[path = "source_rows_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/integrations/composio/ops/source_rows_tests.rs b/crates/openhuman-core/src/integrations/composio/ops/source_rows_tests.rsnew file mode 100644index 0000000000..33aba855ad--- /dev/null+++ b/crates/openhuman-core/src/integrations/composio/ops/source_rows_tests.rs@@ -0,0 +1,112 @@+//! Which registry row a Composio connection belongs to (openhuman#6257).+//!+//! Driven through a real registry file: `list_sources_in` reads the config the+//! pass names, so each test writes one and points its `Config` at it.++use super::*;+use crate::memory::sources::MemorySourceEntry;++fn composio(+ id: &str,+ toolkit: &str,+ connection_id: &str,+ depth_days: Option<u32>,+) -> MemorySourceEntry {+ let mut entry: MemorySourceEntry = serde_json::from_value(serde_json::json!({+ "id": id,+ "kind": "composio",+ "label": format!("{toolkit} source"),+ "enabled": true,+ "toolkit": toolkit,+ "connection_id": connection_id,+ }))+ .expect("a valid composio source entry");+ entry.sync_depth_days = depth_days;+ entry+}++fn folder(id: &str) -> MemorySourceEntry {+ serde_json::from_value(serde_json::json!({+ "id": id,+ "kind": "folder",+ "label": "Notes",+ "enabled": true,+ "path": ".",+ }))+ .expect("a valid folder source entry")+}++/// A config whose registry holds `entries`. The tempdir is returned so it+/// outlives the test body.+fn config_with(entries: &[MemorySourceEntry]) -> (tempfile::TempDir, Config) {+ let dir = tempfile::tempdir().expect("tempdir");+ let config = Config {+ workspace_dir: dir.path().join("workspace"),+ config_path: dir.path().join("config.toml"),+ ..Config::default()+ };+ crate::memory::sources::registry::replace_sources_in(&config, entries)+ .expect("write the registry");+ (dir, config)+}++#[test]+fn a_connection_resolves_to_its_own_registry_row() {+ let (_dir, config) = config_with(&[+ folder("src_notes"),+ composio("src_gmail_work", "gmail", "ca_work", Some(30)),+ composio("src_gmail_home", "gmail", "ca_home", None),+ composio("src_notion", "notion", "ca_work", Some(14)),+ ]);++ assert_eq!(+ source_id_for_connection(&config, "gmail", "ca_home").as_deref(),+ Some("src_gmail_home"),+ "two connections of one toolkit are told apart by connection"+ );+ assert_eq!(+ source_id_for_connection(&config, " GMAIL ", "ca_work ").as_deref(),+ Some("src_gmail_work"),+ "matched the way the engine keys the rows: trimmed, toolkit case-insensitive"+ );+ assert_eq!(+ source_id_for_connection(&config, "notion", "ca_work").as_deref(),+ Some("src_notion"),+ "one connection id under two toolkits is told apart by toolkit"+ );+ assert_eq!(+ source_id_for_connection(&config, "gmail", "ca_unknown"),+ None+ );+}++#[test]+fn the_depth_cap_comes_from_the_same_row() {+ let (_dir, config) = config_with(&[+ composio("src_gmail_work", "gmail", "ca_work", Some(30)),+ composio("src_gmail_home", "gmail", "ca_home", None),+ ]);++ assert_eq!(+ source_sync_depth_days(&config, "gmail", "ca_work"),+ Some(30)+ );+ assert_eq!(source_sync_depth_days(&config, "gmail", "ca_home"), None);+ assert_eq!(source_sync_depth_days(&config, "slack", "ca_work"), None);+}++#[test]+fn an_unreadable_registry_degrades_to_no_row() {+ let dir = tempfile::tempdir().expect("tempdir");+ // A directory where the config file should be cannot be read as one.+ let config_path = dir.path().join("config.toml");+ std::fs::create_dir_all(&config_path).expect("occupy the config path");+ let config = Config {+ workspace_dir: dir.path().join("workspace"),+ config_path,+ ..Config::default()+ };++ assert_eq!(source_id_for_connection(&config, "gmail", "ca_work"), None);+ assert_eq!(source_sync_depth_days(&config, "gmail", "ca_work"), None);+}diff --git a/crates/openhuman-core/src/memory/sources/mod.rs b/crates/openhuman-core/src/memory/sources/mod.rsindex 5f0facd6b1..826d779dfd 100644--- a/crates/openhuman-core/src/memory/sources/mod.rs+++ b/crates/openhuman-core/src/memory/sources/mod.rs@@ -99,6 +99,11 @@ pub mod sync;// for a `config.toml` rewrite.pub mod reconcile;+// The host's record of the sync runs it drives — the Sync button, Apply all and+// every Composio run, none of which the driver's audit log sees — read beside+// the driver's log by the history RPCs (openhuman#6257).+pub(crate) mod run_history;+// The controller aggregators this domain's RPC surface defines. Aliased// exactly as the pre-extraction module exported them.pub use schemas::{diff --git a/crates/openhuman-core/src/memory/sources/rpc.rs b/crates/openhuman-core/src/memory/sources/rpc.rsindex 63ffaa5a9b..648842e40c 100644--- a/crates/openhuman-core/src/memory/sources/rpc.rs+++ b/crates/openhuman-core/src/memory/sources/rpc.rs@@ -60,6 +60,7 @@mod apply_all;mod coding_sessions;mod cost_reporting;+mod driver_run;mod registry_crud;mod source_sync;mod status_toolkits;diff --git a/crates/openhuman-core/src/memory/sources/rpc/apply_all.rs b/crates/openhuman-core/src/memory/sources/rpc/apply_all.rsindex f6e76a6bb9..bac38bda4d 100644--- a/crates/openhuman-core/src/memory/sources/rpc/apply_all.rs+++ b/crates/openhuman-core/src/memory/sources/rpc/apply_all.rs@@ -137,10 +137,18 @@ pub async fn apply_all_in_rpc() -> Result<RpcOutcome<AllInResponse>, String> {let sync = source_sync.ok_or_else(|| {format!("the bound memory driver '{driver_id}' does not serve source sync")})?;- sync.run_source_sync(&source.id)- .await- .map(|_| ())- .map_err(|error| error.to_string())+ // The same start, finish and history row as the Sync button+ // (openhuman#6257).+ super::driver_run::run_recorded(+ config_ref,+ &source.id,+ Some(&source),+ || sync.run_source_sync(&source.id),+ |error| error.to_string(),+ super::driver_run::bus_stage_publisher(&source.id, source.kind.as_str()),+ )+ .await+ .map(|_| ())}}})diff --git a/crates/openhuman-core/src/memory/sources/rpc/cost_reporting.rs b/crates/openhuman-core/src/memory/sources/rpc/cost_reporting.rsindex e7c0ca00fb..d399c47f4e 100644--- a/crates/openhuman-core/src/memory/sources/rpc/cost_reporting.rs+++ b/crates/openhuman-core/src/memory/sources/rpc/cost_reporting.rs@@ -5,10 +5,16 @@ use crate::config::rpc as config_rpc;use crate::memory::api::provider::sync::SyncAuditEntry;use crate::memory::sources::readers;use crate::memory::sources::registry;+use crate::memory::sources::run_history;use crate::rpc::RpcOutcome;// ── Sync Audit Log ──+/// The most rows the history returns once both logs are merged: the driver's+/// own default ceiling, so the host's runs do not grow the response past what+/// the panel was already sized for.+const HISTORY_ROWS: usize = 1_000;+#[derive(Debug, serde::Serialize)]pub struct SyncAuditLogResponse {pub entries: Vec<SyncAuditEntry>,@@ -16,6 +22,14 @@ pub struct SyncAuditLogResponse {/// Past sync runs, newest first.///+/// # Two logs, one history (openhuman#6257)+///+/// The driver's audit log holds the runs the driver schedules itself. The+/// host's run log ([`run_history`]) holds the runs this host drives — the+/// Sources Sync button, Apply all, and every Composio run. Either alone is a+/// history with holes in it, which is what Brain › Sync showed: nothing, for+/// every sync a user started. Both are read and merged by timestamp.+////// # This is now the driver's most recent rows, not the whole log////// The engine call this replaced returned every line in@@ -30,6 +44,7 @@ pub struct SyncAuditLogResponse {/// A read failure is now an error rather than an empty log. The engine wrapper/// ended in `unwrap_or_default()`, so an unreadable file was reported as "no/// syncs have run" — the one answer a caller cannot distinguish from the truth.+/// The host's log follows the same rule.pub async fn sync_audit_log_rpc() -> Result<RpcOutcome<SyncAuditLogResponse>, String> {tracing::debug!("[memory_sources] sync_audit_log_rpc: entry");let config = config_rpc::load_config_with_timeout().await?;@@ -41,13 +56,19 @@ pub async fn sync_audit_log_rpc() -> Result<RpcOutcome<SyncAuditLogResponse>, St// `None` = the driver's own cap. A caller cannot raise it by asking for// more, so passing a number here would only be this host inventing a// ceiling the driver then clamps anyway.- let entries = sync+ let driver_entries = sync.sync_audit_log(None).await.map_err(|error| format!("sync audit log: {error}"))?;+ let host_entries = run_history::read_runs(&config.workspace_dir, run_history::KEEP_ROWS)+ .map_err(|error| format!("sync run log: {error}"))?;+ let (driver_rows, host_rows) = (driver_entries.len(), host_entries.len());+ let entries = run_history::merge_newest_first(driver_entries, host_entries, HISTORY_ROWS);tracing::debug!(driver = %binding.driver_id(),+ driver_rows,+ host_rows,entries = entries.len(),"[memory_sources] sync_audit_log_rpc: exit");@@ -208,6 +229,40 @@ pub(super) fn summarise_month(summary}+/// [`summarise_month`] over the driver's log and the host's run log together+/// (openhuman#6257).+///+/// The totals add. Completeness needs both halves: the driver's rows prove+/// theirs the usual way, and the host's log is complete for any month when it+/// holds fewer rows than a compaction keeps — it has never dropped one — or+/// when it reaches back past the month the way the driver's does.+pub(super) fn summarise_logs(+ driver: &[SyncAuditEntry],+ host: &[SyncAuditEntry],+ month: &str,+) -> MonthlyCostSummaryResponse {+ let driver_summary = summarise_month(driver, month);+ let host_summary = summarise_month(host, month);+ let host_complete = host.len() < run_history::KEEP_ROWS || host_summary.totals_complete;+ MonthlyCostSummaryResponse {+ month: month.to_string(),+ total_cost_usd: driver_summary.total_cost_usd + host_summary.total_cost_usd,+ total_syncs: driver_summary+ .total_syncs+ .saturating_add(host_summary.total_syncs),+ total_items: driver_summary+ .total_items+ .saturating_add(host_summary.total_items),+ total_input_tokens: driver_summary+ .total_input_tokens+ .saturating_add(host_summary.total_input_tokens),+ total_output_tokens: driver_summary+ .total_output_tokens+ .saturating_add(host_summary.total_output_tokens),+ totals_complete: driver_summary.totals_complete && host_complete,+ }+}+pub async fn monthly_cost_summary_rpc() -> Result<RpcOutcome<MonthlyCostSummaryResponse>, String> {tracing::debug!("[memory_sources] monthly_cost_summary_rpc: entry");let config = config_rpc::load_config_with_timeout().await?;@@ -216,18 +271,21 @@ pub async fn monthly_cost_summary_rpc() -> Result<RpcOutcome<MonthlyCostSummaryRreturn Err(unserved(&binding, "source sync", "monthly_cost_summary"));};- let entries = sync+ let driver_entries = sync.sync_audit_log(None).await.map_err(|error| format!("sync audit log: {error}"))?;+ let host_entries = run_history::read_runs(&config.workspace_dir, run_history::KEEP_ROWS)+ .map_err(|error| format!("sync run log: {error}"))?;let month = chrono::Utc::now().format("%Y-%m").to_string();- let summary = summarise_month(&entries, &month);+ let summary = summarise_logs(&driver_entries, &host_entries, &month);tracing::debug!(driver = %binding.driver_id(),month = %summary.month,- rows_read = entries.len(),+ driver_rows = driver_entries.len(),+ host_rows = host_entries.len(),syncs = summary.total_syncs,totals_complete = summary.totals_complete,"[memory_sources] monthly_cost_summary_rpc: exit"diff --git a/crates/openhuman-core/src/memory/sources/rpc/driver_run.rs b/crates/openhuman-core/src/memory/sources/rpc/driver_run.rsnew file mode 100644index 0000000000..df62a67529--- /dev/null+++ b/crates/openhuman-core/src/memory/sources/rpc/driver_run.rs@@ -0,0 +1,152 @@+//! A driver-backed source sync that reports how it ended (openhuman#6257).+//!+//! The Sync button and Apply all hand folder, GitHub, RSS and web sources to+//! `MemorySourceSync::run_source_sync`. Before #5725 those rows went through the+//! engine's own `sync_source`, which published the run's start and finish and+//! wrote its audit row; the contract member does neither. So a manual sync of+//! these kinds finished in silence: the row stayed on the per-document+//! "Queued" stage until the activity tracker gave up on it, no result chip+//! appeared, the post-sync embed never started, and Sync History never gained a+//! row. [`run_recorded`] puts all of that back around the call.++use std::future::Future;+use std::time::Instant;++use crate::config::Config;+use crate::core::events::DomainEvent;+use crate::memory::api::error::MemoryError;+use crate::memory::api::provider::sync::SyncRunOutcome;+use crate::memory::sources::run_history::{self, HostRun};+use crate::memory::sources::types::MemorySourceEntry;++/// The trigger a user-started driver run reports under — the word the engine's+/// `sync_source` used for the Sync button.+const TRIGGER: &str = "manual";++/// The scope a history row names for `entry`: the rule the engine's periodic+/// writer applies (URL, then toolkit, then the id), so a source's manual and+/// scheduled rows read alike.+pub(super) fn history_scope(entry: &MemorySourceEntry) -> String {+ entry+ .url+ .clone()+ .or_else(|| entry.toolkit.clone())+ .unwrap_or_else(|| entry.id.clone())+}++/// The stage event for one driver-backed source.+pub(super) fn stage_event(+ source_id: &str,+ kind: &str,+ stage: &str,+ detail: Option<String>,+) -> DomainEvent {+ DomainEvent::MemorySyncStageChanged {+ trigger: TRIGGER.to_string(),+ stage: stage.to_string(),+ provider: Some(kind.to_string()),+ // The row id here too, as the engine's `sync_source` sent it: the app+ // still falls back to `connection_id` for a core that sends no+ // `source_id`.+ connection_id: Some(source_id.to_string()),+ detail,+ source_id: Some(source_id.to_string()),+ }+}++/// A stage publisher for one source, on the process bus.+pub(super) fn bus_stage_publisher(source_id: &str, kind: &str) -> impl Fn(&str, Option<String>) {+ let source_id = source_id.to_string();+ let kind = kind.to_string();+ move |stage, detail| {+ crate::core::bus::BUS.publish(stage_event(&source_id, &kind, stage, detail));+ }+}++/// Run one driver-backed sync, publishing its start and finish and recording+/// it in the host's run log.+///+/// `run` performs the sync, `describe` turns its failure into the text the+/// caller returns, and `publish` sends one stage for the source. All three are+/// parameters so the sequence is testable without a driver or the bus.+///+/// The row is written before the terminal stage is published, on purpose: the+/// history panel refetches when that stage arrives, and a row written after it+/// would miss that read.+pub(super) async fn run_recorded<Run, Fut, Describe, Publish>(+ config: &Config,+ source_id: &str,+ entry: Option<&MemorySourceEntry>,+ run: Run,+ describe: Describe,+ publish: Publish,+) -> Result<SyncRunOutcome, String>+where+ Run: FnOnce() -> Fut,+ Fut: Future<Output = Result<SyncRunOutcome, MemoryError>>,+ Describe: FnOnce(&MemoryError) -> String,+ Publish: Fn(&str, Option<String>),+{+ let source_kind = entry.map_or("unknown", |entry| entry.kind.as_str());+ tracing::debug!(+ source_id = %source_id,+ kind = source_kind,+ "[memory_sources:driver_run] run starting"+ );+ publish("running", None);+ let started = Instant::now();+ let result = run().await;++ let record = |outcome: Option<&SyncRunOutcome>, error: Option<String>| {+ run_history::record_run(+ config,+ HostRun {+ source_id: source_id.to_string(),+ source_kind: source_kind.to_string(),+ scope: entry.map_or_else(|| source_id.to_string(), history_scope),+ items: outcome.map_or(0, |outcome| u64::from(outcome.records_ingested)),+ duration_ms: run_history::elapsed_ms(started),+ error,+ actions_called: outcome.map_or(0, |outcome| outcome.actions_called),+ provider_cost_usd: outcome.map_or(0.0, |outcome| outcome.provider_cost_usd),+ }+ .into_entry(chrono::Utc::now()),+ );+ };++ match result {+ Ok(outcome) => {+ record(Some(&outcome), None);+ tracing::debug!(+ source_id = %source_id,+ items = outcome.records_ingested,+ more_pending = outcome.more_pending,+ "[memory_sources:driver_run] run completed"+ );+ publish(+ "completed",+ Some(run_history::completed_sync_detail(+ u64::from(outcome.records_ingested),+ outcome.more_pending,+ outcome.note.as_deref(),+ )),+ );+ Ok(outcome)+ }+ Err(error) => {+ let message = describe(&error);+ record(None, Some(message.clone()));+ tracing::warn!(+ source_id = %source_id,+ error = %message,+ "[memory_sources:driver_run] run failed"+ );+ publish("failed", Some(message.clone()));+ Err(message)+ }+ }+}++#[cfg(test)]+#[path = "driver_run_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/memory/sources/rpc/driver_run_tests.rs b/crates/openhuman-core/src/memory/sources/rpc/driver_run_tests.rsnew file mode 100644index 0000000000..a2b806f2fa--- /dev/null+++ b/crates/openhuman-core/src/memory/sources/rpc/driver_run_tests.rs@@ -0,0 +1,221 @@+//! The driver-backed run's stages and history row (openhuman#6257).++use std::cell::RefCell;++use super::*;+use crate::memory::sources::run_history::{read_runs, KEEP_ROWS};++type Stages = RefCell<Vec<(String, Option<String>)>>;++fn config_in(workspace: &std::path::Path) -> Config {+ Config {+ workspace_dir: workspace.to_path_buf(),+ ..Config::default()+ }+}++fn folder(id: &str) -> MemorySourceEntry {+ serde_json::from_value(serde_json::json!({+ "id": id,+ "kind": "folder",+ "label": "Notes",+ "enabled": true,+ "path": ".",+ }))+ .expect("a valid folder source entry")+}++fn publisher(stages: &Stages) -> impl Fn(&str, Option<String>) + '_ {+ move |stage, detail| stages.borrow_mut().push((stage.to_string(), detail))+}++#[tokio::test]+async fn a_completed_run_publishes_its_start_and_finish_and_records_a_row() {+ let dir = tempfile::tempdir().expect("tempdir");+ let config = config_in(dir.path());+ let entry = folder("src_notes");+ let stages = Stages::default();++ let outcome = run_recorded(+ &config,+ "src_notes",+ Some(&entry),+ || async {+ Ok(SyncRunOutcome {+ records_ingested: 3,+ ..SyncRunOutcome::default()+ })+ },+ |_| unreachable!("a completed run has no failure to describe"),+ publisher(&stages),+ )+ .await+ .expect("the run completed");++ assert_eq!(outcome.records_ingested, 3);+ assert_eq!(+ *stages.borrow(),+ vec![+ ("running".to_string(), None),+ (+ "completed".to_string(),+ Some("ingested 3 item(s)".to_string())+ ),+ ]+ );+ let rows = read_runs(dir.path(), KEEP_ROWS).expect("read the run log");+ assert_eq!(rows.len(), 1);+ let row = &rows[0];+ assert!(row.success);+ assert_eq!(row.source_id, "src_notes");+ assert_eq!(row.source_kind, "folder");+ assert_eq!(row.scope, "src_notes", "a folder has no URL or toolkit");+ assert_eq!(row.items_fetched, 3);+}++#[tokio::test]+async fn a_completed_run_that_stopped_short_says_so_in_its_detail() {+ let dir = tempfile::tempdir().expect("tempdir");+ let config = config_in(dir.path());+ let stages = Stages::default();++ run_recorded(+ &config,+ "src_capped",+ Some(&folder("src_capped")),+ || async {+ Ok(SyncRunOutcome {+ records_ingested: 50,+ more_pending: true,+ note: Some("per-source item limit reached".to_string()),+ ..SyncRunOutcome::default()+ })+ },+ |_| unreachable!("a completed run has no failure to describe"),+ publisher(&stages),+ )+ .await+ .expect("the run completed");++ let finish = stages.borrow().last().cloned().expect("a terminal stage");+ assert_eq!(finish.0, "completed");+ let detail = finish.1.expect("a completed detail");+ assert!(+ detail.starts_with("ingested 50 item(s), more pending"),+ "{detail}"+ );+ assert!(+ detail.ends_with("; per-source item limit reached"),+ "{detail}"+ );+}++#[tokio::test]+async fn a_failed_run_publishes_the_described_failure_and_records_it() {+ let dir = tempfile::tempdir().expect("tempdir");+ let config = config_in(dir.path());+ let entry = folder("src_gone");+ let stages = Stages::default();++ let message = run_recorded(+ &config,+ "src_gone",+ Some(&entry),+ || async {+ Err(MemoryError::NotFound(+ "no memory source registered as src_gone".to_string(),+ ))+ },+ |error| format!("described: {error}"),+ publisher(&stages),+ )+ .await+ .expect_err("the run failed");++ assert!(message.starts_with("described: "), "{message}");+ assert_eq!(+ *stages.borrow(),+ vec![+ ("running".to_string(), None),+ ("failed".to_string(), Some(message.clone())),+ ]+ );+ let rows = read_runs(dir.path(), KEEP_ROWS).expect("read the run log");+ assert_eq!(rows.len(), 1);+ assert!(!rows[0].success);+ assert_eq!(rows[0].error.as_deref(), Some(message.as_str()));+ assert_eq!(rows[0].items_fetched, 0);+}++/// The history panel refetches when the terminal stage arrives, so the row+/// has to be on disk by then.+#[tokio::test]+async fn the_row_is_on_disk_before_the_terminal_stage_goes_out() {+ let dir = tempfile::tempdir().expect("tempdir");+ let config = config_in(dir.path());+ let rows_at_finish = RefCell::new(None);++ run_recorded(+ &config,+ "src_unknown",+ None,+ || async { Ok(SyncRunOutcome::default()) },+ |_| unreachable!("a completed run has no failure to describe"),+ |stage: &str, _detail: Option<String>| {+ if stage == "completed" {+ let rows = read_runs(dir.path(), KEEP_ROWS).expect("read the run log");+ *rows_at_finish.borrow_mut() = Some(rows);+ }+ },+ )+ .await+ .expect("the run completed");++ let rows = rows_at_finish+ .into_inner()+ .expect("the terminal stage was published");+ assert_eq!(rows.len(), 1, "a refetch on `completed` must find the row");+ // A source the host registry does not hold is still recorded, under its id.+ assert_eq!(rows[0].source_kind, "unknown");+ assert_eq!(rows[0].scope, "src_unknown");+}++#[test]+fn the_history_scope_prefers_the_url_then_the_toolkit_then_the_id() {+ let mut entry = folder("src_scope");+ assert_eq!(history_scope(&entry), "src_scope");+ entry.toolkit = Some("gmail".to_string());+ assert_eq!(history_scope(&entry), "gmail");+ entry.url = Some("https://github.com/tinyhumansai/openhuman".to_string());+ assert_eq!(+ history_scope(&entry),+ "https://github.com/tinyhumansai/openhuman"+ );+}++#[test]+fn the_stage_event_names_the_source_for_the_row_indicator() {+ match stage_event(+ "src_ev",+ "folder",+ "completed",+ Some("ingested 1 item(s)".into()),+ ) {+ DomainEvent::MemorySyncStageChanged {+ trigger,+ stage,+ provider,+ connection_id,+ detail,+ source_id,+ } => {+ assert_eq!(trigger, "manual");+ assert_eq!(stage, "completed");+ assert_eq!(provider.as_deref(), Some("folder"));+ assert_eq!(connection_id.as_deref(), Some("src_ev"));+ assert_eq!(source_id.as_deref(), Some("src_ev"));+ assert_eq!(detail.as_deref(), Some("ingested 1 item(s)"));+ }+ other => panic!("expected a sync stage event, got {other:?}"),+ }+}diff --git a/crates/openhuman-core/src/memory/sources/rpc/source_sync.rs b/crates/openhuman-core/src/memory/sources/rpc/source_sync.rsindex 7e15d2382d..d6f6a8444b 100644--- a/crates/openhuman-core/src/memory/sources/rpc/source_sync.rs+++ b/crates/openhuman-core/src/memory/sources/rpc/source_sync.rs@@ -165,11 +165,20 @@ pub async fn sync_rpc(req: SyncRequest) -> Result<RpcOutcome<SyncResponse>, Stribinding.driver_id())})?;- sync.run_source_sync(&req.source_id)- .await- .map_err(|error| {- describe_source_sync_failure(&req.source_id, host_entry.is_some(), &error)- })?;+ // `run_source_sync` reports neither the run's start nor its finish and+ // writes no history row; `run_recorded` owns all three (openhuman#6257).+ let kind = host_entry+ .as_ref()+ .map_or("unknown", |entry| entry.kind.as_str());+ super::driver_run::run_recorded(+ &config,+ &req.source_id,+ host_entry.as_ref(),+ || sync.run_source_sync(&req.source_id),+ |error| describe_source_sync_failure(&req.source_id, host_entry.is_some(), error),+ super::driver_run::bus_stage_publisher(&req.source_id, kind),+ )+ .await?;Ok(RpcOutcome::new(SyncResponse {diff --git a/crates/openhuman-core/src/memory/sources/rpc_monthly_summary_tests_tests.rs b/crates/openhuman-core/src/memory/sources/rpc_monthly_summary_tests_tests.rsindex d5c64a5f3e..9b50039049 100644--- a/crates/openhuman-core/src/memory/sources/rpc_monthly_summary_tests_tests.rs+++ b/crates/openhuman-core/src/memory/sources/rpc_monthly_summary_tests_tests.rs@@ -1,7 +1,8 @@use chrono::{DateTime, Utc};use crate::memory::api::provider::sync::SyncAuditEntry;-use crate::memory::sources::rpc::cost_reporting::summarise_month;+use crate::memory::sources::rpc::cost_reporting::{summarise_logs, summarise_month};+use crate::memory::sources::run_history::KEEP_ROWS;/// One audit row, dated `stamp`, costing `estimated` with no real charge.fn row(stamp: &str, items: u32, input: u64, output: u64, estimated: f64) -> SyncAuditEntry {SyncAuditEntry {@@ -119,3 +120,50 @@ fn a_future_stamped_row_is_skipped_and_proves_nothing() {"a newer row says nothing about how far back the read reached");}++/// The host's runs add to the driver's (openhuman#6257), and a host log short+/// of a compaction's worth of rows has dropped none, so it cannot make the+/// totals a floor.+#[test]+fn both_logs_are_totalled_and_a_short_host_log_is_complete() {+ let driver = vec![+ row("2026-08-20T10:00:00Z", 3, 100, 20, 0.5),+ row("2026-07-31T23:59:59Z", 1, 1, 1, 1.0),+ ];+ let host = vec![row("2026-08-21T10:00:00Z", 4, 0, 0, 0.0)];++ let summary = summarise_logs(&driver, &host, "2026-08");++ assert_eq!(summary.month, "2026-08");+ assert_eq!(summary.total_syncs, 2);+ assert_eq!(summary.total_items, 7);+ assert_eq!(summary.total_input_tokens, 100);+ assert_eq!(summary.total_output_tokens, 20);+ assert!(close(summary.total_cost_usd, 0.5));+ assert!(+ summary.totals_complete,+ "the driver read reached past August and the host log never compacted"+ );+}++/// Completeness needs both halves: a driver read cut off at its cap leaves+/// the totals a floor however complete the host log is, and a host log at a+/// compaction's size has to prove its own reach the way the driver's does.+#[test]+fn either_log_can_leave_the_totals_a_floor() {+ let driver_capped = vec![row("2026-08-20T10:00:00Z", 1, 0, 0, 0.0)];+ let host_short = vec![row("2026-08-21T10:00:00Z", 1, 0, 0, 0.0)];+ assert!(!summarise_logs(&driver_capped, &host_short, "2026-08").totals_complete);++ let driver_complete = vec![row("2026-07-01T00:00:00Z", 1, 0, 0, 0.0)];+ let mut host_full: Vec<SyncAuditEntry> = (0..KEEP_ROWS)+ .map(|_| row("2026-08-21T10:00:00Z", 1, 0, 0, 0.0))+ .collect();+ assert!(+ !summarise_logs(&driver_complete, &host_full, "2026-08").totals_complete,+ "a compacted host log holding only this month's rows may have dropped some"+ );++ host_full.push(row("2026-07-30T00:00:00Z", 1, 0, 0, 0.0));+ assert!(summarise_logs(&driver_complete, &host_full, "2026-08").totals_complete);+}diff --git a/crates/openhuman-core/src/memory/sources/run_history.rs b/crates/openhuman-core/src/memory/sources/run_history.rsnew file mode 100644index 0000000000..201758f5ce--- /dev/null+++ b/crates/openhuman-core/src/memory/sources/run_history.rs@@ -0,0 +1,365 @@+//! The host's record of the sync runs it drives, and how a finished run is+//! reported (openhuman#6257).+//!+//! # Why the host keeps a log of its own+//!+//! Brain › Sync › Sync History reads the memory driver's audit log, and the+//! driver writes that log only for the runs it schedules itself: the periodic+//! folder, GitHub, RSS and web loop. Every run this host drives left no row.+//! The Sources Sync button and Apply all reach the driver through+//! `MemorySourceSync::run_source_sync`, which does not audit (tinymemory's own+//! bus test pins that), and every Composio run is read by the connector module+//! and ingested here, so the driver never sees it as a run at all. A user+//! checking a sync saw nothing happen. Those runs are recorded here instead, in+//! the driver's row shape, and the history RPCs read both logs.+//!+//! The driver's file is not appended to from here. Its path, its format pin and+//! its reader sit behind `MemorySourceSync`; a remote or null driver has no such+//! file; and a writer the driver does not know about would be a second owner of+//! its format.+//!+//! # Bounded+//!+//! One line per run, written with a single `write_all` under a process-wide+//! lock, so two runs finishing together cannot interleave half-lines. Past+//! [`COMPACT_AT_BYTES`] an append rewrites the file to its newest [`KEEP_ROWS`]+//! through a temporary file and a rename, so the periodic Composio loop that+//! feeds it cannot grow it without bound. It rewrites again only once the file+//! has doubled since, so long rows cannot turn every append into a rewrite (see+//! [`compaction_trigger`]).++use std::io::Write;+use std::path::{Path, PathBuf};+use std::sync::{Mutex, PoisonError};+use std::time::Instant;++use chrono::{DateTime, Utc};++use crate::config::Config;+use crate::memory::api::provider::sync::SyncAuditEntry;++/// The host-owned directory under the workspace this log lives in, beside the+/// other JSONL files the host writes.+const STATE_DIR: &str = "state";++/// The log's file name — and the only name error messages use: the full path+/// carries the user's home directory, which has no place in a reported error.+const LOG_FILE: &str = "memory_sync_runs.jsonl";++/// Rows a compaction keeps, and the most a read returns.+pub(crate) const KEEP_ROWS: usize = 1_000;++/// Size past which an append compacts the file. A row is a few hundred bytes,+/// so roughly half as many rows again as [`KEEP_ROWS`] accumulate between+/// rewrites — rare enough that an append stays one write.+const COMPACT_AT_BYTES: u64 = 512 * 1024;++/// Serialises appends, compactions and reads of the log within the process,+/// and holds each log's size right after this process last compacted it.+static LOG_STATE: Mutex<Vec<(PathBuf, u64)>> = Mutex::new(Vec::new());++fn log_path(workspace_dir: &Path) -> PathBuf {+ workspace_dir.join(STATE_DIR).join(LOG_FILE)+}++/// One run this host drove, as the host knows it.+///+/// Converted to the driver's [`SyncAuditEntry`] so a history row reads the same+/// whichever log it came from. Two halves of that row stay empty on purpose:+/// the host prices nothing — the inference price is the driver's to state, see+/// `rpc::cost_reporting` — and it has no tree verdict to report, because+/// `SyncRunOutcome` does not carry one.+#[derive(Clone, Debug, Default, PartialEq)]+pub(crate) struct HostRun {+ pub source_id: String,+ pub source_kind: String,+ pub scope: String,+ pub items: u64,+ pub duration_ms: u64,+ /// Why the run failed; `None` for a run that completed.+ pub error: Option<String>,+ /// Provider actions the run called, when the run reported them.+ pub actions_called: u32,+ /// What the provider charged for those actions, in USD.+ pub provider_cost_usd: f64,+}++impl HostRun {+ /// The audit row for this run, stamped as finishing at `finished_at`.+ pub(crate) fn into_entry(self, finished_at: DateTime<Utc>) -> SyncAuditEntry {+ SyncAuditEntry {+ timestamp: finished_at,+ source_id: self.source_id,+ source_kind: self.source_kind,+ scope: self.scope,+ // Saturating: the row's counter is `u32` on the wire, and a run+ // large enough to pass it is still a run, not a panic.+ items_fetched: u32::try_from(self.items).unwrap_or(u32::MAX),+ batches: 0,+ input_tokens: 0,+ output_tokens: 0,+ estimated_cost_usd: 0.0,+ composio_actions_called: self.actions_called,+ composio_cost_usd: self.provider_cost_usd,+ actual_charged_usd: None,+ duration_ms: self.duration_ms,+ success: self.error.is_none(),+ error: self.error,+ tree_ingest_failures: 0,+ tree_error: None,+ }+ }+}++/// Milliseconds since `started`, saturating.+pub(crate) fn elapsed_ms(started: Instant) -> u64 {+ u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)+}++/// The `completed` stage's detail string.+///+/// A parse contract, not prose: the Sources UI extracts the count with+/// `/ingested\s+(\d+)\s+item/i` and falls back to a generic "up to date"+/// when it cannot (#3295). Pinned by a unit test against that exact pattern.+///+/// `note` is what the run said about stopping short — today's request budget+/// being spent, above all. It rides *after* the count, never inside it, so the+/// regex keeps matching and everything past the count is free text the UI can+/// show. Without it a spent budget wrote zero items and read back as "Up to+/// date", the opposite of what happened.+///+/// Owned here, beside the history row, because every kind of run reports its+/// finish through it: the Composio loop and the driver-backed Sync button both+/// (openhuman#6257).+pub(crate) fn completed_sync_detail(+ total_written: u64,+ more_pending: bool,+ note: Option<&str>,+) -> String {+ let mut detail = if more_pending {+ format!("ingested {total_written} item(s), more pending — Sync again to continue")+ } else {+ format!("ingested {total_written} item(s)")+ };+ if let Some(note) = note.map(str::trim).filter(|note| !note.is_empty()) {+ detail.push_str("; ");+ detail.push_str(note);+ }+ detail+}++/// Record one finished run in `config`'s workspace.+///+/// Never fails the run it describes: the run's items are already committed,+/// and a row that could not be written is a gap in the history, not a failed+/// sync. It is still an unexpected I/O failure on the host's own state+/// directory, so it is reported, not only logged.+pub(crate) fn record_run(config: &Config, entry: SyncAuditEntry) {+ match append_run(&config.workspace_dir, &entry) {+ Ok(()) => tracing::debug!(+ source_id = %entry.source_id,+ source_kind = %entry.source_kind,+ success = entry.success,+ items = entry.items_fetched,+ "[memory_sources:history] sync run recorded"+ ),+ Err(error) => {+ tracing::warn!(+ source_id = %entry.source_id,+ error = %error,+ "[memory_sources:history] could not record a sync run; the run itself is unaffected"+ );+ crate::core::observability::report_error(+ error.as_str(),+ "memory_sources",+ "record_sync_run",+ &[("source_kind", entry.source_kind.as_str())],+ );+ }+ }+}++/// Append `entry` to the log under `workspace_dir`, compacting past the size+/// ceiling.+///+/// # Errors+///+/// When the state directory cannot be created or the row cannot be written. A+/// compaction that fails after the row landed is not an error here — the row+/// is recorded — and is reported separately.+pub(crate) fn append_run(workspace_dir: &Path, entry: &SyncAuditEntry) -> Result<(), String> {+ append_run_compacting_at(workspace_dir, entry, COMPACT_AT_BYTES)+}++fn append_run_compacting_at(+ workspace_dir: &Path,+ entry: &SyncAuditEntry,+ compact_at_bytes: u64,+) -> Result<(), String> {+ let mut line = serde_json::to_vec(entry)+ .map_err(|error| format!("encode a sync run for {LOG_FILE}: {error}"))?;+ line.push(b'\n');++ let path = log_path(workspace_dir);+ let mut compacted = LOG_STATE.lock().unwrap_or_else(PoisonError::into_inner);+ if let Some(directory) = path.parent() {+ std::fs::create_dir_all(directory)+ .map_err(|error| format!("create the directory for {LOG_FILE}: {error}"))?;+ }+ let mut file = std::fs::OpenOptions::new()+ .create(true)+ .append(true)+ .open(&path)+ .map_err(|error| format!("open {LOG_FILE}: {error}"))?;+ // One buffer, one write: on an append handle the whole line lands at once.+ file.write_all(&line)+ .map_err(|error| format!("append to {LOG_FILE}: {error}"))?;++ let trigger = compaction_trigger(&compacted, &path, compact_at_bytes);+ match file.metadata() {+ Ok(metadata) if metadata.len() > trigger => {+ drop(file);+ match compact(&path) {+ Ok(size) => remember_compaction(&mut compacted, &path, size),+ Err(error) => {+ tracing::warn!(+ error = %error,+ "[memory_sources:history] {LOG_FILE} compaction failed; the next append retries it"+ );+ crate::core::observability::report_error(+ error.as_str(),+ "memory_sources",+ "compact_sync_run_log",+ &[],+ );+ }+ }+ }+ Ok(_) => {}+ Err(error) => tracing::warn!(+ error = %error,+ "[memory_sources:history] could not size {LOG_FILE}; compaction skipped this time"+ ),+ }+ Ok(())+}++/// The size past which an append to `path` compacts it: the ceiling, or twice+/// the size this process last compacted the file to, whichever is larger.+///+/// A failed run's row carries its error text, so the newest [`KEEP_ROWS`] can+/// outweigh the ceiling on their own. A ceiling-only rule would then rewrite+/// the whole file on every append; the doubling keeps a rewrite to one per+/// file's worth of new rows.+fn compaction_trigger(compacted: &[(PathBuf, u64)], path: &Path, compact_at_bytes: u64) -> u64 {+ compacted+ .iter()+ .find(|(logged, _)| logged.as_path() == path)+ .map_or(compact_at_bytes, |(_, size)| {+ compact_at_bytes.max(size.saturating_mul(2))+ })+}++/// Note that `path` was just compacted to `size` bytes.+fn remember_compaction(compacted: &mut Vec<(PathBuf, u64)>, path: &Path, size: u64) {+ match compacted+ .iter_mut()+ .find(|(logged, _)| logged.as_path() == path)+ {+ Some((_, last)) => *last = size,+ None => compacted.push((path.to_path_buf(), size)),+ }+}++/// Rewrite the log to its newest [`KEEP_ROWS`] parseable lines, answering the+/// rewritten file's size.+///+/// Through a temporary file and a rename, so a crash mid-compaction leaves the+/// old file whole rather than a truncated one. The caller holds [`LOG_STATE`].+fn compact(path: &Path) -> Result<u64, String> {+ let content = std::fs::read_to_string(path)+ .map_err(|error| format!("read {LOG_FILE} to compact it: {error}"))?;+ let rows: Vec<&str> = content+ .lines()+ .filter(|line| serde_json::from_str::<SyncAuditEntry>(line).is_ok())+ .collect();+ let kept = &rows[rows.len().saturating_sub(KEEP_ROWS)..];+ let mut rewritten = kept.join("\n");+ rewritten.push('\n');+ let size = u64::try_from(rewritten.len()).unwrap_or(u64::MAX);++ let staging = path.with_extension("jsonl.tmp");+ std::fs::write(&staging, rewritten)+ .map_err(|error| format!("write the compacted {LOG_FILE}: {error}"))?;+ std::fs::rename(&staging, path)+ .map_err(|error| format!("replace {LOG_FILE} with its compacted copy: {error}"))?;+ tracing::debug!(+ kept = kept.len(),+ dropped = rows.len() - kept.len(),+ "[memory_sources:history] {LOG_FILE} compacted"+ );+ Ok(size)+}++/// The runs recorded under `workspace_dir`, newest first, at most `limit`.+///+/// A missing file is an empty log. A line that does not parse is skipped with+/// a warning: the file is append-only across crashes, so a torn last line must+/// not hide every row before it.+///+/// # Errors+///+/// Only when the file exists and cannot be read. An unreadable log is not+/// reported as "no runs", the one answer a caller cannot tell from the truth.+pub(crate) fn read_runs(workspace_dir: &Path, limit: usize) -> Result<Vec<SyncAuditEntry>, String> {+ let path = log_path(workspace_dir);+ let content = {+ let _guard = LOG_STATE.lock().unwrap_or_else(PoisonError::into_inner);+ match std::fs::read_to_string(&path) {+ Ok(content) => content,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),+ Err(error) => return Err(format!("read {LOG_FILE}: {error}")),+ }+ };++ let mut malformed = 0usize;+ let mut rows: Vec<SyncAuditEntry> = content+ .lines()+ .filter(|line| !line.trim().is_empty())+ .filter_map(|line| match serde_json::from_str(line) {+ Ok(row) => Some(row),+ Err(_) => {+ malformed += 1;+ None+ }+ })+ .collect();+ if malformed > 0 {+ tracing::warn!(+ malformed,+ "[memory_sources:history] skipped malformed lines in {LOG_FILE}"+ );+ }+ rows.reverse();+ rows.truncate(limit);+ Ok(rows)+}++/// Two newest-first logs as one newest-first list of at most `cap` rows.+///+/// A stable sort, so rows stamped with the same instant keep the driver's rows+/// ahead of the host's, as passed.+pub(crate) fn merge_newest_first(+ mut driver: Vec<SyncAuditEntry>,+ host: Vec<SyncAuditEntry>,+ cap: usize,+) -> Vec<SyncAuditEntry> {+ driver.extend(host);+ driver.sort_by_key(|entry| std::cmp::Reverse(entry.timestamp));+ driver.truncate(cap);+ driver+}++#[cfg(test)]+#[path = "run_history_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/memory/sources/run_history_tests.rs b/crates/openhuman-core/src/memory/sources/run_history_tests.rsnew file mode 100644index 0000000000..6b1c6087b0--- /dev/null+++ b/crates/openhuman-core/src/memory/sources/run_history_tests.rs@@ -0,0 +1,214 @@+//! The host's sync-run log and the rows it holds (openhuman#6257).++use chrono::{DateTime, TimeZone, Utc};++use super::*;++fn at(seconds: i64) -> DateTime<Utc> {+ Utc.timestamp_opt(1_789_000_000 + seconds, 0)+ .single()+ .expect("a valid instant")+}++fn run(source_id: &str, items: u64) -> HostRun {+ HostRun {+ source_id: source_id.to_string(),+ source_kind: "folder".to_string(),+ scope: source_id.to_string(),+ items,+ duration_ms: 12,+ ..HostRun::default()+ }+}++fn ids(rows: &[SyncAuditEntry]) -> Vec<&str> {+ rows.iter().map(|row| row.source_id.as_str()).collect()+}++#[test]+fn a_missing_log_reads_as_no_runs() {+ let dir = tempfile::tempdir().expect("tempdir");+ let rows = read_runs(dir.path(), KEEP_ROWS).expect("a missing log is not an error");+ assert!(rows.is_empty());+}++#[test]+fn recorded_runs_read_back_newest_first_within_the_limit() {+ let dir = tempfile::tempdir().expect("tempdir");+ for (offset, id) in ["src_a", "src_b", "src_c"].into_iter().enumerate() {+ let seconds = i64::try_from(offset).expect("small offset");+ append_run(dir.path(), &run(id, 1).into_entry(at(seconds))).expect("append");+ }++ let rows = read_runs(dir.path(), KEEP_ROWS).expect("read");+ assert_eq!(ids(&rows), ["src_c", "src_b", "src_a"]);++ let newest = read_runs(dir.path(), 2).expect("read");+ assert_eq!(ids(&newest), ["src_c", "src_b"]);+}++#[test]+fn a_torn_line_is_skipped_rather_than_hiding_the_rest() {+ let dir = tempfile::tempdir().expect("tempdir");+ append_run(dir.path(), &run("src_a", 1).into_entry(at(1))).expect("append");++ let path = log_path(dir.path());+ let mut content = std::fs::read_to_string(&path).expect("read the raw log");+ content.push_str("{\"timestamp\":\"2026-09-\n");+ std::fs::write(&path, content).expect("write a torn line");++ append_run(dir.path(), &run("src_b", 2).into_entry(at(2))).expect("append after it");+ let rows = read_runs(dir.path(), KEEP_ROWS).expect("a torn line does not fail the read");+ assert_eq!(ids(&rows), ["src_b", "src_a"]);+}++#[test]+fn compaction_keeps_only_the_newest_rows() {+ let dir = tempfile::tempdir().expect("tempdir");+ let total = KEEP_ROWS + 25;+ for offset in 0..total {+ let seconds = i64::try_from(offset).expect("small offset");+ let entry = run(&format!("src_{offset}"), 1).into_entry(at(seconds));+ append_run_compacting_at(dir.path(), &entry, u64::MAX).expect("append");+ }+ let last = run("src_last", 1).into_entry(at(i64::try_from(total).expect("small total")));+ append_run_compacting_at(dir.path(), &last, 0).expect("the append that compacts");++ let raw = std::fs::read_to_string(log_path(dir.path())).expect("read the raw log");+ assert_eq!(+ raw.lines().filter(|line| !line.trim().is_empty()).count(),+ KEEP_ROWS,+ "compaction keeps exactly the newest KEEP_ROWS rows"+ );++ let rows = read_runs(dir.path(), KEEP_ROWS).expect("read");+ assert_eq!(rows[0].source_id, "src_last");+ // `total` rows plus `src_last`, KEEP_ROWS kept: the oldest survivor is+ // `src_{total + 1 - KEEP_ROWS}`.+ let oldest = format!("src_{}", total + 1 - KEEP_ROWS);+ assert_eq!(+ rows.last().map(|row| row.source_id.as_str()),+ Some(oldest.as_str())+ );+}++#[test]+fn a_log_that_stays_over_the_ceiling_is_not_rewritten_on_every_append() {+ let dir = tempfile::tempdir().expect("tempdir");+ let path = log_path(dir.path());+ let failed = |source_id: &str, seconds: i64| {+ let mut row = run(source_id, 0);+ row.error = Some("e".repeat(2_000));+ row.into_entry(at(seconds))+ };+ // A ceiling below one row: every append is over it, and so is every+ // compacted file.+ let ceiling = 64;+ append_run_compacting_at(dir.path(), &failed("src_a", 1), ceiling).expect("append a");++ // A torn line only a compaction removes: while it survives, nothing has+ // rewritten the file.+ let mut raw = std::fs::read_to_string(&path).expect("read the raw log");+ raw.push_str("{\"torn\n");+ std::fs::write(&path, raw).expect("write a torn line");++ let short = run("src_b", 1).into_entry(at(2));+ append_run_compacting_at(dir.path(), &short, ceiling).expect("append b");+ let raw = std::fs::read_to_string(&path).expect("read the raw log");+ assert!(+ raw.contains("{\"torn"),+ "an append short of doubling the last compacted size does not compact again"+ );++ append_run_compacting_at(dir.path(), &failed("src_c", 3), ceiling).expect("append c");+ let raw = std::fs::read_to_string(&path).expect("read the raw log");+ assert!(+ !raw.contains("{\"torn"),+ "past double the last compacted size it compacts again"+ );+ let rows = read_runs(dir.path(), KEEP_ROWS).expect("read");+ assert_eq!(ids(&rows), ["src_c", "src_b", "src_a"]);+}++#[test]+fn a_host_run_maps_onto_the_driver_row_shape() {+ let mut failed = run("src_a", u64::from(u32::MAX) + 5);+ failed.error = Some("boom".to_string());+ failed.actions_called = 3;+ failed.provider_cost_usd = 0.25;+ let row = failed.into_entry(at(0));+ assert!(!row.success);+ assert_eq!(row.error.as_deref(), Some("boom"));+ assert_eq!(+ row.items_fetched,+ u32::MAX,+ "an item count past u32 saturates"+ );+ assert_eq!(row.composio_actions_called, 3);+ assert!((row.composio_cost_usd - 0.25).abs() < 1e-9);+ assert!(+ row.estimated_cost_usd.abs() < 1e-9,+ "the host prices nothing"+ );+ assert_eq!(+ (row.batches, row.input_tokens, row.output_tokens),+ (0, 0, 0)+ );+ assert_eq!((row.tree_ingest_failures, row.tree_error), (0, None));+ assert_eq!(row.timestamp, at(0));++ let completed = run("src_b", 7).into_entry(at(1));+ assert!(completed.success);+ assert_eq!(completed.error, None);+ assert_eq!(completed.items_fetched, 7);+ assert_eq!(completed.duration_ms, 12);+}++#[test]+fn merging_orders_both_logs_newest_first_and_caps_the_result() {+ let driver = vec![+ run("driver_new", 0).into_entry(at(30)),+ run("driver_old", 0).into_entry(at(10)),+ ];+ let host = vec![+ run("host_mid", 0).into_entry(at(20)),+ run("host_oldest", 0).into_entry(at(0)),+ ];++ let merged = merge_newest_first(driver.clone(), host.clone(), 10);+ assert_eq!(+ ids(&merged),+ ["driver_new", "host_mid", "driver_old", "host_oldest"]+ );+ assert_eq!(+ ids(&merge_newest_first(driver, host, 2)),+ ["driver_new", "host_mid"]+ );+}++#[test]+fn a_recorded_run_lands_in_the_configured_workspace() {+ let dir = tempfile::tempdir().expect("tempdir");+ let config = Config {+ workspace_dir: dir.path().to_path_buf(),+ ..Config::default()+ };+ record_run(&config, run("src_cfg", 4).into_entry(at(0)));+ let rows = read_runs(dir.path(), KEEP_ROWS).expect("read");+ assert_eq!(ids(&rows), ["src_cfg"]);+}++/// A row that cannot be written is a gap in the history, never a failed sync:+/// `record_run` returns nothing to fail with and must not panic.+#[test]+fn a_run_that_cannot_be_recorded_does_not_take_the_caller_down() {+ let dir = tempfile::tempdir().expect("tempdir");+ // A file where the state directory should be makes every append fail.+ std::fs::write(dir.path().join(STATE_DIR), "not a directory").expect("occupy the state path");+ let config = Config {+ workspace_dir: dir.path().to_path_buf(),+ ..Config::default()+ };+ record_run(&config, run("src_blocked", 1).into_entry(at(0)));+ assert!(append_run(dir.path(), &run("src_blocked", 1).into_entry(at(0))).is_err());+}diff --git a/crates/openhuman-core/src/memory/sources/status.rs b/crates/openhuman-core/src/memory/sources/status.rsindex f48c296bc3..8334661a0e 100644--- a/crates/openhuman-core/src/memory/sources/status.rs+++ b/crates/openhuman-core/src/memory/sources/status.rs@@ -75,11 +75,17 @@ 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 — plus the two in-flight fields the-/// host adds from its own memory of the stage stream (openhuman#6019).+/// response JSON is unchanged by the move — plus the fields the host adds: the+/// source's registry label (openhuman#6257) and the two in-flight fields from+/// its own memory of the stage stream (openhuman#6019).#[derive(Clone, Debug, Serialize)]pub struct SourceStatus {pub source_id: String,+ /// The source's display label from the registry, so a screen that reads only+ /// this list — Brain › Sync's "Now syncing" card — can name the row without+ /// the full source list, whose read reconciles every connection+ /// (openhuman#6257).+ pub label: String,pub chunks_synced: u64,pub chunks_pending: u64,pub last_chunk_at_ms: Option<i64>,@@ -99,9 +105,10 @@ impl SourceStatus {////// The engine's loop pushed exactly this for a per-source query failure,/// and it is what a degraded read answers here too — see [`status_list`].- fn idle(source_id: String) -> Self {+ fn idle(source_id: String, label: String) -> Self {Self {source_id,+ label,chunks_synced: 0,chunks_pending: 0,last_chunk_at_ms: None,@@ -238,6 +245,7 @@ pub async fn status_list(config: &Config) -> Result<Vec<SourceStatus>, String> {let status = match rows.iter().find(|row| row.source_id == source.id) {Some(row) => SourceStatus {source_id: source.id,+ label: source.label,chunks_synced: row.chunks_synced,chunks_pending: row.chunks_pending,last_chunk_at_ms: row.last_chunk_at_ms,@@ -245,7 +253,7 @@ pub async fn status_list(config: &Config) -> Result<Vec<SourceStatus>, String> {sync_stage: None,sync_detail: None,},- None => SourceStatus::idle(source.id),+ None => SourceStatus::idle(source.id, source.label),};status.with_live_sync(live)})diff --git a/crates/openhuman-core/src/memory/sources/status_tests.rs b/crates/openhuman-core/src/memory/sources/status_tests.rsindex aa00f4ad8d..496b82fff1 100644--- a/crates/openhuman-core/src/memory/sources/status_tests.rs+++ b/crates/openhuman-core/src/memory/sources/status_tests.rs@@ -122,11 +122,12 @@ fn freshness_serialises_snake_case() {/// 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();+ let json = serde_json::to_value(SourceStatus::idle("src_a".into(), "Notes".into())).unwrap();assert_eq!(json,serde_json::json!({"source_id": "src_a",+ "label": "Notes","chunks_synced": 0,"chunks_pending": 0,"last_chunk_at_ms": null,@@ -142,7 +143,7 @@ fn source_status_serde_shape_is_unchanged() {#[test]fn the_run_in_flight_rides_on_the_status_row() {use crate::memory::sync_activity::LiveSync;- let live = SourceStatus::idle("src_a".into()).with_live_sync(Some(LiveSync {+ let live = SourceStatus::idle("src_a".into(), "Notes".into()).with_live_sync(Some(LiveSync {stage: "running".into(),detail: Some("pass 1".into()),updated_at_ms: 1,diff --git a/crates/openhuman-core/src/memory/sync_activity.rs b/crates/openhuman-core/src/memory/sync_activity.rsindex 31df5b7352..6ae9b48433 100644--- a/crates/openhuman-core/src/memory/sync_activity.rs+++ b/crates/openhuman-core/src/memory/sync_activity.rs@@ -51,10 +51,24 @@ const STALE_AFTER_MS: i64 = 30 * 60 * 1_000;static LIVE: OnceLock<Mutex<HashMap<String, LiveSync>>> = OnceLock::new();static HANDLE: OnceLock<SubscriptionHandle> = OnceLock::new();+/// When each source's run last finished, epoch milliseconds.+///+/// A run that has ended must not be reopened by a stage describing one of its+/// items. The sync-stage bridge re-emits the module's per-document events as+/// `stored`, `queued` and `ingesting`, and that stream can deliver after the+/// host has published the run's `completed` — which put a finished row back on+/// "Queued" for the whole [`STALE_AFTER_MS`] with nothing running+/// (openhuman#6257). A marker ages out with the same ceiling.+static FINISHED: OnceLock<Mutex<HashMap<String, i64>>> = OnceLock::new();+fn live() -> &'static Mutex<HashMap<String, LiveSync>> {LIVE.get_or_init(Default::default)}+fn finished() -> &'static Mutex<HashMap<String, i64>> {+ FINISHED.get_or_init(Default::default)+}+fn now_ms() -> i64 {chrono::Utc::now().timestamp_millis()}@@ -64,6 +78,12 @@ pub(crate) fn is_terminal(stage: &str) -> bool {matches!(stage, "completed" | "failed")}+/// The stages that describe one item inside a run rather than the run itself,+/// and so the ones a finished run ignores until a new run starts.+pub(crate) fn is_item_stage(stage: &str) -> bool {+ matches!(stage, "stored" | "queued" | "ingesting")+}+/// 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());@@ -79,28 +99,65 @@ fn prune_stale_at(map: &mut HashMap<String, LiveSync>, now_ms: i64) {map.retain(|_, entry| now_ms.saturating_sub(entry.updated_at_ms) <= STALE_AFTER_MS);}+/// Drop every finished marker older than the ceiling.+fn prune_finished_at(map: &mut HashMap<String, i64>, now_ms: i64) {+ map.retain(|_, finished_at_ms| now_ms.saturating_sub(*finished_at_ms) <= STALE_AFTER_MS);+}+/// Sweep stale entries now. The status list calls it on a batch with no/// sources, the one shape that would otherwise never touch the map.pub fn prune_stale() {+ let now = now_ms();let mut map = live().lock().unwrap_or_else(PoisonError::into_inner);- prune_stale_at(&mut map, now_ms());+ prune_stale_at(&mut map, now);+ let mut done = finished().lock().unwrap_or_else(PoisonError::into_inner);+ prune_finished_at(&mut done, now);}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);- prune_stale_at(&mut map, at_ms);+ let mut done = finished().lock().unwrap_or_else(PoisonError::into_inner);+ apply_stage(&mut map, &mut done, source_id, stage, detail, at_ms);+}++/// One stage applied to the in-flight map and the finished markers.+///+/// Pure over the two maps, so the rules are testable without the+/// process-global state every other test in this module shares.+fn apply_stage(+ in_flight: &mut HashMap<String, LiveSync>,+ finished_at: &mut HashMap<String, i64>,+ source_id: &str,+ stage: &str,+ detail: Option<&str>,+ at_ms: i64,+) {+ prune_stale_at(in_flight, at_ms);+ prune_finished_at(finished_at, at_ms);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,- },+ in_flight.remove(source_id);+ finished_at.insert(source_id.to_string(), at_ms);+ return;+ }+ if is_item_stage(stage) && finished_at.contains_key(source_id) {+ tracing::debug!(+ source_id = %source_id,+ stage = %stage,+ "[memory_sync:activity] item stage after the run finished; not reopening it");+ return;}+ // Anything else starts or continues a run, so an earlier run's marker no+ // longer applies.+ finished_at.remove(source_id);+ in_flight.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.diff --git a/crates/openhuman-core/src/memory/sync_activity_tests.rs b/crates/openhuman-core/src/memory/sync_activity_tests.rsindex 4e587ce3ca..cbc88fbc29 100644--- a/crates/openhuman-core/src/memory/sync_activity_tests.rs+++ b/crates/openhuman-core/src/memory/sync_activity_tests.rs@@ -103,3 +103,119 @@ fn the_latest_stage_wins() {assert_eq!(live.stage, "ingesting");assert_eq!(live.updated_at_ms, 20);}++fn empty_maps() -> (HashMap<String, LiveSync>, HashMap<String, i64>) {+ (HashMap::new(), HashMap::new())+}++/// A per-item stage that trails the run's terminal stage does not reopen it:+/// the bridge re-emits the module's per-document events, and they can arrive+/// after `completed` (openhuman#6257).+#[test]+fn a_late_item_stage_does_not_reopen_a_finished_run() {+ let (mut in_flight, mut finished_at) = empty_maps();+ apply_stage(&mut in_flight, &mut finished_at, "src", "running", None, 10);+ apply_stage(+ &mut in_flight,+ &mut finished_at,+ "src",+ "queued",+ Some("queued chunk extraction"),+ 20,+ );+ assert!(+ in_flight.contains_key("src"),+ "an item stage inside a run keeps the run live"+ );+ apply_stage(+ &mut in_flight,+ &mut finished_at,+ "src",+ "completed",+ Some("ingested 2 item(s)"),+ 30,+ );+ for (stage, at_ms) in [("stored", 40), ("queued", 41), ("ingesting", 42)] {+ apply_stage(&mut in_flight, &mut finished_at, "src", stage, None, at_ms);+ assert!(+ !in_flight.contains_key("src"),+ "`{stage}` after `completed` must not reopen the run"+ );+ }+}++/// A new run is a new run: its start clears the finished marker, and its own+/// item stages count again.+#[test]+fn a_new_run_after_a_finished_one_is_tracked_again() {+ for start in ["running", "requested", "fetching"] {+ let (mut in_flight, mut finished_at) = empty_maps();+ apply_stage(+ &mut in_flight,+ &mut finished_at,+ "src",+ "failed",+ Some("boom"),+ 10,+ );+ apply_stage(&mut in_flight, &mut finished_at, "src", start, None, 20);+ apply_stage(&mut in_flight, &mut finished_at, "src", "queued", None, 30);+ assert_eq!(+ in_flight.get("src").map(|live| live.stage.as_str()),+ Some("queued"),+ "after `{start}`"+ );+ assert!(!finished_at.contains_key("src"), "after `{start}`");+ }+}++/// The marker ages out with the same ceiling as a live entry, so a source+/// whose next run never announced its start is not ignored for the life of+/// the process.+#[test]+fn the_finished_marker_ages_out_with_the_ceiling() {+ let (mut in_flight, mut finished_at) = empty_maps();+ apply_stage(+ &mut in_flight,+ &mut finished_at,+ "src",+ "completed",+ None,+ 0,+ );+ apply_stage(+ &mut in_flight,+ &mut finished_at,+ "src",+ "queued",+ None,+ STALE_AFTER_MS + 1,+ );+ assert!(in_flight.contains_key("src"));+}++/// Through the bus subscriber, against the process-wide maps.+#[tokio::test]+async fn the_tracker_ignores_a_queued_stage_that_trails_completed() {+ let tracker = SyncActivityTracker;+ for (stage, detail) in [+ ("running", None),+ ("completed", Some("ingested 1 item(s)")),+ ("queued", Some("queued chunk extraction")),+ ] {+ tracker+ .handle(&stage_event(Some("src-trailing"), stage, detail))+ .await;+ }+ assert_eq!(live_sync("src-trailing"), None);+}++#[test]+fn the_explicit_sweep_drops_old_finished_markers_too() {+ finished()+ .lock()+ .unwrap()+ .insert("src-old-marker".to_string(), 0);+ prune_stale();+ assert!(!finished().lock().unwrap().contains_key("src-old-marker"));+}diff --git a/crates/openhuman-core/src/platform/about_app/catalog_conversation_intelligence.rs b/crates/openhuman-core/src/platform/about_app/catalog_conversation_intelligence.rsindex 5ce8cfea09..bdc7fb843e 100644--- a/crates/openhuman-core/src/platform/about_app/catalog_conversation_intelligence.rs+++ b/crates/openhuman-core/src/platform/about_app/catalog_conversation_intelligence.rs@@ -397,7 +397,9 @@ Capability {(max_items, sync_depth_days, max_prs/issues/commits, since_days). \An \"All In\" action enables every source and removes the caps to build the richest \memory graph, then triggers a full sync. Already-connected sources are migrated to \- the new defaults once.",+ the new defaults once. Brain > Sync lists every sync run with its item count and \+ outcome (Sync button, All In, first syncs, and background runs that found something \+ new), which sources are syncing right now, and how many memory jobs are queued.",how_to: "Intelligence > Memory Sources — toggle a source, open its gear for per-source \limits, or use \"All In\". Programmatic: openhuman.memory_sources_update and \openhuman.memory_sources_apply_all_in (RPC).",diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.mdindex 41d0c661c8..a3a5f12acc 100644--- a/docs/TEST-COVERAGE-MATRIX.md+++ b/docs/TEST-COVERAGE-MATRIX.md@@ -332,6 +332,7 @@ End-to-end coverage of the agent harness via the web-chat RPC surface against an| 8.2.4 | Raw-archive sync reconcile | RU+RI | `crates/openhuman-core/src/memory/sources/reconcile_tests.rs`, `crates/openhuman-core/src/memory/sources/sync_tests.rs`, `vendor/tinymemory/crates/tinymemory-core/src/sync/workspace/periodic_tests.rs` (vendored `tinymemory`), `tests/json_rpc_e2e.rs` (`json_rpc_memory_sources_reconcile_reports_pending_raw_files`), `tests/memory_sources_e2e.rs` | ✅ | Coverage gate + incremental rebuild + workspace periodic scheduler + `memory_sources_reconcile` RPC || 8.2.5 | Coding-session persona ingestion | RU+RI+VU+WD | `vendor/tinymemory/crates/tinymemory-core/src/engine/persona_tests.rs` (vendored `tinymemory`), `crates/openhuman-core/src/memory/sources/rpc_tests.rs`, `tests/json_rpc_e2e.rs`, `app/src/components/intelligence/__tests__/CodingSessionsCard.test.tsx`, `app/src/services/memorySourcesService.test.ts`, `app/test/e2e/specs/coding-session-memory.spec.ts`, `app/test/playwright/specs/coding-session-memory.spec.ts` | ✅ | Discovers Codex and Claude Code histories, excludes machine-authored turns, exposes status/ingest RPCs, and surfaces incremental ingestion on Brain > Sources || 8.2.6 | Folder-source path picker | RU+VU | `crates/openhuman-app/src/directory_picker.rs`, `app/src/utils/tauriCommands/directoryPicker.test.ts`, `app/src/components/intelligence/FolderField.test.tsx` | ✅ | Browse resolves an absolute path through the OS-native chooser and refuses to store a non-resolvable value (bare directory name) when none is available (#5831) |+| 8.2.7 | Sync History and live sync activity | RU+RI+VU | `crates/openhuman-core/src/memory/sources/run_history_tests.rs`, `crates/openhuman-core/src/memory/sources/rpc/driver_run_tests.rs`, `crates/openhuman-core/src/memory/sources/rpc_monthly_summary_tests_tests.rs`, `crates/openhuman-core/src/integrations/composio/ops/connector_runs_tests.rs`, `crates/openhuman-core/src/integrations/composio/ops/source_rows_tests.rs`, `crates/openhuman-core/src/memory/sync_activity_tests.rs`, `tests/memory_sources_e2e.rs` (`sources_sync_dispatches_to_the_module_rather_than_refusing_the_capability`), `app/src/components/intelligence/SyncAuditPanel.test.tsx`, `app/src/components/intelligence/SyncActivityCard.test.tsx`, `app/src/components/intelligence/__tests__/memorySyncActivityStore.test.ts`, `app/src/components/intelligence/MemorySourceRow.test.tsx`, `app/src/components/intelligence/MemoryTreeStatusPanel.test.tsx` | ✅ | Every host-driven run (Sync button, Apply all, Composio) leaves one history row merged with the driver's audit log; manual driver runs end in `completed` or `failed`; a late per-document stage cannot reopen a finished row; Brain > Sync shows what is syncing and the job queue, and re-reads the history when a run ends (#6257) |### 8.3 Memory Retrieval Benchmarksdiff --git a/tests/memory_sources_e2e.rs b/tests/memory_sources_e2e.rsindex 9b15387700..724edec49a 100644--- a/tests/memory_sources_e2e.rs+++ b/tests/memory_sources_e2e.rs@@ -1171,6 +1171,88 @@ async fn sources_sync_dispatches_to_the_module_rather_than_refusing_the_capabiliclass of failure as #5801, one layer up. Got: {message}");+ // openhuman#6257: whatever the run's outcome, it leaves a Sync History row.+ // A sync that reached the driver and recorded nothing is how Brain › Sync ›+ // Sync History stayed empty after every manual sync.+ //+ // The host's run log is read directly, not only through the history RPC.+ // The module can fault inside the sync itself (the call above then answers+ // `ModuleUnavailable`), and a faulted driver cannot serve its own audit log+ // either, so through the RPC alone the row would be unobservable in exactly+ // the run that failed. `write_config` seeds the pre-login `users/local`+ // directory, whose workspace this core resolves.+ let run_log = openhuman_home+ .join("users")+ .join("local")+ .join("workspace")+ .join("state")+ .join("memory_sync_runs.jsonl");+ let run_log_text = std::fs::read_to_string(&run_log).unwrap_or_else(|e| {+ panic!(+ "a manual sync must write the host run log at {}: {e}. Sync answered: {sync}",+ run_log.display()+ )+ });+ let rows: Vec<Value> = run_log_text+ .lines()+ .filter_map(|line| serde_json::from_str::<Value>(line).ok())+ .filter(|row| row.get("source_id").and_then(Value::as_str) == Some(source_id.as_str()))+ .collect();+ // Exactly one: a run recorded twice would read as two syncs in the history.+ let [row] = rows.as_slice() else {+ panic!(+ "one manual sync must leave exactly one run row for its source, success or \+ failure; found {}. Sync answered: {sync}. Log: {run_log_text}",+ rows.len()+ );+ };+ assert_eq!(+ row.get("success").and_then(Value::as_bool),+ Some(sync.get("error").is_none()),+ "the row must carry the run's outcome. Sync answered: {sync}. Row: {row}"+ );++ // And through the RPC the panel reads, whenever the driver can serve its+ // half. The host's half must always read: only the driver may refuse.+ let history = rpc(+ &rpc_base,+ 904,+ "openhuman.memory_sources_sync_audit_log",+ json!({}),+ )+ .await;+ match history.get("error") {+ None => {+ let history = ok(&history, "sync history after a manual sync");+ let entries = history+ .get("entries")+ .and_then(Value::as_array)+ .expect("entries array in the sync history");+ let named = entries+ .iter()+ .filter(|row| {+ row.get("source_id").and_then(Value::as_str) == Some(source_id.as_str())+ })+ .count();+ assert_eq!(+ named, 1,+ "the history must include the manual sync's row, once. History: {entries:?}"+ );+ }+ Some(history_error) => {+ let history_message = history_error+ .get("message")+ .and_then(Value::as_str)+ .unwrap_or_default();+ assert!(+ history_message.contains("sync audit log:")+ && !history_message.contains("sync run log:"),+ "only the driver's audit log may be unreadable here; the host's run log \+ must always read. Got: {history_error}"+ );+ }+ }+let _ = rpc(&rpc_base,903,