Skip to content

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.

fix(claude): 记录不全时宁可去掉思考,也不让新账号的会话卡住

chipfightere731571e17b3
diff --git a/plugin/src/claude-thinking.ts b/plugin/src/claude-thinking.ts
index 55d42f8..cda90d1 100644
--- a/plugin/src/claude-thinking.ts
+++ b/plugin/src/claude-thinking.ts
@@ -2,11 +2,12 @@
// Anthropic binds each thinking block to everything before it in the conversation (Fable 5.1, Opus 5.5, Sonnet 5.5,
// Haiku 5.5); accounts created from 2026-08-31 refuse a request whose thinking no longer matches, older ones let it
// through (docs/v0.4/plan.md §2). Thinking may be left out, as long as each block kept comes after exactly what it was
-// made after. So the engine remembers, per session, what it sent for each history it saw (as hash chains), and keeps a
-// thinking block only when what comes before it now is what was sent when the block was made.
+// made after. So once the engine has sent a session a changed history, it remembers what it sent for each history (as
+// hash chains), and keeps a thinking block only when what comes before it now is what was sent when it was made. A
+// block made after a history it has no entry for is left out: the record may be incomplete (a lost file, old entries).
// Input: a request's messages as Claude Code built them and as the engine will send them; the session's record.
-// Output: the messages without the thinking that no longer fits, counts, and the chains to remember;
-// <data dir>/claude/thinking/<session>.json (whether the account refuses such thinking, and hashes; never content).
+// Output: the messages without the thinking that no longer fits, counts, the chains to remember;
+// <data dir>/claude/thinking/<session>.json (flags and hashes; never content).
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
@@ -16,7 +17,7 @@ import { claudeThinkingDirOf } from "./paths.ts";
type Json = Record<string, any>;
const THINKING = new Set(["thinking", "redacted_thinking"]);
const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
-// Hashes of the latest histories only: a block is made after the history of the request just before it.
+// The latest histories only: older thinking without an entry is left out.
const KEEP = 2000;
// What Anthropic compares: values, not JSON formatting or key order; content given as a string is the text block it
@@ -40,56 +41,86 @@ export const chainOf = (messages: Json[]): string => messages.reduce((chain: str
const thinkingIn = (message: Json): number =>
message?.role === "assistant" && Array.isArray(message.content) ? message.content.filter((block: Json) => THINKING.has(block?.type)).length : 0;
-export type ThinkingFit = { messages: Json[]; kept: number; left: number; history: string; sent: string };
+// edited: the engine has sent this session a changed history; until then every history went out as Claude Code built
+// it. strict: Anthropic refused this session's thinking after a changed history (the account checks it).
+export type ThinkingRecord = { edited: boolean; strict: boolean; sent: Map<string, string> };
+export const newThinkingRecord = (): ThinkingRecord => ({ edited: false, strict: false, sent: new Map() });
-// sent: for each history the engine changed, the chain of what it sent instead. A history it never changed went out as
-// it was. The rewrite never adds, drops or edits an assistant message, so the n-th one of each list is the same.
-export function fitThinking(original: Json[], outgoing: Json[], sent: ReadonlyMap<string, string>): ThinkingFit {
+// made: the histories the request's thinking was made after.
+export type ThinkingFit = { messages: Json[]; kept: number; left: number; history: string; sent: string; made: string[] };
+
+// The rewrite never adds, drops or edits an assistant message, so the n-th one of each list is the same. keep false
+// leaves out all thinking, which Anthropic always accepts. An assistant message left empty goes too: Anthropic takes no
+// empty message, and joins the user messages around it.
+export function fitThinking(original: Json[], outgoing: Json[], record: ThinkingRecord, keep = true): ThinkingFit {
const madeAfter: string[] = [];
let history = "";
for (const message of original) {
if (message?.role === "assistant") madeAfter.push(history);
history = link(history, message);
}
+ const sentAfter = (made: string) => (record.sent.has(made) ? record.sent.get(made) : record.edited ? null : made);
let chain = "";
let assistant = 0;
let kept = 0;
let left = 0;
- const messages = outgoing.map((message) => {
- let next = message;
+ const made: string[] = [];
+ const messages: Json[] = [];
+ for (const message of outgoing) {
+ let next: Json | null = message;
if (message?.role === "assistant") {
- const made = madeAfter[assistant++];
+ const after = madeAfter[assistant++];
const count = thinkingIn(message);
- if (count) {
+ if (count && after !== undefined) made.push(after);
+ if (count && keep && after !== undefined && sentAfter(after) === chain) kept += count;
+ else if (count) {
+ left += count;
const rest = message.content.filter((block: Json) => !THINKING.has(block?.type));
- // A message of thinking alone stays: Anthropic takes no empty message (the request may then be refused).
- if (made === undefined || (sent.get(made) ?? made) === chain || !rest.length) kept += count;
- else {
- left += count;
- next = { ...message, content: rest };
- }
+ next = rest.length ? { ...message, content: rest } : null;
}
}
+ if (!next) continue;
chain = link(chain, next);
- return next;
- });
- return { messages, kept, left, history, sent: chain };
+ messages.push(next);
+ }
+ return { messages, kept, left, history, sent: chain, made };
+}
+
+// What went out for a history (latest last).
+export function rememberSent(record: ThinkingRecord, history: string, sent: string): void {
+ record.sent.delete(history);
+ record.sent.set(history, sent);
+ for (const key of record.sent.keys()) {
+ if (record.sent.size <= KEEP) break;
+ record.sent.delete(key);
+ }
}
-// strict: Anthropic refused this session's thinking after an edited history once (the account checks it).
-export type ThinkingRecord = { strict: boolean; sent: Map<string, string> };
+// After a request went through: what it sent for its history. The first changed history the engine sends a session
+// starts the record, with the histories its thinking so far was made after (they went out as they were). Returns
+// whether the record changed.
+export function recordSent(record: ThinkingRecord, history: string, sent: string, made: string[]): boolean {
+ if (!record.edited && sent === history) return false;
+ if (!record.edited) {
+ record.edited = true;
+ for (const before of made) rememberSent(record, before, before);
+ }
+ rememberSent(record, history, sent);
+ return true;
+}
export function readThinkingRecord(sessionId: string, dir = claudeThinkingDirOf()): ThinkingRecord {
- const empty: ThinkingRecord = { strict: false, sent: new Map() };
- if (!SESSION_ID.test(sessionId)) return empty;
+ if (!SESSION_ID.test(sessionId)) return newThinkingRecord();
const file = join(dir, `${sessionId}.json`);
- if (!existsSync(file)) return empty;
+ if (!existsSync(file)) return newThinkingRecord();
try {
const json = JSON.parse(readFileSync(file, "utf8"));
const pairs = Array.isArray(json.sent) ? json.sent.filter((pair: unknown) => Array.isArray(pair) && pair.length === 2 && pair.every((hash) => typeof hash === "string")) : [];
- return { strict: json.strict === true, sent: new Map(pairs) };
+ // A record is written once the engine has sent a changed history.
+ return { edited: json.edited !== false, strict: json.strict === true, sent: new Map(pairs) };
} catch {
- return empty;
+ // Unreadable: what went out is unknown, so the thinking made so far is left out.
+ return { edited: true, strict: false, sent: new Map() };
}
}
@@ -97,16 +128,6 @@ export function writeThinkingRecord(sessionId: string, record: ThinkingRecord, d
if (!SESSION_ID.test(sessionId)) return;
mkdirSync(dir, { recursive: true });
const file = join(dir, `${sessionId}.json`);
- writeFileSync(`${file}.tmp`, JSON.stringify({ strict: record.strict, sent: [...record.sent] }));
+ writeFileSync(`${file}.tmp`, JSON.stringify({ edited: record.edited, strict: record.strict, sent: [...record.sent] }));
renameSync(`${file}.tmp`, file);
}
-
-// What went out for a history: a changed one is remembered (latest last), one sent as it was needs no entry.
-export function rememberSent(record: ThinkingRecord, history: string, sent: string): void {
- record.sent.delete(history);
- if (sent !== history) record.sent.set(history, sent);
- for (const key of record.sent.keys()) {
- if (record.sent.size <= KEEP) break;
- record.sent.delete(key);
- }
-}
diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.ts
index b7aa157..6879ef6 100644
--- a/plugin/src/proxy.ts
+++ b/plugin/src/proxy.ts
@@ -27,7 +27,7 @@ import { fileURLToPath } from "node:url";
import zlib from "node:zlib";
import { claudeHome, loadClaudeIndex, type ClaudeIndex } from "./claude-index.ts";
import { findRequestImages, rewriteMessages, type RequestImage } from "./claude-rewrite.ts";
-import { chainOf, fitThinking, readThinkingRecord, rememberSent, writeThinkingRecord, type ThinkingRecord } from "./claude-thinking.ts";
+import { chainOf, fitThinking, readThinkingRecord, recordSent, writeThinkingRecord, type ThinkingRecord } from "./claude-thinking.ts";
import { codexHome } from "./codexconfig.ts";
import { buildOf, DEFAULT_PORT, ENGINE_SERVICE, engineHealth, versionOf, watchForCodex } from "./engine.ts";
import { findImages, type ImageRef } from "./images.ts";
@@ -323,11 +323,13 @@ export function thinkingRejected(status: number, body: string): boolean {
return status === 400 && /thinking/i.test(body) && /signature|bound to a different conversation|prefix/i.test(body);
}
-// v0.4: what to send for a Claude Code request, in order: the rewrite; if Anthropic refuses the thinking after the
-// changed history (thinkingRejected), the rewrite without the thinking that no longer fits (claude-thinking.ts); then
-// the original. Once a session's account refused such thinking (thinking.strict), the rewrite goes without it from the
-// start. history/sent: the chains to remember once an attempt goes through.
-export type ClaudeAttempt = { body: Buffer; report: Json; history: string | null; sent: string | null };
+// v0.4: what to send for a Claude Code request, each next one when Anthropic refuses the thinking after the changed
+// history (thinkingRejected): the rewrite with all its thinking (an account that lets it through); the rewrite without
+// the thinking that no longer fits (claude-thinking.ts), first once the account is known to refuse it; the rewrite
+// without any thinking, always accepted; the original as Claude Code built it. history/sent: the chains to remember
+// once the attempt goes through (null: not the session's conversation); made: the histories its thinking was made
+// after; sure: the record says all its thinking fits, so a refusal means the record misses what went out.
+export type ClaudeAttempt = { body: Buffer; report: Json; history: string | null; sent: string | null; made: string[]; sure: boolean };
// v0.4: the same rules as rewriteBody, for a Claude Code request (Anthropic Messages, claude-rewrite.ts). The current
// turn is the transcript's latest prompt: Claude Code writes it before it sends the request.
@@ -365,10 +367,14 @@ export function rewriteClaudeBody(original: Buffer, encoding: string | undefined
...(report.copies.length ? { copies: report.copies } : {}),
};
const changed = report.replaced.length > 0 || report.copies.length > 0;
+ // Once the engine has sent the session a changed history, thinking made after it may be in every later request, even
+ // with nothing left out now (an image checked again).
+ if (!changed && !thinking?.edited) return { body: original, report: summary, attempts: [] };
const rewritten = changed ? messages : json.messages;
- // Thinking made after an earlier edit may not fit even when nothing is left out now (an image checked again).
- const fit = thinking ? fitThinking(json.messages, rewritten, thinking.sent) : null;
- if (!changed && !(thinking?.strict && fit?.left)) return { body: original, report: summary, attempts: [] };
+ const fit = thinking ? fitThinking(json.messages, rewritten, thinking) : null;
+ // Side requests (no tools: the desktop's status summary, auto mode's check) are not the conversation.
+ const conversation = Array.isArray(json.tools) && json.tools.length > 0;
+ const history = fit && conversation ? fit.history : null;
const experiment = env.CAM_EXPERIMENT_BLOCK_BINDING?.trim();
const encode = (list: Json[], extra: Json) => {
const out: Json = { ...json, messages: list };
@@ -379,14 +385,19 @@ export function rewriteClaudeBody(original: Buffer, encoding: string | undefined
return { body, report: { ...summary, ...extra, ...(asked ? { experiment: { blockBinding: experiment, beta: "thinking-binding-controls-2026-08-01" } } : {}), decodedBefore: decoded.length, decodedAfter: next.length, encodedBefore: original.length, encodedAfter: body.length } };
};
const attempts: ClaudeAttempt[] = [];
- const add = (list: Json[], extra: Json, history: string | null, sent: string | null) => attempts.push({ ...encode(list, extra), history, sent });
- if (changed && !thinking?.strict) add(rewritten, {}, fit?.history ?? null, fit ? chainOf(rewritten) : null);
- if (changed && fit && (thinking?.strict || fit.left)) add(fit.messages, { thinking: { kept: fit.kept, left: fit.left }, ...(thinking?.strict ? {} : { retry: "thinking-signature" }) }, fit.history, fit.sent);
- // Then the original as Claude Code built it, without the thinking made while the engine had changed the history
- // before it: on an account that checks thinking, that no longer fits the original either.
- const back = !thinking ? null : changed ? fitThinking(json.messages, json.messages, thinking.sent) : fit;
- if (back?.left) add(back.messages, { thinking: { kept: back.kept, left: back.left }, ...(changed ? { fallback: "thinking-signature" } : {}) }, back.history, back.sent);
- attempts.push({ body: original, report: { ...summary, fallback: "thinking-signature" }, history: back?.history ?? null, sent: back?.history ?? null });
+ const made = fit?.made ?? [];
+ const add = (list: Json[], extra: Json, sent: string, sure: boolean) => attempts.push({ ...encode(list, extra), history, sent: history ? sent : null, made, sure });
+ const asBuilt = (extra: Json, sure: boolean) => attempts.push({ body: original, report: { ...summary, ...extra }, history, sent: history, made, sure });
+ if (!thinking?.strict) {
+ if (changed) add(rewritten, {}, chainOf(rewritten), fit?.left === 0);
+ else asBuilt({}, fit!.left === 0);
+ }
+ if (fit && (thinking!.strict || fit.left)) add(fit.messages, { thinking: { kept: fit.kept, left: fit.left }, ...(thinking!.strict ? {} : { retry: "thinking-signature" }) }, fit.sent, true);
+ if (fit?.kept) {
+ const bare = fitThinking(json.messages, rewritten, thinking!, false);
+ add(bare.messages, { thinking: { kept: 0, left: bare.left }, retry: "thinking-signature" }, bare.sent, false);
+ }
+ if (changed || thinking?.strict) asBuilt(changed ? { fallback: "thinking-signature" } : {}, false);
return { body: attempts[0].body, report: attempts[0].report, attempts };
}
@@ -598,10 +609,10 @@ async function main(): Promise<void> {
// Codex thread's once something is unchecked there.
const claude = upstream === CLAUDE_HOST ? claudeIdentity(req.headers) : null;
const claudeSession = claude?.sessionId && !claude.agentId && req.method === "POST" && path === "/v1/messages" ? claude.sessionId : null;
- // Once the session's account refused thinking after a changed history, every request of it is looked at, even with
- // nothing left out now: thinking made after an edited history no longer fits the history as it was.
+ // Once the engine has sent the session a changed history, every request of it is looked at, even with nothing left
+ // out now: thinking made after a changed history no longer fits the history as it was.
const thinking = claudeSession ? thinkingOf(claudeSession) : null;
- const claudeRewrite = claudeNeedsRewrite(claudeSession) || !!(thinking?.strict && thinking.sent.size);
+ const claudeRewrite = claudeNeedsRewrite(claudeSession) || !!thinking?.edited;
const claudeFields = claude ? { claudeSessionId: claude.sessionId, claudeAgentId: claude.agentId } : {};
const chunks: Buffer[] = [];
let requestBytes = 0;
@@ -644,7 +655,7 @@ async function main(): Promise<void> {
// What to send, in order: body null streams the request through unchanged. v0.4: Anthropic refusing an attempt's
// thinking after the changed history (thinkingRejected) moves on to the next one (see ClaudeAttempt), the last being
// the original as Claude Code built it; the statistics say which went out (the panel shows a fallback).
- type Attempt = { body: Buffer | null; report: Json | null; edited: boolean; history?: string | null; sent?: string | null };
+ type Attempt = { body: Buffer | null; report: Json | null; edited: boolean } & Partial<Pick<ClaudeAttempt, "history" | "sent" | "made" | "sure">>;
const send = (attempts: Attempt[], at = 0): void => { connectUpstream(viaOf(upstream), upstream).then((socket) => {
const attempt = attempts[at];
const outgoing = forwardHeaders(req.headers, upstream);
@@ -668,9 +679,12 @@ async function main(): Promise<void> {
if (thinkingRejected(status, text)) {
extra = { ...extra, rejected: [...(extra.rejected ?? []), status] };
if (dumpDir) { try { writeFileSync(dumpName(`.rejected-${at}.json`), text); } catch { /* experiments only */ } }
- // The account checks thinking: from now on the session's rewrites leave out what no longer fits.
- if (thinking && claudeSession && attempt.history && !thinking.strict) {
+ // The account checks thinking: from now on the session's rewrites leave out what no longer fits. Refused
+ // although the record said it all fits, the record misses what went out (a lost file, old entries): only
+ // what goes out from now on counts.
+ if (thinking && claudeSession && attempt.history) {
thinking.strict = true;
+ if (attempt.sure) thinking.sent.clear();
try { writeThinkingRecord(claudeSession, thinking); } catch { /* kept in memory */ }
}
socket.destroy();
@@ -685,8 +699,7 @@ async function main(): Promise<void> {
return;
}
// The thinking the model makes now comes after what this attempt sent.
- if (status >= 200 && status < 300 && thinking && claudeSession && attempt.history && attempt.sent) {
- rememberSent(thinking, attempt.history, attempt.sent);
+ if (status >= 200 && status < 300 && thinking && claudeSession && attempt.history && attempt.sent && recordSent(thinking, attempt.history, attempt.sent, attempt.made ?? [])) {
try { writeThinkingRecord(claudeSession, thinking); } catch { /* kept in memory */ }
}
res.writeHead(status, headers);
diff --git a/spike/src/claude-thinking.test.ts b/spike/src/claude-thinking.test.ts
index 2b1f7ce..4e89ee1 100644
--- a/spike/src/claude-thinking.test.ts
+++ b/spike/src/claude-thinking.test.ts
@@ -3,11 +3,11 @@
// test assertions only.
import assert from "node:assert/strict";
-import { mkdtempSync } from "node:fs";
+import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-import { chainOf, fitThinking, readThinkingRecord, rememberSent, writeThinkingRecord, type ThinkingRecord } from "../../plugin/src/claude-thinking.ts";
+import { chainOf, fitThinking, newThinkingRecord, readThinkingRecord, recordSent, rememberSent, writeThinkingRecord } from "../../plugin/src/claude-thinking.ts";
type Json = Record<string, any>;
const think = (signature: string) => ({ type: "thinking", thinking: "", signature });
@@ -28,17 +28,18 @@ function session() {
// The engine's edit: the image becomes a placeholder, and a note follows its message.
const omitted = (m0: Json) => [user(text("[IMG-001 omitted]"), m0.content[1]), { role: "system", content: "note" }];
-test("nothing changed: every thinking block stays, and what is sent is the history", () => {
+test("before the engine changed anything, every thinking block fits the history as it is", () => {
const { original } = session();
- const fit = fitThinking(original, original, new Map());
+ const fit = fitThinking(original, original, newThinkingRecord());
assert.deepEqual([fit.kept, fit.left], [2, 0]);
assert.deepEqual(fit.messages, original);
assert.equal(fit.sent, fit.history);
+ assert.equal(fit.made.length, 2);
});
test("thinking made after the history as it was leaves once an image before it is left out", () => {
const s = session();
- const fit = fitThinking(s.original, [...omitted(s.m0), s.a1, s.m2, s.a3, s.m4], new Map());
+ const fit = fitThinking(s.original, [...omitted(s.m0), s.a1, s.m2, s.a3, s.m4], newThinkingRecord());
assert.deepEqual([fit.kept, fit.left], [0, 2]);
assert.deepEqual(fit.messages[2].content, [text("Red.")]);
assert.deepEqual(fit.messages[4].content, [text("Still red.")]);
@@ -47,31 +48,52 @@ test("thinking made after the history as it was leaves once an image before it i
test("thinking made after what the engine sent stays, as long as the same goes out before it", () => {
const s = session();
+ const record = newThinkingRecord();
// The request of turn 2: the image already left out, s1 with it.
- const before = fitThinking([s.m0, s.a1, s.m2], [...omitted(s.m0), s.a1, s.m2], new Map());
+ const before = fitThinking([s.m0, s.a1, s.m2], [...omitted(s.m0), s.a1, s.m2], record);
assert.equal(before.left, 1);
- const record: ThinkingRecord = { strict: true, sent: new Map() };
- rememberSent(record, before.history, before.sent);
+ assert.equal(recordSent(record, before.history, before.sent, before.made), true);
+ assert.equal(record.edited, true);
// Turn 3: s3 was made after what turn 2 sent.
- const fit = fitThinking(s.original, [...omitted(s.m0), s.a1, s.m2, s.a3, s.m4], record.sent);
+ const fit = fitThinking(s.original, [...omitted(s.m0), s.a1, s.m2, s.a3, s.m4], record);
assert.deepEqual([fit.kept, fit.left], [1, 1]);
assert.deepEqual(fit.messages[4], s.a3);
- // The image checked again: s1 fits again; s3 was made while the image was left out, so it does not.
- const back = fitThinking(s.original, s.original, record.sent);
+ // The image checked again: s1 was made before anything changed, so it fits again; s3 was made while the image was
+ // left out, so it does not.
+ const back = fitThinking(s.original, s.original, record);
assert.deepEqual([back.kept, back.left], [1, 1]);
assert.deepEqual(back.messages[1], s.a1);
assert.deepEqual(back.messages[3].content, [text("Still red.")]);
});
+test("once the engine changed a history, thinking after one it has no entry for is left out", () => {
+ const s = session();
+ // A record that lost its entries (a deleted file, old entries): nothing is known about what went out.
+ const fit = fitThinking(s.original, s.original, { edited: true, strict: true, sent: new Map() });
+ assert.deepEqual([fit.kept, fit.left], [0, 2]);
+});
+
test("an edit after a thinking block leaves that block alone", () => {
const s = session();
const m2 = user(text("And now?"), image("BBBB"));
- const fit = fitThinking([s.m0, s.a1, m2, s.a3], [s.m0, s.a1, user(text("And now?"), text("[IMG-002 omitted]")), { role: "system", content: "note" }, s.a3], new Map());
+ const fit = fitThinking([s.m0, s.a1, m2, s.a3], [s.m0, s.a1, user(text("And now?"), text("[IMG-002 omitted]")), { role: "system", content: "note" }, s.a3], newThinkingRecord());
assert.deepEqual([fit.kept, fit.left], [1, 1]);
assert.deepEqual(fit.messages[1], s.a1);
});
-test("cache breakpoints, key order and string content are not part of the history; a message of thinking alone is not emptied", () => {
+test("without any thinking: every block goes, and a message of thinking alone goes with it", () => {
+ const s = session();
+ const alone = assistant(think("s9"));
+ const bare = fitThinking([...s.original, alone], [...s.original, alone], newThinkingRecord(), false);
+ assert.deepEqual([bare.kept, bare.left], [0, 3]);
+ assert.equal(bare.messages.length, s.original.length);
+ assert.deepEqual(bare.messages[1].content, [text("Red.")]);
+ // Left out because it no longer fits, too.
+ const fit = fitThinking([s.m0, alone], [...omitted(s.m0), alone], newThinkingRecord());
+ assert.deepEqual([fit.kept, fit.left, fit.messages.length], [0, 1, 2]);
+});
+
+test("cache breakpoints, key order and string content are not part of the history", () => {
const s = session();
const moved = [s.m0, s.a1, s.m2, s.a3, user(text("Next.", { cache_control: { type: "ephemeral" } }))];
assert.equal(chainOf(moved), chainOf(s.original));
@@ -82,25 +104,29 @@ test("cache breakpoints, key order and string content are not part of the histor
const result = (content: unknown) => user({ type: "tool_result", tool_use_id: "toolu_1", content });
assert.equal(chainOf([result("done")]), chainOf([result([{ type: "text", text: "done" }])]));
assert.notEqual(chainOf([s.m0, later]), chainOf([s.m0, { ...later, content: "<total_tokens>2 tokens left</total_tokens>" }]));
- const alone = assistant(think("s9"));
- const fit = fitThinking([s.m0, alone], [...omitted(s.m0), alone], new Map());
- assert.deepEqual([fit.kept, fit.left], [1, 0]);
});
-test("the record: what was sent per history, kept per session id, latest entries only", () => {
+test("the record: started by the first changed history, kept per session id, latest entries only", () => {
const dir = mkdtempSync(join(tmpdir(), "cam-thinking-"));
const id = "11111111-2222-4333-8444-555555555555";
const record = readThinkingRecord(id, dir);
- assert.deepEqual(record, { strict: false, sent: new Map() });
+ assert.deepEqual(record, newThinkingRecord());
+ // A history sent as it was, before anything changed: nothing to remember.
+ assert.equal(recordSent(record, "h0", "h0", []), false);
+ assert.equal(record.edited, false);
+ // The first changed one: with the histories the thinking so far was made after.
+ assert.equal(recordSent(record, "h1", "s1", ["h0"]), true);
+ assert.deepEqual([...record.sent], [["h0", "h0"], ["h1", "s1"]]);
+ // From then on, histories sent as they were are remembered too.
+ recordSent(record, "h2", "h2", []);
record.strict = true;
- rememberSent(record, "h1", "s1");
- // A history sent as it was needs no entry, and drops an older one.
- rememberSent(record, "h2", "s2");
- rememberSent(record, "h2", "h2");
writeThinkingRecord(id, record, dir);
- assert.deepEqual(readThinkingRecord(id, dir), { strict: true, sent: new Map([["h1", "s1"]]) });
+ assert.deepEqual(readThinkingRecord(id, dir), { edited: true, strict: true, sent: new Map([["h0", "h0"], ["h1", "s1"], ["h2", "h2"]]) });
writeThinkingRecord("../elsewhere", record, dir);
- assert.equal(readThinkingRecord("../elsewhere", dir).strict, false);
+ assert.deepEqual(readThinkingRecord("../elsewhere", dir), newThinkingRecord());
+ // An unreadable record: what went out is unknown.
+ writeFileSync(join(dir, `${id}.json`), "{");
+ assert.deepEqual(readThinkingRecord(id, dir), { edited: true, strict: false, sent: new Map() });
for (let i = 0; i < 2100; i++) rememberSent(record, `k${i}`, `v${i}`);
assert.equal(record.sent.size, 2000);
assert.equal(record.sent.has("h1"), false);
diff --git a/spike/src/proxy.test.ts b/spike/src/proxy.test.ts
index f5f7a7a..d425e14 100644
--- a/spike/src/proxy.test.ts
+++ b/spike/src/proxy.test.ts
@@ -239,19 +239,22 @@ test("a Claude Code request is rewritten from the session's transcript and selec
test("an account that refuses thinking after an edited history gets the rewrite without the thinking that no longer fits", async () => {
const { usualSession, usualRequest, text } = await import("./claude-fixtures.ts");
const { rewriteClaudeBody } = await import("../../plugin/src/proxy.ts");
- const { rememberSent } = await import("../../plugin/src/claude-thinking.ts");
+ const { newThinkingRecord, recordSent } = await import("../../plugin/src/claude-thinking.ts");
const home = mkdtempSync(join(tmpdir(), "cam-claude-home-"));
const dir = mkdtempSync(join(tmpdir(), "cam-claude-sel-"));
const session = "11111111-2222-4333-8444-555555555555";
const { t, p1 } = usualSession();
mkdirSync(join(home, "projects", "D--work"), { recursive: true });
writeFileSync(join(home, "projects", "D--work", `${session}.jsonl`), t.records.map((record) => JSON.stringify(record)).join("\n") + "\n");
- const body = Buffer.from(JSON.stringify({ model: "claude-haiku-5-5", thinking: { type: "adaptive" }, messages: usualRequest() }));
+ // Claude Code's main loop: the conversation, with its tools.
+ const request = (messages: any[]) => Buffer.from(JSON.stringify({ model: "claude-haiku-5-5", thinking: { type: "adaptive" }, tools: [{ name: "Read", input_schema: { type: "object" } }], messages }));
+ const body = request(usualRequest());
writeSelection({ threadId: session, unchecked: { [`${p1}#1`]: { id: "IMG-002", at: "2026-10-10T00:00:00Z" } } }, dir);
- const record = { strict: false, sent: new Map<string, string>() };
+ const record = newThinkingRecord();
+ const steps = (out: any) => out.attempts.map((attempt: any) => [attempt.report.retry ?? null, attempt.report.fallback ?? null, attempt.report.thinking ?? null]);
// Not known yet: the rewrite as it is, then without the thinking after the placeholder, then the original.
const first = rewriteClaudeBody(body, undefined, session, dir, home, {}, record);
- assert.deepEqual(first.attempts.map((attempt: any) => [attempt.report.retry ?? null, attempt.report.fallback ?? null, attempt.report.thinking ?? null]), [
+ assert.deepEqual(steps(first), [
[null, null, null],
["thinking-signature", null, { kept: 0, left: 1 }],
[null, "thinking-signature", null],
@@ -262,30 +265,30 @@ test("an account that refuses thinking after an edited history gets the rewrite
// Known: that rewrite first.
record.strict = true;
const strict = rewriteClaudeBody(body, undefined, session, dir, home, {}, record);
- assert.deepEqual(strict.attempts.map((attempt: any) => attempt.report.thinking?.left ?? null), [1, null]);
- rememberSent(record, strict.attempts[0].history!, strict.attempts[0].sent!);
+ assert.deepEqual(steps(strict), [[null, null, { kept: 0, left: 1 }], [null, "thinking-signature", null]]);
+ const went = strict.attempts[0];
+ recordSent(record, went.history!, went.sent!, went.made);
// The next request carries thinking made after that; with the image checked again it no longer fits, while the
- // thinking made before the edit fits again.
+ // thinking made before the edit fits again. Should the record be wrong, the request goes without any thinking.
const next = [...usualRequest(), { role: "assistant", content: [{ type: "thinking", thinking: "", signature: "sig-9" }, text("Blue.")] }, { role: "user", content: [text("More?")] }];
writeSelection({ threadId: session, unchecked: {} }, dir);
- const again = rewriteClaudeBody(Buffer.from(JSON.stringify({ model: "claude-haiku-5-5", thinking: { type: "adaptive" }, messages: next })), undefined, session, dir, home, {}, record);
- assert.deepEqual(again.attempts.map((attempt: any) => attempt.report.thinking ?? null), [{ kept: 1, left: 1 }, null]);
+ const again = rewriteClaudeBody(request(next), undefined, session, dir, home, {}, record);
+ assert.deepEqual(steps(again), [[null, null, { kept: 1, left: 1 }], ["thinking-signature", null, { kept: 0, left: 2 }], [null, null, null]]);
+ assert.deepEqual(again.attempts.map((attempt: any) => attempt.sure), [true, false, false]);
const sent = JSON.parse(again.attempts[0].body.toString("utf8")).messages;
assert.deepEqual(sent[1].content.map((block: any) => block.type), ["thinking", "text"]);
assert.deepEqual(sent[9].content.map((block: any) => block.type), ["text"]);
- // Another image unchecked: should that rewrite be refused, the original goes without the thinking made while the
- // engine had changed the history (it no longer fits the original), and only then as Claude Code built it.
+ // An account not known to check: the request as Claude Code built it first.
+ const lenient = rewriteClaudeBody(request(next), undefined, session, dir, home, {}, { ...record, strict: false });
+ assert.deepEqual(steps(lenient), [[null, null, null], ["thinking-signature", null, { kept: 1, left: 1 }], ["thinking-signature", null, { kept: 0, left: 2 }]]);
+ assert.equal(lenient.attempts[0].body.equals(request(next)), true);
+ // Another image unchecked: nothing made so far fits.
writeSelection({ threadId: session, unchecked: { [`${p1}#0`]: { id: "IMG-001", at: "2026-10-10T00:00:00Z" } } }, dir);
- const other = rewriteClaudeBody(Buffer.from(JSON.stringify({ model: "claude-haiku-5-5", thinking: { type: "adaptive" }, messages: next })), undefined, session, dir, home, {}, record);
- assert.deepEqual(other.attempts.map((attempt: any) => [attempt.report.fallback ?? null, attempt.report.thinking ?? null]), [
- [null, { kept: 0, left: 2 }],
- ["thinking-signature", { kept: 1, left: 1 }],
- ["thinking-signature", null],
- ]);
- const back = JSON.parse(other.attempts[1].body.toString("utf8")).messages;
- assert.equal(back.length, next.length);
- assert.deepEqual(back[1].content.map((block: any) => block.type), ["thinking", "text"]);
- assert.deepEqual(back[8].content.map((block: any) => block.type), ["text"]);
+ const other = rewriteClaudeBody(request(next), undefined, session, dir, home, {}, record);
+ assert.deepEqual(steps(other), [[null, null, { kept: 0, left: 2 }], [null, "thinking-signature", null]]);
+ // Side requests (no tools) are not the conversation: nothing of them is remembered.
+ const side = rewriteClaudeBody(Buffer.from(JSON.stringify({ model: "claude-haiku-5-5", messages: next })), undefined, session, dir, home, {}, record);
+ assert.deepEqual(side.attempts.map((attempt: any) => attempt.history), [null, null]);
});
test("Anthropic refusing the thinking after an edited history is told apart from other 400s", async () => {