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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: expose temporary thinking presets and session provenance in the Mind UI (#6285)
[._.]/ Adam Eivy1d38cac257e8
diff --git a/client/src/components/cos/MindRouteBadge.jsx b/client/src/components/cos/MindRouteBadge.jsxnew file mode 100644index 0000000000..4aeaec5796--- /dev/null+++ b/client/src/components/cos/MindRouteBadge.jsx@@ -0,0 +1,45 @@+import { Cpu } from 'lucide-react';+import { classifyMindRouteBilling, formatMindRoute, MIND_ROUTE_BILLING } from '../../lib/mindThinkingPresets.js';++const BILLING_TONE = Object.freeze({+ [MIND_ROUTE_BILLING.LOCAL]: 'border-port-success/30 bg-port-success/10 text-port-success',+ // An unclassifiable route is warned about exactly like an account-backed one:+ // the user's decision is the same either way.+ [MIND_ROUTE_BILLING.ACCOUNT]: 'border-port-warning/40 bg-port-warning/10 text-port-warning',+ [MIND_ROUTE_BILLING.UNKNOWN]: 'border-port-warning/40 bg-port-warning/10 text-port-warning',+});++/**+ * One exact provider/model/effort route, plus what taking it can spend.+ *+ * The single rendering for "which model is this", shared by the preset list,+ * the composer preview, the live-route panel and the session receipts, so the+ * page cannot describe the same route four different ways — and so an+ * account-backed or unclassifiable route is warned about identically wherever+ * it appears.+ *+ * `route` is a plain `{ providerId, model, effort }` descriptor. `provider` is+ * the matching record from the provider catalog, or null when the catalog has+ * not settled or no longer lists it — which is itself reported, as unknown+ * rather than as free.+ */+export default function MindRouteBadge({ route, provider = null, className = '', showBilling = true }) {+ const billing = classifyMindRouteBilling(provider);+ return (+ <span className={`inline-flex flex-wrap items-center gap-1.5 ${className}`}>+ <span className="truncate font-mono text-[11px] text-port-text">+ {formatMindRoute(route, { providerName: provider?.name || null })}+ </span>+ {showBilling && (+ <span+ title={billing.detail}+ className={`inline-flex shrink-0 items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] ${BILLING_TONE[billing.billing]}`}+ >+ <Cpu size={10} aria-hidden="true" /> {billing.label}+ </span>+ )}+ </span>+ );+}++export { BILLING_TONE };diff --git a/client/src/components/cos/PersistentMindRoutePanel.jsx b/client/src/components/cos/PersistentMindRoutePanel.jsxnew file mode 100644index 0000000000..49d375cde0--- /dev/null+++ b/client/src/components/cos/PersistentMindRoutePanel.jsx@@ -0,0 +1,138 @@+import { CircleStop, RotateCcw, Route } from 'lucide-react';+import {+ findMindThinkingPreset,+ formatMindCallOutcome,+ formatMindElapsed,+ mindTurnElapsedMs,+ mindTurnOutcome,+ sameMindRoute,+ temporaryMindTurns,+} from '../../lib/mindThinkingPresets.js';+import MindRouteBadge from './MindRouteBadge.jsx';++/**+ * Default route versus the route the mind is ACTUALLY running on right now.+ *+ * These are different questions and the page has to answer both: a temporary+ * thinking session borrows another model for exactly one turn, so "which model+ * is my Chief of Staff" and "what is this turn spending" can legitimately+ * disagree for the length of that turn. A field the claim never recorded is+ * shown as unknown rather than back-filled from the profile — that fallback+ * would report the default route for a turn that is not taking it.+ *+ * Cancelling routes through the caller's existing lifecycle action (pause),+ * which is the machinery that already interrupts a claimed turn and retires a+ * temporary session rather than requeueing it. There is no second cancel path.+ */+export default function PersistentMindRoutePanel({+ profile,+ state,+ providers = [],+ presets = [],+ turnExecutions = [],+ selectedPresetId = null,+ onReturnToDefault,+ onCancelSession,+ cancelPending = false,+ onInspectSession,+}) {+ const defaultRoute = {+ providerId: profile?.providerId || null,+ model: profile?.model || null,+ effort: profile?.effort || null,+ };+ const defaultProvider = providers.find((provider) => provider.id === profile?.providerId) || null;+ const session = state?.activeThinkingSession || null;+ const activeRoute = state?.activeRoute || null;+ const activeProvider = activeRoute?.providerId+ ? providers.find((provider) => provider.id === activeRoute.providerId) || null+ : null;+ // Editing a preset while a message that selected it is still in flight is a+ // refusal, not a route swap — the server re-validates the accepted route+ // against the saved one. Say so here rather than letting the turn fail with+ // no explanation on the page that offered the edit.+ const savedPreset = session ? findMindThinkingPreset(presets, session.presetId) : null;+ const routeDrifted = Boolean(session?.resolvable && savedPreset && !sameMindRoute(session, savedPreset));+ const lastTemporary = temporaryMindTurns(turnExecutions).slice(-1)[0] || null;+ const queuedTemporary = state?.queuedTemporaryMessageCount || 0;++ return (+ <section aria-label="Thinking route" className="rounded-2xl border border-port-border bg-port-card p-4">+ <div className="flex items-center justify-between gap-3">+ <div>+ <p className="text-[11px] font-semibold uppercase tracking-[0.16em] text-port-text-muted">Thinking route</p>+ <h3 className="mt-1 text-base font-semibold text-port-text">+ {session ? 'Temporary session' : 'Default profile'}+ </h3>+ </div>+ <Route size={16} className="shrink-0 text-port-text-muted" aria-hidden="true" />+ </div>++ <dl className="mt-3 space-y-2 text-xs">+ <div>+ <dt className="text-port-text-muted">Default</dt>+ <dd className="mt-0.5"><MindRouteBadge route={defaultRoute} provider={defaultProvider} /></dd>+ </div>+ <div>+ <dt className="text-port-text-muted">Now</dt>+ <dd className="mt-0.5">+ {activeRoute+ ? <MindRouteBadge route={activeRoute} provider={activeProvider} />+ : <span className="text-port-text-muted">Idle — the next wake uses the default.</span>}+ </dd>+ </div>+ </dl>++ {session && (+ <p className="mt-2 rounded border border-port-accent/40 bg-port-accent/5 px-2 py-1.5 text-[11px] text-port-text">+ Borrowing <span className="font-medium">{session.label || session.presetId}</span> for this turn only.+ {!session.resolvable && ' Its saved route is no longer valid, so this turn will be refused rather than answered on another model.'}+ {routeDrifted && ' That preset has been edited since this message was accepted, so this turn will be refused — send a new message to authorize its new route.'}+ </p>+ )}++ {queuedTemporary > 0 && (+ <p className="mt-2 text-[11px] text-port-text-muted">+ {queuedTemporary} queued message{queuedTemporary === 1 ? '' : 's'} {queuedTemporary === 1 ? 'is' : 'are'} waiting on a borrowed route.+ </p>+ )}++ {lastTemporary && (+ <button+ type="button"+ onClick={() => onInspectSession?.(lastTemporary.turnId)}+ className="mt-3 block w-full rounded border border-port-border px-2 py-1.5 text-left text-[11px] text-port-text-muted hover:border-port-accent/60 hover:text-port-text"+ >+ Last temporary session · {formatMindCallOutcome(mindTurnOutcome(lastTemporary))} · {formatMindElapsed(mindTurnElapsedMs(lastTemporary))}+ </button>+ )}++ <div className="mt-3 flex flex-wrap gap-2">+ {selectedPresetId && (+ <button+ type="button"+ onClick={() => onReturnToDefault?.()}+ className="flex min-h-[32px] items-center gap-1.5 rounded border border-port-border px-2.5 text-[11px] text-port-text hover:bg-port-border/30"+ >+ <RotateCcw size={12} aria-hidden="true" /> Return to default+ </button>+ )}+ {session && (+ <button+ type="button"+ onClick={() => onCancelSession?.()}+ disabled={cancelPending}+ className="flex min-h-[32px] items-center gap-1.5 rounded border border-port-warning/50 px-2.5 text-[11px] text-port-warning hover:bg-port-warning/10 disabled:opacity-50"+ >+ <CircleStop size={12} aria-hidden="true" /> {cancelPending ? 'Cancelling…' : 'Cancel this session'}+ </button>+ )}+ </div>+ {session && (+ <p className="mt-2 text-[11px] text-port-text-muted">+ Cancelling pauses the mind and retires this session instead of requeueing it — a cancelled temporary turn never replays itself. Send a new message to run it again.+ </p>+ )}+ </section>+ );+}diff --git a/client/src/components/cos/PersistentMindSessions.jsx b/client/src/components/cos/PersistentMindSessions.jsxnew file mode 100644index 0000000000..8a87301e06--- /dev/null+++ b/client/src/components/cos/PersistentMindSessions.jsx@@ -0,0 +1,175 @@+import { ArrowLeft } from 'lucide-react';+import { formatDateTime } from '../../utils/formatters';+import {+ formatMindCallOutcome,+ formatMindCallUsage,+ formatMindElapsed,+ formatMindRoute,+ mindTurnElapsedMs,+ mindTurnOutcome,+ temporaryMindTurns,+} from '../../lib/mindThinkingPresets.js';+import MindRouteBadge from './MindRouteBadge.jsx';++const OUTCOME_TONE = Object.freeze({+ completed: 'text-port-success',+ failed: 'text-port-error',+ denied: 'text-port-warning',+ interrupted: 'text-port-warning',+ running: 'text-port-accent',+});++const outcomeTone = (outcome) => OUTCOME_TONE[outcome] || 'text-port-text-muted';++/**+ * Provenance for the turns that borrowed a temporary route.+ *+ * Every value here comes from a receipt the server wrote at the moment of the+ * call, never from the composer's intent: the preset that was selected, the+ * route the call ACTUALLY took, its run id, its wall time, and whatever usage+ * the provider reported. When the provider reported nothing, this says so —+ * a missing token count is rendered as unknown, never as zero, because "free"+ * and "not measured" are different claims about the user's money.+ *+ * `selectedTurnId` is owned by the URL, so one session is directly linkable+ * from the route panel and from a shared address.+ */+export default function PersistentMindSessions({+ turnExecutions = [],+ providers = [],+ selectedTurnId = null,+ onSelectTurn,+}) {+ const sessions = temporaryMindTurns(turnExecutions).slice().reverse();+ const selected = selectedTurnId+ ? sessions.find((turn) => turn.turnId === selectedTurnId) || null+ : null;++ if (selectedTurnId) {+ return (+ <section aria-labelledby="mind-session-heading" className="space-y-3">+ <button+ type="button"+ onClick={() => onSelectTurn?.(null)}+ className="flex min-h-[36px] items-center gap-1.5 rounded border border-port-border px-2.5 text-xs text-port-text hover:bg-port-border/30"+ >+ <ArrowLeft size={13} aria-hidden="true" /> All sessions+ </button>+ <h3 id="mind-session-heading" className="text-sm font-semibold text-port-text">Session provenance</h3>+ {selected ? <SessionDetail turn={selected} providers={providers} /> : (+ <p className="text-xs text-port-text-muted">+ This session is no longer in the retained execution history. Its receipts age out with the trajectory window.+ </p>+ )}+ </section>+ );+ }++ return (+ <section aria-labelledby="mind-sessions-heading" className="space-y-3">+ <div>+ <h3 id="mind-sessions-heading" className="text-sm font-semibold text-port-text">Temporary sessions</h3>+ <p className="mt-1 text-xs text-port-text-muted">+ What each borrowed route actually did — the route taken, how long it ran, and what the provider reported spending. Telemetry a provider never reported is shown as unknown, not as zero.+ </p>+ </div>+ {sessions.length === 0 ? (+ <p className="rounded border border-dashed border-port-border px-3 py-4 text-center text-xs text-port-text-muted">+ No message has borrowed an alternate model yet.+ </p>+ ) : (+ <ul aria-label="Temporary thinking sessions" className="space-y-2">+ {sessions.map((turn) => {+ const outcome = mindTurnOutcome(turn);+ return (+ <li key={turn.turnId}>+ <button+ type="button"+ onClick={() => onSelectTurn?.(turn.turnId)}+ className="w-full rounded border border-port-border bg-port-bg px-3 py-2 text-left hover:border-port-accent/60"+ >+ <span className="flex flex-wrap items-center justify-between gap-2">+ <span className="truncate text-sm font-medium text-port-text">+ {turn.calls?.[0]?.thinkingPresetLabel || turn.thinkingPresetId || 'Temporary session'}+ </span>+ <span className={`shrink-0 text-[11px] font-medium ${outcomeTone(outcome)}`}>{formatMindCallOutcome(outcome)}</span>+ </span>+ <MindRouteBadge+ route={{ providerId: turn.providerId, model: turn.model, effort: turn.effort }}+ provider={providers.find((provider) => provider.id === turn.providerId) || null}+ className="mt-1"+ showBilling={false}+ />+ <span className="mt-1 block text-[11px] text-port-text-muted">+ {turn.startedAt ? formatDateTime(turn.startedAt) : 'Start time unknown'} · {formatMindElapsed(mindTurnElapsedMs(turn))}+ </span>+ </button>+ </li>+ );+ })}+ </ul>+ )}+ </section>+ );+}++function SessionDetail({ turn, providers }) {+ const outcome = mindTurnOutcome(turn);+ const calls = Array.isArray(turn.calls) ? turn.calls : [];+ return (+ <div className="space-y-4">+ <dl className="grid grid-cols-1 gap-2 text-xs sm:grid-cols-2">+ <Field label="Preset">{turn.calls?.[0]?.thinkingPresetLabel || turn.thinkingPresetId || 'Unknown'}</Field>+ <Field label="Outcome"><span className={outcomeTone(outcome)}>{formatMindCallOutcome(outcome)}</span></Field>+ <Field label="Route">+ <MindRouteBadge+ route={{ providerId: turn.providerId, model: turn.model, effort: turn.effort }}+ provider={providers.find((provider) => provider.id === turn.providerId) || null}+ showBilling={false}+ />+ </Field>+ <Field label="Elapsed">{formatMindElapsed(mindTurnElapsedMs(turn))}</Field>+ <Field label="Started">{turn.startedAt ? formatDateTime(turn.startedAt) : 'Unknown'}</Field>+ <Field label="Completed">{turn.completedAt ? formatDateTime(turn.completedAt) : 'Not recorded'}</Field>+ <Field label="Turn id"><span className="break-all font-mono">{turn.turnId || 'Unknown'}</span></Field>+ </dl>++ <div>+ <h4 className="text-xs font-semibold uppercase tracking-wide text-port-accent">Provider calls</h4>+ {calls.length === 0 ? (+ <p className="mt-2 text-xs text-port-text-muted">No provider call was recorded for this turn.</p>+ ) : (+ <ul className="mt-2 space-y-2">+ {calls.map((call, index) => (+ <li key={call.eventId || `${turn.turnId}-${index}`} className="rounded border border-port-border bg-port-bg px-3 py-2 text-[11px]">+ <p className="flex flex-wrap items-center justify-between gap-2">+ <span className="font-medium text-port-text">+ {call.purpose || 'call'}{call.round === null || call.round === undefined ? '' : ` · round ${call.round}`}+ </span>+ <span className={outcomeTone(call.outcome)}>{formatMindCallOutcome(call.outcome)}</span>+ </p>+ <p className="mt-1 font-mono text-port-text-muted">+ {formatMindRoute({ providerId: call.providerId, model: call.model, effort: call.effort })}+ </p>+ <p className="mt-1 text-port-text-muted">+ {formatMindElapsed(call.elapsedMs)} · {formatMindCallUsage(call.usage)}+ </p>+ <p className="mt-1 break-all text-port-text-muted">Run {call.runId || 'unknown'}</p>+ {call.reason && <p className="mt-1 text-port-warning">{call.reason}</p>}+ </li>+ ))}+ </ul>+ )}+ </div>+ </div>+ );+}++function Field({ label, children }) {+ return (+ <div>+ <dt className="text-port-text-muted">{label}</dt>+ <dd className="mt-0.5 text-port-text">{children}</dd>+ </div>+ );+}diff --git a/client/src/components/cos/PersistentMindTemporaryRoute.jsx b/client/src/components/cos/PersistentMindTemporaryRoute.jsxnew file mode 100644index 0000000000..eb0997b9ac--- /dev/null+++ b/client/src/components/cos/PersistentMindTemporaryRoute.jsx@@ -0,0 +1,104 @@+import { useId } from 'react';+import { RotateCcw, Settings2, TriangleAlert } from 'lucide-react';+import { classifyMindRouteBilling, findMindThinkingPreset } from '../../lib/mindThinkingPresets.js';+import MindRouteBadge from './MindRouteBadge.jsx';++/**+ * The composer's "Send with another model" affordance.+ *+ * It only ever DISPLAYS and SELECTS: choosing or previewing a preset makes no+ * provider call, starts nothing, and resumes nothing. Authorization happens on+ * the send itself, one message at a time, which is why the send button below it+ * spells out the borrowed route rather than saying "Send".+ *+ * The selected id is owned by the URL (`?preset=`), so a composed alternate is+ * shareable and survives a reload — and so clearing it after a successful send+ * is a single navigation rather than hidden component state that could drift+ * out of sync with what the next message will actually use.+ */+export default function PersistentMindTemporaryRoute({+ presets = [],+ providers = [],+ selectedPresetId = null,+ onSelectPreset,+ onManagePresets,+ disabled = false,+ paused = false,+ imageCount = 0,+}) {+ const selectId = useId();+ const selected = findMindThinkingPreset(presets, selectedPresetId);+ // A selection the saved list no longer contains is NOT a reason to fall back+ // to the default route — that is exactly the silent substitution the whole+ // feature exists to prevent. Say so and refuse to send until it is resolved.+ const missing = Boolean(selectedPresetId) && selected === null;+ const provider = selected ? providers.find((candidate) => candidate.id === selected.providerId) || null : null;+ const billing = classifyMindRouteBilling(provider);++ if (presets.length === 0 && !missing) {+ return null;+ }++ return (+ <div className="mb-2 space-y-2">+ <div className="flex flex-wrap items-center gap-2">+ <label htmlFor={selectId} className="text-[11px] font-medium text-port-text-muted">Send with another model</label>+ <select+ id={selectId}+ value={missing ? '' : selectedPresetId || ''}+ disabled={disabled}+ onChange={(event) => onSelectPreset?.(event.target.value || null)}+ className="min-h-[32px] max-w-full flex-1 rounded border border-port-border bg-port-bg px-2 py-1 text-xs text-port-text disabled:cursor-not-allowed disabled:opacity-50 sm:flex-none"+ >+ <option value="">Default profile (unchanged)</option>+ {presets.map((preset) => <option key={preset.id} value={preset.id}>{preset.label}</option>)}+ </select>+ {selectedPresetId && (+ <button+ type="button"+ onClick={() => onSelectPreset?.(null)}+ disabled={disabled}+ className="flex min-h-[32px] items-center gap-1 rounded border border-port-border px-2 text-[11px] text-port-text hover:bg-port-border/30 disabled:opacity-50"+ >+ <RotateCcw size={12} aria-hidden="true" /> Return to default+ </button>+ )}+ <button+ type="button"+ onClick={() => onManagePresets?.()}+ className="flex min-h-[32px] items-center gap-1 rounded border border-port-border px-2 text-[11px] text-port-text-muted hover:bg-port-border/30 hover:text-port-text"+ >+ <Settings2 size={12} aria-hidden="true" /> Manage+ </button>+ </div>++ {missing && (+ <p role="alert" className="flex items-start gap-1.5 rounded border border-port-error/40 bg-port-error/10 px-2 py-1.5 text-[11px] text-port-error">+ <TriangleAlert size={12} className="mt-0.5 shrink-0" aria-hidden="true" />+ That preset is no longer saved. Choose another or return to the default profile — this message will not be sent on a substitute model.+ </p>+ )}++ {selected && (+ <div className="rounded border border-port-accent/40 bg-port-accent/5 px-2 py-1.5">+ <p className="text-[11px] font-medium text-port-text">This one message runs on {selected.label}</p>+ <MindRouteBadge route={selected} provider={provider} className="mt-1" />+ <p className="mt-1 text-[11px] text-port-text-muted">+ {billing.detail} The next message and every scheduled wake use the unchanged default.+ </p>+ {billing.spendsAccount && (+ <p className="mt-1 text-[11px] text-port-warning">Sending is what authorizes this route — nothing runs until you press send.</p>+ )}+ {paused && (+ <p className="mt-1 text-[11px] text-port-text-muted">The mind is paused. This message queues on the selected route and only runs once you resume it.</p>+ )}+ {imageCount > 0 && (+ <p className="mt-1 text-[11px] text-port-text-muted">+ {imageCount === 1 ? 'The attached image is' : `All ${imageCount} attached images are`} checked against this route, not the default one. A text-only model refuses the message rather than dropping the image.+ </p>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/cos/PersistentMindThinkingPresets.jsx b/client/src/components/cos/PersistentMindThinkingPresets.jsxnew file mode 100644index 0000000000..098d902f3f--- /dev/null+++ b/client/src/components/cos/PersistentMindThinkingPresets.jsx@@ -0,0 +1,287 @@+import { useEffect, useId, useState } from 'react';+import { Check, Pencil, Plus, Trash2, X } from 'lucide-react';+import useProviderModels from '../../hooks/useProviderModels';+import * as api from '../../services/api';+import { classifyMindRouteBilling, formatMindRoute, mintMindPresetId } from '../../lib/mindThinkingPresets.js';+import MindRouteBadge, { BILLING_TONE } from './MindRouteBadge.jsx';+import ProviderModelSelector from '../ProviderModelSelector';+import toast from '../ui/Toast';++const MAX_PRESETS = 20;+const LABEL_MAX = 80;++const emptyDraft = () => ({ id: null, label: '', providerId: '', model: '', effort: '' });++/**+ * Manage the saved alternates a single Persistent Mind message may borrow.+ *+ * Everything here is inert: the whole list is written through+ * `PATCH /api/cos/config`, which never starts the mind, never resumes a paused+ * one, never infers, and never downloads a model. A list PATCH replaces the+ * whole array by design — there is no way to express "remove one entry" as a+ * merge, and a merge would resurrect a preset the user just deleted.+ *+ * `editingPresetId` is owned by the URL so an open editor is shareable and+ * survives a reload, per the "selection lives in the URL" convention.+ */+export default function PersistentMindThinkingPresets({+ presets = [],+ disabled = false,+ editingPresetId = null,+ onEditPreset,+ onSaved,+ onSavingChange,+}) {+ const labelId = useId();+ const {+ providers,+ availableModels,+ loading: providersLoading,+ setSelectedProviderId,+ setSelectedModel,+ } = useProviderModels({ allowDefault: true, withEffort: true, silent: true });+ const [draft, setDraft] = useState(emptyDraft);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState(null);++ const editingPreset = editingPresetId && editingPresetId !== 'new'+ ? presets.find((candidate) => candidate.id === editingPresetId) || null+ : null;++ // The editor's identity comes from the URL, so a deep link opens straight+ // into it and a stale id (a preset deleted in another tab) closes the editor+ // instead of silently editing a different preset.+ //+ // Keyed on the edited preset's own FIELDS rather than on the `presets` array:+ // the caller re-derives that array on every render, so an array dependency+ // would re-run this on every render — and each run replaces the draft object,+ // which re-renders. That is an unbounded loop whenever the parent's fetch has+ // not settled, which is exactly when the panel is first mounted.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ useEffect(() => {+ if (editingPresetId === null) {+ setDraft(emptyDraft());+ setError(null);+ return;+ }+ if (editingPresetId === 'new') {+ setDraft(emptyDraft());+ setError(null);+ setSelectedProviderId('');+ setSelectedModel('');+ return;+ }+ if (!editingPreset) {+ setError('That preset is no longer saved.');+ setDraft(emptyDraft());+ return;+ }+ setError(null);+ setDraft({ ...editingPreset, label: editingPreset.label || '', effort: editingPreset.effort || '' });+ setSelectedProviderId(editingPreset.providerId);+ setSelectedModel(editingPreset.model);+ // Setter identity is not stable across every host that mocks the provider+ // hook, so this effect describes the SELECTION change only.+ }, [+ editingPresetId,+ editingPreset?.label,+ editingPreset?.providerId,+ editingPreset?.model,+ editingPreset?.effort,+ ]);++ const persist = async (nextPresets, successMessage) => {+ setSaving(true);+ onSavingChange?.(true);+ setError(null);+ try {+ await api.updateCosConfig(+ { persistentMindThinkingPresets: { presets: nextPresets } },+ { silent: true },+ );+ toast.success(successMessage);+ onSaved?.(nextPresets);+ return true;+ } catch (saveError) {+ // The list is the user's authority over which routes exist; a failed write+ // must leave the visible list exactly as the server still has it, never a+ // half-applied local copy that a later send would try to use.+ setError(saveError?.message || 'The preset list was not saved');+ return false;+ } finally {+ setSaving(false);+ onSavingChange?.(false);+ }+ };++ const submit = async (event) => {+ event.preventDefault();+ if (saving || !draft.providerId || !draft.model) return;+ const isNew = draft.id === null;+ if (isNew && presets.length >= MAX_PRESETS) {+ setError(`Only ${MAX_PRESETS} presets can be saved. Remove one first.`);+ return;+ }+ const label = draft.label.trim().slice(0, LABEL_MAX);+ const id = draft.id || mintMindPresetId(label || `${draft.providerId}-${draft.model}`, presets.map((preset) => preset.id));+ const next = {+ id,+ label: label || formatMindRoute({ providerId: draft.providerId, model: draft.model }),+ providerId: draft.providerId,+ model: draft.model,+ effort: draft.effort || '',+ };+ const nextPresets = isNew+ ? [...presets, next]+ : presets.map((preset) => (preset.id === id ? next : preset));+ if (await persist(nextPresets, isNew ? 'Thinking preset saved' : 'Thinking preset updated')) {+ onEditPreset?.(null);+ }+ };++ const remove = async (preset) => {+ if (saving) return;+ if (await persist(presets.filter((candidate) => candidate.id !== preset.id), 'Thinking preset removed')) {+ if (editingPresetId === preset.id) onEditPreset?.(null);+ }+ };++ const draftProvider = providers.find((provider) => provider.id === draft.providerId) || null;+ const draftBilling = classifyMindRouteBilling(draftProvider);+ const editorOpen = editingPresetId !== null;+ const atCapacity = presets.length >= MAX_PRESETS;++ return (+ <section aria-labelledby="mind-presets-heading" className="space-y-3">+ <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">+ <div>+ <h3 id="mind-presets-heading" className="text-sm font-semibold text-port-text">Thinking presets</h3>+ <p className="mt-1 text-xs text-port-text-muted">+ Saved alternates a single message can borrow for one turn. The mind still wakes on its default profile above — saving or previewing a preset never starts a turn, resumes a paused mind, or downloads a model.+ </p>+ </div>+ {!editorOpen && (+ <button+ type="button"+ onClick={() => onEditPreset?.('new')}+ disabled={disabled || saving || atCapacity}+ className="flex min-h-[36px] shrink-0 items-center gap-1.5 rounded border border-port-border px-3 text-sm text-port-text hover:bg-port-border/30 disabled:cursor-not-allowed disabled:opacity-50"+ >+ <Plus size={15} aria-hidden="true" /> Add preset+ </button>+ )}+ </div>++ {error && <p role="alert" className="rounded border border-port-error/40 bg-port-error/10 px-3 py-2 text-xs text-port-error">{error}</p>}++ {presets.length === 0 && !editorOpen ? (+ <p className="rounded border border-dashed border-port-border px-3 py-4 text-center text-xs text-port-text-muted">+ No alternates saved. Add one to unlock “Send with another model” in the composer.+ </p>+ ) : (+ <ul aria-label="Saved thinking presets" className="space-y-2">+ {presets.map((preset) => {+ const provider = providers.find((candidate) => candidate.id === preset.providerId) || null;+ return (+ <li key={preset.id} className="flex flex-col gap-2 rounded border border-port-border bg-port-bg px-3 py-2 sm:flex-row sm:items-center sm:justify-between">+ <div className="min-w-0">+ <p className="truncate text-sm font-medium text-port-text">{preset.label}</p>+ <MindRouteBadge route={preset} provider={provider} className="mt-0.5" />+ </div>+ <div className="flex shrink-0 gap-2">+ <button+ type="button"+ onClick={() => onEditPreset?.(preset.id)}+ disabled={disabled || saving}+ aria-label={`Edit ${preset.label}`}+ className="flex min-h-[36px] min-w-[36px] items-center justify-center rounded border border-port-border text-port-text hover:bg-port-border/30 disabled:opacity-50"+ >+ <Pencil size={14} aria-hidden="true" />+ </button>+ <button+ type="button"+ onClick={() => remove(preset)}+ disabled={disabled || saving}+ aria-label={`Remove ${preset.label}`}+ className="flex min-h-[36px] min-w-[36px] items-center justify-center rounded border border-port-border text-port-error hover:bg-port-error/10 disabled:opacity-50"+ >+ <Trash2 size={14} aria-hidden="true" />+ </button>+ </div>+ </li>+ );+ })}+ </ul>+ )}++ {editorOpen && (+ <form onSubmit={submit} aria-label={draft.id ? 'Edit thinking preset' : 'Add thinking preset'} className="space-y-3 rounded border border-port-accent/40 bg-port-card p-3">+ <div>+ <label htmlFor={labelId} className="block text-sm font-medium text-port-text">Preset name</label>+ <input+ id={labelId}+ type="text"+ value={draft.label}+ maxLength={LABEL_MAX}+ disabled={disabled || saving}+ onChange={(event) => setDraft((current) => ({ ...current, label: event.target.value }))}+ placeholder="Deep think"+ className="mt-1 w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-port-text disabled:opacity-50"+ />+ </div>+ <ProviderModelSelector+ providers={providers}+ selectedProviderId={draft.providerId}+ selectedModel={draft.model}+ availableModels={availableModels}+ effort={draft.effort}+ loading={providersLoading}+ disabled={disabled || saving}+ emptyProviderOption="Select an AI provider"+ emptyModelOption="Select a model"+ alwaysShowModel+ highlightToolUse+ layout="stacked"+ label="AI provider"+ onProviderChange={(providerId) => {+ setSelectedProviderId(providerId);+ setSelectedModel('');+ setDraft((current) => ({ ...current, providerId, model: '', effort: '' }));+ }}+ onModelChange={(model) => {+ setSelectedModel(model);+ setDraft((current) => ({ ...current, model }));+ }}+ onEffortChange={(effort) => setDraft((current) => ({ ...current, effort }))}+ />+ {draft.providerId && draft.model && (+ <div className={`rounded border px-3 py-2 text-xs ${BILLING_TONE[draftBilling.billing]}`}>+ <p className="font-semibold">{draftBilling.label}</p>+ <p className="mt-0.5">{draftBilling.detail}</p>+ </div>+ )}+ <p className="text-xs text-port-text-muted">+ A preset is an exact route. If its model or effort later disappears, the message that selected it is refused rather than answered on another model.+ </p>+ <div className="flex flex-wrap gap-2">+ <button+ type="submit"+ disabled={disabled || saving || !draft.providerId || !draft.model}+ className="flex min-h-[36px] items-center gap-1.5 rounded bg-port-accent px-3 text-sm font-medium text-white disabled:cursor-not-allowed disabled:opacity-50"+ >+ <Check size={15} aria-hidden="true" /> {saving ? 'Saving…' : draft.id ? 'Save preset' : 'Add preset'}+ </button>+ <button+ type="button"+ onClick={() => onEditPreset?.(null)}+ disabled={saving}+ className="flex min-h-[36px] items-center gap-1.5 rounded border border-port-border px-3 text-sm text-port-text hover:bg-port-border/30 disabled:opacity-50"+ >+ <X size={15} aria-hidden="true" /> Cancel+ </button>+ </div>+ </form>+ )}+ </section>+ );+}diff --git a/client/src/components/cos/PersistentMindThinkingPresets.test.jsx b/client/src/components/cos/PersistentMindThinkingPresets.test.jsxnew file mode 100644index 0000000000..1d10b1e4b9--- /dev/null+++ b/client/src/components/cos/PersistentMindThinkingPresets.test.jsx@@ -0,0 +1,75 @@+import { useState } from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++const api = vi.hoisted(() => ({+ getProviders: vi.fn(),+ updateCosConfig: vi.fn(),+}));+const localLlm = vi.hoisted(() => ({ getToolUseModels: vi.fn() }));++vi.mock('../../services/api', () => api);+vi.mock('../../services/apiLocalLlm', () => localLlm);++import PersistentMindThinkingPresets from './PersistentMindThinkingPresets.jsx';++const PRESET = {+ id: 'deep-think', label: 'Deep think', providerId: 'example-cloud', model: 'example-large', effort: 'high',+};++// The Mind page re-derives this list from each `GET /api/cos/mind` response and+// re-renders on a 10s runtime poll and on every socket event — so the array+// identity changes while the editor is open, with identical CONTENTS. A host+// that rebuilds it on every render reproduces that faithfully.+const RefetchingHost = () => {+ const [tick, setTick] = useState(0);+ return (+ <div>+ <button type="button" onClick={() => setTick(tick + 1)}>Refresh</button>+ <PersistentMindThinkingPresets+ presets={[{ ...PRESET }]}+ editingPresetId="deep-think"+ onEditPreset={() => {}}+ />+ </div>+ );+};++describe('PersistentMindThinkingPresets', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ api.getProviders.mockResolvedValue({+ activeProvider: 'example-cloud',+ providers: [{ id: 'example-cloud', name: 'Example Cloud', enabled: true, type: 'api', hasApiKey: true, models: ['example-large'] }],+ });+ api.updateCosConfig.mockResolvedValue({ success: true });+ localLlm.getToolUseModels.mockResolvedValue({ models: [] });+ });++ it('keeps an in-progress edit when the host re-derives an unchanged preset list', async () => {+ const user = userEvent.setup();+ render(<RefetchingHost />);++ await waitFor(() => expect(screen.getByDisplayValue('Deep think')).toBeTruthy());+ await user.clear(screen.getByLabelText('Preset name'));+ await user.type(screen.getByLabelText('Preset name'), 'Renamed while typing');+ await user.click(screen.getByRole('button', { name: 'Refresh' }));++ // A refresh that changed nothing must not reset the field under the user.+ expect(screen.getByLabelText('Preset name').value).toBe('Renamed while typing');+ });++ it('reports a deep link to a preset that is no longer saved instead of editing another', async () => {+ render(+ <PersistentMindThinkingPresets+ presets={[PRESET]}+ editingPresetId="removed"+ onEditPreset={() => {}}+ />,+ );++ await waitFor(() => expect(screen.getByText('That preset is no longer saved.')).toBeTruthy());+ expect(screen.queryByDisplayValue('Deep think')).toBeNull();+ });+});diff --git a/client/src/components/cos/tabs/MindTab.jsx b/client/src/components/cos/tabs/MindTab.jsxindex c65fea719c..495d3e37fc 100644--- a/client/src/components/cos/tabs/MindTab.jsx+++ b/client/src/components/cos/tabs/MindTab.jsx@@ -4,6 +4,7 @@ import { ArrowUp, Brain, Check, CirclePause, CirclePlay, Cpu, Database, Eraser,import { Link } from 'react-router';import { useAutoRefetch } from '../../../hooks/useAutoRefetch.js';import useMounted from '../../../hooks/useMounted';+import useProviderModels from '../../../hooks/useProviderModels';import { useSocket } from '../../../hooks/useSocket';import { uuidv4 } from '../../../lib/uuid.js';import * as api from '../../../services/api';@@ -16,9 +17,14 @@ import TabPills from '../../ui/TabPills';import PersistentMindContextPanel from '../PersistentMindContextPanel';import PersistentMindMaintenancePanel from '../PersistentMindMaintenancePanel';import PersistentMindProfileControls from '../PersistentMindProfileControls';+import PersistentMindRoutePanel from '../PersistentMindRoutePanel';import PersistentMindRuntimePanel, { PersistentMindThoughtStatus } from '../PersistentMindRuntimePanel';+import PersistentMindSessions from '../PersistentMindSessions';+import PersistentMindTemporaryRoute from '../PersistentMindTemporaryRoute';+import PersistentMindThinkingPresets from '../PersistentMindThinkingPresets';import PersistentMindVisibilityPanel from '../PersistentMindVisibilityPanel';import PersistentMindTools from '../../../pages/PersistentMindTools';+import { findMindThinkingPreset } from '../../../lib/mindThinkingPresets.js';import { readFileAsBase64, UPLOAD_IMAGE_ACCEPT, validateImageFile } from '../../../utils/fileUpload';const PAGE_LIMIT = 200;@@ -26,12 +32,17 @@ const MAX_BACKFILL_PAGES = 5;const MAX_VISIBLE_EVENTS = PAGE_LIMIT * MAX_BACKFILL_PAGES;const MAX_MESSAGE_IMAGES = 8;const MAX_MESSAGE_IMAGE_BYTES = 10 * 1024 * 1024;-const MIND_PANELS = new Set(['context', 'memories', 'maintenance', 'tools', 'settings']);+// Stable empties: these feed child props and effect dependencies, so a fresh+// literal on every render would re-fire work that has nothing new to do.+const NO_PRESETS = Object.freeze([]);+const NO_TURN_EXECUTIONS = Object.freeze([]);+const MIND_PANELS = new Set(['context', 'memories', 'maintenance', 'tools', 'models', 'settings']);const MIND_PANEL_TABS = [{ id: 'context', label: 'Context', icon: Brain },{ id: 'memories', label: 'Memories', icon: Database },{ id: 'maintenance', label: 'Cleanup', icon: Eraser },{ id: 'tools', label: 'Tools', icon: Wrench },+ { id: 'models', label: 'Models', icon: Cpu },{ id: 'settings', label: 'Settings', icon: Settings2 },];@@ -154,6 +165,13 @@ export default function MindTab() {const legacyView = searchParams.get('view');const requestedPanel = searchParams.get('panel') || (legacyView === 'setup' ? 'settings' : legacyView);const activePanel = MIND_PANELS.has(requestedPanel) ? requestedPanel : null;+ // Composer selection, preset editor, and inspected session all live in the+ // URL: an armed alternate model is shareable and survives a reload, and+ // clearing it after a send is one navigation rather than hidden state that+ // could drift from what the next message will actually use.+ const selectedPresetId = searchParams.get('preset') || null;+ const editingPresetId = searchParams.get('presetEdit');+ const selectedTurnId = searchParams.get('turn') || null;const socket = useSocket();const [events, setEvents] = useState(null);const [mind, setMind] = useState(null);@@ -174,6 +192,7 @@ export default function MindTab() {const [lifecycleError, setLifecycleError] = useState(null);const [profileSaving, setProfileSaving] = useState(false);const [capabilitiesSaving, setCapabilitiesSaving] = useState(false);+ const [presetsSaving, setPresetsSaving] = useState(false);const [contextRefreshKey, setContextRefreshKey] = useState(0);const [visitedPanels, setVisitedPanels] = useState(() => new Set(activePanel ? [activePanel] : []));const [showActivity, setShowActivity] = useState(false);@@ -188,6 +207,9 @@ export default function MindTab() {// the audio itself is carried by /voice/call-host in another tab.const [callState, setCallState] = useState(null);const [hangingUp, setHangingUp] = useState(false);+ // Read-only catalog: it classifies a route as machine-local or+ // account-backed before the user commits. Never a provider probe.+ const { providers } = useProviderModels({ allowDefault: true, silent: true });const cursorRef = useRef(null);const loadPendingRef = useRef(false);const deferredLoadRef = useRef(false);@@ -200,6 +222,10 @@ export default function MindTab() {const runtimeMountedRef = useMounted();const messageDraftIdRef = useRef(null);const messageDraftImagesRef = useRef(null);+ // `undefined` = the in-flight draft has not frozen a route yet; `null` = it+ // deliberately froze "no preset". A plain null would conflate the two and let+ // a retry silently re-resolve a selection the user had since changed.+ const messageDraftPresetRef = useRef(undefined);const annotationDraftIdRef = useRef(null);const messageListRef = useRef(null);const stickToBottomRef = useRef(true);@@ -241,6 +267,8 @@ export default function MindTab() {capabilities: response.capabilities,imageCapability: response.imageCapability,autonomyMode: response.autonomyMode,+ thinkingPresets: response.thinkingPresets?.presets || NO_PRESETS,+ turnExecutions: response.turnExecutions || NO_TURN_EXECUTIONS,});page += 1;needsMore = response.hasMore === true && !sawGap;@@ -388,20 +416,52 @@ export default function MindTab() {event.preventDefault();const trimmed = messageText.trim();if ((!trimmed && messageImages.length === 0) || submitting || messageImagesUploading) return;+ // A selection whose preset has since disappeared is refused here rather+ // than sent without it: falling through to the home profile would answer on+ // exactly the model the user was deliberately stepping away from.+ if (selectedPresetId && !selectedPreset) {+ setSubmitError('That thinking preset is no longer saved. Choose another or return to the default profile.');+ return;+ }const id = messageDraftIdRef.current || mintId('message');messageDraftIdRef.current = id;const images = messageDraftImagesRef.current || messageImages;messageDraftImagesRef.current = images;+ // The route is frozen with the draft, so a duplicate click or a transport+ // retry re-submits the id AND the route the user approved — the server's+ // fingerprint covers both, so a changed selection would otherwise read as a+ // different, separately-billable request under a reused id.+ if (messageDraftPresetRef.current === undefined) {+ messageDraftPresetRef.current = selectedPreset+ ? {+ id: selectedPreset.id,+ label: selectedPreset.label,+ providerId: selectedPreset.providerId,+ model: selectedPreset.model,+ effort: selectedPreset.effort || '',+ }+ : null;+ }+ const thinkingPreset = messageDraftPresetRef.current;setSubmitting(true);setSubmitError(null);try {- await api.sendPersistentMindMessage({ id, text: trimmed, ...(images.length > 0 ? { images: images.map((image) => image.attachmentId) } : {}) }, { silent: true });+ await api.sendPersistentMindMessage({+ id,+ text: trimmed,+ ...(images.length > 0 ? { images: images.map((image) => image.attachmentId) } : {}),+ ...(thinkingPreset ? { thinkingPresetId: thinkingPreset.id, thinkingPreset } : {}),+ }, { silent: true });stickToBottomRef.current = true;appendLocalInput({ id, content: trimmed, inputKind: 'message', images });setMessageText('');setMessageImages([]);messageDraftIdRef.current = null;messageDraftImagesRef.current = null;+ messageDraftPresetRef.current = undefined;+ // One message, one authorization: the composer returns to the default+ // route so the next message and every scheduled wake use the home profile.+ if (thinkingPreset) clearPresetSelection();await loadHistory();stickToBottomRef.current = true;void loadRuntime();@@ -433,10 +493,15 @@ export default function MindTab() {}};+ const resetMessageDraft = () => {+ messageDraftIdRef.current = null;+ messageDraftImagesRef.current = null;+ messageDraftPresetRef.current = undefined;+ };+const changeMessageText = (next) => {if (submitError) {- messageDraftIdRef.current = null;- messageDraftImagesRef.current = null;+ resetMessageDraft();setSubmitError(null);}setMessageText(next);@@ -444,8 +509,7 @@ export default function MindTab() {const changeMessageImages = (next) => {if (submitError) {- messageDraftIdRef.current = null;- messageDraftImagesRef.current = null;+ resetMessageDraft();setSubmitError(null);}setMessageImages(next);@@ -565,19 +629,31 @@ export default function MindTab() {.filter(([key, value]) => key !== 'schemaVersion' && value === true).length;const { status: imageCapabilityStatus, guidance: imageCapabilityGuidance } = imageCapability(mind);const imageAttachmentsUnavailable = imageCapabilityStatus === 'unsupported';- const setupSaving = profileSaving || capabilitiesSaving;+ const setupSaving = profileSaving || capabilitiesSaving || presetsSaving;const conversationItems = buildConversationItems(events || [], showActivity);+ const thinkingPresets = mind?.thinkingPresets || NO_PRESETS;+ const turnExecutions = mind?.turnExecutions || NO_TURN_EXECUTIONS;+ const selectedPreset = findMindThinkingPreset(thinkingPresets, selectedPresetId);+ // Panel-scoped selections (the open preset editor, the inspected session) are+ // dropped whenever the panel they render in goes away; the composer's armed+ // preset is NOT — it belongs to the message being written, not to a panel.+ const clearPanelSelections = (params) => {+ params.delete('presetEdit');+ params.delete('turn');+ };const openPanel = (panel) => setSearchParams((current) => {const next = new URLSearchParams(current);next.set('panel', panel);next.delete('view');next.delete('event');+ clearPanelSelections(next);return next;});const closePanel = () => setSearchParams((current) => {const next = new URLSearchParams(current);next.delete('panel');next.delete('view');+ clearPanelSelections(next);return next;});const selectEvent = (eventId) => setSearchParams((current) => {@@ -585,6 +661,33 @@ export default function MindTab() {next.set('event', eventId);next.delete('panel');next.delete('view');+ clearPanelSelections(next);+ return next;+ });+ const setMindParam = (key, value) => setSearchParams((current) => {+ const next = new URLSearchParams(current);+ if (value === null) next.delete(key);+ else next.set(key, value);+ return next;+ });+ const clearPresetSelection = () => setMindParam('preset', null);+ // Changing the armed route retires the in-flight draft id: the server's retry+ // fingerprint covers the selection, so reusing one id across two routes is a+ // different request wearing the same idempotency key.+ const selectPreset = (presetId) => {+ if (submitting) return;+ resetMessageDraft();+ setSubmitError(null);+ setMindParam('preset', presetId || null);+ };+ const inspectSession = (turnId) => setSearchParams((current) => {+ const next = new URLSearchParams(current);+ next.set('panel', 'models');+ next.delete('view');+ next.delete('event');+ next.delete('presetEdit');+ if (turnId === null) next.delete('turn');+ else next.set('turn', turnId);return next;});const closeSelectedEvent = () => setSearchParams((current) => {@@ -717,6 +820,16 @@ export default function MindTab() {))}</ul>)}+ <PersistentMindTemporaryRoute+ presets={thinkingPresets}+ providers={providers}+ selectedPresetId={selectedPresetId}+ onSelectPreset={selectPreset}+ onManagePresets={() => openPanel('models')}+ disabled={submitting}+ paused={isPaused}+ imageCount={messageImages.length}+ /><div className="flex items-end gap-2 rounded-[1.35rem] border border-port-border bg-port-bg p-1.5 pl-3 focus-within:border-port-accent/70 focus-within:ring-1 focus-within:ring-port-accent/30"><FilePickerButtonaccept={UPLOAD_IMAGE_ACCEPT}@@ -731,7 +844,7 @@ export default function MindTab() {</FilePickerButton><label htmlFor="mind-input-text" className="sr-only">Message</label><textarea id="mind-input-text" value={messageText} onChange={(event) => changeMessageText(event.target.value)} onKeyDown={handleMessageKeyDown} maxLength={8000} rows={1} className="min-h-[36px] max-h-32 flex-1 resize-y bg-transparent py-2 text-sm leading-5 text-port-text outline-none placeholder:text-port-text-muted" placeholder="Message Persistent Mind" />- <button type="submit" disabled={(!messageText.trim() && messageImages.length === 0) || submitting || messageImagesUploading} aria-label={submitting ? 'Sending message' : submitError ? 'Retry' : 'Send message'} className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-port-accent text-white transition-colors hover:bg-port-accent/85 disabled:cursor-not-allowed disabled:bg-port-border disabled:text-port-text-muted">+ <button type="submit" disabled={(!messageText.trim() && messageImages.length === 0) || submitting || messageImagesUploading} aria-label={submitting ? 'Sending message' : submitError ? 'Retry' : selectedPreset ? `Send with ${selectedPreset.label}` : 'Send message'} title={selectedPreset ? `Send this one message with ${selectedPreset.label}` : undefined} className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-white transition-colors disabled:cursor-not-allowed disabled:bg-port-border disabled:text-port-text-muted ${selectedPreset ? 'bg-port-warning hover:bg-port-warning/85' : 'bg-port-accent hover:bg-port-accent/85'}`}>{submitting ? <RefreshCw size={17} className="animate-spin" aria-hidden="true" /> : <ArrowUp size={19} strokeWidth={2.5} aria-hidden="true" />}</button></div>@@ -763,6 +876,19 @@ export default function MindTab() {)}</section>+ <PersistentMindRoutePanel+ profile={mind?.profile}+ state={state}+ providers={providers}+ presets={thinkingPresets}+ turnExecutions={turnExecutions}+ selectedPresetId={selectedPresetId}+ onReturnToDefault={clearPresetSelection}+ onCancelSession={() => runLifecycle('pause')}+ cancelPending={lifecyclePending === 'pause'}+ onInspectSession={inspectSession}+ />+<div className="grid grid-cols-2 gap-2 xl:grid-cols-1"><MindStateButton icon={Brain} label="Context" value={runtime?.context?.approximateTokens == null ? 'Unavailable' : `~${runtime.context.approximateTokens.toLocaleString()} tokens`} detail={`${runtime?.context?.chars?.toLocaleString() || '—'} characters`} onClick={() => openPanel('context')} /><MindStateButton icon={Database} label="Memories" value={runtime?.context?.memoryCount == null ? 'Unavailable' : `${runtime.context.memoryCount} accessible`} detail="Created and curated" onClick={() => openPanel('memories')} />@@ -816,6 +942,22 @@ export default function MindTab() {{(visitedPanels.has('tools') || activePanel === 'tools') && <div hidden={activePanel !== 'tools'}><PersistentMindTools onCapabilitiesChange={(capabilities) => setMind((current) => current ? { ...current, capabilities } : current)} onSavingChange={setCapabilitiesSaving} /></div>}+ {(visitedPanels.has('models') || activePanel === 'models') && <div hidden={activePanel !== 'models'} className="space-y-6">+ <PersistentMindThinkingPresets+ presets={thinkingPresets}+ disabled={!mind}+ editingPresetId={editingPresetId}+ onEditPreset={(id) => setMindParam('presetEdit', id)}+ onSaved={(presets) => setMind((current) => current ? { ...current, thinkingPresets: presets } : current)}+ onSavingChange={setPresetsSaving}+ />+ <PersistentMindSessions+ turnExecutions={turnExecutions}+ providers={providers}+ selectedTurnId={selectedTurnId}+ onSelectTurn={(turnId) => setMindParam('turn', turnId)}+ />+ </div>}{(visitedPanels.has('settings') || activePanel === 'settings') && <section hidden={activePanel !== 'settings'} aria-labelledby="mind-profile-heading" className="rounded border border-port-border bg-port-card p-4"><div className="mb-3"><h3 id="mind-profile-heading" className="text-sm font-semibold text-port-text">AI profile</h3>diff --git a/client/src/components/cos/tabs/MindTab.temporaryRoute.test.jsx b/client/src/components/cos/tabs/MindTab.temporaryRoute.test.jsxnew file mode 100644index 0000000000..2a9d76ed0e--- /dev/null+++ b/client/src/components/cos/tabs/MindTab.temporaryRoute.test.jsx@@ -0,0 +1,312 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { render, screen, waitFor, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { MemoryRouter } from 'react-router';++const api = vi.hoisted(() => ({+ getPersistentMind: vi.fn(),+ sendPersistentMindMessage: vi.fn(),+ uploadPersistentMindAttachment: vi.fn(),+ deletePersistentMindAttachment: vi.fn(),+ addPersistentMindAnnotation: vi.fn(),+ startPersistentMind: vi.fn(),+ pausePersistentMind: vi.fn(),+ resumePersistentMind: vi.fn(),+ stopPersistentMind: vi.fn(),+ acknowledgePersistentMindEvent: vi.fn(),+ promotePersistentMindEvent: vi.fn(),+ getProviders: vi.fn(),+ updateCosConfig: vi.fn(),+ getPersistentMindContext: vi.fn(),+ getPersistentMindTools: vi.fn(),+ getPersistentMindRuntime: vi.fn(),+ getPersistentMindVisibility: vi.fn(),+ createPersistentMindMemory: vi.fn(),+ updatePersistentMindMemory: vi.fn(),+ cleanupPersistentMind: vi.fn(),+}));++const socket = vi.hoisted(() => {+ const handlers = new Map();+ return {+ on: vi.fn((event, handler) => handlers.set(event, handler)),+ off: vi.fn((event) => handlers.delete(event)),+ emit: vi.fn(),+ reset: () => handlers.clear(),+ };+});+const localLlm = vi.hoisted(() => ({+ getLocalLlmStatus: vi.fn(),+ getToolUseModels: vi.fn(),+}));++vi.mock('../../../services/api', () => api);+vi.mock('../../../services/apiLocalLlm', () => localLlm);+vi.mock('../../../hooks/useSocket', () => ({ useSocket: () => socket }));++import MindTab from './MindTab';++const DEEP_PRESET = {+ id: 'deep-think',+ label: 'Deep think',+ providerId: 'example-cloud',+ model: 'example-large',+ effort: 'high',+};++const runtime = {+ observedAt: '2026-09-01T12:00:00.000Z',+ inference: { active: false, providerId: 'local-llm', model: 'example-small', residency: { status: 'provider-managed', backend: null, loaded: null, memoryBytes: null } },+ context: { chars: 19, maxChars: 32_000, approximateTokens: 5, summaryState: 'empty', memoryCount: 0 },+ system: {+ memory: { total: 8 * 1024 ** 3, used: 4 * 1024 ** 3, free: 4 * 1024 ** 3, usagePercent: 50 },+ process: { rss: 1, heapUsed: 1, heapTotal: 2 },+ cpu: { cores: 8, loadAvg1m: 1 },+ },+};++const response = (overrides = {}) => ({+ events: [],+ cursor: null,+ gap: false,+ hasMore: false,+ truncated: false,+ turnExecutions: [],+ state: {+ enabled: true,+ started: true,+ status: 'waiting',+ pauseReason: null,+ queuedMessageCount: 0,+ queuedTemporaryMessageCount: 0,+ activeTurnId: null,+ activeRoute: null,+ activeThinkingSession: null,+ },+ profile: { enabled: true, providerId: 'local-llm', model: 'example-small', effort: '', thinkingInterface: 'text', wakeIntervalMinutes: 30 },+ thinkingPresets: { schemaVersion: 1, presets: [DEEP_PRESET] },+ capabilities: { schemaVersion: 3, createTasks: false, manageMind: false, readPortos: false, writePortos: false },+ imageCapability: { status: 'supported', guidance: null },+ autonomyMode: 'execute',+ ...overrides,+});++const renderTab = (path = '/cos/mind') => render(+ <MemoryRouter initialEntries={[path]}>+ <MindTab />+ </MemoryRouter>+);++const composerLoaded = async () => {+ await waitFor(() => expect(screen.getByLabelText('Send with another model')).toBeTruthy());+};++describe('MindTab temporary thinking sessions', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ socket.reset();+ api.getPersistentMind.mockResolvedValue(response());+ api.sendPersistentMindMessage.mockResolvedValue({ success: true, duplicate: false });+ api.pausePersistentMind.mockResolvedValue({ success: true });+ api.getPersistentMindRuntime.mockResolvedValue(runtime);+ api.getPersistentMindVisibility.mockResolvedValue({+ schemaVersion: 1, capturedAt: '2026-09-01T12:00:00.000Z',+ freshness: { state: 'fresh', ageMs: 0, ttlMs: 30_000 }, readiness: 'ready', truncated: false, workspaces: [],+ });+ api.getProviders.mockResolvedValue({+ activeProvider: 'local-llm',+ providers: [+ { id: 'local-llm', name: 'Local LLM', enabled: true, type: 'api', endpoint: 'http://127.0.0.1:11434', models: ['example-small'] },+ { id: 'example-cloud', name: 'Example Cloud', enabled: true, type: 'api', hasApiKey: true, models: ['example-large'] },+ ],+ });+ api.updateCosConfig.mockResolvedValue({ success: true });+ localLlm.getLocalLlmStatus.mockResolvedValue({ ollama: { models: [] }, lmstudio: { models: [] } });+ localLlm.getToolUseModels.mockResolvedValue({ models: [] });+ });++ it('previews the exact borrowed route without making any execution call', async () => {+ const user = userEvent.setup();+ renderTab();+ await composerLoaded();++ await user.selectOptions(screen.getByLabelText('Send with another model'), 'deep-think');++ await waitFor(() => expect(screen.getByText('This one message runs on Deep think')).toBeTruthy());+ expect(screen.getAllByText('Example Cloud / example-large · high').length).toBeGreaterThan(0);+ // Account-backed routing is named, and nothing has run.+ expect(screen.getAllByText('Account-backed').length).toBeGreaterThan(0);+ expect(api.sendPersistentMindMessage).not.toHaveBeenCalled();+ expect(api.startPersistentMind).not.toHaveBeenCalled();+ expect(api.resumePersistentMind).not.toHaveBeenCalled();+ });++ it('keeps a paused mind paused while previewing, and says the message will queue', async () => {+ const user = userEvent.setup();+ api.getPersistentMind.mockResolvedValue(response({+ state: { ...response().state, status: 'paused', pauseReason: 'Paused by user' },+ }));+ renderTab();+ await composerLoaded();++ await user.selectOptions(screen.getByLabelText('Send with another model'), 'deep-think');++ await waitFor(() => expect(screen.getByText(/The mind is paused\./)).toBeTruthy());+ expect(api.resumePersistentMind).not.toHaveBeenCalled();+ expect(api.startPersistentMind).not.toHaveBeenCalled();+ expect(api.sendPersistentMindMessage).not.toHaveBeenCalled();+ });++ it('submits the displayed selection for one message and then returns to the default', async () => {+ const user = userEvent.setup();+ renderTab();+ await composerLoaded();++ await user.selectOptions(screen.getByLabelText('Send with another model'), 'deep-think');+ await user.type(screen.getByLabelText('Message'), 'Reason carefully.');+ await user.click(screen.getByRole('button', { name: 'Send with Deep think' }));++ await waitFor(() => expect(api.sendPersistentMindMessage).toHaveBeenCalledTimes(1));+ const [body] = api.sendPersistentMindMessage.mock.calls[0];+ expect(body.thinkingPresetId).toBe('deep-think');+ expect(body.thinkingPreset).toEqual(DEEP_PRESET);++ // Acceptance clears the composer: the very next message is an ordinary one.+ await waitFor(() => expect(screen.getByLabelText('Send message')).toBeTruthy());+ await user.type(screen.getByLabelText('Message'), 'And now normally.');+ await user.click(screen.getByRole('button', { name: 'Send message' }));++ await waitFor(() => expect(api.sendPersistentMindMessage).toHaveBeenCalledTimes(2));+ const [second] = api.sendPersistentMindMessage.mock.calls[1];+ expect(second.thinkingPresetId).toBeUndefined();+ expect(second.thinkingPreset).toBeUndefined();+ });++ it('refuses to send a selection the saved list no longer contains', async () => {+ const user = userEvent.setup();+ renderTab('/cos/mind?preset=removed-preset');+ await composerLoaded();++ await waitFor(() => expect(screen.getByText(/no longer saved/)).toBeTruthy());+ await user.type(screen.getByLabelText('Message'), 'Should not be sent on a substitute.');+ await user.click(screen.getByRole('button', { name: 'Send message' }));++ await waitFor(() => expect(screen.getByText(/That thinking preset is no longer saved/)).toBeTruthy());+ expect(api.sendPersistentMindMessage).not.toHaveBeenCalled();+ });++ it('retries a failed send with the same id and the same route', async () => {+ const user = userEvent.setup();+ api.sendPersistentMindMessage.mockRejectedValueOnce(new Error('Network unavailable'));+ renderTab();+ await composerLoaded();++ await user.selectOptions(screen.getByLabelText('Send with another model'), 'deep-think');+ await user.type(screen.getByLabelText('Message'), 'Reason carefully.');+ await user.click(screen.getByRole('button', { name: 'Send with Deep think' }));++ await waitFor(() => expect(screen.getByText(/Network unavailable/)).toBeTruthy());+ await user.click(screen.getByRole('button', { name: 'Retry' }));++ await waitFor(() => expect(api.sendPersistentMindMessage).toHaveBeenCalledTimes(2));+ const [first] = api.sendPersistentMindMessage.mock.calls[0];+ const [second] = api.sendPersistentMindMessage.mock.calls[1];+ expect(second.id).toBe(first.id);+ expect(second.thinkingPreset).toEqual(first.thinkingPreset);+ });++ it('shows the actual running route beside the default and cancels through the lifecycle API', async () => {+ const user = userEvent.setup();+ api.getPersistentMind.mockResolvedValue(response({+ state: {+ ...response().state,+ status: 'thinking',+ activeTurnId: 'turn-1',+ activeRoute: { providerId: 'example-cloud', model: 'example-large', effort: 'high' },+ activeThinkingSession: {+ presetId: 'deep-think', label: 'Deep think', providerId: 'example-cloud', model: 'example-large', effort: 'high', resolvable: true,+ },+ },+ }));+ renderTab();++ const panel = await screen.findByRole('region', { name: 'Thinking route' });+ await waitFor(() => expect(within(panel).getByText('Local LLM / example-small')).toBeTruthy());+ expect(within(panel).getByText('Example Cloud / example-large · high')).toBeTruthy();+ expect(within(panel).getByText(/Borrowing/)).toBeTruthy();++ await user.click(within(panel).getByRole('button', { name: /Cancel this session/ }));+ await waitFor(() => expect(api.pausePersistentMind).toHaveBeenCalledTimes(1));+ });++ it('saves a new preset as a whole-list replacement without running anything', async () => {+ const user = userEvent.setup();+ renderTab('/cos/mind?panel=models&presetEdit=new');++ await waitFor(() => expect(screen.getByLabelText('Preset name')).toBeTruthy());+ await user.type(screen.getByLabelText('Preset name'), 'Fast local');+ await user.selectOptions(screen.getByLabelText('AI provider'), 'local-llm');+ await user.selectOptions(screen.getByLabelText('Model'), 'example-small');+ await user.click(screen.getByRole('button', { name: /Add preset/ }));++ await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledTimes(1));+ const [config] = api.updateCosConfig.mock.calls[0];+ expect(config.persistentMindThinkingPresets.presets).toEqual([+ DEEP_PRESET,+ { id: 'fast-local', label: 'Fast local', providerId: 'local-llm', model: 'example-small', effort: '' },+ ]);+ // Saving a route is inert: it never wakes, resumes, or sends anything.+ expect(api.startPersistentMind).not.toHaveBeenCalled();+ expect(api.resumePersistentMind).not.toHaveBeenCalled();+ expect(api.sendPersistentMindMessage).not.toHaveBeenCalled();+ });++ it('removes a preset by replacing the list, never by merging a deletion', async () => {+ const user = userEvent.setup();+ renderTab('/cos/mind?panel=models');++ await waitFor(() => expect(screen.getByRole('button', { name: 'Remove Deep think' })).toBeTruthy());+ await user.click(screen.getByRole('button', { name: 'Remove Deep think' }));++ await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledTimes(1));+ expect(api.updateCosConfig.mock.calls[0][0].persistentMindThinkingPresets.presets).toEqual([]);+ });++ it('deep-links one session receipt and reports unreported usage as unknown', async () => {+ api.getPersistentMind.mockResolvedValue(response({+ turnExecutions: [{+ turnId: 'turn-1',+ status: 'completed',+ startedAt: '2026-09-01T12:00:00.000Z',+ completedAt: '2026-09-01T12:00:03.000Z',+ providerId: 'example-cloud',+ model: 'example-large',+ effort: 'high',+ thinkingPresetId: 'deep-think',+ calls: [{+ eventId: 'call-1',+ at: '2026-09-01T12:00:00.000Z',+ purpose: 'turn',+ round: 0,+ runId: 'run-1',+ providerId: 'example-cloud',+ model: 'example-large',+ effort: 'high',+ thinkingPresetId: 'deep-think',+ thinkingPresetLabel: 'Deep think',+ temporaryRoute: true,+ elapsedMs: 3_000,+ outcome: 'completed',+ reason: null,+ usage: { state: 'unknown', source: 'unavailable', inputTokens: null, outputTokens: null, totalTokens: null, costUsd: null },+ }],+ }],+ }));+ renderTab('/cos/mind?panel=models&turn=turn-1');++ await waitFor(() => expect(screen.getByText('Session provenance')).toBeTruthy());+ expect(screen.getByText('Run run-1')).toBeTruthy();+ expect(screen.getByText(/Usage unknown/)).toBeTruthy();+ expect(screen.getAllByText('Completed').length).toBeGreaterThan(0);+ });+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex eae605c7fe..4c105b65bc 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -180,6 +180,7 @@ grep -i "what you want to do" client/src/lib/README.md| `lookaheadTransport.js` | Shared lookahead-transport state machine for the synth players (#2493) — `createLookaheadTransport({ getTotalSec, scheduleWindow, prepare?, seekCursors?, onStop?, onEnded?, onTeardown? })` owns the Web Audio clock + live-node lifecycle (playing / interval / startTime / offsetSec / nodes / playToken, the `resumeAudioContext()` call with the teardown-race guard, the optional `audioSession` claim held for exactly as long as the transport sounds, `track()` node pruning, and the play / pause / stop / seek / position transitions); each player supplies only the scheduling + notify callbacks and stays a thin scheduler over it, so a fix to the token-guard race or teardown lands in one place. Also the single source of the `SYNTH_TIMING` lookahead constants (`LEAD`/`LOOKAHEAD_MS`/`SCHEDULE_AHEAD`) `scorePlayback`/`midiPlayback` share. No React, no score/MIDI concepts — imports only the shared `AudioContext`. || `lossSparkline.js` | `lossSparklineGeometry(series, box)` — projects an unbounded training-loss series (`{step,loss}[]`) into SVG polyline coords, normalized to its own min/max (unlike `editorialHealth.sparklineGeometry`'s fixed 0–100 axis). Returns `{ points, coords, last, min, max }`. Drives the Render Queue's training-row loss curve (#1408). No React. || `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. || `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.jsindex 286d13348a..33c80e0375 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -144,6 +144,7 @@ export * from './episodeSceneImport.js';export * from './lookaheadTransport.js';export * from './lossSparkline.js';export * from './metronome.js';+export * from './mindThinkingPresets.js';export * from './navFeatures.js';export * from './midiChords.js';export * from './midiNotes.js';diff --git a/client/src/lib/mindThinkingPresets.js b/client/src/lib/mindThinkingPresets.jsnew file mode 100644index 0000000000..5dd9803360--- /dev/null+++ b/client/src/lib/mindThinkingPresets.js@@ -0,0 +1,237 @@+/**+ * Presentation helpers for the Persistent Mind's temporary thinking sessions.+ *+ * The mechanism (saved presets, exact-or-refuse resolution, per-call receipts)+ * lives on the server. This module answers only the questions the Mind page has+ * to answer BEFORE the user commits: what exact route is about to be borrowed,+ * whether taking it can spend an account, and — afterwards — what a receipt+ * actually says versus what the provider never reported.+ *+ * Everything here is pure: no fetches, no provider probes. Previewing a preset+ * must never contact a provider, so the classification is deliberately a+ * READ of the already-loaded provider record, not a capability call.+ */++import { formatRuntime } from '../utils/formatters.js';+import {+ credentialSource,+ isApiProvider,+ isLocalInstanceProvider,+ isOllamaBackedProvider,+ isPrivateNetworkEndpoint,+ localBackendForProvider,+} from '../utils/providers.js';++/**+ * How a route is paid for, as far as the client can prove from the provider+ * record alone.+ *+ * - `local` — a daemon the user hosts, on this machine or elsewhere inside the+ * private network. Running it spends no vendor account.+ * - `account` — a stored key, an inherited gateway key, a credential env var,+ * or a vendor subscription stands behind it.+ * - `unknown` — cannot be determined. Treated as account-backed everywhere it+ * matters, because guessing "free" is the one direction that costs money.+ */+export const MIND_ROUTE_BILLING = Object.freeze({+ LOCAL: 'local',+ ACCOUNT: 'account',+ UNKNOWN: 'unknown',+});++const isLocalBackedRecord = (provider) => Boolean(+ localBackendForProvider(provider) || isOllamaBackedProvider(provider)+ || provider?.llamaBacked === true || provider?.mtplxBacked === true+ || provider?.vllmBacked === true || provider?.sglangBacked === true,+);++/**+ * Does the inference run on hardware the user owns?+ *+ * Deliberately NOT `isLocalInstanceProvider` alone: that helper reads a BLANK+ * endpoint as local, which is right for an `ollama` record (every default it+ * falls back to is a loopback URL) and badly wrong for a cloud API provider+ * whose endpoint is implied by its id — calling that one free is exactly the+ * mistake this classification exists to prevent. So a bare API provider must+ * name a private-network endpoint, while a record already identified as a local+ * backend (or a CLI/TUI wrapper fronting one) may leave it blank.+ */+const isSelfHostedRoute = (provider) => (+ (isApiProvider(provider) && isPrivateNetworkEndpoint(provider?.endpoint))+ || (isLocalBackedRecord(provider)+ && (isLocalInstanceProvider(provider) || isPrivateNetworkEndpoint(provider?.endpoint)))+);++/**+ * Classify what sending on this provider can spend.+ *+ * @param {object|null|undefined} provider - a provider record from `GET /api/providers`+ * @returns {{billing: string, label: string, detail: string, spendsAccount: boolean}}+ */+export function classifyMindRouteBilling(provider) {+ if (!provider) {+ return {+ billing: MIND_ROUTE_BILLING.UNKNOWN,+ label: 'Routing unknown',+ detail: 'This provider is not in the current catalog, so PortOS cannot say whether sending spends an account. Treat it as billable.',+ spendsAccount: true,+ };+ }+ if (isSelfHostedRoute(provider)) {+ return {+ billing: MIND_ROUTE_BILLING.LOCAL,+ label: 'Local model',+ detail: 'Runs on hardware you host. Sending spends no account credit.',+ spendsAccount: false,+ };+ }+ if (credentialSource(provider).kind !== 'none') {+ return {+ billing: MIND_ROUTE_BILLING.ACCOUNT,+ label: 'Account-backed',+ detail: 'Backed by a credential or vendor subscription. Sending can use paid quota.',+ spendsAccount: true,+ };+ }+ return {+ billing: MIND_ROUTE_BILLING.UNKNOWN,+ label: 'Routing unknown',+ detail: 'PortOS cannot tell whether this route runs on your own hardware or against an account. Treat it as billable.',+ spendsAccount: true,+ };+}++/** "provider / model · high" — the one phrasing for an exact borrowed route. */+export function formatMindRoute({ providerId, model, effort } = {}, { providerName = null } = {}) {+ const provider = providerName || providerId || 'Unknown provider';+ const modelText = model || 'Unknown model';+ return `${provider} / ${modelText}${effort ? ` · ${effort}` : ''}`;+}++/**+ * Is this saved preset still exactly the route the composer is displaying?+ *+ * The server refuses a selection whose preset changed after acceptance, so the+ * composer must not offer to send a stale one. Labels are presentation and do+ * not participate — only the exact route does, mirroring+ * `samePersistentMindThinkingSelection` on the server.+ */+export function sameMindRoute(left, right) {+ if (!left || !right) return false;+ return ['providerId', 'model'].every((key) => left[key] === right[key])+ && (left.effort || '') === (right.effort || '');+}++/** Find one saved preset by id, or null. Never falls back to another preset. */+export function findMindThinkingPreset(presets, presetId) {+ if (!presetId) return null;+ return (Array.isArray(presets) ? presets : []).find((preset) => preset.id === presetId) || null;+}++const PRESET_ID_MAX = 64;++/**+ * Mint a stable, server-legal preset id from a label.+ *+ * Must satisfy the server's `^[A-Za-z0-9][A-Za-z0-9_-]*$`. A label that reduces+ * to nothing (emoji, CJK) still gets an id, because refusing to save a preset+ * over its display name would be a worse failure than a generated id.+ */+export function mintMindPresetId(label, existingIds = []) {+ const taken = new Set(existingIds);+ const slug = String(label || '')+ .normalize('NFKD')+ .replace(/[^A-Za-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .toLowerCase()+ .slice(0, PRESET_ID_MAX - 4);+ const base = /^[A-Za-z0-9]/.test(slug) ? slug : `preset${slug ? `-${slug}` : ''}`;+ if (!taken.has(base)) return base;+ for (let suffix = 2; suffix < 1000; suffix += 1) {+ const candidate = `${base}-${suffix}`.slice(0, PRESET_ID_MAX);+ if (!taken.has(candidate)) return candidate;+ }+ return `${base}-${Date.now()}`.slice(0, PRESET_ID_MAX);+}++/**+ * Render a call receipt's usage block.+ *+ * `state: 'unknown'` is a real answer — the provider reported nothing — and it+ * must read as unknown rather than as a free call. Never coerce a missing count+ * or price to zero.+ */+export function formatMindCallUsage(usage) {+ if (usage?.state !== 'reported') return 'Usage unknown';+ const parts = [];+ if (usage.totalTokens !== null && usage.totalTokens !== undefined) {+ parts.push(`${usage.totalTokens.toLocaleString()} tokens`);+ } else if (usage.inputTokens !== null && usage.inputTokens !== undefined) {+ parts.push(`${usage.inputTokens.toLocaleString()} in`);+ }+ if (usage.costUsd !== null && usage.costUsd !== undefined) {+ parts.push(`$${usage.costUsd.toFixed(4)}`);+ }+ return parts.length > 0 ? parts.join(' · ') : 'Usage unknown';+}++/**+ * Wall time of a call or turn — "Elapsed unknown" when nothing measured it.+ *+ * The one phrasing, so the route card and the receipt list cannot disagree+ * about what an unmeasured span reads as. A measured zero is a real value and+ * renders as one.+ */+export function formatMindElapsed(ms) {+ if (!Number.isFinite(ms) || ms < 0) return 'Elapsed unknown';+ return formatRuntime(ms) || '0ms';+}++const OUTCOME_LABELS = Object.freeze({+ completed: 'Completed',+ failed: 'Failed',+ denied: 'Refused',+ interrupted: 'Interrupted',+});++/** Human label for a receipt/turn outcome; an unrecognized value is unknown. */+export function formatMindCallOutcome(outcome) {+ return OUTCOME_LABELS[outcome] || 'Outcome unknown';+}++const TERMINAL_TURN_STATUSES = Object.freeze(['completed', 'failed', 'denied', 'interrupted']);++/**+ * Terminal outcome of one turn, from its own status when it has one and+ * otherwise from its last receipt. A turn that is still running reads as+ * `running`, never as a silent success.+ */+export function mindTurnOutcome(turn) {+ if (TERMINAL_TURN_STATUSES.includes(turn?.status)) return turn.status;+ const calls = Array.isArray(turn?.calls) ? turn.calls : [];+ const last = calls[calls.length - 1];+ if (TERMINAL_TURN_STATUSES.includes(last?.outcome)) return last.outcome;+ return turn?.completedAt ? 'completed' : 'running';+}++/**+ * Wall time of a turn, preferring its own timestamps and falling back to the+ * sum of its receipts. Returns null — never 0 — when neither is available.+ */+export function mindTurnElapsedMs(turn) {+ const startedAt = Date.parse(turn?.startedAt);+ const completedAt = Date.parse(turn?.completedAt);+ if (Number.isFinite(startedAt) && Number.isFinite(completedAt) && completedAt >= startedAt) {+ return completedAt - startedAt;+ }+ const calls = Array.isArray(turn?.calls) ? turn.calls : [];+ const measured = calls.filter((call) => Number.isFinite(call?.elapsedMs));+ return measured.length > 0 ? measured.reduce((total, call) => total + call.elapsedMs, 0) : null;+}++/** Only the turns that borrowed a preset — the ones this page is accountable for. */+export function temporaryMindTurns(turnExecutions) {+ return (Array.isArray(turnExecutions) ? turnExecutions : [])+ .filter((turn) => Boolean(turn?.thinkingPresetId)+ || (Array.isArray(turn?.calls) && turn.calls.some((call) => call?.temporaryRoute === true)));+}diff --git a/client/src/lib/mindThinkingPresets.test.js b/client/src/lib/mindThinkingPresets.test.jsnew file mode 100644index 0000000000..5b4feb49dc--- /dev/null+++ b/client/src/lib/mindThinkingPresets.test.js@@ -0,0 +1,109 @@+import { describe, expect, it } from 'vitest';+import {+ classifyMindRouteBilling,+ formatMindCallUsage,+ mindTurnElapsedMs,+ mindTurnOutcome,+ mintMindPresetId,+ sameMindRoute,+ temporaryMindTurns,+} from './mindThinkingPresets.js';++describe('classifyMindRouteBilling', () => {+ // The composer warns before spending the user's money, so the only failure+ // that matters is calling a billable route free. Every ambiguous shape must+ // therefore land on `spendsAccount: true`.+ it('treats a loopback HTTP backend as spending nothing', () => {+ const verdict = classifyMindRouteBilling({+ id: 'ollama', type: 'api', endpoint: 'http://127.0.0.1:11434',+ });+ expect(verdict.billing).toBe('local');+ expect(verdict.spendsAccount).toBe(false);+ });++ it('treats a canonical local backend with no endpoint as spending nothing', () => {+ // Every default an `ollama`/`lmstudio` record falls back to is a loopback+ // URL, so a blank endpoint on THAT record really is this machine.+ expect(classifyMindRouteBilling({ id: 'lmstudio', type: 'api' }).spendsAccount).toBe(false);+ });++ it('does NOT read a blank-endpoint cloud provider as local', () => {+ // `isLocalInstanceProvider` alone answers "true" here, which would badge a+ // paid vendor API as free — the exact regression this classification exists+ // to prevent.+ const verdict = classifyMindRouteBilling({+ id: 'example-cloud', name: 'Example Cloud', type: 'api', hasApiKey: true,+ });+ expect(verdict.billing).toBe('account');+ expect(verdict.spendsAccount).toBe(true);+ });++ it('reports a vendor CLI with no discoverable credential as unknown, not free', () => {+ const verdict = classifyMindRouteBilling({ id: 'example-cli', name: 'Example CLI', type: 'cli' });+ expect(verdict.billing).toBe('unknown');+ expect(verdict.spendsAccount).toBe(true);+ });++ it('reports a provider missing from the catalog as unknown, not free', () => {+ expect(classifyMindRouteBilling(null).spendsAccount).toBe(true);+ });+});++describe('formatMindCallUsage', () => {+ it('renders an unreported usage block as unknown rather than as zero', () => {+ expect(formatMindCallUsage({+ state: 'unknown', source: 'unavailable', inputTokens: null, outputTokens: null, totalTokens: null, costUsd: null,+ })).toBe('Usage unknown');+ expect(formatMindCallUsage(undefined)).toBe('Usage unknown');+ });++ it('renders a reported zero cost as a real measured value', () => {+ expect(formatMindCallUsage({+ state: 'reported', source: 'provider-reported', inputTokens: 10, outputTokens: 5, totalTokens: 15, costUsd: 0,+ })).toBe('15 tokens · $0.0000');+ });+});++describe('mindTurnOutcome / mindTurnElapsedMs', () => {+ it('reads an unfinished turn as running rather than as a silent success', () => {+ expect(mindTurnOutcome({ turnId: 't', status: 'thinking', calls: [] })).toBe('running');+ expect(mindTurnElapsedMs({ turnId: 't', startedAt: '2026-09-01T00:00:00.000Z', calls: [] })).toBeNull();+ });++ it('falls back to the last receipt when the turn carries no terminal status', () => {+ const turn = { turnId: 't', status: 'thinking', calls: [{ outcome: 'completed', elapsedMs: 40 }, { outcome: 'denied', elapsedMs: 2 }] };+ expect(mindTurnOutcome(turn)).toBe('denied');+ expect(mindTurnElapsedMs(turn)).toBe(42);+ });+});++describe('temporaryMindTurns', () => {+ it('keeps only turns that borrowed a route', () => {+ const turns = [+ { turnId: 'a', calls: [{ temporaryRoute: false }] },+ { turnId: 'b', thinkingPresetId: 'deep', calls: [{ temporaryRoute: true }] },+ { turnId: 'c', calls: [{ temporaryRoute: true }] },+ ];+ expect(temporaryMindTurns(turns).map((turn) => turn.turnId)).toEqual(['b', 'c']);+ });+});++describe('sameMindRoute', () => {+ it('ignores the label but not the effort', () => {+ const base = { providerId: 'p', model: 'm', effort: 'high' };+ expect(sameMindRoute(base, { ...base, label: 'Renamed' })).toBe(true);+ expect(sameMindRoute(base, { ...base, effort: 'low' })).toBe(false);+ expect(sameMindRoute({ providerId: 'p', model: 'm' }, { providerId: 'p', model: 'm', effort: '' })).toBe(true);+ });+});++describe('mintMindPresetId', () => {+ it('produces a server-legal id and never collides with an existing one', () => {+ const pattern = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;+ expect(mintMindPresetId('Deep think')).toBe('deep-think');+ expect(mintMindPresetId('Deep think', ['deep-think'])).toBe('deep-think-2');+ // A label with no ASCII left still has to yield a usable id.+ expect(pattern.test(mintMindPresetId('🧠'))).toBe(true);+ expect(pattern.test(mintMindPresetId('-leading-dash'))).toBe(true);+ });+});diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.mdindex 87dbee9df8..d0ffda4680 100644--- a/docs/features/chief-of-staff.md+++ b/docs/features/chief-of-staff.md@@ -92,6 +92,23 @@ The `selectModelForTask` function routes tasks to appropriate model tiers:| persistentMindThinkingPresets.presets | [] | Saved named alternates (exact provider/model/effort) one message may borrow for a single turn. Empty by default; storing one changes nothing about the route the mind wakes on || avatarStyle | svg | Default CoS UI avatar style (`svg`, `ascii`, `core`, the 3D styles, or a `rigged-<modelId>` record) |+### Temporary thinking sessions in the Mind UI++Saved alternates are managed in **Mind → Models** (`/cos/mind?panel=models`). Adding, editing, previewing, or removing a preset writes only `persistentMindThinkingPresets` through `PATCH /api/cos/config` — it never starts a turn, never resumes a paused mind, never infers, and never downloads a model. A list PATCH replaces the whole array, because a merge cannot express "remove this one entry" and would resurrect a deleted preset.++The composer's **Send with another model** picker arms one preset for the **next single message**, and nothing else:++- The armed preset lives in the URL (`?preset=<id>`), so it is shareable and reload-safe. Previewing shows the exact provider/model/effort plus whether the route is machine-local, account-backed, or unclassifiable — an unclassifiable route is treated as billable.+- **Pressing send is the authorization.** It covers that one message, including its bounded tool rounds and its summary. The selection clears on acceptance, so the next message and every scheduled wake use the unchanged home profile.+- The route is frozen with the draft: a duplicate click or a transport retry re-submits the same id **and** the same route, because the server's retry fingerprint covers both. Changing the armed preset mints a new id instead.+- A preset that disappears is refused, never substituted — the composer blocks the send rather than answering on the default profile the user was stepping away from.+- Attached images are validated against the borrowed route, not the default one, so a text-only alternate refuses the message instead of dropping the image.+- A paused mind stays paused: the message queues on the selected route and runs only when the user resumes it.++**Mind → Thinking route** (the sidebar card) shows the default profile beside the route the current turn is *actually* taking, warns when a preset was edited after its message was accepted, and offers **Return to default**. **Cancel this session** goes through the existing pause lifecycle, which retires a temporary session rather than requeueing it — a cancelled temporary turn never replays itself.++**Mind → Models** also lists the per-session receipts (`?turn=<turnId>`): preset, actual route, elapsed time, run and turn ids, outcome, and usage/cost. Telemetry a provider never reported renders as *unknown*, never as zero — "free" and "not measured" are different claims.+Temporary thinking messages retain the exact accepted provider, model, and effort. Changing or revoking a preset refuses the pending session; a label-only rename preserves its route. Revoked selections and interruptions after inference may have begun require a fresh message to run again. Temporary provider outages before inference leave the accepted message queued. Matching transport retries keep the original selection even after revocation. Older queued temporary messages without a recorded route retain their content but require explicit resubmission.## API Endpointsdiff --git a/server/lib/persistentMindPublic.js b/server/lib/persistentMindPublic.jsindex d054785ba7..ef5f8660b3 100644--- a/server/lib/persistentMindPublic.js+++ b/server/lib/persistentMindPublic.js@@ -1,6 +1,7 @@/** Safe client projection for the machine-local persistent-mind state. */import { nextPersistentMindWakeAt } from './persistentMind.js';+import { normalizePersistentMindThinkingSelection } from './persistentMindThinkingPresets.js';const publicReason = (state) => {if (!state.pauseReason) return null;@@ -9,15 +10,58 @@ const publicReason = (state) => {return 'Waiting for the next eligible wake';};+// The route the claimed turn is ACTUALLY running on, which is not always the+// home profile: a temporary thinking session borrows another one for its single+// turn. A field the claim never recorded stays null rather than falling back to+// the profile — "unknown" and "the default" are different answers to "what is+// this turn spending", and only the caller can decide how to say so.+const publicActiveRoute = (activeTurn) => {+ if (!activeTurn) return null;+ const text = (value) => (typeof value === 'string' && value.trim() ? value.trim() : null);+ return {+ providerId: text(activeTurn.providerId),+ model: text(activeTurn.model),+ effort: text(activeTurn.effort),+ };+};++// The accepted selection carried by the message the active turn is answering.+// Presentation only — consent already happened at admission, and the resolver+// re-validates the route against the saved preset before any provider call.+const publicActiveThinkingSession = (activeTurn) => {+ const message = activeTurn?.wake?.kind === 'message' ? activeTurn.wake.message : null;+ if (!message?.thinkingPresetId) return null;+ const selection = normalizePersistentMindThinkingSelection(message.thinkingPreset);+ return {+ presetId: message.thinkingPresetId,+ // A message whose stored selection no longer validates is exactly the+ // "revoked mid-flight" case the resolver refuses; say so instead of+ // rendering a route the turn will not be allowed to take.+ label: selection?.label || null,+ providerId: selection?.providerId || null,+ model: selection?.model || null,+ effort: selection?.effort ?? null,+ resolvable: selection !== null,+ };+};+export function publicPersistentMindState(state = {}) {const nextWakeAt = nextPersistentMindWakeAt(state);+ const activeTurn = state.activeTurn || null;+ const queuedMessages = Array.isArray(state.queuedMessages) ? state.queuedMessages : [];return {enabled: state.enabled === true,started: state.started === true,status: typeof state.status === 'string' ? state.status : 'unknown',pauseReason: publicReason(state),- queuedMessageCount: Array.isArray(state.queuedMessages) ? state.queuedMessages.length : 0,- activeTurnId: typeof state.activeTurn?.id === 'string' ? state.activeTurn.id : null,+ 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,+ activeRoute: publicActiveRoute(activeTurn),+ activeThinkingSession: publicActiveThinkingSession(activeTurn),lastCompletedTurnId: typeof state.lastCompletedTurnId === 'string' ? state.lastCompletedTurnId : null,lastCompletedAt: typeof state.lastCompletedAt === 'string' ? state.lastCompletedAt : null,nextEligibleWakeAt: typeof state.nextEligibleWakeAt === 'string' ? state.nextEligibleWakeAt : null,diff --git a/server/lib/persistentMindPublic.test.js b/server/lib/persistentMindPublic.test.jsindex 42c9d35b20..e2ca716907 100644--- a/server/lib/persistentMindPublic.test.js+++ b/server/lib/persistentMindPublic.test.js@@ -1,7 +1,41 @@import { describe, expect, it } from 'vitest';-import { createDefaultPersistentMindState } from './persistentMind.js';+import { createDefaultPersistentMindState, normalizePersistentMindState } from './persistentMind.js';import { publicPersistentMindState } from './persistentMindPublic.js';+const selection = {+ id: 'deep-think',+ label: 'Deep think',+ providerId: 'example-provider',+ model: 'example-model',+ effort: 'high',+};++const stateWithActiveTemporaryTurn = (overrides = {}) => normalizePersistentMindState({+ ...createDefaultPersistentMindState(),+ enabled: true,+ started: true,+ status: 'thinking',+ activeTurn: {+ id: 'turn-9',+ startedAt: '2026-09-01T00:00:00.000Z',+ heartbeatAt: '2026-09-01T00:00:05.000Z',+ providerId: 'example-provider',+ model: 'example-model',+ effort: 'high',+ wake: {+ kind: 'message',+ message: {+ id: 'message-9',+ text: 'Think harder about this one.',+ thinkingPresetId: 'deep-think',+ thinkingPreset: selection,+ createdAt: '2026-09-01T00:00:00.000Z',+ },+ },+ },+ ...overrides,+});+describe('public persistent mind state', () => {it('projects the scheduled wake without exposing queued message content', () => {const nextWakeAt = new Date(Date.now() + 15 * 60_000).toISOString();@@ -25,4 +59,100 @@ describe('public persistent mind state', () => {expect(projected).not.toHaveProperty('selfWake');expect(projected).not.toHaveProperty('queuedMessages');});++ it('reports the route a temporary session is actually running on, not the home profile', () => {+ const projected = publicPersistentMindState(stateWithActiveTemporaryTurn());++ expect(projected.activeRoute).toEqual({+ providerId: 'example-provider',+ model: 'example-model',+ effort: 'high',+ });+ expect(projected.activeThinkingSession).toEqual({+ presetId: 'deep-think',+ label: 'Deep think',+ providerId: 'example-provider',+ model: 'example-model',+ effort: 'high',+ resolvable: true,+ });+ // The message body itself must never ride the status payload.+ expect(JSON.stringify(projected)).not.toContain('Think harder');+ });++ it('marks a session whose stored selection no longer validates as unresolvable', () => {+ // `sanitizeMessage` keeps a selected-but-unvalidatable message as a durable+ // record with a null selection, which is exactly the revoked-mid-flight case+ // the resolver refuses. The page must say so instead of rendering a route.+ const state = normalizePersistentMindState({+ ...createDefaultPersistentMindState(),+ enabled: true,+ started: true,+ status: 'thinking',+ activeTurn: {+ id: 'turn-10',+ startedAt: '2026-09-01T00:00:00.000Z',+ heartbeatAt: '2026-09-01T00:00:05.000Z',+ providerId: 'example-provider',+ model: 'example-model',+ effort: 'high',+ wake: {+ kind: 'message',+ message: {+ id: 'message-10',+ text: 'Selection was revoked.',+ thinkingPresetId: 'deep-think',+ thinkingPreset: { ...selection, effort: 'not-a-level' },+ createdAt: '2026-09-01T00:00:00.000Z',+ },+ },+ },+ });++ const projected = publicPersistentMindState(state);++ expect(projected.activeThinkingSession).toMatchObject({+ presetId: 'deep-think',+ resolvable: false,+ providerId: null,+ model: null,+ });+ });++ it('leaves the temporary-session fields null for an ordinary wake', () => {+ const projected = publicPersistentMindState({+ ...createDefaultPersistentMindState(),+ enabled: true,+ started: true,+ status: 'waiting',+ });++ expect(projected.activeRoute).toBeNull();+ expect(projected.activeThinkingSession).toBeNull();+ expect(projected.queuedTemporaryMessageCount).toBe(0);+ });++ it('counts only the queued messages that carry a borrowed route', () => {+ const state = normalizePersistentMindState({+ ...createDefaultPersistentMindState(),+ enabled: true,+ started: true,+ status: 'waiting',+ queuedMessages: [+ { id: 'ordinary', text: 'no preset', createdAt: '2026-09-01T00:00:00.000Z' },+ {+ id: 'borrowed',+ text: 'with preset',+ thinkingPresetId: 'deep-think',+ thinkingPreset: selection,+ createdAt: '2026-09-01T00:00:01.000Z',+ },+ ],+ });++ const projected = publicPersistentMindState(state);++ expect(projected.queuedMessageCount).toBe(2);+ expect(projected.queuedTemporaryMessageCount).toBe(1);+ });});