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.

feat(panel): 标题显示任务名;新任务发出第一条消息后面板自动切过去;分叉后打开面板不再卡

chipfighterace725bbed70
diff --git a/docs/plan.md b/docs/plan.md
index 28e7734..4401964 100644
--- a/docs/plan.md
+++ b/docs/plan.md
@@ -416,16 +416,23 @@ P1 通过后,再按用户的节奏一步步探索改写。
- `forked_from_id`、`parent_thread_id`。
- 带历史启动的子代理,Codex 也记成从父任务分叉(`forked_from_id` 是父任务)。
- **每个任务各有一个插件服务进程**。所以分叉出来的任务第一次开面板时,插件服务是新起的,内存里的缓存是空的。
+- **任务记录的存放**:放在 `sessions/YYYY/MM/DD`,按任务创建那天的本地日期分目录。新任务、分叉和长任务的后续分页,都落在当天的目录里。
+- **记录第一行的时间**:每行开头的 `timestamp` 是写入这一行的时间。新任务的记录是发第一条消息时才写的,所以第一行的时间就是任务开始的时间。
+- **压缩的旧记录**:新版 Codex 会把一周没动过的任务记录压缩成 `.jsonl.zst`。要往里追加时,先解压回 `.jsonl`、再删掉压缩文件。以前的代码只认 `.jsonl`,面板打开这种旧任务时是空的。
### 设计
- **标题**:显示 `session_index.jsonl` 里的名称;没有名称时,显示第一条用户消息的开头;任务还没开始时,显示“新任务”。改名后,面板下次刷新时跟着变。
- **新任务自动绑定**:
- - 面板所在的任务还没有记录时,插件服务列出“刚开始的、用户自己开的任务”:
- - 第一次写入记录的时间,不早于面板打开前 10 秒,而且在最近 30 秒内;
+ - 面板页面记下自己哪些时间段显示在屏幕上(页面可见、宽高不为 0),每次读数据时带给插件服务:
+ - 第一段从页面打开前 10 秒算起,因为发第一条消息时 Codex 可能重新加载面板页面;
+ - 页面被挡住或切走后再显示,就开始新的一段;最多保留 20 段。
+ - 面板所在的任务还没有记录时,插件服务列出符合条件的任务:
+ - 开始的时间落在某一段里,或者在这一段结束后 5 秒内(用户发完消息马上切走,页面还没来得及记下);
- 来源不是子代理、内部任务、`exec` 或 `mcp`,不是分叉,`thread_source` 为空或者是 `user`。
- - 面板只在自己显示在屏幕上时处理这份名单:正好一个就自动切过去;两个以上就列出名称,让用户选。
- - 30 秒的限制是为了排除这种情况:面板开在一个新任务页上,用户却去别处开了任务,之后才回来。
+ - 正好一个就自动切过去;两个以上就列出名称,让用户选。
+ - 为什么按时间段,不按“最近 30 秒”:第一版按 30 秒算。可是用户发完第一条消息就切到别的窗口、过一会儿才回来,任务就超过 30 秒了,面板会一直等下去。按时间段算,回来多晚都能切过去;在别的页面开始的任务,因为当时这个面板不在屏幕上,照样不会被认走。
+ - 已知的例外:两个窗口并排、两个面板都开在新任务页上,在一个窗口里发消息,两个面板都会切过去。
- 绑定记在数据目录的 `bindings/<面板的任务编号>.json`。之后这个标签页的所有调用都按新任务处理,面板重新加载后也一样。
- 只接受面板的绑定调用,模型调用会被拒绝。
- **卡顿**:
@@ -437,3 +444,8 @@ P1 通过后,再按用户的节奏一步步探索改写。
- 像素指纹存进数据目录的 `cache/pixels/`,引擎和各个插件服务共用。只存指纹,不存图片内容。
- 任务记录的目录只完整遍历一次,之后每次只重新列出今天和昨天的目录;每分钟再完整遍历一次,作为兜底。
- 缩略图不写到磁盘,免得在数据目录里留下图片内容;仍然在内存里缓存。
+ - 改后实测(同样的数据):
+ - 分叉的任务在新进程里第一次读面板数据:0.07 秒(指纹已由引擎或原任务的面板存好);
+ - 之后每次读:2–6 毫秒;
+ - 每张缩略图 0.08 秒,一张张补上,不挡列表。
+- **压缩的旧记录**:`.jsonl.zst` 用 Node 自带的 zstd 解压后整份读入;同时存在 `.jsonl` 时以它为准。
diff --git a/docs/tasks.md b/docs/tasks.md
index f913a0a..88a1f6f 100644
--- a/docs/tasks.md
+++ b/docs/tasks.md
@@ -52,13 +52,18 @@
- “停用”改名“停用插件”,停用后显示“启用插件”,两种样式区分开,放在标题右侧;
- 按用户第二次的要求,点一下立即生效,不用再确认;中间的提示说明要重启 Codex;
- 撤回到 Codex 启动时的状态,就不再提示重启。
-- [ ] **v0.1-9 面板标题显示任务名**(用户 2026-09-25 定)
+- [x] **v0.1-9 面板标题显示任务名**(用户 2026-09-25 定;`thread-names.ts`;证据:3 个单元测试,面板开发页截图)
- 名称取自 Codex 的 `session_index.jsonl`,同一个任务以最后一行为准,改名后面板下次刷新就跟着变;
- - 没有名称时显示第一条用户消息的开头,还没开始的任务显示“新任务”。
-- [ ] **v0.1-10 新任务发出第一条消息后,面板自动切过去**(用户 2026-09-25 定;取代 v0.1-8 的“关掉再打开”提示;规则见 plan.md 第 15 节)
+ - 没有名称时显示第一条用户消息的开头,还没开始的任务显示“新任务”;太长时用省略号,鼠标悬停显示全名。
+- [x] **v0.1-10 新任务发出第一条消息后,面板自动切过去**(用户 2026-09-25 定;取代 v0.1-8 的“关掉再打开”提示;`binding.ts`、`panel.html`、工具 `cam_bind`;规则见 plan.md 第 15 节;证据:新增单元测试,面板开发页在无头 Edge 里跑通“自动切过去”和“两个任务时让用户选”)
- 查证:Codex 的侧边面板按任务保存,切换任务不用处理(桌面版前端代码,用户实测);在分叉里新开的面板绑在分叉上,勾选按规则继承(用户实测)。
+ - 判断“是不是这个页面上开始的任务”,按面板显示在屏幕上的时间段,不按“最近 30 秒”(原因见 plan.md 第 15 节)。
- 子代理不单独处理,等开源后的反馈(用户 2026-09-25 定)。
-- [ ] **v0.1-11 分叉后打开面板有点卡**(用户 2026-09-25 报告;测量和改法见 plan.md 第 15 节)
+ - 待用户在桌面版上实测。
+- [x] **v0.1-11 分叉后打开面板有点卡**(用户 2026-09-25 报告;`thread-index.ts`;测量和改法见 plan.md 第 15 节;证据:合成数据上新进程第一次读面板数据从 1.2 秒降到 0.07 秒,之后每次从 30–60 毫秒降到 2–6 毫秒)
+ - 插件服务记录超过 300 毫秒的调用和耗时(`plugin-server.jsonl` 里的 `slow`),用户实测时可以对照。
+ - 顺带:面板能读 Codex 压缩过的旧任务记录(`.jsonl.zst`);以前打开一周没动的任务,面板是空的。
+ - 待用户在桌面版上实测。
- [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/binding.ts b/plugin/src/binding.ts
new file mode 100644
index 0000000..9307d59
--- /dev/null
+++ b/plugin/src/binding.ts
@@ -0,0 +1,72 @@
+// Purpose: v0.1-10 — a panel opened on a new chat before its first message is tied to a thread Codex prepared, which
+// Codex may drop for a new one when the message is sent; the panel keeps asking about the prepared one (v0.1-8).
+// Here: which threads the user just started (for the panel to switch to), and which thread such a panel was switched
+// to, so every later call from that tab is about the new thread.
+// Input: the sessions directory (read-only) and the tool's data directory.
+// Output: <data dir>/bindings/<the panel's thread id>.json = { "threadId": "<the thread it shows>", "at": "…" }.
+
+import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { bindingsDirOf } from "./paths.ts";
+import { hasRollout, threadsStartedSince } from "./thread-index.ts";
+
+type Json = Record<string, any>;
+const THREAD_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+// Bindings never change once written, so they are remembered; a missing one is looked up again.
+const known = new Map<string, string>();
+
+// A thread the user started in a chat. Not: a sub-agent, an internal task (memory, guardian), a fork, a `codex exec`
+// run, a call through Codex's own MCP server, or a thread some feature started (e.g. an automation).
+export function isUserThread(meta: Json | null): boolean {
+ if (!meta || meta.forked_from_id || meta.parent_thread_id) return false;
+ const source = meta.source;
+ if (source && typeof source === "object" && ("subagent" in source || "internal" in source)) return false;
+ if (source === "exec" || source === "mcp") return false;
+ return meta.thread_source === undefined || meta.thread_source === null || meta.thread_source === "user";
+}
+
+// When the panel page was on screen, as it reports it: [from, to] in ms, newest last. The user sends the first message
+// on the page the panel is on, so a thread started while the page was on screen is this page's; one started while the
+// page was hidden (the user on another chat) is not, however late the user comes back. The page notes itself every few
+// seconds, so a thread started up to 5 s after the last note still counts (the user sent and left at once).
+export type Shown = Array<[number, number]>;
+export const LEFT_AT_ONCE_MS = 5_000;
+const MAX_PERIODS = 20;
+
+export function newThreads(sessionsDir: string, shown: unknown): Array<{ threadId: string; startedAt: number }> {
+ const periods = (Array.isArray(shown) ? shown : [])
+ .filter((period): period is [number, number] => Array.isArray(period) && Number.isFinite(period[0]) && Number.isFinite(period[1]) && period[0] <= period[1])
+ .slice(-MAX_PERIODS);
+ if (!periods.length) return [];
+ const since = Math.min(...periods.map(([from]) => from));
+ return threadsStartedSince(sessionsDir, since)
+ .filter((entry) => isUserThread(entry.meta) && periods.some(([from, to]) => entry.startedAt >= from && entry.startedAt <= to + LEFT_AT_ONCE_MS))
+ .map(({ threadId, startedAt }) => ({ threadId, startedAt }));
+}
+
+export function boundThread(threadId: string, dir = bindingsDirOf()): string | null {
+ const key = `${dir}|${threadId}`;
+ if (known.has(key)) return known.get(key)!;
+ if (!THREAD_ID.test(threadId)) return null;
+ try {
+ const target = JSON.parse(readFileSync(join(dir, `${threadId}.json`), "utf8"))?.threadId;
+ if (typeof target !== "string" || !THREAD_ID.test(target)) return null;
+ known.set(key, target);
+ return target;
+ } catch { return null; }
+}
+
+export function bindThread(threadId: string, target: string, dir = bindingsDirOf()): void {
+ if (!THREAD_ID.test(threadId) || !THREAD_ID.test(target)) throw new Error("不是任务编号");
+ mkdirSync(dir, { recursive: true });
+ const file = join(dir, `${threadId}.json`);
+ writeFileSync(`${file}.tmp`, JSON.stringify({ threadId: target, at: new Date().toISOString() }));
+ renameSync(`${file}.tmp`, file);
+ known.set(`${dir}|${threadId}`, target);
+}
+
+// The thread a panel's call is about: the panel's own once that has a rollout, otherwise the one it was switched to.
+export function resolveThread(threadId: string, sessionsDir: string, dir = bindingsDirOf()): string {
+ if (!THREAD_ID.test(threadId) || hasRollout(sessionsDir, threadId)) return threadId;
+ return boundThread(threadId, dir) ?? threadId;
+}
diff --git a/plugin/src/panel-state.ts b/plugin/src/panel-state.ts
index 41f14ef..2554144 100644
--- a/plugin/src/panel-state.ts
+++ b/plugin/src/panel-state.ts
@@ -2,6 +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).
// 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/.
@@ -9,6 +10,7 @@ import { dataDir, requestStatsDirOf, selectionDirOf } from "./paths.ts";
import { readRequestStats, type RequestStats } from "./request-stats.ts";
import { effectiveSelection, writeSelection } from "./selection.ts";
import { buildIndex, imageData, readThreadHistory, type IndexedImage, type ThreadIndex } from "./thread-index.ts";
+import { threadTitle } from "./thread-names.ts";
import { pngThumbnail } from "./thumbnail.ts";
type Json = Record<string, any>;
@@ -31,7 +33,7 @@ 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.
export type PanelState = {
- threadId: string; started: boolean; turns: number; images: PanelImage[]; requested: string[];
+ threadId: string; title: string | null; started: boolean; turns: number; images: PanelImage[]; requested: string[];
totals: { images: number; unchecked: number; checkedBytes: number; allBytes: number };
send: SendInfo;
};
@@ -95,7 +97,7 @@ export function sameContent(index: ThreadIndex, image: IndexedImage): string[] {
.map((other) => other.id);
}
-export function panelState(threadId: string, history: Record_[], index: ThreadIndex, unchecked: Set<string>, stats: RequestStats | null): PanelState {
+export function panelState(threadId: string, history: Record_[], index: ThreadIndex, unchecked: Set<string>, stats: RequestStats | null, title: string | null = null): PanelState {
const requested = requestedIds(history);
const carried: Record<string, number> | null = stats?.lastHttp?.imageSizes ?? null;
// Images after the last one that request carried, or from a later turn, were added since and go out next time.
@@ -115,7 +117,7 @@ export function panelState(threadId: string, history: Record_[], index: ThreadIn
};
});
return {
- threadId, started: history.length > 0, turns: index.turns, images, requested,
+ threadId, title, started: history.length > 0, turns: index.turns, images, requested,
totals: {
images: images.length,
unchecked: images.filter((image) => !image.checked).length,
@@ -142,16 +144,17 @@ function load(threadId: string, options: PanelOptions) {
const index = buildIndex(threadId, history);
const selection = effectiveSelection(threadId, options.sessionsDir, selectionDirOf(root));
const stats = readRequestStats(threadId, requestStatsDirOf(root));
- return { root, history, index, selection, stats };
+ const title = threadTitle(options.sessionsDir, threadId, history);
+ return { root, history, index, selection, stats, title };
}
export function loadPanelState(threadId: string, options: PanelOptions): PanelState {
- const { history, index, selection, stats } = load(threadId, options);
- return panelState(threadId, history, index, new Set(Object.keys(selection.unchecked)), stats);
+ const { history, index, selection, stats, title } = load(threadId, options);
+ return panelState(threadId, history, index, new Set(Object.keys(selection.unchecked)), stats, title);
}
export function applySelection(threadId: string, change: { uncheck?: string[]; check?: string[]; checkAll?: boolean }, options: PanelOptions): PanelState {
- const { root, history, index, selection, stats } = load(threadId, options);
+ const { root, history, index, selection, stats, title } = 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 ?? []) {
@@ -166,7 +169,7 @@ export function applySelection(threadId: string, change: { uncheck?: string[]; c
delete unchecked[image.key];
}
writeSelection({ threadId, unchecked }, selectionDirOf(root));
- return panelState(threadId, history, index, new Set(Object.keys(unchecked)), stats);
+ return panelState(threadId, history, index, new Set(Object.keys(unchecked)), stats, title);
}
// One image for the panel: a PNG larger than maxSide is scaled down; smaller PNGs and other formats (which the
diff --git a/plugin/src/panel.html b/plugin/src/panel.html
index 224fddb..a519e7e 100644
--- a/plugin/src/panel.html
+++ b/plugin/src/panel.html
@@ -12,7 +12,9 @@
v0.1-5 — 启用插件 / 停用插件 (cam_setup): point Codex at the engine, or back to a direct connection before uninstalling.
The state is polled, and also re-read whenever the user moves to or touches the panel, or presses 刷新.
v0.1-8 — a panel opened on a new chat before its first message may stay tied to a thread Codex prepared and then
- replaced; it cannot follow the new one, so it says to reopen.
+ replaced. v0.1-10: such a panel switches to the thread the user starts there (cam_bind): the page notes when it is on
+ screen, and only a thread started meanwhile counts; when several did, the user picks one. v0.1-9: the title shows the
+ task's name.
-->
<style>
/* Fallbacks follow Codex's own widget palette; inside Codex its theme variables (MCP Apps host styles) win. */
@@ -57,10 +59,10 @@
header { flex: none; padding: 16px 18px 14px; }
.title { display: flex; align-items: center; gap: 8px; }
- .title h1 { margin: 0; font-size: 15px; font-weight: 600; letter-spacing: .01em; }
- .count { padding: 0 7px; border-radius: 999px; background: var(--bg-soft); color: var(--text-2); font-size: 12px; font-weight: 500; line-height: 20px; font-variant-numeric: tabular-nums; }
+ .title h1 { flex: 0 1 auto; min-width: 0; margin: 0; font-size: 15px; font-weight: 600; letter-spacing: .01em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .count { flex: none; padding: 0 7px; border-radius: 999px; background: var(--bg-soft); color: var(--text-2); font-size: 12px; font-weight: 500; line-height: 20px; font-variant-numeric: tabular-nums; }
.count:empty { display: none; }
- .actions { margin-left: auto; display: flex; align-items: center; gap: 6px; }
+ .actions { flex: none; margin-left: auto; display: flex; align-items: center; gap: 6px; }
.icon-quiet { width: 28px; height: 28px; padding: 0; border: 0; border-radius: 999px; background: transparent; color: var(--text-3); cursor: pointer; display: grid; place-items: center; transition: background .15s, color .15s; }
.icon-quiet:hover { background: var(--bg-soft); color: var(--text-2); }
.icon-quiet svg { width: 16px; height: 16px; }
@@ -144,6 +146,12 @@
.notice.info { background: var(--info-bg); color: var(--text); }
.notice .grow { flex: 1; }
.notice button { flex: none; border: 0; background: none; padding: 0; font-weight: 600; cursor: pointer; color: inherit; font-size: 12.5px; }
+ .notice.chooser { flex-direction: column; align-items: stretch; gap: 6px; }
+ .notice .pick { display: flex; gap: 8px; align-items: baseline; width: 100%; padding: 7px 10px; border: 1px solid var(--border); border-radius: 8px; background: var(--bg); text-align: left; font-weight: 500; transition: border-color .15s; }
+ .notice .pick:hover:not(:disabled) { border-color: var(--border-strong); }
+ .notice .pick:disabled { opacity: .5; cursor: default; }
+ .pick .pick-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .pick .pick-time { flex: none; color: var(--text-3); font-variant-numeric: tabular-nums; }
.empty { height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; padding: 24px; text-align: center; color: var(--text-3); }
.empty svg { width: 36px; height: 36px; margin-bottom: 6px; }
@@ -186,7 +194,7 @@
</head>
<body>
<header>
- <div class="title"><h1>图片</h1><span class="count" id="count"></span><div class="actions"><button class="icon-quiet" id="refresh" type="button" title="刷新" aria-label="刷新"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/></svg></button><span class="plugin" id="plugin"></span></div></div>
+ <div class="title"><h1 id="title">上下文素材</h1><span class="count" id="count"></span><div class="actions"><button class="icon-quiet" id="refresh" type="button" title="刷新" aria-label="刷新"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/></svg></button><span class="plugin" id="plugin"></span></div></div>
<div class="plan" id="plan">正在读取…</div>
<div class="meter" id="meter" hidden>
<div class="meter-head"><span id="meterLabel"></span><b id="meterValue"></b><span class="meter-full" id="meterFull"></span></div>
@@ -270,9 +278,16 @@
viewer: null, // { id, url, loading, failed }
refreshing: false, saving: false,
switching: false, // a 启用插件 / 停用插件 call is under way
+ switchingTask: false, // a cam_bind call is under way
manual: false, // the running refresh was asked for with the 刷新 button
};
let lastFresh = 0; // when the panel last received the thread's state
+ // When this page was on screen (v0.1-10), sent with every read: a panel on a new chat is offered the threads started
+ // meanwhile. [from, to] pairs in ms, newest last; the first reaches back 10 s for a page Codex reloads when the chat
+ // becomes a thread. Once hidden (another chat, another window in front), the page starts a new pair when shown again.
+ const openedAt = Date.now();
+ const shown = [];
+ let screenGap = true;
const images = () => S.data?.images ?? [];
const byId = (id) => images().find((image) => image.id === id);
const isChecked = (image) => (S.pending.has(image.id) ? S.pending.get(image.id) : image.checked);
@@ -304,7 +319,8 @@
S.manual = manual;
lastRefresh = Date.now();
renderRefresh();
- try { ingest((await callTool("cam_panel")).structuredContent); }
+ noteScreen();
+ try { ingest((await callTool("cam_panel", { shown })).structuredContent); followNewTask(); }
catch (error) { S.error = "读取失败:" + error.message; render(); }
finally { S.refreshing = false; S.manual = false; renderRefresh(); }
}
@@ -345,6 +361,34 @@
}
}
+ // ---- a panel opened on a new chat follows the thread its first message starts (v0.1-10) ----
+ // The plugin offers only threads started while this page was on screen, so a panel left on another new chat does not
+ // take a task started elsewhere. One: switch to it. Several (e.g. two windows side by side): the user picks one.
+ const onScreen = () => document.visibilityState === "visible" && window.innerWidth > 0 && window.innerHeight > 0;
+ function noteScreen() {
+ const now = Date.now();
+ if (!onScreen()) { screenGap = true; return; }
+ const last = shown[shown.length - 1];
+ if (last && !screenGap) last[1] = now;
+ else {
+ shown.push([shown.length ? now - 2000 : Math.min(openedAt - 10000, now), now]);
+ if (shown.length > 20) shown.shift();
+ }
+ screenGap = false;
+ }
+ const newTasks = () => (S.data?.started === false && !S.data?.switchedFrom ? S.data?.newTasks ?? [] : []);
+ function followNewTask() {
+ const tasks = newTasks();
+ if (tasks.length === 1) switchTo(tasks[0].threadId);
+ }
+ async function switchTo(threadId) {
+ if (S.switchingTask) return;
+ S.switchingTask = true; render();
+ try { ingest((await callTool("cam_bind", { target: threadId })).structuredContent); }
+ catch (error) { S.error = "切换失败:" + error.message; }
+ finally { S.switchingTask = false; render(); }
+ }
+
// 启用 / 停用: Codex reads the setting when it starts, so either one waits for a restart (the notices say so).
async function switchEngine(enable) {
if (S.switching) return;
@@ -491,6 +535,9 @@
function renderHeader() {
const list = images();
const plan = $("plan");
+ const title = !S.data ? "上下文素材" : S.data.title ?? (S.data.started === false ? "新任务" : "未命名任务");
+ $("title").textContent = title;
+ $("title").title = title;
$("count").textContent = list.length ? String(list.length) : "";
if (!S.data || !list.length) {
plan.textContent = !S.data ? (S.error ? "读取失败" : "正在读取…") : "还没有图片";
@@ -542,6 +589,32 @@
return box;
}
+ // Several threads started since the panel was opened: which one is this panel's?
+ function chooser(tasks) {
+ const key = `chooser|${tasks.map((task) => `${task.threadId}:${task.title ?? ""}`).join("|")}`;
+ let box = notices.get(key);
+ if (!box) {
+ box = document.createElement("div");
+ box.className = "notice info chooser";
+ const text = document.createElement("span");
+ text.textContent = "刚刚开始了好几个任务,这个面板要显示哪一个?";
+ box.append(text);
+ for (const task of tasks) {
+ const button = document.createElement("button");
+ button.type = "button";
+ button.className = "pick";
+ const name = Object.assign(document.createElement("span"), { className: "pick-name", textContent: task.title ?? "新任务" });
+ const time = Object.assign(document.createElement("span"), { className: "pick-time", textContent: clockOf(task.startedAt) });
+ button.append(name, time);
+ button.addEventListener("click", () => switchTo(task.threadId));
+ box.append(button);
+ }
+ notices.set(key, box);
+ }
+ for (const button of box.querySelectorAll("button")) button.disabled = S.switchingTask;
+ return box;
+ }
+
function setupNotices() {
const setup = S.data?.setup;
if (!setup) return [];
@@ -582,7 +655,10 @@
const nodes = [];
if (S.error) nodes.push(notice("error", S.error, { label: "重试", run: () => { S.error = null; render(); refresh(); } }));
nodes.push(...setupNotices());
- if (S.data?.started === false) nodes.push(notice("info", "这个任务还没开始。发出第一条消息后,如果这里没有出现图片,请关掉这个标签页,再从“插件和 MCP”里打开一次:Codex 有时会给新任务换一个编号,已经打开的面板跟不上。"));
+ if (S.data?.started === false) {
+ const tasks = newTasks();
+ nodes.push(tasks.length > 1 ? chooser(tasks) : notice("info", "这个任务还没开始。发出第一条消息后,这里会自动切到这个任务。"));
+ }
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}。`));
@@ -688,10 +764,12 @@
.finally(() => setTimeout(() => { if (!S.data) refresh(); }, 1200));
// Slower, not stopped, while the page reports itself hidden: a host frame may report that wrongly.
setInterval(() => {
+ noteScreen();
if (!document.hidden || Date.now() - lastRefresh > 5 * POLL_MS) refresh();
renderRefresh();
}, POLL_MS);
- document.addEventListener("visibilitychange", () => { if (!document.hidden) refresh(); });
+ document.addEventListener("visibilitychange", () => { noteScreen(); if (!document.hidden) refresh(); });
+ window.addEventListener("resize", noteScreen);
document.documentElement.addEventListener("pointerenter", nudge);
document.addEventListener("pointerdown", nudge, { capture: true });
window.addEventListener("focus", nudge);
diff --git a/plugin/src/paths.ts b/plugin/src/paths.ts
index d85fb96..64a65ac 100644
--- a/plugin/src/paths.ts
+++ b/plugin/src/paths.ts
@@ -1,4 +1,5 @@
-// Purpose: one place for where the tool keeps its own data (selection state, request statistics, logs, backups).
+// Purpose: one place for where the tool keeps its own data (selection state, request statistics, logs, backups; since
+// v0.1-10 which task a panel was switched to, and v0.1-11 pixel fingerprints — never image content).
// Input: CAM_DATA_DIR when set; otherwise a per-user folder: %LOCALAPPDATA%\codex-attachment-manager on Windows,
// ~/Library/Application Support/codex-attachment-manager on macOS, $XDG_DATA_HOME (or ~/.local/share)/
// codex-attachment-manager on Linux. Never inside the plugin folder, which Codex replaces on every update, and never
@@ -19,3 +20,5 @@ export function dataDir(env: NodeJS.ProcessEnv = process.env, platform: NodeJS.P
export const selectionDirOf = (root = dataDir()) => join(root, "selection");
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");
+export const pixelCacheDirOf = (root = dataDir()) => join(root, "cache", "pixels");
diff --git a/plugin/src/plugin-server.ts b/plugin/src/plugin-server.ts
index 20cb588..79ce0db 100644
--- a/plugin/src/plugin-server.ts
+++ b/plugin/src/plugin-server.ts
@@ -6,6 +6,9 @@
// P4 — the panel page itself (an MCP App resource). cam_panel declares a "thread" entrypoint, so Codex lists the panel
// under the side panel's New Tab → 插件和 MCP, and the user opens it without the model.
// v0.1-5 — cam_setup: the panel's 启用 / 停用 point Codex at the engine or back to a direct connection (setup.ts).
+// v0.1-10 — a panel opened on a new chat before its first message is told which threads the user has just started,
+// and switches to one with cam_bind; from then on its calls are about that thread (binding.ts). v0.1-11 — slow calls
+// are logged with their duration; pixel fingerprints are shared with the engine through the data directory.
// Input: MCP JSON-RPC over stdio. Env: CAM_ENGINE_PORT (default 17891), CAM_NO_ENGINE=1 (tests), CAM_DATA_DIR.
// Output: tool results; <data dir>/plugin-server.jsonl (events and counts only, no conversation content).
@@ -14,11 +17,14 @@ import { dirname, join } from "node:path";
import { createInterface } from "node:readline";
import { fileURLToPath } from "node:url";
import { codexHome } from "./codexconfig.ts";
+import { bindThread, isUserThread, newThreads, resolveThread } from "./binding.ts";
import { DEFAULT_PORT, ensureEngine } from "./engine.ts";
import { isEntryPoint } from "./entry.ts";
import { applySelection, imageFor, loadPanelState, type PanelState } from "./panel-state.ts";
-import { dataDir } from "./paths.ts";
+import { dataDir, pixelCacheDirOf } from "./paths.ts";
import { connectDirectly, useEngine, usesEngine } from "./setup.ts";
+import { hasRollout, readThreadHistory, sessionMetaOf, setPixelCache } from "./thread-index.ts";
+import { threadTitle } from "./thread-names.ts";
type Json = Record<string, any>;
const here = dirname(fileURLToPath(import.meta.url));
@@ -33,7 +39,7 @@ export const TOOLS = [
name: "cam_panel",
title: "上下文素材",
description: "上下文素材面板:查看这个任务里的历史图片,勾选下一条消息要发给模型的图片。由用户在侧边面板里打开,模型不需要调用。",
- inputSchema: { type: "object", properties: { ...threadArg } },
+ inputSchema: { type: "object", properties: { ...threadArg, shown: { type: "array", items: { type: "array", items: { type: "number" } }, description: "面板页面显示在屏幕上的时间段(毫秒);面板调用时带上。" } } },
_meta: { ui: { resourceUri: PANEL_URI, visibility: ["app"] }, "openai/ui": { entrypoints: [{ type: "thread" }] } },
},
{
@@ -57,6 +63,13 @@ export const TOOLS = [
inputSchema: { type: "object", properties: { ...threadArg, enable: { type: "boolean" } }, required: ["enable"] },
_meta: APP_ONLY,
},
+ {
+ name: "cam_bind",
+ title: "上下文素材:切到新任务",
+ description: "素材面板内部使用:在新任务发出第一条消息之前打开的面板,切到用户刚开始的那个任务。只有用户能操作,模型调用会被拒绝。",
+ inputSchema: { type: "object", properties: { ...threadArg, target: { type: "string" } }, required: ["target"] },
+ _meta: APP_ONLY,
+ },
];
// A stack of pictures, drawn for light and dark themes (Codex takes https or data URLs only).
@@ -103,19 +116,43 @@ export function threadOf(args: Json, meta: Json | undefined): string | null {
}
const summary = (state: PanelState) => `共 ${state.totals.images} 张图,取消了 ${state.totals.unchecked} 张。`;
+const SLOW_MS = 300;
+
+// What a panel on a thread without a rollout is offered: the threads the user started while the panel was on screen.
+function newTasks(sessionsDir: string, shown: unknown): Json[] {
+ return newThreads(sessionsDir, shown).map(({ threadId, startedAt }) => {
+ let title: string | null = null;
+ try { title = threadTitle(sessionsDir, threadId, readThreadHistory(sessionsDir, threadId)); } catch { /* shown by its time */ }
+ return { threadId, startedAt, title };
+ });
+}
export function callTool(name: string, args: Json, meta: Json | undefined, sessionsDir = join(codexHome(), "sessions")): Json {
- const threadId = threadOf(args, meta);
- if (!threadId) throw new Error("不知道是哪个任务:缺少 threadId");
+ const own = threadOf(args, meta);
+ if (!own) throw new Error("不知道是哪个任务:缺少 threadId");
+ // A panel switched to a new thread (v0.1-10) keeps sending its own thread id; its calls are about the new one.
+ const threadId = resolveThread(own, sessionsDir);
const options = { sessionsDir };
+ const panel = (state: PanelState, extra: Json = {}) => ({ ...state, engineRunning, setup: setupState(), ...(threadId === own ? {} : { switchedFrom: own }), ...extra });
if (name === "cam_panel") {
const state = loadPanelState(threadId, options);
- return { content: [{ type: "text", text: summary(state) }], structuredContent: { ...state, engineRunning, setup: setupState() } };
+ // Only the panel page says when it was on screen; Codex's own first call does not, and gets no list.
+ const offer = !state.started && threadId === own && Array.isArray(args.shown) ? { newTasks: newTasks(sessionsDir, args.shown) } : {};
+ return { content: [{ type: "text", text: summary(state) }], structuredContent: panel(state, offer) };
}
if (name === "cam_set_selection") {
if (fromModel(meta)) throw new Error("只有用户能勾选或取消图片;需要某张图时,请回复“需要 IMG-xxx”。");
const state = applySelection(threadId, { uncheck: args.uncheck, check: args.check, checkAll: args.checkAll }, options);
- return { content: [{ type: "text", text: summary(state) }], structuredContent: { ...state, engineRunning, setup: setupState() } };
+ return { content: [{ type: "text", text: summary(state) }], structuredContent: panel(state) };
+ }
+ if (name === "cam_bind") {
+ if (fromModel(meta)) throw new Error("只有用户能切换面板对应的任务。");
+ const target = String(args.target ?? "");
+ if (hasRollout(sessionsDir, own)) throw new Error("这个面板的任务已经开始了,不用切换。");
+ if (!isUserThread(sessionMetaOf(sessionsDir, target))) throw new Error("只能切到用户自己开始的任务。");
+ bindThread(own, target);
+ const state = loadPanelState(target, options);
+ return { content: [{ type: "text", text: summary(state) }], structuredContent: { ...state, engineRunning, setup: setupState(), switchedFrom: own } };
}
if (name === "cam_setup") {
if (fromModel(meta)) throw new Error("只有用户能启用或停用。");
@@ -123,7 +160,7 @@ export function callTool(name: string, args: Json, meta: Json | undefined, sessi
// A conflict with the user's own settings throws here, before anything is written.
const plan = args.enable === true ? useEngine(enginePort) : connectDirectly();
const state = loadPanelState(threadId, options);
- return { content: [{ type: "text", text: args.enable === true ? "已启用,重启 Codex 后生效。" : "已停用,重启 Codex 后恢复直连。" }], structuredContent: { ...state, engineRunning, setup: setupState(), notes: plan.notes } };
+ return { content: [{ type: "text", text: args.enable === true ? "已启用,重启 Codex 后生效。" : "已停用,重启 Codex 后恢复直连。" }], structuredContent: panel(state, { notes: plan.notes }) };
}
if (name === "cam_image") {
const image = imageFor(threadId, String(args.id), Number(args.maxSide ?? 160), options);
@@ -146,6 +183,7 @@ function main(): void {
};
log({ event: "start", ppid: process.ppid });
setupState(); // what Codex read when it started this session
+ setPixelCache(pixelCacheDirOf());
// Codex starts several instances at once; a little jitter keeps them from racing to start the engine.
setTimeout(supervise, Math.floor(Math.random() * 400));
// Short enough that a crashed engine is back within Codex's own retry window.
@@ -172,10 +210,14 @@ function main(): void {
send({ id, error: { code: -32002, message: error instanceof Error ? error.message : String(error) } });
}
} else if (method === "tools/call") {
+ const started = performance.now();
try {
const result = callTool(params.name, params.arguments ?? {}, params._meta);
- // The open panel reads its state every few seconds and loads each image once; only changes are worth a line.
- if (params.name === "cam_set_selection" || params.name === "cam_setup" || fromModel(params._meta)) log({ event: "tools/call", name: params.name, fromModel: fromModel(params._meta) });
+ const ms = Math.round(performance.now() - started);
+ // The open panel reads its state every few seconds and loads each image once; only changes, and slow calls
+ // (v0.1-11), are worth a line.
+ if (["cam_set_selection", "cam_setup", "cam_bind"].includes(params.name) || fromModel(params._meta)) log({ event: "tools/call", name: params.name, fromModel: fromModel(params._meta), ms });
+ else if (ms >= SLOW_MS) log({ event: "slow", name: params.name, ms });
send({ id, result });
} catch (error) {
log({ event: "tools/call", name: params.name, fromModel: fromModel(params._meta), error: String(error) });
diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.ts
index dbd59b9..bbc40fa 100644
--- a/plugin/src/proxy.ts
+++ b/plugin/src/proxy.ts
@@ -4,6 +4,7 @@
// P4: the statistics also name the images each full request carried (the panel's size baseline), and note a
// WebSocket turn that kept running after images were unchecked (it cannot be rewritten).
// v0.1-3: reports its build and version; POST /__cam/retire hands the port to a newer engine (see engine.ts).
+// v0.1-11: pixel fingerprints go to the shared cache in the data directory, for the panels to reuse.
// Only metadata is logged (never auth headers or conversation content).
// Input: [--port 17891] [--stay (no auto-exit)] [--force-http] [--dump-requests (synthetic test threads only)];
// the outbound proxy is taken from HTTPS_PROXY/HTTP_PROXY or the system proxy settings (Windows, macOS).
@@ -22,12 +23,12 @@ import { codexHome } from "./codexconfig.ts";
import { buildOf, DEFAULT_PORT, ENGINE_SERVICE, engineHealth, versionOf, watchForCodex } from "./engine.ts";
import { findImages, type ImageRef } from "./images.ts";
import { isEntryPoint } from "./entry.ts";
-import { dataDir, proxyLogDirOf } from "./paths.ts";
+import { dataDir, pixelCacheDirOf, proxyLogDirOf } from "./paths.ts";
import { recordRequest } from "./request-stats.ts";
import { rewriteItems, type Described } from "./rewrite.ts";
import { connectDirectly, pluginGone, usesEngine } from "./setup.ts";
import { effectiveSelection, selectionDir } from "./selection.ts";
-import { loadThreadIndex, pixelHashOf, type ThreadIndex } from "./thread-index.ts";
+import { loadThreadIndex, pixelHashOf, setPixelCache, type ThreadIndex } from "./thread-index.ts";
type Json = Record<string, any>;
const UPSTREAM_HOST = "chatgpt.com";
@@ -234,6 +235,7 @@ async function main(): Promise<void> {
const forceHttp = process.argv.includes("--force-http");
const dumpDir = process.argv.includes("--dump-requests") ? join(dataDir(), "p2", "requests") : null;
const sessionsDir = join(codexHome(), "sessions");
+ setPixelCache(pixelCacheDirOf());
const via = outboundProxy();
const startedAt = new Date().toISOString();
// v0.1-3: which code this engine runs, so the plugin can tell when an update needs a new engine.
diff --git a/plugin/src/thread-index.ts b/plugin/src/thread-index.ts
index 384122a..f0150b1 100644
--- a/plugin/src/thread-index.ts
+++ b/plugin/src/thread-index.ts
@@ -1,50 +1,81 @@
// Purpose: P2 — the image timeline of one thread, read from its rollout (read-only): every image occurrence in
// history order with a stable id (IMG-001…), turn number, name, size and content hashes. The CLI and the proxy both
// derive it from the same files, so they agree on ids without sharing state.
+// v0.1-11 — a panel read on a new process used to walk every rollout folder on each call and decode every PNG for its
+// pixel fingerprint (1.2 s for 12 screenshots). Now the tree is walked in full once a minute and only the folders of
+// today and yesterday in between; fingerprints can be shared between processes through a cache folder. Rollouts
+// 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.
// Input: the sessions directory and a thread id. Output: ThreadIndex (in memory; files are parsed incrementally).
-import { closeSync, openSync, readdirSync, readSync, statSync } from "node:fs";
+import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, statSync, writeFileSync } from "node:fs";
import { basename, join } from "node:path";
+import { zstdDecompressSync } from "node:zlib";
import { findImages, type ImageRef } from "./images.ts";
import { decodePng } from "./png.ts";
type Json = Record<string, any>;
export type IndexedImage = ImageRef & { id: string; turn: number | null; bytes: number; pixelSha256: string | null };
export type ThreadIndex = { threadId: string; images: IndexedImage[]; byKey: Map<string, IndexedImage>; turns: number; turnNumbers: Map<string, number> };
-type Parsed = { offset: number; type: string; payload: Json };
+export type Parsed = { offset: number; type: string; payload: Json; timestamp: string | null };
type FileCache = { size: number; mtimeMs: number; parsedTo: number; records: Parsed[] };
-const SEGMENT_NAME = /rollout-[0-9T:-]+-([0-9a-f-]{36})(?:_([0-9a-f-]{36}))?\.jsonl$/;
+const SEGMENT_NAME = /^rollout-[0-9T:-]+-([0-9a-f-]{36})(?:_([0-9a-f-]{36}))?\.jsonl(?:\.zst)?$/;
const files = new Map<string, FileCache>();
const pixelHashes = new Map<string, string | null>();
function walk(directory: string): string[] {
- return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
+ let entries;
+ try { entries = readdirSync(directory, { withFileTypes: true }); } catch { return []; }
+ return entries.flatMap((entry) => {
const full = join(directory, entry.name);
return entry.isDirectory() ? walk(full) : entry.isFile() ? [full] : [];
});
}
-// Rollouts are append-only: parse only the complete lines added since the last read.
-function records(file: string): Parsed[] {
+function parseLines(buffer: Buffer, base: number, cache: FileCache): number {
+ let start = 0;
+ for (let end = buffer.indexOf(0x0a); end >= 0; end = buffer.indexOf(0x0a, start)) {
+ const text = buffer.toString("utf8", start, end).replace(/\r$/, "");
+ // A damaged line is skipped rather than failing the whole index; unknown images are sent unchanged anyway.
+ let record: Json | null = null;
+ if (text.trim()) { try { record = JSON.parse(text); } catch { record = null; } }
+ if (record) cache.records.push({ offset: base + start, type: record.type, payload: record.payload ?? {}, timestamp: typeof record.timestamp === "string" ? record.timestamp : null });
+ start = end + 1;
+ }
+ return start;
+}
+
+const missing = (plain: string) => Object.assign(new Error(`rollout missing: ${basename(plain)}`), { code: "ENOENT" });
+
+// A rollout is kept under its plain name; Codex may have compressed it (.jsonl.zst), or turned a compressed one back
+// into plain text to append to it.
+function existing(plain: string): string | null {
+ return existsSync(plain) ? plain : existsSync(`${plain}.zst`) ? `${plain}.zst` : null;
+}
+
+// Rollouts are append-only: parse only the complete lines added since the last read. A compressed one does not change
+// until Codex turns it back into plain text, so it is read whole once.
+function records(plain: string): Parsed[] {
+ const file = existing(plain);
+ if (!file) throw missing(plain);
const stat = statSync(file);
let cache = files.get(file);
+ if (file.endsWith(".zst")) {
+ if (!cache || cache.size !== stat.size || cache.mtimeMs !== stat.mtimeMs) {
+ cache = { size: stat.size, mtimeMs: stat.mtimeMs, parsedTo: 0, records: [] };
+ cache.parsedTo = parseLines(zstdDecompressSync(readFileSync(file)), 0, cache);
+ files.set(file, cache);
+ }
+ return cache.records;
+ }
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).replace(/\r$/, "");
- // A damaged line is skipped rather than failing the whole index; unknown images are sent unchanged anyway.
- let record: Json | null = null;
- if (text.trim()) { try { record = JSON.parse(text); } catch { record = null; } }
- if (record) cache.records.push({ offset: cache.parsedTo + start, type: record.type, payload: record.payload ?? {} });
- start = end + 1;
- }
- cache.parsedTo += start;
+ cache.parsedTo += parseLines(buffer, cache.parsedTo, cache);
cache.size = stat.size;
cache.mtimeMs = stat.mtimeMs;
files.set(file, cache);
@@ -54,16 +85,54 @@ function records(file: string): Parsed[] {
// Every rollout segment by id: a thread's first segment uses the thread id itself, later pages are named
// <thread>_<segment>. A fork's history_base points into its parent's segments, so bases are looked up globally.
-function allSegments(sessionsDir: string): { segments: Map<string, string>; threadOf: Map<string, string> } {
- const segments = new Map<string, string>();
- const threadOf = new Map<string, string>();
- for (const file of walk(sessionsDir)) {
- const match = SEGMENT_NAME.exec(basename(file));
- if (!match) continue;
- segments.set(match[2] ?? match[1], file);
- threadOf.set(match[2] ?? match[1], match[1]);
+// Codex files each rollout under <sessions>/YYYY/MM/DD of the day it was created (local time), so new threads, forks
+// and later pages all land in today's folder: between full walks only today's and yesterday's folders (local and UTC)
+// are listed again. A file moved elsewhere is found by the next full walk, or at once when a read misses it.
+type Tree = { walkedAt: number; segments: Map<string, string>; threadOf: Map<string, string> };
+const FULL_WALK_MS = 60_000;
+const trees = new Map<string, Tree>();
+
+export function recentFolders(sessionsDir: string, now = Date.now()): string[] {
+ const pad = (n: number) => String(n).padStart(2, "0");
+ const folders = new Set<string>();
+ for (const at of [now, now - 86_400_000]) {
+ const day = new Date(at);
+ folders.add(join(sessionsDir, String(day.getFullYear()), pad(day.getMonth() + 1), pad(day.getDate())));
+ folders.add(join(sessionsDir, String(day.getUTCFullYear()), pad(day.getUTCMonth() + 1), pad(day.getUTCDate())));
+ }
+ return [...folders];
+}
+
+function addSegment(tree: Tree, file: string): void {
+ const match = SEGMENT_NAME.exec(basename(file));
+ if (!match) return;
+ tree.segments.set(match[2] ?? match[1], file.replace(/\.zst$/, ""));
+ tree.threadOf.set(match[2] ?? match[1], match[1]);
+}
+
+function allSegments(sessionsDir: string, fresh = false): Tree {
+ const now = Date.now();
+ let tree = trees.get(sessionsDir);
+ if (!tree || fresh || now - tree.walkedAt > FULL_WALK_MS) {
+ tree = { walkedAt: now, segments: new Map(), threadOf: new Map() };
+ for (const file of walk(sessionsDir)) addSegment(tree, file);
+ trees.set(sessionsDir, tree);
+ return tree;
+ }
+ for (const folder of recentFolders(sessionsDir, now)) {
+ let names: string[];
+ try { names = readdirSync(folder); } catch { continue; }
+ for (const name of names) addSegment(tree, join(folder, name));
+ }
+ return tree;
+}
+
+// Reads that miss a file (moved or deleted since the last full walk) walk the tree again once.
+function withSegments<T>(sessionsDir: string, read: (tree: Tree) => T): T {
+ try { return read(allSegments(sessionsDir)); } catch (error) {
+ if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") throw error;
+ return read(allSegments(sessionsDir, true));
}
- return { segments, threadOf };
}
const baseOf = (file: string): Json | null => (records(file)[0]?.type === "session_meta" ? records(file)[0].payload.history_base ?? null : null);
@@ -76,10 +145,39 @@ function effective(segments: Map<string, string>, segmentId: string, endOffset =
return [...inherited, ...records(file).filter((record) => record.offset < endOffset)];
}
+// The engine and the plugin services (Codex starts one per task) share pixel fingerprints through this folder, so a
+// new process does not decode every PNG again. Only fingerprints are stored, never image content. Unset: memory only
+// (tests). "-" marks a PNG our decoder cannot read.
+let pixelCacheDir: string | null = null;
+export function setPixelCache(dir: string | null): void { pixelCacheDir = dir; }
+const SHA256 = /^[0-9a-f]{64}$/;
+
+function storedPixelHash(contentId: string): string | null | undefined {
+ if (!pixelCacheDir || !SHA256.test(contentId)) return undefined;
+ try {
+ const text = readFileSync(join(pixelCacheDir, contentId.slice(0, 2), contentId), "utf8").trim();
+ return text === "-" ? null : SHA256.test(text) ? text : undefined;
+ } catch { return undefined; }
+}
+
+function storePixelHash(contentId: string, hash: string | null): void {
+ if (!pixelCacheDir || !SHA256.test(contentId)) return;
+ try {
+ const folder = join(pixelCacheDir, contentId.slice(0, 2));
+ mkdirSync(folder, { recursive: true });
+ writeFileSync(join(folder, contentId), hash ?? "-", { flag: "wx" });
+ } catch { /* best effort; another process may have written it first */ }
+}
+
function pixelHash(ref: ImageRef, value: string): string | null {
if (ref.mime !== "image/png") return null;
if (!pixelHashes.has(ref.contentId)) {
- try { pixelHashes.set(ref.contentId, decodePng(Buffer.from(value, "base64")).pixelSha256); } catch { pixelHashes.set(ref.contentId, null); }
+ let hash = storedPixelHash(ref.contentId);
+ if (hash === undefined) {
+ try { hash = decodePng(Buffer.from(value, "base64")).pixelSha256; } catch { hash = null; }
+ storePixelHash(ref.contentId, hash);
+ }
+ pixelHashes.set(ref.contentId, hash);
}
return pixelHashes.get(ref.contentId) ?? null;
}
@@ -151,32 +249,78 @@ function firstLine(file: string): string {
}
}
+// The first record of a rollout: read from a plain file without parsing the rest; a compressed one is read whole.
+function firstRecord(plain: string): Parsed | null {
+ if (!existsSync(plain)) return records(plain)[0] ?? null;
+ try {
+ const raw = JSON.parse(firstLine(plain));
+ return { offset: 0, type: raw.type, payload: raw.payload ?? {}, timestamp: typeof raw.timestamp === "string" ? raw.timestamp : null };
+ } catch { return null; }
+}
+
const origins = new Map<string, { parent: string; at: string } | null>();
// A forked thread's session_meta names the thread it came from and when it was forked. Cached: it never changes.
export function forkOrigin(sessionsDir: string, threadId: string): { parent: string; at: string } | null {
if (origins.has(threadId)) return origins.get(threadId)!;
- const first = allSegments(sessionsDir).segments.get(threadId);
+ const meta = withSegments(sessionsDir, ({ segments }) => {
+ const first = segments.get(threadId);
+ return first ? { found: true, record: firstRecord(first) } : { found: false, record: null };
+ });
// No rollout yet: do not cache, it may appear once the thread starts.
- if (!first) return null;
- let origin: { parent: string; at: string } | null = null;
- try {
- const meta = JSON.parse(firstLine(first));
- if (meta.type === "session_meta" && meta.payload?.forked_from_id) origin = { parent: meta.payload.forked_from_id, at: meta.payload.timestamp ?? "" };
- } catch { /* unreadable first line: treat as not a fork */ }
+ if (!meta.found) return null;
+ const origin = meta.record?.type === "session_meta" && meta.record.payload.forked_from_id ? { parent: meta.record.payload.forked_from_id, at: meta.record.payload.timestamp ?? "" } : null;
origins.set(threadId, origin);
return origin;
}
+// Whether the thread has a rollout at all: a thread Codex prepared for a new chat has none until its first message.
+export function hasRollout(sessionsDir: string, threadId: string): boolean {
+ return allSegments(sessionsDir).segments.has(threadId);
+}
+
+// The thread's session_meta (where it came from: source, thread_source, forked_from_id, parent_thread_id), or null.
+export function sessionMetaOf(sessionsDir: string, threadId: string): Json | null {
+ return withSegments(sessionsDir, ({ segments }) => {
+ const first = segments.get(threadId);
+ const record = first ? firstRecord(first) : null;
+ return record?.type === "session_meta" ? record.payload : null;
+ });
+}
+
+// Threads whose rollout was first written at or after `since` (ms), with their session_meta, newest last. Only
+// today's and yesterday's folders are looked at. For a thread started by a message, the first line is written when
+// that message is sent (Codex writes rollouts lazily), so its timestamp tells when the thread started.
+export function threadsStartedSince(sessionsDir: string, since: number): Array<{ threadId: string; startedAt: number; meta: Json }> {
+ const found: Array<{ threadId: string; startedAt: number; meta: Json }> = [];
+ for (const folder of recentFolders(sessionsDir)) {
+ let names: string[];
+ try { names = readdirSync(folder); } catch { continue; }
+ for (const name of names) {
+ const match = SEGMENT_NAME.exec(name);
+ // First segments only (named after the thread); plain text, since a compressed rollout is a week old.
+ if (!match || match[2] || name.endsWith(".zst")) continue;
+ const file = join(folder, name);
+ try { if (statSync(file).mtimeMs < since) continue; } catch { continue; }
+ const record = firstRecord(file);
+ if (record?.type !== "session_meta") continue;
+ const startedAt = Date.parse(record.timestamp ?? record.payload.timestamp ?? "");
+ if (Number.isFinite(startedAt) && startedAt >= since && !found.some((entry) => entry.threadId === match[1])) found.push({ threadId: match[1], startedAt, meta: record.payload });
+ }
+ }
+ return found.sort((a, b) => a.startedAt - b.startedAt);
+}
+
// The thread's model-visible history records, following paginated segments back through history_base.
export function readThreadHistory(sessionsDir: string, threadId: string): Parsed[] {
- const { segments, threadOf } = allSegments(sessionsDir);
- 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 withSegments(sessionsDir, ({ segments, threadOf }) => {
+ 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]);
+ });
}
export function loadThreadIndex(sessionsDir: string, threadId: string): ThreadIndex {
diff --git a/plugin/src/thread-names.ts b/plugin/src/thread-names.ts
new file mode 100644
index 0000000..0d0351d
--- /dev/null
+++ b/plugin/src/thread-names.ts
@@ -0,0 +1,66 @@
+// Purpose: v0.1-9 — the task's name for the panel's title, as Codex shows it. Codex keeps names in
+// <CODEX_HOME>/session_index.jsonl, one {id, thread_name, updated_at} per line, append-only: a rename appends a line
+// and the last non-empty name of a thread wins; removing a thread's names rewrites the file. A task without a name is
+// shown by the start of the first message the user sent.
+// Input: the sessions directory (the index sits next to it) and a thread's history records. Output: strings; read-only.
+
+import { closeSync, openSync, readSync, statSync } from "node:fs";
+import { dirname, join } from "node:path";
+
+type Json = Record<string, any>;
+type IndexCache = { ino: number; size: number; mtimeMs: number; parsedTo: number; names: Map<string, string> };
+const indexes = new Map<string, IndexCache>();
+const TITLE_CHARS = 40;
+
+export const sessionIndexOf = (sessionsDir: string) => join(dirname(sessionsDir), "session_index.jsonl");
+
+// Parsed incrementally like a rollout; a rewritten file (another file id, or shorter) is read again from the start.
+function names(file: string): Map<string, string> {
+ let stat;
+ try { stat = statSync(file); } catch { return new Map(); }
+ let cache = indexes.get(file);
+ if (!cache || cache.ino !== stat.ino || stat.size < cache.parsedTo) cache = { ino: stat.ino, size: 0, mtimeMs: 0, parsedTo: 0, names: new Map() };
+ 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)) {
+ try {
+ const entry = JSON.parse(buffer.toString("utf8", start, end));
+ const name = typeof entry?.thread_name === "string" ? entry.thread_name.trim() : "";
+ if (typeof entry?.id === "string" && name) cache.names.set(entry.id, name);
+ } catch { /* a damaged line is skipped, as Codex does */ }
+ start = end + 1;
+ }
+ cache.parsedTo += start;
+ cache.size = stat.size;
+ cache.mtimeMs = stat.mtimeMs;
+ indexes.set(file, cache);
+ }
+ return cache.names;
+}
+
+export function threadName(sessionsDir: string, threadId: string): string | null {
+ return names(sessionIndexOf(sessionsDir)).get(threadId) ?? null;
+}
+
+// The first message the user sent (Codex records it as an event_msg user_message), on one line.
+export function firstMessage(history: Array<{ type: string; payload: Json }>): string | null {
+ for (const record of history) {
+ if (record.type !== "event_msg" || record.payload.type !== "user_message" || typeof record.payload.message !== "string") continue;
+ const text = record.payload.message.replace(/\s+/g, " ").trim();
+ if (text) return text;
+ }
+ return null;
+}
+
+export function threadTitle(sessionsDir: string, threadId: string, history: Array<{ type: string; payload: Json }>): string | null {
+ const name = threadName(sessionsDir, threadId);
+ if (name) return name;
+ const message = firstMessage(history);
+ if (!message) return null;
+ const chars = [...message];
+ return chars.length > TITLE_CHARS ? `${chars.slice(0, TITLE_CHARS).join("")}…` : message;
+}
diff --git a/spike/scripts/panel-dev.ts b/spike/scripts/panel-dev.ts
index d4a808e..20109db 100644
--- a/spike/scripts/panel-dev.ts
+++ b/spike/scripts/panel-dev.ts
@@ -4,7 +4,9 @@
// Input: none; `node spike/scripts/panel-dev.ts [--port 17895]`. Output: http://127.0.0.1:<port>/
// (?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).
+// 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).
+// 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.
@@ -58,6 +60,29 @@ 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"));
+// 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" })}
+`);
+
+// New tasks the user starts after opening the panel on a new chat (?newtask=): Codex files them in today's folder.
+let started = 0;
+function startTasks(count: number): void {
+ const now = new Date();
+ const pad = (n: number) => String(n).padStart(2, "0");
+ const today = join(root, "sessions", String(now.getFullYear()), pad(now.getMonth() + 1), pad(now.getDate()));
+ mkdirSync(today, { recursive: true });
+ const messages = ["把这张海报改成暖色调,标题再大一点", "另一个窗口里:整理一下设置页的截图"];
+ for (let i = 0; i < count; i++) {
+ const id = `01a0d301-0000-7000-8000-${String(++started).padStart(8, "0")}beef`;
+ const at = new Date(Date.now() - (count - i) * 1000).toISOString();
+ const first = (type: string, payload: object) => `${JSON.stringify({ timestamp: at, type, payload })}
+`;
+ writeFileSync(join(today, `rollout-${at.slice(0, 19).replace(/:/g, "-")}-${id}.jsonl`),
+ first("session_meta", { id, timestamp: at, source: "vscode", thread_source: "user" }) + turn("n1") +
+ line("event_msg", { type: "user_message", message: messages[i] }) + upload(`msg_n${started}`, "n1", [[i ? "settings.png" : "poster.png", i ? screenshot : sunset]]));
+ }
+}
+
const { callTool, resetSetupBaseline } = await import("../../plugin/src/plugin-server.ts");
const { imageSizesOf } = await import("../../plugin/src/proxy.ts");
const { recordRequest } = await import("../../plugin/src/request-stats.ts");
@@ -111,7 +136,9 @@ const HOST = `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><tit
const frame = document.getElementById("app");
const send = (message) => frame.contentWindow.postMessage({ jsonrpc: "2.0", ...message }, "*");
// ?thread=fresh: a thread that has no rollout, like a panel opened on a new chat whose prepared thread was replaced.
- const call = (name, args) => fetch("/call" + (params.get("thread") === "fresh" ? "?fresh=1" : ""), { method: "POST", body: JSON.stringify({ name, arguments: args }) }).then((r) => r.json());
+ // 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());
window.addEventListener("message", async (event) => {
const m = event.data;
if (!m || event.source !== frame.contentWindow) return;
@@ -127,6 +154,8 @@ const HOST = `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><tit
if (params.get("demo") === "preview") d.querySelector('[data-id="IMG-004"] .thumb')?.click();
if (params.get("demo") === "disabled") d.querySelector("#plugin .off")?.click();
}, 700);
+ // The user sends the first message on this new chat (or two tasks start at once).
+ if (params.get("newtask")) setTimeout(() => fetch("/newtask?count=" + params.get("newtask"), { method: "POST" }), 1500);
}
document.getElementById("theme").onclick = () => { theme = theme === "dark" ? "light" : "dark"; document.body.classList.toggle("dark", theme === "dark"); send({ method: "ui/notifications/host-context-changed", params: { theme } }); };
document.getElementById("grow").onclick = () => fetch("/grow", { method: "POST" });
@@ -152,6 +181,10 @@ createServer((request, response) => {
resetSetupBaseline();
return reply(200, "application/json", "{}");
}
+ if (request.method === "POST" && request.url?.startsWith("/newtask")) {
+ startTasks(Number(new URL(request.url, "http://x").searchParams.get("count")) || 1);
+ return reply(200, "application/json", "{}");
+ }
if (request.method === "POST" && request.url === "/grow") {
// A new turn with one more upload, to watch the panel pick it up by polling.
extra++;
@@ -160,12 +193,13 @@ createServer((request, response) => {
return reply(200, "application/json", "{}");
}
if (request.method === "POST" && request.url?.startsWith("/call")) {
- const fresh = request.url.includes("fresh=1");
+ const fresh = new URL(request.url, "http://x").searchParams.get("fresh");
let body = "";
request.on("data", (chunk) => { body += chunk; });
request.on("end", () => {
const { name, arguments: args } = JSON.parse(body);
- const threadMeta = fresh ? { threadId: `${THREAD.slice(0, -4)}f00d`, thread_id: `${THREAD.slice(0, -4)}f00d` } : meta;
+ const freshId = `${THREAD.slice(0, -4)}${fresh}`;
+ const threadMeta = fresh && /^[0-9a-f]{4}$/.test(fresh) ? { threadId: freshId, thread_id: freshId } : 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/binding.test.ts b/spike/src/binding.test.ts
new file mode 100644
index 0000000..101d628
--- /dev/null
+++ b/spike/src/binding.test.ts
@@ -0,0 +1,71 @@
+// Purpose: v0.1-10 — a panel opened on a new chat: which threads count as "the user just started one" (not sub-agents,
+// internal tasks, forks, exec or automation threads; only those started while the panel page was on screen), and the
+// binding that makes the panel's later calls about the new thread.
+// Input: synthetic rollouts in today's folder of temporary sessions directories; output: Node test assertions only.
+
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { bindThread, boundThread, isUserThread, newThreads, resolveThread, type Shown } from "../../plugin/src/binding.ts";
+import { startThread } from "./testfixtures.ts";
+
+const PANEL = "01a0d301-0000-7000-8000-00000000f00d";
+const USER = "01a0d301-0000-7000-8000-0000000000c1";
+const SUB = "01a0d301-0000-7000-8000-0000000000c2";
+const FORK = "01a0d301-0000-7000-8000-0000000000c3";
+const ELSEWHERE = "01a0d301-0000-7000-8000-0000000000c4";
+const AUTO = "01a0d301-0000-7000-8000-0000000000c5";
+
+function dirs() {
+ const root = mkdtempSync(join(tmpdir(), "cam-binding-"));
+ mkdirSync(join(root, "sessions"));
+ return { sessionsDir: join(root, "sessions"), bindings: join(root, "data", "bindings") };
+}
+
+test("only threads the user started in a chat count", () => {
+ assert.equal(isUserThread({ source: "vscode", thread_source: "user" }), true);
+ assert.equal(isUserThread({ source: "cli" }), true, "older rollouts have no thread_source");
+ assert.equal(isUserThread({ source: { custom: "desktop" } }), true);
+ assert.equal(isUserThread({ source: { subagent: { thread_spawn: { parent_thread_id: USER, depth: 1 } } }, thread_source: "subagent", parent_thread_id: USER }), false);
+ assert.equal(isUserThread({ source: { subagent: "review" } }), false);
+ assert.equal(isUserThread({ source: { internal: "memory_consolidation" } }), false);
+ assert.equal(isUserThread({ source: "vscode", thread_source: "user", forked_from_id: USER }), false, "a fork");
+ assert.equal(isUserThread({ source: "exec" }), false);
+ assert.equal(isUserThread({ source: "mcp" }), false);
+ assert.equal(isUserThread({ source: "vscode", thread_source: "pull_request_fix_automation" }), false, "a feature's thread");
+ assert.equal(isUserThread(null), false);
+});
+
+test("only user threads started while the panel was on screen are offered, however late the panel asks", () => {
+ const { sessionsDir } = dirs();
+ const now = Date.now();
+ startThread(sessionsDir, USER, {}, 40_000);
+ startThread(sessionsDir, SUB, { source: { subagent: { thread_spawn: { parent_thread_id: USER, depth: 1 } } }, thread_source: "subagent", parent_thread_id: USER, forked_from_id: USER }, 38_000);
+ startThread(sessionsDir, FORK, { forked_from_id: USER }, 39_000);
+ startThread(sessionsDir, AUTO, { thread_source: "heartbeat_automation" }, 39_000);
+ startThread(sessionsDir, ELSEWHERE, {}, 20_000);
+ // On screen until 42 s ago (the user sent 2 s after the page last noted itself, then left), and again for 5 s.
+ const shown: Shown = [[now - 60_000, now - 42_000], [now - 5_000, now]];
+ assert.deepEqual(newThreads(sessionsDir, shown).map((entry) => entry.threadId), [USER], "the one started while the page was hidden is not this page's");
+ assert.deepEqual(newThreads(sessionsDir, [[now - 60_000, now - 50_000]]), [], "hidden for 10 s by then");
+ assert.deepEqual(newThreads(sessionsDir, []), []);
+ assert.deepEqual(newThreads(sessionsDir, "not a list"), []);
+ const [only] = newThreads(sessionsDir, shown);
+ assert.ok(Math.abs(only.startedAt - (now - 40_000)) < 1_000, "started when its first line was written");
+});
+
+test("a panel's calls follow its binding until its own thread has a rollout", () => {
+ const { sessionsDir, bindings } = dirs();
+ startThread(sessionsDir, USER);
+ assert.equal(resolveThread(PANEL, sessionsDir, bindings), PANEL, "not bound yet");
+ assert.equal(boundThread(PANEL, bindings), null);
+ bindThread(PANEL, USER, bindings);
+ assert.equal(resolveThread(PANEL, sessionsDir, bindings), USER);
+ assert.equal(resolveThread(USER, sessionsDir, bindings), USER, "a thread with a rollout is itself");
+ assert.equal(resolveThread("chatgpt:abc", sessionsDir, bindings), "chatgpt:abc");
+ startThread(sessionsDir, PANEL);
+ assert.equal(resolveThread(PANEL, sessionsDir, bindings), PANEL, "its own rollout wins");
+ assert.throws(() => bindThread(PANEL, "../x", bindings), /不是任务编号/);
+});
diff --git a/spike/src/panel-state.test.ts b/spike/src/panel-state.test.ts
index 3c48077..e58b8b3 100644
--- a/spike/src/panel-state.test.ts
+++ b/spike/src/panel-state.test.ts
@@ -1,8 +1,10 @@
// 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.
+// P4 — previews and other formats, and threads without a rollout yet. v0.1-9 — the task's name as the title.
// Input: synthetic rollouts in temporary folders; output: Node test assertions only.
import assert from "node:assert/strict";
+import { writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
import test from "node:test";
import { decodePng } from "../../plugin/src/png.ts";
import { applySelection, imageFor, loadPanelState, requestedIds, sendInfo } from "../../plugin/src/panel-state.ts";
@@ -103,3 +105,12 @@ test("a thread without a rollout yet shows an empty panel instead of an error, a
assert.deepEqual([state.images, state.turns, state.totals.images, state.started], [[], 0, 0, false]);
assert.equal(loadPanelState(THREAD, options).started, true);
});
+
+test("the title is the task's name, else the start of its first message; a thread that has not started has none", () => {
+ const options = sampleSessions(line("event_msg", { type: "user_message", message: "第一条消息" }));
+ assert.equal(loadPanelState(THREAD, options).title, "第一条消息");
+ writeFileSync(join(dirname(options.sessionsDir), "session_index.jsonl"), `${JSON.stringify({ id: THREAD, thread_name: "改图任务", updated_at: "2026-09-25T10:00:00Z" })}
+`);
+ assert.equal(loadPanelState(THREAD, options).title, "改图任务");
+ assert.equal(loadPanelState("01a0d301-0000-7000-8000-00000000ffff", options).title, null);
+});
diff --git a/spike/src/plugin-server.test.ts b/spike/src/plugin-server.test.ts
index 8b79fcc..5545b38 100644
--- a/spike/src/plugin-server.test.ts
+++ b/spike/src/plugin-server.test.ts
@@ -1,6 +1,7 @@
// Purpose: P3-3 — the plugin's MCP server: thread resolution, the rule that only the user may check or uncheck,
// thumbnails kept out of model-visible content, and a full stdio session (engine supervision switched off).
-// P4 — the panel's entrypoint and page resource.
+// P4 — the panel's entrypoint and page resource. v0.1-10 — a panel on a new chat is offered the thread the user just
+// started and follows it once bound.
// Input: synthetic rollouts in temporary folders; output: Node test assertions only.
import assert from "node:assert/strict";
@@ -9,7 +10,7 @@ import { dirname, join } from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
import { callTool, fromModel, PANEL_MIME, PANEL_URI, readResource, threadOf, TOOLS } from "../../plugin/src/plugin-server.ts";
-import { sampleSessions, THREAD } from "./testfixtures.ts";
+import { line, red, sampleSessions, startThread, THREAD, turn, upload } from "./testfixtures.ts";
const here = dirname(fileURLToPath(import.meta.url));
const modelMeta = { callId: "exec-1", "x-codex-turn-metadata": { thread_id: THREAD, turn_id: "t9" } };
@@ -88,10 +89,40 @@ test("a stdio session lists the tools and answers calls", async () => {
child.stdin.end();
assert.deepEqual(replies[1].result.capabilities, { tools: {}, resources: {} });
assert.deepEqual(replies[1].result.serverInfo.icons.map((icon: any) => [icon.theme, icon.src.slice(0, 26)]), [["light", "data:image/svg+xml;base64,"], ["dark", "data:image/svg+xml;base64,"]]);
- assert.deepEqual(replies[2].result.tools.map((tool: any) => tool.name), ["cam_panel", "cam_set_selection", "cam_image", "cam_setup"]);
+ assert.deepEqual(replies[2].result.tools.map((tool: any) => tool.name), ["cam_panel", "cam_set_selection", "cam_image", "cam_setup", "cam_bind"]);
assert.equal(replies[3].result.structuredContent.images.length, 3);
assert.equal(replies[3].result.structuredContent.engineRunning, null, "engine supervision is off in this test");
assert.equal(replies[4].result.isError, true);
assert.deepEqual(replies[5].result.resources.map((resource: any) => [resource.uri, resource.mimeType]), [[PANEL_URI, PANEL_MIME]]);
assert.equal(replies[6].result.contents[0].mimeType, PANEL_MIME);
});
+
+test("a panel on a new chat is offered the thread the user just started, and follows it once bound", () => {
+ const { sessionsDir, dataRoot } = sampleSessions();
+ process.env.CAM_DATA_DIR = dataRoot;
+ const PANEL = "01a0d301-0000-7000-8000-00000000f00d";
+ const NEW = "01a0d301-0000-7000-8000-0000000000d1";
+ const SUB = "01a0d301-0000-7000-8000-0000000000d2";
+ const meta = { thread_id: PANEL, threadId: PANEL };
+ try {
+ const shown = [[Date.now() - 5_000, Date.now()]];
+ assert.deepEqual(callTool("cam_panel", { shown }, meta, sessionsDir).structuredContent.newTasks, []);
+ startThread(sessionsDir, NEW, {}, 1_000, line("event_msg", { type: "user_message", message: "看看这张图" }) + turn("t1") + upload("msg_n", "t1", [["n.png", red]]));
+ startThread(sessionsDir, SUB, { source: { subagent: { thread_spawn: { parent_thread_id: NEW, depth: 1 } } }, thread_source: "subagent", parent_thread_id: NEW }, 500);
+ const waiting = callTool("cam_panel", { shown }, meta, sessionsDir).structuredContent;
+ assert.equal(waiting.started, false);
+ assert.deepEqual(waiting.newTasks.map((task: any) => [task.threadId, task.title]), [[NEW, "看看这张图"]], "the sub-agent is not offered");
+ assert.equal(callTool("cam_panel", {}, meta, sessionsDir).structuredContent.newTasks, undefined, "Codex's own call gets no list");
+ assert.throws(() => callTool("cam_bind", { target: NEW }, { ...meta, "x-codex-turn-metadata": { thread_id: PANEL } }, sessionsDir), /只有用户能切换/);
+ assert.throws(() => callTool("cam_bind", { target: SUB }, meta, sessionsDir), /只能切到用户自己开始的任务/);
+ const bound = callTool("cam_bind", { target: NEW }, meta, sessionsDir).structuredContent;
+ assert.deepEqual([bound.threadId, bound.switchedFrom, bound.images.length, bound.title], [NEW, PANEL, 1, "看看这张图"]);
+ const later = callTool("cam_panel", { shown }, meta, sessionsDir).structuredContent;
+ assert.deepEqual([later.threadId, later.switchedFrom, later.newTasks], [NEW, PANEL, undefined]);
+ callTool("cam_set_selection", { uncheck: ["IMG-001"] }, meta, sessionsDir);
+ assert.equal(callTool("cam_panel", {}, { thread_id: NEW, threadId: NEW }, sessionsDir).structuredContent.totals.unchecked, 1, "the change is the new thread's");
+ assert.throws(() => callTool("cam_bind", { target: NEW }, panelMeta, sessionsDir), /已经开始/, "a panel on a started thread stays");
+ } finally {
+ delete process.env.CAM_DATA_DIR;
+ }
+});
diff --git a/spike/src/selection.test.ts b/spike/src/selection.test.ts
index fab2249..772582c 100644
--- a/spike/src/selection.test.ts
+++ b/spike/src/selection.test.ts
@@ -9,6 +9,7 @@ import { join } from "node:path";
import test from "node:test";
import { hasUnchecked } from "../../plugin/src/proxy.ts";
import { effectiveSelection, readSelection, writeSelection } from "../../plugin/src/selection.ts";
+import { startThread } from "./testfixtures.ts";
const PARENT = "01a0d301-0000-7000-8000-0000000000f0";
const FORK = "01a0d301-0000-7000-8000-0000000000f1";
@@ -59,8 +60,9 @@ test("a fork of a fork asks its own parent; ordinary threads stay empty and get
});
test("a thread whose rollout is not written yet is looked up again later", () => {
- const { sessionsDir, dir, rollout } = setup();
+ const { sessionsDir, dir } = setup();
assert.deepEqual(effectiveSelection(LATE, sessionsDir, dir).unchecked, {});
- rollout(LATE, { forked_from_id: PARENT, timestamp: "2026-09-24T12:00:00Z" });
+ // Codex files a new rollout in today's folder.
+ startThread(sessionsDir, LATE, { forked_from_id: PARENT, timestamp: "2026-09-24T12:00:00Z" });
assert.deepEqual(Object.values(effectiveSelection(LATE, sessionsDir, dir).unchecked).map((entry) => entry.id), ["IMG-001"]);
});
diff --git a/spike/src/testfixtures.ts b/spike/src/testfixtures.ts
index fe2c5ca..b1c3f86 100644
--- a/spike/src/testfixtures.ts
+++ b/spike/src/testfixtures.ts
@@ -36,3 +36,20 @@ export function sampleSessions(extra = ""): { sessionsDir: string; dataRoot: str
turn("t2") + assistant("需要 IMG-001。IMG-003 与 IMG-002 相同。", "t2") + extra);
return { sessionsDir: join(root, "sessions"), dataRoot: join(root, "data") };
}
+
+// The folder Codex files a rollout started now in (sessions/YYYY/MM/DD, local time): where new threads appear.
+export function todayFolder(sessionsDir: string): string {
+ const now = new Date();
+ const pad = (n: number) => String(n).padStart(2, "0");
+ const folder = join(sessionsDir, String(now.getFullYear()), pad(now.getMonth() + 1), pad(now.getDate()));
+ mkdirSync(folder, { recursive: true });
+ return folder;
+}
+
+// A thread whose first message was sent `agoMs` ago: Codex writes the rollout's first line at that moment.
+export function startThread(sessionsDir: string, id: string, meta: Record<string, any> = {}, agoMs = 0, body = ""): string {
+ const at = new Date(Date.now() - agoMs).toISOString();
+ const file = join(todayFolder(sessionsDir), `rollout-${at.slice(0, 19).replace(/:/g, "-")}-${id}.jsonl`);
+ writeFileSync(file, `${JSON.stringify({ timestamp: at, type: "session_meta", payload: { id, timestamp: at, source: "vscode", thread_source: "user", ...meta } })}\n${body}`);
+ return file;
+}
diff --git a/spike/src/thread-index.test.ts b/spike/src/thread-index.test.ts
index 1698521..90356a0 100644
--- a/spike/src/thread-index.test.ts
+++ b/spike/src/thread-index.test.ts
@@ -1,13 +1,18 @@
// Purpose: P2 — the thread index read from rollouts: stable ids in history order, turn numbers, incremental
// 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.
// Input: synthetic rollouts in a temporary directory; output: Node test assertions only.
import assert from "node:assert/strict";
-import { appendFileSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { createHash } from "node:crypto";
+import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
-import { loadThreadIndex } from "../../plugin/src/thread-index.ts";
+import { zstdCompressSync } from "node:zlib";
+import { hasRollout, loadThreadIndex, setPixelCache, threadsStartedSince } from "../../plugin/src/thread-index.ts";
+import { startThread, todayFolder } from "./testfixtures.ts";
import { png } from "./testkit.ts";
const THREAD = "01a0d301-0000-7000-8000-000000000001";
@@ -79,3 +84,55 @@ test("an unnamed image takes the name of an identical named one", () => {
writeFileSync(join(day, `rollout-2026-09-24T10-00-00-${THREAD}.jsonl`), line("session_meta", { id: THREAD }) + turn("t1") + upload("msg_1", "t1", "a.png", red) + viewed);
assert.deepEqual(loadThreadIndex(dir, THREAD).images.map((i) => [i.id, i.kind, i.name]), [["IMG-001", "upload", "a.png"], ["IMG-002", "tool", "a.png"]]);
});
+
+test("a rollout Codex compressed after a week (.jsonl.zst) is read; once Codex restores the plain file, that one counts", () => {
+ const { dir, day } = sessions();
+ const plain = join(day, `rollout-2026-09-24T10-00-00-${THREAD}.jsonl`);
+ const content = line("session_meta", { id: THREAD }) + turn("t1") + upload("msg_1", "t1", "a.png", red);
+ writeFileSync(`${plain}.zst`, zstdCompressSync(Buffer.from(content)));
+ assert.equal(hasRollout(dir, THREAD), true);
+ assert.deepEqual(loadThreadIndex(dir, THREAD).images.map((i) => i.name), ["a.png"]);
+ // To append, Codex writes the plain file back and then removes the compressed one.
+ writeFileSync(plain, content + turn("t2") + upload("msg_2", "t2", "b.png", blue));
+ rmSync(`${plain}.zst`);
+ assert.deepEqual(loadThreadIndex(dir, THREAD).images.map((i) => i.name), ["a.png", "b.png"]);
+});
+
+test("new rollouts in today's folder are found between full walks; a moved rollout is found again when a read misses it", () => {
+ const { dir, day } = sessions();
+ const name = `rollout-2026-09-24T10-00-00-${THREAD}.jsonl`;
+ writeFileSync(join(day, name), line("session_meta", { id: THREAD }) + turn("t1") + upload("msg_1", "t1", "a.png", red));
+ assert.equal(loadThreadIndex(dir, THREAD).images.length, 1);
+ const NEW = "01a0d301-0000-7000-8000-0000000000e1";
+ assert.equal(hasRollout(dir, NEW), false);
+ startThread(dir, NEW, {}, 1_000);
+ assert.equal(hasRollout(dir, NEW), true, "without waiting for the next full walk");
+ // A later page of a thread is not a new thread.
+ writeFileSync(join(todayFolder(dir), `rollout-2026-09-25T10-00-00-${NEW}_01a0d301-0000-7000-8000-0000000000e2.jsonl`), line("session_meta", { id: NEW }));
+ assert.deepEqual(threadsStartedSince(dir, Date.now() - 60_000).map((entry) => entry.threadId), [NEW]);
+ const elsewhere = join(dir, "2026", "08", "01");
+ mkdirSync(elsewhere, { recursive: true });
+ renameSync(join(day, name), join(elsewhere, name));
+ assert.equal(loadThreadIndex(dir, THREAD).images.length, 1);
+});
+
+test("pixel fingerprints are shared through the cache folder: a stored one is used instead of decoding again", () => {
+ const cache = mkdtempSync(join(tmpdir(), "cam-pixels-"));
+ setPixelCache(cache);
+ try {
+ const { dir, day } = sessions();
+ const green = png(3, 5, () => [0, 200, 0]);
+ const olive = png(5, 3, () => [120, 120, 0]);
+ writeFileSync(join(day, `rollout-2026-09-24T10-00-00-${THREAD}.jsonl`), line("session_meta", { id: THREAD }) + turn("t1") + upload("msg_1", "t1", "g.png", green) + upload("msg_2", "t1", "o.png", olive));
+ const idOf = (bytes: Buffer) => createHash("sha256").update(bytes.toString("base64")).digest("hex");
+ const oliveId = idOf(olive);
+ mkdirSync(join(cache, oliveId.slice(0, 2)), { recursive: true });
+ writeFileSync(join(cache, oliveId.slice(0, 2), oliveId), "f".repeat(64));
+ const index = loadThreadIndex(dir, THREAD);
+ assert.equal(index.images[1].pixelSha256, "f".repeat(64), "stored by another process");
+ assert.match(index.images[0].pixelSha256 ?? "", /^[0-9a-f]{64}$/);
+ assert.equal(readFileSync(join(cache, idOf(green).slice(0, 2), idOf(green)), "utf8"), index.images[0].pixelSha256, "decoded once, stored for the others");
+ } finally {
+ setPixelCache(null);
+ }
+});
diff --git a/spike/src/thread-names.test.ts b/spike/src/thread-names.test.ts
new file mode 100644
index 0000000..232cb8d
--- /dev/null
+++ b/spike/src/thread-names.test.ts
@@ -0,0 +1,55 @@
+// Purpose: v0.1-9 — the task's name for the panel's title: Codex's session_index.jsonl read incrementally (last
+// non-empty name wins, a rewritten file is read again), and the first message as the fallback.
+// Input: synthetic index files and history records in temporary folders; output: Node test assertions only.
+
+import assert from "node:assert/strict";
+import { appendFileSync, mkdirSync, mkdtempSync, renameSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import test from "node:test";
+import { firstMessage, sessionIndexOf, threadName, threadTitle } from "../../plugin/src/thread-names.ts";
+
+const A = "01a0d301-0000-7000-8000-0000000000a1";
+const B = "01a0d301-0000-7000-8000-0000000000b2";
+const entry = (id: string, name: string) => `${JSON.stringify({ id, thread_name: name, updated_at: "2026-09-25T10:00:00Z" })}\n`;
+const message = (text: string) => ({ type: "event_msg", payload: { type: "user_message", message: text } });
+
+function home(): string {
+ const root = mkdtempSync(join(tmpdir(), "cam-names-"));
+ mkdirSync(join(root, "sessions"));
+ return join(root, "sessions");
+}
+
+test("the index sits next to the sessions folder; the last non-empty name of a thread wins, renames included", () => {
+ const sessions = home();
+ const index = sessionIndexOf(sessions);
+ assert.equal(index, join(sessions, "..", "session_index.jsonl").replace(/[\\/]sessions[\\/]\.\./, ""));
+ assert.equal(threadName(sessions, A), null, "no index yet");
+ writeFileSync(index, entry(A, "第一版") + entry(B, "别的任务"));
+ assert.equal(threadName(sessions, A), "第一版");
+ appendFileSync(index, entry(A, " 改过的名字 ") + entry(A, " ") + "{broken\n");
+ assert.equal(threadName(sessions, A), "改过的名字", "a rename appends a line; an empty name and a damaged line are skipped");
+ assert.equal(threadName(sessions, B), "别的任务");
+});
+
+test("a rewritten index (Codex removing a thread's names) is read again from the start", () => {
+ const sessions = home();
+ const index = sessionIndexOf(sessions);
+ writeFileSync(index, entry(A, "要删掉的名字") + entry(B, "留下的名字"));
+ assert.equal(threadName(sessions, A), "要删掉的名字");
+ writeFileSync(`${index}.tmp`, entry(B, "留下的名字"));
+ renameSync(`${index}.tmp`, index);
+ assert.equal(threadName(sessions, A), null);
+ assert.equal(threadName(sessions, B), "留下的名字");
+});
+
+test("without a name, the title is the start of the first message the user sent", () => {
+ const sessions = home();
+ assert.equal(firstMessage([{ type: "session_meta", payload: {} }, message(" 帮我看看\n这张图 "), message("第二条")]), "帮我看看 这张图");
+ assert.equal(firstMessage([{ type: "event_msg", payload: { type: "user_message", message: " " } }]), null);
+ const long = "一".repeat(45);
+ assert.equal(threadTitle(sessions, A, [message(long)]), `${"一".repeat(40)}…`);
+ assert.equal(threadTitle(sessions, A, []), null, "a thread that has not started has no title");
+ writeFileSync(sessionIndexOf(sessions), entry(A, "有名字的任务"));
+ assert.equal(threadTitle(sessions, A, [message(long)]), "有名字的任务");
+});