From 49bb1c331f451e6cbe2ed100a8a2297aafe29c38 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sun, 18 Oct 2026 17:47:15 +0800 Subject: [PATCH 1/4] fix: guard maybeRetry self-heal against a superseded respawn flight MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A self-heal origin fetch started under activation N could resolve after the agent was re-activated (originGen bumped), and its stale origin was written unconditionally into the live register — the same class of bug as #3616, reachable through the bootstrap guard's return value. Snapshot originGen before the fetch and drop the write when the world moved on. A post-giveUp revival is still allowed by design (#983): only the gen check is added, giveUpSeq is deliberately not consulted. --- src/agent/dsh-native.ts | 8 +++++++ tests/dsh-native.test.ts | 46 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/src/agent/dsh-native.ts b/src/agent/dsh-native.ts index 8da74f2eeb..2072d42bcf 100644 --- a/src/agent/dsh-native.ts +++ b/src/agent/dsh-native.ts @@ -988,9 +988,17 @@ function maybeRetry(ctx: PluginContext): void { state.respawn = respawn; } register.retryAt = Date.now() + retryIntervalMs(); + // #3616: same supersession rule as bootstrap()'s own guard — a + // self-heal flight that started in a previous origin world must not + // bind its (possibly stale) origin onto the current world's register + // when it lands. bootstrap()'s `if (gen !== originGen) return + // handle.origin` only covers its OWN writes; this .then wrote the + // returned origin unconditionally, so the guard was bypassed here. + const gen = originGen; void trackChain(respawn()) .then((origin) => { if (origin === undefined) return; + if (gen !== originGen) return; register.base = origin; state.origin = origin; void registerTools(ctx).catch(() => {}); diff --git a/tests/dsh-native.test.ts b/tests/dsh-native.test.ts index f3dbf35758..73bcd0a106 100644 --- a/tests/dsh-native.test.ts +++ b/tests/dsh-native.test.ts @@ -5,7 +5,7 @@ import os from "node:os"; import path from "node:path"; import http from "node:http"; import { pathToFileURL } from "node:url"; -import { apply, planNativeDsh, shouldBootstrapNativeDsh, persistClientEvent, _attributionHealthForTest, _resetAttributionHealthForTest, _resetRegisterForTest, _setModelInfoForTest, _setSpawnForTest, _setThrewRetryForTest, _settleNativeForTest, _stateHeadersForTest, _stateRespawnForTest, _stateTakeoverGateForTest, _stateToolsReadyForTest, _stateBeforeSendForTest, _stateOnResponseForTest, _noteRoutedForTest, _resetRoutedForTest, _resetWebProfileWarningForTest, _resetTitlesForTest, type PluginContext } from "../src/agent/dsh-native.ts"; +import { apply, planNativeDsh, shouldBootstrapNativeDsh, persistClientEvent, _attributionHealthForTest, _resetAttributionHealthForTest, _registerStateForTest, _resetRegisterForTest, _setModelInfoForTest, _setSpawnForTest, _setThrewRetryForTest, _settleNativeForTest, _stateHeadersForTest, _stateRespawnForTest, _stateTakeoverGateForTest, _stateToolsReadyForTest, _stateBeforeSendForTest, _stateOnResponseForTest, _noteRoutedForTest, _resetRoutedForTest, _resetWebProfileWarningForTest, _resetTitlesForTest, type PluginContext } from "../src/agent/dsh-native.ts"; import { __resetIncrementalClientForTests } from "../src/agent/incremental-client.ts"; import { BILI_COMPACTION_DISABLE_SERVICE } from "../src/agent/dsh-compaction-disable.ts"; import { once } from "node:events"; @@ -776,6 +776,50 @@ test("#3616 apply() attach mode: a superseded verify landing must not revert the } }); +// #3616 (maybeRetry self-heal): the base-less respawn flight has the same +// supersession rule as bootstrap()'s own guard — pre-fix its .then wrote +// register.base/state.origin unconditionally, so a flight started in world A +// that landed after a re-activation (world B) bound the STALE origin onto the +// new world's register, exactly the bypass #3616 closed everywhere else. +test("#3616 maybeRetry self-heal: a superseded respawn flight must not bind its stale origin", async () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-selfheal-")); + try { + await withEnv({ DSH_HOME: home, BILLION_CONTEXT_PROXY: undefined, BILI_DSH_RECOVERY_INTERVAL_MS: "5", BILI_PROVIDER_REWRITES: undefined, BILLION_CONTEXT_PLUGIN: undefined, BILI_NATIVE_DSH: undefined, BILI_MITM_HOSTS: undefined }, async () => { + _resetRegisterForTest(undefined); + let started = false; + let release: (() => void) | undefined; + const gate = new Promise((resolve) => { + release = resolve; + }); + _setSpawnForTest(() => { + started = true; + return gate.then(() => "http://stale-origin:1"); + }); + try { + const ctx1 = mockCtx(); + apply(ctx1); + // World A is base-less: the recovery timer's first tick arms the + // self-heal respawn (our stub) and leaves it IN FLIGHT on the gate. + await waitFor(() => started, "self-heal respawn flight started"); + // World switch: a re-activation bumps originGen and owns the + // register with a fresh base. + _resetRegisterForTest("http://new-origin:1"); + release?.(); + await _settleNativeForTest(); + // The stale flight landed AFTER the switch — it must write + // nothing. Pre-fix register.base reverted to http://stale-origin:1. + assert.equal(_registerStateForTest().base, "http://new-origin:1"); + } finally { + release?.(); + _setSpawnForTest(undefined); + _resetRegisterForTest(undefined); + } + }); + } finally { + rmrf(home); + } +}); + test("apply() /acp-cache (#1146): forwards acp_cache bound to the initiator session, falls back to latest", async () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-cache-")); try { From 98d0dce777d75f7dd74eb2042d9892d57467e701 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sun, 18 Oct 2026 17:47:21 +0800 Subject: [PATCH 2/4] fix: report real compression count in cold-load diagnostics MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit logColdLoad printed session.stats.tokensSaved, but since #2734 nothing in the tree increments that counter, so the line always showed a stale zero (tests hand-set 42000 to fake it). Read the kernel's live counter state.stats.compressionCount instead — it starts at 0, is bumped on every fold, and round-trips with the persisted state. --- src/persist.ts | 21 +++++++++++-------- tests/issue3573-cold-load-diagnostics.test.ts | 15 +++++++------ 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/src/persist.ts b/src/persist.ts index f9824d25dd..62f9fa9cd7 100644 --- a/src/persist.ts +++ b/src/persist.ts @@ -1160,21 +1160,24 @@ export class SessionStore { * guess into a one-line diagnosis. refs>0 with zero blocks is the * incident signature (#3573): identity loaded but every fold missing, so * the full history replays and preflight must rebuild from scratch. - * savedTok (stats.tokensSaved) disambiguates that signature in one grep: - * >0 proves compression ran in this session's lifetime, so zero blocks - * means folds existed and are now missing (investigate); 0 means the - * session was likely never folded (raw replay is its normal shape). The - * warn stays broad on purpose — a loss mode that erases stats must not - * be able to go silent again. */ + * compressions (state.stats.compressionCount) disambiguates that + * signature in one grep: >0 proves compression ran in this session's + * lifetime, so zero blocks means folds existed and are now missing + * (investigate); 0 means the session was likely never folded (raw replay + * is its normal shape). (#2734 removed the last writer of the legacy + * stats.tokensSaved counter — reading it here logged a dead 0 and broke + * exactly this disambiguation, so the diagnostic now reads the kernel's + * live counter instead.) The warn stays broad on purpose — a loss mode + * that erases stats must not be able to go silent again. */ private logColdLoad(id: string, source: string, session: Session, savedAt?: number): void { const refs = Object.keys(session.state.messageRefs.byRef ?? {}).length; const blocks = session.state.blocks.length; const active = session.state.blocks.filter((b) => b.active).length; - const savedTok = session.stats.tokensSaved; + const compressions = session.state.stats?.compressionCount ?? 0; const ageMin = savedAt ? Math.round(Math.max(0, Date.now() - savedAt) / 60000) : undefined; - this.log("info", `[persist] cold-loaded ${id} from ${source}: ${refs} ref(s), ${blocks} block(s) (${active} active), baseline ${session.stats.lastInputTokens} tok, savedTok ${savedTok}${ageMin !== undefined ? `, savedAt ~${ageMin} min ago` : ""}`); + this.log("info", `[persist] cold-loaded ${id} from ${source}: ${refs} ref(s), ${blocks} block(s) (${active} active), baseline ${session.stats.lastInputTokens} tok, compressions ${compressions}${ageMin !== undefined ? `, savedAt ~${ageMin} min ago` : ""}`); if (refs > 0 && blocks === 0) { - this.log("warn", `[persist] ${id} loaded with ${refs} mapped ref(s) but NO persisted blocks (savedTok=${savedTok}) — the folded history will replay raw and preflight must rebuild from scratch (#3573)`); + this.log("warn", `[persist] ${id} loaded with ${refs} mapped ref(s) but NO persisted blocks (compressions=${compressions}) — the folded history will replay raw and preflight must rebuild from scratch (#3573)`); } } diff --git a/tests/issue3573-cold-load-diagnostics.test.ts b/tests/issue3573-cold-load-diagnostics.test.ts index 9707dad21f..53387164cf 100644 --- a/tests/issue3573-cold-load-diagnostics.test.ts +++ b/tests/issue3573-cold-load-diagnostics.test.ts @@ -64,9 +64,12 @@ test("#3573: cold load carrying refs but NO persisted blocks warns loudly (the i const s = makeSession("s-ghost"); seedRefs(s, 6); s.stats.lastInputTokens = 119_940; - // The incident session HAD been folded — savedTok>0 is what makes the - // zero-blocks signature diagnosable (folds existed, now missing). - s.stats.tokensSaved = 42_000; + // The incident session HAD been folded — compressions>0 is what makes + // the zero-blocks signature diagnosable (folds existed, now missing). + // state.stats.compressionCount is the kernel's live counter + // (incremented on every fold); the legacy stats.tokensSaved used + // here pre-#2734 has no writer left and always logged 0. + s.state.stats.compressionCount = 42; await writer.writeNow(s); const logs: LogLine[] = []; @@ -79,11 +82,11 @@ test("#3573: cold load carrying refs but NO persisted blocks warns loudly (the i const info = logs.find((l) => l.level === "info" && l.msg.includes("cold-loaded s-ghost")); assert.ok(info, `an info line records what the cold load carried (logs: ${JSON.stringify(logs)})`); assert.match(info!.msg, /6 ref\(s\), 0 block\(s\) \(0 active\)/); - assert.match(info!.msg, /baseline 119940 tok, savedTok 42000/); + assert.match(info!.msg, /baseline 119940 tok, compressions 42/); const warn = logs.find((l) => l.level === "warn" && l.msg.includes("s-ghost")); assert.ok(warn, "refs-without-blocks must WARN — silence is exactly what made #3573 un-diagnosable"); - assert.match(warn!.msg, /6 mapped ref\(s\) but NO persisted blocks \(savedTok=42000\)/); + assert.match(warn!.msg, /6 mapped ref\(s\) but NO persisted blocks \(compressions=42\)/); assert.match(warn!.msg, /#3573/); } finally { rmrf(dir); @@ -145,7 +148,7 @@ test("#3573: a fresh empty state logs its counts and does not false-positive the const info = logs.find((l) => l.level === "info" && l.msg.includes("cold-loaded s-empty")); assert.ok(info, `an info line records the empty cold load (logs: ${JSON.stringify(logs)})`); assert.match(info!.msg, /0 ref\(s\), 0 block\(s\) \(0 active\)/); - assert.match(info!.msg, /savedTok 0/); + assert.match(info!.msg, /compressions 0/); assert.ok(!logs.some((l) => l.level === "warn" && l.msg.includes("s-empty")), "zero refs must NOT trigger the no-blocks warning"); } finally { rmrf(dir); From 3730a8a7a3058ce1d6575fcc8aa090d1953012a4 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sun, 18 Oct 2026 17:47:21 +0800 Subject: [PATCH 3/4] fix: startup audit must tolerate JSONC config files (#3572) auditStartupSummaryCredentials read the config file with strict safeReadJson, so a JSONC config (accepted by the runtime loader since #3572) logged a bogus parse error and silently skipped the global external-summary chain at boot. Route the boot audit through loadConfigFile, which uses the tolerant parser and never throws. The per-route chain already went through loadRoutes and was correct. --- src/external-summary-credentials.ts | 10 +++++++--- tests/issue3488-credential-status.test.ts | 22 ++++++++++++++++++++++ 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/external-summary-credentials.ts b/src/external-summary-credentials.ts index 5b44e83a5b..b07ba7e24e 100644 --- a/src/external-summary-credentials.ts +++ b/src/external-summary-credentials.ts @@ -2,7 +2,7 @@ import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readF import { dirname } from "node:path"; import { randomUUID } from "node:crypto"; import { configFile } from "./paths.js"; -import { loadNamedProviders, loadRoutes, safeReadJson, type NamedProviderRecipe } from "./config.js"; +import { loadConfigFile, loadNamedProviders, loadRoutes, type NamedProviderRecipe } from "./config.js"; import { expandExternalSummaryChain, parseExternalSummaryChain, validSummaryCredentialName } from "./external-summary-settings.js"; function validKey(value: unknown): value is string { @@ -135,8 +135,12 @@ export function auditExternalSummaryCredentials(block: unknown, recipes: Record< * because one file object can be effective for many slots. Returns * human-readable problem lines (empty when everything resolves). */ export function auditStartupSummaryCredentials(env: NodeJS.ProcessEnv = process.env): string[] { - const file = safeReadJson(configFile()); - const compress = file && typeof file === "object" && !Array.isArray(file) ? (file as { compress?: unknown }).compress : undefined; + // #3572/#3488: read the global block through loadConfigFile()'s tolerant + // JSONC parser (the same one the runtime loader uses). safeReadJson is + // strict JSON — a commented config silently evaluated to `file === null` + // here, skipping the boot audit for every global externalSummary chain + // while route-level chains (loadRoutes → loadConfigFile) still audited. + const compress = loadConfigFile().compress; const globalBlock = compress && typeof compress === "object" && !Array.isArray(compress) ? (compress as { externalSummary?: unknown }).externalSummary : undefined; const routes = loadRoutes(env); const recipes = loadNamedProviders(env); diff --git a/tests/issue3488-credential-status.test.ts b/tests/issue3488-credential-status.test.ts index 1767ae5bd7..4803232304 100644 --- a/tests/issue3488-credential-status.test.ts +++ b/tests/issue3488-credential-status.test.ts @@ -127,6 +127,28 @@ test("startup audit walks the global/route/model cascade and reports each effect assert.deepEqual(auditStartupSummaryCredentials({ AUDIT_A: "key-a", AUDIT_B: "key-b" }), []); }); +// #3572/#3488: the startup audit reads the GLOBAL block through +// loadConfigFile()'s tolerant JSONC parser. Pre-fix it used strict safeReadJson, +// so a commented config evaluated to null and every global externalSummary +// chain silently skipped the boot audit (route chains still audited — the +// asymmetry masked the bug). +test("startup audit still walks the global chain when the config file is JSONC", () => { + writeFileSync(biliConfig, [ + "{ // commented config — valid JSONC, valid at runtime (#3572)", + " \"providers\": {", + " \"nexus\": { \"baseUrl\": \"http://127.0.0.1:9/v1\", \"api\": \"openai\", \"apiKeyEnv\": \"AUDIT_A\", \"models\": { \"free\": {} } },", + " },", + " \"compress\": { \"externalSummary\": { \"enabled\": true, \"targets\": [\"nexus/free\"] }, }, // trailing comma", + "}", + ].join("\n") + "\n", "utf8"); + + const problems = auditStartupSummaryCredentials({}); + assert.equal(problems.length, 1, `the global chain must still be audited (got: ${JSON.stringify(problems)})`); + assert.ok(problems[0].includes("AUDIT_A is not set")); + + assert.deepEqual(auditStartupSummaryCredentials({ AUDIT_A: "key-a" }), []); +}); + function captureConfigGet(): Promise> { return new Promise((resolve, reject) => { const res = { From ed14be908c60bf457d831d759856be3552696e4d Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sun, 18 Oct 2026 17:47:21 +0800 Subject: [PATCH 4/4] fix: web editor accepts JSONC config text (#3572, #3488) The server accepts JSONC since #3572, but the web client still strict- parsed the draft in five places: quick-config hydrate, freshDraft, summary hydrate read(), save-quick and save-file. A user with a JSONC config saw the quick panel vanish (#3488) and could not save. Add one tolerant parser (strict JSON first, then comment/trailing-comma stripping) defined once in the TS module, inlined into the browser IIFE via toString(), and used by all five call sites. A genuinely broken draft still throws locally and the server's parseBiliConfig remains the authoritative check on save. --- src/web/client.ts | 122 ++++++++++++++++++++- tests/issue3572-client-draft-parse.test.ts | 76 +++++++++++++ 2 files changed, 193 insertions(+), 5 deletions(-) create mode 100644 tests/issue3572-client-draft-parse.test.ts diff --git a/src/web/client.ts b/src/web/client.ts index 35d1df6932..cc06cd3e04 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -1,7 +1,119 @@ import { MESSAGES } from "./i18n.js"; +// #3572 (client half): the server accepts JSONC config files (comments + +// trailing commas) since the parseBiliConfig fix, but the web editor still +// strict-parses the draft text in five places — so a user with a JSONC config +// sees the quick-config panel vanish (#3488) and cannot save. These three pure +// helpers implement the same tolerance client-side; they live in the TS module +// (importable by tests) and are inlined into the browser IIFE below via +// toString(), so there is exactly one implementation. +export function stripJsoncComments(text: string): string { + let out = ""; + let i = 0; + let inString = false; + while (i < text.length) { + const c = text.charAt(i); + const d = i + 1 < text.length ? text.charAt(i + 1) : ""; + if (inString) { + out += c; + if (c === "\\") { + if (d !== "") { + out += d; + i += 2; + continue; + } + } else if (c === '"') inString = false; + i += 1; + continue; + } + if (c === '"') { + inString = true; + out += c; + i += 1; + continue; + } + // Comments become spaces (not deleted) so JSON.parse error offsets stay honest. + if (c === "/" && d === "/") { + while (i < text.length && text.charAt(i) !== "\n") { + out += " "; + i += 1; + } + continue; + } + if (c === "/" && d === "*") { + while (i < text.length && !(text.charAt(i) === "*" && text.charAt(i + 1) === "/")) { + out += text.charAt(i) === "\n" ? "\n" : " "; + i += 1; + } + out += " "; // the closing */ — kept as spaces so offsets stay honest + i += 2; + continue; + } + out += c; + i += 1; + } + return out; +} + +// Second pass, string-aware: drop a comma only when the next meaningful char +// closes the current object/array. Run AFTER stripJsoncComments so commas and +// closers inside string literals are the only ones left to protect. +export function stripJsoncTrailingCommas(text: string): string { + let out = ""; + let i = 0; + let inString = false; + while (i < text.length) { + const c = text.charAt(i); + if (inString) { + out += c; + if (c === "\\") { + const d = i + 1 < text.length ? text.charAt(i + 1) : ""; + if (d !== "") { + out += d; + i += 2; + continue; + } + } else if (c === '"') inString = false; + i += 1; + continue; + } + if (c === '"') { + inString = true; + out += c; + i += 1; + continue; + } + if (c === ",") { + let j = i + 1; + while (j < text.length && " \t\r\n".includes(text.charAt(j))) j += 1; + if (j < text.length && (text.charAt(j) === "}" || text.charAt(j) === "]")) { + i += 1; + continue; + } + } + out += c; + i += 1; + } + return out; +} + +// Strict JSON first so a valid file takes the exact same path as before; +// fall back to the JSONC tolerance above; a genuinely malformed draft still +// throws, and the server's parseBiliConfig remains the authoritative check on save. +export function parseConfigDraft(text: string): unknown { + try { + return JSON.parse(text); + } catch { + // fall through to the tolerant path + } + return JSON.parse(stripJsoncTrailingCommas(stripJsoncComments(text))); +} + export const WEB_CLIENT = `(function () { "use strict"; + const stripJsoncComments = ${stripJsoncComments.toString()}; + const stripJsoncTrailingCommas = ${stripJsoncTrailingCommas.toString()}; + const parseConfigDraft = ${parseConfigDraft.toString()}; const MESSAGES=${JSON.stringify(MESSAGES)}; let locale = "zh-CN"; try { @@ -2202,7 +2314,7 @@ export const WEB_CLIENT = `(function () { box.innerHTML = ""; const fe = $("cfg-file-edit"); let draft = {}; - try { draft = JSON.parse(fe && fe.value ? fe.value : "{}"); if (!draft || typeof draft !== "object" || Array.isArray(draft)) draft = {}; } catch (e) { return; } + try { const p = parseConfigDraft(fe && fe.value ? fe.value : "{}"); draft = p && typeof p === "object" && !Array.isArray(p) ? p : {}; } catch (e) { return; } function compressOf(d) { return (d.compress && typeof d.compress === "object" && !Array.isArray(d.compress)) ? d.compress : null; } const NUDGE_DEFAULT = 50000, NUDGE_STEP = 5000, NUDGE_LOW = 20000, NUDGE_HIGH = 100000; const PRM_KERNEL_DEFAULT = 3; @@ -2216,7 +2328,7 @@ export const WEB_CLIENT = `(function () { } function freshDraft() { try { - const p = JSON.parse(fe && fe.value ? fe.value : "{}"); + const p = parseConfigDraft(fe && fe.value ? fe.value : "{}"); if (!p || typeof p !== "object" || Array.isArray(p)) return {}; return p; } catch (e) { quickBroken(true); return null; } @@ -2554,7 +2666,7 @@ export const WEB_CLIENT = `(function () { // #3488: five-state view; falls back to the legacy boolean on old servers. const detail = cfg.externalSummaryCredentialStatus || {}; function read() { - const draft = JSON.parse(fe.value || "{}"); + const draft = parseConfigDraft(fe.value || "{}"); if (!draft || typeof draft !== "object" || Array.isArray(draft)) throw new Error(t("cfg.invalid_json")); return draft; } @@ -2899,7 +3011,7 @@ export const WEB_CLIENT = `(function () { const el = $("cfg-file-edit"); const raw = el ? el.value : ""; let parsed; - try { parsed = JSON.parse(raw || "{}"); } catch (e) { toast(t("cfg.invalid_json"), "err"); return; } + try { parsed = parseConfigDraft(raw || "{}"); } catch (e) { toast(t("cfg.invalid_json"), "err"); return; } if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) { toast(t("cfg.invalid_json"), "err"); return; } await putCfg(sq, { file: raw }); }); @@ -2911,7 +3023,7 @@ export const WEB_CLIENT = `(function () { const el = $("cfg-file-edit"); const raw = el ? el.value : ""; let parsed; - try { parsed = JSON.parse(raw || "{}"); } catch (e) { toast(t("cfg.invalid_json"), "err"); return; } + try { parsed = parseConfigDraft(raw || "{}"); } catch (e) { toast(t("cfg.invalid_json"), "err"); return; } if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) { toast(t("cfg.invalid_json"), "err"); return; } await putCfg(sf, { file: raw }); }); diff --git a/tests/issue3572-client-draft-parse.test.ts b/tests/issue3572-client-draft-parse.test.ts new file mode 100644 index 0000000000..bd1d8d0036 --- /dev/null +++ b/tests/issue3572-client-draft-parse.test.ts @@ -0,0 +1,76 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { WEB_CLIENT, parseConfigDraft, stripJsoncComments, stripJsoncTrailingCommas } from "../src/web/client.ts"; + +// #3572 (client half): the server accepts JSONC config files (comments + trailing +// commas), but the web editor used to strict-parse the draft text in five places +// (quick-config hydrate, freshDraft, summary hydrate read(), save-quick, save-file), +// so a JSONC config made the quick panel vanish (#3488) and blocked saves. The +// helpers live in the TS module and are inlined into the browser IIFE via +// toString() — one implementation, exercised directly here plus a syntax check on +// the assembled client string. + +test("parseConfigDraft: strict JSON takes the fast path unchanged", () => { + assert.deepEqual(parseConfigDraft('{"providers":{}}'), { providers: {} }); + assert.deepEqual(parseConfigDraft("[]"), []); + assert.equal(parseConfigDraft("null"), null); +}); + +test("parseConfigDraft: comments and trailing commas are tolerated", () => { + const draft = `{ + // upstream relay + "compress": { "targets": ["a", "b",], }, + /* block note */ + "upstreamProxy": null, + }`; + const parsed = parseConfigDraft(draft) as Record; + assert.deepEqual(parsed.compress, { targets: ["a", "b"] }); + assert.equal(parsed.upstreamProxy, null); + assert.equal(parsed["/* block note */"], undefined); +}); + +test("parseConfigDraft: string literals containing //, */, commas and brackets survive", () => { + const draft = '{"a": "x // not a comment", "b": "y /* nope */,]", "c": "esc\\\\"}'; + const parsed = parseConfigDraft(draft) as Record; + assert.equal(parsed.a, "x // not a comment"); + assert.equal(parsed.b, "y /* nope */,]"); + assert.equal(parsed.c, "esc\\"); +}); + +test("parseConfigDraft: genuinely malformed text still throws", () => { + assert.throws(() => parseConfigDraft("{")); + assert.throws(() => parseConfigDraft('{"a": ')); + assert.throws(() => parseConfigDraft("// only a comment")); + assert.throws(() => parseConfigDraft('{"a":1,,}')); + // Documented tolerance beyond jsonc-parser: a lone stray comma before a + // closer ({,} / [x,]) is dropped too. Harmless — the server's parseBiliConfig + // stays authoritative on save and rejects the original text. + assert.deepEqual(parseConfigDraft("{,}"), {}); +}); + +test("stripJsoncComments: comments become spaces, newlines preserved for error offsets", () => { + const stripped = stripJsoncComments('{\n // line\n /* block */ "a": 1\n}'); + assert.equal(stripped, '{\n ' + ' '.repeat(7) + '\n ' + ' '.repeat(11) + ' "a": 1\n}'); + assert.equal(stripped.length, '{\n // line\n /* block */ "a": 1\n}'.length, "comment stripping must be length-preserving"); + assert.equal(stripJsoncComments('{"a":"s//b"}'), '{"a":"s//b"}'); +}); + +test("stripJsoncTrailingCommas: drops only real trailing commas", () => { + assert.equal(stripJsoncTrailingCommas('{"a":1,}'), '{"a":1}'); + assert.equal(stripJsoncTrailingCommas('[1, 2 , ]'), '[1, 2 ]'); + assert.equal(stripJsoncTrailingCommas('{"a": "keep, me"}'), '{"a": "keep, me"}'); + // comma inside a string before a bracket must NOT be treated as trailing + assert.equal(stripJsoncTrailingCommas('{"a": "x,]"}'), '{"a": "x,]"}'); +}); + +test("WEB_CLIENT embeds the tolerant parser and stays valid JS", () => { + assert.ok(WEB_CLIENT.includes("parseConfigDraft"), "client IIFE must embed parseConfigDraft"); + assert.ok(WEB_CLIENT.includes("stripJsoncComments"), "client IIFE must embed stripJsoncComments"); + // web-routing.test.ts already compiles the whole string with new Function(); + // here we additionally execute the embedded copy and prove it behaves the same. + const grab = WEB_CLIENT.replace(/^[\s\S]*?(?=const stripJsoncComments)/, ""); + const start = grab.indexOf("const stripJsoncComments"); + const fn = new Function(`${grab.slice(start, grab.indexOf("const MESSAGES"))}; return parseConfigDraft;`)(); + assert.deepEqual(fn('{"a":1,}'), { a: 1 }); + assert.throws(() => fn("{oops")); +});