Stop paying the multimodal tax. Your AI agent keeps every image it has seen but only sends the ones it needs: lighter chats, no endless reconnecting, no starting over. Works with Codex, Claude Code, Cline, Gemini CLI, OpenCode, WorkBuddy and more. Install once, forget it.
TypeScript ai-agentsai-imageclaude-codeclaude-code-pluginclinecodexcodex-plugincomputer-usecontext-engineeringcontext-managementdeveloper-toolsgemini-cliimage-generationmcpmultimodalmultimodal-aiopencodeqwen-codetoken-optimizationvision-language-model
fix(panel): 原任务的记录被删掉时,列出还能找到的图并提示缺了一段历史
chipfighter5465ef9a6279
diff --git a/docs/plan.md b/docs/plan.mdindex 6807192..132a8d7 100644--- a/docs/plan.md+++ b/docs/plan.md@@ -451,3 +451,8 @@ P1 通过后,再按用户的节奏一步步探索改写。- 每张缩略图 0.08 秒,一张张补上,不挡列表。- **压缩的旧记录**:`.jsonl.zst` 用 Node 自带的 zstd 解压后整份读入;同时存在 `.jsonl` 时以它为准。- **归档的任务**:完整查找时把 `archived_sessions` 也算上,同一段记录两边都有时以 `sessions` 里的为准。读的时候找不到某一段(例如上次查找之后才归档),立刻重新查找一遍,最多每 5 秒一次。+- **找不到的历史**(v0.1-13,用户 2026-09-25 要求):重新查找之后,前面某一段历史还是找不到(例如原任务的记录被删掉了,不是归档),就跳过这一段,照常读剩下的:+ - 面板列出剩下的图,并提示“前面有一段历史找不到了,那一段里的图片没法列出”;+ - 编号和轮次从剩下的部分重新算;+ - 引擎也按剩下的部分改写。取消过的图照样换成占位符,认不出的图原样发送。+ - 任务自己的最后一段找不到时,仍然当作没有记录。diff --git a/docs/tasks.md b/docs/tasks.mdindex 7627817..c6d09cb 100644--- a/docs/tasks.md+++ b/docs/tasks.md@@ -67,6 +67,8 @@- [x] **v0.1-12 原任务归档后,从它分叉的任务打开面板报错**(用户 2026-09-25 报告:“rollout segment not found”;`thread-index.ts`;设计见 plan.md 第 15 节;证据:新增单元测试覆盖“先归档”和“读过之后才归档”两种情况;用修好的代码只读地跑用户那个任务,读出 16 轮、10 张图,标题也对)- 原因:分叉出来的任务,记录开头指向原任务的某一段历史;原任务归档后,那一段挪到了 `archived_sessions`,面板只在 `sessions` 里找。- 和任务里的图片数量、mp3 文件无关。+- [x] **v0.1-13 原任务的记录被彻底删掉时,列出还能找到的图**(用户 2026-09-25 要求;`thread-index.ts`、`panel-state.ts`、`panel.html`;设计见 plan.md 第 15 节;证据:新增 2 个单元测试,面板开发页截图)+ - 以前这种情况面板只显示报错;现在列出剩下的图,并提示前面有一段历史找不到了。- [x] **v0.1-7 许可证和 CI**(用户 2026-09-25 定:MIT,并加上 CI):`LICENSE`(插件目录里也放一份);`.github/workflows/ci.yml` 在 Windows、macOS、Linux 上跑单元测试;问题反馈模板,方便 macOS、Linux 用户在 GitHub 上报问题。- 待定:Windows 上不先停用就移除插件,Codex 会断连,只能靠卸载命令恢复;要不要用计划任务让引擎不依赖插件启动,见 spec.md 第 5 节。diff --git a/plugin/src/panel-state.ts b/plugin/src/panel-state.tsindex 2554144..212bbf4 100644--- a/plugin/src/panel-state.ts+++ b/plugin/src/panel-state.ts@@ -2,7 +2,7 @@// for in its latest reply, and the engine's statistics of the latest request. Also applies check/uncheck actions.// P4 — serves each image for the panel's thumbnails and previews, and the inputs of its "next message" estimate:// the last full request as a size baseline, which images it carried, and whether the engine could not rewrite it.-// v0.1-9 — the task's name for the title (thread-names.ts).+// v0.1-9 — the task's name for the title (thread-names.ts). v0.1-13 — whether part of the history could not be found.// Input: thread id, the sessions directory (rollouts are only read) and the tool's data directory.// Output: PanelState as plain JSON; selection changes are written to <data dir>/selection/.@@ -32,8 +32,10 @@ export type SendInfo = {};// started: the thread has a rollout. A panel opened on a new chat before its first message may be tied to a thread// Codex prepared and then replaced (v0.1-8); that one never gets a rollout.+// historyMissing: an earlier part of the history is gone for good (e.g. the task a fork came from was deleted), so the+// images in it are not listed (v0.1-13).export type PanelState = {- threadId: string; title: string | null; started: boolean; turns: number; images: PanelImage[]; requested: string[];+ threadId: string; title: string | null; started: boolean; historyMissing: boolean; turns: number; images: PanelImage[]; requested: string[];totals: { images: number; unchecked: number; checkedBytes: number; allBytes: number };send: SendInfo;};@@ -117,7 +119,7 @@ export function panelState(threadId: string, history: Record_[], index: ThreadIn};});return {- threadId, title, started: history.length > 0, turns: index.turns, images, requested,+ threadId, title, started: history.length > 0, historyMissing: false, turns: index.turns, images, requested,totals: {images: images.length,unchecked: images.filter((image) => !image.checked).length,@@ -128,33 +130,35 @@ export function panelState(threadId: string, history: Record_[], index: ThreadIn};}-// A thread with no rollout yet (new, or the panel opened outside a thread) simply has no images.-function historyOf(threadId: string, sessionsDir: string): Record_[] {+// A thread with no rollout yet (new, or the panel opened outside a thread) simply has no images. An earlier part of+// the history that is gone for good is left out and reported.+function historyOf(threadId: string, sessionsDir: string): { history: Record_[]; missing: string[] } {+ const missing: string[] = [];try {- return readThreadHistory(sessionsDir, threadId);+ return { history: readThreadHistory(sessionsDir, threadId, missing), missing };} catch (error) {- if (error instanceof Error && error.message.startsWith("no rollout found")) return [];+ if (error instanceof Error && error.message.startsWith("no rollout found")) return { history: [], missing };throw error;}}function load(threadId: string, options: PanelOptions) {const root = options.dataRoot ?? dataDir();- const history = historyOf(threadId, options.sessionsDir);+ const { history, missing } = historyOf(threadId, options.sessionsDir);const index = buildIndex(threadId, history);const selection = effectiveSelection(threadId, options.sessionsDir, selectionDirOf(root));const stats = readRequestStats(threadId, requestStatsDirOf(root));const title = threadTitle(options.sessionsDir, threadId, history);- return { root, history, index, selection, stats, title };+ return { root, history, index, selection, stats, title, historyMissing: missing.length > 0 };}export function loadPanelState(threadId: string, options: PanelOptions): PanelState {- const { history, index, selection, stats, title } = load(threadId, options);- return panelState(threadId, history, index, new Set(Object.keys(selection.unchecked)), stats, title);+ const { history, index, selection, stats, title, historyMissing } = load(threadId, options);+ return { ...panelState(threadId, history, index, new Set(Object.keys(selection.unchecked)), stats, title), historyMissing };}export function applySelection(threadId: string, change: { uncheck?: string[]; check?: string[]; checkAll?: boolean }, options: PanelOptions): PanelState {- const { root, history, index, selection, stats, title } = load(threadId, options);+ const { root, history, index, selection, stats, title, historyMissing } = load(threadId, options);const unchecked = change.checkAll ? {} : { ...selection.unchecked };const byId = new Map(index.images.map((image) => [image.id, image]));for (const id of change.uncheck ?? []) {@@ -169,13 +173,13 @@ export function applySelection(threadId: string, change: { uncheck?: string[]; cdelete unchecked[image.key];}writeSelection({ threadId, unchecked }, selectionDirOf(root));- return panelState(threadId, history, index, new Set(Object.keys(unchecked)), stats, title);+ return { ...panelState(threadId, history, index, new Set(Object.keys(unchecked)), stats, title), historyMissing };}// One image for the panel: a PNG larger than maxSide is scaled down; smaller PNGs and other formats (which the// browser scales itself) are passed through as they are.export function imageFor(threadId: string, id: string, maxSide: number, options: PanelOptions): { id: string; dataUrl: string | null } {- const history = historyOf(threadId, options.sessionsDir);+ const { history } = historyOf(threadId, options.sessionsDir);const index = buildIndex(threadId, history);const image = index.images.find((candidate) => candidate.id === id);if (!image) throw new Error(`${id} is not an image of this thread`);diff --git a/plugin/src/panel.html b/plugin/src/panel.htmlindex a519e7e..45e8615 100644--- a/plugin/src/panel.html+++ b/plugin/src/panel.html@@ -14,7 +14,8 @@v0.1-8 — a panel opened on a new chat before its first message may stay tied to a thread Codex prepared and thenreplaced. v0.1-10: such a panel switches to the thread the user starts there (cam_bind): the page notes when it is onscreen, and only a thread started meanwhile counts; when several did, the user picks one. v0.1-9: the title shows the- task's name.+ task's name. v0.1-13: a notice when an earlier part of the history cannot be found (e.g. the task a fork came from+ was deleted); the images left are listed as usual.--><style>/* Fallbacks follow Codex's own widget palette; inside Codex its theme variables (MCP Apps host styles) win. */@@ -659,6 +660,7 @@const tasks = newTasks();nodes.push(tasks.length > 1 ? chooser(tasks) : notice("info", "这个任务还没开始。发出第一条消息后,这里会自动切到这个任务。"));}+ if (S.data?.historyMissing) nodes.push(notice("warn", "这个任务前面有一段历史找不到了(它所在的任务记录可能已被删除),那一段里的图片没法在这里列出。"));if (S.data?.engineRunning === false && S.data?.setup?.usesEngine !== false) nodes.push(notice("warn", "代理没有在运行,取消勾选暂时不会生效。关掉 Codex 再打开,一般就能恢复。"));const sendNotice = S.data?.send?.notice;if (sendNotice?.kind === "skipped") nodes.push(notice("error", `上一次请求(${timeOf(sendNotice.at)})没能按勾选替换,图片原样发给了模型。原因:${sendNotice.reason}。`));diff --git a/plugin/src/thread-index.ts b/plugin/src/thread-index.tsindex 0b7a9f7..7ed37b1 100644--- a/plugin/src/thread-index.ts+++ b/plugin/src/thread-index.ts@@ -7,7 +7,8 @@// Codex compressed after a week without activity (.jsonl.zst) are read as well.// v0.1-10 — the first line of recent rollouts, so a panel opened on a new chat can find the thread that started there.// v0.1-12 — archived tasks (<CODEX_HOME>/archived_sessions) are looked up too: a fork's history may start in a page of-// a task the user has archived since.+// a task the user has archived since. v0.1-13 — if that page is gone for good (its task deleted), the rest is read and+// the gap reported, instead of failing.// Input: the sessions directory and a thread id. Output: ThreadIndex (in memory; files are parsed incrementally).import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, statSync, writeFileSync } from "node:fs";@@ -144,12 +145,20 @@ function withSegments<T>(sessionsDir: string, read: (tree: Tree) => T): T {const baseOf = (file: string): Json | null => (records(file)[0]?.type === "session_meta" ? records(file)[0].payload.history_base ?? null : null);-function effective(segments: Map<string, string>, segmentId: string, endOffset = Number.POSITIVE_INFINITY): Parsed[] {+// With `missing` (the second look, after walking the tree again), a page the history starts in that is still not found+// is left out and its id added to `missing`; without it, the miss is thrown for the caller to look again.+function effective(segments: Map<string, string>, segmentId: string, endOffset = Number.POSITIVE_INFINITY, missing: string[] | null = null): Parsed[] {const file = segments.get(segmentId);// Not listed (yet): the caller walks the tree again once.if (!file) throw Object.assign(new Error(`rollout segment not found: ${segmentId}`), { code: "ENOENT" });const base = baseOf(file);- const inherited = base ? effective(segments, base.thread_id, base.end_byte_offset) : [];+ let inherited: Parsed[] = [];+ if (base) {+ try { inherited = effective(segments, base.thread_id, base.end_byte_offset, missing); } catch (error) {+ if (!missing || (error as NodeJS.ErrnoException)?.code !== "ENOENT") throw error;+ if (!missing.includes(base.thread_id)) missing.push(base.thread_id);+ }+ }return [...inherited, ...records(file).filter((record) => record.offset < endOffset)];}@@ -320,15 +329,22 @@ export function threadsStartedSince(sessionsDir: string, since: number): Array<{}// The thread's model-visible history records, following paginated segments back through history_base.-export function readThreadHistory(sessionsDir: string, threadId: string): Parsed[] {- return withSegments(sessionsDir, ({ segments, threadOf }) => {+// A page the history starts in may be gone for good (its task deleted rather than archived): after walking the tree+// again, what is left is returned and the missing page ids are added to `missing`. The thread's own latest page must+// be there.+export function readThreadHistory(sessionsDir: string, threadId: string, missing: string[] = []): Parsed[] {+ const read = ({ segments, threadOf }: Tree, gaps: string[] | null) => {const own = [...segments.keys()].filter((id) => threadOf.get(id) === threadId);if (!own.length) throw new Error(`no rollout found for thread ${threadId}`);const bases = new Set(own.map((id) => baseOf(segments.get(id)!)?.thread_id).filter(Boolean));const heads = own.filter((id) => !bases.has(id));if (heads.length !== 1) throw new Error(`expected one latest rollout segment for ${threadId}, found ${heads.length}`);- return effective(segments, heads[0]);- });+ return effective(segments, heads[0], Number.POSITIVE_INFINITY, gaps);+ };+ try { return read(allSegments(sessionsDir), null); } catch (error) {+ if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") throw error;+ return read(allSegments(sessionsDir, true), missing);+ }}export function loadThreadIndex(sessionsDir: string, threadId: string): ThreadIndex {diff --git a/spike/scripts/panel-dev.ts b/spike/scripts/panel-dev.tsindex 20109db..f63f723 100644--- a/spike/scripts/panel-dev.ts+++ b/spike/scripts/panel-dev.ts@@ -5,7 +5,8 @@// (?theme=dark, ?solo=1 for the panel alone, ?demo=pending|preview for a state to screenshot, ?slow=1 for slow calls,// ?stats=none|skipped|websocket for other engine statistics than a normal rewritten request, ?setup=off for a Codex that// does not go through the engine yet, ?demo=disabled for right after 停用插件, ?thread=fresh for a task with no rollout;-// with &newtask=1 the user then starts one task — the panel switches to it — and with &newtask=2 two at once).+// with &newtask=1 the user then starts one task — the panel switches to it — and with &newtask=2 two at once;+// ?thread=gap for a fork whose original task was deleted, v0.1-13).// The demo task has a name, as if the user had renamed it in Codex (v0.1-9).// Everything is written to a temporary folder, including a Codex home of its own: nothing in the user's Codex home is// read or changed, whatever is clicked.@@ -60,6 +61,12 @@ writeFileSync(join(day, `rollout-2026-09-24T10-00-00-${THREAD}.jsonl`),turn("t4") + upload("msg_4", "t4", [["settings-screenshot.png", screenshot]]) +line("response_item", { type: "image_generation_call", id: "ig_1", status: "completed", result: png(256, 256, (x, y) => [x, y, 180]).toString("base64") }) + say("需要 IMG-001 才能回答。", "t4"));+// ?thread=gap: a fork whose history starts in a page of a task that was deleted since.+const GAP = `${THREAD.slice(0, -4)}0a90`;+writeFileSync(join(day, `rollout-2026-09-24T11-00-00-${GAP}.jsonl`),+ line("session_meta", { id: GAP, forked_from_id: "01a0d301-0000-7000-8000-00000000dead", history_base: { thread_id: "01a0d301-0000-7000-8000-00000000dead", end_byte_offset: 4096 } }) ++ turn("g1") + upload("msg_g1", "g1", [["after-fork.png", sunset]]));+// Its name, as Codex keeps it next to the sessions folder (the panel's title).writeFileSync(join(root, "session_index.jsonl"), `${JSON.stringify({ id: THREAD, thread_name: "海报配色调整", updated_at: "2026-09-24T10:00:00Z" })}`);@@ -138,7 +145,8 @@ const HOST = `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><tit// ?thread=fresh: a thread that has no rollout, like a panel opened on a new chat whose prepared thread was replaced.// Each page load gets a thread of its own, so a switch made on an earlier load does not carry over.const fresh = params.get("thread") === "fresh" ? Math.random().toString(16).slice(2, 6).padEnd(4, "0") : null;- const call = (name, args) => fetch("/call" + (fresh ? "?fresh=" + fresh : ""), { method: "POST", body: JSON.stringify({ name, arguments: args }) }).then((r) => r.json());+ const query = fresh ? "?fresh=" + fresh : params.get("thread") === "gap" ? "?gap=1" : "";+ const call = (name, args) => fetch("/call" + query, { method: "POST", body: JSON.stringify({ name, arguments: args }) }).then((r) => r.json());window.addEventListener("message", async (event) => {const m = event.data;if (!m || event.source !== frame.contentWindow) return;@@ -199,7 +207,8 @@ createServer((request, response) => {request.on("end", () => {const { name, arguments: args } = JSON.parse(body);const freshId = `${THREAD.slice(0, -4)}${fresh}`;- const threadMeta = fresh && /^[0-9a-f]{4}$/.test(fresh) ? { threadId: freshId, thread_id: freshId } : meta;+ const gap = new URL(request.url, "http://x").searchParams.has("gap");+ const threadMeta = fresh && /^[0-9a-f]{4}$/.test(fresh) ? { threadId: freshId, thread_id: freshId } : gap ? { threadId: GAP, thread_id: GAP } : meta;try { reply(200, "application/json", JSON.stringify(callTool(name, args ?? {}, threadMeta, sessionsDir))); }catch (error) { reply(200, "application/json", JSON.stringify({ isError: true, content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }] })); }});diff --git a/spike/src/panel-state.test.ts b/spike/src/panel-state.test.tsindex e58b8b3..76080b6 100644--- a/spike/src/panel-state.test.ts+++ b/spike/src/panel-state.test.ts@@ -1,5 +1,6 @@// Purpose: P3-3 — the panel's data: image states, the ids the model asked for, check/uncheck, and thumbnails.// P4 — previews and other formats, and threads without a rollout yet. v0.1-9 — the task's name as the title.+// v0.1-13 — a fork whose earlier history is gone.// Input: synthetic rollouts in temporary folders; output: Node test assertions only.import assert from "node:assert/strict";@@ -10,7 +11,7 @@ import { decodePng } from "../../plugin/src/png.ts";import { applySelection, imageFor, loadPanelState, requestedIds, sendInfo } from "../../plugin/src/panel-state.ts";import { requestStatsDirOf } from "../../plugin/src/paths.ts";import { recordRequest } from "../../plugin/src/request-stats.ts";-import { assistant, line, red, sampleSessions, THREAD, turn } from "./testfixtures.ts";+import { assistant, line, red, sampleSessions, THREAD, turn, upload } from "./testfixtures.ts";import { shrink } from "../../plugin/src/thumbnail.ts";const records = (text: string) => text.trim().split("\n").map((raw) => JSON.parse(raw));@@ -114,3 +115,14 @@ test("the title is the task's name, else the start of its first message; a threaassert.equal(loadPanelState(THREAD, options).title, "改图任务");assert.equal(loadPanelState("01a0d301-0000-7000-8000-00000000ffff", options).title, null);});++test("a fork whose earlier history is gone lists the images left and says part of the history is missing", () => {+ const options = sampleSessions();+ const FORK = "01a0d301-0000-7000-8000-00000000abce";+ writeFileSync(join(options.sessionsDir, "2026", "09", "24", `rollout-2026-09-24T11-00-00-${FORK}.jsonl`),+ line("session_meta", { id: FORK, forked_from_id: "01a0d301-0000-7000-8000-00000000dead", history_base: { thread_id: "01a0d301-0000-7000-8000-00000000dead", end_byte_offset: 99 } }) ++ turn("t5") + upload("msg_5", "t5", [["later.png", red]]));+ const state = loadPanelState(FORK, options);+ assert.deepEqual([state.historyMissing, state.started, state.images.map((image) => image.name)], [true, true, ["later.png"]]);+ assert.equal(loadPanelState(THREAD, options).historyMissing, false);+});diff --git a/spike/src/thread-index.test.ts b/spike/src/thread-index.test.tsindex cc88711..d5ceee5 100644--- a/spike/src/thread-index.test.ts+++ b/spike/src/thread-index.test.ts@@ -2,6 +2,7 @@// re-reads of an appended file, and paginated segments chained through history_base.// v0.1-10/11 — compressed rollouts, new rollouts found in today's folder between full walks, a moved rollout found// again, and pixel fingerprints shared through the cache folder. v0.1-12 — a fork's history in an archived task's page.+// v0.1-13 — a history whose earlier page is gone for good.// Input: synthetic rollouts in a temporary directory; output: Node test assertions only.import assert from "node:assert/strict";@@ -11,7 +12,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import test from "node:test";import { zstdCompressSync } from "node:zlib";-import { hasRollout, loadThreadIndex, setPixelCache, threadsStartedSince } from "../../plugin/src/thread-index.ts";+import { buildIndex, hasRollout, loadThreadIndex, readThreadHistory, setPixelCache, threadsStartedSince } from "../../plugin/src/thread-index.ts";import { startThread, todayFolder } from "./testfixtures.ts";import { png } from "./testkit.ts";@@ -159,3 +160,15 @@ test("a fork's history may start in a page of a task the user archived, before o}}});++test("when a page the history starts in is gone for good (its task deleted), the rest is read and the gap reported", () => {+ const { dir, day } = sessions();+ const GONE = "01a0d301-0000-7000-8000-0000000000dd";+ writeFileSync(join(day, `rollout-2026-09-24T10-00-00-${THREAD}.jsonl`),+ line("session_meta", { id: THREAD, forked_from_id: GONE, history_base: { thread_id: GONE, end_byte_offset: 1234 } }) + turn("t2") + upload("msg_2", "t2", "b.png", blue));+ const missing: string[] = [];+ assert.deepEqual(buildIndex(THREAD, readThreadHistory(dir, THREAD, missing)).images.map((i) => [i.id, i.name]), [["IMG-001", "b.png"]]);+ assert.deepEqual(missing, [GONE]);+ assert.deepEqual(loadThreadIndex(dir, THREAD).images.map((i) => i.name), ["b.png"], "the engine reads what is left too");+ assert.throws(() => readThreadHistory(dir, "01a0d301-0000-7000-8000-0000000000ee"), /no rollout found/, "a thread without a page of its own still has no history");+});