Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: refuse bringing back a working task

Samrat Talukdar8281eab554af
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.tsx
index 891c50c0..4133d150 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
@@ -4,6 +4,7 @@ import { useSearchParams } from "react-router";
import { useQueryClient } from "@tanstack/react-query";
import {
AlertCircle,
+ ArrowDownToLine,
FileDiff,
GitBranch,
GitMerge,
@@ -12,7 +13,6 @@ import {
Plus,
Square,
Trash2,
- Undo2,
} from "lucide-react";
import type { OmniRushWorkspaceTask } from "@/app/lib/omnirush-server";
@@ -385,7 +385,7 @@ function TaskCard({ task, busy, ...actions }: TaskCardProps) {
{task.finished ? (
<>
<Button size="sm" variant="outline" onClick={actions.onApply} disabled={busy || !canBringBack} data-testid="task-apply">
- <Undo2 /> Apply here
+ <ArrowDownToLine /> Apply here
</Button>
<Button size="sm" variant="outline" onClick={actions.onMerge} disabled={busy || !canBringBack} data-testid="task-merge">
<GitMerge /> Merge
diff --git a/apps/app/src/react-app/shell/session-route.tsx b/apps/app/src/react-app/shell/session-route.tsx
index e145ef8c..fce86f3e 100644
--- a/apps/app/src/react-app/shell/session-route.tsx
+++ b/apps/app/src/react-app/shell/session-route.tsx
@@ -3270,7 +3270,8 @@ export function SessionRoute() {
*/
const startParallelTask = useCallback(async (workspaceId: string, prompt: string) => {
if (!client || !baseUrl || !token) throw new Error("omnirush.ai server is unavailable.");
- const created = await client.createWorkspaceTask(workspaceId, { prompt, parentSessionId: selectedSessionId });
+ // The board has no chat open: a task started there has no parent chat.
+ const created = await client.createWorkspaceTask(workspaceId, { prompt, parentSessionId: tasksRouteActive ? null : selectedSessionId });
const taskWorkspace = created.workspace;
await refreshRouteState();
void queryClient.invalidateQueries({ queryKey: workspaceTasksQueryKey(workspaceId) });
@@ -3297,7 +3298,7 @@ export function SessionRoute() {
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]);
+ }, [baseUrl, client, environmentRuntimeKey, local.prefs.defaultModel, modelVariantValue, queryClient, refreshRouteState, selectedAgent, selectedSessionId, tasksRouteActive, token]);
// The new task's folder, picked above its composer: switch to another
// workspace, or open a folder as a new one (the sidebar's "+" in one step).
@@ -3592,6 +3593,13 @@ export function SessionRoute() {
}}
onWorkspacesChanged={() => void refreshRouteState()}
/>
+ ) : tasksRouteActive && selectedWorkspace?.workspaceType === "remote" ? (
+ <div className="mx-auto max-w-xl p-6 pt-16 text-center" data-testid="tasks-remote">
+ <h2 className="text-base font-medium">Parallel tasks run on this computer</h2>
+ <p className="mt-2 text-sm text-muted-foreground">
+ This workspace is on a remote worker. Open a project folder on this computer to start tasks in their own copies of it.
+ </p>
+ </div>
) : appsRouteActive ? (
<AppsPage onNewApp={startAppConversation} />
) : automationsRouteActive ? (
diff --git a/apps/server/src/routes/workspace-tasks.ts b/apps/server/src/routes/workspace-tasks.ts
index 455b33c3..2de44444 100644
--- a/apps/server/src/routes/workspace-tasks.ts
+++ b/apps/server/src/routes/workspace-tasks.ts
@@ -1,3 +1,5 @@
+import path from "node:path";
+
import { ApiError } from "../errors.js";
import type { ServerConfig, WorkspaceInfo } from "../types.js";
import { workspaceIdForPath } from "../workspaces.js";
@@ -84,7 +86,7 @@ export type TaskView = {
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;
+ return config.workspaces.find((entry) => entry.id === id && entry.task?.taskId === record.id) ?? null;
}
function sinceMs(iso: string | null, now: number): number {
@@ -134,7 +136,10 @@ export async function taskView(config: ServerConfig, record: TaskRecord, now = D
startedAt: record.startedAt,
finishedAt: record.finishedAt,
age: relativeAge(Date.parse(record.startedAt || record.createdAt), now),
- files: await taskFileCount(record).catch(() => null),
+ // A task brought back or gone has nothing left to count (its result says how many).
+ files: record.state === "applied" || record.state === "merged" ? record.result?.files ?? null
+ : record.state === "missing" ? null
+ : await taskFileCount(record).catch(() => null),
finished: isFinished(record),
result: record.result,
};
@@ -155,6 +160,9 @@ function taskApiError(error: unknown): never {
* and that it runs, and that chat's trace gets "worktree.task_started" once.
* Only for task workspaces; every other prompt is untouched.
*/
+/** Tasks whose first prompt was noted already: later prompts in their chats skip the record read. */
+const startedTasks = new Set<string>();
+
export async function noteTaskPrompt(
workspace: WorkspaceInfo,
sessionId: string,
@@ -162,15 +170,19 @@ export async function noteTaskPrompt(
now = Date.now(),
): Promise<void> {
const link = workspace.task;
- if (!link) return;
+ if (!link || startedTasks.has(link.taskId)) return;
const record = await readTask(workspace.path, link.taskId).catch(() => null);
- if (!record || record.sessionId) return;
+ if (!record || record.sessionId) {
+ if (record) startedTasks.add(link.taskId);
+ return;
+ }
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) startedTasks.add(link.taskId);
if (started && first) recordTrace(sessionId, TASK_STARTED_EVENT, taskStartedData(started));
}
@@ -185,9 +197,19 @@ export function registerWorkspaceTaskRoutes(options: RegisterWorkspaceTaskRoutes
const findRecord = async (workspace: WorkspaceInfo, taskId: string) => {
const record = await readTask(workspace.path, taskId).catch(taskApiError);
+ // Only a record of this workspace's own repository (a copied or edited record names another).
+ const repo = await repoOf(workspace.path);
+ if (!repo || path.resolve(record.repo) !== repo.top) throw new ApiError(404, "task_not_found", "No such task in this repository.");
return liveTask(record, taskWorkspaceOf(config, record), engine);
};
+ /** Whether the task's chat works now (continued after it finished): its files are then still changing. */
+ const chatWorking = async (record: TaskRecord) => {
+ const taskWorkspace = taskWorkspaceOf(config, record);
+ if (!taskWorkspace || !record.sessionId) return false;
+ return (await engine.sessionBusy(taskWorkspace, record.sessionId).catch(() => null)) === true;
+ };
+
/** 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);
@@ -256,7 +278,7 @@ export function registerWorkspaceTaskRoutes(options: RegisterWorkspaceTaskRoutes
? (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(() => "");
+ const stat = record.state === "running" || record.state === "created" || (await chatWorking(record)) ? "" : await taskStat(record).catch(() => "");
return jsonResponse({ task: await taskView(config, record), stat, reply });
});
@@ -265,6 +287,7 @@ export function registerWorkspaceTaskRoutes(options: RegisterWorkspaceTaskRoutes
ensureWritable(config);
const workspace = await repoWorkspace(ctx.params.id);
const record = await findRecord(workspace, ctx.params.taskId);
+ if (await chatWorking(record)) throw new ApiError(409, "task_running", "The task's chat is still working; wait for it or stop it.");
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) });
diff --git a/apps/server/src/workspace-tasks.test.ts b/apps/server/src/workspace-tasks.test.ts
index 8d36f9bf..edaca472 100644
--- a/apps/server/src/workspace-tasks.test.ts
+++ b/apps/server/src/workspace-tasks.test.ts
@@ -302,6 +302,43 @@ describe("parallel tasks (desktop)", () => {
expect(existsSync(String(task.path))).toBe(false);
});
+ test("a stopped task whose chat was continued is not brought back while that chat works", async () => {
+ const created = await h.call("POST", `/workspaces/${mainId}/tasks`, { prompt: "Continued later" });
+ 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_task5", () => undefined, Date.now() - 10_000);
+ h.busy.set("ses_task5", true);
+ await h.call("POST", `/workspaces/${mainId}/tasks/${task.id}/stop`);
+ await writeFile(join(task.path, "later.txt"), "written after the stop\n");
+ for (const mode of ["apply", "merge"]) {
+ const refused = await h.call("POST", `/workspaces/${mainId}/tasks/${task.id}/${mode}`);
+ expect(refused).toMatchObject({ status: 409, json: { code: "task_running" } });
+ }
+ const shown = await h.call("GET", `/workspaces/${mainId}/tasks/${task.id}`);
+ expect(shown.json.stat).toBe("");
+ expect(git(task.path, "diff", "--cached", "--name-only")).toBe("");
+ expect(existsSync(join(repo, "later.txt"))).toBe(false);
+ h.busy.set("ses_task5", false);
+ const applied = await h.call("POST", `/workspaces/${mainId}/tasks/${task.id}/apply`);
+ expect(applied.status).toBe(200);
+ expect(existsSync(join(repo, "later.txt"))).toBe(true);
+ git(repo, "add", "-A");
+ git(repo, "commit", "-q", "-m", "later");
+ await h.call("DELETE", `/workspaces/${mainId}/tasks/${task.id}`);
+ });
+
+ test("a record that names another repository is not this workspace's task", async () => {
+ const created = await h.call("POST", `/workspaces/${mainId}/tasks`, { prompt: "Foreign record" });
+ const task = created.json.task as Record<string, string>;
+ const file = join(tasksDir(repo), ".omnirush-tasks", `${task.id}.json`);
+ const record = JSON.parse(await readFile(file, "utf8")) as Record<string, unknown>;
+ await writeFile(file, JSON.stringify({ ...record, repo: join(root, "elsewhere") }));
+ const shown = await h.call("GET", `/workspaces/${mainId}/tasks/${task.id}`);
+ expect(shown).toMatchObject({ status: 404, json: { code: "task_not_found" } });
+ await writeFile(file, JSON.stringify(record));
+ await h.call("DELETE", `/workspaces/${mainId}/tasks/${task.id}`);
+ });
+
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>;