Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(web): 智能体 API 页那三张确认框被拒时留着,原因也留在框里(7.35)

lmlihengf99b34dd1533
diff --git a/changelog/unreleased/2026-10-24-agent-api-refusal.md b/changelog/unreleased/2026-10-24-agent-api-refusal.md
new file mode 100644
index 00000000..0cc2dea0
--- /dev/null
+++ b/changelog/unreleased/2026-10-24-agent-api-refusal.md
@@ -0,0 +1,42 @@
+# Agent API: a refused off-switch, keyless switch or key delete keeps its question — and the reason
+
+- **Date:** 2026-10-24
+- **Type:** fix
+- **Scope:** `web`
+- **Breaking:** no
+
+[中文](2026-10-24-agent-api-refusal.zh.md)
+
+The API tab of an Agent's settings asks three questions: turn the API off, allow keyless access,
+delete a key. All three used to close first and write second, so a refusal changed nothing on the
+page or on the server (the switch stayed on, the key stayed listed) yet the reason arrived as a
+toast that dismissed itself after six seconds and sat above the card. The user was left looking at
+the state as it had been, with nothing on screen saying why the write did not happen.
+
+Now each card stays until its write lands; a refusal leaves it open with the server's words drawn
+under its sentence (`ConfirmModal`'s `refusal` slot, same "Refused:" lead-in as the other cards in
+the app), so the retry is the same button. While the write is in flight the card's two buttons are
+disabled, and opening a card again drops the previous reason, which belonged to the attempt it
+named.
+
+## Details
+
+- `features/agents/api-tab.tsx`: the three confirmations (`AgentApiOffConfirm`, `KeylessOnConfirm`,
+ `DeleteKeyConfirm`) no longer call `onClose()` before writing — they hand the outcome on, and the
+ tab closes the card only on the landing of the write. Each refusal gets its own state
+ (`offRefusal` / `keylessRefusal` / `deleteRefusal`) rendered through `S.common.refused`; the key
+ delete hands the server's words on via `onRefused` where it used to toast. The three openers (the
+ API switch, the keyless switch, a row's trash button) clear their refusal as they open.
+- The controls without a question of their own (turning the API on, the approval mode, keyless off)
+ still report a refused write as a toast: there is no card to keep, and the control stays on the
+ value the server holds.
+- New browser test `e2e/agent-api-refusal.spec.mjs` (three): an API-off, a keyless switch and a key
+ delete each refused at `page.route` 500 keep the card, its sentence and the state the server
+ holds (nothing to dismiss in the notification region), and reopening shows no stale reason; the
+ retry on the same card writes it — the card closes, and the server answers with the new state.
+
+## Compatibility
+
+- No interface, wire-format, stored-data or dependency change: only *when* the cards close, *where*
+ the reason is drawn, and that the card's buttons are disabled while its write is in flight. No new
+ copy beyond the existing `S.common.refused` lead-in.
diff --git a/changelog/unreleased/2026-10-24-agent-api-refusal.zh.md b/changelog/unreleased/2026-10-24-agent-api-refusal.zh.md
new file mode 100644
index 00000000..e4fe576c
--- /dev/null
+++ b/changelog/unreleased/2026-10-24-agent-api-refusal.zh.md
@@ -0,0 +1,34 @@
+# 智能体的 API 页:关闭访问 / 无密钥访问 / 删除密钥被拒时,框留着,原因也留在框里
+
+- **Date:** 2026-10-24
+- **Type:** fix
+- **Scope:** `web`
+- **Breaking:** no
+
+[English](2026-10-24-agent-api-refusal.md)
+
+智能体设置 › API 页上有三个会先问一句的动作:关闭 API 访问、允许无密钥访问、删除密钥。三处过去都是先关框、
+再写请求,于是写入被拒的时候页面上与服务端上什么都没变(开关还是开着、那一行密钥还在),原因却落进一条六秒后
+自己消失、还浮在框上方的通知里 —— 用户面对的仍是原来的样子,屏幕上没有任何一句说明这次写入为什么没成。
+
+现在每张框都留到自己的写入落地;被拒时框留着,服务端的原话画在它自己那句话下面(`ConfirmModal` 的
+`refusal` 槽,用的是应用既有的「操作被拒绝:」前缀),重试就是同一个按钮。写入在途时框上两个按钮置灰,重开这
+张框会先清掉上一次的原因 —— 那句话属于上次那次尝试。
+
+## 细节
+
+- `features/agents/api-tab.tsx`:三张确认框(`AgentApiOffConfirm` / `KeylessOnConfirm` /
+ `DeleteKeyConfirm`)不再在写之前调 `onClose()`,而是把结果交回去,由这一页只在写入落地时才关框。每处拒绝各
+ 有一个状态(`offRefusal` / `keylessRefusal` / `deleteRefusal`),经 `S.common.refused` 画进框里;删除密钥
+ 过去弹 toast,现在把服务端原话交给 `onRefused`。三个入口(API 开关、无密钥开关、行上的删除按钮)在打开框时
+ 先清掉各自的原因。
+- 没有自己那张框的控件(打开 API、审批模式、关掉无密钥)被拒时仍用 toast:没有框可留,开关也停在服务端持有的
+ 那个值上。
+- 新增浏览器用例 `e2e/agent-api-refusal.spec.mjs`(三条):关闭 API、无密钥开关、删除密钥各用
+ `page.route` 拒成 500 之后,框、框里那句话与服务端持有的状态都不变(通知区没有可点的按钮),重开不带旧原因;
+ 在同一张框上重试才真正写入 —— 框关,服务端回的是新状态。
+
+## 兼容性
+
+- 没有接口、传输格式、已存数据或依赖变化:只改了「框什么时候关」「原因画在哪」,以及写入在途时框上的按钮置灰。
+ 除既有的 `S.common.refused` 前缀外没有新文案。
diff --git a/docs/FORK-PROGRESS.md b/docs/FORK-PROGRESS.md
index a4e5e40d..6312d9f3 100644
--- a/docs/FORK-PROGRESS.md
+++ b/docs/FORK-PROGRESS.md
@@ -1434,6 +1434,23 @@ mock 路由导入序、`chat-page.tsx` 的旧探针体),自带 4 份用例
`features/settings/agent-api-section.tsx` 的密钥保存,以及 `features/company/` 的日历 / 员工 / 组织 /
手册 / 频道各处(按「一轮一处」往下排)。
+- [x] **7.35 智能体 API 页那三张确认框(关闭 API 访问 / 允许无密钥访问 / 删除密钥)被拒时,框留着,原因也留在
+ 框里**(**2026-10-24 第一百二十轮**落地,提交见该节;1 处源码 `features/agents/api-tab.tsx` + 1 个新文件
+ `packages/web/e2e/agent-api-refusal.spec.mjs`(3 条用例)+ 既有单测 `test/agent-api-tab.test.ts` 跟上
+ (19 条,含三条新的)+ changelog 一对,**无新依赖、不碰接口、无新文案**):7.34 末尾排下的「同一条扫描线」的
+ 下一处,也是「点击即关、失败只弹 toast」这一族在 `agents` 页的最后一块 —— API 页的三个动作过去都是
+ `onConfirm` 里**先** `onClose()` **再**发请求:被拒时页面上与服务端上什么都没变(开关照旧开着、那一行密钥
+ 照旧在),原因却落进一条六秒后自己消失、还浮在框上方的 toast 里。**现在**:三张框都留到自己的写入落地才算
+ 数(落地由这一页关框),被拒时把服务端原话交给各自的状态(`offRefusal` / `keylessRefusal` /
+ `deleteRefusal`),经 `ConfirmModal` 的 `refusal` 槽画在句子下面、重试按钮正上方;写入在途时框上两个按钮
+ 置灰(`busy`);三个入口(API 开关、无密钥开关、行上的删除按钮)先开框再清上一次的原因。删除密钥过去弹
+ toast,现在把原话交给新的 `onRefused`。没有自己那张框的控件(打开 API、审批模式、关掉无密钥)照旧弹 toast:
+ 没有框可留,开关也停在服务端持有的值上。细节、两态读数与反证见「第一百二十轮」一节。**还差什么**:
+ `features/settings/agent-api-section.tsx` 里**管理员那一侧**的关闭确认框仍按下即关(它的失败原因画在开关
+ 下面、不会消失,比 toast 好一层,但框本身没收住,按「一轮一处」留给下一轮);以及 7.34 末尾列的
+ `features/company/` 日历 / 员工 / 组织 / 手册 / 频道各处。
+
+
## 发布 v0.2.0(2026-10-05)
用户要求「先发布最新版本到 GitHub,说明是基于 penguin harness 做的」。这一版是**源码版**:
@@ -2067,6 +2084,7 @@ v0.2.2」——它只加台账里 v0.2.2 那一节与两行表格,**跟本轮
| 2026-10-23 | 用户点单(图片上限·输入侧) | **这一轮输入自己就超上限时也裁**(接手 13:20 那笔留在工作区里的续做(+27 −13):`packages/core/src/llm/generative-model.ts` 的 `fitReplayedImages` 先按上限裁**输入**、把要送出的那条消息交回 `streamGenerate`(不再原地改调用方对象),历史再从剩余额度里分;`capHistoryImages` 加第三参 `limit`,占位写的是卖家上限而不是剩余额度(默认等于 `budget`,纯函数行为不变);`core/test/image-budget.test.ts` 的假客户端记下真正发出的消息,新增两条用例,并修掉 HEAD 上原有的两处 `TS2749`;changelog 一对加一节,`models.{zh,en}.md` 各补一句)**为什么是它**:一轮读五张图会被合并成同一条输入消息,而打断的一轮在会话继续时是作为新输入重送的 —— 只裁历史修不好用户碰上的那条 `400 media_count_exceeded`;待办里能一轮做完的条目仍然没有(2.2c / 3.5 / 3.6 / 4.1—4.3 / 5.6 / 5.10 各自卡在拍板、桌面壳或新凭证上) | 六包 `typecheck` **`EXIT=0`**(六个 `Done`;`gen:ifaces` 报 **`src/ifaces.json unchanged`(195 接口 / 589 类型)** —— 本笔不碰服务契约)· `npx oxlint` 改动面 **0 警告 0 错误**(2 文件)· 改动文件与 changelog / 两份文档 `prettier --check` 全绿 · `git diff --check` 干净 · 逐包 test **`EXIT=0`、0 失败**:core **69 通过文件 + 1 跳过 / 1420 通过 / 6 跳过**(13:20 那笔 1418 + 本笔 2 条)· ui **130 / 1053** · cli **38 / 561** · server **203 / 2961 通过 / 4 跳过** · web **264 / 3239 通过 / 2 跳过** · **反证**:`git stash push -- packages/core/src/llm/generative-model.ts`(只带这一个路径)→ 两条新用例 **2 failed**(`expected 5 to be 4`、占位写成 1),`git stash pop` 后 **10 passed** · 这一笔没有界面面,没有起服务 / 截图(改的是请求装配,由「真正发出的那条消息」的断言钉住);3003 / 3004 / 4000 / 7364 / 7369 一个没碰;数据没往 `~/.penguin` / `~/.adelie` 写 · 没有切版本号、没发 npm、没发安装包、没发发布汇总 | `20dde0d6` |
| 2026-10-23 | 7.33 | **文件面板的新建 / 重命名 / 删除被拒时,框留着、原因也留在框里**(不是移植:1 处源码 `packages/web/src/features/chat/workspace-browser.tsx` + 1 个新文件 `packages/web/e2e/files-action-refusal.spec.mjs`(3 条用例)+ 既有用例一处断言收窄 + 两句文案(`changedBeforeAction` 中英)+ changelog 一对,**无新依赖、不碰接口**):三处入口动作过去只把失败弹成 toast —— 框确实还开着,但原因六秒后自己消失、还浮在框上方;重命名与删除更糟,被拒时框里的确认按钮带的还是那次已经作废的版本标记,同一颗按钮只能换回同一句拒绝。**现在**:原因画在 `ConfirmModal` 的 `refusal` 槽里(既有的 `S.common.refused` 前缀),`file_changed` 被拒时重新读一次版本(读的过程中确认按钮灰着),重试就落在文件此刻的样子上;新建撞名时名字留在输入框里,重开框不带旧原因。**为什么是它**:第一百一十六轮末尾排下来的同形写入第一条 | 六包 `typecheck` **`EXIT=0`**(六个 `Done`;`gen:ifaces` 报 `src/ifaces.json unchanged`(195 接口 / 589 类型))· `npx oxlint` 改动面 **0 警告 0 错误** · 改动五个文件 `prettier --check` 干净 · `git diff --check` 干净 · 逐包 test **`EXIT=0`、0 失败**:ui **130 / 1053** · core **69 通过文件 + 1 跳过 / 1420 通过 / 6 跳过** · cli **38 / 561** · server **203 / 2961 通过 / 4 跳过** · web **264 / 3239 通过 / 2 跳过**(与上一轮同,本笔是界面行为,改由 e2e 钉住)· **真服务 + 真浏览器整套 e2e**(`SKIP_BUILD=1 SRV_PORT=8993 MOCK_PORT=8994`,脚本自己的 `mktemp` 根):**139 passed(8.4m)、0 failed**(上一轮 136 + 本笔 3)· **反证**:`git stash push --` 只带那一个源码文件并重建 web → 同一份 spec **3 failed**(三条都死在框里找不到「操作被拒绝」),`git stash pop` + 重建后 **3 passed** · **两态实测真看一眼**(一次性数据根、`localhost:8981`、`r118probe`、mock 8982、1280×900,两处写由 `page.route` 拒成 500 / 409):新建框里是「操作被拒绝:README.md 已存在,未做改动。」且名字仍在输入框;重命名框里是「操作被拒绝:workspace is read-only」,磁盘上那条没动、`archive/` 没出现,6.5 秒后框内文字逐字相同;删除框里是「操作被拒绝:notes.md 在你决定期间被改写…已按它现在的版本重新读取,可以直接重试。」,通知区 **0** 个按钮、确认按钮在重读后恢复可点,文件仍在;console 只有刻意造的 409 / 500 与一条 `GET …/machines` 的 403(老现象),**无 pageerror**;截图 `r118/shots/{1-tree,2-create-refused,3-rename-refused,4-rename-refused-after-6s,5-delete-refused}.png`、探针 `r118/probe.spec.mjs` 与 `r118/one.sh` 在 scratchpad · 端口只用 e2e 的 8993 / 8994 与探针的 8981 / 8982(跑完都已停),3003 / 3004 / 4000 / 7364 / 7369 一个没碰;数据只落在 `mktemp` 根,没往 `~/.penguin` / `~/.adelie` 里写(`packages/*/dist`、`test-results/` 未 `git add`)· 没有切版本号、没发 npm、没发安装包、没发发布汇总 | `eb9dd76a` |
| 2026-10-23 | 7.34 | **项目设置的「删除项目」被拒时,框留着、原因也留在框里**(不是移植:1 处源码 `components/layout/project-dialogs.tsx`(`GeneralSection` 的 `doDelete`)+ 1 个新文件 `packages/web/e2e/project-delete-refusal.spec.mjs`(2 条用例)+ changelog 一对,**无新依赖、不碰接口、无新文案**):`doDelete` 过去把失败弹成 toast 就返回 —— 框还开着(什么都没删掉,项目在服务端也还在),但原因落在那条六秒后自己消失、还浮在框外面的通知里,六秒之后屏幕上一行字都不剩,只剩同一个问题和一颗没有解释的按钮。**现在**:只有删除落地才关框(`setConfirmDelete(false)` 挪到写入之后,设置对话框照旧跟着关),被拒时服务端原话画在 `ConfirmModal` 的 `refusal` 槽里(`S.common.refused` 前缀)、重开框先清旧原因;另加 `deleteBusy`,删除在途时连点第二下不再发第二个 DELETE(那一下只会换回 404,落在正在关的框上方)。**为什么是它**:第一百一十八轮末尾排下来的同形写入第一条 | 六包 `typecheck` **`EXIT=0`**(六个;`gen:ifaces` 报 `src/ifaces.json unchanged`(195 接口 / 589 类型))· `npx oxlint` 改动面 **0 警告 0 错误** · 改动四个文件 `prettier --check` 干净 · `git diff --check` 干净 · 逐包 test **`EXIT=0`、0 失败**:ui **130 / 1053** · core **69 通过文件 + 1 跳过 / 1420 通过 / 6 跳过** · cli **38 / 561** · web **264 / 3239 通过 / 2 跳过** · server **203 / 2961 通过 / 4 跳过**(与上一轮同:界面行为由 e2e 钉住)· **真服务 + 真浏览器整套 e2e**(`SKIP_BUILD=1 SRV_PORT=8997 MOCK_PORT=8998`,脚本自己的 `mktemp` 根):**141 passed(8.9m)、0 failed**(上一轮 139 + 本笔 2)· **反证**:`git stash push --` 只带那一个源码文件并重建 web → 同一份 spec **2 failed**(都死在框里找不到 `project store is locked`),`git stash pop` + 重建后 **2 passed(7.1s)** · **两态实测真看一眼**(一次性数据根 `/root/adelie-fork-data/r119-a`、`localhost:8996`、mock 8995、1280×900,删除由 `page.route` 拒成 500):**旧**代码 `reasonInCard 0`、框内文字与打开时逐字相同、通知区一条 `project store is locked`(1 个可点按钮),6.5 秒后通知区**空了**而框与项目都还在;**新**代码 `reasonInCard 1`,框里是「确认删除该项目?项目目录将被递归删除,不可恢复。/操作被拒绝:project store is locked」,通知区 **0** 个按钮,6.5 秒后逐字相同,重开 `reasonInCard 0`,放行重试后框 0 / 设置对话框 0 / 项目已不在服务端;console 只有刻意造的那一次 500 与三条 `GET …/machines` 的 403(老现象),**无 pageerror**;截图 `r119/{before,after}-{1-settings,2-card,3-refused,4-after-6s,5-written}.png`、读数 `r119/{before,after}.json`、探针 `r119/probe.spec.mjs` 在 scratchpad(临时 `pw-probe.config.mjs` 跑完即删,均未 `git add`)· 端口只用探针的 8995 / 8996 与 e2e 的 8997 / 8998(跑完都已停),3003 / 3004 / 4000 / 7364 / 7369 一个没碰;数据只落在 `mktemp` 根与 `/root/adelie-fork-data/r119-a`,没往 `~/.penguin` / `~/.adelie` 里写(`packages/*/dist`、`test-results/` 未 `git add`)· 没有切版本号、没发 npm、没发安装包、没发发布汇总 | `0267e0fe` |
+| 2026-10-24 | 7.35 | **智能体 API 页那三张确认框(关闭 API 访问 / 允许无密钥访问 / 删除密钥)被拒时,框留着,原因也留在框里**(不是移植:1 处源码 `packages/web/src/features/agents/api-tab.tsx` + 1 个新文件 `packages/web/e2e/agent-api-refusal.spec.mjs`(3 条用例)+ 既有单测 `test/agent-api-tab.test.ts` 跟上(19 条,含三条新的)+ changelog 一对,**无新依赖、不碰接口、无新文案**):三张框的 `onConfirm` 过去都是先 `onClose()` 再发请求 —— 被拒时页面上与服务端上什么都没变(开关照旧开着、那一行密钥照旧在),原因却落进一条六秒后自己消失、还浮在框上方的 toast 里。**现在**:三张框都留到自己的写入落地才由这一页关掉;被拒时服务端原话交给各自的状态(`offRefusal` / `keylessRefusal` / `deleteRefusal`),经 `ConfirmModal` 的 `refusal` 槽画在句子下面,重试就是同一个按钮;写入在途时框上两个按钮置灰;三个入口先开框再清上一次的原因;删除密钥的失败从 `toastError` 改成 `onRefused`。没有自己那张框的控件(打开 API、审批模式、关掉无密钥)照旧弹 toast | 六包 `typecheck` **`EXIT=0`**(六个 `Done`;`gen:ifaces` 报 **`src/ifaces.json unchanged`**,195 接口 / 589 类型 —— 本笔不动服务契约)· `npx oxlint` 改动面 **0 警告 0 错误** · 改动五个文件 `prettier --check` 干净 · `git diff --check` 干净 · 逐包 test **`EXIT=0`、0 失败**:core **69 通过文件 + 1 跳过 / 1420 通过 / 6 跳过** · ui **130 / 1053** · cli **38 / 561** · web **264 文件 / 3242 通过 / 2 跳过**(上一轮 3239,**+3 正是本笔新用例**)· server **203 / 2961 通过 / 4 跳过** · hmr 无测试文件 · **真服务 + 真浏览器整套 e2e**(`SKIP_BUILD=1 SRV_PORT=8999 MOCK_PORT=9000 pnpm -C packages/web test:e2e`,脚本自己的 `mktemp` 数据根、mock 9000 / 服务端 8999):**144 passed(8.9m)、0 failed**(上一轮 141 + 本笔 3)· **反证**:`git stash push -- packages/web/src/features/agents/api-tab.tsx`(只带这一个路径)并重建 web → 同一份 spec **3 failed**(三条都死在框里找不到 `agent api is read-only`,16.6 s / 16.5 s / 16.6 s);`git stash pop` + 重建 → **3 passed(7.3s)** · **两态实测**(一次性数据根 `/root/adelie-fork-data/r120-look`、`localhost:9001`、mock 9002、`admin`,两个写入都由 `page.route` 拒成 500):**旧代码** 删密钥被拒后 `cardOpen false`、`reasonInCard false`、通知区 **1** 个可点按钮,**6.5 秒后**通知区 0 个按钮、`reasonOnScreen false`(屏幕上再没有一句解释);关 API 被拒后 `cardOpen false`、通知区 1 个按钮、开关仍 `true`。**新代码** 删密钥被拒后 `cardOpen true`、`reasonInCard true`、通知区 **0** 个按钮、6.5 秒后原因仍在框里;关 API 被拒后 `cardOpen true`、`reasonInCard true`、通知区 0 个按钮、开关仍 `aria-checked=true`、服务端仍 `enabled: true`。两态 console 只有刻意造的两次 500,**无 pageerror**,截图 `r120/shots/{old,new,new2}-*.png` · 端口只用 9001 / 9002(探针)、8997 / 8998(单 spec)与 8999 / 9000(整套 e2e),跑完都已停,3003 / 3004 / 4000 / 7364 / 7369 一个没碰;数据只落在 `mktemp` 根与 `/root/adelie-fork-data/r120-look`,一个字节没往 `~/.penguin` / `~/.adelie` 里写(`packages/*/dist`、`test-results/` 都是产物,未 `git add`)· 没有切版本号、没发 npm、没发安装包、没发发布汇总 | 见本行提交 |
> **2026-10-11 与另一条线的交汇(第三十七轮)**:定时任务触发时(07:00)`git status --short` **不干净**
> —— 另一条线(会话 `session-2026-10-05-20-32-50-2ee69aba`)正在做**用户点单**的「回复能复制成纯文本」
@@ -14817,3 +14835,82 @@ changelog、没有台账。
(active / 7364 在听 / `GET /` 200 / `/api/version` 报 0.5.5)留给下一轮巡台开工时做。
- 桌面端 macOS 未签名,照旧不随 Release 发布。
- `changelog/unreleased/` 没有按 `changelog/README.md` 改名成版本目录 —— 本仓 v0.3.x 起一直如此。
+
+## 第一百二十轮:智能体 API 页那三张确认框被拒时,框留着、原因也留在框里(2026-10-24,条目 7.35)
+
+### 为什么是这一条
+
+待办里能一轮做完的条目仍然没有(2.2c 只剩桌面壳一侧、3.5 / 5.6 / 5.10 要拍板、3.6 要模型 key、
+4.1—4.3 明令不动),所以接着 7.34 末尾排下的那条扫描线往下做 —— 它点名的下一处正是
+`features/agents/api-tab.tsx`。开工时这棵树是干净的(`git status --short` 空),
+`git fetch origin && git merge --ff-only origin/main` 报 `Already up to date.`,主线尖端是
+`ce471b16`(v0.5.5 那一轮的台账补记)。
+
+这一处是同一种病,而且三处一起犯:API 页上「关闭 API 访问」「允许无密钥访问」「删除密钥」三张确认框的
+`onConfirm` 都是**先** `onClose()` **再**发请求。被拒的时候页面上与服务端上什么都没变(开关照旧开着、那一行
+密钥照旧在),原因却落进一条六秒后自己消失、还浮在框上方的 toast 里 —— 六秒之后屏幕上没有任何一句说明。
+删除密钥那处连框都不留(`onClose()` 在 `deleteKey()` 之前),只能靠那条 toast。
+
+### 改了什么(1 处源码 + 1 个新 spec + 既有单测跟上 + 一对 changelog)
+
+- `packages/web/src/features/agents/api-tab.tsx`:
+ - 三张框的 `onConfirm` 不再调 `onClose()`,只报「开始写了」(`onWriting`)并把结果交回去;**关框搬回这一页**,
+ 且只在写入落地那一条路径上关。`AgentApiOffConfirm` / `KeylessOnConfirm` / `DeleteKeyConfirm` 各多两个
+ prop:`busy`(写入在途时两个按钮置灰)与 `refusal`(画进 `ConfirmModal` 的 `refusal` 槽)。
+ - `DeleteKeyConfirm` 的失败分支从 `toastError` 改成回调 `onRefused(apiErrorText(error))`:原话交给这一页,
+ 由它画进框里。
+ - 这一页新增三个拒绝原因状态(`offRefusal` / `keylessRefusal` / `deleteRefusal`),都经 `S.common.refused`
+ 画出来(既有前缀,无新文案);三个入口(API 开关、无密钥开关、行上的删除按钮)在打开框时先清掉各自的上一次
+ 原因 —— 那句话属于上次那次尝试。
+ - 没有自己那张框的控件(打开 API、审批模式、关掉无密钥)不动:仍用 toast,开关也停在服务端持有的值上。
+ - 文件头的模块注释补一句「这三张框只在写入落地时才关」。
+- `packages/web/e2e/agent-api-refusal.spec.mjs`(新,3 条):
+ ① 删除密钥被 `page.route` 拒成 500 → 框、框里那句话与那一行密钥都还在(通知区 0 个可点的按钮),取消后重开
+ 不带旧原因;放行重试 → 框关、那一行没了、服务端的表里也没了。
+ ② 关闭 API 被拒 → 框留着、开关仍是 `aria-checked=true`、服务端仍是 `enabled: true`,密钥段照旧在;重试放行
+ → 框关、开关翻到 false、服务端 `enabled: false`,这一次的请求体逐字是 `{"enabled":false}`。
+ ③ 允许无密钥访问被拒 → 框留着、`open` 仍是 false;重试放行 → 框关、服务端 `open: true`、请求体 `{"open":true}`。
+ 三条都先把 API 打开、把上一次运行留下的密钥删干净再种一把自己的,单跑一条也成立。
+- `packages/web/test/agent-api-tab.test.ts`:19 条(+3)。既有那两条「拒绝时说为什么」改成新的契约(原因交给
+ `onRefused`,一条 toast 都不弹),并新增「answered yes 时不先关框」「被拒时 `refusal` 原样交给卡片」两条。
+- changelog 一对 `changelog/unreleased/2026-10-24-agent-api-refusal{,.zh}.md`。
+
+### 验证(都不是推测)
+
+- 六包 `typecheck` **`EXIT=0`**(core / server / web / ui / cli / hmr 六个 `Done`;`gen:ifaces` 报
+ `src/ifaces.json unchanged`(195 接口 / 589 类型)—— 本笔不动服务契约)。
+- `npx oxlint` 改动面(源码 + 新 spec + 单测)**0 警告 0 错误**;改动五个文件 `prettier --check` 干净;
+ `git diff --check` 干净。
+- 逐包 test **`EXIT=0`、0 失败**:core **69 通过文件 + 1 跳过 / 1420 通过 / 6 跳过** · ui **130 / 1053** ·
+ cli **38 / 561** · web **264 文件 / 3242 通过 / 2 跳过**(上一轮 3239,**+3 正是本笔新用例**)·
+ server **203 / 2961 通过 / 4 跳过** · hmr 无测试文件。
+- **真服务 + 真浏览器整套 e2e**(`SKIP_BUILD=1 SRV_PORT=8999 MOCK_PORT=9000 pnpm -C packages/web test:e2e`,
+ 脚本自己的 `mktemp` 数据根、mock 9000 / 服务端 8999):**144 passed(8.9m)、0 failed**(上一轮 141 + 本笔 3)。
+- **反证(旧行为)**:`git stash push -- packages/web/src/features/agents/api-tab.tsx`(只带这一个路径)并重建
+ web → 同一份 spec **3 failed**,三条都死在「框里找不到 `agent api is read-only`」(16.6 s / 16.5 s / 16.6 s);
+ `git stash pop` + 重建后 **3 passed(7.3s)**。
+- **两态实测真看一眼**(一次性数据根 `/root/adelie-fork-data/r120-look`、`localhost:9001`、mock 9002、
+ 1280×900、`admin`;两个写入都由 `page.route` 拒成 500,`agent_api_read_only` / `agent api is read-only`):
+ - **旧代码**:删密钥被拒后 `cardOpen false`、`reasonInCard false`、通知区 **1** 个可点按钮(文字正是那句
+ 拒绝)、密钥在页面上与服务端上都还在;**6.5 秒后**通知区 **0** 个按钮、`reasonOnScreen false` ——
+ 屏幕上再没有一句解释。关 API 被拒同理:`cardOpen false`、通知区 1 个按钮、开关仍 `true`。
+ - **新代码**:删密钥被拒后 `cardOpen true`、`reasonInCard true`、通知区 **0** 个按钮,**6.5 秒后**那句原因
+ 仍在框里;关 API 被拒后 `cardOpen true`、`reasonInCard true`、通知区 0 个按钮、开关仍 `aria-checked=true`、
+ 服务端仍 `enabled: true`。
+ - `console` 只有刻意造的两次 500(及其资源加载错误),**无 pageerror**;截图
+ `r120/shots/{old,new,new2}-*.png`、两次读数(`old` / `new` / `new2`)与探针 `r120/probe.mjs`、
+ 单 spec 脚本 `r120/run-one.sh` 在 scratchpad(探针靠一个软链的 `node_modules` 跑,未 `git add`)。
+- 端口只用 9001 / 9002(探针)、8997 / 8998(单 spec)与 8999 / 9000(整套 e2e),跑完都已停;
+ 3003 / 3004 / 4000 / 7364 / 7369 一个没碰;数据只落在 `mktemp` 根与 `/root/adelie-fork-data/r120-look`,
+ 一个字节没往 `~/.penguin` / `~/.adelie` 里写(`packages/*/dist`、`packages/web/test-results/` 都是产物,未
+ `git add`)。
+- 没有切版本号、没发 npm、没发安装包、没发汇总。
+
+### 没做 / 还差什么
+
+- `features/settings/agent-api-section.tsx` 里**管理员那一侧**的「关闭 API」确认框仍按下即关(`onConfirm` 先
+ `onClose()` 再写):它的失败原因画在开关下面、不会自己消失,比 toast 好一层,但框本身没收住 —— 按「一轮一处」
+ 留给下一轮。
+- 7.34 末尾列的 `features/company/` 日历 / 员工 / 组织 / 手册 / 频道各处照旧。
+- 待办里能一轮做完的条目仍然没有(2.2c 只剩桌面壳一侧、3.5 / 5.6 / 5.10 拍板、3.6 模型 key、
+ 4.1—4.3 明令不动)。
diff --git a/packages/web/e2e/agent-api-refusal.spec.mjs b/packages/web/e2e/agent-api-refusal.spec.mjs
new file mode 100644
index 00000000..b4148b3b
--- /dev/null
+++ b/packages/web/e2e/agent-api-refusal.spec.mjs
@@ -0,0 +1,227 @@
+/**
+ * Regression: the three questions the Agent's own API tab asks — turn the API off, allow keyless
+ * access, delete a key — close only once their write landed, and one the server refused keeps the
+ * card with the reason inside it instead of closing on the way out of the request.
+ *
+ * All three used to close first and write second: when the write came back refused, the page and
+ * the server were exactly as they had been (the switch on, the key still listed), yet the reason
+ * arrived as a toast that dismissed itself after six seconds and sat above the card. The cards now
+ * stay until the write lands, and a refusal is drawn under the sentence they asked with
+ * (`ConfirmModal`'s `refusal` slot), so the retry is the same button.
+ *
+ * Every write is the page's own — refused at `page.route` — and every check reads the server
+ * through the API, so both halves of the contract are covered.
+ */
+import { test, expect } from "@playwright/test";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const MOCK = process.env.MOCK_URL;
+const P = "password123";
+const AGENT = "default_agent";
+
+/** The key under test; the tab lists it by name and by its prefix alone. */
+const KEY = "PROBE_API_KEY";
+
+/** The refusal both writes answer with: its own words prove the reason came back into the card. */
+const REFUSAL = { code: "agent_api_read_only", message: "agent api is read-only" };
+
+const apiUrl = (projectId) => `${BASE}/api/projects/${projectId}/agents/${AGENT}/api`;
+
+/**
+ * Provision the user, give the Project a model (the onboarding overlay covers the page without
+ * one), and open the Agent's API with one key on it. The writes are absolute — `enabled` on, and
+ * any earlier run's keys dropped — so rerunning this file alone on one data root stays clean.
+ */
+async function projectWithApi(page, user) {
+ await provisionAndLogin(page.request, user, P);
+ const projectId = (await (await page.request.get(`${BASE}/api/projects`)).json()).projects[0]
+ .projectId;
+ const models = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {
+ data: {
+ defaultModel: { provider: "custom", modelId: "claude-4-8" },
+ models: [
+ {
+ provider: "custom",
+ modelId: "claude-4-8",
+ apiKey: "sk-mock",
+ baseUrl: MOCK,
+ contextWindow: 200000,
+ },
+ ],
+ },
+ });
+ expect(models.ok(), "put models").toBeTruthy();
+
+ const enabled = await page.request.put(apiUrl(projectId), {
+ data: { enabled: true, open: false },
+ });
+ expect(enabled.ok(), "open the API").toBeTruthy();
+ for (const record of (await enabled.json()).api.keys) {
+ await page.request.delete(`${apiUrl(projectId)}/keys/${record.keyId}`);
+ }
+ const minted = await page.request.post(`${apiUrl(projectId)}/keys`, { data: { name: KEY } });
+ expect(minted.ok(), "mint a key").toBeTruthy();
+
+ /** The Agent's API as the server holds it: what the tab reads and writes back. */
+ const stored = async () => (await (await page.request.get(apiUrl(projectId))).json()).api;
+ return { projectId, stored };
+}
+
+/**
+ * Take over one write: every request of that method is kept in `seen`, and while `state.refuse`
+ * is set it is answered with the server's refusal instead of reaching the real route.
+ */
+async function interceptWrite(page, pattern, method, state) {
+ await page.route(pattern, async (route) => {
+ if (route.request().method() !== method) return route.fallback();
+ state.seen.push(route.request().postData() ?? "");
+ if (!state.refuse) return route.fallback();
+ await route.fulfill({
+ status: 500,
+ contentType: "application/json",
+ body: JSON.stringify({ error: REFUSAL }),
+ });
+ });
+}
+
+/** The key's row: the only place the page writes the probe's name. */
+const keyRow = (page) => page.locator('[data-testid="api-key"]', { hasText: KEY });
+
+/** The card's own text with the refusal line dropped — the only thing a refusal may change. */
+async function cardText(card) {
+ return (await card.innerText()).replace(/\n操作被拒绝:[^\n]*/, "");
+}
+
+/** The notification region: a refusal must not be announced there (that is the old toast). */
+const notifications = (page) => page.getByRole("region", { name: "通知" });
+
+test("a refused key delete keeps the card, its sentence and the key", async ({ page }) => {
+ const { stored } = await projectWithApi(page, "r120key");
+ expect((await stored()).keys.map((k) => k.name)).toContain(KEY);
+
+ const state = { seen: [], refuse: true };
+ await interceptWrite(page, "**/api/projects/*/agents/*/api/keys/*", "DELETE", state);
+
+ await page.goto(`/agents/${AGENT}?tab=api`);
+ await expect(keyRow(page)).toBeVisible();
+ await keyRow(page)
+ .getByRole("button", { name: `删除密钥 ${KEY}` })
+ .click();
+ const dialog = page.getByRole("dialog", { name: "删除密钥" });
+ await expect(dialog).toBeVisible();
+ const sentence = await cardText(dialog);
+ expect(sentence).toContain(KEY);
+
+ await dialog.getByRole("button", { name: "删除", exact: true }).click();
+
+ // The reason is in the card that asked, and it is not a toast.
+ await expect(dialog.getByText(REFUSAL.message)).toBeVisible();
+ await expect(notifications(page).getByRole("button")).toHaveCount(0);
+ expect(state.seen).toHaveLength(1);
+ await expect(dialog).toBeVisible();
+ expect(await cardText(dialog)).toBe(sentence);
+
+ // Nothing was removed anywhere: the row is still on the page and still in the server's list.
+ await expect(keyRow(page)).toBeVisible();
+ expect((await stored()).keys.map((k) => k.name)).toContain(KEY);
+
+ // Closing the card decides nothing, and opening it again does not carry the old reason over.
+ await dialog.getByRole("button", { name: "取消" }).click();
+ await expect(dialog).toHaveCount(0);
+ await keyRow(page)
+ .getByRole("button", { name: `删除密钥 ${KEY}` })
+ .click();
+ const reopened = page.getByRole("dialog", { name: "删除密钥" });
+ await expect(reopened).toBeVisible();
+ await expect(reopened.getByText(REFUSAL.message)).toHaveCount(0);
+
+ // The retry is the same card; this time the delete lands.
+ state.refuse = false;
+ await reopened.getByRole("button", { name: "删除", exact: true }).click();
+ await expect(reopened).toHaveCount(0);
+ expect(state.seen).toHaveLength(2);
+ await expect(keyRow(page)).toHaveCount(0);
+ expect((await stored()).keys.map((k) => k.name)).not.toContain(KEY);
+});
+
+test("a refused API-off keeps the card, its sentence and the API on", async ({ page }) => {
+ const { stored } = await projectWithApi(page, "r120off");
+ expect((await stored()).enabled).toBe(true);
+
+ const state = { seen: [], refuse: true };
+ await interceptWrite(page, "**/api/projects/*/agents/*/api", "PUT", state);
+
+ await page.goto(`/agents/${AGENT}?tab=api`);
+ const apiSwitch = page.getByRole("switch", { name: "开启 API 访问" });
+ await expect(apiSwitch).toHaveAttribute("aria-checked", "true");
+ await apiSwitch.click();
+ const dialog = page.getByRole("dialog", { name: "关闭 API 访问?" });
+ await expect(dialog).toBeVisible();
+ const sentence = await cardText(dialog);
+
+ await dialog.getByRole("button", { name: "关闭", exact: true }).click();
+
+ await expect(dialog.getByText(REFUSAL.message)).toBeVisible();
+ await expect(notifications(page).getByRole("button")).toHaveCount(0);
+ expect(state.seen).toHaveLength(1);
+ await expect(dialog).toBeVisible();
+ expect(await cardText(dialog)).toBe(sentence);
+
+ // The switch never flipped and the server still has the API on (keys and all).
+ await expect(apiSwitch).toHaveAttribute("aria-checked", "true");
+ expect((await stored()).enabled).toBe(true);
+ await expect(keyRow(page)).toBeVisible();
+
+ // Cancel, then ask again: no stale reason; this time the write lands and the card closes.
+ await dialog.getByRole("button", { name: "取消" }).click();
+ await expect(dialog).toHaveCount(0);
+ await apiSwitch.click();
+ const reopened = page.getByRole("dialog", { name: "关闭 API 访问?" });
+ await expect(reopened).toBeVisible();
+ await expect(reopened.getByText(REFUSAL.message)).toHaveCount(0);
+ state.refuse = false;
+ await reopened.getByRole("button", { name: "关闭", exact: true }).click();
+ await expect(reopened).toHaveCount(0);
+ expect(state.seen).toHaveLength(2);
+ expect(JSON.parse(state.seen[1])).toEqual({ enabled: false });
+ await expect(apiSwitch).toHaveAttribute("aria-checked", "false");
+ expect((await stored()).enabled).toBe(false);
+});
+
+test("a refused keyless switch keeps the card, its sentence and keyless access off", async ({
+ page,
+}) => {
+ const { stored } = await projectWithApi(page, "r120open");
+ expect((await stored()).open).toBe(false);
+
+ const state = { seen: [], refuse: true };
+ await interceptWrite(page, "**/api/projects/*/agents/*/api", "PUT", state);
+
+ await page.goto(`/agents/${AGENT}?tab=api`);
+ const openSwitch = page.getByRole("switch", { name: "允许无密钥访问" });
+ await expect(openSwitch).toHaveAttribute("aria-checked", "false");
+ await openSwitch.click();
+ const dialog = page.getByRole("dialog", { name: "允许无密钥访问?" });
+ await expect(dialog).toBeVisible();
+ const sentence = await cardText(dialog);
+
+ await dialog.getByRole("button", { name: "仍然开启" }).click();
+
+ await expect(dialog.getByText(REFUSAL.message)).toBeVisible();
+ await expect(notifications(page).getByRole("button")).toHaveCount(0);
+ expect(state.seen).toHaveLength(1);
+ await expect(dialog).toBeVisible();
+ expect(await cardText(dialog)).toBe(sentence);
+ await expect(openSwitch).toHaveAttribute("aria-checked", "false");
+ expect((await stored()).open).toBe(false);
+
+ // The retry on the same card lands: it closes, and the server holds keyless access on.
+ state.refuse = false;
+ await dialog.getByRole("button", { name: "仍然开启" }).click();
+ await expect(dialog).toHaveCount(0);
+ expect(state.seen).toHaveLength(2);
+ expect(JSON.parse(state.seen[1])).toEqual({ open: true });
+ await expect(openSwitch).toHaveAttribute("aria-checked", "true");
+ expect((await stored()).open).toBe(true);
+});
diff --git a/packages/web/src/features/agents/api-tab.tsx b/packages/web/src/features/agents/api-tab.tsx
index 3970675f..7a0b273d 100644
--- a/packages/web/src/features/agents/api-tab.tsx
+++ b/packages/web/src/features/agents/api-tab.tsx
@@ -7,9 +7,11 @@
* synced Project file — so the Agent can neither expose itself nor loosen its own approvals. Any
* member reads it; only the Project owner changes it. Each control applies on the flip, with no
* Save: turning the API on writes at once, while turning it off and deleting a key ask first,
- * because a program using them is refused from then on. A new key's secret exists only in the
- * create response: it is shown once, in a panel with its copy button, until Done, and afterwards
- * the list names the key by its prefix alone.
+ * because a program using them is refused from then on. Those three questions close only once
+ * their write landed; one the server refused keeps the card open with the reason drawn inside it,
+ * so the retry is the button that was just pressed rather than a toast that has already left. A
+ * new key's secret exists only in the create response: it is shown once, in a panel with its copy
+ * button, until Done, and afterwards the list names the key by its prefix alone.
*
* The admin's server-wide switch (Settings › Server › Agent API) overrides every Agent: when it is
* off the switch here is disabled and says so, and nothing is lost. The tab's own read carries that
@@ -96,7 +98,7 @@ const switchOnKeyless = (projectId: string, agentId: string): Promise<AgentApiRe
* The warning before keyless access goes on, in the danger tone: once it is on, anything that
* can reach the server talks to the Agent on the Project's models and credentials. Answered yes,
* it says the write began, writes the switch on and hands on the outcome. Turning it off needs
- * no question.
+ * no question. The card stays until the write lands — a refusal is drawn inside it.
*/
export function KeylessOnConfirm({
open,
@@ -105,6 +107,8 @@ export function KeylessOnConfirm({
onClose,
onWriting,
onSettled,
+ busy,
+ refusal,
}: {
open: boolean;
projectId: string;
@@ -112,14 +116,17 @@ export function KeylessOnConfirm({
onClose: () => void;
onWriting: () => void;
onSettled: (outcome: AgentApiResponse | { error: unknown }) => void;
+ busy: boolean;
+ refusal?: string;
}) {
return (
<ConfirmModal
open={open}
title={S.agent.apiOpenTitle}
onClose={onClose}
+ busy={busy}
+ {...(refusal !== undefined ? { refusal } : {})}
onConfirm={() => {
- onClose();
onWriting();
switchOnKeyless(projectId, agentId).then(
(res) => onSettled(res),
@@ -141,7 +148,7 @@ const deleteKey = (projectId: string, agentId: string, keyId: string): Promise<v
/**
* The question before the Agent's API goes off, in the danger tone. Answered yes, it says the
* write began, writes the switch off and hands on the outcome: what the server stored, or the
- * failure.
+ * failure. The card stays until the write lands — a refusal is drawn inside it.
*/
export function AgentApiOffConfirm({
open,
@@ -150,6 +157,8 @@ export function AgentApiOffConfirm({
onClose,
onWriting,
onSettled,
+ busy,
+ refusal,
}: {
open: boolean;
projectId: string;
@@ -157,14 +166,17 @@ export function AgentApiOffConfirm({
onClose: () => void;
onWriting: () => void;
onSettled: (outcome: AgentApiResponse | { error: unknown }) => void;
+ busy: boolean;
+ refusal?: string;
}) {
return (
<ConfirmModal
open={open}
title={S.agent.apiOffTitle}
onClose={onClose}
+ busy={busy}
+ {...(refusal !== undefined ? { refusal } : {})}
onConfirm={() => {
- onClose();
onWriting();
switchOffAgentApi(projectId, agentId).then(
(res) => onSettled(res),
@@ -180,34 +192,46 @@ export function AgentApiOffConfirm({
}
/**
- * The question before a key is deleted, naming it, in the danger tone. Answered yes, it deletes
- * the key and hands on which one went; a refused delete says why and hands on nothing.
+ * The question before a key is deleted, naming it, in the danger tone. Answered yes, it says the
+ * write began, deletes the key and hands on which one went; a refused delete keeps the card —
+ * with the reason inside it — and hands on the server's words instead, because the key is still
+ * there and retrying is the same button.
*/
export function DeleteKeyConfirm({
record,
projectId,
agentId,
onClose,
+ onWriting,
onDeleted,
+ onRefused,
+ busy,
+ refusal,
}: {
/** The key in question; null keeps the dialog closed. */
record: AgentApiKeyInfo | null;
projectId: string;
agentId: string;
onClose: () => void;
+ onWriting: () => void;
onDeleted: (keyId: string) => void;
+ onRefused: (reason: string) => void;
+ busy: boolean;
+ refusal?: string;
}) {
return (
<ConfirmModal
open={record !== null}
title={S.agent.apiDeleteKey}
onClose={onClose}
+ busy={busy}
+ {...(refusal !== undefined ? { refusal } : {})}
onConfirm={() => {
if (record === null) return;
- onClose();
+ onWriting();
deleteKey(projectId, agentId, record.keyId).then(
() => onDeleted(record.keyId),
- (error: unknown) => toastError(apiErrorText(error)),
+ (error: unknown) => onRefused(apiErrorText(error)),
);
}}
confirmLabel={S.common.delete}
@@ -467,13 +491,20 @@ export function ApiTab({
}) {
const { reloadAgents } = useProject();
const [settings, setSettings] = useState<AgentApiSettings | null>(null);
- // Only the initial load failure renders inline; writes report via toast.
+ // Only the initial load failure renders inline; a write with no question of its own (turning the
+ // API on, the approval mode, keyless off) reports via toast; a write asked for in a card reports
+ // inside that card (the three refusals below).
const [loadError, setLoadError] = useState<string | null>(null);
const [serverEnabled, setServerEnabled] = useState(true);
const [busy, setBusy] = useState(false);
const [confirmOff, setConfirmOff] = useState(false);
const [confirmKeyless, setConfirmKeyless] = useState(false);
const [deleting, setDeleting] = useState<AgentApiKeyInfo | null>(null);
+ // The server's words for a write the card asked for and it refused, drawn inside that card: the
+ // reason has to outlive the six-second toast, because retrying is the next thing the user does.
+ const [offRefusal, setOffRefusal] = useState<string | null>(null);
+ const [keylessRefusal, setKeylessRefusal] = useState<string | null>(null);
+ const [deleteRefusal, setDeleteRefusal] = useState<string | null>(null);
const [draftName, setDraftName] = useState<string | null>(null);
const [draftError, setDraftError] = useState<string | undefined>(undefined);
const [secret, setSecret] = useState<string | null>(null);
@@ -555,12 +586,19 @@ export function ApiTab({
secret={secret}
onToggleEnabled={(next) => {
if (next) void write({ enabled: true });
- else setConfirmOff(true);
+ else {
+ // Open first, then drop the previous refusal: that sentence belonged to the attempt
+ // before this one.
+ setConfirmOff(true);
+ setOffRefusal(null);
+ }
}}
onApprovalMode={(approvalMode) => void write({ approvalMode })}
onToggleOpen={(open) => {
- if (open) setConfirmKeyless(true);
- else void write({ open: false });
+ if (open) {
+ setConfirmKeyless(true);
+ setKeylessRefusal(null);
+ } else void write({ open: false });
}}
onStartKey={() => {
setDraftName("");
@@ -576,7 +614,10 @@ export function ApiTab({
setDraftError(undefined);
}}
onSecretDone={() => setSecret(null)}
- onDeleteKey={setDeleting}
+ onDeleteKey={(record) => {
+ setDeleting(record);
+ setDeleteRefusal(null);
+ }}
/>
<AgentApiOffConfirm
open={confirmOff}
@@ -584,12 +625,15 @@ export function ApiTab({
agentId={agentId}
onClose={() => setConfirmOff(false)}
onWriting={() => setBusy(true)}
+ busy={busy}
+ {...(offRefusal !== null ? { refusal: S.common.refused(offRefusal) } : {})}
onSettled={(outcome) => {
if ("api" in outcome) {
setSettings(outcome.api);
setServerEnabled(outcome.serverEnabled);
void reloadAgents();
- } else toastError(apiErrorText(outcome.error));
+ setConfirmOff(false);
+ } else setOffRefusal(apiErrorText(outcome.error));
setBusy(false);
}}
/>
@@ -599,11 +643,14 @@ export function ApiTab({
agentId={agentId}
onClose={() => setConfirmKeyless(false)}
onWriting={() => setBusy(true)}
+ busy={busy}
+ {...(keylessRefusal !== null ? { refusal: S.common.refused(keylessRefusal) } : {})}
onSettled={(outcome) => {
if ("api" in outcome) {
setSettings(outcome.api);
setServerEnabled(outcome.serverEnabled);
- } else toastError(apiErrorText(outcome.error));
+ setConfirmKeyless(false);
+ } else setKeylessRefusal(apiErrorText(outcome.error));
setBusy(false);
}}
/>
@@ -612,11 +659,20 @@ export function ApiTab({
projectId={projectId}
agentId={agentId}
onClose={() => setDeleting(null)}
- onDeleted={(keyId) =>
+ onWriting={() => setBusy(true)}
+ busy={busy}
+ {...(deleteRefusal !== null ? { refusal: S.common.refused(deleteRefusal) } : {})}
+ onDeleted={(keyId) => {
setSettings((prev) =>
prev === null ? prev : { ...prev, keys: prev.keys.filter((k) => k.keyId !== keyId) },
- )
- }
+ );
+ setDeleting(null);
+ setBusy(false);
+ }}
+ onRefused={(reason) => {
+ setDeleteRefusal(reason);
+ setBusy(false);
+ }}
/>
</>
);
diff --git a/packages/web/test/agent-api-tab.test.ts b/packages/web/test/agent-api-tab.test.ts
index 1512858b..697e9a56 100644
--- a/packages/web/test/agent-api-tab.test.ts
+++ b/packages/web/test/agent-api-tab.test.ts
@@ -18,7 +18,7 @@
* - Turning the API off asks first, in the danger tone. Answered yes, it writes the switch off
* and hands on what the server stored; a failed write is handed on as the failure.
* - Deleting a key asks first, naming it. Answered yes, it deletes that key and hands on its id;
- * a refused delete says why and hands on nothing.
+ * a refused delete hands the server's words on, so the card that asked can keep them.
* - The Agents list carries the plug mark, named for screen readers, only on an Agent whose API
* is on.
* - Turning the Agent API off server-wide asks first, in the danger tone; answered yes, it writes
@@ -121,6 +121,8 @@ type Confirm = ReactElement<{
confirmLabel: string;
children: ReactNode;
onConfirm: () => void;
+ /** The server's words for a write the card asked for and it refused (confirm-modal's slot). */
+ refusal?: string;
}>;
/** Every element of `type` in a tree of plain elements, its children followed. */
@@ -230,14 +232,15 @@ describe("the API tab", () => {
});
describe("turning an Agent's API off", () => {
- const confirm = (onSettled: (o: unknown) => void, onWriting = noop) =>
+ const confirm = (onSettled: (o: unknown) => void, onWriting = noop, onClose = noop) =>
AgentApiOffConfirm({
open: true,
projectId: "demo",
agentId: "coder",
- onClose: noop,
+ onClose,
onWriting,
onSettled,
+ busy: false,
}) as Confirm;
it("asks first in the danger tone; answered yes, writes it off and hands on what was stored", async () => {
@@ -264,17 +267,28 @@ describe("turning an Agent's API off", () => {
await vi.waitFor(() => expect(onSettled).toHaveBeenCalledOnce());
expect(onSettled.mock.calls[0]![0]).toHaveProperty("error");
});
+
+ it("leaves the card open: answering yes writes without closing it first", async () => {
+ stubFetch(() => apiError(403, "forbidden"));
+ const onClose = vi.fn();
+ const onSettled = vi.fn();
+ confirm(onSettled, noop, onClose).props.onConfirm();
+ await vi.waitFor(() => expect(onSettled).toHaveBeenCalledOnce());
+ // The page closes this card on the landing of the write, and keeps it on a refusal.
+ expect(onClose).not.toHaveBeenCalled();
+ });
});
describe("allowing keyless access", () => {
- const confirm = (onSettled: (o: unknown) => void, onWriting = noop) =>
+ const confirm = (onSettled: (o: unknown) => void, onWriting = noop, onClose = noop) =>
KeylessOnConfirm({
open: true,
projectId: "demo",
agentId: "coder",
- onClose: noop,
+ onClose,
onWriting,
onSettled,
+ busy: false,
}) as Confirm;
it("warns first in the danger tone; answered yes, writes it on and hands on what was stored", async () => {
@@ -301,19 +315,37 @@ describe("allowing keyless access", () => {
await vi.waitFor(() => expect(onSettled).toHaveBeenCalledOnce());
expect(onSettled.mock.calls[0]![0]).toHaveProperty("error");
});
+
+ it("leaves the card open: answering yes writes without closing it first", async () => {
+ stubFetch(() => apiError(403, "forbidden"));
+ const onClose = vi.fn();
+ const onSettled = vi.fn();
+ confirm(onSettled, noop, onClose).props.onConfirm();
+ await vi.waitFor(() => expect(onSettled).toHaveBeenCalledOnce());
+ expect(onClose).not.toHaveBeenCalled();
+ });
});
describe("deleting a key", () => {
- it("asks first, naming the key; answered yes, deletes it and hands on its id", async () => {
- const fetch = stubFetch(() => new Response(null, { status: 204 }));
- const onDeleted = vi.fn();
- const question = DeleteKeyConfirm({
+ const confirm = (handlers: {
+ onDeleted: (id: string) => void;
+ onRefused: (why: string) => void;
+ }) =>
+ DeleteKeyConfirm({
record: USED,
projectId: "demo",
agentId: "coder",
onClose: noop,
- onDeleted,
+ onWriting: noop,
+ onDeleted: handlers.onDeleted,
+ onRefused: handlers.onRefused,
+ busy: false,
}) as Confirm;
+
+ it("asks first, naming the key; answered yes, deletes it and hands on its id", async () => {
+ const fetch = stubFetch(() => new Response(null, { status: 204 }));
+ const onDeleted = vi.fn();
+ const question = confirm({ onDeleted, onRefused: vi.fn() });
expect(question.props.open).toBe(true);
expect(question.props.tone).toBeUndefined();
expect(renderToStaticMarkup(question.props.children as ReactElement)).toContain(
@@ -327,21 +359,45 @@ describe("deleting a key", () => {
]);
});
- it("says why a refused delete failed, and hands on nothing", async () => {
+ it("hands a refused delete's reason on, for the card to keep, and hands on no id", async () => {
stubFetch(() => apiError(404, "key_not_found", "No such key."));
const onDeleted = vi.fn();
+ const onRefused = vi.fn();
+ const onClose = vi.fn();
(
DeleteKeyConfirm({
record: USED,
projectId: "demo",
agentId: "coder",
- onClose: noop,
+ onClose,
+ onWriting: noop,
onDeleted,
+ onRefused,
+ busy: false,
}) as Confirm
).props.onConfirm();
- await vi.waitFor(() => expect(toasts).toHaveLength(1));
- expect(toasts[0]).toMatch(/^error: /);
+ await vi.waitFor(() => expect(onRefused).toHaveBeenCalledOnce());
+ // A refused delete leaves the card (and the key it named) where it was.
+ expect(onClose).not.toHaveBeenCalled();
+ // The server's own words, which the card wraps in S.common.refused — not a toast that leaves.
+ expect(onRefused.mock.calls[0]![0]).toContain("No such key.");
expect(onDeleted).not.toHaveBeenCalled();
+ expect(toasts).toEqual([]);
+ });
+
+ it("draws a refusal the page hands back inside the card, beside the button that retries it", () => {
+ const question = DeleteKeyConfirm({
+ record: USED,
+ projectId: "demo",
+ agentId: "coder",
+ onClose: noop,
+ onWriting: noop,
+ onDeleted: noop,
+ onRefused: noop,
+ busy: false,
+ refusal: S.common.refused("No such key."),
+ }) as Confirm;
+ expect(question.props.refusal).toBe(S.common.refused("No such key."));
});
});