Skip to content

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

fix(web): a refused terminal kill keeps its reason in the card that asked

lmliheng38c3eb52868b
diff --git a/changelog/unreleased/2026-11-13-terminal-kill-refusal.md b/changelog/unreleased/2026-11-13-terminal-kill-refusal.md
new file mode 100644
index 00000000..8a9ba024
--- /dev/null
+++ b/changelog/unreleased/2026-11-13-terminal-kill-refusal.md
@@ -0,0 +1,58 @@
+# Ending a terminal the server refused keeps its reason in the card that asked
+
+- **Date:** 2026-11-13
+- **Type:** fix
+- **Scope:** `web`
+- **Breaking:** no
+
+[中文版](2026-11-13-terminal-kill-refusal.zh.md)
+
+Both ways to end a shell — a dock tab's × and the terminal.close shortcut (⌃⌥` / Ctrl+Alt+`) in a
+standalone `/terminal` window — ask first in a confirmation card, because ending a shell cannot be
+undone. Both then ignored the answer: the kill was sent and forgotten (`void killTerminal(...)`),
+and that call neither read a non-2xx response nor reported a dropped connection. So a refused kill
+removed the tab, or closed the window, while the shell kept running on the server, and the screen
+said nothing at all — not even the six-second notification the other refusals used to get. The list
+also dropped the entry before the round trip and never gave it back.
+
+Now a kill the server refuses hands the entry back and says why inside the card that asked, in the
+shared `refusal` slot (`操作被拒绝:<reason>`): the tab stays in the strip (or the window stays open,
+because it is the only surface that shell is on), the server's own words are drawn under the
+card's sentence, and the card's own button is the retry. The tab leaves only once the kill landed.
+
+## Details
+
+- `packages/web/src/features/terminal/terminal-list.ts`: `killTerminal` sends the DELETE through
+ the app's API client instead of a bare `fetch`, so a non-2xx response becomes the usual
+ `ApiError` (its code localized like every other refusal) and a dead connection becomes
+ `network_error`; on either, the entry is put back, the pending-kill marker is dropped and the
+ list is re-read — a 404 for a shell that really is gone takes it away again, which is the outcome
+ the user asked for. The DELETE still addresses the machine that holds the pty.
+- `packages/web/src/features/dock/dock-panel.tsx`: the kill card keeps a `killRefusal`; the tab is
+ removed and the card closed only after the kill resolved. The reason is cleared when the card
+ opens and when it closes.
+- `packages/web/src/features/terminal/terminal-page.tsx`: the standalone window does the same, and
+ a refusal no longer closes the window over a shell that is still running.
+- The dictionary gains one code: `terminal_not_found` (the DELETE's own 404), in both languages.
+
+## Tests
+
+- `packages/web/test/terminal-kill-refusal.test.ts` (new, four cases, the node suite's one `fetch`
+ fake): a refused DELETE puts the entry back and rejects with the server's code; a dropped
+ connection is a `network_error` and does the same; a kill that landed leaves the entry out and
+ addresses the machine that holds the pty; a 200 with a body is not a failure.
+- `packages/web/e2e/terminal-kill-refusal.spec.mjs` (new, three cases, real server + the
+ repository's mock model + a real browser): the dock card keeps `terminal_not_found`'s sentence,
+ the tab and the live shell, with nothing left in the notification region and everything still
+ there after seven seconds — then the same button retries and the kill lands (204), the tab leaves
+ and the shell is gone; a card closed with Escape after a refusal leaves the next one clean; and
+ the standalone window keeps its own refusal (`internal`) on screen, still attached to the shell,
+ then ends it on the retry.
+- Run against the page as it was before the change (`HEAD`'s source, rebuilt): all three cases fail
+ on the card's missing `role="alert"`.
+
+## Compatibility
+
+No wire change, no new dependency, no Project config change. Every successful kill behaves exactly
+as before — the entry leaves the list immediately and the tab leaves once the server confirmed;
+what changes is a kill that never happened, which no longer looks like one that did.
diff --git a/changelog/unreleased/2026-11-13-terminal-kill-refusal.zh.md b/changelog/unreleased/2026-11-13-terminal-kill-refusal.zh.md
new file mode 100644
index 00000000..640cd240
--- /dev/null
+++ b/changelog/unreleased/2026-11-13-terminal-kill-refusal.zh.md
@@ -0,0 +1,46 @@
+# 结束终端被拒时,原因留在发问的那张卡片里
+
+- **日期:** 2026-11-13
+- **类型:** 修复
+- **范围:** `web`
+- **破坏性变更:** 否
+
+[English](2026-11-13-terminal-kill-refusal.md)
+
+结束一个 Shell 有两条路 —— 停靠栏里终端标签的 ×,以及独立 `/terminal` 窗口里的 terminal.close 快捷键
+(⌃⌥` / Ctrl+Alt+`)—— 两条都会先问一句,因为结束一个 Shell 无法撤销。可两条都不看答案:请求发出去就不管了
+(`void killTerminal(...)`),而那个函数既不读非 2xx 的回话、也不报连不上的连接。于是被拒的结束照样把标签摘掉、
+或者把窗口关掉,而 Shell 仍在服务端跑着,屏幕上**一个字都没有** —— 连别的拒绝以前至少还有的那条六秒通知都没有。
+列表同样在发请求之前就把条目删了,从不还回来。
+
+现在被拒的结束会把条目还回去,并在发问的那张卡片里说明原因(共享卡片的 `refusal` 槽,`操作被拒绝:<原因>`):
+标签留在停靠栏里(窗口也留着,因为它是这个 Shell 唯一被显示的地方),服务端自己的话画在卡片那句话下面,卡片的
+按钮就是重试。标签只在结束真的落地之后才离开。
+
+## 细节
+
+- `packages/web/src/features/terminal/terminal-list.ts`:`killTerminal` 的 DELETE 改走应用的 API 客户端,
+ 不再是裸 `fetch` —— 非 2xx 于是变成全应用同一个 `ApiError`(码按词典本地化),连不上变成 `network_error`;
+ 两种情况都把条目放回、清掉 `pendingKills` 里的记号、并重读一次列表 —— 对一个真的已经没了的 Shell,404 会让它
+ 再次消失,那正是用户要的结果。DELETE 仍然发给持有这个 pty 的那台机器。
+- `packages/web/src/features/dock/dock-panel.tsx`:结束卡片多一个 `killRefusal`;标签只在结束 resolve 之后才
+ 移除、卡片才关闭。这句话在卡片打开时与关闭时清掉。
+- `packages/web/src/features/terminal/terminal-page.tsx`:独立窗口同理,被拒时不再关窗 —— 那会把仍在跑的
+ Shell 藏起来。
+- 词典多一条码:`terminal_not_found`(DELETE 自己的 404),中英各一条。
+
+## 测试
+
+- `packages/web/test/terminal-kill-refusal.test.ts`(新增,四条,走 node 套件唯一的 `fetch` 假件):被拒的
+ DELETE 把条目放回并以服务端的码拒绝;连接断掉算 `network_error`,条目同样放回;真的落地的那次让条目留在外面,
+ 且发给持有 pty 的那台机器;200 带 body 不算失败。
+- `packages/web/e2e/terminal-kill-refusal.spec.mjs`(新增,三条,真服务端 + 仓库自带的 mock 模型 + 真浏览器):
+ 停靠栏的卡片留下 `terminal_not_found` 的那句话、标签与活着的 Shell,通知区什么都没有,七秒后仍在 —— 随后
+ 同一个按钮重试、结束落地(204),标签离开、Shell 也没了;被拒之后按 Escape 关掉,下一次打开的卡片是干净的;
+ 独立窗口同样把自己那条拒绝(`internal`)留在屏幕上、仍连着那个 Shell,重试后才结束它。
+- 拿改动前的页面(`HEAD` 的源码重新构建)跑同一份用例,三条都死在卡片里找不到 `role="alert"`。
+
+## 兼容性
+
+线上接口没变、没有新依赖、Project 配置没变。每一次成功的结束与以前一模一样(条目立刻离开列表,标签在服务端确认后
+离开);变的是「根本没发生的结束」—— 它不再看起来像发生了。
diff --git a/packages/web/e2e/terminal-kill-refusal.spec.mjs b/packages/web/e2e/terminal-kill-refusal.spec.mjs
new file mode 100644
index 00000000..86858a82
--- /dev/null
+++ b/packages/web/e2e/terminal-kill-refusal.spec.mjs
@@ -0,0 +1,220 @@
+/**
+ * Regression: ending a terminal can be REFUSED, and the card that asked is the one that says so.
+ *
+ * Both ways to end a shell — a dock tab's × and the standalone /terminal window's
+ * terminal.close shortcut — ask first in the same confirmation card, and both used to ignore the
+ * answer entirely (`void killTerminal(...)`, which swallowed a non-2xx as well as a dead
+ * connection): the tab left the strip, or the window closed, while the shell kept running, and
+ * nothing on screen said a word. Now the tab goes only once the kill landed, the card stays
+ * standing with the server's words inside it, and its own button is the retry.
+ *
+ * The refusal is the server's own shape — `{error:{code,message}}` — with the two codes a DELETE
+ * of a terminal really answers: `terminal_not_found` (this id's shell is already gone) in the
+ * dock, `internal` in the window, so both localized sentences are exercised.
+ */
+import { test, expect } from "@playwright/test";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const U = "killrefusaluser";
+const P = "password123";
+
+/** The card's title, which is also its accessible name. */
+const CARD = "关闭此终端?";
+/** The confirm button: the action's own verb. */
+const CONFIRM = "关闭此终端";
+/** The shared lead-in plus each code's own words. */
+const NOT_FOUND_REFUSED = "操作被拒绝:该终端已不存在或已被关闭。";
+const INTERNAL_REFUSED = "操作被拒绝:服务器内部错误,请稍后重试。";
+
+/** Live shells accumulate across reruns on one server; MAX 12/user would 429. */
+async function killAllTerminals(request) {
+ const { terminals } = await (await request.get(`${BASE}/api/terminals`)).json();
+ for (const t of terminals) await request.delete(`${BASE}/api/terminals/${t.id}`);
+ await expect
+ .poll(
+ async () => {
+ const res = await (await request.get(`${BASE}/api/terminals`)).json();
+ return res.terminals.filter((t) => t.alive).length;
+ },
+ { timeout: 10000 },
+ )
+ .toBe(0);
+}
+
+/** How many shells this user has alive right now. */
+async function aliveCount(request) {
+ const res = await (await request.get(`${BASE}/api/terminals`)).json();
+ return res.terminals.filter((t) => t.alive).length;
+}
+
+/** A Project without a model pops the onboarding overlay over the dock; configure the mock one. */
+async function configureProjectModel(request) {
+ const projectId = (await (await request.get(`${BASE}/api/projects`)).json()).projects[0]
+ .projectId;
+ const put = await 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: process.env.MOCK_URL,
+ contextWindow: 200000,
+ },
+ ],
+ },
+ });
+ expect(put.ok(), "put models").toBeTruthy();
+}
+
+/**
+ * Refuses the kill with `code`. Only DELETE is touched: the same path is also probed with GET
+ * (attach) and read as a list, and both have to keep working for the page to be usable.
+ */
+async function refuseKill(page, code) {
+ await page.route("**/api/terminals/**", (route) => {
+ if (route.request().method() !== "DELETE") return route.continue();
+ return route.fulfill({
+ status: code === "internal" ? 500 : 404,
+ contentType: "application/json",
+ body: JSON.stringify({ error: { code, message: "refused by the test" } }),
+ });
+ });
+}
+
+/** Lets the same path through again, so the card's button becomes a retry that lands. */
+async function allowKill(page) {
+ await page.unroute("**/api/terminals/**");
+}
+
+/**
+ * The terminal page draws its rows as text, so the screen is readable without pixels; "ready"
+ * only means the stream is attached, so a sentinel proves the shell is at a prompt (the tag is
+ * quote-split: the command's own echo never contains it).
+ */
+async function waitForShell(page, tag) {
+ await expect(page.locator('[data-testid="terminal-status"][data-status="ready"]')).toBeVisible({
+ timeout: 20000,
+ });
+ await page.click(".xterm-screen");
+ await page.keyboard.type(`echo ${tag.slice(0, 2)}''${tag.slice(2)}`);
+ await page.keyboard.press("Enter");
+ await expect
+ .poll(() => page.locator(".xterm-rows").innerText(), { timeout: 30000 })
+ .toMatch(new RegExp(`${tag}$`, "m"));
+}
+
+test("a dock tab's × keeps its refusal in the card, and the shell keeps running", async ({
+ page,
+}) => {
+ await provisionAndLogin(page.request, U, P);
+ await configureProjectModel(page.request);
+ await killAllTerminals(page.request);
+ await page.goto(`${BASE}/chat`);
+ await expect(page.locator("aside")).toBeVisible({ timeout: 20000 });
+
+ // Ctrl+` opens a shell in the bottom dock, like Codex / VS Code.
+ await page.keyboard.press("Control+Backquote");
+ const dock = page.locator('[data-testid="dock"][data-position="bottom"][data-open="true"]');
+ await expect(dock).toBeVisible({ timeout: 20000 });
+ const tab = dock.locator('[data-testid="dock-tab"][data-terminal-id]');
+ await expect(tab).toHaveCount(1);
+
+ const notices = page.getByRole("region", { name: "通知" });
+ await refuseKill(page, "terminal_not_found");
+
+ // The tab's × asks first; the answer to that question is a refusal.
+ await tab.getByTestId("dock-tab-close").click();
+ const card = page.getByRole("dialog", { name: CARD });
+ await expect(card).toBeVisible();
+ await card.getByRole("button", { name: CONFIRM }).click();
+
+ // The reason is drawn inside the card that asked, and nothing is left in the notification
+ // region (which is where it used to be — and only for six seconds).
+ await expect(card.getByRole("alert")).toHaveText(NOT_FOUND_REFUSED);
+ await expect(notices.getByRole("button")).toHaveCount(0);
+ // Six seconds is how long a toast lives: the card and its sentence have to outlive it.
+ await page.waitForTimeout(7_000);
+ await expect(card).toBeVisible();
+ await expect(card.getByRole("alert")).toHaveText(NOT_FOUND_REFUSED);
+ // Nothing was ended: the tab is still in the strip, and so is the shell.
+ await expect(tab).toHaveCount(1);
+ expect(await aliveCount(page.request), "the shell is still alive").toBe(1);
+
+ // The same button is the retry: with the server answering again, the kill lands, the tab
+ // leaves the strip and the shell is gone — the dock closes because its last tab went.
+ await allowKill(page);
+ const landed = page.waitForResponse(
+ (res) => res.request().method() === "DELETE" && res.url().includes("/api/terminals/"),
+ );
+ await card.getByRole("button", { name: CONFIRM }).click();
+ expect((await landed).status(), "the kill landed").toBe(204);
+ await expect(card).toHaveCount(0);
+ await expect(page.locator('[data-testid="dock"][data-open="true"]')).toHaveCount(0);
+ await expect.poll(() => aliveCount(page.request), { timeout: 10000 }).toBe(0);
+});
+
+test("cancelling a refused kill leaves the next card clean", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ await configureProjectModel(page.request);
+ await killAllTerminals(page.request);
+ await page.goto(`${BASE}/chat`);
+ await expect(page.locator("aside")).toBeVisible({ timeout: 20000 });
+ await page.keyboard.press("Control+Backquote");
+ const dock = page.locator('[data-testid="dock"][data-position="bottom"][data-open="true"]');
+ await expect(dock).toBeVisible({ timeout: 20000 });
+ const tab = dock.locator('[data-testid="dock-tab"][data-terminal-id]');
+
+ await refuseKill(page, "terminal_not_found");
+ await tab.getByTestId("dock-tab-close").click();
+ const card = page.getByRole("dialog", { name: CARD });
+ await card.getByRole("button", { name: CONFIRM }).click();
+ await expect(card.getByRole("alert")).toHaveText(NOT_FOUND_REFUSED);
+
+ // Escape closes the card; the sentence belonged to that question, so the next one is clean.
+ await page.keyboard.press("Escape");
+ await expect(card).toHaveCount(0);
+ await tab.getByTestId("dock-tab-close").click();
+ const again = page.getByRole("dialog", { name: CARD });
+ await expect(again).toBeVisible();
+ await expect(again.getByRole("alert")).toHaveCount(0);
+});
+
+test("the standalone window keeps its refusal on screen, and its shell running", async ({
+ page,
+}) => {
+ await provisionAndLogin(page.request, U, P);
+ await killAllTerminals(page.request);
+ await page.goto(`${BASE}/terminal`);
+ await waitForShell(page, "KILL_REFUSED_1");
+
+ const notices = page.getByRole("region", { name: "通知" });
+ await refuseKill(page, "internal");
+
+ // terminal.close (Ctrl+Alt+`) inside the terminal takes the dock tab's × path.
+ await page.click(".xterm-screen");
+ await page.keyboard.press("Control+Alt+Backquote");
+ const card = page.getByRole("dialog", { name: CARD });
+ await expect(card).toBeVisible();
+ await card.getByRole("button", { name: CONFIRM }).click();
+
+ // The window is the only surface that shell is on, so a refusal must not close it.
+ await expect(card.getByRole("alert")).toHaveText(INTERNAL_REFUSED);
+ await expect(notices.getByRole("button")).toHaveCount(0);
+ await page.waitForTimeout(7_000);
+ await expect(card.getByRole("alert")).toHaveText(INTERNAL_REFUSED);
+ expect(page.url(), "the window is still here").toContain("/terminal");
+ await expect(page.locator('[data-testid="terminal-status"][data-status="ready"]')).toBeVisible();
+ expect(await aliveCount(page.request), "the shell is still alive").toBe(1);
+
+ // The same button again, with the server answering, ends the shell it was asked about.
+ await allowKill(page);
+ const landed = page.waitForResponse(
+ (res) => res.request().method() === "DELETE" && res.url().includes("/api/terminals/"),
+ );
+ await card.getByRole("button", { name: CONFIRM }).click();
+ expect((await landed).status(), "the kill landed").toBe(204);
+ await expect.poll(() => aliveCount(page.request), { timeout: 10000 }).toBe(0);
+});
diff --git a/packages/web/src/features/dock/dock-panel.tsx b/packages/web/src/features/dock/dock-panel.tsx
index 9ea8b17a..25820b64 100644
--- a/packages/web/src/features/dock/dock-panel.tsx
+++ b/packages/web/src/features/dock/dock-panel.tsx
@@ -73,6 +73,7 @@ import {
} from "@adelie/ui";
import type { DockPickerChoice, DockTabItem } from "@adelie/ui";
import { S } from "../../lib/strings";
+import { refusalText } from "../../lib/api-error";
import { NAV_ICONS } from "../../lib/nav-icons";
import { chordKeys } from "../../components/ui/chord-kbd";
import { useDisplayedBinding, useShortcutLabel } from "../../lib/shortcuts/use-keymap";
@@ -313,8 +314,16 @@ export function DockPanel({
// a close guard (the Files panel's editor holding unsaved text), which asks first: the
// tab's × is the one gesture here that really unmounts a body.
const [confirmKill, setConfirmKill] = useState<{ id: string; label: string } | null>(null);
+ /**
+ * The server's words for a kill it refused, for the card that asked to draw. The entry and
+ * the tab stay (the shell is still running), so this sentence is the only place that says so
+ * — it is cleared when the card opens again and when it closes, and the card's own button is
+ * the retry.
+ */
+ const [killRefusal, setKillRefusal] = useState<string | null>(null);
const closeTab = useCallback((tab: DockTab, label: string) => {
if (tab.kind === "terminal") {
+ setKillRefusal(null);
setConfirmKill({ id: tab.terminalId, label });
return;
}
@@ -323,9 +332,17 @@ export function DockPanel({
// Hiding puts the surface away and nothing else — every body stays mounted at zero size —
// so there is nothing to ask about, however much unsaved work a tab is holding.
const hide = useCallback(() => hideView(view), [view]);
- const killConfirmed = useCallback(() => {
+ const killConfirmed = useCallback(async () => {
if (!confirmKill) return;
- void killTerminal(confirmKill.id);
+ setKillRefusal(null); // this attempt's own answer is the one that gets drawn
+ try {
+ await killTerminal(confirmKill.id);
+ } catch (err) {
+ // Refused: the tab is only removed by a kill that landed, so it is still in the strip
+ // and its × is where the user retries from.
+ setKillRefusal(refusalText(err));
+ return;
+ }
removeTab(`terminal:${confirmKill.id}`);
setConfirmKill(null);
}, [confirmKill]);
@@ -834,10 +851,14 @@ export function DockPanel({
<ConfirmModal
open={confirmKill !== null}
title={S.dock.killConfirmTitle}
- onClose={() => setConfirmKill(null)}
- onConfirm={killConfirmed}
+ onClose={() => {
+ setConfirmKill(null);
+ setKillRefusal(null); // the sentence belonged to that question
+ }}
+ onConfirm={() => void killConfirmed()}
confirmLabel={S.terminal.killShell}
cancelLabel={S.common.cancel}
+ refusal={killRefusal === null ? undefined : S.common.refused(killRefusal)}
>
{confirmKill !== null && (
<p className="break-words text-sm text-gray-600 dark:text-gray-300">
diff --git a/packages/web/src/features/terminal/terminal-list.ts b/packages/web/src/features/terminal/terminal-list.ts
index a65ba04b..53bec778 100644
--- a/packages/web/src/features/terminal/terminal-list.ts
+++ b/packages/web/src/features/terminal/terminal-list.ts
@@ -12,14 +12,15 @@
* tab cannot see (a shell exiting on its own, terminals opened from another window).
*/
import type { TerminalInfo } from "./terminal-view";
+import { apiFetch } from "../../api/client";
import { probeSession } from "../../api/session-probe";
import { pruneTerminalTabs } from "../dock/dock-state";
import { apiUrl } from "../../lib/server-context";
import {
+ machineForTerminal,
rememberTerminalMachine,
terminalMachinesPublished,
terminalSources,
- terminalUrl,
} from "../../lib/terminal-machines";
/**
@@ -204,17 +205,34 @@ export function noteTerminalCreated(info: TerminalInfo): void {
* list (count, tabs, badge) before the server round-trip; delayed refreshes reconcile once
* the pty has actually exited, with `pendingKills` keeping the dying shell from
* reappearing in between.
+ *
+ * The DELETE can be REFUSED — the shell is already gone under this id (404
+ * `terminal_not_found`), the machine holding it does not answer, this window is not signed
+ * in any more — and nothing here used to look: the entry was gone before the answer, so the
+ * tab vanished while the shell kept running and the screen said nothing at all. A refusal
+ * now takes the entry back (a shell the server would not end is still a shell the user has)
+ * and rejects with the server's words, for the card that asked to draw (the card keeps
+ * itself open on one, exactly like every other refusal in the app).
*/
export async function killTerminal(id: string): Promise<void> {
+ // What the list held before the entry left it: a refusal puts exactly this back, since the
+ // alternative — re-reading the server — would show the truth a round trip later and flicker.
+ const previous = raw;
pendingKills.set(id, Date.now() + 10_000);
commit(raw.filter((t) => t.id !== id));
try {
- await fetch(terminalUrl(`/api/terminals/${encodeURIComponent(id)}`), {
+ await apiFetch<void>(`/api/terminals/${encodeURIComponent(id)}`, {
method: "DELETE",
- credentials: "same-origin",
+ server: machineForTerminal(id),
});
- } catch {
- // The delayed refreshes below still reconcile with whatever the server thinks.
+ } catch (err) {
+ // Nothing was ended. Un-hide the entry so the pane and its tab keep their owner, and ask
+ // the server what it thinks now: a 404 for a shell that really is gone takes it away
+ // again, which is the outcome the user asked for anyway.
+ pendingKills.delete(id);
+ if (!raw.some((t) => t.id === id)) commit(previous);
+ void refreshTerminals();
+ throw err;
}
for (const delay of [300, 1500]) {
setTimeout(() => void refreshTerminals(), delay);
diff --git a/packages/web/src/features/terminal/terminal-page.tsx b/packages/web/src/features/terminal/terminal-page.tsx
index 732a383a..9f6e781e 100644
--- a/packages/web/src/features/terminal/terminal-page.tsx
+++ b/packages/web/src/features/terminal/terminal-page.tsx
@@ -26,6 +26,7 @@
import { useCallback, useMemo, useState } from "react";
import { ConfirmModal, GlyphIcon, ICONS, ICON_SIZE } from "@adelie/ui";
import { S } from "../../lib/strings";
+import { refusalText } from "../../lib/api-error";
import { useCoarsePointer } from "../../lib/use-coarse-pointer";
import { useVisualViewportHeight } from "../../lib/use-visual-viewport-height";
import { useTerminalChrome } from "./terminal-appearance";
@@ -172,15 +173,32 @@ export function TerminalPage() {
* stays, showing the exited shell with "New terminal" one click away. The kill is awaited
* first so the dock's detach watcher, which probes the shell when the window closes, finds
* it ended rather than restoring a tab for it.
+ *
+ * A kill the server REFUSED leaves both the shell and this window in place: the card stays
+ * open with the server's own words in it (`killRefusal`), and its button is the retry — the
+ * window is the only surface that shell is shown on, so closing it over a shell that is still
+ * running would hide the thing the user has to deal with.
*/
const [confirmKill, setConfirmKill] = useState(false);
+ const [killRefusal, setKillRefusal] = useState<string | null>(null);
const killConfirmed = useCallback(async () => {
if (!info) return;
+ setKillRefusal(null); // this attempt's own answer is the one that gets drawn
+ try {
+ await killTerminal(info.id);
+ } catch (err) {
+ setKillRefusal(refusalText(err));
+ return;
+ }
setConfirmKill(false);
- await killTerminal(info.id);
window.close();
}, [info]);
+ const askToKill = useCallback(() => {
+ setKillRefusal(null);
+ setConfirmKill(true);
+ }, []);
+
const statusText =
status === "exited" && detail
? `${S.terminal.status.exited} — ${S.terminal.exitedWithCode(detail)}`
@@ -234,16 +252,20 @@ export function TerminalPage() {
ensure={ensure}
onStatus={onStatus}
onInfo={setInfo}
- onCloseRequest={info ? () => setConfirmKill(true) : undefined}
+ onCloseRequest={info ? askToKill : undefined}
className="min-h-0 flex-1 overflow-hidden px-2 py-1"
/>
<ConfirmModal
open={confirmKill}
title={S.dock.killConfirmTitle}
- onClose={() => setConfirmKill(false)}
+ onClose={() => {
+ setConfirmKill(false);
+ setKillRefusal(null); // the sentence belonged to that question
+ }}
onConfirm={() => void killConfirmed()}
confirmLabel={S.terminal.killShell}
cancelLabel={S.common.cancel}
+ refusal={killRefusal === null ? undefined : S.common.refused(killRefusal)}
>
{info && (
<p className="break-words text-sm text-gray-600 dark:text-gray-300">
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index c5f949ea..254d3e9e 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -5997,6 +5997,7 @@ export const en: Strings = {
approval_not_found: "This approval request was already answered, or is no longer valid.",
process_not_found: "This background process already exited, or was removed.",
process_running: "This background process is still running — stop it before removing it.",
+ terminal_not_found: "This terminal no longer exists, or it has been closed.",
memory_file_not_found: "This memory file no longer exists.",
memory_scope_not_found: "This memory scope no longer exists.",
task_in_progress: "This Session already has a task running.",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 4e3301f5..6337eb6e 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -6049,6 +6049,7 @@ export const zh = {
approval_not_found: "该授权请求已处理或已失效。",
process_not_found: "该后台进程已结束或已被移除。",
process_running: "该后台进程仍在运行,请先结束再移除。",
+ terminal_not_found: "该终端已不存在或已被关闭。",
memory_file_not_found: "该记忆文件已不存在。",
memory_scope_not_found: "该记忆范围已不存在。",
task_in_progress: "该 Session 已有任务在运行。",
diff --git a/packages/web/test/terminal-kill-refusal.test.ts b/packages/web/test/terminal-kill-refusal.test.ts
new file mode 100644
index 00000000..b55167b3
--- /dev/null
+++ b/packages/web/test/terminal-kill-refusal.test.ts
@@ -0,0 +1,91 @@
+/**
+ * Ending a terminal the server REFUSES (features/terminal/terminal-list.ts).
+ *
+ * The kill is optimistic — the entry leaves the list before the round trip, so the tab and the
+ * count react to the user's own click — which used to make a refusal invisible twice over: the
+ * non-2xx answer was not even read, a network failure was swallowed, and the entry was never
+ * given back, so the screen showed a shell as ended while it was still running. What is pinned
+ * here is the other half of the contract: a refusal hands the entry back and rejects with the
+ * server's words (a `terminal_not_found` is the app's own sentence), a network failure is the
+ * app's `network_error`, and the DELETE still addresses the machine that holds the shell.
+ */
+import { describe, expect, it } from "vitest";
+import { ApiError } from "../src/api/client";
+import {
+ killTerminal,
+ liveTerminals,
+ noteTerminalCreated,
+} from "../src/features/terminal/terminal-list";
+import { rememberTerminalMachine, forgetTerminalMachines } from "../src/lib/terminal-machines";
+import { apiError, json, stubFetch } from "./helpers/fetch";
+import type { TerminalInfo } from "../src/features/terminal/terminal-view";
+
+/** A live shell as the list holds it. */
+function terminal(id: string): TerminalInfo {
+ return { id, name: id, cwd: "/tmp", alive: true };
+}
+
+/** Is this terminal in the list the UI draws? */
+function listed(id: string): boolean {
+ return liveTerminals().some((t) => t.id === id);
+}
+
+describe("a kill the server refused", () => {
+ it("puts the entry back and rejects with the server's own code", async () => {
+ // The server still lists the shell (it was never ended) and refuses the DELETE under it.
+ const fake = stubFetch((request) =>
+ request.method === "DELETE"
+ ? apiError(404, "terminal_not_found", "Terminal does not exist or has been closed.")
+ : json({ terminals: [terminal("t-refused")] }),
+ );
+ noteTerminalCreated(terminal("t-refused"));
+
+ await expect(killTerminal("t-refused")).rejects.toMatchObject({
+ name: "ApiError",
+ status: 404,
+ code: "terminal_not_found",
+ });
+ // The shell is still there, so the list the tabs are drawn from has to hold it again.
+ expect(listed("t-refused")).toBe(true);
+ expect(fake.requests.filter((r) => r.method === "DELETE").map((r) => r.path)).toEqual([
+ "/api/terminals/t-refused",
+ ]);
+ // The refusal also re-reads the list: the answer, not the optimistic removal, decides.
+ expect(fake.requests.some((r) => r.method === "GET")).toBe(true);
+ });
+
+ it("treats a dropped connection as a refusal too — the shell never heard the request", async () => {
+ stubFetch(() => {
+ throw new TypeError("Failed to fetch");
+ });
+ noteTerminalCreated(terminal("t-unreachable"));
+
+ const refusal = await killTerminal("t-unreachable").catch((err: unknown) => err);
+ expect(refusal).toBeInstanceOf(ApiError);
+ expect((refusal as ApiError).code).toBe("network_error");
+ expect(listed("t-unreachable")).toBe(true);
+ });
+});
+
+describe("a kill that landed", () => {
+ it("leaves the entry out of the list, and goes to the machine that holds the shell", async () => {
+ const fake = stubFetch(() => new Response(null, { status: 204 }));
+ noteTerminalCreated(terminal("t-landed"));
+ rememberTerminalMachine("t-landed", "M1");
+ try {
+ await killTerminal("t-landed");
+ expect(listed("t-landed")).toBe(false);
+ // The pty is on one machine's kernel: a DELETE sent to this server ends nothing.
+ expect(fake.requests.map((r) => r.url)).toEqual(["/server/M1/api/terminals/t-landed"]);
+ } finally {
+ forgetTerminalMachines();
+ }
+ });
+
+ it("does not treat a 200 with a body as a failure", async () => {
+ stubFetch(() => json({ ok: true }));
+ noteTerminalCreated(terminal("t-json"));
+ await expect(killTerminal("t-json")).resolves.toBeUndefined();
+ expect(listed("t-json")).toBe(false);
+ });
+});