Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/clean-claude-fallback-titles.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions api-report/ui-sdk.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1487,6 +1487,7 @@ export "./internal" (./src/internal.ts)
startEgressProxy
startInferenceRelay
startProviderRelay
stripHostContextFromTitle
turnTempLimit
turnTempSpace
verifiedWorkerIdentity
Expand Down
8 changes: 8 additions & 0 deletions docs/hosting/session-prompt-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/plans/chat-history-deletion.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions packages/ui-backend-claude/src/history.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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,
Expand Down
6 changes: 3 additions & 3 deletions packages/ui-backend-claude/src/transcript-archive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -296,7 +296,7 @@ export async function archiveIdleSessions(options: ArchiveOptions): Promise<void
const roots = [join(live, `${id}.jsonl`), join(live, id)].filter(existsSync);
if (Math.max(...roots.map(newestMtime)) >= 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: [],
};
Expand Down
17 changes: 17 additions & 0 deletions packages/ui-backend-claude/tests/history.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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-"));
Expand Down Expand Up @@ -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[] = [
{
Expand Down
21 changes: 21 additions & 0 deletions packages/ui-backend-claude/tests/transcript-archive.test.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -246,3 +247,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");
});
2 changes: 1 addition & 1 deletion packages/ui-sdk/src/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
12 changes: 11 additions & 1 deletion packages/ui-sdk/src/server/session-prompt-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>;
interface OwnedTurn { original: string; wireDigest: string; facts: SessionPromptFacts; providerId?: string }
interface Snapshot { append?: string; delivered: SessionPromptFacts; turns: Record<string, OwnedTurn> }
Expand Down Expand Up @@ -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);
Expand Down
14 changes: 13 additions & 1 deletion packages/ui-sdk/tests/session-prompt-context.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }); });
Expand Down Expand Up @@ -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);
});
Loading