feat: draft settings persistence — shared model/thinking/context record for the new-session surfaces
Both new-session pages (the home graph view's topic dock and /chat/new)
held their model + thinking + knowledge-context choices in plain
useState(undefined) — every navigation reset them to config defaults.
Now both surfaces read/write ONE server-side record
(data/draft-settings.json via GET/PUT /api/settings/draft, the
render-settings pattern): whatever the learner last left the controls on
is what every later visit shows. useDraftSettings loads on mount with a
touch-guard (a slow GET never clobbers a fast choice), saves
optimistically. Session creation still carries the choice into the new
chat exactly as before; per-session settings are untouched.
The PUT validation is the exact per-chat contract — parseSettingsBody
extracted verbatim from app/api/chats/[id]/settings and shared by both
routes (unknown model/level → 400 with the supported list, never a
silent clamp). 400s on garbage, {} = the clear-overrides write.
Live-verified: Cmd+K+Enter model pick, Shift+Tab thinking cycle, context
slider — all held across home → session → home → /chat/new, and carried
into a created session's record.
This commit is contained in:
@@ -1,6 +1,5 @@
|
||||
import { getChat, validateChatSettings, stores } from "@/src/server";
|
||||
import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
|
||||
import { GRAPH_CONTEXT_TOKENS_MAX, type ChatSettings } from "@/src/core";
|
||||
import { getChat, validateChatSettings, parseSettingsBody, stores } from "@/src/server";
|
||||
import type { ChatSettings } from "@/src/core";
|
||||
|
||||
/**
|
||||
* The per-chat model control (model-control wave): replace-whole settings —
|
||||
@@ -10,60 +9,25 @@ import { GRAPH_CONTEXT_TOKENS_MAX, type ChatSettings } from "@/src/core";
|
||||
* thinking level is a 400 carrying the supported list, never a silent clamp
|
||||
* — the user must see what the model actually accepts. Effective next turn
|
||||
* by construction (agents are stateless per turn).
|
||||
*
|
||||
* The body parsing itself is shared with the draft route
|
||||
* (src/server/settings-body.ts, draft-settings wave 2026-09-18).
|
||||
*/
|
||||
export async function PUT(req: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
if (!getChat(id)) return Response.json({ error: "Not found" }, { status: 404 });
|
||||
|
||||
const body = (await req.json().catch(() => null)) as
|
||||
| { model?: { provider?: unknown; id?: unknown }; thinkingLevel?: unknown; graphContextTokens?: unknown }
|
||||
| null;
|
||||
if (!body || typeof body !== "object") {
|
||||
return Response.json({ error: "Invalid JSON body" }, { status: 400 });
|
||||
}
|
||||
const settings: ChatSettings = {};
|
||||
if (body.model !== undefined) {
|
||||
if (
|
||||
typeof body.model !== "object" ||
|
||||
body.model === null ||
|
||||
typeof body.model.provider !== "string" ||
|
||||
typeof body.model.id !== "string"
|
||||
) {
|
||||
return Response.json({ error: "model must be {provider, id}" }, { status: 400 });
|
||||
}
|
||||
settings.model = { provider: body.model.provider, id: body.model.id };
|
||||
}
|
||||
if (body.thinkingLevel !== undefined) {
|
||||
if (typeof body.thinkingLevel !== "string") {
|
||||
return Response.json({ error: "thinkingLevel must be a string" }, { status: 400 });
|
||||
}
|
||||
settings.thinkingLevel = body.thinkingLevel as ThinkingLevel;
|
||||
}
|
||||
// Graph context injection budget (vision-context-injection.md): integer
|
||||
// tokens, 0 (off) to GRAPH_CONTEXT_TOKENS_MAX, no silent clamping — the
|
||||
// slider is the only writer, and it only ever sends multiples of the step.
|
||||
if (body.graphContextTokens !== undefined) {
|
||||
if (
|
||||
typeof body.graphContextTokens !== "number" ||
|
||||
!Number.isInteger(body.graphContextTokens) ||
|
||||
body.graphContextTokens < 0 ||
|
||||
body.graphContextTokens > GRAPH_CONTEXT_TOKENS_MAX
|
||||
) {
|
||||
return Response.json(
|
||||
{ error: `graphContextTokens must be an integer between 0 and ${GRAPH_CONTEXT_TOKENS_MAX}` },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
settings.graphContextTokens = body.graphContextTokens;
|
||||
}
|
||||
const body = await req.json().catch(() => null);
|
||||
const parsed = parseSettingsBody(body);
|
||||
if (!parsed.ok) return Response.json({ error: parsed.error }, { status: 400 });
|
||||
|
||||
const verdict = validateChatSettings(settings);
|
||||
const verdict = validateChatSettings(parsed.settings);
|
||||
if (!verdict.ok) {
|
||||
return Response.json({ error: verdict.error, supported: verdict.supported }, { status: 400 });
|
||||
}
|
||||
|
||||
// Replace-whole persists the validated object verbatim — no merges, so a
|
||||
// stale client can never resurrect a cleared override.
|
||||
stores.chatStore.saveSettings(id, settings);
|
||||
return Response.json({ settings });
|
||||
stores.chatStore.saveSettings(id, parsed.settings);
|
||||
return Response.json({ settings: parsed.settings satisfies ChatSettings });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* GET/PUT /api/settings/draft — server persistence for the DRAFT (pre-
|
||||
* session) settings: the model + thinking-level + knowledge-context
|
||||
* selections made on the new-session surfaces (the home graph view's topic
|
||||
* dock and /chat/new). Both surfaces share ONE record (owner, 2026-09-18):
|
||||
* whatever the learner last left the controls on is what the next visit
|
||||
* shows. The file lives at data/draft-settings.json
|
||||
* (config.DRAFT_SETTINGS_FILE).
|
||||
*
|
||||
* GET → 200 {settings} once saved, 200 null on first boot (the surfaces
|
||||
* keep config-pinned defaults until the learner chooses something).
|
||||
* PUT → 200 {settings} — the VALIDATED copy persisted verbatim. The exact
|
||||
* per-chat contract (parseSettingsBody + the catalog gate): unknown
|
||||
* provider/model or an unsupported thinking level is a 400 carrying
|
||||
* the supported list, never a silent clamp.
|
||||
*
|
||||
* Per-session settings (PUT /api/chats/:id/settings) are a separate record
|
||||
* untouched by this — the draft choice still rides along on session
|
||||
* creation exactly as before.
|
||||
*/
|
||||
import { readDraftSettings, writeDraftSettings, parseSettingsBody, validateChatSettings } from "@/src/server";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET() {
|
||||
return Response.json(readDraftSettings());
|
||||
}
|
||||
|
||||
export async function PUT(request: Request) {
|
||||
const body = await request.json().catch(() => null);
|
||||
const parsed = parseSettingsBody(body);
|
||||
if (!parsed.ok) return Response.json({ error: parsed.error }, { status: 400 });
|
||||
const verdict = validateChatSettings(parsed.settings);
|
||||
if (!verdict.ok) {
|
||||
return Response.json({ error: verdict.error, supported: verdict.supported }, { status: 400 });
|
||||
}
|
||||
writeDraftSettings(parsed.settings);
|
||||
return Response.json({ settings: parsed.settings });
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* The DRAFT (pre-session) settings hook — the shared persistence behind
|
||||
* the two new-session surfaces (the home graph view's topic dock and
|
||||
* /chat/new). The model + thinking + knowledge-context choices live in
|
||||
* ONE server-side record (GET/PUT /api/settings/draft →
|
||||
* data/draft-settings.json), so whatever the learner last left the
|
||||
* controls on is what every later visit shows (owner, draft-settings wave
|
||||
* 2026-09-18): navigating away and back keeps the feel. Per-session
|
||||
* settings are a different record (the chat's own) — untouched here.
|
||||
*
|
||||
* Contract: settings === undefined until the first GET resolves — the
|
||||
* controls render config-pinned defaults in that window, same as today.
|
||||
* The GET is touch-guarded: if the learner changes something before the
|
||||
* load lands, the loaded copy is dropped, never clobbering the choice.
|
||||
* Saves are optimistic (the controls only ever send valid values — the
|
||||
* picker offers catalog models, the slider sends its stops) and
|
||||
* fire-and-forget; a failed write logs, and the next mount falls back to
|
||||
* the persisted truth.
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import type { ChatSettings } from "@/src/core";
|
||||
|
||||
export function useDraftSettings(): {
|
||||
settings: ChatSettings | undefined;
|
||||
save: (settings: ChatSettings) => void;
|
||||
} {
|
||||
const [settings, setSettings] = useState<ChatSettings | undefined>(undefined);
|
||||
const touchedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
fetch("/api/settings/draft")
|
||||
.then((res) => (res.ok ? (res.json() as Promise<ChatSettings | null>) : null))
|
||||
.then((loaded) => {
|
||||
// Never clobber a choice made while the load was in flight.
|
||||
if (!cancelled && loaded !== null && !touchedRef.current) setSettings(loaded);
|
||||
})
|
||||
.catch(() => {
|
||||
/* transient — defaults stand, the next change rewrites the record */
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const save = useCallback((next: ChatSettings) => {
|
||||
touchedRef.current = true;
|
||||
setSettings(next);
|
||||
void fetch("/api/settings/draft", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(next),
|
||||
}).catch((err: unknown) => {
|
||||
console.error("draft settings write failed:", err);
|
||||
});
|
||||
}, []);
|
||||
|
||||
return { settings, save };
|
||||
}
|
||||
+10
-8
@@ -5,6 +5,7 @@ import { useRouter } from "next/navigation";
|
||||
import { CornerDownLeftIcon } from "lucide-react";
|
||||
import { GraphView } from "@/components/graph-view";
|
||||
import { GraphContextControl, effectiveContextTokens } from "@/components/graph-context-control";
|
||||
import { useDraftSettings } from "@/components/draft-settings";
|
||||
import { DictationBar, useDictation } from "@/components/dictation";
|
||||
import { SidebarToggle } from "@/components/sidebar";
|
||||
import { StatsBar } from "@/components/stats-bar";
|
||||
@@ -25,10 +26,13 @@ export function Home() {
|
||||
append: (t) => setTopic((v) => (v ? v.replace(/\s+$/, "") + " " + t : t)),
|
||||
});
|
||||
const [busy, setBusy] = useState(false);
|
||||
// The model+thinking selection made pre-chat — lifted from the StatsBar's
|
||||
// ModelControl, carried to the chat POST then PUT-on-create (the model
|
||||
// picker defers its save when chatId is empty; see components/model-picker).
|
||||
const [settings, setSettings] = useState<ChatSettings | undefined>(undefined);
|
||||
// The model+thinking+context selection made pre-chat — the SHARED draft
|
||||
// record (draft-settings wave, 2026-09-18): both new-session surfaces
|
||||
// (this topic dock and /chat/new) read and write ONE persisted choice,
|
||||
// so what the learner last left the controls on is what shows on return.
|
||||
// Still carried to the chat POST then PUT-on-create (the model picker
|
||||
// defers its save when chatId is empty; see components/model-picker).
|
||||
const { settings, save: saveDraft } = useDraftSettings();
|
||||
|
||||
const start = async () => {
|
||||
const t = topic.trim();
|
||||
@@ -140,13 +144,11 @@ export function Home() {
|
||||
turns={[] as TurnUsage[]}
|
||||
chatId=""
|
||||
settings={settings}
|
||||
onSettingsSaved={setSettings}
|
||||
onSettingsSaved={saveDraft}
|
||||
leftSlot={
|
||||
<GraphContextControl
|
||||
value={effectiveContextTokens(settings)}
|
||||
onChange={(tokens) =>
|
||||
setSettings((s) => ({ ...s, graphContextTokens: tokens }))
|
||||
}
|
||||
onChange={(tokens) => saveDraft({ ...settings, graphContextTokens: tokens })}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Conversation, ConversationContent, ConversationEmptyState } from "@/com
|
||||
import { Composer } from "@/components/composer";
|
||||
import { DictationBar, useDictation } from "@/components/dictation";
|
||||
import { GraphContextControl, effectiveContextTokens } from "@/components/graph-context-control";
|
||||
import { useDraftSettings } from "@/components/draft-settings";
|
||||
import { PhaseChip } from "@/components/phase-divider";
|
||||
import { SidebarToggle } from "@/components/sidebar";
|
||||
import { StatsBar } from "@/components/stats-bar";
|
||||
@@ -150,9 +151,13 @@ export function NewSession() {
|
||||
const router = useRouter();
|
||||
const [text, setText] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
// The pre-chat model+thinking selection, lifted from the StatsBar's
|
||||
// ModelControl (empty chatId → it never PUTs; it hands the choice up).
|
||||
const [settings, setSettings] = useState<ChatSettings | undefined>(undefined);
|
||||
// The pre-chat model+thinking+context selection — the SHARED draft
|
||||
// record (draft-settings wave, 2026-09-18): /chat/new and the home
|
||||
// topic dock read and write ONE persisted choice, so what the learner
|
||||
// last left the controls on is what shows on return. ModelControl with
|
||||
// an empty chatId never PUTs — it hands the choice up; it still rides
|
||||
// the session POST then PUT-on-create.
|
||||
const { settings, save: saveDraft } = useDraftSettings();
|
||||
|
||||
const send = useCallback(() => {
|
||||
if (!text.trim() || busy) return;
|
||||
@@ -172,7 +177,7 @@ export function NewSession() {
|
||||
onChange={setText}
|
||||
onSend={send}
|
||||
settings={settings}
|
||||
onSettingsSaved={setSettings}
|
||||
onSettingsSaved={saveDraft}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -132,3 +132,11 @@ export const EMBEDDINGS_FILE = path.join(PATHS.graph, "embeddings.json");
|
||||
* read-modify-write. Shared shape/sanitizer: src/core/render-settings.ts.
|
||||
*/
|
||||
export const RENDER_SETTINGS_FILE = path.join(PATHS.graph, "render-settings.json");
|
||||
|
||||
/**
|
||||
* DRAFT (pre-session) settings — the model + thinking + knowledge-context
|
||||
* selections shared by the two new-session surfaces (the home graph view
|
||||
* and /chat/new). One small JSON blob, read-modify-write, written only
|
||||
* through the validated app/api/settings/draft route.
|
||||
*/
|
||||
export const DRAFT_SETTINGS_FILE = path.join(DATA_ROOT, "draft-settings.json");
|
||||
|
||||
@@ -11,6 +11,8 @@ export * from "./commit-positions.ts";
|
||||
export * from "./jobs.ts";
|
||||
export * from "./stores.ts";
|
||||
export { readRenderSettings, writeRenderSettings } from "../store/render-settings.ts";
|
||||
export { readDraftSettings, writeDraftSettings } from "../store/draft-settings.ts";
|
||||
export * from "./settings-body.ts";
|
||||
export * from "./turn-liveness.ts";
|
||||
export * from "./observability.ts";
|
||||
export * from "./model-catalog.ts";
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* The shared settings-PUT body parser — the one seam both settings routes
|
||||
* use (per-chat: app/api/chats/[id]/settings; pre-session draft:
|
||||
* app/api/settings/draft). Extracted verbatim from the per-chat route
|
||||
* (draft-settings wave, 2026-09-18): identical parse, identical errors.
|
||||
*
|
||||
* Replace-whole semantics: the client sends the complete desired object;
|
||||
* absent fields are absent overrides ({} clears everything). No merges, so
|
||||
* a stale client can never resurrect a cleared override.
|
||||
*/
|
||||
|
||||
import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
|
||||
import { GRAPH_CONTEXT_TOKENS_MAX, type ChatSettings } from "../core";
|
||||
|
||||
/** Parsed-or-rejected — `ok: false` carries the 400's error message. */
|
||||
export type SettingsBodyResult =
|
||||
| { ok: true; settings: ChatSettings }
|
||||
| { ok: false; error: string };
|
||||
|
||||
export function parseSettingsBody(body: unknown): SettingsBodyResult {
|
||||
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
||||
return { ok: false, error: "Invalid JSON body" };
|
||||
}
|
||||
const raw = body as {
|
||||
model?: { provider?: unknown; id?: unknown };
|
||||
thinkingLevel?: unknown;
|
||||
graphContextTokens?: unknown;
|
||||
};
|
||||
const settings: ChatSettings = {};
|
||||
if (raw.model !== undefined) {
|
||||
if (
|
||||
typeof raw.model !== "object" ||
|
||||
raw.model === null ||
|
||||
typeof raw.model.provider !== "string" ||
|
||||
typeof raw.model.id !== "string"
|
||||
) {
|
||||
return { ok: false, error: "model must be {provider, id}" };
|
||||
}
|
||||
settings.model = { provider: raw.model.provider, id: raw.model.id };
|
||||
}
|
||||
if (raw.thinkingLevel !== undefined) {
|
||||
if (typeof raw.thinkingLevel !== "string") {
|
||||
return { ok: false, error: "thinkingLevel must be a string" };
|
||||
}
|
||||
settings.thinkingLevel = raw.thinkingLevel as ThinkingLevel;
|
||||
}
|
||||
// Graph context injection budget (vision-context-injection.md): integer
|
||||
// tokens, 0 (off) to GRAPH_CONTEXT_TOKENS_MAX, no silent clamping — the
|
||||
// slider is the only writer, and it only ever sends multiples of the step.
|
||||
if (raw.graphContextTokens !== undefined) {
|
||||
if (
|
||||
typeof raw.graphContextTokens !== "number" ||
|
||||
!Number.isInteger(raw.graphContextTokens) ||
|
||||
raw.graphContextTokens < 0 ||
|
||||
raw.graphContextTokens > GRAPH_CONTEXT_TOKENS_MAX
|
||||
) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `graphContextTokens must be an integer between 0 and ${GRAPH_CONTEXT_TOKENS_MAX}`,
|
||||
};
|
||||
}
|
||||
settings.graphContextTokens = raw.graphContextTokens;
|
||||
}
|
||||
return { ok: true, settings };
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* Server-side persistence for the DRAFT (pre-session) settings — the
|
||||
* model + thinking-level + knowledge-context choices made on the
|
||||
* new-session surfaces (the home graph view's topic dock and /chat/new).
|
||||
* One small JSON blob: data/draft-settings.json, read-modify-write.
|
||||
*
|
||||
* Both surfaces share ONE record (owner, draft-settings wave 2026-09-18):
|
||||
* whatever the learner last left the controls on is what the next visit
|
||||
* shows — navigating away and back must not reset the feel. Per-session
|
||||
* settings live in the chat record (PUT /api/chats/:id/settings) and are
|
||||
* untouched by this.
|
||||
*
|
||||
* This module only moves bytes: the file is written exclusively through the
|
||||
* validated route (app/api/settings/draft — parseSettingsBody +
|
||||
* validateChatSettings gate every write), so no sanitizer runs here. On
|
||||
* read, anything unreadable/corrupt is null = first boot = config defaults.
|
||||
*/
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { DRAFT_SETTINGS_FILE } from "../../config.ts";
|
||||
import type { ChatSettings } from "../core";
|
||||
|
||||
/** The persisted draft settings, or null when never saved / unreadable. */
|
||||
export function readDraftSettings(): ChatSettings | null {
|
||||
let raw: string;
|
||||
try {
|
||||
raw = fs.readFileSync(DRAFT_SETTINGS_FILE, "utf-8");
|
||||
} catch {
|
||||
return null; // never saved / unreadable → the surfaces use config defaults
|
||||
}
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
||||
return parsed as ChatSettings;
|
||||
} catch {
|
||||
return null; // corrupt → defaults, never crash the surfaces
|
||||
}
|
||||
}
|
||||
|
||||
/** Persist the validated settings verbatim. */
|
||||
export function writeDraftSettings(settings: ChatSettings): void {
|
||||
fs.mkdirSync(path.dirname(DRAFT_SETTINGS_FILE), { recursive: true });
|
||||
fs.writeFileSync(DRAFT_SETTINGS_FILE, JSON.stringify(settings, null, "\t"), "utf-8");
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* Tests for the draft-settings wave (2026-09-18): the shared settings-body
|
||||
* parser (the one seam behind BOTH settings routes — per-chat and draft —
|
||||
* so their parse behavior is identical) and the draft-settings store
|
||||
* (data/draft-settings.json read/write, first-boot null semantics).
|
||||
*
|
||||
* The store tests write the real repo data file (npm test's shared data/,
|
||||
* disposable scratch by doctrine) and clean up after themselves.
|
||||
*/
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import { afterEach, describe, it } from "node:test";
|
||||
import { GRAPH_CONTEXT_TOKENS_MAX, type ChatSettings } from "../src/core";
|
||||
import { parseSettingsBody } from "../src/server/settings-body.ts";
|
||||
import { DRAFT_SETTINGS_FILE } from "../config.ts";
|
||||
import { readDraftSettings, writeDraftSettings } from "../src/store/draft-settings.ts";
|
||||
|
||||
describe("parseSettingsBody (shared by both settings routes)", () => {
|
||||
it("an empty object parses to {} — the clear-overrides write", () => {
|
||||
const r = parseSettingsBody({});
|
||||
assert.ok(r.ok);
|
||||
assert.deepEqual(r.ok ? r.settings : null, {});
|
||||
});
|
||||
|
||||
it("a full valid body parses field-for-field", () => {
|
||||
const r = parseSettingsBody({
|
||||
model: { provider: "openrouter", id: "z-ai/glm-5.3-flash" },
|
||||
thinkingLevel: "high",
|
||||
graphContextTokens: 256,
|
||||
});
|
||||
assert.ok(r.ok);
|
||||
assert.deepEqual(r.settings, {
|
||||
model: { provider: "openrouter", id: "z-ai/glm-5.3-flash" },
|
||||
thinkingLevel: "high",
|
||||
graphContextTokens: 256,
|
||||
});
|
||||
});
|
||||
|
||||
it("partial bodies keep only the present overrides (replace-whole)", () => {
|
||||
const r = parseSettingsBody({ thinkingLevel: "low" });
|
||||
assert.ok(r.ok);
|
||||
assert.deepEqual(r.settings, { thinkingLevel: "low" });
|
||||
});
|
||||
|
||||
it("rejects non-object bodies", () => {
|
||||
for (const body of ["junk", 42, [{}]]) {
|
||||
const r = parseSettingsBody(body);
|
||||
assert.equal(r.ok, false, JSON.stringify(body));
|
||||
if (!r.ok) assert.match(r.error, /Invalid JSON body/);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects malformed model and non-string thinkingLevel", () => {
|
||||
assert.equal(parseSettingsBody({ model: "nope" }).ok, false);
|
||||
assert.equal(parseSettingsBody({ model: { provider: 1, id: "x" } }).ok, false);
|
||||
assert.equal(parseSettingsBody({ thinkingLevel: 7 }).ok, false);
|
||||
});
|
||||
|
||||
it("rejects out-of-range or non-integer graphContextTokens — never clamps", () => {
|
||||
for (const bad of [-1, GRAPH_CONTEXT_TOKENS_MAX + 1, 64.5, "256"]) {
|
||||
const r = parseSettingsBody({ graphContextTokens: bad });
|
||||
assert.equal(r.ok, false, String(bad));
|
||||
}
|
||||
const ok = parseSettingsBody({ graphContextTokens: GRAPH_CONTEXT_TOKENS_MAX });
|
||||
assert.equal(ok.ok, true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the draft-settings store", () => {
|
||||
afterEach(() => {
|
||||
try {
|
||||
fs.rmSync(DRAFT_SETTINGS_FILE);
|
||||
} catch {
|
||||
/* nothing to clean */
|
||||
}
|
||||
});
|
||||
|
||||
it("reads null on first boot (no file) — the surfaces use config defaults", () => {
|
||||
try {
|
||||
fs.rmSync(DRAFT_SETTINGS_FILE);
|
||||
} catch {
|
||||
/* absent already */
|
||||
}
|
||||
assert.equal(readDraftSettings(), null);
|
||||
});
|
||||
|
||||
it("write then read roundtrips verbatim — validated shape, no sanitizer games", () => {
|
||||
const settings: ChatSettings = {
|
||||
model: { provider: "openrouter", id: "z-ai/glm-5.3-flash" },
|
||||
thinkingLevel: "high",
|
||||
graphContextTokens: 1024,
|
||||
};
|
||||
writeDraftSettings(settings);
|
||||
assert.deepEqual(readDraftSettings(), settings);
|
||||
});
|
||||
|
||||
it("an empty {} record roundtrips (all overrides cleared)", () => {
|
||||
writeDraftSettings({});
|
||||
assert.deepEqual(readDraftSettings(), {});
|
||||
});
|
||||
|
||||
it("a corrupt file reads as null — defaults, never a crash", () => {
|
||||
fs.rmSync(DRAFT_SETTINGS_FILE, { force: true }); // a directory from a broken earlier run also blocks
|
||||
fs.writeFileSync(DRAFT_SETTINGS_FILE, "{ not json", "utf-8");
|
||||
assert.equal(readDraftSettings(), null);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user