diff --git a/README.md b/README.md index 0c46ea09..a123dd84 100644 --- a/README.md +++ b/README.md @@ -450,6 +450,12 @@ for intentional non-interactive execution, `--json` for structured output and `--scope user|workspace` to choose installation scope. Marketplace Git access behind a proxy uses `ZCODE_HTTP_PROXY`. +Each launcher plugin request has a 60-second timeout. For slow marketplace or +plugin downloads, set `ZCODE_PLUGIN_REQUEST_TIMEOUT_MS` to a larger duration in +milliseconds. For marketplace addition/update and plugin installation, +cancellation asks the runtime to stop the operation and release its storage lock +before the launcher terminates an unresponsive app-server. + Plugins with configuration can load options from a JSON file without exposing values in the process argument list: diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 39fff6bb..91657654 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -705,6 +705,14 @@ export ZCODE_TUI_NOTIFICATION_CONDITION=always # unfocused|always zcode ``` +## Plugin request timeout + +Launcher plugin requests time out after 60 seconds. Set +`ZCODE_PLUGIN_REQUEST_TIMEOUT_MS` to a positive integer in milliseconds (up to +2147483647) to allow longer downloads. Marketplace addition/update and plugin +installation request runtime cleanup on timeout or cancellation before terminating +an unresponsive app-server. + ## Official MCP Availability When the bundled runtime has no official MCP trusted-origin registry, official diff --git a/docs/CONFIGURATION.zh-CN.md b/docs/CONFIGURATION.zh-CN.md index 826b60da..e4248ebb 100644 --- a/docs/CONFIGURATION.zh-CN.md +++ b/docs/CONFIGURATION.zh-CN.md @@ -595,6 +595,12 @@ export ZCODE_TUI_NOTIFICATION_CONDITION=always # unfocused|always zcode ``` +## 插件请求超时 + +启动器的插件请求默认在 60 秒后超时。下载较慢时,可将 +`ZCODE_PLUGIN_REQUEST_TIMEOUT_MS` 设置为更大的正整数毫秒值(最大 2147483647)。 +添加或更新市场、安装插件时,超时或取消会先请求 runtime 清理操作,再终止无响应的 app-server。 + ## 官方 MCP 可用性 如果捆绑 runtime 没有官方 MCP 的可信来源 registry,官方 HTTP MCP 服务会显示为禁用, diff --git a/src/app-server-client.ts b/src/app-server-client.ts index 76fef0fe..29d84ec5 100644 --- a/src/app-server-client.ts +++ b/src/app-server-client.ts @@ -5,6 +5,7 @@ import { StringDecoder } from "node:string_decoder"; const maximumOutputBytes = 16 * 1024 * 1024; const forceTerminationDelayMilliseconds = 500; +const cooperativeCancellationDelayMilliseconds = 3_000; export interface AppServerTransport { args: string[]; @@ -14,10 +15,12 @@ export interface AppServerTransport { } export interface AppServerRequest { + cancellation?: { method: string; params: Record }; method: string; onStderr?: (stderr: string) => void; params: Record; signal?: AbortSignal; + timeoutMs?: number; transport: AppServerTransport; } @@ -56,6 +59,13 @@ export class AppServerCancellationError extends Error { } } +export class AppServerTimeoutError extends Error { + constructor(public readonly timeoutMs: number) { + super(`App-server request timed out after ${timeoutMs}ms.`); + this.name = "TimeoutError"; + } +} + function signalExitCode(signal: NodeJS.Signals | null): number { if (!signal) return 1; const number = (osConstants.signals as Record)[signal]; @@ -120,6 +130,10 @@ function responseEnvelope(stdout: string): AppServerEnvelope | undefined { export async function requestAppServer(request: AppServerRequest): Promise { if (request.signal?.aborted) throw cancellationError(request.signal); + if (request.timeoutMs !== undefined && (!Number.isInteger(request.timeoutMs) + || request.timeoutMs <= 0 || request.timeoutMs > 2_147_483_647)) { + throw new Error("App-server timeoutMs must be an integer between 1 and 2147483647."); + } const child = spawn(request.transport.command, request.transport.args, { cwd: request.transport.cwd, @@ -130,6 +144,9 @@ export async function requestAppServer(request: AppServerRequest): Promise((resolve) => { let settled = false; const finish = (code: number) => { @@ -147,7 +164,7 @@ export async function requestAppServer(request: AppServerRequest): Promise { + const terminate = () => { if (child.exitCode !== null || child.signalCode !== null) return; child.kill(terminationSignal(request.signal)); forceTerminationTimer = setTimeout(() => { @@ -155,8 +172,19 @@ export async function requestAppServer(request: AppServerRequest): Promise { + if (cancelling || child.exitCode !== null || child.signalCode !== null) return; + cancelling = true; + if (requestTimeoutTimer) clearTimeout(requestTimeoutTimer); + if (request.cancellation && !child.stdin.writableEnded && !child.stdin.destroyed) { + // Serial app-server handlers may not read the cancellation until the original + // request finishes. EOF also triggers client-disconnect cancellation so the + // runtime can abort downloads and unwind its storage-lock finally blocks. + child.stdin.end(`${JSON.stringify({ id: 2, ...request.cancellation })}\n`); + forceTerminationTimer = setTimeout(terminate, cooperativeCancellationDelayMilliseconds); + forceTerminationTimer.unref(); + } else terminate(); + }; child.stdin.on("error", () => {}); // 3.14 treats stdin EOF as client disconnection and cancels outstanding work. @@ -173,6 +201,12 @@ export async function requestAppServer(request: AppServerRequest): Promise { timedOut = true; onAbort(); }, request.timeoutMs); + requestTimeoutTimer.unref(); + } try { const [code, stdout, stderr] = await Promise.all([ @@ -180,6 +214,7 @@ export async function requestAppServer(request: AppServerRequest): Promise([ + pluginProtocolMethods.marketplaceAdd, pluginProtocolMethods.marketplaceUpdate, pluginProtocolMethods.install +]); + +function pluginRequestTimeoutMs(): number { + const value = process.env.ZCODE_PLUGIN_REQUEST_TIMEOUT_MS?.trim(); + const timeout = value ? Number(value) : 60_000; + if (!Number.isInteger(timeout) || timeout <= 0 || timeout > 2_147_483_647) { + throw new Error("ZCODE_PLUGIN_REQUEST_TIMEOUT_MS must be an integer between 1 and 2147483647."); + } + return timeout; +} export function resolveModelRetryMaxRetries(env: NodeJS.ProcessEnv): string { @@ -539,25 +553,32 @@ export async function main(args: string[]): Promise { let pluginCommand: number | undefined; try { pluginCommand = await runPluginCommand(args, { - request: async ({ method, params, signal, workingDirectory }) => await requestAppServer({ - method, - params, - onStderr: stderr => { - for (const line of stderr.split(/\r?\n/u)) { - if (!line.startsWith("ZCode Built-in: ignoring unavailable ZCODE_BUILTIN_PROVIDER_CONFIG_FILE ") - || builtinProviderWarnings.has(line)) continue; - builtinProviderWarnings.add(line); - process.stderr.write(`${line}\n`); + request: async ({ method, params, signal, workingDirectory }) => { + const operationId = cancellablePluginMethods.has(method) ? randomUUID() : undefined; + return await requestAppServer({ + method, + params: operationId ? { ...params, operationId } : params, + ...(operationId ? { cancellation: { + method: "plugins/cancelOperation", params: { operationId } + } } : {}), + timeoutMs: pluginRequestTimeoutMs(), + onStderr: stderr => { + for (const line of stderr.split(/\r?\n/u)) { + if (!line.startsWith("ZCode Built-in: ignoring unavailable ZCODE_BUILTIN_PROVIDER_CONFIG_FILE ") + || builtinProviderWarnings.has(line)) continue; + builtinProviderWarnings.add(line); + process.stderr.write(`${line}\n`); + } + }, + signal: signal ?? pluginAbortController.signal, + transport: { + args: [runtimePath, "app-server"], + command: node, + cwd: workingDirectory, + env: runtimeEnvironment() } - }, - signal: signal ?? pluginAbortController.signal, - transport: { - args: [runtimePath, "app-server"], - command: node, - cwd: workingDirectory, - env: runtimeEnvironment() - } - }), + }); + }, signal: pluginAbortController.signal }); } finally { diff --git a/src/plugin-cli.ts b/src/plugin-cli.ts index 467c48ba..2087928a 100644 --- a/src/plugin-cli.ts +++ b/src/plugin-cli.ts @@ -432,6 +432,7 @@ export async function runPluginCommand( if (!command.yes && !await confirm(`Add marketplace from ${printable(value)}?`)) { throw new Error("Marketplace addition cancelled. Use --yes for non-interactive use."); } + if (!command.json) stdout.write("Adding marketplace...\n"); const result = await call(pluginProtocolMethods.marketplaceAdd, { source: value }); print(result, () => renderMutation(stdout, result, { failure: "Marketplace addition failed.", diff --git a/test/README.md b/test/README.md index add37d57..60b605fe 100644 --- a/test/README.md +++ b/test/README.md @@ -60,6 +60,7 @@ Counts describe this reset, not an assertion that future suites must have a fixe | File | Failure this must prevent | | --- | --- | | `launcher.test.ts` | Keyless prompts run, missing sessions leak diagnostics, repeated cancellation leaves the runtime alive, or a local plugin cannot be installed and discovered. | +| `plugin-cancellation.test.ts` | A stalled marketplace add leaves its native storage lock after cancellation or timeout, blocking the next command. | | `app-server-auth.test.ts` | Real protocol turns use the wrong credential owner, fail to rotate keys, or fall back from missing credentials to host authentication. | | `settings-file.test.ts` | Runtime writes and trust changes escape a host-selected settings store or change native MCP precedence. | | `config-migration.test.ts` | Migration loses providers, overwrites conflicting/invalid configuration, or runs twice concurrently. | diff --git a/test/app-server-client.test.ts b/test/app-server-client.test.ts index 10da5952..8a813b9e 100644 --- a/test/app-server-client.test.ts +++ b/test/app-server-client.test.ts @@ -3,6 +3,7 @@ import { describe, expect, test } from "bun:test"; import { AppServerProcessError, AppServerRequestError, + AppServerTimeoutError, requestAppServer } from "../src/app-server-client.ts"; @@ -78,12 +79,13 @@ describe("app-server NDJSON client", () => { })).rejects.toMatchObject({ name: "AbortError" }); }); - test("finishes cancellation when the app-server ignores SIGTERM", async () => { + test.each([false, true])("finishes cancellation when the app-server ignores SIGTERM (cooperative: %s)", async cooperative => { const controller = new AbortController(); const pending = requestAppServer({ method: "plugins/list", params: {}, signal: controller.signal, + ...(cooperative ? { cancellation: { method: "plugins/cancelOperation", params: { operationId: "fixture" } } } : {}), transport: transport(` process.on("SIGTERM", () => {}); process.stdin.resume(); @@ -93,6 +95,17 @@ describe("app-server NDJSON client", () => { setTimeout(() => controller.abort(), 150); await expect(pending).rejects.toMatchObject({ name: "AbortError" }); - }, 3_000); + }, 6_000); + + test.each([false, true])("times out a stalled request instead of waiting for process exit (reply: %s)", async reply => { + await expect(requestAppServer({ + method: "plugins/overview", params: {}, timeoutMs: 100, + transport: transport(` + process.stdin.resume(); + ${reply ? 'process.stdin.once("data", () => console.log(JSON.stringify({ id: 1, result: {} })));' : ""} + setInterval(() => {}, 1000); + `) + })).rejects.toBeInstanceOf(AppServerTimeoutError); + }, 2_000); }); diff --git a/test/runtime/plugin-cancellation.test.ts b/test/runtime/plugin-cancellation.test.ts new file mode 100644 index 00000000..8b7a3a75 --- /dev/null +++ b/test/runtime/plugin-cancellation.test.ts @@ -0,0 +1,58 @@ +import { expect, test } from "bun:test"; +import { mkdtemp, readdir, rm, stat } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { runtimeTestEnv } from "../fixtures/runtime-env.ts"; + +const root = join(import.meta.dir, "../.."); + +test.skipIf(process.platform === "win32").each(["signal", "timeout"] as const)( + "a stalled marketplace add releases its native lock on %s and allows the next add", async kind => { + const home = await mkdtemp(join(tmpdir(), "zcode-plugin-cancel-")); + let started!: () => void; + const downloading = new Promise(resolve => { started = resolve; }); + const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { + if (new URL(request.url).pathname === "/stalled.json") { + started(); + return await new Promise(() => {}); + } + return Response.json({ name: "recovered-marketplace", plugins: [] }); + } }); + const env = { ...runtimeTestEnv(home), + http_proxy: "", https_proxy: "", HTTP_PROXY: "", HTTPS_PROXY: "", all_proxy: "", ALL_PROXY: "", + ZCODE_PLUGIN_REQUEST_TIMEOUT_MS: kind === "timeout" ? "5000" : "15000" }; + const launch = (path: string) => Bun.spawn([ + Bun.which("node")!, join(root, "bin/zcode.js"), "plugins", "marketplace", "add", `${server.url.origin}/${path}`, "--yes", "--json" + ], { cwd: home, env, stdin: "ignore", stdout: "pipe", stderr: "pipe" }); + let child = launch("stalled.json"); + const deadline = setTimeout(() => child.kill("SIGKILL"), 20_000); + const lock = join(home, ".zcode/cli/plugins/installed_plugins.json.lock"); + try { + const output = Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text()]); + // The request starts after the runtime acquires the real mutation lock. + await Promise.race([downloading, child.exited.then(() => { throw new Error("Add exited before starting the download."); })]); + expect((await readdir(lock)).some(name => name.startsWith("owner-"))).toBe(true); + if (kind === "signal") child.kill("SIGTERM"); + const code = await child.exited; + const [stdout, stderr] = await output; + expect(code, `${stdout}\n${stderr}`).toBe(kind === "signal" ? 143 : 1); + expect(stderr).toContain(kind === "signal" ? "App-server request cancelled." : "timed out after 5000ms"); + await expect(stat(lock)).rejects.toMatchObject({ code: "ENOENT" }); + + child = launch("healthy.json"); + const [nextCode, nextOut, nextErr] = await Promise.all([ + child.exited, new Response(child.stdout).text(), new Response(child.stderr).text() + ]); + expect(nextCode, nextErr).toBe(0); + expect(JSON.parse(nextOut)).toMatchObject({ marketplace: { id: "recovered-marketplace" }, diagnostics: [] }); + await expect(stat(lock)).rejects.toMatchObject({ code: "ENOENT" }); + } finally { + clearTimeout(deadline); + if (child.exitCode === null) child.kill("SIGKILL"); + await child.exited; + server.stop(true); + await rm(home, { recursive: true, force: true }); + } + }, 25_000 +);