A desktop coding agent with free access to frontier models.
TypeScript
feat: parallel task routes
Samrat Talukdare8f58423d871
diff --git a/apps/server/package.json b/apps/server/package.jsonindex e99ed89a..6c00b5eb 100644--- a/apps/server/package.json+++ b/apps/server/package.json@@ -12,7 +12,7 @@"test:coverage": "bun --conditions=development test --coverage --coverage-reporter=text --coverage-reporter=lcov --coverage-dir=coverage","test:artifacts": "bun --conditions=development test src/artifact-files.e2e.test.ts src/workspace-init.test.ts src/server.normalizeWorkspaceRelativePath.test.ts","build:enterprise-mcp-client": "pnpm --filter @omnirush/enterprise-mcp-client build",- "build": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && tsc -p tsconfig.json && node scripts/copy-mcp-allow.mjs && bun build src/opencode-plugins/managed-policy-next.ts src/opencode-plugins/managed-policy.ts src/opencode-plugins/omnirush-chrome-devtools.ts src/opencode-plugins/omnirush-extensions-preview.ts src/opencode-plugins/omnirush-capabilities-knowledge.ts src/opencode-plugins/omnirush-office-attachments.ts src/opencode-plugins/omnirush-spreadsheets.ts src/opencode-plugins/omnirush-pdf-attachments.ts src/opencode-plugins/omnirush-anthropic-adaptive-thinking.ts src/opencode-plugins/omnirush-anthropic-tool-schema.ts src/opencode-plugins/omnirush-title-recovery.ts src/opencode-plugins/omnirush-reasoning-effort.ts src/opencode-plugins/omnirush-swarm.ts src/opencode-plugins/omnirush-budget-wrap.ts src/opencode-plugins/omnirush-mcp-policy.ts src/opencode-plugins/omnirush-box.ts src/opencode-plugins/omnirush-buildathon.ts src/opencode-plugins/omnirush-agent-assist.ts --root src/opencode-plugins --outdir dist/opencode-plugins --target node --format esm && node scripts/copy-pdfium-wasm.mjs dist/opencode-plugins",+ "build": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && tsc -p tsconfig.json && node scripts/copy-mcp-allow.mjs && node scripts/copy-shared-modules.mjs && bun build src/opencode-plugins/managed-policy-next.ts src/opencode-plugins/managed-policy.ts src/opencode-plugins/omnirush-chrome-devtools.ts src/opencode-plugins/omnirush-extensions-preview.ts src/opencode-plugins/omnirush-capabilities-knowledge.ts src/opencode-plugins/omnirush-office-attachments.ts src/opencode-plugins/omnirush-spreadsheets.ts src/opencode-plugins/omnirush-pdf-attachments.ts src/opencode-plugins/omnirush-anthropic-adaptive-thinking.ts src/opencode-plugins/omnirush-anthropic-tool-schema.ts src/opencode-plugins/omnirush-title-recovery.ts src/opencode-plugins/omnirush-reasoning-effort.ts src/opencode-plugins/omnirush-swarm.ts src/opencode-plugins/omnirush-budget-wrap.ts src/opencode-plugins/omnirush-mcp-policy.ts src/opencode-plugins/omnirush-box.ts src/opencode-plugins/omnirush-buildathon.ts src/opencode-plugins/omnirush-agent-assist.ts --root src/opencode-plugins --outdir dist/opencode-plugins --target node --format esm && node scripts/copy-pdfium-wasm.mjs dist/opencode-plugins","build:bin": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && bun build --compile src/cli.ts --outfile dist/bin/omnirush-server","build:bin:all": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && bun ./script/build.ts --outdir dist/bin --target bun-darwin-arm64 --target bun-darwin-x64 --target bun-linux-x64 --target bun-linux-arm64 --target bun-windows-x64 --target bun-windows-arm64","prepare:npm": "pnpm build:bin && node scripts/publish-npm.mjs --prepare-only",diff --git a/apps/server/scripts/copy-shared-modules.mjs b/apps/server/scripts/copy-shared-modules.mjsnew file mode 100644index 00000000..b2c43353--- /dev/null+++ b/apps/server/scripts/copy-shared-modules.mjs@@ -0,0 +1,17 @@+// tsc emits only TypeScript: the plain-JavaScript modules shared with the CLI+// (src/workspace/*.mjs, see PARITY.sha256 there) are copied into dist as they are.+import { copyFileSync, mkdirSync, readdirSync } from "node:fs";+import { join, resolve } from "node:path";++const root = resolve(import.meta.dirname, "..");+const copied = [];+for (const folder of ["workspace"]) {+ const from = join(root, "src", folder);+ const to = join(root, "dist", folder);+ mkdirSync(to, { recursive: true });+ for (const name of readdirSync(from).filter((file) => file.endsWith(".mjs"))) {+ copyFileSync(join(from, name), join(to, name));+ copied.push(join(folder, name));+ }+}+process.stdout.write(`${JSON.stringify({ copied })}\n`);diff --git a/apps/server/src/routes/workspace-tasks.ts b/apps/server/src/routes/workspace-tasks.tsnew file mode 100644index 00000000..23c33cc5--- /dev/null+++ b/apps/server/src/routes/workspace-tasks.ts@@ -0,0 +1,281 @@+import { ApiError } from "../errors.js";+import type { ServerConfig, WorkspaceInfo } from "../types.js";+import { workspaceIdForPath } from "../workspaces.js";+import { projectName, relativeAge } from "../workspace/home-view.mjs";+import {+ bringBack,+ createTask,+ isFinished,+ listTasks,+ readTask,+ removeTask,+ repoOf,+ stateLabel,+ TaskError,+ taskFileCount,+ taskMergedData,+ taskStartedData,+ taskStat,+ TASK_MERGED_EVENT,+ TASK_STARTED_EVENT,+ updateTask,+ type TaskRecord,+} from "../workspace/worktree-tasks.mjs";+import { addRoute, type Route } from "./registry.js";+import { addLocalWorkspace, forgetLocalWorkspace } from "./workspaces.js";++/** At most this many tasks of one repository run at once (the CLI's limit too). */+export const MAX_RUNNING_TASKS = 4;+/** A task whose engine session is not busy yet right after its prompt is still starting, not done. */+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;+const REPLY_MAX_CHARS = 4_000;++/** What the routes need from the engine, per task workspace (server.ts supplies it; tests fake it). */+export interface TaskEngine {+ /** Whether the session is working now; null when the engine could not say. */+ sessionBusy(workspace: WorkspaceInfo, sessionId: string): Promise<boolean | null>;+ abort(workspace: WorkspaceInfo, sessionId: string): Promise<void>;+ /** The text of the session's last assistant reply ("" when none). */+ lastReply(workspace: WorkspaceInfo, sessionId: string): Promise<string>;+}++interface RegisterWorkspaceTaskRoutesOptions {+ routes: Route[];+ config: ServerConfig;+ onWorkspacesChanged: () => void;+ jsonResponse: (data: unknown, status?: number) => Response;+ readJsonBody: (request: Request) => Promise<Record<string, unknown>>;+ ensureWritable: (config: ServerConfig) => void;+ resolveWorkspace: (config: ServerConfig, id: string) => Promise<WorkspaceInfo>;+ serializeWorkspace: (workspace: WorkspaceInfo) => unknown;+ stopWorkspaceWork?: (config: ServerConfig, workspace: WorkspaceInfo) => Promise<void>;+ engine: TaskEngine;+ /** Records a trace event on a session the uploader has open; a no-op otherwise. */+ recordTrace: (sessionId: string, type: string, data: Record<string, unknown>) => void;+}++export type TaskView = {+ id: string;+ title: string;+ prompt: string;+ state: TaskRecord["state"];+ label: string;+ branch: string;+ baseBranch: string | null;+ name: string;+ path: string;+ workspaceId: string | null;+ sessionId: string | null;+ createdAt: string;+ startedAt: string | null;+ finishedAt: string | null;+ age: string;+ files: number | null;+ finished: boolean;+ result: TaskRecord["result"];+};++function taskWorkspaceOf(config: ServerConfig, record: TaskRecord): WorkspaceInfo | null {+ const id = workspaceIdForPath(record.path);+ return config.workspaces.find((entry) => entry.task?.taskId === record.id || entry.id === id) ?? null;+}++function sinceMs(iso: string | null, now: number): number {+ const at = iso ? Date.parse(iso) : Number.NaN;+ return Number.isFinite(at) ? now - at : Number.POSITIVE_INFINITY;+}++/**+ * A desktop task's state as it is now: running while its session works, done+ * once it is idle (and running again when the person continues it), stopped+ * 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> {+ if (record.state === "created" && !record.sessionId && sinceMs(record.createdAt, now) > NEVER_STARTED_MS) {+ return updateTask(record, { 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 === false && record.state === "running" && sinceMs(record.startedAt, now) > START_GRACE_MS) {+ return updateTask(record, { state: "done", finishedAt: new Date(now).toISOString() });+ }+ return record;+}++export async function taskView(config: ServerConfig, record: TaskRecord, now = Date.now()): Promise<TaskView> {+ return {+ id: record.id,+ title: record.title,+ prompt: record.prompt,+ state: record.state,+ label: stateLabel(record.state),+ branch: record.branch,+ baseBranch: record.baseBranch,+ name: projectName(record.path),+ path: record.path,+ workspaceId: taskWorkspaceOf(config, record)?.id ?? null,+ sessionId: record.sessionId,+ createdAt: record.createdAt,+ startedAt: record.startedAt,+ finishedAt: record.finishedAt,+ age: relativeAge(Date.parse(record.startedAt || record.createdAt), now),+ files: await taskFileCount(record).catch(() => null),+ finished: isFinished(record),+ result: record.result,+ };+}++function taskApiError(error: unknown): never {+ if (error instanceof TaskError) {+ const status = error.code === "not_found" ? 404+ : error.code === "not_git" || error.code === "no_commit" || error.code === "no_prompt" || error.code === "bad_id" ? 400+ : 409;+ throw new ApiError(status, `task_${error.code}`, error.message, error.details === undefined ? undefined : { details: error.details });+ }+ throw error;+}++/**+ * The first prompt of a task's own chat: the task records which chat it is+ * and that it runs, and that chat's trace gets "worktree.task_started" once.+ * Only for task workspaces; every other prompt is untouched.+ */+export async function noteTaskPrompt(+ workspace: WorkspaceInfo,+ sessionId: string,+ recordTrace: (sessionId: string, type: string, data: Record<string, unknown>) => void,+ now = Date.now(),+): Promise<void> {+ const link = workspace.task;+ 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));+}++export function registerWorkspaceTaskRoutes(options: RegisterWorkspaceTaskRoutesOptions): void {+ const { routes, config, jsonResponse, readJsonBody, ensureWritable, resolveWorkspace, engine } = options;++ /** The workspace the board was opened in (a task's own workspace counts as its repository's). */+ const repoWorkspace = (id: string) => resolveWorkspace(config, id).then((workspace) => {+ if (workspace.workspaceType === "remote") throw new ApiError(400, "task_remote", "Parallel tasks run on this computer's folders only.");+ return workspace;+ });++ const findRecord = async (workspace: WorkspaceInfo, taskId: string) => {+ const record = await readTask(workspace.path, taskId).catch(taskApiError);+ return liveTask(record, taskWorkspaceOf(config, record), engine);+ };++ /** Stops the task's work, removes its folder, branch and record, and its workspace. */+ const removeOne = async (record: TaskRecord) => {+ const workspace = taskWorkspaceOf(config, record);+ if (workspace) await options.stopWorkspaceWork?.(config, workspace).catch(() => undefined);+ await removeTask(record, { force: true }).catch(taskApiError);+ if (workspace) await forgetLocalWorkspace(config, workspace.id);+ };++ addRoute(routes, "GET", "/workspaces/:id/tasks", "host", async (ctx) => {+ const workspace = await repoWorkspace(ctx.params.id);+ const repo = await repoOf(workspace.path);+ if (!repo) return jsonResponse({ git: false, repo: null, branch: null, hasCommit: false, tasks: [] });+ const records = await listTasks(workspace.path, { repo });+ const now = Date.now();+ const live = await Promise.all(records.map((record) => liveTask(record, taskWorkspaceOf(config, record), engine, now)));+ return jsonResponse({+ git: true,+ repo: repo.name,+ branch: repo.branch,+ hasCommit: Boolean(repo.head),+ tasks: await Promise.all(live.map((record) => taskView(config, record, now))),+ });+ });++ addRoute(routes, "POST", "/workspaces/:id/tasks", "host", async (ctx) => {+ ensureWritable(config);+ const workspace = await repoWorkspace(ctx.params.id);+ const body = await readJsonBody(ctx.request);+ const prompt = typeof body.prompt === "string" ? body.prompt.trim() : "";+ const title = typeof body.title === "string" && body.title.trim() ? body.title.trim() : null;+ const parentSessionId = typeof body.parentSessionId === "string" && body.parentSessionId.trim() ? body.parentSessionId.trim() : null;+ if (!prompt) throw new ApiError(400, "task_no_prompt", "A task needs a prompt.");+ const running = (await listTasks(workspace.path)).filter((record) => record.state === "running" || record.state === "created");+ if (running.length >= MAX_RUNNING_TASKS) {+ throw new ApiError(409, "task_busy", `${MAX_RUNNING_TASKS} tasks are running already; wait for one to finish.`);+ }+ const record = await createTask({ dir: workspace.path, prompt, title, origin: "desktop", parentSessionId }).catch(taskApiError);+ const parentWorkspaceId = workspace.task?.parentWorkspaceId ?? workspace.id;+ const { workspace: taskWorkspace } = await addLocalWorkspace(config, {+ folderPath: record.path,+ name: projectName(record.path),+ preset: workspace.preset || "starter",+ actor: ctx.actor,+ task: { parentWorkspaceId, taskId: record.id },+ }).catch(async (error: unknown) => {+ // No workspace for it: nothing half-made is left behind.+ await removeTask(record, { force: true }).catch(() => undefined);+ throw error;+ });+ options.onWorkspacesChanged();+ return jsonResponse({ task: await taskView(config, record), workspace: options.serializeWorkspace(taskWorkspace) }, 201);+ });++ addRoute(routes, "GET", "/workspaces/:id/tasks/:taskId", "host", async (ctx) => {+ const workspace = await repoWorkspace(ctx.params.id);+ const record = await findRecord(workspace, ctx.params.taskId);+ const taskWorkspace = taskWorkspaceOf(config, record);+ const reply = taskWorkspace && record.sessionId+ ? (await engine.lastReply(taskWorkspace, record.sessionId).catch(() => "")).slice(0, REPLY_MAX_CHARS)+ : "";+ // Reading the changes stages them in the task's own index: never while it works.+ const stat = record.state === "running" || record.state === "created" ? "" : await taskStat(record).catch(() => "");+ return jsonResponse({ task: await taskView(config, record), stat, reply });+ });++ for (const mode of ["apply", "merge"] as const) {+ addRoute(routes, "POST", `/workspaces/:id/tasks/:taskId/${mode}`, "host", async (ctx) => {+ ensureWritable(config);+ const workspace = await repoWorkspace(ctx.params.id);+ const record = await findRecord(workspace, ctx.params.taskId);+ const done = await bringBack(record, { mode }).catch(taskApiError);+ if (done.record.sessionId) options.recordTrace(done.record.sessionId, TASK_MERGED_EVENT, taskMergedData(done.record, done));+ return jsonResponse({ mode, files: done.files, task: await taskView(config, done.record) });+ });+ }++ addRoute(routes, "POST", "/workspaces/:id/tasks/:taskId/stop", "host", async (ctx) => {+ ensureWritable(config);+ const workspace = await repoWorkspace(ctx.params.id);+ const record = await findRecord(workspace, ctx.params.taskId);+ const taskWorkspace = taskWorkspaceOf(config, record);+ if (record.state !== "running" && record.state !== "created") return jsonResponse({ stopped: false, task: await taskView(config, record) });+ if (taskWorkspace && record.sessionId) await engine.abort(taskWorkspace, record.sessionId).catch(() => undefined);+ const stopped = await updateTask(record, { state: "stopped", finishedAt: new Date().toISOString() });+ return jsonResponse({ stopped: true, task: await taskView(config, stopped) });+ });++ addRoute(routes, "DELETE", "/workspaces/:id/tasks/:taskId", "host", async (ctx) => {+ ensureWritable(config);+ const workspace = await repoWorkspace(ctx.params.id);+ const record = await findRecord(workspace, ctx.params.taskId);+ await removeOne(record);+ options.onWorkspacesChanged();+ return jsonResponse({ ok: true, removed: record.id });+ });++ addRoute(routes, "POST", "/workspaces/:id/tasks/clean", "host", async (ctx) => {+ ensureWritable(config);+ const workspace = await repoWorkspace(ctx.params.id);+ const removed: string[] = [];+ for (const record of await listTasks(workspace.path)) {+ if (record.state !== "applied" && record.state !== "merged" && record.state !== "missing") continue;+ await removeOne(record).then(() => removed.push(record.id), () => undefined);+ }+ if (removed.length) options.onWorkspacesChanged();+ return jsonResponse({ removed });+ });+}diff --git a/apps/server/src/routes/workspaces.ts b/apps/server/src/routes/workspaces.tsindex c67342fe..4ef1971e 100644--- a/apps/server/src/routes/workspaces.ts+++ b/apps/server/src/routes/workspaces.ts@@ -10,7 +10,7 @@ import { ensureDir, exists, shortId } from "../utils.js";import { defaultWorkspaceOmniRushConfig, ensureWorkspaceFiles } from "../workspace-init.js";import { seedOmniRushWorkspaceConfigIfEmpty } from "../omnirush-workspace-config-store.js";import { workspaceIdForPath, workspaceIdForRemote } from "../workspaces.js";-import { addRoute, type Route } from "./registry.js";+import { addRoute, type RequestContext, type Route } from "./registry.js";type JsonResponse = (data: unknown, status?: number) => Response;type ReadJsonBody = (request: Request) => Promise<Record<string, unknown>>;@@ -217,6 +217,7 @@ function serializeWorkspaceConfigEntry(workspace: WorkspaceInfo): Record<string,...(workspace.sandboxContainerName ? { sandboxContainerName: workspace.sandboxContainerName } : {}),...(!isLocalWorkspace && workspace.opencodeUsername ? { opencodeUsername: workspace.opencodeUsername } : {}),...(!isLocalWorkspace && workspace.opencodePassword ? { opencodePassword: workspace.opencodePassword } : {}),+ ...(workspace.task ? { task: workspace.task } : {}),};}@@ -238,6 +239,67 @@ async function persistServerWorkspaceState(config: ServerConfig): Promise<booleareturn true;}+/**+ * Registers a local folder as a workspace (the POST /workspaces/local flow):+ * its runtime config row, its authorized root, the saved registry and the+ * audit line. The caller announces the change (onWorkspacesChanged).+ */+export async function addLocalWorkspace(+ config: ServerConfig,+ input: { folderPath: string; name: string; preset: string; actor?: RequestContext["actor"]; task?: WorkspaceInfo["task"] },+): Promise<{ workspace: WorkspaceInfo; persisted: boolean }> {+ const { name, preset } = input;+ const workspacePath = resolve(input.folderPath);+ await ensureDir(workspacePath);+ await ensureWorkspaceFiles(workspacePath, preset);++ const workspaceId = workspaceIdForPath(workspacePath);+ // Seed the per-workspace omnirush config in the runtime DB (replaces the+ // legacy `.opencode/omnirush.json` file). No-op if a row already exists.+ await seedOmniRushWorkspaceConfigIfEmpty(+ config,+ workspaceId,+ defaultWorkspaceOmniRushConfig(workspacePath, preset),+ );++ const workspace: WorkspaceInfo = {+ id: workspaceId,+ name,+ path: workspacePath,+ preset,+ workspaceType: "local",+ ...inheritWorkspaceOpencodeConnection(config),+ ...(input.task ? { task: input.task } : {}),+ };++ config.workspaces = [workspace, ...config.workspaces.filter((entry) => entry.id !== workspace.id)];+ if (!config.authorizedRoots.some((root) => resolve(root) === workspacePath)) {+ config.authorizedRoots = [...config.authorizedRoots, workspacePath];+ }+ const persisted = await persistServerWorkspaceState(config);++ await recordAudit(workspace.path, {+ id: shortId(),+ workspaceId: workspace.id,+ actor: input.actor ?? { type: "host" },+ action: "workspace.create",+ target: workspace.path,+ summary: `Created workspace ${name}`,+ timestamp: Date.now(),+ });+ return { workspace, persisted };+}++/** Removes a local workspace from the registry (not its folder); the caller announces the change. */+export async function forgetLocalWorkspace(config: ServerConfig, workspaceId: string): Promise<boolean> {+ const workspace = config.workspaces.find((entry) => entry.id === workspaceId);+ if (!workspace) return false;+ config.workspaces = config.workspaces.filter((entry) => entry.id !== workspaceId);+ config.authorizedRoots = config.authorizedRoots.filter((root) => resolve(root) !== resolve(workspace.path));+ await persistServerWorkspaceState(config);+ return true;+}+export function registerWorkspaceRoutes(options: RegisterWorkspaceRoutesOptions): void {const {routes,@@ -279,45 +341,9 @@ export function registerWorkspaceRoutes(options: RegisterWorkspaceRoutesOptions)throw new ApiError(400, "invalid_payload", "folderPath is required");}- const workspacePath = resolve(folderPath);- await ensureDir(workspacePath);- await ensureWorkspaceFiles(workspacePath, preset);-- const workspaceId = workspaceIdForPath(workspacePath);- // Seed the per-workspace omnirush config in the runtime DB (replaces the- // legacy `.opencode/omnirush.json` file). No-op if a row already exists.- await seedOmniRushWorkspaceConfigIfEmpty(- config,- workspaceId,- defaultWorkspaceOmniRushConfig(workspacePath, preset),- );-- const workspace: WorkspaceInfo = {- id: workspaceId,- name,- path: workspacePath,- preset,- workspaceType: "local",- ...inheritWorkspaceOpencodeConnection(config),- };-- config.workspaces = [workspace, ...config.workspaces.filter((entry) => entry.id !== workspace.id)];- if (!config.authorizedRoots.some((root) => resolve(root) === workspacePath)) {- config.authorizedRoots = [...config.authorizedRoots, workspacePath];- }- const persisted = await persistServerWorkspaceState(config);+ const { workspace, persisted } = await addLocalWorkspace(config, { folderPath, name, preset, actor: ctx.actor });onWorkspacesChanged();- await recordAudit(workspace.path, {- id: shortId(),- workspaceId: workspace.id,- actor: ctx.actor ?? { type: "host" },- action: "workspace.create",- target: workspace.path,- summary: `Created workspace ${name}`,- timestamp: Date.now(),- });-return jsonResponse({activeId: workspace.id,workspaces: config.workspaces.map(serializeWorkspace),diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 117163ba..26fc1a5b 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -124,6 +124,7 @@ import { addRoute, matchRoute, type AuthMode, type RequestContext, type Route }import { registerSessionGroupRoutes } from "./routes/session-groups.js";import { registerUiControlRoutes } from "./routes/ui-control.js";import { registerWorkspaceRoutes } from "./routes/workspaces.js";+import { noteTaskPrompt, registerWorkspaceTaskRoutes, type TaskEngine } from "./routes/workspace-tasks.js";import { registerCloudMcpRoutes } from "./routes/cloud-mcp.js";import { registerLocalWorkflowRoutes } from "./routes/local-workflows.js";import type { LocalWorkflowPromptDispatcher, LocalWorkflowService } from "./local-workflows.js";@@ -308,6 +309,32 @@ function recordSubagentModelFallback(config: ServerConfig, rootSessionId: stringcapture.recordTrace(rootSessionId, SUBAGENT_MODEL_FALLBACK_TRACE, data);}+/** A trace event on a session the uploader has open (and nothing otherwise). */+function recordOpenSessionTrace(config: ServerConfig, sessionId: string, type: string, data: Record<string, unknown>): void {+ const capture = captureServicesByServer.get(config);+ if (!capture?.uploadEnabled || !capture.hasSession(sessionId)) return;+ capture.recordTrace(sessionId, type, data);+}++/** The engine reads of the parallel-task board (routes/workspace-tasks.ts), on the engine generation holding each session. */+function workspaceTaskEngine(config: ServerConfig): TaskEngine {+ return {+ sessionBusy: async (workspace, sessionId) => {+ const statuses = unwrapOpencodeResult(await createWorkspaceOpencodeClient(config, workspace, { sessionId }).session.status(), "/session/status");+ const status = (statuses as Record<string, { type?: string } | undefined>)[sessionId];+ return Boolean(status && status.type !== "idle");+ },+ abort: async (workspace, sessionId) => {+ await createWorkspaceOpencodeClient(config, workspace, { sessionId }).session.abort({ sessionID: sessionId });+ },+ lastReply: async (workspace, sessionId) => {+ const messages = unwrapOpencodeResult(await createWorkspaceOpencodeClient(config, workspace, { sessionId }).session.messages({ sessionID: sessionId, limit: 40 }), "/session/messages");+ const last = [...messages].reverse().find((message) => message.info.role === "assistant" && message.parts.some((part) => part.type === "text" && part.text.trim()));+ return last ? last.parts.flatMap((part) => part.type === "text" && !part.synthetic ? [part.text.trim()] : []).filter(Boolean).join("\n\n") : "";+ },+ };+}+function engineModelRef(value: unknown): (EngineModelRef & { variant: string | null }) | null {if (!isRecord(value)) return null;const providerID = typeof value.providerID === "string" ? value.providerID.trim() : "";@@ -1972,6 +1999,10 @@ export async function proxyOpencodeV2Request(input: {capture.captureSnapshot(uploadedSessionId, "prompt");capture.archiveSessionStarted(uploadedSessionId, input.workspace.path, engine);}+ // A parallel task's first prompt (routes/workspace-tasks.ts): only task workspaces.+ if (input.workspace.task && promptDispatch && sessionId) {+ await noteTaskPrompt(input.workspace, sessionId, (id, type, data) => recordOpenSessionTrace(input.config, id, type, data));+ }const response = await loopbackFetch(target.toString(), { method, headers, body, signal: input.recoverySignal });// The engine has the prompt: its session status says busy from now on.turnActivity?.promptDispatched();@@ -2395,6 +2426,10 @@ export async function proxyOpencodeRequest(input: {capture.archiveSessionStarted(uploadedSessionId, workspace.path, engineTarget(baseUrl, headers, search));}}+ // A parallel task's first prompt (routes/workspace-tasks.ts): only task workspaces.+ if (workspace?.task && uploadedSessionId && !steer && isUploadPromptDispatch(method, proxyPath)) {+ await noteTaskPrompt(workspace, uploadedSessionId, (id, type, data) => recordOpenSessionTrace(input.config, id, type, data));+ }// A review or its fixes (command-events.ts), typed or from a button: an additive event of the chat's// trace, recorded once the engine answers the command with a 2xx.const reviewEvent = capture && captured && uploadedSessionId && isSessionCommandProxyRequest(method, proxyPath)@@ -3412,6 +3447,20 @@ function createRoutes(stopWorkspaceWork: stopWorkspaceEngineWork,});+ registerWorkspaceTaskRoutes({+ routes,+ config,+ onWorkspacesChanged,+ jsonResponse,+ readJsonBody,+ ensureWritable,+ resolveWorkspace,+ serializeWorkspace,+ stopWorkspaceWork: stopWorkspaceEngineWork,+ engine: workspaceTaskEngine(config),+ recordTrace: (sessionId, type, data) => recordOpenSessionTrace(config, sessionId, type, data),+ });+registerSessionGroupRoutes({routes,config,diff --git a/apps/server/src/types.ts b/apps/server/src/types.tsindex 81889101..ff47eee0 100644--- a/apps/server/src/types.ts+++ b/apps/server/src/types.ts@@ -1,4 +1,4 @@-import type { WorkspaceWire } from "@omnirush/types/workspace";+import type { WorkspaceTaskLink, WorkspaceWire } from "@omnirush/types/workspace";export type WorkspaceType = "local" | "remote";@@ -33,6 +33,7 @@ export interface WorkspaceConfig {sandboxContainerName?: string;opencodeUsername?: string;opencodePassword?: string;+ task?: WorkspaceTaskLink;}export interface WorkspaceInfo {@@ -60,6 +61,8 @@ export interface WorkspaceInfo {username?: string;password?: string;};+ /** A parallel task's own checkout of another workspace (routes/workspace-tasks.ts). */+ task?: WorkspaceTaskLink;}// Compile-time contract tripwires against the shared wire shape consumed bydiff --git a/apps/server/src/workspace-tasks.test.ts b/apps/server/src/workspace-tasks.test.tsnew file mode 100644index 00000000..21c6335e--- /dev/null+++ b/apps/server/src/workspace-tasks.test.ts@@ -0,0 +1,316 @@+import { afterAll, beforeAll, describe, expect, test } from "bun:test";+import { execFileSync } from "node:child_process";+import { createHash } from "node:crypto";+import { existsSync, readdirSync, readFileSync } from "node:fs";+import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { basename, dirname, join } from "node:path";++import { matchRoute, type RequestContext, type Route } from "./routes/registry.js";+import { liveTask, noteTaskPrompt, registerWorkspaceTaskRoutes, type TaskEngine } from "./routes/workspace-tasks.js";+import { startServer } from "./server.js";+import type { ServerConfig, WorkspaceInfo } from "./types.js";+import { readTask, TASK_MERGED_EVENT, TASK_STARTED_EVENT, tasksDir } from "./workspace/worktree-tasks.mjs";+import { workspaceIdForPath } from "./workspaces.js";++const roots: string[] = [];+const savedEnv = { ...process.env };++beforeAll(() => {+ process.env.GIT_AUTHOR_NAME = "Test";+ process.env.GIT_AUTHOR_EMAIL = "[email protected]";+ process.env.GIT_COMMITTER_NAME = "Test";+ process.env.GIT_COMMITTER_EMAIL = "[email protected]";+});++afterAll(async () => {+ process.env = savedEnv;+ while (roots.length) await rm(roots.pop()!, { recursive: true, force: true });+});++function git(cwd: string, ...args: string[]): string {+ return execFileSync("git", args, { cwd, encoding: "utf8" }).trim();+}++async function makeRepo(): Promise<{ root: string; repo: string }> {+ const root = await mkdtemp(join(tmpdir(), "omnirush-tasks-"));+ roots.push(root);+ const repo = join(root, "app");+ await mkdir(repo);+ git(repo, "init", "-q", "-b", "main");+ git(repo, "config", "commit.gpgsign", "false");+ await writeFile(join(repo, "README.md"), "hello\n");+ await writeFile(join(repo, "notes.txt"), "one\n");+ git(repo, "add", "-A");+ git(repo, "commit", "-q", "-m", "first");+ return { root, repo };+}++function makeConfig(root: string, workspaces: WorkspaceInfo[]): ServerConfig {+ process.env.OMNIRUSH_DATA_DIR = join(root, "data");+ return {+ host: "127.0.0.1",+ port: 0,+ token: "owt_tasks_client",+ hostToken: "owt_tasks_host",+ configPath: join(root, "server.json"),+ approval: { mode: "auto", timeoutMs: 1000 },+ corsOrigins: ["*"],+ workspaces,+ authorizedRoots: workspaces.map((workspace) => workspace.path),+ readOnly: false,+ startedAt: Date.now(),+ tokenSource: "cli",+ hostTokenSource: "cli",+ logFormat: "pretty",+ logRequests: false,+ };+}++function localWorkspace(path: string): WorkspaceInfo {+ return { id: workspaceIdForPath(path), name: basename(path), path, preset: "starter", workspaceType: "local" };+}++type Harness = {+ config: ServerConfig;+ traces: Array<{ sessionId: string; type: string; data: Record<string, unknown> }>;+ busy: Map<string, boolean>;+ aborted: string[];+ stopped: string[];+ changes: number;+ call: (method: string, path: string, body?: unknown) => Promise<{ status: number; json: Record<string, unknown> }>;+};++function harness(config: ServerConfig): Harness {+ const routes: Route[] = [];+ const state: Harness = {+ config, traces: [], busy: new Map(), aborted: [], stopped: [], changes: 0,+ call: async () => ({ status: 0, json: {} }),+ };+ const engine: TaskEngine = {+ sessionBusy: async (_workspace, sessionId) => state.busy.get(sessionId) ?? false,+ abort: async (_workspace, sessionId) => { state.aborted.push(sessionId); },+ lastReply: async () => "All done: added the file.",+ };+ registerWorkspaceTaskRoutes({+ routes,+ config,+ onWorkspacesChanged: () => { state.changes += 1; },+ jsonResponse: (data, status = 200) => Response.json(data, { status }),+ readJsonBody: async (request) => request.json(),+ ensureWritable: () => undefined,+ resolveWorkspace: async (routeConfig, id) => {+ const found = routeConfig.workspaces.find((workspace) => workspace.id === id);+ if (!found) throw new Error("workspace not found");+ return found;+ },+ serializeWorkspace: (workspace) => workspace,+ stopWorkspaceWork: async (_config, workspace) => { state.stopped.push(workspace.id); },+ engine,+ recordTrace: (sessionId, type, data) => { state.traces.push({ sessionId, type, data }); },+ });+ state.call = async (method, path, body) => {+ const matched = matchRoute(routes, method, path);+ if (!matched) throw new Error(`no route ${method} ${path}`);+ const url = new URL(`http://127.0.0.1${path}`);+ const request = new Request(url, { method, ...(body === undefined ? {} : { body: JSON.stringify(body), headers: { "content-type": "application/json" } }) });+ // Only the fields these routes read: the request, its params and the server config.+ const ctx = { request, url, params: matched.params, config } as unknown as RequestContext;+ try {+ const response = await matched.handler(ctx);+ return { status: response.status, json: await response.json() };+ } catch (error) {+ const failure = error as { status?: number; code?: string; message?: string };+ return { status: failure.status ?? 500, json: { code: failure.code, message: failure.message } };+ }+ };+ return state;+}++describe("parallel tasks (desktop)", () => {+ let repo = "";+ let root = "";+ let h: Harness;+ let mainId = "";++ beforeAll(async () => {+ ({ root, repo } = await makeRepo());+ const main = localWorkspace(repo);+ mainId = main.id;+ h = harness(makeConfig(root, [main]));+ });++ test("a folder outside git has no tasks and says why", async () => {+ const plain = join(root, "plain");+ await mkdir(plain);+ const config = makeConfig(root, [localWorkspace(plain)]);+ const other = harness(config);+ const listed = await other.call("GET", `/workspaces/${config.workspaces[0]!.id}/tasks`);+ expect(listed.status).toBe(200);+ expect(listed.json.git).toBe(false);+ const created = await other.call("POST", `/workspaces/${config.workspaces[0]!.id}/tasks`, { prompt: "x" });+ expect(created.status).toBe(400);+ expect(created.json.code).toBe("task_not_git");+ });++ test("creating a task makes a worktree next to the repository and registers it as its own workspace", async () => {+ const created = await h.call("POST", `/workspaces/${mainId}/tasks`, { prompt: "Add a greeting file" });+ expect(created.status).toBe(201);+ const task = created.json.task as Record<string, string>;+ expect(dirname(task.path)).toBe(tasksDir(repo));+ expect(existsSync(join(task.path, ".git"))).toBe(true);+ expect(task.branch.startsWith("omnirush/")).toBe(true);+ expect(task.state).toBe("created");+ const workspace = h.config.workspaces.find((entry) => entry.path === task.path);+ expect(workspace?.task).toEqual({ parentWorkspaceId: mainId, taskId: task.id });+ expect(task.workspaceId).toBe(workspace!.id);+ expect(h.config.authorizedRoots).toContain(task.path);+ const saved = JSON.parse(await readFile(join(root, "server.json"), "utf8")) as { workspaces: WorkspaceInfo[] };+ expect(saved.workspaces.find((entry) => entry.path === task.path)?.task).toEqual({ parentWorkspaceId: mainId, taskId: task.id });+ // The main checkout is untouched.+ expect(git(repo, "status", "--porcelain")).toBe("");+ });++ test("the first prompt of the task's chat records its session and worktree.task_started once", async () => {+ const workspace = h.config.workspaces.find((entry) => entry.task)!;+ await noteTaskPrompt(workspace, "ses_task1", (sessionId, type, data) => h.traces.push({ sessionId, type, data }), Date.now() - 10_000);+ await noteTaskPrompt(workspace, "ses_task1", (sessionId, type, data) => h.traces.push({ sessionId, type, data }));+ await noteTaskPrompt(workspace, "ses_other", (sessionId, type, data) => h.traces.push({ sessionId, type, data }));+ const started = h.traces.filter((trace) => trace.type === TASK_STARTED_EVENT);+ expect(started.length).toBe(1);+ expect(started[0]!.sessionId).toBe("ses_task1");+ expect(started[0]!.data.origin).toBe("desktop");+ expect(JSON.stringify(started[0]!.data)).not.toContain(repo);+ const record = await readTask(repo, workspace.task!.taskId);+ expect(record.sessionId).toBe("ses_task1");+ expect(record.state).toBe("running");+ });++ test("a prompt in an ordinary workspace changes nothing", async () => {+ const before = h.traces.length;+ await noteTaskPrompt(localWorkspace(repo), "ses_main", (sessionId, type, data) => h.traces.push({ sessionId, type, data }));+ expect(h.traces.length).toBe(before);+ });++ test("the board shows running while the chat works and done once it is idle, with the changed files", async () => {+ const workspace = h.config.workspaces.find((entry) => entry.task)!;+ h.busy.set("ses_task1", true);+ let listed = await h.call("GET", `/workspaces/${mainId}/tasks`);+ let task = (listed.json.tasks as Array<Record<string, unknown>>)[0]!;+ expect(task.state).toBe("running");+ const refused = await h.call("POST", `/workspaces/${mainId}/tasks/${String(task.id)}/apply`);+ expect(refused.status).toBe(409);+ expect(refused.json.code).toBe("task_running");+ await writeFile(join(workspace.path, "greeting.txt"), "hi\n");+ await writeFile(join(workspace.path, "notes.txt"), "one\ntwo\n");+ h.busy.set("ses_task1", false);+ listed = await h.call("GET", `/workspaces/${mainId}/tasks`);+ task = (listed.json.tasks as Array<Record<string, unknown>>)[0]!;+ expect(task.state).toBe("done");+ expect(task.files).toBe(2);+ expect(listed.json.repo).toBe("app");+ expect(listed.json.branch).toBe("main");+ const shown = await h.call("GET", `/workspaces/${mainId}/tasks/${String(task.id)}`);+ expect(String(shown.json.stat)).toContain("greeting.txt");+ expect(shown.json.reply).toBe("All done: added the file.");+ });++ test("apply puts the changes into the main checkout uncommitted and records worktree.task_merged on the task's chat", async () => {+ const id = (await readTask(repo, h.config.workspaces.find((entry) => entry.task)!.task!.taskId)).id;+ const applied = await h.call("POST", `/workspaces/${mainId}/tasks/${id}/apply`);+ expect(applied.status).toBe(200);+ expect(readFileSync(join(repo, "greeting.txt"), "utf8")).toBe("hi\n");+ expect(git(repo, "log", "--oneline").split("\n").length).toBe(1);+ const merged = h.traces.filter((trace) => trace.type === TASK_MERGED_EVENT);+ expect(merged.length).toBe(1);+ expect(merged[0]!.sessionId).toBe("ses_task1");+ expect(merged[0]!.data).toMatchObject({ mode: "apply", files_changed: 2, origin: "desktop" });+ expect((applied.json.task as Record<string, unknown>).state).toBe("applied");+ git(repo, "add", "-A");+ git(repo, "commit", "-q", "-m", "applied");+ });++ test("a conflicting apply changes nothing and says so; merge brings a clean task in as a merge commit", async () => {+ const created = await h.call("POST", `/workspaces/${mainId}/tasks`, { prompt: "Edit the readme" });+ const task = created.json.task as Record<string, string>;+ const workspace = h.config.workspaces.find((entry) => entry.task?.taskId === task.id)!;+ await noteTaskPrompt(workspace, "ses_task2", () => undefined, Date.now() - 10_000);+ await writeFile(join(task.path, "README.md"), "hello from the task\n");+ await writeFile(join(repo, "README.md"), "hello from main\n");+ const conflict = await h.call("POST", `/workspaces/${mainId}/tasks/${task.id}/apply`);+ expect(conflict.status).toBe(409);+ expect(conflict.json.code).toBe("task_conflict");+ expect(readFileSync(join(repo, "README.md"), "utf8")).toBe("hello from main\n");+ git(repo, "checkout", "--", "README.md");+ const merged = await h.call("POST", `/workspaces/${mainId}/tasks/${task.id}/merge`);+ expect(merged.status).toBe(200);+ expect(readFileSync(join(repo, "README.md"), "utf8")).toBe("hello from the task\n");+ expect(git(repo, "log", "-1", "--format=%P").split(" ").length).toBe(2);+ expect(git(repo, "status", "--porcelain")).toBe("");+ });++ test("stop aborts the task's chat; remove deletes the worktree, branch, record and workspace; clean removes finished ones", async () => {+ const created = await h.call("POST", `/workspaces/${mainId}/tasks`, { prompt: "Something long" });+ const task = created.json.task as Record<string, string>;+ const workspace = h.config.workspaces.find((entry) => entry.task?.taskId === task.id)!;+ await noteTaskPrompt(workspace, "ses_task3", () => undefined);+ h.busy.set("ses_task3", true);+ const stopped = await h.call("POST", `/workspaces/${mainId}/tasks/${task.id}/stop`);+ expect(stopped.json.stopped).toBe(true);+ expect(h.aborted).toContain("ses_task3");+ expect((stopped.json.task as Record<string, unknown>).state).toBe("stopped");+ const removed = await h.call("DELETE", `/workspaces/${mainId}/tasks/${task.id}`);+ expect(removed.status).toBe(200);+ expect(existsSync(task.path)).toBe(false);+ expect(git(repo, "branch", "--list", task.branch)).toBe("");+ expect(h.config.workspaces.some((entry) => entry.task?.taskId === task.id)).toBe(false);+ expect(h.config.authorizedRoots).not.toContain(task.path);+ expect(h.stopped).toContain(workspace.id);++ const cleaned = await h.call("POST", `/workspaces/${mainId}/tasks/clean`);+ expect((cleaned.json.removed as string[]).length).toBe(2);+ expect(h.config.workspaces.filter((entry) => entry.task)).toEqual([]);+ expect(readdirSync(tasksDir(repo)).filter((name) => !name.startsWith("."))).toEqual([]);+ const listed = await h.call("GET", `/workspaces/${mainId}/tasks`);+ expect(listed.json.tasks).toEqual([]);+ });++ 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>;+ const record = await readTask(repo, task.id);+ const later = await liveTask(record, null, { sessionBusy: async () => null, abort: async () => undefined, lastReply: async () => "" }, Date.now() + 3 * 60_000);+ expect(later.state).toBe("stopped");+ await h.call("DELETE", `/workspaces/${mainId}/tasks/${task.id}`);+ });+});++describe("parallel task routes on the server", () => {+ test("listed for the host, refused without its token", async () => {+ const { root, repo } = await makeRepo();+ const config = makeConfig(root, [localWorkspace(repo)]);+ const server = await startServer(config) as { port: number; stop: (close?: boolean) => void | Promise<void> };+ try {+ const url = `http://127.0.0.1:${server.port}/workspaces/${config.workspaces[0]!.id}/tasks`;+ const denied = await fetch(url, { headers: { Authorization: `Bearer ${config.token}` } });+ expect(denied.status).toBe(401);+ const allowed = await fetch(url, { headers: { Authorization: `Bearer ${config.token}`, "X-OmniRush-Host-Token": config.hostToken } });+ expect(allowed.status).toBe(200);+ expect(await allowed.json()).toMatchObject({ git: true, repo: "app", tasks: [] });+ } finally {+ await server.stop(true);+ }+ });+});++test("CLI/desktop parity: the workspace modules match PARITY.sha256 (the same list ships in the CLI)", () => {+ const dir = join(import.meta.dir, "workspace");+ const lines = readFileSync(join(dir, "PARITY.sha256"), "utf8").split("\n").filter((line) => line && !line.startsWith("#"));+ const listed = new Map(lines.map((line) => { const [hash, name] = line.split(/\s+/); return [name!, hash!]; }));+ const files = readdirSync(dir).filter((name) => name.endsWith(".mjs")).sort();+ expect([...listed.keys()].sort()).toEqual(files);+ expect(files).toEqual(["home-view.mjs", "worktree-tasks.mjs"]);+ for (const name of files) {+ expect(createHash("sha256").update(readFileSync(join(dir, name))).digest("hex")).toBe(listed.get(name)!);+ }+});diff --git a/apps/server/src/workspace/PARITY.sha256 b/apps/server/src/workspace/PARITY.sha256new file mode 100644index 00000000..95e4322a--- /dev/null+++ b/apps/server/src/workspace/PARITY.sha256@@ -0,0 +1,3 @@+# Byte-identical in omnirush-cli assets/extensions/omnirush/workspace/ (worktree tasks + home view).+40b1579de2e3db46ad3aa7377329b2668e24aae59636557122934149571f500f worktree-tasks.mjs+90bdb16dd097c79f5f5bc68f33d8eb530b56c6d8c380dd4c3b6290640a03b9e2 home-view.mjsdiff --git a/apps/server/src/workspace/home-view.d.mts b/apps/server/src/workspace/home-view.d.mtsnew file mode 100644index 00000000..8ddf4a40--- /dev/null+++ b/apps/server/src/workspace/home-view.d.mts@@ -0,0 +1,22 @@+// Types of home-view.mjs (the shared module itself is plain JavaScript).++export type StoredChat = { id: string; title?: string | null; directory: string; updatedAt: number; parentId?: string | null; archived?: boolean };+export type RecentChat = { id: string; title: string; directory: string; project: string; updatedAt: number };+export type RecentProject = { directory: string; name: string; updatedAt: number; chats: number; lastSessionId: string; task: boolean };+export type SearchHit = { sessionId: string; title?: string | null; directory: string; updatedAt: number; text?: string | null; role?: string | null };+export type RankedResult = { sessionId: string; title: string; directory: string; project: string; updatedAt: number; score: number; excerpt: string; role: string | null };++export const RECENT_SESSIONS: number;+export const RECENT_PROJECTS: number;+export const SEARCH_RESULTS: number;+export const SNIPPET_WIDTH: number;++export function projectName(directory: string): string;+export function isTaskFolder(directory: string): boolean;+export function relativeAge(ms: number, now?: number): string;+export function chatTitle(title: string | null | undefined): string;+export function recentView(sessions: StoredChat[], options?: { sessionLimit?: number; projectLimit?: number }): { sessions: RecentChat[]; projects: RecentProject[] };+export function searchTerms(query: string): string[];+export function matchesAll(text: string, terms: string[]): boolean;+export function snippet(text: string, terms: string[], width?: number): string;+export function rankHits(hits: SearchHit[], query: string, options?: { limit?: number }): RankedResult[];diff --git a/apps/server/src/workspace/home-view.mjs b/apps/server/src/workspace/home-view.mjsnew file mode 100644index 00000000..19342da9--- /dev/null+++ b/apps/server/src/workspace/home-view.mjs@@ -0,0 +1,127 @@+// omnirush: the home screen's model (recent projects and chats, local chat search).+//+// PARITY: byte-identical in omnirush-cli assets/extensions/omnirush/workspace/+// and omnirush-gui apps/server/src/workspace/ (see PARITY.sha256 there).+//+// Pure functions over the chats already stored on this computer. Searching+// reads only the local engine store: nothing here sends chat history anywhere.++import path from "node:path";++import { TASKS_SUFFIX } from "./worktree-tasks.mjs";++export const RECENT_SESSIONS = 8;+export const RECENT_PROJECTS = 6;+export const SEARCH_RESULTS = 30;+export const SNIPPET_WIDTH = 90;++/** A folder's display name; a task worktree reads "app › fix-login-3f2a". */+export function projectName(directory) {+ const dir = String(directory || "");+ if (!dir) return "";+ const base = path.basename(dir) || dir;+ const parent = path.basename(path.dirname(dir));+ if (parent.endsWith(TASKS_SUFFIX) && parent.length > TASKS_SUFFIX.length) return `${parent.slice(0, -TASKS_SUFFIX.length)} › ${base}`;+ return base;+}++/** Whether a folder is a task worktree (`<repo>-tasks/<name>`). */+export function isTaskFolder(directory) {+ const parent = path.basename(path.dirname(String(directory || "")));+ return parent.endsWith(TASKS_SUFFIX) && parent.length > TASKS_SUFFIX.length;+}++/** "just now", "5 min ago", "3 h ago", "yesterday", "4 d ago", then the date. */+export function relativeAge(ms, now = Date.now()) {+ const t = Number(ms);+ if (!Number.isFinite(t) || t <= 0) return "";+ const s = Math.max(0, Math.round((now - t) / 1000));+ if (s < 60) return "just now";+ if (s < 3600) return `${Math.round(s / 60)} min ago`;+ if (s < 86_400) return `${Math.round(s / 3600)} h ago`;+ if (s < 2 * 86_400) return "yesterday";+ if (s < 14 * 86_400) return `${Math.round(s / 86_400)} d ago`;+ return new Date(t).toISOString().slice(0, 10);+}++/** A chat's title for lists (the engine's default "New session - <date>" reads "Untitled chat"). */+export function chatTitle(title) {+ const text = String(title || "").replace(/\s+/g, " ").trim();+ if (!text || /^(new session|child session)\s*-\s*\d{4}-/i.test(text)) return "Untitled chat";+ return text.length > 72 ? `${text.slice(0, 69).trimEnd()}…` : text;+}++/**+ * Recent chats and projects from a list of root sessions+ * ({ id, title, directory, updatedAt }), newest first; sub-agent sessions+ * (with a parentId) and archived ones are left out.+ */+export function recentView(sessions, { sessionLimit = RECENT_SESSIONS, projectLimit = RECENT_PROJECTS } = {}) {+ const roots = (Array.isArray(sessions) ? sessions : [])+ .filter((s) => s && s.id && s.directory && !s.parentId && !s.archived)+ .map((s) => ({ ...s, updatedAt: Number(s.updatedAt) || 0 }))+ .sort((a, b) => b.updatedAt - a.updatedAt);+ const projects = new Map();+ for (const s of roots) {+ const p = projects.get(s.directory);+ if (p) p.chats += 1;+ else projects.set(s.directory, { directory: s.directory, name: projectName(s.directory), updatedAt: s.updatedAt, chats: 1, lastSessionId: s.id, task: isTaskFolder(s.directory) });+ }+ return {+ sessions: roots.slice(0, sessionLimit).map((s) => ({ id: s.id, title: chatTitle(s.title), directory: s.directory, project: projectName(s.directory), updatedAt: s.updatedAt })),+ projects: [...projects.values()].slice(0, projectLimit),+ };+}++/** The words of a search (lower case, at least one character, at most 8). */+export function searchTerms(query) {+ return String(query || "").toLowerCase().split(/\s+/).map((w) => w.trim()).filter(Boolean).slice(0, 8);+}++/** Whether every term occurs in the text (case-insensitive). */+export function matchesAll(text, terms) {+ const hay = String(text || "").toLowerCase();+ return terms.length > 0 && terms.every((term) => hay.includes(term));+}++/** A one-line excerpt around the first term found ("…before term after…"). */+export function snippet(text, terms, width = SNIPPET_WIDTH) {+ const flat = String(text || "").replace(/\s+/g, " ").trim();+ if (!flat) return "";+ const lower = flat.toLowerCase();+ let at = -1;+ for (const term of terms) {+ const i = lower.indexOf(term);+ if (i >= 0 && (at < 0 || i < at)) at = i;+ }+ if (at < 0 || flat.length <= width) return flat.length > width ? `${flat.slice(0, width - 1)}…` : flat;+ const start = Math.max(0, at - Math.floor(width / 3));+ const end = Math.min(flat.length, start + width);+ return `${start > 0 ? "…" : ""}${flat.slice(start, end).trim()}${end < flat.length ? "…" : ""}`;+}++/**+ * Ranks search hits ({ sessionId, title, directory, updatedAt, text, role })+ * into one result per chat: title matches first, then the newest; each result+ * carries the excerpt of its best hit.+ */+export function rankHits(hits, query, { limit = SEARCH_RESULTS } = {}) {+ const terms = searchTerms(query);+ if (!terms.length) return [];+ const best = new Map();+ for (const hit of Array.isArray(hits) ? hits : []) {+ if (!hit?.sessionId) continue;+ const inTitle = matchesAll(hit.title, terms);+ const inText = matchesAll(hit.text, terms);+ if (!inTitle && !inText) continue;+ const score = (inTitle ? 2 : 0) + (inText ? 1 : 0);+ const prev = best.get(hit.sessionId);+ if (!prev || score > prev.score || (score === prev.score && (hit.updatedAt || 0) > (prev.updatedAt || 0))) {+ best.set(hit.sessionId, {+ sessionId: hit.sessionId, title: chatTitle(hit.title), directory: hit.directory, project: projectName(hit.directory),+ updatedAt: Number(hit.updatedAt) || 0, score, excerpt: inText ? snippet(hit.text, terms) : "", role: inText ? hit.role || null : null,+ });+ }+ }+ return [...best.values()].sort((a, b) => b.score - a.score || b.updatedAt - a.updatedAt).slice(0, limit);+}diff --git a/apps/server/src/workspace/worktree-tasks.d.mts b/apps/server/src/workspace/worktree-tasks.d.mtsnew file mode 100644index 00000000..80a1cc54--- /dev/null+++ b/apps/server/src/workspace/worktree-tasks.d.mts@@ -0,0 +1,82 @@+// Types of worktree-tasks.mjs (the shared module itself is plain JavaScript).++export type TaskState = "created" | "running" | "done" | "failed" | "stopped" | "applied" | "merged" | "missing";++export type TaskRecord = {+ version: number;+ id: string;+ title: string;+ prompt: string;+ origin: string;+ repo: string;+ repoName: string;+ path: string;+ branch: string;+ baseBranch: string | null;+ baseCommit: string;+ state: TaskState;+ createdAt: string;+ startedAt: string | null;+ finishedAt: string | null;+ sessionId: string | null;+ parentSessionId: string | null;+ pid: number | null;+ exitCode: number | null;+ summary: string | null;+ log: string | null;+ result: { mode: "apply" | "merge"; files: number; at: string } | null;+};++export type RepoInfo = {+ top: string;+ here: string;+ commonDir: string;+ branch: string | null;+ head: string | null;+ name: string;+ inWorktree: boolean;+};++export type TaskChange = { status: string; file: string };++export const TASKS_VERSION: number;+export const TASKS_SUFFIX: string;+export const RECORDS_DIR: string;+export const BRANCH_PREFIX: string;+export const TASK_STARTED_EVENT: "worktree.task_started";+export const TASK_MERGED_EVENT: "worktree.task_merged";+export const STATES: readonly TaskState[];++export class TaskError extends Error {+ constructor(message: string, code?: string, details?: unknown);+ code: string;+ details?: unknown;+}++export function runGit(args: string[], options?: { cwd?: string; env?: Record<string, string>; input?: string; timeoutMs?: number }): Promise<{ code: number; stdout: string; stderr: string }>;+export function repoOf(dir: string): Promise<RepoInfo | null>;+export function tasksDir(top: string): string;+export function recordsDir(top: string): string;+export function recordPath(top: string, id: string): string;+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 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 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 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 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;+export function stateLabel(state: TaskState | string): string;diff --git a/apps/server/src/workspace/worktree-tasks.mjs b/apps/server/src/workspace/worktree-tasks.mjsnew file mode 100644index 00000000..6d3b8336--- /dev/null+++ b/apps/server/src/workspace/worktree-tasks.mjs@@ -0,0 +1,400 @@+// omnirush: parallel tasks, each in its own git worktree (shared by the CLI and the desktop app).+//+// PARITY: byte-identical in omnirush-cli assets/extensions/omnirush/workspace/+// and omnirush-gui apps/server/src/workspace/ (see PARITY.sha256 there).+//+// A task is a prompt that runs in a separate checkout of the repository, on its+// own branch, so several can run at once without touching the main checkout:+//+// ~/code/app the main checkout (where the user works)+// ~/code/app-tasks/<slug> one worktree per task (branch omnirush/<slug>)+// ~/code/app-tasks/.omnirush-tasks/<id>.json the task records+//+// The worktrees sit NEXT TO the repository, never inside it, so a session in the+// main checkout never sees (or uploads) another task's files, and a task's+// session has exactly one project root: its worktree. Each task runs as its own+// session in that folder (the CLI: a separate headless run; the desktop: a+// workspace of its own), so capture, project copies and the sandbox treat it+// like any other project folder.+//+// The result comes back to the main checkout in one of two ways:+// apply the task's changes (vs the commit it started from) are applied to+// the main checkout's working tree, uncommitted, for review+// merge the task's changes are committed on its branch, which is merged+// into the main checkout's current branch (no fast-forward)+// Nothing here commits in the main checkout except `merge`, and nothing ever+// pushes. Removing a task removes its worktree and (unless kept) its branch.+//+// Plain JavaScript (node and bun), no dependencies besides node:*.++import { execFile } 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";++export const TASKS_VERSION = 1;+/** Where the worktrees of `<repo>` go: a sibling folder `<repo>-tasks`. */+export const TASKS_SUFFIX = "-tasks";+/** The task records, inside the tasks folder (never inside a worktree). */+export const RECORDS_DIR = ".omnirush-tasks";+/** Task branches: `omnirush/<slug>`. */+export const BRANCH_PREFIX = "omnirush/";++/** Trace event on the task's own session when it starts (additive; see docs). */+export const TASK_STARTED_EVENT = "worktree.task_started";+/** Trace event when a task's result is applied or merged into the main checkout (additive). */+export const TASK_MERGED_EVENT = "worktree.task_merged";++/** The states a record goes through. */+export const STATES = Object.freeze(["created", "running", "done", "failed", "stopped", "applied", "merged", "missing"]);+const FINISHED = new Set(["done", "failed", "stopped"]);++const GIT_TIMEOUT_MS = 60_000;+const MAX_BUFFER = 64 * 1024 * 1024;++/** Runs git; resolves { code, stdout, stderr } (never rejects for a git error). */+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" },+ }, (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) : "") });+ });+ if (input !== undefined) child.stdin?.end(input);+ });+}++async function gitOut(args, options) {+ const result = await runGit(args, options);+ if (result.code !== 0) throw new TaskError(firstLine(result.stderr) || `git ${args[0]} failed`, "git_failed");+ return result.stdout.trim();+}++export class TaskError extends Error {+ constructor(message, code = "task_failed", details) {+ super(message);+ this.name = "TaskError";+ this.code = code;+ if (details !== undefined) this.details = details;+ }+}++function firstLine(text) {+ return String(text || "").split(/\r?\n/).map((line) => line.trim()).find(Boolean) || "";+}++/**+ * The repository `dir` belongs to, resolved to its MAIN checkout (a task+ * started from inside a task's worktree still belongs to the main repository).+ * Null when `dir` is not in a git repository.+ */+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 });+ if (common.code !== 0) return null;+ const commonDir = path.resolve(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;+ const branch = (await runGit(["symbolic-ref", "--quiet", "--short", "HEAD"], { cwd: main })).stdout.trim() || null;+ const head = (await runGit(["rev-parse", "--verify", "--quiet", "HEAD"], { cwd: main })).stdout.trim() || null;+ return { top: main, here, commonDir, branch, head, name: path.basename(main), inWorktree: here !== main };+}++/** The sibling folder holding `<repo>`'s task worktrees. */+export function tasksDir(top) {+ return path.join(path.dirname(top), `${path.basename(top)}${TASKS_SUFFIX}`);+}++export function recordsDir(top) {+ return path.join(tasksDir(top), RECORDS_DIR);+}++export function recordPath(top, id) {+ if (!/^[a-z0-9-]{4,64}$/.test(String(id))) throw new TaskError("Unknown task.", "bad_id");+ return path.join(recordsDir(top), `${id}.json`);+}++/** A short, filesystem- and branch-safe name from a title or prompt. */+export function slugify(text, max = 32) {+ const words = String(text || "").toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "")+ .replace(/[^a-z0-9]+/g, " ").trim().split(/\s+/).filter(Boolean);+ let slug = "";+ for (const word of words) {+ const next = slug ? `${slug}-${word}` : word;+ if (next.length > max) break;+ slug = next;+ }+ return slug || "task";+}++/** A title for a prompt: its first line, trimmed to 60 characters. */+export function titleFor(prompt) {+ const line = firstLine(prompt).replace(/\s+/g, " ");+ return line.length > 60 ? `${line.slice(0, 57).trimEnd()}…` : line || "Task";+}++export function newTaskId(now = Date.now(), random = randomBytes(3)) {+ return `${now.toString(36)}-${Buffer.from(random).toString("hex")}`;+}++async function exists(file) {+ return stat(file).then(() => true, () => false);+}++async function writeRecord(file, record) {+ await mkdir(path.dirname(file), { recursive: true });+ const temp = `${file}.${process.pid}.${randomBytes(3).toString("hex")}.tmp`;+ await writeFile(temp, `${JSON.stringify(record, null, 2)}\n`, "utf8");+ await rename(temp, file);+}++/**+ * Creates a task: a new branch from the main checkout's HEAD and a worktree+ * for it in `<repo>-tasks/<slug>`, plus its record. Does not start anything.+ */+export async function createTask({ dir, prompt, title, origin = "cli", parentSessionId = null, now = Date.now() } = {}) {+ const text = String(prompt ?? "").trim();+ if (!text) throw new TaskError("A task needs a prompt.", "no_prompt");+ const 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 (added.code !== 0) throw new TaskError(firstLine(added.stderr) || "Could not create the task's folder.", "worktree_failed");+ 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,+ };+ 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). */+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 };+ await writeRecord(file, next);+ return next;+}++/** Merges `patch` into the record at `file` (a task's run reports through this); null when it is gone. */+export async function updateTaskFile(file, patch) {+ const raw = await readFile(file, "utf8").catch(() => null);+ if (!raw) return null;+ const next = { ...JSON.parse(raw), ...patch };+ await writeRecord(file, next);+ return next;+}++/** Whether a process id is alive (signal 0). */+export function pidAlive(pid) {+ if (!Number.isInteger(pid) || pid <= 0) return false;+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return error?.code === "EPERM";+ }+}++/** 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" };+ return next;+}++/** Reads one task of the repository `dir` belongs to. */+export async function readTask(dir, id) {+ const repo = await repoOf(dir);+ if (!repo) throw new TaskError("This folder is not in a git repository.", "not_git");+ const raw = await readFile(recordPath(repo.top, id), "utf8").catch(() => null);+ if (!raw) throw new TaskError(`No task ${id}.`, "not_found");+ return reconcile(JSON.parse(raw));+}++/** All tasks of the repository `dir` belongs to, newest first. [] outside git. */+export async function listTasks(dir, options = {}) {+ const repo = options.repo ?? (await repoOf(dir));+ if (!repo) return [];+ const folder = recordsDir(repo.top);+ const names = await readdir(folder).catch(() => []);+ const records = [];+ for (const name of names) {+ if (!name.endsWith(".json")) continue;+ try {+ const record = JSON.parse(await readFile(path.join(folder, name), "utf8"));+ if (record?.version === TASKS_VERSION && record.id) records.push(await reconcile(record, options));+ } catch {+ // A half-written or foreign file: skipped.+ }+ }+ return records.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)));+}++/** Finds a task by id or by a unique id/name prefix. */+export async function findTask(dir, ref) {+ const tasks = await listTasks(dir);+ const wanted = String(ref || "").trim();+ const exact = tasks.find((task) => task.id === wanted || path.basename(task.path) === wanted);+ if (exact) return exact;+ const matches = tasks.filter((task) => task.id.startsWith(wanted) || path.basename(task.path).startsWith(wanted));+ if (matches.length === 1) return matches[0];+ throw new TaskError(matches.length ? `"${wanted}" matches ${matches.length} tasks; use more of the id.` : `No task "${wanted}".`, matches.length ? "ambiguous" : "not_found");+}++/**+ * Stages everything in the task's worktree (its own index, never the main+ * checkout's) and returns the changed files vs the commit it started from:+ * [{ status: "A"|"M"|"D"|"R"|..., file }].+ */+export async function taskChanges(task) {+ if (!(await exists(task.path))) return [];+ const added = await runGit(["add", "-A"], { cwd: task.path });+ if (added.code !== 0) throw new TaskError(firstLine(added.stderr) || "Could not read the task's changes.", "git_failed");+ const out = await gitOut(["diff", "--cached", "--name-status", "-M", task.baseCommit], { cwd: task.path });+ return out ? out.split("\n").map((line) => {+ const [status, ...files] = line.split("\t");+ return { status: status[0], file: files[files.length - 1] };+ }) : [];+}++/**+ * How many files differ from the commit the task started from, read without+ * touching the worktree's index (safe while the task runs). Null when unknown.+ */+export async function taskFileCount(task) {+ if (!(await exists(task.path))) return null;+ const status = await runGit(["status", "--porcelain", "--untracked-files=all"], { cwd: task.path });+ const committed = await runGit(["diff", "--name-only", task.baseCommit, "HEAD"], { cwd: task.path });+ if (status.code !== 0 || committed.code !== 0) return null;+ const files = new Set(committed.stdout.split("\n").filter(Boolean));+ for (const line of status.stdout.split("\n")) if (line.length > 3) files.add(line.slice(3).replace(/^.* -> /, ""));+ return files.size;+}++/** The task's changes as a binary-safe patch vs the commit it started from ("" when none). */+export async function taskPatch(task) {+ await taskChanges(task);+ const result = await runGit(["diff", "--cached", "--binary", "-M", task.baseCommit], { cwd: task.path });+ if (result.code !== 0) throw new TaskError(firstLine(result.stderr) || "Could not read the task's changes.", "git_failed");+ return result.stdout;+}++/** A short text diff stat (`git diff --stat`) of the task's changes. */+export async function taskStat(task) {+ await taskChanges(task);+ return gitOut(["diff", "--cached", "--stat", "-M", task.baseCommit], { cwd: task.path }).catch(() => "");+}++/**+ * Brings a finished task's result into the main checkout.+ * mode "apply": its patch is applied to the working tree (index untouched), all or nothing.+ * mode "merge": its changes are committed on the task branch, which is merged (--no-ff).+ * Refuses a task that is still running. Returns the updated record plus+ * { files, mode }. On a conflict nothing is left half-done (merge --abort).+ */+export async function bringBack(task, { mode = "apply", message, now = Date.now() } = {}) {+ if (task.state === "running" || task.state === "created") throw new TaskError("The task is still running; wait for it to finish (or stop it) first.", "running");+ if (task.state === "missing") throw new TaskError("The task's folder is gone.", "missing");+ if (task.state === "applied" || task.state === "merged") throw new TaskError(`The task was ${task.state} already.`, "done_already");+ const files = await taskChanges(task);+ if (!files.length) throw new TaskError("The task changed nothing.", "no_changes");+ if (mode === "apply") {+ const patch = await taskPatch(task);+ const check = await runGit(["apply", "--check", "--binary", "-"], { cwd: task.repo, input: patch });+ if (check.code !== 0) throw new TaskError("The changes do not apply cleanly to the main checkout (it changed in the same places). Use merge, or resolve by hand.", "conflict", { stderr: check.stderr.slice(0, 2000) });+ 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 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)) {+ throw new TaskError(firstLine(committed.stderr) || "Could not commit the task's changes.", "commit_failed");+ }+ 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 });+ 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 {+ throw new TaskError(`Unknown mode ${mode}.`, "bad_mode");+ }+ const record = await updateTask(task, { state: mode === "apply" ? "applied" : "merged", result: { mode, files: files.length, at: new Date(now).toISOString() } });+ return { record, files, mode };+}++/**+ * 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 (await exists(task.path)) {+ const removed = await runGit(["worktree", "remove", "--force", task.path], { cwd: task.repo });+ if (removed.code !== 0) {+ // A folder git no longer knows as a worktree: removed by hand, then pruned.+ await rm(task.path, { recursive: true, force: true });+ }+ }+ await runGit(["worktree", "prune"], { cwd: task.repo });+ if (!keepBranch) await runGit(["branch", "-D", task.branch], { cwd: task.repo });+ await rm(recordPath(task.repo, task.id), { force: true });+ return { removed: true, branchKept: keepBranch };+}++/** Removes every task that was applied, merged or whose folder is gone. */+export async function cleanTasks(dir, options = {}) {+ const removed = [];+ for (const task of await listTasks(dir, options)) {+ if (["applied", "merged", "missing"].includes(task.state)) {+ await removeTask(task, options).then(() => removed.push(task.id), () => undefined);+ }+ }+ return removed;+}++/** The trace data of TASK_STARTED_EVENT (no paths, no prompt: the session has those). */+export function taskStartedData(task) {+ return {+ task_id: task.id, origin: task.origin, branch: task.branch,+ base_branch: task.baseBranch, base_commit: task.baseCommit,+ parent_session_id: task.parentSessionId || null,+ };+}++/** The trace data of TASK_MERGED_EVENT. */+export function taskMergedData(task, { mode, files }) {+ return {+ task_id: task.id, origin: task.origin, mode, files_changed: Array.isArray(files) ? files.length : Number(files) || 0,+ task_session_id: task.sessionId || null, branch: task.branch, base_commit: task.baseCommit,+ };+}++/** Whether a task finished (successfully or not) and can be brought back or removed. */+export function isFinished(task) {+ return FINISHED.has(task.state);+}++/** One line for lists: "● running fix-login-3f2a Fix the login redirect (2 min)". */+export function stateLabel(state) {+ return {+ created: "starting", running: "running", done: "done", failed: "failed", stopped: "stopped",+ applied: "applied", merged: "merged", missing: "missing",+ }[state] || state;+}diff --git a/apps/server/src/workspaces.ts b/apps/server/src/workspaces.tsindex 1c598dfc..24cd11f1 100644--- a/apps/server/src/workspaces.ts+++ b/apps/server/src/workspaces.ts@@ -67,6 +67,9 @@ export function buildWorkspaceInfos(sandboxContainerName: workspace.sandboxContainerName,opencodeUsername: workspace.opencodeUsername,opencodePassword: workspace.opencodePassword,+ ...(typeof workspace.task?.parentWorkspaceId === "string" && typeof workspace.task.taskId === "string"+ ? { task: { parentWorkspaceId: workspace.task.parentWorkspaceId, taskId: workspace.task.taskId } }+ : {}),};});}diff --git a/packages/types/src/workspace.ts b/packages/types/src/workspace.tsindex 3fb3bd34..0080e44f 100644--- a/packages/types/src/workspace.ts+++ b/packages/types/src/workspace.ts@@ -16,6 +16,12 @@ export type WorkspaceKind = "local" | "remote";export type WorkspaceRemoteKind = "opencode" | "omnirush";+/** A workspace that is one parallel task's own checkout (a git worktree) of another workspace. */+export type WorkspaceTaskLink = {+ parentWorkspaceId: string;+ taskId: string;+};+export type WorkspaceWire = {id: string;name: string;@@ -50,4 +56,6 @@ export type WorkspaceWire = {username?: string;password?: string;} | null;+ /** Set on a parallel task's workspace (omnirush-server only). */+ task?: WorkspaceTaskLink | null;};