Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

address review (codex): coalesce on explicit background provenance, dedupe by op id

[._.]/ Adam Eivy6613e26e65e4
diff --git a/client/src/hooks/useAIStatusNotifications.js b/client/src/hooks/useAIStatusNotifications.js
index 5e9bee9c7a..49f3aa1f32 100644
--- a/client/src/hooks/useAIStatusNotifications.js
+++ b/client/src/hooks/useAIStatusNotifications.js
@@ -22,22 +22,25 @@ import socket from '../services/socket';
* errors, or calls that take longer than a couple seconds.
* - Non-silent ops render from the start so the user sees feedback for
* explicit actions (Generate Summary, etc.) even on fast calls.
- * - Silent-op *errors* are coalesced per-provider within a short rolling
- * window (see COALESCE below). An unattended background job that fans out
- * one AI call per record (e.g. a multi-goal check-in via `Promise.all` in
- * server/services/goalCheckIn.js) can produce N systematic failures at
- * once — each with a unique op id, so Toast's content dedupe can't collapse
- * them. Instead of N stacked red toasts the user never watched start, they
- * get ONE toast that counts the failures. User-triggered ops (those that
- * passed `op` → not silent) still toast immediately, individually, with the
- * provider's real reason — that behavior is load-bearing for #2733's
- * single-voice Go-deeper design and is intentionally left untouched.
+ * - *Background*-op errors are coalesced per-provider within a short rolling
+ * window (see COALESCE below). An unattended job that fans out one AI call
+ * per record (e.g. the multi-goal check-in via `Promise.all` in
+ * server/services/goalCheckIn.js, which passes `background: true`) can
+ * produce N systematic failures at once — each with a unique op id, so
+ * Toast's content dedupe can't collapse them. Instead of N stacked red
+ * toasts from a job the user never watched start, they get ONE toast that
+ * counts the failures. The `background` flag is explicit provenance from the
+ * unattended caller — NOT inferred from `silent`, because user-triggered
+ * op-less actions (generateGoalPhases/decomposeGoal/checkInGoal) are silent
+ * too and must keep toasting individually. Every user-triggered op — silent
+ * or not — reports its failure immediately, individually, with the real
+ * reason; that is load-bearing for #2733's single-voice Go-deeper design.
*/
export function useAIStatusNotifications() {
// Per-op state: { silent, opened, slowTimer? }
const opsRef = useRef(new Map());
- // Per-provider silent-error coalescing: providerKey -> { toastId, count, firstReason, timer }
- const silentErrorsRef = useRef(new Map());
+ // Per-provider background-error coalescing: providerKey -> { toastId, count, firstReason, seen, timer }
+ const bgErrorsRef = useRef(new Map());
// Monotonic window counter so each fresh coalescing window gets a unique toast
// id (see coalesceSilentError) — a reused id would let a prior window's pending
// auto-dismiss timer remove a successor window's toast.
@@ -45,11 +48,11 @@ export function useAIStatusNotifications() {
useEffect(() => {
const SLOW_CALL_MS = 2500;
- // Rolling window over which concurrent silent-op failures from the same
+ // Rolling window over which concurrent background-op failures from the same
// provider collapse into a single counted toast. A burst from `Promise.all`
// arrives near-simultaneously, well inside this window; genuinely
// spaced-out failures (> window apart) each show their real reason again.
- const SILENT_ERROR_WINDOW_MS = 4000;
+ const BG_ERROR_WINDOW_MS = 4000;
const phaseIcon = {
start: '🤖',
@@ -59,41 +62,53 @@ export function useAIStatusNotifications() {
error: '✕'
};
- // Collapse a burst of silent-op failures from one provider into a single
+ // Collapse a burst of background-op failures from one provider into a single
// toast keyed by provider. The first failure in the window shows the real
- // reason; subsequent failures update the SAME toast with a running count,
+ // reason; subsequent DISTINCT ops update the SAME toast with a running count,
// keeping that first reason visible so the toast stays actionable.
- const coalesceSilentError = (event) => {
+ const coalesceBackgroundError = (event) => {
const key = event.providerId || event.providerName || '__unknown_provider__';
const providerLabel = event.providerName || event.providerId || 'AI provider';
const reason = event.message || `${providerLabel} background AI call failed`;
- const entry = silentErrorsRef.current.get(key);
// The hook owns the coalesced toast's whole lifetime: render it with
// `duration: Infinity` so Toast schedules NO auto-dismiss timer of its own
// (it never cancels those, and each update's stale timer would otherwise
// dismiss the toast mid-window), and dismiss it ourselves once the rolling
- // window lapses — SILENT_ERROR_WINDOW_MS after the LAST failure, since the
+ // window lapses — BG_ERROR_WINDOW_MS after the LAST failure, since the
// timer is reset on every update below.
const armWindowExpiry = (k, toastId) =>
setTimeout(() => {
toast.dismiss(toastId);
- silentErrorsRef.current.delete(k);
- }, SILENT_ERROR_WINDOW_MS);
+ bgErrorsRef.current.delete(k);
+ }, BG_ERROR_WINDOW_MS);
+
+ const entry = bgErrorsRef.current.get(key);
if (!entry) {
// Fresh window. Give the toast a window-unique id so that even if a
// dismissal ever races a brand-new window (e.g. rapid lapse/re-open),
// it can only ever target its own window's toast, never a successor's.
windowSeqRef.current += 1;
- const toastId = `ai-silent-error::${key}::${windowSeqRef.current}`;
- const fresh = { toastId, count: 1, firstReason: reason, timer: undefined };
+ const toastId = `ai-bg-error::${key}::${windowSeqRef.current}`;
+ const fresh = { toastId, count: 1, firstReason: reason, seen: new Set([event.id]), timer: undefined };
fresh.timer = armWindowExpiry(key, toastId);
- silentErrorsRef.current.set(key, fresh);
+ bgErrorsRef.current.set(key, fresh);
toast.error(reason, { id: toastId, duration: Infinity, icon: '✕' });
return;
}
+ // Count DISTINCT operations, not error events: one failed call can emit
+ // more than one error event with the same op id (an LM Studio model-load
+ // failure emits an error phase, then callProviderAISimple emits the final
+ // error too), which would otherwise report a single failure as two. A
+ // repeat id just keeps the window alive.
+ if (entry.seen.has(event.id)) {
+ if (entry.timer) clearTimeout(entry.timer);
+ entry.timer = armWindowExpiry(key, entry.toastId);
+ return;
+ }
+ entry.seen.add(event.id);
entry.count += 1;
if (entry.timer) clearTimeout(entry.timer);
entry.timer = armWindowExpiry(key, entry.toastId);
@@ -159,17 +174,18 @@ export function useAIStatusNotifications() {
if (event.phase === 'error') {
if (state.slowTimer) clearTimeout(state.slowTimer);
opsRef.current.delete(event.id);
- // Silent-op failures (unattended background jobs) coalesce per-provider
- // so a systematic failure yields one counted toast, not N — and this
- // must hold for SLOW failures too (an unreachable endpoint / timeout,
- // where every parallel op has already opened its own spinner). Dismiss
- // that orphan-prone Infinity-duration spinner first, then coalesce, so
- // the goal-check-in flood collapses whether the provider fails fast or
- // slow. A user-triggered op always toasts immediately, individually,
- // with the real reason — load-bearing and never aggregated away.
- if (state.silent || event.silent) {
+ // Only UNATTENDED background jobs coalesce per-provider, so a systematic
+ // failure yields one counted toast, not N — and this holds for SLOW
+ // failures too (an unreachable endpoint / timeout, where every parallel
+ // op has already opened its own spinner): dismiss that orphan-prone
+ // Infinity-duration spinner first, then coalesce, so the goal-check-in
+ // flood collapses whether the provider fails fast or slow. Everything
+ // the user triggered — INCLUDING op-less "silent" actions — toasts
+ // immediately, individually, with the real reason (updating its own
+ // spinner in place if it had one). Load-bearing and never aggregated.
+ if (event.background) {
if (state.opened) toast.dismiss(event.id);
- coalesceSilentError(event);
+ coalesceBackgroundError(event);
} else {
toast.error(event.message || 'AI call failed', { id: event.id, duration: 6000, icon: '✕' });
}
@@ -183,13 +199,13 @@ export function useAIStatusNotifications() {
if (s.slowTimer) clearTimeout(s.slowTimer);
}
opsRef.current.clear();
- for (const e of silentErrorsRef.current.values()) {
+ for (const e of bgErrorsRef.current.values()) {
if (e.timer) clearTimeout(e.timer);
// These toasts render with duration: Infinity, so nothing else will
// dismiss them once we drop their window timer — clear them explicitly.
toast.dismiss(e.toastId);
}
- silentErrorsRef.current.clear();
+ bgErrorsRef.current.clear();
};
}, []);
}
diff --git a/client/src/hooks/useAIStatusNotifications.test.jsx b/client/src/hooks/useAIStatusNotifications.test.jsx
index 1eab0d3fd3..bd82f4854a 100644
--- a/client/src/hooks/useAIStatusNotifications.test.jsx
+++ b/client/src/hooks/useAIStatusNotifications.test.jsx
@@ -42,26 +42,26 @@ afterEach(() => {
vi.useRealTimers();
});
-describe('useAIStatusNotifications — silent-op error coalescing', () => {
- it('collapses a burst of silent-op failures from one provider into ONE counted toast', () => {
+describe('useAIStatusNotifications — background-op error coalescing', () => {
+ it('collapses a burst of background-op failures from one provider into ONE counted toast', () => {
renderHook(() => useAIStatusNotifications());
- // Simulate an unattended multi-goal check-in: 5 concurrent silent calls to
- // the same failing provider, each with a unique op id (as startAIOp mints).
+ // Simulate an unattended multi-goal check-in: 5 concurrent background calls
+ // to the same failing provider, each with a unique op id (as startAIOp mints).
act(() => {
for (let i = 0; i < 5; i++) {
const id = `op-${i}`;
- emit({ id, phase: 'start', silent: true, providerId: 'prov-1', providerName: 'Example Provider' });
- emit({ id, phase: 'error', silent: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'HTTP 401 Unauthorized' });
+ emit({ id, phase: 'start', silent: true, background: true, providerId: 'prov-1', providerName: 'Example Provider' });
+ emit({ id, phase: 'error', silent: true, background: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'HTTP 401 Unauthorized' });
}
});
- // Every silent error routes to the SAME provider-keyed toast id — one toast,
- // not five. The first shows the real reason; later ones update to a count.
+ // Every background error routes to the SAME provider-keyed toast id — one
+ // toast, not five. The first shows the real reason; later ones add a count.
const errs = errorCalls();
const uniqueIds = new Set(errs.map(c => c.opts?.id));
expect(uniqueIds.size).toBe(1);
- expect([...uniqueIds][0]).toMatch(/^ai-silent-error::prov-1::/);
+ expect([...uniqueIds][0]).toMatch(/^ai-bg-error::prov-1::/);
// The counted toast keeps the first real reason visible — since these
// events can all land before a paint, the counted toast is often the only
@@ -73,7 +73,7 @@ describe('useAIStatusNotifications — silent-op error coalescing', () => {
expect(errs[0].message).toBe('HTTP 401 Unauthorized');
});
- it('keeps user-triggered (non-silent) failures immediate, individual, and with the real reason', () => {
+ it('keeps user-triggered (non-background) failures immediate, individual, and with the real reason', () => {
renderHook(() => useAIStatusNotifications());
act(() => {
@@ -95,13 +95,50 @@ describe('useAIStatusNotifications — silent-op error coalescing', () => {
expect(errs[1].message).toBe('timeout');
});
- it('coalesces silent failures per-provider, not across providers', () => {
+ it('does NOT coalesce silent-but-user-triggered ops (op-less goal actions) — they still toast individually', () => {
renderHook(() => useAIStatusNotifications());
+ // generateGoalPhases / decomposeGoal / checkInGoal call the provider WITHOUT
+ // `op`, so they are silent (no start toast) but they are NOT background work —
+ // the user clicked a button. Two such failures from the same provider within
+ // the coalescing window must remain two individual toasts labelled with their
+ // own reason, never merged into "failed on 2 background AI calls".
act(() => {
- emit({ id: 'x1', phase: 'error', silent: true, providerId: 'prov-a', providerName: 'Provider A', message: 'a fail' });
- emit({ id: 'x2', phase: 'error', silent: true, providerId: 'prov-b', providerName: 'Provider B', message: 'b fail' });
- emit({ id: 'x3', phase: 'error', silent: true, providerId: 'prov-a', providerName: 'Provider A', message: 'a fail again' });
+ emit({ id: 'goal-decompose', phase: 'error', silent: true, background: false, providerId: 'prov-1', providerName: 'Example Provider', message: 'decompose failed: 401' });
+ emit({ id: 'goal-checkin', phase: 'error', silent: true, background: false, providerId: 'prov-1', providerName: 'Example Provider', message: 'check-in failed: 401' });
+ });
+
+ const errs = errorCalls();
+ expect(errs).toHaveLength(2);
+ expect(errs.map(c => c.opts?.id).sort()).toEqual(['goal-checkin', 'goal-decompose']);
+ expect(errs.map(c => c.message).sort()).toEqual(['check-in failed: 401', 'decompose failed: 401']);
+ // None of them is the coalescing toast.
+ expect(errs.some(c => /^ai-bg-error::/.test(c.opts?.id))).toBe(false);
+ });
+
+ it('counts DISTINCT operations, not error events — one op emitting two error events increments once', () => {
+ renderHook(() => useAIStatusNotifications());
+
+ // An LM Studio model-load failure emits an error phase, then the outer
+ // callProviderAISimple emits the final error too — both with the SAME op id.
+ act(() => {
+ emit({ id: 'op-A', phase: 'error', silent: true, background: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'Failed to load model' });
+ emit({ id: 'op-A', phase: 'error', silent: true, background: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'completion failed' });
+ emit({ id: 'op-B', phase: 'error', silent: true, background: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'Failed to load model' });
+ });
+
+ const errs = errorCalls();
+ // Two distinct ops (A, B) → count 2, NOT 3 (op-A's second error is deduped).
+ expect(errs[errs.length - 1].message).toBe('Example Provider failed on 2 background AI calls — Failed to load model');
+ });
+
+ it('coalesces background failures per-provider, not across providers', () => {
+ renderHook(() => useAIStatusNotifications());
+
+ act(() => {
+ emit({ id: 'x1', phase: 'error', silent: true, background: true, providerId: 'prov-a', providerName: 'Provider A', message: 'a fail' });
+ emit({ id: 'x2', phase: 'error', silent: true, background: true, providerId: 'prov-b', providerName: 'Provider B', message: 'b fail' });
+ emit({ id: 'x3', phase: 'error', silent: true, background: true, providerId: 'prov-a', providerName: 'Provider A', message: 'a fail again' });
});
const errs = errorCalls();
@@ -116,21 +153,21 @@ describe('useAIStatusNotifications — silent-op error coalescing', () => {
expect(provA[provA.length - 1].message).toBe('Provider A failed on 2 background AI calls — a fail');
});
- it('coalesces SLOW silent failures too — dismisses each orphan-prone spinner, collapses to one counted toast', () => {
+ it('coalesces SLOW background failures too — dismisses each orphan-prone spinner, collapses to one counted toast', () => {
renderHook(() => useAIStatusNotifications());
- // Two silent ops both cross the 2.5s slow threshold, so each opens its own
+ // Two background ops both cross the 2.5s slow threshold, so each opens its own
// Infinity-duration loading spinner (a timeout / unreachable-endpoint burst).
act(() => {
- emit({ id: 'slow-a', phase: 'start', silent: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'Calling…' });
- emit({ id: 'slow-b', phase: 'start', silent: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'Calling…' });
+ emit({ id: 'slow-a', phase: 'start', silent: true, background: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'Calling…' });
+ emit({ id: 'slow-b', phase: 'start', silent: true, background: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'Calling…' });
});
act(() => { vi.advanceTimersByTime(3000); });
expect(toastCalls.filter(c => c.type === 'loading').map(c => c.opts?.id).sort()).toEqual(['slow-a', 'slow-b']);
act(() => {
- emit({ id: 'slow-a', phase: 'error', silent: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'endpoint timeout' });
- emit({ id: 'slow-b', phase: 'error', silent: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'endpoint timeout' });
+ emit({ id: 'slow-a', phase: 'error', silent: true, background: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'endpoint timeout' });
+ emit({ id: 'slow-b', phase: 'error', silent: true, background: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'endpoint timeout' });
});
// Both orphan-prone spinners are dismissed by id (else they spin forever)...
@@ -147,11 +184,11 @@ describe('useAIStatusNotifications — silent-op error coalescing', () => {
renderHook(() => useAIStatusNotifications());
act(() => {
- emit({ id: 'w1', phase: 'error', silent: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'first' });
+ emit({ id: 'w1', phase: 'error', silent: true, background: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'first' });
});
act(() => { vi.advanceTimersByTime(5000); }); // window lapses
act(() => {
- emit({ id: 'w2', phase: 'error', silent: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'second' });
+ emit({ id: 'w2', phase: 'error', silent: true, background: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'second' });
});
const errs = errorCalls();
@@ -159,19 +196,19 @@ describe('useAIStatusNotifications — silent-op error coalescing', () => {
// prior add()'s auto-dismiss timer, so a reused id would let window 1's
// pending dismissal remove window 2's toast).
expect(errs[0].opts?.id).not.toBe(errs[errs.length - 1].opts?.id);
- expect(errs[0].opts?.id).toMatch(/^ai-silent-error::prov-1::/);
+ expect(errs[0].opts?.id).toMatch(/^ai-bg-error::prov-1::/);
});
it('keeps the coalesced toast alive across staggered same-window failures until the window lapses after the LAST one', () => {
renderHook(() => useAIStatusNotifications());
act(() => {
- emit({ id: 's1', phase: 'error', silent: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'first' });
+ emit({ id: 's1', phase: 'error', silent: true, background: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'first' });
});
// Second failure 3.5s later — still inside the 4s rolling window.
act(() => { vi.advanceTimersByTime(3500); });
act(() => {
- emit({ id: 's2', phase: 'error', silent: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'second' });
+ emit({ id: 's2', phase: 'error', silent: true, background: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'second' });
});
const coalescedId = errorCalls()[0].opts?.id;
@@ -191,12 +228,12 @@ describe('useAIStatusNotifications — silent-op error coalescing', () => {
renderHook(() => useAIStatusNotifications());
act(() => {
- emit({ id: 'g1', phase: 'error', silent: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'first reason' });
+ emit({ id: 'g1', phase: 'error', silent: true, background: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'first reason' });
});
// Advance past the rolling window so the entry is cleaned up.
act(() => { vi.advanceTimersByTime(5000); });
act(() => {
- emit({ id: 'g2', phase: 'error', silent: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'second reason' });
+ emit({ id: 'g2', phase: 'error', silent: true, background: true, providerId: 'prov-1', providerName: 'Example Provider', message: 'second reason' });
});
const errs = errorCalls();
diff --git a/server/lib/aiProvider.js b/server/lib/aiProvider.js
index 2ef529df62..e9c3f04ce6 100644
--- a/server/lib/aiProvider.js
+++ b/server/lib/aiProvider.js
@@ -213,7 +213,7 @@ async function postChatCompletion(provider, model, prompt, { temperature, max_to
* so the beam's thickness can track tokens/sec.
*/
export async function callProviderAISimple(provider, model, prompt, options = {}) {
- const { temperature = 0.3, max_tokens = 1000, op, opLabel, appId, workspacePath } = options;
+ const { temperature = 0.3, max_tokens = 1000, op, opLabel, appId, workspacePath, background } = options;
if (provider.type !== 'api') {
return { error: 'This operation requires an API-based provider' };
}
@@ -232,7 +232,13 @@ export async function callProviderAISimple(provider, model, prompt, options = {}
model,
appId,
workspacePath,
- silent: !op
+ silent: !op,
+ // `background` marks an UNATTENDED fan-out job (e.g. the scheduled multi-goal
+ // check-in) so the client coalesces its per-provider error toasts. It is the
+ // caller's explicit provenance signal — NOT inferred from `!op`, because
+ // user-triggered actions (generateGoalPhases/decomposeGoal/checkInGoal) are
+ // also op-less/silent and must keep toasting individually.
+ background: !!background
});
const doneLabel = effectiveLabel.replace(/…$/, '');
diff --git a/server/services/aiStatusEvents.js b/server/services/aiStatusEvents.js
index fdca2b0411..ddb342ff72 100644
--- a/server/services/aiStatusEvents.js
+++ b/server/services/aiStatusEvents.js
@@ -40,6 +40,12 @@ const ICONS = {
* @param {string} [init.model]
* @param {string} [init.appId] — managed-app id this call works on behalf of
* @param {string} [init.workspacePath] — CoS-agent workspace this call works on behalf of
+ * @param {boolean} [init.background] — this call is part of an UNATTENDED job (a
+ * scheduled/autopilot task the user isn't watching), NOT merely display-silent.
+ * Distinct from `silent` (which only suppresses the start toast — user-triggered
+ * op-less actions are silent too). The client coalesces per-provider error toasts
+ * for background ops so a systematically-failing provider in a fan-out job (e.g.
+ * the multi-goal check-in) yields one notification instead of N stacked toasts.
*
* `appId`/`workspacePath` let the CyberCity AI Core aim its activity beam at the
* originating building; ops with neither get the generic radial beam. Token counts
@@ -56,7 +62,8 @@ export function startAIOp(init) {
model: init.model,
appId: init.appId,
workspacePath: init.workspacePath,
- silent: !!init.silent
+ silent: !!init.silent,
+ background: !!init.background
};
emit('start', base, init.label || `Calling ${init.providerName || init.providerId || 'AI'}…`);
diff --git a/server/services/goalCheckIn.js b/server/services/goalCheckIn.js
index 6fa7e38017..550d5c6ce8 100644
--- a/server/services/goalCheckIn.js
+++ b/server/services/goalCheckIn.js
@@ -68,9 +68,12 @@ export async function runGoalCheckIn() {
return { goal, expectedProgress, actualProgress, status, attendanceRate, prompt };
});
- // Parallelize LLM calls
+ // Parallelize LLM calls. `background: true` marks these as an unattended
+ // fan-out (this runs from a scheduled job — see autonomousJobs/scriptHandlers.js)
+ // so the client coalesces per-provider error toasts: a systematically-failing
+ // provider yields one notification, not one red toast per goal.
const llmResults = await Promise.all(
- checkInData.map(d => callProviderAISimple(provider, provider.defaultModel, d.prompt))
+ checkInData.map(d => callProviderAISimple(provider, provider.defaultModel, d.prompt, { background: true }))
);
const results = [];