Skip to content

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

fix: preserve accepted temporary mind model routes (#6283)

[._.]/ Adam Eivyb2a9cf7ac102
diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.md
index 93d2736bf0..0b01eeedec 100644
--- a/docs/features/chief-of-staff.md
+++ b/docs/features/chief-of-staff.md
@@ -92,6 +92,8 @@ 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 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. A refused or interrupted temporary attempt requires a fresh message to run again. 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 Endpoints
| Route | Description |
diff --git a/scripts/migrations/343-persistent-mind-accepted-routes.js b/scripts/migrations/343-persistent-mind-accepted-routes.js
new file mode 100644
index 0000000000..baab19e689
--- /dev/null
+++ b/scripts/migrations/343-persistent-mind-accepted-routes.js
@@ -0,0 +1,36 @@
+/**
+ * Stamp accepted-route support without deriving consent from today's presets.
+ * CoS state remains machine-local runtime state; there is no new store or seed.
+ * Old temporary messages keep their content and get an explicit missing-route
+ * sentinel. Execution refuses them until the user submits a fresh message.
+ */
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import { atomicWrite, safeJSONParse } from '../../server/lib/fileUtils.js';
+
+export default {
+ async up({ rootDir }) {
+ const path = join(rootDir, 'data', 'cos', 'state.json');
+ const raw = await readFile(path, 'utf8').catch((error) => {
+ if (error.code === 'ENOENT') return null;
+ throw error;
+ });
+ if (raw === null) return { updated: 0, reason: 'no-state' };
+ const state = safeJSONParse(raw, null, { logError: false });
+ const mind = state?.persistentMind;
+ if (!mind || typeof mind !== 'object' || Array.isArray(mind)) return { updated: 0, reason: 'no-mind' };
+ if (mind.schemaVersion > 7) return { updated: 0, reason: 'newer-schema' };
+ let changed = mind.schemaVersion !== 7;
+ const markUnverified = (message) => {
+ if (!message?.thinkingPresetId || Object.hasOwn(message, 'thinkingPreset')) return;
+ message.thinkingPreset = null;
+ changed = true;
+ };
+ for (const message of Array.isArray(mind.queuedMessages) ? mind.queuedMessages : []) markUnverified(message);
+ if (mind.activeTurn?.wake?.kind === 'message') markUnverified(mind.activeTurn.wake.message);
+ if (!changed) return { updated: 0, reason: 'already-applied' };
+ mind.schemaVersion = 7;
+ await atomicWrite(path, state);
+ return { updated: 1 };
+ },
+};
diff --git a/scripts/migrations/343-persistent-mind-accepted-routes.test.js b/scripts/migrations/343-persistent-mind-accepted-routes.test.js
new file mode 100644
index 0000000000..d77b2e814e
--- /dev/null
+++ b/scripts/migrations/343-persistent-mind-accepted-routes.test.js
@@ -0,0 +1,62 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import migration from './343-persistent-mind-accepted-routes.js';
+
+let rootDir;
+afterEach(async () => {
+ if (rootDir) await rm(rootDir, { recursive: true, force: true });
+ rootDir = null;
+});
+
+describe('migration 343 accepted thinking routes', () => {
+ it('preserves messages, attachments, pause and unknown fields without inventing temporary authority', async () => {
+ rootDir = await mkdtemp(join(tmpdir(), 'portos-mind-accepted-routes-'));
+ const dir = join(rootDir, 'data', 'cos');
+ await mkdir(dir, { recursive: true });
+ const statePath = join(dir, 'state.json');
+ const configPath = join(dir, 'config.json');
+ const ordinary = { id: 'ordinary', text: 'Keep me', images: [{ attachmentId: 'example-image' }] };
+ const temporary = { id: 'temporary', text: 'Keep this too', thinkingPresetId: 'deep', custom: 'preserved' };
+ const state = {
+ config: { persistentMindProfile: { enabled: false, providerId: 'example', model: 'example-model' } },
+ unknown: { keep: true },
+ persistentMind: {
+ schemaVersion: 6, enabled: true, started: true, status: 'paused', futureField: 'keep',
+ queuedMessages: [ordinary, temporary],
+ activeTurn: { id: 'interrupted', wake: { kind: 'message', message: { ...temporary, id: 'active' } } },
+ recentMessageFingerprints: [{ id: 'completed', fingerprint: 'a'.repeat(64) }],
+ },
+ };
+ await writeFile(statePath, JSON.stringify(state));
+ const config = JSON.stringify({ persistentMindProfile: state.config.persistentMindProfile, persistentMindThinkingPresets: { presets: [] } });
+ await writeFile(configPath, config);
+
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 1 });
+ const migrated = JSON.parse(await readFile(statePath, 'utf8'));
+ expect(migrated).toEqual({
+ ...state,
+ persistentMind: {
+ ...state.persistentMind, schemaVersion: 7,
+ queuedMessages: [ordinary, { ...temporary, thinkingPreset: null }],
+ activeTurn: { ...state.persistentMind.activeTurn, wake: { kind: 'message', message: { ...temporary, id: 'active', thinkingPreset: null } } },
+ },
+ });
+ expect(await readFile(configPath, 'utf8')).toBe(config);
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });
+ });
+
+ it('does not create a state file or replace invalid input or newer state', async () => {
+ rootDir = await mkdtemp(join(tmpdir(), 'portos-mind-route-missing-'));
+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ updated: 0 });
+ const dir = join(rootDir, 'data', 'cos');
+ await mkdir(dir, { recursive: true });
+ const path = join(dir, 'state.json');
+ for (const raw of ['{broken', JSON.stringify({ persistentMind: { schemaVersion: 100, queuedMessages: [{ thinkingPresetId: 'future' }] } })]) {
+ await writeFile(path, raw);
+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ updated: 0 });
+ expect(await readFile(path, 'utf8')).toBe(raw);
+ }
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index a987f9f6d9..9d209fed67 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -51,14 +51,14 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `agentRunReconcile.js` | CoS run reconciliation (#4540) — pure diff between a ledger projection (`projectRunStates`) and the durable run record. Closed finding vocabulary `RUN_RECONCILE_FINDINGS` (`record-open`, `record-missing`, `verdict-mismatch`, `ledger-open`), `diffRunRecord()`, `reconcileRunRecords()` with a zero-filled per-kind summary, and `planRunRecordRepair()` — the metadata patch that closes a record the ledger proves is finished. Repairs are one-directional (ledger → record) by design: a record closed while the ledger missed the close is reported, never back-filled, so the stream stays an audit of the record rather than a copy of it. I/O half: `services/agentRunReconciler.js`. |
| `agentScratchPaths.js` | Runtime scratch PortOS itself writes into an agent worktree and never commits — `PUBLIC_REVIEW_INPUT_FILENAME` / `PUBLIC_REVIEW_PATCH_DIRNAME` (the public-review bundle materialized by `services/modelAbuseGuard.js`), the `AGENT_SCRATCH_PATHS` list, prefix-aware `matchesScratchRoot(path, roots)` and `isAgentScratchPath(path)`. `classifyWorktreeDirt` (`services/worktreeManager.js`) subtracts these for EVERY caller and uses the same matcher for its per-call `ignoredPaths`, so a worktree holding only scratch reads as clean end to end — before this, it was preserved by `removeWorktree`, held by `reapMergedWorktrees`, filed as a repo-state recovery task, and dispatched to a branch-reconcile coordinator, forever. Only STATIC names live here; a run-scoped name like `.agent-done-<agentId>` (`agentSentinel.js`) is passed per call instead. |
| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME`, `doneSentinelName(agentId)` → the per-instance filename `.agent-done-<agentId>` (worktree-less agents share one workspace, so a shared name lets concurrent runs clobber — and finalize on — each other's signal), `doneSentinelPath(workspacePath, agentId)` → the single path every producer and consumer resolves, + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. `extractSentinelPayloadFromTranscript(transcript, isPayload)` (async) is the third tier for programmatic-I/O types ONLY — scans the ANSI-stripped PTY transcript, newest balanced JSON block first, for a payload the model PRINTED instead of writing, and adopts it only if the owning hook's shape predicate accepts it (#3640). `PROGRAMMATIC_OUTPUT_COMPLETION_HEADING` names the briefing section that prints this run's absolute sentinel path — a task-type hook renders its prompt before spawn, so it points the agent at that section by name rather than at a filename it cannot know. |
-| `persistentMind.js` | Pure persistent-CoS-mind runtime state: default-off durable shape, normalization, FIFO-message/self-wake selection, interrupted-wake requeue, image-work rollback guard, bounded exponential backoff, watchdog staleness, and next-wake projection. |
+| `persistentMind.js` | Pure persistent-CoS-mind runtime state: default-off durable shape, normalization, FIFO-message/self-wake selection, interrupted-wake requeue, accepted-route fingerprints/receipts, image-work rollback guard, bounded exponential backoff, watchdog staleness, and next-wake projection. |
| `persistentMindCapabilities.js` | Default-off persistent-mind action grants plus bounded typed CoS-task, private-Eidoverse, and self-cleanup contracts (app/provider/model/effort, PR completion policy, the optional exact provider/model task allowlist, and mind-owned context scopes). |
| `cosToolContracts.js` | Provider-neutral `portos_tool` catalog/call schema version, request-id and per-turn bounds, catalog query formats, and Persistent Mind tool-call shape. |
| `persistentMindTrajectory.js` | Pure persistent-mind trajectory vocabulary, sequence cursor parsing, replay projection, provenance-tagged rollup validation, and hard-budget context assembly with explicit empty/missing/failed/stale summary states. |
| `persistentMindProfile.js` | Versioned, default-off persistent-mind provider profile (`enabled`, provider/model/effort, text interface, maximum quiet interval), its strict API schema, duration resolver, and safe partial-update merge that clears model/effort on a provider switch. |
| `persistentMindPrompt.js` | Editable persistent-mind identity and operating-instructions schema/defaults; saving it never starts inference. |
| `persistentMindPublic.js` | `publicPersistentMindState(state)` — the sole client/socket projection of durable mind state: exposes lifecycle fields, queue count, and the derived next wake time; drops queued message bodies/active wake payloads, and replaces free-form provider errors with coarse safe reasons. |
-| `persistentMindThinkingPresets.js` | Saved named temporary thinking presets for the persistent mind (exact provider/model/effort alternates to its one home profile): default-empty durable shape, normalization that drops half-pinned entries, strict API schema, whole-list replace merge, and preset lookup. Storage only — saving or selecting a preset starts no inference. |
+| `persistentMindThinkingPresets.js` | Saved named temporary thinking presets for the persistent mind (exact provider/model/effort alternates to its one home profile): default-empty durable shape, normalization that drops half-pinned entries, strict API schema, whole-list replace merge, preset lookup, strict accepted-selection schema/normalization, and route equality independent of labels. Storage only — saving or selecting a preset starts no inference. |
| `heavyJobClaim.js` | Cross-process, machine-wide accelerator claim: `claimHeavyLocalJob({ kind, id, timeoutMs? })` either acquires an ephemeral `data/` lock or reports its active holder; dead-PID claims are reclaimed, and a spawned child can take over the recorded PID across a server restart. |
| `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. |
| `quotaBurnConfig.js` | Quota-burn plan shape: the provider families, the burn-job type alphabet + catalog the config page renders its form from, `QUOTA_BURN_BOUNDS` (the one bounds table the normalizer clamps to, the Zod schemas reject against, and the catalog descriptors publish as min/max), and total normalization (`normalizeQuotaBurnConfig`). Owns the dispatch-cap sentinel too (`QUOTA_BURN_UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap`) — -1 means the window is not counted, and is the default. Also owns the queued burn task's description shape (`burnTaskDescription` / `quotaBurnFamilyOfDescription`), shared with migration 225, and the `run once` vocabulary (`quotaBurnJobKey` / `jobIsSpent`, plus the two family predicates `familyIsConfigured` and `familyHasRunnableJobs`). Pure — no storage, no provider I/O. |
diff --git a/server/lib/persistentMind.js b/server/lib/persistentMind.js
index 61d1259273..8ccd17f31f 100644
--- a/server/lib/persistentMind.js
+++ b/server/lib/persistentMind.js
@@ -11,9 +11,12 @@ import { PERSISTENT_MIND_ID } from './persistentMindTrajectory.js';
import { MAX_SCREENSHOT_BYTES } from './uploadLimits.js';
import { sanitizeFilename } from './mimeTypes.js';
import { isSafeFilename } from './pathSafety.js';
-import { asPersistentMindThinkingPresetId } from './persistentMindThinkingPresets.js';
+import {
+ asPersistentMindThinkingPresetId,
+ normalizePersistentMindThinkingSelection,
+} from './persistentMindThinkingPresets.js';
-export const PERSISTENT_MIND_SCHEMA_VERSION = 6;
+export const PERSISTENT_MIND_SCHEMA_VERSION = 7;
export const PERSISTENT_MIND_IMAGE_EXTENSIONS = Object.freeze(['.png', '.jpg', '.jpeg', '.gif', '.webp']);
export const PERSISTENT_MIND_IMAGE_MIME_TYPES = Object.freeze({
@@ -190,15 +193,29 @@ export function persistentMindMessageFingerprint(value) {
.filter(Boolean)
: [];
const thinkingPresetId = asPersistentMindThinkingPresetId(value?.thinkingPresetId);
+ const selection = normalizePersistentMindThinkingSelection(value?.thinkingPreset);
return createHash('sha256')
.update(JSON.stringify({
text: asBoundedString(value?.text, PERSISTENT_MIND_LIMITS.MAX_MESSAGE_CHARS),
images,
...(thinkingPresetId ? { thinkingPresetId } : {}),
+ ...(thinkingPresetId && selection ? {
+ thinkingPreset: { id: selection.id, providerId: selection.providerId, model: selection.model, effort: selection.effort },
+ } : {}),
}))
.digest('hex');
}
+/** Retain the accepted selection so id-only clients can retry after revocation. */
+export function persistentMindMessageReceipt(message) {
+ const selection = normalizePersistentMindThinkingSelection(message?.thinkingPreset);
+ return {
+ id: message.id,
+ fingerprint: persistentMindMessageFingerprint(message),
+ ...(selection ? { thinkingPreset: selection } : {}),
+ };
+}
+
/** Build the safe upload response without exposing claim bookkeeping. */
export function publicPersistentMindAttachment(value) {
const attachment = normalizePersistentMindAttachment(value);
@@ -236,7 +253,12 @@ const sanitizeMessage = (value) => {
// Absent on every ordinary message. Kept on the durable queued/active record
// so a requeue or a restart replays the route the user actually chose,
// instead of quietly answering on the home profile.
- ...(thinkingPresetId ? { thinkingPresetId } : {}),
+ ...(thinkingPresetId || value?.thinkingPresetId || value?.thinkingPreset ? {
+ thinkingPresetId: thinkingPresetId || 'invalid-preset',
+ thinkingPreset: thinkingPresetId
+ ? normalizePersistentMindThinkingSelection(value?.thinkingPreset)
+ : null,
+ } : {}),
createdAt: asIso(value?.createdAt) || new Date(0).toISOString(),
};
};
@@ -344,7 +366,8 @@ export function normalizePersistentMindState(raw) {
const fingerprint = asFingerprint(candidate?.fingerprint);
if (!id || !fingerprint || seenFingerprintIds.has(id)) continue;
seenFingerprintIds.add(id);
- recentMessageFingerprints.push({ id, fingerprint });
+ const selection = normalizePersistentMindThinkingSelection(candidate?.thinkingPreset);
+ recentMessageFingerprints.push({ id, fingerprint, ...(selection ? { thinkingPreset: selection } : {}) });
}
const callHistory = [];
for (const candidate of Array.isArray(source.callHistory) ? source.callHistory : []) {
@@ -384,10 +407,7 @@ export function normalizePersistentMindState(raw) {
const queuedIndex = queuedMessages.findIndex((queued) => queued.id === message.id);
if (queuedIndex >= 0) queuedMessages.splice(queuedIndex, 1);
recentMessageIds.push(message.id);
- recentMessageFingerprints.push({
- id: message.id,
- fingerprint: persistentMindMessageFingerprint(message),
- });
+ recentMessageFingerprints.push(persistentMindMessageReceipt(message));
} else if (!seenQueued.has(message.id)) {
queuedMessages.unshift(message);
if (queuedMessages.length > PERSISTENT_MIND_LIMITS.MAX_QUEUED_MESSAGES) queuedMessages.pop();
@@ -525,7 +545,7 @@ export function holdPersistentMindWake(raw, wake) {
.slice(-PERSISTENT_MIND_LIMITS.MAX_RECENT_MESSAGE_IDS),
recentMessageFingerprints: [
...state.recentMessageFingerprints.filter((entry) => entry.id !== id),
- { id, fingerprint: persistentMindMessageFingerprint(sanitized.message) },
+ persistentMindMessageReceipt(sanitized.message),
].slice(-PERSISTENT_MIND_LIMITS.MAX_RECENT_MESSAGE_IDS),
};
}
diff --git a/server/lib/persistentMind.test.js b/server/lib/persistentMind.test.js
index 1e40564ee3..23749b24ea 100644
--- a/server/lib/persistentMind.test.js
+++ b/server/lib/persistentMind.test.js
@@ -279,7 +279,7 @@ describe('persistent mind state', () => {
// Hand-edited or downgraded state cannot smuggle in an unusable selection.
expect(normalizePersistentMindState({
enabled: true, started: true, queuedMessages: [{ ...message, thinkingPresetId: '../escape' }],
- }).queuedMessages[0].thinkingPresetId).toBeUndefined();
+ }).queuedMessages[0]).toMatchObject({ thinkingPresetId: 'invalid-preset', thinkingPreset: null });
// The selection is content: the same text on another model is a different
// request, but a message without one must hash exactly as it always did.
diff --git a/server/lib/persistentMindThinkingPresets.js b/server/lib/persistentMindThinkingPresets.js
index 03936d71bc..2a40bf2d0f 100644
--- a/server/lib/persistentMindThinkingPresets.js
+++ b/server/lib/persistentMindThinkingPresets.js
@@ -38,6 +38,23 @@ export const persistentMindThinkingPresetSchema = z.object({
effort: z.union([z.literal(''), z.enum(EFFORT_LEVELS)]).optional(),
}).strict();
+// Accepted messages require an explicit effort sentinel too: a missing field
+// on an old/partial record is not permission to use the provider default.
+export const persistentMindThinkingSelectionSchema = persistentMindThinkingPresetSchema
+ .required({ effort: true });
+
+export function normalizePersistentMindThinkingSelection(value) {
+ const parsed = persistentMindThinkingSelectionSchema.safeParse(value);
+ return parsed.success ? parsed.data : null;
+}
+
+/** Labels are presentation; only the exact route participates in consent. */
+export function samePersistentMindThinkingSelection(left, right) {
+ const a = normalizePersistentMindThinkingSelection(left);
+ const b = normalizePersistentMindThinkingSelection(right);
+ return Boolean(a && b && ['id', 'providerId', 'model', 'effort'].every((key) => a[key] === b[key]));
+}
+
export const persistentMindThinkingPresetsSchema = z.object({
schemaVersion: z.literal(PERSISTENT_MIND_THINKING_PRESETS_SCHEMA_VERSION).optional(),
// A list PATCH replaces the whole list: there is no stable way to express
@@ -67,20 +84,18 @@ export function asPersistentMindThinkingPresetId(value) {
return ID_PATTERN.test(id) ? id : null;
}
+const storedThinkingPresetSchema = persistentMindThinkingPresetSchema.strip();
+
const sanitizePreset = (value) => {
- const id = asPersistentMindThinkingPresetId(value?.id);
- const providerId = text(value?.providerId, PERSISTENT_MIND_THINKING_PRESET_LIMITS.PROVIDER_ID_MAX);
- const model = text(value?.model, PERSISTENT_MIND_THINKING_PRESET_LIMITS.MODEL_MAX);
- // A preset without an exact route cannot be resolved without inventing one,
- // so it is dropped rather than stored as a half-pin.
- if (!id || !providerId || !model) return null;
- const effort = text(value?.effort, 20);
+ const parsed = storedThinkingPresetSchema.safeParse(value);
+ if (!parsed.success) return null;
+ const { id, providerId, model, effort = '', label } = parsed.data;
return {
id,
- label: text(value?.label, PERSISTENT_MIND_THINKING_PRESET_LIMITS.LABEL_MAX) || `${providerId} / ${model}`,
+ label: label || text(`${providerId} / ${model}`, PERSISTENT_MIND_THINKING_PRESET_LIMITS.LABEL_MAX),
providerId,
model,
- effort: EFFORT_LEVELS.includes(effort) ? effort : '',
+ effort,
};
};
diff --git a/server/lib/persistentMindThinkingPresets.test.js b/server/lib/persistentMindThinkingPresets.test.js
index 9c45b6529e..d0961029bf 100644
--- a/server/lib/persistentMindThinkingPresets.test.js
+++ b/server/lib/persistentMindThinkingPresets.test.js
@@ -6,6 +6,7 @@ import {
normalizePersistentMindThinkingPresets,
PERSISTENT_MIND_THINKING_PRESET_LIMITS,
persistentMindThinkingPresetsSchema,
+ persistentMindThinkingSelectionSchema,
} from './persistentMindThinkingPresets.js';
const preset = (overrides = {}) => ({
@@ -41,8 +42,12 @@ describe('persistent mind thinking presets', () => {
const { presets } = normalizePersistentMindThinkingPresets({
presets: [preset({ effort: 'turbo' }), preset({ id: 'plain', label: ' ', effort: undefined })],
});
- expect(presets[0].effort).toBe('');
- expect(presets[1]).toMatchObject({ label: 'example-provider / example-model', effort: '' });
+ expect(presets).toHaveLength(1);
+ expect(presets[0]).toMatchObject({ label: 'example-provider / example-model', effort: '' });
+ const longRoute = normalizePersistentMindThinkingPresets({
+ presets: [preset({ providerId: 'p'.repeat(100), model: 'm'.repeat(200), label: '' })],
+ }).presets[0];
+ expect(persistentMindThinkingSelectionSchema.safeParse(longRoute).success).toBe(true);
});
it('keeps the first of a duplicated id and caps the stored list', () => {
diff --git a/server/routes/cosMindRoutes.js b/server/routes/cosMindRoutes.js
index 502c5ba171..5407b21602 100644
--- a/server/routes/cosMindRoutes.js
+++ b/server/routes/cosMindRoutes.js
@@ -22,6 +22,7 @@ import { normalizePersistentMindProfile } from '../lib/persistentMindProfile.js'
import {
normalizePersistentMindThinkingPresets,
persistentMindThinkingPresetSchema,
+ persistentMindThinkingSelectionSchema,
} from '../lib/persistentMindThinkingPresets.js';
import { normalizePersistentMindPrompt } from '../lib/persistentMindPrompt.js';
import { publicPersistentMindState } from '../lib/persistentMindPublic.js';
@@ -90,7 +91,11 @@ const messageSchema = z.object({
z.literal(''),
z.null(),
]).optional(),
+ thinkingPreset: persistentMindThinkingSelectionSchema.optional(),
}).strict().superRefine((value, ctx) => {
+ if (value.thinkingPreset && value.thinkingPreset.id !== value.thinkingPresetId) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['thinkingPreset'], message: 'The displayed selection must match thinkingPresetId' });
+ }
const images = Array.isArray(value.images) ? value.images : [];
const ids = images.map((image) => typeof image === 'string' ? image : image.attachmentId);
if (!value.text && ids.length === 0) {
diff --git a/server/routes/cosMindRoutes.test.js b/server/routes/cosMindRoutes.test.js
index dcb1bfcb17..f01d99fe8c 100644
--- a/server/routes/cosMindRoutes.test.js
+++ b/server/routes/cosMindRoutes.test.js
@@ -367,6 +367,22 @@ describe('persistent mind routes', () => {
});
});
+ it('validates the displayed temporary selection and requires its preset id to match', async () => {
+ const thinkingPreset = { id: 'deep', label: 'Deep', providerId: 'example-provider', model: 'example-model', effort: '' };
+ const input = { id: 'selected-message', text: 'Use this selection.', thinkingPresetId: 'deep', thinkingPreset };
+ expect((await post('/mind/messages', input)).status).toBe(202);
+ expect(mocks.enqueuePersistentMindMessage).toHaveBeenCalledWith(input);
+ mocks.enqueuePersistentMindMessage.mockClear();
+ for (const patch of [
+ { thinkingPresetId: 'other' },
+ { thinkingPreset: { ...thinkingPreset, effort: 'invalid' } },
+ { thinkingPreset: { ...thinkingPreset, credential: 'redacted-example' } },
+ ]) {
+ expect((await post('/mind/messages', { ...input, ...patch })).status).toBe(400);
+ }
+ expect(mocks.enqueuePersistentMindMessage).not.toHaveBeenCalled();
+ });
+
it('rejects empty, duplicate, oversized, and traversal image references', async () => {
expect((await post('/mind/messages', { id: 'empty' })).status).toBe(400);
expect((await post('/mind/messages', { id: 'duplicate', images: ['attachment-1', 'attachment-1'] })).status).toBe(400);
diff --git a/server/services/persistentMindProfile.js b/server/services/persistentMindProfile.js
index ec5d54b8bb..d5d86df85d 100644
--- a/server/services/persistentMindProfile.js
+++ b/server/services/persistentMindProfile.js
@@ -13,7 +13,11 @@
import { effortLevelsForProvider } from '../lib/providerModels.js';
import { normalizePersistentMindProfile } from '../lib/persistentMindProfile.js';
-import { findPersistentMindThinkingPreset } from '../lib/persistentMindThinkingPresets.js';
+import {
+ findPersistentMindThinkingPreset,
+ normalizePersistentMindThinkingSelection,
+ samePersistentMindThinkingSelection,
+} from '../lib/persistentMindThinkingPresets.js';
import { getProviderById } from './providers.js';
import { getProviderStatus, isProviderAvailable } from './providerStatus.js';
@@ -25,7 +29,7 @@ const providerModelIds = (provider) => (provider?.models || [])
* Validate one exact provider/model/effort selection against the live registry.
* Every failure is a refusal: nothing here may substitute a nearby route.
*/
-async function resolveExactRoute({ providerId, model, effort, noun, incompleteError }) {
+async function resolveExactRoute({ providerId, model, effort, noun, incompleteError, requireCatalog = false }) {
if (!providerId || !model) return { ok: false, error: incompleteError };
const provider = await getProviderById(providerId);
@@ -38,7 +42,7 @@ async function resolveExactRoute({ providerId, model, effort, noun, incompleteEr
}
const models = providerModelIds(provider);
- if (models.length > 0 && !models.includes(model)) {
+ if ((requireCatalog || models.length > 0) && !models.includes(model)) {
return { ok: false, error: `${noun} model "${model}" is not available from provider "${provider.id}"` };
}
const supportedEfforts = effortLevelsForProvider(provider, model);
@@ -75,17 +79,25 @@ export async function resolvePersistentMindProfile(rawProfile) {
* dropped is a refusal — the turn must not quietly answer on the default route
* the user was deliberately stepping away from.
*/
-export async function resolvePersistentMindThinkingSession({ presetId, config } = {}) {
+export async function resolvePersistentMindThinkingSession({ presetId, selection, config } = {}) {
const profile = normalizePersistentMindProfile(config?.persistentMindProfile);
if (!profile.enabled) return { ok: false, error: 'Persistent mind profile is disabled' };
const preset = findPersistentMindThinkingPreset(config?.persistentMindThinkingPresets, presetId);
if (!preset) {
return { ok: false, error: `Temporary thinking preset "${presetId}" is no longer available` };
}
+ const accepted = normalizePersistentMindThinkingSelection(selection);
+ if (!accepted || accepted.id !== presetId) {
+ return { ok: false, error: 'Temporary thinking session has no valid accepted route; send a new message to authorize it' };
+ }
+ if (!samePersistentMindThinkingSelection(accepted, preset)) {
+ return { ok: false, error: 'Temporary thinking preset changed after acceptance; send a new message to authorize its new route' };
+ }
const route = await resolveExactRoute({
- providerId: preset.providerId,
- model: preset.model,
- effort: preset.effort,
+ providerId: accepted.providerId,
+ model: accepted.model,
+ effort: accepted.effort,
+ requireCatalog: true,
noun: `Temporary thinking preset "${preset.label}"`,
// Unreachable: normalization drops a preset without both, so this is the
// belt-and-braces refusal rather than a route the resolver could invent.
@@ -96,7 +108,7 @@ export async function resolvePersistentMindThinkingSession({ presetId, config }
...route,
temporary: true,
presetId: preset.id,
- presetLabel: preset.label,
+ presetLabel: accepted.label || preset.label,
thinkingInterface: profile.thinkingInterface,
};
}
diff --git a/server/services/persistentMindProfile.test.js b/server/services/persistentMindProfile.test.js
index cab73a0c86..4e5144b6c0 100644
--- a/server/services/persistentMindProfile.test.js
+++ b/server/services/persistentMindProfile.test.js
@@ -74,7 +74,7 @@ describe('resolvePersistentMindThinkingSession', () => {
});
it('borrows one exact alternate route while the mind keeps its own identity', async () => {
- await expect(resolvePersistentMindThinkingSession({ presetId: 'deep', config })).resolves.toMatchObject({
+ await expect(resolvePersistentMindThinkingSession({ presetId: 'deep', selection: config.persistentMindThinkingPresets.presets[0], config })).resolves.toMatchObject({
ok: true,
temporary: true,
presetId: 'deep',
@@ -89,13 +89,13 @@ describe('resolvePersistentMindThinkingSession', () => {
it('refuses instead of quietly answering on the default the user stepped away from', async () => {
await expect(resolvePersistentMindThinkingSession({ presetId: 'removed', config })).resolves
.toEqual({ ok: false, error: 'Temporary thinking preset "removed" is no longer available' });
- await expect(resolvePersistentMindThinkingSession({ presetId: 'retired', config })).resolves
+ await expect(resolvePersistentMindThinkingSession({ presetId: 'retired', selection: config.persistentMindThinkingPresets.presets[1], config })).resolves
.toMatchObject({ ok: false, error: /not available from provider/ });
- await expect(resolvePersistentMindThinkingSession({ presetId: 'strained', config })).resolves
+ await expect(resolvePersistentMindThinkingSession({ presetId: 'strained', selection: config.persistentMindThinkingPresets.presets[2], config })).resolves
.toMatchObject({ ok: false, error: /not supported/ });
mocks.available = false;
- await expect(resolvePersistentMindThinkingSession({ presetId: 'deep', config })).resolves
+ await expect(resolvePersistentMindThinkingSession({ presetId: 'deep', selection: config.persistentMindThinkingPresets.presets[0], config })).resolves
.toEqual({ ok: false, error: 'offline' });
});
@@ -105,4 +105,21 @@ describe('resolvePersistentMindThinkingSession', () => {
config: { ...config, persistentMindProfile: { ...profile, enabled: false } },
})).resolves.toEqual({ ok: false, error: 'Persistent mind profile is disabled' });
});
+
+ it('refuses missing/malformed consent, route edits, and an empty provider catalog', async () => {
+ const selection = config.persistentMindThinkingPresets.presets[0];
+ for (const changed of [
+ undefined,
+ { ...selection, effort: 'invalid' },
+ { ...selection, providerId: 'another-provider' },
+ { ...selection, model: 'another-model' },
+ { ...selection, effort: 'high' },
+ ]) {
+ await expect(resolvePersistentMindThinkingSession({ presetId: 'deep', selection: changed, config }))
+ .resolves.toMatchObject({ ok: false });
+ }
+ mocks.provider.models = [];
+ await expect(resolvePersistentMindThinkingSession({ presetId: 'deep', selection, config }))
+ .resolves.toMatchObject({ ok: false, error: /not available/ });
+ });
});
diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.js
index 6c861778f7..eced1ada09 100644
--- a/server/services/persistentMindSupervisor.js
+++ b/server/services/persistentMindSupervisor.js
@@ -24,6 +24,7 @@ import {
nextPersistentMindWakeAt,
normalizePersistentMindState,
persistentMindMessageFingerprint,
+ persistentMindMessageReceipt,
persistentMindBackoffMs,
persistentMindTurnIsStale,
persistentMindWakeConsumesAttempt,
@@ -55,6 +56,8 @@ import { normalizePersistentMindProfile, persistentMindWakeIntervalMs } from '..
import { getProviderById } from './providers.js';
import {
findPersistentMindThinkingPreset,
+ normalizePersistentMindThinkingSelection,
+ samePersistentMindThinkingSelection,
PERSISTENT_MIND_THINKING_PRESET_LIMITS,
} from '../lib/persistentMindThinkingPresets.js';
import {
@@ -140,13 +143,13 @@ const claimedAttachmentsForMessage = (mind, messageId) => mind.pendingAttachment
))
.map(({ attachment }) => attachment);
-const messageFromAttachments = ({ id, text, createdAt, attachments, thinkingPresetId }) => ({
+const messageFromAttachments = ({ id, text, createdAt, attachments, thinkingPresetId, thinkingPreset }) => ({
id,
text,
...(attachments.length > 0 ? {
images: attachments.map(normalizePersistentMindMessageImage).filter(Boolean),
} : {}),
- ...(thinkingPresetId ? { thinkingPresetId } : {}),
+ ...(thinkingPresetId ? { thinkingPresetId, thinkingPreset: thinkingPreset || null } : {}),
createdAt,
});
@@ -581,15 +584,15 @@ async function interruptActiveTurn(reason, status, { retry = false, expectedTurn
*
* `consumedAttempt` says the provider span had already opened, so a temporary
* thinking session must not be replayed automatically. Every refusal decided
- * before that point — an unresolvable route, an unavailable adapter, a busy
- * local endpoint — spent nothing and still requeues normally.
+ * before that point normally requeues. A refused temporary route is explicitly
+ * retired too: changing a preset back later must not resurrect refused work.
*/
-async function parkActiveTurn(turnId, reason, status = 'waiting', { retryAt = null, consumedAttempt = false } = {}) {
+async function parkActiveTurn(turnId, reason, status = 'waiting', { retryAt = null, consumedAttempt = false, retireWake = false } = {}) {
const result = await mutateMindState((mind) => {
if (mind.activeTurn?.id !== turnId) return { mind, value: false };
- // A refusal decided before the provider span opened spent nothing, so it
- // requeues even for a temporary session.
- const held = consumedAttempt && persistentMindWakeConsumesAttempt(mind.activeTurn.wake);
+ // Transport/slot waits may retry; a revoked route or uncertain inference
+ // requires a fresh user submission.
+ const held = (consumedAttempt || retireWake) && persistentMindWakeConsumesAttempt(mind.activeTurn.wake);
const next = held
? holdPersistentMindWake(mind, mind.activeTurn.wake)
: requeuePersistentMindWake(mind, mind.activeTurn.wake);
@@ -612,7 +615,7 @@ async function parkActiveTurn(turnId, reason, status = 'waiting', { retryAt = nu
mindId: result.state.mindId,
turnId,
eventId: `mind-failed:${turnId}:${status}`,
- data: { status, error: reason, retryAt, consumedAttempt: result.value === true },
+ data: { status, error: reason, retryAt, consumedAttempt: consumedAttempt && result.value === true, requiresResubmission: result.value === true },
});
emitMindStatus(result.state);
return result.state;
@@ -718,18 +721,14 @@ async function completeTurn(turnId, result, generation) {
const messageId = mind.activeTurn.wake.kind === 'message'
? mind.activeTurn.wake.message.id
: null;
- const messageFingerprint = messageId
- ? persistentMindMessageFingerprint(mind.activeTurn.wake.message)
- : null;
const recentMessageIds = messageId
? [...mind.recentMessageIds.filter((id) => id !== messageId), messageId]
.slice(-PERSISTENT_MIND_LIMITS.MAX_RECENT_MESSAGE_IDS)
: mind.recentMessageIds;
const recentMessageFingerprints = messageId
- ? [...mind.recentMessageFingerprints.filter((entry) => entry.id !== messageId), {
- id: messageId,
- fingerprint: messageFingerprint,
- }].slice(-PERSISTENT_MIND_LIMITS.MAX_RECENT_MESSAGE_IDS)
+ ? [...mind.recentMessageFingerprints.filter((entry) => entry.id !== messageId),
+ persistentMindMessageReceipt(mind.activeTurn.wake.message),
+ ].slice(-PERSISTENT_MIND_LIMITS.MAX_RECENT_MESSAGE_IDS)
: mind.recentMessageFingerprints;
const quietPeriodMs = persistentMindWakeIntervalMs(root.config?.persistentMindProfile);
const quietDeadline = Date.parse(completedAt) + quietPeriodMs;
@@ -915,11 +914,16 @@ async function runOnePersistentMindTurn() {
const thinkingPresetId = turn.wake.kind === 'message'
? turn.wake.message.thinkingPresetId || null
: null;
+ const routeConfig = (await loadState()).config;
const profile = thinkingPresetId
- ? await resolvePersistentMindThinkingSession({ presetId: thinkingPresetId, config: root.config })
- : await resolvePersistentMindProfile(root.config?.persistentMindProfile);
+ ? await resolvePersistentMindThinkingSession({
+ presetId: thinkingPresetId,
+ selection: turn.wake.message.thinkingPreset,
+ config: routeConfig,
+ })
+ : await resolvePersistentMindProfile(routeConfig?.persistentMindProfile);
if (!profile.ok) {
- await parkActiveTurn(turn.id, profile.error, 'degraded');
+ await parkActiveTurn(turn.id, profile.error, 'degraded', { retireWake: Boolean(thinkingPresetId) });
return;
}
// Adapters receive the exact profile. They may prepare their text
@@ -1284,6 +1288,7 @@ export async function enqueuePersistentMindMessage({
text,
images,
thinkingPresetId,
+ thinkingPreset,
createdAt = nowIso(),
} = {}) {
const messageId = typeof id === 'string' ? id.trim().slice(0, 200) : '';
@@ -1295,37 +1300,15 @@ export async function enqueuePersistentMindMessage({
if (!messageId || attachmentIds === null || (!messageText && attachmentIds.length === 0)) {
return attachmentFailure('Message id and text or at least one image are required', { code: 'VALIDATION_ERROR' });
}
- if (presetId || attachmentIds.length > 0) {
- const root = await loadState();
- const profile = normalizePersistentMindProfile(root.config?.persistentMindProfile);
- // Admission reads the saved preset list only — a lookup, never a provider
- // call, model pull, or generation. Selecting a model must stay free.
- const preset = presetId
- ? findPersistentMindThinkingPreset(root.config?.persistentMindThinkingPresets, presetId)
- : null;
- if (presetId && !preset) {
- return attachmentFailure(`Temporary thinking preset "${presetId}" is not available`, {
- code: 'THINKING_PRESET_UNAVAILABLE',
- status: 422,
- });
- }
- if (attachmentIds.length > 0) {
- // Images are checked against the route this message will actually take,
- // so a text-only alternate cannot accept an image it can never read.
- const routeProviderId = preset ? preset.providerId : profile.providerId;
- const routeModel = preset ? preset.model : profile.model;
- const provider = routeProviderId ? await getProviderById(routeProviderId) : null;
- const imageCapability = await resolvePersistentMindImageCapability({ provider, model: routeModel });
- if (!imageCapabilityAllowsAttempt(imageCapability, provider)) {
- return attachmentFailure(imageCapability.reason, { code: 'IMAGE_CAPABILITY_UNSUPPORTED', status: 422 });
- }
- }
+ const submittedSelection = normalizePersistentMindThinkingSelection(thinkingPreset);
+ if (thinkingPreset !== undefined && (!submittedSelection || submittedSelection.id !== presetId)) {
+ return attachmentFailure('A temporary selection must include the exact preset, provider, model and effort', { code: 'VALIDATION_ERROR' });
}
const messageCreatedAt = typeof createdAt === 'string' && Number.isFinite(Date.parse(createdAt))
? new Date(createdAt).toISOString()
: nowIso();
await cleanupPersistentMindAttachments();
- const result = await mutateMindState(async (mind) => {
+ const result = await mutateMindState(async (mind, root) => {
if (attachmentIds.length > 0 && isUpdateInProgress()) {
return {
mind,
@@ -1338,12 +1321,15 @@ export async function enqueuePersistentMindMessage({
const existingMessage = findMessageById(mind, messageId);
const claimedRecords = claimedAttachmentsForMessage(mind, messageId);
const duplicate = Boolean(existingMessage) || mind.recentMessageIds.includes(messageId);
+ const recentReceipt = mind.recentMessageFingerprints.find((entry) => entry.id === messageId);
+ const acceptedSelection = existingMessage?.thinkingPreset || recentReceipt?.thinkingPreset || null;
const requestedFingerprint = persistentMindMessageFingerprint({
text: messageText,
images: attachmentIds,
thinkingPresetId: presetId,
+ thinkingPreset: submittedSelection || acceptedSelection,
});
- const recentFingerprint = mind.recentMessageFingerprints.find((entry) => entry.id === messageId)?.fingerprint;
+ const recentFingerprint = recentReceipt?.fingerprint;
const existingImageIds = existingMessage
? imageIdsForMessage(existingMessage)
: claimedRecords.map((attachment) => attachment.attachmentId);
@@ -1384,6 +1370,16 @@ export async function enqueuePersistentMindMessage({
}),
};
}
+ if (existingMessage && submittedSelection
+ && !samePersistentMindThinkingSelection(submittedSelection, acceptedSelection)) {
+ return {
+ mind,
+ value: attachmentFailure('A retry must use the same accepted thinking route', {
+ code: 'IDEMPOTENCY_CONFLICT',
+ status: 409,
+ }),
+ };
+ }
if (!sameAttachmentIds(existingImageIds, attachmentIds)) {
return {
mind,
@@ -1407,10 +1403,34 @@ export async function enqueuePersistentMindMessage({
createdAt: messageCreatedAt,
attachments: resolved.attachments,
thinkingPresetId: presetId,
+ thinkingPreset: acceptedSelection,
}),
},
};
}
+ // Resolve new admissions inside the same state update that accepts them.
+ // Matching retries above use their receipt, even if the preset was revoked.
+ const selection = presetId
+ ? findPersistentMindThinkingPreset(root.config?.persistentMindThinkingPresets, presetId)
+ : null;
+ if (presetId && !selection) {
+ return { mind, value: attachmentFailure('The temporary thinking preset is unavailable', {
+ code: 'THINKING_PRESET_UNAVAILABLE', status: 422,
+ }) };
+ }
+ if (submittedSelection && !samePersistentMindThinkingSelection(submittedSelection, selection)) {
+ return { mind, value: attachmentFailure('The displayed preset changed; select its current route before sending', {
+ code: 'THINKING_PRESET_CHANGED', status: 409,
+ }) };
+ }
+ if (attachmentIds.length > 0) {
+ const profile = selection || normalizePersistentMindProfile(root.config?.persistentMindProfile);
+ const provider = profile.providerId ? await getProviderById(profile.providerId) : null;
+ const capability = await resolvePersistentMindImageCapability({ provider, model: profile.model });
+ if (!imageCapabilityAllowsAttempt(capability, provider)) {
+ return { mind, value: attachmentFailure(capability.reason, { code: 'IMAGE_CAPABILITY_UNSUPPORTED', status: 422 }) };
+ }
+ }
if (claimedRecords.length > 0 && !sameAttachmentIds(
claimedRecords.map((attachment) => attachment.attachmentId),
attachmentIds,
@@ -1455,6 +1475,7 @@ export async function enqueuePersistentMindMessage({
createdAt: messageCreatedAt,
attachments: resolved.attachments,
thinkingPresetId: presetId,
+ thinkingPreset: selection,
});
return {
mind: {
@@ -1481,6 +1502,7 @@ export async function enqueuePersistentMindMessage({
displayText: acceptedMessage.text,
textChars: acceptedMessage.text.length,
thinkingPresetId: acceptedMessage.thinkingPresetId || null,
+ thinkingPreset: acceptedMessage.thinkingPreset || null,
imageCount: Array.isArray(acceptedMessage.images) ? acceptedMessage.images.length : 0,
images: Array.isArray(acceptedMessage.images)
? acceptedMessage.images.map(normalizePersistentMindMessageImage).filter(Boolean)
diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.js
index 9cb6074515..c54fd5ca8e 100644
--- a/server/services/persistentMindSupervisor.test.js
+++ b/server/services/persistentMindSupervisor.test.js
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { createDefaultPersistentMindState, PERSISTENT_MIND_LIMITS } from '../lib/persistentMind.js';
+import { createDefaultPersistentMindState, normalizePersistentMindState, PERSISTENT_MIND_LIMITS } from '../lib/persistentMind.js';
import {
__resetCosAdmissionReservations,
acquireCosActionReservation,
@@ -26,6 +26,8 @@ const mock = vi.hoisted(() => ({
},
imageCapability: { status: 'supported', reason: 'Supported.' },
thinkingSession: null,
+ useActualThinkingSession: false,
+ providerOverride: null,
}));
vi.mock('./cosState.js', () => ({
@@ -65,11 +67,17 @@ vi.mock('./persistentMindContext.js', () => ({
preparePersistentMindContext: (...args) => mock.prepareContext(...args),
}));
-vi.mock('./persistentMindProfile.js', () => ({
+vi.mock('./persistentMindProfile.js', async (importOriginal) => ({
resolvePersistentMindProfile: vi.fn(async () => mock.profile),
- resolvePersistentMindThinkingSession: vi.fn(async () => mock.thinkingSession),
+ resolvePersistentMindThinkingSession: vi.fn(async (input) => mock.useActualThinkingSession
+ ? (await importOriginal()).resolvePersistentMindThinkingSession(input)
+ : mock.thinkingSession),
+}));
+vi.mock('./providers.js', () => ({ getProviderById: vi.fn(async () => mock.providerOverride || mock.profile.provider) }));
+vi.mock('./providerStatus.js', () => ({
+ isProviderAvailable: () => true,
+ getProviderStatus: () => ({}),
}));
-vi.mock('./providers.js', () => ({ getProviderById: vi.fn(async () => mock.profile.provider) }));
vi.mock('./persistentMindImageCapability.js', () => ({
resolvePersistentMindImageCapability: vi.fn(async () => mock.imageCapability),
imageCapabilityAllowsAttempt: (capability, provider) => capability?.status === 'supported'
@@ -108,6 +116,8 @@ describe('persistent mind supervisor', () => {
mock.budget = { withinBudget: true, exceeded: null };
mock.daemonRunning = true;
mock.updateInProgress = false;
+ mock.useActualThinkingSession = false;
+ mock.providerOverride = null;
mock.recordUsage.mockClear();
mock.profile = {
ok: true,
@@ -828,8 +838,87 @@ describe('persistent mind supervisor', () => {
expect(run).not.toHaveBeenCalled();
expect(mock.root.persistentMind.status).toBe('degraded');
expect(mock.root.persistentMind.pauseReason).toMatch(/Temporary thinking preset/);
- // Nothing was spent, so the message stays queued for the user to fix the preset.
- expect(mock.root.persistentMind.queuedMessages.map((item) => item.id)).toEqual(['message-1']);
+ // A refused route cannot revive if a preset with the same id reappears.
+ expect(mock.root.persistentMind.queuedMessages).toEqual([]);
+ expect(mock.root.persistentMind.recentMessageIds).toContain('message-1');
+ });
+
+ it('pins acceptance through persistence and refuses a later preset edit without reviving a matching retry', async () => {
+ withDeepPreset();
+ mock.root.config.persistentMindThinkingPresets.presets[0].effort = '';
+ const selection = structuredClone(mock.root.config.persistentMindThinkingPresets.presets[0]);
+ mock.useActualThinkingSession = true;
+ mock.providerOverride = { id: 'example-alt', type: 'api', models: ['alt-model', 'other-model'] };
+ const run = vi.fn(async () => ({}));
+ await supervisor.registerPersistentMindTurnAdapter({ prepare: echoProfileAdapter(), run });
+ await supervisor.setPersistentMindEnabled(true);
+ await supervisor.startPersistentMind();
+ await supervisor.pausePersistentMind();
+ const input = { id: 'accepted-route', text: 'Use this exact route.', thinkingPresetId: 'deep', thinkingPreset: selection };
+ expect(await supervisor.enqueuePersistentMindMessage(input)).toMatchObject({ success: true, duplicate: false });
+ expect(mock.root.persistentMind.status).toBe('paused');
+ expect(run).not.toHaveBeenCalled();
+ mock.root = JSON.parse(JSON.stringify(mock.root));
+ mock.root.persistentMind = normalizePersistentMindState(mock.root.persistentMind);
+ expect(mock.root.persistentMind.queuedMessages[0].thinkingPreset).toEqual(selection);
+ mock.root.config.persistentMindThinkingPresets.presets[0].model = 'other-model';
+ expect(await supervisor.enqueuePersistentMindMessage({ ...input, id: 'stale-display' }))
+ .toMatchObject({ success: false, code: 'THINKING_PRESET_CHANGED' });
+ expect(await supervisor.enqueuePersistentMindMessage({ ...input, thinkingPreset: { ...selection, model: 'other-model' } }))
+ .toMatchObject({ success: false, code: 'IDEMPOTENCY_CONFLICT' });
+
+ await supervisor.resumePersistentMind();
+ await supervisor.drainPersistentMind();
+ expect(run).not.toHaveBeenCalled();
+ expect(mock.root.persistentMind).toMatchObject({ status: 'degraded', queuedMessages: [] });
+ expect(mock.appendMindEvent).toHaveBeenCalledWith(expect.objectContaining({
+ kind: 'mind.failed', data: expect.objectContaining({ requiresResubmission: true, consumedAttempt: false }),
+ }));
+ mock.root.config.persistentMindThinkingPresets.presets = [];
+ expect(await supervisor.enqueuePersistentMindMessage(input)).toMatchObject({ success: true, duplicate: true });
+ // Old clients send only the id. Their retry reads the accepted receipt,
+ // rather than revalidating a preset that no longer exists.
+ const { thinkingPreset: _selection, ...legacyInput } = input;
+ expect(await supervisor.enqueuePersistentMindMessage(legacyInput)).toMatchObject({ success: true, duplicate: true });
+ expect(mock.root.persistentMind.queuedMessages).toEqual([]);
+ expect(mock.root.config.persistentMindProfile).toMatchObject({ providerId: 'example-cloud', model: 'example-model', effort: 'high' });
+ });
+
+ it('lets an id-only client retry after completion and a label-only edit while retaining the accepted route', async () => {
+ withDeepPreset();
+ mock.root.config.persistentMindThinkingPresets.presets[0].effort = '';
+ mock.useActualThinkingSession = true;
+ mock.providerOverride = { id: 'example-alt', type: 'api', models: ['alt-model'] };
+ const run = vi.fn(async () => ({}));
+ await supervisor.registerPersistentMindTurnAdapter({ prepare: echoProfileAdapter(), run });
+ await supervisor.setPersistentMindEnabled(true);
+ await supervisor.startPersistentMind();
+ const input = { id: 'id-only', text: 'Keep the accepted model.', thinkingPresetId: 'deep' };
+ await supervisor.enqueuePersistentMindMessage(input);
+ const accepted = structuredClone(mock.root.persistentMind.queuedMessages[0].thinkingPreset);
+ mock.root.config.persistentMindThinkingPresets.presets[0].label = 'Renamed';
+ await supervisor.drainPersistentMind();
+ expect(run).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ model: 'alt-model', effort: null }));
+ expect(mock.root.persistentMind.recentMessageFingerprints[0].thinkingPreset).toEqual(accepted);
+ mock.root.config.persistentMindThinkingPresets.presets = [];
+ expect(await supervisor.enqueuePersistentMindMessage(input)).toMatchObject({ success: true, duplicate: true });
+ expect(await supervisor.enqueuePersistentMindMessage({ ...input, thinkingPreset: { ...accepted, effort: 'high' } }))
+ .toMatchObject({ success: false, code: 'IDEMPOTENCY_CONFLICT' });
+ expect(mock.root.persistentMind.queuedMessages).toEqual([]);
+ });
+
+ it('retains legacy temporary input but refuses to derive a route from current config', async () => {
+ withDeepPreset();
+ mock.useActualThinkingSession = true;
+ const run = vi.fn();
+ await supervisor.registerPersistentMindTurnAdapter({ prepare: echoProfileAdapter(), run });
+ await supervisor.setPersistentMindEnabled(true);
+ await supervisor.startPersistentMind();
+ mock.root.persistentMind.queuedMessages = [{ id: 'legacy', text: 'Saved before snapshots.', thinkingPresetId: 'deep' }];
+ await supervisor.drainPersistentMind();
+ expect(run).not.toHaveBeenCalled();
+ expect(mock.root.persistentMind.pauseReason).toMatch(/no valid accepted route/);
+ expect(mock.root.persistentMind.recentMessageIds).toContain('legacy');
});
it('never auto-replays a temporary session interrupted after its provider span opened', async () => {