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): address review on the sync history change
Shanu1acf8a7e74e8
diff --git a/app/src/components/intelligence/SyncActivityCard.test.tsx b/app/src/components/intelligence/SyncActivityCard.test.tsxindex 3478a96c36..b07fd51c32 100644--- a/app/src/components/intelligence/SyncActivityCard.test.tsx+++ b/app/src/components/intelligence/SyncActivityCard.test.tsx@@ -187,4 +187,51 @@ describe('<SyncActivityCard />', () => {expect(getMemorySyncActivity().syncingIds.has('gmail:ca_1:msg-42')).toBe(true);expect(screen.getByTestId('sync-activity-card')).not.toHaveTextContent('msg-42');});++ it('ignores a status read that answers after a newer one', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ let answerFirst: (rows: SourceStatus[]) => void = () => {};+ mockStatusList+ .mockImplementationOnce(+ () =>+ new Promise<SourceStatus[]>(resolve => {+ answerFirst = resolve;+ })+ )+ .mockResolvedValue([status('src-h', { label: 'Newer', sync_stage: null })]);+ render(<SyncActivityCard />);+ await act(async () => {+ vi.advanceTimersByTime(STATUS_POLL_MS);+ });+ await waitFor(() => expect(mockStatusList).toHaveBeenCalledTimes(2));+ act(() => {+ applyStageEvent({ stage: 'running', source_id: 'src-h', detail: null });+ });+ const row = await screen.findByTestId('sync-activity-row-src-h');+ await waitFor(() => expect(row).toHaveTextContent('Newer'));++ // The first read answers last, with an older label.+ await act(async () => {+ answerFirst([status('src-h', { label: 'Older', sync_stage: null })]);+ });+ expect(screen.getByTestId('sync-activity-row-src-h')).toHaveTextContent('Newer');+ });++ it('hides the detail of a stage it does not know', async () => {+ mockStatusList.mockResolvedValue([status('src-u', { label: 'Feed' })]);+ render(<SyncActivityCard />);+ await waitFor(() => expect(mockStatusList).toHaveBeenCalled());+ act(() => {+ noteSyncRequested('src-u');+ applyStageEvent({+ stage: 'embedding',+ source_id: 'src-u',+ detail: 'batch for mem_src:src-u:7',+ });+ });++ const row = await screen.findByTestId('sync-activity-row-src-u');+ expect(row).toHaveTextContent('memorySources.stage.unknown');+ expect(row).not.toHaveTextContent('mem_src:');+ });});diff --git a/app/src/components/intelligence/SyncActivityCard.tsx b/app/src/components/intelligence/SyncActivityCard.tsxindex 852b22d18b..934997d05c 100644--- a/app/src/components/intelligence/SyncActivityCard.tsx+++ b/app/src/components/intelligence/SyncActivityCard.tsx@@ -36,10 +36,24 @@ export function SyncActivityCard() {useEffect(() => {let cancelled = false;+ // Polls can answer out of order: a read slower than the poll interval must+ // not put an older account back over a newer one.+ let requested = 0;+ let applied = 0;const refresh = async () => {+ const seq = ++requested;try {const statuses = await memorySourcesStatusList();if (cancelled) return;+ if (seq < applied) {+ console.debug(+ '[sync-activity] dropped an older status read seq=%d applied=%d',+ seq,+ applied+ );+ return;+ }+ applied = seq;setLabels(sourceLabelsById(statuses));setSourceIds(new Set(statuses.map(status => status.source_id)));reconcileWithStatuses(statuses);diff --git a/app/src/components/intelligence/SyncAuditPanel.test.tsx b/app/src/components/intelligence/SyncAuditPanel.test.tsxindex abf7dbe010..e84b2d82a5 100644--- a/app/src/components/intelligence/SyncAuditPanel.test.tsx+++ b/app/src/components/intelligence/SyncAuditPanel.test.tsx@@ -324,6 +324,15 @@ describe('<SyncAuditPanel />', () => {expect(mockAuditLog).toHaveBeenCalledTimes(1);});+ it('shows the history without waiting for the status list', async () => {+ mockAuditLog.mockResolvedValue([entry({ source_id: 'src-slow', scope: 'github:org/slow' })]);+ mockStatusList.mockImplementation(() => new Promise<SourceStatus[]>(() => {}));+ render(<SyncAuditPanel />);++ expect(await screen.findByText('GitHub · org/slow')).toBeInTheDocument();+ expect(screen.getByTestId('sync-history-refresh')).not.toBeDisabled();+ });+it('re-reads the history when Refresh is pressed', async () => {mockAuditLog.mockResolvedValue([]);render(<SyncAuditPanel />);diff --git a/app/src/components/intelligence/SyncAuditPanel.tsx b/app/src/components/intelligence/SyncAuditPanel.tsxindex 61e896e194..2784801b08 100644--- a/app/src/components/intelligence/SyncAuditPanel.tsx+++ b/app/src/components/intelligence/SyncAuditPanel.tsx@@ -97,28 +97,17 @@ export function SyncAuditPanel() {useEffect(() => {let cancelled = false;+ // The history and the labels are read side by side, not together: a slow+ // status list must not hold back the rows or the Refresh button.void (async () => {console.debug('[sync-audit] load: entry token=%d', reloadToken);try {- const [data, 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;- }),- ]);+ const data = await memorySyncAuditLog();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);@@ -129,6 +118,21 @@ export function SyncAuditPanel() {}}})();+ // Labels and source ids only. A failed or superseded read keeps what the+ // last read that answered said, and a row with no label names itself by+ // its scope.+ void (async () => {+ try {+ const statuses = await memorySourcesStatusList();+ if (cancelled) return;+ setLabels(sourceLabelsById(statuses));+ setSourceIds(new Set(statuses.map(status => status.source_id)));+ } catch (err) {+ if (!cancelled) {+ console.warn('[sync-audit] status list failed; keeping the last labels', err);+ }+ }+ })();return () => {cancelled = true;};diff --git a/app/src/components/intelligence/__tests__/memorySyncActivityStore.test.ts b/app/src/components/intelligence/__tests__/memorySyncActivityStore.test.tsindex 042fa2de1b..b34f882ca5 100644--- a/app/src/components/intelligence/__tests__/memorySyncActivityStore.test.ts+++ b/app/src/components/intelligence/__tests__/memorySyncActivityStore.test.ts@@ -171,8 +171,8 @@ describe('memorySyncActivityStore', () => {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.+ // A run whose start the app never saw shows up as per-item stages only, so+ // once the window the core applies too has passed, those stages count.it('counts per-item stages again once the finished run is past the window', () => {const now = vi.spyOn(Date, 'now');const finishedAt = 5_000_000;diff --git a/app/src/components/intelligence/memorySourcesSyncTypes.ts b/app/src/components/intelligence/memorySourcesSyncTypes.tsindex c2a98b7ce7..eb59c9e7eb 100644--- a/app/src/components/intelligence/memorySourcesSyncTypes.ts+++ b/app/src/components/intelligence/memorySourcesSyncTypes.ts@@ -84,12 +84,17 @@ export function stageLabelKey(stage: string): string {}/**- * 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.+ * The stages whose detail a person can read: the connector's `running` detail+ * ("pass 2 done, 400 item(s) so far"), a reader's `fetching` ratio, and the+ * request itself. Listed rather than inferred, so a per-item stage's detail+ * (`mem_src:…`, `queue_depth=…`) and a stage this app does not know yet stay+ * hidden.*/+const DETAIL_STAGES = new Set(['requested', 'running', 'fetching']);++/** Whether a stage's detail is worth showing (see `DETAIL_STAGES`). */export function showsStageDetail(stage: string): boolean {- return !isItemStage(stage);+ return DETAIL_STAGES.has(stage);}/**diff --git a/app/src/components/intelligence/memorySyncActivityStore.ts b/app/src/components/intelligence/memorySyncActivityStore.tsindex 70391d89fb..476539f6af 100644--- a/app/src/components/intelligence/memorySyncActivityStore.ts+++ b/app/src/components/intelligence/memorySyncActivityStore.ts@@ -147,9 +147,11 @@ let state: MemorySyncActivity = EMPTY;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.+ * ceiling (`STALE_AFTER_MS` in `memory/sync_activity.rs`). A new run normally+ * announces itself first (the Sync button, or a `requested`, `fetching` or+ * `running` stage), which clears the mark at once. Past the window, a per-item+ * stage is taken as a later run whose start this app never saw, as the core's+ * status list takes it.*/export const LATE_ITEM_STAGE_WINDOW_MS = 30 * 60 * 1_000;diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.tsindex c4c8d65f9d..25c94ece7f 100644--- a/app/src/lib/i18n/es.ts+++ b/app/src/lib/i18n/es.ts@@ -997,7 +997,7 @@ const messages: TranslationMap = {'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',+ 'Tareas de memoria: {ready} en espera, {running} en curso, {failed} con error','memoryTree.status.toggleFailed': 'No se pudo activar la sincronización automática','memoryTree.status.justNow': 'justo ahora','memoryTree.status.secondsAgo': '{count}s hace',diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.tsindex 7dc9eb6fdd..975c6cf73e 100644--- a/app/src/lib/i18n/it.ts+++ b/app/src/lib/i18n/it.ts@@ -1000,7 +1000,7 @@ const messages: TranslationMap = {'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',+ 'Attività di memoria: {ready} in attesa, {running} in corso, {failed} con errore','memoryTree.status.toggleFailed':'Impossibile attivare/disattivare la sincronizzazione automatica','memoryTree.status.justNow': 'proprio adesso',diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.tsindex 2fb9ba7a22..0a9e67459a 100644--- a/app/src/lib/i18n/pl.ts+++ b/app/src/lib/i18n/pl.ts@@ -990,7 +990,7 @@ const messages: TranslationMap = {'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',+ 'Zadania pamięci (oczekujące: {ready}, w toku: {running}, nieudane: {failed})','memoryTree.status.toggleFailed': 'Nie udało się przełączyć automatycznej synchronizacji','memoryTree.status.justNow': 'przed chwilą','memoryTree.status.secondsAgo': '{count} s temu',diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.tsindex 9b72918eb2..61b105836e 100644--- a/app/src/lib/i18n/ru.ts+++ b/app/src/lib/i18n/ru.ts@@ -984,7 +984,7 @@ const messages: TranslationMap = {'memoryTree.status.retryFailedCount': 'Задач в очереди на повторный запуск: {count}.','memoryTree.status.retryFailedError': 'Не удалось вернуть неудавшиеся задачи в очередь','memoryTree.status.jobQueue':- 'Задачи памяти: {ready} ожидают, {running} выполняются, {failed} с ошибкой',+ 'Задачи памяти (в очереди: {ready}, выполняются: {running}, с ошибкой: {failed})','memoryTree.status.toggleFailed': 'Не удалось включить автосинхронизацию.','memoryTree.status.justNow': 'прямо сейчас','memoryTree.status.secondsAgo': '{count} сек. назад',diff --git a/crates/openhuman-core/src/integrations/composio/ops/pass_budget.rs b/crates/openhuman-core/src/integrations/composio/ops/pass_budget.rsindex cefdf36ad3..3e2cbd19ac 100644--- a/crates/openhuman-core/src/integrations/composio/ops/pass_budget.rs+++ b/crates/openhuman-core/src/integrations/composio/ops/pass_budget.rs@@ -30,6 +30,18 @@ pub(crate) const SINGLE_CALL_ITEM_BUDGET: u32 = 500;/// trickle cannot pin the caller.const SINGLE_CALL_MAX_PASSES: usize = 50;+/// A drain a pass error ended, with what the passes before it wrote.+///+/// Those writes are committed by the driver whatever the later pass did, so the+/// run's history row reports them rather than zero (Codex review on #6264).+#[derive(Debug, PartialEq)]+pub(crate) struct DrainFailure {+ /// The failing pass's error.+ pub error: String,+ /// Records written by the passes that finished before it.+ pub written: u32,+}+/// Run passes until the connector reports the end, `budget` records have been/// read, a pass reads nothing, or [`SINGLE_CALL_MAX_PASSES`] is reached; each/// pass is capped at `SYNC_PASS_MAX_ITEMS` through [`next_pass_budget`].@@ -37,12 +49,13 @@ const SINGLE_CALL_MAX_PASSES: usize = 50;/// The outcome sums `records_read` and `written` across passes, is/// `already_ingested` only when every pass was a no-op, and carries the last/// pass's `more_pending` and `message` — the same "last pass's word wins" rule-/// the Sources-row loop applies. A pass error ends the run with that error;-/// what earlier passes wrote is already committed by the driver.+/// the Sources-row loop applies. A pass error ends the run with a+/// [`DrainFailure`] carrying that error and what the earlier passes wrote,+/// which the driver has already committed.pub(crate) async fn run_passes_within_budget<F, Fut>(budget: u32,mut run_pass: F,-) -> Result<SyncPassOutcome, String>+) -> Result<SyncPassOutcome, DrainFailure>whereF: FnMut(usize) -> Fut,Fut: Future<Output = Result<SyncPassOutcome, String>>,@@ -57,7 +70,15 @@ whereif passes >= SINGLE_CALL_MAX_PASSES {break;}- let pass = run_pass(pass_budget).await?;+ let pass = match run_pass(pass_budget).await {+ Ok(pass) => pass,+ Err(error) => {+ return Err(DrainFailure {+ error,+ written: total.written,+ });+ }+ };passes += 1;read = read.saturating_add(u64::try_from(pass.records_read).unwrap_or(u64::MAX));total.records_read = total.records_read.saturating_add(pass.records_read);@@ -88,8 +109,8 @@ where/// 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.+/// one rule. A drain a later pass fails still records what its earlier passes+/// wrote: the driver has committed those.pub(crate) async fn run_sync_within_budget(config: &Config,toolkit: &str,@@ -101,6 +122,10 @@ pub(crate) async fn run_sync_within_budget(run_sync_pass(config, toolkit, connection_id, reason, pass_budget)}).await;+ let (written, error) = match &result {+ Ok(pass) => (pass.written, None),+ Err(failure) => (failure.written, Some(failure.error.as_str())),+ };super::connector_runs::record(config,&super::connector_runs::ConnectorRun {@@ -109,11 +134,11 @@ pub(crate) async fn run_sync_within_budget(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),+ written: u64::from(written),+ error,},);- result+ result.map_err(|failure| failure.error)}#[cfg(test)]diff --git a/crates/openhuman-core/src/integrations/composio/ops/pass_budget_tests.rs b/crates/openhuman-core/src/integrations/composio/ops/pass_budget_tests.rsindex f46c3adab2..0f87615100 100644--- a/crates/openhuman-core/src/integrations/composio/ops/pass_budget_tests.rs+++ b/crates/openhuman-core/src/integrations/composio/ops/pass_budget_tests.rs@@ -8,7 +8,7 @@ use std::cell::RefCell;use std::collections::VecDeque;use super::super::providers_ops::{SyncPassOutcome, SYNC_PASS_MAX_ITEMS};-use super::{run_passes_within_budget, SINGLE_CALL_ITEM_BUDGET};+use super::{run_passes_within_budget, DrainFailure, SINGLE_CALL_ITEM_BUDGET};fn pass(written: u32, more_pending: bool) -> SyncPassOutcome {SyncPassOutcome {@@ -25,7 +25,7 @@ fn pass(written: u32, more_pending: bool) -> SyncPassOutcome {async fn drive(budget: u32,script: Vec<Result<SyncPassOutcome, String>>,-) -> (Result<SyncPassOutcome, String>, Vec<usize>) {+) -> (Result<SyncPassOutcome, DrainFailure>, Vec<usize>) {let script = RefCell::new(VecDeque::from(script));let asked = RefCell::new(Vec::new());let out = run_passes_within_budget(budget, |pass_budget| {@@ -88,16 +88,41 @@ async fn a_small_account_is_still_one_pass() {}#[tokio::test]-async fn a_pass_error_ends_the_run_with_that_error() {+async fn a_pass_error_ends_the_run_with_that_error_and_the_earlier_writes() {let (out, asked) = drive(SINGLE_CALL_ITEM_BUDGET,vec![Ok(pass(200, true)), Err("module went away".to_string())],).await;- assert_eq!(out.unwrap_err(), "module went away");+ // The first pass's 200 records are committed whatever the second did, so+ // the run's history row reports them (openhuman#6257).+ assert_eq!(+ out.unwrap_err(),+ DrainFailure {+ error: "module went away".to_string(),+ written: 200,+ }+ );assert_eq!(asked.len(), 2, "no pass is attempted after the failure");}+#[tokio::test]+async fn a_first_pass_error_reports_nothing_written() {+ let (out, asked) = drive(+ SINGLE_CALL_ITEM_BUDGET,+ vec![Err("connector refused the call".to_string())],+ )+ .await;+ assert_eq!(+ out.unwrap_err(),+ DrainFailure {+ error: "connector refused the call".to_string(),+ written: 0,+ }+ );+ assert_eq!(asked.len(), 1);+}+#[tokio::test]async fn already_ingested_holds_only_when_every_pass_was_a_no_op() {let noop = SyncPassOutcome {