Auto-approve all (全部自动同意) ships in agent-console 1.3.1, split out of #727 (qingnian108).
The mode is off by default. In it, Codex runs with its sandbox off and Claude Code skips its checks. Cursor, OpenCode and dsh requests are answered allow-once by the console, never allow_always or acceptForSession. Each auto answer is saved with `auto: true` before the Agent goes on, and a banner shows while the mode is on. Plan confirmations and questions still ask. A 1.2 默认 of 全部放行 is not silently upgraded to real auto-approve. Pi keeps the `default` mode id ("Pi never asks"), so switching Agents before the first message never carries auto-approve into an Agent the user didn't pick.
Reviewed at 7e55c87ca merged onto main 20b89389:
- Linux (WSL2 Ubuntu 24.04): root `bun test packages/agent-console` 6/6; `bun scripts/check.mjs` OK; `npm run check` OK; vitest 461 passed / 17 skipped; `verify:build` 5/5 identical.
- Windows 11 (Edge): `e2e:v1` 29/29.
- Linux e2e stops at scenario 5 (steer timeout). It does the same on main 1.3.0, so it was filed as #753.
- Broken by hand:
- Pi's modeMap back to bypassPermissions: 2 tests red.
- The keeps line shown for every Agent: 1 test red.
- Pi's label branch removed: 1 test red.
- An earlier round at 049449612 on macOS checked the daemon behaviour with probes. This version is published from the dist branch; the package isn't on npm.
This commit is contained in:
@@ -41,6 +41,20 @@ UI principle: **obvious at a glance, nothing extra**. Three columns — sidebar
|
||||
- **Persistent sessions**: each thread binds to a long-lived Agent process; after a daemon restart, running threads are marked closed and can be resumed (`--resume` / `thread/resume`)
|
||||
- **Multiple Agents**: Claude Code, Codex, Cursor, Copilot, OpenCode, Pi, Devin, dsh; missing CLIs show an install hint
|
||||
- **Model / permission / thinking**: per-thread; four permission modes and five thinking levels (what each Agent actually supports)
|
||||
- **全部自动同意 / Auto-approve all (1.3)**: a permission mode for every Agent; the default stays 每次询问 / Always Ask. While a conversation is in it, a one-line strip above the composer (全部自动同意已开启 on the left, whose tooltip says what it does for this Agent, and a 改回每次询问 link on the right) and a warning-coloured mode chip stay on screen, at any width and in light and dark. What it does per Agent, as the menu hint says:
|
||||
|
||||
| Agent | What 全部自动同意 turns on |
|
||||
| --- | --- |
|
||||
| Codex | `approvalPolicy: never` + `sandbox: danger-full-access`: **the sandbox is off**, nothing asks |
|
||||
| Claude Code | `--permission-mode bypassPermissions` (started with `--allow-dangerously-skip-permissions`): **skips all permission checks** |
|
||||
| Copilot | its Allow All (`allow_all` on, agent mode) |
|
||||
| Devin CLI | its Bypass Permissions mode |
|
||||
| Cursor, OpenCode, dsh | no switch over ACP: Agent / Build mode, and the daemon answers each approval request with its **allow once** option |
|
||||
| Pi | Pi never asks before its tools anyway (its extensions' own dialogs still ask you) |
|
||||
|
||||
The daemon only ever answers with the option for that one request (allow once / accept), never allow-always, so no lasting rule is written into the Agent's own config; when a request offers nothing narrower, the card stays for you. Plan approvals and questions are never answered for you. Every approval it gives is saved in the conversation (`permission_request` + `permission_resolved`, both `auto: true`) and shown as a quiet row after its tool calls, 已自动同意 3 项 · npm test · git status, that opens to each request's title, command or file and the answer. Turning the mode on also approves a card that is already waiting. Only the page (with its token) can switch it on.
|
||||
|
||||
**Upgrading from 1.2.** 1.2's 全部放行 (`bypassPermissions`) did nothing for Cursor and OpenCode (they had no such mode, so it fell back to 每次询问) and dsh still asked; from 1.3 the same setting would really auto-approve for them. It is not escalated silently: on the first 1.3 start, Cursor / OpenCode / dsh conversations saved in that mode go back to 每次询问 with a notice in the conversation, and if your default permission mode was 全部放行, new Cursor / OpenCode / dsh conversations keep starting in 每次询问; the first one shows a notice that the new mode exists, with a button to turn it on there. Claude Code, Codex, Copilot and Devin keep the mode, which already meant the same in 1.2. Choosing the default permission mode again in Settings ends this.
|
||||
- **Structured timeline**: user message → thinking (expandable) → tool calls (read / edit / command, with line-level diffs) → todos → usage and duration; answer permission requests (tools / plan / questions) on the card. Since 1.3 every tool call is one compact row: a type icon, the command or path (monospace, relative to the project, never wrapping), `+N -M` for an edit and the status on the right; click a row for its output or diff, and a failed step opens by itself. A run of more than 6 tool calls (with the short thinking between them) folds into one summary row (改动 2 · 运行 3 · 读取 4 · 搜索 1 · 1 失败) that expands to the same rows; while it runs, one line shows the current step (正在运行:npm test…). The Agent's step list (Claude Code TodoWrite, Codex plan updates, an ACP agent's plan) is a checklist with N/M, and while it has open items an "N/M 个任务" pill above the composer jumps to it. Each reply ends with 复制 · model · time · duration (plus tokens / cost when the Agent reports them). Code blocks have a language label, line numbers, a wrap toggle and a copy button (the copy is the raw code). The look is grayscale and was inspired by [Better Paseo](https://github.com/RoundRedDot/better-paseo) (MIT); no code was copied
|
||||
- **Instant send (1.3)**: your message shows in the timeline the moment you click 发送 and the composer switches to working at once. The daemon saves and pushes the message before it starts the Agent (spawn + ACP `initialize` / `session/new`, seconds on Windows) instead of after; the page draws it right away and swaps in the daemon's copy by a client message id, so it neither doubles nor jumps. A send that fails stays in place marked 发送失败 with 重试 / 移除. A message sent while a turn runs still goes to the queue list
|
||||
- **Steer and queue**: steer while running, queue the next message, interrupt
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+159
-9
@@ -147,6 +147,8 @@ var init_i18n = __esm({
|
||||
"notice.sessionStartFailed": "\u4F1A\u8BDD\u542F\u52A8\u5931\u8D25\uFF1A{detail}",
|
||||
"notice.sendFailed": "\u53D1\u9001\u5931\u8D25\uFF1A{detail}",
|
||||
"notice.bashMissing": "\u6CA1\u6709\u627E\u5230 Git Bash\u3002\u8FD9\u4E2A Agent \u5728 Windows \u4E0A\u8981\u7528 Git Bash \u8FD0\u884C\u547D\u4EE4\uFF08C:\\Windows\\System32\\bash.exe \u662F WSL \u542F\u52A8\u5668\uFF0C\u4E0D\u80FD\u7528\uFF09\u3002\u8BF7\u5B89\u88C5 Git for Windows\uFF1Ahttps://git-scm.com/download/win \uFF0C\u6216\u5728\u300C\u8BBE\u7F6E \u2192 Bash \u8DEF\u5F84\u300D\u91CC\u624B\u52A8\u6307\u5B9A bash.exe\u3002",
|
||||
"notice.autoApproveUpgrade": "1.3 \u65B0\u589E\u300C\u5168\u90E8\u81EA\u52A8\u540C\u610F\u300D\uFF1A\u73B0\u5728\u5BF9 Cursor\u3001OpenCode\u3001dsh \u4E5F\u4F1A\u771F\u6B63\u81EA\u52A8\u540C\u610F\uFF081.2 \u7684\u300C\u5168\u90E8\u653E\u884C\u300D\u5BF9\u5B83\u4EEC\u4E0D\u751F\u6548\uFF0C\u4ECD\u4F1A\u8BE2\u95EE\uFF09\u3002\u4F60\u4E4B\u524D\u628A\u9ED8\u8BA4\u6743\u9650\u6A21\u5F0F\u8BBE\u6210\u4E86\u5B83\uFF0C\u4E3A\u5B89\u5168\u8D77\u89C1\u8FD9\u4E2A\u5BF9\u8BDD\u4ECD\u4ECE\u300C\u6BCF\u6B21\u8BE2\u95EE\u300D\u5F00\u59CB\uFF1B\u9700\u8981\u65F6\u8BF7\u5728\u4E0B\u65B9\u6743\u9650\u83DC\u5355\u91CC\u624B\u52A8\u5F00\u542F\uFF0C\u6216\u5728\u8BBE\u7F6E\u91CC\u91CD\u65B0\u9009\u62E9\u9ED8\u8BA4\u6743\u9650\u6A21\u5F0F\u3002",
|
||||
"notice.autoApproveMigrated": "\u8FD9\u4E2A\u5BF9\u8BDD\u5728 1.2 \u91CC\u8BBE\u6210\u4E86\u300C\u5168\u90E8\u653E\u884C\u300D\uFF0C\u5F53\u65F6\u8FD9\u4E2A Agent \u5B9E\u9645\u4ECD\u4F1A\u8BE2\u95EE\u30021.3 \u8D77\u300C\u5168\u90E8\u81EA\u52A8\u540C\u610F\u300D\u4F1A\u771F\u6B63\u81EA\u52A8\u540C\u610F\uFF0C\u6240\u4EE5\u5DF2\u6539\u56DE\u300C\u6BCF\u6B21\u8BE2\u95EE\u300D\uFF1B\u9700\u8981\u65F6\u8BF7\u5728\u4E0B\u65B9\u6743\u9650\u83DC\u5355\u91CC\u624B\u52A8\u5F00\u542F\u3002",
|
||||
"notice.effortNextTurn": "\u601D\u8003\u5F3A\u5EA6\u5DF2\u4FDD\u5B58\uFF0C\u5C06\u5728\u4E0B\u4E00\u8F6E\u751F\u6548",
|
||||
"notice.effortResetOnModel": "\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u8BE5\u601D\u8003\u5F3A\u5EA6\uFF0C\u5DF2\u6062\u590D\u4E3A Default",
|
||||
"turn.agentExit": "Agent \u8FDB\u7A0B\u610F\u5916\u9000\u51FA",
|
||||
@@ -258,6 +260,8 @@ var init_i18n = __esm({
|
||||
"notice.sessionStartFailed": "Session start failed: {detail}",
|
||||
"notice.sendFailed": "Send failed: {detail}",
|
||||
"notice.bashMissing": "Git Bash was not found. On Windows this agent runs its commands with Git Bash (C:\\Windows\\System32\\bash.exe is the WSL launcher and won't work). Install Git for Windows: https://git-scm.com/download/win , or set bash.exe under Settings \u2192 Bash path.",
|
||||
"notice.autoApproveUpgrade": "New in 1.3: Auto-approve all now really auto-approves for Cursor, OpenCode and dsh too (1.2's bypass mode did nothing for them; they still asked). Your default permission mode was set to it, so to be safe this conversation starts in Always Ask; switch it on in the permission menu below if you want it, or pick the default permission mode again in Settings.",
|
||||
"notice.autoApproveMigrated": "This conversation was set to bypass permissions in 1.2, where this agent still asked anyway. From 1.3 Auto-approve all really auto-approves, so it was put back to Always Ask; switch it on in the permission menu below if you want it.",
|
||||
"notice.effortNextTurn": "Reasoning effort saved \u2014 takes effect on the next turn",
|
||||
"notice.effortResetOnModel": "This model does not support that effort level; reset to Default",
|
||||
"turn.agentExit": "Agent process exited unexpectedly",
|
||||
@@ -4871,7 +4875,7 @@ var init_session3 = __esm({
|
||||
return hit?.id ?? want;
|
||||
}
|
||||
if (this.o.flavor === "cursor") {
|
||||
const map = { default: "agent", plan: "plan", ask: "ask" };
|
||||
const map = { default: "agent", bypassPermissions: "agent", plan: "plan", ask: "ask" };
|
||||
const want = map[mode2] ?? "agent";
|
||||
const avail = this.active?.modes?.availableModes ?? [];
|
||||
const hit = avail.find((m) => m.id === want || m.name.toLowerCase() === want);
|
||||
@@ -5138,7 +5142,7 @@ async function resolveProviderBin(cfg2) {
|
||||
}
|
||||
function createAcpProvider(cfg2) {
|
||||
const base = cfg2.capabilities ?? acpCapabilities;
|
||||
const ORDER = ["plan", "default", "acceptEdits", "bypassPermissions"];
|
||||
const ORDER = ["plan", "default", "acceptEdits", "bypassPermissions", "ask"];
|
||||
const caps = cfg2.modeMap ? { ...base, modes: ORDER.filter((m) => cfg2.modeMap[m] !== void 0), modeLabels: cfg2.modeLabels } : base;
|
||||
return {
|
||||
id: cfg2.id,
|
||||
@@ -5219,7 +5223,9 @@ var init_provider3 = __esm({
|
||||
cursorAcpCapabilities = {
|
||||
...acpCapabilities,
|
||||
questions: true,
|
||||
modes: ["default", "plan", "ask"]
|
||||
// 1.3: bypassPermissions = 全部自动同意: Cursor's agent mode, every approval answered "allow once" by the daemon
|
||||
// (Cursor's own --force only exists at spawn, and Auto-review is not applied over ACP)
|
||||
modes: ["default", "bypassPermissions", "plan", "ask"]
|
||||
};
|
||||
}
|
||||
});
|
||||
@@ -5487,8 +5493,9 @@ function acpConfigForEntry(entry, appVersion) {
|
||||
...base,
|
||||
acpArgs: ["acp"],
|
||||
fetchModels: acpProbeModels(["acp"], entry.id),
|
||||
modeMap: { plan: "plan", default: "build" },
|
||||
modeLabels: { plan: "Plan", default: "Build" }
|
||||
// 1.3: 全部自动同意 = build + the daemon answers each approval "allow once" (OPENCODE_PERMISSION only applies at spawn)
|
||||
modeMap: { plan: "plan", default: "build", bypassPermissions: "build" },
|
||||
modeLabels: { plan: "Plan", default: "Build", bypassPermissions: "Build" }
|
||||
};
|
||||
case "copilot":
|
||||
return {
|
||||
@@ -5866,6 +5873,106 @@ var init_modes = __esm({
|
||||
}
|
||||
});
|
||||
|
||||
// daemon/src/providers/autoApprove.ts
|
||||
function pickAllowOnce(options) {
|
||||
const once = options.find((o) => o.kind === "allow_once");
|
||||
if (once) return once;
|
||||
const plain = options.find((o) => {
|
||||
const s = `${o.id} ${o.label ?? ""}`;
|
||||
return !o.kind?.startsWith("reject") && !REJECT.test(s) && ALLOW.test(s) && !/always|session|总是|始终/i.test(s);
|
||||
});
|
||||
return plain ?? null;
|
||||
}
|
||||
function autoApproveOption(mode2, providerId, req) {
|
||||
if (mode2 !== FULL_AUTO) return null;
|
||||
if (FULL_AUTO_NATIVE[providerId]?.daemonAnswers === false) return null;
|
||||
if (req.kind === "plan" || req.kind === "switch_mode") return null;
|
||||
return pickAllowOnce(req.options);
|
||||
}
|
||||
var FULL_AUTO, FULL_AUTO_NATIVE, REJECT, ALLOW;
|
||||
var init_autoApprove = __esm({
|
||||
"daemon/src/providers/autoApprove.ts"() {
|
||||
FULL_AUTO = "bypassPermissions";
|
||||
FULL_AUTO_NATIVE = {
|
||||
claude: { native: "--permission-mode bypassPermissions (+ --allow-dangerously-skip-permissions)", live: "nextTurn", daemonAnswers: true },
|
||||
codex: { native: "approvalPolicy never + sandbox danger-full-access (turn/start)", live: "nextTurn", daemonAnswers: true },
|
||||
cursor: { native: "none over ACP (--force is spawn-only); ACP mode agent", live: "live", daemonAnswers: true },
|
||||
copilot: { native: "ACP config allow_all = on (agent mode)", live: "live", daemonAnswers: true },
|
||||
opencode: { native: "none over ACP (OPENCODE_PERMISSION is spawn-only); ACP mode build", live: "live", daemonAnswers: true },
|
||||
devin: { native: "ACP mode bypass", live: "live", daemonAnswers: true },
|
||||
dsh: { native: "none known; ACP default mode", live: "live", daemonAnswers: true },
|
||||
// pi never asks before its own tools; requestPermission only carries Pi extensions' own dialogs, which stay with the user
|
||||
pi: { native: "always (Pi has no tool approvals)", live: "live", daemonAnswers: false },
|
||||
mock: { native: "mock", live: "live", daemonAnswers: true }
|
||||
};
|
||||
REJECT = /reject|deny|decline|cancel|never|拒绝/i;
|
||||
ALLOW = /allow|accept|approve|yes|允许|同意/i;
|
||||
}
|
||||
});
|
||||
|
||||
// daemon/src/migrate/autoApprove13.ts
|
||||
var autoApprove13_exports = {};
|
||||
__export(autoApprove13_exports, {
|
||||
LEGACY_NO_AUTO: () => LEGACY_NO_AUTO,
|
||||
MIGRATED_NOTICE_CODE: () => MIGRATED_NOTICE_CODE,
|
||||
UPGRADE_NOTICE_CODE: () => UPGRADE_NOTICE_CODE,
|
||||
endLegacyDefault: () => endLegacyDefault,
|
||||
guardLegacyMode: () => guardLegacyMode,
|
||||
migrateAutoApprove13: () => migrateAutoApprove13,
|
||||
upgradeNotice: () => upgradeNotice
|
||||
});
|
||||
function state(s) {
|
||||
const v = s[KEY];
|
||||
return v && typeof v === "object" && v.done === true ? { done: true, legacyDefault: v.legacyDefault === true, noticed: v.noticed === true } : null;
|
||||
}
|
||||
async function migrateAutoApprove13(stores) {
|
||||
const s = await stores.settings.get();
|
||||
if (state(s)) return { threads: [], legacyDefault: false, skipped: true };
|
||||
const moved = [];
|
||||
for (const t of await stores.threads.list()) {
|
||||
if (t.mode !== FULL_AUTO || !LEGACY_NO_AUTO.has(t.provider)) continue;
|
||||
try {
|
||||
await stores.threads.patch(t.id, { mode: "default" });
|
||||
await stores.threads.appendEvent(t.id, { type: "notice", level: "warn", code: MIGRATED_NOTICE_CODE, message: tr("notice.autoApproveMigrated") });
|
||||
moved.push(t.id);
|
||||
} catch (e) {
|
||||
log("warn", `\u5168\u90E8\u81EA\u52A8\u540C\u610F\u8FC1\u79FB\uFF1A\u5BF9\u8BDD ${t.id} \u5931\u8D25\uFF1A${String(e)}`);
|
||||
}
|
||||
}
|
||||
const legacyDefault = s.defaultMode === FULL_AUTO;
|
||||
await stores.settings.set({ [KEY]: { done: true, legacyDefault, noticed: false } });
|
||||
if (moved.length || legacyDefault) log("info", `\u5168\u90E8\u81EA\u52A8\u540C\u610F\u8FC1\u79FB\uFF1A${moved.length} \u4E2A\u5BF9\u8BDD\u6539\u56DE\u6BCF\u6B21\u8BE2\u95EE\uFF1B\u65E7\u7684\u9ED8\u8BA4\u5168\u90E8\u653E\u884C=${legacyDefault}`);
|
||||
return { threads: moved, legacyDefault, skipped: false };
|
||||
}
|
||||
async function guardLegacyMode(settings, providerId, mode2) {
|
||||
if (mode2 !== FULL_AUTO || !LEGACY_NO_AUTO.has(providerId)) return { mode: mode2, notice: false };
|
||||
const s = await settings.get();
|
||||
const st = state(s);
|
||||
if (!st?.legacyDefault) return { mode: mode2, notice: false };
|
||||
if (st.noticed) return { mode: "default", notice: false };
|
||||
await settings.set({ [KEY]: { ...st, noticed: true } });
|
||||
return { mode: "default", notice: true };
|
||||
}
|
||||
async function endLegacyDefault(settings) {
|
||||
const st = state(await settings.get());
|
||||
if (st?.legacyDefault) await settings.set({ [KEY]: { ...st, legacyDefault: false } });
|
||||
}
|
||||
function upgradeNotice() {
|
||||
return { type: "notice", level: "info", code: UPGRADE_NOTICE_CODE, message: tr("notice.autoApproveUpgrade") };
|
||||
}
|
||||
var LEGACY_NO_AUTO, UPGRADE_NOTICE_CODE, MIGRATED_NOTICE_CODE, KEY;
|
||||
var init_autoApprove13 = __esm({
|
||||
"daemon/src/migrate/autoApprove13.ts"() {
|
||||
init_autoApprove();
|
||||
init_i18n();
|
||||
init_log();
|
||||
LEGACY_NO_AUTO = /* @__PURE__ */ new Set(["cursor", "opencode", "dsh"]);
|
||||
UPGRADE_NOTICE_CODE = "auto_approve_upgrade";
|
||||
MIGRATED_NOTICE_CODE = "auto_approve_migrated";
|
||||
KEY = "autoApproveUpgrade";
|
||||
}
|
||||
});
|
||||
|
||||
// daemon/src/util/mentions.ts
|
||||
import { realpath, stat as stat8 } from "node:fs/promises";
|
||||
import { isAbsolute as isAbsolute2, resolve as resolve3, sep as sep2, win32 as win322, posix as posix2 } from "node:path";
|
||||
@@ -6795,6 +6902,7 @@ function registerMethods(gw, svc) {
|
||||
if (!checked.ok) throw new ApiError("bad_params", `Invalid setting: ${checked.error}`);
|
||||
const before = await svc.settings.get();
|
||||
const next = await svc.settings.set(checked.patch);
|
||||
if ("defaultMode" in checked.patch) await endLegacyDefault(svc.settings);
|
||||
if ("bashPath" in checked.patch && (before.bashPath ?? "") !== (next.bashPath ?? "")) {
|
||||
await refreshAgentShell(typeof next.bashPath === "string" ? next.bashPath : "");
|
||||
}
|
||||
@@ -6944,8 +7052,10 @@ function registerMethods(gw, svc) {
|
||||
throw new ApiError("bad_params", tr("provider.plannedNamed", { name: cat.name }));
|
||||
}
|
||||
const provider = getProvider(p.provider);
|
||||
const mode2 = clampMode(provider?.capabilities.modes ?? [], p.mode);
|
||||
const guard = await guardLegacyMode(svc.settings, p.provider, clampMode(provider?.capabilities.modes ?? [], p.mode));
|
||||
const mode2 = guard.mode;
|
||||
const meta = await svc.threads.create({ ...p, mode: mode2 });
|
||||
if (guard.notice) await svc.threads.appendEvent(meta.id, upgradeNotice());
|
||||
gw.publish("sidebar", { type: "thread.upsert", thread: meta });
|
||||
return meta;
|
||||
}
|
||||
@@ -7286,6 +7396,7 @@ var init_methods = __esm({
|
||||
init_infoCache();
|
||||
init_launch();
|
||||
init_modes();
|
||||
init_autoApprove13();
|
||||
init_i18n();
|
||||
init_mentions();
|
||||
init_openExternal();
|
||||
@@ -8561,6 +8672,8 @@ init_registry();
|
||||
// daemon/src/agents/manager.ts
|
||||
init_launch();
|
||||
init_modes();
|
||||
init_autoApprove13();
|
||||
init_autoApprove();
|
||||
init_attachmentRefs();
|
||||
init_registry();
|
||||
init_catalog();
|
||||
@@ -8967,9 +9080,21 @@ var AgentManager = class {
|
||||
},
|
||||
event: ev
|
||||
};
|
||||
if (ev.type === "permission_request") {
|
||||
const meta = await this.threads.get(threadId);
|
||||
const auto = meta ? autoApproveOption(meta.mode, meta.provider, ev) : null;
|
||||
if (auto) {
|
||||
log("info", `thread ${threadId} \u81EA\u52A8\u540C\u610F ${ev.title.slice(0, 80)} \u2192 ${auto.id}`);
|
||||
await this.appendRaw(threadId, { ...ev, auto: true });
|
||||
await this.appendRaw(threadId, { type: "permission_resolved", requestId: ev.requestId, optionId: auto.id, auto: true });
|
||||
rt.session?.respond(ev.requestId, { optionId: auto.id });
|
||||
return;
|
||||
}
|
||||
}
|
||||
const toolName = ev.detail?.toolName;
|
||||
if (toolName && rt.allowAlways.has(toolName)) {
|
||||
rt.session?.respond(ev.requestId, { optionId: "accept" });
|
||||
const allow = options.find((o) => o.kind === "allow_once") ?? options.find((o) => o.kind === "allow_always");
|
||||
rt.session?.respond(ev.requestId, { optionId: allow?.id ?? "accept" });
|
||||
return;
|
||||
}
|
||||
rt.pending.set(ev.requestId, pending);
|
||||
@@ -9051,6 +9176,22 @@ var AgentManager = class {
|
||||
}
|
||||
rt.session?.respond(requestId, answer);
|
||||
}
|
||||
/** Answer every waiting tool approval with its allow-once option (full-auto just turned on). Returns how many. */
|
||||
async autoApprovePending(threadId, providerId, mode2) {
|
||||
const rt = this.rt(threadId);
|
||||
let n = 0;
|
||||
for (const p of [...rt.pending.values()]) {
|
||||
if (p.kind !== "permission") continue;
|
||||
const ev = p.event;
|
||||
const opt = autoApproveOption(mode2, providerId, { kind: ev.kind, options: p.options });
|
||||
if (!opt) continue;
|
||||
rt.pending.delete(p.requestId);
|
||||
await this.appendRaw(threadId, { type: "permission_resolved", requestId: p.requestId, optionId: opt.id, auto: true });
|
||||
rt.session?.respond(p.requestId, { optionId: opt.id });
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
// ---- interrupt ----
|
||||
async interrupt(threadId) {
|
||||
const rt = this.rt(threadId);
|
||||
@@ -9095,8 +9236,9 @@ var AgentManager = class {
|
||||
this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) });
|
||||
}
|
||||
async setMode(threadId, mode2) {
|
||||
await this.threads.patch(threadId, { mode: mode2 });
|
||||
const meta = await this.threads.patch(threadId, { mode: mode2 });
|
||||
const rt = this.rt(threadId);
|
||||
if (mode2 === FULL_AUTO) await this.autoApprovePending(threadId, meta.provider, mode2);
|
||||
if (rt.session) await rt.session.setMode(mode2);
|
||||
this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) });
|
||||
}
|
||||
@@ -9149,14 +9291,16 @@ var AgentManager = class {
|
||||
rt.commands = [];
|
||||
}
|
||||
rt.status = "idle";
|
||||
const guard = await guardLegacyMode(this.settings, providerId, clampMode(p.capabilities.modes, meta.mode));
|
||||
await this.threads.patch(threadId, {
|
||||
provider: providerId,
|
||||
model: null,
|
||||
mode: clampMode(p.capabilities.modes, meta.mode),
|
||||
mode: guard.mode,
|
||||
effort: null,
|
||||
providerSessionId: null,
|
||||
status: "idle"
|
||||
});
|
||||
if (guard.notice) await this.appendRaw(threadId, upgradeNotice());
|
||||
this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) });
|
||||
}
|
||||
async close(threadId) {
|
||||
@@ -10044,6 +10188,12 @@ async function main() {
|
||||
} catch (e) {
|
||||
log("error", "\u65E7\u6570\u636E\u8FC1\u79FB\u5931\u8D25", { err: String(e) });
|
||||
}
|
||||
try {
|
||||
const { migrateAutoApprove13: migrateAutoApprove132 } = await Promise.resolve().then(() => (init_autoApprove13(), autoApprove13_exports));
|
||||
await migrateAutoApprove132({ settings, threads });
|
||||
} catch (e) {
|
||||
log("error", "\u5168\u90E8\u81EA\u52A8\u540C\u610F\u8FC1\u79FB\u5931\u8D25", { err: String(e) });
|
||||
}
|
||||
const manager = new AgentManager(gateway, threads, projects, settings, attachments);
|
||||
await manager.recoverOnStart();
|
||||
const terminals = new TerminalService(gateway);
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
@@ -7,6 +7,8 @@ import type { AttachmentStore } from "../store/attachments.js";
|
||||
import type { Provider, ProviderSession, SendInput, RespondAnswer, Mode, SlashCommand } from "../providers/types.js";
|
||||
import { launchFromSettings } from "../providers/launch.js";
|
||||
import { clampMode } from "../providers/modes.js";
|
||||
import { guardLegacyMode, upgradeNotice } from "../migrate/autoApprove13.js";
|
||||
import { autoApproveOption, FULL_AUTO } from "../providers/autoApprove.js";
|
||||
import { resolveAttachmentRefs } from "../util/attachmentRefs.js";
|
||||
import { getProvider } from "../providers/registry.js";
|
||||
import { catalogById, providerCreatable } from "../providers/catalog.js";
|
||||
@@ -450,10 +452,25 @@ export class AgentManager {
|
||||
resolve: () => {},
|
||||
event: ev,
|
||||
};
|
||||
// allowAlways hit → approve directly
|
||||
if (ev.type === "permission_request") {
|
||||
// 1.3 全部自动同意: the daemon answers "allow once" itself; no card (the tool call still shows in the timeline)
|
||||
const meta = await this.threads.get(threadId);
|
||||
const auto = meta ? autoApproveOption(meta.mode, meta.provider, ev) : null;
|
||||
if (auto) {
|
||||
// #727 review: every auto-approval leaves a trace. The request (title, command / path / diff, options) and its
|
||||
// answer are persisted like a card the user answered, both marked auto, before the Agent is told to go on.
|
||||
log("info", `thread ${threadId} 自动同意 ${ev.title.slice(0, 80)} → ${auto.id}`);
|
||||
await this.appendRaw(threadId, { ...ev, auto: true });
|
||||
await this.appendRaw(threadId, { type: "permission_resolved", requestId: ev.requestId, optionId: auto.id, auto: true });
|
||||
rt.session?.respond(ev.requestId, { optionId: auto.id });
|
||||
return;
|
||||
}
|
||||
}
|
||||
// allowAlways hit → approve directly (with this request's own allow option, not a guessed id)
|
||||
const toolName = (ev as { detail?: { toolName?: string } }).detail?.toolName;
|
||||
if (toolName && rt.allowAlways.has(toolName)) {
|
||||
rt.session?.respond(ev.requestId, { optionId: "accept" });
|
||||
const allow = options.find((o) => o.kind === "allow_once") ?? options.find((o) => o.kind === "allow_always");
|
||||
rt.session?.respond(ev.requestId, { optionId: allow?.id ?? "accept" });
|
||||
return;
|
||||
}
|
||||
rt.pending.set(ev.requestId, pending);
|
||||
@@ -544,6 +561,23 @@ export class AgentManager {
|
||||
rt.session?.respond(requestId, answer);
|
||||
}
|
||||
|
||||
/** Answer every waiting tool approval with its allow-once option (full-auto just turned on). Returns how many. */
|
||||
private async autoApprovePending(threadId: string, providerId: string, mode: Mode): Promise<number> {
|
||||
const rt = this.rt(threadId);
|
||||
let n = 0;
|
||||
for (const p of [...rt.pending.values()]) {
|
||||
if (p.kind !== "permission") continue;
|
||||
const ev = p.event as { kind?: string };
|
||||
const opt = autoApproveOption(mode, providerId, { kind: ev.kind, options: p.options });
|
||||
if (!opt) continue;
|
||||
rt.pending.delete(p.requestId);
|
||||
await this.appendRaw(threadId, { type: "permission_resolved", requestId: p.requestId, optionId: opt.id, auto: true });
|
||||
rt.session?.respond(p.requestId, { optionId: opt.id });
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
// ---- interrupt ----
|
||||
async interrupt(threadId: string): Promise<void> {
|
||||
const rt = this.rt(threadId);
|
||||
@@ -592,8 +626,10 @@ export class AgentManager {
|
||||
this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) });
|
||||
}
|
||||
async setMode(threadId: string, mode: Mode): Promise<void> {
|
||||
await this.threads.patch(threadId, { mode });
|
||||
const meta = await this.threads.patch(threadId, { mode });
|
||||
const rt = this.rt(threadId);
|
||||
// 1.3: turning 全部自动同意 on also approves the cards already waiting (the user was stuck exactly there)
|
||||
if (mode === FULL_AUTO) await this.autoApprovePending(threadId, meta.provider, mode);
|
||||
if (rt.session) await rt.session.setMode(mode);
|
||||
this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) });
|
||||
}
|
||||
@@ -652,14 +688,17 @@ export class AgentManager {
|
||||
rt.commands = [];
|
||||
}
|
||||
rt.status = "idle";
|
||||
// 1.3 (#727 review 3): same guard as threads.create for a pre-1.3 default of 全部放行
|
||||
const guard = await guardLegacyMode(this.settings, providerId, clampMode(p.capabilities.modes, meta.mode));
|
||||
await this.threads.patch(threadId, {
|
||||
provider: providerId,
|
||||
model: null,
|
||||
mode: clampMode(p.capabilities.modes, meta.mode),
|
||||
mode: guard.mode,
|
||||
effort: null,
|
||||
providerSessionId: null,
|
||||
status: "idle",
|
||||
});
|
||||
if (guard.notice) await this.appendRaw(threadId, upgradeNotice());
|
||||
this.gw.publish("sidebar", { type: "thread.upsert", thread: await this.threads.get(threadId) });
|
||||
}
|
||||
|
||||
|
||||
@@ -68,6 +68,13 @@ async function main(): Promise<void> {
|
||||
} catch (e) {
|
||||
log("error", "旧数据迁移失败", { err: String(e) });
|
||||
}
|
||||
// 1.3 (#727 review 3): a 1.2 "全部放行" never turns into real auto-approval silently for Cursor / OpenCode / dsh
|
||||
try {
|
||||
const { migrateAutoApprove13 } = await import("./migrate/autoApprove13.js");
|
||||
await migrateAutoApprove13({ settings, threads });
|
||||
} catch (e) {
|
||||
log("error", "全部自动同意迁移失败", { err: String(e) });
|
||||
}
|
||||
const manager = new AgentManager(gateway, threads, projects, settings, attachments);
|
||||
await manager.recoverOnStart();
|
||||
const terminals = new TerminalService(gateway);
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
// 1.3 全部自动同意 upgrade safety (#727 review 3).
|
||||
//
|
||||
// In 1.2, "bypassPermissions" (全部放行) only did something for Agents with a native switch (Claude, Codex, Copilot,
|
||||
// Devin). Cursor and OpenCode had no such mode, so a saved default of bypassPermissions was clamped to "default" for
|
||||
// them, and dsh accepted the mode but still asked for every tool. In 1.3 the daemon answers those Agents' approvals
|
||||
// itself, so the same saved setting would silently start approving everything for them.
|
||||
//
|
||||
// Choice: never escalate silently. On the first 1.3 start:
|
||||
// - conversations of those Agents stored in bypassPermissions go back to "default" (每次询问), each with a notice;
|
||||
// - a pre-1.3 default of bypassPermissions is remembered as "legacy": new conversations of those Agents start in
|
||||
// "default" and the first one says once that the new mode exists (the user can switch it on there, explicitly).
|
||||
// Choosing a default permission mode in Settings after the upgrade is a 1.3-era decision and ends the legacy state.
|
||||
// Claude / Codex / Copilot / Devin keep bypassPermissions: for them 1.2 already meant the same thing.
|
||||
import type { SettingsStore } from "../store/settings.js";
|
||||
import type { ThreadsStore } from "../store/threads.js";
|
||||
import type { Mode } from "../timeline/types.js";
|
||||
import { FULL_AUTO } from "../providers/autoApprove.js";
|
||||
import { tr } from "../util/i18n.js";
|
||||
import { log } from "../log.js";
|
||||
|
||||
/** Agents for which 1.2's bypassPermissions did not auto-approve anything */
|
||||
export const LEGACY_NO_AUTO = new Set(["cursor", "opencode", "dsh"]);
|
||||
export const UPGRADE_NOTICE_CODE = "auto_approve_upgrade";
|
||||
export const MIGRATED_NOTICE_CODE = "auto_approve_migrated";
|
||||
|
||||
/** Kept in settings.json; written only by the daemon (not in settingsPatchSchema, so the page cannot set it) */
|
||||
export type AutoApproveUpgradeState = { done: true; legacyDefault: boolean; noticed: boolean };
|
||||
const KEY = "autoApproveUpgrade";
|
||||
|
||||
function state(s: Record<string, unknown>): AutoApproveUpgradeState | null {
|
||||
const v = s[KEY] as Partial<AutoApproveUpgradeState> | undefined;
|
||||
return v && typeof v === "object" && v.done === true
|
||||
? { done: true, legacyDefault: v.legacyDefault === true, noticed: v.noticed === true }
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Runs once, on the first start of a build with this code (fresh installs: nothing to do, just marks it done) */
|
||||
export async function migrateAutoApprove13(stores: { settings: SettingsStore; threads: ThreadsStore }): Promise<{ threads: string[]; legacyDefault: boolean; skipped: boolean }> {
|
||||
const s = await stores.settings.get();
|
||||
if (state(s)) return { threads: [], legacyDefault: false, skipped: true };
|
||||
const moved: string[] = [];
|
||||
for (const t of await stores.threads.list()) {
|
||||
if (t.mode !== FULL_AUTO || !LEGACY_NO_AUTO.has(t.provider)) continue;
|
||||
try {
|
||||
await stores.threads.patch(t.id, { mode: "default" });
|
||||
await stores.threads.appendEvent(t.id, { type: "notice", level: "warn", code: MIGRATED_NOTICE_CODE, message: tr("notice.autoApproveMigrated") });
|
||||
moved.push(t.id);
|
||||
} catch (e) {
|
||||
log("warn", `全部自动同意迁移:对话 ${t.id} 失败:${String(e)}`);
|
||||
}
|
||||
}
|
||||
const legacyDefault = s.defaultMode === FULL_AUTO;
|
||||
await stores.settings.set({ [KEY]: { done: true, legacyDefault, noticed: false } satisfies AutoApproveUpgradeState });
|
||||
if (moved.length || legacyDefault) log("info", `全部自动同意迁移:${moved.length} 个对话改回每次询问;旧的默认全部放行=${legacyDefault}`);
|
||||
return { threads: moved, legacyDefault, skipped: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* The mode a new (or re-pointed) conversation of this Agent really starts in. A pre-1.3 default of bypassPermissions
|
||||
* does not turn into real auto-approval for Agents where it did nothing in 1.2; the first time, a notice says so.
|
||||
*/
|
||||
export async function guardLegacyMode(settings: SettingsStore, providerId: string, mode: Mode): Promise<{ mode: Mode; notice: boolean }> {
|
||||
if (mode !== FULL_AUTO || !LEGACY_NO_AUTO.has(providerId)) return { mode, notice: false };
|
||||
const s = await settings.get();
|
||||
const st = state(s);
|
||||
if (!st?.legacyDefault) return { mode, notice: false };
|
||||
if (st.noticed) return { mode: "default", notice: false };
|
||||
await settings.set({ [KEY]: { ...st, noticed: true } satisfies AutoApproveUpgradeState });
|
||||
return { mode: "default", notice: true };
|
||||
}
|
||||
|
||||
/** The user picked a default permission mode in Settings: their 1.3 choice from now on */
|
||||
export async function endLegacyDefault(settings: SettingsStore): Promise<void> {
|
||||
const st = state(await settings.get());
|
||||
if (st?.legacyDefault) await settings.set({ [KEY]: { ...st, legacyDefault: false } satisfies AutoApproveUpgradeState });
|
||||
}
|
||||
|
||||
/** The one-time notice appended to the conversation the guard kept in 每次询问 */
|
||||
export function upgradeNotice(): { type: "notice"; level: "info"; code: string; message: string } {
|
||||
return { type: "notice", level: "info", code: UPGRADE_NOTICE_CODE, message: tr("notice.autoApproveUpgrade") };
|
||||
}
|
||||
@@ -45,7 +45,9 @@ export const acpCapabilities: Capabilities = {
|
||||
export const cursorAcpCapabilities: Capabilities = {
|
||||
...acpCapabilities,
|
||||
questions: true,
|
||||
modes: ["default", "plan", "ask"],
|
||||
// 1.3: bypassPermissions = 全部自动同意: Cursor's agent mode, every approval answered "allow once" by the daemon
|
||||
// (Cursor's own --force only exists at spawn, and Auto-review is not applied over ACP)
|
||||
modes: ["default", "bypassPermissions", "plan", "ask"],
|
||||
};
|
||||
|
||||
function runVersion(r: ResolveResult & { ok: true }, args: string[], timeoutMs = 8000): Promise<string> {
|
||||
@@ -79,7 +81,7 @@ async function resolveProviderBin(cfg: AcpProviderConfig) {
|
||||
export function createAcpProvider(cfg: AcpProviderConfig): Provider {
|
||||
const base = cfg.capabilities ?? acpCapabilities;
|
||||
// With a mode table, expose only the modes the Agent really has (in our fixed order)
|
||||
const ORDER: Mode[] = ["plan", "default", "acceptEdits", "bypassPermissions"];
|
||||
const ORDER: Mode[] = ["plan", "default", "acceptEdits", "bypassPermissions", "ask"];
|
||||
const caps: Capabilities = cfg.modeMap
|
||||
? { ...base, modes: ORDER.filter((m) => cfg.modeMap![m] !== undefined), modeLabels: cfg.modeLabels }
|
||||
: base;
|
||||
|
||||
@@ -268,7 +268,7 @@ export class AcpSession implements ProviderSession {
|
||||
return hit?.id ?? want;
|
||||
}
|
||||
if (this.o.flavor === "cursor") {
|
||||
const map: Partial<Record<Mode, string>> = { default: "agent", plan: "plan", ask: "ask" };
|
||||
const map: Partial<Record<Mode, string>> = { default: "agent", bypassPermissions: "agent", plan: "plan", ask: "ask" };
|
||||
const want = map[mode] ?? "agent";
|
||||
const avail = this.active?.modes?.availableModes ?? [];
|
||||
const hit = avail.find((m) => m.id === want || m.name.toLowerCase() === want);
|
||||
|
||||
@@ -49,8 +49,9 @@ export function acpConfigForEntry(entry: ProviderCatalogEntry, appVersion: strin
|
||||
...base,
|
||||
acpArgs: ["acp"],
|
||||
fetchModels: acpProbeModels(["acp"], entry.id),
|
||||
modeMap: { plan: "plan", default: "build" },
|
||||
modeLabels: { plan: "Plan", default: "Build" },
|
||||
// 1.3: 全部自动同意 = build + the daemon answers each approval "allow once" (OPENCODE_PERMISSION only applies at spawn)
|
||||
modeMap: { plan: "plan", default: "build", bypassPermissions: "build" },
|
||||
modeLabels: { plan: "Plan", default: "Build", bypassPermissions: "Build" },
|
||||
};
|
||||
case "copilot":
|
||||
// As Paseo: Agent / Plan / Allow All. Allow All = agent mode + allow_all config on (autopilot is not used)
|
||||
@@ -62,7 +63,9 @@ export function acpConfigForEntry(entry: ProviderCatalogEntry, appVersion: strin
|
||||
modeLabels: { plan: "Plan", default: "Agent", bypassPermissions: "Allow All" },
|
||||
};
|
||||
case "pi":
|
||||
// pi-acp has no mode options; thinking level thought_level (low…max)
|
||||
// pi-acp has no mode options; thinking level thought_level (low…max). Pi never asks before its tools, so its one
|
||||
// mode uses the neutral default id (shown read-only; nothing is sent), so switching Agents never carries
|
||||
// bypassPermissions into an Agent the user did not choose. Pi extensions' own dialogs still reach the user.
|
||||
return { ...base, acpArgs: [], fetchModels: acpProbeModels([], entry.id), modeMap: { default: "" } };
|
||||
case "dsh":
|
||||
// Started on the conversation's route (--patch), so its initialize advertises image input for that model (see dsh.ts)
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
// 1.3 "全部自动同意" (full auto-approve): the permission chip's bypassPermissions mode, for every Agent.
|
||||
//
|
||||
// Where the Agent has its own switch we use it (see FULL_AUTO); the daemon also answers every tool approval the Agent
|
||||
// still asks for while the mode is on, so Agents that only ask over their protocol (Cursor / OpenCode / dsh over ACP)
|
||||
// stop asking too, and a card already on screen is approved the moment the user turns the mode on.
|
||||
//
|
||||
// The answer is always the option that covers this one request ("Allow once" / accept), never "Allow always":
|
||||
// an allow-always answer can make the Agent write a permanent rule into the user's own config (Cursor's allowlist,
|
||||
// OpenCode's permission file), which would outlive the mode. Questions and plan approvals are never auto-answered.
|
||||
import type { Mode } from "./types.js";
|
||||
|
||||
export const FULL_AUTO: Mode = "bypassPermissions";
|
||||
|
||||
export type ApprovalOption = { id: string; label?: string; kind?: string };
|
||||
export type ApprovalRequest = { kind?: string; options: ApprovalOption[] };
|
||||
|
||||
/** How full-auto works for each Agent (also the source of the plan's table) */
|
||||
export const FULL_AUTO_NATIVE: Record<string, { native: string; live: "live" | "nextTurn" | "none"; daemonAnswers: boolean }> = {
|
||||
claude: { native: "--permission-mode bypassPermissions (+ --allow-dangerously-skip-permissions)", live: "nextTurn", daemonAnswers: true },
|
||||
codex: { native: "approvalPolicy never + sandbox danger-full-access (turn/start)", live: "nextTurn", daemonAnswers: true },
|
||||
cursor: { native: "none over ACP (--force is spawn-only); ACP mode agent", live: "live", daemonAnswers: true },
|
||||
copilot: { native: "ACP config allow_all = on (agent mode)", live: "live", daemonAnswers: true },
|
||||
opencode: { native: "none over ACP (OPENCODE_PERMISSION is spawn-only); ACP mode build", live: "live", daemonAnswers: true },
|
||||
devin: { native: "ACP mode bypass", live: "live", daemonAnswers: true },
|
||||
dsh: { native: "none known; ACP default mode", live: "live", daemonAnswers: true },
|
||||
// pi never asks before its own tools; requestPermission only carries Pi extensions' own dialogs, which stay with the user
|
||||
pi: { native: "always (Pi has no tool approvals)", live: "live", daemonAnswers: false },
|
||||
mock: { native: "mock", live: "live", daemonAnswers: true },
|
||||
};
|
||||
|
||||
const REJECT = /reject|deny|decline|cancel|never|拒绝/i;
|
||||
const ALLOW = /allow|accept|approve|yes|允许|同意/i;
|
||||
|
||||
/**
|
||||
* The option that allows just this request: kind allow_once, else an allow-looking id/label that is not "always" /
|
||||
* "session". Never allow_always (that writes a lasting rule into the Agent's own config): when a request offers
|
||||
* nothing narrower, null, and the card is left for the user.
|
||||
*/
|
||||
export function pickAllowOnce(options: ApprovalOption[]): ApprovalOption | null {
|
||||
const once = options.find((o) => o.kind === "allow_once");
|
||||
if (once) return once;
|
||||
const plain = options.find((o) => {
|
||||
const s = `${o.id} ${o.label ?? ""}`;
|
||||
return !o.kind?.startsWith("reject") && !REJECT.test(s) && ALLOW.test(s) && !/always|session|总是|始终/i.test(s);
|
||||
});
|
||||
return plain ?? null;
|
||||
}
|
||||
|
||||
/** The daemon answers this request itself: the mode is full-auto, the Agent lets us, it is a tool approval and something allows it */
|
||||
export function autoApproveOption(
|
||||
mode: Mode | null | undefined,
|
||||
providerId: string,
|
||||
req: ApprovalRequest,
|
||||
): ApprovalOption | null {
|
||||
if (mode !== FULL_AUTO) return null;
|
||||
if (FULL_AUTO_NATIVE[providerId]?.daemonAnswers === false) return null;
|
||||
// A plan ("implement this plan?") is a decision, not a tool permission
|
||||
if (req.kind === "plan" || req.kind === "switch_mode") return null;
|
||||
return pickAllowOnce(req.options);
|
||||
}
|
||||
@@ -17,8 +17,8 @@ export type TimelineEvent =
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "tool_call"; itemId: string; kind: ToolKind; title: string; status: "running" | "ok" | "failed"; input?: unknown; detail?: unknown; output?: string; exitCode?: number; durationMs?: number }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "plan"; itemId: string; markdown: string; entries?: { step: string; status: string }[] }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "todo"; items: { text: string; status: string }[] }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "permission_request"; requestId: string; title: string; kind: string; detail?: unknown; options: { id: string; label: string; kind: string }[] }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "permission_resolved"; requestId: string; optionId?: string; cancelled?: boolean }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "permission_request"; requestId: string; title: string; kind: string; detail?: unknown; options: { id: string; label: string; kind: string }[]; auto?: boolean }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "permission_resolved"; requestId: string; optionId?: string; cancelled?: boolean; auto?: boolean }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "question"; requestId: string; questions: unknown[] }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "question_answered"; requestId: string; answers: Record<string, string> }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "usage"; inputTokens: number; outputTokens: number; cacheReadTokens: number; costUsd: number; contextWindow?: number }
|
||||
@@ -37,8 +37,8 @@ export type ProviderEvent =
|
||||
| { type: "tool_call"; itemId: string; kind: string; title: string; status: "running" | "ok" | "failed"; input?: unknown; detail?: unknown; output?: string; exitCode?: number; durationMs?: number }
|
||||
| { type: "plan"; itemId: string; markdown: string; entries?: { step: string; status: string }[] }
|
||||
| { type: "todo"; items: { text: string; status: string }[] }
|
||||
| { type: "permission_request"; requestId: string; title: string; kind: string; detail?: unknown; options: { id: string; label: string; kind: string }[] }
|
||||
| { type: "permission_resolved"; requestId: string; optionId?: string; cancelled?: boolean }
|
||||
| { type: "permission_request"; requestId: string; title: string; kind: string; detail?: unknown; options: { id: string; label: string; kind: string }[]; auto?: boolean }
|
||||
| { type: "permission_resolved"; requestId: string; optionId?: string; cancelled?: boolean; auto?: boolean }
|
||||
| { type: "question"; requestId: string; questions: unknown[] }
|
||||
| { type: "question_answered"; requestId: string; answers: Record<string, string> }
|
||||
| { type: "usage"; inputTokens: number; outputTokens: number; cacheReadTokens: number; costUsd: number; contextWindow?: number }
|
||||
|
||||
@@ -29,6 +29,8 @@ const dict: Record<AppLocale, Record<string, string>> = {
|
||||
"notice.sessionStartFailed": "会话启动失败:{detail}",
|
||||
"notice.sendFailed": "发送失败:{detail}",
|
||||
"notice.bashMissing": "没有找到 Git Bash。这个 Agent 在 Windows 上要用 Git Bash 运行命令(C:\\Windows\\System32\\bash.exe 是 WSL 启动器,不能用)。请安装 Git for Windows:https://git-scm.com/download/win ,或在「设置 → Bash 路径」里手动指定 bash.exe。",
|
||||
"notice.autoApproveUpgrade": "1.3 新增「全部自动同意」:现在对 Cursor、OpenCode、dsh 也会真正自动同意(1.2 的「全部放行」对它们不生效,仍会询问)。你之前把默认权限模式设成了它,为安全起见这个对话仍从「每次询问」开始;需要时请在下方权限菜单里手动开启,或在设置里重新选择默认权限模式。",
|
||||
"notice.autoApproveMigrated": "这个对话在 1.2 里设成了「全部放行」,当时这个 Agent 实际仍会询问。1.3 起「全部自动同意」会真正自动同意,所以已改回「每次询问」;需要时请在下方权限菜单里手动开启。",
|
||||
"notice.effortNextTurn": "思考强度已保存,将在下一轮生效",
|
||||
"notice.effortResetOnModel": "当前模型不支持该思考强度,已恢复为 Default",
|
||||
"turn.agentExit": "Agent 进程意外退出",
|
||||
@@ -140,6 +142,8 @@ const dict: Record<AppLocale, Record<string, string>> = {
|
||||
"notice.sessionStartFailed": "Session start failed: {detail}",
|
||||
"notice.sendFailed": "Send failed: {detail}",
|
||||
"notice.bashMissing": "Git Bash was not found. On Windows this agent runs its commands with Git Bash (C:\\Windows\\System32\\bash.exe is the WSL launcher and won't work). Install Git for Windows: https://git-scm.com/download/win , or set bash.exe under Settings → Bash path.",
|
||||
"notice.autoApproveUpgrade": "New in 1.3: Auto-approve all now really auto-approves for Cursor, OpenCode and dsh too (1.2's bypass mode did nothing for them; they still asked). Your default permission mode was set to it, so to be safe this conversation starts in Always Ask; switch it on in the permission menu below if you want it, or pick the default permission mode again in Settings.",
|
||||
"notice.autoApproveMigrated": "This conversation was set to bypass permissions in 1.2, where this agent still asked anyway. From 1.3 Auto-approve all really auto-approves, so it was put back to Always Ask; switch it on in the permission menu below if you want it.",
|
||||
"notice.effortNextTurn": "Reasoning effort saved — takes effect on the next turn",
|
||||
"notice.effortResetOnModel": "This model does not support that effort level; reset to Default",
|
||||
"turn.agentExit": "Agent process exited unexpectedly",
|
||||
|
||||
@@ -23,6 +23,7 @@ import { clearBinCache } from "../util/bin.js";
|
||||
import { cachedDetect, cachedModels, clearProviderCache } from "../providers/infoCache.js";
|
||||
import { launchFromSettings } from "../providers/launch.js";
|
||||
import { clampMode } from "../providers/modes.js";
|
||||
import { endLegacyDefault, guardLegacyMode, upgradeNotice } from "../migrate/autoApprove13.js";
|
||||
import { setAppLocale, tr, intlLocale } from "../util/i18n.js";
|
||||
import { MAX_MENTIONS } from "../util/mentions.js";
|
||||
import { openExternal } from "../util/openExternal.js";
|
||||
@@ -153,6 +154,8 @@ export function registerMethods(gw: Gateway, svc: Services): void {
|
||||
if (!checked.ok) throw new ApiError("bad_params", `Invalid setting: ${checked.error}`);
|
||||
const before = await svc.settings.get();
|
||||
const next = await svc.settings.set(checked.patch as Partial<Settings>);
|
||||
// 1.3: a default permission mode picked after the upgrade is the user's 1.3 choice (ends the 1.2 全部放行 guard)
|
||||
if ("defaultMode" in checked.patch) await endLegacyDefault(svc.settings);
|
||||
// 1.3: Settings → Bash path (Windows) re-runs Git Bash detection for the next agent start
|
||||
if ("bashPath" in checked.patch && (before.bashPath ?? "") !== (next.bashPath ?? "")) {
|
||||
await refreshAgentShell(typeof next.bashPath === "string" ? next.bashPath : "");
|
||||
@@ -329,8 +332,11 @@ export function registerMethods(gw: Gateway, svc: Services): void {
|
||||
}
|
||||
// B8: the default permission mode is mapped onto this Agent's own modes (same rule as thread.setProvider)
|
||||
const provider = getProvider(p.provider);
|
||||
const mode = clampMode(provider?.capabilities.modes ?? [], p.mode);
|
||||
// 1.3 (#727 review 3): a pre-1.3 default of 全部放行 stays 每次询问 for Agents it did nothing for in 1.2 (told once)
|
||||
const guard = await guardLegacyMode(svc.settings, p.provider, clampMode(provider?.capabilities.modes ?? [], p.mode));
|
||||
const mode = guard.mode;
|
||||
const meta = await svc.threads.create({ ...p, mode });
|
||||
if (guard.notice) await svc.threads.appendEvent(meta.id, upgradeNotice());
|
||||
gw.publish("sidebar", { type: "thread.upsert", thread: meta });
|
||||
return meta;
|
||||
}
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@magpie-community/page-agent-console",
|
||||
"version": "1.3.0",
|
||||
"version": "1.3.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@magpie-community/page-agent-console",
|
||||
"version": "1.3.0",
|
||||
"version": "1.3.1",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "2.1.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/page-agent-console",
|
||||
"version": "1.3.0",
|
||||
"version": "1.3.1",
|
||||
"description": "在 magpie 窗口里加一个「Agent 控制台」页面:用常驻本地服务驱动本机的 Agent CLI(Claude Code、Codex、Cursor 等),带结构化时间线。A Magpie page that drives local Agent CLIs (Claude Code, Codex, Cursor, and others) with a persistent local daemon and a structured timeline.",
|
||||
"author": "qingnian108 (https://github.com/qingnian108)",
|
||||
"homepage": "https://github.com/qingnian108/magpie-agent-console",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// e2e (§11.2): playwright-core + Edge, isolated data directory _tmp/e2e-xdg, port 3497, AGENT_CONSOLE_MOCK=1.
|
||||
// Scenarios 1–12, 16–26 (20, 22–26: 1.3 overlap at 600 px, message actions, quotes, instant send, tool rows / summary,
|
||||
// checklist + pill + reply footer + code block); each prints ✓/✗, and any ✗ exits with code 1.
|
||||
// Scenarios 1–12, 16–27 (20–27: 1.3 overlap at 600 px, 全部自动同意, message actions, quotes, instant send, tool rows / summary,
|
||||
// checklist + pill + reply footer + code block, the 全部自动同意 indicator / trace / upgrade notice); each prints ✓/✗, and any ✗ exits with code 1.
|
||||
// The mock Agent starts slowly (E2E_MOCK_START_MS, default 1200 ms) like a real one on Windows, so every scenario runs
|
||||
// with the user's message arriving before the Agent is up.
|
||||
import { spawn, execFileSync } from "node:child_process";
|
||||
@@ -14,7 +14,7 @@ const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const TMP = join(root, "_tmp");
|
||||
const XDG = join(TMP, "e2e-xdg");
|
||||
const PROJ = join(TMP, "e2e-proj");
|
||||
const PORT = 3497;
|
||||
const PORT = Number(process.env.E2E_PORT || 3497);
|
||||
// Edge / Chrome / Chromium (Windows, macOS, Linux); MSEDGE_PATH or CHROME_PATH may be set
|
||||
const EDGE = findBrowser();
|
||||
|
||||
@@ -80,6 +80,10 @@ async function setup() {
|
||||
g(["add", "-A"]); g(["commit", "-m", "init", "-q"]);
|
||||
} catch (e) { log("[e2e] git init 失败(场景13 会失败):", String(e).slice(0, 120)); }
|
||||
|
||||
// Scenario 27: this data dir is an upgraded 1.2 user whose default was 全部放行 (as migrate/autoApprove13.ts leaves it;
|
||||
// the default itself is 每次询问 here so the mock scenarios keep asking)
|
||||
mkdirSync(join(XDG, "magpie/agent-console"), { recursive: true });
|
||||
writeFileSync(join(XDG, "magpie/agent-console/settings.json"), JSON.stringify({ v1Migrated: true, autoApproveUpgrade: { done: true, legacyDefault: true, noticed: false } }));
|
||||
daemon = spawn("node", [join(root, "daemon/dist/main.js"), "--port", String(PORT), "--data", XDG], {
|
||||
env: { ...process.env, AGENT_CONSOLE_MOCK: "1", AGENT_CONSOLE_MOCK_START_MS: process.env.E2E_MOCK_START_MS ?? "1200" },
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
@@ -486,6 +490,121 @@ async function scenario20() {
|
||||
record("场景20 600px 运行中折叠行/运行行不重叠", approved && seen.size === 0, [...seen].slice(0, 3).join(" | "));
|
||||
}
|
||||
|
||||
async function scenario21() {
|
||||
// 全部自动同意: a waiting card is approved by the switch, the next request never shows a card; both approvals are in
|
||||
// the timeline (#727 review 2) as the quiet 已自动同意 row, not as cards
|
||||
await newThread();
|
||||
await send("/perm");
|
||||
await page.waitForSelector(".card.perm:not(.done)", { timeout: 15000 });
|
||||
await page.click(".mode-chip");
|
||||
await page.click('.mode-menu .sm-opt:has-text("全部自动同意")');
|
||||
await page.waitForSelector('[data-testid="auto-approved"]', { timeout: 8000 });
|
||||
const chipAuto = await page.$(".mode-chip.auto");
|
||||
await waitIdle();
|
||||
await send("/perm");
|
||||
await sleep(500);
|
||||
await waitIdle();
|
||||
const cards = (await page.$$(".card.perm")).length;
|
||||
const rows = await page.$$eval('[data-testid="auto-approved"] .apv-n', (els) => els.map((e) => e.textContent));
|
||||
record("场景21 全部自动同意:待批卡片自动同意,之后不再弹", !!chipAuto && cards === 0 && rows.length === 2 && rows.every((r) => /已自动同意 1 项/.test(r ?? "")), `cards=${cards} rows=${JSON.stringify(rows)}`);
|
||||
}
|
||||
|
||||
async function scenario27() {
|
||||
// #727 review 1–3: the persistent 全部自动同意 indicator at 600 px (light + dark), the auto-approved trace (persisted,
|
||||
// folded, expandable, still there after a reload), and the one-time upgrade notice for a 1.2 全部放行 default
|
||||
await newThread();
|
||||
const tid = await curThread();
|
||||
await page.setViewportSize({ width: 600, height: 860 });
|
||||
const banner = () => page.evaluate(() => {
|
||||
const b = document.querySelector('[data-testid="auto-on"]');
|
||||
if (!b) return null;
|
||||
const r = b.getBoundingClientRect(); const cs = getComputedStyle(b.querySelector("b"));
|
||||
const chip = document.querySelector(".mode-chip.auto");
|
||||
const [cr, cg, cb] = (cs.color.match(/[\d.]+/g) ?? []).map(Number);
|
||||
// No visible hint between the label and the link (Nolan): the per-Agent text is the label's tooltip + description
|
||||
const lab = b.querySelector(".cp-auto-t");
|
||||
const tip = lab?.getAttribute("title") ?? "";
|
||||
const descEl = lab && document.getElementById(lab.getAttribute("aria-describedby") ?? "");
|
||||
const visible = [...b.querySelectorAll(".cp-auto-t, .cp-auto-back")].map((e) => e.innerText).join("|");
|
||||
return { h: Math.round(r.height), hintGone: !b.querySelector(".cp-auto-d"), tip, described: !!descEl && descEl.textContent === tip, visible,
|
||||
onlyTwo: [...b.children].filter((e) => !e.classList.contains("sr-only")).length === 2, text: b.textContent, inView: r.width > 0 && r.top >= 0 && r.bottom <= innerHeight && r.right <= innerWidth + 0.5,
|
||||
warm: cr - cb > 60 && cr > cg, chip: !!chip, theme: document.documentElement.dataset.theme };
|
||||
});
|
||||
const before = await banner();
|
||||
await page.click(".mode-chip");
|
||||
const menuHint = await page.textContent('.mode-menu .sm-opt:has-text("全部自动同意") .sm-hint');
|
||||
await page.click('.mode-menu .sm-opt:has-text("全部自动同意")');
|
||||
await page.waitForSelector('[data-testid="auto-on"]', { timeout: 5000 });
|
||||
const light = await banner();
|
||||
// persists: a turn, another conversation and back, a reload
|
||||
await send("/perm");
|
||||
await waitIdle();
|
||||
const other = await wsCall("threads.create", { projectId: (await wsCall("threads.get", { id: tid })).meta.projectId, provider: "mock", mode: "default" });
|
||||
await page.evaluate(([t]) => { const u = window.__stores.useUi.getState(); u.select(u.currentProjectId, t); }, [other.id]);
|
||||
await sleep(500);
|
||||
const offOther = await banner();
|
||||
await page.evaluate(([t]) => { const u = window.__stores.useUi.getState(); u.select(u.currentProjectId, t); }, [tid]);
|
||||
await page.waitForSelector('[data-testid="auto-on"]', { timeout: 5000 });
|
||||
await page.reload();
|
||||
await page.waitForFunction(() => window.__ws && window.__ws.getState() === "open", null, { timeout: 10000 });
|
||||
await page.waitForFunction((t) => window.__stores?.useUi?.getState?.().currentThreadId === t, tid, { timeout: 10000 });
|
||||
await page.waitForSelector('[data-testid="auto-on"]', { timeout: 8000 });
|
||||
await wsCall("settings.set", { patch: { theme: "dark" } });
|
||||
await page.evaluate(() => { document.documentElement.dataset.theme = "dark"; });
|
||||
await sleep(300);
|
||||
const dark = await banner();
|
||||
await wsCall("settings.set", { patch: { theme: "auto" } });
|
||||
await page.evaluate(() => { document.documentElement.dataset.theme = "light"; });
|
||||
// trace: persisted with auto, shown folded, opens to the command
|
||||
const evs = (await wsCall("threads.get", { id: tid })).events;
|
||||
const req = evs.find((e) => e.type === "permission_request");
|
||||
const res = evs.find((e) => e.type === "permission_resolved");
|
||||
await page.waitForSelector('[data-testid="auto-approved"]', { timeout: 8000 });
|
||||
const collapsed = await page.textContent('[data-testid="auto-approved"] .apv-head');
|
||||
await page.click('[data-testid="auto-approved"] .apv-head');
|
||||
const cmd = await page.textContent('[data-testid="auto-approved"] .apv-cmd').catch(() => null);
|
||||
const meta = await page.textContent('[data-testid="auto-approved"] .apv-meta').catch(() => null);
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
await sleep(200);
|
||||
const wide = await banner();
|
||||
await page.setViewportSize({ width: 600, height: 860 });
|
||||
// back to 每次询问 from the banner
|
||||
await page.click(".cp-auto-back");
|
||||
await page.waitForFunction(() => !document.querySelector('[data-testid="auto-on"]'), null, { timeout: 5000 });
|
||||
const modeAfter = (await wsCall("threads.get", { id: tid })).meta.mode;
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
const okBanner = !before && !!light?.inView && light.warm && light.chip && /全部自动同意已开启/.test(light.text) && !offOther
|
||||
&& !!dark?.inView && dark.warm && dark.theme === "dark"
|
||||
// one slim line (Nolan): never wraps; only 全部自动同意已开启 + 改回每次询问 are visible, the per-Agent text is the tooltip
|
||||
&& light.h <= 26 && dark.h <= 26 && !!wide && wide.h <= 26 && light.hintGone && dark.hintGone && light.onlyTwo
|
||||
&& light.visible === "全部自动同意已开启|改回每次询问" && light.described && /计划确认/.test(light.tip);
|
||||
const okTrace = req?.auto === true && res?.auto === true && res.requestId === req.requestId && /已自动同意 1 项/.test(collapsed ?? "")
|
||||
&& /npm test/.test(collapsed ?? "") && /npm test/.test(cmd ?? "") && /全部自动同意/.test(meta ?? "");
|
||||
record("场景27a 全部自动同意:600px 常驻提示(浅/深色)+ 菜单写明", okBanner && /允许一次|跳过|沙箱/.test(menuHint ?? "") && modeAfter === "default",
|
||||
JSON.stringify({ before: !!before, light, dark, wideH: wide?.h, offOther: !!offOther, menuHint, modeAfter }).slice(0, 500));
|
||||
record("场景27b 自动同意留痕:持久化 auto + 折叠行可展开", okTrace, JSON.stringify({ collapsed, cmd, meta, req: req?.auto, res: res?.auto }).slice(0, 400));
|
||||
|
||||
// upgrade: a 1.2 全部放行 default does not become real auto-approval for Cursor; told once
|
||||
const projectId = (await wsCall("threads.get", { id: tid })).meta.projectId;
|
||||
const c1 = await wsCall("threads.create", { projectId, provider: "cursor", mode: "bypassPermissions" });
|
||||
const c2 = await wsCall("threads.create", { projectId, provider: "cursor", mode: "bypassPermissions" });
|
||||
const m1 = await wsCall("threads.get", { id: c1.id });
|
||||
const m2 = await wsCall("threads.get", { id: c2.id });
|
||||
await page.evaluate(([p, t]) => window.__stores.useUi.getState().select(p, t), [projectId, c1.id]);
|
||||
await page.waitForSelector('[data-testid="auto-upgrade-notice"]', { timeout: 8000 });
|
||||
const noticeText = await page.textContent('[data-testid="auto-upgrade-notice"]');
|
||||
const bannerOnCursor = await page.$('[data-testid="auto-on"]');
|
||||
await page.click('[data-testid="auto-upgrade-notice"] .btn:has-text("开启")');
|
||||
await waitFor(async () => (await wsCall("threads.get", { id: c1.id })).meta.mode === "bypassPermissions", 5000, "开启全部自动同意");
|
||||
await page.waitForSelector('[data-testid="auto-on"]', { timeout: 5000 });
|
||||
const cursorHint = await page.getAttribute('[data-testid="auto-on"] .cp-auto-t', "title");
|
||||
const okUp = m1.meta.mode === "default" && m2.meta.mode === "default"
|
||||
&& m1.events.filter((e) => e.code === "auto_approve_upgrade").length === 1 && m2.events.length === 0
|
||||
&& /Cursor/.test(noticeText ?? "") && !bannerOnCursor && /允许一次/.test(cursorHint ?? "");
|
||||
record("场景27c 升级:1.2 全部放行默认值对 Cursor 不静默升级,只提示一次", okUp,
|
||||
JSON.stringify({ m1: m1.meta.mode, m2: m2.meta.mode, n1: m1.events.map((e) => e.code), n2: m2.events.length, cursorHint }).slice(0, 400));
|
||||
}
|
||||
|
||||
async function scenario22() {
|
||||
// User-message actions: under the bubble, reachable without a hover gap, copy feedback, edit fills the input
|
||||
await newThread();
|
||||
@@ -769,10 +888,10 @@ async function main() {
|
||||
await setup();
|
||||
try {
|
||||
await newProjectFlow();
|
||||
// E2E_ONLY_13=1 runs just the 1.3 scenarios (20–23) and the console-error check
|
||||
// E2E_ONLY_13=1 runs just the 1.3 scenarios (20–27) and the console-error check
|
||||
const all = [scenario2, scenario3, scenario4, scenario5, scenario6, scenario7, scenario8, scenario9, scenario10, scenario11,
|
||||
scenario12, scenario13, scenario14, scenario15, scenario16, scenario17, scenario18, scenario20, scenario22, scenario23, scenario24, scenario25, scenario26, scenario19];
|
||||
const only13 = new Set([scenario20, scenario22, scenario23, scenario24, scenario25, scenario26, scenario19]);
|
||||
scenario12, scenario13, scenario14, scenario15, scenario16, scenario17, scenario18, scenario20, scenario21, scenario22, scenario23, scenario24, scenario25, scenario26, scenario27, scenario19];
|
||||
const only13 = new Set([scenario20, scenario21, scenario22, scenario23, scenario24, scenario25, scenario26, scenario27, scenario19]);
|
||||
for (const f of all) if (!process.env.E2E_ONLY_13 || only13.has(f)) await f();
|
||||
} catch (e) {
|
||||
record("中途异常", false, String(e?.message ?? e).slice(0, 600) + " ||daemon:" + daemonErr.slice(-4).join("|").slice(0, 400));
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
// 1.3 全部自动同意 upgrade (#727 review 3): a 1.2 全部放行 never becomes real auto-approval silently for the Agents it
|
||||
// did nothing for in 1.2 (Cursor / OpenCode / dsh); Claude / Codex keep it (it meant the same there).
|
||||
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { ThreadsStore } from "../../daemon/src/store/threads.js";
|
||||
import { SettingsStore, parseSettingsPatch } from "../../daemon/src/store/settings.js";
|
||||
import {
|
||||
migrateAutoApprove13, guardLegacyMode, endLegacyDefault, LEGACY_NO_AUTO, MIGRATED_NOTICE_CODE, upgradeNotice, UPGRADE_NOTICE_CODE,
|
||||
} from "../../daemon/src/migrate/autoApprove13.js";
|
||||
|
||||
let dir: string;
|
||||
beforeEach(() => { dir = mkdtempSync(join(tmpdir(), "ac-up-")); });
|
||||
afterEach(() => rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }));
|
||||
|
||||
const stores = () => ({ settings: new SettingsStore(dir), threads: new ThreadsStore(dir) });
|
||||
|
||||
describe("migrateAutoApprove13", () => {
|
||||
it("an upgraded 1.2 user: Cursor/OpenCode/dsh conversations in bypass go back to 每次询问 with a notice; others keep it", async () => {
|
||||
writeFileSync(join(dir, "settings.json"), JSON.stringify({ defaultMode: "bypassPermissions", v1Migrated: true }));
|
||||
const s = stores();
|
||||
const mk = (provider: string, mode: "bypassPermissions" | "default") => s.threads.create({ projectId: "p", provider, mode });
|
||||
const cur = await mk("cursor", "bypassPermissions");
|
||||
const oc = await mk("opencode", "bypassPermissions");
|
||||
const dsh = await mk("dsh", "bypassPermissions");
|
||||
const cl = await mk("claude", "bypassPermissions");
|
||||
const cx = await mk("codex", "bypassPermissions");
|
||||
const curDef = await mk("cursor", "default");
|
||||
const r = await migrateAutoApprove13(s);
|
||||
expect(r.skipped).toBe(false);
|
||||
expect(r.legacyDefault).toBe(true);
|
||||
expect(r.threads.sort()).toEqual([cur.id, oc.id, dsh.id].sort());
|
||||
for (const t of [cur, oc, dsh]) {
|
||||
expect((await s.threads.get(t.id))?.mode).toBe("default");
|
||||
const evs = await s.threads.readEvents(t.id, 0, 10);
|
||||
expect(evs.map((e) => (e as { code?: string }).code)).toEqual([MIGRATED_NOTICE_CODE]);
|
||||
}
|
||||
for (const t of [cl, cx]) expect((await s.threads.get(t.id))?.mode).toBe("bypassPermissions");
|
||||
expect((await s.threads.readEvents(curDef.id, 0, 10)).length).toBe(0);
|
||||
// runs once
|
||||
const again = await migrateAutoApprove13(stores());
|
||||
expect(again.skipped).toBe(true);
|
||||
});
|
||||
|
||||
it("a fresh install (or a default that is not 全部放行) has nothing to guard", async () => {
|
||||
const s = stores();
|
||||
const r = await migrateAutoApprove13(s);
|
||||
expect(r.legacyDefault).toBe(false);
|
||||
expect(await guardLegacyMode(s.settings, "cursor", "bypassPermissions")).toEqual({ mode: "bypassPermissions", notice: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe("guardLegacyMode", () => {
|
||||
it("new Cursor/OpenCode/dsh conversations from a 1.2 全部放行 default start in 每次询问; told once; Claude unaffected", async () => {
|
||||
writeFileSync(join(dir, "settings.json"), JSON.stringify({ defaultMode: "bypassPermissions" }));
|
||||
const s = stores();
|
||||
await migrateAutoApprove13(s);
|
||||
expect(await guardLegacyMode(s.settings, "claude", "bypassPermissions")).toEqual({ mode: "bypassPermissions", notice: false });
|
||||
expect(await guardLegacyMode(s.settings, "codex", "bypassPermissions")).toEqual({ mode: "bypassPermissions", notice: false });
|
||||
expect(await guardLegacyMode(s.settings, "cursor", "bypassPermissions")).toEqual({ mode: "default", notice: true });
|
||||
expect(await guardLegacyMode(s.settings, "opencode", "bypassPermissions")).toEqual({ mode: "default", notice: false });
|
||||
expect(await guardLegacyMode(s.settings, "dsh", "bypassPermissions")).toEqual({ mode: "default", notice: false });
|
||||
expect(await guardLegacyMode(s.settings, "cursor", "plan")).toEqual({ mode: "plan", notice: false });
|
||||
// survives a daemon restart
|
||||
expect(await guardLegacyMode(new SettingsStore(dir), "cursor", "bypassPermissions")).toEqual({ mode: "default", notice: false });
|
||||
// the user picks the default again in Settings (a 1.3 decision): from then on it is honoured
|
||||
await endLegacyDefault(s.settings);
|
||||
expect(await guardLegacyMode(s.settings, "cursor", "bypassPermissions")).toEqual({ mode: "bypassPermissions", notice: false });
|
||||
});
|
||||
|
||||
it("the guard state can't be set from the page, and the notice has its code", () => {
|
||||
expect(parseSettingsPatch({ autoApproveUpgrade: { done: true, legacyDefault: false, noticed: true } }).ok).toBe(false);
|
||||
expect(upgradeNotice().code).toBe(UPGRADE_NOTICE_CODE);
|
||||
expect([...LEGACY_NO_AUTO].sort()).toEqual(["cursor", "dsh", "opencode"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,249 @@
|
||||
// 1.3 全部自动同意: per-Agent mode mapping, the allow-once pick, and the daemon auto-approve path (never when the mode is off).
|
||||
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { AgentManager } from "../../daemon/src/agents/manager.js";
|
||||
import { ThreadsStore } from "../../daemon/src/store/threads.js";
|
||||
import { ProjectsStore } from "../../daemon/src/store/projects.js";
|
||||
import { SettingsStore, parseSettingsPatch } from "../../daemon/src/store/settings.js";
|
||||
import { AttachmentStore } from "../../daemon/src/store/attachments.js";
|
||||
import { Gateway } from "../../daemon/src/ws/gateway.js";
|
||||
import { initProviders, getProvider } from "../../daemon/src/providers/registry.js";
|
||||
import { autoApproveOption, pickAllowOnce, FULL_AUTO_NATIVE } from "../../daemon/src/providers/autoApprove.js";
|
||||
import { acpConfigForEntry } from "../../daemon/src/providers/acp/specs.js";
|
||||
import { createAcpProvider, cursorAcpCapabilities } from "../../daemon/src/providers/acp/provider.js";
|
||||
import { catalogById } from "../../daemon/src/providers/catalog.js";
|
||||
import { clampMode } from "../../daemon/src/providers/modes.js";
|
||||
import { clearProviderCache } from "../../daemon/src/providers/infoCache.js";
|
||||
import { claudeArgs } from "../../daemon/src/providers/claude/cli.js";
|
||||
import type { Config } from "../../daemon/src/config.js";
|
||||
import type { Mode } from "../../daemon/src/providers/types.js";
|
||||
|
||||
process.env.AGENT_CONSOLE_MOCK = "1";
|
||||
|
||||
const ACP_OPTS = [
|
||||
{ id: "allow-once", label: "Allow once", kind: "allow_once" },
|
||||
{ id: "allow-always", label: "Allow always", kind: "allow_always" },
|
||||
{ id: "reject-once", label: "Reject", kind: "reject_once" },
|
||||
];
|
||||
|
||||
describe("pickAllowOnce", () => {
|
||||
it("prefers allow_once over allow_always (no permanent rule in the user's config)", () => {
|
||||
expect(pickAllowOnce(ACP_OPTS)?.id).toBe("allow-once");
|
||||
expect(pickAllowOnce([...ACP_OPTS].reverse())?.id).toBe("allow-once");
|
||||
});
|
||||
it("Codex / Claude / OpenCode option sets", () => {
|
||||
expect(pickAllowOnce([{ id: "accept", kind: "allow_once" }, { id: "acceptForSession", kind: "allow_always" }, { id: "decline", kind: "reject_once" }])?.id).toBe("accept");
|
||||
expect(pickAllowOnce([{ id: "allow", kind: "allow_once" }, { id: "allow_always", kind: "allow_always" }, { id: "deny", kind: "reject_once" }])?.id).toBe("allow");
|
||||
expect(pickAllowOnce([{ id: "once", kind: "allow_once" }, { id: "always", kind: "allow_always" }, { id: "reject", kind: "reject_once" }])?.id).toBe("once");
|
||||
});
|
||||
it("without kinds: an allow-looking option that is not 'always', never a reject", () => {
|
||||
expect(pickAllowOnce([{ id: "deny" }, { id: "always_allow" }, { id: "approve" }])?.id).toBe("approve");
|
||||
expect(pickAllowOnce([{ id: "reject" }, { id: "cancel" }])).toBeNull();
|
||||
});
|
||||
it("never allow_always: with nothing narrower the card stays for the user", () => {
|
||||
expect(pickAllowOnce([{ id: "a", kind: "allow_always" }, { id: "r", kind: "reject_once" }])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("autoApproveOption", () => {
|
||||
const req = { kind: "execute", options: ACP_OPTS };
|
||||
it("never fires when the mode is not full-auto", () => {
|
||||
for (const m of ["default", "plan", "acceptEdits", "ask", null, undefined] as (Mode | null | undefined)[]) {
|
||||
for (const p of Object.keys(FULL_AUTO_NATIVE)) expect(autoApproveOption(m, p, req)).toBeNull();
|
||||
}
|
||||
});
|
||||
it("fires for every Agent that lets the daemon answer", () => {
|
||||
for (const p of ["claude", "codex", "cursor", "copilot", "opencode", "devin", "dsh", "mock"]) {
|
||||
expect(autoApproveOption("bypassPermissions", p, req)?.id).toBe("allow-once");
|
||||
}
|
||||
});
|
||||
it("leaves Pi extension dialogs, plan approvals and mode switches to the user", () => {
|
||||
expect(autoApproveOption("bypassPermissions", "pi", req)).toBeNull();
|
||||
expect(autoApproveOption("bypassPermissions", "claude", { kind: "plan", options: [{ id: "implement", kind: "allow_once" }] })).toBeNull();
|
||||
expect(autoApproveOption("bypassPermissions", "cursor", { kind: "switch_mode", options: ACP_OPTS })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("mode mapping per Agent", () => {
|
||||
const acp = (id: string) => {
|
||||
const entry = catalogById(id);
|
||||
expect(entry).toBeTruthy();
|
||||
return createAcpProvider(acpConfigForEntry(entry!, "0.0.0")!);
|
||||
};
|
||||
it("every Agent that has a full-auto choice offers 全部自动同意 (bypassPermissions)", () => {
|
||||
for (const id of ["cursor", "devin", "opencode", "copilot", "dsh"]) {
|
||||
expect(acp(id).capabilities.modes, id).toContain("bypassPermissions");
|
||||
}
|
||||
});
|
||||
it("Cursor: Agent / 全部自动同意 / Plan / Ask", () => {
|
||||
expect(cursorAcpCapabilities.modes).toEqual(["default", "bypassPermissions", "plan", "ask"]);
|
||||
});
|
||||
it("OpenCode: full-auto runs in build; Copilot: allow-all; Devin: bypass", () => {
|
||||
const oc = acpConfigForEntry(catalogById("opencode")!, "0")!;
|
||||
expect(oc.modeMap?.bypassPermissions).toBe("build");
|
||||
expect(acpConfigForEntry(catalogById("copilot")!, "0")!.modeMap?.bypassPermissions).toBe("allow-all");
|
||||
expect(acpConfigForEntry(catalogById("devin")!, "0")!.modeMap?.bypassPermissions).toBe("bypass");
|
||||
});
|
||||
it("Pi persists its single mode as default and sends no ACP mode override", () => {
|
||||
const pi = acp("pi");
|
||||
const config = acpConfigForEntry(catalogById("pi")!, "0")!;
|
||||
expect(pi.capabilities.modes).toEqual(["default"]);
|
||||
expect(config.modeMap).toEqual({ default: "" });
|
||||
expect(clampMode(pi.capabilities.modes, "default")).toBe("default");
|
||||
// Full-auto from another Agent cannot become Pi's persisted mode either.
|
||||
expect(clampMode(pi.capabilities.modes, "bypassPermissions")).toBe("default");
|
||||
});
|
||||
it("Claude: bypassPermissions goes to --permission-mode and is allowed at launch", () => {
|
||||
const a = claudeArgs({ model: null, permissionMode: "bypassPermissions", effort: null, resume: null });
|
||||
expect(a.join(" ")).toContain("--permission-mode bypassPermissions");
|
||||
expect(a).toContain("--allow-dangerously-skip-permissions");
|
||||
expect(claudeArgs({ model: null, permissionMode: "default", effort: null, resume: null })).not.toContain("--allow-dangerously-skip-permissions");
|
||||
});
|
||||
it("the unused warning flag is refused; the real default-mode setting is still accepted", () => {
|
||||
expect(parseSettingsPatch({ autoApproveWarned: true }).ok).toBe(false);
|
||||
expect(parseSettingsPatch({ defaultMode: "bypassPermissions" }).ok).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---- the daemon path, with the mock Agent (/perm asks once for "npm test") ----
|
||||
const cfg: Config = { port: 0, dataDir: "", token: "t", version: "0.0.0", idleExitMinutes: 60, buildStamp: "0" };
|
||||
let dir: string, threads: ThreadsStore, manager: AgentManager, threadId: string, projectId: string;
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
const waitFor = async (fn: () => boolean | Promise<boolean>, ms = 10000) => {
|
||||
const t0 = Date.now();
|
||||
while (Date.now() - t0 < ms) { if (await fn()) return; await sleep(30); }
|
||||
throw new Error("waitFor timeout");
|
||||
};
|
||||
const events = () => threads.readEvents(threadId, 0, 50000);
|
||||
const idle = () => waitFor(async () => (await threads.get(threadId))?.status === "idle", 15000);
|
||||
|
||||
describe("AgentManager provider switching", () => {
|
||||
beforeEach(async () => {
|
||||
dir = mkdtempSync(join(tmpdir(), "ac-auto-switch-"));
|
||||
threads = new ThreadsStore(dir);
|
||||
const projects = new ProjectsStore(dir);
|
||||
manager = new AgentManager(new Gateway(cfg), threads, projects, new SettingsStore(dir), new AttachmentStore(join(dir, "att")));
|
||||
projectId = (await projects.create(dir)).id;
|
||||
});
|
||||
afterEach(async () => {
|
||||
await manager.shutdown();
|
||||
rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
|
||||
});
|
||||
|
||||
it("Pi's default id does not arm another Agent, including on a round trip", async () => {
|
||||
initProviders();
|
||||
const agents = ["pi", "codex", "claude", "cursor", "opencode", "dsh", "copilot", "devin"];
|
||||
for (const id of agents) {
|
||||
getProvider(id)!.detect = async () => ({ available: true, bin: "test-double" });
|
||||
clearProviderCache(id);
|
||||
}
|
||||
const pi = getProvider("pi")!;
|
||||
threadId = (await threads.create({
|
||||
projectId,
|
||||
provider: "pi",
|
||||
mode: clampMode(pi.capabilities.modes, "default"),
|
||||
})).id;
|
||||
expect((await threads.get(threadId))?.mode).toBe("default");
|
||||
|
||||
for (const id of agents.slice(1)) {
|
||||
await manager.setProvider(threadId, "pi");
|
||||
await manager.setProvider(threadId, id);
|
||||
expect((await threads.get(threadId))?.mode, `Pi → ${id}`).toBe("default");
|
||||
}
|
||||
|
||||
await manager.setProvider(threadId, "pi");
|
||||
expect((await threads.get(threadId))?.mode).toBe("default");
|
||||
await manager.setProvider(threadId, "codex");
|
||||
expect((await threads.get(threadId))?.mode).toBe("default");
|
||||
});
|
||||
});
|
||||
|
||||
describe("AgentManager auto-approve", () => {
|
||||
beforeEach(async () => {
|
||||
dir = mkdtempSync(join(tmpdir(), "ac-auto-"));
|
||||
threads = new ThreadsStore(dir);
|
||||
const projects = new ProjectsStore(dir);
|
||||
initProviders();
|
||||
manager = new AgentManager(new Gateway(cfg), threads, projects, new SettingsStore(dir), new AttachmentStore(join(dir, "att")));
|
||||
const proj = await projects.create(dir);
|
||||
threadId = (await threads.create({ projectId: proj.id, provider: "mock" })).id;
|
||||
});
|
||||
afterEach(async () => { await manager.shutdown(); await sleep(50); rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }); });
|
||||
|
||||
it("mode on: the request is answered allow-once by the daemon, and the approval is persisted (auto) in the timeline", async () => {
|
||||
await manager.setMode(threadId, "bypassPermissions");
|
||||
await manager.send(threadId, { text: "/perm" });
|
||||
await idle();
|
||||
const evs = await events();
|
||||
// #727 review: no silent approvals. The request (what was approved) and its answer are both in the timeline, marked auto
|
||||
const iReq = evs.findIndex((e) => e.type === "permission_request");
|
||||
const iRes = evs.findIndex((e) => e.type === "permission_resolved");
|
||||
const iOk = evs.findIndex((e) => e.type === "tool_call" && (e as { status?: string }).status === "ok");
|
||||
expect(iReq).toBeGreaterThanOrEqual(0);
|
||||
const req = evs[iReq] as { auto?: boolean; title?: string; requestId?: string; detail?: { command?: string } };
|
||||
expect(req.auto).toBe(true);
|
||||
expect(req.title).toBeTruthy();
|
||||
const res = evs[iRes] as { auto?: boolean; optionId?: string; requestId?: string };
|
||||
expect(res).toMatchObject({ auto: true, optionId: "accept", requestId: req.requestId });
|
||||
// written before the Agent was told to go on
|
||||
expect(iRes).toBeGreaterThan(iReq);
|
||||
expect(iOk).toBeGreaterThan(iRes);
|
||||
expect(manager.runtimeInfo(threadId)?.pending ?? []).toHaveLength(0);
|
||||
}, 20000);
|
||||
|
||||
it("mode off: nothing is answered for the user, the card waits", async () => {
|
||||
await manager.send(threadId, { text: "/perm" });
|
||||
await waitFor(async () => (await events()).some((e) => e.type === "permission_request"));
|
||||
await sleep(400);
|
||||
const evs = await events();
|
||||
expect(evs.some((e) => e.type === "permission_resolved")).toBe(false);
|
||||
expect(evs.some((e) => e.type === "tool_call" && (e as { status?: string }).status === "ok")).toBe(false);
|
||||
expect((await threads.get(threadId))?.status).toBe("running");
|
||||
await manager.interrupt(threadId);
|
||||
await idle();
|
||||
}, 20000);
|
||||
|
||||
it("acceptEdits / plan are not full-auto either", async () => {
|
||||
await manager.setMode(threadId, "acceptEdits");
|
||||
await manager.send(threadId, { text: "/perm" });
|
||||
await waitFor(async () => (await events()).some((e) => e.type === "permission_request"));
|
||||
await sleep(300);
|
||||
expect((await events()).some((e) => e.type === "permission_resolved")).toBe(false);
|
||||
await manager.interrupt(threadId);
|
||||
await idle();
|
||||
}, 20000);
|
||||
|
||||
it("a card already waiting is approved (allow once, marked auto) when the mode is switched on", async () => {
|
||||
await manager.send(threadId, { text: "/perm" });
|
||||
await waitFor(async () => (await events()).some((e) => e.type === "permission_request"));
|
||||
await manager.setMode(threadId, "bypassPermissions");
|
||||
await idle();
|
||||
const evs = await events();
|
||||
const res = evs.find((e) => e.type === "permission_resolved") as { optionId?: string; auto?: boolean } | undefined;
|
||||
expect(res?.optionId).toBe("accept");
|
||||
expect(res?.auto).toBe(true);
|
||||
expect(evs.some((e) => e.type === "tool_call" && (e as { status?: string }).status === "ok")).toBe(true);
|
||||
}, 20000);
|
||||
|
||||
it("switching to another mode does not approve a waiting card", async () => {
|
||||
await manager.send(threadId, { text: "/perm" });
|
||||
await waitFor(async () => (await events()).some((e) => e.type === "permission_request"));
|
||||
await manager.setMode(threadId, "acceptEdits");
|
||||
await sleep(300);
|
||||
expect((await events()).some((e) => e.type === "permission_resolved")).toBe(false);
|
||||
await manager.interrupt(threadId);
|
||||
await idle();
|
||||
}, 20000);
|
||||
|
||||
it("a plan approval is never auto-answered", async () => {
|
||||
await manager.setMode(threadId, "bypassPermissions");
|
||||
await manager.send(threadId, { text: "/plan" });
|
||||
await waitFor(async () => (await events()).some((e) => e.type === "permission_request"));
|
||||
await sleep(300);
|
||||
expect((await events()).some((e) => e.type === "permission_resolved")).toBe(false);
|
||||
await manager.interrupt(threadId);
|
||||
await idle();
|
||||
}, 20000);
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
// 1.3 全部自动同意 (#727 review item 2): auto-approvals are in the timeline and shown as one quiet foldable row per run
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { foldTimeline } from "../../web/src/timeline/fold.js";
|
||||
import { collectAutoApproved, approvalTarget, approvalChoice } from "../../web/src/timeline/autoApproved.js";
|
||||
import { reduceTimeline, type DisplayItem } from "../../web/src/timeline/reducer.js";
|
||||
|
||||
type Ev = Record<string, unknown>;
|
||||
let seq = 0;
|
||||
const tl = (evs: Ev[]) => evs.map((e) => ({ seq: ++seq, ts: 0, threadId: "t", turnId: "u1", ...e })) as never[];
|
||||
const tool = (itemId: string, kind: string, status: string): Ev => ({ type: "tool_call", itemId, kind, title: `${kind} ${itemId}`, status });
|
||||
const opts = [{ id: "once", label: "允许一次", kind: "allow_once" }, { id: "always", label: "总是允许", kind: "allow_always" }, { id: "no", label: "拒绝", kind: "reject_once" }];
|
||||
const autoReq = (id: string, command: string): Ev[] => [
|
||||
{ type: "permission_request", requestId: id, title: `运行 ${command}`, kind: "tool", detail: { command }, options: opts, auto: true },
|
||||
{ type: "permission_resolved", requestId: id, optionId: "once", auto: true },
|
||||
];
|
||||
const show = (evs: Ev[], status = "idle") => foldTimeline(collectAutoApproved(reduceTimeline(tl(evs), { runtimeStatus: status }).items));
|
||||
const kinds = (items: DisplayItem[]) => items.map((i) => i.kind);
|
||||
|
||||
describe("auto-approved trace", () => {
|
||||
it("a run's auto approvals become one row after the run, and don't break the tool summary", () => {
|
||||
const items = show([
|
||||
{ type: "user_message", text: "跑测试" },
|
||||
tool("a", "bash", "running"), ...autoReq("r1", "npm test"), tool("a", "bash", "ok"),
|
||||
tool("b", "bash", "running"), ...autoReq("r2", "git status"), tool("b", "bash", "ok"),
|
||||
{ type: "assistant_message", itemId: "m", text: "好了" },
|
||||
]);
|
||||
expect(kinds(items)).toEqual(["user", "toolgroup", "autoperm", "assistant"]);
|
||||
const g = items[1] as Extract<DisplayItem, { kind: "toolgroup" }>;
|
||||
expect(g.steps.map((s) => s.itemId)).toEqual(["a", "b"]);
|
||||
const a = items[2] as Extract<DisplayItem, { kind: "autoperm" }>;
|
||||
expect(a.items.map(approvalTarget)).toEqual(["npm test", "git status"]);
|
||||
expect(a.items.map(approvalChoice)).toEqual(["允许一次", "允许一次"]);
|
||||
expect(a.items.every((p) => p.status === "resolved" && p.auto)).toBe(true);
|
||||
});
|
||||
|
||||
it("a card the user answered stays a normal card; a card approved when the mode was switched on joins the row", () => {
|
||||
const items = show([
|
||||
tool("a", "bash", "running"),
|
||||
{ type: "permission_request", requestId: "u1", title: "运行 rm x", kind: "tool", detail: { command: "rm x" }, options: opts },
|
||||
{ type: "permission_resolved", requestId: "u1", optionId: "once" },
|
||||
tool("b", "bash", "running"),
|
||||
{ type: "permission_request", requestId: "w1", title: "运行 ls", kind: "tool", detail: { command: "ls" }, options: opts },
|
||||
{ type: "permission_resolved", requestId: "w1", optionId: "once", auto: true },
|
||||
]);
|
||||
expect(kinds(items)).toEqual(["toolgroup", "permission", "toolgroup", "autoperm"]);
|
||||
expect((items[3] as Extract<DisplayItem, { kind: "autoperm" }>).items[0]!.requestId).toBe("w1");
|
||||
});
|
||||
|
||||
it("an auto request is never a pending card with buttons, even before its answer arrives", () => {
|
||||
const items = show([tool("a", "bash", "running"), autoReq("r1", "make")[0]!], "running");
|
||||
expect(kinds(items)).toEqual(["toolgroup", "autoperm"]);
|
||||
});
|
||||
|
||||
it("nothing auto: the items are passed through untouched", () => {
|
||||
const base = reduceTimeline(tl([{ type: "user_message", text: "x" }, tool("a", "read", "ok")]), { runtimeStatus: "idle" }).items;
|
||||
expect(collectAutoApproved(base)).toBe(base);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
// 1.3 全部自动同意 (#727 review 1): a persistent indicator for as long as the conversation is in auto-approve.
|
||||
// One slim line (Nolan): amber shield + 全部自动同意已开启 on the left, the way back to 每次询问 on the right, nothing in
|
||||
// between. What the mode does for this Agent (Codex: sandbox off, Claude: skips all permission checks …) is the left
|
||||
// label's tooltip and its accessible description; the permission menu shows the same wording. Not dismissible.
|
||||
import { useId } from "react";
|
||||
import { Icon } from "./Icons";
|
||||
import { autoApproveBannerDesc } from "../i18n/modes.js";
|
||||
import { t } from "../i18n/index.js";
|
||||
|
||||
export function AutoApproveBanner({ providerId, onBack }: { providerId?: string; onBack?: () => void }) {
|
||||
const desc = autoApproveBannerDesc(providerId);
|
||||
const descId = useId();
|
||||
return (
|
||||
<div className="cp-auto-on" role="status" aria-live="polite" data-testid="auto-on">
|
||||
<span className="cp-auto-t" title={desc} aria-describedby={descId} tabIndex={0}>
|
||||
<span className="cp-auto-ic" aria-hidden><Icon name="shieldCheck" size={13} /></span>
|
||||
<b>{t("composer.autoOn.title")}</b>
|
||||
</span>
|
||||
<span id={descId} className="sr-only">{desc}</span>
|
||||
{onBack && (
|
||||
<button type="button" className="cp-auto-back" onClick={onBack}>{t("composer.autoOn.back")}</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// 1.3 全部自动同意 (#727 review): the approvals the daemon gave by itself, one quiet row per run of tool calls.
|
||||
// Collapsed: "已自动同意 3 项 · npm test · git status …"; expanded: each request's title, command / file and the answer.
|
||||
import { useState } from "react";
|
||||
import type { DisplayItem } from "../timeline/reducer";
|
||||
import { approvalChoice, approvalTarget } from "../timeline/autoApproved";
|
||||
import { Icon } from "./Icons";
|
||||
import { t, tf } from "../i18n/index.js";
|
||||
import { ws } from "../main";
|
||||
|
||||
export function AutoApprovedItem({ it }: { it: Extract<DisplayItem, { kind: "autoperm" }> }) {
|
||||
// Same flat one-line rows as the 1.3 tool steps: icon slot · text · right-edge meta; the shield keeps the amber of the
|
||||
// 全部自动同意 chip so the row reads "approved for you", not "you approved"
|
||||
const [open, setOpen] = useState(false);
|
||||
const peek = it.items.map(approvalTarget).filter(Boolean).join(" · ");
|
||||
return (
|
||||
<div className={`apv${open ? " open" : ""}`} data-testid="auto-approved">
|
||||
<button className="apv-head" aria-expanded={open} onClick={() => setOpen(!open)}
|
||||
title={t("timeline.autoApproved.title")}>
|
||||
<span className="apv-ic" aria-hidden><Icon name="shieldCheck" size={13} /></span>
|
||||
<span className="apv-n">{tf("timeline.autoApproved.count", { n: it.items.length })}</span>
|
||||
{!open && peek && <span className="apv-peek">{peek}</span>}
|
||||
<span className={`caret${open ? " open" : ""}`} aria-hidden>›</span>
|
||||
</button>
|
||||
{open && (
|
||||
<div className="apv-list">
|
||||
{it.items.map((p) => {
|
||||
const d = (p.detail ?? {}) as { command?: unknown; path?: unknown };
|
||||
const choice = approvalChoice(p);
|
||||
const cmd = typeof d.command === "string" && d.command.trim() ? d.command.trim() : "";
|
||||
const path = !cmd && typeof d.path === "string" && d.path.trim() ? d.path.trim() : "";
|
||||
const answer = p.status === "pending"
|
||||
? t("timeline.autoApproved.pending")
|
||||
: tf("timeline.autoApproved.answer", { opt: choice ?? t("timeline.permAllowed") });
|
||||
return (
|
||||
<div key={p.requestId} className="apv-row" title={[p.title, cmd || path, answer].filter(Boolean).join("\n")}>
|
||||
<span className="ts-ic" aria-hidden><Icon name={p.status === "pending" ? "hourglass" : "check"} size={13} /></span>
|
||||
{cmd ? <span className="apv-cmd">{cmd}</span>
|
||||
: path ? <span className="apv-path">{path}</span>
|
||||
: <span className="apv-title">{p.title}</span>}
|
||||
<span className="apv-meta">{answer}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 1.3 upgrade (#727 review 3): a 1.2 全部放行 that did nothing for this Agent was not turned into real auto-approval */
|
||||
export const AUTO_UPGRADE_CODES = new Set(["auto_approve_upgrade", "auto_approve_migrated"]);
|
||||
|
||||
export function AutoUpgradeNotice({ it, threadId }: { it: Extract<DisplayItem, { kind: "notice" }>; threadId: string }) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const migrated = it.code === "auto_approve_migrated";
|
||||
const turnOn = () => {
|
||||
setBusy(true);
|
||||
void ws.call("thread.setMode", { id: threadId, mode: "bypassPermissions" }).catch(() => {}).finally(() => setBusy(false));
|
||||
};
|
||||
return (
|
||||
<div className="nt nt-auto" data-testid="auto-upgrade-notice" role="note">
|
||||
<div className="nt-auto-h">
|
||||
<span className="apv-ic"><Icon name="shieldCheck" size={14} /></span>
|
||||
<b>{t("timeline.autoUpgrade.title")}</b>
|
||||
</div>
|
||||
<div>{t(migrated ? "timeline.autoUpgrade.migrated" : "timeline.autoUpgrade.body")}</div>
|
||||
<div className="nt-actions">
|
||||
<button type="button" className="btn" disabled={busy} onClick={turnOn}>{t("timeline.autoUpgrade.turnOn")}</button>
|
||||
<button type="button" className="btn" onClick={() => window.dispatchEvent(new Event("open-settings"))}>{t("timeline.autoUpgrade.settings")}</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { useData, pickDefaultProvider } from "../stores/data";
|
||||
import { useTimeline } from "../stores/timeline";
|
||||
import { TimelineRow } from "./Timeline";
|
||||
import { foldTimeline, TOOL_COLLAPSE_AT } from "../timeline/fold";
|
||||
import { collectAutoApproved } from "../timeline/autoApproved";
|
||||
import { Composer } from "./Composer";
|
||||
import { QuoteSelect } from "./QuoteSelect";
|
||||
import { Icon } from "./Icons";
|
||||
@@ -23,7 +24,8 @@ export function Chat() {
|
||||
const prefs = useLiveSettings();
|
||||
// 1.3: runs of tool calls (and short thinking between them) fold into one summary row
|
||||
// (tl.items is a fresh array after every timeline change, so the memo follows the stream)
|
||||
const items = useMemo(() => foldTimeline(tl.items, { showThinking: prefs.showThinking }), [tl.items, prefs.showThinking]);
|
||||
// 1.3 全部自动同意: the daemon's own approvals become one quiet row after their run (collectAutoApproved)
|
||||
const items = useMemo(() => foldTimeline(collectAutoApproved(tl.items), { showThinking: prefs.showThinking }), [tl.items, prefs.showThinking]);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const [stick, setStick] = useState(true);
|
||||
const [hasNew, setHasNew] = useState(false);
|
||||
|
||||
@@ -19,6 +19,7 @@ import { composerModeOptions, effortLabel } from "../i18n/modes.js";
|
||||
import { Logo } from "./Logo";
|
||||
import { currentChecklist, todoProgress } from "../timeline/fold";
|
||||
import { SelectMenu } from "./SelectMenu";
|
||||
import { AutoApproveBanner } from "./AutoApproveBanner";
|
||||
import { errMsg, t as tr, tf } from "../i18n/index.js";
|
||||
import {
|
||||
applySlashPick,
|
||||
@@ -397,8 +398,12 @@ export function Composer() {
|
||||
};
|
||||
|
||||
const setMode = (m: Mode) => {
|
||||
if (thread) void ws.call("thread.setMode", { id: thread.id, mode: m });
|
||||
if (!thread) return;
|
||||
void ws.call("thread.setMode", { id: thread.id, mode: m }).catch((e) => toast(errMsg(e), true));
|
||||
};
|
||||
// 1.3 (#727 review 1): while the mode this Agent really uses is 全部自动同意, a persistent banner + warning-coloured chip
|
||||
const autoOn = !!(modes.find((m) => m.id === mode) ?? modes[0])?.auto;
|
||||
const canAsk = modes.some((m) => m.id === "default" && !m.auto);
|
||||
const setEffort = (effort: string | null) => {
|
||||
if (thread) void ws.call("thread.setEffort", { id: thread.id, effort });
|
||||
};
|
||||
@@ -469,10 +474,8 @@ export function Composer() {
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{mode === "bypassPermissions" && (
|
||||
<div className="cp-danger">{tr("composer.bypassWarn")}</div>
|
||||
)}
|
||||
<div className={`cp-card${waiting ? " waiting" : ""}${mode === "bypassPermissions" ? " danger" : ""}${dropHint ? " drop-on" : ""}`}>
|
||||
{autoOn && <AutoApproveBanner providerId={thread?.provider} onBack={canAsk ? () => setMode("default") : undefined} />}
|
||||
<div className={`cp-card${waiting ? " waiting" : ""}${autoOn ? " auto-on" : ""}${dropHint ? " drop-on" : ""}`}>
|
||||
{dropHint && <div className="cp-drop-hint">{tr("mention.drop")}</div>}
|
||||
{imagesByPath && attachments.some((a) => a.mime.startsWith("image/")) && (
|
||||
<div className="att-note">{tf("composer.imagesByPath", { agent: provider?.name ?? "" })}</div>
|
||||
@@ -728,13 +731,19 @@ export function Composer() {
|
||||
<ChipCaret />
|
||||
</SelectMenu>
|
||||
)}
|
||||
{/* permission mode: list only the modes this Agent really has; hidden when there is only one (e.g. Pi has no modes) */}
|
||||
{/* permission mode: list only the modes this Agent really has; one mode only (Pi: always auto) = a plain label */}
|
||||
{modes.length === 1 && (
|
||||
<span className={`pill ipill mode-chip static${modes[0]!.auto ? " auto" : ""}`} title={modes[0]!.desc} data-mode={modes[0]!.id}>
|
||||
<Icon name={modes[0]!.auto ? "shieldCheck" : "shield"} size={14} />
|
||||
<span className="ip-l">{modes[0]!.label}</span>
|
||||
</span>
|
||||
)}
|
||||
{modes.length > 1 && (() => {
|
||||
// The mode stored on the conversation doesn't exist for this Agent → show the one it will actually use
|
||||
const shown = modes.find((m) => m.id === mode) ?? modes[0]!;
|
||||
return (
|
||||
<SelectMenu
|
||||
className={`pill ipill${shown.danger ? " danger" : ""}`}
|
||||
className={`pill ipill mode-chip${shown.danger ? " danger" : ""}${shown.auto ? " auto" : ""}`}
|
||||
title={shown.desc}
|
||||
ariaLabel={tr("composer.modeTitle")}
|
||||
prefer="up"
|
||||
@@ -742,9 +751,9 @@ export function Composer() {
|
||||
menuClassName="mode-menu"
|
||||
value={shown.id}
|
||||
onChange={(v) => setMode(v as Mode)}
|
||||
options={modes.map((m) => ({ value: m.id, label: m.label, hint: m.desc, danger: m.danger }))}
|
||||
options={modes.map((m) => ({ value: m.id, label: m.label, hint: m.desc, danger: m.danger, warn: m.auto, icon: m.auto ? "shieldCheck" : undefined }))}
|
||||
>
|
||||
<Icon name="shield" size={14} />
|
||||
<Icon name={shown.auto ? "shieldCheck" : "shield"} size={14} />
|
||||
<span className="ip-l">{shown.label}</span>
|
||||
<ChipCaret />
|
||||
</SelectMenu>
|
||||
|
||||
@@ -29,6 +29,7 @@ const PATHS: Record<string, string> = {
|
||||
shield: "M12 3l8 3v6c0 5-3.5 9-8 11-4.5-2-8-6-8-11V6l8-3z",
|
||||
quote: "M5 7h5v5H7c0 2 1 3 3 4M14 7h5v5h-3c0 2 1 3 3 4",
|
||||
pencil: "M4 20h4L19 9a2.1 2.1 0 0 0-3-3L5 17v3zM14 7l3 3",
|
||||
shieldCheck: "M12 3l8 3v6c0 5-3.5 9-8 11-4.5-2-8-6-8-11V6l8-3zM8.5 12.2l2.4 2.4 4.6-4.8",
|
||||
zap: "M13 2L4 14h7l-1 8 9-12h-7l1-8z",
|
||||
// 1.3 timeline rows / footer / code blocks
|
||||
prompt: "M5 7l5 5-5 5M12 17h7",
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// Enter/Space pick, Esc/Tab close (Esc returns focus to the trigger). Click outside closes. The menu is portaled to <body> with
|
||||
// fixed positioning, opens below the trigger or flips above it when there's no room (the composer sits at the bottom), and is
|
||||
// kept inside the window; no browser popup is involved, so it behaves the same inside Magpie's sandboxed iframe.
|
||||
import { Icon } from "./Icons";
|
||||
import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
|
||||
@@ -12,6 +13,10 @@ export type SelectOption<T extends string = string> = {
|
||||
hint?: string;
|
||||
disabled?: boolean;
|
||||
danger?: boolean;
|
||||
/** Warning colour (1.3: 全部自动同意, #727 review 1) */
|
||||
warn?: boolean;
|
||||
/** Small icon before the label (1.3: the 全部自动同意 shield) */
|
||||
icon?: string;
|
||||
};
|
||||
|
||||
const GAP = 4;
|
||||
@@ -186,12 +191,12 @@ export function SelectMenu<T extends string>({
|
||||
role="option"
|
||||
aria-selected={o.value === value}
|
||||
aria-disabled={o.disabled || undefined}
|
||||
className={`mi sm-opt${i === active ? " on" : ""}${o.disabled ? " off" : ""}${o.danger ? " danger" : ""}${o.hint ? " has-hint" : ""}`}
|
||||
className={`mi sm-opt${i === active ? " on" : ""}${o.disabled ? " off" : ""}${o.danger ? " danger" : ""}${o.warn ? " warn" : ""}${o.hint ? " has-hint" : ""}`}
|
||||
onPointerMove={() => { if (!o.disabled && active !== i) setActive(i); }}
|
||||
onClick={() => pick(i)}
|
||||
>
|
||||
<span className="sm-text">
|
||||
<span className="sm-label">{o.label}</span>
|
||||
<span className="sm-label">{o.icon && <Icon name={o.icon} size={13} />}{o.label}</span>
|
||||
{o.hint && <span className="sm-hint">{o.hint}</span>}
|
||||
</span>
|
||||
<span className="sm-check" aria-hidden="true">{o.value === value ? (
|
||||
|
||||
@@ -225,10 +225,10 @@ export function SettingsDialog({ onClose, providers }: { onClose: () => void; pr
|
||||
{row(t("settings.defaultMode"), (
|
||||
<SelectMenu className="tinput sm-field" matchWidth ariaLabel={t("settings.defaultMode")}
|
||||
value={s.defaultMode ?? "default"} onChange={(v) => void set({ defaultMode: v })}
|
||||
options={modes.map((m) => ({ value: m.id, label: m.label, hint: m.desc }))}>
|
||||
options={modes.map((m) => ({ value: m.id, label: m.label, hint: m.desc, icon: m.auto ? "shieldCheck" : undefined }))}>
|
||||
<span className="sm-val">{(() => { const m = modes.find((x) => x.id === (s.defaultMode ?? "default")); return m ? `${m.label} — ${m.desc}` : ""; })()}</span>
|
||||
</SelectMenu>
|
||||
), t("settings.defaultModeHint"))}
|
||||
), s.defaultMode === "bypassPermissions" ? `${t("settings.defaultModeHint")} ${t("composer.autoWarn")}` : t("settings.defaultModeHint"))}
|
||||
{row(t("settings.theme"), (
|
||||
<SelectMenu className="tinput sm-field" matchWidth ariaLabel={t("settings.theme")}
|
||||
value={normalizeThemeSetting(s.theme)} onChange={(v) => void set({ theme: v })}
|
||||
|
||||
@@ -17,6 +17,7 @@ import { splitLocalLinks } from "../util/localLinks";
|
||||
import { onChatLinkClick, openExternal } from "../preview/open";
|
||||
import { splitQuotes } from "../composer/quotes";
|
||||
import { localClientIds, useTimeline } from "../stores/timeline";
|
||||
import { AUTO_UPGRADE_CODES, AutoApprovedItem, AutoUpgradeNotice } from "./AutoApproved";
|
||||
|
||||
export const GIT_FOR_WINDOWS_URL = "https://git-scm.com/download/win";
|
||||
|
||||
@@ -409,7 +410,8 @@ export function PermissionItem({ it, threadId }: { it: Extract<DisplayItem, { ki
|
||||
const detail = it.detail as { command?: string; path?: string; plan?: string; hunks?: DiffHunk[]; diff?: { path?: string; hunks?: DiffHunk[] } } | undefined;
|
||||
const hunks = detail?.hunks ?? detail?.diff?.hunks;
|
||||
const label = it.status === "resolved"
|
||||
? it.choice === "allow_always" || it.choice === "acceptForSession" ? t("timeline.permAllowSession")
|
||||
? it.auto ? t("timeline.permAutoAllowed")
|
||||
: it.choice === "allow_always" || it.choice === "acceptForSession" ? t("timeline.permAllowSession")
|
||||
: it.choice === "deny" || it.choice === "reject" || it.choice === "decline" ? t("timeline.permDenied")
|
||||
: it.choice === "implement" ? t("timeline.permAllowed") : t("timeline.permAllowed")
|
||||
: t("timeline.permCancelled");
|
||||
@@ -567,9 +569,11 @@ export function TimelineRow({ it, threadId, onEditResend, onRetryLast, replyText
|
||||
case "plan": return <PlanItem it={it} />;
|
||||
case "todo": return <TodoItem it={it} />;
|
||||
case "permission": return <PermissionItem it={it} threadId={threadId} />;
|
||||
case "autoperm": return <AutoApprovedItem it={it} />;
|
||||
case "question": return <QuestionItem it={it} threadId={threadId} />;
|
||||
case "notice":
|
||||
if (it.code === "bash_missing") return <BashMissingNotice it={it} />;
|
||||
if (it.code && AUTO_UPGRADE_CODES.has(it.code)) return <AutoUpgradeNotice it={it} threadId={threadId} />;
|
||||
return <div className={`nt ${it.level}`}>{localizeDaemonMessage(it.message)}</div>;
|
||||
case "turnend": return <TurnEndItem it={it} onRetry={onRetryLast} replyText={replyText} />;
|
||||
case "gone": return null;
|
||||
|
||||
@@ -61,7 +61,25 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
queuePlaceholderNoSteer: "继续补充要求,回车排队发送…",
|
||||
steerUnsupported: "{agent} 不支持插话:运行中发的消息会排队,本回合结束后再发送。",
|
||||
queuedToast: "已排队:本回合结束后发送", steeredToast: "已插话",
|
||||
inputPlaceholder: "输入消息,/ 使用命令…", bypassWarn: "Bypass:Agent 的所有操作不会再问你。",
|
||||
inputPlaceholder: "输入消息,/ 使用命令…",
|
||||
autoWarn: "全部自动同意会让 Agent 不经询问直接运行命令、修改文件:Codex 关闭沙箱(danger-full-access),Claude Code 跳过所有权限检查,其他 Agent 的授权请求由控制台自动「允许一次」。请谨慎使用。",
|
||||
// 1.3 (#727 review 1): shown for as long as the conversation is in 全部自动同意, above the composer
|
||||
autoOn: {
|
||||
title: "全部自动同意已开启",
|
||||
back: "改回每次询问",
|
||||
keeps: "计划确认和提问仍会问你;每次只同意当前这一个请求,不会写入永久规则。",
|
||||
},
|
||||
// What 全部自动同意 really does for each Agent (menu hint, banner, tooltip)
|
||||
autoDesc: {
|
||||
claude: "Claude Code 以 bypassPermissions 运行:跳过所有权限检查,命令和改文件都不再询问(请谨慎使用)",
|
||||
codex: "Codex 沙箱关闭(danger-full-access)且从不询问:命令可读写整台电脑、可联网(请谨慎使用)",
|
||||
copilot: "Copilot Allow All:所有工具调用都不再确认(请谨慎使用)",
|
||||
devin: "Devin Bypass Permissions:跳过所有权限检查(请谨慎使用)",
|
||||
cursor: "Agent 模式,每个授权请求都由控制台自动「允许一次」:命令和改文件直接执行(请谨慎使用)",
|
||||
opencode: "Build 模式,每个授权请求都由控制台自动「允许一次」:命令和改文件直接执行(请谨慎使用)",
|
||||
generic: "每个授权请求都由控制台自动「允许一次」:命令和改文件直接执行,不再询问(请谨慎使用)",
|
||||
pi: "Pi 本身从不询问:命令和改文件直接执行(扩展发起的确认仍会问你)",
|
||||
},
|
||||
imagesByPath: "{agent} 不能直接看图片:会把图片的文件路径发给它(它能用文件工具打开)。",
|
||||
agentModel: "Agent & model", agentLocked: "Agent (locked)", agent: "Agent",
|
||||
model: "Model", searchModel: "Search", searchAllModels: "Search models…", providers: "Agent",
|
||||
@@ -82,10 +100,12 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
plan: { label: "规划", desc: "只分析代码库,不执行工具或修改" },
|
||||
default: { label: "每次询问", desc: "首次使用工具时会请求授权" },
|
||||
acceptEdits: { label: "接受编辑", desc: "自动批准编辑类工具,不再逐项询问" },
|
||||
bypass: { label: "全部放行", desc: "跳过所有授权提示(请谨慎使用)" },
|
||||
bypass: { label: "全部自动同意", desc: "不再询问:Codex 关闭沙箱,Claude Code 跳过所有权限检查,其他 Agent 的请求自动「允许一次」(请谨慎使用)" },
|
||||
cursorBypass: { label: "全部自动同意", desc: "Agent 模式,每个授权请求都由控制台自动「允许一次」(请谨慎使用)" },
|
||||
cursorAgent: { label: "Agent", desc: "完整 Agent:可读写、执行工具" },
|
||||
cursorPlan: { label: "规划", desc: "只读规划:分析并提出方案,不改文件" },
|
||||
cursorAsk: { label: "问答", desc: "问答模式:解释与讨论,只读" },
|
||||
pi: { label: "Pi 本身从不询问", desc: "Pi 本身从不询问:命令和改文件直接执行(扩展发起的确认仍会问你)" },
|
||||
},
|
||||
// Agent-specific mode names reported by the daemon
|
||||
agentMode: {
|
||||
@@ -109,7 +129,7 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
sendKey: "发送键", sendEnter: "Enter 发送 / Shift+Enter 换行", sendCtrl: "Ctrl+Enter 发送 / Enter 换行",
|
||||
runningSend: "运行中再发送", queue: "排队(发完自动继续)", steer: "插话(立即打断当前思路)",
|
||||
steerHint: "插话只对支持的 Agent 生效(目前是 Codex);其他 Agent 仍会排队,输入框下方会提示。",
|
||||
defaultModeHint: "新对话使用;每个 Agent 会换成自己最接近的模式(例如 OpenCode 只有 Plan / Build,Build 会直接改文件)。",
|
||||
defaultModeHint: "新对话使用;每个 Agent 会换成自己最接近的模式(例如 OpenCode 只有 Plan / Build,Build 会直接改文件)。选「全部自动同意」后,所有 Agent 都不再弹授权。",
|
||||
thinking: "思考过程", showThinking: "显示 Agent 的思考/推理内容",
|
||||
idleClose: "空闲回收", idleMinutes: "分钟后自动关闭空闲会话(5–240;最多保留 3 个空闲 Agent 进程)",
|
||||
idleInvalid: "请输入 5 到 240 之间的整数",
|
||||
@@ -155,7 +175,14 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
timeline: {
|
||||
thinking: "思考 {s}s", todo: "待办 {done}/{total}", steer: "插话", tasks: "任务", tasksPill: "{done}/{total} 个任务", tasksPillTitle: "查看任务清单",
|
||||
codeWrap: "自动换行",
|
||||
permAllowSession: "本对话都允许", permDenied: "已拒绝", permAllowed: "已允许", permCancelled: "已取消",
|
||||
permAllowSession: "本对话都允许", permDenied: "已拒绝", permAllowed: "已允许", permAutoAllowed: "已自动同意(全部自动同意)", permCancelled: "已取消",
|
||||
autoUpgrade: {
|
||||
title: "1.3 新增:全部自动同意",
|
||||
body: "现在「全部自动同意」对 Cursor、OpenCode、dsh 也会真正生效:授权请求由控制台自动「允许一次」,命令和改文件直接执行。1.2 的「全部放行」对它们不生效(仍会询问)。你之前把默认权限模式设成了它,为安全起见,这个对话仍从「每次询问」开始。在设置里重新选择一次默认权限模式后,新对话就按你的选择来。",
|
||||
migrated: "这个对话在 1.2 里设成了「全部放行」,当时这个 Agent 实际仍会询问。1.3 起「全部自动同意」会真正自动同意(命令和改文件直接执行),所以已改回「每次询问」。",
|
||||
turnOn: "在此对话开启全部自动同意", settings: "打开设置",
|
||||
},
|
||||
autoApproved: { count: "已自动同意 {n} 项", title: "全部自动同意替你同意了这些请求(点开查看)", answer: "{opt} · 全部自动同意", pending: "正在自动同意…" },
|
||||
submitted: "已提交:{ans}", turnError: "出错:{err}", unknownError: "未知错误",
|
||||
interrupted: "已打断", filesChanged: "改动 {n} 个文件 ›", editMsg: "编辑(填回输入框,不会马上发送)", sendFailed: "发送失败", sendRetry: "重新发送", sendDismiss: "移除这条没发出的消息", resend: "重新发送这条消息", retryHint: "重试:重新发送上一条消息", msgActions: "消息操作", editBusy: "输入框里还有没发送的内容:先发送或清空,再点编辑",
|
||||
tool: {
|
||||
@@ -256,7 +283,23 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
queuePlaceholderNoSteer: "Add to the task — Enter queues it…",
|
||||
steerUnsupported: "{agent} can't steer: messages sent while it runs are queued and sent after this turn.",
|
||||
queuedToast: "Queued — sends after this turn", steeredToast: "Steered",
|
||||
inputPlaceholder: "Message the agent, / for commands…", bypassWarn: "Bypass: the agent will not ask for permission.",
|
||||
inputPlaceholder: "Message the agent, / for commands…",
|
||||
autoWarn: "Auto-approve all lets the agent run commands and edit files without asking: Codex turns its sandbox off (danger-full-access), Claude Code skips all permission checks, and every other agent's approval requests are answered \"allow once\" by the console. Use with care.",
|
||||
autoOn: {
|
||||
title: "Auto-approve all is on",
|
||||
back: "Back to Always Ask",
|
||||
keeps: "Plan approvals and questions still ask you; each approval covers only that one request and never saves a lasting rule.",
|
||||
},
|
||||
autoDesc: {
|
||||
claude: "Claude Code runs with bypassPermissions: skips all permission checks, commands and edits never ask (use with care)",
|
||||
codex: "Codex sandbox off (danger-full-access) and never asks: commands can read and write your whole machine and use the network (use with care)",
|
||||
copilot: "Copilot Allow All: no tool call asks for confirmation (use with care)",
|
||||
devin: "Devin Bypass Permissions: skips all permission checks (use with care)",
|
||||
cursor: "Agent mode, every approval request answered \"allow once\" by the console: commands and edits run without asking (use with care)",
|
||||
opencode: "Build mode, every approval request answered \"allow once\" by the console: commands and edits run without asking (use with care)",
|
||||
generic: "Every approval request is answered \"allow once\" by the console: commands and edits run without asking (use with care)",
|
||||
pi: "Pi itself never asks: commands and edits run directly (dialogs from Pi extensions still ask you)",
|
||||
},
|
||||
imagesByPath: "{agent} can't see images directly: it gets the image's file path instead (it can open it with its file tools).",
|
||||
agentModel: "Agent & model", agentLocked: "Agent (locked after first message)", agent: "Agent",
|
||||
model: "Model", searchModel: "Search", searchAllModels: "Search all models…", providers: "Providers",
|
||||
@@ -276,10 +319,12 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
plan: { label: "Plan Mode", desc: "Analyze the codebase without running tools or edits" },
|
||||
default: { label: "Always Ask", desc: "Ask permission the first time a tool is used" },
|
||||
acceptEdits: { label: "Accept File Edits", desc: "Auto-approve edit tools without prompting" },
|
||||
bypass: { label: "Bypass", desc: "Skip all permission prompts (use with caution)" },
|
||||
bypass: { label: "Auto-approve all", desc: "Never asks: Codex turns its sandbox off, Claude Code skips all permission checks, other agents' requests are answered \"allow once\" (use with care)" },
|
||||
cursorBypass: { label: "Auto-approve all", desc: "Agent mode, every approval request answered \"allow once\" by the console (use with care)" },
|
||||
cursorAgent: { label: "Agent", desc: "Full agent: tools and edits" },
|
||||
cursorPlan: { label: "Plan", desc: "Read-only planning and analysis" },
|
||||
cursorAsk: { label: "Ask", desc: "Q&A style explanations (read-only)" },
|
||||
pi: { label: "Pi never asks", desc: "Pi itself never asks: commands and edits run directly (dialogs from Pi extensions still ask you)" },
|
||||
},
|
||||
agentMode: {},
|
||||
effort: { low: "Low", medium: "Medium", high: "High", xhigh: "Extra high", max: "Max", minimal: "Minimal", none: "Off" },
|
||||
@@ -300,7 +345,7 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
sendCtrl: "Ctrl+Enter sends / Enter newline",
|
||||
runningSend: "While running", queue: "Queue (run after current turn)", steer: "Steer (interrupt now)",
|
||||
steerHint: "Steer only works for agents that support it (Codex today); other agents still queue, and the composer says so.",
|
||||
defaultModeHint: "For new conversations. Each agent maps it to its own nearest mode (OpenCode only has Plan / Build, and Build edits without asking).",
|
||||
defaultModeHint: "For new conversations. Each agent maps it to its own nearest mode (OpenCode only has Plan / Build, and Build edits without asking). With Auto-approve all, no agent asks for approval.",
|
||||
thinking: "Reasoning", showThinking: "Show agent reasoning/thinking",
|
||||
idleClose: "Idle cleanup", idleMinutes: "minutes before closing idle sessions (5–240; at most 3 idle agent processes are kept)",
|
||||
idleInvalid: "Enter a whole number from 5 to 240",
|
||||
@@ -346,7 +391,14 @@ export const messages: Record<LocaleId, MessageTree> = {
|
||||
timeline: {
|
||||
thinking: "Thinking {s}s", todo: "Todos {done}/{total}", steer: "Steer", tasks: "tasks", tasksPill: "{done}/{total} tasks", tasksPillTitle: "Show the task list",
|
||||
codeWrap: "Wrap lines",
|
||||
permAllowSession: "Allowed for this chat", permDenied: "Denied", permAllowed: "Allowed", permCancelled: "Cancelled",
|
||||
permAllowSession: "Allowed for this chat", permDenied: "Denied", permAllowed: "Allowed", permAutoAllowed: "Auto-approved (Auto-approve all)", permCancelled: "Cancelled",
|
||||
autoUpgrade: {
|
||||
title: "New in 1.3: Auto-approve all",
|
||||
body: "Auto-approve all now really works for Cursor, OpenCode and dsh: the console answers their approval requests \"allow once\", so commands and edits run without asking. 1.2's bypass mode did nothing for them (they still asked). Your default permission mode was set to it, so to be safe this conversation starts in Always Ask. Pick the default permission mode again in Settings and new conversations follow your choice.",
|
||||
migrated: "This conversation was set to bypass permissions in 1.2, where this agent still asked anyway. From 1.3 Auto-approve all really auto-approves (commands and edits run without asking), so it was put back to Always Ask.",
|
||||
turnOn: "Turn on Auto-approve all here", settings: "Open Settings",
|
||||
},
|
||||
autoApproved: { count: "Auto-approved {n}", title: "Requests Auto-approve all approved for you (click to see them)", answer: "{opt} · Auto-approve all", pending: "Auto-approving…" },
|
||||
submitted: "Submitted: {ans}", turnError: "Error: {err}", unknownError: "Unknown error",
|
||||
interrupted: "Interrupted", filesChanged: "{n} file(s) changed ›", editMsg: "Edit (puts it back in the input; nothing is sent yet)", sendFailed: "Not sent", sendRetry: "Send again", sendDismiss: "Remove this unsent message", resend: "Send this message again", retryHint: "Retry: send the last message again", msgActions: "Message actions", editBusy: "The input still has unsent text: send or clear it first, then click Edit",
|
||||
tool: {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
// 1.3: per-Agent permission options and hints; Pi keeps the default id but clearly says it never asks.
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { setLocale } from "./index.js";
|
||||
import { autoApproveBannerDesc, composerModeOptions, permissionModes } from "./modes.js";
|
||||
|
||||
describe("composerModeOptions", () => {
|
||||
beforeEach(() => { setLocale("zh"); });
|
||||
it("keeps 每次询问 and adds 全部自动同意 with the shield flag", () => {
|
||||
const all = permissionModes();
|
||||
expect(all.find((m) => m.id === "default")?.label).toBe("每次询问");
|
||||
const auto = all.find((m) => m.id === "bypassPermissions")!;
|
||||
expect(auto.label).toBe("全部自动同意");
|
||||
expect(auto.auto).toBe(true);
|
||||
expect(auto.danger).toBeFalsy(); // grayscale, not the red danger style
|
||||
});
|
||||
it("Cursor: Agent, 全部自动同意, 规划, 问答", () => {
|
||||
const m = composerModeOptions("cursor", ["default", "bypassPermissions", "plan", "ask"]);
|
||||
expect(m.map((x) => x.label)).toEqual(["Agent", "全部自动同意", "规划", "问答"]);
|
||||
});
|
||||
it("the hint says plainly what full-auto does for the Agent (#727 review 1); the label stays 全部自动同意", () => {
|
||||
const m = composerModeOptions("codex", ["default", "acceptEdits", "bypassPermissions"], { default: "Read Only", acceptEdits: "Auto", bypassPermissions: "Full Access" });
|
||||
const auto = m.find((x) => x.id === "bypassPermissions")!;
|
||||
expect(auto.label).toBe("全部自动同意");
|
||||
expect(auto.desc).toContain("沙箱关闭");
|
||||
expect(auto.desc).toContain("danger-full-access");
|
||||
expect(m.find((x) => x.id === "default")?.label).toBe("只读");
|
||||
const claude = composerModeOptions("claude", ["plan", "default", "acceptEdits", "bypassPermissions"]).find((x) => x.auto)!;
|
||||
expect(claude.desc).toContain("跳过所有权限检查");
|
||||
for (const p of ["cursor", "opencode", "dsh", "mock"]) {
|
||||
expect(composerModeOptions(p, ["default", "bypassPermissions"]).find((x) => x.auto)!.desc).toContain("允许一次");
|
||||
}
|
||||
setLocale("en");
|
||||
expect(composerModeOptions("codex", ["bypassPermissions"])[0]!.desc).toMatch(/sandbox off/i);
|
||||
expect(composerModeOptions("claude", ["bypassPermissions"])[0]!.desc).toMatch(/skips all permission checks/i);
|
||||
});
|
||||
it("Pi: one default-id mode labelled as never asking in both locales", () => {
|
||||
const m = composerModeOptions("pi", ["default"]);
|
||||
expect(m).toHaveLength(1);
|
||||
expect(m[0]).toMatchObject({ id: "default", label: "Pi 本身从不询问", auto: true });
|
||||
expect(m[0]!.desc).toContain("Pi 本身从不询问");
|
||||
setLocale("en");
|
||||
expect(composerModeOptions("pi", ["default"])[0]).toMatchObject({ id: "default", label: "Pi never asks", auto: true });
|
||||
});
|
||||
it("the banner's per-request explanation is limited to Agents that answer individual requests", () => {
|
||||
const phrase = "每次只同意当前这一个请求";
|
||||
for (const p of ["cursor", "opencode", "dsh", undefined, "mock"]) {
|
||||
expect(autoApproveBannerDesc(p), p).toContain(phrase);
|
||||
}
|
||||
for (const p of ["codex", "claude", "pi", "copilot", "devin"]) {
|
||||
expect(autoApproveBannerDesc(p), p).not.toContain(phrase);
|
||||
}
|
||||
});
|
||||
it("English", () => {
|
||||
setLocale("en");
|
||||
expect(permissionModes().find((m) => m.id === "bypassPermissions")?.label).toBe("Auto-approve all");
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,32 @@
|
||||
import type { Mode } from "../types/models.js";
|
||||
import { t } from "./index.js";
|
||||
|
||||
export type PermissionModeOption = { id: Mode; label: string; desc: string; danger?: boolean };
|
||||
/** auto: 全部自动同意 (bypassPermissions), drawn with the shield-check in the warning colour (#727 review 1) */
|
||||
export type PermissionModeOption = { id: Mode; label: string; desc: string; danger?: boolean; auto?: boolean };
|
||||
|
||||
const AUTO_DESC_IDS = new Set(["claude", "codex", "copilot", "devin", "cursor", "opencode", "pi"]);
|
||||
const PER_REQUEST_AUTO_IDS = new Set(["cursor", "opencode", "dsh"]);
|
||||
|
||||
/** What 全部自动同意 really does for this Agent: sandbox off / skips all permission checks / the console answers allow-once */
|
||||
export function autoModeDesc(providerId: string | undefined): string {
|
||||
return t(`composer.autoDesc.${providerId && AUTO_DESC_IDS.has(providerId) ? providerId : "generic"}`);
|
||||
}
|
||||
|
||||
export function autoApproveBannerDesc(providerId: string | undefined): string {
|
||||
const desc = autoModeDesc(providerId);
|
||||
return !providerId || !AUTO_DESC_IDS.has(providerId) || PER_REQUEST_AUTO_IDS.has(providerId)
|
||||
? `${desc}\n${t("composer.autoOn.keeps")}`
|
||||
: desc;
|
||||
}
|
||||
|
||||
export const FULL_AUTO: Mode = "bypassPermissions";
|
||||
|
||||
export function permissionModes(): PermissionModeOption[] {
|
||||
return [
|
||||
{ id: "plan", label: t("composer.mode.plan.label"), desc: t("composer.mode.plan.desc") },
|
||||
{ id: "default", label: t("composer.mode.default.label"), desc: t("composer.mode.default.desc") },
|
||||
{ id: "acceptEdits", label: t("composer.mode.acceptEdits.label"), desc: t("composer.mode.acceptEdits.desc") },
|
||||
{ id: "bypassPermissions", label: t("composer.mode.bypass.label"), desc: t("composer.mode.bypass.desc"), danger: true },
|
||||
{ id: "bypassPermissions", label: t("composer.mode.bypass.label"), desc: t("composer.mode.bypass.desc"), auto: true },
|
||||
];
|
||||
}
|
||||
|
||||
@@ -16,6 +34,7 @@ export function permissionModes(): PermissionModeOption[] {
|
||||
export function cursorExecutionModes(): PermissionModeOption[] {
|
||||
return [
|
||||
{ id: "default", label: t("composer.mode.cursorAgent.label"), desc: t("composer.mode.cursorAgent.desc") },
|
||||
{ id: "bypassPermissions", label: t("composer.mode.cursorBypass.label"), desc: t("composer.mode.cursorBypass.desc"), auto: true },
|
||||
{ id: "plan", label: t("composer.mode.cursorPlan.label"), desc: t("composer.mode.cursorPlan.desc") },
|
||||
{ id: "ask", label: t("composer.mode.cursorAsk.label"), desc: t("composer.mode.cursorAsk.desc") },
|
||||
];
|
||||
@@ -27,10 +46,19 @@ export function composerModeOptions(
|
||||
labels?: Partial<Record<Mode, string>>,
|
||||
): PermissionModeOption[] {
|
||||
const base = providerId === "cursor" ? cursorExecutionModes() : permissionModes();
|
||||
// As in Paseo: when an Agent has its own mode names, use them (Copilot shows Agent rather than Always Ask)
|
||||
// As in Paseo: when an Agent has its own mode names, use them (Copilot shows Agent rather than Always Ask).
|
||||
// 1.3: 全部自动同意 keeps one name for every Agent; the description says what it does for that Agent.
|
||||
return base
|
||||
.filter((m) => allowed.includes(m.id))
|
||||
.map((m) => (labels?.[m.id] ? { ...m, label: agentModeLabel(labels[m.id]!) } : m));
|
||||
.map((m) => {
|
||||
// Pi still runs without tool approvals, but its persisted id stays default so it cannot arm another Agent.
|
||||
if (providerId === "pi" && m.id === "default") {
|
||||
return { ...m, label: t("composer.mode.pi.label"), desc: t("composer.mode.pi.desc"), auto: true };
|
||||
}
|
||||
// #727 review 1: the hint says plainly what the Agent's own switch does (Codex: sandbox off; Claude: skips all checks)
|
||||
if (m.id === FULL_AUTO) return { ...m, desc: autoModeDesc(providerId) };
|
||||
return labels?.[m.id] ? { ...m, label: agentModeLabel(labels[m.id]!) } : m;
|
||||
});
|
||||
}
|
||||
|
||||
/** An Agent's own mode name (from the daemon, English) in the UI language when we know it */
|
||||
|
||||
@@ -152,6 +152,7 @@ textarea.tinput { height: auto; min-height: 60px; padding: 6px 10px; resize: ver
|
||||
.sm-opt.off:hover { background: none; }
|
||||
.sm-text { display: flex; flex-direction: column; min-width: 0; flex: 1 1 auto; }
|
||||
.sm-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.sm-label > svg { vertical-align: -2px; margin-right: 5px; }
|
||||
.sm-hint { font-size: var(--fs-s); color: var(--muted); white-space: normal; line-height: 1.4; }
|
||||
.sm-check { flex: none; width: 14px; display: inline-flex; color: var(--accent); }
|
||||
.sm-opt[aria-selected="true"] .sm-label { font-weight: 500; }
|
||||
|
||||
@@ -268,3 +268,32 @@ a.ac-local { cursor: pointer; }
|
||||
display: block; margin: 2px 0 6px; padding-left: 8px; border-left: 2px solid color-mix(in oklab, var(--fg) 30%, transparent);
|
||||
color: var(--muted); font-size: var(--chat-fs-s); max-height: 7.5em; overflow: hidden;
|
||||
}
|
||||
|
||||
/* 1.3 全部自动同意 (#727 review): the daemon's own approvals, one foldable row per run of tool calls, in the same flat
|
||||
one-line style as the tool rows (icon slot · text · right-edge meta; clip, never wrap). Only the shield is amber. */
|
||||
.apv { margin: 0 0 8px; min-width: 0; }
|
||||
.apv-head {
|
||||
display: flex; align-items: center; gap: 8px; width: 100%; min-height: 26px; padding: 0 6px; overflow: hidden; border-radius: var(--r-s);
|
||||
color: var(--muted); font-size: var(--chat-fs-s); text-align: left; white-space: nowrap;
|
||||
}
|
||||
.apv-head:hover, .apv.open > .apv-head { color: var(--fg); background: var(--surface-hover); }
|
||||
.apv-head .caret { flex: none; color: var(--meta); transition: transform var(--dur-1); }
|
||||
.apv-head .caret.open { transform: rotate(90deg); }
|
||||
.apv-ic { width: 14px; flex: none; display: inline-flex; justify-content: center; color: var(--auto-fg, var(--warn)); }
|
||||
.apv-n { flex: none; }
|
||||
.apv-peek { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--meta); font-family: var(--font-mono); font-size: var(--chat-code-fs); }
|
||||
.apv-peek::before { content: "·"; margin-right: 8px; font-family: var(--font-ui); }
|
||||
.apv-list { margin: 2px 0 0 13px; padding-left: 6px; border-left: 1px solid var(--line); }
|
||||
.apv-row {
|
||||
display: flex; align-items: center; gap: 8px; min-height: 26px; padding: 0 6px; min-width: 0; overflow: hidden; white-space: nowrap;
|
||||
border-radius: var(--r-s); color: var(--muted); font-size: var(--chat-fs-s);
|
||||
}
|
||||
.apv-row:hover { background: var(--surface-hover); color: var(--fg); }
|
||||
.apv-cmd, .apv-path, .apv-title { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.apv-cmd, .apv-path { font-family: var(--font-mono); font-size: var(--chat-code-fs); }
|
||||
.apv-meta { flex: none; margin-left: auto; color: var(--meta); font-size: var(--fs-xs); }
|
||||
/* 1.3 upgrade notice (#727 review 3): told once that 全部自动同意 now really applies to Cursor / OpenCode / dsh */
|
||||
.nt-auto {
|
||||
text-align: left; padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--r-m); line-height: 1.6; color: var(--text);
|
||||
}
|
||||
.nt-auto-h { display: flex; align-items: center; gap: 6px; margin-bottom: 2px; }
|
||||
|
||||
@@ -8,11 +8,29 @@
|
||||
}
|
||||
.cp-card:focus-within { border-color: var(--cp-focus); box-shadow: 0 0 0 3px var(--cp-ring), 0 1px 2px rgb(0 0 0 / .04); }
|
||||
.cp-card.waiting { border-color: color-mix(in oklab, var(--warn) 45%, var(--bg)); }
|
||||
.cp-card.danger { border-color: color-mix(in oklab, var(--danger) 40%, var(--bg)); }
|
||||
.cp-danger {
|
||||
max-width: var(--col); margin: 0 auto 6px; display: flex; align-items: center; gap: 6px;
|
||||
color: var(--danger); font-size: var(--fs-s); padding: 0 2px;
|
||||
/* 1.3 全部自动同意 (#727 review 1): a persistent one-line strip above the card (Nolan: one slim line is enough) for as long as the conversation is in it, plus a
|
||||
warning-tinted card border and chip. The one exception to the grayscale accent: the semantic warning colour, darker in
|
||||
light mode so small text stays readable (≥4.5:1 on the page background), lighter in dark mode. */
|
||||
:root { --auto-fg: #b45309; --auto-bg: color-mix(in oklab, #f59e0b 10%, var(--bg)); --auto-line: color-mix(in oklab, #d97706 40%, var(--bg)); }
|
||||
:root[data-theme="dark"] { --auto-fg: #fbbf24; --auto-bg: color-mix(in oklab, #f59e0b 13%, var(--bg)); --auto-line: color-mix(in oklab, #f59e0b 42%, var(--bg)); }
|
||||
.cp-auto-on {
|
||||
max-width: var(--col); margin: 0 auto 4px; display: flex; align-items: center; gap: 6px; min-width: 0;
|
||||
height: 22px; padding: 0 4px; white-space: nowrap; overflow: hidden;
|
||||
color: var(--muted); font-size: var(--fs-s); line-height: 22px;
|
||||
}
|
||||
.cp-auto-ic { flex: none; display: inline-flex; color: var(--auto-fg); }
|
||||
.cp-auto-t { flex: 0 1 auto; min-width: 0; display: inline-flex; align-items: center; gap: 6px; overflow: hidden; cursor: help; border-radius: var(--r-s); }
|
||||
.cp-auto-t:focus-visible { outline: 2px solid var(--auto-line); outline-offset: 1px; }
|
||||
.cp-auto-t b { min-width: 0; overflow: hidden; text-overflow: ellipsis; color: var(--auto-fg); font-weight: 600; }
|
||||
.cp-auto-on .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }
|
||||
.cp-auto-back {
|
||||
flex: none; margin-left: auto; padding: 0 2px; border: 0; background: none; white-space: nowrap;
|
||||
color: var(--fg); font-size: var(--fs-s); text-decoration: underline; text-underline-offset: 2px;
|
||||
text-decoration-color: color-mix(in oklab, var(--fg) 35%, transparent); cursor: pointer;
|
||||
}
|
||||
.cp-auto-back:hover { text-decoration-color: currentColor; }
|
||||
.cp-card.auto-on { border-color: var(--auto-line); }
|
||||
.cp-card.auto-on:focus-within { border-color: var(--auto-fg); }
|
||||
.cp-hint { max-width: var(--col); margin: 6px auto 0; font-size: var(--fs-xs); color: var(--meta); text-align: center; }
|
||||
.att-note { padding: 6px 10px 0; color: var(--muted); font-size: var(--fs-s); }
|
||||
.cp-ta-wrap { position: relative; }
|
||||
@@ -82,6 +100,12 @@
|
||||
}
|
||||
.tasks-pill:hover { color: var(--fg); background: var(--surface-hover); }
|
||||
.tasks-pill svg { flex: none; color: var(--meta); }
|
||||
/* 1.3 全部自动同意: Cursor's shield idea, a filled chip with a shield-check, in the warning colour (#727 review 1) */
|
||||
.ipill.auto, .cp-bar .ipill.auto { color: var(--auto-fg); background: var(--auto-bg); border-color: var(--auto-line); font-weight: 600; }
|
||||
.ipill.auto:hover, .ipill.auto[aria-expanded="true"], .cp-bar .ipill.auto:hover, .cp-bar .ipill.auto[aria-expanded="true"] { background: color-mix(in oklab, var(--auto-fg) 16%, var(--bg)); }
|
||||
.ipill.auto svg { color: var(--auto-fg); }
|
||||
.mi.warn .sm-label { color: var(--auto-fg); }
|
||||
.ipill.static { cursor: default; }
|
||||
.mode-menu { max-width: 300px; }
|
||||
.cp-div { width: 1px; height: 14px; background: var(--line); margin: 0 4px; flex: none; }
|
||||
.cp-bar > .ibtn { flex: none; }
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
// 1.3 全部自动同意 (#727 review): every approval the daemon answers by itself is in the timeline (permission_request +
|
||||
// permission_resolved, both marked auto), so the user can always look up what was approved. Shown quietly: the auto
|
||||
// approvals of one run of tool calls become one foldable row ("已自动同意 3 项") placed after that run, so they neither
|
||||
// break the folded tool summary nor show up as cards with buttons. Pure: the reducer's items are not changed.
|
||||
import type { DisplayItem } from "./reducer.js";
|
||||
import { isShortThinking } from "./fold.js";
|
||||
|
||||
type Perm = Extract<DisplayItem, { kind: "permission" }>;
|
||||
type AutoPerm = Extract<DisplayItem, { kind: "autoperm" }>;
|
||||
|
||||
export function isAutoApproved(it: DisplayItem): it is Perm {
|
||||
return it.kind === "permission" && !!it.auto && it.status !== "cancelled";
|
||||
}
|
||||
|
||||
/** Items a tool run is made of (what foldTimeline merges); anything else ends the run */
|
||||
function inRun(it: DisplayItem): boolean {
|
||||
return it.kind === "toolgroup" || it.kind === "gone" || isShortThinking(it);
|
||||
}
|
||||
|
||||
/** Run before foldTimeline: pull auto-approved permissions out and put one "autoperm" row at the end of their run */
|
||||
export function collectAutoApproved(items: DisplayItem[]): DisplayItem[] {
|
||||
if (!items.some(isAutoApproved)) return items;
|
||||
const out: DisplayItem[] = [];
|
||||
let bucket: AutoPerm | null = null;
|
||||
const flush = () => {
|
||||
if (bucket) out.push(bucket);
|
||||
bucket = null;
|
||||
};
|
||||
for (const it of items) {
|
||||
if (isAutoApproved(it)) {
|
||||
if (!bucket) bucket = { kind: "autoperm", key: `autoperm:${it.requestId}`, items: [] };
|
||||
bucket.items.push(it);
|
||||
continue;
|
||||
}
|
||||
if (bucket && !inRun(it)) flush();
|
||||
out.push(it);
|
||||
}
|
||||
flush();
|
||||
return out;
|
||||
}
|
||||
|
||||
/** What one approval was for, on one line: the command, else the file, else the Agent's title */
|
||||
export function approvalTarget(p: Perm): string {
|
||||
const d = (p.detail ?? {}) as { command?: unknown; path?: unknown; diff?: { path?: unknown } };
|
||||
const s = typeof d.command === "string" && d.command.trim() ? d.command
|
||||
: typeof d.path === "string" && d.path.trim() ? d.path
|
||||
: typeof d.diff?.path === "string" && d.diff.path.trim() ? d.diff.path
|
||||
: p.title;
|
||||
return s.replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
/** The label of the option the daemon picked ("Allow once" …), or its id */
|
||||
export function approvalChoice(p: Perm): string | null {
|
||||
if (!p.choice) return null;
|
||||
return p.options.find((o) => o.id === p.choice)?.label ?? p.choice;
|
||||
}
|
||||
@@ -25,9 +25,11 @@ export type DisplayItem =
|
||||
| { kind: "toolgroup"; key: string; steps: ToolStep[] }
|
||||
| { kind: "plan"; key: string; itemId: string; markdown: string }
|
||||
| { kind: "todo"; key: string; items: { text: string; status: string }[] }
|
||||
| { kind: "permission"; key: string; requestId: string; title: string; kindStr: string; detail?: unknown; options: { id: string; label: string; kind: string }[]; status: "pending" | "resolved" | "cancelled"; choice?: string }
|
||||
| { kind: "permission"; key: string; requestId: string; title: string; kindStr: string; detail?: unknown; options: { id: string; label: string; kind: string }[]; status: "pending" | "resolved" | "cancelled"; choice?: string; auto?: boolean }
|
||||
| { kind: "question"; key: string; requestId: string; questions: unknown[]; answers?: Record<string, string>; status: "pending" | "answered" | "cancelled" }
|
||||
| { kind: "notice"; key: string; level: string; message: string; code?: string }
|
||||
/** 1.3 全部自动同意: the approvals the daemon gave in one run of tool calls, as one quiet foldable row (autoApproved.ts) */
|
||||
| { kind: "autoperm"; key: string; items: Extract<DisplayItem, { kind: "permission" }>[] }
|
||||
| { kind: "gone"; key: string } // placeholder: duplicate delta items cleared by sweepSiblings; skipped when rendering
|
||||
| { kind: "turnend"; key: string; status: string; durationMs?: number; error?: string; filesChanged?: number; usage?: TurnUsage;
|
||||
/** 1.3: the model the turn ran on (turn_started; null = the Agent's default) and when it ended, for the reply footer */
|
||||
@@ -224,6 +226,8 @@ export function applyEvent(st: State, ev: TimelineEvent): void {
|
||||
st.items.push({
|
||||
kind: "permission", key: `perm:${ev.requestId}`, requestId: ev.requestId,
|
||||
title: ev.title, kindStr: ev.kind, detail: ev.detail, options: ev.options, status: "pending",
|
||||
// 1.3 全部自动同意: the daemon answered it itself (never a card with buttons; see timeline/autoApproved.ts)
|
||||
...(ev.auto ? { auto: true } : {}),
|
||||
});
|
||||
return;
|
||||
case "permission_resolved": {
|
||||
@@ -232,6 +236,7 @@ export function applyEvent(st: State, ev: TimelineEvent): void {
|
||||
if (it?.kind === "permission") {
|
||||
it.status = ev.cancelled ? "cancelled" : "resolved";
|
||||
it.choice = ev.optionId;
|
||||
if (ev.auto) it.auto = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -16,8 +16,8 @@ export type TimelineEvent =
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "tool_call"; itemId: string; kind: ToolKind; title: string; status: "running" | "ok" | "failed"; input?: unknown; detail?: unknown; output?: string; exitCode?: number; durationMs?: number }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "plan"; itemId: string; markdown: string; entries?: { step: string; status: string }[] }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "todo"; items: { text: string; status: string }[] }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "permission_request"; requestId: string; title: string; kind: string; detail?: unknown; options: { id: string; label: string; kind: string }[] }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "permission_resolved"; requestId: string; optionId?: string; cancelled?: boolean }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "permission_request"; requestId: string; title: string; kind: string; detail?: unknown; options: { id: string; label: string; kind: string }[]; auto?: boolean }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "permission_resolved"; requestId: string; optionId?: string; cancelled?: boolean; auto?: boolean }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "question"; requestId: string; questions: unknown[] }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "question_answered"; requestId: string; answers: Record<string, string> }
|
||||
| { seq: number; ts: number; threadId: string; turnId?: string; type: "usage"; inputTokens: number; outputTokens: number; cacheReadTokens: number; costUsd: number; contextWindow?: number }
|
||||
|
||||
Reference in New Issue
Block a user