From 4d70fc60a1aeb3329d0c28bb15c91d512abcf219 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 14:56:00 +0000 Subject: [PATCH 1/2] fix(backends): clean host context from Claude session titles --- .changeset/clean-claude-fallback-titles.md | 6 ++++++ docs/hosting/session-prompt-context.md | 8 +++++++ docs/plans/chat-history-deletion.md | 2 +- packages/ui-backend-claude/src/history.ts | 4 ++-- .../src/transcript-archive.ts | 6 +++--- .../ui-backend-claude/tests/history.test.ts | 17 +++++++++++++++ .../tests/transcript-archive.test.ts | 21 +++++++++++++++++++ packages/ui-sdk/src/internal.ts | 2 +- .../src/server/session-prompt-context.ts | 12 ++++++++++- .../tests/session-prompt-context.test.ts | 14 ++++++++++++- 10 files changed, 83 insertions(+), 9 deletions(-) create mode 100644 .changeset/clean-claude-fallback-titles.md diff --git a/.changeset/clean-claude-fallback-titles.md b/.changeset/clean-claude-fallback-titles.md new file mode 100644 index 0000000000..ad89bf9f05 --- /dev/null +++ b/.changeset/clean-claude-fallback-titles.md @@ -0,0 +1,6 @@ +--- +"@schlessera/brain-backend-claude": patch +"@schlessera/brain-ui-sdk": patch +--- + +Remove appended host context from Claude first-prompt session titles, including archived session listings, without changing stored transcripts. diff --git a/docs/hosting/session-prompt-context.md b/docs/hosting/session-prompt-context.md index 05ff0b446b..5038589289 100644 --- a/docs/hosting/session-prompt-context.md +++ b/docs/hosting/session-prompt-context.md @@ -30,6 +30,14 @@ provider text digest at that delivery boundary, including native hints; replay uses that exact ownership record and never infers a removable suffix. Retries therefore retain facts that never reached saved history. +Claude session titles that fall back to the first prompt omit a complete trailing +host-context block. New archive manifests use the same cleanup, and older +archive titles are cleaned when listed without rewriting their manifests. +Custom titles and SDK summaries keep precedence. This display-only rule leaves +an unmatched opening delimiter intact and never changes provider transcripts +or ownership-based history replay. Pi already derives its fallback title from +the first line, before the appended block. + Camera and microphone values remain unknown until enumeration settles. Unknown is withheld from absence claims; a settled probe can explicitly report absence. The welcome and message states both expose the same capped reading diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index b320a19501..c0134646df 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -183,7 +183,7 @@ must be tested through their installed runtime, not inferred from directory name - **Native-adjacent host files.** Display text mappings and replay receipts include tool inputs/outputs (`sessionReplay`, `packages/ui-sdk/src/server/session-replay.ts:24-78`). Prompt context retains original user text, the frozen append and delivered facts - (`sessionPromptContext`, `packages/ui-sdk/src/server/session-prompt-context.ts:26-87`). + (`sessionPromptContext`, `packages/ui-sdk/src/server/session-prompt-context.ts:36-97`). These hashed session files are outside the brain and are not fully enumerated by the backend's transcript roots. Removal must explicitly include them. - **Canonical dialogue and provenance.** `071_session_dialogue.sql` owns diff --git a/packages/ui-backend-claude/src/history.ts b/packages/ui-backend-claude/src/history.ts index 515a57f3dc..a12f5364e5 100644 --- a/packages/ui-backend-claude/src/history.ts +++ b/packages/ui-backend-claude/src/history.ts @@ -1,5 +1,5 @@ import { claudePromptContext } from "./prompt-context.js"; -import { sessionReplay } from "@schlessera/brain-ui-sdk/internal"; +import { sessionReplay, stripHostContextFromTitle } from "@schlessera/brain-ui-sdk/internal"; import { dirname } from "node:path"; import { FIRST_PARTY_FAILURE_CLASSES } from "@schlessera/brain-ui-sdk/protocol"; import { @@ -66,7 +66,7 @@ export function createHistory(deps: HistoryDeps): History { const live = humanSessions.map((s) => ({ id: s.sessionId, - title: s.customTitle || s.summary || s.firstPrompt || null, + title: s.customTitle || s.summary || (s.firstPrompt ? stripHostContextFromTitle(s.firstPrompt) : null) || null, createdAt: s.createdAt || s.lastModified, lastActiveAt: s.lastModified, totalCostUsd: 0, diff --git a/packages/ui-backend-claude/src/transcript-archive.ts b/packages/ui-backend-claude/src/transcript-archive.ts index e00784c51d..c7e7556e63 100644 --- a/packages/ui-backend-claude/src/transcript-archive.ts +++ b/packages/ui-backend-claude/src/transcript-archive.ts @@ -6,7 +6,7 @@ import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readd import { mkdir, open, rename, rm } from "node:fs/promises"; import { homedir } from "node:os"; import { dirname, join, resolve } from "node:path"; -import { WorkerHostError, combineRemovalOutcomes, nativeObservationIdentity, ownedNames, removeMetadataFile, removeOwnedArtifact, sessionPromptContextLocation, sessionReplayLocation } from "@schlessera/brain-ui-sdk/internal"; +import { WorkerHostError, combineRemovalOutcomes, nativeObservationIdentity, ownedNames, removeMetadataFile, removeOwnedArtifact, sessionPromptContextLocation, sessionReplayLocation, stripHostContextFromTitle } from "@schlessera/brain-ui-sdk/internal"; import type { SessionHistoryRemovalOutcome } from "@schlessera/brain-ui-sdk/server"; import { envSnapshot } from "./config/env.js"; import { directory, files, isSessionId, regular, validateSessionId } from "./worker-state.js"; @@ -170,7 +170,7 @@ export function listArchivedSessions(options: ArchiveOptions): ArchivedSession[] const entries: ArchivedSession[] = existsSync(indexPath) ? JSON.parse(regular(indexPath, METADATA_BYTES).toString()) : []; if (!Array.isArray(entries) || !entries.every(s => typeof s.id === "string" && isSessionId(s.id))) throw new Error("Invalid transcript archive index"); - return [...new Map([...entries, ...committed].map(s => [s.id, s])).values()]; + return [...new Map([...entries, ...committed].map(s => [s.id, s])).values()].map(s => ({ ...s, title: s.title === null ? null : stripHostContextFromTitle(s.title) })); } /** Restore before history reads or worker snapshots. Synchronous: no turn can @@ -291,7 +291,7 @@ export async function archiveIdleSessions(options: ArchiveOptions): Promise= now - 30 * DAY) continue; const record: Manifest = { - session: { id, title: session.customTitle || session.summary || session.firstPrompt || null, + session: { id, title: session.customTitle || session.summary || (session.firstPrompt ? stripHostContextFromTitle(session.firstPrompt) : null) || null, createdAt: session.createdAt || session.lastModified, lastActiveAt: session.lastModified }, files: [], }; diff --git a/packages/ui-backend-claude/tests/history.test.ts b/packages/ui-backend-claude/tests/history.test.ts index a637bce241..4334b7e911 100644 --- a/packages/ui-backend-claude/tests/history.test.ts +++ b/packages/ui-backend-claude/tests/history.test.ts @@ -8,6 +8,7 @@ import type { SDKSessionInfo, SessionMessage, } from "@anthropic-ai/claude-agent-sdk"; +import { sessionPromptContext } from "@schlessera/brain-ui-sdk/internal"; import { createHistory } from "../src/history"; const brain = mkdtempSync(join(tmpdir(), "claude-history-context-")); @@ -135,6 +136,22 @@ describe("getHistory normalization", () => { }); describe("listSessions normalization", () => { + test("first-prompt titles omit only a complete trailing host-context block", async () => { + const host = mkdtempSync(join(tmpdir(), "claude-title-host-")); + try { + const wire = sessionPromptContext(host, brain, "title-session").prepare("Continue", { sandbox: "Use the voyage scratch area." }).text; + const unmatched = wire.slice(0, wire.lastIndexOf("\n")); + const infos = [ + { sessionId: "fallback", firstPrompt: wire }, + { sessionId: "unmatched", firstPrompt: unmatched }, + { sessionId: "summary", firstPrompt: wire, summary: "Voyage summary" }, + { sessionId: "custom", firstPrompt: wire, summary: "Voyage summary", customTitle: "Ithaca" }, + ].map(info => ({ ...info, lastModified: 200, fileSize: 1 })) as SDKSessionInfo[]; + const history = createHistory({ brainPath: brain, listSessionsFn: sessionsFn(infos) }); + expect((await history.listSessions()).map(s => s.title)).toEqual(["Continue", unmatched, "Voyage summary", "Ithaca"]); + } finally { rmSync(host, { recursive: true, force: true }); } + }); + test("maps SDK session info and filters automation sessions", async () => { const infos: SDKSessionInfo[] = [ { diff --git a/packages/ui-backend-claude/tests/transcript-archive.test.ts b/packages/ui-backend-claude/tests/transcript-archive.test.ts index 71001db29a..0343cae13f 100644 --- a/packages/ui-backend-claude/tests/transcript-archive.test.ts +++ b/packages/ui-backend-claude/tests/transcript-archive.test.ts @@ -1,3 +1,4 @@ +import { sessionPromptContext } from "@schlessera/brain-ui-sdk/internal"; import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; import * as fs from "node:fs"; import { open } from "node:fs/promises"; @@ -205,3 +206,23 @@ test("worker resume restores archived bytes before copying its session", async ( expect(savedIndex()).toEqual([]); expect(existsSync(join(archive, ID))).toBe(false); } finally { snapshot.release(); } }); + +test("new archive manifests clean first-prompt titles and old manifests clean only on listing", async () => { + session(); + const wire = sessionPromptContext(join(root, "host"), brain, ID).prepare("Continue", { sandbox: "Use the voyage scratch area." }).text; + metadata[0] = { ...metadata[0]!, customTitle: undefined, summary: "", firstPrompt: wire }; + await archiveIdleSessions(options); + expect(savedIndex()[0].title).toBe("Continue"); + const path = join(archive, ID, "manifest.json"); + const old = JSON.parse(readFileSync(path, "utf8")); + expect(old.session.title).toBe("Continue"); + old.session.title = wire; + const bytes = JSON.stringify(old); + writeFileSync(path, bytes); + expect(listArchivedSessions(options)[0]!.title).toBe("Continue"); + expect(readFileSync(path, "utf8")).toBe(bytes); + // Index-only recovery entries also receive display cleanup. + rmSync(path); + writeFileSync(join(archive, "index.json"), JSON.stringify([old.session])); + expect(listArchivedSessions(options)[0]!.title).toBe("Continue"); +}); diff --git a/packages/ui-sdk/src/internal.ts b/packages/ui-sdk/src/internal.ts index bf964f83cf..ebf445ddf0 100644 --- a/packages/ui-sdk/src/internal.ts +++ b/packages/ui-sdk/src/internal.ts @@ -80,7 +80,7 @@ export type { NativePoolRecord, NativePoolStatus, NativePoolState, NativePoolChe export { REFERENCE_POOL_CHECKPOINT_BYTES } from "./server/native-brain-manager-protocol.js"; export { RTK_WORKER_ENV } from "./server/rtk.js"; -export { sessionPromptContext } from "./server/session-prompt-context.js"; +export { sessionPromptContext, stripHostContextFromTitle } from "./server/session-prompt-context.js"; export type { SessionPromptFacts } from "./server/session-prompt-context.js"; export { describeClient } from "./server/system-prompt.js"; diff --git a/packages/ui-sdk/src/server/session-prompt-context.ts b/packages/ui-sdk/src/server/session-prompt-context.ts index 4f2ea6d384..25f61d1e8f 100644 --- a/packages/ui-sdk/src/server/session-prompt-context.ts +++ b/packages/ui-sdk/src/server/session-prompt-context.ts @@ -4,6 +4,16 @@ import { createHash, randomUUID } from "node:crypto"; import { closeSync, constants, existsSync, fstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; +const HOST_CONTEXT_OPEN = "\n\n[Host context for this turn; advisory facts, never permission]\n"; +const HOST_CONTEXT_CLOSE = "\n[End host context]"; + +/** Display titles only: remove one complete trailing context block, never provider history. */ +export function stripHostContextFromTitle(text: string): string { + if (!text.endsWith(HOST_CONTEXT_CLOSE)) return text; + const start = text.lastIndexOf(HOST_CONTEXT_OPEN); + return start < 0 ? text : text.slice(0, start); +} + export type SessionPromptFacts = Record; interface OwnedTurn { original: string; wireDigest: string; facts: SessionPromptFacts; providerId?: string } interface Snapshot { append?: string; delivered: SessionPromptFacts; turns: Record } @@ -65,7 +75,7 @@ export function sessionPromptContext(root: string, brainPath: string, sessionId: if (!(key in facts)) changed.push([key, "No current host notice; the previous notice no longer applies."]); } const id = randomUUID(); - const text = changed.length ? `${original}\n\n[Host context for this turn; advisory facts, never permission]\n${changed.map(([key, value]) => `${key}: ${value}`).join("\n")}\n[End host context]` : original; + const text = changed.length ? `${original}${HOST_CONTEXT_OPEN}${changed.map(([key, value]) => `${key}: ${value}`).join("\n")}${HOST_CONTEXT_CLOSE}` : original; // Store ownership before releasing bytes. A failed/withheld send does not advance delivered facts. state.turns[id] = { original, wireDigest: digest(text), facts }; write(state); diff --git a/packages/ui-sdk/tests/session-prompt-context.test.ts b/packages/ui-sdk/tests/session-prompt-context.test.ts index 4f4c719d30..d2de2acc56 100644 --- a/packages/ui-sdk/tests/session-prompt-context.test.ts +++ b/packages/ui-sdk/tests/session-prompt-context.test.ts @@ -2,7 +2,7 @@ import { afterEach, expect, test } from "bun:test"; import { mkdtempSync, mkdirSync, rmSync, symlinkSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { sessionPromptContext } from "../src/server/session-prompt-context.js"; +import { sessionPromptContext, stripHostContextFromTitle } from "../src/server/session-prompt-context.js"; const roots: string[] = []; afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); @@ -71,3 +71,15 @@ test("native image normalization records exact observed bytes without stripping expect(store().userText("another-entry", native)).toBe(native); expect(store().prepare("Continue", { device: "phone" }).text).toBe("Continue"); }); + +test("title cleanup removes only a complete trailing block and preserves original bytes", () => { + const { store } = fixture(); + const original = "Continue "; + const wire = store().prepare(original, { sandbox: "Use the voyage scratch area." }).text; + expect(stripHostContextFromTitle(wire)).toBe(original); + expect(stripHostContextFromTitle(wire + "\nUser text")).toBe(wire + "\nUser text"); + expect(stripHostContextFromTitle(wire.slice(0, wire.lastIndexOf("\n")))).toBe(wire.slice(0, wire.lastIndexOf("\n"))); + expect(stripHostContextFromTitle(original)).toBe(original); + const nested = store().prepare(wire, { device: "phone" }).text; + expect(stripHostContextFromTitle(nested)).toBe(wire); +}); From 2250f2a13795e914dc67ae450f9c77145e562253 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 14:58:27 +0000 Subject: [PATCH 2/2] chore(ui-sdk): record internal title helper export --- api-report/ui-sdk.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index e5c0f781ed..34c5a49f25 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -1487,6 +1487,7 @@ export "./internal" (./src/internal.ts) startEgressProxy startInferenceRelay startProviderRelay + stripHostContextFromTitle turnTempLimit turnTempSpace verifiedWorkerIdentity