A local plugin for image-heavy chats in Codex, Claude Code and other agents: earlier images stop going out with every message, and the model fetches the one it needs by its ID, also after compaction.
TypeScript ai-agentsclaude-codeclaude-code-plugincodexcodex-plugincontext-managementdeveloper-toolsimage-generationmcpmultimodal
feat(claude): 从 Claude Code 会话记录只读地找图和编号
chipfighter518668eab0b7
diff --git a/plugin/src/claude-index.ts b/plugin/src/claude-index.tsnew file mode 100644index 0000000..c9062cc--- /dev/null+++ b/plugin/src/claude-index.ts@@ -0,0 +1,256 @@+// Purpose: v0.4 — the image timeline of one Claude Code session, read from its transcript (read-only), the way+// thread-index.ts reads a Codex rollout: every image occurrence in conversation order with a stable id (IMG-001…),+// its turn, name, size and content hashes. The engine and the plugin service each derive it from the same file, so+// they agree on ids without sharing state.+// A transcript is <Claude config dir>/projects/<project>/<session id>.jsonl, appended to as the session goes on. Its+// records form a tree (parentUuid): a rewind or an edited prompt starts a branch, and the conversation is the path+// from the newest message back to the start, across compaction boundaries (logicalParentUuid). Images are in user+// records: pasted ones as image blocks, a tool's inside its tool_result. A resumed or forked session copies the+// records it continues from, with their uuids, so keys built on them stay the same in the new session.+// Keys: "<record uuid>#<n>" for a pasted image, "tool:<tool_use_id>#<n>" for one in a tool result. A request carries+// tool_use_id but not record uuids: claude-rewrite.ts matches pasted images to records by their content.+// Input: the session id (and optionally the Claude config dir). Output: ClaudeIndex (in memory; files are parsed+// incrementally).++import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";+import { baseName, FETCHED_STATE, imageDigest, type ImageKind, type ImageRef } from "./images.ts";+import { pixelHashOfData, type FetchedCopy, type IndexedImage, type ThreadIndex } from "./thread-index.ts";++type Json = Record<string, any>;+export type ClaudeRecord = Json & { type: string; uuid?: string; parentUuid?: string | null; logicalParentUuid?: string | null };+// Where an image sits: the record (its position in the conversation) and block, and for a tool result the image's+// position within that result's content.+export type ClaudeImage = IndexedImage & { recordUuid: string; toolUseId: string | null; sub: number | null; compacted: boolean };+// The records with pasted images, in conversation order, with the digests of their images: what a request's user+// messages are matched against. compacted: before the latest compaction, so no longer in requests.+export type UploadRecord = { uuid: string; contentIds: string[]; compacted: boolean };+export type ClaudeIndex = ThreadIndex & {+ images: ClaudeImage[];+ byKey: Map<string, ClaudeImage>;+ uploads: UploadRecord[];+ // The conversation, oldest first: what image positions point into.+ chain: ClaudeRecord[];+ title: string | null;+ // The text of the latest finished assistant reply (its turn), for the ids the model asked for.+ replies: string[];+ transcript: string | null;+};++const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;+const FETCHED_LINE = new RegExp(`^\\[(?:图片|Image) (IMG-\\d{3,}) (?:${FETCHED_STATE.zh}|${FETCHED_STATE.en})(?:|| \\|)`);++export function claudeHome(env: NodeJS.ProcessEnv = process.env): string {+ return env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), ".claude");+}++// Where each session's transcript is: <home>/projects/<project>/<id>.jsonl. Looked up again when a session is not+// found (at most every 5 s), since a new session's file appears with its first message.+const located = new Map<string, string>();+const missedAt = new Map<string, number>();+export function transcriptOf(sessionId: string, home = claudeHome()): string | null {+ if (!SESSION_ID.test(sessionId)) return null;+ const key = `${home}\0${sessionId}`;+ const known = located.get(key);+ if (known && existsSync(known)) return known;+ if (Date.now() - (missedAt.get(key) ?? 0) < 5000) return null;+ missedAt.set(key, Date.now());+ let projects: string[];+ try { projects = readdirSync(join(home, "projects")); } catch { return null; }+ for (const project of projects) {+ const file = join(home, "projects", project, `${sessionId}.jsonl`);+ if (existsSync(file)) { located.set(key, file); missedAt.delete(key); return file; }+ }+ return null;+}++type FileCache = { size: number; mtimeMs: number; parsedTo: number; records: ClaudeRecord[] };+const files = new Map<string, FileCache>();++// Append-only: only the complete lines added since the last read are parsed. A damaged line is skipped.+export function readTranscript(file: string): ClaudeRecord[] {+ const stat = statSync(file);+ let cache = files.get(file);+ if (!cache || stat.size < cache.parsedTo) cache = { size: 0, mtimeMs: 0, parsedTo: 0, records: [] };+ if (stat.size !== cache.size || stat.mtimeMs !== cache.mtimeMs) {+ const length = stat.size - cache.parsedTo;+ const buffer = Buffer.alloc(length);+ const fd = openSync(file, "r");+ try { readSync(fd, buffer, 0, length, cache.parsedTo); } finally { closeSync(fd); }+ let start = 0;+ for (let end = buffer.indexOf(0x0a); end >= 0; end = buffer.indexOf(0x0a, start)) {+ const text = buffer.toString("utf8", start, end).trim();+ if (text) { try { cache.records.push(JSON.parse(text)); } catch { /* damaged line */ } }+ start = end + 1;+ }+ cache.parsedTo += start;+ cache.size = stat.size;+ cache.mtimeMs = stat.mtimeMs;+ files.set(file, cache);+ }+ return cache.records;+}++const isMessage = (record: ClaudeRecord) => (record.type === "user" || record.type === "assistant") && typeof record.uuid === "string";+const isBoundary = (record: ClaudeRecord) => record.type === "system" && (record.subtype === "compact_boundary" || !!record.compactMetadata);++// The conversation as it stands: from the newest message (not a subagent's sidechain) back to the start.+export function activeChain(records: ClaudeRecord[]): ClaudeRecord[] {+ const byUuid = new Map<string, ClaudeRecord>();+ for (const record of records) if (typeof record.uuid === "string") byUuid.set(record.uuid, record);+ let leaf: ClaudeRecord | undefined;+ for (let i = records.length - 1; i >= 0; i--) if (isMessage(records[i]) && !records[i].isSidechain) { leaf = records[i]; break; }+ const chain: ClaudeRecord[] = [];+ const seen = new Set<string>();+ for (let record = leaf; record && !seen.has(record.uuid!); ) {+ seen.add(record.uuid!);+ chain.push(record);+ const parent = record.parentUuid ?? (isBoundary(record) ? record.logicalParentUuid : null);+ record = parent ? byUuid.get(parent) : undefined;+ }+ return chain.reverse();+}++// A prompt the user sent (or a delivery queued as one): not a tool result, not Claude Code's own meta message or a+// compaction summary.+export function isPrompt(record: ClaudeRecord): boolean {+ if (record.type !== "user" || record.isMeta || record.isCompactSummary || record.toolUseResult !== undefined) return false;+ const content = record.message?.content;+ if (typeof content === "string") return true;+ return Array.isArray(content) && content.some((block: Json) => block?.type !== "tool_result");+}++const textOf = (block: Json | undefined) => (block?.type === "text" && typeof block.text === "string" ? block.text : null);++// Every image block of a user record, in order: pasted ones, then those inside each tool result.+export type BlockImage = { part: number; sub: number | null; block: Json; toolUseId: string | null; before: string | null };+export function imageBlocks(content: unknown): BlockImage[] {+ if (!Array.isArray(content)) return [];+ const found: BlockImage[] = [];+ content.forEach((block: Json, part: number) => {+ if (block?.type === "image" && typeof block.source?.data === "string") found.push({ part, sub: null, block, toolUseId: null, before: textOf(content[part - 1]) });+ if (block?.type === "tool_result" && Array.isArray(block.content)) {+ block.content.forEach((inner: Json, sub: number) => {+ if (inner?.type === "image" && typeof inner.source?.data === "string") found.push({ part, sub, block: inner, toolUseId: String(block.tool_use_id ?? ""), before: textOf(block.content[sub - 1]) });+ });+ }+ });+ return found;+}++export function buildClaudeIndex(sessionId: string, records: ClaudeRecord[], transcript: string | null = null): ClaudeIndex {+ const chain = activeChain(records);+ let lastBoundary = -1;+ chain.forEach((record, position) => { if (isBoundary(record)) lastBoundary = position; });+ const tools = new Map<string, { name: string; input: Json }>();+ const turnNumbers = new Map<string, number>();+ const images: ClaudeImage[] = [];+ const byKey = new Map<string, ClaudeImage>();+ const copies = new Map<string, FetchedCopy>();+ const uploads: UploadRecord[] = [];+ let turn = 0;+ // The assistant's text in the current turn and in the one before (Codex: requestedIds in panel-state.ts).+ let current: string[] = [];+ let previous: string[] = [];+ chain.forEach((record, position) => {+ const content = record.message?.content;+ if (record.type === "assistant" && Array.isArray(content)) {+ for (const block of content as Json[]) {+ if (block?.type === "tool_use" && block.id) tools.set(String(block.id), { name: String(block.name ?? ""), input: block.input ?? {} });+ const text = textOf(block);+ if (text) current.push(text);+ }+ return;+ }+ if (record.type !== "user") return;+ if (isPrompt(record)) {+ turn++;+ turnNumbers.set(record.uuid!, turn);+ if (current.length) previous = current;+ current = [];+ }+ const compacted = position < lastBoundary;+ const pasted: string[] = [];+ let n = 0;+ const perTool = new Map<string, number>();+ for (const found of imageBlocks(content)) {+ const mime = typeof found.block.source.media_type === "string" ? found.block.source.media_type : null;+ const digest = imageDigest(found.block, found.block.source.data, mime);+ const tool = found.toolUseId ? tools.get(found.toolUseId) : undefined;+ let key: string;+ let kind: ImageKind;+ let name: string | null = null;+ if (found.toolUseId === null) {+ key = `${record.uuid}#${n++}`;+ kind = "upload";+ pasted.push(digest.contentId);+ } else {+ const m = perTool.get(found.toolUseId) ?? 0;+ perTool.set(found.toolUseId, m + 1);+ key = `tool:${found.toolUseId}#${m}`;+ kind = tool?.name === "Read" ? "view" : "tool";+ if (tool?.name === "Read" && typeof tool.input.file_path === "string") name = baseName(tool.input.file_path);+ }+ if (byKey.has(key) || copies.has(key)) continue;+ const pixelSha256 = pixelHashOfData(digest, found.block.source.data);+ // What our fetch tool brought back is a copy of an image already listed: no id of its own (thread-index.ts).+ const fetchedId = found.toolUseId && found.before ? FETCHED_LINE.exec(found.before)?.[1] ?? null : null;+ const original = fetchedId ? images.find((image) => image.id === fetchedId) : undefined;+ if (original && (original.contentId === digest.contentId || (pixelSha256 !== null && original.pixelSha256 === pixelSha256))) {+ copies.set(key, { key, of: original.id, turn: turn || null });+ continue;+ }+ const ref: ImageRef = {+ ...digest, key, item: position, part: found.part, openTag: null, closeTag: null, kind, replaceable: true, name, label: null,+ turnId: null, source: kind, pdfPage: null, pdfName: null, fetchedId,+ };+ const entry: ClaudeImage = {+ ...ref, id: `IMG-${String(images.length + 1).padStart(3, "0")}`, turn: turn || null, bytes: Math.floor((digest.base64Chars * 3) / 4), pixelSha256,+ recordUuid: record.uuid!, toolUseId: found.toolUseId, sub: found.sub, compacted,+ };+ images.push(entry);+ byKey.set(key, entry);+ }+ if (pasted.length) uploads.push({ uuid: record.uuid!, contentIds: pasted, compacted });+ });+ // A turn with no reply yet falls back to the one before.+ const replies = current.length ? current : previous;+ for (const entry of images) {+ if (entry.name) continue;+ const twin = images.find((other) => other.name && (other.contentId === entry.contentId || (entry.pixelSha256 !== null && other.pixelSha256 === entry.pixelSha256)));+ if (twin) entry.name = twin.name;+ }+ return { threadId: sessionId, images, byKey, turns: turn, turnNumbers, copies, uploads, chain, title: titleOf(records, chain), replies, transcript };+}++// The session's name as Claude Code shows it: the latest custom title, else the start of the first prompt.+export function titleOf(records: ClaudeRecord[], chain: ClaudeRecord[]): string | null {+ for (let i = records.length - 1; i >= 0; i--) {+ const title = records[i].type === "custom-title" ? records[i].customTitle : null;+ if (typeof title === "string" && title.trim()) return title.trim();+ }+ const first = chain.find(isPrompt);+ const content = first?.message?.content;+ const text = typeof content === "string" ? content : Array.isArray(content) ? content.map(textOf).filter(Boolean).join(" ") : "";+ const line = text.replace(/<[^>]+>[^]*?<\/[^>]+>/g, " ").replace(/\s+/g, " ").trim();+ return line ? (line.length > 40 ? `${line.slice(0, 40)}…` : line) : null;+}++// The base64 of one indexed image, from the record it sits in.+export function claudeImageData(index: ClaudeIndex, image: ClaudeImage): string | null {+ const block = index.chain[image.item]?.message?.content?.[image.part!];+ const inner = image.sub === null ? block : block?.content?.[image.sub];+ return typeof inner?.source?.data === "string" ? inner.source.data : null;+}++// An empty index for a session without a transcript yet.+export function emptyClaudeIndex(sessionId: string): ClaudeIndex {+ return buildClaudeIndex(sessionId, []);+}++export function loadClaudeIndex(sessionId: string, home = claudeHome()): ClaudeIndex {+ const file = transcriptOf(sessionId, home);+ if (!file) return emptyClaudeIndex(sessionId);+ return buildClaudeIndex(sessionId, readTranscript(file), file);+}diff --git a/plugin/src/images.ts b/plugin/src/images.tsindex eb48792..9866ad9 100644--- a/plugin/src/images.ts+++ b/plugin/src/images.ts@@ -90,6 +90,11 @@ function digest(owner: object, value: string, mime: string | null): ImageDigestreturn result;}+// v0.4: the same digest for an image block of a Claude Code transcript or request (raw base64, not a data URL).+export function imageDigest(owner: object, value: string, mime: string | null): ImageDigest {+ return digest(owner, value, mime);+}+function partDigest(part: Json): ImageDigest | null {if (part?.type !== "input_image" && part?.type !== "output_image") return null;if (typeof part.file_id === "string") return { contentId: `file:${part.file_id}`, mime: null, base64Chars: 0, width: null, height: null };diff --git a/plugin/src/paths.ts b/plugin/src/paths.tsindex e2352ee..4233137 100644--- a/plugin/src/paths.ts+++ b/plugin/src/paths.ts@@ -23,6 +23,9 @@ export function dataDir(env: NodeJS.ProcessEnv = process.env, platform: NodeJS.P}export const selectionDirOf = (root = dataDir()) => join(root, "selection");+// v0.4: Claude Code sessions keep their own selections and request statistics, apart from Codex's.+export const claudeSelectionDirOf = (root = dataDir()) => join(root, "claude", "selection");+export const claudeRequestStatsDirOf = (root = dataDir()) => join(root, "claude", "requests");export const requestStatsDirOf = (root = dataDir()) => join(root, "state", "requests");export const proxyLogDirOf = (root = dataDir()) => join(root, "proxy");export const bindingsDirOf = (root = dataDir()) => join(root, "bindings");diff --git a/plugin/src/thread-index.ts b/plugin/src/thread-index.tsindex a93179a..a6001b2 100644--- a/plugin/src/thread-index.ts+++ b/plugin/src/thread-index.ts@@ -202,6 +202,11 @@ function pixelHash(ref: ImageRef, value: string): string | null {return pixelHashes.get(ref.contentId) ?? null;}+// v0.4: the same fingerprint for an image held elsewhere (a Claude Code transcript), by its digest and base64.+export function pixelHashOfData(ref: Pick<ImageRef, "contentId" | "mime">, value: string): string | null {+ return pixelHash(ref as ImageRef, value);+}+export function imageData(items: Json[], ref: ImageRef): string | null {const item = items[ref.item];if (ref.part === null) return typeof item?.result === "string" ? item.result : null;diff --git a/spike/src/claude-fixtures.ts b/spike/src/claude-fixtures.tsnew file mode 100644index 0000000..c1be382--- /dev/null+++ b/spike/src/claude-fixtures.ts@@ -0,0 +1,68 @@+// Purpose: v0.4 — synthetic Claude Code transcripts and the requests Claude Code would build from them, for the tests+// of claude-index.ts and claude-rewrite.ts. Shapes follow Claude Code 2.1.293's transcript (records linked by+// parentUuid, one assistant content block per record) and its Messages requests; no real session data.+// Output: record lists, request message lists and small synthetic PNGs.++import { png } from "./testkit.ts";++type Json = Record<string, any>;++export const pngA = png(8, 8, () => [220, 30, 30]).toString("base64");+export const pngB = png(8, 8, () => [40, 70, 210]).toString("base64");+export const pngC = png(16, 8, () => [255, 255, 255]).toString("base64");+export const image = (data: string, extra: Json = {}) => ({ type: "image", source: { type: "base64", media_type: "image/png", data }, ...extra });+export const text = (value: string, extra: Json = {}) => ({ type: "text", text: value, ...extra });++// A transcript builder: each record links to the one before unless told otherwise.+export function transcript() {+ const records: Json[] = [];+ let last: string | null = null;+ let n = 0;+ const add = (record: Json, parent: string | null | undefined = last) => {+ const uuid = record.uuid ?? `00000000-0000-4000-8000-${String(++n).padStart(12, "0")}`;+ const full = { parentUuid: parent ?? null, isSidechain: false, sessionId: "s", ...record, uuid };+ records.push(full);+ if (!full.isSidechain) last = uuid;+ return uuid;+ };+ return {+ records,+ prompt: (content: Json[] | string, extra: Json = {}, parent?: string | null) => add({ type: "user", message: { role: "user", content }, ...extra }, parent),+ assistant: (block: Json, extra: Json = {}, parent?: string | null) => add({ type: "assistant", message: { role: "assistant", content: [block] }, ...extra }, parent),+ toolResult: (toolUseId: string, content: Json[], extra: Json = {}) => add({ type: "user", message: { role: "user", content: [{ type: "tool_result", tool_use_id: toolUseId, content }] }, toolUseResult: {}, ...extra }),+ attachment: () => add({ type: "attachment", attachment: { type: "x" } }),+ boundary: () => add({ type: "system", subtype: "compact_boundary", compactMetadata: {}, logicalParentUuid: last }, null),+ summary: () => add({ type: "user", isCompactSummary: true, message: { role: "user", content: "summary" } }),+ get last() { return last; },+ };+}++// The usual session: turn 1 pastes A and B; turn 2 reads c.png; turn 3 pastes A again.+export function usualSession() {+ const t = transcript();+ const p1 = t.prompt([image(pngA), image(pngB), text("What are these?")]);+ t.assistant({ type: "thinking", thinking: "", signature: "sig-1" });+ t.assistant(text("A red square and a blue square."));+ const p2 = t.prompt("Read c.png");+ t.assistant({ type: "tool_use", id: "toolu_1", name: "Read", input: { file_path: "C:\\work\\c.png" } });+ t.toolResult("toolu_1", [image(pngC)]);+ t.assistant(text("A white rectangle. need IMG-001"));+ const p3 = t.prompt([image(pngA), text("Again?")]);+ t.assistant(text("Same red square."));+ return { t, p1, p2, p3 };+}++// The request Claude Code would send after the usual session, with a fourth prompt.+export function usualRequest(): Json[] {+ return [+ { role: "user", content: [image(pngA), image(pngB), text("What are these?"), text("<system-reminder>x</system-reminder>")] },+ { role: "assistant", content: [{ type: "thinking", thinking: "", signature: "sig-1" }, text("A red square and a blue square.")] },+ { role: "user", content: [text("Read c.png")] },+ { role: "assistant", content: [{ type: "tool_use", id: "toolu_1", name: "Read", input: { file_path: "C:\\work\\c.png" } }] },+ { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_1", content: [image(pngC)] }] },+ { role: "assistant", content: [text("A white rectangle. need IMG-001")] },+ { role: "user", content: [image(pngA), text("Again?")] },+ { role: "assistant", content: [text("Same red square.")] },+ { role: "user", content: [text("And now?", { cache_control: { type: "ephemeral" } })] },+ ];+}diff --git a/spike/src/claude-index.test.ts b/spike/src/claude-index.test.tsnew file mode 100644index 0000000..f1d50f3--- /dev/null+++ b/spike/src/claude-index.test.ts@@ -0,0 +1,105 @@+// Purpose: v0.4 — the image timeline of a Claude Code session (claude-index.ts): ids in conversation order, keys,+// kinds and names, turns, branches and compaction, copies the fetch tool returned, and the session's title.+// Input: synthetic transcripts (claude-fixtures.ts) and temporary files; output: Node test assertions only.++import assert from "node:assert/strict";+import { appendFileSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";+import { activeChain, buildClaudeIndex, claudeImageData, loadClaudeIndex, transcriptOf } from "../../plugin/src/claude-index.ts";+import { image, pngA, pngB, pngC, text, transcript, usualSession } from "./claude-fixtures.ts";++test("images get ids in conversation order: pasted ones by record, tool ones by tool_use_id", () => {+ const { t, p1, p3 } = usualSession();+ const index = buildClaudeIndex("s", t.records);+ assert.deepEqual(index.images.map((entry) => [entry.id, entry.key, entry.kind, entry.turn, entry.name]), [+ ["IMG-001", `${p1}#0`, "upload", 1, null],+ ["IMG-002", `${p1}#1`, "upload", 1, null],+ ["IMG-003", "tool:toolu_1#0", "view", 2, "c.png"],+ ["IMG-004", `${p3}#0`, "upload", 3, null],+ ]);+ assert.equal(index.turns, 3);+ assert.equal(index.images[2].width, 16);+ assert.deepEqual(index.uploads.map((upload) => [upload.uuid, upload.contentIds.length, upload.compacted]), [[p1, 2, false], [p3, 1, false]]);+ assert.equal(claudeImageData(index, index.images[2]), pngC);+ assert.equal(claudeImageData(index, index.images[1]), pngB);+});++test("the conversation is the branch the newest message is on; sidechains and attachments do not change it", () => {+ const t = transcript();+ const p1 = t.prompt([image(pngA), text("first")]);+ const a1 = t.assistant(text("ok"));+ t.prompt([image(pngB), text("abandoned")]);+ t.assistant(text("old answer"));+ // A rewind: a new prompt from the first answer.+ const p2 = t.prompt([image(pngC), text("edited")], {}, a1);+ t.attachment();+ t.assistant(text("sub"), { isSidechain: true });+ const chain = activeChain(t.records);+ assert.deepEqual(chain.filter((record) => record.type === "user").map((record) => record.uuid), [p1, p2]);+ const index = buildClaudeIndex("s", t.records);+ assert.deepEqual(index.images.map((entry) => entry.key), [`${p1}#0`, `${p2}#0`]);+});++test("compaction: the chain goes on across the boundary, and images before it are marked compacted", () => {+ const t = transcript();+ const p1 = t.prompt([image(pngA), text("first")]);+ t.assistant(text("ok"));+ t.boundary();+ t.summary();+ const p2 = t.prompt([image(pngB), text("after")]);+ const index = buildClaudeIndex("s", t.records);+ assert.deepEqual(index.images.map((entry) => [entry.id, entry.key, entry.compacted, entry.turn]), [["IMG-001", `${p1}#0`, true, 1], ["IMG-002", `${p2}#0`, false, 2]]);+ assert.deepEqual(index.uploads.map((upload) => upload.compacted), [true, false]);+});++test("an image our fetch tool returned is a copy of the original: no id, recorded with its turn", () => {+ const t = transcript();+ t.prompt([image(pngA), text("look")]);+ t.assistant(text("red"));+ t.prompt("look again");+ t.assistant({ type: "tool_use", id: "toolu_9", name: "mcp__plugin_codex-attachment-manager_codex_attachment_manager__cam_view_image", input: { ids: ["IMG-001"] } });+ t.toolResult("toolu_9", [text("[图片 IMG-001 取回的原图|未命名|用户上传|第 1 轮|8×8]"), image(pngA)]);+ t.prompt([image(pngB), text("new")]);+ const index = buildClaudeIndex("s", t.records);+ assert.deepEqual(index.images.map((entry) => entry.id), ["IMG-001", "IMG-002"]);+ assert.deepEqual([...index.copies.values()], [{ key: "tool:toolu_9#0", of: "IMG-001", turn: 2 }]);+});++test("the latest reply's text is kept for the ids the model asked for; a turn without a reply falls back", () => {+ const { t } = usualSession();+ assert.deepEqual(buildClaudeIndex("s", t.records).replies, ["Same red square."]);+ t.prompt("next");+ assert.deepEqual(buildClaudeIndex("s", t.records).replies, ["Same red square."]);+ const u = transcript();+ u.prompt("q");+ u.assistant(text("need IMG-002"));+ u.prompt("r");+ assert.deepEqual(buildClaudeIndex("s", u.records).replies, ["need IMG-002"]);+});++test("the title is the latest custom title, else the start of the first prompt", () => {+ const { t } = usualSession();+ assert.equal(buildClaudeIndex("s", t.records).title, "What are these?");+ t.records.push({ type: "custom-title", customTitle: "Keyframes", sessionId: "s" });+ assert.equal(buildClaudeIndex("s", t.records).title, "Keyframes");+});++test("a transcript is found by session id under projects/, and read again as it grows", () => {+ const home = mkdtempSync(join(tmpdir(), "cam-claude-"));+ const id = "11111111-2222-4333-8444-555555555555";+ mkdirSync(join(home, "projects", "D--work"), { recursive: true });+ const file = join(home, "projects", "D--work", `${id}.jsonl`);+ const t = transcript();+ t.prompt([image(pngA), text("one")]);+ writeFileSync(file, t.records.map((record) => JSON.stringify(record)).join("\n") + "\n");+ assert.equal(transcriptOf(id, home), file);+ assert.equal(transcriptOf("not-a-session", home), null);+ assert.equal(loadClaudeIndex(id, home).images.length, 1);+ t.assistant(text("ok"));+ t.prompt([image(pngB), text("two")]);+ appendFileSync(file, t.records.slice(1).map((record) => JSON.stringify(record)).join("\n") + "\n");+ assert.deepEqual(loadClaudeIndex(id, home).images.map((entry) => entry.id), ["IMG-001", "IMG-002"]);+ assert.equal(loadClaudeIndex("22222222-2222-4333-8444-555555555555", home).images.length, 0);+});