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(i18n): 面板、插件服务和发给模型的文字跟随 Codex 的界面语言(简体中文、英文)

chipfighter62d7f646b31b
diff --git a/docs/plan.md b/docs/plan.md
index 132a8d7..7db73e2 100644
--- a/docs/plan.md
+++ b/docs/plan.md
@@ -456,3 +456,28 @@ P1 通过后,再按用户的节奏一步步探索改写。
- 编号和轮次从剩下的部分重新算;
- 引擎也按剩下的部分改写。取消过的图照样换成占位符,认不出的图原样发送。
- 任务自己的最后一段找不到时,仍然当作没有记录。
+
+## 16. 中英文界面(v0.1-14)
+
+### 已查证的事实
+
+- **Codex 把界面语言告诉面板**:MCP 应用规范里,Codex 打开面板时给的 host context 带 `locale`,变了会再发一次。Codex 实际给不给,重装后用 `cam status` 确认(显示语言来自 Codex 还是系统)。
+- **插件清单只能写一种文字**:Codex 的插件清单(codex-rs 的 manifest.rs)里,名称、简介、详细说明都是普通字符串,没有按语言切换的写法。
+- **工具列表在插件服务启动时读取**:标签页标题就是面板工具的 `title`,所以它的语言在插件服务启动时就定了。
+
+### 设计
+
+- **判断语言**(`language.ts`):以 `zh` 开头的都算简体中文,其他都算英文。
+ - 面板:先看 host context 的 `locale`,没有就看浏览器语言。
+ - 面板每次调用都带上语言;读面板数据时还带上“来自 Codex 还是系统”,插件记在数据目录的 `language.json` 里,变了才写。
+ - 引擎(发给模型的文字)和工具列表(标签页标题)读这份记录;没有记录时用系统语言。
+ - 命令行一律按系统语言:POSIX 的 `LC_ALL`、`LC_MESSAGES`、`LANG`,都没有就看运行时报告的语言。
+- **文字表**:
+ - 插件服务和命令行的文字在 `messages.ts`;
+ - 面板的文字在 `panel.html` 里一段 JSON,英文可以多一条 `key_one`(数量为 1 时用);
+ - 发给模型的文字在 `rewrite.ts`,中文原样保留,改动前后逐字节比对过。
+ - 单元测试检查两种语言的条目一一对应、占位的 `{名字}` 也一致。
+- **插件服务返回的文字**:报错和结果按面板带来的语言给出;改写失败的原因改成代码,由面板翻译;和用户设置冲突的报错带一个文字键,面板和命令行各按自己的语言显示。
+- **面板认模型索要**:英文说明让模型回复“need IMG-004”,面板也认带引号的写法。
+- **已知代价**:同一个任务中途切换 Codex 的语言,说明文字会变,模型那边缓存的上下文要重算一次。
+- **验证**:`v01-placeholder-selftest.ts --lang en` 用同样的五轮对话检查英文说明:模型不收回之前的回答,被问到没说过的细节时回复“need IMG-xxx”。
diff --git a/docs/spec.md b/docs/spec.md
index 3a53e60..3b21922 100644
--- a/docs/spec.md
+++ b/docs/spec.md
@@ -43,7 +43,8 @@
- **重复占位符**:包含编号、名称、来源、所在轮次和尺寸,说明它和哪一条(编号、名称、轮次)内容完全相同,那一条照常提供,请参考那一条。内容仍然看得到,不需要上面的说明。
- 占位符里不写本地路径。Codex 附在上传图片前后的路径标签,也一起换掉。
- 勾选状态不变时,占位符和说明的文字、位置每次都一样,不影响缓存。
-- 现行措辞见 `plugin/src/rewrite.ts`,占位符格式用户 2026-09-24 认可,说明是按用户 2026-09-25 的要求加的。以后改措辞,要重新运行 `spike/src/v01-placeholder-selftest.ts`。
+- 现行措辞见 `plugin/src/rewrite.ts`,占位符格式用户 2026-09-24 认可,说明是按用户 2026-09-25 的要求加的。以后改措辞,要重新运行 `spike/src/v01-placeholder-selftest.ts`,中文、英文(`--lang en`)各跑一次。
+- 占位符和说明跟着界面语言:中文界面用上面这版中文,英文界面用意思相同的英文版,模型需要图时回复“need IMG-004”(用户 2026-09-25 定,避免上下文里的语言不一致)。
### 界面
@@ -68,7 +69,12 @@
- 标题右侧是“停用插件”或“启用插件”,两种样式不同。点一下立即生效,不用再确认(用户 2026-09-25 定)。
- 停用或启用后,中间的提示说明要重启 Codex 才生效,另一个按钮随时可以撤回;
- 撤回到 Codex 启动时的状态,就不再提示重启。
-- 以上是用户 2026-09-24 定的 MVP,外加 2026-09-25 要求补上的发送预览、改写失败提示、自动刷新、这两个按钮的位置和名称、标题里的任务名,以及新任务的自动绑定。
+- 语言(用户 2026-09-25 定):
+ - 面板跟随 Codex 的界面语言;Codex 没告诉面板时,看系统语言。
+ - v0.1 支持简体中文和英文:任何地区的中文都显示简体中文,其他语言都显示英文。以后有用户反馈再加其他语言。
+ - Codex 自己显示的名字:插件页上名称和一句话简介用英文(Codex Attachment Manager),详细说明先英文、再附一段中文,因为插件清单只能写一种文字;标签页标题跟着语言(“上下文素材”或 Context Assets)。
+ - 安装命令在终端里的输出,按系统语言。
+- 以上是用户 2026-09-24 定的 MVP,外加 2026-09-25 要求补上的发送预览、改写失败提示、自动刷新、这两个按钮的位置和名称、标题里的任务名、新任务的自动绑定,以及中英文界面。
### 为后续扩展预留
@@ -79,6 +85,7 @@
首版不做下面这些。其中前两项已确认是后续方向。
- 图片以外的文件类型,例如音频、视频、md、docx、xlsx;
+- 简体中文和英文以外的语言,以及面板里手动切换语言(用户 2026-09-25 定:等有用户反馈再说);
- 按文件类型筛选的栏目(全选、只看某一类)和跨任务的素材库;
- 存储清理;
- coding agent 场景,例如省略模型已读过的代码文件;
diff --git a/docs/tasks.md b/docs/tasks.md
index 509ed47..12de58d 100644
--- a/docs/tasks.md
+++ b/docs/tasks.md
@@ -69,6 +69,11 @@
- 和任务里的图片数量、mp3 文件无关。
- [x] **v0.1-13 原任务的记录被彻底删掉时,列出还能找到的图**(用户 2026-09-25 要求;`thread-index.ts`、`panel-state.ts`、`panel.html`;设计见 plan.md 第 15 节;证据:新增 2 个单元测试,面板开发页截图)
- 以前这种情况面板只显示报错;现在列出剩下的图,并提示前面有一段历史找不到了。
+- [x] **v0.1-14 中英文界面**(用户 2026-09-25 定:先做简体中文和英文,其他语言等用户反馈;`language.ts`、`messages.ts`、`panel.html`、`rewrite.ts`;设计见 plan.md 第 16 节;证据:6 个单元测试,面板开发页的中英文截图,英文自测 `local/v01/placeholder-en-run1.json`、`placeholder-en-run2.json`,两次结果一致)
+ - 面板跟随 Codex 的界面语言;发给模型的说明也跟着换,中文原样不动;
+ - 插件页英文为主、附一段中文;标签页标题跟着语言;命令行按系统语言;
+ - 英文自测:模型不收回回答;被问到没说过的细节时回复“need IMG-001”,没有编造。
+ - 待用户重装后确认:Codex 会不会把界面语言告诉面板(`cam status` 看来源)。
- [x] **v0.1-7 许可证和 CI**(用户 2026-09-25 定:MIT,并加上 CI):`LICENSE`(插件目录里也放一份);`.github/workflows/ci.yml` 在 Windows、macOS、Linux 上跑单元测试;问题反馈模板,方便 macOS、Linux 用户在 GitHub 上报问题。
- 待定:Windows 上不先停用就移除插件,Codex 会断连,只能靠卸载命令恢复;要不要用计划任务让引擎不依赖插件启动,见 spec.md 第 5 节。
diff --git a/plugin/.codex-plugin/plugin.json b/plugin/.codex-plugin/plugin.json
index 7b143a4..61db3e5 100644
--- a/plugin/.codex-plugin/plugin.json
+++ b/plugin/.codex-plugin/plugin.json
@@ -11,9 +11,9 @@
"keywords": ["codex", "images", "context", "attachments", "mcp-app", "proxy"],
"mcpServers": "./.mcp.json",
"interface": {
- "displayName": "上下文素材管理器",
- "shortDescription": "选择哪些历史图片随下一条消息发给模型",
- "longDescription": "长任务里的图片会一轮轮累积在上下文里。这个插件在 Codex 右侧的侧边面板里,按时间顺序列出任务历史里的全部图片:勾选的照常发送,取消的换成占位符(有内容相同的图还在发送时,指向那一张)。任务不换,对话连续。模型需要某张图时会回复“需要 IMG-xxx”,给不给由你决定。所有数据只留在本机;除了 Codex 本来就要发给 OpenAI 的请求,不向任何地方发送数据。装好后打开面板(侧边面板 → 新建标签页 → 插件和 MCP → 上下文素材),点“启用”,再重启 Codex。移除插件前,请先在面板里点“停用”。",
+ "displayName": "Codex Attachment Manager",
+ "shortDescription": "Choose which past images go to the model with your next message",
+ "longDescription": "In long tasks, images pile up in the context turn after turn. This plugin lists every image in the task's history, in order, in Codex's side panel: checked images are sent as usual, unchecked ones become short placeholders (pointing to an identical image when one is still being sent). The task stays the same and the conversation goes on. When the model needs an image, it replies \"need IMG-xxx\", and you decide whether to send it. All data stays on your machine; nothing is sent anywhere besides the requests Codex already makes to OpenAI. After installing, open the panel (side panel → New tab → Plugins and MCP → Context Assets), click \"Enable plugin\", then restart Codex. Before removing the plugin, click \"Disable plugin\" in the panel first. The panel follows Codex's language: Simplified Chinese or English.\n\n长任务里的图片会一轮轮累积在上下文里。这个插件在 Codex 右侧的侧边面板里,按时间顺序列出任务历史里的全部图片:勾选的照常发送,取消的换成占位符(有内容相同的图还在发送时,指向那一张)。任务不换,对话连续。模型需要某张图时会回复“需要 IMG-xxx”,给不给由你决定。所有数据只留在本机;除了 Codex 本来就要发给 OpenAI 的请求,不向任何地方发送数据。装好后打开面板(侧边面板 → 新建标签页 → 插件和 MCP → 上下文素材),点“启用插件”,再重启 Codex。移除插件前,请先在面板里点“停用插件”。面板跟随 Codex 的界面语言,支持简体中文和英文。",
"developerName": "chipfighter",
"category": "Productivity",
"capabilities": ["Interactive", "Read", "Write"],
diff --git a/plugin/src/binding.ts b/plugin/src/binding.ts
index 9307d59..c0c89c4 100644
--- a/plugin/src/binding.ts
+++ b/plugin/src/binding.ts
@@ -57,7 +57,7 @@ export function boundThread(threadId: string, dir = bindingsDirOf()): string | n
}
export function bindThread(threadId: string, target: string, dir = bindingsDirOf()): void {
- if (!THREAD_ID.test(threadId) || !THREAD_ID.test(target)) throw new Error("不是任务编号");
+ if (!THREAD_ID.test(threadId) || !THREAD_ID.test(target)) throw new Error("not a thread id");
mkdirSync(dir, { recursive: true });
const file = join(dir, `${threadId}.json`);
writeFileSync(`${file}.tmp`, JSON.stringify({ threadId: target, at: new Date().toISOString() }));
diff --git a/plugin/src/cam.ts b/plugin/src/cam.ts
index d2513c3..d7c02fb 100644
--- a/plugin/src/cam.ts
+++ b/plugin/src/cam.ts
@@ -6,6 +6,7 @@
// Codex is never left pointed at an engine that nothing would start.
// v0.1-5: setup, run from the copy Codex installed (the install scripts do this after Codex's own command line added
// the plugin), points Codex at the engine and starts it. The settings themselves are switched in setup.ts.
+// v0.1-14: it speaks the system language (messages.ts); status shows the language the panel reported.
// Input: install [--port N] | setup [--port N] | uninstall | status | list|uncheck|check|check-all <thread id> [IMG-…].
// Output: config.toml (copied to <data dir>/config-backup/ before every change), ~/.codex/.env (never copied or
// printed: it may hold credentials), the plugin cache (through Codex's command line), the selection files, and a
@@ -19,13 +20,21 @@ import { findCodexCli, runCodex } from "./codexcli.ts";
import { codexHome, MCP_BEGIN, noProxyStatus, proxyStatus } from "./codexconfig.ts";
import { buildOf, DEFAULT_PORT, engineHealth, ensureEngine } from "./engine.ts";
import { isEntryPoint } from "./entry.ts";
+import { storedLang, systemLang } from "./language.ts";
+import { say, type MessageKey } from "./messages.ts";
import { MARKETPLACE, PLUGIN, PLUGIN_ID, planInstall, pluginStatus } from "./install.ts";
import { applySelection, loadPanelState, type PanelState } from "./panel-state.ts";
import { dataDir, selectionDirOf } from "./paths.ts";
import { backupConfig, connectDirectly, readConfig, readEnv, useEngine, userProxyEnv } from "./setup.ts";
type Json = Record<string, any>;
-const KIND: Record<string, string> = { upload: "上传", view: "工具查看", generated: "生成", tool: "工具结果" };
+const lang = systemLang();
+const t = (key: MessageKey, vars?: Record<string, string | number>) => say(lang, key, vars);
+// A conflict with the user's settings (codexconfig.ts) comes with a message key.
+const localized = (error: unknown) => {
+ const known = error as { key?: MessageKey; vars?: Record<string, string> };
+ return known?.key ? new Error(t(known.key, known.vars)) : error;
+};
// This file lives in <repository>/plugin/src; the repository root is the marketplace.
const repository = resolve(import.meta.dirname, "..", "..");
const pluginVersion = (): string => JSON.parse(readFileSync(resolve(import.meta.dirname, "..", ".codex-plugin", "plugin.json"), "utf8")).version;
@@ -34,19 +43,19 @@ export const pluginCacheDir = (version: string) => join(codexHome(), "plugins",
function table(state: PanelState): string {
const rows = state.images.map((image) => [
image.id,
- !image.replaceable ? "锁定" : image.checked ? "勾选" : "取消",
- KIND[image.kind] ?? image.kind,
+ t(!image.replaceable ? "cli.state.locked" : image.checked ? "cli.state.checked" : "cli.state.unchecked"),
+ ["upload", "view", "generated", "tool"].includes(image.kind) ? t(`cli.kind.${image.kind}` as MessageKey) : image.kind,
image.name ?? "—",
image.turn ?? "—",
image.width && image.height ? `${image.width}×${image.height}` : "—",
`${(image.bytes / 1024).toFixed(0)} KB`,
image.sameAs.join(",") || "—",
- image.requested ? "模型索要" : "",
+ image.requested ? t("cli.requested") : "",
].join(" | "));
const mb = (bytes: number) => (bytes / 1e6).toFixed(2);
return [
- `任务 ${state.threadId}:${state.totals.images} 张图,${state.turns} 轮;取消 ${state.totals.unchecked} 张;勾选的图共 ${mb(state.totals.checkedBytes)} MB(全部勾选时 ${mb(state.totals.allBytes)} MB)`,
- "编号 | 状态 | 来源 | 名称 | 轮次 | 尺寸 | 大小 | 内容相同 | 备注",
+ t("cli.table.title", { thread: state.threadId, images: state.totals.images, turns: state.turns, unchecked: state.totals.unchecked, checkedMb: mb(state.totals.checkedBytes), allMb: mb(state.totals.allBytes) }),
+ t("cli.table.header"),
...rows,
].join("\n");
}
@@ -59,7 +68,7 @@ const samePath = (a: string, b: string) => {
function codex(cli: string, args: string[]): string {
const { ok, output } = runCodex(cli, args);
- if (!ok) throw new Error(`codex ${args.join(" ")} 失败:${output || "没有输出"}`);
+ if (!ok) throw new Error(t("cli.codexFailed", { args: args.join(" "), output: output || t("cli.noOutput") }));
return output;
}
@@ -85,7 +94,7 @@ export function selfTest(dir: string, timeoutMs = 20_000): Promise<{ ok: boolean
child.stdin.end();
done(result);
};
- const timer = setTimeout(() => finish({ ok: false, tools: [], error: `没有在 ${timeoutMs / 1000} 秒内响应。${errors.trim()}` }), timeoutMs);
+ const timer = setTimeout(() => finish({ ok: false, tools: [], error: t("cli.selfTest.timeout", { seconds: timeoutMs / 1000, errors: errors.trim() }) }), timeoutMs);
child.stderr.on("data", (chunk: Buffer) => { errors += chunk.toString("utf8"); });
child.on("error", (error) => finish({ ok: false, tools: [], error: String(error) }));
child.stdout.on("data", (chunk: Buffer) => {
@@ -99,7 +108,7 @@ export function selfTest(dir: string, timeoutMs = 20_000): Promise<{ ok: boolean
if (replies.has(3)) {
const tools = (replies.get(2)?.result?.tools ?? []).map((tool: Json) => tool.name);
const page = replies.get(3)?.result?.contents?.[0]?.text ?? "";
- finish(tools.includes("cam_panel") && page.includes("<title>") ? { ok: true, tools, error: null } : { ok: false, tools, error: "工具或面板页面不完整" });
+ finish(tools.includes("cam_panel") && page.includes("<title>") ? { ok: true, tools, error: null } : { ok: false, tools, error: t("cli.selfTest.incomplete") });
}
});
const send = (message: Json) => child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`);
@@ -131,50 +140,52 @@ async function main(): Promise<void> {
const port = Number(process.argv.includes("--port") ? process.argv[process.argv.indexOf("--port") + 1] : process.env.CAM_ENGINE_PORT ?? DEFAULT_PORT);
if (command === "install") {
- if (!existsSync(join(repository, ".agents", "plugins", "marketplace.json"))) throw new Error("请在仓库里运行:node plugin/src/cam.ts install");
+ if (!existsSync(join(repository, ".agents", "plugins", "marketplace.json"))) throw new Error(t("cli.runInRepo"));
const cli = findCodexCli();
- if (!cli) throw new Error("找不到 Codex 的命令行。请先安装 Codex 桌面版并至少打开过一次,或者安装 Codex 命令行;也可以用环境变量 CODEX_CLI_PATH 指定它的位置。");
+ if (!cli) throw new Error(t("cli.noCli"));
// A conflict with the user's own settings stops everything before anything changes.
- planInstall({ configText: readConfig(), envText: readEnv(), env: userProxyEnv(), port });
+ try { planInstall({ configText: readConfig(), envText: readEnv(), env: userProxyEnv(), port }); } catch (error) { throw localized(error); }
backupConfig();
const steps: string[] = [];
const registered = pluginStatus(readConfig()).marketplace;
- if (registered && !samePath(registered, repository)) { codex(cli, ["plugin", "marketplace", "remove", MARKETPLACE]); steps.push("去掉指向别处的旧插件市场"); }
- if (!registered || !samePath(registered, repository)) { codex(cli, ["plugin", "marketplace", "add", repository]); steps.push("登记插件市场(这个仓库)"); }
+ if (registered && !samePath(registered, repository)) { codex(cli, ["plugin", "marketplace", "remove", MARKETPLACE]); steps.push(t("cli.step.oldMarketplace")); }
+ if (!registered || !samePath(registered, repository)) { codex(cli, ["plugin", "marketplace", "add", repository]); steps.push(t("cli.step.addMarketplace")); }
// Installed afresh every time, so Codex's copy matches this checkout.
- if (pluginStatus(readConfig()).installed) { codex(cli, ["plugin", "remove", PLUGIN_ID]); steps.push("卸掉旧的插件副本"); }
+ if (pluginStatus(readConfig()).installed) { codex(cli, ["plugin", "remove", PLUGIN_ID]); steps.push(t("cli.step.oldPlugin")); }
codex(cli, ["plugin", "add", PLUGIN_ID]);
- steps.push("安装插件");
+ steps.push(t("cli.step.install"));
const installed = pluginCacheDir(pluginVersion());
const test = await selfTest(installed);
- if (!test.ok) throw new Error(`装好的插件服务没能启动:${test.error}。代理设置没有写入,Codex 仍然直连。`);
- steps.push(`自检通过:插件服务能启动,提供 ${test.tools.join("、")}`);
+ if (!test.ok) throw new Error(t("cli.selfTest.failed", { error: test.error ?? "" }));
+ steps.push(t("cli.step.selfTest", { tools: test.tools.join(t("cli.list")) }));
const plan = useEngine(port);
const migrated = migrateSelections();
// The installed copy runs the engine, as it will when Codex starts it; an older engine still running is replaced.
const engine = await ensureEngine({ port, dir: join(installed, "src") });
- console.log(JSON.stringify({ command, steps, configChanged: plan.configChanged, envChanged: plan.envChanged, notes: plan.notes, migratedSelections: migrated, dataDir: dataDir(), engine: engine.state, enginePid: engine.health?.pid ?? null, next: "重启 Codex 后生效。面板在任务右侧的侧边面板:新建标签页 → 插件和 MCP → 上下文素材" }, null, 2));
+ console.log(JSON.stringify({ command, steps, configChanged: plan.configChanged, envChanged: plan.envChanged, notes: plan.notes, migratedSelections: migrated, dataDir: dataDir(), engine: engine.state, enginePid: engine.health?.pid ?? null, next: t("cli.next.install") }, null, 2));
return;
}
if (command === "setup") {
// Only once Codex has the plugin: otherwise nothing would start the engine after Codex restarts.
- if (!pluginStatus(readConfig()).installed || !existsSync(pluginCacheDir(pluginVersion()))) throw new Error("插件还没有装进 Codex:请先安装插件,再运行 setup。");
- const plan = useEngine(port);
+ if (!pluginStatus(readConfig()).installed || !existsSync(pluginCacheDir(pluginVersion()))) throw new Error(t("cli.notInstalled"));
+ let plan;
+ try { plan = useEngine(port); } catch (error) { throw localized(error); }
// Started from this copy, which is the installed one when the install scripts run it.
const engine = await ensureEngine({ port });
- console.log(JSON.stringify({ command, configChanged: plan.configChanged, envChanged: plan.envChanged, notes: plan.notes, dataDir: dataDir(), engine: engine.state, enginePid: engine.health?.pid ?? null, next: "重启 Codex 后生效。面板在任务右侧的侧边面板:新建标签页 → 插件和 MCP → 上下文素材" }, null, 2));
+ console.log(JSON.stringify({ command, configChanged: plan.configChanged, envChanged: plan.envChanged, notes: plan.notes, dataDir: dataDir(), engine: engine.state, enginePid: engine.health?.pid ?? null, next: t("cli.next.install") }, null, 2));
return;
}
if (command === "uninstall") {
// Codex goes back to connecting directly first; only then is the plugin that starts the engine removed.
- const plan = connectDirectly();
- const steps = ["恢复直连:去掉代理设置" + (plan.envChanged ? "和 .env 里的 NO_PROXY" : "")];
+ let plan;
+ try { plan = connectDirectly(); } catch (error) { throw localized(error); }
+ const steps = [t(plan.envChanged ? "cli.step.directEnv" : "cli.step.direct")];
const cli = findCodexCli();
const status = pluginStatus(readConfig());
- if (!cli && (status.installed || status.marketplace)) steps.push("找不到 Codex 的命令行,插件没有卸载;可以在 Codex 的插件页面里移除");
- if (cli && status.installed) { codex(cli, ["plugin", "remove", PLUGIN_ID]); steps.push("卸载插件"); }
- if (cli && status.marketplace) { codex(cli, ["plugin", "marketplace", "remove", MARKETPLACE]); steps.push("去掉插件市场"); }
- console.log(JSON.stringify({ command, steps, configChanged: plan.configChanged, envChanged: plan.envChanged, dataDir: dataDir(), next: "重启 Codex 后生效;引擎会在 Codex 全部退出后自己退出。勾选记录留在数据目录里,不需要可以删掉" }, null, 2));
+ if (!cli && (status.installed || status.marketplace)) steps.push(t("cli.step.noCli"));
+ if (cli && status.installed) { codex(cli, ["plugin", "remove", PLUGIN_ID]); steps.push(t("cli.step.removePlugin")); }
+ if (cli && status.marketplace) { codex(cli, ["plugin", "marketplace", "remove", MARKETPLACE]); steps.push(t("cli.step.removeMarketplace")); }
+ console.log(JSON.stringify({ command, steps, configChanged: plan.configChanged, envChanged: plan.envChanged, dataDir: dataDir(), next: t("cli.next.uninstall") }, null, 2));
return;
}
if (command === "status") {
@@ -189,6 +200,8 @@ async function main(): Promise<void> {
dotenv: noProxyStatus(readEnv() ?? ""),
engine: health ? { running: true, pid: health.pid, startedAt: health.startedAt, version: health.version ?? null, build: health.build ?? null, sameAsInstalled: health.build === buildOf(join(pluginCacheDir(version), "src")) } : { running: false },
codexCli: findCodexCli(),
+ // Codex's interface language as the panel last reported it; the text for the model follows it.
+ language: storedLang() ?? { lang: systemLang(), source: "system", note: t("cli.language.notReported") },
dataDir: dataDir(),
}, null, 2));
return;
diff --git a/plugin/src/codexconfig.ts b/plugin/src/codexconfig.ts
index d2a2d3e..52e0e2b 100644
--- a/plugin/src/codexconfig.ts
+++ b/plugin/src/codexconfig.ts
@@ -11,6 +11,10 @@ import { execFileSync } from "node:child_process";
import { homedir } from "node:os";
import { join } from "node:path";
+// v0.1-14: a conflict with the user's settings carries a message key (messages.ts), so the panel and the command line
+// can say it in the user's language; the message itself stays English for logs.
+const conflict = (message: string, key: string, vars: Record<string, string> = {}) => Object.assign(new Error(message), { key, vars });
+
export const BEGIN = "# >>> codex-attachment-manager: managed proxy setting, remove it with the tool >>>";
export const END = "# <<< codex-attachment-manager <<<";
@@ -65,7 +69,7 @@ export function disableMcpServer(text: string): { text: string; changed: boolean
export function enableMcpServer(text: string, name: string, command: string, args: string[]): { text: string; changed: boolean } {
const { bom, body, eol } = parts(disableMcpServer(text).text);
- if (body.split(eol).some((line) => line.trim() === `[mcp_servers.${name}]`)) throw new Error(`config.toml already defines mcp_servers.${name}; not overwriting it`);
+ if (body.split(eol).some((line) => line.trim() === `[mcp_servers.${name}]`)) throw conflict(`config.toml already defines mcp_servers.${name}; not overwriting it`, "conflict.mcpServer", { name });
// JSON string syntax is valid TOML basic-string syntax, including backslashes in Windows paths.
const block = [MCP_BEGIN, `[mcp_servers.${name}]`, `command = ${JSON.stringify(command)}`, `args = ${JSON.stringify(args)}`, 'default_tools_approval_mode = "approve"', END];
const next = bom + body + (body === "" || body.endsWith(eol) ? "" : eol) + block.join(eol) + eol;
@@ -80,7 +84,7 @@ function removeBlocks(text: string, begin: string): { text: string; changed: boo
for (let i = 0; i < lines.length; i++) {
if (lines[i].trim() !== begin) { kept.push(lines[i]); continue; }
const end = lines.findIndex((line, j) => j > i && line.trim() === END);
- if (end < 0) throw new Error("a managed block in config.toml has no end marker");
+ if (end < 0) throw conflict("a managed block in config.toml has no end marker", "conflict.noEnd");
const atTop = kept.length === 0;
i = end;
if (atTop && lines[i + 1] === "") i++;
@@ -94,9 +98,9 @@ function removeBlocks(text: string, begin: string): { text: string; changed: boo
export function enableProxy(text: string, url: string): { text: string; changed: boolean } {
const { bom, body, eol } = parts(disableProxy(text).text);
const lines = body.split(eol);
- if (topLevelValue(lines, "openai_base_url") !== null) throw new Error("config.toml already sets openai_base_url; not overwriting it");
+ if (topLevelValue(lines, "openai_base_url") !== null) throw conflict("config.toml already sets openai_base_url; not overwriting it", "conflict.baseUrl");
const own = userRespectSystemProxy(lines);
- if (own !== null && own !== "true") throw new Error("config.toml turns respect_system_proxy off; not overriding it");
+ if (own !== null && own !== "true") throw conflict("config.toml turns respect_system_proxy off; not overriding it", "conflict.systemProxy");
const header = featuresHeader(lines);
const top = [BEGIN, `openai_base_url = "${url}"`];
if (own === null && header < 0) top.push("features.respect_system_proxy = true");
@@ -142,7 +146,7 @@ export function coversLoopback(value: string | null): boolean {
// The block goes first, like in config.toml, so disableProxy removes it and the blank line after it.
export function enableNoProxy(text: string, value: string): { text: string; changed: boolean } {
const { bom, body, eol } = parts(disableProxy(text).text);
- if (body.split(eol).some((line) => NO_PROXY_LINE.test(line))) throw new Error(".env already sets NO_PROXY; not overriding it");
+ if (body.split(eol).some((line) => NO_PROXY_LINE.test(line))) throw conflict(".env already sets NO_PROXY; not overriding it", "conflict.noProxy");
const next = bom + [BEGIN, `NO_PROXY=${value}`, END, ""].join(eol) + eol + body;
return { text: next, changed: next !== text };
}
diff --git a/plugin/src/install.ts b/plugin/src/install.ts
index 0f3eb92..64b9724 100644
--- a/plugin/src/install.ts
+++ b/plugin/src/install.ts
@@ -2,10 +2,12 @@
// config.toml gets the proxy settings; ~/.codex/.env gets NO_PROXY only when the user's environment proxy would
// otherwise swallow requests to this machine. Uninstall removes exactly those blocks.
// P5 — the MCP server now comes with the plugin, which Codex's own command line installs (see cam.ts); an MCP server
-// block left by an earlier install is removed here.
+// block left by an earlier install is removed here. v0.1-14 — notes in the system language (the command line's reader).
// Input: current texts and the user's persisted proxy variables. Output: next texts (envText null = delete the file).
import { coversLoopback, disableMcpServer, disableProxy, enableNoProxy, enableProxy, noProxyValue } from "./codexconfig.ts";
+import { systemLang } from "./language.ts";
+import { say } from "./messages.ts";
export const PLUGIN = "codex-attachment-manager";
export const MARKETPLACE = "codex-attachment-manager";
@@ -25,14 +27,14 @@ export function planInstall(input: { configText: string; envText: string | null;
const notes: string[] = [];
const proxied = enableProxy(input.configText, `http://localhost:${input.port}/backend-api/codex`);
const legacy = disableMcpServer(proxied.text);
- if (legacy.changed) notes.push("去掉旧版写进 config.toml 的插件服务:现在由插件自己提供");
+ if (legacy.changed) notes.push(say(systemLang(), "note.legacyMcp"));
let envText = input.envText;
let envChanged = false;
if (needsNoProxy(input.env)) {
const next = enableNoProxy(input.envText ?? "", noProxyValue(input.env.noProxy));
envText = next.text;
envChanged = next.changed;
- notes.push("写入 .env 的 NO_PROXY:环境变量里有代理,而且没有覆盖本机地址");
+ notes.push(say(systemLang(), "note.noProxy"));
} else {
// A block from an earlier install is no longer needed.
const cleared = input.envText === null ? { text: null, changed: false } : disableProxy(input.envText);
diff --git a/plugin/src/language.ts b/plugin/src/language.ts
new file mode 100644
index 0000000..cf83392
--- /dev/null
+++ b/plugin/src/language.ts
@@ -0,0 +1,63 @@
+// Purpose: v0.1-14 — which language the plugin speaks: Simplified Chinese or English (user 2026-09-25: these two for
+// v0.1; Chinese of any region gets Simplified Chinese, every other language gets English). The panel learns Codex's
+// interface language and reports it with its calls; it is kept in the data directory, where the engine (the text for
+// the model) and the plugin service (the tab's title) read it. Until a panel has reported one, the system language
+// counts; the command line always follows the system language.
+// Input: language tags (BCP 47 or POSIX, e.g. "zh-CN", "zh_TW.UTF-8", "en-US"), the environment, the data directory.
+// Output: "zh" | "en"; <data dir>/language.json = { "lang": "zh", "source": "codex" | "system", "at": "…" }.
+
+import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { dataDir } from "./paths.ts";
+
+export type Lang = "zh" | "en";
+// codex: the panel got Codex's interface language; system: it only had the system's.
+export type LangSource = "codex" | "system";
+type Stored = { lang: Lang; source: LangSource; at: string };
+
+export function langOf(tag: unknown): Lang | null {
+ if (typeof tag !== "string") return null;
+ const value = tag.trim().toLowerCase();
+ if (!value || value === "c" || value === "posix" || value.startsWith("c.")) return null;
+ return value.startsWith("zh") ? "zh" : "en";
+}
+
+// POSIX locale variables when set (macOS, Linux, some Windows shells), else what the runtime reports (Windows).
+export function systemLang(env: NodeJS.ProcessEnv = process.env): Lang {
+ for (const name of ["LC_ALL", "LC_MESSAGES", "LANG"]) {
+ const lang = langOf(env[name]);
+ if (lang) return lang;
+ }
+ return langOf(Intl.DateTimeFormat().resolvedOptions().locale) ?? "en";
+}
+
+export const languageFileOf = (root = dataDir()) => join(root, "language.json");
+let cache: { file: string; mtimeMs: number; value: Stored | null } | null = null;
+
+export function storedLang(file = languageFileOf()): Stored | null {
+ try {
+ const { mtimeMs } = statSync(file);
+ if (cache?.file === file && cache.mtimeMs === mtimeMs) return cache.value;
+ const raw = JSON.parse(readFileSync(file, "utf8"));
+ const lang = raw?.lang === "zh" || raw?.lang === "en" ? (raw.lang as Lang) : null;
+ const value: Stored | null = lang ? { lang, source: raw.source === "codex" ? "codex" : "system", at: String(raw.at ?? "") } : null;
+ cache = { file, mtimeMs, value };
+ return value;
+ } catch {
+ return null;
+ }
+}
+
+// Written only when it changes, whole file then renamed, so readers never see half of it.
+export function rememberLang(lang: Lang, source: LangSource, file = languageFileOf()): void {
+ const known = storedLang(file);
+ if (known?.lang === lang && known.source === source) return;
+ mkdirSync(dirname(file), { recursive: true });
+ writeFileSync(`${file}.tmp`, JSON.stringify({ lang, source, at: new Date().toISOString() }));
+ renameSync(`${file}.tmp`, file);
+ cache = null;
+}
+
+export function currentLang(file = languageFileOf()): Lang {
+ return storedLang(file)?.lang ?? systemLang();
+}
diff --git a/plugin/src/messages.ts b/plugin/src/messages.ts
new file mode 100644
index 0000000..31ff7c4
--- /dev/null
+++ b/plugin/src/messages.ts
@@ -0,0 +1,155 @@
+// Purpose: v0.1-14 — the plugin's own words in Simplified Chinese and English: Codex's tool list and the panel's tab
+// title, results and refusals of the panel's calls, conflicts with the user's settings, and the command line. The
+// panel page keeps its texts in panel.html, and the text for the model is in rewrite.ts. Every key exists in both
+// languages (a unit test checks it), so changing a text means changing both.
+// Input: a language and a key, with {name} values filled in. Output: strings.
+
+import type { Lang } from "./language.ts";
+
+const zh = {
+ // Codex's tool list; the panel tool's title is the tab's title.
+ "tool.threadId": "任务 ID;面板调用时由 Codex 自动带上。",
+ "tool.shown": "面板页面显示在屏幕上的时间段(毫秒);面板调用时带上。",
+ "tool.lang": "面板显示的语言(zh 或 en);面板调用时带上。",
+ "tool.panel.title": "上下文素材",
+ "tool.panel.description": "上下文素材面板:查看这个任务里的历史图片,勾选下一条消息要发给模型的图片。由用户在侧边面板里打开,模型不需要调用。",
+ "tool.select.title": "上下文素材:勾选",
+ "tool.select.description": "素材面板内部使用:勾选或取消图片。只有用户能操作,模型调用会被拒绝。",
+ "tool.image.title": "上下文素材:图片",
+ "tool.image.description": "素材面板内部使用:读取一张图片的缩略图或预览图。模型不需要调用。",
+ "tool.setup.title": "上下文素材:启用或停用",
+ "tool.setup.description": "素材面板内部使用:让 Codex 经过本机代理(启用),或者恢复直连(停用),重启 Codex 后生效。只有用户能操作,模型调用会被拒绝。",
+ "tool.bind.title": "上下文素材:切到新任务",
+ "tool.bind.description": "素材面板内部使用:在新任务发出第一条消息之前打开的面板,切到用户刚开始的那个任务。只有用户能操作,模型调用会被拒绝。",
+ "server.title": "上下文素材管理器",
+ "resource.name": "上下文素材面板",
+ // Results and refusals of calls (a refusal of the model's call is read by the model).
+ "call.noThread": "不知道是哪个任务:缺少 threadId",
+ "call.summary": "共 {images} 张图,取消了 {unchecked} 张。",
+ "call.modelSelect": "只有用户能勾选或取消图片;需要某张图时,请回复“需要 IMG-xxx”。",
+ "call.modelSetup": "只有用户能启用或停用。",
+ "call.modelBind": "只有用户能切换面板对应的任务。",
+ "call.started": "这个面板的任务已经开始了,不用切换。",
+ "call.notUserThread": "只能切到用户自己开始的任务。",
+ "call.enabled": "已启用,重启 Codex 后生效。",
+ "call.disabled": "已停用,重启 Codex 后恢复直连。",
+ "call.imageOk": "ok",
+ "call.imageNone": "无法显示",
+ // A setting of the user's that the tool does not overwrite (codexconfig.ts).
+ "conflict.baseUrl": "config.toml 里已经设置了 openai_base_url,没有覆盖它。",
+ "conflict.systemProxy": "config.toml 关掉了 respect_system_proxy,没有改动它。",
+ "conflict.noProxy": ".env 里已经设置了 NO_PROXY,没有覆盖它。",
+ "conflict.mcpServer": "config.toml 里已经有名为 {name} 的 MCP 服务,没有覆盖它。",
+ "conflict.noEnd": "config.toml 里有一段带标记的设置缺少结束标记,没有改动。",
+ // Notes of an install or setup (install.ts).
+ "note.legacyMcp": "去掉旧版写进 config.toml 的插件服务:现在由插件自己提供",
+ "note.noProxy": "写入 .env 的 NO_PROXY:环境变量里有代理,而且没有覆盖本机地址",
+ // The command line (cam.ts).
+ "cli.kind.upload": "上传",
+ "cli.kind.view": "工具查看",
+ "cli.kind.generated": "生成",
+ "cli.kind.tool": "工具结果",
+ "cli.state.locked": "锁定",
+ "cli.state.checked": "勾选",
+ "cli.state.unchecked": "取消",
+ "cli.requested": "模型索要",
+ "cli.table.title": "任务 {thread}:{images} 张图,{turns} 轮;取消 {unchecked} 张;勾选的图共 {checkedMb} MB(全部勾选时 {allMb} MB)",
+ "cli.table.header": "编号 | 状态 | 来源 | 名称 | 轮次 | 尺寸 | 大小 | 内容相同 | 备注",
+ "cli.codexFailed": "codex {args} 失败:{output}",
+ "cli.noOutput": "没有输出",
+ "cli.selfTest.timeout": "没有在 {seconds} 秒内响应。{errors}",
+ "cli.selfTest.incomplete": "工具或面板页面不完整",
+ "cli.selfTest.failed": "装好的插件服务没能启动:{error}。代理设置没有写入,Codex 仍然直连。",
+ "cli.runInRepo": "请在仓库里运行:node plugin/src/cam.ts install",
+ "cli.noCli": "找不到 Codex 的命令行。请先安装 Codex 桌面版并至少打开过一次,或者安装 Codex 命令行;也可以用环境变量 CODEX_CLI_PATH 指定它的位置。",
+ "cli.notInstalled": "插件还没有装进 Codex:请先安装插件,再运行 setup。",
+ "cli.step.oldMarketplace": "去掉指向别处的旧插件市场",
+ "cli.step.addMarketplace": "登记插件市场(这个仓库)",
+ "cli.step.oldPlugin": "卸掉旧的插件副本",
+ "cli.step.install": "安装插件",
+ "cli.step.selfTest": "自检通过:插件服务能启动,提供 {tools}",
+ "cli.step.direct": "恢复直连:去掉代理设置",
+ "cli.step.directEnv": "恢复直连:去掉代理设置和 .env 里的 NO_PROXY",
+ "cli.step.noCli": "找不到 Codex 的命令行,插件没有卸载;可以在 Codex 的插件页面里移除",
+ "cli.step.removePlugin": "卸载插件",
+ "cli.step.removeMarketplace": "去掉插件市场",
+ "cli.list": "、",
+ "cli.next.install": "重启 Codex 后生效。面板在任务右侧的侧边面板:新建标签页 → 插件和 MCP → 上下文素材",
+ "cli.next.uninstall": "重启 Codex 后生效;引擎会在 Codex 全部退出后自己退出。勾选记录留在数据目录里,不需要可以删掉",
+ "cli.language.notReported": "还没有面板报告过 Codex 的界面语言,暂用系统语言",
+};
+
+const en: Record<keyof typeof zh, string> = {
+ "tool.threadId": "Task ID; Codex adds it when the panel calls.",
+ "tool.shown": "When the panel page was on screen (ms); the panel sends it.",
+ "tool.lang": "The panel's language (zh or en); the panel sends it.",
+ "tool.panel.title": "Context Assets",
+ "tool.panel.description": "Context Assets panel: see the images in this task's history and choose which go to the model with the next message. The user opens it from the side panel; the model does not need to call it.",
+ "tool.select.title": "Context Assets: check",
+ "tool.select.description": "Used by the panel: check or uncheck images. Only the user can do this; calls from the model are refused.",
+ "tool.image.title": "Context Assets: image",
+ "tool.image.description": "Used by the panel: read an image's thumbnail or preview. The model does not need to call it.",
+ "tool.setup.title": "Context Assets: enable or disable",
+ "tool.setup.description": "Used by the panel: route Codex through the local proxy (enable) or connect directly again (disable); takes effect after Codex restarts. Only the user can do this; calls from the model are refused.",
+ "tool.bind.title": "Context Assets: switch to the new task",
+ "tool.bind.description": "Used by the panel: a panel opened on a new chat before its first message switches to the task the user just started. Only the user can do this; calls from the model are refused.",
+ "server.title": "Codex Attachment Manager",
+ "resource.name": "Context Assets panel",
+ "call.noThread": "Which task? The threadId is missing.",
+ "call.summary": "Images: {images}, unchecked: {unchecked}.",
+ "call.modelSelect": "Only the user can check or uncheck images; if you need an image, reply \"need IMG-xxx\".",
+ "call.modelSetup": "Only the user can enable or disable the plugin.",
+ "call.modelBind": "Only the user can switch the panel to another task.",
+ "call.started": "This panel's task has already started; there is nothing to switch.",
+ "call.notUserThread": "The panel can only switch to a task the user started.",
+ "call.enabled": "Enabled. Restart Codex for it to take effect.",
+ "call.disabled": "Disabled. Restart Codex to connect directly again.",
+ "call.imageOk": "ok",
+ "call.imageNone": "cannot be shown",
+ "conflict.baseUrl": "config.toml already sets openai_base_url; it was left as it is.",
+ "conflict.systemProxy": "config.toml turns respect_system_proxy off; it was left as it is.",
+ "conflict.noProxy": ".env already sets NO_PROXY; it was left as it is.",
+ "conflict.mcpServer": "config.toml already has an MCP server named {name}; it was left as it is.",
+ "conflict.noEnd": "A marked block in config.toml has no end marker; nothing was changed.",
+ "note.legacyMcp": "Removed the plugin service an older version wrote into config.toml: the plugin provides it now",
+ "note.noProxy": "Wrote NO_PROXY into .env: a proxy is set in the environment and does not leave out this machine",
+ "cli.kind.upload": "upload",
+ "cli.kind.view": "viewed",
+ "cli.kind.generated": "generated",
+ "cli.kind.tool": "tool result",
+ "cli.state.locked": "locked",
+ "cli.state.checked": "checked",
+ "cli.state.unchecked": "unchecked",
+ "cli.requested": "asked for by the model",
+ "cli.table.title": "Task {thread}: {images} images, {turns} turns; {unchecked} unchecked; checked images {checkedMb} MB ({allMb} MB with all checked)",
+ "cli.table.header": "ID | State | Source | Name | Turn | Size | Bytes | Same as | Note",
+ "cli.codexFailed": "codex {args} failed: {output}",
+ "cli.noOutput": "no output",
+ "cli.selfTest.timeout": "No reply within {seconds} s. {errors}",
+ "cli.selfTest.incomplete": "The tools or the panel page are incomplete",
+ "cli.selfTest.failed": "The installed plugin service did not start: {error}. The proxy settings were not written; Codex still connects directly.",
+ "cli.runInRepo": "Run this in the repository: node plugin/src/cam.ts install",
+ "cli.noCli": "Codex's command line was not found. Install the Codex desktop app and open it at least once, or install the Codex command line; you can also set CODEX_CLI_PATH to its location.",
+ "cli.notInstalled": "The plugin is not in Codex yet: install the plugin first, then run setup.",
+ "cli.step.oldMarketplace": "Removed an older plugin marketplace that pointed elsewhere",
+ "cli.step.addMarketplace": "Registered the plugin marketplace (this repository)",
+ "cli.step.oldPlugin": "Removed the old copy of the plugin",
+ "cli.step.install": "Installed the plugin",
+ "cli.step.selfTest": "Self-test passed: the plugin service starts and offers {tools}",
+ "cli.step.direct": "Connected directly again: removed the proxy settings",
+ "cli.step.directEnv": "Connected directly again: removed the proxy settings and the NO_PROXY in .env",
+ "cli.step.noCli": "Codex's command line was not found, so the plugin was not removed; remove it on Codex's plugins page",
+ "cli.step.removePlugin": "Removed the plugin",
+ "cli.step.removeMarketplace": "Removed the plugin marketplace",
+ "cli.list": ", ",
+ "cli.next.install": "Restart Codex for this to take effect. The panel is in the task's side panel: New tab > Plugins and MCP > Context Assets",
+ "cli.next.uninstall": "Restart Codex for this to take effect; the engine exits by itself once Codex has quit. Your selections stay in the data folder; delete it if you no longer need them",
+ "cli.language.notReported": "No panel has reported Codex's interface language yet; the system language is used for now",
+};
+
+export type MessageKey = keyof typeof zh;
+export const MESSAGES: Record<Lang, Record<MessageKey, string>> = { zh, en };
+
+export function say(lang: Lang, key: MessageKey, vars: Record<string, string | number> = {}): string {
+ return MESSAGES[lang][key].replace(/\{(\w+)\}/g, (all, name: string) => (name in vars ? String(vars[name]) : all));
+}
diff --git a/plugin/src/panel-state.ts b/plugin/src/panel-state.ts
index 212bbf4..0079b44 100644
--- a/plugin/src/panel-state.ts
+++ b/plugin/src/panel-state.ts
@@ -28,7 +28,7 @@ export type SendInfo = {
baseline: { at: string; bytes: number } | null;
// What the engine sent for that request.
last: { at: string; bytesBefore: number; bytesAfter: number; replaced: number; skipped: boolean } | null;
- notice: { kind: "skipped"; at: string; reason: string } | { kind: "websocket"; at: string } | null;
+ notice: { kind: "skipped"; at: string; reason: SkipReason } | { kind: "websocket"; at: string } | null;
};
// started: the thread has a rollout. A panel opened on a new chat before its first message may be tied to a thread
// Codex prepared and then replaced (v0.1-8); that one never gets a rollout.
@@ -40,13 +40,14 @@ export type PanelState = {
send: SendInfo;
};
-// The engine's reasons for forwarding a request unchanged, in the user's words.
-const SKIP_REASONS: Array<[RegExp, string]> = [
- [/^undecodable body/, "请求内容无法解压"],
- [/^unparsable body/, "请求内容无法解析"],
- [/^no input array/, "请求的格式和预期不同"],
- [/^integer beyond/, "请求里有超大整数,改写会改变它的值"],
- [/^thread index/, "读取这个任务的记录失败"],
+// 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";
+const SKIP_REASONS: Array<[RegExp, SkipReason]> = [
+ [/^undecodable body/, "undecodable"],
+ [/^unparsable body/, "unparsable"],
+ [/^no input array/, "format"],
+ [/^integer beyond/, "integer"],
+ [/^thread index/, "index"],
];
export function sendInfo(stats: RequestStats | null): SendInfo {
@@ -57,7 +58,7 @@ export function sendInfo(stats: RequestStats | null): SendInfo {
let notice: SendInfo["notice"] = null;
if (latest?.transport === "websocket" && (latest.event === "active-while-unchecked" || latest.activeWhileUnchecked)) notice = { kind: "websocket", at: latest.at };
else if (latest?.transport === "http" && rewrite?.skipped) {
- notice = { kind: "skipped", at: http!.at, reason: SKIP_REASONS.find(([pattern]) => pattern.test(rewrite.skipped))?.[1] ?? "改写时出错" };
+ notice = { kind: "skipped", at: http!.at, reason: SKIP_REASONS.find(([pattern]) => pattern.test(rewrite.skipped))?.[1] ?? "other" };
}
return {
baseline: http && bytes !== null && http.imageSizes ? { at: http.at, bytes } : null,
@@ -67,10 +68,11 @@ export function sendInfo(stats: RequestStats | null): SendInfo {
}
export type PanelOptions = { sessionsDir: string; dataRoot?: string };
-// "需要 IMG-004" or a list right after it ("需要 IMG-004、IMG-002 和 IMG-007"); a full stop ends the list.
+// "需要 IMG-004" or a list right after it ("需要 IMG-004、IMG-002 和 IMG-007"); a full stop ends the list. The English
+// wording (v0.1-14) asks for "need IMG-004", which the model may quote.
const ASKED = [
/需要((?:\s*[“"'「]?\s*IMG-\d{3,}\s*[”"'」]?\s*(?:[、,,/]|以及|和|与|及)?)+)/g,
- /\bneeds?((?:\s*IMG-\d{3,}\s*(?:,|and)?)+)/gi,
+ /\bneeds?((?:\s*["'“”‘’]?\s*IMG-\d{3,}\s*["'“”‘’]?\s*(?:,|and)?)+)/gi,
];
// Ids the model asked for ("需要 IMG-003") in its latest reply; a turn still running falls back to the one before.
diff --git a/plugin/src/panel.html b/plugin/src/panel.html
index 45e8615..f1a120c 100644
--- a/plugin/src/panel.html
+++ b/plugin/src/panel.html
@@ -16,6 +16,8 @@
screen, and only a thread started meanwhile counts; when several did, the user picks one. v0.1-9: the title shows the
task's name. v0.1-13: a notice when an earlier part of the history cannot be found (e.g. the task a fork came from
was deleted); the images left are listed as usual.
+ v0.1-14: Simplified Chinese or English, following Codex's interface language (the host context's locale; else the
+ system's). Every call tells the plugin the language, so its answers match and the text for the model follows it.
-->
<style>
/* Fallbacks follow Codex's own widget palette; inside Codex its theme variables (MCP Apps host styles) win. */
@@ -219,18 +221,232 @@
<div class="viewer-stage" id="viewerStage"></div>
<div class="viewer-bottom">
<span class="meta" id="viewerMeta"></span>
- <label class="check" id="viewerCheck"><input type="checkbox"><span class="box"></span><span>发送这张图</span></label>
+ <label class="check" id="viewerCheck"><input type="checkbox"><span class="box"></span><span class="label">发送这张图</span></label>
</div>
</div>
+<!-- The panel's words (v0.1-14): Simplified Chinese and English, the same keys in both (a unit test checks it);
+ "key_one" is the English text for a count of one. -->
+<script type="application/json" id="messages">
+ {
+ "zh": {
+ "page.title": "上下文素材",
+ "title.loading": "上下文素材",
+ "title.newTask": "新任务",
+ "title.unnamed": "未命名任务",
+ "refresh": "刷新",
+ "refresh.at": "刷新(上次更新 {time})",
+ "refresh.stale": "刷新(有一会儿没更新了;上次更新 {time})",
+ "plugin.disable": "停用插件",
+ "plugin.enable": "启用插件",
+ "plan.loading": "正在读取…",
+ "plan.failed": "读取失败",
+ "plan.empty": "还没有图片",
+ "plan.next": "下一条消息:发送 {sent} 张",
+ "plan.dropped": " · 占位 {dropped} 张",
+ "plan.duplicates": "(其中重复 {duplicates} 张)",
+ "plan.gone": " · {gone} 张已不在上下文",
+ "meter.request": "预计请求",
+ "meter.images": "预计图片数据",
+ "meter.full": "全部发送 {full} · 省 {percent}%",
+ "meter.none": "未取消任何图",
+ "last.noBaseline": "还没有记录到经过代理的完整请求,先按图片大小估算",
+ "last.skipped": "上一次请求 {time}:没能替换,原样发出 {bytes}",
+ "last.replaced": "上一次请求 {time}:替换了 {count} 张,少发 {saved},实际发出 {after}",
+ "last.none": "上一次请求 {time}:没有替换,发出 {bytes}",
+ "kind.upload": "用户上传",
+ "kind.view": "查看的图片",
+ "kind.generated": "生成的图片",
+ "kind.tool": "工具返回",
+ "tag.locked": "无法取消",
+ "tag.gone": "已不在上下文",
+ "tag.requested": "模型需要这张",
+ "tag.replacedBy": "由 {id} 代替",
+ "tag.notSent": "不发送",
+ "tag.sameAs": "与 {id} 相同",
+ "turn.n": "第 {n} 轮",
+ "turn.earlier": "更早",
+ "row.unnamed": "未命名",
+ "row.preview": "预览 {id}",
+ "row.send": "发送 {id}",
+ "thumb.none": "无预览",
+ "empty.title": "这个任务里还没有图片",
+ "empty.text": "上传、查看或生成的图片会按时间顺序出现在这里。",
+ "notice.retry": "重试",
+ "notice.enabled": "已启用。重启 Codex 后生效,取消勾选的图就不再发送了。",
+ "notice.disabled": "已停用。重启 Codex 后恢复直连,取消勾选不再生效。要卸载插件,现在可以去插件页面移除。",
+ "notice.notEnabled": "插件没有启用:Codex 现在直连,取消勾选不会生效。点右上角的“启用插件”,然后重启 Codex。",
+ "notice.waiting": "这个任务还没开始。发出第一条消息后,这里会自动切到这个任务。",
+ "notice.historyMissing": "这个任务前面有一段历史找不到了(它所在的任务记录可能已被删除),那一段里的图片没法在这里列出。",
+ "notice.engineDown": "代理没有在运行,取消勾选暂时不会生效。关掉 Codex 再打开,一般就能恢复。",
+ "notice.skipped": "上一次请求({time})没能按勾选替换,图片原样发给了模型。原因:{reason}。",
+ "notice.websocket": "取消勾选时这一轮对话还在进行,这一轮剩下的请求仍带着原图;从下一条消息起生效。",
+ "reason.undecodable": "请求内容无法解压",
+ "reason.unparsable": "请求内容无法解析",
+ "reason.format": "请求的格式和预期不同",
+ "reason.integer": "请求里有超大整数,改写会改变它的值",
+ "reason.index": "读取这个任务的记录失败",
+ "reason.other": "改写时出错",
+ "chooser.title": "刚刚开始了好几个任务,这个面板要显示哪一个?",
+ "chooser.untitled": "新任务",
+ "footer.saving": "正在保存…",
+ "footer.pending": "有 {count} 处改动,点“确定”后生效",
+ "footer.saved": "已保存,从下一条消息开始生效",
+ "footer.hint": "勾选的图片会随下一条消息发给模型",
+ "button.undo": "撤销",
+ "button.confirm": "确定",
+ "viewer.label": "图片预览",
+ "viewer.close": "关闭预览",
+ "viewer.closeTitle": "关闭(Esc)",
+ "viewer.send": "发送这张图",
+ "viewer.loading": "正在加载…",
+ "viewer.none": "这张图无法预览",
+ "error.load": "读取失败:{message}",
+ "error.save": "保存失败:{message}",
+ "error.switch": "切换失败:{message}",
+ "error.enable": "启用失败:{message}",
+ "error.disable": "停用失败:{message}",
+ "error.noReply": "Codex 没有响应",
+ "error.call": "调用失败"
+ },
+ "en": {
+ "page.title": "Context Assets",
+ "title.loading": "Context Assets",
+ "title.newTask": "New task",
+ "title.unnamed": "Untitled task",
+ "refresh": "Refresh",
+ "refresh.at": "Refresh (last updated {time})",
+ "refresh.stale": "Refresh (not updated for a while; last updated {time})",
+ "plugin.disable": "Disable plugin",
+ "plugin.enable": "Enable plugin",
+ "plan.loading": "Loading…",
+ "plan.failed": "Could not load",
+ "plan.empty": "No images yet",
+ "plan.next": "Next message sends {sent} images",
+ "plan.next_one": "Next message sends {sent} image",
+ "plan.dropped": " · {dropped} as placeholders",
+ "plan.dropped_one": " · {dropped} as a placeholder",
+ "plan.duplicates": " ({duplicates} of them duplicates)",
+ "plan.duplicates_one": " ({duplicates} of them a duplicate)",
+ "plan.gone": " · {gone} no longer in context",
+ "meter.request": "Estimated request",
+ "meter.images": "Estimated image data",
+ "meter.full": "All images {full} · {percent}% saved",
+ "meter.none": "Nothing unchecked",
+ "last.noBaseline": "No full request through the proxy recorded yet; estimated from the image sizes",
+ "last.skipped": "Last request {time}: not rewritten, sent as it was ({bytes})",
+ "last.replaced": "Last request {time}: {count} images replaced, {saved} less, {after} sent",
+ "last.replaced_one": "Last request {time}: {count} image replaced, {saved} less, {after} sent",
+ "last.none": "Last request {time}: nothing replaced, {bytes} sent",
+ "kind.upload": "Uploaded",
+ "kind.view": "Viewed",
+ "kind.generated": "Generated",
+ "kind.tool": "Tool result",
+ "tag.locked": "Can't uncheck",
+ "tag.gone": "No longer in context",
+ "tag.requested": "The model needs this",
+ "tag.replacedBy": "Replaced by {id}",
+ "tag.notSent": "Not sent",
+ "tag.sameAs": "Same as {id}",
+ "turn.n": "Turn {n}",
+ "turn.earlier": "Earlier",
+ "row.unnamed": "Unnamed",
+ "row.preview": "Preview {id}",
+ "row.send": "Send {id}",
+ "thumb.none": "No preview",
+ "empty.title": "No images in this task yet",
+ "empty.text": "Images you upload, and images the model views or generates, show up here in order.",
+ "notice.retry": "Retry",
+ "notice.enabled": "Enabled. After you restart Codex, unchecked images are no longer sent.",
+ "notice.disabled": "Disabled. After you restart Codex it connects directly, and unchecking has no effect. To uninstall, you can now remove the plugin on the plugins page.",
+ "notice.notEnabled": "The plugin is not enabled: Codex connects directly, so unchecking has no effect. Click \"Enable plugin\" at the top right, then restart Codex.",
+ "notice.waiting": "This task has not started yet. Once you send the first message, the panel switches to it.",
+ "notice.historyMissing": "An earlier part of this task's history cannot be found (the task it came from may have been deleted), so the images from that part are not listed here.",
+ "notice.engineDown": "The proxy is not running, so unchecking has no effect for now. Closing and reopening Codex usually brings it back.",
+ "notice.skipped": "The last request ({time}) could not be rewritten as selected; the images went to the model as they were. Reason: {reason}.",
+ "notice.websocket": "This turn was still running when you unchecked images, so its remaining requests still carry the originals; the change applies from the next message.",
+ "reason.undecodable": "the request could not be decompressed",
+ "reason.unparsable": "the request could not be parsed",
+ "reason.format": "the request is not in the expected format",
+ "reason.integer": "the request holds an integer too large to rewrite safely",
+ "reason.index": "this task's records could not be read",
+ "reason.other": "an error occurred while rewriting",
+ "chooser.title": "Several tasks just started. Which one should this panel show?",
+ "chooser.untitled": "New task",
+ "footer.saving": "Saving…",
+ "footer.pending": "{count} changes; click \"Confirm\" to apply them",
+ "footer.pending_one": "{count} change; click \"Confirm\" to apply it",
+ "footer.saved": "Saved; applies from the next message",
+ "footer.hint": "Checked images go to the model with the next message",
+ "button.undo": "Undo",
+ "button.confirm": "Confirm",
+ "viewer.label": "Image preview",
+ "viewer.close": "Close preview",
+ "viewer.closeTitle": "Close (Esc)",
+ "viewer.send": "Send this image",
+ "viewer.loading": "Loading…",
+ "viewer.none": "This image cannot be previewed",
+ "error.load": "Could not load: {message}",
+ "error.save": "Could not save: {message}",
+ "error.switch": "Could not switch: {message}",
+ "error.enable": "Could not enable: {message}",
+ "error.disable": "Could not disable: {message}",
+ "error.noReply": "Codex did not respond",
+ "error.call": "The call failed"
+ }
+ }
+</script>
<script>
(() => {
- const KIND = { upload: "用户上传", view: "查看的图片", generated: "生成的图片", tool: "工具返回" };
const THUMB_SIDE = 160;
const POLL_MS = 3000;
const STALE_MS = 30000; // older than this, the 刷新 button turns orange
const $ = (id) => document.getElementById(id);
const main = $("main");
+ // ---- language (v0.1-14): Codex's interface language when the host context gives one, else the system's ----
+ const MESSAGES = JSON.parse($("messages").textContent);
+ const langOf = (tag) => (typeof tag === "string" && tag.trim() ? (tag.trim().toLowerCase().startsWith("zh") ? "zh" : "en") : null);
+ let lang = langOf(navigator.language) ?? "en";
+ let langSource = "system";
+ const template = (key, count) => {
+ const table = MESSAGES[lang];
+ return (count === 1 && table[`${key}_one`]) || table[key] || MESSAGES.en[key] || key;
+ };
+ const fill = (text, vars) => text.replace(/\{(\w+)\}/g, (all, name) => (name in vars ? String(vars[name]) : all));
+ const t = (key, vars = {}) => fill(template(key, vars.count), vars);
+ // A text with some of its values in bold, e.g. the number of images the next message sends.
+ function rich(key, vars, bold) {
+ return template(key, vars.count).split(/(\{\w+\})/).filter(Boolean).map((part) => {
+ const name = /^\{(\w+)\}$/.exec(part)?.[1];
+ if (!name || !(name in vars)) return part;
+ return name === bold ? Object.assign(document.createElement("b"), { textContent: String(vars[name]) }) : String(vars[name]);
+ });
+ }
+ function setLanguage(tag, source) {
+ const next = langOf(tag);
+ if (!next) return;
+ const changed = next !== lang;
+ lang = next;
+ langSource = source;
+ if (changed) applyLanguage();
+ }
+ // The texts outside what render() draws, and the caches that hold words.
+ function applyLanguage() {
+ document.documentElement.lang = lang === "zh" ? "zh-CN" : "en";
+ document.title = t("page.title");
+ $("refresh").setAttribute("aria-label", t("refresh"));
+ $("undo").textContent = t("button.undo");
+ $("confirm").textContent = t("button.confirm");
+ $("viewer").setAttribute("aria-label", t("viewer.label"));
+ $("viewerClose").setAttribute("aria-label", t("viewer.close"));
+ $("viewerClose").title = t("viewer.closeTitle");
+ $("viewerCheck").querySelector(".label").textContent = t("viewer.send");
+ emptyState.querySelector("strong").textContent = t("empty.title");
+ emptyState.querySelector("span").textContent = t("empty.text");
+ turnLabels.clear();
+ render();
+ }
+
// ---- MCP Apps bridge (JSON-RPC over postMessage with Codex) ----
let nextId = 1;
const waiting = new Map();
@@ -238,15 +454,17 @@
function request(method, params, timeoutMs = 30000) {
return new Promise((resolve, reject) => {
const id = nextId++;
- const timer = setTimeout(() => { waiting.delete(id); reject(new Error("Codex 没有响应")); }, timeoutMs);
+ const timer = setTimeout(() => { waiting.delete(id); reject(new Error(t("error.noReply"))); }, timeoutMs);
waiting.set(id, { resolve: (value) => { clearTimeout(timer); resolve(value); }, reject: (error) => { clearTimeout(timer); reject(error); } });
post({ id, method, params });
});
}
const textOf = (result) => (result?.content ?? []).map((part) => part?.text).filter(Boolean).join("\n");
+ // Every call says which language the panel shows, so the plugin answers in it; the panel's reads also say where the
+ // language came from, and the plugin remembers it for the text it gives the model.
async function callTool(name, args) {
- const result = await request("tools/call", { name, arguments: args ?? {} });
- if (result?.isError) throw new Error(textOf(result) || "调用失败");
+ const result = await request("tools/call", { name, arguments: { ...(args ?? {}), lang, ...(name === "cam_panel" ? { langSource } : {}) } });
+ if (result?.isError) throw new Error(textOf(result) || t("error.call"));
return result;
}
window.addEventListener("message", (event) => {
@@ -255,7 +473,7 @@
if (message.id !== undefined && waiting.has(message.id) && ("result" in message || "error" in message)) {
const waiter = waiting.get(message.id);
waiting.delete(message.id);
- if (message.error) waiter.reject(new Error(message.error.message ?? "调用失败")); else waiter.resolve(message.result);
+ if (message.error) waiter.reject(new Error(message.error.message ?? t("error.call"))); else waiter.resolve(message.result);
return;
}
if (message.method === "ui/notifications/tool-result") ingest(message.params?.structuredContent);
@@ -264,6 +482,7 @@
});
function applyHost(context) {
if (!context) return;
+ if (typeof context.locale === "string") setLanguage(context.locale, "codex");
if (context.theme === "dark" || context.theme === "light") document.documentElement.dataset.theme = context.theme;
const variables = context.styles?.variables;
if (variables && typeof variables === "object") {
@@ -273,7 +492,9 @@
// ---- state ----
const S = {
- data: null, threadId: null, error: null, flash: null,
+ data: null, threadId: null,
+ error: null, // { key, message }: said in the current language when drawn
+ flash: null, // a text key
pending: new Map(), // id -> checked, changes not confirmed yet
thumbs: new Map(), // id -> data URL or null
viewer: null, // { id, url, loading, failed }
@@ -322,7 +543,7 @@
renderRefresh();
noteScreen();
try { ingest((await callTool("cam_panel", { shown })).structuredContent); followNewTask(); }
- catch (error) { S.error = "读取失败:" + error.message; render(); }
+ catch (error) { S.error = { key: "error.load", message: error.message }; render(); }
finally { S.refreshing = false; S.manual = false; renderRefresh(); }
}
// Moving to or touching the panel brings it up to date at once, whatever the host does to a background frame's
@@ -352,11 +573,11 @@
check: changes.filter(([, checked]) => checked).map(([id]) => id),
});
S.pending.clear();
- S.flash = "已保存,从下一条消息开始生效";
+ S.flash = "footer.saved";
setTimeout(() => { S.flash = null; renderFooter(); }, 4000);
ingest(result.structuredContent);
} catch (error) {
- S.error = "保存失败:" + error.message;
+ S.error = { key: "error.save", message: error.message };
} finally {
S.saving = false; render();
}
@@ -386,7 +607,7 @@
if (S.switchingTask) return;
S.switchingTask = true; render();
try { ingest((await callTool("cam_bind", { target: threadId })).structuredContent); }
- catch (error) { S.error = "切换失败:" + error.message; }
+ catch (error) { S.error = { key: "error.switch", message: error.message }; }
finally { S.switchingTask = false; render(); }
}
@@ -398,7 +619,7 @@
const result = await callTool("cam_setup", { enable });
ingest(result.structuredContent);
} catch (error) {
- S.error = (enable ? "启用失败:" : "停用失败:") + error.message;
+ S.error = { key: enable ? "error.enable" : "error.disable", message: error.message };
} finally {
S.switching = false; render();
}
@@ -439,23 +660,23 @@
const turnLabels = new Map();
const emptyState = document.createElement("div");
emptyState.className = "empty";
- emptyState.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="6" width="14" height="14" rx="2.5"/><path d="M7 3h10.5A3.5 3.5 0 0 1 21 6.5V16"/><circle cx="8" cy="11" r="1.5"/><path d="m3.5 18 4.5-4.5 3 3 2-2 3.5 3.5"/></svg><strong>这个任务里还没有图片</strong><span>上传、查看或生成的图片会按时间顺序出现在这里。</span>';
+ emptyState.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="6" width="14" height="14" rx="2.5"/><path d="M7 3h10.5A3.5 3.5 0 0 1 21 6.5V16"/><circle cx="8" cy="11" r="1.5"/><path d="m3.5 18 4.5-4.5 3 3 2-2 3.5 3.5"/></svg><strong></strong><span></span>';
const formatBytes = (bytes) => bytes < 1024 ? `${bytes} B` : bytes < 1024 * 1024 ? `${Math.round(bytes / 1024)} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`;
- const describe = (image) => [KIND[image.kind] ?? image.kind, image.width && image.height ? `${image.width}×${image.height}` : null, formatBytes(image.bytes)].filter(Boolean).join(" · ");
+ const describe = (image) => [MESSAGES[lang][`kind.${image.kind}`] ? t(`kind.${image.kind}`) : image.kind, image.width && image.height ? `${image.width}×${image.height}` : null, formatBytes(image.bytes)].filter(Boolean).join(" · ");
// An unchecked image becomes a duplicate placeholder when a copy of the same content is still sent in that request.
const sentCopyOf = (image) => image.sameAs.find((id) => { const other = byId(id); return other && other.inNextRequest && isChecked(other); });
function tagsOf(image) {
const tags = [];
- if (!image.replaceable) tags.push(["无法取消", ""]);
+ if (!image.replaceable) tags.push([t("tag.locked"), ""]);
// Compacted out of the history: it is not sent either way.
- if (!image.inNextRequest) { tags.push(["已不在上下文", ""]); return tags; }
+ if (!image.inNextRequest) { tags.push([t("tag.gone"), ""]); return tags; }
const checked = isChecked(image);
const sentCopy = sentCopyOf(image);
- if (!checked && image.requested) tags.push(["模型需要这张", "warn"]);
- if (!checked) tags.push([sentCopy ? `由 ${sentCopy} 代替` : "不发送", ""]);
- else if (image.sameAs.length) tags.push([`与 ${image.sameAs[0]} 相同`, ""]);
+ if (!checked && image.requested) tags.push([t("tag.requested"), "warn"]);
+ if (!checked) tags.push([sentCopy ? t("tag.replacedBy", { id: sentCopy }) : t("tag.notSent"), ""]);
+ else if (image.sameAs.length) tags.push([t("tag.sameAs", { id: image.sameAs[0] }), ""]);
return tags;
}
@@ -478,12 +699,13 @@
const pad = (n) => String(n).padStart(2, "0");
return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
}
+ // Today: 10:30; another day: 9月25日 10:30 or Sep 25, 10:30.
function timeOf(at) {
const date = new Date(at);
if (Number.isNaN(date.getTime())) return "";
- const pad = (n) => String(n).padStart(2, "0");
- const time = `${pad(date.getHours())}:${pad(date.getMinutes())}`;
- return date.toDateString() === new Date().toDateString() ? time : `${date.getMonth() + 1}月${date.getDate()}日 ${time}`;
+ const today = date.toDateString() === new Date().toDateString();
+ const time = { hour: "2-digit", minute: "2-digit", hourCycle: "h23" };
+ return new Intl.DateTimeFormat(lang === "zh" ? "zh-CN" : "en-US", today ? time : { month: lang === "zh" ? "long" : "short", day: "numeric", ...time }).format(date);
}
function makeRow(id) {
@@ -506,7 +728,7 @@
if (!img) { img = document.createElement("img"); img.alt = ""; button.replaceChildren(img); }
if (img.src !== url) img.src = url;
} else if (S.thumbs.has(id)) {
- button.innerHTML = '<span class="none">无预览</span>';
+ button.replaceChildren(Object.assign(document.createElement("span"), { className: "none", textContent: t("thumb.none") }));
}
}
@@ -514,14 +736,14 @@
const checked = isChecked(image);
row.classList.toggle("off", !checked);
row.classList.toggle("pending", S.pending.has(image.id));
- row.querySelector(".thumb").setAttribute("aria-label", `预览 ${image.id}`);
+ row.querySelector(".thumb").setAttribute("aria-label", t("row.preview", { id: image.id }));
row.querySelector(".id").textContent = image.id;
- row.querySelector(".name").textContent = image.name ?? "未命名";
+ row.querySelector(".name").textContent = image.name ?? t("row.unnamed");
row.querySelector(".meta").textContent = describe(image);
const input = row.querySelector("input");
input.checked = checked;
input.disabled = !image.replaceable || S.saving;
- input.setAttribute("aria-label", `发送 ${image.id}`);
+ input.setAttribute("aria-label", t("row.send", { id: image.id }));
row.querySelector(".check").classList.toggle("locked", !image.replaceable);
const tags = row.querySelector(".tags");
tags.replaceChildren(...tagsOf(image).map(([text, tone]) => {
@@ -536,36 +758,35 @@
function renderHeader() {
const list = images();
const plan = $("plan");
- const title = !S.data ? "上下文素材" : S.data.title ?? (S.data.started === false ? "新任务" : "未命名任务");
+ const title = !S.data ? t("title.loading") : S.data.title ?? (S.data.started === false ? t("title.newTask") : t("title.unnamed"));
$("title").textContent = title;
$("title").title = title;
$("count").textContent = list.length ? String(list.length) : "";
if (!S.data || !list.length) {
- plan.textContent = !S.data ? (S.error ? "读取失败" : "正在读取…") : "还没有图片";
+ plan.textContent = !S.data ? (S.error ? t("plan.failed") : t("plan.loading")) : t("plan.empty");
$("meter").hidden = true;
$("last").textContent = "";
return;
}
const f = forecast();
- const bold = (text) => Object.assign(document.createElement("b"), { textContent: String(text) });
plan.replaceChildren(
- "下一条消息:发送 ", bold(f.sent), " 张",
- f.dropped ? ` · 占位 ${f.dropped} 张${f.duplicates ? `(其中重复 ${f.duplicates} 张)` : ""}` : "",
- f.gone ? ` · ${f.gone} 张已不在上下文` : "",
+ ...rich("plan.next", { sent: f.sent, count: f.sent }, "sent"),
+ f.dropped ? t("plan.dropped", { dropped: f.dropped, count: f.dropped }) + (f.duplicates ? t("plan.duplicates", { duplicates: f.duplicates, count: f.duplicates }) : "") : "",
+ f.gone ? t("plan.gone", { gone: f.gone, count: f.gone }) : "",
);
$("meter").hidden = false;
- $("meterLabel").textContent = f.whole ? "预计请求" : "预计图片数据";
+ $("meterLabel").textContent = t(f.whole ? "meter.request" : "meter.images");
$("meterValue").textContent = formatBytes(f.after);
const saving = f.after < f.full;
const percent = (1 - f.after / f.full) * 100;
- $("meterFull").textContent = saving ? `全部发送 ${formatBytes(f.full)} · 省 ${percent < 1 ? "<1" : Math.round(percent)}%` : "未取消任何图";
+ $("meterFull").textContent = saving ? t("meter.full", { full: formatBytes(f.full), percent: percent < 1 ? "<1" : Math.round(percent) }) : t("meter.none");
$("meterFull").classList.toggle("saved", saving);
$("meterBar").style.width = `${f.full > 0 ? Math.max(2, Math.round((f.after / f.full) * 100)) : 100}%`;
const last = S.data.send?.last;
- $("last").textContent = !last ? (f.whole ? "" : "还没有记录到经过代理的完整请求,先按图片大小估算")
- : last.skipped ? `上一次请求 ${timeOf(last.at)}:没能替换,原样发出 ${formatBytes(last.bytesBefore)}`
- : last.replaced ? `上一次请求 ${timeOf(last.at)}:替换了 ${last.replaced} 张,少发 ${formatBytes(last.bytesBefore - last.bytesAfter)},实际发出 ${formatBytes(last.bytesAfter)}`
- : `上一次请求 ${timeOf(last.at)}:没有替换,发出 ${formatBytes(last.bytesBefore)}`;
+ $("last").textContent = !last ? (f.whole ? "" : t("last.noBaseline"))
+ : last.skipped ? t("last.skipped", { time: timeOf(last.at), bytes: formatBytes(last.bytesBefore) })
+ : last.replaced ? t("last.replaced", { time: timeOf(last.at), count: last.replaced, saved: formatBytes(last.bytesBefore - last.bytesAfter), after: formatBytes(last.bytesAfter) })
+ : t("last.none", { time: timeOf(last.at), bytes: formatBytes(last.bytesBefore) });
}
// Notices are reused while their text stays the same, so re-rendering does not move the list around.
@@ -592,19 +813,19 @@
// Several threads started since the panel was opened: which one is this panel's?
function chooser(tasks) {
- const key = `chooser|${tasks.map((task) => `${task.threadId}:${task.title ?? ""}`).join("|")}`;
+ const key = `chooser|${lang}|${tasks.map((task) => `${task.threadId}:${task.title ?? ""}`).join("|")}`;
let box = notices.get(key);
if (!box) {
box = document.createElement("div");
box.className = "notice info chooser";
const text = document.createElement("span");
- text.textContent = "刚刚开始了好几个任务,这个面板要显示哪一个?";
+ text.textContent = t("chooser.title");
box.append(text);
for (const task of tasks) {
const button = document.createElement("button");
button.type = "button";
button.className = "pick";
- const name = Object.assign(document.createElement("span"), { className: "pick-name", textContent: task.title ?? "新任务" });
+ const name = Object.assign(document.createElement("span"), { className: "pick-name", textContent: task.title ?? t("chooser.untitled") });
const time = Object.assign(document.createElement("span"), { className: "pick-time", textContent: clockOf(task.startedAt) });
button.append(name, time);
button.addEventListener("click", () => switchTo(task.threadId));
@@ -619,9 +840,9 @@
function setupNotices() {
const setup = S.data?.setup;
if (!setup) return [];
- if (setup.changed === "enabled") return [notice("info", "已启用。重启 Codex 后生效,取消勾选的图就不再发送了。")];
- if (setup.changed === "disabled") return [notice("warn", "已停用。重启 Codex 后恢复直连,取消勾选不再生效。要卸载插件,现在可以去插件页面移除。")];
- if (!setup.usesEngine) return [notice("info", "插件没有启用:Codex 现在直连,取消勾选不会生效。点右上角的“启用插件”,然后重启 Codex。")];
+ if (setup.changed === "enabled") return [notice("info", t("notice.enabled"))];
+ if (setup.changed === "disabled") return [notice("warn", t("notice.disabled"))];
+ if (!setup.usesEngine) return [notice("info", t("notice.notEnabled"))];
return [];
}
@@ -630,15 +851,16 @@
let pluginKey = "";
function renderPlugin() {
const setup = S.data?.setup;
- const key = !setup ? "" : setup.usesEngine ? "on" : "off";
+ const on = !!setup?.usesEngine;
+ const key = !setup ? "" : `${on ? "on" : "off"}|${lang}`;
const box = $("plugin");
if (key !== pluginKey) {
pluginKey = key;
const button = document.createElement("button");
button.type = "button";
- button.textContent = key === "on" ? "停用插件" : "启用插件";
- button.className = key === "on" ? "off" : "on";
- button.addEventListener("click", () => switchEngine(key !== "on"));
+ button.textContent = t(on ? "plugin.disable" : "plugin.enable");
+ button.className = on ? "off" : "on";
+ button.addEventListener("click", () => switchEngine(!on));
box.replaceChildren(...(key ? [button] : []));
}
for (const button of box.children) button.disabled = S.switching;
@@ -649,22 +871,22 @@
const stale = lastFresh > 0 && Date.now() - lastFresh > STALE_MS;
button.classList.toggle("spinning", S.refreshing && S.manual);
button.classList.toggle("stale", stale && !S.refreshing);
- button.title = !lastFresh ? "刷新" : `刷新(${stale ? "有一会儿没更新了;" : ""}上次更新 ${clockOf(lastFresh)})`;
+ button.title = !lastFresh ? t("refresh") : t(stale ? "refresh.stale" : "refresh.at", { time: clockOf(lastFresh) });
}
function renderList() {
const nodes = [];
- if (S.error) nodes.push(notice("error", S.error, { label: "重试", run: () => { S.error = null; render(); refresh(); } }));
+ if (S.error) nodes.push(notice("error", t(S.error.key, { message: S.error.message }), { label: t("notice.retry"), run: () => { S.error = null; render(); refresh(); } }));
nodes.push(...setupNotices());
if (S.data?.started === false) {
const tasks = newTasks();
- nodes.push(tasks.length > 1 ? chooser(tasks) : notice("info", "这个任务还没开始。发出第一条消息后,这里会自动切到这个任务。"));
+ nodes.push(tasks.length > 1 ? chooser(tasks) : notice("info", t("notice.waiting")));
}
- if (S.data?.historyMissing) nodes.push(notice("warn", "这个任务前面有一段历史找不到了(它所在的任务记录可能已被删除),那一段里的图片没法在这里列出。"));
- if (S.data?.engineRunning === false && S.data?.setup?.usesEngine !== false) nodes.push(notice("warn", "代理没有在运行,取消勾选暂时不会生效。关掉 Codex 再打开,一般就能恢复。"));
+ if (S.data?.historyMissing) nodes.push(notice("warn", t("notice.historyMissing")));
+ if (S.data?.engineRunning === false && S.data?.setup?.usesEngine !== false) nodes.push(notice("warn", t("notice.engineDown")));
const sendNotice = S.data?.send?.notice;
- if (sendNotice?.kind === "skipped") nodes.push(notice("error", `上一次请求(${timeOf(sendNotice.at)})没能按勾选替换,图片原样发给了模型。原因:${sendNotice.reason}。`));
- if (sendNotice?.kind === "websocket") nodes.push(notice("warn", "取消勾选时这一轮对话还在进行,这一轮剩下的请求仍带着原图;从下一条消息起生效。"));
+ if (sendNotice?.kind === "skipped") nodes.push(notice("error", t("notice.skipped", { time: timeOf(sendNotice.at), reason: t(MESSAGES[lang][`reason.${sendNotice.reason}`] ? `reason.${sendNotice.reason}` : "reason.other") })));
+ if (sendNotice?.kind === "websocket") nodes.push(notice("warn", t("notice.websocket")));
const list = images();
if (S.data && !list.length) nodes.push(emptyState);
let turn;
@@ -674,7 +896,7 @@
if (!turnLabels.has(turn)) {
const label = document.createElement("div");
label.className = "turn";
- label.textContent = turn === null ? "更早" : `第 ${turn} 轮`;
+ label.textContent = turn === null ? t("turn.earlier") : t("turn.n", { n: turn });
turnLabels.set(turn, label);
}
nodes.push(turnLabels.get(turn));
@@ -696,10 +918,10 @@
const status = $("status");
const count = S.pending.size;
status.className = "status";
- if (S.saving) status.textContent = "正在保存…";
- else if (count) { status.textContent = `有 ${count} 处改动,点“确定”后生效`; status.classList.add("pending"); }
- else if (S.flash) { status.textContent = S.flash; status.classList.add("ok"); }
- else status.textContent = images().length ? "勾选的图片会随下一条消息发给模型" : "";
+ if (S.saving) status.textContent = t("footer.saving");
+ else if (count) { status.textContent = t("footer.pending", { count }); status.classList.add("pending"); }
+ else if (S.flash) { status.textContent = t(S.flash); status.classList.add("ok"); }
+ else status.textContent = images().length ? t("footer.hint") : "";
$("undo").hidden = !count;
$("undo").disabled = S.saving;
$("confirm").disabled = !count || S.saving;
@@ -711,8 +933,8 @@
if (!image) { viewer.hidden = true; return; }
viewer.hidden = false;
$("viewerId").textContent = image.id;
- $("viewerName").textContent = image.name ?? "未命名";
- $("viewerMeta").textContent = [image.turn === null ? null : `第 ${image.turn} 轮`, describe(image)].filter(Boolean).join(" · ");
+ $("viewerName").textContent = image.name ?? t("row.unnamed");
+ $("viewerMeta").textContent = [image.turn === null ? null : t("turn.n", { n: image.turn }), describe(image)].filter(Boolean).join(" · ");
const input = $("viewerCheck").querySelector("input");
input.checked = isChecked(image);
input.disabled = !image.replaceable || S.saving;
@@ -724,7 +946,7 @@
if (!img) { img = document.createElement("img"); img.alt = image.name ?? image.id; stage.replaceChildren(img); }
if (img.src !== url) img.src = url;
} else {
- stage.innerHTML = `<span class="none">${S.viewer.loading ? "正在加载…" : "这张图无法预览"}</span>`;
+ stage.replaceChildren(Object.assign(document.createElement("span"), { className: "none", textContent: t(S.viewer.loading ? "viewer.loading" : "viewer.none") }));
}
}
@@ -759,7 +981,7 @@
// ---- start: handshake, then Codex sends its own cam_panel result; poll so new images show up ----
if (window.matchMedia?.("(prefers-color-scheme: dark)").matches) document.documentElement.dataset.theme = "dark";
- render();
+ applyLanguage();
request("ui/initialize", { protocolVersion: "2026-01-26", appInfo: { name: "codex-attachment-manager", version: "0.1.0" }, appCapabilities: {} })
.then((init) => { applyHost(init?.hostContext); post({ method: "ui/notifications/initialized", params: {} }); })
.catch(() => {})
diff --git a/plugin/src/plugin-server.ts b/plugin/src/plugin-server.ts
index 79ce0db..6233e97 100644
--- a/plugin/src/plugin-server.ts
+++ b/plugin/src/plugin-server.ts
@@ -9,6 +9,8 @@
// v0.1-10 — a panel opened on a new chat before its first message is told which threads the user has just started,
// and switches to one with cam_bind; from then on its calls are about that thread (binding.ts). v0.1-11 — slow calls
// are logged with their duration; pixel fingerprints are shared with the engine through the data directory.
+// v0.1-14 — the panel reports Codex's interface language with its calls; it is remembered (language.ts), and the tool
+// list (the tab's title), results and refusals speak it (messages.ts).
// Input: MCP JSON-RPC over stdio. Env: CAM_ENGINE_PORT (default 17891), CAM_NO_ENGINE=1 (tests), CAM_DATA_DIR.
// Output: tool results; <data dir>/plugin-server.jsonl (events and counts only, no conversation content).
@@ -20,6 +22,8 @@ import { codexHome } from "./codexconfig.ts";
import { bindThread, isUserThread, newThreads, resolveThread } from "./binding.ts";
import { DEFAULT_PORT, ensureEngine } from "./engine.ts";
import { isEntryPoint } from "./entry.ts";
+import { currentLang, langOf, rememberLang, type Lang } from "./language.ts";
+import { say } from "./messages.ts";
import { applySelection, imageFor, loadPanelState, type PanelState } from "./panel-state.ts";
import { dataDir, pixelCacheDirOf } from "./paths.ts";
import { connectDirectly, useEngine, usesEngine } from "./setup.ts";
@@ -32,45 +36,50 @@ const here = dirname(fileURLToPath(import.meta.url));
export const PANEL_URI = "ui://codex-attachment-manager/panel.html";
export const PANEL_MIME = "text/html;profile=mcp-app";
const APP_ONLY = { ui: { visibility: ["app"] } };
-const threadArg = { threadId: { type: "string", description: "任务 ID;面板调用时由 Codex 自动带上。" } };
-
-export const TOOLS = [
- {
- name: "cam_panel",
- title: "上下文素材",
- description: "上下文素材面板:查看这个任务里的历史图片,勾选下一条消息要发给模型的图片。由用户在侧边面板里打开,模型不需要调用。",
- inputSchema: { type: "object", properties: { ...threadArg, shown: { type: "array", items: { type: "array", items: { type: "number" } }, description: "面板页面显示在屏幕上的时间段(毫秒);面板调用时带上。" } } },
- _meta: { ui: { resourceUri: PANEL_URI, visibility: ["app"] }, "openai/ui": { entrypoints: [{ type: "thread" }] } },
- },
- {
- name: "cam_set_selection",
- title: "上下文素材:勾选",
- description: "素材面板内部使用:勾选或取消图片。只有用户能操作,模型调用会被拒绝。",
- inputSchema: { type: "object", properties: { ...threadArg, uncheck: { type: "array", items: { type: "string" } }, check: { type: "array", items: { type: "string" } }, checkAll: { type: "boolean" } } },
- _meta: APP_ONLY,
- },
- {
- name: "cam_image",
- title: "上下文素材:图片",
- description: "素材面板内部使用:读取一张图片的缩略图或预览图。模型不需要调用。",
- inputSchema: { type: "object", properties: { ...threadArg, id: { type: "string" }, maxSide: { type: "number" } }, required: ["id"] },
- _meta: APP_ONLY,
- },
- {
- name: "cam_setup",
- title: "上下文素材:启用或停用",
- description: "素材面板内部使用:让 Codex 经过本机代理(启用),或者恢复直连(停用),重启 Codex 后生效。只有用户能操作,模型调用会被拒绝。",
- inputSchema: { type: "object", properties: { ...threadArg, enable: { type: "boolean" } }, required: ["enable"] },
- _meta: APP_ONLY,
- },
- {
- name: "cam_bind",
- title: "上下文素材:切到新任务",
- description: "素材面板内部使用:在新任务发出第一条消息之前打开的面板,切到用户刚开始的那个任务。只有用户能操作,模型调用会被拒绝。",
- inputSchema: { type: "object", properties: { ...threadArg, target: { type: "string" } }, required: ["target"] },
- _meta: APP_ONLY,
- },
-];
+// The tool list is read when Codex starts this service: it speaks the language last reported by a panel (or the system's).
+export function toolsFor(lang: Lang) {
+ const threadArg = { threadId: { type: "string", description: say(lang, "tool.threadId") } };
+ const langArg = { lang: { type: "string", description: say(lang, "tool.lang") } };
+ const shared = { ...threadArg, ...langArg };
+ return [
+ {
+ name: "cam_panel",
+ title: say(lang, "tool.panel.title"),
+ description: say(lang, "tool.panel.description"),
+ inputSchema: { type: "object", properties: { ...shared, langSource: { type: "string" }, shown: { type: "array", items: { type: "array", items: { type: "number" } }, description: say(lang, "tool.shown") } } },
+ _meta: { ui: { resourceUri: PANEL_URI, visibility: ["app"] }, "openai/ui": { entrypoints: [{ type: "thread" }] } },
+ },
+ {
+ 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" } } },
+ _meta: APP_ONLY,
+ },
+ {
+ name: "cam_image",
+ title: say(lang, "tool.image.title"),
+ description: say(lang, "tool.image.description"),
+ inputSchema: { type: "object", properties: { ...shared, id: { type: "string" }, maxSide: { type: "number" } }, required: ["id"] },
+ _meta: APP_ONLY,
+ },
+ {
+ name: "cam_setup",
+ title: say(lang, "tool.setup.title"),
+ description: say(lang, "tool.setup.description"),
+ inputSchema: { type: "object", properties: { ...shared, enable: { type: "boolean" } }, required: ["enable"] },
+ _meta: APP_ONLY,
+ },
+ {
+ name: "cam_bind",
+ title: say(lang, "tool.bind.title"),
+ description: say(lang, "tool.bind.description"),
+ inputSchema: { type: "object", properties: { ...shared, target: { type: "string" } }, required: ["target"] },
+ _meta: APP_ONLY,
+ },
+ ];
+}
+export const TOOLS = toolsFor("zh");
// A stack of pictures, drawn for light and dark themes (Codex takes https or data URLs only).
const ICON_SVG = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="6" width="14" height="14" rx="2.5"/><path d="M7 3h10.5A3.5 3.5 0 0 1 21 6.5V16"/><circle cx="8" cy="11" r="1.5"/><path d="m3.5 18 4.5-4.5 3 3 2-2 3.5 3.5"/></svg>';
@@ -78,7 +87,7 @@ const icon = (theme: "light" | "dark", color: string) => ({
src: `data:image/svg+xml;base64,${Buffer.from(ICON_SVG.replace("currentColor", color)).toString("base64")}`,
mimeType: "image/svg+xml", sizes: ["any"], theme,
});
-export const SERVER_INFO = { name: "codex-attachment-manager", title: "上下文素材管理器", version: "0.1.0", icons: [icon("light", "#5d5d5d"), icon("dark", "#cdcdcd")] };
+export const serverInfo = (lang: Lang) => ({ name: "codex-attachment-manager", title: say(lang, "server.title"), version: "0.1.0", icons: [icon("light", "#5d5d5d"), icon("dark", "#cdcdcd")] });
export function readResource(uri: string): Json {
if (uri !== PANEL_URI) throw new Error(`unknown resource ${uri}`);
@@ -115,7 +124,13 @@ export function threadOf(args: Json, meta: Json | undefined): string | null {
return args.threadId ?? meta?.threadId ?? meta?.thread_id ?? meta?.["x-codex-turn-metadata"]?.thread_id ?? null;
}
-const summary = (state: PanelState) => `共 ${state.totals.images} 张图,取消了 ${state.totals.unchecked} 张。`;
+const summary = (lang: Lang, state: PanelState) => say(lang, "call.summary", { images: state.totals.images, unchecked: state.totals.unchecked });
+
+// A conflict with the user's settings comes with a message key (codexconfig.ts): said in the panel's language.
+function localized(error: unknown, lang: Lang): unknown {
+ const known = error as { key?: Parameters<typeof say>[1]; vars?: Record<string, string> };
+ return known?.key ? new Error(say(lang, known.key, known.vars)) : error;
+}
const SLOW_MS = 300;
// What a panel on a thread without a rollout is offered: the threads the user started while the panel was on screen.
@@ -128,8 +143,11 @@ function newTasks(sessionsDir: string, shown: unknown): Json[] {
}
export function callTool(name: string, args: Json, meta: Json | undefined, sessionsDir = join(codexHome(), "sessions")): Json {
+ // The panel sends the language it shows; calls without one (Codex's first call, the model's) get the remembered one.
+ const lang = langOf(args.lang) ?? currentLang();
+ if (name === "cam_panel" && langOf(args.lang) && !fromModel(meta)) rememberLang(lang, args.langSource === "codex" ? "codex" : "system");
const own = threadOf(args, meta);
- if (!own) throw new Error("不知道是哪个任务:缺少 threadId");
+ if (!own) throw new Error(say(lang, "call.noThread"));
// A panel switched to a new thread (v0.1-10) keeps sending its own thread id; its calls are about the new one.
const threadId = resolveThread(own, sessionsDir);
const options = { sessionsDir };
@@ -138,34 +156,35 @@ export function callTool(name: string, args: Json, meta: Json | undefined, sessi
const state = loadPanelState(threadId, options);
// Only the panel page says when it was on screen; Codex's own first call does not, and gets no list.
const offer = !state.started && threadId === own && Array.isArray(args.shown) ? { newTasks: newTasks(sessionsDir, args.shown) } : {};
- return { content: [{ type: "text", text: summary(state) }], structuredContent: panel(state, offer) };
+ return { content: [{ type: "text", text: summary(lang, state) }], structuredContent: panel(state, offer) };
}
if (name === "cam_set_selection") {
- if (fromModel(meta)) throw new Error("只有用户能勾选或取消图片;需要某张图时,请回复“需要 IMG-xxx”。");
+ if (fromModel(meta)) throw new Error(say(lang, "call.modelSelect"));
const state = applySelection(threadId, { uncheck: args.uncheck, check: args.check, checkAll: args.checkAll }, options);
- return { content: [{ type: "text", text: summary(state) }], structuredContent: panel(state) };
+ return { content: [{ type: "text", text: summary(lang, state) }], structuredContent: panel(state) };
}
if (name === "cam_bind") {
- if (fromModel(meta)) throw new Error("只有用户能切换面板对应的任务。");
+ if (fromModel(meta)) throw new Error(say(lang, "call.modelBind"));
const target = String(args.target ?? "");
- if (hasRollout(sessionsDir, own)) throw new Error("这个面板的任务已经开始了,不用切换。");
- if (!isUserThread(sessionMetaOf(sessionsDir, target))) throw new Error("只能切到用户自己开始的任务。");
+ if (hasRollout(sessionsDir, own)) throw new Error(say(lang, "call.started"));
+ if (!isUserThread(sessionMetaOf(sessionsDir, target))) throw new Error(say(lang, "call.notUserThread"));
bindThread(own, target);
const state = loadPanelState(target, options);
- return { content: [{ type: "text", text: summary(state) }], structuredContent: { ...state, engineRunning, setup: setupState(), switchedFrom: own } };
+ return { content: [{ type: "text", text: summary(lang, state) }], structuredContent: { ...state, engineRunning, setup: setupState(), switchedFrom: own } };
}
if (name === "cam_setup") {
- if (fromModel(meta)) throw new Error("只有用户能启用或停用。");
+ if (fromModel(meta)) throw new Error(say(lang, "call.modelSetup"));
setupState(); // the baseline, in case this is the first call
// A conflict with the user's own settings throws here, before anything is written.
- const plan = args.enable === true ? useEngine(enginePort) : connectDirectly();
+ let plan;
+ try { plan = args.enable === true ? useEngine(enginePort) : connectDirectly(); } catch (error) { throw localized(error, lang); }
const state = loadPanelState(threadId, options);
- return { content: [{ type: "text", text: args.enable === true ? "已启用,重启 Codex 后生效。" : "已停用,重启 Codex 后恢复直连。" }], structuredContent: panel(state, { notes: plan.notes }) };
+ return { content: [{ type: "text", text: say(lang, args.enable === true ? "call.enabled" : "call.disabled") }], structuredContent: panel(state, { notes: plan.notes }) };
}
if (name === "cam_image") {
const image = imageFor(threadId, String(args.id), Number(args.maxSide ?? 160), options);
// The image data goes in _meta, which only the panel sees.
- return { content: [{ type: "text", text: image.dataUrl ? "ok" : "无法显示" }], structuredContent: { id: image.id, available: image.dataUrl !== null }, _meta: { dataUrl: image.dataUrl } };
+ return { content: [{ type: "text", text: say(lang, image.dataUrl ? "call.imageOk" : "call.imageNone") }], structuredContent: { id: image.id, available: image.dataUrl !== null }, _meta: { dataUrl: image.dataUrl } };
}
throw new Error(`unknown tool ${name}`);
}
@@ -195,11 +214,11 @@ function main(): void {
try { message = JSON.parse(line); } catch { return; }
const { id, method, params = {} } = message;
if (method === "initialize") {
- send({ id, result: { protocolVersion: params.protocolVersion ?? "2025-06-18", capabilities: { tools: {}, resources: {} }, serverInfo: SERVER_INFO } });
+ send({ id, result: { protocolVersion: params.protocolVersion ?? "2025-06-18", capabilities: { tools: {}, resources: {} }, serverInfo: serverInfo(currentLang()) } });
} else if (method === "tools/list") {
- send({ id, result: { tools: TOOLS } });
+ send({ id, result: { tools: toolsFor(currentLang()) } });
} else if (method === "resources/list") {
- send({ id, result: { resources: [{ uri: PANEL_URI, name: "上下文素材面板", mimeType: PANEL_MIME }] } });
+ send({ id, result: { resources: [{ uri: PANEL_URI, name: say(currentLang(), "resource.name"), mimeType: PANEL_MIME }] } });
} else if (method === "resources/templates/list") {
send({ id, result: { resourceTemplates: [] } });
} else if (method === "resources/read") {
diff --git a/plugin/src/proxy.ts b/plugin/src/proxy.ts
index bbc40fa..7e13ae8 100644
--- a/plugin/src/proxy.ts
+++ b/plugin/src/proxy.ts
@@ -5,6 +5,7 @@
// WebSocket turn that kept running after images were unchecked (it cannot be rewritten).
// v0.1-3: reports its build and version; POST /__cam/retire hands the port to a newer engine (see engine.ts).
// v0.1-11: pixel fingerprints go to the shared cache in the data directory, for the panels to reuse.
+// v0.1-14: the text for the model is in the language the panel last reported (Codex's interface language).
// Only metadata is logged (never auth headers or conversation content).
// Input: [--port 17891] [--stay (no auto-exit)] [--force-http] [--dump-requests (synthetic test threads only)];
// the outbound proxy is taken from HTTPS_PROXY/HTTP_PROXY or the system proxy settings (Windows, macOS).
@@ -23,6 +24,7 @@ import { codexHome } from "./codexconfig.ts";
import { buildOf, DEFAULT_PORT, ENGINE_SERVICE, engineHealth, versionOf, watchForCodex } from "./engine.ts";
import { findImages, type ImageRef } from "./images.ts";
import { isEntryPoint } from "./entry.ts";
+import { currentLang } from "./language.ts";
import { dataDir, pixelCacheDirOf, proxyLogDirOf } from "./paths.ts";
import { recordRequest } from "./request-stats.ts";
import { rewriteItems, type Described } from "./rewrite.ts";
@@ -208,7 +210,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 { items, report } = rewriteItems(json.input, describe, new Set(Object.keys(selection.unchecked)), pixels);
+ const { items, report } = rewriteItems(json.input, describe, new Set(Object.keys(selection.unchecked)), pixels, currentLang());
const summary: Json = {
images: report.images,
replaced: report.replaced.map(({ key: _key, ...rest }) => rest),
diff --git a/plugin/src/rewrite.ts b/plugin/src/rewrite.ts
index 5b64110..3d2a25f 100644
--- a/plugin/src/rewrite.ts
+++ b/plugin/src/rewrite.ts
@@ -2,9 +2,12 @@
// Nothing else changes: checked images, unknown images and all other items are forwarded as they are.
// v0.1 — placeholders say the image was seen when it appeared and is left out now by the user's choice, so the model
// keeps trusting what it said about it (user report 2026-09-25).
+// v0.1-14 — in the user's language (Codex's interface language, language.ts): the Chinese wording is the one tested on
+// 2026-09-25; the English one says the same and is checked by the same self-test (v01-placeholder-selftest.ts --lang en).
// Input: request items, a lookup into the thread index, the unchecked keys. Output: new items plus a metadata report.
import { findImages, type ImageKind, type ImageRef } from "./images.ts";
+import type { Lang } from "./language.ts";
type Json = Record<string, any>;
export type Described = { id: string; name: string | null; label: string | null; kind: ImageKind; turn: number | null; width: number | null; height: number | null };
@@ -12,32 +15,76 @@ export type Replacement = { id: string; key: string; kind: ImageKind; mode: "pla
// noteAt: where the developer message explaining omitted images was inserted, if one was.
export type RewriteReport = { images: number; replaced: Replacement[]; locked: string[]; sentContentIds: string[]; noteAt?: number };
-const KIND_TEXT: Record<ImageKind, string> = { upload: "用户上传", view: "工具查看的图片", generated: "生成的图片", tool: "工具结果里的图片" };
-
-function heading(image: Described, state: string): string {
- const fields = [image.name ?? "未命名", KIND_TEXT[image.kind]];
- if (image.turn !== null) fields.push(`第 ${image.turn} 轮`);
- if (image.width && image.height) fields.push(`${image.width}×${image.height}`);
- return `[图片 ${image.id}${image.label ? `(${image.label})` : ""} ${state}|${fields.join("|")}]`;
-}
+type Words = {
+ kind: Record<ImageKind, string>; unnamed: string; turn: (n: number) => string; thisTurn: string; newImage: string;
+ omitted: string; notRepeated: string; separator: string;
+ heading: (id: string, label: string | null, state: string, fields: string[]) => string;
+ plain: (id: string) => string; duplicate: (id: string, where: string) => string; note: string;
+};
// The image sits in the history, so the model concludes it never saw it and takes back what it said about it (user
// report 2026-09-25). Saying otherwise inside the placeholder did not help: it is user content, which the model does
// not take as proof. So the explanation goes once into a developer message, before the turn where the first omitted
// image appeared, and each placeholder only points to it.
-export const OMISSION_NOTE = [
- "上下文管理说明(来自用户安装的上下文素材管理工具):为了节省上下文,用户取消勾选了这个任务里的部分图片。后面的对话里,这些图片原来的位置被换成了“[图片 IMG-xxx 已省略…]”这样的占位文字。",
- "这些图片在它们出现的那一轮真实存在,你当时收到并看过;你之前对它们的描述,以及据此做出的判断,都是看着原图做出的,仍然有效。不要因为现在看不到,就认为之前的回答是猜测或错误,也不要收回或道歉。",
- "被问到现在能不能看到时,如实说明现在看不到(被用户省略了),并说明之前的描述仍然有效。现在看不到画面,就不要补充之前没说过的细节;需要重新看某张图时,在回复里写出“需要 IMG-xxx”,用户可以重新勾选;不要自己用工具去读取这些图片。",
-].join("\n");
+const WORDS: Record<Lang, Words> = {
+ zh: {
+ kind: { upload: "用户上传", view: "工具查看的图片", generated: "生成的图片", tool: "工具结果里的图片" },
+ unnamed: "未命名",
+ turn: (n) => `第 ${n} 轮`,
+ thisTurn: "本轮",
+ newImage: "(新图片)",
+ omitted: "已省略",
+ notRepeated: "未重复提供",
+ separator: ",",
+ heading: (id, label, state, fields) => `[图片 ${id}${label ? `(${label})` : ""} ${state}|${fields.join("|")}]`,
+ plain: (id) => `原图被用户省略以节省上下文,情况见前面的“上下文管理说明”;需要重新看这张图时,在回复里写出“需要 ${id}”。`,
+ duplicate: (id, where) => `这张图和 ${id}(${where})内容完全相同,那一条在本次请求里照常提供,请直接参考那一条。`,
+ note: [
+ "上下文管理说明(来自用户安装的上下文素材管理工具):为了节省上下文,用户取消勾选了这个任务里的部分图片。后面的对话里,这些图片原来的位置被换成了“[图片 IMG-xxx 已省略…]”这样的占位文字。",
+ "这些图片在它们出现的那一轮真实存在,你当时收到并看过;你之前对它们的描述,以及据此做出的判断,都是看着原图做出的,仍然有效。不要因为现在看不到,就认为之前的回答是猜测或错误,也不要收回或道歉。",
+ "被问到现在能不能看到时,如实说明现在看不到(被用户省略了),并说明之前的描述仍然有效。现在看不到画面,就不要补充之前没说过的细节;需要重新看某张图时,在回复里写出“需要 IMG-xxx”,用户可以重新勾选;不要自己用工具去读取这些图片。",
+ ].join("\n"),
+ },
+ en: {
+ kind: { upload: "uploaded by the user", view: "viewed with a tool", generated: "generated image", tool: "image from a tool result" },
+ unnamed: "unnamed",
+ turn: (n) => `turn ${n}`,
+ thisTurn: "this turn",
+ newImage: "(new image)",
+ omitted: "omitted",
+ notRepeated: "not repeated",
+ separator: ", ",
+ heading: (id, label, state, fields) => `[Image ${id}${label ? ` (${label})` : ""} ${state} | ${fields.join(" | ")}]`,
+ plain: (id) => `The user left out the original image to save context; see the "Context management note" above. If you need to see this image again, write "need ${id}" in your reply.`,
+ duplicate: (id, where) => `This image is identical to ${id} (${where}), which is included in this request as usual; refer to that one.`,
+ note: [
+ "Context management note (from the context asset manager the user installed): to save context, the user unchecked some images in this task. Further on in the conversation, where those images were, there is now placeholder text such as \"[Image IMG-xxx omitted…]\".",
+ "These images really existed in the turn where they appeared, and you received and looked at them then; what you said about them before, and the judgments you based on it, were made looking at the original images and remain valid. Do not treat your earlier answers as guesses or mistakes because you cannot see the images now, and do not take them back or apologize.",
+ "If asked whether you can see them now, say truthfully that you cannot see them now (the user left them out), and that your earlier descriptions remain valid. Since you cannot see them now, do not add details you did not mention before; if you need to look at an image again, write \"need IMG-xxx\" in your reply, and the user can check it again; do not read these images yourself with tools.",
+ ].join("\n"),
+ },
+};
+
+// Kept for the tests and the 2026-09-25 record: the Chinese note as tested then.
+export const OMISSION_NOTE = WORDS.zh.note;
+export const omissionNote = (lang: Lang) => WORDS[lang].note;
+
+function heading(words: Words, image: Described, state: string): string {
+ const fields = [image.name ?? words.unnamed, words.kind[image.kind]];
+ if (image.turn !== null) fields.push(words.turn(image.turn));
+ if (image.width && image.height) fields.push(`${image.width}×${image.height}`);
+ return words.heading(image.id, image.label, state, fields);
+}
-export function plainPlaceholder(image: Described): string {
- return `${heading(image, "已省略")}\n原图被用户省略以节省上下文,情况见前面的“上下文管理说明”;需要重新看这张图时,在回复里写出“需要 ${image.id}”。`;
+export function plainPlaceholder(image: Described, lang: Lang = "zh"): string {
+ const words = WORDS[lang];
+ return `${heading(words, image, words.omitted)}\n${words.plain(image.id)}`;
}
-export function duplicatePlaceholder(image: Described, same: Described): string {
- const where = [same.name, same.turn !== null ? `第 ${same.turn} 轮` : "本轮"].filter(Boolean).join(",");
- return `${heading(image, "未重复提供")}\n这张图和 ${same.id}(${where})内容完全相同,那一条在本次请求里照常提供,请直接参考那一条。`;
+export function duplicatePlaceholder(image: Described, same: Described, lang: Lang = "zh"): string {
+ const words = WORDS[lang];
+ const where = [same.name, same.turn !== null ? words.turn(same.turn) : words.thisTurn].filter(Boolean).join(words.separator);
+ return `${heading(words, image, words.notRepeated)}\n${words.duplicate(same.id, where)}`;
}
export function rewriteItems(
@@ -45,6 +92,7 @@ export function rewriteItems(
describe: (ref: ImageRef) => Described | undefined,
unchecked: Set<string>,
pixelHash: (ref: ImageRef) => string | null,
+ lang: Lang = "zh",
): { items: Json[]; report: RewriteReport } {
const refs = findImages(items);
const report: RewriteReport = { images: refs.length, replaced: [], locked: [], sentContentIds: [] };
@@ -65,8 +113,8 @@ export function rewriteItems(
for (const ref of drop) {
const image = describe(ref)!;
const copy = sent.find((other) => same(other, ref));
- const copyImage = copy ? describe(copy) ?? { id: "(新图片)", name: copy.name, label: copy.label, kind: copy.kind, turn: null, width: copy.width, height: copy.height } : null;
- const text = copyImage ? duplicatePlaceholder(image, copyImage) : plainPlaceholder(image);
+ const copyImage = copy ? describe(copy) ?? { id: WORDS[lang].newImage, name: copy.name, label: copy.label, kind: copy.kind, turn: null, width: copy.width, height: copy.height } : null;
+ const text = copyImage ? duplicatePlaceholder(image, copyImage, lang) : plainPlaceholder(image, lang);
if (!copyImage && firstPlain === null) firstPlain = ref.item;
report.replaced.push({ id: image.id, key: ref.key, kind: ref.kind, mode: copyImage ? "duplicate" : "plain", sameAs: copyImage?.id ?? null, base64Chars: ref.base64Chars });
const list = edits.get(ref.item) ?? [];
@@ -86,7 +134,7 @@ export function rewriteItems(
if (firstPlain !== null) {
let at = firstPlain;
while (at > 0 && !(next[at].type === "message" && next[at].role === "user")) at--;
- next.splice(at, 0, { type: "message", role: "developer", content: [{ type: "input_text", text: OMISSION_NOTE }] });
+ next.splice(at, 0, { type: "message", role: "developer", content: [{ type: "input_text", text: WORDS[lang].note }] });
report.noteAt = at;
}
return { items: next, report };
diff --git a/spike/scripts/panel-dev.ts b/spike/scripts/panel-dev.ts
index f63f723..4a94685 100644
--- a/spike/scripts/panel-dev.ts
+++ b/spike/scripts/panel-dev.ts
@@ -6,7 +6,7 @@
// ?stats=none|skipped|websocket for other engine statistics than a normal rewritten request, ?setup=off for a Codex that
// does not go through the engine yet, ?demo=disabled for right after 停用插件, ?thread=fresh for a task with no rollout;
// with &newtask=1 the user then starts one task — the panel switches to it — and with &newtask=2 two at once;
-// ?thread=gap for a fork whose original task was deleted, v0.1-13).
+// ?thread=gap for a fork whose original task was deleted, v0.1-13; ?lang=en for Codex in English, v0.1-14).
// The demo task has a name, as if the user had renamed it in Codex (v0.1-9).
// Everything is written to a temporary folder, including a Codex home of its own: nothing in the user's Codex home is
// read or changed, whatever is clicked.
@@ -150,7 +150,7 @@ const HOST = `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><tit
window.addEventListener("message", async (event) => {
const m = event.data;
if (!m || event.source !== frame.contentWindow) return;
- if (m.method === "ui/initialize") send({ id: m.id, result: { protocolVersion: "2026-01-26", hostInfo: { name: "panel-dev" }, hostCapabilities: { serverTools: {} }, hostContext: { theme, displayMode: "inline", locale: "zh-CN" } } });
+ if (m.method === "ui/initialize") send({ id: m.id, result: { protocolVersion: "2026-01-26", hostInfo: { name: "panel-dev" }, hostCapabilities: { serverTools: {} }, hostContext: { theme, displayMode: "inline", locale: params.get("lang") === "en" ? "en-US" : "zh-CN" } } });
else if (m.method === "ui/notifications/initialized") { send({ method: "ui/notifications/tool-result", params: await call("cam_panel", {}) }); demo(); }
else if (m.method === "tools/call") { const delay = params.get("slow") ? 900 : 60; const result = await call(m.params.name, m.params.arguments); setTimeout(() => send({ id: m.id, result }), delay); }
});
diff --git a/spike/src/binding.test.ts b/spike/src/binding.test.ts
index 101d628..5cfe621 100644
--- a/spike/src/binding.test.ts
+++ b/spike/src/binding.test.ts
@@ -67,5 +67,5 @@ test("a panel's calls follow its binding until its own thread has a rollout", ()
assert.equal(resolveThread("chatgpt:abc", sessionsDir, bindings), "chatgpt:abc");
startThread(sessionsDir, PANEL);
assert.equal(resolveThread(PANEL, sessionsDir, bindings), PANEL, "its own rollout wins");
- assert.throws(() => bindThread(PANEL, "../x", bindings), /不是任务编号/);
+ assert.throws(() => bindThread(PANEL, "../x", bindings), /not a thread id/);
});
diff --git a/spike/src/language.test.ts b/spike/src/language.test.ts
new file mode 100644
index 0000000..6e2cd44
--- /dev/null
+++ b/spike/src/language.test.ts
@@ -0,0 +1,90 @@
+// Purpose: v0.1-14 — the plugin speaks Simplified Chinese or English: which language a tag or the system gives, the
+// language the panel reports is remembered, every text exists in both languages with the same {values}, and the text
+// for the model and the plugin's answers follow the language.
+// Input: synthetic tags, environments and temporary data folders; output: Node test assertions only.
+
+import assert from "node:assert/strict";
+import { mkdtempSync, readFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+import { currentLang, langOf, rememberLang, storedLang, systemLang } from "../../plugin/src/language.ts";
+import { MESSAGES, say } from "../../plugin/src/messages.ts";
+import { callTool, toolsFor } from "../../plugin/src/plugin-server.ts";
+import { OMISSION_NOTE, omissionNote, rewriteItems, type Described } from "../../plugin/src/rewrite.ts";
+import { sampleSessions } from "./testfixtures.ts";
+
+const here = dirname(fileURLToPath(import.meta.url));
+const valuesOf = (text: string) => [...text.matchAll(/\{(\w+)\}/g)].map((match) => match[1]).sort();
+
+test("any Chinese is Simplified Chinese, anything else English; locale variables come before the runtime", () => {
+ assert.deepEqual(["zh-CN", "zh-TW", "zh_HK.UTF-8", "ZH", "en-US", "fr-FR", "ja", "", "C", "POSIX", "C.UTF-8", null].map(langOf), ["zh", "zh", "zh", "zh", "en", "en", "en", null, null, null, null, null]);
+ assert.equal(systemLang({ LANG: "zh_CN.UTF-8" }), "zh");
+ assert.equal(systemLang({ LC_ALL: "en_US.UTF-8", LANG: "zh_CN.UTF-8" }), "en", "LC_ALL wins");
+ assert.equal(systemLang({ LANG: "C" }), langOf(Intl.DateTimeFormat().resolvedOptions().locale) ?? "en", "C says nothing: the runtime decides");
+});
+
+test("the language a panel reports is kept, with where it came from; without one the system decides", () => {
+ const file = join(mkdtempSync(join(tmpdir(), "cam-lang-")), "language.json");
+ assert.equal(storedLang(file), null);
+ assert.equal(currentLang(file), systemLang());
+ rememberLang("en", "codex", file);
+ assert.deepEqual([storedLang(file)?.lang, storedLang(file)?.source], ["en", "codex"]);
+ assert.equal(currentLang(file), "en");
+ const written = readFileSync(file, "utf8");
+ rememberLang("en", "codex", file);
+ assert.equal(readFileSync(file, "utf8"), written, "unchanged: not written again");
+ rememberLang("zh", "system", file);
+ assert.deepEqual([currentLang(file), storedLang(file)?.source], ["zh", "system"]);
+});
+
+test("the plugin's texts exist in both languages with the same {values}", () => {
+ assert.deepEqual(Object.keys(MESSAGES.en).sort(), Object.keys(MESSAGES.zh).sort());
+ for (const key of Object.keys(MESSAGES.zh) as Array<keyof typeof MESSAGES.zh>) assert.deepEqual(valuesOf(MESSAGES.en[key]), valuesOf(MESSAGES.zh[key]), key);
+ assert.equal(say("zh", "call.summary", { images: 3, unchecked: 1 }), "共 3 张图,取消了 1 张。");
+ assert.equal(say("en", "call.summary", { images: 3, unchecked: 1 }), "Images: 3, unchecked: 1.");
+});
+
+test("the panel's texts exist in both languages with the same {values}; English may add a form for one", () => {
+ const page = readFileSync(join(here, "..", "..", "plugin", "src", "panel.html"), "utf8");
+ const table = JSON.parse(/<script type="application\/json" id="messages">([\s\S]*?)<\/script>/.exec(page)![1]);
+ const base = (keys: string[]) => keys.filter((key) => !key.endsWith("_one")).sort();
+ assert.deepEqual(base(Object.keys(table.en)), base(Object.keys(table.zh)));
+ for (const key of Object.keys(table.en)) assert.deepEqual(valuesOf(table.en[key]), valuesOf(table.zh[key.replace(/_one$/, "")]), key);
+ assert.ok(Object.keys(table.zh).length > 70);
+});
+
+test("the tab's title and the tools speak the language; the panel's calls are answered in its language", () => {
+ assert.deepEqual([toolsFor("zh")[0].title, toolsFor("en")[0].title], ["上下文素材", "Context Assets"]);
+ const { sessionsDir, dataRoot } = sampleSessions();
+ process.env.CAM_DATA_DIR = dataRoot;
+ try {
+ const model = { "x-codex-turn-metadata": { thread_id: "01a0d301-0000-7000-8000-00000000abcd" } };
+ assert.throws(() => callTool("cam_set_selection", { uncheck: ["IMG-001"], lang: "en" }, model, sessionsDir), /Only the user can check or uncheck images; if you need an image, reply "need IMG-xxx"/);
+ const panel = { threadId: "01a0d301-0000-7000-8000-00000000abcd" };
+ assert.equal(callTool("cam_panel", { lang: "en", langSource: "codex" }, panel, sessionsDir).content[0].text, "Images: 3, unchecked: 0.");
+ assert.deepEqual([storedLang(join(dataRoot, "language.json"))?.lang, storedLang(join(dataRoot, "language.json"))?.source], ["en", "codex"], "remembered for the engine");
+ assert.equal(callTool("cam_panel", {}, panel, sessionsDir).content[0].text, "Images: 3, unchecked: 0.", "a call without a language gets the remembered one");
+ } finally {
+ delete process.env.CAM_DATA_DIR;
+ }
+});
+
+test("the text for the model follows the language; the Chinese is the one tested on 2026-09-25", () => {
+ assert.equal(omissionNote("zh"), OMISSION_NOTE);
+ const en = omissionNote("en");
+ assert.match(en, /really existed in the turn where they appeared/);
+ assert.match(en, /do not take them back or apologize/);
+ assert.match(en, /need IMG-xxx/);
+ assert.doesNotMatch(en, /[一-鿿]/);
+ const image = (id: string) => ({ type: "input_image", image_url: `data:image/png;base64,${Buffer.from(id).toString("base64")}` });
+ const input = [{ type: "message", id: "msg_1", role: "user", content: [{ type: "input_text", text: "look" }, image("a")] }];
+ const described: Described = { id: "IMG-001", name: "a.png", label: null, kind: "upload", turn: 1, width: 4, height: 4 };
+ const run = (lang: "zh" | "en") => rewriteItems(input, () => described, new Set(["msg_1#0"]), () => null, lang).items;
+ const english = JSON.stringify(run("en"));
+ assert.match(english, /\[Image IMG-001 omitted \| a\.png \| uploaded by the user \| turn 1 \| 4×4\]/);
+ assert.match(english, /write \\"need IMG-001\\" in your reply/);
+ assert.doesNotMatch(english, /[一-鿿]/);
+ assert.match(JSON.stringify(run("zh")), /\[图片 IMG-001 已省略|a\.png|用户上传|第 1 轮|4×4\]/);
+});
diff --git a/spike/src/panel-state.test.ts b/spike/src/panel-state.test.ts
index 76080b6..68bff71 100644
--- a/spike/src/panel-state.test.ts
+++ b/spike/src/panel-state.test.ts
@@ -20,6 +20,7 @@ test("the ids the model asked for come from its latest reply only", () => {
assert.deepEqual(requestedIds(records(turn("t1") + assistant("需要 IMG-001", "t1") + turn("t2") + assistant("好的,需要 “IMG-004” 和 IMG-002。", "t2"))), ["IMG-004", "IMG-002"]);
assert.deepEqual(requestedIds(records(turn("t1") + assistant("need IMG-007 to answer", "t1") + turn("t2"))), ["IMG-007"], "a turn still running falls back to the one before");
assert.deepEqual(requestedIds(records(turn("t1") + assistant("IMG-003 与 IMG-002 相同", "t1"))), [], "mentioning an id is not asking for it");
+ assert.deepEqual(requestedIds(records(turn("t1") + assistant("To answer that I need \"IMG-004\" and IMG-002.", "t1"))), ["IMG-004", "IMG-002"], "the English wording, quoted");
});
test("panel state lists every image with checked, same-content and requested flags", () => {
@@ -57,7 +58,7 @@ test("the size baseline: images the last request carried, images added since, an
test("the panel is told when the engine could not rewrite, or a WebSocket turn kept the unchecked images", () => {
const http = { at: "t1", transport: "http", decodedBytes: 900, rewrite: { skipped: "thread index: Error: boom" } };
- assert.deepEqual(sendInfo({ latest: http, lastHttp: http }).notice, { kind: "skipped", at: "t1", reason: "读取这个任务的记录失败" });
+ assert.deepEqual(sendInfo({ latest: http, lastHttp: http }).notice, { kind: "skipped", at: "t1", reason: "index" });
assert.deepEqual(sendInfo({ latest: { ...http, rewrite: { skipped: "rewrite failed: x" } }, lastHttp: { ...http, rewrite: { skipped: "rewrite failed: x" } } }).notice?.kind, "skipped");
const busy = { at: "t2", transport: "websocket", event: "active-while-unchecked" };
assert.deepEqual(sendInfo({ latest: busy, lastHttp: http }).notice, { kind: "websocket", at: "t2" });
diff --git a/spike/src/v01-placeholder-selftest.ts b/spike/src/v01-placeholder-selftest.ts
index c8214b0..f9b179f 100644
--- a/spike/src/v01-placeholder-selftest.ts
+++ b/spike/src/v01-placeholder-selftest.ts
@@ -2,7 +2,10 @@
// report of 2026-09-25 with the new placeholder wording: see the image → describe it → uncheck it → "can you see it?"
// → recall the earlier description → ask a detail never described (must ask for the image instead of guessing).
// Runs a test engine of this checkout on its own port and data folder, so the user's running engine is not touched.
-// Input: [--label name] [--port 17899]. Output: local/v01/placeholder-<label>.json (synthetic test thread only).
+// v0.1-14 — --lang en runs the same turns in English, with the engine told the panel shows English, so the English
+// text for the model is checked the same way.
+// Input: [--label name] [--port 17899] [--lang zh|en]. Output: local/v01/placeholder-<label>.json (synthetic test thread
+// only).
import { spawn } from "node:child_process";
import { mkdirSync, writeFileSync } from "node:fs";
@@ -12,6 +15,7 @@ import { fileURLToPath } from "node:url";
import { AppServer, findBundledCodex } from "./appserver.ts";
import { codexHome } from "../../plugin/src/codexconfig.ts";
import { engineHealth } from "../../plugin/src/engine.ts";
+import { languageFileOf, rememberLang } from "../../plugin/src/language.ts";
import { selectionDirOf } from "../../plugin/src/paths.ts";
import { readRequestStats } from "../../plugin/src/request-stats.ts";
import { writeSelection } from "../../plugin/src/selection.ts";
@@ -21,45 +25,78 @@ import { loadThreadIndex } from "../../plugin/src/thread-index.ts";
type Json = Record<string, any>;
const here = dirname(fileURLToPath(import.meta.url));
const localRoot = join(resolve(here, "../.."), "local");
-// Taking back an earlier answer, in the ways the model phrased it in the report.
+// Taking back an earlier answer, in the ways the model phrased it in the report (and their English counterparts).
const RETRACTION = /猜|不可靠|没有依据|错误回答|说错|抱歉|收回|撤回|并不准确/;
+const RETRACTION_EN = /\b(guess(ed|ing)?|unreliable|no basis|mistaken|was wrong|incorrect|apologi[sz]e|sorry|take (it|that|them) back|retract)/i;
+
+// The five turns and what each reply must show, per language.
+const SCRIPT = {
+ zh: {
+ name: (label: string) => `[CAM测试] v0.1 占位符自测 ${label}`,
+ upload: "这是两张测试图,先不用描述,只回复“收到”。",
+ describe: "a.png 是什么背景色、什么主要形状?角落里有什么小标记,在哪个角?不要调用任何工具。",
+ canYouSee: "现在能看到a.png吗?",
+ recall: "你刚才说 a.png 的背景是什么颜色、中间是什么形状?",
+ newDetail: "a.png 里那个红色正方形的四个角,是直角还是圆角?",
+ colors: [/白/, /红/, /黑/],
+ recalled: [/白/, /(方|正方)/],
+ retraction: RETRACTION,
+ asks: (id: string) => new RegExp(`需要\\s*${id}`),
+ },
+ en: {
+ name: (label: string) => `[CAM test] v0.1 placeholder self-test ${label}`,
+ upload: "Here are two test images. Don't describe them yet; just reply \"received\".",
+ describe: "What is the background color of a.png, and what is its main shape? What small mark is in a corner, and which corner? Do not call any tools.",
+ canYouSee: "Can you see a.png now?",
+ recall: "What did you say earlier about the background color of a.png and the shape in the middle?",
+ newDetail: "Are the four corners of the red square in a.png sharp right angles or rounded?",
+ colors: [/white/i, /red/i, /black/i],
+ recalled: [/white/i, /square/i],
+ retraction: RETRACTION_EN,
+ asks: (id: string) => new RegExp(`need\\s*["“]?${id}`, "i"),
+ },
+};
async function main(): Promise<void> {
const option = (name: string, fallback: string) => (process.argv.includes(name) ? process.argv[process.argv.indexOf(name) + 1] : fallback);
const label = option("--label", "run1");
const port = Number(option("--port", "17899"));
+ const lang = option("--lang", "zh") === "en" ? "en" : "zh";
+ const words = SCRIPT[lang];
const root = join(localRoot, "v01");
const data = join(root, `data-${label}`);
const work = join(root, "work");
mkdirSync(work, { recursive: true });
writeFileSync(join(work, "a.png"), testImages.redSquare());
writeFileSync(join(work, "b.png"), testImages.blueCircle());
+ // What the panel would have told the plugin: Codex shows this language.
+ rememberLang(lang, "codex", languageFileOf(data));
const engine = spawn(process.execPath, [join(here, "..", "..", "plugin", "src", "proxy.ts"), "--port", String(port), "--stay"], { env: { ...process.env, CAM_DATA_DIR: data }, stdio: "ignore", windowsHide: true });
for (let i = 0; i < 50 && !(await engineHealth(port)); i++) await sleep(200);
const startedAt = new Date().toISOString();
const server = new AppServer(findBundledCodex(), ["-c", `openai_base_url="http://localhost:${port}/backend-api/codex"`, "-c", "features.respect_system_proxy=true"], { NO_PROXY: undefined, no_proxy: undefined }, join(root, `appserver-${label}.log`));
- const result: Json = { createdAt: startedAt, label, turns: {} };
+ const result: Json = { createdAt: startedAt, label, lang, turns: {} };
try {
await server.initialize();
const { thread } = await server.request<{ thread: Json }>("thread/start", { model: TEST_MODEL, cwd: work, approvalPolicy: "never", sandbox: "read-only", ephemeral: false });
const threadId: string = thread.id;
result.threadId = threadId;
- await server.request("thread/name/set", { threadId, name: `[CAM测试] v0.1 占位符自测 ${label}` });
+ await server.request("thread/name/set", { threadId, name: words.name(label) });
const turn = async (name: string, prompt: string, images: string[] = []) => {
result.turns[name] = await runTurn(server, threadId, [text(prompt), ...images.map((file) => ({ type: "localImage", path: join(work, file) }))]);
};
- await turn("upload", "这是两张测试图,先不用描述,只回复“收到”。", ["a.png", "b.png"]);
- await turn("describe", "a.png 是什么背景色、什么主要形状?角落里有什么小标记,在哪个角?不要调用任何工具。");
+ await turn("upload", words.upload, ["a.png", "b.png"]);
+ await turn("describe", words.describe);
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));
await sleep(2500);
- await turn("canYouSee", "现在能看到a.png吗?");
- await turn("recall", "你刚才说 a.png 的背景是什么颜色、中间是什么形状?");
- await turn("newDetail", "a.png 里那个红色正方形的四个角,是直角还是圆角?");
+ await turn("canYouSee", words.canYouSee);
+ await turn("recall", words.recall);
+ await turn("newDetail", words.newDetail);
result.lastRequest = readRequestStats(threadId, join(data, "state", "requests"))?.lastHttp?.rewrite ?? null;
} finally {
await server.stop();
@@ -68,10 +105,10 @@ async function main(): Promise<void> {
const reply = (name: string) => String(result.turns[name]?.reply ?? "");
result.checks = {
- describeSeesImage: /白/.test(reply("describe")) && /红/.test(reply("describe")) && /黑/.test(reply("describe")),
- canYouSeeNoRetraction: !RETRACTION.test(reply("canYouSee")),
- recallKeepsEarlierAnswer: /白/.test(reply("recall")) && /(方|正方)/.test(reply("recall")) && !RETRACTION.test(reply("recall")),
- newDetailAsksForImage: new RegExp(`需要\\s*${result.aId}`).test(reply("newDetail")),
+ describeSeesImage: words.colors.every((color) => color.test(reply("describe"))),
+ canYouSeeNoRetraction: !words.retraction.test(reply("canYouSee")),
+ recallKeepsEarlierAnswer: words.recalled.every((word) => word.test(reply("recall"))) && !words.retraction.test(reply("recall")),
+ newDetailAsksForImage: words.asks(result.aId).test(reply("newDetail")),
lastRequestReplacedA: JSON.stringify(result.lastRequest?.replaced?.map((r: Json) => `${r.id}:${r.mode}`)) === JSON.stringify([`${result.aId}:plain`]),
noErrors: Object.values(result.turns as Record<string, Json>).every((t) => t.status === "completed" && !t.errors.length),
};