Skip to content

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.

feat(engine): 子代理和旁聊也自动选图

chipfighter2bc873bcf8d0
diff --git a/plugin/src/children.ts b/plugin/src/children.ts
new file mode 100644
index 0000000..c75ecc1
--- /dev/null
+++ b/plugin/src/children.ts
@@ -0,0 +1,46 @@
+// Purpose: v0.7 — a task's subagents (started without history) and side chats, as the engine sees their requests, so
+// the task's panel can list them. A side chat leaves no rollout: its requests are the only trace of it.
+// Input: request identities (proxy.ts) and the sessions directory (read-only).
+// Output: <data dir>/state/children/<task id>.json, e.g.
+// { "<thread id>": { "kind": "side", "from": "<the thread it came from>", "at": "<its first request>" } }.
+
+import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { childrenDirOf } from "./paths.ts";
+import { mainTaskOf } from "./selection.ts";
+import { sideChatOrigin, spawnParent } from "./thread-index.ts";
+
+export type Child = { kind: "subagent" | "side"; from: string; at: string };
+const THREAD_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+// Recorded once each: later requests do not touch the file.
+const known = new Set<string>();
+
+export function readChildren(taskId: string, dir = childrenDirOf()): Record<string, Child> {
+ if (!THREAD_ID.test(taskId)) return {};
+ try { return JSON.parse(readFileSync(join(dir, `${taskId}.json`), "utf8")); } catch { return {}; }
+}
+
+// Whether the child was new. Written to a temporary file first, so the panel never reads a half-written list.
+export function recordChild(taskId: string, childId: string, child: Child, dir = childrenDirOf()): boolean {
+ const key = `${dir}\0${taskId}\0${childId}`;
+ if (known.has(key) || !THREAD_ID.test(taskId) || !THREAD_ID.test(childId)) return false;
+ known.add(key);
+ const children = readChildren(taskId, dir);
+ if (children[childId]) return false;
+ mkdirSync(dir, { recursive: true });
+ const file = join(dir, `${taskId}.json`);
+ writeFileSync(`${file}.tmp`, JSON.stringify({ ...children, [childId]: child }, null, 2));
+ renameSync(`${file}.tmp`, file);
+ return true;
+}
+
+// The task a request's thread belongs to as a side chat or as a subagent started without history, or null. A
+// subagent's first request can come before Codex writes its rollout; it is found at the next one.
+export function childOf(identity: { threadId: string | null; forkedFrom: string | null }, sessionsDir: string, at: string): { task: string; id: string; child: Child } | null {
+ const id = identity.threadId;
+ if (!id) return null;
+ const origin = sideChatOrigin(id, identity.forkedFrom, sessionsDir);
+ if (origin) return { task: mainTaskOf(sessionsDir, origin) ?? origin, id, child: { kind: "side", from: origin, at } };
+ const parent = spawnParent(sessionsDir, id);
+ return parent ? { task: mainTaskOf(sessionsDir, id) ?? parent, id, child: { kind: "subagent", from: parent, at } } : null;
+}
diff --git a/plugin/src/panel-state.ts b/plugin/src/panel-state.ts
index 65a1f00..9941208 100644
--- a/plugin/src/panel-state.ts
+++ b/plugin/src/panel-state.ts
@@ -6,15 +6,18 @@
// v0.2 — each image's source, which the panel filters by.
// v0.3 — automatic selection: the switch, the checkboxes meaning "pinned" while it is on (kept apart from the manual
// checks), and the images the model fetched in the latest turn.
+// v0.7 — a Codex task's subagents and side chats (children.ts), each with its last request and whether automatic
+// selection manages it, and the task's switch for them.
// 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/.
+import { readChildren } from "./children.ts";
import { claudeHome, claudeImageData, claudeStartedAt, loadClaudeIndex, type ClaudeIndex } from "./claude-index.ts";
import type { ImageSource } from "./images.ts";
-import { claudeRequestStatsDirOf, claudeSelectionDirOf, dataDir, requestStatsDirOf, selectionDirOf } from "./paths.ts";
+import { childrenDirOf, claudeRequestStatsDirOf, claudeSelectionDirOf, dataDir, requestStatsDirOf, selectionDirOf } from "./paths.ts";
import { readRequestStats, type RequestStats } from "./request-stats.ts";
-import { claudeSelection, effectiveSelection, writeSelection, type Mark, type Selection } from "./selection.ts";
-import { buildIndex, imageData, readThreadHistory, type IndexedImage, type ThreadIndex } from "./thread-index.ts";
+import { claudeSelection, effectiveSelection, sideChatSelection, writeSelection, type Mark, type Selection } from "./selection.ts";
+import { buildIndex, imageData, readThreadHistory, sessionMetaOf, type IndexedImage, type ThreadIndex } from "./thread-index.ts";
import { threadTitle } from "./thread-names.ts";
import { pngThumbnail } from "./thumbnail.ts";
@@ -50,12 +53,17 @@ export type SendInfo = {
// 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).
// auto: automatic selection is on (v0.3); fetched: the ids the model fetched in the latest turn.
+// childrenAuto: the task's switch for its subagents and side chats; children: those the engine has seen (v0.7).
export type PanelState = {
threadId: string; title: string | null; started: boolean; historyMissing: boolean; turns: number; images: PanelImage[]; requested: string[];
auto: boolean; fetched: string[];
totals: { images: number; unchecked: number; checkedBytes: number; allBytes: number };
send: SendInfo;
+ childrenAuto: boolean; children: ChildInfo[];
};
+// v0.7: a subagent (name: its nickname in Codex) or side chat, when it first sent a request, whether automatic selection
+// manages it now, and its last full request (images: how many it carried, as Codex built it).
+export type ChildInfo = { threadId: string; kind: "subagent" | "side"; name: string | null; startedAt: string; auto: boolean; images: number | null; last: SendInfo["last"] };
// The engine's reasons for forwarding a request unchanged, as codes the panel says in its language (v0.1-14).
export type SkipReason = "undecodable" | "unparsable" | "format" | "integer" | "index" | "other";
@@ -179,9 +187,26 @@ export function panelStateOf(threadId: string, index: ThreadIndex, unchecked: Se
allBytes: images.reduce((sum, image) => sum + image.bytes, 0),
},
send: sendInfo(stats),
+ childrenAuto: true, children: [],
};
}
+// v0.7: oldest first, as the engine first saw each one.
+function childrenOf(taskId: string, selection: Selection, options: PanelOptions): Pick<PanelState, "childrenAuto" | "children"> {
+ const root = options.dataRoot ?? dataDir();
+ const dir = selectionDirOf(root);
+ const children = Object.entries(readChildren(taskId, childrenDirOf(root)))
+ .sort(([, a], [, b]) => a.at.localeCompare(b.at))
+ .map(([threadId, child]): ChildInfo => {
+ const stats = readRequestStats(threadId, requestStatsDirOf(root));
+ const spawn = child.kind === "subagent" ? sessionMetaOf(options.sessionsDir, threadId)?.source?.subagent?.thread_spawn : null;
+ const auto = child.kind === "side" ? sideChatSelection(child.from, options.sessionsDir, dir) !== null : !!effectiveSelection(threadId, options.sessionsDir, dir).auto;
+ const images = stats?.lastHttp?.images;
+ return { threadId, kind: child.kind, name: spawn?.agent_nickname ?? spawn?.agent_path?.split("/").pop() ?? null, startedAt: child.at, auto, images: typeof images === "number" ? images : null, last: sendInfo(stats).last };
+ });
+ return { childrenAuto: selection.childrenAuto !== false, children };
+}
+
// 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[] } {
@@ -214,23 +239,24 @@ function offKeys(index: ThreadIndex, selection: Selection): Set<string> {
export function loadPanelState(threadId: string, options: PanelOptions): PanelState {
const { history, index, selection, stats, title, historyMissing } = load(threadId, options);
- return { ...panelState(threadId, history, index, offKeys(index, selection), stats, title, !!selection.auto), historyMissing };
+ return { ...panelState(threadId, history, index, offKeys(index, selection), stats, title, !!selection.auto), historyMissing, ...childrenOf(threadId, selection, options) };
}
// v0.3: `auto` switches automatic selection; with `mode: "auto"` a tick pins an image instead of sending it, each kept
-// in its own record, so switching back finds the manual checks as they were.
-export type SelectionChange = { uncheck?: string[]; check?: string[]; checkAll?: boolean; auto?: boolean; mode?: "manual" | "auto" };
+// in its own record, so switching back finds the manual checks as they were. v0.7: `childrenAuto` switches it for the
+// task's subagents and side chats.
+export type SelectionChange = { uncheck?: string[]; check?: string[]; checkAll?: boolean; auto?: boolean; mode?: "manual" | "auto"; childrenAuto?: boolean };
export function applySelection(threadId: string, change: SelectionChange, options: PanelOptions): PanelState {
const { root, history, index, selection, stats, title, historyMissing } = load(threadId, options);
const next = changedSelection(threadId, index, selection, change);
writeSelection(next, selectionDirOf(root));
- return { ...panelState(threadId, history, index, offKeys(index, next), stats, title, !!next.auto), historyMissing };
+ return { ...panelState(threadId, history, index, offKeys(index, next), stats, title, !!next.auto), historyMissing, ...childrenOf(threadId, next, options) };
}
// The selection after a change; nothing is written.
export function changedSelection(threadId: string, index: ThreadIndex, selection: Selection, change: SelectionChange): Selection {
const now = new Date().toISOString();
- let next: Selection = { ...selection, threadId };
+ let next: Selection = { ...selection, threadId, ...(typeof change.childrenAuto === "boolean" ? { childrenAuto: change.childrenAuto } : {}) };
// Switched on for the first time, the thread is marked: from then on its history may hold copies the model fetched.
if (typeof change.auto === "boolean" && change.auto !== !!selection.auto) next = { ...next, auto: change.auto, autoAt: now, autoSince: selection.autoSince ?? now };
const pins = change.mode === "auto";
diff --git a/plugin/src/paths.ts b/plugin/src/paths.ts
index a86cb90..9bfa6d5 100644
--- a/plugin/src/paths.ts
+++ b/plugin/src/paths.ts
@@ -29,6 +29,8 @@ export const claudeRequestStatsDirOf = (root = dataDir()) => join(root, "claude"
// What the engine sent for each history it changed, so the thinking that still fits can stay (claude-thinking.ts).
export const claudeThinkingDirOf = (root = dataDir()) => join(root, "claude", "thinking");
export const requestStatsDirOf = (root = dataDir()) => join(root, "state", "requests");
+// v0.7: each task's subagents and side chats, as the engine saw their requests (children.ts).
+export const childrenDirOf = (root = dataDir()) => join(root, "state", "children");
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 19b842b..8f1b934 100644
--- a/plugin/src/plugin-server.ts
+++ b/plugin/src/plugin-server.ts
@@ -18,6 +18,8 @@
// engine running, and serves the Claude plugin's mod (its panel and its routing, hooks/register.js) and the model's
// cam_view_image for a Claude Code session, read from that session's transcript (claude-index.ts). The session is the
// one the call names (the mod passes it), else the one Claude Code started this service for (CLAUDE_CODE_SESSION_ID).
+// v0.7 — in a side chat (kept in memory only, so without a rollout) cam_view_image fetches from the task the chat was
+// forked from, which its calls name; the panel switches automatic selection for a task's subagents and side chats.
// Input: MCP JSON-RPC over stdio. Env: CAM_ENGINE_PORT (default 17891), CAM_NO_ENGINE=1 (tests), CAM_DATA_DIR,
// CAM_HOST. Output: tool results; <data dir>/plugin-server.jsonl (events and counts only, no conversation content).
@@ -36,9 +38,9 @@ import { migrateDataOnce } from "./migrate-data.ts";
import { applySelection, claudeImageFor, imageFor, loadPanelState, type ClaudePanelOptions, type PanelState } from "./panel-state.ts";
import { claudeSelectionDirOf, dataDir, pixelCacheDirOf, selectionDirOf } from "./paths.ts";
import { fetchedLabel, fetchWords } from "./rewrite.ts";
-import { claudeSelection, effectiveSelection, ensureAutoDefault } from "./selection.ts";
+import { claudeSelection, effectiveSelection, ensureAutoDefault, sideChatSelection } from "./selection.ts";
import { connectDirectly, useEngine, usesEngine } from "./setup.ts";
-import { hasRollout, loadThreadIndex, readThreadHistory, sessionMetaOf, setPixelCache } from "./thread-index.ts";
+import { hasRollout, loadThreadIndex, readThreadHistory, sessionMetaOf, setPixelCache, sideChatOrigin } from "./thread-index.ts";
import { threadTitle } from "./thread-names.ts";
type Json = Record<string, any>;
@@ -66,7 +68,7 @@ export function toolsFor(lang: Lang) {
name: "cam_set_selection",
title: say(lang, "tool.select.title"),
description: say(lang, "tool.select.description"),
- inputSchema: { type: "object", properties: { ...shared, uncheck: { type: "array", items: { type: "string" } }, check: { type: "array", items: { type: "string" } }, checkAll: { type: "boolean" }, auto: { type: "boolean" }, mode: { type: "string", enum: ["manual", "auto"] } } },
+ inputSchema: { type: "object", properties: { ...shared, uncheck: { type: "array", items: { type: "string" } }, check: { type: "array", items: { type: "string" } }, checkAll: { type: "boolean" }, auto: { type: "boolean" }, mode: { type: "string", enum: ["manual", "auto"] }, childrenAuto: { type: "boolean" } } },
_meta: APP_ONLY,
},
{
@@ -187,7 +189,7 @@ export function callTool(name: string, args: Json, meta: Json | undefined, sessi
}
if (name === "cam_set_selection") {
if (fromModel(meta)) throw new Error(say(lang, "call.modelSelect"));
- const state = applySelection(threadId, { uncheck: args.uncheck, check: args.check, checkAll: args.checkAll, auto: typeof args.auto === "boolean" ? args.auto : undefined, mode: args.mode === "auto" ? "auto" : "manual" }, options);
+ const state = applySelection(threadId, { uncheck: args.uncheck, check: args.check, checkAll: args.checkAll, auto: typeof args.auto === "boolean" ? args.auto : undefined, mode: args.mode === "auto" ? "auto" : "manual", childrenAuto: typeof args.childrenAuto === "boolean" ? args.childrenAuto : undefined }, options);
return { content: [{ type: "text", text: summary(lang, state) }], structuredContent: panel(state) };
}
if (name === "cam_bind") {
@@ -211,25 +213,29 @@ export function callTool(name: string, args: Json, meta: Json | undefined, sessi
if (name === "cam_view_image") {
const words = fetchWords(lang);
const ids: string[] = Array.isArray(args.ids) ? args.ids.map(String) : typeof args.id === "string" ? [args.id] : [];
+ // v0.7: a side chat's images are those of the task it came from.
+ const origin = sideChatOrigin(threadId, meta?.["x-codex-turn-metadata"]?.forked_from_thread_id, sessionsDir);
+ const dir = selectionDirOf(dataDir());
// Only where the user switched automatic selection on; otherwise images come back only when the user checks them.
- if (!effectiveSelection(threadId, sessionsDir, selectionDirOf(dataDir())).auto) {
- log({ event: "fetch", threadId, ids, refused: "automatic selection is off" });
+ if (origin ? !sideChatSelection(origin, sessionsDir, dir) : !effectiveSelection(threadId, sessionsDir, dir).auto) {
+ log({ event: "fetch", threadId, ...(origin ? { from: origin } : {}), ids, refused: "automatic selection is off" });
return { content: [{ type: "text", text: words.off }], isError: true };
}
- const index = loadThreadIndex(sessionsDir, threadId);
+ const source = origin ?? threadId;
+ const index = loadThreadIndex(sessionsDir, source);
const content: Json[] = [];
const found: string[] = [];
for (const asked of ids) {
const id = asked.trim().toUpperCase();
const image = index.images.find((candidate) => candidate.id === id);
if (!image) { content.push({ type: "text", text: words.missing(asked) }); continue; }
- const { dataUrl } = imageFor(threadId, id, Number.MAX_SAFE_INTEGER, options);
+ const { dataUrl } = imageFor(source, id, Number.MAX_SAFE_INTEGER, options);
const parts = dataUrl ? /^data:([^;,]+);base64,(.*)$/s.exec(dataUrl) : null;
if (!parts) { content.push({ type: "text", text: words.unavailable(id) }); continue; }
content.push({ type: "text", text: fetchedLabel(image, lang) }, { type: "image", data: parts[2], mimeType: parts[1] });
found.push(id);
}
- log({ event: "fetch", threadId, ids, found });
+ log({ event: "fetch", threadId, ...(origin ? { from: origin } : {}), ids, found });
return { content, isError: ids.length > 0 && !found.length };
}
if (name === "cam_image") {
diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.ts
index 815e83b..86675d2 100644
--- a/plugin/src/proxy.ts
+++ b/plugin/src/proxy.ts
@@ -25,6 +25,7 @@ import type { Duplex } from "node:stream";
import tls from "node:tls";
import { fileURLToPath } from "node:url";
import zlib from "node:zlib";
+import { childOf, recordChild } from "./children.ts";
import { claudeHome, claudeImageData, claudeStartedAt, loadClaudeIndex, type ClaudeIndex } from "./claude-index.ts";
import { addCompacted, findRequestImages, rewriteMessages, summaryAt, type RequestImage, type Resend } from "./claude-rewrite.ts";
import { chainOf, fitThinking, readThinkingRecord, recordSent, writeThinkingRecord, type ThinkingRecord } from "./claude-thinking.ts";
@@ -39,8 +40,8 @@ import { claudeRequestStatsDirOf, claudeSelectionDirOf, dataDir, pixelCacheDirOf
import { recordRequest } from "./request-stats.ts";
import { rewriteItems, type Described } from "./rewrite.ts";
import { connectDirectly, pluginGone, usesEngine } from "./setup.ts";
-import { claudeSelection, effectiveSelection, ensureAutoDefault, selectionDir } from "./selection.ts";
-import { loadThreadIndex, pixelHashOf, pixelHashOfData, setPixelCache, type ThreadIndex } from "./thread-index.ts";
+import { claudeSelection, effectiveSelection, ensureAutoDefault, selectionDir, sideChatSelection } from "./selection.ts";
+import { loadThreadIndex, pixelHashOf, pixelHashOfData, setPixelCache, sideChatOrigin, type ThreadIndex } from "./thread-index.ts";
type Json = Record<string, any>;
const here = dirname(fileURLToPath(import.meta.url));
@@ -124,10 +125,17 @@ export function forwardHeaders(headers: IncomingHttpHeaders, upstream = UPSTREAM
}
// Which task a request belongs to, from Codex's own turn metadata header.
-export function requestIdentity(headers: IncomingHttpHeaders): { threadId: string | null; turnId: string | null; windowId: string | null } {
+// v0.7: and where that task came from: a side chat (a fork Codex keeps in memory only) names the task it was forked
+// from, a subagent its parent (also in Codex's own header).
+export type RequestIdentity = { threadId: string | null; turnId: string | null; windowId: string | null; forkedFrom: string | null; parentThreadId: string | null; subagentKind: string | null };
+export function requestIdentity(headers: IncomingHttpHeaders): RequestIdentity {
let meta: Json = {};
try { meta = JSON.parse(String(headers["x-codex-turn-metadata"] ?? "{}")); } catch { /* not JSON */ }
- return { threadId: meta.thread_id ?? meta.session_id ?? null, turnId: meta.turn_id ?? null, windowId: (headers["x-codex-window-id"] as string) ?? null };
+ const header = (name: string) => { const value = headers[name]; return (Array.isArray(value) ? value[0] : value) || null; };
+ return {
+ threadId: meta.thread_id ?? meta.session_id ?? null, turnId: meta.turn_id ?? null, windowId: header("x-codex-window-id"),
+ forkedFrom: meta.forked_from_thread_id ?? null, parentThreadId: meta.parent_thread_id ?? header("x-codex-parent-thread-id"), subagentKind: meta.subagent_kind ?? null,
+ };
}
// v0.4: which Claude Code session a request belongs to, and whether a subagent's loop sent it (its own conversation).
@@ -241,9 +249,12 @@ export function hasUnchecked(threadId: string | null, dir = selectionDir, sessio
// Whether a thread's requests go through the rewrite (and so over HTTP): something unchecked, or automatic selection
// used at some point (v0.3), since from then on the history may hold copies the model fetched, left out of later turns.
-export function needsRewrite(threadId: string | null, dir = selectionDir, sessionsDir = join(codexHome(), "sessions")): boolean {
+// v0.7: a side chat's, unless its task's switch for subagents and side chats is off.
+export function needsRewrite(threadId: string | null, dir = selectionDir, sessionsDir = join(codexHome(), "sessions"), forkedFrom: string | null = null): boolean {
if (!threadId) return false;
try {
+ const origin = sideChatOrigin(threadId, forkedFrom, sessionsDir);
+ if (origin) return sideChatSelection(origin, sessionsDir, dir) !== null;
const selection = effectiveSelection(threadId, sessionsDir, dir);
return Object.keys(selection.unchecked).length > 0 || !!selection.autoSince;
} catch { return false; }
@@ -260,7 +271,12 @@ export function currentTurnOf(index: ThreadIndex, turnId: string | null): number
// forwarded unchanged and the reason is logged; the report never contains conversation content.
// v0.3: with automatic selection on, the images of earlier turns that are not pinned instead; in either mode, copies
// the model fetched in an earlier turn.
-export function rewriteBody(original: Buffer, encoding: string | undefined, threadId: string, sessionsDir: string, dir = selectionDir, turnId: string | null = null): { body: Buffer; report: Json } {
+// v0.7: a side chat's request carries the history of the task it came from: that task's index, with every one of its
+// turns counting as earlier (sideChatSelection).
+export function rewriteBody(original: Buffer, encoding: string | undefined, threadId: string, sessionsDir: string, dir = selectionDir, turnId: string | null = null, forkedFrom: string | null = null): { body: Buffer; report: Json } {
+ const origin = sideChatOrigin(threadId, forkedFrom, sessionsDir);
+ const side = origin ? sideChatSelection(origin, sessionsDir, dir) : null;
+ if (origin && !side) return { body: original, report: { sideChatOf: origin, off: true } };
const decoded = decodeBody(original, encoding);
if (!decoded) return { body: original, report: { skipped: "undecodable body" } };
const text = decoded.toString("utf8");
@@ -269,8 +285,8 @@ export function rewriteBody(original: Buffer, encoding: string | undefined, thre
if (!Array.isArray(json.input)) return { body: original, report: { skipped: "no input array" } };
if (hasUnsafeInteger(text)) return { body: original, report: { skipped: "integer beyond 2^53 would change when re-serialized" } };
let index: ThreadIndex;
- try { index = loadThreadIndex(sessionsDir, threadId); } catch (error) { return { body: original, report: { skipped: `thread index: ${String(error)}` } }; }
- const selection = effectiveSelection(threadId, sessionsDir, dir);
+ try { index = loadThreadIndex(sessionsDir, origin ?? threadId); } catch (error) { return { body: original, report: { skipped: `thread index: ${String(error)}` } }; }
+ const selection = side ?? effectiveSelection(threadId, sessionsDir, dir);
const describe = (ref: ImageRef): Described | undefined => {
const known = index.byKey.get(ref.key);
if (known) return known;
@@ -278,7 +294,7 @@ export function rewriteBody(original: Buffer, encoding: string | undefined, thre
return stored ? { id: stored.id, name: ref.name, label: ref.label, kind: ref.kind, turn: null, width: ref.width, height: ref.height } : undefined;
};
const pixels = (ref: ImageRef) => index.byKey.get(ref.key)?.pixelSha256 ?? pixelHashOf(json.input, ref);
- const current = currentTurnOf(index, turnId);
+ const current = side ? index.turns + 1 : currentTurnOf(index, turnId);
const copies = new Map([...index.copies.values()].filter((copy) => copy.turn === null || copy.turn < current).map((copy) => [copy.key, copy.of]));
let leaveOut = new Set(Object.keys(selection.unchecked));
if (selection.auto) {
@@ -293,6 +309,7 @@ export function rewriteBody(original: Buffer, encoding: string | undefined, thre
sentImageHashes: report.sentContentIds.map((id) => id.slice(0, 16)),
...(selection.auto ? { auto: true } : {}),
...(report.copies.length ? { copies: report.copies } : {}),
+ ...(origin ? { sideChatOf: origin } : {}),
};
if (!report.replaced.length && !report.copies.length) return { body: original, report: summary };
json.input = items;
@@ -507,6 +524,13 @@ async function main(): Promise<void> {
const build = buildOf();
const version = versionOf();
let sequence = 0;
+ // v0.7: a subagent's or side chat's request, noted under its task for the task's panel (children.ts).
+ const noteChild = (identity: RequestIdentity, at: string) => {
+ try {
+ const found = childOf(identity, sessionsDir, at);
+ if (found) recordChild(found.task, found.id, found.child);
+ } catch { /* only the panel's list misses it */ }
+ };
// v0.4: per Claude Code session, whether its account refuses thinking after a changed history and what was sent
// (claude-thinking.ts); the latest sessions stay in memory.
const thinkingRecords = new Map<string, ThinkingRecord>();
@@ -572,7 +596,8 @@ async function main(): Promise<void> {
};
setInterval(() => {
for (const [threadId, connections] of live) {
- if (!needsRewrite(threadId)) continue;
+ const forkedFrom = [...connections][0]?.identity.forkedFrom ?? null;
+ if (!needsRewrite(threadId, selectionDir, sessionsDir, forkedFrom)) continue;
for (const connection of connections) {
if (Date.now() - connection.last < 1500) {
// A turn still running here keeps the images the server already holds; noted once so the panel can say so.
@@ -636,7 +661,7 @@ async function main(): Promise<void> {
const path = (req.url ?? "/").split("?")[0];
const upstream = upstreamOf(path);
const identity = requestIdentity(req.headers);
- const rewrite = req.method === "POST" && /\/responses(\/compact)?$/.test(path) && needsRewrite(identity.threadId);
+ const rewrite = req.method === "POST" && /\/responses(\/compact)?$/.test(path) && needsRewrite(identity.threadId, selectionDir, sessionsDir, identity.forkedFrom);
// v0.4: a Claude Code request of a session's main conversation (a subagent's loop has its own); rewritten like a
// Codex thread's once something is unchecked there.
const claude = upstream === CLAUDE_HOST ? claudeIdentity(req.headers) : null;
@@ -681,7 +706,10 @@ async function main(): Promise<void> {
const entry = { at: new Date(started).toISOString(), id, transport: "http", method: req.method, path, status, requestBytes, decodedBytes: decoded?.length ?? null, contentEncoding: req.headers["content-encoding"] ?? null, responseBytes, ms: Date.now() - started, ...identity, ...claudeFields, ...details, ...extra, error: error ?? null };
log(entry);
// Image keys go to the per-thread statistics only, not to the log.
- if (/\/responses$/.test(path)) recordRequest(identity.threadId, imageSizes ? { ...entry, imageSizes } : entry);
+ if (/\/responses$/.test(path)) {
+ recordRequest(identity.threadId, imageSizes ? { ...entry, imageSizes } : entry);
+ noteChild(identity, entry.at);
+ }
if (claudeSession && claudeConversationRequest(details)) recordRequest(claudeSession, imageSizes ? { ...entry, imageSizes } : entry, claudeRequestStatsDirOf());
};
// What to send, in order: body null streams the request through unchanged. v0.4: Anthropic refusing an attempt's
@@ -764,7 +792,7 @@ async function main(): Promise<void> {
const original = Buffer.concat(chunks);
const encoding = req.headers["content-encoding"] as string | undefined;
let out: { body: Buffer; report: Json; attempts?: ClaudeAttempt[] };
- try { out = claudeRewrite ? rewriteClaudeBody(original, encoding, claudeSession!, undefined, undefined, undefined, thinking) : rewriteBody(original, encoding, identity.threadId!, sessionsDir, selectionDir, identity.turnId); }
+ try { out = claudeRewrite ? rewriteClaudeBody(original, encoding, claudeSession!, undefined, undefined, undefined, thinking) : rewriteBody(original, encoding, identity.threadId!, sessionsDir, selectionDir, identity.turnId, identity.forkedFrom); }
catch (error) { out = { body: original, report: { skipped: `rewrite failed: ${String(error)}` } }; }
const attempts: Attempt[] = out.attempts?.length ? out.attempts.map((attempt) => ({ ...attempt, edited: attempt.body !== original })) : [{ body: out.body, report: out.report, edited: out.body !== original }];
send(attempts);
@@ -781,7 +809,7 @@ async function main(): Promise<void> {
client.end("HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
return;
}
- if (/\/responses$/.test(path) && (forceHttp || needsRewrite(identity.threadId))) {
+ if (/\/responses$/.test(path) && (forceHttp || needsRewrite(identity.threadId, selectionDir, sessionsDir, identity.forkedFrom))) {
client.end("HTTP/1.1 426 Upgrade Required\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
log({ at: new Date(started).toISOString(), id, transport: "websocket", path, declined: 426, reason: forceHttp ? "--force-http" : "thread needs its requests rewritten", ...identity });
return;
@@ -800,6 +828,7 @@ async function main(): Promise<void> {
const opened = { at: new Date(started).toISOString(), id, transport: "websocket", event: "open", path, ...identity };
log(opened);
recordRequest(identity.threadId, opened);
+ noteChild(identity, opened.at);
const lines = [`${req.method} ${req.url} HTTP/1.1`];
for (let i = 0; i < req.rawHeaders.length; i += 2) {
const name = req.rawHeaders[i];
diff --git a/plugin/src/selection.ts b/plugin/src/selection.ts
index 5568f4c..ec5725b 100644
--- a/plugin/src/selection.ts
+++ b/plugin/src/selection.ts
@@ -10,16 +10,19 @@
// 2026-10-13: every new task and session, in Codex and Claude Code; the ones from before keep what they had). That
// time is written once next to the selections (auto-default.json); a thread's own switch always wins, and the default
// itself is never written down.
+// v0.7 — a task's subagents (started without history) and side chats get automatic selection unless the user turned
+// that off in the task's panel ("childrenAuto": false; user 2026-10-13), whatever the task's own switch says.
// Input/Output: <data dir>/selection/<thread id>.json, e.g. { "threadId": "…", "unchecked": { "<key>": { "id": "IMG-003", "at": "…" } } },
-// plus "auto", "autoAt", "autoSince" and "pinned" (same shape as "unchecked") once automatic selection has been used.
+// plus "auto", "autoAt", "autoSince" and "pinned" (same shape as "unchecked") once automatic selection has been used,
+// and "childrenAuto" once the switch for subagents and side chats has been changed.
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { selectionDirOf } from "./paths.ts";
-import { forkOrigin, threadStartedAt } from "./thread-index.ts";
+import { forkOrigin, spawnParent, threadStartedAt } from "./thread-index.ts";
export type Mark = { id: string; at: string };
-export type Selection = { threadId: string; unchecked: Record<string, Mark>; auto?: boolean; autoAt?: string; autoSince?: string; pinned?: Record<string, Mark>; inheritedFrom?: string };
+export type Selection = { threadId: string; unchecked: Record<string, Mark>; auto?: boolean; autoAt?: string; autoSince?: string; pinned?: Record<string, Mark>; inheritedFrom?: string; childrenAuto?: boolean };
export const selectionDir = selectionDirOf();
const THREAD_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
@@ -92,8 +95,35 @@ export function claudeSelection(sessionId: string, dir: string, startedAt: strin
// (a fork of a fork asks its own parent in turn) and keeps them as its own file from then on. v0.3: likewise the
// pinned images and the switch, when it was turned on before the fork. v0.6: then the default applies, a fork
// counting from the thread it came from.
+// v0.7: a subagent without a switch of its own follows its task's switch for subagents and side chats instead.
export function effectiveSelection(threadId: string, sessionsDir: string, dir = selectionDir, depth = 0): Selection {
- return withAutoDefault(ownSelection(threadId, sessionsDir, dir, depth), threadStartedAt(sessionsDir, threadId), autoDefaultSince(dir));
+ const own = ownSelection(threadId, sessionsDir, dir, depth);
+ const main = typeof own.auto === "boolean" || depth > 16 ? null : mainTaskOf(sessionsDir, threadId);
+ if (main) return childSelection(own, effectiveSelection(main, sessionsDir, dir, depth + 1), threadStartedAt(sessionsDir, threadId));
+ return withAutoDefault(own, threadStartedAt(sessionsDir, threadId), autoDefaultSince(dir));
+}
+
+// v0.7: the task a subagent started without history belongs to: its parent, followed up while that is such a subagent
+// too. null for any other thread.
+export function mainTaskOf(sessionsDir: string, threadId: string, depth = 0): string | null {
+ const parent = spawnParent(sessionsDir, threadId);
+ if (!parent) return null;
+ return (depth < 16 ? mainTaskOf(sessionsDir, parent, depth + 1) : null) ?? parent;
+}
+
+// v0.7: on, automatic selection from the subagent's start; off, none, so its requests go out as they are.
+export function childSelection(own: Selection, main: Selection, startedAt: string | null): Selection {
+ if (main.childrenAuto === false) return { ...own, auto: false };
+ return { ...own, auto: true, autoSince: own.autoSince ?? startedAt ?? new Date().toISOString() };
+}
+
+// v0.7: what a side chat forked from `origin` is sent with: the images of that task, every one of its turns counting as
+// earlier, so all of them are left out but the ones pinned there. null when its task's switch is off.
+export function sideChatSelection(origin: string, sessionsDir: string, dir = selectionDir): Selection | null {
+ const main = mainTaskOf(sessionsDir, origin) ?? origin;
+ if (effectiveSelection(main, sessionsDir, dir).childrenAuto === false) return null;
+ const from = effectiveSelection(origin, sessionsDir, dir);
+ return { threadId: origin, unchecked: {}, auto: true, autoSince: from.autoSince ?? new Date().toISOString(), ...(from.pinned ? { pinned: from.pinned } : {}) };
}
function ownSelection(threadId: string, sessionsDir: string, dir: string, depth: number): Selection {
diff --git a/plugin/src/thread-index.ts b/plugin/src/thread-index.ts
index 2cc2a96..369538a 100644
--- a/plugin/src/thread-index.ts
+++ b/plugin/src/thread-index.ts
@@ -303,6 +303,26 @@ export function forkOrigin(sessionsDir: string, threadId: string): { parent: str
return origin;
}
+const spawners = new Map<string, string | null>();
+
+// v0.7: the thread that started a subagent without history (session_meta source.subagent.thread_spawn); null for
+// anything else: the user's tasks, forks (a subagent started with history is one), Codex's background tasks (review,
+// compaction, memory). Cached once the rollout exists: it never changes.
+export function spawnParent(sessionsDir: string, threadId: string): string | null {
+ const key = `${sessionsDir}\0${threadId}`;
+ if (spawners.has(key)) return spawners.get(key)!;
+ const meta = withSegments(sessionsDir, ({ segments }) => {
+ const first = segments.get(threadId);
+ return first ? { found: true, record: firstRecord(first) } : { found: false, record: null };
+ });
+ if (!meta.found) return null;
+ const payload = meta.record?.type === "session_meta" ? meta.record.payload : null;
+ const spawn = payload?.source?.subagent?.thread_spawn;
+ const parent = payload && !payload.forked_from_id && spawn ? spawn.parent_thread_id ?? payload.parent_thread_id : null;
+ spawners.set(key, typeof parent === "string" ? parent : null);
+ return spawners.get(key)!;
+}
+
const starts = new Map<string, string | null>();
// v0.6: when a thread started, from its session_meta; a fork counts from the thread it came from (followed to the
@@ -327,6 +347,13 @@ export function hasRollout(sessionsDir: string, threadId: string): boolean {
return allSegments(sessionsDir).segments.has(threadId);
}
+// v0.7: the task a side chat came from. Codex keeps a side chat in memory only: its requests and tool calls name the
+// task it was forked from (forked_from_thread_id), and it has no rollout of its own (a fork the user made has one, and
+// follows the fork rules). null for any other thread.
+export function sideChatOrigin(threadId: string, forkedFrom: string | null | undefined, sessionsDir: string): string | null {
+ return forkedFrom && forkedFrom !== threadId && !hasRollout(sessionsDir, threadId) ? forkedFrom : null;
+}
+
// 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 }) => {
diff --git a/spike/src/children.test.ts b/spike/src/children.test.ts
new file mode 100644
index 0000000..5e581bc
--- /dev/null
+++ b/spike/src/children.test.ts
@@ -0,0 +1,61 @@
+// Purpose: v0.7 — a task's subagents (started without history) and side chats, as the engine sees their requests, are
+// recorded once each under the task, for its panel (docs/v0.7/plan.md).
+// Input: synthetic rollouts and temporary folders; output: Node test assertions only.
+
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { childOf, readChildren, recordChild } from "../../plugin/src/children.ts";
+
+const MAIN = "01a0d307-0000-7000-8000-0000000000c0";
+const CHILD = "01a0d307-0000-7000-8000-0000000000c1";
+const FORKED_CHILD = "01a0d307-0000-7000-8000-0000000000c2";
+const USER_FORK = "01a0d307-0000-7000-8000-0000000000c3";
+const SIDE = "01a0d307-0000-7000-8000-0000000000c4";
+const SIDE_OF_CHILD = "01a0d307-0000-7000-8000-0000000000c5";
+
+function sessions() {
+ const root = mkdtempSync(join(tmpdir(), "cam-children-"));
+ const day = join(root, "sessions", "2026", "10", "13");
+ mkdirSync(day, { recursive: true });
+ const rollout = (id: string, meta: Record<string, unknown>) =>
+ writeFileSync(join(day, `rollout-2026-10-13T10-00-00-${id}.jsonl`), `${JSON.stringify({ type: "session_meta", payload: { id, timestamp: "2026-10-13T10:00:00Z", ...meta } })}\n`);
+ const spawned = { parent_thread_id: MAIN, source: { subagent: { thread_spawn: { parent_thread_id: MAIN, depth: 1, agent_nickname: "Franklin" } } } };
+ rollout(MAIN, {});
+ rollout(CHILD, spawned);
+ rollout(FORKED_CHILD, { ...spawned, forked_from_id: MAIN });
+ rollout(USER_FORK, { forked_from_id: MAIN });
+ return { root, sessionsDir: join(root, "sessions") };
+}
+
+test("a side chat belongs to the task it came from, or to that task's own task; a subagent to the task at the top", () => {
+ const { sessionsDir } = sessions();
+ const at = "2026-10-13T10:05:00Z";
+ assert.deepEqual(childOf({ threadId: SIDE, forkedFrom: MAIN }, sessionsDir, at), { task: MAIN, id: SIDE, child: { kind: "side", from: MAIN, at } });
+ assert.deepEqual(childOf({ threadId: SIDE_OF_CHILD, forkedFrom: CHILD }, sessionsDir, at), { task: MAIN, id: SIDE_OF_CHILD, child: { kind: "side", from: CHILD, at } });
+ assert.deepEqual(childOf({ threadId: CHILD, forkedFrom: null }, sessionsDir, at), { task: MAIN, id: CHILD, child: { kind: "subagent", from: MAIN, at } });
+ // Not a child here: a subagent started with history, a fork the user made (it has a rollout), the task itself.
+ assert.equal(childOf({ threadId: FORKED_CHILD, forkedFrom: null }, sessionsDir, at), null);
+ assert.equal(childOf({ threadId: USER_FORK, forkedFrom: MAIN }, sessionsDir, at), null);
+ assert.equal(childOf({ threadId: MAIN, forkedFrom: null }, sessionsDir, at), null);
+ assert.equal(childOf({ threadId: null, forkedFrom: MAIN }, sessionsDir, at), null);
+});
+
+test("each child is recorded once under its task; later requests leave the record as it was", () => {
+ const { root } = sessions();
+ const dir = join(root, "children");
+ assert.deepEqual(readChildren(MAIN, dir), {});
+ assert.equal(recordChild(MAIN, SIDE, { kind: "side", from: MAIN, at: "2026-10-13T10:05:00Z" }, dir), true);
+ assert.equal(recordChild(MAIN, SIDE, { kind: "side", from: MAIN, at: "2026-10-13T10:09:00Z" }, dir), false);
+ assert.equal(recordChild(MAIN, CHILD, { kind: "subagent", from: MAIN, at: "2026-10-13T10:06:00Z" }, dir), true);
+ assert.deepEqual(readChildren(MAIN, dir), {
+ [SIDE]: { kind: "side", from: MAIN, at: "2026-10-13T10:05:00Z" },
+ [CHILD]: { kind: "subagent", from: MAIN, at: "2026-10-13T10:06:00Z" },
+ });
+ assert.deepEqual(Object.keys(JSON.parse(readFileSync(join(dir, `${MAIN}.json`), "utf8"))), [SIDE, CHILD]);
+ // Only real thread ids name a file.
+ assert.equal(recordChild("../escape", SIDE, { kind: "side", from: MAIN, at: "x" }, dir), false);
+ assert.deepEqual(readChildren("../escape", dir), {});
+});
diff --git a/spike/src/panel-state.test.ts b/spike/src/panel-state.test.ts
index f8ccdd9..c08a4b1 100644
--- a/spike/src/panel-state.test.ts
+++ b/spike/src/panel-state.test.ts
@@ -9,10 +9,11 @@ import { dirname, join } from "node:path";
import test from "node:test";
import { decodePng } from "../../plugin/src/png.ts";
import { applySelection, imageFor, loadPanelState, panelStateOf, requestedIds, sendInfo } from "../../plugin/src/panel-state.ts";
-import { requestStatsDirOf } from "../../plugin/src/paths.ts";
+import { childrenDirOf, requestStatsDirOf } from "../../plugin/src/paths.ts";
+import { recordChild } from "../../plugin/src/children.ts";
import { recordRequest } from "../../plugin/src/request-stats.ts";
import { readSelection, writeSelection } from "../../plugin/src/selection.ts";
-import { assistant, line, red, sampleSessions, THREAD, turn, upload } from "./testfixtures.ts";
+import { assistant, line, red, sampleSessions, startThread, THREAD, turn, upload } from "./testfixtures.ts";
import { shrink } from "../../plugin/src/thumbnail.ts";
import { png } from "./testkit.ts";
@@ -240,3 +241,29 @@ test("a fork whose earlier history is gone lists the images left and says part o
assert.deepEqual([state.historyMissing, state.started, state.images.map((image) => image.name)], [true, true, ["later.png"]]);
assert.equal(loadPanelState(THREAD, options).historyMissing, false);
});
+
+// v0.7: the task's subagents and side chats, from the engine's record of them and their own requests.
+test("the task's panel lists its subagents and side chats with their last request, and the switch for them", () => {
+ const options = sampleSessions();
+ const CHILD = "01a0d307-0000-7000-8000-0000000000e1";
+ const SIDE = "01a0d307-0000-7000-8000-0000000000e2";
+ assert.deepEqual([loadPanelState(THREAD, options).childrenAuto, loadPanelState(THREAD, options).children], [true, []]);
+ // A subagent has a rollout naming its parent, started now (today's folder); a side chat has none.
+ startThread(options.sessionsDir, CHILD, { parent_thread_id: THREAD, source: { subagent: { thread_spawn: { parent_thread_id: THREAD, depth: 1, agent_path: "/root/reviewer", agent_nickname: "Franklin" } } }, thread_source: "subagent" });
+ const children = childrenDirOf(options.dataRoot);
+ recordChild(THREAD, SIDE, { kind: "side", from: THREAD, at: "2026-09-24T10:06:00Z" }, children);
+ recordChild(THREAD, CHILD, { kind: "subagent", from: THREAD, at: "2026-09-24T10:05:00Z" }, children);
+ recordRequest(SIDE, { at: "2026-09-24T10:07:00Z", transport: "http", images: 3, decodedBytes: 9000, rewrite: { images: 3, replaced: [{ id: "IMG-001" }, { id: "IMG-002" }, { id: "IMG-003" }], decodedAfter: 1000, auto: true, sideChatOf: THREAD } }, requestStatsDirOf(options.dataRoot));
+ let state = loadPanelState(THREAD, options);
+ assert.equal(state.childrenAuto, true);
+ // Oldest first; the subagent has sent nothing through the engine yet.
+ assert.deepEqual(state.children.map((child) => [child.threadId, child.kind, child.name, child.startedAt, child.auto, child.images, child.last?.replaced ?? null, child.last?.bytesAfter ?? null]), [
+ [CHILD, "subagent", "Franklin", "2026-09-24T10:05:00Z", true, null, null, null],
+ [SIDE, "side", null, "2026-09-24T10:06:00Z", true, 3, 3, 1000],
+ ]);
+ // Switched off in the panel: neither is managed; the task's own switch and checks stay as they were.
+ state = applySelection(THREAD, { childrenAuto: false }, options);
+ assert.deepEqual([state.childrenAuto, state.children.map((child) => child.auto)], [false, [false, false]]);
+ assert.deepEqual(readSelection(THREAD, join(options.dataRoot, "selection")), { threadId: THREAD, unchecked: {}, childrenAuto: false });
+ assert.deepEqual(applySelection(THREAD, { childrenAuto: true }, options).children.map((child) => child.auto), [true, true]);
+});
diff --git a/spike/src/plugin-server.test.ts b/spike/src/plugin-server.test.ts
index 9e2d842..67c2432 100644
--- a/spike/src/plugin-server.test.ts
+++ b/spike/src/plugin-server.test.ts
@@ -92,6 +92,30 @@ test("the model fetches originals by id only where automatic selection is on (v0
}
});
+// v0.7: Codex keeps a side chat in memory only; the model's calls there name the task it was forked from.
+test("in a side chat the model fetches the originals of the task it came from, unless the user turned that off", () => {
+ const { sessionsDir, dataRoot } = sampleSessions();
+ process.env.CAM_DATA_DIR = dataRoot;
+ try {
+ const SIDE = "01a0d307-0000-7000-8000-0000000000d1";
+ const sideMeta = { callId: "exec-2", threadId: SIDE, "x-codex-turn-metadata": { thread_id: SIDE, session_id: SIDE, turn_id: "s1", forked_from_thread_id: THREAD } };
+ // The task's own automatic selection is off; its side chats have it all the same.
+ const on = callTool("cam_view_image", { ids: ["IMG-001"] }, sideMeta, sessionsDir);
+ assert.equal(on.isError, false);
+ assert.equal(on.content[0].text, "[图片 IMG-001 取回的原图|a.png|用户上传|第 1 轮|64×32]");
+ assert.equal(Buffer.from(on.content[1].data, "base64").equals(red), true);
+ assert.equal(callTool("cam_panel", {}, panelMeta, sessionsDir).structuredContent.childrenAuto, true);
+ // Only the user switches it, in the task's panel.
+ assert.throws(() => callTool("cam_set_selection", { childrenAuto: false }, modelMeta, sessionsDir), /只有用户能勾选或取消/);
+ assert.equal(callTool("cam_set_selection", { childrenAuto: false }, panelMeta, sessionsDir).structuredContent.childrenAuto, false);
+ const off = callTool("cam_view_image", { ids: ["IMG-001"] }, sideMeta, sessionsDir);
+ assert.equal(off.isError, true);
+ assert.match(off.content[0].text, /没有开自动选图/);
+ } finally {
+ delete process.env.CAM_DATA_DIR;
+ }
+});
+
test("a stdio session lists the tools and answers calls", async () => {
const { sessionsDir, dataRoot } = sampleSessions();
const child = spawn(process.execPath, [join(here, "..", "..", "plugin", "src", "plugin-server.ts")], { env: { ...process.env, CAM_NO_ENGINE: "1", CAM_DATA_DIR: dataRoot, CODEX_HOME: dirname(sessionsDir) }, stdio: ["pipe", "pipe", "inherit"] });
diff --git a/spike/src/proxy.test.ts b/spike/src/proxy.test.ts
index 9bf28af..5eb4998 100644
--- a/spike/src/proxy.test.ts
+++ b/spike/src/proxy.test.ts
@@ -41,8 +41,18 @@ test("NO_PROXY entries covering the upstream host mean a direct connection", ()
test("the task a request belongs to is read from x-codex-turn-metadata", () => {
const headers = { "x-codex-turn-metadata": JSON.stringify({ thread_id: "thread-a", turn_id: "turn-1" }), "x-codex-window-id": "thread-a:0" };
- assert.deepEqual(requestIdentity(headers), { threadId: "thread-a", turnId: "turn-1", windowId: "thread-a:0" });
- assert.deepEqual(requestIdentity({ "x-codex-turn-metadata": "not json" }), { threadId: null, turnId: null, windowId: null });
+ assert.deepEqual(requestIdentity(headers), { threadId: "thread-a", turnId: "turn-1", windowId: "thread-a:0", forkedFrom: null, parentThreadId: null, subagentKind: null });
+ assert.deepEqual(requestIdentity({ "x-codex-turn-metadata": "not json" }), { threadId: null, turnId: null, windowId: null, forkedFrom: null, parentThreadId: null, subagentKind: null });
+});
+
+// v0.7: as Codex 0.162 sends them (docs/v0.7/plan.md §3).
+test("a side chat's requests name the task it was forked from, a subagent's its parent", () => {
+ const side = { "x-codex-turn-metadata": JSON.stringify({ thread_id: "side", session_id: "side", turn_id: "turn-s", forked_from_thread_id: "main" }) };
+ assert.deepEqual(requestIdentity(side), { threadId: "side", turnId: "turn-s", windowId: null, forkedFrom: "main", parentThreadId: null, subagentKind: null });
+ const child = { "x-codex-turn-metadata": JSON.stringify({ thread_id: "child", session_id: "main", turn_id: "turn-c", parent_thread_id: "main", subagent_kind: "thread_spawn" }), "x-codex-parent-thread-id": "main", "x-openai-subagent": "collab_spawn" };
+ assert.deepEqual(requestIdentity(child), { threadId: "child", turnId: "turn-c", windowId: null, forkedFrom: null, parentThreadId: "main", subagentKind: "thread_spawn" });
+ // Codex's own header, when the metadata does not say.
+ assert.equal(requestIdentity({ "x-codex-turn-metadata": JSON.stringify({ thread_id: "child" }), "x-codex-parent-thread-id": "main" }).parentThreadId, "main");
});
test("request metadata counts images in messages and in tool outputs, without content", () => {
@@ -405,3 +415,31 @@ test("v0.5: the request writing a second summary is rewritten as usual; after it
assert.deepEqual(after.report.compacted, { at: 0, listed: 2, resent: ["IMG-001", "IMG-002"] });
assert.deepEqual(partsOf(sent(after)[0]), ["second summary", "IMG-001", "image:A", "IMG-002", "image:B"]);
});
+
+// v0.7: a side chat. Codex keeps it in memory only, so it has no rollout; its requests carry the task's history and
+// name that task (forked_from_thread_id).
+test("a side chat's request is rewritten with the images of the task it came from; with the switch off it goes out as it is", () => {
+ const { threadId, sessions, selections, red, blue, body } = fixture();
+ const SIDE = "01a0d307-0000-7000-8000-0000000000b1";
+ // The task's own switch is off and nothing is unchecked there: the side chat still leaves the images out.
+ assert.equal(needsRewrite(SIDE, selections, sessions, threadId), true);
+ const json = JSON.parse(zlib.zstdDecompressSync(body()).toString("utf8"));
+ json.input.push({ type: "message", role: "user", content: [{ type: "input_text", text: "主任务在做什么?" }] });
+ const original = zlib.zstdCompressSync(Buffer.from(JSON.stringify(json)));
+ const { body: out, report } = rewriteBody(original, "zstd", SIDE, sessions, selections, "side-turn", threadId);
+ const text = zlib.zstdDecompressSync(out).toString("utf8");
+ assert.ok(!text.includes(red.slice(30)) && !text.includes(blue.slice(30)), "the task's images are left out, those of its latest turn too");
+ assert.match(text, /\[图片 IMG-001(\[Image #1\]) 已省略|a\.png|用户上传|第 1 轮|64×64\]/);
+ assert.deepEqual([report.auto, report.sideChatOf, report.replaced.map((r: Record<string, unknown>) => r.id)], [true, threadId, ["IMG-001", "IMG-002"]]);
+ // Pinned in the task: still sent.
+ const pinned = { "msg_1#1": { id: "IMG-002", at: "2026-10-06T10:00:00Z" } };
+ writeSelection({ threadId, unchecked: {}, auto: true, autoAt: "2026-10-06T10:00:00Z", autoSince: "2026-10-06T10:00:00Z", pinned }, selections);
+ const kept = zlib.zstdDecompressSync(rewriteBody(original, "zstd", SIDE, sessions, selections, "side-turn", threadId).body).toString("utf8");
+ assert.ok(!kept.includes(red.slice(30)) && kept.includes(blue.slice(30)));
+ // Turned off in the task's panel.
+ writeSelection({ threadId, unchecked: {}, auto: true, autoAt: "2026-10-06T10:00:00Z", autoSince: "2026-10-06T10:00:00Z", pinned, childrenAuto: false }, selections);
+ assert.equal(needsRewrite(SIDE, selections, sessions, threadId), false);
+ assert.equal(rewriteBody(original, "zstd", SIDE, sessions, selections, "side-turn", threadId).body, original);
+ // A thread with a rollout of its own is no side chat, whatever its requests say (a fork the user made).
+ assert.equal(needsRewrite(threadId, selections, sessions, "01a0d307-0000-7000-8000-0000000000b9"), true);
+});
diff --git a/spike/src/selection.test.ts b/spike/src/selection.test.ts
index b4c1606..a91869f 100644
--- a/spike/src/selection.test.ts
+++ b/spike/src/selection.test.ts
@@ -8,7 +8,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import { hasUnchecked, needsRewrite } from "../../plugin/src/proxy.ts";
-import { autoDefaultSince, effectiveSelection, ensureAutoDefault, readSelection, writeSelection } from "../../plugin/src/selection.ts";
+import { autoDefaultSince, effectiveSelection, ensureAutoDefault, mainTaskOf, readSelection, sideChatSelection, writeSelection } from "../../plugin/src/selection.ts";
import { startThread } from "./testfixtures.ts";
const PARENT = "01a0d301-0000-7000-8000-0000000000f0";
@@ -136,3 +136,63 @@ test("v0.6: a fork counts from the task it came from", () => {
// Forked from a task that started after: on, like it.
assert.equal(effectiveSelection(NEW_FORK, sessionsDir, dir).auto, true);
});
+
+// v0.7: subagents and side chats (docs/v0.7/plan.md). As Codex 0.162 records them: a subagent started without history
+// names its parent; one started with history is also a fork.
+const MAIN = "01a0d307-0000-7000-8000-0000000000a0";
+const CHILD = "01a0d307-0000-7000-8000-0000000000a1";
+const GRANDCHILD = "01a0d307-0000-7000-8000-0000000000a2";
+const FORKED_CHILD = "01a0d307-0000-7000-8000-0000000000a3";
+const REVIEW = "01a0d307-0000-7000-8000-0000000000a4";
+
+function family() {
+ const { sessionsDir, dir, rollout } = setup();
+ const spawned = (parent: string, depth: number) => ({ parent_thread_id: parent, source: { subagent: { thread_spawn: { parent_thread_id: parent, depth, agent_path: "/root/child", agent_nickname: "Franklin", agent_role: null } } }, thread_source: "subagent" });
+ rollout(MAIN, { timestamp: "2026-09-24T10:00:00Z" });
+ rollout(CHILD, { ...spawned(MAIN, 1), timestamp: "2026-09-24T10:05:00Z" });
+ rollout(GRANDCHILD, { ...spawned(CHILD, 2), timestamp: "2026-09-24T10:06:00Z" });
+ rollout(FORKED_CHILD, { ...spawned(MAIN, 1), forked_from_id: MAIN, timestamp: "2026-09-24T10:07:00Z" });
+ rollout(REVIEW, { parent_thread_id: MAIN, source: { subagent: "review" }, timestamp: "2026-09-24T10:08:00Z" });
+ return { sessionsDir, dir };
+}
+
+test("v0.7: a subagent started without history belongs to the task at the top of its parents", () => {
+ const { sessionsDir } = family();
+ assert.equal(mainTaskOf(sessionsDir, CHILD), MAIN);
+ assert.equal(mainTaskOf(sessionsDir, GRANDCHILD), MAIN);
+ // A fork follows the fork rules; the user's task, Codex's background tasks and unknown threads belong to none.
+ for (const other of [FORKED_CHILD, MAIN, REVIEW, "01a0d307-0000-7000-8000-0000000000af"]) assert.equal(mainTaskOf(sessionsDir, other), null, other);
+});
+
+test("v0.7: a subagent follows its task's switch for subagents and side chats, on unless the user turned it off", () => {
+ const { sessionsDir, dir } = family();
+ // No default for the task itself here (no auto-default.json): the subagents' switch is on regardless.
+ const child = effectiveSelection(CHILD, sessionsDir, dir);
+ assert.deepEqual([child.auto, child.autoSince], [true, "2026-09-24T10:05:00Z"], "from the subagent's start");
+ assert.equal(needsRewrite(CHILD, dir, sessionsDir), true);
+ assert.equal(effectiveSelection(GRANDCHILD, sessionsDir, dir).auto, true);
+ // The task's own switch is a different one.
+ writeSelection({ threadId: MAIN, unchecked: {}, auto: false, autoAt: "2026-09-24T10:01:00Z", autoSince: "2026-09-24T10:00:30Z" }, dir);
+ assert.equal(effectiveSelection(CHILD, sessionsDir, dir).auto, true);
+ // Turned off: nothing is managed, so the requests go out as they are.
+ writeSelection({ threadId: MAIN, unchecked: {}, childrenAuto: false }, dir);
+ assert.equal(effectiveSelection(CHILD, sessionsDir, dir).auto, false);
+ assert.equal(effectiveSelection(GRANDCHILD, sessionsDir, dir).auto, false);
+ assert.equal(needsRewrite(CHILD, dir, sessionsDir), false);
+ // A switch of the subagent's own wins.
+ writeSelection({ threadId: CHILD, unchecked: {}, auto: true, autoAt: "2026-09-24T10:10:00Z", autoSince: "2026-09-24T10:10:00Z" }, dir);
+ assert.equal(effectiveSelection(CHILD, sessionsDir, dir).auto, true);
+});
+
+test("v0.7: a side chat uses the selection of the task it came from, keeping what is pinned there; none with the switch off", () => {
+ const { sessionsDir, dir } = family();
+ const pinned = { "msg_9#0": { id: "IMG-009", at: "2026-09-24T10:02:00Z" } };
+ writeSelection({ threadId: MAIN, unchecked: {}, auto: true, autoAt: "2026-09-24T10:01:00Z", autoSince: "2026-09-24T10:01:00Z", pinned }, dir);
+ const side = sideChatSelection(MAIN, sessionsDir, dir);
+ assert.deepEqual([side?.threadId, side?.auto, side?.pinned], [MAIN, true, pinned]);
+ // Forked from a subagent: its images, its task's switch.
+ assert.deepEqual([sideChatSelection(CHILD, sessionsDir, dir)?.threadId, sideChatSelection(CHILD, sessionsDir, dir)?.auto], [CHILD, true]);
+ writeSelection({ threadId: MAIN, unchecked: {}, auto: true, autoAt: "2026-09-24T10:01:00Z", autoSince: "2026-09-24T10:01:00Z", pinned, childrenAuto: false }, dir);
+ assert.equal(sideChatSelection(MAIN, sessionsDir, dir), null);
+ assert.equal(sideChatSelection(CHILD, sessionsDir, dir), null);
+});