A desktop coding agent with free access to frontier models.
TypeScript
fix: safer task removal and start note
Samrat Talukdaraac427d1667e
diff --git a/apps/app/src/app/lib/omnirush-server.ts b/apps/app/src/app/lib/omnirush-server.tsindex 5cc5886e..2070d530 100644--- a/apps/app/src/app/lib/omnirush-server.ts+++ b/apps/app/src/app/lib/omnirush-server.ts@@ -269,6 +269,9 @@ export type OmniRushWorkspaceTask = {label: string;branch: string;baseBranch: string | null;+ baseCommit: string;+ /** The main checkout had uncommitted changes when the task started: they are not in it. */+ startedDirty: boolean;name: string;path: string;workspaceId: string | null;diff --git a/apps/app/src/react-app/domains/workspace/tasks/tasks-board-page.tsx b/apps/app/src/react-app/domains/workspace/tasks/tasks-board-page.tsxindex dad49646..891c50c0 100644--- a/apps/app/src/react-app/domains/workspace/tasks/tasks-board-page.tsx+++ b/apps/app/src/react-app/domains/workspace/tasks/tasks-board-page.tsx@@ -34,7 +34,7 @@ export type TasksBoardPageProps = {workspaceId: string;workspaceName: string;/** Creates the task and sends its prompt in its own chat, like the composer. */- onStartTask: (prompt: string) => Promise<void>;+ onStartTask: (prompt: string) => Promise<OmniRushWorkspaceTask>;onOpenChat: (workspaceId: string, sessionId: string | null) => void;/** The workspace list changed (a task's workspace was added or removed). */onWorkspacesChanged: () => void;@@ -95,10 +95,10 @@ export function TasksBoardPage(props: TasksBoardPageProps) {if (!text || starting) return;setStarting(true);try {- await props.onStartTask(text);+ const task = await props.onStartTask(text);setPrompt("");setNewOpen(false);- toast.success("Task started in its own copy of the repository");+ toast.success("Task started in its own copy of the repository", task.startedDirty ? { description: dirtyNote(task) } : undefined);} catch (error) {toast.error(errorMessage(error));} finally {@@ -315,6 +315,10 @@ export function TasksBoardPage(props: TasksBoardPageProps) {);}+function dirtyNote(task: Pick<OmniRushWorkspaceTask, "baseCommit">): string {+ return `It starts from the last commit (${task.baseCommit.slice(0, 7)}); your uncommitted changes are not in it.`;+}+function confirmMessage(pending: PendingAction, branch: string | null): string {const into = branch ? ` (${branch})` : "";if (pending.kind === "apply") {@@ -365,6 +369,7 @@ function TaskCard({ task, busy, ...actions }: TaskCardProps) {{task.age ? <span>Started {task.age}</span> : null}{task.result ? <span>{task.result.mode === "apply" ? "Applied" : "Merged"} {plural(task.result.files, "file")}</span> : null}</div>+ {task.startedDirty && !task.result ? <p className="text-xs text-muted-foreground" data-testid="task-dirty-note">{dirtyNote(task)}</p> : null}<div className="mt-auto flex flex-wrap gap-1.5"><Button size="sm" variant="outline" onClick={actions.onOpenChat} disabled={!task.workspaceId || !task.sessionId}><MessageSquare /> Open chatdiff --git a/apps/app/src/react-app/shell/session-route.tsx b/apps/app/src/react-app/shell/session-route.tsxindex 40c7914f..531f016e 100644--- a/apps/app/src/react-app/shell/session-route.tsx+++ b/apps/app/src/react-app/shell/session-route.tsx@@ -3296,6 +3296,7 @@ export function SessionRoute() {if (model) useSessionModelStore.getState().setModel(session.id, model, modelVariantValue ?? null);writeLastSessionFor(taskWorkspace.id, session.id);void queryClient.invalidateQueries({ queryKey: workspaceTasksQueryKey(workspaceId) });+ return created.task;}, [baseUrl, client, environmentRuntimeKey, local.prefs.defaultModel, modelVariantValue, queryClient, refreshRouteState, selectedAgent, selectedSessionId, token]);// The new task's folder, picked above its composer: switch to anotherdiff --git a/apps/app/tests/workspace-tasks-board.test.tsx b/apps/app/tests/workspace-tasks-board.test.tsxindex 2f942abf..2d01b41c 100644--- a/apps/app/tests/workspace-tasks-board.test.tsx+++ b/apps/app/tests/workspace-tasks-board.test.tsx@@ -25,7 +25,7 @@ type Root = ReturnType<typeof createRoot>;function task(overrides: Partial<OmniRushWorkspaceTask>): OmniRushWorkspaceTask {return {id: "t1", title: "Add a greeting", prompt: "Add a greeting", state: "running", label: "running",- branch: "omnirush/add-a-greeting-ab12", baseBranch: "main", name: "app › add-a-greeting-ab12",+ branch: "omnirush/add-a-greeting-ab12", baseBranch: "main", baseCommit: "0123456789abcdef0123456789abcdef01234567", startedDirty: false, name: "app › add-a-greeting-ab12",path: "/code/app-tasks/add-a-greeting-ab12", workspaceId: "ws_task1", sessionId: "ses_1",createdAt: "2026-10-20T00:00:00.000Z", startedAt: "2026-10-20T00:00:00.000Z", finishedAt: null,age: "2 min ago", files: 1, finished: false, result: null, ...overrides,@@ -71,7 +71,7 @@ async function mount(client: WorkspaceTasksClient, extra: { opened?: string[]; sclient={client}workspaceId="ws_main"workspaceName="app"- onStartTask={async (prompt) => { extra.started?.push(prompt); }}+ onStartTask={async (prompt) => { extra.started?.push(prompt); return task({ prompt, startedDirty: true }); }}onOpenChat={(workspaceId, sessionId) => extra.opened?.push(`${workspaceId}/${sessionId}`)}onWorkspacesChanged={() => undefined}/>@@ -119,6 +119,7 @@ describe("parallel tasks board", () => {expect(cards[0]!.querySelector("[data-testid=task-apply]")).toBeNull();expect(button("Stop", cards[0]!)).toBeTruthy();expect(cards[1]!.textContent).toContain("2 files changed");+ expect(document.querySelector("[data-testid=task-dirty-note]")).toBeNull();expect(document.body.textContent).toContain("1 task running");await click(button("Open chat", cards[1]!));expect(opened).toEqual(["ws_task2/ses_2"]);@@ -176,6 +177,13 @@ describe("parallel tasks board", () => {await view.unmount();});+ test("a task started while the checkout had uncommitted changes says they are not in it", async () => {+ const { client } = fakeClient({ git: true, repo: "app", branch: "main", hasCommit: true, tasks: [task({ startedDirty: true })] });+ const view = await mount(client);+ expect(document.querySelector("[data-testid=task-dirty-note]")?.textContent).toBe("It starts from the last commit (0123456); your uncommitted changes are not in it.");+ await view.unmount();+ });+test("the sidebar count is the number of tasks still working", () => {expect(runningTaskCount(undefined)).toBe(0);expect(runningTaskCount({ git: true, repo: "app", branch: "main", hasCommit: true, tasks: [task({}), task({ id: "t2", state: "created" }), task({ id: "t3", state: "done" })] })).toBe(2);diff --git a/apps/server/src/routes/workspace-tasks.ts b/apps/server/src/routes/workspace-tasks.tsindex 23c33cc5..455b33c3 100644--- a/apps/server/src/routes/workspace-tasks.ts+++ b/apps/server/src/routes/workspace-tasks.ts@@ -30,6 +30,8 @@ export const MAX_RUNNING_TASKS = 4;const START_GRACE_MS = 5_000;/** A task that never got its prompt (the app closed in between) stops counting as starting. */const NEVER_STARTED_MS = 2 * 60_000;+/** How long removing a running task waits for its stopped chat to end. */+const STOP_WAIT_MS = 15_000;const REPLY_MAX_CHARS = 4_000;/** What the routes need from the engine, per task workspace (server.ts supplies it; tests fake it). */@@ -64,6 +66,9 @@ export type TaskView = {label: string;branch: string;baseBranch: string | null;+ baseCommit: string;+ /** The main checkout had uncommitted changes when the task started: they are not in the task. */+ startedDirty: boolean;name: string;path: string;workspaceId: string | null;@@ -93,14 +98,19 @@ function sinceMs(iso: string | null, now: number): number {* when its prompt never arrived. Changes are saved into the record.*/export async function liveTask(record: TaskRecord, workspace: WorkspaceInfo | null, engine: TaskEngine, now = Date.now()): Promise<TaskRecord> {+ // Each change is decided again on the stored record: its first prompt may be noted at the same time.if (record.state === "created" && !record.sessionId && sinceMs(record.createdAt, now) > NEVER_STARTED_MS) {- return updateTask(record, { state: "stopped", finishedAt: new Date(now).toISOString() });+ return updateTask(record, (current) => current.state === "created" && !current.sessionId+ ? { state: "stopped", finishedAt: new Date(now).toISOString() }+ : {});}if (!workspace || !record.sessionId || (record.state !== "running" && record.state !== "done")) return record;const busy = await engine.sessionBusy(workspace, record.sessionId).catch(() => null);- if (busy === true && record.state === "done") return updateTask(record, { state: "running", finishedAt: null });+ if (busy === true && record.state === "done") {+ return updateTask(record, (current) => current.state === "done" ? { state: "running", finishedAt: null } : {});+ }if (busy === false && record.state === "running" && sinceMs(record.startedAt, now) > START_GRACE_MS) {- return updateTask(record, { state: "done", finishedAt: new Date(now).toISOString() });+ return updateTask(record, (current) => current.state === "running" ? { state: "done", finishedAt: new Date(now).toISOString() } : {});}return record;}@@ -114,6 +124,8 @@ export async function taskView(config: ServerConfig, record: TaskRecord, now = Dlabel: stateLabel(record.state),branch: record.branch,baseBranch: record.baseBranch,+ baseCommit: record.baseCommit,+ startedDirty: record.startedDirty === true,name: projectName(record.path),path: record.path,workspaceId: taskWorkspaceOf(config, record)?.id ?? null,@@ -153,8 +165,13 @@ export async function noteTaskPrompt(if (!link) return;const record = await readTask(workspace.path, link.taskId).catch(() => null);if (!record || record.sessionId) return;- const started = await updateTask(record, { sessionId, state: "running", startedAt: new Date(now).toISOString() }).catch(() => null);- if (started) recordTrace(sessionId, TASK_STARTED_EVENT, taskStartedData(started));+ let first = false;+ const started = await updateTask(record, (current) => {+ if (current.sessionId) return {};+ first = true;+ return { sessionId, state: "running", startedAt: new Date(now).toISOString() };+ }).catch(() => null);+ if (started && first) recordTrace(sessionId, TASK_STARTED_EVENT, taskStartedData(started));}export function registerWorkspaceTaskRoutes(options: RegisterWorkspaceTaskRoutesOptions): void {@@ -171,9 +188,16 @@ export function registerWorkspaceTaskRoutes(options: RegisterWorkspaceTaskRoutesreturn liveTask(record, taskWorkspaceOf(config, record), engine);};- /** Stops the task's work, removes its folder, branch and record, and its workspace. */+ /** Stops the task's work (and waits for its chat to end), removes its folder, branch and record, and its workspace. */const removeOne = async (record: TaskRecord) => {const workspace = taskWorkspaceOf(config, record);+ if (workspace && record.sessionId && (record.state === "running" || record.state === "created")) {+ await engine.abort(workspace, record.sessionId).catch(() => undefined);+ const deadline = Date.now() + STOP_WAIT_MS;+ while (Date.now() < deadline && (await engine.sessionBusy(workspace, record.sessionId).catch(() => false))) {+ await new Promise((resolve) => setTimeout(resolve, 250));+ }+ }if (workspace) await options.stopWorkspaceWork?.(config, workspace).catch(() => undefined);await removeTask(record, { force: true }).catch(taskApiError);if (workspace) await forgetLocalWorkspace(config, workspace.id);diff --git a/apps/server/src/workspace-tasks.test.ts b/apps/server/src/workspace-tasks.test.tsindex 21c6335e..44b40ebd 100644--- a/apps/server/src/workspace-tasks.test.ts+++ b/apps/server/src/workspace-tasks.test.ts@@ -275,6 +275,27 @@ describe("parallel tasks (desktop)", () => {expect(listed.json.tasks).toEqual([]);});+ test("removing a running task stops its chat and waits for it to end first; a dirty checkout is noted on the task", async () => {+ await writeFile(join(repo, "README.md"), "edited, not committed\n");+ const created = await h.call("POST", `/workspaces/${mainId}/tasks`, { prompt: "Runs a while" });+ const task = created.json.task as Record<string, unknown>;+ expect(task.startedDirty).toBe(true);+ expect(String(task.baseCommit)).toMatch(/^[0-9a-f]{40}$/);+ git(repo, "checkout", "--", "README.md");+ const workspace = h.config.workspaces.find((entry) => entry.task?.taskId === task.id)!;+ await noteTaskPrompt(workspace, "ses_task4", () => undefined);+ h.busy.set("ses_task4", true);+ const order: string[] = [];+ const before = h.aborted.length;+ setTimeout(() => { order.push("ended"); h.busy.set("ses_task4", false); }, 600);+ const removed = await h.call("DELETE", `/workspaces/${mainId}/tasks/${String(task.id)}`);+ order.push("removed");+ expect(removed.status).toBe(200);+ expect(h.aborted.slice(before)).toEqual(["ses_task4"]);+ expect(order).toEqual(["ended", "removed"]);+ expect(existsSync(String(task.path))).toBe(false);+ });+test("a task whose prompt never arrived stops counting as starting", async () => {const created = await h.call("POST", `/workspaces/${mainId}/tasks`, { prompt: "Never sent" });const task = created.json.task as Record<string, string>;diff --git a/apps/server/src/workspace/PARITY.sha256 b/apps/server/src/workspace/PARITY.sha256index 95e4322a..4e06453d 100644--- a/apps/server/src/workspace/PARITY.sha256+++ b/apps/server/src/workspace/PARITY.sha256@@ -1,3 +1,3 @@# Byte-identical in omnirush-cli assets/extensions/omnirush/workspace/ (worktree tasks + home view).-40b1579de2e3db46ad3aa7377329b2668e24aae59636557122934149571f500f worktree-tasks.mjs+2ca6461ea4cfa0f7fdf77861fdb6e1aa6c19ade861943e31d515c77a324fe408 worktree-tasks.mjs90bdb16dd097c79f5f5bc68f33d8eb530b56c6d8c380dd4c3b6290640a03b9e2 home-view.mjsdiff --git a/apps/server/src/workspace/worktree-tasks.d.mts b/apps/server/src/workspace/worktree-tasks.d.mtsindex 80a1cc54..1074c593 100644--- a/apps/server/src/workspace/worktree-tasks.d.mts+++ b/apps/server/src/workspace/worktree-tasks.d.mts@@ -25,6 +25,9 @@ export type TaskRecord = {summary: string | null;log: string | null;result: { mode: "apply" | "merge"; files: number; at: string } | null;+ /** The main checkout had uncommitted changes when the task started (they are not in it). */+ startedDirty?: boolean;+ pidStart?: string | null;};export type RepoInfo = {@@ -62,20 +65,23 @@ export function slugify(text: string, max?: number): string;export function titleFor(prompt: string): string;export function newTaskId(now?: number, random?: Uint8Array): string;export function createTask(input: { dir: string; prompt: string; title?: string | null; origin?: string; parentSessionId?: string | null; now?: number }): Promise<TaskRecord>;-export function updateTask(record: TaskRecord, patch: Partial<TaskRecord>): Promise<TaskRecord>;+export function updateTask(record: TaskRecord, patch: Partial<TaskRecord> | ((current: TaskRecord) => Partial<TaskRecord>)): Promise<TaskRecord>;export function updateTaskFile(file: string, patch: Partial<TaskRecord>): Promise<TaskRecord | null>;-export function pidAlive(pid: number | null): boolean;-export function reconcile(record: TaskRecord, options?: { alive?: (pid: number | null) => boolean }): Promise<TaskRecord>;+export function processStartTime(pid: number | null): string | null;+export function pidAlive(pid: number | null, record?: TaskRecord | null): boolean;+export function reconcile(record: TaskRecord, options?: { alive?: (pid: number | null, record?: TaskRecord | null) => boolean }): Promise<TaskRecord>;export function readTask(dir: string, id: string): Promise<TaskRecord>;-export function listTasks(dir: string, options?: { repo?: RepoInfo; alive?: (pid: number | null) => boolean }): Promise<TaskRecord[]>;-export function findTask(dir: string, ref: string): Promise<TaskRecord>;+export function listTasks(dir: string, options?: { repo?: RepoInfo; alive?: (pid: number | null, record?: TaskRecord | null) => boolean }): Promise<TaskRecord[]>;+export function findTask(dir: string, ref: string, options?: { repo?: RepoInfo }): Promise<TaskRecord>;export function taskChanges(task: TaskRecord): Promise<TaskChange[]>;export function taskFileCount(task: TaskRecord): Promise<number | null>;export function taskPatch(task: TaskRecord): Promise<string>;export function taskStat(task: TaskRecord): Promise<string>;export function bringBack(task: TaskRecord, options?: { mode?: "apply" | "merge"; message?: string; now?: number }): Promise<{ record: TaskRecord; files: TaskChange[]; mode: "apply" | "merge" }>;-export function removeTask(task: TaskRecord, options?: { keepBranch?: boolean; force?: boolean; alive?: (pid: number | null) => boolean }): Promise<{ removed: boolean; branchKept: boolean }>;-export function cleanTasks(dir: string, options?: { keepBranch?: boolean; force?: boolean; alive?: (pid: number | null) => boolean }): Promise<string[]>;+export function gitBusy(dir: string): Promise<"merge" | "rebase" | "cherry-pick" | "revert" | null>;+export function isTaskPath(repo: string, folder: string): boolean;+export function removeTask(task: TaskRecord, options?: { keepBranch?: boolean; force?: boolean; alive?: (pid: number | null, record?: TaskRecord | null) => boolean }): Promise<{ removed: boolean; branchKept: boolean }>;+export function cleanTasks(dir: string, options?: { keepBranch?: boolean; force?: boolean; alive?: (pid: number | null, record?: TaskRecord | null) => boolean }): Promise<string[]>;export function taskStartedData(task: TaskRecord): Record<string, unknown>;export function taskMergedData(task: TaskRecord, result: { mode: "apply" | "merge"; files: TaskChange[] | number }): Record<string, unknown>;export function isFinished(task: TaskRecord): boolean;diff --git a/apps/server/src/workspace/worktree-tasks.mjs b/apps/server/src/workspace/worktree-tasks.mjsindex 6d3b8336..4fd948b1 100644--- a/apps/server/src/workspace/worktree-tasks.mjs+++ b/apps/server/src/workspace/worktree-tasks.mjs@@ -27,7 +27,7 @@//// Plain JavaScript (node and bun), no dependencies besides node:*.-import { execFile } from "node:child_process";+import { execFile, execFileSync } from "node:child_process";import { randomBytes } from "node:crypto";import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";import path from "node:path";@@ -57,7 +57,8 @@ export function runGit(args, { cwd, env, input, timeoutMs = GIT_TIMEOUT_MS } = {return new Promise((resolve) => {const child = execFile("git", args, {cwd, timeout: timeoutMs, maxBuffer: MAX_BUFFER, windowsHide: true,- env: { ...process.env, ...env, GIT_TERMINAL_PROMPT: "0", LC_ALL: "C" },+ // GIT_OPTIONAL_LOCKS=0: reading a running task's status never takes its index.lock.+ env: { ...process.env, ...env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0", LC_ALL: "C" },}, (error, stdout, stderr) => {const code = error ? (typeof error.code === "number" ? error.code : 1) : 0;resolve({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") || (error && typeof error.code !== "number" ? String(error.message) : "") });@@ -93,9 +94,10 @@ function firstLine(text) {export async function repoOf(dir) {const top = await runGit(["rev-parse", "--show-toplevel"], { cwd: dir });if (top.code !== 0) return null;- const common = await runGit(["rev-parse", "--path-format=absolute", "--git-common-dir"], { cwd: dir });+ // Relative to `dir` when relative (git before 2.31 has no --path-format=absolute).+ const common = await runGit(["rev-parse", "--git-common-dir"], { cwd: dir });if (common.code !== 0) return null;- const commonDir = path.resolve(common.stdout.trim());+ const commonDir = path.resolve(dir, common.stdout.trim());const here = path.resolve(top.stdout.trim());// The main checkout is the folder holding the common .git directory (a bare repository has none).const main = path.basename(commonDir) === ".git" ? path.dirname(commonDir) : here;@@ -162,31 +164,48 @@ export async function createTask({ dir, prompt, title, origin = "cli", parentSesconst repo = await repoOf(dir);if (!repo) throw new TaskError("Tasks run in a git repository; this folder is not in one.", "not_git");if (!repo.head) throw new TaskError("The repository has no commit yet; commit once, then start a task.", "no_commit");- const id = newTaskId(now);- const name = `${slugify(title || text, 24)}-${id.slice(-4)}`;- const branch = `${BRANCH_PREFIX}${name}`;- const worktree = path.join(tasksDir(repo.top), name);- if (await exists(worktree)) throw new TaskError("A task folder with that name exists already; try again.", "exists");- await mkdir(tasksDir(repo.top), { recursive: true });- const added = await runGit(["worktree", "add", "-b", branch, worktree, repo.head], { cwd: repo.top });+ if (path.dirname(repo.top) === repo.top) throw new TaskError("Tasks need the repository inside a folder (its worktrees go next to it).", "no_parent");+ try {+ await mkdir(tasksDir(repo.top), { recursive: true });+ } catch (error) {+ throw new TaskError(`Cannot create ${tasksDir(repo.top)} for the task's folder (${error?.code || error?.message}).`, "no_tasks_dir");+ }+ let id, name, branch, worktree, added;+ // A new id when the name or the branch is taken already (a rare collision of the short id).+ for (let attempt = 0; attempt < 3; attempt += 1) {+ id = newTaskId(now + attempt);+ name = `${slugify(title || text, 24)}-${id.slice(-4)}`;+ branch = `${BRANCH_PREFIX}${name}`;+ worktree = path.join(tasksDir(repo.top), name);+ if (await exists(worktree)) continue;+ if ((await runGit(["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`], { cwd: repo.top })).code === 0) continue;+ added = await runGit(["worktree", "add", "-b", branch, worktree, repo.head], { cwd: repo.top });+ break;+ }+ if (!added) throw new TaskError("A task folder or branch with that name exists already; try again.", "exists");if (added.code !== 0) throw new TaskError(firstLine(added.stderr) || "Could not create the task's folder.", "worktree_failed");+ // The task starts from the last commit: what is not committed in the main checkout is not in it.+ const dirty = (await runGit(["status", "--porcelain", "--untracked-files=no"], { cwd: repo.top })).stdout.trim() !== "";const record = {version: TASKS_VERSION, id, title: titleFor(title || text), prompt: text, origin,repo: repo.top, repoName: repo.name, path: worktree, branch,baseBranch: repo.branch, baseCommit: repo.head,state: "created", createdAt: new Date(now).toISOString(), startedAt: null, finishedAt: null,sessionId: null, parentSessionId: parentSessionId || null, pid: null, exitCode: null,- summary: null, log: null, result: null,+ summary: null, log: null, result: null, startedDirty: dirty,};await writeRecord(recordPath(repo.top, id), record);return record;}-/** Merges `patch` into the stored record (re-read first, so concurrent writers keep each other's fields). */+/**+ * Merges `patch` into the stored record (re-read first, so concurrent writers keep each other's+ * fields); `patch` may be a function of the stored record.+ */export async function updateTask(record, patch) {const file = recordPath(record.repo, record.id);const current = JSON.parse(await readFile(file, "utf8").catch(() => "null")) || record;- const next = { ...current, ...patch };+ const next = { ...current, ...(typeof patch === "function" ? patch(current) : patch) };await writeRecord(file, next);return next;}@@ -200,22 +219,40 @@ export async function updateTaskFile(file, patch) {return next;}-/** Whether a process id is alive (signal 0). */-export function pidAlive(pid) {+/**+ * When a process started (`ps -o lstart=`; null on Windows or when unknown):+ * kept with a task's pid, so a pid the system gave to another process later is+ * never taken for the task's run (nor signalled).+ */+export function processStartTime(pid) {+ if (process.platform === "win32" || !Number.isInteger(pid) || pid <= 0) return null;+ try {+ return execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 3_000, stdio: ["ignore", "pipe", "ignore"] }).trim() || null;+ } catch {+ return null;+ }+}++/** Whether a process id is alive (signal 0) and, when `record.pidStart` is known, still the same process. */+export function pidAlive(pid, record = null) {if (!Number.isInteger(pid) || pid <= 0) return false;try {process.kill(pid, 0);- return true;} catch (error) {- return error?.code === "EPERM";+ if (error?.code !== "EPERM") return false;+ }+ if (record?.pidStart) {+ const started = processStartTime(pid);+ if (started && started !== record.pidStart) return false;}+ return true;}/** A record as it is now: a running task whose process is gone is "stopped", a task whose folder is gone "missing". */export async function reconcile(record, { alive = pidAlive } = {}) {let next = record;if (!["applied", "merged"].includes(record.state) && !(await exists(record.path))) next = { ...next, state: "missing" };- else if (record.state === "running" && record.pid && !alive(record.pid)) next = { ...next, state: "stopped" };+ else if (record.state === "running" && record.pid && !alive(record.pid, record)) next = { ...next, state: "stopped" };return next;}@@ -248,8 +285,8 @@ export async function listTasks(dir, options = {}) {}/** Finds a task by id or by a unique id/name prefix. */-export async function findTask(dir, ref) {- const tasks = await listTasks(dir);+export async function findTask(dir, ref, options = {}) {+ const tasks = await listTasks(dir, options);const wanted = String(ref || "").trim();const exact = tasks.find((task) => task.id === wanted || path.basename(task.path) === wanted);if (exact) return exact;@@ -322,6 +359,10 @@ export async function bringBack(task, { mode = "apply", message, now = Date.now(const applied = await runGit(["apply", "--binary", "-"], { cwd: task.repo, input: patch });if (applied.code !== 0) throw new TaskError(firstLine(applied.stderr) || "Could not apply the changes.", "apply_failed");} else if (mode === "merge") {+ const here = await repoOf(task.repo);+ if (!here?.branch) throw new TaskError("The main checkout is not on a branch (detached HEAD); use apply instead.", "detached");+ const busy = await gitBusy(task.repo);+ if (busy) throw new TaskError(`The main checkout has a ${busy} in progress; finish or abort it first.`, "busy");const subject = message || `${task.title}`;const committed = await runGit(["commit", "-q", "-m", subject], { cwd: task.path });if (committed.code !== 0 && !/nothing to commit/.test(committed.stdout + committed.stderr)) {@@ -329,7 +370,8 @@ export async function bringBack(task, { mode = "apply", message, now = Date.now(}const merged = await runGit(["merge", "--no-ff", "--no-edit", task.branch], { cwd: task.repo });if (merged.code !== 0) {- await runGit(["merge", "--abort"], { cwd: task.repo });+ // Only the merge this call started is undone (there was none in progress before it).+ if (await gitBusy(task.repo)) await runGit(["merge", "--abort"], { cwd: task.repo });throw new TaskError(firstLine(merged.stderr) || firstLine(merged.stdout) || "The merge stopped on a conflict; nothing was changed.", "conflict", { stderr: (merged.stdout + merged.stderr).slice(0, 2000) });}} else {@@ -339,12 +381,30 @@ export async function bringBack(task, { mode = "apply", message, now = Date.now(return { record, files, mode };}+/** "merge", "rebase", "cherry-pick" or "revert" when one is in progress in `dir`, else null. */+export async function gitBusy(dir) {+ const has = async (ref) => (await runGit(["rev-parse", "-q", "--verify", ref], { cwd: dir })).code === 0;+ if (await has("MERGE_HEAD")) return "merge";+ if (await has("CHERRY_PICK_HEAD")) return "cherry-pick";+ if (await has("REVERT_HEAD")) return "revert";+ const gitDir = (await runGit(["rev-parse", "--git-dir"], { cwd: dir })).stdout.trim();+ if (gitDir && ((await exists(path.resolve(dir, gitDir, "rebase-merge"))) || (await exists(path.resolve(dir, gitDir, "rebase-apply"))))) return "rebase";+ return null;+}++/** Whether `folder` is a task folder of `repo` (directly in its tasks folder, not the records folder). */+export function isTaskPath(repo, folder) {+ const resolved = path.resolve(String(folder || ""));+ return path.dirname(resolved) === tasksDir(path.resolve(repo)) && path.basename(resolved) !== RECORDS_DIR && path.basename(resolved) !== "";+}+/*** Removes a task: its worktree (even with changes left in it), its branch* (unless keepBranch) and its record. A running task is refused unless force.*/export async function removeTask(task, { keepBranch = false, force = false, alive = pidAlive } = {}) {- if (task.state === "running" && alive(task.pid) && !force) throw new TaskError("The task is still running; stop it first.", "running");+ if (task.state === "running" && alive(task.pid, task) && !force) throw new TaskError("The task is still running; stop it first.", "running");+ if (!isTaskPath(task.repo, task.path)) throw new TaskError("That record does not name a task folder; nothing was removed.", "bad_record");if (await exists(task.path)) {const removed = await runGit(["worktree", "remove", "--force", task.path], { cwd: task.repo });if (removed.code !== 0) {