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

fix: take the quota retry time from the readiness probe, which is the only thing that sets it

[._.]/ Adam Eivya61c851f6c84
diff --git a/client/src/components/cos/PersistentMindRuntimePanel.jsx b/client/src/components/cos/PersistentMindRuntimePanel.jsx
index c28654c7ce..b5047366d5 100644
--- a/client/src/components/cos/PersistentMindRuntimePanel.jsx
+++ b/client/src/components/cos/PersistentMindRuntimePanel.jsx
@@ -1,5 +1,5 @@
import { AlertTriangle, Brain, Cpu, Gauge } from 'lucide-react';
-import { describeMindTurnProgress } from '../../lib/mindTurnProgress.js';
+import { describeMindTurnProgress, mindTurnHeadline } from '../../lib/mindTurnProgress.js';
import { formatBytes, timeUntil } from '../../utils/formatters.js';
const number = (value) => Number.isFinite(value) ? value.toLocaleString() : '—';
@@ -23,22 +23,25 @@ const residencyLabel = (runtime) => {
: `Running now · ${state.toLowerCase()}`;
};
+// Statuses whose headline is a plain lookup, kept beside RESIDENCY_STATES so
+// neither grows back into a ternary chain.
+const STATUS_HEADLINES = {
+ waiting: 'Waiting for the next wake',
+ paused: 'Mind paused',
+ idle: 'Mind idle',
+ disabled: 'Mind disabled',
+};
+
export function PersistentMindThoughtStatus({ state, model, progress }) {
// A caller with no /mind/runtime snapshot (the CoS Config tab) still gets the
// state-only reading: the quota/retry phase resolves from the public state
// alone, while elapsed and heartbeat freshness stay absent rather than guessed.
const turn = progress || describeMindTurnProgress({ state });
const scheduled = state?.started && state?.nextWakeAt && ['idle', 'waiting'].includes(state.status);
- const headline = turn.phase === 'blocked'
- ? `${turn.reason || 'Blocked'}${turn.retryAt ? ` · retry ${timeUntil(turn.retryAt)}` : ''}`
- : turn.phase === 'stalled' ? 'Stalled, checking…'
- : turn.phase === 'thinking' ? `Thinking${model ? ` with ${model}` : ''}`
- : scheduled ? `Waiting · next wake ${timeUntil(state.nextWakeAt)}`
- : state?.status === 'waiting' ? 'Waiting for the next wake'
- : state?.status === 'paused' ? 'Mind paused'
- : state?.status === 'idle' ? 'Mind idle'
- : state?.status === 'disabled' ? 'Mind disabled'
- : 'Mind status unknown';
+ const headline = mindTurnHeadline(turn, timeUntil)
+ || (turn.phase === 'thinking' ? `Thinking${model ? ` with ${model}` : ''}`
+ : scheduled ? `Waiting · next wake ${timeUntil(state.nextWakeAt)}`
+ : STATUS_HEADLINES[state?.status] || 'Mind status unknown');
// The stage answers "is it actually processing?", the durations answer "for
// how long?" — a bare headline could not distinguish either from a hang.
const label = [headline, turn.stage, turn.detail].filter(Boolean).join(' · ');
diff --git a/client/src/components/cos/tabs/MindTab.jsx b/client/src/components/cos/tabs/MindTab.jsx
index 608668947c..ece81c6d54 100644
--- a/client/src/components/cos/tabs/MindTab.jsx
+++ b/client/src/components/cos/tabs/MindTab.jsx
@@ -27,7 +27,7 @@ import PersistentMindThinkingPresets from '../PersistentMindThinkingPresets';
import PersistentMindVisibilityPanel from '../PersistentMindVisibilityPanel';
import PersistentMindTools from '../../../pages/PersistentMindTools';
import { findMindThinkingPreset } from '../../../lib/mindThinkingPresets.js';
-import { describeMindTurnProgress } from '../../../lib/mindTurnProgress.js';
+import { describeMindTurnProgress, mindTurnHeadline, mindTurnRuntimeSnapshot } from '../../../lib/mindTurnProgress.js';
import { readFileAsBase64, UPLOAD_IMAGE_ACCEPT, validateImageFile } from '../../../utils/fileUpload';
const PAGE_LIMIT = 200;
@@ -118,14 +118,15 @@ const MindTurnIndicator = ({ progress }) => {
const detail = [progress.stage, progress.detail].filter(Boolean).join(' · ');
if (progress.phase === 'thinking') {
+ const typingLabel = detail ? `Chief of Staff is typing — ${detail}` : 'Chief of Staff is typing';
return (
<span
data-testid="mind-typing-indicator"
+ data-phase={progress.phase}
role="status"
- aria-label={detail ? `Chief of Staff is typing — ${detail}` : 'Chief of Staff is typing'}
+ aria-label={typingLabel}
className="inline-flex min-w-0 items-center gap-1.5 text-port-text-muted"
>
- <span className="sr-only">{detail ? `Chief of Staff is typing — ${detail}` : 'Chief of Staff is typing'}</span>
<span className="inline-flex items-center gap-0.5 text-port-accent">
{[0, 1, 2].map((index) => (
<span
@@ -141,13 +142,13 @@ const MindTurnIndicator = ({ progress }) => {
);
}
- const label = progress.phase === 'stalled'
- ? ['Stalled, checking…', detail].filter(Boolean).join(' · ')
- : [progress.reason || 'Blocked', progress.retryAt ? `retry ${timeUntil(progress.retryAt)}` : null].filter(Boolean).join(' · ');
+ const label = [mindTurnHeadline(progress, timeUntil), progress.phase === 'stalled' ? detail : null]
+ .filter(Boolean).join(' · ');
return (
<span
- data-testid={progress.phase === 'stalled' ? 'mind-stalled-indicator' : 'mind-blocked-indicator'}
+ data-testid="mind-turn-indicator"
+ data-phase={progress.phase}
role="status"
className="inline-flex min-w-0 items-center gap-1.5 rounded-full border border-port-warning/60 bg-port-warning/10 px-2 py-0.5 text-[11px] font-normal text-port-warning"
>
@@ -760,9 +761,7 @@ export default function MindTab() {
<PersistentMindThoughtStatus
state={state}
progress={turnProgress}
- model={state?.activeTurnId && state.activeTurnId === runtime?.inference?.turnId
- ? runtime.inference.model
- : mind?.profile?.model}
+ model={mindTurnRuntimeSnapshot(state, runtime)?.model || mind?.profile?.model}
/>
{!state?.started && <ActionButton label={profileReady ? 'Start' : 'Configure'} icon={profileReady ? CirclePlay : Settings2} pending={profileReady && lifecyclePending === 'start'} disabled={loading || setupSaving} onClick={() => (profileReady ? runLifecycle('start') : openPanel('settings'))} />}
<ActionButton label="Wake now" icon={CirclePlay} pending={lifecyclePending === 'wake'} disabled={loading || setupSaving || !profileReady || Boolean(lifecyclePending) || Boolean(state?.activeTurn)} onClick={() => runLifecycle('wake')} />
diff --git a/client/src/components/cos/tabs/MindTab.test.jsx b/client/src/components/cos/tabs/MindTab.test.jsx
index 5fe6241aaa..31081652f2 100644
--- a/client/src/components/cos/tabs/MindTab.test.jsx
+++ b/client/src/components/cos/tabs/MindTab.test.jsx
@@ -623,8 +623,9 @@ describe('MindTab', () => {
expect(within(screen.getByTestId('mind-chat')).queryByText('Thinking…')).not.toBeInTheDocument();
});
-const thinkingRuntime = (inference = {}) => ({
+ const thinkingRuntime = (inference = {}, usageLimitRetryAt = null) => ({
observedAt: '2026-08-27T12:02:40.000Z',
+ usageLimitRetryAt,
inference: {
active: true,
turnId: 'mind-turn-1',
@@ -673,25 +674,13 @@ const thinkingRuntime = (inference = {}) => ({
api.getPersistentMindRuntime.mockResolvedValue(thinkingRuntime({ heartbeatAgeMs: 190_000, heartbeatStale: true }));
renderTab();
- const stalled = await screen.findByTestId('mind-stalled-indicator');
+ const stalled = await screen.findByTestId('mind-turn-indicator');
expect(stalled).toHaveTextContent(/Stalled, checking…/);
expect(stalled).toHaveTextContent(/no heartbeat for 3m 10s/);
expect(screen.queryByTestId('mind-typing-indicator')).not.toBeInTheDocument();
expect(await screen.findByTestId('mind-thought-status')).toHaveAttribute('data-phase', 'stalled');
});
- it('shows a cold local model as loading instead of leaving it an indefinite wait', async () => {
- api.getPersistentMind.mockResolvedValue(response({
- state: { enabled: true, started: true, status: 'thinking', pauseReason: null, activeTurnId: 'mind-turn-1' },
- }));
- api.getPersistentMindRuntime.mockResolvedValue(thinkingRuntime({
- residency: { status: 'not-loaded', backend: 'ollama', loaded: false, memoryBytes: null },
- }));
- renderTab();
-
- expect(await screen.findByTestId('mind-turn-progress-detail')).toHaveTextContent('loading model');
- });
-
it('renders a quota block with its retry time inline instead of an indefinite thinking state', async () => {
api.getPersistentMind.mockResolvedValue(response({
state: {
@@ -701,14 +690,18 @@ const thinkingRuntime = (inference = {}) => ({
usageLimited: true,
pauseReason: 'Provider usage limit reached',
activeTurnId: null,
- // +12m30s: `timeUntil` floors, so a flat 12m would race the test clock
- // down to "11m" and flake.
- nextEligibleWakeAt: new Date(Date.now() + 12 * 60_000 + 30_000).toISOString(),
+ nextEligibleWakeAt: null,
},
}));
+ api.getPersistentMindRuntime.mockResolvedValue(thinkingRuntime({
+ active: false,
+ turnId: null,
+ // +12m30s: `timeUntil` floors, so a flat 12m would race the test clock
+ // down to "11m" and flake.
+ }, new Date(Date.now() + 12 * 60_000 + 30_000).toISOString()));
renderTab();
- const blocked = await screen.findByTestId('mind-blocked-indicator');
+ const blocked = await screen.findByTestId('mind-turn-indicator');
expect(blocked).toHaveTextContent(/Provider usage limit reached/);
expect(blocked).toHaveTextContent(/retry in 12m/);
expect(screen.queryByTestId('mind-typing-indicator')).not.toBeInTheDocument();
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 3b27dfb527..346a61fb2d 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -206,7 +206,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `managedAppSources.js` | Readers for the managed-app repository-source payload (`GET /api/apps/:id/repository-sources`). `primaryRepositorySource` picks the application checkout out of the source list; `repositoryForkDiverged` / `repositoryForkPushable` / `repositoryForkNeedsSync` answer whether a managed update may ask the server to fast-forward the origin fork (a diverged fork never can, nor can a fork PortOS lacks push access to — a correctness rule, not a label), with `describeForkUnsyncable` explaining why when it may not; `describeRepositorySourcesBehind` renders one clause per checkout an update can actually pull forward, over the shared `countText` pluralizer both surfaces phrase counts with. Shared by the app Git tab's Repository sources panel and the Eidoverse page's out-of-date advisory. |
| `metronome.js` | Sample-accurate Web Audio metronome — the shared timing grid for the song system and first consumer of the song `tempo` field. `createMetronome({ bpm, beatsPerBar, countInBars, onBeat, onCountInComplete })` lookahead-schedules accented click tones on the shared `AudioContext` clock (same pattern as `songPlayback.js`), emits `{ beat, bar, accent, countIn, whenAudioTime }` per beat (the beat-clock callback color-match/sing-to-score subscribe to), and tears down all timers on `stop()`. Plus `clampBpm` (20–320), `secondsPerBeat`, `timeSignatureFromScore`, `beatDescriptor`, and `normalizeBeatsPerBar` — the ONE reading of a time-signature numerator (garbled/zero/negative → 4), shared by the scheduler and the visual `<BeatPulse>` so the dots can't disagree with the clicks. |
| `mindThinkingPresets.js` | Presentation helpers for the Persistent Mind's temporary thinking sessions (#6285). `classifyMindRouteBilling(provider)` answers the question the composer must settle without contacting anything: does borrowing this route run on THIS machine (`local`), stand behind a credential/subscription (`account`), or can PortOS not tell (`unknown`)? Unknown is treated as billable — guessing "free" is the one direction that costs money. Plus `formatMindRoute` (the one "provider / model · effort" phrasing), `sameMindRoute` (client mirror of the server's route-only equality, so a label rename does not read as a changed route), `findMindThinkingPreset` / `mintMindPresetId` (a server-legal id minted from a label), and the receipt readers `formatMindCallUsage` / `formatMindCallOutcome` / `formatMindElapsed` / `mindTurnOutcome` / `mindTurnElapsedMs` / `temporaryMindTurns` — all of which keep "the provider reported nothing" rendering as unknown rather than as a free, instant, successful call. Pure; no fetches, so previewing a preset can never start an inference. |
-| `mindTurnProgress.js` | Live progress derivation for a Persistent Mind turn (#7409). `describeMindTurnProgress({ state, runtime, events })` folds the public state and the `/mind/runtime` snapshot into one `{ phase: 'thinking'|'stalled'|'blocked'|'idle', stage, elapsedMs, heartbeatAgeMs, residency, retryAt, reason, detail }` reading, so the Mind page can tell healthy-but-slow local inference from a wedged turn from a quota autopause instead of showing one indefinite three-dot indicator for all three. Turn freshness is taken from the runtime snapshot ONLY when its `turnId` matches the claimed turn (a stale snapshot would date a fresh turn as stalled), and a missing measurement stays `null` rather than collapsing into zero. `mindTurnStage` reads the newest trajectory event for the turn by `sequence`; `mindTurnRuntimeSnapshot` exposes the turn-matched inference block. Status enums and durations only — no provider reasoning crosses the hidden chain-of-thought boundary. |
+| `mindTurnProgress.js` | Live progress derivation for a Persistent Mind turn (#7409). `describeMindTurnProgress({ state, runtime, events })` folds the public state and the `/mind/runtime` snapshot into one `{ phase: 'thinking'|'stalled'|'blocked'|'idle', busy, stage, retryAt, reason, detail }` reading, so the Mind page can tell healthy-but-slow local inference from a wedged turn from a quota autopause instead of showing one indefinite three-dot indicator for all three. Freshness comes from the runtime snapshot ONLY when its `turnId` matches the claimed turn (a stale snapshot would date a fresh turn as stalled), and an unreported measurement renders nothing rather than zero. `retryAt` reads `runtime.usageLimitRetryAt` before `state.nextEligibleWakeAt`, because a usage-limit autopause clears the backoff gate and its schedule lives only in the readiness probe. `mindTurnHeadline(progress, formatRetry)` is the one phrasing of a stalled/blocked turn, shared by the header pill and the chat indicator; `mindTurnStage` reads the newest trajectory event for the turn by `sequence`; `mindTurnRuntimeSnapshot` is the one turn-match rule. Status enums and durations only — no provider reasoning crosses the hidden chain-of-thought boundary. |
| `midiChords.js` | Chord detection for the MIDI visualization UI (#2477). `detectChordWindows(notes, { minWindowSec })` sweeps the normalized note list for maximal spans where ≥2 distinct pitch classes sound simultaneously → `[{ startSec, endSec, label, midis }]` (adjacent same-label windows merged); `nameChord(pcs, bassPc)` maps a pitch-class set to a compact symbol (maj/min/dim/aug triads, maj7/7/m7/m7b5/dim7, sus2/sus4/add9, slash-chord inversions) and falls back to sorted pitch-class names (`C E G#`) rather than guessing wrong; `chordNoteNames(midis)` for tooltips. Pure — no canvas/React. |
| `midiNotes.js` | Minimal Standard MIDI File parser + normalizer for the MIDI visualization UI (#2477) — in-tree, zero deps. `parseMidiFile(arrayBuffer)` parses SMF format 0/1 (running status, note-on vel-0-as-off, tempo map incl. mid-file changes, SMPTE division, track names) into the piano-roll view-model `{ durationSec, minMidi, maxMidi, notes:[{id,midi,startSec,durationSec,velocity,track,name}], tracks, tempos }`. Throws on non-MIDI bytes. Consumed by `useMidiNotes` → `<MidiPianoRoll>`. NOT the lead-sheet parser (`scoreNotation.js`). |
| `midiPlayback.js` | Synth preview of a transcribed `.mid` (#2490) — `createMidiPlayer(data, { onEnded })` plays the `parseMidiFile` view-model as velocity-scaled oscillator tones through a per-play master bus on the shared `AudioContext`, with the same lookahead-scheduler idiom + tone envelope (`scheduleTone`) as `scorePlayback.js`. Transport: `play`/`pause`/`stop`/`seek(sec)` (seek re-anchors a running transport and sounds the tails of notes sustaining across the seek point) and `position()` for the `<MidiPianoRoll>` moving playhead. Pure (no React) — `useMidiPlayer` wraps it. |
diff --git a/client/src/lib/mindTurnProgress.js b/client/src/lib/mindTurnProgress.js
index e7050a4ab9..fc3743edaa 100644
--- a/client/src/lib/mindTurnProgress.js
+++ b/client/src/lib/mindTurnProgress.js
@@ -6,14 +6,14 @@
* the watchdog has not noticed yet", and "the provider hit a quota and the mind
* auto-paused" all looked identical. Everything needed to tell them apart is
* already reported — `GET /mind/runtime` carries turn freshness measured
- * against the SERVER clock, and the public state carries the pause/retry
- * fields — so this module only has to read them.
+ * against the SERVER clock plus the usage-limit probe schedule, and the public
+ * state carries the pause fields — so this module only has to read them.
*
* Two rules the callers depend on:
* - Turn freshness is taken from the runtime snapshot ONLY when its `turnId`
* matches the claimed turn. A snapshot from the previous turn would
* otherwise date a fresh turn and read as stalled.
- * - A missing measurement stays `null` and renders nothing. "Not reported"
+ * - A missing measurement renders nothing rather than zero. "Not reported"
* and "zero elapsed" are different answers; collapsing them would show a
* just-started turn as having no heartbeat.
*
@@ -37,6 +37,9 @@ const STAGE_LABELS = {
'mind.memory.created': 'Saving a memory',
};
+// Only the statuses that answer "is the local runtime actually processing?".
+// `provider-managed` and `unconfigured` map to nothing on purpose: there is no
+// local residency to report, and inventing a clause would imply otherwise.
const RESIDENCY_LABELS = {
loaded: 'model loaded',
'not-loaded': 'loading model',
@@ -70,6 +73,20 @@ export function mindTurnStage(state, events) {
return best ? STAGE_LABELS[best.kind] : null;
}
+/**
+ * The one phrasing of a blocked/stalled turn, so the header pill and the chat
+ * indicator cannot drift apart on wording.
+ *
+ * @param {object} progress — a `describeMindTurnProgress` result
+ * @param {(iso: string) => string} formatRetry — renders `retryAt` as a relative span
+ */
+export function mindTurnHeadline(progress, formatRetry) {
+ if (progress.phase === 'stalled') return 'Stalled, checking…';
+ if (progress.phase !== 'blocked') return null;
+ const reason = progress.reason || 'Blocked';
+ return progress.retryAt ? `${reason} · retry ${formatRetry(progress.retryAt)}` : reason;
+}
+
/**
* Describe what the mind is doing right now.
*
@@ -78,8 +95,7 @@ export function mindTurnStage(state, events) {
* @param {object|null} args.runtime — `GET /mind/runtime` snapshot
* @param {Array|null} args.events — visible trajectory events
* @returns {{phase: 'thinking'|'stalled'|'blocked'|'idle', busy: boolean,
- * stage: string|null, elapsedMs: number|null, heartbeatAgeMs: number|null,
- * residency: string|null, retryAt: string|null, reason: string|null,
+ * stage: string|null, retryAt: string|null, reason: string|null,
* detail: string|null}}
*/
export function describeMindTurnProgress({ state, runtime, events } = {}) {
@@ -89,34 +105,34 @@ export function describeMindTurnProgress({ state, runtime, events } = {}) {
const thinking = state?.status === 'thinking' && Boolean(trimmed(state?.activeTurnId));
// A degraded/interrupted wake is as opaque as a quota pause: both stop making
// progress and both retry on their own, so both get the retry time inline.
- const blocked = state?.usageLimited === true
- || (!thinking && ['degraded', 'interrupted'].includes(state?.status));
+ const blocked = state?.usageLimited === true || ['degraded', 'interrupted'].includes(state?.status);
const stalled = thinking && inference?.heartbeatStale === true;
-
- const residency = thinking
- ? RESIDENCY_LABELS[inference?.residency?.status] || null
- : null;
const phase = blocked ? 'blocked' : stalled ? 'stalled' : thinking ? 'thinking' : 'idle';
+ const busy = phase === 'thinking' || phase === 'stalled';
const parts = [];
- if (phase === 'blocked') {
- if (trimmed(state?.nextEligibleWakeAt)) parts.push('retrying automatically');
- } else if (phase !== 'idle') {
+ if (busy) {
if (elapsedMs !== null) parts.push(formatDurationMs(elapsedMs));
if (heartbeatAgeMs !== null) {
- parts.push(stalled ? `no heartbeat for ${formatDurationMs(heartbeatAgeMs)}` : `heartbeat ${formatDurationMs(heartbeatAgeMs)} ago`);
+ parts.push(stalled
+ ? `no heartbeat for ${formatDurationMs(heartbeatAgeMs)}`
+ : `heartbeat ${formatDurationMs(heartbeatAgeMs)} ago`);
}
+ const residency = RESIDENCY_LABELS[inference?.residency?.status];
if (residency) parts.push(residency);
}
return {
phase,
- busy: phase === 'thinking' || phase === 'stalled',
- stage: phase === 'idle' || phase === 'blocked' ? null : mindTurnStage(state, events),
- elapsedMs,
- heartbeatAgeMs,
- residency,
- retryAt: phase === 'blocked' ? trimmed(state?.nextEligibleWakeAt) : null,
+ busy,
+ stage: busy ? mindTurnStage(state, events) : null,
+ // A usage-limit autopause clears `nextEligibleWakeAt` (no backoff gate, no
+ // failureCount climb), so its schedule lives only in the readiness probe
+ // the runtime endpoint reports. Read the probe first and fall back to the
+ // ordinary backoff gate, which is what a degraded wake uses instead.
+ retryAt: phase === 'blocked'
+ ? trimmed(runtime?.usageLimitRetryAt) || trimmed(state?.nextEligibleWakeAt)
+ : null,
reason: phase === 'blocked' ? trimmed(state?.pauseReason) : null,
detail: parts.length > 0 ? parts.join(' · ') : null,
};
diff --git a/client/src/lib/mindTurnProgress.test.js b/client/src/lib/mindTurnProgress.test.js
index 70b045073c..d0f2b6c1ce 100644
--- a/client/src/lib/mindTurnProgress.test.js
+++ b/client/src/lib/mindTurnProgress.test.js
@@ -35,37 +35,19 @@ describe('describeMindTurnProgress', () => {
expect(progress.phase).toBe('thinking');
expect(progress.busy).toBe(true);
- expect(progress.elapsedMs).toBe(160_000);
expect(progress.detail).toBe('2m 40s · heartbeat 5s ago · model loaded');
});
- it('renders a cold local model as loading rather than as a silent hang', () => {
- const progress = describeMindTurnProgress({
- state: thinkingState(),
- runtime: runtimeFor({ residency: { status: 'not-loaded', backend: 'ollama', loaded: false } }),
- });
-
- expect(progress.residency).toBe('loading model');
- expect(progress.detail).toContain('loading model');
- });
-
- it('names an unreachable local runtime instead of implying healthy inference', () => {
- const progress = describeMindTurnProgress({
+ it('names each local residency state so a cold load never reads as a hang', () => {
+ const detailFor = (status) => describeMindTurnProgress({
state: thinkingState(),
- runtime: runtimeFor({ residency: { status: 'unknown', backend: 'lmstudio', loaded: null } }),
- });
-
- expect(progress.residency).toBe('local runtime unreachable');
- });
-
- it('says nothing about residency for a provider-managed route', () => {
- const progress = describeMindTurnProgress({
- state: thinkingState(),
- runtime: runtimeFor({ residency: { status: 'provider-managed', backend: null, loaded: null } }),
- });
+ runtime: runtimeFor({ residency: { status, backend: 'ollama', loaded: status === 'loaded' } }),
+ }).detail;
- expect(progress.residency).toBeNull();
- expect(progress.detail).toBe('2m 40s · heartbeat 5s ago');
+ expect(detailFor('not-loaded')).toContain('loading model');
+ expect(detailFor('unknown')).toContain('local runtime unreachable');
+ // Nothing local to report — a clause here would imply otherwise.
+ expect(detailFor('provider-managed')).toBe('2m 40s · heartbeat 5s ago');
});
it('separates a stale heartbeat from ordinary thinking', () => {
@@ -90,8 +72,6 @@ describe('describeMindTurnProgress', () => {
});
expect(progress.phase).toBe('thinking');
- expect(progress.elapsedMs).toBeNull();
- expect(progress.heartbeatAgeMs).toBeNull();
expect(progress.detail).toBeNull();
});
@@ -109,24 +89,29 @@ describe('describeMindTurnProgress', () => {
expect(unreported.detail).toBe('model loaded');
});
- it('reports a quota autopause as blocked with a retry time, not as a user pause', () => {
+ it('takes the quota retry time from the probe schedule, which is the only thing that sets it', () => {
+ // A usage-limit autopause clears nextEligibleWakeAt (no backoff gate), so a
+ // projection that only read that field would never show a retry time for the
+ // exact case this feature exists for.
+ const quotaState = {
+ status: 'paused',
+ started: true,
+ activeTurnId: null,
+ usageLimited: true,
+ pauseReason: 'Provider usage limit reached',
+ nextEligibleWakeAt: null,
+ };
const progress = describeMindTurnProgress({
- state: {
- status: 'paused',
- started: true,
- activeTurnId: null,
- usageLimited: true,
- pauseReason: 'Provider usage limit reached',
- nextEligibleWakeAt: '2026-09-01T00:30:00.000Z',
- },
- runtime: null,
+ state: quotaState,
+ runtime: { usageLimitRetryAt: '2026-09-01T00:30:00.000Z' },
});
expect(progress.phase).toBe('blocked');
expect(progress.busy).toBe(false);
expect(progress.reason).toBe('Provider usage limit reached');
expect(progress.retryAt).toBe('2026-09-01T00:30:00.000Z');
- expect(progress.detail).toBe('retrying automatically');
+ // No probe scheduled yet: say nothing rather than invent a time.
+ expect(describeMindTurnProgress({ state: quotaState, runtime: null }).retryAt).toBeNull();
});
it('treats a degraded wake as blocked so a failing provider is not read as working', () => {
@@ -135,6 +120,8 @@ describe('describeMindTurnProgress', () => {
});
expect(progress.phase).toBe('blocked');
+ // Falls back to the backoff gate, which a degraded wake (unlike a quota
+ // autopause) really does set.
expect(progress.retryAt).toBe('2026-09-01T00:05:00.000Z');
});
diff --git a/server/lib/persistentMind.js b/server/lib/persistentMind.js
index 5663d270e8..12588deeb6 100644
--- a/server/lib/persistentMind.js
+++ b/server/lib/persistentMind.js
@@ -44,6 +44,11 @@ export const PERSISTENT_MIND_STATUSES = [
export const PERSISTENT_MIND_WAKE_KINDS = ['message', 'self'];
export const PERSISTENT_MIND_SELF_WAKE_SCHEDULE_KINDS = ['quiet', 'requested'];
+// How often a running turn pulses its heartbeat. Hoisted so the stale-warning
+// threshold below can be DERIVED from it rather than restating the number:
+// slowing the pulse would otherwise make every healthy turn read as stalled.
+const HEARTBEAT_INTERVAL_MS = 60_000;
+
export const PERSISTENT_MIND_LIMITS = Object.freeze({
MAX_QUEUED_MESSAGES: 100,
MAX_RECENT_MESSAGE_IDS: 200,
@@ -63,10 +68,13 @@ export const PERSISTENT_MIND_LIMITS = Object.freeze({
BACKOFF_BASE_MS: 5_000,
BACKOFF_MAX_MS: 15 * 60_000,
WATCHDOG_STALE_MS: 5 * 60_000,
- // UI warning threshold: two missed 60s heartbeats, well before the watchdog
- // kills the turn at WATCHDOG_STALE_MS, so "stalled" is visible while the turn
- // can still recover on its own.
- HEARTBEAT_STALE_WARNING_MS: 2 * 60_000,
+ // The adapter owns the pulse timer and imports this back, so one edit moves
+ // the cadence and the threshold derived from it together.
+ HEARTBEAT_INTERVAL_MS,
+ // UI warning threshold: two missed pulses, well before the watchdog kills the
+ // turn at WATCHDOG_STALE_MS, so "stalled" is visible while the turn can still
+ // recover on its own.
+ HEARTBEAT_STALE_WARNING_MS: 2 * HEARTBEAT_INTERVAL_MS,
MAX_QUIET_MS: 30 * 60_000,
});
diff --git a/server/lib/persistentMindPublic.js b/server/lib/persistentMindPublic.js
index ab6ba5f996..5d158cb60f 100644
--- a/server/lib/persistentMindPublic.js
+++ b/server/lib/persistentMindPublic.js
@@ -71,11 +71,6 @@ export function publicPersistentMindState(state = {}) {
// work rather than only ordinary heartbeat messages.
queuedTemporaryMessageCount: queuedMessages.filter((message) => Boolean(message?.thinkingPresetId)).length,
activeTurnId: typeof activeTurn?.id === 'string' ? activeTurn.id : null,
- // Turn freshness. Timestamps only — the derived age belongs to whoever has a
- // clock to subtract with, and /mind/runtime already reports it against the
- // server clock for the page that renders live progress.
- activeTurnStartedAt: typeof activeTurn?.startedAt === 'string' ? activeTurn.startedAt : null,
- activeTurnHeartbeatAt: typeof activeTurn?.heartbeatAt === 'string' ? activeTurn.heartbeatAt : null,
activeRoute: publicActiveRoute(activeTurn),
activeThinkingSession: publicActiveThinkingSession(activeTurn),
lastCompletedTurnId: typeof state.lastCompletedTurnId === 'string' ? state.lastCompletedTurnId : null,
diff --git a/server/lib/persistentMindPublic.test.js b/server/lib/persistentMindPublic.test.js
index 3c42ba95a0..fc6fd7c5d5 100644
--- a/server/lib/persistentMindPublic.test.js
+++ b/server/lib/persistentMindPublic.test.js
@@ -156,25 +156,6 @@ describe('public persistent mind state', () => {
expect(projected.queuedMessageCount).toBe(2);
expect(projected.queuedTemporaryMessageCount).toBe(1);
});
-it('publishes the freshness stamps of the active turn so the page can age it', () => {
- const projected = publicPersistentMindState(stateWithActiveTemporaryTurn());
-
- expect(projected.activeTurnStartedAt).toBe('2026-09-01T00:00:00.000Z');
- expect(projected.activeTurnHeartbeatAt).toBe('2026-09-01T00:00:05.000Z');
- });
-
- it('leaves the freshness stamps null when no turn is claimed', () => {
- const projected = publicPersistentMindState({
- ...createDefaultPersistentMindState(),
- enabled: true,
- started: true,
- status: 'waiting',
- });
-
- expect(projected.activeTurnStartedAt).toBeNull();
- expect(projected.activeTurnHeartbeatAt).toBeNull();
- expect(projected.usageLimited).toBe(false);
- });
it('distinguishes a quota autopause from a pause the user asked for', () => {
const quota = publicPersistentMindState(normalizePersistentMindState({
@@ -198,6 +179,7 @@ it('publishes the freshness stamps of the active turn so the page can age it', (
expect(quota.nextEligibleWakeAt).toBe('2026-09-01T00:30:00.000Z');
expect(byUser.usageLimited).toBe(false);
expect(byUser.pauseReason).toBe('Paused by user');
+ expect(publicPersistentMindState(createDefaultPersistentMindState()).usageLimited).toBe(false);
});
it('still reveals no raw pause text for a quota autopause', () => {
diff --git a/server/routes/cosMindRoutes.js b/server/routes/cosMindRoutes.js
index 67707f7b0c..ae876d70af 100644
--- a/server/routes/cosMindRoutes.js
+++ b/server/routes/cosMindRoutes.js
@@ -63,6 +63,7 @@ import {
startPersistentMind,
stopPersistentMind,
wakePersistentMind,
+ persistentMindUsageLimitRetryAt,
} from '../services/persistentMindSupervisor.js';
const router = Router();
@@ -299,7 +300,9 @@ router.get('/mind/runtime', asyncHandler(async (_req, res) => {
const profile = normalizePersistentMindProfile(root.config?.persistentMindProfile);
const providerId = state.activeTurn?.providerId || profile.providerId;
const provider = providerId ? await getProviderById(providerId) : null;
- res.json(await inspectPersistentMindRuntime({ state, profile, prompt, provider }));
+ res.json(await inspectPersistentMindRuntime({
+ state, profile, prompt, provider, usageLimitRetryAt: persistentMindUsageLimitRetryAt(),
+ }));
}));
router.get('/mind/visibility', asyncHandler(async (req, res) => {
diff --git a/server/routes/cosMindRoutes.test.js b/server/routes/cosMindRoutes.test.js
index 18695a9f71..9e0316d71d 100644
--- a/server/routes/cosMindRoutes.test.js
+++ b/server/routes/cosMindRoutes.test.js
@@ -25,6 +25,7 @@ const mocks = vi.hoisted(() => ({
pausePersistentMind: vi.fn(),
resumePersistentMind: vi.fn(),
stopPersistentMind: vi.fn(),
+ persistentMindUsageLimitRetryAt: vi.fn(() => null),
inspectPersistentMindRuntime: vi.fn(),
readPersistentMindVisibility: vi.fn(),
readPersistentMindTaskCatalog: vi.fn(),
@@ -87,6 +88,7 @@ vi.mock('../services/persistentMindSupervisor.js', () => ({
pausePersistentMind: mocks.pausePersistentMind,
resumePersistentMind: mocks.resumePersistentMind,
stopPersistentMind: mocks.stopPersistentMind,
+ persistentMindUsageLimitRetryAt: mocks.persistentMindUsageLimitRetryAt,
}));
vi.mock('../services/persistentMindRuntime.js', () => ({
inspectPersistentMindRuntime: mocks.inspectPersistentMindRuntime,
@@ -401,6 +403,19 @@ describe('persistent mind routes', () => {
expect(mocks.getProviderById).toHaveBeenCalledWith('ollama');
});
+ it('hands the usage-limit probe schedule to the runtime inspector', async () => {
+ // A usage-limit autopause clears nextEligibleWakeAt, so the readiness probe
+ // is the only thing that knows when a quota block clears. The route is
+ // where that read happens — the inspector never reaches for the scheduler.
+ mocks.persistentMindUsageLimitRetryAt.mockReturnValue('2026-09-01T00:30:00.000Z');
+ const res = await get('/mind/runtime');
+
+ expect(res.status).toBe(200);
+ expect(mocks.inspectPersistentMindRuntime).toHaveBeenCalledWith(expect.objectContaining({
+ usageLimitRetryAt: '2026-09-01T00:30:00.000Z',
+ }));
+ });
+
it('serves the shared environment visibility projection and accepts an explicit refresh', async () => {
const res = await get('/mind/visibility?refresh=true');
expect(res.status).toBe(200);
diff --git a/server/services/persistentMindAdapter.js b/server/services/persistentMindAdapter.js
index 4cb4a346b6..3695d9fbd8 100644
--- a/server/services/persistentMindAdapter.js
+++ b/server/services/persistentMindAdapter.js
@@ -10,6 +10,7 @@
import { persistentMindNamePrompt, persistentMindChosenNameSchema } from '../lib/persistentMindChosenName.js';
import { persistentMindMemoryProtectionSchema } from '../lib/persistentMindMemory.js';
+import { PERSISTENT_MIND_LIMITS } from '../lib/persistentMind.js';
import { z } from 'zod';
import {
PERSISTENT_MIND_TASK_LIMITS,
@@ -58,7 +59,7 @@ import {
isCosTaskToolName,
} from './cosToolRegistry.js';
-const HEARTBEAT_INTERVAL_MS = 60_000;
+const { HEARTBEAT_INTERVAL_MS } = PERSISTENT_MIND_LIMITS;
const MAX_TOOL_PROVIDER_ROUNDS = 4;
const MAX_TOOL_RESULT_CHARS = 4_000;
const MAX_MEMORY_CANDIDATES_PER_TURN = 5;
diff --git a/server/services/persistentMindRuntime.js b/server/services/persistentMindRuntime.js
index 451cc46a91..dd2d4accfa 100644
--- a/server/services/persistentMindRuntime.js
+++ b/server/services/persistentMindRuntime.js
@@ -82,7 +82,7 @@ function turnFreshness(activeTurn, observedAtMs) {
};
}
-export async function inspectPersistentMindRuntime({ state, profile, prompt, provider } = {}) {
+export async function inspectPersistentMindRuntime({ state, profile, prompt, provider, usageLimitRetryAt = null } = {}) {
const activeTurn = state?.activeTurn || null;
const activeModel = activeTurn?.model || profile?.model;
const [memories, memory, residency] = await Promise.all([
@@ -103,6 +103,10 @@ export async function inspectPersistentMindRuntime({ state, profile, prompt, pro
return {
observedAt: observedAt.toISOString(),
+ // When a blocked mind clears itself. A usage-limit autopause clears
+ // `nextEligibleWakeAt`, so its schedule lives only in the readiness probe;
+ // callers pass it in rather than this module reaching for the scheduler.
+ usageLimitRetryAt: typeof usageLimitRetryAt === 'string' ? usageLimitRetryAt : null,
inference: {
active: Boolean(activeTurn),
turnId: activeTurn?.id || null,
diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.js
index fa22edb72d..0d6254374f 100644
--- a/server/services/persistentMindSupervisor.js
+++ b/server/services/persistentMindSupervisor.js
@@ -44,7 +44,7 @@ export {
deletePersistentMindAttachment,
} from './persistentMindAttachments.js';
import { cosEvents, emitLog } from './cosEvents.js';
-import { schedule, cancel } from './eventScheduler.js';
+import { schedule, cancel, getEvent } from './eventScheduler.js';
import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';
import { acquireLocalEndpointProviderSlot } from './cosLocalEndpointSlots.js';
import { acquireCosActionReservation, acquireCosGlobalSlot } from './cosAdmissionReservations.js';
@@ -255,6 +255,21 @@ function scheduleUsageLimitProbe(attempt = 0) {
});
}
+/**
+ * When the next usage-limit readiness probe will run, or null when none is
+ * pending. READ-ONLY — it reports the schedule, it does not set or change it.
+ *
+ * A usage-limit autopause deliberately clears `nextEligibleWakeAt` (see
+ * `parkActiveTurn`: a hard quota gets no backoff gate and no failureCount
+ * climb), so recovery is owned by this probe alone. Without this accessor the
+ * page can say a quota block is retrying but never when — the one question the
+ * user actually has while waiting one out.
+ */
+export function persistentMindUsageLimitRetryAt() {
+ const nextRunAt = getEvent(PERSISTENT_MIND_USAGE_LIMIT_PROBE_EVENT_ID)?.nextRunAt;
+ return Number.isFinite(nextRunAt) ? new Date(nextRunAt).toISOString() : null;
+}
+
/**
* If paused solely for a provider usage limit, probe readiness and auto-resume
* when the pinned provider is usable again. Other pause reasons are ignored.