Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix(server): deleting a session or workspace stops its work first and never brings a folder back

Samrat Talukdar9e7060258a63
diff --git a/apps/server/src/embedded.ts b/apps/server/src/embedded.ts
index 3b6ab60d..fa17abd0 100644
--- a/apps/server/src/embedded.ts
+++ b/apps/server/src/embedded.ts
@@ -198,7 +198,9 @@ export async function startEmbeddedServer(options: EmbeddedServerOptions): Promi
};
if (!config.readOnly) {
- await ensureLocalWorkspaceFiles(config.workspaces);
+ // The desktop creates a workspace's folder when it adds the workspace; a
+ // registered workspace whose folder is gone is never recreated at startup.
+ await ensureLocalWorkspaceFiles(config.workspaces, { createMissing: false });
// First among the runtime-DB migrations: the store drops leftover
// registry launches on any write, before this could rewrite them.
await migrateLegacyOmniRushUiMcpCommand(config, options.omnirushUiMcp ?? null);
diff --git a/apps/server/src/opencode-proxy.e2e.test.ts b/apps/server/src/opencode-proxy.e2e.test.ts
index 9ec205a6..13243870 100644
--- a/apps/server/src/opencode-proxy.e2e.test.ts
+++ b/apps/server/src/opencode-proxy.e2e.test.ts
@@ -1,5 +1,5 @@
import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test";
-import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { mkdtemp, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -615,3 +615,132 @@ describe("workspace OpenCode proxy", () => {
});
});
});
+
+// An engine holding a running session with a sub-agent in another folder, as
+// OpenCode answers the reads, aborts and delete the local server sends.
+function startSessionTreeEngine(input: { childDirectory: string; busy?: string[] }) {
+ const requests: Array<{ method: string; pathname: string; directory: string | null }> = [];
+ const running = new Set(input.busy ?? ["ses_parent", "ses_child"]);
+ const deleted = new Set<string>();
+ const server = Bun.serve({
+ hostname: "127.0.0.1",
+ port: 0,
+ fetch(request) {
+ const url = new URL(request.url);
+ const directory = request.headers.get("x-opencode-directory");
+ requests.push({ method: request.method, pathname: url.pathname, directory });
+ const sessions: Record<string, { directory: string | null; parentID?: string }> = {
+ ses_parent: { directory },
+ ses_child: { directory: input.childDirectory, parentID: "ses_parent" },
+ };
+ if (url.pathname === "/session/status") {
+ return Response.json(Object.fromEntries([...running].map((id) => [id, { type: "busy" }])));
+ }
+ const match = url.pathname.match(/^\/session\/([^/]+)(\/children|\/abort)?$/);
+ const id = match?.[1] ?? "";
+ if (!match || !sessions[id] || deleted.has(id)) return Response.json({ name: "NotFoundError" }, { status: 404 });
+ if (match[2] === "/abort") {
+ running.delete(id);
+ return Response.json(true);
+ }
+ if (match[2] === "/children") {
+ return Response.json(Object.entries(sessions).filter(([, s]) => s.parentID === id).map(([childId, s]) => ({ id: childId, ...s })));
+ }
+ if (request.method === "DELETE") {
+ deleted.add(id);
+ deleted.add("ses_child");
+ return Response.json(true);
+ }
+ return Response.json({ id, ...sessions[id] });
+ },
+ }) as Served;
+ stops.push(() => server.stop(true));
+ return { server, requests, running };
+}
+
+describe("deleting sessions and workspaces", () => {
+ test("a session delete stops the session and its sub-agents first, each in its own folder", async () => {
+ const workspaceRoot = await createWorkspaceRoot();
+ const childDirectory = await createWorkspaceRoot("elsewhere");
+ const engine = startSessionTreeEngine({ childDirectory });
+ const omnirush = await startOmniRushServer({ workspaceRoot, opencodeBaseUrl: `http://127.0.0.1:${engine.server.port}`, readOnly: false });
+
+ const response = await fetch(`http://127.0.0.1:${omnirush.server.port}/workspace/ws_1/opencode/session/ses_parent`, {
+ method: "DELETE",
+ headers: auth(omnirush.token),
+ });
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toBe(true);
+ expect([...engine.running]).toEqual([]);
+ const aborts = engine.requests.filter((request) => request.pathname.endsWith("/abort"));
+ expect(aborts.map((request) => [request.pathname, request.directory])).toEqual(expect.arrayContaining([
+ ["/session/ses_parent/abort", workspaceRoot],
+ ["/session/ses_child/abort", childDirectory],
+ ]));
+ const deleteIndex = engine.requests.findIndex((request) => request.method === "DELETE");
+ expect(deleteIndex).toBeGreaterThan(Math.max(...aborts.map((request) => engine.requests.indexOf(request))));
+ });
+
+ test("a delete of a session that is already gone still answers the engine's not-found", async () => {
+ const workspaceRoot = await createWorkspaceRoot();
+ const engine = startSessionTreeEngine({ childDirectory: workspaceRoot });
+ const omnirush = await startOmniRushServer({ workspaceRoot, opencodeBaseUrl: `http://127.0.0.1:${engine.server.port}`, readOnly: false });
+
+ const response = await fetch(`http://127.0.0.1:${omnirush.server.port}/workspace/ws_1/opencode/session/ses_missing`, {
+ method: "DELETE",
+ headers: auth(omnirush.token),
+ });
+
+ expect(response.status).toBe(404);
+ expect(engine.requests.filter((request) => request.pathname.endsWith("/abort"))).toEqual([]);
+ });
+
+ test("reading or removing a workspace whose folder was deleted never recreates the folder", async () => {
+ const parent = await createWorkspaceRoot();
+ const workspaceRoot = join(parent, "project");
+ await mkdir(workspaceRoot, { recursive: true });
+ const engine = startSessionTreeEngine({ childDirectory: workspaceRoot, busy: ["ses_parent"] });
+ const omnirush = await startOmniRushServer({ workspaceRoot, opencodeBaseUrl: `http://127.0.0.1:${engine.server.port}`, readOnly: false });
+ omnirush.config.configPath = join(parent, "server.json");
+ const base = `http://127.0.0.1:${omnirush.server.port}`;
+ await rm(workspaceRoot, { recursive: true, force: true });
+
+ const read = await fetch(`${base}/workspace/ws_1/opencode-config?scope=project`, { headers: auth(omnirush.token) });
+ await read.body?.cancel();
+ expect(await stat(workspaceRoot).catch(() => null)).toBeNull();
+
+ const removed = await fetch(`${base}/workspaces/ws_1`, {
+ method: "DELETE",
+ headers: { ...auth(omnirush.token), "X-OmniRush-Host-Token": "owt_host_token" },
+ });
+ expect(removed.status).toBe(200);
+ expect(await removed.json()).toMatchObject({ deleted: true, persisted: true, items: [] });
+ expect(await stat(workspaceRoot).catch(() => null)).toBeNull();
+ // Its running session was stopped before the workspace went away.
+ expect(engine.requests.some((request) => request.pathname === "/session/ses_parent/abort" && request.directory === workspaceRoot)).toBe(true);
+ expect([...engine.running]).toEqual([]);
+ const saved: unknown = JSON.parse(await readFile(join(parent, "server.json"), "utf8"));
+ expect(saved).toMatchObject({ workspaces: [] });
+ });
+
+ test("a workspace removal that cannot be saved keeps the workspace and says so", async () => {
+ const parent = await createWorkspaceRoot();
+ const workspaceRoot = join(parent, "project");
+ await mkdir(workspaceRoot, { recursive: true });
+ const blocker = join(parent, "not-a-directory");
+ await writeFile(blocker, "x");
+ const omnirush = await startOmniRushServer({ workspaceRoot, readOnly: false });
+ omnirush.config.configPath = join(blocker, "server.json");
+ const base = `http://127.0.0.1:${omnirush.server.port}`;
+
+ const removed = await fetch(`${base}/workspaces/ws_1`, {
+ method: "DELETE",
+ headers: { ...auth(omnirush.token), "X-OmniRush-Host-Token": "owt_host_token" },
+ });
+
+ expect(removed.status).toBe(500);
+ expect(await removed.json()).toMatchObject({ code: "workspace_registry_write_failed" });
+ expect(omnirush.config.workspaces.map((workspace) => workspace.id)).toEqual(["ws_1"]);
+ });
+});
diff --git a/apps/server/src/routes/workspaces.ts b/apps/server/src/routes/workspaces.ts
index 2ec1cf80..e06a95dd 100644
--- a/apps/server/src/routes/workspaces.ts
+++ b/apps/server/src/routes/workspaces.ts
@@ -32,6 +32,12 @@ interface RegisterWorkspaceRoutesOptions {
* so activation never reloads or disposes an engine instance.
*/
syncWorkspaceRuntimeMcp: (config: ServerConfig, workspace: WorkspaceInfo) => Promise<void>;
+ /**
+ * Stops everything that may still write into a workspace being removed: its
+ * running sessions are aborted and its engine instance (file watcher, tool
+ * processes, open handles) is released. Best effort; never throws.
+ */
+ stopWorkspaceWork?: (config: ServerConfig, workspace: WorkspaceInfo) => Promise<void>;
}
function isRecord(value: unknown): value is Record<string, unknown> {
@@ -213,6 +219,27 @@ function serializeWorkspaceConfigEntry(workspace: WorkspaceInfo): Record<string,
};
}
+const RENAME_RETRY_DELAYS_MS = [50, 150, 400, 1_000];
+
+/**
+ * Windows refuses to replace a file another process has open for a moment
+ * (antivirus, indexer, a concurrent reader): EPERM, EACCES or EBUSY. Those
+ * clear on their own; a registry change must not be lost to one.
+ */
+async function renameWithRetry(from: string, to: string): Promise<void> {
+ for (let attempt = 0; ; attempt += 1) {
+ try {
+ await rename(from, to);
+ return;
+ } catch (error) {
+ const code = isRecord(error) && typeof error.code === "string" ? error.code : "";
+ const delay = RENAME_RETRY_DELAYS_MS[attempt];
+ if (delay === undefined || !["EPERM", "EACCES", "EBUSY"].includes(code)) throw error;
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, delay));
+ }
+ }
+}
+
async function persistServerWorkspaceState(config: ServerConfig): Promise<boolean> {
const configPath = config.configPath?.trim() ?? "";
if (!configPath) return false;
@@ -228,7 +255,7 @@ async function persistServerWorkspaceState(config: ServerConfig): Promise<boolea
const tmpPath = `${configPath}.tmp.${shortId()}`;
try {
await writeFile(tmpPath, `${JSON.stringify(next, null, 2)}\n`, "utf8");
- await rename(tmpPath, configPath);
+ await renameWithRetry(tmpPath, configPath);
return true;
} finally {
try {
@@ -490,17 +517,39 @@ export function registerWorkspaceRoutes(options: RegisterWorkspaceRoutesOptions)
addRoute(routes, "DELETE", "/workspaces/:id", "host", async (ctx) => {
ensureWritable(config);
- const workspace = await resolveWorkspaceForRegistry(ctx.params.id);
+ // Only the registry entry: resolving the workspace would bootstrap it,
+ // recreating a folder the person already deleted, and a folder that is
+ // gone or locked must never block its removal.
+ const workspaceId = ctx.params.id.trim();
+ const aliasWorkspaceId = workspaceId.startsWith("rem_") ? workspaceId.slice("rem_".length) : "";
+ const workspace = config.workspaces.find((entry) => entry.id === workspaceId)
+ ?? (aliasWorkspaceId ? config.workspaces.find((entry) => entry.id === aliasWorkspaceId) : undefined);
+ if (!workspace) {
+ throw new ApiError(404, "workspace_not_found", "Workspace not found");
+ }
+ if (workspace.workspaceType !== "remote") await options.stopWorkspaceWork?.(config, workspace);
- const before = config.workspaces.length;
+ const previousWorkspaces = config.workspaces;
+ const previousAuthorizedRoots = config.authorizedRoots;
config.workspaces = config.workspaces.filter((entry) => entry.id !== workspace.id);
- const deleted = before !== config.workspaces.length;
+ const deleted = previousWorkspaces.length !== config.workspaces.length;
if (deleted && workspace.workspaceType === "local") {
// Only remove exact matches; authorizedRoots can contain broader entries.
config.authorizedRoots = config.authorizedRoots.filter((root) => resolve(root) !== resolve(workspace.path));
}
- const persisted = await persistServerWorkspaceState(config);
+ let persisted: boolean;
+ try {
+ persisted = await persistServerWorkspaceState(config);
+ } catch (error) {
+ // Not saved: the next start would bring the workspace back, so it stays
+ // listed now too and the person sees the failure instead.
+ config.workspaces = previousWorkspaces;
+ config.authorizedRoots = previousAuthorizedRoots;
+ throw new ApiError(500, "workspace_registry_write_failed", "The workspace could not be removed: saving the workspace list failed", {
+ cause: error instanceof Error ? error.message : String(error),
+ });
+ }
onWorkspacesChanged();
await recordAudit(workspace.path, {
@@ -511,7 +560,7 @@ export function registerWorkspaceRoutes(options: RegisterWorkspaceRoutesOptions)
target: "workspace",
summary: "Deleted workspace from OmniRush.ai server",
timestamp: Date.now(),
- });
+ }).catch(() => undefined); // The removal is saved; a failed audit line must not report it as failed.
const active = config.workspaces[0] ?? null;
return jsonResponse({
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 10991e71..7f423637 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -874,6 +874,57 @@ function collectorDeletedSessionId(method: string, proxyPath: string): string |
return match?.[1] ? decodeEngineRouteParam(match[1]) : null;
}
+type EngineRequestTarget = { baseUrl: string; headers: Headers };
+
+const SESSION_STOP_TIMEOUT_MS = 5_000;
+const SESSION_STOP_MAX_SESSIONS = 100;
+
+async function engineJson(target: EngineRequestTarget, path: string, directory: string | null, init?: { method: string }): Promise<unknown> {
+ const scoped = scopeWorkspaceOpencodeRequest(target.headers, "", directory);
+ const response = await loopbackFetch(buildOpencodeProxyUrl(target.baseUrl, path, scoped.search), {
+ method: init?.method ?? "GET",
+ headers: scoped.headers,
+ signal: AbortSignal.timeout(SESSION_STOP_TIMEOUT_MS),
+ });
+ if (!response.ok) {
+ await response.body?.cancel().catch(() => undefined);
+ return null;
+ }
+ return response.json().catch(() => null);
+}
+
+/**
+ * The engine's session delete removes the records and cancels background
+ * jobs, not the session's own run: a turn inside a long tool call goes on
+ * running (and writing into the folder) with its status stuck on busy, which
+ * also parks every engine restart that waits for running sessions. Abort the
+ * session and its sub-agent sessions first, each in its own folder's engine
+ * instance (the one its run lives in) and on every engine that may run it.
+ * Best effort and bounded: the delete goes ahead whatever this finds.
+ */
+async function stopSessionTreeBeforeDelete(targets: EngineRequestTarget[], sessionId: string, requestDirectory: string | null): Promise<void> {
+ await Promise.all(targets.map(async (target) => {
+ const sessions: Array<{ id: string; directory: string | null }> = [];
+ const queue = [sessionId];
+ const seen = new Set<string>();
+ while (queue.length > 0 && sessions.length < SESSION_STOP_MAX_SESSIONS) {
+ const id = queue.shift() ?? "";
+ if (seen.has(id)) continue;
+ seen.add(id);
+ const info = await engineJson(target, `/session/${encodeURIComponent(id)}`, requestDirectory).catch(() => null);
+ if (!isRecord(info)) continue;
+ sessions.push({ id, directory: typeof info.directory === "string" && info.directory.trim() ? info.directory : null });
+ const children = await engineJson(target, `/session/${encodeURIComponent(id)}/children`, requestDirectory).catch(() => null);
+ if (Array.isArray(children)) {
+ for (const child of children) if (isRecord(child) && typeof child.id === "string") queue.push(child.id);
+ }
+ }
+ await Promise.all(sessions.map((session) =>
+ engineJson(target, `/session/${encodeURIComponent(session.id)}/abort`, session.directory, { method: "POST" }).catch(() => null),
+ ));
+ }));
+}
+
export async function startServer(config: ServerConfig): Promise<ServeResult> {
let taskRecovery: Awaited<ReturnType<typeof createTaskRecovery>> | undefined;
const approvals = new ApprovalService(config.approval);
@@ -2113,6 +2164,15 @@ export async function proxyOpencodeRequest(input: {
return response;
};
+ if (deletedCollectedSessionId && workspace && workspace.workspaceType !== "remote") {
+ await stopSessionTreeBeforeDelete(
+ pool
+ ? pool.connections().map((connection) => ({ baseUrl: connection.baseUrl, headers: headersForEngineConnection(headers, connection) }))
+ : [{ baseUrl, headers }],
+ deletedCollectedSessionId,
+ directory,
+ );
+ }
if (workspace && workspace.workspaceType !== "remote" && isPromptAsyncProxyRequest(method, proxyPath)) {
return withEngineDirectoryFence(input.config, workspace, forwardAndCollect);
}
@@ -2867,6 +2927,7 @@ function createRoutes(
serverState: activeEngineMcpServerState(routeConfig),
trigger: "workspace_activate",
}),
+ stopWorkspaceWork: stopWorkspaceEngineWork,
});
registerSessionGroupRoutes({
@@ -4685,7 +4746,7 @@ async function resolveWorkspace(config: ServerConfig, id: string): Promise<Works
const workspace = await resolveWorkspaceWithoutBootstrap(config, id);
const resolvedWorkspace = workspace.path;
if (!config.readOnly) {
- const ensured = await ensureWorkspaceFiles(resolvedWorkspace, workspace.preset ?? "starter");
+ const ensured = await ensureWorkspaceFiles(resolvedWorkspace, workspace.preset ?? "starter", { createMissing: false });
const bootstrapReloadReasons = new Set<ReloadReason>(ensured.reloadReasons);
if (await repairCommands(resolvedWorkspace)) {
bootstrapReloadReasons.add("commands");
@@ -5239,6 +5300,50 @@ async function disposeIdleEngineInstance(
if (!response.ok) throw new Error(`OpenCode instance dispose failed with status ${response.status}`);
}
+/**
+ * Before a local workspace is removed: abort its running sessions and, on the
+ * engines this server manages, dispose its per-folder instance, so no agent
+ * run, tool process, file watcher or open handle keeps writing into the
+ * folder (and bringing it back after the person deletes it) or keeps it
+ * locked on Windows. Bounded; a failure never blocks the removal.
+ */
+async function stopWorkspaceEngineWork(config: ServerConfig, workspace: WorkspaceInfo): Promise<void> {
+ const directory = resolveOpencodeDirectory(workspace);
+ if (!directory) return;
+ const pool = enginePoolForConfig(config);
+ const connection = pool ? null : resolveWorkspaceOpencodeConnection(config, workspace);
+ const targets: EngineRequestTarget[] = pool
+ ? pool.connections().map((entry) => ({
+ baseUrl: entry.baseUrl,
+ headers: new Headers({ Authorization: buildEngineAuthProbeHeader(entry.username, entry.password) }),
+ }))
+ : connection?.baseUrl?.trim()
+ ? [{ baseUrl: connection.baseUrl.trim(), headers: new Headers(connection.authHeader ? { Authorization: connection.authHeader } : {}) }]
+ : [];
+ await Promise.all(targets.map(async (target) => {
+ const statuses = await engineJson(target, "/session/status", directory).catch(() => null);
+ const busy = isRecord(statuses)
+ ? Object.entries(statuses).flatMap(([id, status]) => isRecord(status) && status.type !== "idle" ? [id] : [])
+ : [];
+ await Promise.all(busy.map((id) =>
+ engineJson(target, `/session/${encodeURIComponent(id)}/abort`, directory, { method: "POST" }).catch(() => null),
+ ));
+ if (!pool) return;
+ await loopbackFetch(buildOpencodeReloadUrl(target.baseUrl, directory), {
+ method: "POST",
+ headers: target.headers,
+ signal: AbortSignal.timeout(Math.min(opencodeDisposeTimeoutMs(), 2 * SESSION_STOP_TIMEOUT_MS)),
+ }).then((response) => response.body?.cancel()).catch((error: unknown) => {
+ createServerLogger(config).log("warn", "Engine instance dispose for a removed workspace failed.", {
+ "workspace.id": workspace.id,
+ "error.message": error instanceof Error ? error.message : String(error),
+ });
+ });
+ }));
+ const mcpState = activeEngineMcpServerState(config);
+ if (mcpState) invalidateEngineMcpWorkspace(mcpState, workspace.id);
+}
+
/**
* Record engine traffic for a local workspace's directory instance. When this
* is the first traffic after that instance was evicted, re-attach the state a
diff --git a/apps/server/src/task-recovery.test.ts b/apps/server/src/task-recovery.test.ts
index 7f4712d7..a6de50e3 100644
--- a/apps/server/src/task-recovery.test.ts
+++ b/apps/server/src/task-recovery.test.ts
@@ -257,3 +257,41 @@ for (const engine of ["v1", "v2"] as const) {
expect(f.resumes).toEqual([]);
});
}
+
+test("stop and delete never queue behind a session's long synchronous request", async () => {
+ const root = await mkdtemp(join(tmpdir(), "task-recovery-"));
+ const previousDb = process.env.OMNIRUSH_RUNTIME_DB;
+ process.env.OMNIRUSH_RUNTIME_DB = join(root, "runtime.sqlite");
+ const workspace = { id: "ws", name: "Work", path: root, preset: "starter", workspaceType: "local" as const };
+ const config: ServerConfig = {
+ host: "127.0.0.1", port: 1234, token: "test-token", hostToken: "test-host", configPath: join(root, "server.json"),
+ approval: { mode: "auto", timeoutMs: 1000 }, corsOrigins: [], workspaces: [workspace], authorizedRoots: [root],
+ readOnly: false, startedAt: Date.now(), tokenSource: "generated", hostTokenSource: "generated", logFormat: "json", logRequests: false,
+ };
+ const recovery = await createTaskRecovery(config, async () => new Response(null, { status: 204 }));
+ cleanups.push(async () => {
+ await recovery.stop();
+ if (previousDb === undefined) delete process.env.OMNIRUSH_RUNTIME_DB;
+ else process.env.OMNIRUSH_RUNTIME_DB = previousDb;
+ await rm(root, { recursive: true, force: true });
+ });
+ const forward = (method: string, path: string, send: () => Promise<Response>) =>
+ recovery.forward(workspace, "v1", `/opencode${path}`, new Request(`http://localhost/workspace/ws/opencode${path}`, { method }), send);
+ const sent: string[] = [];
+ let finishShell: () => void = () => undefined;
+ // A `!` shell command: the engine answers only when the command ends.
+ const shell = forward("POST", "/session/ses_1/shell", () => new Promise<Response>((resolve) => {
+ sent.push("shell");
+ finishShell = () => resolve(Response.json({}));
+ }));
+ await Bun.sleep(20);
+ const revert = forward("POST", "/session/ses_1/revert", async () => { sent.push("revert"); return Response.json(true); });
+ const abort = await forward("POST", "/session/ses_1/abort", async () => { sent.push("abort"); return Response.json(true); });
+ const deleted = await forward("DELETE", "/session/ses_1", async () => { sent.push("delete"); return Response.json(true); });
+ expect([abort.status, deleted.status]).toEqual([200, 200]);
+ // Other mutations still wait their turn behind the running command.
+ expect(sent).toEqual(["shell", "abort", "delete"]);
+ finishShell();
+ await Promise.all([shell, revert]);
+ expect(sent).toEqual(["shell", "abort", "delete", "revert"]);
+});
diff --git a/apps/server/src/task-recovery.ts b/apps/server/src/task-recovery.ts
index d37111dd..cfbe6ee0 100644
--- a/apps/server/src/task-recovery.ts
+++ b/apps/server/src/task-recovery.ts
@@ -255,7 +255,14 @@ export async function createTaskRecovery(
observingSince.set(key(record), Date.now());
}
await persist();
- const response = await serializedSend();
+ // Stop and delete never queue behind the session's in-flight mutations:
+ // a synchronous shell command or compaction holds its slot until it
+ // ends, which is exactly what the person is trying to stop or discard.
+ // The record above is already invalidated, so a queued recovery send
+ // for this session cancels itself instead of racing them.
+ const interrupts = (req.method === "DELETE" && suffix === "")
+ || (req.method === "POST" && /^\/(?:abort|interrupt)$/.test(suffix));
+ const response = await (interrupts ? send() : serializedSend());
if (current(record) && !response.ok) { remove(record); await persist(); }
return response;
},
diff --git a/apps/server/src/workspace-init.test.ts b/apps/server/src/workspace-init.test.ts
index e6631e0e..6306bf18 100644
--- a/apps/server/src/workspace-init.test.ts
+++ b/apps/server/src/workspace-init.test.ts
@@ -177,6 +177,15 @@ describe("ensureWorkspaceFiles", () => {
});
describe("ensureLocalWorkspaceFiles", () => {
+ test("never recreates the deleted folder of a registered workspace", async () => {
+ await withWorkspace(async (root) => {
+ const deleted = join(root, "deleted-project");
+ await expect(ensureWorkspaceFiles(deleted, "starter", { createMissing: false })).resolves.toEqual({ changed: false, reloadReasons: [] });
+ await ensureLocalWorkspaceFiles([{ path: deleted, preset: "starter", workspaceType: "local" }], { createMissing: false });
+ await expect(stat(deleted)).rejects.toThrow();
+ });
+ });
+
test("continues provisioning after an uncreatable workspace path", async () => {
await withWorkspace(async (root) => {
const blockingFile = join(root, "blocking-file");
diff --git a/apps/server/src/workspace-init.ts b/apps/server/src/workspace-init.ts
index e36c2c70..19071d58 100644
--- a/apps/server/src/workspace-init.ts
+++ b/apps/server/src/workspace-init.ts
@@ -66,11 +66,24 @@ async function ensureOpencodeConfig(workspaceRoot: string): Promise<boolean> {
return false;
}
-export async function ensureWorkspaceFiles(workspaceRoot: string, presetInput: string): Promise<EnsureWorkspaceFilesResult> {
+/**
+ * `createMissing: false` is for a workspace that is already registered: its
+ * folder is never recreated. A folder the person deleted (or is deleting,
+ * with the workspace about to be removed) must stay gone; only creating a
+ * workspace makes its folder.
+ */
+export async function ensureWorkspaceFiles(
+ workspaceRoot: string,
+ presetInput: string,
+ options: { createMissing?: boolean } = {},
+): Promise<EnsureWorkspaceFilesResult> {
const preset = normalizePreset(presetInput);
if (!workspaceRoot.trim()) {
throw new ApiError(400, "invalid_workspace_path", "workspace path is required");
}
+ if (options.createMissing === false && !(await exists(workspaceRoot))) {
+ return { changed: false, reloadReasons: [] };
+ }
try {
await ensureDir(workspaceRoot);
} catch (error) {
@@ -104,11 +117,12 @@ export async function ensureWorkspaceFiles(workspaceRoot: string, presetInput: s
*/
export async function ensureLocalWorkspaceFiles(
workspaces: ReadonlyArray<Pick<WorkspaceInfo, "path" | "preset" | "workspaceType">>,
+ options: { createMissing?: boolean } = {},
): Promise<void> {
for (const workspace of workspaces) {
if (workspace.workspaceType === "remote" || !workspace.path.trim()) continue;
try {
- await ensureWorkspaceFiles(workspace.path, workspace.preset);
+ await ensureWorkspaceFiles(workspace.path, workspace.preset, options);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.warn(`Failed to provision workspace files at ${workspace.path}: ${message}`);