A local-first multi-agent app development platform, built on PenguinHarness
fix: 更新插件时技能目录被别的程序占着,不再直接报「内部错误」
lmliheng6f25e14596de
diff --git a/packages/core/src/state/agent-state.ts b/packages/core/src/state/agent-state.tsindex 257bd0bd..0eee176a 100644--- a/packages/core/src/state/agent-state.ts+++ b/packages/core/src/state/agent-state.ts@@ -527,6 +527,67 @@ export async function installSkill(await replaceSkillDirectory(dir, files);}+/**+ * The errnos a removal gets **before** the directory is really gone: Windows reports `EBUSY`+ * ("resource busy or locked") while any other process still has a handle inside the directory —+ * a virus scanner reading files that were written a moment ago, an editor, or a long-lived child+ * process that was started from that directory. `EPERM` is the same story under a different+ * spelling, `ENOTEMPTY` is the race with a writer that got in between.+ */+const BUSY_ERRNOS = new Set(["EBUSY", "EPERM", "ENOTEMPTY"]);++/** How long to wait before each retry: 30 + 70 + 150 + 300 + 600 ms, then give up. */+const REMOVAL_DELAYS_MS = [30, 70, 150, 300, 600];++/** A Skill or hook directory that another program is holding open, after the retries ran out. */+export class DirectoryBusyError extends Error {+ constructor(+ readonly directory: string,+ options?: { cause?: unknown },+ ) {+ super(+ `Directory is in use by another program: ${directory}. ` ++ `Close whatever is using it (an editor, a scanner, a process started in that directory) and try again.`,+ options,+ );+ this.name = "DirectoryBusyError";+ }+}++/**+ * Runs `run` until it succeeds, retrying only the "in use" errnos above: they clear on their own+ * within a few hundred milliseconds, and without the retry one busy moment fails an entire+ * operation the user then has to run again by hand — which is what a Windows install reported:+ * `EBUSY: resource busy or locked, rmdir '…\agent_state\skills\wps-office'` aborting a plugin+ * update. Every other failure is the operation's own and is rethrown untouched.+ *+ * `sleep` is injectable so a test can drive the policy without the wall-clock wait.+ */+export async function retryWhileBusy<T>(+ run: () => Promise<T>,+ options: { directory: string; sleep?: (ms: number) => Promise<void> },+): Promise<T> {+ const sleep = options.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms)));+ for (let attempt = 0; ; attempt++) {+ try {+ return await run();+ } catch (err) {+ const code = (err as NodeJS.ErrnoException | null)?.code ?? "";+ if (!BUSY_ERRNOS.has(code)) throw err;+ const delay = REMOVAL_DELAYS_MS[attempt];+ if (delay === undefined) {+ throw new DirectoryBusyError(options.directory, { cause: err });+ }+ await sleep(delay);+ }+ }+}++/** Deletes a directory tree, riding out the busy errnos above (absent directory = nothing to do). */+async function removeDirectory(dir: string): Promise<void> {+ await retryWhileBusy(() => fs.rm(dir, { recursive: true, force: true }), { directory: dir });+}+/*** Replaces one Skill directory with exactly `files` (relative path → content, subdirectories* created as needed). Everything is written into a staging directory and swapped in as the last@@ -543,7 +604,7 @@ export async function replaceSkillDirectory(files: Iterable<[string, string | Uint8Array]>,): Promise<void> {const staging = `${path.join(path.dirname(dir), `.${path.basename(dir)}`)}.incoming`;- await fs.rm(staging, { recursive: true, force: true });+ await removeDirectory(staging);await fs.mkdir(staging, { recursive: true });try {await Promise.all(@@ -556,7 +617,7 @@ export async function replaceSkillDirectory(// rename(2) refuses to replace a non-empty directory, so the old one goes first. The window// between the two is the one case this cannot make atomic; it is bounded by a single rm and// leaves the Skill absent rather than corrupt.- await fs.rm(dir, { recursive: true, force: true });+ await removeDirectory(dir);await fs.rename(staging, dir);} catch (err) {await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined);@@ -574,10 +635,7 @@ export async function removeSkill(assertValidId("project_id", projectId);assertValidId("agent_id", agentId);assertValidId("skill_name", name);- await fs.rm(path.join(skillsDir(root, projectId, agentId), name), {- recursive: true,- force: true,- });+ await removeDirectory(path.join(skillsDir(root, projectId, agentId), name));}/** An installed Skill entry: frontmatter metadata (including an optional short description) + the optional icon.svg content in the directory. */@@ -766,10 +824,7 @@ export async function removeHook(assertValidId("project_id", projectId);assertValidId("agent_id", agentId);assertValidId("skill_name", name);- await fs.rm(path.join(hooksDir(root, projectId, agentId), name), {- recursive: true,- force: true,- });+ await removeDirectory(path.join(hooksDir(root, projectId, agentId), name));}/** An installed hook package: its manifest plus the directory its commands resolve against. */diff --git a/packages/core/test/agent-skills.test.ts b/packages/core/test/agent-skills.test.tsindex 94430c58..a1c99b83 100644--- a/packages/core/test/agent-skills.test.ts+++ b/packages/core/test/agent-skills.test.ts@@ -6,18 +6,20 @@import fs from "node:fs/promises";import os from "node:os";import path from "node:path";-import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { librarySkill } from "../src/index.js";import {AGENTS_MD_PLACEHOLDER,DEFAULT_AGENT_ID,DEFAULT_PROJECT_ID,+ DirectoryBusyError,SKILL_METADATA_PLACEHOLDER,agentStateDir,assembleSystemPrompt,installSkill,listInstalledSkills,removeSkill,+ retryWhileBusy,skillMetadataSection,skillsDir,} from "../src/state/index.js";@@ -136,6 +138,93 @@ describe("installSkill / removeSkill", () => {});});+describe("a Skill directory another program is holding open", () => {+ /** The shape Windows reports while a handle is still open inside the directory. */+ const busy = (code: string) =>+ Object.assign(new Error(`${code}: resource busy or locked, rmdir 'x'`), { code });++ it("retries the 'in use' errnos on the fixed schedule, then reports a busy directory", async () => {+ const waits: number[] = [];+ const codes = ["EBUSY", "EPERM", "ENOTEMPTY"];+ let calls = 0;+ const err = await retryWhileBusy(+ async () => {+ throw busy(codes[calls++ % codes.length]!);+ },+ { directory: "C:\\skills\\wps-office", sleep: async (ms) => void waits.push(ms) },+ ).catch((thrown: unknown) => thrown);++ // One attempt plus five retries — enough for a scanner's momentary handle, short enough that a+ // directory held open for real still answers the user instead of hanging.+ expect(calls).toBe(6);+ expect(waits).toEqual([30, 70, 150, 300, 600]);+ expect(err).toBeInstanceOf(DirectoryBusyError);+ expect((err as DirectoryBusyError).directory).toBe("C:\\skills\\wps-office");+ expect((err as DirectoryBusyError).cause).toBeInstanceOf(Error);+ });++ it("returns the value as soon as a retry succeeds", async () => {+ const waits: number[] = [];+ let calls = 0;+ const result = await retryWhileBusy(+ async () => {+ if (calls++ < 2) throw busy("EBUSY");+ return "done";+ },+ { directory: "/skills/x", sleep: async (ms) => void waits.push(ms) },+ );++ expect(result).toBe("done");+ expect(calls).toBe(3);+ expect(waits).toEqual([30, 70]);+ });++ it("rethrows any other failure immediately, without retrying", async () => {+ const original = Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" });+ let calls = 0;+ await expect(+ retryWhileBusy(+ async () => {+ calls++;+ throw original;+ },+ { directory: "/skills/x", sleep: async () => {} },+ ),+ ).rejects.toBe(original);+ expect(calls).toBe(1);+ });++ it("finishes an install that lands while the old directory is briefly busy", async () => {+ const before = "---\nname: wps-office\nversion: 1\n---\n\nOld body\n";+ const after = "---\nname: wps-office\nversion: 2\n---\n\nNew body\n";+ await install("wps-office", before);+ const dir = path.join(skillsDir(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID), "wps-office");++ // The first two removals of that directory say "in use" and the third goes through.+ const realRm = fs.rm.bind(fs);+ let busyLeft = 2;+ const rm = vi.spyOn(fs, "rm").mockImplementation(async (target, options) => {+ if (path.resolve(String(target)) === path.resolve(dir) && busyLeft > 0) {+ busyLeft--;+ throw busy("EBUSY");+ }+ return realRm(target, options);+ });+ try {+ await install("wps-office", after);+ } finally {+ rm.mockRestore();+ }++ expect(busyLeft).toBe(0); // the retries really ran+ expect(await fs.readFile(skillMd("wps-office"), "utf8")).toBe(after);+ // And the staging directory did not survive them.+ expect(await fs.readdir(skillsDir(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID))).toEqual([+ "wps-office",+ ]);+ });+});+describe("listInstalledSkills", () => {it("returns [] when the skills directory does not exist", async () => {expect(await list()).toEqual([]);diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex d25ceedb..67fe79ed 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -71,7 +71,7 @@ import { AuthService } from "./auth/service.js";import { newAuthRuntimeState } from "./auth/runtime-state.js";import { AuthSessionsRepo } from "./db/repos/auth-sessions.js";import { ensureInstallId } from "./install-id.js";-import { handleError, HttpError, errorBody } from "./http/errors.js";+import { handleError, HttpError, errorBody, normalizeError } from "./http/errors.js";import { attributedProjectId } from "./http/attribution.js";import { STREAM_IDLE_MS } from "./http/sse.js";import { installRoutes } from "./http/routes/install.js";@@ -383,12 +383,14 @@ export function createApp(boot: ServerBoot): Hono<AppEnv> {// to the DB is just a side-effect layered on top.app.onError((err, c) => {const projectId = attributedProjectId(c, { access: access() });+ // Normalize first: response and recording must agree on what this error is (see http/errors.ts).+ const normalized = normalizeError(err);errors().record({source: "http",- err,+ err: normalized,...(projectId !== undefined ? { ctx: { projectId } } : {}),});- return handleError(err, c);+ return handleError(normalized, c);});app.notFound((c) => c.json(errorBody("not_found", "Endpoint does not exist."), 404));diff --git a/packages/server/src/http/app.ts b/packages/server/src/http/app.tsindex f5cce1fc..d0dbb205 100644--- a/packages/server/src/http/app.ts+++ b/packages/server/src/http/app.ts@@ -7,7 +7,7 @@ import type { MiddlewareHandler } from "hono";import { bodyLimit } from "hono/body-limit";import { authMiddleware, jsonOnlyWrites } from "../auth/middleware.js";import { AMSP_PREFIX, amspAllowOrigin } from "../amsp/cors.js";-import { HttpError, handleError } from "./errors.js";+import { HttpError, handleError, normalizeError } from "./errors.js";import { attributedProjectId } from "./attribution.js";import { bodyLimitBytes } from "../services/attachment-limits.js";import { declined } from "../hmr/hono-seam.js";@@ -54,12 +54,14 @@ export class HttpModule {const app = new Hono<AppEnv>();app.onError((err, c) => {const projectId = attributedProjectId(c, { access });+ // Normalize first: response and recording must agree on what this error is (see errors.ts).+ const normalized = normalizeError(err);errors.record({source: "http",- err,+ err: normalized,...(projectId !== undefined ? { ctx: { projectId } } : {}),});- return handleError(err, c);+ return handleError(normalized, c);});app.notFound(() => declined());app.use("*", async (c, next) => {diff --git a/packages/server/src/http/errors.ts b/packages/server/src/http/errors.tsindex 24f4579a..fb5525d4 100644--- a/packages/server/src/http/errors.ts+++ b/packages/server/src/http/errors.ts@@ -7,6 +7,7 @@* (never leaking internal details to the client).*/import type { Context } from "hono";+import { DirectoryBusyError } from "@adelie/core";import type { ErrorBody } from "../api/types.js";export class HttpError extends Error {@@ -45,6 +46,31 @@ export function modelCredentialMissing(modelId: string): HttpError {);}+/**+ * Converges an error caught by onError into the one `handleError` and the error recorder+ * understand. Almost everything passes through untouched; a `DirectoryBusyError` — where Core+ * already exhausted its removal retries because another program (an editor, a virus scanner, a+ * process that was started inside that directory) is holding a Skill or hook directory open —+ * becomes the 409 refusal below.+ *+ * Both are needed because the raw error is handed to two consumers: the response (otherwise a+ * bare 500) and the error recorder, which classifies by `instanceof HttpError` alone — with the+ * original error the error center would show "internal / unexpected", i.e. a bug for the user to+ * report, when the fix is on their machine. Normalizing once, ahead of both, keeps the two in+ * step. Both onError funnels call this (src/app.ts and src/http/app.ts).+ */+export function normalizeError(err: Error): Error {+ if (err instanceof DirectoryBusyError) {+ return new HttpError(+ 409,+ "skill_dir_busy",+ `Another program is holding this directory open: ${err.directory}. ` ++ `Close it (an editor, a scanner, a process started in that directory) and try again.`,+ );+ }+ return err;+}+/** app.onError handler: maps HttpError through as-is; everything else is logged and converged to 500. */export function handleError(err: Error, c: Context): Response {if (err instanceof HttpError) {diff --git a/packages/server/test/errors.test.ts b/packages/server/test/errors.test.tsindex e7ed72c1..5c1fc734 100644--- a/packages/server/test/errors.test.ts+++ b/packages/server/test/errors.test.ts@@ -34,6 +34,8 @@* - A business error is expected, an internal one unexpected with a 500, each attributed to* the Project only when the requester has access to it (unauthenticated and non-member* failures stay unattributed, and a throwing access check degrades to unattributed).+ * - A Skill directory another program is holding open (Windows EBUSY) answers as a named 409+ * and is filed as expected, not as the internal failure the raw errno would look like.* - The usage endpoint shows a Project's own errors; unattributed ones only to the admin.* - The paged error route pages within the caller's tenant, narrows to one kind on request,* and refuses a page it cannot serve; it and the dashboard fold by the viewer's day, and an@@ -43,6 +45,8 @@* - Deleting a Project deletes its error records and nobody else's.*/import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import fs from "node:fs/promises";+import path from "node:path";import type { DatabaseSync } from "node:sqlite";import {abortEvent,@@ -52,6 +56,7 @@ import {requestBegin,requestEnd,sessionMeta,+ skillsDir,toolCall,toolCallOutput,withOrigin,@@ -1087,6 +1092,41 @@ describe("HTTP onError persistence (integration)", () => {expect(rows[0]!.project_id).toBe(projectId);});+ it("a Skill directory another program is holding open → 409 skill_dir_busy, recorded as expected", async () => {+ const agentId = "agent-busy";+ const dir = path.join(skillsDir(t.root, projectId, agentId), "busy-skill");+ await fs.mkdir(dir, { recursive: true });+ await fs.writeFile(path.join(dir, "SKILL.md"), "---\nname: busy-skill\n---\nBody\n");++ // Windows reports EBUSY ("resource busy or locked") on every removal while another program+ // still holds a handle inside the directory; Core retries and eventually gives up. The answer+ // must name what is wrong (409), not converge to a bare 500, and the error center must file it+ // where the user can act on it rather than as an internal bug.+ const realRm = fs.rm.bind(fs);+ const rm = vi.spyOn(fs, "rm").mockImplementation(async (target, options) => {+ if (path.resolve(String(target)) === path.resolve(dir)) {+ throw Object.assign(+ new Error(`EBUSY: resource busy or locked, rmdir '${String(target)}'`),+ { code: "EBUSY" },+ );+ }+ return realRm(target, options);+ });+ const res = await api.delete(`/api/projects/${projectId}/agents/${agentId}/skills/busy-skill`);+ rm.mockRestore();++ expect(res.status).toBe(409);+ expect(await res.json()).toMatchObject({ error: { code: "skill_dir_busy" } });++ const rows = errorRows();+ expect(rows).toHaveLength(1);+ expect(rows[0]!.source).toBe("http");+ expect(rows[0]!.kind).toBe("expected");+ expect(rows[0]!.code).toBe("skill_dir_busy");+ expect(rows[0]!.status).toBe(409);+ expect(rows[0]!.project_id).toBe(projectId);+ });+it("errors exposed via the usage endpoint: summary / top code / recent", async () => {// An error in another Project owned by the same owner: attributed to that Project, not this one's view.const other = (await (diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 72b4f6ab..0fb4a486 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -5447,6 +5447,8 @@ export const en: Strings = {desktop_single_user: "The desktop app is single-user; user management is unavailable.",not_found: "This resource does not exist, or you do not have access.",internal: "The server hit an internal error. Please try again shortly.",+ skill_dir_busy:+ "Another program is holding this Skill's directory open (an editor, a virus scan, or a process started in it — the WPS bridge, for one), so it cannot be replaced. Close it and retry.",agent_not_found: "This agent no longer exists.",unknown_agent: "That agent does not exist in this Project.",agent_exists: "This agent id is already taken.",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 727bc5bf..aff530cb 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -5464,6 +5464,8 @@ export const zh = {desktop_single_user: "桌面应用为单用户模式,用户管理不可用。",not_found: "资源不存在,或你没有访问权限。",internal: "服务器内部错误,请稍后重试。",+ skill_dir_busy:+ "技能目录正被别的程序占着(编辑器、杀毒扫描,或从该目录启动的进程如 WPS 桥),无法替换;关掉它再试一次。",agent_not_found: "该 Agent 已不存在。",unknown_agent: "该 Agent 不存在于本项目。",agent_exists: "该 Agent id 已被占用。",diff --git a/plugins/use-wps-office/skills/wps-office/kit/install.mjs b/plugins/use-wps-office/skills/wps-office/kit/install.mjsindex 2a96ecf9..2bc2dc8b 100644--- a/plugins/use-wps-office/skills/wps-office/kit/install.mjs+++ b/plugins/use-wps-office/skills/wps-office/kit/install.mjs@@ -217,6 +217,10 @@ function installAutostart(root) {const body = ["@echo off",`rem Adelie 的 WPS 桥:由「Adelie WPS 面板」安装脚本生成,删掉这一行即可取消开机自启。`,+ // Leave the Startup folder before launching, for the same reason startBridge does: a bridge+ // whose cwd sits inside the Skill's directory blocks that directory's removal (Windows EBUSY),+ // and the plugin could then never be updated or uninstalled while it runs.+ `cd /d "%USERPROFILE%"`,`start "adelie-wps-bridge" /min "${process.execPath}" "${SERVE}" --root "${root}"`,"",].join("\r\n");@@ -250,6 +254,11 @@ function startBridge(root) {detached: true,stdio: "ignore",windowsHide: true,+ // Never inherit the caller's working directory. Windows refuses to delete a directory that is+ // some process's cwd (`EBUSY: resource busy or locked`), so a bridge started from a shell that+ // was sitting in this Skill's directory would make every later update of this plugin fail+ // until the bridge was killed. The data root is ours, always exists, and is nobody's Skill.+ cwd: root,});child.unref();}