Skip to content

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

fix(server,web,ui): 删除大 Agent 不再卡住应用,文件在后台删、右下角有进度

lmliheng8de40b0f427a
diff --git a/changelog/unreleased/2026-11-01-agent-delete-background.md b/changelog/unreleased/2026-11-01-agent-delete-background.md
new file mode 100644
index 00000000..fbffdc6f
--- /dev/null
+++ b/changelog/unreleased/2026-11-01-agent-delete-background.md
@@ -0,0 +1,43 @@
+# Deleting a large agent no longer freezes the app, and shows its progress
+
+- **Date:** 2026-11-01
+- **Type:** fix
+- **Scope:** `server`, `web`, `ui`, `docs`
+- **Breaking:** no
+
+[中文](2026-11-01-agent-delete-background.zh.md)
+
+Deleting an agent whose folder held many files — a temporary Workspace with installed dependencies
+is the usual one — kept the server busy until the last file was gone. The Web App sat on the
+confirmation dialog, and every other page that read a file waited behind the delete. Restarting the
+app partway through left the agent on the Agents list, while opening or deleting it answered "This
+agent no longer exists."
+
+A delete now moves the agent's folder into `agents/.deleting/` in one rename, drops its index rows
+and answers `202` with the deletion. From then on the agent is on no list, every route answers 404,
+and its id can be used again. The folder's contents are removed in the background with only a
+couple of filesystem calls in flight at a time, so the server keeps answering other requests.
+
+Ported from PenguinHarness `#1348` (`4dca3c66`), not a branch merge: this tree has no workbench
+mechanism and no machine-side Agents, so the two release-before-move calls for those are left out,
+and so is the "still an employee" refusal, which belongs to a company-mode change this tree does
+not have.
+
+## Details
+
+- `GET /api/projects/:projectId/agent-deletions/:deletionId` reports the removal: `counting`, then
+ `removing` with `removed` out of `total` entries, then `done`, or `failed` with the operating
+ system's reason.
+- Whatever a removal leaves behind — an entry it could not remove, or the rest when the server
+ stopped — is removed again at the next start under the same deletion id
+ (`AgentLifecycle.resumeDeletions()`, called from `Startup.setup`).
+- Before the move the server stops the agent's runs, as before. If the folder still cannot be moved
+ because another program has a file in it open, the delete is refused with `409 agent_folder_busy`
+ and nothing is deleted.
+- The Agents list shows an agent only while its `agent_state/system_config.yaml` exists — the rule
+ every agent route already applied — so a listed agent always opens and deletes, and one an
+ interrupted delete left half-gone is no longer listed.
+- When the removal takes noticeable time, a card in the bottom-right corner follows it: counting
+ first, then items removed out of the total, then the result. Closing the card does not stop the
+ removal, and the card stays on screen after you leave the Agents page. The card is
+ `ProgressToasts` in the UI package, available to other long operations.
diff --git a/changelog/unreleased/2026-11-01-agent-delete-background.zh.md b/changelog/unreleased/2026-11-01-agent-delete-background.zh.md
new file mode 100644
index 00000000..173619de
--- /dev/null
+++ b/changelog/unreleased/2026-11-01-agent-delete-background.zh.md
@@ -0,0 +1,34 @@
+# 删除大 Agent 不再卡住应用,并显示进度
+
+- **Date:** 2026-11-01
+- **Type:** fix
+- **Scope:** `server`, `web`, `ui`, `docs`
+- **Breaking:** no
+
+[English](2026-11-01-agent-delete-background.md)
+
+删除一个目录里文件很多的 Agent(最常见的是临时 Workspace 里装了依赖)时,服务端要一直忙到最后一个
+文件删完:Web App 停在确认弹窗上,其他要读文件的页面也都排在这次删除后面。删到一半重启应用,Agents
+列表里还留着这个 Agent,点进去或再删一次却提示「该 Agent 已不存在」。
+
+现在删除先用一次 rename 把 Agent 目录移进 `agents/.deleting/`,删掉索引行,随即以 `202` 返回这次删除。
+从这一刻起,任何列表里都没有这个 Agent,所有路由都答 404,同一个 id 可以马上再用。目录里的内容在后台
+删除,同一时间只有少量文件系统调用在进行,服务端照常应答其他请求。
+
+移植自 PenguinHarness `#1348`(`4dca3c66`),照改动落、不是合分支:本树没有 workbench 机制、也没有
+「机器那边的 Agent」,所以「移动之前先释放 workbench」的两处调用没有落;「仍是组织员工」那条拒绝属于
+本树还没有的公司模式改动,也一并省去。
+
+## 细节
+
+- `GET /api/projects/:projectId/agent-deletions/:deletionId` 报告删除进度:先是 `counting`,再是
+ `removing`(`total` 条中已删 `removed` 条),最后是 `done`,或 `failed` 并附操作系统给出的原因。
+- 删除留下的东西,不论是删不掉的条目,还是服务端中途停止时剩下的部分,都会在下次启动时以同一个
+ deletion id 继续删除(`AgentLifecycle.resumeDeletions()`,由 `Startup.setup` 调用)。
+- 移动目录之前,服务端照旧中止该 Agent 的运行。如果目录仍因其他程序打开着其中的文件而移不走,删除以
+ `409 agent_folder_busy` 拒绝,什么都不删。
+- Agents 列表只在 `agent_state/system_config.yaml` 存在时列出一个 Agent——与各 Agent 路由一直以来的
+ 判据相同——所以列出来的 Agent 总能打开、能删除;被中断的删除留下的半个 Agent 不再出现在列表里。
+- 删除耗时明显时,右下角出现一张卡片跟进:先统计条目,再显示已删条目数与总数,最后显示结果。关掉卡片
+ 不会中断删除,离开 Agents 页面后卡片也还在。这张卡片是 UI 包的 `ProgressToasts`,其他耗时操作也可以
+ 用。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index c8c53a62..978b0664 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -434,7 +434,8 @@ The paths below omit the `/api/projects/:projectId` prefix, except the two globa
| Method | Path | Description |
| --- | --- | --- |
| GET / POST | `/agents` | Lists agents / creates one |
-| DELETE | `/agents/:agentId` | Deletes an agent (owner only) |
+| DELETE | `/agents/:agentId` | Deletes an agent (owner only): its folder leaves the agents directory in one rename and its files are removed in the background → `202 {deletion}`; `409 agent_folder_busy` when another program holds a file in the folder open, with nothing deleted |
+| GET | `/agent-deletions/:deletionId` | How far a delete's background removal has got (owner only): `{deletion: {phase: counting\|removing\|done\|failed, total, removed, error?}}` |
| GET / PUT | `/agents/:agentId/config` | Reads / writes the config (`AGENTS.md` and `system_config.yaml`; PUT preserves YAML comments) |
| POST | `/agents/:agentId/config/mcp-test` | Tests one MCP server entry: `{name, config}` → `{ok, tools?, error?, latencyMs?}` |
| POST | `/agents/:agentId/config/kernel-update` | Merges the config up to the current defaults: → `{advanced, kept, kernelVersion}` |
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 3cd5df34..60102a48 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -434,7 +434,8 @@ flow id 指向的流程不存在时返回 `404 platform_auth_flow_not_found`。`
| 方法 | 路径 | 说明 |
| --- | --- | --- |
| GET / POST | `/agents` | 列出 Agent / 创建 Agent |
-| DELETE | `/agents/:agentId` | 删除一个 Agent(仅所有者) |
+| DELETE | `/agents/:agentId` | 删除一个 Agent(仅所有者):目录以一次 rename 移出 agents 目录,文件在后台删除 → `202 {deletion}`;其他程序打开着目录里的文件时返回 `409 agent_folder_busy`,什么都不删 |
+| GET | `/agent-deletions/:deletionId` | 一次删除在后台进行到哪一步(仅所有者):`{deletion: {phase: counting\|removing\|done\|failed, total, removed, error?}}` |
| GET / PUT | `/agents/:agentId/config` | 读取 / 写入配置(`AGENTS.md` 和 `system_config.yaml`;PUT 保留 YAML 注释) |
| POST | `/agents/:agentId/config/mcp-test` | 测试一条 MCP 服务器配置:`{name, config}` → `{ok, tools?, error?, latencyMs?}` |
| POST | `/agents/:agentId/config/kernel-update` | 将配置合并升级到当前默认值:→ `{advanced, kept, kernelVersion}` |
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index c621c5fe..f6efd91c 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -1522,6 +1522,41 @@ export interface AgentCreateResponse {
agent: AgentSummary;
}
+/**
+ * Where a deleted Agent's files stand. The Agent itself is gone the moment DELETE answers: its
+ * folder was moved out of the Project's agents directory in one rename, and every list and route
+ * stopped seeing it. What follows is the removal of that folder's contents in the background,
+ * which this reports.
+ */
+export interface AgentDeletionInfo {
+ /** Names this deletion (GET /api/projects/:projectId/agent-deletions/:deletionId). */
+ deletionId: string;
+ agentId: string;
+ /**
+ * `counting`: the folder is walked to learn how many entries it holds (`total` grows);
+ * `removing`: they are removed (`removed` grows towards `total`); `done`: nothing is left;
+ * `failed`: some entries could not be removed (`error` says why). What is left is tried again
+ * when the server next starts.
+ */
+ phase: "counting" | "removing" | "done" | "failed";
+ /** Entries found: so far while counting, then in all. Files and folders alike. */
+ total: number;
+ /** Entries removed so far. */
+ removed: number;
+ /** The first error the removal met, as the operating system worded it (`failed` only). */
+ error?: string;
+}
+
+/** DELETE /api/projects/:projectId/agents/:agentId (202). */
+export interface AgentDeleteResponse {
+ deletion: AgentDeletionInfo;
+}
+
+/** GET /api/projects/:projectId/agent-deletions/:deletionId. */
+export interface AgentDeletionResponse {
+ deletion: AgentDeletionInfo;
+}
+
export interface AgentModelConfigDto {
maxTokens?: number;
thinkingLevel?: ThinkingLevelName;
diff --git a/packages/server/src/http/routes/agents.ts b/packages/server/src/http/routes/agents.ts
index 18303ef3..9ad95b5c 100644
--- a/packages/server/src/http/routes/agents.ts
+++ b/packages/server/src/http/routes/agents.ts
@@ -1,13 +1,23 @@
/**
* Agent routes:
- * GET|POST /api/projects/:p/agents, DELETE /:agentId (owner only).
+ * GET|POST /api/projects/:p/agents, DELETE /:agentId (owner only), and
+ * GET /api/projects/:p/agent-deletions/:deletionId (owner only), how far a delete's background
+ * removal has got.
* The list is the union of DB entries and directory scan results, including active
* Session count, total Session count, config last-modified time, and whether the Agent's API
* switch is on.
*/
import { Hono } from "hono";
-import type { AgentCreateResponse, AgentsResponse, AgentSummary } from "../../api/types.js";
+import type {
+ AgentCreateResponse,
+ AgentDeleteResponse,
+ AgentDeletionInfo,
+ AgentDeletionResponse,
+ AgentsResponse,
+ AgentSummary,
+} from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
+import { HttpError } from "../errors.js";
import { settleWithin } from "../settle.js";
import {
badRequest,
@@ -27,6 +37,7 @@ import type { ErrorLog } from "../../mechanisms/observability.js";
import type { Schedules, SessionIndex } from "../../mechanisms/sessions.js";
import type { Access } from "../../mechanisms/projects.js";
import type { AgentApi } from "../../mechanisms/agent-api.js";
+import { refuseBuiltinDeletion } from "../../services/agent-service.js";
/** What this route group reaches — bound by its module (src/modules). */
export interface AgentsRouteDeps {
@@ -134,17 +145,22 @@ export function agentsRoutes(deps: AgentsRouteDeps): Hono<AppEnv> {
// Deletion is a Project-level management operation: owner only.
deps.access.requireProjectOwner(c.var.user.userId, projectId);
await deps.agentConfigService.requireExists(projectId, agentId);
+ // Refused before any run is touched.
+ refuseBuiltinDeletion(agentId);
// Mark as deleting and converge active runs (beginAgentDeletion): any new Task during
// this window gets 409, preventing the race where a new task recreates the directory
- // and revives the Agent between abort and rm. Abort cleanup writes the Trace
- // asynchronously; wait for it to finish before removing the directory, and clear the
- // deleting flag once deletion completes (success or failure).
+ // and revives the Agent between abort and the move. Abort cleanup writes the Trace
+ // asynchronously; wait for it to finish before moving the directory, and clear the
+ // deleting flag once the move is done (success or failure).
const runnings = deps.manager.beginAgentDeletion(projectId, agentId);
+ let deletion: AgentDeletionInfo;
try {
await settleWithin(runnings, 5000);
- await deps.agentService.deleteAgent(projectId, agentId);
+ // One rename takes the folder out of every list and route; its contents are removed in
+ // the background, which the answer reports and GET /agent-deletions/:id follows.
+ deletion = await deps.agentService.deleteAgent(projectId, agentId);
deps.sessionsRepo.deleteByAgent(projectId, agentId);
- // Trace-index rows describe files the rm above just removed: drop them with the Agent.
+ // Trace-index rows describe files that just left: drop them with the Agent.
deps.traceIndex.removeAgent(projectId, agentId);
// Per-Agent runtime state keyed on the now-removed sessions/agent: drop it so nothing is
// orphaned (session ids are never reused, so a leftover row is dead weight). Usage records
@@ -157,7 +173,27 @@ export function agentsRoutes(deps: AgentsRouteDeps): Hono<AppEnv> {
} finally {
deps.manager.endAgentDeletion(projectId, agentId);
}
- return c.body(null, 204);
+ return c.json({ deletion } satisfies AgentDeleteResponse, 202);
+ });
+
+ return app;
+}
+
+/** GET /api/projects/:projectId/agent-deletions/:deletionId: where a delete's removal stands. */
+export function agentDeletionsRoutes(
+ deps: Pick<AgentsRouteDeps, "access" | "agentService">,
+): Hono<AppEnv> {
+ const app = new Hono<AppEnv>();
+
+ app.get("/:deletionId", (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const deletionId = requireValidId(c, "deletionId");
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
+ const deletion = deps.agentService.agentDeletion(projectId, deletionId);
+ if (deletion === null) {
+ throw new HttpError(404, "agent_deletion_not_found", "No such deletion is in progress.");
+ }
+ return c.json({ deletion } satisfies AgentDeletionResponse);
});
return app;
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index 77855576..0dd0210f 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -132,7 +132,7 @@ import { Channels, Config, Desktop } from "../../hmr/capabilities.js";
import { Sessions as ManagerIface, SessionServiceIface } from "../../runtime/session-manager.js";
import { Messaging } from "../../runtime/messaging/bridge.js";
-import { agentsRoutes } from "./agents.js";
+import { agentDeletionsRoutes, agentsRoutes } from "./agents.js";
import { agentConfigRoutes } from "./agent-config.js";
import { vaultRoutes } from "./vault.js";
import { modelsRoutes } from "./models.js";
@@ -2020,6 +2020,12 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
auth: "user",
order: 140,
},
+ {
+ id: "session-api.agent-deletions",
+ prefix: "/api/projects/:projectId/agent-deletions",
+ auth: "user",
+ order: 141,
+ },
{
id: "session-api.agent-config",
prefix: "/api/projects/:projectId/agents/:agentId/config",
@@ -2104,6 +2110,7 @@ export class SessionApiRoutes {
@Bind("session-api.chat-defaults") chatDefaultsRoutes!: Hono<AppEnv>;
@Bind("session-api.command-policy") commandPolicyRoutes!: Hono<AppEnv>;
@Bind("session-api.agents") agentsRoutes!: Hono<AppEnv>;
+ @Bind("session-api.agent-deletions") agentDeletionsRoutes!: Hono<AppEnv>;
@Bind("session-api.agent-config") agentConfigRoutes!: Hono<AppEnv>;
@Bind("session-api.vault") vaultRoutes!: Hono<AppEnv>;
@Bind("session-api.agent-sessions") agentSessionsRoutes!: Hono<AppEnv>;
@@ -2189,6 +2196,7 @@ export class SessionApiRoutes {
sessionsRepo,
traceIndex: this.traceIndex,
});
+ this.agentDeletionsRoutes = agentDeletionsRoutes({ access, agentService: this.agents });
this.agentConfigRoutes = agentConfigRoutes({ agentConfigService, manager, access });
this.vaultRoutes = vaultRoutes({
agentConfigService,
diff --git a/packages/server/src/mechanisms/agents.ts b/packages/server/src/mechanisms/agents.ts
index ff6c058e..f0a8c59a 100644
--- a/packages/server/src/mechanisms/agents.ts
+++ b/packages/server/src/mechanisms/agents.ts
@@ -5,6 +5,7 @@ import { Interface } from "@adelie/core/kernel";
import type { AgentConfigView } from "../services/agent-config-service.js";
import type {
AgentConfigUpdateRequest,
+ AgentDeletionInfo,
AgentKernelUpdateResponse,
BenchmarkCasesResponse,
BenchmarksResponse,
@@ -155,7 +156,17 @@ export abstract class AgentLifecycle {
abstract listAgents(projectId: string): Promise<AgentListItem[]>;
/** Every id `createAgent` refuses as taken, as names only, including a folder that does not list. */
abstract takenAgentIds(projectId: string): Promise<string[]>;
- abstract deleteAgent(projectId: string, agentId: string): Promise<void>;
+ /**
+ * Moves the Agent's folder out of the agents directory in one rename and drops its index row,
+ * so it is gone from every list and route at once; its files are then removed in the
+ * background, as the returned deletion reports. Refuses a built-in Agent, and a folder another
+ * program holds open (409 `agent_folder_busy`, nothing deleted).
+ */
+ abstract deleteAgent(projectId: string, agentId: string): Promise<AgentDeletionInfo>;
+ /** Where one deletion stands; null once it is unknown here (finished long ago, or never was). */
+ abstract agentDeletion(projectId: string, deletionId: string): AgentDeletionInfo | null;
+ /** Removes whatever deleted Agents left behind when the server last stopped mid-removal. */
+ abstract resumeDeletions(): Promise<void>;
abstract createAgent(
projectId: string,
agentId: string,
diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.ts
index b1a73073..53b7e86e 100644
--- a/packages/server/src/platform.ts
+++ b/packages/server/src/platform.ts
@@ -201,6 +201,7 @@ export class Startup {
@Use() private readonly errors!: Errors;
@Use() private readonly projectConfig!: ProjectConfigStore;
@Use() private readonly usage!: UsageQueries;
+ @Use() private readonly agents!: AgentLifecycle;
async setup() {
// The shared default Project's display name, on every start rather than only where it is
@@ -228,6 +229,11 @@ export class Startup {
void this.sessionService.adoptUnmanagedTraceSessions().catch((err: unknown) => {
this.errors.record({ source: "process", err, code: "trace_adoption_failed" });
});
+ // Deleted Agents whose files a stopped process had not finished removing: removed now, in
+ // the background, the way the delete itself removes them.
+ void this.agents.resumeDeletions().catch((err: unknown) => {
+ this.errors.record({ source: "process", err, code: "agent_purge_failed" });
+ });
// Machines, in one sweep (machines/service.ts start()): a push here is a push everywhere,
// so this App booting hands the same build on to any machine still carrying a different
// one, and then re-holds every connection the record says was held — the generation
diff --git a/packages/server/src/runtime/scheduler.ts b/packages/server/src/runtime/scheduler.ts
index 73034165..f7f79974 100644
--- a/packages/server/src/runtime/scheduler.ts
+++ b/packages/server/src/runtime/scheduler.ts
@@ -316,7 +316,8 @@ export class Scheduler implements Scheduling {
const items = await fs.readdir(agentsDir(this.root, projectId), {
withFileTypes: true,
});
- ids = items.filter((d) => d.isDirectory()).map((d) => d.name);
+ // A dot-directory (`.deleting/`, where a deleted Agent's files wait) is never an Agent.
+ ids = items.filter((d) => d.isDirectory() && !d.name.startsWith(".")).map((d) => d.name);
} catch {
this.agentDirs.delete(projectId);
return [];
diff --git a/packages/server/src/services/agent-service.ts b/packages/server/src/services/agent-service.ts
index a594756d..5bb4488f 100644
--- a/packages/server/src/services/agent-service.ts
+++ b/packages/server/src/services/agent-service.ts
@@ -1,10 +1,14 @@
/**
* Agent service.
*
- * The list is the union of "DB index ∪ directory scan": a subdirectory under
- * `<project>/` containing `agent_state/system_config.yaml` is treated as an Agent;
- * unmanaged ones found are backfilled into the DB — this handles Agents created
- * directly via the CLI.
+ * The list is the union of "DB index ∪ directory scan", held to the one rule every Agent route
+ * applies: an Agent exists while `agents/<id>/agent_state/system_config.yaml` does. Unmanaged
+ * directories found are backfilled into the DB — this handles Agents created directly via the
+ * CLI — and an index row whose folder no longer has that file is not listed, so a listed Agent
+ * can always be opened and deleted.
+ * Delete: the folder is renamed into `agents/.deleting/` (one rename, so it leaves every list
+ * and route at once) and its contents are removed in the background, the removal reporting how
+ * far it got; a server that stops mid-removal resumes it at its next start.
* Create: generate agent-<8hex>, initialize Agent State via core's `createAgent`,
* then write name/description into system_config.yaml (parseDocument preserves the
* template's comments).
@@ -13,6 +17,7 @@ import fs from "node:fs/promises";
import type { Dirent } from "node:fs";
import path from "node:path";
import { HttpError } from "../http/errors.js";
+import { countEntries, FsLimiter, purgeTree } from "./tree-purge.js";
import {
agentDir,
agentsDir,
@@ -36,10 +41,11 @@ import {
import type { LibraryPlugin } from "@adelie/core";
import { SEMANTIC_ID_PATTERN, SEMANTIC_ID_RULE } from "./ids.js";
import { isTopicFileName } from "./memory-service.js";
-import type { PluginUpdateRef } from "../api/types.js";
+import type { AgentDeletionInfo, PluginUpdateRef } from "../api/types.js";
import { resolveLibraryPlugins } from "./plugin-library.js";
import { resolveDirectorySkills } from "./directory-skills.js";
import { Component, Use } from "@adelie/core/kernel";
+import type { ClassCtx } from "@adelie/core/kernel";
import type { Config, Paths } from "../hmr/capabilities.js";
import type { AgentConfig, AgentLifecycle, Snapshots } from "../mechanisms/agents.js";
import type { AgentIndex } from "../mechanisms/projects.js";
@@ -66,6 +72,51 @@ async function readHead(file: string, bytes: number): Promise<string> {
}
}
+/**
+ * `agents/.deleting/`: where a deleted Agent's folder waits while its contents are removed. A
+ * sibling of the Agents, so moving one in is a rename within one directory — never a copy across
+ * filesystems — and a dot-name, which no Agent id can be, so nothing that walks `agents/` takes
+ * it for one.
+ */
+export const DELETING_DIR = ".deleting";
+
+/** `<agentsDir>/.deleting`. */
+export function deletingDir(root: string, projectId: string): string {
+ return path.join(agentsDir(root, projectId), DELETING_DIR);
+}
+
+/** A deletion's name, which is its folder's name under `.deleting/`: the Agent id and when. */
+const DELETION_NAME = /^(.+)-(\d+)$/;
+
+/**
+ * Filesystem calls the background removal keeps in flight, across every deletion at once. libuv
+ * gives file I/O four threads by default; holding two leaves the others free for the requests
+ * the server is answering meanwhile.
+ */
+const PURGE_SLOTS = 2;
+
+/** How long a finished deletion stays readable, for a page that polls it a little late. */
+const FINISHED_DELETION_TTL_MS = 10 * 60 * 1000;
+
+/**
+ * Windows refuses to move a folder while a program holds a file in it open; the hold is often
+ * momentary (an indexer, an antivirus scan), so the move is tried a few times before giving up.
+ */
+const MOVE_RETRIES = 4;
+const MOVE_RETRY_STEP_MS = 100;
+const MOVE_BUSY = new Set(["EBUSY", "EPERM", "EACCES"]);
+
+/** Refuses deleting a built-in Agent: they are provisioned with the Project. */
+export function refuseBuiltinDeletion(agentId: string): void {
+ if (BUILTIN_AGENT_IDS.includes(agentId)) {
+ throw new HttpError(
+ 409,
+ "cannot_delete_builtin_agent",
+ "Built-in Agents are provisioned with the Project and cannot be deleted from the web.",
+ );
+ }
+}
+
export interface AgentListItem {
agentId: string;
name?: string;
@@ -103,7 +154,23 @@ export class AgentService implements AgentLifecycle {
@Use() private readonly agentConfig!: AgentConfig;
@Use() private readonly snapshots!: Snapshots;
- /** Union of DB index ∪ directory scan; unmanaged directory Agents are backfilled into the DB. */
+ /** Deletions this process knows, by `${projectId}/${deletionId}`. */
+ private readonly deletions = new Map<string, AgentDeletionInfo>();
+ /** The removals in flight, by the same key. */
+ private readonly running = new Map<string, Promise<void>>();
+ /** Shared by every removal, so two deletions at once still hold only PURGE_SLOTS calls. */
+ private readonly limiter = new FsLimiter(PURGE_SLOTS);
+ /** Ends this generation's removals when it is disposed; the next one resumes them from disk. */
+ private readonly stopping = new AbortController();
+
+ setup(ctx: ClassCtx) {
+ ctx.effect(() => this.stopping.abort());
+ }
+
+ /**
+ * Union of DB index ∪ directory scan; unmanaged directory Agents are backfilled into the DB.
+ * Only what `AgentConfig.exists` accepts is listed — the rule every route checks.
+ */
async listAgents(projectId: string): Promise<AgentListItem[]> {
const known = new Map(this.agents.list(projectId).map((r) => [r.agentId, r]));
@@ -133,13 +200,22 @@ export class AgentService implements AgentLifecycle {
// same files). Meta reads and mtime stats for each Agent run in parallel (Promise.all
// preserves the sorted order).
const library = loadLibraryPlugins(this.root);
- const sorted = [...known.values()].sort((a, b) =>
- a.createdAt === b.createdAt
- ? a.agentId.localeCompare(b.agentId)
- : a.createdAt < b.createdAt
- ? -1
- : 1,
+ // An index row is listed only while its folder is an Agent by the routes' own rule: a row
+ // whose folder has lost its system_config.yaml would be a card that neither opens nor deletes.
+ const present = await Promise.all(
+ [...known.values()].map(async (row) =>
+ (await this.agentConfig.exists(projectId, row.agentId)) ? row : null,
+ ),
);
+ const sorted = present
+ .filter((row) => row !== null)
+ .sort((a, b) =>
+ a.createdAt === b.createdAt
+ ? a.agentId.localeCompare(b.agentId)
+ : a.createdAt < b.createdAt
+ ? -1
+ : 1,
+ );
return Promise.all(
sorted.map(async (row) => {
const [meta, updatedAt, vaultKeyCount, scheduleCount, installed, memoryCount] =
@@ -373,23 +449,149 @@ export class AgentService implements AgentLifecycle {
}
/**
- * Delete an Agent: the sole built-in Agent
- * default_agent (shared with the CLI, the default conversation Agent) cannot be
- * deleted; callers must first drain any active run via manager.abortAgent.
- * The directory is deleted recursively (including Trace), and the DB's
- * agents/sessions index rows are removed along with it; usage records are kept
- * (historical stats are unaffected).
+ * Delete an Agent: the built-in Agents cannot be deleted; callers must first drain any active
+ * run (the session manager's `beginAgentDeletion`) and let go of what holds the folder open.
+ *
+ * The folder (Agent State, Traces, scratchpads, temporary Workspaces) is moved to
+ * `agents/.deleting/<id>-<time>` in one rename and the index row dropped: from then on no list
+ * shows the Agent and no route accepts it, and a new Agent may take its id. The move is the
+ * whole of what the caller waits for — the contents are removed in the background, reported by
+ * the deletion returned (and by `agentDeletion` as it goes). A folder that cannot be moved is
+ * refused with nothing deleted (409 `agent_folder_busy`). Usage records are kept (historical
+ * stats are unaffected); the caller drops the Agent's other index rows.
*/
- async deleteAgent(projectId: string, agentId: string): Promise<void> {
- if (BUILTIN_AGENT_IDS.includes(agentId)) {
- throw new HttpError(
- 409,
- "cannot_delete_builtin_agent",
- "Built-in Agents (default_agent) are provisioned with the Project and cannot be deleted from the web.",
- );
- }
- await fs.rm(agentDir(this.root, projectId, agentId), { recursive: true, force: true });
+ async deleteAgent(projectId: string, agentId: string): Promise<AgentDeletionInfo> {
+ refuseBuiltinDeletion(agentId);
+ const deletionId = await this.moveAside(projectId, agentId);
this.agents.delete(projectId, agentId);
+ if (deletionId === null) {
+ // The folder was already gone: there is nothing to remove.
+ return { deletionId: `${agentId}-0`, agentId, phase: "done", total: 0, removed: 0 };
+ }
+ return this.startPurge(projectId, deletionId, agentId);
+ }
+
+ agentDeletion(projectId: string, deletionId: string): AgentDeletionInfo | null {
+ const known = this.deletions.get(`${projectId}/${deletionId}`);
+ return known ? { ...known } : null;
+ }
+
+ /**
+ * Every folder left under a Project's `agents/.deleting/` — a deletion the last process did
+ * not finish, or one that met an entry it could not remove — is removed again, one after
+ * another. Folders a deletion of this process is already removing are left to it.
+ */
+ async resumeDeletions(): Promise<void> {
+ let projects: Dirent[] = [];
+ try {
+ projects = await fs.readdir(this.root, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const project of projects) {
+ if (!project.isDirectory() || !isValidId(project.name)) continue;
+ let entries: string[] = [];
+ try {
+ entries = await fs.readdir(deletingDir(this.root, project.name));
+ } catch {
+ continue;
+ }
+ for (const name of entries) {
+ if (this.stopping.signal.aborted) return;
+ if (!isValidId(name)) continue;
+ const known = this.deletions.get(`${project.name}/${name}`);
+ if (known && (known.phase === "counting" || known.phase === "removing")) continue;
+ const agentId = DELETION_NAME.exec(name)?.[1] ?? name;
+ this.startPurge(project.name, name, agentId);
+ await this.running.get(`${project.name}/${name}`);
+ }
+ }
+ }
+
+ /**
+ * Renames the Agent's folder into `.deleting/`. Null when there was no folder to move; a
+ * folder a program keeps holding is refused with nothing moved.
+ */
+ private async moveAside(projectId: string, agentId: string): Promise<string | null> {
+ const from = agentDir(this.root, projectId, agentId);
+ const trash = deletingDir(this.root, projectId);
+ await fs.mkdir(trash, { recursive: true });
+ const deletionId = `${agentId}-${Date.now()}`;
+ for (let attempt = 0; ; attempt++) {
+ try {
+ await fs.rename(from, path.join(trash, deletionId));
+ return deletionId;
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code ?? "";
+ if (code === "ENOENT") return null;
+ if (!MOVE_BUSY.has(code)) throw err;
+ if (attempt >= MOVE_RETRIES) {
+ throw new HttpError(
+ 409,
+ "agent_folder_busy",
+ `The agent's folder could not be moved aside (${code}): another program may have a file in it open. Nothing was deleted.`,
+ );
+ }
+ await new Promise((resolve) => setTimeout(resolve, MOVE_RETRY_STEP_MS * (attempt + 1)));
+ }
+ }
+ }
+
+ /** Starts removing `.deleting/<deletionId>` in the background; answers its first reading. */
+ private startPurge(projectId: string, deletionId: string, agentId: string): AgentDeletionInfo {
+ const key = `${projectId}/${deletionId}`;
+ const info: AgentDeletionInfo = {
+ deletionId,
+ agentId,
+ phase: "counting",
+ total: 0,
+ removed: 0,
+ };
+ this.deletions.set(key, info);
+ const dir = path.join(deletingDir(this.root, projectId), deletionId);
+ const signal = this.stopping.signal;
+ const run = (async () => {
+ try {
+ const total = await countEntries(dir, {
+ limiter: this.limiter,
+ signal,
+ onCount: (n) => {
+ info.total = n;
+ },
+ });
+ if (signal.aborted) return;
+ info.total = total;
+ info.phase = "removing";
+ const failure = await purgeTree(dir, {
+ limiter: this.limiter,
+ signal,
+ onRemoved: () => {
+ info.removed += 1;
+ },
+ });
+ if (signal.aborted) return;
+ if (failure === null) {
+ info.phase = "done";
+ // Something added under the folder after it was counted would read past the total.
+ info.total = Math.max(info.total, info.removed);
+ } else {
+ info.phase = "failed";
+ info.error = failure.error;
+ }
+ } catch (err) {
+ info.phase = "failed";
+ info.error = err instanceof Error ? err.message : String(err);
+ } finally {
+ this.running.delete(key);
+ if (info.phase === "done" || info.phase === "failed") {
+ setTimeout(() => {
+ if (this.deletions.get(key) === info) this.deletions.delete(key);
+ }, FINISHED_DELETION_TTL_MS).unref?.();
+ }
+ }
+ })();
+ this.running.set(key, run);
+ return { ...info };
}
/**
diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.ts
index 4178f6b8..cf5dd7e9 100644
--- a/packages/server/src/services/session-service.ts
+++ b/packages/server/src/services/session-service.ts
@@ -828,6 +828,8 @@ export class SessionService {
for (const projectId of await listChildDirs(this.deps.root)) {
const agentIds = await listChildDirs(agentsDir(this.deps.root, projectId));
for (const agentId of agentIds) {
+ // A dot-directory (`.deleting/`, where a deleted Agent's files wait) is never an Agent.
+ if (agentId.startsWith(".")) continue;
const known = new Set(
this.deps.sessions.listByAgent(projectId, agentId).map((r) => r.sessionId),
);
diff --git a/packages/server/src/services/trace-index.ts b/packages/server/src/services/trace-index.ts
index b44ebc74..bcd0ac82 100644
--- a/packages/server/src/services/trace-index.ts
+++ b/packages/server/src/services/trace-index.ts
@@ -169,6 +169,8 @@ export class TraceIndexService implements TraceIndex {
/** Reconciles every Agent of a Project (the subagent-pointer resolver's miss path). */
async reconcileProject(projectId: string, opts: { force?: boolean } = {}): Promise<void> {
for (const agentId of await listDirs(agentsDir(this.root, projectId))) {
+ // A dot-directory (`.deleting/`, where a deleted Agent's files wait) is never an Agent.
+ if (agentId.startsWith(".")) continue;
await this.reconcileAgent(projectId, agentId, opts);
}
}
diff --git a/packages/server/src/services/tree-purge.ts b/packages/server/src/services/tree-purge.ts
new file mode 100644
index 00000000..4f0dd18c
--- /dev/null
+++ b/packages/server/src/services/tree-purge.ts
@@ -0,0 +1,219 @@
+/**
+ * Removing a large directory tree without stalling the server.
+ *
+ * `fs.promises.rm(dir, { recursive: true })` walks the tree by starting the removal of every
+ * child of a directory at once, all the way down: a folder of a hundred thousand files puts a
+ * hundred thousand requests in libuv's thread pool queue together. That queue is shared by every
+ * file read the server makes (a page's list, a static asset, a Trace), and it is first in, first
+ * out — so each of those waits behind the whole tree, and the server looks frozen for as long as
+ * the removal takes. The walk here keeps at most `concurrency` filesystem calls of its own in
+ * flight across every purge sharing a `FsLimiter`, so any other request waits behind a handful of
+ * them at most.
+ *
+ * Two passes, each reporting as it goes: `countEntries` learns how much there is, so a reader can
+ * be shown how far along the removal is; `purgeTree` then removes files before the directory that
+ * held them, depth first. A symbolic link is removed as a link and never followed. An entry that
+ * is already gone counts as removed: another purge of the same tree (a successor process taking
+ * over) may have got there first. An entry that cannot be removed is skipped and reported, and
+ * its directories stay behind, so a later purge of the same tree can try again.
+ */
+import fs from "node:fs/promises";
+import type { Dirent } from "node:fs";
+import path from "node:path";
+
+/** At most `slots` calls run at once; the rest wait their turn, first come first served. */
+export class FsLimiter {
+ private active = 0;
+ private readonly waiting: (() => void)[] = [];
+
+ constructor(private readonly slots: number) {}
+
+ async run<T>(fn: () => Promise<T>): Promise<T> {
+ if (this.active >= this.slots) {
+ await new Promise<void>((resolve) => this.waiting.push(resolve));
+ } else {
+ this.active += 1;
+ }
+ try {
+ return await fn();
+ } finally {
+ const next = this.waiting.shift();
+ // The slot passes straight to the next waiter, so `active` stays counted for it.
+ if (next) next();
+ else this.active -= 1;
+ }
+ }
+}
+
+/** What a purge could not remove: how many entries, and the first error, as the OS worded it. */
+export interface PurgeFailure {
+ failed: number;
+ error: string;
+}
+
+export interface PurgeOptions {
+ limiter: FsLimiter;
+ /** Stops the walk between calls; whatever is left stays on disk for a later purge. */
+ signal?: AbortSignal;
+}
+
+const code = (err: unknown): string | undefined => (err as NodeJS.ErrnoException).code;
+
+/**
+ * Windows reports a file or folder another program has open as busy or not permitted, and lets go
+ * of it a moment later more often than not (an indexer, an antivirus scan): the same few retries
+ * Node's own `rm` makes before giving up.
+ */
+const RETRYABLE = new Set(["EBUSY", "EPERM", "EACCES", "ENOTEMPTY", "EMFILE", "ENFILE"]);
+const RETRIES = 3;
+/** Files of one directory removed side by side; the limiter still caps what actually runs. */
+const FILE_LANES = 8;
+const RETRY_STEP_MS = 100;
+
+async function withRetries(fn: () => Promise<void>): Promise<void> {
+ for (let attempt = 0; ; attempt++) {
+ try {
+ await fn();
+ return;
+ } catch (err) {
+ if (code(err) === "ENOENT") return;
+ if (attempt >= RETRIES || !RETRYABLE.has(code(err) ?? "")) throw err;
+ await new Promise((resolve) => setTimeout(resolve, RETRY_STEP_MS * (attempt + 1)));
+ }
+ }
+}
+
+async function readEntries(dir: string, limiter: FsLimiter): Promise<Dirent[]> {
+ try {
+ return await limiter.run(() => fs.readdir(dir, { withFileTypes: true }));
+ } catch (err) {
+ if (code(err) === "ENOENT" || code(err) === "ENOTDIR") return [];
+ throw err;
+ }
+}
+
+/** Runs `fn` over `items` with at most `width` of them in progress, in order of starting. */
+async function eachLimited<T>(
+ items: readonly T[],
+ width: number,
+ fn: (item: T) => Promise<void>,
+): Promise<void> {
+ let next = 0;
+ const lanes = Array.from({ length: Math.min(width, items.length) }, async () => {
+ while (next < items.length) {
+ const item = items[next++]!;
+ await fn(item);
+ }
+ });
+ await Promise.all(lanes);
+}
+
+/**
+ * How many entries `root` holds, itself included: what `purgeTree` will report as removed once it
+ * has removed all of it. `onCount` hears the running total after each directory is read.
+ */
+export async function countEntries(
+ root: string,
+ opts: PurgeOptions & { onCount?: (total: number) => void },
+): Promise<number> {
+ let total = 0;
+ const walk = async (dir: string): Promise<void> => {
+ if (opts.signal?.aborted) return;
+ const entries = await readEntries(dir, opts.limiter);
+ total += entries.length;
+ opts.onCount?.(total);
+ // Directories one at a time, depth first: lanes per level would multiply with the depth.
+ for (const e of entries) if (e.isDirectory()) await walk(path.join(dir, e.name));
+ };
+ try {
+ await opts.limiter.run(() => fs.lstat(root));
+ } catch (err) {
+ if (code(err) === "ENOENT") return 0;
+ throw err;
+ }
+ total = 1;
+ await walk(root);
+ return total;
+}
+
+/**
+ * Removes `root` and everything under it. `onRemoved` hears each entry as it goes. Resolves with
+ * what could not be removed (its error naming the entry by its path under `root`), or null when
+ * nothing is left; never rejects for an entry it could not remove (only an abort ends it early,
+ * leaving the rest).
+ */
+export async function purgeTree(
+ root: string,
+ opts: PurgeOptions & { onRemoved?: () => void },
+): Promise<PurgeFailure | null> {
+ let failed = 0;
+ let firstError = "";
+ const fail = (err: unknown): void => {
+ failed += 1;
+ if (firstError !== "") return;
+ // The OS names the entry by its absolute path; inside the tree, its place in it says more.
+ const message = err instanceof Error ? err.message : String(err);
+ firstError = message.split(root + path.sep).join("");
+ };
+ const removed = (): void => opts.onRemoved?.();
+
+ const unlink = async (file: string): Promise<void> => {
+ try {
+ await withRetries(() =>
+ opts.limiter.run(async () => {
+ try {
+ await fs.unlink(file);
+ } catch (err) {
+ // A read-only file on Windows refuses to be unlinked until it is made writable.
+ if (code(err) !== "EPERM" && code(err) !== "EACCES") throw err;
+ await fs.chmod(file, 0o666).catch(() => undefined);
+ await fs.unlink(file);
+ }
+ }),
+ );
+ removed();
+ } catch (err) {
+ fail(err);
+ }
+ };
+
+ /** Removes `dir`'s contents and then `dir`; false when something under it stayed behind. */
+ const walk = async (dir: string): Promise<boolean> => {
+ let entries: Dirent[];
+ try {
+ entries = await readEntries(dir, opts.limiter);
+ } catch (err) {
+ fail(err);
+ return false;
+ }
+ const before = failed;
+ const files = entries.filter((e) => !e.isDirectory()).map((e) => path.join(dir, e.name));
+ await eachLimited(files, FILE_LANES, async (file) => {
+ if (!opts.signal?.aborted) await unlink(file);
+ });
+ for (const e of entries) {
+ if (e.isDirectory() && !opts.signal?.aborted) await walk(path.join(dir, e.name));
+ }
+ if (opts.signal?.aborted || failed > before) return false;
+ try {
+ await withRetries(() => opts.limiter.run(() => fs.rmdir(dir)));
+ removed();
+ return true;
+ } catch (err) {
+ fail(err);
+ return false;
+ }
+ };
+
+ let stat;
+ try {
+ stat = await opts.limiter.run(() => fs.lstat(root));
+ } catch (err) {
+ if (code(err) === "ENOENT") return null;
+ fail(err);
+ return { failed, error: firstError };
+ }
+ if (stat.isDirectory()) await walk(root);
+ else await unlink(root);
+ return failed > 0 ? { failed, error: firstError } : null;
+}
diff --git a/packages/server/test/agent-api-settings.test.ts b/packages/server/test/agent-api-settings.test.ts
index ee7ce943..5f9991e6 100644
--- a/packages/server/test/agent-api-settings.test.ts
+++ b/packages/server/test/agent-api-settings.test.ts
@@ -184,7 +184,7 @@ describe("Agent API settings", () => {
const { secret } = (await (
await owner.post(`${tab("short_lived")}/keys`, { name: "k" })
).json()) as AgentApiKeyCreateResponse;
- expect((await owner.delete(`/api/projects/${projectId}/agents/short_lived`)).status).toBe(204);
+ expect((await owner.delete(`/api/projects/${projectId}/agents/short_lived`)).status).toBe(202);
await owner.post(`/api/projects/${projectId}/agents`, { agentId: "short_lived" });
expect(await read(owner, "short_lived")).toEqual({
diff --git a/packages/server/test/agent-delete-background.test.ts b/packages/server/test/agent-delete-background.test.ts
new file mode 100644
index 00000000..9e67ba0c
--- /dev/null
+++ b/packages/server/test/agent-delete-background.test.ts
@@ -0,0 +1,245 @@
+/**
+ * Deleting an Agent whose folder is large, over the real app on a real temp root.
+ *
+ * - Given an Agent with a temporary Workspace full of files, when its owner deletes it, the
+ * answer (202) comes once the folder has left the agents directory: the Agent is in no list,
+ * no route accepts it, and its id can be taken again at once. The deletion then reports its
+ * removal to the end — the readings never go back, every entry counted is removed, and nothing
+ * of the old folder is left — while the new Agent under the same id is not touched.
+ * - Given an entry the removal cannot remove, the Agent is still gone for the user; the deletion
+ * ends `failed` with the operating system's reason, naming the entry by its place in the folder,
+ * and what is left waits under `.deleting/`.
+ * The next start removes what is left, under the same deletion id — here the boot's own call is
+ * made directly (`resumeDeletions()`), because this suite's helper has no restart.
+ * - Given a folder that cannot be moved, the delete is refused with 409 `agent_folder_busy` and
+ * nothing is deleted: the Agent still lists, opens, and keeps its Sessions.
+ * - Given an index row whose folder lost its system_config.yaml (a delete an earlier server did
+ * not finish), the list leaves it out, so every listed Agent opens.
+ */
+import fs from "node:fs/promises";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import { agentDir, systemConfigPath } from "@adelie/core";
+import type {
+ AgentDeleteResponse,
+ AgentDeletionInfo,
+ AgentDeletionResponse,
+ AgentsResponse,
+} from "../src/api/types.js";
+import { deletingDir } from "../src/services/agent-service.js";
+import { apiClient, createTestApp, provisionUser } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+const PROJECT = "olivia-default_project";
+/** Permission bits do not stop root, and mean something else on Windows. */
+const permissionsHold = process.platform !== "win32" && process.getuid?.() !== 0;
+
+describe("deleting a large Agent", () => {
+ let t: TestApp;
+ let cookie: string;
+ let api: ReturnType<typeof apiClient>;
+ const agentsPath = `/api/projects/${PROJECT}/agents`;
+ const root = () => t.deps.config.root;
+
+ beforeAll(async () => {
+ t = await createTestApp();
+ cookie = (await provisionUser(t.app, "olivia")).cookie;
+ api = apiClient(t.app, cookie);
+ });
+
+ afterAll(async () => {
+ await t.cleanup();
+ });
+
+ async function createAgent(agentId: string): Promise<void> {
+ expect((await api.post(agentsPath, { agentId })).status).toBe(201);
+ }
+
+ async function listed(): Promise<string[]> {
+ const res = await api.get(agentsPath);
+ expect(res.status).toBe(200);
+ return ((await res.json()) as AgentsResponse).agents.map((a) => a.agentId);
+ }
+
+ /** A temporary Workspace the way an install leaves one: many small files in nested folders. */
+ async function fillWorkspace(agentId: string, dirs: number, filesPerDir: number): Promise<void> {
+ const base = path.join(agentDir(root(), PROJECT, agentId), "workspaces", "ws_big");
+ for (let d = 0; d < dirs; d++) {
+ const dir = path.join(base, "node_modules", `pkg${d % 7}`, `lib${d}`);
+ await fs.mkdir(dir, { recursive: true });
+ for (let f = 0; f < filesPerDir; f++) {
+ await fs.writeFile(path.join(dir, `f${f}.js`), "module.exports = 1;\n");
+ }
+ }
+ }
+
+ /** Every entry under `dir`, `dir` itself included. */
+ async function countTree(dir: string): Promise<number> {
+ let n = 1;
+ for (const e of await fs.readdir(dir, { withFileTypes: true })) {
+ n += e.isDirectory() ? await countTree(path.join(dir, e.name)) : 1;
+ }
+ return n;
+ }
+
+ async function reading(deletionId: string, client = api): Promise<AgentDeletionInfo> {
+ const res = await client.get(`/api/projects/${PROJECT}/agent-deletions/${deletionId}`);
+ expect(res.status).toBe(200);
+ return ((await res.json()) as AgentDeletionResponse).deletion;
+ }
+
+ /** Reads the deletion until it is over; every reading on the way, oldest first. */
+ async function readUntilOver(deletionId: string, client = api): Promise<AgentDeletionInfo[]> {
+ const seen: AgentDeletionInfo[] = [];
+ await vi.waitFor(
+ async () => {
+ const now = await reading(deletionId, client);
+ seen.push(now);
+ expect(["done", "failed"]).toContain(now.phase);
+ },
+ { timeout: 20_000, interval: 5 },
+ );
+ return seen;
+ }
+
+ const exists = (p: string) =>
+ fs.access(p).then(
+ () => true,
+ () => false,
+ );
+
+ it("lists only Agents the routes accept: a row whose folder lost its config is left out", async () => {
+ await createAgent("half_gone");
+ await fillWorkspace("half_gone", 2, 3);
+ // What an interrupted recursive delete left: the small agent_state/ went first.
+ await fs.rm(path.dirname(systemConfigPath(root(), PROJECT, "half_gone")), {
+ recursive: true,
+ });
+
+ const ids = await listed();
+ expect(ids).not.toContain("half_gone");
+ for (const id of ids) {
+ expect((await api.get(`${agentsPath}/${id}/config`)).status).toBe(200);
+ }
+ });
+
+ it.skipIf(!permissionsHold)(
+ "refuses a folder that cannot be moved, and deletes nothing",
+ async () => {
+ await createAgent("pinned_one");
+ const sessionId = "session-2026-10-26-09-00-00-0abc0001";
+ t.deps.sessionsRepo.insert({
+ sessionId,
+ projectId: PROJECT,
+ agentId: "pinned_one",
+ provider: "custom",
+ modelId: "m-dev",
+ workspace: "/tmp",
+ approvalMode: "allow-all",
+ title: null,
+ client: "web",
+ createdAt: "2026-10-26T09:00:00.000Z",
+ lastActiveAt: "2026-10-26T09:00:00.000Z",
+ });
+ const agents = path.dirname(agentDir(root(), PROJECT, "pinned_one"));
+ await fs.mkdir(deletingDir(root(), PROJECT), { recursive: true });
+ // A directory nobody may write to: nothing can be moved out of it.
+ await fs.chmod(agents, 0o555);
+ let res: Response;
+ try {
+ res = await api.delete(`${agentsPath}/pinned_one`);
+ } finally {
+ await fs.chmod(agents, 0o755);
+ }
+
+ expect(res.status).toBe(409);
+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe(
+ "agent_folder_busy",
+ );
+ expect(await listed()).toContain("pinned_one");
+ expect((await api.get(`${agentsPath}/pinned_one/config`)).status).toBe(200);
+ expect(t.deps.sessionsRepo.findById(sessionId)).not.toBeNull();
+ },
+ );
+
+ it("takes the Agent off every list at once, frees its id, and removes its files in the background", async () => {
+ await createAgent("big_one");
+ await fillWorkspace("big_one", 40, 25);
+ const folder = agentDir(root(), PROJECT, "big_one");
+ const entries = await countTree(folder);
+
+ const res = await api.delete(`${agentsPath}/big_one`);
+ expect(res.status).toBe(202);
+ const { deletion } = (await res.json()) as AgentDeleteResponse;
+ expect(deletion.agentId).toBe("big_one");
+
+ expect(await exists(folder)).toBe(false);
+ expect(await listed()).not.toContain("big_one");
+ expect((await api.get(`${agentsPath}/big_one/config`)).status).toBe(404);
+ // The id is free while the old files are still being removed.
+ await createAgent("big_one");
+
+ const seen = await readUntilOver(deletion.deletionId);
+ const last = seen[seen.length - 1]!;
+ expect(last).toMatchObject({ phase: "done", total: entries, removed: entries });
+ const removed = [deletion, ...seen].map((r) => r.removed);
+ expect(removed).toEqual([...removed].sort((a, b) => a - b));
+ expect(await exists(path.join(deletingDir(root(), PROJECT), deletion.deletionId))).toBe(false);
+ // The removal stayed inside the old folder: the new Agent under the same id is whole.
+ expect(await exists(systemConfigPath(root(), PROJECT, "big_one"))).toBe(true);
+ expect(await listed()).toContain("big_one");
+ });
+
+ it.skipIf(!permissionsHold)(
+ "keeps what it cannot remove for the next start, which removes it",
+ async () => {
+ await createAgent("stuck_one");
+ const locked = path.join(agentDir(root(), PROJECT, "stuck_one"), "workspaces", "locked");
+ await fs.mkdir(locked, { recursive: true });
+ await fs.writeFile(path.join(locked, "keep.txt"), "x");
+ // No write permission on the folder: its file cannot be unlinked.
+ await fs.chmod(locked, 0o555);
+
+ const res = await api.delete(`${agentsPath}/stuck_one`);
+ expect(res.status).toBe(202);
+ const { deletion } = (await res.json()) as AgentDeleteResponse;
+ const last = (await readUntilOver(deletion.deletionId)).pop()!;
+ expect(last.phase).toBe("failed");
+ expect(last.error).toMatch(/EACCES|EPERM/);
+ // The entry is named by its place in the agent's folder, not by the data root's path.
+ expect(last.error).toContain(`'${path.join("workspaces", "locked", "keep.txt")}'`);
+ expect(last.error).not.toContain(root());
+ expect(await listed()).not.toContain("stuck_one");
+ const left = path.join(deletingDir(root(), PROJECT), deletion.deletionId);
+ expect(await exists(path.join(left, "workspaces", "locked", "keep.txt"))).toBe(true);
+
+ // Whatever held the file let go while the server was down; the next start picks the
+ // leftovers up. `resumeDeletions()` is exactly what the boot calls (see platform.ts), so
+ // calling it here is the same walk without a second App on the same root.
+ await fs.chmod(path.join(left, "workspaces", "locked"), 0o755);
+ await t.deps.agentService.resumeDeletions();
+ const resumed = (await readUntilOver(deletion.deletionId)).pop()!;
+ expect(resumed.phase).toBe("done");
+ expect(await exists(left)).toBe(false);
+ },
+ );
+
+ it("removes a leftover folder the last process did not finish, when the next start looks", async () => {
+ // What a process killed mid-delete leaves: the folder under `.deleting/` and no index row.
+ // Written by hand rather than by a kill, so this half runs without permission bits (the two
+ // cases above need them, and root ignores them).
+ await createAgent("left_behind");
+ const folder = agentDir(root(), PROJECT, "left_behind");
+ const deletionId = `left_behind-${Date.now()}`;
+ await fs.mkdir(deletingDir(root(), PROJECT), { recursive: true });
+ await fs.rename(folder, path.join(deletingDir(root(), PROJECT), deletionId));
+ expect(await exists(folder)).toBe(false); // moved, not copied
+ // The row the last process did not get to drop is not listed either: its folder is no Agent.
+ expect(await listed()).not.toContain("left_behind");
+
+ await t.deps.agentService.resumeDeletions();
+ const reading = (await readUntilOver(deletionId)).pop()!;
+ expect(reading).toMatchObject({ phase: "done", agentId: "left_behind" });
+ expect(await exists(path.join(deletingDir(root(), PROJECT), deletionId))).toBe(false);
+ });
+});
diff --git a/packages/server/test/builtin-agents.test.ts b/packages/server/test/builtin-agents.test.ts
index af9cbd5a..e77b7e6d 100644
--- a/packages/server/test/builtin-agents.test.ts
+++ b/packages/server/test/builtin-agents.test.ts
@@ -152,6 +152,6 @@ describe("built-in Agent provisioning", () => {
});
expect(created.status).toBe(201);
const res = await owner.delete(`/api/projects/${projectId}/agents/agent_creator`);
- expect(res.status).toBe(204);
+ expect(res.status).toBe(202);
});
});
diff --git a/packages/server/test/workspace-files.test.ts b/packages/server/test/workspace-files.test.ts
index 3a3314a5..dc6c57ae 100644
--- a/packages/server/test/workspace-files.test.ts
+++ b/packages/server/test/workspace-files.test.ts
@@ -746,7 +746,7 @@ describe("agent delete route", () => {
// A name per attempt: the Project is the file's, so a retry must not meet its own Agent.
let temps = 0;
- it("owner deletes an Agent: 204, the directory and list entry disappear; default_agent 409; outsiders 404", async () => {
+ it("owner deletes an Agent: 202, the directory and list entry disappear; default_agent 409; outsiders 404", async () => {
temps += 1;
const created = (await (
await owner.post(`/api/projects/${projectId}/agents`, {
@@ -762,7 +762,7 @@ describe("agent delete route", () => {
expect(outsiderRes.status).toBe(404); // no access → don't leak existence
const res = await owner.delete(`/api/projects/${projectId}/agents/${agentId}`);
- expect(res.status).toBe(204);
+ expect(res.status).toBe(202);
await expect(fs.access(dir)).rejects.toThrow();
const list = (await (await owner.get(`/api/projects/${projectId}/agents`)).json()) as {
agents: Array<{ agentId: string }>;
diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.ts
index 92925ed3..fe46f562 100644
--- a/packages/ui-gallery/src/app/mock/routes.ts
+++ b/packages/ui-gallery/src/app/mock/routes.ts
@@ -17,6 +17,8 @@ import type {
AgentApiSettings,
AgentConfigResponse,
AgentCreateResponse,
+ AgentDeleteResponse,
+ AgentDeletionInfo,
AgentHooksResponse,
AgentKernelUpdateResponse,
AgentPluginsInstallResponse,
@@ -1059,8 +1061,20 @@ router
if (agent.agentId === IDS.agents.docs)
fail(409, "agent_builtin", "The docs Agent is the demo's; it stays.");
ctx.store.f.agents = ctx.store.f.agents.filter((a) => a.agentId !== agent.agentId);
- return empty();
- });
+ // The demo has no files to remove: the deletion is over as it answers.
+ const deletion: AgentDeletionInfo = {
+ deletionId: `${agent.agentId}-0`,
+ agentId: agent.agentId,
+ phase: "done",
+ total: 0,
+ removed: 0,
+ };
+ return json({ deletion } satisfies AgentDeleteResponse, 202);
+ })
+ // No removal ever runs in the background here, so no deletion is known.
+ .get("/api/projects/:projectId/agent-deletions/:deletionId", () =>
+ fail(404, "agent_deletion_not_found", "No such deletion is in progress."),
+ );
// ---------------------------------------------------------------------------------------------
// An Agent's public API: its switches, approval mode and keys (the stream itself is not mocked)
diff --git a/packages/ui/src/components/overlays/progress-toasts/progress-toasts.tsx b/packages/ui/src/components/overlays/progress-toasts/progress-toasts.tsx
new file mode 100644
index 00000000..7cdf2af8
--- /dev/null
+++ b/packages/ui/src/components/overlays/progress-toasts/progress-toasts.tsx
@@ -0,0 +1,225 @@
+/**
+ * Long operations in the corner: a card per operation that takes noticeable time — a title, a
+ * bar, a line of figures — which keeps the user informed while the work goes on elsewhere, and
+ * which they can close at any point without stopping it.
+ *
+ * Raise one from anywhere with `startProgress({ title })`, then drive it through the handle it
+ * returns: `update` as readings arrive, `finish` once the work is over (`failed` for a stop short),
+ * and `closed` to learn whether the user has let it go. One `<ProgressToasts />` mounted at the app
+ * root draws them. The words are the caller's; the package adds only the close cross's name.
+ *
+ * An operation is shown only once it has run for `PROGRESS_REVEAL_MS`: one that ends sooner never
+ * appears, since a card flashing up and away says nothing the result does not. A shown card that
+ * finishes well stays for `PROGRESS_DONE_STAY_MS` with its finishing words and a full bar, then
+ * leaves; one that fails stays until closed, since its words need reading. Without `value` the bar
+ * is indeterminate (a phase with no amount yet, such as counting).
+ *
+ * The stack sits at the bottom right — clear of the toasts at the top centre — across the width
+ * at phone size, portaled above dialogs like the toasts. It lets the pointer through and only the
+ * cards take it. A visually hidden polite live region reads each shown card's title, which the
+ * caller changes on the transitions that matter (started, finished, failed); the figures update
+ * too often to be read out and stay in the bar and the visible line.
+ */
+import { useEffect, useRef } from "react";
+import { createPortal } from "react-dom";
+import { useStore } from "zustand/react";
+import { createStore } from "zustand/vanilla";
+import { CloseButton } from "../../actions/close-button/close-button";
+import { ProgressBar } from "../../feedback/progress-bar/progress-bar";
+
+export type ProgressState = "running" | "done" | "failed";
+
+export interface ProgressItem {
+ id: number;
+ title: string;
+ /** The line under the bar: what is being done, in figures. */
+ detail?: string;
+ /** How far along, out of `max`; absent while there is no amount to show. */
+ value?: number;
+ max?: number;
+ state: ProgressState;
+ /** On screen: false until the operation has run for `PROGRESS_REVEAL_MS`. */
+ shown: boolean;
+ /** Leaving: plays the exit, then is removed. */
+ leaving?: boolean;
+}
+
+/** What `update` and `finish` change. */
+export interface ProgressPatch {
+ title?: string;
+ detail?: string;
+ value?: number;
+ max?: number;
+}
+
+export interface ProgressHandle {
+ update(patch: ProgressPatch): void;
+ /** The work is over: `failed` keeps the card until it is closed. */
+ finish(patch?: ProgressPatch & { failed?: boolean }): void;
+ /** Takes the card away now. */
+ close(): void;
+ /** True once the card is gone — closed by the user, by `close`, or after finishing. */
+ readonly closed: boolean;
+}
+
+/** How long an operation runs before its card appears, ms. */
+export const PROGRESS_REVEAL_MS = 600;
+/** How long a card that finished well stays, ms. */
+export const PROGRESS_DONE_STAY_MS = 4000;
+/**
+ * How long a leaving card waits for its exit animation before it is removed anyway, ms: under
+ * reduced motion, or a theme that jumps, no animation runs and none reports its end. Past every
+ * theme's exit duration.
+ */
+const LEAVE_FALLBACK_MS = 400;
+
+/** The operations, oldest first, shown or not. Drive them through `startProgress`. */
+export const progressStore = createStore<{ items: ProgressItem[] }>(() => ({ items: [] }));
+let nextId = 1;
+
+const find = (id: number): ProgressItem | undefined =>
+ progressStore.getState().items.find((i) => i.id === id);
+
+function patchItem(id: number, patch: Partial<ProgressItem>): void {
+ progressStore.setState((s) => ({
+ items: s.items.map((i) => (i.id === id ? { ...i, ...patch } : i)),
+ }));
+}
+
+function remove(id: number): void {
+ progressStore.setState((s) => ({ items: s.items.filter((i) => i.id !== id) }));
+}
+
+/**
+ * Takes a card away — what its close cross does: plays the exit of a shown card, or drops one
+ * never shown at once. The operation behind it goes on; its handle reads `closed` from then on.
+ */
+export function closeProgress(id: number): void {
+ const item = find(id);
+ if (!item || item.leaving) return;
+ if (!item.shown) {
+ remove(id);
+ return;
+ }
+ patchItem(id, { leaving: true });
+ setTimeout(() => remove(id), LEAVE_FALLBACK_MS);
+}
+
+/** Starts an operation's card; it appears once the operation has run for `PROGRESS_REVEAL_MS`. */
+export function startProgress(init: ProgressPatch & { title: string }): ProgressHandle {
+ const id = nextId++;
+ progressStore.setState((s) => ({
+ items: [...s.items, { ...init, id, state: "running", shown: false }],
+ }));
+ setTimeout(() => {
+ const item = find(id);
+ if (item && item.state === "running" && !item.leaving) patchItem(id, { shown: true });
+ }, PROGRESS_REVEAL_MS);
+ return {
+ update(patch) {
+ const item = find(id);
+ if (item && item.state === "running" && !item.leaving) patchItem(id, patch);
+ },
+ finish({ failed = false, ...patch } = {}) {
+ const item = find(id);
+ if (!item || item.state !== "running" || item.leaving) return;
+ if (!item.shown && !failed) {
+ // Over before anyone saw it: nothing to report that the result does not say.
+ remove(id);
+ return;
+ }
+ patchItem(id, { ...patch, state: failed ? "failed" : "done", shown: true });
+ if (!failed) setTimeout(() => closeProgress(id), PROGRESS_DONE_STAY_MS);
+ },
+ close() {
+ closeProgress(id);
+ },
+ get closed() {
+ const item = find(id);
+ return item === undefined || item.leaving === true;
+ },
+ };
+}
+
+const TONE: Readonly<Record<ProgressState, "accent" | "success" | "danger">> = {
+ running: "accent",
+ done: "success",
+ failed: "danger",
+};
+
+/** One card as it is drawn. */
+function ProgressCard({ item, onClose }: { item: ProgressItem; onClose: () => void }) {
+ const box = useRef<HTMLDivElement>(null);
+ // No exit plays under reduced motion or in a theme that jumps: the card goes at once rather
+ // than standing still until the fallback.
+ useEffect(() => {
+ if (item.leaving && box.current && getComputedStyle(box.current).animationName === "none") {
+ remove(item.id);
+ }
+ }, [item.leaving, item.id]);
+ // A finished operation reads as complete whatever its last reading was.
+ const value = item.state === "done" ? (item.max ?? 1) : item.value;
+ return (
+ <div
+ ref={box}
+ data-presence={item.leaving ? "exit" : "enter"}
+ data-side="bottom"
+ onAnimationEnd={(e) => {
+ if (item.leaving && e.target === e.currentTarget) remove(item.id);
+ }}
+ className="pointer-events-auto w-full rounded-lg border border-line bg-overlay px-3 py-2.5 shadow-lg sm:w-80"
+ >
+ <div className="flex items-start gap-2">
+ <p className="min-w-0 flex-1 break-words text-sm font-medium text-fg">{item.title}</p>
+ <CloseButton onClose={onClose} className="-my-1 -mr-1.5 shrink-0" />
+ </div>
+ <ProgressBar
+ label={item.title}
+ value={value}
+ max={item.state === "done" ? (item.max ?? 1) : item.max}
+ indeterminate={item.state === "running" && item.value === undefined}
+ tone={TONE[item.state]}
+ className="mt-2"
+ />
+ {item.detail !== undefined && item.detail !== "" && (
+ <p
+ className={`mt-1.5 break-words text-xs tabular-nums ${item.state === "failed" ? "text-tone-danger-fg" : "text-fg-muted"}`}
+ >
+ {item.detail}
+ </p>
+ )}
+ </div>
+ );
+}
+
+/** The stack as it is drawn, without the portal: what `ProgressToasts` renders into the body. */
+export function ProgressStack({
+ items,
+ onClose,
+}: {
+ items: readonly ProgressItem[];
+ onClose: (id: number) => void;
+}) {
+ const shown = items.filter((i) => i.shown);
+ return (
+ <div className="pointer-events-none fixed inset-x-4 bottom-4 z-[100] flex flex-col items-end gap-2 sm:left-auto">
+ <p className="sr-only" aria-live="polite">
+ {shown
+ .filter((i) => !i.leaving)
+ .map((i) => i.title)
+ .join(". ")}
+ </p>
+ {shown.map((item) => (
+ <ProgressCard key={item.id} item={item} onClose={() => onClose(item.id)} />
+ ))}
+ </div>
+ );
+}
+
+/** The operations' stack: mount once at the app root. */
+export function ProgressToasts() {
+ const items = useStore(progressStore, (s) => s.items);
+ // A static render has no document to portal into, and nothing to show there.
+ if (typeof document === "undefined") return null;
+ return createPortal(<ProgressStack items={items} onClose={closeProgress} />, document.body);
+}
diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts
index 8b103819..9fe80a31 100644
--- a/packages/ui/src/index.ts
+++ b/packages/ui/src/index.ts
@@ -98,6 +98,7 @@ export * from "./motion/use-reduced-motion";
// (with the `toast*` functions and their store).
export * from "./components/feedback/notice/notice-strip";
export * from "./components/overlays/toaster/toaster";
+export * from "./components/overlays/progress-toasts/progress-toasts";
// W5 — content: Markdown as reading text and its pipeline, the code surface and block with the
// language tables, the type roles, and the diff viewer. The Shiki engine is not here: it is the
diff --git a/packages/ui/test/progress-toasts.test.ts b/packages/ui/test/progress-toasts.test.ts
new file mode 100644
index 00000000..c827d96c
--- /dev/null
+++ b/packages/ui/test/progress-toasts.test.ts
@@ -0,0 +1,138 @@
+/**
+ * The long-operation cards (src/components/overlays/progress-toasts/progress-toasts.tsx): when a
+ * card appears and leaves, what its handle may still change, and the stack as it is drawn.
+ *
+ * - Given an operation that ends before the reveal delay, no card ever shows.
+ * - Given one still running at the reveal delay, its card shows and follows its updates.
+ * - When it finishes well, the card shows its finishing words on a full bar, then leaves.
+ * - When it fails, the card shows at once (even before the delay) and stays until closed.
+ * - Once closed, the handle says so, and nothing it is told changes the card again.
+ * - The stack reads out each shown card's title, never its figures; the bar is named by the
+ * title and carries its reading.
+ *
+ * The portal itself needs a document, which this suite has not; `ProgressStack` is what
+ * `ProgressToasts` portals, so the markup is asserted on it.
+ */
+import { createElement } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ PROGRESS_DONE_STAY_MS,
+ PROGRESS_REVEAL_MS,
+ ProgressStack,
+ progressStore,
+ startProgress,
+} from "../src/components/overlays/progress-toasts/progress-toasts";
+import type { ProgressItem } from "../src/components/overlays/progress-toasts/progress-toasts";
+import { renderStatic } from "../src/testing";
+
+const items = () => progressStore.getState().items;
+const shown = () => items().filter((i) => i.shown && !i.leaving);
+
+describe("a long operation's card", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ progressStore.setState({ items: [] });
+ });
+ afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ progressStore.setState({ items: [] });
+ });
+
+ it("never shows for an operation that ends before the reveal delay", () => {
+ const card = startProgress({ title: "Deleting agent" });
+ vi.advanceTimersByTime(PROGRESS_REVEAL_MS - 1);
+ card.finish({ title: "Deleted agent" });
+ vi.advanceTimersByTime(PROGRESS_REVEAL_MS);
+ expect(items()).toEqual([]);
+ expect(card.closed).toBe(true);
+ });
+
+ it("shows once the operation has run for the delay, and follows its updates", () => {
+ const card = startProgress({ title: "Deleting agent", detail: "Counting" });
+ expect(shown()).toEqual([]);
+ vi.advanceTimersByTime(PROGRESS_REVEAL_MS);
+ card.update({ detail: "10 of 40 removed", value: 10, max: 40 });
+ expect(shown()).toEqual([
+ expect.objectContaining({
+ title: "Deleting agent",
+ detail: "10 of 40 removed",
+ value: 10,
+ max: 40,
+ state: "running",
+ }),
+ ]);
+ });
+
+ it("shows the finishing words, then leaves after its stay", () => {
+ const card = startProgress({ title: "Deleting agent" });
+ vi.advanceTimersByTime(PROGRESS_REVEAL_MS);
+ card.finish({ title: "Deleted agent", detail: "40 removed" });
+ expect(shown()).toEqual([
+ expect.objectContaining({ title: "Deleted agent", detail: "40 removed", state: "done" }),
+ ]);
+ card.update({ detail: "late reading" });
+ expect(shown()[0]?.detail).toBe("40 removed");
+ vi.advanceTimersByTime(PROGRESS_DONE_STAY_MS);
+ expect(shown()).toEqual([]);
+ expect(card.closed).toBe(true);
+ });
+
+ it("shows a failure at once and keeps it until it is closed", () => {
+ const card = startProgress({ title: "Deleting agent" });
+ card.finish({ failed: true, title: "Some files stayed", detail: "EBUSY" });
+ expect(shown()).toEqual([expect.objectContaining({ state: "failed", detail: "EBUSY" })]);
+ vi.advanceTimersByTime(PROGRESS_DONE_STAY_MS * 10);
+ expect(shown()).toHaveLength(1);
+ card.close();
+ expect(shown()).toEqual([]);
+ expect(card.closed).toBe(true);
+ });
+
+ it("is let go once closed: later updates and a finish change nothing", () => {
+ const card = startProgress({ title: "Deleting agent" });
+ vi.advanceTimersByTime(PROGRESS_REVEAL_MS);
+ card.close();
+ expect(card.closed).toBe(true);
+ card.update({ detail: "10 of 40 removed" });
+ card.finish({ title: "Deleted agent" });
+ vi.advanceTimersByTime(PROGRESS_DONE_STAY_MS * 2);
+ expect(items()).toEqual([]);
+ });
+});
+
+const CARDS: ProgressItem[] = [
+ {
+ id: 1,
+ title: "Deleting agent “writer”",
+ detail: "1,200 of 9,000 items removed",
+ value: 1200,
+ max: 9000,
+ state: "running",
+ shown: true,
+ },
+ { id: 2, title: "Some files stayed", detail: "EBUSY", state: "failed", shown: true },
+ { id: 3, title: "Not yet shown", state: "running", shown: false },
+];
+
+describe("ProgressStack", () => {
+ const html = renderStatic(createElement(ProgressStack, { items: CARDS, onClose: () => {} }));
+
+ it("reads out the shown cards' titles, and nothing else", () => {
+ const live = /<p class="sr-only" aria-live="polite">([^<]*)<\/p>/.exec(html);
+ expect(live?.[1]).toBe("Deleting agent “writer”. Some files stayed");
+ expect(html).not.toContain("Not yet shown");
+ });
+
+ it("names each bar by its card's title and carries the reading", () => {
+ expect(html).toContain('role="progressbar" aria-label="Deleting agent “writer”"');
+ expect(html).toMatch(
+ /aria-label="Deleting agent “writer”" aria-valuemin="0" aria-valuemax="9000" aria-valuenow="1200"/,
+ );
+ expect(html).toContain("1,200 of 9,000 items removed");
+ });
+
+ it("gives every shown card a close cross", () => {
+ expect(html.match(/<button type="button" aria-label="Close"/g)).toHaveLength(2);
+ });
+});
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 608786b4..738cdc71 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -17,6 +17,8 @@ import type {
AgentConfigUpdateRequest,
AgentCreateRequest,
AgentCreateResponse,
+ AgentDeleteResponse,
+ AgentDeletionResponse,
AgentHooksResponse,
AgentImportRequest,
AgentImportResponse,
@@ -1589,8 +1591,22 @@ export const getUsage = (
// Agent deletion & Workspace files --------------------------------------------------
+/**
+ * Deletes an Agent. The answer carries the background removal of its files to follow; a server
+ * from before that removal moved to the background answers 204 once everything is gone, which
+ * reads as undefined here.
+ */
export const deleteAgent = (projectId: string, agentId: string) =>
- apiFetch<void>(`/api/projects/${projectId}/agents/${agentId}`, { method: "DELETE" });
+ apiFetch<AgentDeleteResponse | undefined>(
+ `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}`,
+ { method: "DELETE" },
+ );
+
+/** Where a delete's background removal stands (404 `agent_deletion_not_found` once it is unknown). */
+export const getAgentDeletion = (projectId: string, deletionId: string) =>
+ apiFetch<AgentDeletionResponse>(
+ `/api/projects/${encodeURIComponent(projectId)}/agent-deletions/${encodeURIComponent(deletionId)}`,
+ );
export const listWorkspaceFiles = (sessionId: string, path: string) =>
apiFetch<WorkspaceFilesResponse>(`/api/sessions/${sessionId}/files`, { query: { path } });
diff --git a/packages/web/src/app.tsx b/packages/web/src/app.tsx
index d025f78d..a47ff3e2 100644
--- a/packages/web/src/app.tsx
+++ b/packages/web/src/app.tsx
@@ -15,6 +15,7 @@ import { useEffect } from "react";
import {
ClipboardWriterProvider,
CodeHighlighterProvider,
+ ProgressToasts,
Toaster,
TooltipLayer,
} from "@adelie/ui";
@@ -53,6 +54,8 @@ export function App({ initialPath }: { initialPath?: string } = {}) {
<AppRouter {...(initialPath === undefined ? {} : { initialPath })} />
{/* Top toast overlay: portaled to body, z-index above modals, shared site-wide. */}
<Toaster />
+ {/* Long operations' progress cards, bottom right (an Agent's files being removed). */}
+ <ProgressToasts />
{/* The hover hints of every `data-tooltip` element: one listener set, one panel. */}
<TooltipLayer />
</LocaleScope>
diff --git a/packages/web/src/features/agents/agent-deletion-progress.ts b/packages/web/src/features/agents/agent-deletion-progress.ts
new file mode 100644
index 00000000..9566ff21
--- /dev/null
+++ b/packages/web/src/features/agents/agent-deletion-progress.ts
@@ -0,0 +1,90 @@
+/**
+ * Following a delete's background removal on a progress card (the UI package's
+ * `startProgress`). By the time this starts the Agent is already off every list; what is left is
+ * the removal of its files, which on a large folder takes a while. The card appears only when it
+ * does take a while, and it is driven from here rather than from the Agents page, so it stays on
+ * screen wherever the user goes next.
+ *
+ * The removal is read from the server the Agent lived on every `DELETION_POLL_MS`. A deletion that
+ * server no longer knows (404: finished long enough ago to be forgotten, or never recorded) reads
+ * as finished — the Agent is gone either way. Reads that keep failing (the server out of reach)
+ * end the card quietly after `READ_FAILURES_TO_STOP` in a row: the removal goes on without a
+ * reader, and the server takes up whatever is left at its next start. Closing the card stops the
+ * reads; nothing on the server depends on them.
+ */
+import type { AgentDeletionInfo } from "@adelie/server/api";
+import { startProgress } from "@adelie/ui";
+import type { ProgressHandle, ProgressPatch } from "@adelie/ui";
+import { ApiError } from "../../api/client";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+
+/** How often the removal is read, ms. */
+export const DELETION_POLL_MS = 500;
+/** Failed reads in a row after which the card stops following. */
+export const READ_FAILURES_TO_STOP = 20;
+
+/** The card's bar and line for one reading. */
+function reading(d: AgentDeletionInfo): ProgressPatch {
+ if (d.phase === "counting") return { detail: S.agent.deleteCounting(d.total) };
+ return { detail: S.agent.deleteRemoving(d.removed, d.total), value: d.removed, max: d.total };
+}
+
+/** Moves the card to `d`; true once the removal is over. */
+function show(card: ProgressHandle, name: string, d: AgentDeletionInfo): boolean {
+ if (d.phase === "done") {
+ card.finish({ title: S.agent.deletedAgent(name), detail: S.agent.deleteRemoved(d.total) });
+ return true;
+ }
+ if (d.phase === "failed") {
+ card.finish({
+ failed: true,
+ title: S.agent.deleteIncomplete(name),
+ detail: S.agent.deleteRetryOnRestart(d.error ?? ""),
+ value: d.removed,
+ max: d.total,
+ });
+ return true;
+ }
+ card.update(reading(d));
+ return false;
+}
+
+/**
+ * Follows `deletion` (the delete's answer) until its removal is over or the card is closed.
+ * Resolves then; never rejects.
+ */
+export async function followAgentDeletion(opts: {
+ projectId: string;
+ /** The Agent's display name, for the card's title. */
+ name: string;
+ deletion: AgentDeletionInfo;
+}): Promise<void> {
+ const { projectId, name, deletion } = opts;
+ if (deletion.phase === "done") return;
+ const card = startProgress({ title: S.agent.deletingAgent(name), ...reading(deletion) });
+ if (show(card, name, deletion)) return;
+ let failures = 0;
+ for (;;) {
+ await new Promise((resolve) => setTimeout(resolve, DELETION_POLL_MS));
+ if (card.closed) return;
+ let next: AgentDeletionInfo;
+ try {
+ next = (await api.getAgentDeletion(projectId, deletion.deletionId)).deletion;
+ failures = 0;
+ } catch (e) {
+ if (e instanceof ApiError && e.status === 404) {
+ card.finish({ title: S.agent.deletedAgent(name) });
+ return;
+ }
+ failures += 1;
+ if (failures >= READ_FAILURES_TO_STOP) {
+ card.close();
+ return;
+ }
+ continue;
+ }
+ if (card.closed) return;
+ if (show(card, name, next)) return;
+ }
+}
diff --git a/packages/web/src/features/agents/agents-page.tsx b/packages/web/src/features/agents/agents-page.tsx
index 1001b976..fb3a533e 100644
--- a/packages/web/src/features/agents/agents-page.tsx
+++ b/packages/web/src/features/agents/agents-page.tsx
@@ -17,6 +17,10 @@
* Skills from a project directory's .agents/skills or .claude/skills — through form-variant
* dropdowns over the shared multi-select panel, with select all / select none. A plain new Agent
* otherwise starts with none.
+ *
+ * A delete answers once the Agent has left every list; its files are removed in the background,
+ * on a progress card that appears only when that takes a while (agent-deletion-progress.ts), so
+ * a folder full of installed dependencies no longer holds the request open.
*/
import { useEffect, useMemo, useRef, useState } from "react";
import type { ChangeEvent } from "react";
@@ -83,6 +87,7 @@ import { mergeAgents } from "../../lib/benchmark-merge";
import type { AgentSource } from "../../lib/benchmark-merge";
import { useSessions } from "../../state/sessions";
import { scoped, scopedValue, type Scoped } from "../../lib/project-scope";
+import { followAgentDeletion } from "./agent-deletion-progress";
/** Built-in Agent shipped with every Project (default_agent only; the server also rejects deletion, so no delete entry point is shown here). */
const BUILTIN_AGENT_IDS = new Set(["default_agent"]);
@@ -452,8 +457,17 @@ export function AgentsPage() {
setBusy(true);
setDeleteError(null);
try {
- await api.deleteAgent(projectId, deleting.agentId);
+ const answer = await api.deleteAgent(projectId, deleting.agentId);
setDeleting(null);
+ // The Agent is gone from every list already; its files go in the background, on a card
+ // that shows once that takes a while (an older server answered after removing them).
+ if (answer !== undefined) {
+ void followAgentDeletion({
+ projectId,
+ name: deleting.name,
+ deletion: answer.deletion,
+ });
+ }
await reloadAgents();
} catch (e) {
setDeleteError(apiErrorText(e));
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index cdd6b608..59519d1f 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -1821,6 +1821,18 @@ export const en: Strings = {
builtinUndeletable: "Built-in agents cannot be deleted",
deleteConfirm: (name: string): string =>
`Delete agent "${name}"? Its directory (including all Traces) will be removed recursively and cannot be recovered.`,
+ deletingAgent: (name: string): string => `Deleting agent "${name}"`,
+ deletedAgent: (name: string): string => `Deleted agent "${name}"`,
+ deleteIncomplete: (name: string): string =>
+ `Some files of agent "${name}" could not be removed`,
+ deleteCounting: (found: number): string =>
+ `Counting: ${found.toLocaleString("en-US")} ${found === 1 ? "item" : "items"} found`,
+ deleteRemoving: (removed: number, total: number): string =>
+ `${removed.toLocaleString("en-US")} of ${total.toLocaleString("en-US")} ${total === 1 ? "item" : "items"} removed`,
+ deleteRemoved: (total: number): string =>
+ `${total.toLocaleString("en-US")} ${total === 1 ? "item" : "items"} removed`,
+ deleteRetryOnRestart: (error: string): string =>
+ `${error}. The rest is removed when the server next starts.`,
stateTitle: "Agent State",
stateVersion: "Agent State version",
transferDesc:
@@ -5704,6 +5716,8 @@ export const en: Strings = {
calendar_event_exists: "A calendar event with that name already exists.",
calendar_event_not_found: "That calendar event no longer exists.",
desk_unavailable: "The desk session could not be opened.",
+ agent_folder_busy:
+ "Another program has a file in this agent's folder open, so the folder could not be moved and nothing was deleted. Close that program and try again.",
ticket_not_found: "That ticket no longer exists.",
ticket_invalid: "This ticket file needs repair; it accepts no changes until then.",
ticket_session_failed: "The ticket session could not be started.",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 517b4f93..fd0e18f2 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -1848,6 +1848,22 @@ export const zh = {
builtinUndeletable: "内置 Agent 不可被删除",
deleteConfirm: (name: string): string =>
`确认删除 Agent「${name}」?其目录(含全部 Trace)将被递归删除,不可恢复。`,
+ /**
+ * The delete's progress card: its title while the Agent's files are removed in the
+ * background, once they are all gone, and when some could not be removed.
+ */
+ deletingAgent: (name: string): string => `正在删除 Agent「${name}」`,
+ deletedAgent: (name: string): string => `已删除 Agent「${name}」`,
+ deleteIncomplete: (name: string): string => `Agent「${name}」有文件未能删除`,
+ /** The card's line: while the folder is walked, while it is removed, and at the end (files and folders alike). */
+ deleteCounting: (found: number): string =>
+ `正在统计,已找到 ${found.toLocaleString("zh-CN")} 项`,
+ deleteRemoving: (removed: number, total: number): string =>
+ `已删除 ${removed.toLocaleString("zh-CN")} / ${total.toLocaleString("zh-CN")} 项`,
+ deleteRemoved: (total: number): string => `共删除 ${total.toLocaleString("zh-CN")} 项`,
+ /** A removal that stopped short: the operating system's reason, and when the rest goes. */
+ deleteRetryOnRestart: (error: string): string =>
+ `${error}。其余文件会在服务端下次启动时再删除。`,
/** Agent State section: the State version with the snapshot transfer actions, plus the copyable State path. */
stateTitle: "Agent State",
stateVersion: "Agent State 版本",
@@ -5720,6 +5736,8 @@ export const zh = {
calendar_event_exists: "已存在同名日程。",
calendar_event_not_found: "该日程已不存在。",
desk_unavailable: "无法打开工位会话。",
+ agent_folder_busy:
+ "其他程序正占用该 Agent 目录中的文件,目录无法移走,未删除任何内容。关闭该程序后重试。",
ticket_not_found: "该工单已不存在。",
ticket_invalid: "该工单文件需要修复,修好前不接受改动。",
ticket_session_failed: "无法发起工单会话。",
diff --git a/packages/web/test/agent-deletion-progress.test.ts b/packages/web/test/agent-deletion-progress.test.ts
new file mode 100644
index 00000000..9b1108b4
--- /dev/null
+++ b/packages/web/test/agent-deletion-progress.test.ts
@@ -0,0 +1,121 @@
+/**
+ * Following a delete's background removal on a progress card
+ * (src/features/agents/agent-deletion-progress.ts), against the real endpoints and the UI
+ * package's real card store, with the package's one fetch fake.
+ *
+ * - Given a removal that takes a while, the card follows the server's readings — a count with no
+ * bar yet, then removed out of total — and finishes when the server says done.
+ * - Given a deletion the server no longer knows (404), the card finishes: the Agent is gone.
+ * - Given a removal that stops short, the card stays, failed, at the last reading.
+ * - When the user closes the card, the reads stop.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { AgentDeletionInfo } from "@adelie/server/api";
+import { closeProgress, PROGRESS_REVEAL_MS, progressStore } from "@adelie/ui";
+import {
+ DELETION_POLL_MS,
+ followAgentDeletion,
+} from "../src/features/agents/agent-deletion-progress";
+import { apiError, json, stubFetch } from "./helpers/fetch";
+
+const START: AgentDeletionInfo = {
+ deletionId: "writer-1761465600000",
+ agentId: "writer",
+ phase: "counting",
+ total: 0,
+ removed: 0,
+};
+
+const card = () => progressStore.getState().items[0];
+
+/** Answers each read with the next reading, then keeps answering the last one. */
+function readings(...list: AgentDeletionInfo[]) {
+ let i = 0;
+ return stubFetch(() => json({ deletion: list[Math.min(i++, list.length - 1)] }));
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ progressStore.setState({ items: [] });
+});
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ progressStore.setState({ items: [] });
+});
+
+describe("following an agent's removal", () => {
+ it("follows the readings to the end", async () => {
+ const fetch = readings(
+ { ...START, total: 3000 },
+ { ...START, phase: "removing", total: 9000, removed: 1200 },
+ { ...START, phase: "done", total: 9000, removed: 9000 },
+ );
+ const done = followAgentDeletion({
+ projectId: "p",
+ name: "Writer",
+ deletion: START,
+ });
+
+ await vi.advanceTimersByTimeAsync(PROGRESS_REVEAL_MS);
+ expect(card()).toMatchObject({ shown: true, state: "running" });
+ // Still counting: no amount yet, so the bar has no value.
+ expect(card()?.value).toBeUndefined();
+ await vi.advanceTimersByTimeAsync(DELETION_POLL_MS);
+ expect(card()).toMatchObject({ state: "running", value: 1200, max: 9000 });
+ await vi.advanceTimersByTimeAsync(DELETION_POLL_MS);
+ await done;
+ expect(card()?.state).toBe("done");
+ expect(fetch.requests.map((r) => r.path)).toEqual(
+ fetch.requests.map(() => "/api/projects/p/agent-deletions/writer-1761465600000"),
+ );
+ });
+
+ it("finishes when the server no longer knows the deletion", async () => {
+ let reads = 0;
+ stubFetch(() =>
+ reads++ === 0
+ ? json({ deletion: { ...START, phase: "removing", total: 9000, removed: 10 } })
+ : apiError(404, "agent_deletion_not_found"),
+ );
+ const done = followAgentDeletion({
+ projectId: "p",
+ name: "Writer",
+ deletion: START,
+ });
+ await vi.advanceTimersByTimeAsync(PROGRESS_REVEAL_MS);
+ expect(card()).toMatchObject({ shown: true, state: "running" });
+ await vi.advanceTimersByTimeAsync(DELETION_POLL_MS);
+ await done;
+ expect(card()?.state).toBe("done");
+ });
+
+ it("stays, failed, when the removal stops short", async () => {
+ readings({ ...START, phase: "failed", total: 9000, removed: 8999, error: "EBUSY: unlink" });
+ const done = followAgentDeletion({
+ projectId: "p",
+ name: "Writer",
+ deletion: START,
+ });
+ await vi.advanceTimersByTimeAsync(DELETION_POLL_MS);
+ await done;
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(card()).toMatchObject({ state: "failed", value: 8999, max: 9000, shown: true });
+ });
+
+ it("stops reading once the user closes the card", async () => {
+ const fetch = readings({ ...START, phase: "removing", total: 9000, removed: 10 });
+ const done = followAgentDeletion({
+ projectId: "p",
+ name: "Writer",
+ deletion: START,
+ });
+ await vi.advanceTimersByTimeAsync(PROGRESS_REVEAL_MS);
+ const reads = fetch.requests.length;
+ expect(reads).toBeGreaterThan(0);
+ closeProgress(card()!.id);
+ await vi.advanceTimersByTimeAsync(DELETION_POLL_MS * 4);
+ await done;
+ expect(fetch.requests.length).toBeLessThanOrEqual(reads + 1);
+ });
+});