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: 新任务和新会话默认开启自动选图;Claude 桌面版有图时自动打开面板

chipfighter80ceb3aff78f
diff --git a/hooks/register.js b/hooks/register.js
index 7d37e45..a3d10a9 100644
--- a/hooks/register.js
+++ b/hooks/register.js
@@ -14,7 +14,13 @@
// Also: the model's cam_view_image call gets this session's id (the service may outlive a /clear or /resume), and needs
// no permission prompt: it is the plugin's own read-only tool, approved as in Codex (default_tools_approval_mode
// "approve" there; user 2026-10-10 here). A deny or ask from the user's own hooks or settings still stands.
-// Input: mod events. Output: env changes for this process, a pane, requests to the engine on 127.0.0.1.
+// v0.6 (user 2026-10-13): in Claude Desktop the page opens by itself once the session has images, without /cam.
+// Claude Desktop stops an idle session's process after 30 minutes and closes the browser tabs it opened (its log:
+// "WarmLifecycle … Idle timeout reached"); the process starts again when the session is used, and the page opens
+// again then. Closed by the user, it stays closed in that session until /cam: a turn that ends without the tab, in the
+// process that had it open, means the user closed it, kept in the plugin's store for the session.
+// Input: mod events. Output: env changes for this process, a pane, requests to the engine on 127.0.0.1, the page in
+// Claude Desktop's browser.
const PLUGIN = 'codex-attachment-manager'
// The engine's port (engine.ts, DEFAULT_PORT); the plugin's MCP server starts the engine on it.
@@ -23,6 +29,9 @@ const PANE = 'cam'
const ROUTING = { plugin: 'codex-attachment-manager', key: 'routing' }
// The model's image fetch, as Claude Code names the tool of this plugin's MCP server (.claude-plugin/plugin.json).
const FETCH_TOOL = 'mcp__plugin_codex-attachment-manager_codex_attachment_manager__cam_view_image'
+// v0.6: the sessions where the user closed the page ($.store: session id → when), the newest kept.
+const CLOSED = 'closedPanels'
+const CLOSED_KEPT = 200
const WORDS = {
zh: {
@@ -67,6 +76,8 @@ let inBrowser = false
let overview = null
let paneOpened = false
let copied = false
+// v0.6: the session whose page this process had open in Claude's browser (null: none).
+let pageFor = null
// The engine's panel API answers in JSON; the header marks a request as the panel's (a browser page cannot send it).
async function api($, path) {
@@ -165,14 +176,79 @@ async function openInBrowser($, url) {
}
}
-// /cam.
+// v0.6: the session's tabs in Claude's browser (tabs_context answers JSON, then a line of text), the page's told apart
+// by the engine's origin; null when the browser tools are not there or fail.
+const PAGE_ORIGIN = `http://localhost:${ENGINE_PORT}`
+async function pageTabs($) {
+ try {
+ const result = await $.mcp.call('Claude_Browser', 'tabs_context', {})
+ if (result?.isError) return null
+ const text = (result?.content ?? []).map((block) => block?.text ?? '').join('\n')
+ const tabs = JSON.parse(text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1)).tabs
+ return Array.isArray(tabs) ? tabs.filter((tab) => tab?.origin === PAGE_ORIGIN) : null
+ } catch {
+ return null
+ }
+}
+
+async function closedHere($, sessionId) {
+ const closed = (await $.store.get(CLOSED)) ?? {}
+ return typeof closed[sessionId] === 'string'
+}
+
+async function markClosed($, sessionId, isClosed) {
+ const closed = { ...((await $.store.get(CLOSED)) ?? {}) }
+ if (isClosed) closed[sessionId] = new Date(await $.clock.now()).toISOString()
+ else if (sessionId in closed) delete closed[sessionId]
+ else return
+ const newest = Object.entries(closed).sort((a, b) => String(b[1]).localeCompare(String(a[1]))).slice(0, CLOSED_KEPT)
+ await $.store.set(CLOSED, Object.fromEntries(newest))
+}
+
+// /cam: the user asked, so a close before no longer counts. One tab of the page: the new one replaces any open.
async function openPanel($) {
routingState = (await readRouting($)) ?? routingState
- inBrowser = await openInBrowser($, panelUrl(await $.session.id()))
+ const sessionId = await $.session.id()
+ await markClosed($, sessionId, false).catch(() => {})
+ const before = (await pageTabs($)) ?? []
+ inBrowser = await openInBrowser($, panelUrl(sessionId))
+ if (inBrowser) {
+ pageFor = sessionId
+ for (const tab of before) await $.mcp.call('Claude_Browser', 'tabs_close', { tabId: tab.tabId }).catch(() => {})
+ }
if (!inBrowser || !routingState?.active) await openPane($)
else await $.ui.invalidate('ui.render')
}
+// v0.6: in Claude Desktop, with the requests going through the engine, the page opens by itself in a session with
+// images, unless the user closed it there. Run when the process starts (also when Claude Desktop wakes the session),
+// when the desktop attaches, and after each turn.
+async function keepPage($) {
+ if (!routingState?.active) return
+ if (!(await $.session.surfaces()).includes('desktop')) return
+ const sessionId = await $.session.id()
+ const open = await pageTabs($)
+ if (open === null) return
+ if (open.length) { pageFor = sessionId; return }
+ // Open in this process, gone while it runs: the user closed it.
+ if (pageFor === sessionId) { pageFor = null; await markClosed($, sessionId, true); return }
+ if (await closedHere($, sessionId)) return
+ const state = await api($, `/__cam/claude/panel?session=${encodeURIComponent(sessionId)}`).catch(() => null)
+ if (!state?.totals?.images) return
+ if (await openInBrowser($, panelUrl(sessionId))) pageFor = sessionId
+}
+
+// v0.6: after /clear or /resume the page follows the new session: the open tab is pointed at it, or it opens as above.
+async function followSession($) {
+ const sessionId = await $.session.id()
+ const open = await pageTabs($)
+ if (!open?.length) { pageFor = null; return keepPage($) }
+ await $.mcp.call('Claude_Browser', 'navigate', { url: panelUrl(sessionId), tabId: open[0].tabId })
+ pageFor = sessionId
+}
+
+const keepPageLater = ($) => $.clock.after(0, () => { keepPage($).catch(() => {}) })
+
async function loadOverview($) {
try {
const state = await api($, `/__cam/claude/panel?session=${encodeURIComponent(await $.session.id())}`)
@@ -234,6 +310,14 @@ export function register(on) {
// rest of the wait goes on in the background.
const done = await startRouting($, 12).catch(() => true)
if (!done) $.clock.after(0, () => { startRouting($).catch(() => {}) })
+ // v0.6: the page, once routing is settled; when it is still waiting for the engine, after the first turn instead.
+ else keepPageLater($)
+ return next(e)
+ })
+
+ // v0.6: the desktop connects after the process started (a session woken up, or opened again).
+ on('session.attach', { surface: 'desktop' }, async ($, e, next) => {
+ keepPageLater($)
return next(e)
})
@@ -242,12 +326,14 @@ export function register(on) {
on('classic.SessionStart', { source: ['clear', 'resume', 'fork'] }, async ($, e, next) => {
if (routingState) await $.state.set(ROUTING, routingState).catch(() => {})
reloadOverview($)
+ $.clock.after(0, () => { followSession($).catch(() => {}) })
return next(e)
})
on('turn.complete', async ($, e, next) => {
const result = await next(e)
reloadOverview($)
+ keepPageLater($)
return result
})
diff --git a/plugin/src/claude-index.ts b/plugin/src/claude-index.ts
index 9622f5e..725326c 100644
--- a/plugin/src/claude-index.ts
+++ b/plugin/src/claude-index.ts
@@ -268,6 +268,13 @@ export function titleOf(records: ClaudeRecord[], chain: ClaudeRecord[]): string
return line ? (line.length > 40 ? `${line.slice(0, 40)}…` : line) : null;
}
+// v0.6: when the session started: Claude Code stamps its records, and the conversation's first one is the oldest.
+// null before its first message.
+export function claudeStartedAt(index: ClaudeIndex): string | null {
+ const first = index.chain.find((record) => typeof record.timestamp === "string");
+ return first ? first.timestamp : null;
+}
+
// The base64 of one indexed image, from the record it sits in.
export function claudeImageData(index: ClaudeIndex, image: ClaudeImage): string | null {
const block = index.chain[image.item]?.message?.content?.[image.part!];
diff --git a/plugin/src/panel-state.ts b/plugin/src/panel-state.ts
index 5c1b406..65a1f00 100644
--- a/plugin/src/panel-state.ts
+++ b/plugin/src/panel-state.ts
@@ -9,11 +9,11 @@
// 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 { claudeHome, claudeImageData, loadClaudeIndex, type ClaudeIndex } from "./claude-index.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 { readRequestStats, type RequestStats } from "./request-stats.ts";
-import { effectiveSelection, readSelection, writeSelection, type Mark, type Selection } from "./selection.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 { threadTitle } from "./thread-names.ts";
import { pngThumbnail } from "./thumbnail.ts";
@@ -276,7 +276,7 @@ export type ClaudePanelOptions = { dataRoot?: string; home?: string };
function loadClaude(sessionId: string, options: ClaudePanelOptions) {
const root = options.dataRoot ?? dataDir();
const index = loadClaudeIndex(sessionId, options.home ?? claudeHome());
- const selection = readSelection(sessionId, claudeSelectionDirOf(root));
+ const selection = claudeSelection(sessionId, claudeSelectionDirOf(root), claudeStartedAt(index));
const stats = readRequestStats(sessionId, claudeRequestStatsDirOf(root));
return { root, index, selection, stats };
}
diff --git a/plugin/src/plugin-server.ts b/plugin/src/plugin-server.ts
index 28783f7..b5aa78a 100644
--- a/plugin/src/plugin-server.ts
+++ b/plugin/src/plugin-server.ts
@@ -27,7 +27,7 @@ import { createInterface } from "node:readline";
import { fileURLToPath } from "node:url";
import { codexHome } from "./codexconfig.ts";
import { bindThread, isUserThread, newThreads, resolveThread } from "./binding.ts";
-import { loadClaudeIndex } from "./claude-index.ts";
+import { claudeStartedAt, loadClaudeIndex } from "./claude-index.ts";
import { DEFAULT_PORT, ensureEngine } from "./engine.ts";
import { isEntryPoint } from "./entry.ts";
import { currentLang, langOf, rememberLang, type Lang } from "./language.ts";
@@ -36,7 +36,7 @@ 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 { effectiveSelection, readSelection } from "./selection.ts";
+import { claudeSelection, effectiveSelection, ensureAutoDefault } from "./selection.ts";
import { connectDirectly, useEngine, usesEngine } from "./setup.ts";
import { hasRollout, loadThreadIndex, readThreadHistory, sessionMetaOf, setPixelCache } from "./thread-index.ts";
import { threadTitle } from "./thread-names.ts";
@@ -251,11 +251,11 @@ export function callClaudeTool(name: string, args: Json, options: ClaudePanelOpt
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] : [];
- if (!readSelection(sessionId, claudeSelectionDirOf(options.dataRoot ?? dataDir())).auto) {
+ const index = loadClaudeIndex(sessionId, options.home);
+ if (!claudeSelection(sessionId, claudeSelectionDirOf(options.dataRoot ?? dataDir()), claudeStartedAt(index)).auto) {
log({ event: "fetch", host: "claude", sessionId, ids, refused: "automatic selection is off" });
return { content: [{ type: "text", text: words.off }], isError: true };
}
- const index = loadClaudeIndex(sessionId, options.home);
const content: Json[] = [];
const found: string[] = [];
for (const asked of ids) {
@@ -276,6 +276,9 @@ export function callClaudeTool(name: string, args: Json, options: ClaudePanelOpt
function main(): void {
migrateDataOnce(); // v0.1-15: Windows moved the data folder
+ // v0.6: the panel may read a selection before the engine has started: the same start for both (selection.ts).
+ ensureAutoDefault(selectionDirOf());
+ ensureAutoDefault(claudeSelectionDirOf());
const send = (message: Json) => process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`);
let engineState = "";
const supervise = async () => {
diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.ts
index 76f82ee..815e83b 100644
--- a/plugin/src/proxy.ts
+++ b/plugin/src/proxy.ts
@@ -25,7 +25,7 @@ import type { Duplex } from "node:stream";
import tls from "node:tls";
import { fileURLToPath } from "node:url";
import zlib from "node:zlib";
-import { claudeHome, claudeImageData, loadClaudeIndex, type ClaudeIndex } from "./claude-index.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";
import { codexHome } from "./codexconfig.ts";
@@ -35,11 +35,11 @@ import { isEntryPoint } from "./entry.ts";
import { currentLang } from "./language.ts";
import { migrateDataOnce } from "./migrate-data.ts";
import { applyClaudeSelection, claudeImageFor, loadClaudePanelState, type ClaudePanelOptions } from "./panel-state.ts";
-import { claudeRequestStatsDirOf, claudeSelectionDirOf, dataDir, pixelCacheDirOf, proxyLogDirOf } from "./paths.ts";
+import { claudeRequestStatsDirOf, claudeSelectionDirOf, dataDir, pixelCacheDirOf, proxyLogDirOf, selectionDirOf } 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, readSelection, selectionDir } from "./selection.ts";
+import { claudeSelection, effectiveSelection, ensureAutoDefault, selectionDir } from "./selection.ts";
import { loadThreadIndex, pixelHashOf, pixelHashOfData, setPixelCache, type ThreadIndex } from "./thread-index.ts";
type Json = Record<string, any>;
@@ -306,11 +306,13 @@ export function rewriteBody(original: Buffer, encoding: string | undefined, thre
// before the compaction, which the user may keep sending.
export function claudeNeedsRewrite(sessionId: string | null, dir = claudeSelectionDirOf(), home = claudeHome()): boolean {
if (!sessionId) return false;
+ let index: ClaudeIndex | null = null;
+ try { index = loadClaudeIndex(sessionId, home); } catch { /* the selection still decides */ }
try {
- const selection = readSelection(sessionId, dir);
+ const selection = claudeSelection(sessionId, dir, index ? claudeStartedAt(index) : null);
if (Object.keys(selection.unchecked).length > 0 || selection.autoSince) return true;
} catch { /* the transcript still decides */ }
- try { return loadClaudeIndex(sessionId, home).images.some((image) => image.compacted); } catch { return false; }
+ return !!index?.images.some((image) => image.compacted);
}
// The images a Claude Code request carried, by index key, with the base64 characters each took (the panel's
@@ -348,7 +350,7 @@ export function rewriteClaudeBody(original: Buffer, encoding: string | undefined
if (hasUnsafeInteger(text)) return asIs({ skipped: "integer beyond 2^53 would change when re-serialized" });
let index: ClaudeIndex;
try { index = loadClaudeIndex(sessionId, home); } catch (error) { return asIs({ skipped: `thread index: ${String(error)}` }); }
- const selection = readSelection(sessionId, dir);
+ const selection = claudeSelection(sessionId, dir, claudeStartedAt(index));
const current = index.turns;
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));
@@ -480,6 +482,9 @@ export function claudePanelApi(method: string, url: string, headers: IncomingHtt
async function main(): Promise<void> {
migrateDataOnce(); // v0.1-15: Windows moved the data folder
+ // v0.6: tasks and sessions started from now on have automatic selection on by default (selection.ts).
+ ensureAutoDefault(selectionDirOf());
+ ensureAutoDefault(claudeSelectionDirOf());
const portIndex = process.argv.indexOf("--port");
const port = Number(portIndex >= 0 ? process.argv[portIndex + 1] : DEFAULT_PORT);
// One engine per machine: a second start leaves the running one alone.
diff --git a/plugin/src/selection.ts b/plugin/src/selection.ts
index ee829e7..5568f4c 100644
--- a/plugin/src/selection.ts
+++ b/plugin/src/selection.ts
@@ -6,13 +6,17 @@
// the manual checks, which come back as they were when it is switched off. `autoAt` is when it was last switched,
// `autoSince` when it was first switched on: from then on the history may hold copies the model fetched, which the
// engine leaves out of later turns even with the switch off.
+// v0.6 — automatic selection is on by default in a thread started after this version first ran here (user
+// 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.
// 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.
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { selectionDirOf } from "./paths.ts";
-import { forkOrigin } from "./thread-index.ts";
+import { forkOrigin, 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 };
@@ -45,10 +49,54 @@ export function writeSelection(selection: Selection, dir = selectionDir): void {
renameSync(`${file}.tmp`, file);
}
+// v0.6: written by the engine and the plugin service when they start; the first one wins.
+const AUTO_DEFAULT = "auto-default.json";
+const sinceOf = new Map<string, string>();
+export function ensureAutoDefault(dir = selectionDir, now = new Date()): void {
+ mkdirSync(dir, { recursive: true });
+ try {
+ writeFileSync(join(dir, AUTO_DEFAULT), JSON.stringify({ since: now.toISOString() }, null, 2), { flag: "wx" });
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
+ }
+}
+
+// null until this version has run here: then nothing is on by default.
+export function autoDefaultSince(dir = selectionDir): string | null {
+ const known = sinceOf.get(dir);
+ if (known) return known;
+ try {
+ const since = JSON.parse(readFileSync(join(dir, AUTO_DEFAULT), "utf8")).since;
+ if (typeof since === "string") sinceOf.set(dir, since);
+ return typeof since === "string" ? since : null;
+ } catch {
+ return null;
+ }
+}
+
+// A thread with no switch of its own that started at or after `since` has automatic selection on, from its start;
+// one with no history yet (startedAt null) is just starting.
+export function withAutoDefault(selection: Selection, startedAt: string | null, since: string | null): Selection {
+ if (typeof selection.auto === "boolean" || !since) return selection;
+ const started = startedAt ?? new Date().toISOString();
+ if (Date.parse(started) < Date.parse(since)) return selection;
+ return { ...selection, auto: true, autoSince: selection.autoSince ?? started };
+}
+
+// v0.6: a Claude Code session's selection with the default applied, given when it started (claudeStartedAt).
+export function claudeSelection(sessionId: string, dir: string, startedAt: string | null): Selection {
+ return withAutoDefault(readSelection(sessionId, dir), startedAt, autoDefaultSince(dir));
+}
+
// The thread's own selection; a fork without one takes the images its parent had unchecked by the time of the fork
// (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.
+// 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.
export function effectiveSelection(threadId: string, sessionsDir: string, dir = selectionDir, depth = 0): Selection {
+ return withAutoDefault(ownSelection(threadId, sessionsDir, dir, depth), threadStartedAt(sessionsDir, threadId), autoDefaultSince(dir));
+}
+
+function ownSelection(threadId: string, sessionsDir: string, dir: string, depth: number): Selection {
if (existsSync(fileFor(threadId, dir)) || depth > 16) return readSelection(threadId, dir);
const origin = forkOrigin(sessionsDir, threadId);
if (!origin) return { threadId, unchecked: {} };
diff --git a/plugin/src/thread-index.ts b/plugin/src/thread-index.ts
index a6001b2..2cc2a96 100644
--- a/plugin/src/thread-index.ts
+++ b/plugin/src/thread-index.ts
@@ -303,6 +303,25 @@ export function forkOrigin(sessionsDir: string, threadId: string): { parent: str
return origin;
}
+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
+// first one; the fork's own time when that one is gone). null while the thread has no rollout. Cached once known.
+export function threadStartedAt(sessionsDir: string, threadId: string, depth = 0): string | null {
+ const origin = forkOrigin(sessionsDir, threadId);
+ if (origin && depth < 16) return threadStartedAt(sessionsDir, origin.parent, depth + 1) ?? (origin.at || null);
+ const key = `${sessionsDir}\0${threadId}`;
+ if (starts.has(key)) return starts.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 at = (meta.record?.type === "session_meta" ? meta.record.payload.timestamp : null) ?? meta.record?.timestamp ?? null;
+ starts.set(key, typeof at === "string" ? at : null);
+ return starts.get(key)!;
+}
+
// 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);
diff --git a/spike/src/claude-panel.test.ts b/spike/src/claude-panel.test.ts
index 3082adc..c14da91 100644
--- a/spike/src/claude-panel.test.ts
+++ b/spike/src/claude-panel.test.ts
@@ -11,8 +11,9 @@ import { join } from "node:path";
import test from "node:test";
import { claudeSelectionDirOf } from "../../plugin/src/paths.ts";
import { callClaudeTool, claudeToolsFor } from "../../plugin/src/plugin-server.ts";
-import { claudePanelApi, claudePanelPage, ownRequest } from "../../plugin/src/proxy.ts";
-import { pngC, usualSession } from "./claude-fixtures.ts";
+import { claudeNeedsRewrite, claudePanelApi, claudePanelPage, ownRequest, rewriteClaudeBody } from "../../plugin/src/proxy.ts";
+import { ensureAutoDefault } from "../../plugin/src/selection.ts";
+import { pngC, usualRequest, usualSession } from "./claude-fixtures.ts";
process.env.CAM_LANG = "zh";
const session = "11111111-2222-4333-8444-555555555555";
@@ -86,6 +87,33 @@ test("cam_view_image works only with automatic selection on, and returns the ori
assert.equal(callClaudeTool("cam_view_image", { ids: ["IMG-003"] }, options, { CLAUDE_CODE_SESSION_ID: session }).isError, false);
});
+// v0.6 (user 2026-10-13): automatic selection is on by default in a session started after this version first ran here.
+test("v0.6: a session started after the default began has automatic selection on; one from before keeps its own", () => {
+ const started = (at: string) => {
+ const { options } = setup();
+ // Claude Code stamps its records: the first one says when the session started.
+ const file = join(options.home, "projects", "D--work", `${session}.jsonl`);
+ const records = readFileSync(file, "utf8").trim().split("\n").map((line) => JSON.parse(line));
+ records[0].timestamp = at;
+ writeFileSync(file, records.map((record) => JSON.stringify(record)).join("\n") + "\n");
+ ensureAutoDefault(claudeSelectionDirOf(options.dataRoot), new Date("2026-10-13T00:00:00Z"));
+ return options;
+ };
+ const request = Buffer.from(JSON.stringify({ model: "claude-haiku-5-5", tools: [{ name: "Read", input_schema: { type: "object" } }], messages: usualRequest() }));
+ const fresh = started("2026-10-13T01:00:00Z");
+ const dir = claudeSelectionDirOf(fresh.dataRoot);
+ assert.equal(get(`/__cam/claude/panel?session=${session}`, fresh).body.auto, true);
+ assert.equal(claudeNeedsRewrite(session, dir, fresh.home), true);
+ assert.equal(rewriteClaudeBody(request, undefined, session, dir, fresh.home, {}).report.auto, true);
+ assert.equal(callClaudeTool("cam_view_image", { sessionId: session, ids: ["IMG-003"] }, fresh).isError, false);
+ // Switched off in the panel: written down, and it stays off.
+ assert.equal(post(`/__cam/claude/select?session=${session}`, { auto: false }, fresh).body.auto, false);
+ assert.equal(get(`/__cam/claude/panel?session=${session}`, fresh).body.auto, false);
+ const old = started("2026-10-12T23:00:00Z");
+ assert.equal(get(`/__cam/claude/panel?session=${session}`, old).body.auto, false);
+ assert.equal(claudeNeedsRewrite(session, claudeSelectionDirOf(old.dataRoot), old.home), false);
+});
+
test("the panel page and API answer only requests naming the engine by a loopback name, from no other site", () => {
assert.equal(ownRequest({ host: "localhost:17891" }), true, "the mod: no Origin");
assert.equal(ownRequest({ host: "localhost:17891", origin: "http://localhost:17891" }), true, "the page itself");
diff --git a/spike/src/engine.test.ts b/spike/src/engine.test.ts
index 4b6781d..acc1bd1 100644
--- a/spike/src/engine.test.ts
+++ b/spike/src/engine.test.ts
@@ -16,7 +16,7 @@ import { fileURLToPath } from "node:url";
import { buildOf, compareVersions, countClaudeInPs, countClaudeProcesses, countCodexInPs, countCodexProcesses, engineHealth, ensureEngine, isEngineHealth, shouldReplace, watchForCodex, type Health } from "../../plugin/src/engine.ts";
import { selectionDirOf } from "../../plugin/src/paths.ts";
import { readRequestStats, recordRequest } from "../../plugin/src/request-stats.ts";
-import { writeSelection } from "../../plugin/src/selection.ts";
+import { autoDefaultSince, writeSelection } from "../../plugin/src/selection.ts";
const here = dirname(fileURLToPath(import.meta.url));
const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } };
@@ -56,11 +56,15 @@ test("the engine gives up only after consecutive checks without Codex", async ()
test("ensure starts one engine; a second start on the same port leaves it alone", async (t) => {
const port = 20000 + Math.floor(Math.random() * 20000);
- process.env.CAM_DATA_DIR = mkdtempSync(join(tmpdir(), "cam-engine-"));
+ const data = mkdtempSync(join(tmpdir(), "cam-engine-"));
+ process.env.CAM_DATA_DIR = data;
t.after(() => { delete process.env.CAM_DATA_DIR; });
const first = await ensureEngine({ port, extraArgs: ["--stay"] });
assert.equal(first.state, "started");
t.after(() => { try { process.kill(first.health!.pid); } catch { /* already gone */ } });
+ // v0.6: from now on new tasks and sessions have automatic selection on by default.
+ assert.notEqual(autoDefaultSince(join(data, "selection")), null);
+ assert.notEqual(autoDefaultSince(join(data, "claude", "selection")), null);
const again = await ensureEngine({ port });
assert.deepEqual([again.state, again.health?.pid], ["running", first.health!.pid]);
const second = await new Promise<string>((resolve) => execFile(process.execPath, [join(here, "..", "..", "plugin", "src", "proxy.ts"), "--port", String(port), "--stay"], (_error, stdout) => resolve(stdout)));
diff --git a/spike/src/p2-selftest.ts b/spike/src/p2-selftest.ts
index 962a5f0..cf1d43b 100644
--- a/spike/src/p2-selftest.ts
+++ b/spike/src/p2-selftest.ts
@@ -19,7 +19,7 @@ type Json = Record<string, any>;
const localRoot = join(resolve(dirname(fileURLToPath(import.meta.url)), "../.."), "local");
function setChecked(threadId: string, keys: Record<string, string>, uncheck: string[]): void {
- writeSelection({ threadId, unchecked: Object.fromEntries(uncheck.map((id) => [keys[id], { id, at: new Date().toISOString() }])) });
+ writeSelection({ threadId, unchecked: Object.fromEntries(uncheck.map((id) => [keys[id], { id, at: new Date().toISOString() }])), auto: false });
}
async function main(): Promise<void> {
diff --git a/spike/src/p3-selftest.ts b/spike/src/p3-selftest.ts
index b5fda0e..9c3af91 100644
--- a/spike/src/p3-selftest.ts
+++ b/spike/src/p3-selftest.ts
@@ -87,7 +87,7 @@ async function main(): Promise<void> {
const turns: Json = {};
turns.t1Upload = await runTurn(server, t1, [text("这是两张测试图,先不用描述,只回复“收到”。"), { type: "localImage", path: file("a.png") }, { type: "localImage", path: file("b.png") }]);
turns.t2Upload = await runTurn(server, t2, [text("这是一张测试图,先不用描述,只回复“收到”。"), { type: "localImage", path: file("c.png") }]);
- applySelection(t1, { uncheck: ["IMG-001"] }, { sessionsDir: join(codexHome(), "sessions") });
+ applySelection(t1, { uncheck: ["IMG-001"], auto: false }, { sessionsDir: join(codexHome(), "sessions") });
await sleep(2500);
turns.t1AfterUncheck = await runTurn(server, t1, [text("请只回复“好的”。")]);
turns.t2Normal = await runTurn(server, t2, [text("请只回复“好的”。")]);
diff --git a/spike/src/selection.test.ts b/spike/src/selection.test.ts
index f9d2e1f..b4c1606 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 { effectiveSelection, readSelection, writeSelection } from "../../plugin/src/selection.ts";
+import { autoDefaultSince, effectiveSelection, ensureAutoDefault, readSelection, writeSelection } from "../../plugin/src/selection.ts";
import { startThread } from "./testfixtures.ts";
const PARENT = "01a0d301-0000-7000-8000-0000000000f0";
@@ -89,3 +89,50 @@ test("switched on again after the fork, the switch stays the parent's; first use
assert.equal(effectiveSelection(FORK, later.sessionsDir, later.dir).auto, undefined);
assert.equal(needsRewrite(FORK, later.dir, later.sessionsDir), false);
});
+
+// v0.6 (user 2026-10-13): automatic selection is on by default in a task started after this version first ran here;
+// tasks from before keep what they had. The start time is written once next to the selections.
+test("v0.6: the default's start time is written once and kept", () => {
+ const { dir } = setup();
+ assert.equal(autoDefaultSince(dir), null, "before this version runs, no default");
+ ensureAutoDefault(dir, new Date("2026-09-24T11:00:00Z"));
+ ensureAutoDefault(dir, new Date("2026-09-25T00:00:00Z"));
+ assert.equal(autoDefaultSince(dir), "2026-09-24T11:00:00.000Z");
+});
+
+test("v0.6: a task started after the default began has automatic selection on, unless it has its own switch", () => {
+ const { sessionsDir, dir, rollout } = setup();
+ ensureAutoDefault(dir, new Date("2026-09-24T11:00:00Z"));
+ const NEW = "01a0d301-0000-7000-8000-0000000000f5";
+ rollout(NEW, { timestamp: "2026-09-24T11:30:00Z" });
+ const fresh = effectiveSelection(NEW, sessionsDir, dir);
+ assert.deepEqual([fresh.auto, fresh.autoSince], [true, "2026-09-24T11:30:00Z"]);
+ assert.equal(existsSync(join(dir, `${NEW}.json`)), false, "the default is not written down");
+ assert.equal(needsRewrite(NEW, dir, sessionsDir), true);
+ // Started before (10:00): as before.
+ assert.equal(effectiveSelection(PLAIN, sessionsDir, dir).auto, undefined);
+ assert.equal(needsRewrite(PLAIN, dir, sessionsDir), false);
+ // No rollout yet: a new task.
+ assert.equal(effectiveSelection("01a0d301-0000-7000-8000-0000000000f9", sessionsDir, dir).auto, true);
+ // Its own switch wins, either way.
+ writeSelection({ threadId: NEW, unchecked: {}, auto: false, autoAt: "2026-09-24T11:40:00Z", autoSince: "2026-09-24T11:30:00Z" }, dir);
+ assert.equal(effectiveSelection(NEW, sessionsDir, dir).auto, false);
+ writeSelection({ threadId: PLAIN, unchecked: {}, auto: true, autoAt: "2026-09-24T11:40:00Z", autoSince: "2026-09-24T11:40:00Z" }, dir);
+ assert.equal(effectiveSelection(PLAIN, sessionsDir, dir).auto, true);
+});
+
+test("v0.6: a fork counts from the task it came from", () => {
+ const { sessionsDir, dir, rollout } = setup();
+ ensureAutoDefault(dir, new Date("2026-09-24T11:00:00Z"));
+ const OLD_FORK = "01a0d301-0000-7000-8000-0000000000f6";
+ const NEW = "01a0d301-0000-7000-8000-0000000000f7";
+ const NEW_FORK = "01a0d301-0000-7000-8000-0000000000f8";
+ rollout(OLD_FORK, { forked_from_id: PLAIN, timestamp: "2026-09-24T12:00:00Z" });
+ rollout(NEW, { timestamp: "2026-09-24T11:30:00Z" });
+ rollout(NEW_FORK, { forked_from_id: NEW, timestamp: "2026-09-24T12:00:00Z" });
+ // Forked at 12:00 from tasks that started at 10:00: as before, whether or not anything comes along.
+ assert.equal(effectiveSelection(FORK, sessionsDir, dir).auto, undefined);
+ assert.equal(effectiveSelection(OLD_FORK, sessionsDir, dir).auto, undefined);
+ // Forked from a task that started after: on, like it.
+ assert.equal(effectiveSelection(NEW_FORK, sessionsDir, dir).auto, true);
+});
diff --git a/spike/src/v01-needs-selftest.ts b/spike/src/v01-needs-selftest.ts
index 03b84bd..ee83d56 100644
--- a/spike/src/v01-needs-selftest.ts
+++ b/spike/src/v01-needs-selftest.ts
@@ -148,7 +148,8 @@ async function main(): Promise<void> {
}
if (!index) throw new Error(`thread ${threadId}: its screenshots never showed up in the index`);
const unchecked = Object.fromEntries(index.images.map((image) => [image.key, { id: image.id, at: new Date().toISOString() }]));
- writeSelection({ threadId, unchecked }, selectionDirOf(data));
+ // Manual mode on purpose: from v0.6 a new task has automatic selection on by default.
+ writeSelection({ threadId, unchecked, auto: false }, selectionDirOf(data));
await sleep(2500);
entry.images = index.images.map((image) => `${image.id}:${image.kind}:${image.name ?? "-"}`);
for (const [name, prompt] of questions) entry.turns[name] = await runTurn(server, threadId, [text(prompt)]);
@@ -156,7 +157,7 @@ async function main(): Promise<void> {
// asks again; the model must now answer from the image (GPT-6 Luna kept saying it could not see it).
const asked = askedIn(String(entry.turns[questions[questions.length - 1][0]]?.reply ?? ""));
if (recheck && asked.length) {
- writeSelection({ threadId, unchecked: Object.fromEntries(Object.entries(unchecked).filter(([, value]) => !asked.includes(value.id))) }, selectionDirOf(data));
+ writeSelection({ threadId, unchecked: Object.fromEntries(Object.entries(unchecked).filter(([, value]) => !asked.includes(value.id))), auto: false }, selectionDirOf(data));
await sleep(2500);
entry.rechecked = asked;
entry.turns.recheck = await runTurn(server, threadId, [text(words.recheck)]);
diff --git a/spike/src/v01-placeholder-selftest.ts b/spike/src/v01-placeholder-selftest.ts
index a08b3d9..fc3394c 100644
--- a/spike/src/v01-placeholder-selftest.ts
+++ b/spike/src/v01-placeholder-selftest.ts
@@ -100,7 +100,8 @@ async function main(): Promise<void> {
const index = loadThreadIndex(join(codexHome(), "sessions"), threadId);
const a = index.images.find((image) => image.name === "a.png")!;
result.aId = a.id;
- writeSelection({ threadId, unchecked: { [a.key]: { id: a.id, at: new Date().toISOString() } } }, selectionDirOf(data));
+ // Manual mode on purpose: from v0.6 a new task has automatic selection on by default.
+ writeSelection({ threadId, unchecked: { [a.key]: { id: a.id, at: new Date().toISOString() } }, auto: false }, selectionDirOf(data));
await sleep(2500);
await turn("canYouSee", words.canYouSee);
await turn("recall", words.recall);
@@ -110,7 +111,7 @@ async function main(): Promise<void> {
result.lastRequest = await lastRewrite();
const b = index.images.find((image) => image.name === "b.png")!;
result.bId = b.id;
- writeSelection({ threadId, unchecked: { [b.key]: { id: b.id, at: new Date().toISOString() } } }, selectionDirOf(data));
+ writeSelection({ threadId, unchecked: { [b.key]: { id: b.id, at: new Date().toISOString() } }, auto: false }, selectionDirOf(data));
await sleep(2500);
await turn("recheck", words.recheck);
result.recheckRequest = await lastRewrite();
diff --git a/spike/src/v03-auto-selftest.ts b/spike/src/v03-auto-selftest.ts
index 27198d7..9a23272 100644
--- a/spike/src/v03-auto-selftest.ts
+++ b/spike/src/v03-auto-selftest.ts
@@ -8,7 +8,9 @@
// Thread A asks outright for a fetch; thread B asks questions that need an image or do not; thread C has one image, so
// nothing else in the context can mislead the reading. Each test image hides a digit in a corner that the descriptions
// leave out. Drafts of the wording were tried the same way before it was built, with the rewrite done by a stand-in.
-// Input: [--label name] [--lang zh|en] [--port 17897] [--threads A,B,C]; CAM_TEST_MODEL, CAM_TEST_EFFORT.
+// v0.6 — thread D sets no switch: a new task has automatic selection on by default. Its question needs two images the
+// model has not fetched before, at once (user 2026-10-13: does it fetch every image it needs?).
+// Input: [--label name] [--lang zh|en] [--port 17897] [--threads A,B,C,D]; CAM_TEST_MODEL, CAM_TEST_EFFORT.
// Output: local/v03/auto-<label>.json (synthetic images only).
import { spawn } from "node:child_process";
@@ -64,6 +66,8 @@ const SCRIPT = {
textOnly: "把“今天天气很好”翻译成英文。",
sum: "黄色背景那张图左上角的数字,和 a.png 右下角的数字,加起来是多少?",
corner: "这张图右上角的数字是几?",
+ uploadDescribe: "这是三张测试图。分别用一句话说说它们的背景色和中间的主要形状,只说这两样,不要提角落里的东西。",
+ pair: "a.png 右下角的数字,和紫色背景那张图右上角的数字,加起来是多少?",
recallWords: [/黄/, /圆/],
},
en: {
@@ -79,12 +83,14 @@ const SCRIPT = {
textOnly: "Translate \"今天天气很好\" into English.",
sum: "What do the number in the top-left corner of the yellow image and the number in the bottom-right corner of a.png add up to?",
corner: "What is the number in the top-right corner of this image?",
+ uploadDescribe: "Here are three test images. In one sentence each, give their background color and the main shape in the middle. Only those two things: don't mention anything in the corners.",
+ pair: "What do the number in the bottom-right corner of a.png and the number in the top-right corner of the purple image add up to?",
recallWords: [/yellow/i, /circle|disc|disk/i],
},
};
// A number in the reply, as a numeral or a word, ignoring image ids.
-const NUMBER_WORDS: Record<number, RegExp> = { 3: /三|three/i, 5: /五|five/i, 7: /七|seven/i, 10: /十|ten\b/i };
+const NUMBER_WORDS: Record<number, RegExp> = { 3: /三|three/i, 5: /五|five/i, 7: /七|seven/i, 10: /十|ten\b/i, 12: /十二|twelve/i };
const says = (reply: string, n: number) => {
const clean = reply.replace(/IMG-\d{3}/g, "");
return new RegExp(`(^|[^0-9])${n}([^0-9]|$)`).test(clean) || NUMBER_WORDS[n].test(clean);
@@ -95,7 +101,7 @@ async function main(): Promise<void> {
const label = option("--label", "run1");
const lang: Lang = option("--lang", "zh") === "en" ? "en" : "zh";
const port = Number(option("--port", "17897"));
- const only = option("--threads", "A,B,C").split(",");
+ const only = option("--threads", "A,B,C,D").split(",");
const words = SCRIPT[lang];
const root = join(localRoot, "v03");
const data = join(root, `data-${label}`);
@@ -173,6 +179,13 @@ async function main(): Promise<void> {
turns.corner = await turn(id, words.corner);
return { threadId: id, turns };
},
+ // v0.6: no switch set; described while the images are still this turn's.
+ D: async () => {
+ const id = await start("D");
+ const turns: Json = { upload: await turn(id, words.uploadDescribe, ["a.png", "b.png", "c.png"]) };
+ turns.pair = await turn(id, words.pair);
+ return { threadId: id, turns };
+ },
};
for (const name of only) if (threads[name]) result.threads[name] = await threads[name]();
} finally {
@@ -184,6 +197,7 @@ async function main(): Promise<void> {
const A = result.threads.A?.turns ?? {};
const B = result.threads.B?.turns ?? {};
const C = result.threads.C?.turns ?? {};
+ const D = result.threads.D?.turns ?? {};
const reply = (t: Json) => String(t?.reply ?? "");
const ran = (name: string) => !!result.threads[name];
result.checks = {
@@ -210,7 +224,12 @@ async function main(): Promise<void> {
C_cornerFetchesImg001: C.corner.fetched.includes("IMG-001"),
C_cornerAnswers5: says(reply(C.corner), 5),
} : {}),
- noErrors: [...Object.values(A), ...Object.values(B), ...Object.values(C)].every((t: Json) => t.status === "completed" && !t.errors.length),
+ ...(ran("D") ? {
+ D_onByDefault: !!D.pair.lastRewrite?.auto && ["IMG-001", "IMG-002", "IMG-003"].every((id) => D.pair.lastRewrite.replaced.includes(`${id}:plain`)),
+ D_pairFetchesBoth: ["IMG-001", "IMG-003"].every((id) => D.pair.fetched.includes(id)),
+ D_pairAnswers12: says(reply(D.pair), 12),
+ } : {}),
+ noErrors: [...Object.values(A), ...Object.values(B), ...Object.values(C), ...Object.values(D)].every((t: Json) => t.status === "completed" && !t.errors.length),
};
// Fetching an image it already answered about is not wrong, only slower.
result.notes = { refetched: [A.again?.fetched.length ? "A.again" : null, B.sum?.fetched.includes("IMG-001") ? "B.sum" : null].filter(Boolean) };