From e3dee58304b631ebd49c22c1f46890a848fc2375 Mon Sep 17 00:00:00 2001 From: ci-check Date: Mon, 26 Oct 2026 04:37:16 +0800 Subject: [PATCH 1/2] fix: honest titles and diagnostics for clients without stable conversation ids (#4776) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closed-source harnesses like WorkBuddy/CodeBuddy send none of the conversation-id headers, so bili mints pfa-* sessions by content affinity — and every fork/resume mints another one. Three surfaces then lied or degraded: derived titles captured host XML wrappers verbatim (139 of 166 session titles were raw injection text), /__bili/status reported zero splits while 144 anonymous splits existed, and the mint log never named the identity gap. - deriveTitle: skip tag-shaped user-text openers (structural rule, not a keyword list); stored markup titles re-derive on the session's next request in all four prepare lanes (#2286 self-heal pattern) - web UI: a markup-shaped title falls through to label/firstBlockHint instead of shadowing them forever (list cell + detail head); the raw stored value stays visible in the detail KV row - /__bili/status: additive anonymousIdentity {total,forkBorn,truncatedBorn} counted from session metadata; splitSessions keeps its #2165 shared-base canary meaning untouched - prefix-affinity mint log lines now state the id is content-affinity derived and unstable across forks - anonymousPrefixAffinity.lineage is sticky across continuation turns (latest-wins erased the birth attribution after the second request) --- src/server.ts | 25 ++++++- src/server/admin.ts | 10 ++- src/server/handle.ts | 19 +++-- src/server/prepare-anthropic.ts | 4 +- src/server/prepare-google.ts | 4 +- src/server/prepare-openai.ts | 4 +- src/server/prepare-responses.ts | 4 +- src/session.ts | 25 +++++++ src/web/client.ts | 18 ++++- tests/issue4776-anonymous-identity.test.ts | 80 ++++++++++++++++++++++ tests/title-derive.test.ts | 71 ++++++++++++++++++- 11 files changed, 240 insertions(+), 24 deletions(-) create mode 100644 tests/issue4776-anonymous-identity.test.ts diff --git a/src/server.ts b/src/server.ts index 2dd74daee8..bb8c3d8383 100644 --- a/src/server.ts +++ b/src/server.ts @@ -4097,11 +4097,29 @@ export function isAutoInjectedNotification(text: string): boolean { return AUTO_INJECTED_NOTIFICATION_PREFIXES.some((p) => asciiCI(t.slice(0, p.length), p)); } +// Host-injected XML-wrapped context fragments (WorkBuddy/CodeBuddy, #4776): +// closed-source harnesses splice machine-generated wrappers into the +// conversation as USER-role messages ahead of the first real question — +// `…`, +// `…`, `…`, `…`, `…`. The +// marker/prefix permitlists above are per-host and cannot keep up with +// closed-source harnesses, so this one is a STRUCTURAL rule instead: a +// tag-shaped opener identifies no human question on any host observed so far, +// while real user text essentially never opens with a tag. A literal paste +// that does (e.g. HTML being debugged) only DEFERS the title to the next +// message — self-healing — whereas adopting it locks a garbage title behind +// set-once semantics. That consequence asymmetry is what licenses deviating +// from the evidence-permitlist discipline used by the two checks above. +export function isTagShapedText(text: string): boolean { + const t = text.trim(); + return /^<\/?[a-z_][\w:.-]*/i.test(t); +} + /** Derive a short human-readable title from the first real user text message. * Used so the web UI can show "Fix auth bug" instead of an opaque hash. - * Contextual fragments (#2118) and host-injected notifications (#2286) are - * skipped — if no real question has arrived yet, no title is set and - * derivation retries on later requests. */ + * Contextual fragments (#2118), host-injected notifications (#2286) and + * tag-shaped wrapper openers (#4776) are skipped — if no real question has + * arrived yet, no title is set and derivation retries on later requests. */ export function deriveTitle(messages: CoreMessage[]): string | undefined { for (const m of messages) { if (m.role !== "user" || m.contentType !== "text") continue; @@ -4109,6 +4127,7 @@ export function deriveTitle(messages: CoreMessage[]): string | undefined { if (!raw.trim()) continue; if (isContextualUserFragment(raw)) continue; if (isAutoInjectedNotification(raw)) continue; + if (isTagShapedText(raw)) continue; const clean = raw.replace(/\s+/g, " ").trim(); return clean.length > 60 ? clean.slice(0, 57) + "\u2026" : clean; } diff --git a/src/server/admin.ts b/src/server/admin.ts index bd0fb963e9..a1d4cc1b05 100644 --- a/src/server/admin.ts +++ b/src/server/admin.ts @@ -22,7 +22,7 @@ import { getUnrecognizedPathStats } from "./observability.js"; import { getStore } from "../persist.js"; import { BodyTooLargeError, headerValue, readBody } from "../server.js"; import { dismissHostPlugin, visibleHostPluginNotices } from "../host-plugin-notice.js"; -import { listSessions, memoryReport, peekSession, splitSessionWarnings, totalInFlight } from "../session.js"; +import { anonymousIdentitySummary, listSessions, memoryReport, peekSession, splitSessionWarnings, totalInFlight } from "../session.js"; import { BILI_TUNNEL_HEADER } from "../tunnel-guard.js"; import { isLoopbackAddress } from "../util.js"; import { clearUpstreamAlertsForHost, getUpstreamAlerts } from "../upstream-alerts.js"; @@ -1185,14 +1185,18 @@ async function sendStatus(res: http.ServerResponse, opts: ProxyOptions, laneHost // fs hiccup: report running state only, never fail the status endpoint } res.writeHead(200, { "content-type": "application/json" }); - const splitWarnings = splitSessionWarnings(listSessions()); + const statusSessions = listSessions(); + const splitWarnings = splitSessionWarnings(statusSessions); for (const w of splitWarnings) { if (!splitWarnedBases.has(w.base)) { splitWarnedBases.add(w.base); loggerLog("warn", `split-session canary (#2170): conversation ${w.base} has live traffic under multiple session keys (design persona forks are excluded): ${w.sessions.map((s) => `${s.id} (requests=${s.requests})`).join("; ")}. For a non-persona host this is the #2165 failure shape (stolen anchor / never-compressing split) — investigate if unexpected.`); } } - res.end(JSON.stringify({ version: VERSION, commit: BUILD_COMMIT, origin: laneHost ?? null, diskVersion, stale, lastInstall, updateReady: updateReadyPayload(), autoRestartOnUpdate: opts.autoRestartOnUpdate, advisory: currentAdvisoryPayload(), updatePolicy: updatePolicyPayload(), pluginAdvisories: detectCostAdvisories(process.env), inFlight: totalInFlight(), splitSessions: splitWarnings, conflicts: summarizeConflicts(listSessions()), storage: storageStatusWire(), snapshotShadow: snapshotShadowStatusWire(), attribution: attributionStatusWire() }, null, 2)); + // #4776: additive honest count for identity-less clients — splitSessions above + // is the #2165 shared-base canary and structurally blind to pfa-* forks. + const anonymousIdentity = anonymousIdentitySummary(statusSessions); + res.end(JSON.stringify({ version: VERSION, commit: BUILD_COMMIT, origin: laneHost ?? null, diskVersion, stale, lastInstall, updateReady: updateReadyPayload(), autoRestartOnUpdate: opts.autoRestartOnUpdate, advisory: currentAdvisoryPayload(), updatePolicy: updatePolicyPayload(), pluginAdvisories: detectCostAdvisories(process.env), inFlight: totalInFlight(), splitSessions: splitWarnings, anonymousIdentity, conflicts: summarizeConflicts(statusSessions), storage: storageStatusWire(), snapshotShadow: snapshotShadowStatusWire(), attribution: attributionStatusWire() }, null, 2)); } // #2090 plan A — read-only view backing the web UI's "Signed upstreams" card: diff --git a/src/server/handle.ts b/src/server/handle.ts index 1ec676fcd4..f917e8ee4e 100644 --- a/src/server/handle.ts +++ b/src/server/handle.ts @@ -1275,8 +1275,12 @@ async function handleRequest( anonProvenance = buildAnonymousProvenance(req.headers, affinityMessageList(), req.socket?.remoteAddress); const provSuffix = `; ua=${JSON.stringify(anonProvenance.ua ?? "-")} plugin=${anonProvenance.pluginAgent ?? "-"} first=${JSON.stringify(anonProvenance.firstMsg ?? "-")}`; const lineage = anonAffinity.lineage ? `; lineage=${anonAffinity.lineage.reason} of ${anonAffinity.lineage.parents.join(",")}` : ""; - log("info", `[prefix-affinity] new anonymous session ${anonAffinity.sessionId} (depth=${anonAffinity.incomingDepth}, tail=${anonAffinity.tailHash.slice(0, 8)}${lineage}${provSuffix})`); - loggerLog("info", `[prefix-affinity] new session ${anonAffinity.sessionId} at depth ${anonAffinity.incomingDepth} (tail=${anonAffinity.tailHash.slice(0, 8)}${lineage}${provSuffix})`); + // #4776: name the identity gap at the ONE observable moment — this + // client sent no stable conversation id, so the pfa-* id is + // content-affinity-derived and will split again on fork/resume. + const identityNote = "; no client-provided conversation id - content-affinity identity, unstable across forks"; + log("info", `[prefix-affinity] new anonymous session ${anonAffinity.sessionId} (depth=${anonAffinity.incomingDepth}, tail=${anonAffinity.tailHash.slice(0, 8)}${lineage}${provSuffix}${identityNote})`); + loggerLog("info", `[prefix-affinity] new session ${anonAffinity.sessionId} at depth ${anonAffinity.incomingDepth} (tail=${anonAffinity.tailHash.slice(0, 8)}${lineage}${provSuffix}${identityNote})`); // A verified anonymous history replay is evidence of possible // identity loss, not proof that the identified client moved. if (anonAffinity.orphanSuspect !== undefined && anonAffinity.orphanSuspect.length > 0) { @@ -1430,14 +1434,17 @@ async function handleRequest( if (anonAffinity) { prefixAffinity.note(sessionId, anonAffinity.incomingDepth, anonAffinity.tailHash, anonAffinity.itemHashes, false, anonAffinity.sketches, anonAffinity.userFlags, undefined, anonAffinity.tailFragments); scheduleAffinityPersist(); - // The rest of this stamp is latest-wins; `producer` is NOT — the - // mint request's fingerprint must survive every later turn (#2879). - const existingProducer = (session.metadata.anonymousPrefixAffinity as { producer?: AnonymousProvenance } | undefined)?.producer; + // The rest of this stamp is latest-wins; `producer` and `lineage` are NOT — + // both exist only on the mint request (via==="new"), so latest-wins would + // erase them on the first continuation turn: the mint fingerprint (#2879) + // and the birth attribution that /__bili/status counts on (#4776). + const existingApa = session.metadata.anonymousPrefixAffinity as { producer?: AnonymousProvenance; lineage?: { parents: string[]; reason: "truncated" | "forked"; sharedPrefix?: number } } | undefined; + const existingProducer = existingApa?.producer; session.metadata.anonymousPrefixAffinity = { depth: anonAffinity.incomingDepth, tailHash: anonAffinity.tailHash, via: anonAffinity.via, - ...(anonAffinity.lineage ? { lineage: anonAffinity.lineage } : {}), + ...(anonAffinity.lineage ? { lineage: anonAffinity.lineage } : existingApa?.lineage ? { lineage: existingApa.lineage } : {}), ...(existingProducer ? { producer: existingProducer } : anonProvenance ? { producer: anonProvenance } : {}), }; } else if (clientProvided) { diff --git a/src/server/prepare-anthropic.ts b/src/server/prepare-anthropic.ts index fa57f1e68e..e4133d6408 100644 --- a/src/server/prepare-anthropic.ts +++ b/src/server/prepare-anthropic.ts @@ -7,7 +7,7 @@ import { captureThreadsTurn, estimateThreadsTokens, isThreadsBody, threadsReforg import type { CompressReasoningConfig } from "../reasoning-drop.js"; import type { ProxyOptions } from "../config.js"; import { pluginAgentHeader } from "../plugin.js"; -import { applyReasoningDrop, diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, planReasoningDrop, reapOrphansLogged, runNudgeDecision, stripKernelSummaries, warnAnthropicThinkingPairs, type Prepared } from "../server.js"; +import { applyReasoningDrop, diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, isTagShapedText, planReasoningDrop, reapOrphansLogged, runNudgeDecision, stripKernelSummaries, warnAnthropicThinkingPairs, type Prepared } from "../server.js"; import { buildDecisionPrompt, buildDirectiveText, consumeFallback, ladderMode, resolveDecisionRange, stripDecisionReasoningFields, type DecideConfig } from "../nudge-decide.js"; import { excludeDeadRefRanges } from "../acp-status.js"; import { reconcileFoldCoverage, noteSystemPromptFingerprint, resolveFoldReconcileMode } from "../fold-reconcile.js"; @@ -379,7 +379,7 @@ export async function prepareAnthropic( nudge = turn.nudge; session.stats.contextTokens = tokenCount; session.stats.contextTokensSource = tokenCountSource; - if (!session.meta.title || isAutoInjectedNotification(session.meta.title)) { + if (!session.meta.title || isAutoInjectedNotification(session.meta.title) || isTagShapedText(session.meta.title)) { const t = deriveTitle(msgs); if (t) session.meta.title = t; } diff --git a/src/server/prepare-google.ts b/src/server/prepare-google.ts index 0fa7957240..79a45c63cb 100644 --- a/src/server/prepare-google.ts +++ b/src/server/prepare-google.ts @@ -5,7 +5,7 @@ import { coreToGoogle, googleToCore, normalizeGoogleUserPartOrder, type BiliMess import type { ProxyOptions } from "../config.js"; import { pluginAgentHeader } from "../plugin.js"; import { currentCalibrationFactor } from "../util.js"; -import { diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, reapOrphansLogged, resolveKnownOutputCeiling, runNudgeDecision, stripKernelSummaries, usageGradeInputBaseline, type Prepared } from "../server.js"; +import { diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, isTagShapedText, reapOrphansLogged, resolveKnownOutputCeiling, runNudgeDecision, stripKernelSummaries, usageGradeInputBaseline, type Prepared } from "../server.js"; import { buildDecisionPrompt, buildDirectiveText, consumeFallback, ladderMode, resolveDecisionRange, stripDecisionReasoningFields, type DecideConfig } from "../nudge-decide.js"; import { excludeDeadRefRanges } from "../acp-status.js"; import { reconcileFoldCoverage, noteSystemPromptFingerprint, resolveFoldReconcileMode } from "../fold-reconcile.js"; @@ -215,7 +215,7 @@ export async function prepareGoogle( nudge = turn.nudge; session.stats.contextTokens = tokenCount; session.stats.contextTokensSource = tokenCountSource; - if (!session.meta.title || isAutoInjectedNotification(session.meta.title)) { + if (!session.meta.title || isAutoInjectedNotification(session.meta.title) || isTagShapedText(session.meta.title)) { const t = deriveTitle(msgs); if (t) session.meta.title = t; } diff --git a/src/server/prepare-openai.ts b/src/server/prepare-openai.ts index 0767039e0b..16a865e445 100644 --- a/src/server/prepare-openai.ts +++ b/src/server/prepare-openai.ts @@ -7,7 +7,7 @@ import type { ProxyOptions } from "../config.js"; import { currentCalibrationFactor, hardenOpenaiAssistantContent, systemToUser } from "../util.js"; import { conversationHeaderSource, resolveRelayAffinityPck } from "../session-id.js"; import { pluginAgentHeader } from "../plugin.js"; -import { applyReasoningDrop, diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, planReasoningDrop, reapOrphansLogged, resolveKnownOutputCeiling, runNudgeDecision, stripKernelSummaries, warnDroppedOpenaiParts, warnReasoningPairs, type Prepared } from "../server.js"; +import { applyReasoningDrop, diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, isTagShapedText, planReasoningDrop, reapOrphansLogged, resolveKnownOutputCeiling, runNudgeDecision, stripKernelSummaries, warnDroppedOpenaiParts, warnReasoningPairs, type Prepared } from "../server.js"; import { buildDecisionPrompt, buildDirectiveText, consumeFallback, ladderMode, resolveDecisionRange, stripDecisionReasoningFields, type DecideConfig } from "../nudge-decide.js"; import { excludeDeadRefRanges } from "../acp-status.js"; import { reconcileFoldCoverage, noteSystemPromptFingerprint, resolveFoldReconcileMode } from "../fold-reconcile.js"; @@ -233,7 +233,7 @@ export async function prepareOpenai( nudge = turn.nudge; session.stats.contextTokens = tokenCount; session.stats.contextTokensSource = tokenCountSource; - if (!session.meta.title || isAutoInjectedNotification(session.meta.title)) { + if (!session.meta.title || isAutoInjectedNotification(session.meta.title) || isTagShapedText(session.meta.title)) { const t = deriveTitle(msgs); if (t) session.meta.title = t; } diff --git a/src/server/prepare-responses.ts b/src/server/prepare-responses.ts index b69820843e..f52ac02219 100644 --- a/src/server/prepare-responses.ts +++ b/src/server/prepare-responses.ts @@ -6,7 +6,7 @@ import type { CompressReasoningConfig } from "../reasoning-drop.js"; import { resolveAbsorbSettings } from "../compress-settings.js"; import { resolveCompressProtocol, type CompressSettings, type ProxyOptions } from "../config.js"; import { currentCalibrationFactor, strippedResponseIdWarning } from "../util.js"; -import { applyReasoningDrop, diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, planReasoningDrop, repairResponsesAssistantOrdering, reapOrphansLogged, resolveKnownOutputCeiling, runNudgeDecision, stripKernelSummaries, usageGradeInputBaseline, warnResponsesReasoningPairs, type Prepared } from "../server.js"; +import { applyReasoningDrop, diagNudge, diagTagSummary, deriveTitle, effectiveTokenCount, imageBillingFor, imageReserveFor, imageTokenCapFor, isAutoInjectedNotification, isTagShapedText, planReasoningDrop, repairResponsesAssistantOrdering, reapOrphansLogged, resolveKnownOutputCeiling, runNudgeDecision, stripKernelSummaries, usageGradeInputBaseline, warnResponsesReasoningPairs, type Prepared } from "../server.js"; import { buildDecisionPrompt, buildDirectiveText, consumeFallback, ladderMode, resolveDecisionRange, stripDecisionReasoningFields, type DecideConfig } from "../nudge-decide.js"; import { excludeDeadRefRanges } from "../acp-status.js"; import { mergeAdjacentConfigurationUpdates, patchResponsesInputWithToolImages as patchResponsesInput, responsesToCoreWithToolImages as responsesToCore } from "../responses-tool-output.js"; @@ -340,7 +340,7 @@ reconcileFoldCoverage(session, msgs, { mode: foldMode, sessionId, log, markerStr nudge = turn.nudge; session.stats.contextTokens = tokenCount; session.stats.contextTokensSource = tokenCountSource; - if (!session.meta.title || isAutoInjectedNotification(session.meta.title)) { + if (!session.meta.title || isAutoInjectedNotification(session.meta.title) || isTagShapedText(session.meta.title)) { const t = deriveTitle(msgs); if (t) session.meta.title = t; } diff --git a/src/session.ts b/src/session.ts index 5d581f2bab..d41902fd8d 100644 --- a/src/session.ts +++ b/src/session.ts @@ -1281,6 +1281,31 @@ export function splitSessionWarnings(sessions: Session[], now: number = Date.now return out; } +// #4776: splitSessionWarnings is the #2165 stolen-anchor canary — it only fires +// when several sessions SHARE one id base (`|sub:` children), so it is structurally +// blind to anonymous prefix-affinity forks: every pfa-* fork owns a unique id, and an +// anonymous-heavy deployment reads [] while one conversation split dozens of times. +// This reports what bili actually knows from session metadata: how many in-memory +// sessions carry no client-provided identity, and how many were born as a fork +// (diverged shared prefix) or truncated replay (compaction/resume dropped the head) +// of another anonymous session's history. +export interface AnonymousIdentitySummary { + total: number; + forkBorn: number; + truncatedBorn: number; +} +export function anonymousIdentitySummary(sessions: Session[]): AnonymousIdentitySummary { + let total = 0, forkBorn = 0, truncatedBorn = 0; + for (const s of sessions) { + const apa = s.metadata?.anonymousPrefixAffinity as { lineage?: { reason?: string } } | undefined; + if (!apa) continue; + total++; + if (apa.lineage?.reason === "forked") forkBorn++; + else if (apa.lineage?.reason === "truncated") truncatedBorn++; + } + return { total, forkBorn, truncatedBorn }; +} + /** Read-only in-memory lookup. Unlike getSession, never creates or reloads a * session — used by the plugin tool API, which must not conjure state for a * conversation it has never seen. */ diff --git a/src/web/client.ts b/src/web/client.ts index 3cfc74910d..8b6d654bf6 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -555,12 +555,23 @@ export const WEB_CLIENT = `(function () { } } + // #4776: a markup-shaped derived title (a host XML wrapper captured before the #4776 skip + // rule shipped) identifies nothing — treat it as absent so the label / firstBlockHint + // fallbacks can show instead of being shadowed forever. The raw stored title stays visible + // in the detail KV row; self-healing re-derivation fixes the data itself on next request. + function effectiveSessionName(d) { + const raw = d && typeof d.title === "string" ? d.title : ""; + const title = /^\s*' + t("common.back") + ""); - parts.push('

' + escapeHtml(d.title || d.label || d.id.slice(0, 16)) + '

' + escapeHtml(d.id) + "
" + detailBadges(d) + "
"); + const headName = effectiveSessionName(d) || d.id.slice(0, 16); + parts.push('

' + escapeHtml(headName) + '

' + escapeHtml(d.id) + "
" + detailBadges(d) + "
"); parts.push('
' + t("det.report_note") + '
'); // #3917: the detail page splits into panes — overview (identity, usage, // cache economics), the compression tree, and the handoff document. The diff --git a/tests/issue4776-anonymous-identity.test.ts b/tests/issue4776-anonymous-identity.test.ts new file mode 100644 index 0000000000..7efca1719d --- /dev/null +++ b/tests/issue4776-anonymous-identity.test.ts @@ -0,0 +1,80 @@ +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import test from "node:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.js"; +import type { ProxyOptions } from "../src/config.js"; +import { SessionStore, _setStoreForTest } from "../src/persist.js"; +import { anonymousIdentitySummary, listSessions, type Session } from "../src/session.js"; + +// #4776: honest accounting for identity-less clients. splitSessions on +// /__bili/status is the #2165 stolen-anchor canary (shared id base + |sub: +// child) and structurally blind to anonymous prefix-affinity forks — every +// pfa-* fork owns a unique id. anonymousIdentity reports what bili actually +// knows from session metadata instead. + +process.env.NODE_ENV = "test"; +const testRoot = mkdtempSync(join(tmpdir(), "bili-anon-id-")); +test.after(() => rmSync(testRoot, { recursive: true, force: true })); +for (const key of ["XDG_STATE_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_CONFIG_HOME"]) process.env[key] = testRoot; + +const mk = (id: string, apa?: unknown): Session => + ({ id, lastSeen: 0, createdAt: 0, stats: { requests: 1 }, metadata: apa === undefined ? {} : { anonymousPrefixAffinity: apa } }) as unknown as Session; + +test("(A) anonymousIdentitySummary counts identity-less sessions by birth reason", () => { + assert.deepEqual(anonymousIdentitySummary([mk("A"), mk("B")]), { total: 0, forkBorn: 0, truncatedBorn: 0 }, "identified or unstamped sessions never count"); + const mixed = anonymousIdentitySummary([ + mk("pfa-1", { depth: 1, tailHash: "t1", via: "new" }), + mk("pfa-2", { depth: 3, tailHash: "t2", via: "new", lineage: { parents: ["pfa-1"], reason: "forked", sharedPrefix: 3 } }), + mk("pfa-3", { depth: 2, tailHash: "t3", via: "new", lineage: { parents: ["pfa-1"], reason: "truncated" } }), + mk("pfa-4", { depth: 5, tailHash: "t4", via: "prefix" }), + mk("identified-client"), + ]); + assert.deepEqual(mixed, { total: 4, forkBorn: 1, truncatedBorn: 1 }); +}); + +test("(B) /__bili/status exposes anonymousIdentity for anonymous traffic while splitSessions stays silent", async () => { + const dir = mkdtempSync(join(testRoot, "run-")); + for (const key of ["XDG_STATE_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_CONFIG_HOME"]) process.env[key] = dir; + const store = new SessionStore({ dir: dir + "/sessions", enabled: false, debounceMs: 60000 }); + _setStoreForTest(store); + const upstream = await new Promise<{ url: string; close: () => Promise }>((resolve) => { + const server = http.createServer((req, res) => { + req.resume(); + req.on("end", () => { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ id: "chat_test", object: "chat.completion", choices: [{ index: 0, message: { role: "assistant", content: "answer" }, finish_reason: "stop" }], usage: { prompt_tokens: 100, completion_tokens: 10, total_tokens: 110 } })); + }); + }); + server.listen(0, "127.0.0.1", () => resolve({ url: `http://127.0.0.1:${(server.address() as { port: number }).port}`, close: async () => { server.close(); } })); + }); + const proxy = await startServer({ port: 0, host: "127.0.0.1", upstream: upstream.url, routes: { [upstream.url]: { models: { "claude-test": { context: 400000 } } } }, modelContextLimit: 400000, kernelConfig: defaultConfig(400000), compress: { injectTool: true, injectNudge: true, preserveRecentMessages: 1, preserveRecentTokens: 0, minCompressRangeChars: 100 }, promptCache: { routing: "auto" }, sessionHeader: "x-acp-session", log: false, debug: false, passthrough: false, autoUpdate: false, mitm: { enabled: false, domains: [] } } as ProxyOptions); + await once(proxy, "listening"); + try { + const origin = `http://127.0.0.1:${(proxy.address() as { port: number }).port}`; + // anonymous OpenAI lane: NO conversation-id headers of any kind (#4776 WorkBuddy shape) + const r1 = await fetch(`${origin}/bili/${upstream.url}/v1/chat/completions`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "claude-test", stream: false, messages: [{ role: "user", content: "hello" }] }), + }); + assert.equal(r1.status, 200, await r1.text()); + assert.ok(listSessions().some((s) => s.id.startsWith("pfa-")), "an identity-less client mints a pfa-* session"); + + const status = (await (await fetch(`${origin}/__bili/status`)).json()) as { splitSessions?: unknown[]; anonymousIdentity?: { total: number; forkBorn: number; truncatedBorn: number } }; + assert.ok(status.anonymousIdentity, "anonymousIdentity is present on /__bili/status"); + assert.ok(status.anonymousIdentity!.total >= 1, `at least the minted pfa session is counted (got ${JSON.stringify(status.anonymousIdentity)})`); + assert.equal(status.anonymousIdentity!.forkBorn, 0); + assert.equal(status.anonymousIdentity!.truncatedBorn, 0); + assert.deepEqual(status.splitSessions, [], "the #2165 shared-base canary stays silent for unique-id pfa forks — that is why the separate count exists"); + } finally { + store.cancelAll(); + proxy.close(); + await upstream.close(); + await new Promise((r2) => setTimeout(r2, 50)); + } +}); diff --git a/tests/title-derive.test.ts b/tests/title-derive.test.ts index 0754455080..b69e42faef 100644 --- a/tests/title-derive.test.ts +++ b/tests/title-derive.test.ts @@ -1,6 +1,6 @@ import { describe, it } from "node:test"; import assert from "node:assert/strict"; -import { deriveTitle, isContextualUserFragment, isAutoInjectedNotification } from "../src/server.js"; +import { deriveTitle, isContextualUserFragment, isAutoInjectedNotification, isTagShapedText } from "../src/server.js"; import type { CoreMessage } from "acp-kernel"; let seq = 0; @@ -144,3 +144,72 @@ describe("#2286 isAutoInjectedNotification prefix permitlist", () => { assert.equal(isAutoInjectedNotification(" \t\n "), false); }); }); + +// Wrapper shapes observed in WorkBuddy 5.9.2 (CodeBuddy kernel) traffic (#4776): +// the host injects these as USER-role messages ahead of the first real question, +// and 139 of 166 session titles were exactly these wrappers. +const WB_COMPACT_SUMMARY = ' This session is being continued from a previous conversation that ran out of context. The conversation is summarized below:\n…'; +const WB_USER_CTX = ' \n/c/Users/dev\n'; +const WB_MEMORY = ' # auto memory\n- user prefers concise answers\n'; +const WB_USER_QUERY = "\nPlease fix the login bug"; +const WB_TASK_NOTIF = "The background task completed successfully."; +const WB_CB_SUMMARY = "Session summary: …"; + +describe("#4776 deriveTitle skips tag-shaped host wrapper openers", () => { + it("a WorkBuddy compact-summary wrapper ahead of the real question does not become the title", () => { + const t = deriveTitle([msg("user", "text", WB_COMPACT_SUMMARY), msg("user", "text", "帮我看看这个报错")]); + assert.equal(t, "帮我看看这个报错"); + }); + + it("every observed WorkBuddy wrapper shape is skipped in favor of the real question", () => { + for (const w of [WB_COMPACT_SUMMARY, WB_USER_CTX, WB_MEMORY, WB_USER_QUERY, WB_TASK_NOTIF, WB_CB_SUMMARY]) { + const t = deriveTitle([msg("user", "text", w), msg("user", "text", "real question")]); + assert.equal(t, "real question", `wrapper: ${w.slice(0, 40)}`); + } + }); + + it("only wrappers present: no title yet (retries once the real question arrives)", () => { + assert.equal(deriveTitle([msg("user", "text", WB_USER_QUERY)]), undefined); + }); + + it("a literal paste that opens with a tag defers the title instead of locking garbage", () => { + const t = deriveTitle([msg("user", "text", '
why is this red?
'), msg("user", "text", "debug this page")]); + assert.equal(t, "debug this page"); + }); + + it("plain questions never look tag-shaped — no false positives", () => { + for (const s of ["Fix auth bug", "<3 warm up this session", "<> note", "1 < 2 ? a : b"]) { + assert.equal(deriveTitle([msg("user", "text", s)]), s, s); + } + }); +}); + +describe("#4776 isTagShapedText structural rule", () => { + it("matches opening tags with attributes, hyphens, underscores, colons; case-insensitive", () => { + assert.equal(isTagShapedText('y'), true); + assert.equal(isTagShapedText("x"), true); + assert.equal(isTagShapedText("x"), true); + assert.equal(isTagShapedText("x"), true); + assert.equal(isTagShapedText(" x "), true); + }); + + it("matches closing-tag openers (wrapper residue)", () => { + assert.equal(isTagShapedText(""), true); + }); + + it("matches a polluted set-once title truncated at 60 chars with ellipsis", () => { + const truncated = WB_USER_QUERY.slice(0, 57) + "\u2026"; + assert.equal(isTagShapedText(truncated), true); + }); + + it("does not match non-tag text starting with <", () => { + assert.equal(isTagShapedText("<3 warm up"), false); + assert.equal(isTagShapedText("<x"), false); + assert.equal(isTagShapedText("< spaced out>"), false); + }); + + it("does not match empty text or mid-sentence mentions", () => { + assert.equal(isTagShapedText(""), false); + assert.equal(isTagShapedText("why is my
broken?"), false); + }); +}); From 8c9b4ab42b3867b00ab76fb808981148d3902fbd Mon Sep 17 00:00:00 2001 From: ci-check Date: Mon, 26 Oct 2026 08:44:26 +0800 Subject: [PATCH 2/2] fix: un-export AnonymousIdentitySummary (unused-exports gate) CI unused-exports job flags the interface as INTERNAL_ONLY: it is only referenced within src/session.ts (return type of anonymousIdentitySummary). Drop the leading export; the function stays exported for admin.ts. --- src/session.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/session.ts b/src/session.ts index d41902fd8d..f39bb629b2 100644 --- a/src/session.ts +++ b/src/session.ts @@ -1289,7 +1289,7 @@ export function splitSessionWarnings(sessions: Session[], now: number = Date.now // sessions carry no client-provided identity, and how many were born as a fork // (diverged shared prefix) or truncated replay (compaction/resume dropped the head) // of another anonymous session's history. -export interface AnonymousIdentitySummary { +interface AnonymousIdentitySummary { total: number; forkBorn: number; truncatedBorn: number;