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

feat: show live turn progress on the Mind page so a long think reads differently from a stall (#7409)

[._.]/ Adam Eivy0d0691433374
diff --git a/client/src/components/cos/PersistentMindRuntimePanel.jsx b/client/src/components/cos/PersistentMindRuntimePanel.jsx
index bb83eb6ee0..c28654c7ce 100644
--- a/client/src/components/cos/PersistentMindRuntimePanel.jsx
+++ b/client/src/components/cos/PersistentMindRuntimePanel.jsx
@@ -1,39 +1,62 @@
-import { Brain, Cpu, Gauge } from 'lucide-react';
+import { AlertTriangle, Brain, Cpu, Gauge } from 'lucide-react';
+import { describeMindTurnProgress } from '../../lib/mindTurnProgress.js';
import { formatBytes, timeUntil } from '../../utils/formatters.js';
const number = (value) => Number.isFinite(value) ? value.toLocaleString() : '—';
+const RESIDENCY_STATES = {
+ loaded: 'Loaded in memory',
+ 'not-loaded': 'Not loaded',
+ 'provider-managed': 'Provider-managed',
+ unconfigured: 'Not configured',
+};
+
+// "Running now" alone answered the wrong question during a turn: a cold local
+// model that has not finished loading looks exactly like one mid-inference, and
+// that ambiguity is what made a slow start indistinguishable from a hang.
const residencyLabel = (runtime) => {
- if (runtime?.inference?.active) return 'Running now';
const status = runtime?.inference?.residency?.status;
- if (status === 'loaded') return 'Loaded in memory';
- if (status === 'not-loaded') return 'Not loaded';
- if (status === 'provider-managed') return 'Provider-managed';
- if (status === 'unconfigured') return 'Not configured';
- return 'Status unknown';
+ const state = RESIDENCY_STATES[status] || 'Status unknown';
+ if (!runtime?.inference?.active) return state;
+ return status === 'provider-managed' || status === 'unconfigured'
+ ? 'Running now'
+ : `Running now · ${state.toLowerCase()}`;
};
-export function PersistentMindThoughtStatus({ state, model }) {
- const thinking = state?.status === 'thinking' && Boolean(state.activeTurnId);
+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 label = 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 = 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';
+ // 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(' · ');
+ const attention = turn.phase === 'stalled' || turn.phase === 'blocked';
return (
<span
+ data-testid="mind-thought-status"
+ data-phase={turn.phase}
role="status"
- aria-busy={thinking}
- className={`inline-flex min-w-0 max-w-full items-center gap-2 rounded-full border px-3 py-1.5 text-xs font-medium ${thinking ? 'border-port-accent/60 bg-port-accent/10 text-port-accent' : 'border-port-border text-port-text-muted'}`}
+ aria-busy={turn.busy}
+ className={`inline-flex min-w-0 max-w-full items-center gap-2 rounded-full border px-3 py-1.5 text-xs font-medium ${attention ? 'border-port-warning/60 bg-port-warning/10 text-port-warning' : turn.busy ? 'border-port-accent/60 bg-port-accent/10 text-port-accent' : 'border-port-border text-port-text-muted'}`}
>
- <Brain size={14} className={thinking ? 'shrink-0 animate-pulse motion-reduce:animate-none' : 'shrink-0'} aria-hidden="true" />
+ {attention
+ ? <AlertTriangle size={14} className="shrink-0" aria-hidden="true" />
+ : <Brain size={14} className={turn.busy ? 'shrink-0 animate-pulse motion-reduce:animate-none' : 'shrink-0'} aria-hidden="true" />}
<span className="truncate" title={label}>{label}</span>
- {thinking && (
+ {turn.phase === 'thinking' && (
<span className="inline-flex shrink-0 gap-0.5" aria-hidden="true">
{[0, 1, 2].map((index) => (
<span
diff --git a/client/src/components/cos/tabs/MindTab.jsx b/client/src/components/cos/tabs/MindTab.jsx
index 17403c477f..608668947c 100644
--- a/client/src/components/cos/tabs/MindTab.jsx
+++ b/client/src/components/cos/tabs/MindTab.jsx
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useSearchParams } from 'react-router';
-import { ArrowUp, Brain, Check, CirclePause, CirclePlay, Cpu, Database, Eraser, ImagePlus, MessageCircle, PhoneCall, PhoneOff, RefreshCw, Settings2, Square, StickyNote, Upload, Wrench, X } from 'lucide-react';
+import { AlertTriangle, ArrowUp, Brain, Check, CirclePause, CirclePlay, Cpu, Database, Eraser, ImagePlus, MessageCircle, PhoneCall, PhoneOff, RefreshCw, Settings2, Square, StickyNote, Upload, Wrench, X } from 'lucide-react';
import { Link } from 'react-router';
import { useAutoRefetch } from '../../../hooks/useAutoRefetch.js';
import useMounted from '../../../hooks/useMounted';
@@ -27,6 +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 { readFileAsBase64, UPLOAD_IMAGE_ACCEPT, validateImageFile } from '../../../utils/fileUpload';
const PAGE_LIMIT = 200;
@@ -108,24 +109,53 @@ const imageCapability = (mind) => {
return { status, guidance: typeof capability?.guidance === 'string' ? capability.guidance : null };
};
-const MindTypingIndicator = () => (
- <span
- data-testid="mind-typing-indicator"
- role="status"
- aria-label="Chief of Staff is typing"
- className="inline-flex items-center gap-0.5"
- >
- <span className="sr-only">Chief of Staff is typing</span>
- {[0, 1, 2].map((index) => (
+// The chat header's live turn readout. Three bouncing dots alone said only
+// "not idle", so a cold model load, a wedged turn, and a quota autopause were
+// indistinguishable from healthy inference; the phase decides which of those
+// the user is looking at, and the stage/elapsed text says how far in it is.
+const MindTurnIndicator = ({ progress }) => {
+ if (progress.phase === 'idle') return null;
+ const detail = [progress.stage, progress.detail].filter(Boolean).join(' · ');
+
+ if (progress.phase === 'thinking') {
+ return (
<span
- key={index}
- aria-hidden="true"
- className="h-1.5 w-1.5 animate-bounce rounded-full bg-current motion-reduce:animate-none"
- style={{ animationDelay: `${index * 120}ms` }}
- />
- ))}
- </span>
-);
+ data-testid="mind-typing-indicator"
+ role="status"
+ aria-label={detail ? `Chief of Staff is typing — ${detail}` : 'Chief of Staff is typing'}
+ 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
+ key={index}
+ aria-hidden="true"
+ className="h-1.5 w-1.5 animate-bounce rounded-full bg-current motion-reduce:animate-none"
+ style={{ animationDelay: `${index * 120}ms` }}
+ />
+ ))}
+ </span>
+ {detail && <span aria-hidden="true" className="truncate text-[11px] font-normal">{detail}</span>}
+ </span>
+ );
+ }
+
+ const label = progress.phase === 'stalled'
+ ? ['Stalled, checking…', detail].filter(Boolean).join(' · ')
+ : [progress.reason || 'Blocked', progress.retryAt ? `retry ${timeUntil(progress.retryAt)}` : null].filter(Boolean).join(' · ');
+
+ return (
+ <span
+ data-testid={progress.phase === 'stalled' ? 'mind-stalled-indicator' : 'mind-blocked-indicator'}
+ 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"
+ >
+ <AlertTriangle size={12} aria-hidden="true" className="shrink-0" />
+ <span className="truncate" title={label}>{label}</span>
+ </span>
+ );
+};
const mergeEvents = (previous, incoming) => {
const byId = new Map(previous.map((event) => [event.eventId, event]));
@@ -628,6 +658,11 @@ export default function MindTab() {
};
const state = mind?.state;
+ // Derived from the runtime snapshot, whose freshness numbers are measured
+ // against the SERVER clock — so elapsed/heartbeat never subtract a browser
+ // clock from a server timestamp, and both refresh on the existing 10s
+ // runtime poll plus every socket-driven reload.
+ const turnProgress = describeMindTurnProgress({ state, runtime, events });
const selectedEvent = events?.find((event) => event.eventId === selectedEventId) || null;
const isPaused = state?.status === 'paused';
const profileReady = Boolean(mind?.profile?.enabled && mind.profile.providerId && mind.profile.model);
@@ -724,6 +759,7 @@ export default function MindTab() {
<div className="flex min-w-0 max-w-full flex-wrap items-center gap-2" role="group" aria-label="Persistent mind lifecycle">
<PersistentMindThoughtStatus
state={state}
+ progress={turnProgress}
model={state?.activeTurnId && state.activeTurnId === runtime?.inference?.turnId
? runtime.inference.model
: mind?.profile?.model}
@@ -770,7 +806,7 @@ export default function MindTab() {
<div className="grid min-h-0 flex-1 items-stretch gap-4 xl:grid-cols-[minmax(0,1fr)_19rem]">
<section data-testid="mind-chat" aria-label="Persistent mind chat" className="flex h-[68dvh] min-h-[30rem] flex-col overflow-hidden rounded-[1.5rem] border border-port-border bg-port-card shadow-lg shadow-black/10 sm:min-h-[34rem] xl:h-full xl:min-h-0">
<header className="flex shrink-0 items-center justify-between gap-3 border-b border-port-border bg-port-card/95 px-3 py-2.5 sm:px-4">
- <h3 className="flex items-center gap-2 text-sm font-medium text-port-text">Conversation {state?.status === 'thinking' && <MindTypingIndicator />}</h3>
+ <h3 className="flex min-w-0 items-center gap-2 text-sm font-medium text-port-text"><span className="shrink-0">Conversation</span> <MindTurnIndicator progress={turnProgress} /></h3>
<label htmlFor="mind-show-activity" className="flex shrink-0 items-center gap-2 rounded-full border border-port-border px-2.5 py-1.5 text-[11px] text-port-text-muted">
<input id="mind-show-activity" type="checkbox" checked={showActivity} onChange={(event) => setShowActivity(event.target.checked)} className="accent-port-accent" /> Activity
</label>
@@ -858,11 +894,24 @@ export default function MindTab() {
<p className="text-[11px] font-semibold uppercase tracking-[0.16em] text-port-text-muted">Live workspace</p>
<h3 id="mind-state-heading" className="mt-1 text-base font-semibold text-port-text">Mind state</h3>
</div>
- <span className={`h-2.5 w-2.5 rounded-full ${state?.status === 'thinking' ? 'animate-pulse bg-port-accent' : state?.started && !isPaused ? 'bg-port-success' : 'bg-port-text-muted'}`} aria-hidden="true" />
+ <span className={`h-2.5 w-2.5 rounded-full ${turnProgress.phase === 'stalled' || turnProgress.phase === 'blocked' ? 'bg-port-warning' : turnProgress.phase === 'thinking' ? 'animate-pulse bg-port-accent' : state?.started && !isPaused ? 'bg-port-success' : 'bg-port-text-muted'}`} aria-hidden="true" />
</div>
<p className="mt-3 text-sm text-port-text-muted">
- {state?.status === 'thinking' ? 'Working through the current turn.' : state?.pauseReason || (state?.started ? 'Listening for messages and scheduled wakes.' : 'Configure the AI profile to begin.')}
+ {turnProgress.phase === 'stalled' ? 'No heartbeat from the current turn — checking whether it is still alive.'
+ : turnProgress.phase === 'blocked' ? `${turnProgress.reason || 'Blocked'} — the mind retries on its own; no action needed.`
+ : turnProgress.phase === 'thinking' ? `${turnProgress.stage || 'Working through the current turn'}.`
+ : state?.pauseReason || (state?.started ? 'Listening for messages and scheduled wakes.' : 'Configure the AI profile to begin.')}
</p>
+ {turnProgress.detail && (
+ <p data-testid="mind-turn-progress-detail" className={`mt-1 text-xs ${turnProgress.phase === 'stalled' || turnProgress.phase === 'blocked' ? 'text-port-warning' : 'text-port-text-muted'}`}>
+ {turnProgress.detail}
+ </p>
+ )}
+ {turnProgress.retryAt && (
+ <p className="mt-1 text-xs text-port-warning">
+ Next retry <time dateTime={turnProgress.retryAt} className="font-medium">{formatDateTime(turnProgress.retryAt)}</time> · {timeUntil(turnProgress.retryAt)}
+ </p>
+ )}
{state?.queuedMessageCount > 0 && <p className="mt-2 text-xs font-medium text-port-accent">{state.queuedMessageCount} queued message{state.queuedMessageCount === 1 ? '' : 's'}</p>}
{state?.started && state?.nextWakeAt && (
<button
diff --git a/client/src/components/cos/tabs/MindTab.test.jsx b/client/src/components/cos/tabs/MindTab.test.jsx
index 05223e0508..5fe6241aaa 100644
--- a/client/src/components/cos/tabs/MindTab.test.jsx
+++ b/client/src/components/cos/tabs/MindTab.test.jsx
@@ -623,6 +623,114 @@ describe('MindTab', () => {
expect(within(screen.getByTestId('mind-chat')).queryByText('Thinking…')).not.toBeInTheDocument();
});
+const thinkingRuntime = (inference = {}) => ({
+ observedAt: '2026-08-27T12:02:40.000Z',
+ inference: {
+ active: true,
+ turnId: 'mind-turn-1',
+ startedAt: '2026-08-27T12:00:00.000Z',
+ heartbeatAt: '2026-08-27T12:02:35.000Z',
+ elapsedMs: 160_000,
+ heartbeatAgeMs: 5_000,
+ heartbeatStale: false,
+ providerId: 'ollama',
+ model: 'demo-model',
+ residency: { status: 'loaded', backend: 'ollama', loaded: true, memoryBytes: 2 * 1024 ** 3 },
+ ...inference,
+ },
+ context: { chars: 12000, maxChars: 32000, approximateTokens: 3000, summaryState: 'ready', memoryCount: 4 },
+ system: {
+ memory: { total: 8 * 1024 ** 3, used: 4 * 1024 ** 3, free: 4 * 1024 ** 3, usagePercent: 50 },
+ process: { rss: 256 * 1024 ** 2, heapUsed: 64 * 1024 ** 2, heapTotal: 128 * 1024 ** 2 },
+ cpu: { cores: 8, loadAvg1m: 1.25 },
+ },
+ });
+
+ it('shows elapsed think time, heartbeat freshness, and the current stage while a turn runs', async () => {
+ api.getPersistentMind.mockResolvedValue(response({
+ state: { enabled: true, started: true, status: 'thinking', pauseReason: null, activeTurnId: 'mind-turn-1' },
+ events: [
+ event(),
+ { ...event({ eventId: 'mind-wake:1', kind: 'mind.wake', turnId: 'mind-turn-1', sequence: 2, data: {} }) },
+ { ...event({ eventId: 'mind-model-request:1', kind: 'mind.model.request', turnId: 'mind-turn-1', sequence: 3, data: {} }) },
+ ],
+ }));
+ api.getPersistentMindRuntime.mockResolvedValue(thinkingRuntime());
+ renderTab();
+
+ const indicator = await screen.findByTestId('mind-typing-indicator');
+ expect(indicator).toHaveAccessibleName(/Waiting on the model/);
+ expect(indicator).toHaveAccessibleName(/2m 40s/);
+ expect(indicator).toHaveAccessibleName(/heartbeat 5s ago/);
+ expect(await screen.findByTestId('mind-turn-progress-detail'))
+ .toHaveTextContent('2m 40s · heartbeat 5s ago · model loaded');
+ });
+
+ it('renders a stale heartbeat as a stalled state rather than the normal thinking dots', async () => {
+ api.getPersistentMind.mockResolvedValue(response({
+ state: { enabled: true, started: true, status: 'thinking', pauseReason: null, activeTurnId: 'mind-turn-1' },
+ }));
+ api.getPersistentMindRuntime.mockResolvedValue(thinkingRuntime({ heartbeatAgeMs: 190_000, heartbeatStale: true }));
+ renderTab();
+
+ const stalled = await screen.findByTestId('mind-stalled-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: {
+ enabled: true,
+ started: true,
+ status: 'paused',
+ 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(),
+ },
+ }));
+ renderTab();
+
+ const blocked = await screen.findByTestId('mind-blocked-indicator');
+ expect(blocked).toHaveTextContent(/Provider usage limit reached/);
+ expect(blocked).toHaveTextContent(/retry in 12m/);
+ expect(screen.queryByTestId('mind-typing-indicator')).not.toBeInTheDocument();
+ expect(await screen.findByText(/the mind retries on its own/)).toBeInTheDocument();
+ });
+
+ it('never renders raw provider reasoning in the live progress readout', async () => {
+ api.getPersistentMind.mockResolvedValue(response({
+ state: { enabled: true, started: true, status: 'thinking', pauseReason: null, activeTurnId: 'mind-turn-1' },
+ }));
+ api.getPersistentMindRuntime.mockResolvedValue(thinkingRuntime({
+ // A payload a future runtime change might carry: the progress readout must
+ // stay a function of status enums and durations, never of model text.
+ reasoning: 'SECRET-CHAIN-OF-THOUGHT',
+ residency: { status: 'loaded', backend: 'ollama', loaded: true, memoryBytes: 2 * 1024 ** 3, note: 'SECRET-CHAIN-OF-THOUGHT' },
+ }));
+ renderTab();
+
+ await screen.findByTestId('mind-typing-indicator');
+ expect(screen.queryByText(/SECRET-CHAIN-OF-THOUGHT/)).not.toBeInTheDocument();
+ });
+
it('animates active thought status and shows context, system, and loaded-model telemetry', async () => {
const user = userEvent.setup();
api.getPersistentMind.mockResolvedValue(response({
@@ -646,14 +754,16 @@ describe('MindTab', () => {
});
renderTab();
- const thoughtStatus = (await screen.findByText('Thinking with demo-model')).closest('[role="status"]');
+ const thoughtStatus = await screen.findByTestId('mind-thought-status');
expect(thoughtStatus).toHaveTextContent('Thinking with demo-model');
expect(thoughtStatus).toHaveAttribute('aria-busy', 'true');
expect(thoughtStatus.querySelector('.animate-pulse')).toBeInTheDocument();
expect(screen.getByText('~3,000 tokens')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: /Context/i }));
expect(screen.getByText('4 GB / 8 GB')).toBeInTheDocument();
- expect(screen.getAllByText('Running now').length).toBeGreaterThan(0);
+ // The active turn no longer hides residency behind a bare "Running now" —
+ // a cold local model that has not finished loading must read differently.
+ expect(screen.getAllByText('Running now · loaded in memory').length).toBeGreaterThan(0);
expect(screen.getByText(/ollama · 2 GB/)).toBeInTheDocument();
});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 9a0c4050fa..3b27dfb527 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -206,6 +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. |
| `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/index.js b/client/src/lib/index.js
index 98aa7d3ba6..faa21de5d1 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -164,6 +164,7 @@ export * from './lossSparkline.js';
export * from './managedAppSources.js';
export * from './metronome.js';
export * from './mindThinkingPresets.js';
+export * from './mindTurnProgress.js';
export * from './navFeatures.js';
export * from './pageNavTabs.js';
export * from './midiChords.js';
diff --git a/client/src/lib/mindTurnProgress.js b/client/src/lib/mindTurnProgress.js
new file mode 100644
index 0000000000..e7050a4ab9
--- /dev/null
+++ b/client/src/lib/mindTurnProgress.js
@@ -0,0 +1,123 @@
+/**
+ * Live progress derivation for a Persistent Mind turn (#7409).
+ *
+ * The Mind page used to render one indefinite three-dot indicator for every
+ * non-idle state, so "healthy but slow local inference", "the turn wedged and
+ * 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.
+ *
+ * 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"
+ * and "zero elapsed" are different answers; collapsing them would show a
+ * just-started turn as having no heartbeat.
+ *
+ * Privacy: every string here is derived from status enums and durations. No
+ * provider reasoning, prompt text, or trajectory payload crosses into it — the
+ * hidden chain-of-thought boundary stays exactly where `persistentMindVisibility`
+ * put it.
+ */
+
+import { formatDurationMs } from '../utils/formatters.js';
+
+/** Turn stages the trajectory can pin, newest event wins. */
+const STAGE_LABELS = {
+ 'mind.wake': 'Preparing context',
+ 'mind.model.request': 'Waiting on the model',
+ 'mind.model.result': 'Reading the model response',
+ 'mind.capability.request': 'Running a granted action',
+ 'mind.capability.result': 'Reading the action result',
+ 'mind.thought': 'Continuing after a working note',
+ 'mind.memory.candidate': 'Proposing a memory',
+ 'mind.memory.created': 'Saving a memory',
+};
+
+const RESIDENCY_LABELS = {
+ loaded: 'model loaded',
+ 'not-loaded': 'loading model',
+ unknown: 'local runtime unreachable',
+};
+
+const trimmed = (value) => (typeof value === 'string' && value.trim() ? value.trim() : null);
+
+/**
+ * The runtime snapshot for THIS turn, or null when it describes another one.
+ * A turn with no id (state still loading) never matches.
+ */
+export function mindTurnRuntimeSnapshot(state, runtime) {
+ const turnId = trimmed(state?.activeTurnId);
+ const inference = runtime?.inference;
+ if (!turnId || !inference?.active || trimmed(inference.turnId) !== turnId) return null;
+ return inference;
+}
+
+/** Newest trajectory stage for the claimed turn, or null when none is pinned. */
+export function mindTurnStage(state, events) {
+ const turnId = trimmed(state?.activeTurnId);
+ if (!turnId || !Array.isArray(events)) return null;
+ let best = null;
+ for (const event of events) {
+ if (event?.turnId !== turnId || !STAGE_LABELS[event.kind]) continue;
+ // `sequence` is the trajectory's own monotonic order; a bare array position
+ // would be wrong after a merge that backfilled an older page.
+ if (best === null || (event.sequence ?? -1) >= (best.sequence ?? -1)) best = event;
+ }
+ return best ? STAGE_LABELS[best.kind] : null;
+}
+
+/**
+ * Describe what the mind is doing right now.
+ *
+ * @param {object} args
+ * @param {object|null} args.state — public persistent-mind state
+ * @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,
+ * detail: string|null}}
+ */
+export function describeMindTurnProgress({ state, runtime, events } = {}) {
+ const inference = mindTurnRuntimeSnapshot(state, runtime);
+ const elapsedMs = Number.isFinite(inference?.elapsedMs) ? inference.elapsedMs : null;
+ const heartbeatAgeMs = Number.isFinite(inference?.heartbeatAgeMs) ? inference.heartbeatAgeMs : null;
+ 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 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 parts = [];
+ if (phase === 'blocked') {
+ if (trimmed(state?.nextEligibleWakeAt)) parts.push('retrying automatically');
+ } else if (phase !== 'idle') {
+ if (elapsedMs !== null) parts.push(formatDurationMs(elapsedMs));
+ if (heartbeatAgeMs !== null) {
+ parts.push(stalled ? `no heartbeat for ${formatDurationMs(heartbeatAgeMs)}` : `heartbeat ${formatDurationMs(heartbeatAgeMs)} ago`);
+ }
+ 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,
+ 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
new file mode 100644
index 0000000000..70b045073c
--- /dev/null
+++ b/client/src/lib/mindTurnProgress.test.js
@@ -0,0 +1,169 @@
+import { describe, expect, it } from 'vitest';
+import { describeMindTurnProgress, mindTurnStage } from './mindTurnProgress.js';
+
+const thinkingState = (overrides = {}) => ({
+ enabled: true,
+ started: true,
+ status: 'thinking',
+ activeTurnId: 'turn-1',
+ pauseReason: null,
+ usageLimited: false,
+ nextEligibleWakeAt: null,
+ ...overrides,
+});
+
+const runtimeFor = (inference = {}) => ({
+ observedAt: '2026-09-01T00:02:40.000Z',
+ inference: {
+ active: true,
+ turnId: 'turn-1',
+ startedAt: '2026-09-01T00:00:00.000Z',
+ heartbeatAt: '2026-09-01T00:02:35.000Z',
+ elapsedMs: 160_000,
+ heartbeatAgeMs: 5_000,
+ heartbeatStale: false,
+ providerId: 'example-provider',
+ model: 'example-model',
+ residency: { status: 'loaded', backend: 'ollama', loaded: true },
+ ...inference,
+ },
+});
+
+describe('describeMindTurnProgress', () => {
+ it('reports elapsed time, heartbeat freshness, and residency while a turn runs', () => {
+ const progress = describeMindTurnProgress({ state: thinkingState(), runtime: runtimeFor() });
+
+ 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({
+ 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 } }),
+ });
+
+ expect(progress.residency).toBeNull();
+ expect(progress.detail).toBe('2m 40s · heartbeat 5s ago');
+ });
+
+ it('separates a stale heartbeat from ordinary thinking', () => {
+ const fresh = describeMindTurnProgress({ state: thinkingState(), runtime: runtimeFor() });
+ const stale = describeMindTurnProgress({
+ state: thinkingState(),
+ runtime: runtimeFor({ heartbeatAgeMs: 190_000, heartbeatStale: true }),
+ });
+
+ expect(fresh.phase).toBe('thinking');
+ expect(stale.phase).toBe('stalled');
+ expect(stale.busy).toBe(true);
+ expect(stale.detail).toContain('no heartbeat for 3m 10s');
+ });
+
+ it('ignores freshness from a snapshot describing a different turn', () => {
+ const progress = describeMindTurnProgress({
+ state: thinkingState(),
+ // The previous turn's snapshot: dating THIS turn with it would report a
+ // just-started turn as long-running and stalled.
+ runtime: runtimeFor({ turnId: 'turn-0', heartbeatAgeMs: 900_000, heartbeatStale: true }),
+ });
+
+ expect(progress.phase).toBe('thinking');
+ expect(progress.elapsedMs).toBeNull();
+ expect(progress.heartbeatAgeMs).toBeNull();
+ expect(progress.detail).toBeNull();
+ });
+
+ it('keeps a just-started turn distinct from one reporting no measurement at all', () => {
+ const justStarted = describeMindTurnProgress({
+ state: thinkingState(),
+ runtime: runtimeFor({ elapsedMs: 0, heartbeatAgeMs: 0 }),
+ });
+ const unreported = describeMindTurnProgress({
+ state: thinkingState(),
+ runtime: runtimeFor({ elapsedMs: null, heartbeatAgeMs: null }),
+ });
+
+ expect(justStarted.detail).toBe('0s · heartbeat 0s ago · model loaded');
+ expect(unreported.detail).toBe('model loaded');
+ });
+
+ it('reports a quota autopause as blocked with a retry time, not as a user pause', () => {
+ 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,
+ });
+
+ 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');
+ });
+
+ it('treats a degraded wake as blocked so a failing provider is not read as working', () => {
+ const progress = describeMindTurnProgress({
+ state: { status: 'degraded', started: true, activeTurnId: null, usageLimited: false, pauseReason: 'Provider unavailable or wake failed', nextEligibleWakeAt: '2026-09-01T00:05:00.000Z' },
+ });
+
+ expect(progress.phase).toBe('blocked');
+ expect(progress.retryAt).toBe('2026-09-01T00:05:00.000Z');
+ });
+
+ it('leaves a user pause and an ordinary wait idle', () => {
+ expect(describeMindTurnProgress({ state: { status: 'paused', usageLimited: false } }).phase).toBe('idle');
+ expect(describeMindTurnProgress({ state: { status: 'waiting', started: true } }).phase).toBe('idle');
+ expect(describeMindTurnProgress({}).phase).toBe('idle');
+ });
+});
+
+describe('mindTurnStage', () => {
+ const events = [
+ { eventId: 'a', kind: 'mind.wake', turnId: 'turn-1', sequence: 1 },
+ { eventId: 'b', kind: 'mind.model.request', turnId: 'turn-1', sequence: 2 },
+ { eventId: 'c', kind: 'mind.capability.request', turnId: 'turn-1', sequence: 4 },
+ { eventId: 'd', kind: 'mind.model.result', turnId: 'turn-1', sequence: 3 },
+ { eventId: 'e', kind: 'mind.model.request', turnId: 'turn-0', sequence: 9 },
+ ];
+
+ it('reads the newest stage for the claimed turn by sequence, not array order', () => {
+ expect(mindTurnStage({ activeTurnId: 'turn-1' }, events)).toBe('Running a granted action');
+ });
+
+ it('ignores events belonging to another turn', () => {
+ expect(mindTurnStage({ activeTurnId: 'turn-2' }, events)).toBeNull();
+ });
+
+ it('returns null when no turn is claimed or no events are loaded', () => {
+ expect(mindTurnStage({ activeTurnId: null }, events)).toBeNull();
+ expect(mindTurnStage({ activeTurnId: 'turn-1' }, null)).toBeNull();
+ });
+});
diff --git a/server/lib/persistentMind.js b/server/lib/persistentMind.js
index 0747ae07d9..5663d270e8 100644
--- a/server/lib/persistentMind.js
+++ b/server/lib/persistentMind.js
@@ -63,6 +63,10 @@ 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,
MAX_QUIET_MS: 30 * 60_000,
});
diff --git a/server/lib/persistentMindPublic.js b/server/lib/persistentMindPublic.js
index e1df54cb62..ab6ba5f996 100644
--- a/server/lib/persistentMindPublic.js
+++ b/server/lib/persistentMindPublic.js
@@ -2,9 +2,14 @@
import { nextPersistentMindWakeAt } from './persistentMind.js';
import { normalizePersistentMindThinkingSelection } from './persistentMindThinkingPresets.js';
+import { isUsageLimitPauseReason } from './persistentMindUsageLimit.js';
const publicReason = (state) => {
if (!state.pauseReason) return null;
+ // A quota autopause is NOT a user action. Saying "Paused by user" there is the
+ // exact confusion this projection exists to prevent: the page would blame the
+ // human for a provider limit it will retry out of on its own.
+ if (isUsageLimitPauseReason(state.pauseReason)) return 'Provider usage limit reached';
if (state.status === 'paused') return 'Paused by user';
if (state.status === 'degraded' || state.status === 'interrupted') return 'Provider unavailable or wake failed';
return 'Waiting for the next eligible wake';
@@ -56,12 +61,21 @@ export function publicPersistentMindState(state = {}) {
started: state.started === true,
status: typeof state.status === 'string' ? state.status : 'unknown',
pauseReason: publicReason(state),
+ // The one pause the mind clears by itself. The page needs it separated from
+ // an ordinary user pause so it can say "blocked, retrying at X" rather than
+ // leaving a quota stall indistinguishable from a deliberate stop.
+ usageLimited: isUsageLimitPauseReason(state.pauseReason),
queuedMessageCount: queuedMessages.length,
// How many of those queued messages will spend a borrowed (possibly
// account-backed) route, so the page can say that a pause is holding paid
// 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 e2ca716907..3c42ba95a0 100644
--- a/server/lib/persistentMindPublic.test.js
+++ b/server/lib/persistentMindPublic.test.js
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import { createDefaultPersistentMindState, normalizePersistentMindState } from './persistentMind.js';
import { publicPersistentMindState } from './persistentMindPublic.js';
+import { PROVIDER_USAGE_LIMIT_PAUSE_REASON } from './persistentMindUsageLimit.js';
const selection = {
id: 'deep-think',
@@ -155,4 +156,59 @@ 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({
+ ...createDefaultPersistentMindState(),
+ enabled: true,
+ started: true,
+ status: 'paused',
+ pauseReason: PROVIDER_USAGE_LIMIT_PAUSE_REASON,
+ nextEligibleWakeAt: '2026-09-01T00:30:00.000Z',
+ }));
+ const byUser = publicPersistentMindState(normalizePersistentMindState({
+ ...createDefaultPersistentMindState(),
+ enabled: true,
+ started: true,
+ status: 'paused',
+ pauseReason: 'Paused from the Mind page',
+ }));
+
+ expect(quota.usageLimited).toBe(true);
+ expect(quota.pauseReason).toBe('Provider usage limit reached');
+ expect(quota.nextEligibleWakeAt).toBe('2026-09-01T00:30:00.000Z');
+ expect(byUser.usageLimited).toBe(false);
+ expect(byUser.pauseReason).toBe('Paused by user');
+ });
+
+ it('still reveals no raw pause text for a quota autopause', () => {
+ const projected = publicPersistentMindState(normalizePersistentMindState({
+ ...createDefaultPersistentMindState(),
+ status: 'paused',
+ pauseReason: PROVIDER_USAGE_LIMIT_PAUSE_REASON,
+ lastError: 'provider said: key sk-EXAMPLE exceeded your current quota',
+ }));
+
+ expect(projected.lastError).toBe('The last wake did not complete; local diagnostics have details');
+ expect(JSON.stringify(projected)).not.toContain('sk-EXAMPLE');
+ });
});
diff --git a/server/services/persistentMindRuntime.js b/server/services/persistentMindRuntime.js
index 4171f0bb99..451cc46a91 100644
--- a/server/services/persistentMindRuntime.js
+++ b/server/services/persistentMindRuntime.js
@@ -4,6 +4,7 @@ import os from 'os';
import { localRuntimeForProvider } from '../lib/localProviderRuntime.js';
import { getMemoryStats } from '../lib/memoryStats.js';
import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';
+import { PERSISTENT_MIND_LIMITS } from '../lib/persistentMind.js';
import { PERSISTENT_MIND_TRAJECTORY_LIMITS } from '../lib/persistentMindTrajectory.js';
import { getLoadedModelsAt as getLoadedOllamaModelsAt } from './ollamaManager.js';
import {
@@ -61,6 +62,26 @@ async function inspectModelResidency(provider, model) {
};
}
+// Turn freshness measured against the SERVER clock at `observedAt`, so the page
+// never subtracts a browser clock from a server timestamp. A missing or
+// unparseable stamp stays `null` — "not reported" and "zero elapsed" are
+// different answers, and a UI that collapses them reads a fresh turn as stalled.
+function turnFreshness(activeTurn, observedAtMs) {
+ const since = (value) => {
+ const at = Date.parse(value);
+ if (!Number.isFinite(at)) return null;
+ return Math.max(0, observedAtMs - at);
+ };
+ if (!activeTurn) return { elapsedMs: null, heartbeatAgeMs: null, heartbeatStale: false };
+ const heartbeatAgeMs = since(activeTurn.heartbeatAt);
+ return {
+ elapsedMs: since(activeTurn.startedAt),
+ heartbeatAgeMs,
+ heartbeatStale: heartbeatAgeMs !== null
+ && heartbeatAgeMs >= PERSISTENT_MIND_LIMITS.HEARTBEAT_STALE_WARNING_MS,
+ };
+}
+
export async function inspectPersistentMindRuntime({ state, profile, prompt, provider } = {}) {
const activeTurn = state?.activeTurn || null;
const activeModel = activeTurn?.model || profile?.model;
@@ -75,15 +96,19 @@ export async function inspectPersistentMindRuntime({ state, profile, prompt, pro
memories,
});
const processMemory = process.memoryUsage();
+ const observedAt = new Date();
+ const freshness = turnFreshness(activeTurn, observedAt.getTime());
const totalMemory = Number(memory.total) || 0;
const usedMemory = Number(memory.used) || 0;
return {
- observedAt: new Date().toISOString(),
+ observedAt: observedAt.toISOString(),
inference: {
active: Boolean(activeTurn),
turnId: activeTurn?.id || null,
startedAt: activeTurn?.startedAt || null,
+ heartbeatAt: activeTurn?.heartbeatAt || null,
+ ...freshness,
providerId: activeTurn?.providerId || profile?.providerId || null,
model: activeTurn?.model || profile?.model || null,
residency,
diff --git a/server/services/persistentMindRuntime.test.js b/server/services/persistentMindRuntime.test.js
index de34392be5..e88c8006a3 100644
--- a/server/services/persistentMindRuntime.test.js
+++ b/server/services/persistentMindRuntime.test.js
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
getMemoryStats: vi.fn(),
@@ -127,4 +127,73 @@ describe('persistent mind runtime telemetry', () => {
expect(mocks.probeOpenAiModels).toHaveBeenCalledWith('http://localhost:5568/v1', { apiKey: '' });
expect(runtime.inference.residency).toMatchObject({ status: 'loaded', backend: 'llama', loaded: true });
});
+describe('active-turn freshness', () => {
+ // Injected clock: the contract is "measured against the server clock at
+ // observedAt", so a real sleep would prove nothing a fake one does not.
+ const OBSERVED_AT = '2026-09-01T00:03:00.000Z';
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(OBSERVED_AT));
+ });
+ afterEach(() => vi.useRealTimers());
+
+ const inspectTurn = (activeTurn) => inspectPersistentMindRuntime({
+ state: { activeTurn },
+ profile: { providerId: 'codex', model: 'example-model' },
+ prompt: {},
+ provider: null,
+ });
+
+ it('ages the claimed turn against the observation clock rather than a caller clock', async () => {
+ const runtime = await inspectTurn({
+ id: 'turn-1',
+ startedAt: '2026-09-01T00:00:00.000Z',
+ heartbeatAt: '2026-09-01T00:02:55.000Z',
+ model: 'example-model',
+ });
+
+ expect(runtime.observedAt).toBe(OBSERVED_AT);
+ expect(runtime.inference.heartbeatAt).toBe('2026-09-01T00:02:55.000Z');
+ expect(runtime.inference.elapsedMs).toBe(180_000);
+ expect(runtime.inference.heartbeatAgeMs).toBe(5_000);
+ expect(runtime.inference.heartbeatStale).toBe(false);
+ });
+
+ it('flags a heartbeat past the warning threshold while the watchdog has not fired', async () => {
+ const runtime = await inspectTurn({
+ id: 'turn-1',
+ startedAt: '2026-09-01T00:00:00.000Z',
+ heartbeatAt: '2026-09-01T00:00:30.000Z',
+ model: 'example-model',
+ });
+
+ expect(runtime.inference.heartbeatAgeMs).toBe(150_000);
+ expect(runtime.inference.heartbeatStale).toBe(true);
+ });
+
+ it('reports no measurement rather than a zero age for an unparseable stamp', async () => {
+ const runtime = await inspectTurn({
+ id: 'turn-1',
+ startedAt: 'not-a-date',
+ heartbeatAt: 'not-a-date',
+ model: 'example-model',
+ });
+
+ expect(runtime.inference.elapsedMs).toBeNull();
+ expect(runtime.inference.heartbeatAgeMs).toBeNull();
+ expect(runtime.inference.heartbeatStale).toBe(false);
+ });
+
+ it('leaves every freshness field empty when no turn is claimed', async () => {
+ const runtime = await inspectTurn(null);
+
+ expect(runtime.inference).toMatchObject({
+ active: false,
+ heartbeatAt: null,
+ elapsedMs: null,
+ heartbeatAgeMs: null,
+ heartbeatStale: false,
+ });
+ });
+ });
});