Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
Batch delete-file confirmations by turn
wytaceab30f4959
diff --git a/src/main/model/core-agent/client.ts b/src/main/model/core-agent/client.tsindex 60ca446c..a07662dc 100644--- a/src/main/model/core-agent/client.ts+++ b/src/main/model/core-agent/client.ts@@ -180,6 +180,7 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<StreadOnlyExtraRoots,agentId,cid,+ turnId,projectId,onFileWritten,hasProducedPath,@@ -290,6 +291,7 @@ export async function* streamChatWithModel(opts: ChatOptions): AsyncGenerator<StuserId,agentId,...(cid ? { cid } : {}),+ ...(turnId ? { turnId } : {}),...(projectId ? { projectId } : {}),...(skillList !== undefined ? { skillList } : {}),...(projectAllowedSkillIds !== undefined ? { projectAllowedSkillIds } : {}),diff --git a/src/main/model/core-agent/delete-file-confirm.ts b/src/main/model/core-agent/delete-file-confirm.tsindex 3a86cd20..6cf5d16e 100644--- a/src/main/model/core-agent/delete-file-confirm.ts+++ b/src/main/model/core-agent/delete-file-confirm.ts@@ -7,15 +7,17 @@* 1. LLM calls `delete_file({ path })` (no token).* Tool calls `requestConfirmation(absPath, ctx)` → gets a fresh* `confirmation_token` synchronously, returns it to the LLM along- * with `requires_user_confirmation: true`. The renderer renders an- * inline card.+ * with `requires_user_confirmation: true`. The renderer renders it in+ * an inline card; multiple pending tokens from the same turn may be+ * grouped into one card.* 2. LLM sees the token-bearing result; per skill-creator's SKILL.md* rule, it MUST end the turn with a prose ask, NOT immediately* re-call delete_file in the same turn. The token is in `pending`* state until the user clicks the card.* 3. User clicks Confirm / Cancel → renderer invokes- * `delete_file.respond` → `resolveConfirmation(token, granted)`- * flips the state to `granted` / `denied`.+ * `delete_file.respond` for each token in that card →+ * `resolveConfirmation(token, granted)` flips each state to+ * `granted` / `denied`.* 4. LLM (in a later turn, after the user has replied) calls* `delete_file({ path, confirmation_token })` → tool calls* `consumeGrantedConfirmation(token, absPath)`:@@ -76,6 +78,9 @@ export interface DeleteConfirmContext {display_path: string;/** Active conv id; lets the renderer optionally scope its UI hint. */cid?: string;+ /** Stable id for the current visible actor turn. Used by the renderer to+ * batch only confirmations produced by the same model turn. */+ turn_id?: string;}/** Mint a fresh confirmation token, emit the inline card to the renderer,@@ -90,6 +95,7 @@ export function requestConfirmation(absPath: string, ctx: DeleteConfirmContext):path: ctx.display_path,abs_path: absPath,cid: ctx.cid ?? '',+ turn_id: ctx.turn_id ?? '',});} catch (err) {log.warn(`emit confirmation_required failed token=${token}: ${(err as Error).message}`);diff --git a/src/main/model/core-agent/local-tools.ts b/src/main/model/core-agent/local-tools.tsindex 79e45636..0cb12816 100644--- a/src/main/model/core-agent/local-tools.ts+++ b/src/main/model/core-agent/local-tools.ts@@ -74,6 +74,9 @@ export interface LocalToolsOpts {* (artifacts live under `chat_artifacts/<cid>/`); the tool errors out* when it's missing. */cid?: string;+ /** Stable id for the current actor/model turn. Renderer uses this to group+ * only delete confirmations produced by that same turn. */+ turnId?: string;/** The actor id producing this turn (an agent's id, or `''` for the* group-chat commander / edit chats). Stamped into `create_artifact`'s* metadata so the renderer knows which actor to route an interaction@@ -93,7 +96,7 @@ export interface LocalToolsOpts {extraRoots?: readonly string[];/** Extra absolute roots that are **read-only** for write-side tools* (`write_file` / `edit_file`) but in-scope for `delete_file`. The- * per-call UI confirmation modal on `delete_file` is the safety gate+ * per-call UI confirmation card on `delete_file` is the safety gate* that makes this asymmetry safe — every delete requires explicit* user click, so a path the caller marked read-only is still* protected from silent overwrite by `write_file` / `edit_file`@@ -851,12 +854,14 @@ function createCreateArtifactTool(opts: LocalToolsOpts): AgentTool {/** Wrapped `delete_file` tool — single-file unlink, sandboxed identically to* `edit_file` (workspace + current attachment dir + extraRoots / readonly).* Destructive, so on top of `localExec` we require a per-call user click- * in the inline confirm card.+ * in the inline confirm card. The renderer may group multiple pending+ * per-file tokens from the same turn into one card, but the tool still+ * consumes one token per file.** Async token model (does NOT block the LLM turn — see* delete-file-confirm.ts header):* - First call: `delete_file({path})` (no token). Tool mints a token,- * emits the card, and returns IMMEDIATELY with `requires_user_confirmation`+ * emits/adds to a card, and returns IMMEDIATELY with `requires_user_confirmation`* so the LLM can keep doing other tool calls / finish the turn.* Skill-creator authoring rules require the LLM to stop in prose* after this and ask the user; never retry in the same turn.@@ -880,7 +885,8 @@ function createDeleteFileTool(opts: LocalToolsOpts): AgentTool {'Flow:\n' +' Step 1 — `delete_file({path})` (no token). Tool emits an inline ' +'confirm card to the user and returns `requires_user_confirmation: ' +- 'true` with a `confirmation_token`. The tool does NOT block. Tell ' ++ 'true` with a `confirmation_token`. Multiple Step 1 calls from the ' ++ 'same turn may be grouped into one user-facing card. The tool does NOT block. Tell ' +'the user in prose what you intend to delete; do NOT retry with ' +'the token in the same turn — wait for the user to click the card ' +'and reply, then retry on the next turn.\n' +@@ -996,13 +1002,17 @@ function createDeleteFileTool(opts: LocalToolsOpts): AgentTool {isError: true,};}- const newToken = requestDeleteConfirmation(abs, { display_path: rawPath, cid: opts.cid });+ const newToken = requestDeleteConfirmation(abs, {+ display_path: rawPath,+ cid: opts.cid,+ turn_id: opts.turnId,+ });log.info(`delete_file confirmation requested user=${opts.userId ?? '?'} path=${abs} token=${newToken}`);return {content:- `requires_user_confirmation: a confirmation card for "${rawPath}" has been shown to the user.\n` ++ `requires_user_confirmation: "${rawPath}" has been added to the user's confirmation card.\n` +`confirmation_token: ${newToken}\n` +- `Next step: stop calling tools this turn. In your reply prose, tell the user what you plan to delete and ask them to click the card. ` ++ `Next step: stop calling tools this turn after requesting all intended deletes. In your reply prose, tell the user what you plan to delete and ask them to click the card. ` +`On the user's next reply, call delete_file again with BOTH \`path\` and \`confirmation_token\` set to complete the deletion.`,};},diff --git a/src/main/model/core-agent/runner.ts b/src/main/model/core-agent/runner.tsindex ea263f96..a92560e7 100644--- a/src/main/model/core-agent/runner.ts+++ b/src/main/model/core-agent/runner.ts@@ -97,6 +97,9 @@ export interface BuildRunnerParams {* / process_file_full calls whose path targets the attachment dir of the* current conv. */cid?: string;+ /** Stable id for the current visible actor/model turn. Used by delete_file+ * confirmation UI so batching never crosses prior conversation turns. */+ turnId?: string;/** Project id of the conversation, when it belongs to one. Threaded* through to local-tools / file-tools / image-gen-tool so workspace* resolution picks up the project-scoped selection. Resolved once at@@ -363,6 +366,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{const localTools = createLocalTools({...(uid ? { userId: uid } : {}),...(params.cid ? { cid: params.cid } : {}),+ ...(params.turnId ? { turnId: params.turnId } : {}),...(agentId ? { agentId } : {}),...(params.projectId ? { projectId: params.projectId } : {}),...(params.extraRoots?.length ? { extraRoots: params.extraRoots } : {}),@@ -371,7 +375,7 @@ export async function buildRunner(params: BuildRunnerParams): Promise<{// write-side tools (`write_file` / `edit_file`) still use// `guardEditPath`, which ignores readOnly roots and keeps them// immutable. The asymmetry exists because `delete_file` carries a- // per-call UI confirm modal (`delete-file-confirm.ts`) that the user+ // per-call UI confirm card (`delete-file-confirm.ts`) that the user// physically has to click — that gate justifies allowing deletion of// paths the caller marked read-only for silent writes....(params.readOnlyExtraRoots?.length ? { readOnlyExtraRoots: params.readOnlyExtraRoots } : {}),diff --git a/src/main/model/core-agent/tool-catalog.ts b/src/main/model/core-agent/tool-catalog.tsindex a9a9c93c..c5da4335 100644--- a/src/main/model/core-agent/tool-catalog.ts+++ b/src/main/model/core-agent/tool-catalog.ts@@ -65,7 +65,7 @@ export const TOOL_CATALOG: ToolCatalogEntry[] = [{ name: 'read_file', group: 'fs', summary: 'Read a slice of text from a workspace or attachment file (PDF/DOCX text or image as multimodal).' },{ name: 'write_file', group: 'fs', permission: 'localExec', summary: 'Write text/code/markdown into the workspace; resolves under $working_dir.' },{ name: 'edit_file', group: 'fs', permission: 'localExec', summary: 'In-place `old_string → new_string` replacement on an existing text file (instead of rewriting the whole file).' },- { name: 'delete_file', group: 'fs', permission: 'localExec', summary: 'Delete a single file from the workspace / current attachment dir / extraRoots. Every call pops an in-app confirm modal — the tool blocks until the user clicks yes; on deny / timeout no file is touched. Use instead of `bash rm` for single-file removals.' },+ { name: 'delete_file', group: 'fs', permission: 'localExec', summary: 'Delete a single file from the workspace / current attachment dir / extraRoots. The first call shows an inline confirmation card and returns a token; multiple deletes from the same turn are grouped in one card when possible. Use instead of `bash rm` for removals.' },{ name: 'list_files', group: 'fs', summary: 'List the workspace directory tree.' },{ name: 'stat_file', group: 'fs', summary: 'Trigger PDF/DOCX extraction and return total_chars; call before read_file.' },{ name: 'search_files', group: 'fs', summary: 'Find files by name / glob across the workspace + attachment scope.' },diff --git a/src/main/system_skills/skill-creator/SKILL.md b/src/main/system_skills/skill-creator/SKILL.mdindex cfbe78da..b245727b 100644--- a/src/main/system_skills/skill-creator/SKILL.md+++ b/src/main/system_skills/skill-creator/SKILL.md@@ -135,14 +135,14 @@ Each file under the skill directory is written via this whole-file replacement bUse the `delete_file` tool (NOT a `<<<skill-file>>>` block) — two-step token flow:-1. **Step 1: ask** — `delete_file({ path: "<abs path>" })` without a token. Tool returns immediately with `requires_user_confirmation: true` + a `confirmation_token`, and an inline card appears for the user. Do NOT call delete_file again this turn. In your reply prose, tell the user what file you're about to delete and ask them to click the card. End the turn.+1. **Step 1: ask** — `delete_file({ path: "<abs path>" })` without a token. Tool returns immediately with `requires_user_confirmation: true` + a `confirmation_token`, and the path is added to an inline confirmation card for the user. For multiple intended deletes, issue one Step 1 call per file in the same turn, then stop. Do NOT call delete_file with any token again this turn. In your reply prose, tell the user what file(s) you're about to delete and ask them to click the card. End the turn.2. **Step 2: complete** — after the user's next reply (which can be anything: "yes", "go ahead", silence, or unrelated chat — the card click is what matters), call `delete_file({ path, confirmation_token: "<token from step 1>" })`. Tool checks the card state:- `granted` → file is unlinked.- `pending` (`E_AWAITING_USER`) → user hasn't clicked yet; stop and wait for the next reply, then retry with the same token.- `denied` (`E_USER_DENIED`) → user declined; do not retry, treat the file as kept.- `invalid` (`E_INVALID_TOKEN`) → token expired or path changed; call Step 1 again to mint a fresh card.-**Only call `delete_file` for files inside the current skill directory.** If the user explicitly names files, delete only those. If the user asked to import / create / clean up a skill, that request implicitly authorizes you to propose cleanup for unrelated files you found inside the copied skill directory; still use the two-step confirmation card and name the evidence for each proposed deletion. Bundle multiple deletes by issuing one Step 1 call per file in the same turn (each gets its own card + token); the user then clicks each card and you complete them all in the next turn(s).+**Only call `delete_file` for files inside the current skill directory.** If the user explicitly names files, delete only those. If the user asked to import / create / clean up a skill, that request implicitly authorizes you to propose cleanup for unrelated files you found inside the copied skill directory; still use the two-step confirmation card and name the evidence for each proposed deletion. Bundle multiple deletes by issuing one Step 1 call per file in the same turn; each call gets its own token, and the UI groups pending paths into one confirmation card when possible. After the user confirms, complete each file on the next turn with its matching token.## Container shape@@ -381,7 +381,7 @@ Audit protocol:4. Delete-unneeded when the file is not referenced, not read/executed, not an input asset/template/example, and not needed to reproduce behavior. Typical delete-unneeded files include source marketplace metadata (`_skillhub_meta.json`, `.skillhub*`, install manifests), repository metadata (`.git/`, `.github/`, `.gitignore`, `.gitattributes`, `.editorconfig`), dependency/build/cache outputs (`node_modules/`, `.venv/`, `__pycache__/`, `dist/`, `build/`, `coverage/`), logs, release/contribution docs, copied workspace notes, prompt drafts, and one-off evaluation output.5. Source marketplace metadata is delete-unneeded even when it came from the source package and even when source/current diff is empty. Example: `_skillhub_meta.json` records installation/source bookkeeping and is not read by the skill runtime.6. Keep uncertain files only when they may contain domain knowledge, placeholders, templates, examples, assets, or tests; summarize why they were kept.-7. When deleting, use `delete_file` confirmation cards for each path, then complete the deletion on the next user turn. If this surface cannot delete automatically, list exact absolute paths and the evidence for deletion; do not claim the directory is clean.+7. When deleting, use `delete_file` once per path, let the UI group those paths into a confirmation card, then complete each deletion on the next user turn with its matching token. If this surface cannot delete automatically, list exact absolute paths and the evidence for deletion; do not claim the directory is clean.8. Do not finish with "no cleanup needed" until the tree inventory has been checked and every non-SKILL.md file has a keep/delete reason.**Scope = the original skill's full feature set**: by default migrate everything. If the original has 20 commands, migrate 20. Do NOT present "option A vs B" choices; do NOT drop features citing "less code / no new dependencies". If the source is a multi-skill package, install each sub-skill as an independent skill and keep each source skill's boundary. **Exception**: if the user explicitly requests a subset ("I only want the search capability"), follow what the user said.diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.jsonindex 9c04ea64..0b6dbf8f 100644--- a/src/renderer/locales/en.json+++ b/src/renderer/locales/en.json@@ -332,10 +332,15 @@"chat.send_failed": "Send failed: {msg}","local.delete_file.title": "Confirm file deletion","local.delete_file.message": "The agent is requesting deletion of the file below. Confirming removes it from disk immediately and cannot be undone.",+ "local.delete_file.batch_title": "Confirm deletion of {count} files",+ "local.delete_file.batch_message": "The agent is requesting deletion of the {count} files below. Confirming removes them from disk immediately and cannot be undone.","local.delete_file.confirm_button": "Delete",+ "local.delete_file.batch_confirm_button": "Delete all {count}","local.delete_file.cancel_button": "Cancel","local.delete_file.confirmed": "Deletion confirmed",+ "local.delete_file.batch_confirmed": "Deletion confirmed for {count} files","local.delete_file.cancelled": "Cancelled",+ "local.delete_file.batch_cancelled": "Cancelled {count} files","local.delete_file.user_continue": "Confirmed, please continue.","local.delete_file.send_to_continue": "Send a message to let the agent finish the deletion.","chat.interrupted": "Interrupted",diff --git a/src/renderer/locales/ja.json b/src/renderer/locales/ja.jsonindex 71241732..c1afc1a2 100644--- a/src/renderer/locales/ja.json+++ b/src/renderer/locales/ja.json@@ -322,10 +322,15 @@"chat.send_failed": "送信に失敗しました: {msg}","local.delete_file.title": "ファイル削除の確認","local.delete_file.message": "エージェントが以下のファイルの削除を要求しています。確認するとすぐにディスクから削除され、元に戻せません。",+ "local.delete_file.batch_title": "{count} 件のファイル削除を確認",+ "local.delete_file.batch_message": "エージェントが以下 {count} 件のファイル削除を要求しています。確認するとすぐにディスクから削除され、元に戻せません。","local.delete_file.confirm_button": "削除",+ "local.delete_file.batch_confirm_button": "{count} 件すべて削除","local.delete_file.cancel_button": "キャンセル","local.delete_file.confirmed": "削除を確認しました",+ "local.delete_file.batch_confirmed": "{count} 件のファイル削除を確認しました","local.delete_file.cancelled": "キャンセルされました",+ "local.delete_file.batch_cancelled": "{count} 件のファイル削除をキャンセルしました","local.delete_file.user_continue": "確認しました、続行してください。","local.delete_file.send_to_continue": "エージェントに削除を完了させるためメッセージを送信してください。","chat.interrupted": "中断されました",diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.jsonindex e8778756..9ffd8173 100644--- a/src/renderer/locales/zh.json+++ b/src/renderer/locales/zh.json@@ -332,10 +332,15 @@"chat.send_failed": "发送失败: {msg}","local.delete_file.title": "确认删除文件","local.delete_file.message": "智能体请求删除以下文件,确认后立即从磁盘移除,不可撤销。",+ "local.delete_file.batch_title": "确认删除 {count} 个文件",+ "local.delete_file.batch_message": "智能体请求删除以下 {count} 个文件,确认后立即从磁盘移除,不可撤销。","local.delete_file.confirm_button": "删除",+ "local.delete_file.batch_confirm_button": "删除全部 {count} 个","local.delete_file.cancel_button": "取消","local.delete_file.confirmed": "已确认删除",+ "local.delete_file.batch_confirmed": "已确认删除 {count} 个文件","local.delete_file.cancelled": "已取消",+ "local.delete_file.batch_cancelled": "已取消 {count} 个文件","local.delete_file.user_continue": "已确认,请继续。","local.delete_file.send_to_continue": "请发送一条消息让智能体继续完成删除。","chat.interrupted": "已中断",diff --git a/src/renderer/modules/delete-file-confirm.js b/src/renderer/modules/delete-file-confirm.jsindex b02dc00f..98acfec0 100644--- a/src/renderer/modules/delete-file-confirm.js+++ b/src/renderer/modules/delete-file-confirm.js@@ -2,9 +2,9 @@// Main emits a `delete_file.confirmation_required` push when an LLM agent// calls `delete_file(path)`; we render an inline card at the bottom of the// chat history (NOT a modal — the modal was disruptive and blocked the rest-// of the UI). The card carries the path + Cancel / Delete buttons; clicking-// either sends `delete_file.respond` back through IPC and the main-side-// tool unblocks.+// of the UI). Multiple pending deletes from the same visible actor turn are+// grouped into one card, so the user can confirm/cancel that turn's batch with+// a single click. Each path still keeps its own main-side confirmation token.//// See: src/main/model/core-agent/delete-file-confirm.ts (request side)// src/main/ipc/index.ts (`delete_file.respond` handler)@@ -18,6 +18,8 @@ const _deleteFileLog = (typeof createLogger === 'function'): { info: () => {}, warn: () => {} };let _deleteFileSubscription = null;+const _deleteFileBatches = new Map();+const _DELETE_CONFIRM_FALLBACK_BATCH_MS = 1000;function startDeleteFileConfirmSubscription() {if (_deleteFileSubscription) return; // idempotent@@ -88,52 +90,100 @@ function _mountDeleteConfirmCard(payload) {_respondDeleteConfirm(payload.confirm_id, false);return;}- const displayPath = String(payload.path || payload.abs_path || '');- const title = _tDelete('local.delete_file.title', '确认删除文件');- const message = _tDelete('local.delete_file.message', '是否删除以下文件?该操作不可撤销。');- const okLabel = _tDelete('local.delete_file.confirm_button', '删除');+ const key = _deleteConfirmBatchKey(container, payload);+ const hasTurnId = _deleteConfirmHasTurnId(payload);+ let batch = _deleteFileBatches.get(key);+ if (!batch || batch.settled || batch.container !== container || batch.card.parentNode !== container || (!hasTurnId && !batch.accepting)) {+ batch = _createDeleteConfirmBatch(container, key, hasTurnId);+ _deleteFileBatches.set(key, batch);+ }+ _addDeleteConfirmEntry(batch, payload);+}++function _deleteConfirmTurnId(payload) {+ return String((payload && (payload.turn_id || payload.turnId)) || '');+}++function _deleteConfirmHasTurnId(payload) {+ return !!_deleteConfirmTurnId(payload);+}++function _deleteConfirmBatchKey(container, payload) {+ const surface = container.id || 'chat-history';+ const cid = String(payload && payload.cid ? payload.cid : '');+ const turnId = _deleteConfirmTurnId(payload);+ return surface + ':' + cid + ':' + (turnId ? ('turn:' + turnId) : 'fallback');+}++function _createDeleteConfirmBatch(container, key, hasTurnId) {const cancelLabel = _tDelete('local.delete_file.cancel_button', '取消');- const confirmedText = _tDelete('local.delete_file.confirmed', '已确认删除');- const cancelledText = _tDelete('local.delete_file.cancelled', '已取消');const card = document.createElement('div');card.className = 'delete-confirm-card';- card.dataset.deleteConfirmId = payload.confirm_id;+ card.dataset.deleteConfirmBatch = key;card.innerHTML = `- <div class="delete-confirm-title">${escapeHtml(title)}</div>- <div class="delete-confirm-path"><code></code></div>- <div class="delete-confirm-message">${escapeHtml(message)}</div>+ <div class="delete-confirm-title"></div>+ <div class="delete-confirm-path-list"></div>+ <div class="delete-confirm-message"></div><div class="delete-confirm-actions">- <button class="btn" type="button" data-delete-act="cancel">${escapeHtml(cancelLabel)}</button>- <button class="btn btn-danger" type="button" data-delete-act="ok">${escapeHtml(okLabel)}</button>+ <button class="btn" type="button" data-delete-act="cancel"></button>+ <button class="btn btn-danger" type="button" data-delete-act="ok"></button></div><div class="delete-confirm-result" hidden></div>`;- // Set the path via textContent to avoid any HTML interpretation of slashes- // / quoting that escapeHtml on long abs paths can mangle visually.- card.querySelector('.delete-confirm-path code').textContent = displayPath;container.appendChild(card);_scrollDeleteConfirmIntoView(card);+ const titleEl = card.querySelector('.delete-confirm-title');+ const pathListEl = card.querySelector('.delete-confirm-path-list');+ const messageEl = card.querySelector('.delete-confirm-message');const okBtn = card.querySelector('[data-delete-act="ok"]');const cancelBtn = card.querySelector('[data-delete-act="cancel"]');const resultEl = card.querySelector('.delete-confirm-result');+ cancelBtn.textContent = cancelLabel;++ const batch = {+ key,+ container,+ card,+ titleEl,+ pathListEl,+ messageEl,+ okBtn,+ cancelBtn,+ resultEl,+ entries: [],+ ids: new Set(),+ settled: false,+ accepting: true,+ hasTurnId,+ fallbackTimer: null,+ };+ _refreshDeleteConfirmFallbackWindow(batch);- let settled = false;const settle = async (granted) => {- if (settled) return;- settled = true;+ if (batch.settled) return;+ batch.settled = true;+ _deleteFileBatches.delete(batch.key);+ if (batch.fallbackTimer) {+ clearTimeout(batch.fallbackTimer);+ batch.fallbackTimer = null;+ }+ const entries = batch.entries.slice();+ const count = entries.length;okBtn.disabled = true;cancelBtn.disabled = true;card.classList.add(granted ? 'is-confirmed' : 'is-cancelled');- resultEl.textContent = granted ? confirmedText : cancelledText;+ resultEl.textContent = _deleteConfirmResultText(granted, count);resultEl.hidden = false;- await _respondDeleteConfirm(payload.confirm_id, granted);+ for (const entry of entries) {+ await _respondDeleteConfirm(entry.confirm_id, granted);+ }// The token state flip alone doesn't wake the LLM — Step 1 already// ended the turn, so without a fresh user message Step 2 never fires// and the file isn't actually unlinked. Auto-dispatch a short user- // message via the active surface's input + send button so the LLM- // gets a new turn and retries with the token. Cancel doesn't need+ // message via the active surface's input + send button once per batch+ // so the LLM gets a new turn and retries with the tokens. Cancel doesn't need// this — the LLM treats `denied` as terminal.if (granted) {const trigger = _tDelete('local.delete_file.user_continue', '已确认,请继续。');@@ -147,6 +197,66 @@ function _mountDeleteConfirmCard(payload) {okBtn.addEventListener('click', () => settle(true));cancelBtn.addEventListener('click', () => settle(false));+ return batch;+}++function _addDeleteConfirmEntry(batch, payload) {+ const confirmId = String(payload.confirm_id || '');+ if (!confirmId || batch.ids.has(confirmId) || batch.settled) return;+ _refreshDeleteConfirmFallbackWindow(batch);+ const displayPath = String(payload.path || payload.abs_path || '');+ batch.ids.add(confirmId);+ batch.entries.push({ confirm_id: confirmId, path: displayPath });+ batch.card.dataset.deleteConfirmId = batch.entries[0].confirm_id;+ batch.card.dataset.deleteConfirmCount = String(batch.entries.length);+ _renderDeleteConfirmBatch(batch);+ _scrollDeleteConfirmIntoView(batch.card);+}++function _refreshDeleteConfirmFallbackWindow(batch) {+ if (!batch || batch.hasTurnId) return;+ if (batch.fallbackTimer) clearTimeout(batch.fallbackTimer);+ batch.accepting = true;+ batch.fallbackTimer = setTimeout(() => {+ batch.accepting = false;+ batch.fallbackTimer = null;+ }, _DELETE_CONFIRM_FALLBACK_BATCH_MS);+}++function _renderDeleteConfirmBatch(batch) {+ const count = batch.entries.length;+ const isBatch = count > 1;+ batch.titleEl.textContent = isBatch+ ? _tDelete('local.delete_file.batch_title', '确认删除 {count} 个文件', { count })+ : _tDelete('local.delete_file.title', '确认删除文件');+ batch.messageEl.textContent = isBatch+ ? _tDelete('local.delete_file.batch_message', '智能体请求删除以下 {count} 个文件,确认后立即从磁盘移除,不可撤销。', { count })+ : _tDelete('local.delete_file.message', '是否删除以下文件?该操作不可撤销。');+ batch.okBtn.textContent = isBatch+ ? _tDelete('local.delete_file.batch_confirm_button', '删除全部 {count} 个', { count })+ : _tDelete('local.delete_file.confirm_button', '删除');++ while (batch.pathListEl.firstChild) batch.pathListEl.removeChild(batch.pathListEl.firstChild);+ for (const entry of batch.entries) {+ const row = document.createElement('div');+ row.className = 'delete-confirm-path';+ row.dataset.deleteConfirmId = entry.confirm_id;+ const code = document.createElement('code');+ code.textContent = entry.path;+ row.appendChild(code);+ batch.pathListEl.appendChild(row);+ }+}++function _deleteConfirmResultText(granted, count) {+ if (count > 1) {+ return granted+ ? _tDelete('local.delete_file.batch_confirmed', '已确认删除 {count} 个文件', { count })+ : _tDelete('local.delete_file.batch_cancelled', '已取消 {count} 个文件', { count });+ }+ return granted+ ? _tDelete('local.delete_file.confirmed', '已确认删除')+ : _tDelete('local.delete_file.cancelled', '已取消');}/** Fire a fresh user message in the currently active chat surface so thediff --git a/src/renderer/style.css b/src/renderer/style.cssindex 22444882..e1d9bcaa 100644--- a/src/renderer/style.css+++ b/src/renderer/style.css@@ -6529,6 +6529,16 @@ body.model-not-configured .main-content { flex-direction: column; }font-weight: 600;color: var(--danger, #dc2626);}+.delete-confirm-path-list {+ display: flex;+ flex-direction: column;+ gap: 6px;+ max-height: 180px;+ overflow: auto;+}+.delete-confirm-path {+ min-width: 0;+}.delete-confirm-path code {display: block;padding: 6px 10px;diff --git a/test/renderer/delete-file-confirm.test.ts b/test/renderer/delete-file-confirm.test.tsnew file mode 100644index 00000000..1bee76d4--- /dev/null+++ b/test/renderer/delete-file-confirm.test.ts@@ -0,0 +1,312 @@+import { describe, it, expect } from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import * as vm from 'node:vm';++class FakeClassList {+ private readonly items = new Set<string>();++ setFromString(value: string) {+ this.items.clear();+ for (const item of String(value || '').split(/\s+/)) {+ if (item) this.items.add(item);+ }+ }++ add(...names: string[]) {+ for (const name of names) this.items.add(name);+ }++ remove(...names: string[]) {+ for (const name of names) this.items.delete(name);+ }++ contains(name: string) {+ return this.items.has(name);+ }+}++class FakeElement {+ id = '';+ readonly tagName: string;+ readonly children: FakeElement[] = [];+ parentNode: FakeElement | null = null;+ dataset: Record<string, string> = {};+ style: Record<string, string> = {};+ classList = new FakeClassList();+ hidden = false;+ disabled = false;+ value = '';+ offsetParent: unknown = {};+ private listeners = new Map<string, Function[]>();+ private _className = '';+ private _innerHTML = '';+ private _textContent = '';++ constructor(tagName = 'div') {+ this.tagName = tagName.toUpperCase();+ }++ set className(value: string) {+ this._className = String(value || '');+ this.classList.setFromString(this._className);+ }++ get className() {+ return this._className;+ }++ set innerHTML(value: string) {+ this._innerHTML = String(value || '');+ this.children.splice(0);+ if (this._innerHTML.includes('delete-confirm-title')) {+ this.appendChild(makeEl('div', 'delete-confirm-title'));+ this.appendChild(makeEl('div', 'delete-confirm-path-list'));+ this.appendChild(makeEl('div', 'delete-confirm-message'));+ const actions = makeEl('div', 'delete-confirm-actions');+ const cancel = makeEl('button', 'btn');+ cancel.dataset.deleteAct = 'cancel';+ const ok = makeEl('button', 'btn btn-danger');+ ok.dataset.deleteAct = 'ok';+ actions.appendChild(cancel);+ actions.appendChild(ok);+ this.appendChild(actions);+ const result = makeEl('div', 'delete-confirm-result');+ result.hidden = true;+ this.appendChild(result);+ }+ }++ get innerHTML() {+ return this._innerHTML;+ }++ set textContent(value: string) {+ this._textContent = String(value ?? '');+ }++ get textContent() {+ return this._textContent;+ }++ get firstChild() {+ return this.children[0] || null;+ }++ appendChild(child: FakeElement) {+ child.parentNode = this;+ this.children.push(child);+ return child;+ }++ removeChild(child: FakeElement) {+ const idx = this.children.indexOf(child);+ if (idx >= 0) this.children.splice(idx, 1);+ child.parentNode = null;+ return child;+ }++ querySelector(selector: string): FakeElement | null {+ return findInTree(this, selector);+ }++ addEventListener(type: string, fn: Function) {+ const arr = this.listeners.get(type) || [];+ arr.push(fn);+ this.listeners.set(type, arr);+ }++ dispatchEvent(ev: { type: string }) {+ for (const fn of this.listeners.get(ev.type) || []) fn(ev);+ return true;+ }++ async click() {+ for (const fn of this.listeners.get('click') || []) {+ await fn({ target: this, preventDefault() {}, stopPropagation() {} });+ }+ }++ scrollIntoView() {}+}++function makeEl(tagName: string, className = '') {+ const el = new FakeElement(tagName);+ el.className = className;+ return el;+}++function findInTree(root: FakeElement, selector: string): FakeElement | null {+ for (const child of root.children) {+ if (matches(child, selector)) return child;+ const nested = findInTree(child, selector);+ if (nested) return nested;+ }+ return null;+}++function matches(el: FakeElement, selector: string) {+ if (selector.startsWith('.')) return el.classList.contains(selector.slice(1));+ const attrMatch = /^\[data-([a-z-]+)="([^"]+)"\]$/.exec(selector);+ if (attrMatch) {+ const key = attrMatch[1].replace(/-([a-z])/g, (_, c) => c.toUpperCase());+ return el.dataset[key] === attrMatch[2];+ }+ if (/^[a-z]+$/i.test(selector)) return el.tagName.toLowerCase() === selector.toLowerCase();+ return false;+}++function loadHarness() {+ const elements = new Map<string, FakeElement>();+ const history = makeEl('div');+ history.id = 'chat-history';+ const input = makeEl('textarea');+ input.id = 'chat-input';+ const send = makeEl('button');+ send.id = 'chat-send-btn';+ elements.set(history.id, history);+ elements.set(input.id, input);+ elements.set(send.id, send);++ const invokeCalls: Array<{ channel: string; payload: any }> = [];+ let sendClicks = 0;+ send.click = async () => { sendClicks += 1; };++ const dict: Record<string, string> = {+ 'local.delete_file.title': 'Confirm file deletion',+ 'local.delete_file.message': 'Delete this file?',+ 'local.delete_file.batch_title': 'Confirm deletion of {count} files',+ 'local.delete_file.batch_message': 'Delete these {count} files?',+ 'local.delete_file.confirm_button': 'Delete',+ 'local.delete_file.batch_confirm_button': 'Delete all {count}',+ 'local.delete_file.cancel_button': 'Cancel',+ 'local.delete_file.confirmed': 'Deletion confirmed',+ 'local.delete_file.batch_confirmed': 'Deletion confirmed for {count} files',+ 'local.delete_file.cancelled': 'Cancelled',+ 'local.delete_file.batch_cancelled': 'Cancelled {count} files',+ 'local.delete_file.user_continue': 'Confirmed, please continue.',+ };++ const context: any = {+ console,+ Map,+ Set,+ Object,+ String,+ RegExp,+ setTimeout,+ clearTimeout,+ createLogger: () => ({ info() {}, warn() {} }),+ t: (key: string, vars?: Record<string, unknown>) => {+ let text = dict[key] || key;+ for (const [k, v] of Object.entries(vars || {})) {+ text = text.replace(new RegExp('\\{' + k + '\\}', 'g'), String(v));+ }+ return text;+ },+ Event: class {+ type: string;+ constructor(type: string) { this.type = type; }+ },+ KeyboardEvent: class {+ type: string;+ key: string;+ code: string;+ constructor(type: string, init: { key?: string; code?: string } = {}) {+ this.type = type;+ this.key = init.key || '';+ this.code = init.code || '';+ }+ },+ document: {+ getElementById: (id: string) => elements.get(id) || null,+ createElement: (tagName: string) => makeEl(tagName),+ },+ window: {+ orkas: {+ invoke: async (channel: string, payload: any) => {+ invokeCalls.push({ channel, payload });+ return { ok: true };+ },+ },+ },+ };+ context.window.window = context.window;+ vm.createContext(context);+ const code = fs.readFileSync(+ path.join(__dirname, '../../src/renderer/modules/delete-file-confirm.js'),+ 'utf8',+ );+ vm.runInContext(code, context, { filename: 'delete-file-confirm.js' });+ return {+ context,+ history,+ input,+ send,+ invokeCalls,+ get sendClicks() { return sendClicks; },+ };+}++function pathTexts(card: FakeElement) {+ const list = card.querySelector('.delete-confirm-path-list');+ if (!list) return [];+ return list.children.map((row) => row.querySelector('code')?.textContent || '');+}++describe('delete-file-confirm batching', () => {+ it('groups multiple pending delete confirmations into one card', async () => {+ const h = loadHarness();++ h.context._handleDeleteFileConfirmRequest({ confirm_id: 'tok-a', path: 'a.txt', cid: 'c1', turn_id: 'turn-1' });+ h.context._handleDeleteFileConfirmRequest({ confirm_id: 'tok-b', path: 'b.txt', cid: 'c1', turn_id: 'turn-1' });++ expect(h.history.children).toHaveLength(1);+ const card = h.history.children[0];+ expect(card.dataset.deleteConfirmCount).toBe('2');+ expect(card.querySelector('.delete-confirm-title')?.textContent).toBe('Confirm deletion of 2 files');+ expect(pathTexts(card)).toEqual(['a.txt', 'b.txt']);++ await card.querySelector('[data-delete-act="ok"]')!.click();++ expect(h.invokeCalls).toEqual([+ { channel: 'delete_file.respond', payload: { confirm_id: 'tok-a', granted: true } },+ { channel: 'delete_file.respond', payload: { confirm_id: 'tok-b', granted: true } },+ ]);+ expect(h.sendClicks).toBe(1);+ expect(h.input.value).toBe('Confirmed, please continue.');+ expect(card.classList.contains('is-confirmed')).toBe(true);+ expect(card.querySelector('.delete-confirm-result')?.textContent).toBe('Deletion confirmed for 2 files');+ });++ it('cancels every token in the grouped card without auto-continuing', async () => {+ const h = loadHarness();++ h.context._handleDeleteFileConfirmRequest({ confirm_id: 'tok-a', path: 'a.txt', cid: 'c1', turn_id: 'turn-1' });+ h.context._handleDeleteFileConfirmRequest({ confirm_id: 'tok-b', path: 'b.txt', cid: 'c1', turn_id: 'turn-1' });++ const card = h.history.children[0];+ await card.querySelector('[data-delete-act="cancel"]')!.click();++ expect(h.invokeCalls).toEqual([+ { channel: 'delete_file.respond', payload: { confirm_id: 'tok-a', granted: false } },+ { channel: 'delete_file.respond', payload: { confirm_id: 'tok-b', granted: false } },+ ]);+ expect(h.sendClicks).toBe(0);+ expect(card.classList.contains('is-cancelled')).toBe(true);+ expect(card.querySelector('.delete-confirm-result')?.textContent).toBe('Cancelled 2 files');+ });++ it('does not merge a new turn into an older pending card', () => {+ const h = loadHarness();++ h.context._handleDeleteFileConfirmRequest({ confirm_id: 'tok-old', path: 'old.txt', cid: 'c1', turn_id: 'turn-1' });+ h.context._handleDeleteFileConfirmRequest({ confirm_id: 'tok-new', path: 'new.txt', cid: 'c1', turn_id: 'turn-2' });++ expect(h.history.children).toHaveLength(2);+ expect(h.history.children[0].dataset.deleteConfirmCount).toBe('1');+ expect(h.history.children[1].dataset.deleteConfirmCount).toBe('1');+ expect(pathTexts(h.history.children[0])).toEqual(['old.txt']);+ expect(pathTexts(h.history.children[1])).toEqual(['new.txt']);+ });+});