Open-source, local-first AI agent team for your desktop: multi-agent group chats, computer use, browser, MCP, routines and approvals. macOS, Windows, Linux + Android. Built on pi.
TypeScript agentai-agentai-agentsai-assistantandroidautomationchatgptcoding-agentcomputer-usedesktop-appelectronllmlocal-firstmcpmulti-agentollamaopenaiprivacyself-hostedtypescript
fix(groups): parallel steps take turns safely when their workspace cannot be set up
leen.zhou3f2aa9989251
diff --git a/packages/brain/src/runtime/workspaces/port.ts b/packages/brain/src/runtime/workspaces/port.tsindex eaeaa73..824a34d 100644--- a/packages/brain/src/runtime/workspaces/port.ts+++ b/packages/brain/src/runtime/workspaces/port.ts@@ -154,6 +154,10 @@ export interface GroupWorktreesPort {signal: AbortSignal,step?: PlanStepWorkspace,): Promise<StepWorkspaceFallback | undefined>;+ /** After a fallback: waits until the steps ahead in the same shared folder have ended. */+ waitTurn(context: ToolRunContext, signal: AbortSignal): Promise<void>;+ /** Whether this task's run is still waiting for its turn (it has not started working). */+ waitingTurn(taskId: string): boolean;/** A task's isolated checkout and the primary folder it mirrors, for checks inside it. */isolated(taskId: string): { root: string; primary: string } | undefined;integratedRoot?(taskId: string): { root: string; primary: string } | undefined;diff --git a/packages/orchestration/src/conversations/groups/group-plan-merges.ts b/packages/orchestration/src/conversations/groups/group-plan-merges.tsindex 5a03ff2..0193257 100644--- a/packages/orchestration/src/conversations/groups/group-plan-merges.ts+++ b/packages/orchestration/src/conversations/groups/group-plan-merges.ts@@ -323,6 +323,12 @@ function turnsReason(reason: string, zh: boolean) {return zh? "这台电脑没有安装 Git,建不了独立工作区": "Git is not installed on this computer, so steps cannot have own workspaces";+ case "group_workspace_setup_failed":+ return zh ? "这次建独立工作区没有成功" : "setting up its own workspace failed this time";+ case "group_workspace_cleanup_pending":+ return zh+ ? "之前的独立工作区还没清理完,重启 Pi Bot 后才能再建"+ : "an earlier workspace here is still being cleaned up; restart Pi Bot to use own workspaces again";case "worktree_quota":return zh? "这个仓库的独立工作区已达上限"diff --git a/packages/orchestration/src/conversations/groups/group-plan-progress.ts b/packages/orchestration/src/conversations/groups/group-plan-progress.tsindex 8296e4d..2e1989e 100644--- a/packages/orchestration/src/conversations/groups/group-plan-progress.ts+++ b/packages/orchestration/src/conversations/groups/group-plan-progress.ts@@ -65,10 +65,15 @@ function facts(service: GroupService, record: GroupWorkflowRunRecord): GroupPlanconst steps = states.map((step) => {const workspace = workspaceOf(service, step, own);const files = workspace === "conflict" ? merges[step.stepId]?.files : undefined;+ const taskId =+ step.status === "running" && own.has(step.stepId) ? stepTaskId(service, step) : undefined;+ // A step waiting for its turn in the shared folder has not started: it reads as waiting, so+ // the bar never counts it among the steps running at once.+ const waiting = !!taskId && service.memberWorktrees.waitingTurn(taskId);return {stepId: step.stepId,executionRunId: step.executionRunId,- status: step.status,+ status: waiting ? ("ready" as const) : step.status,attempt: step.attempt,verdictResolution: verdictResolution(progressOf(record), step.stepId),...(progressOf(record).verdicts[step.stepId]diff --git a/packages/orchestration/src/conversations/groups/group-service.ts b/packages/orchestration/src/conversations/groups/group-service.tsindex 3fe9a5e..c0263c6 100644--- a/packages/orchestration/src/conversations/groups/group-service.ts+++ b/packages/orchestration/src/conversations/groups/group-service.ts@@ -781,7 +781,11 @@ export class GroupService implements CollaborationPort {if (!frozen) {const step = this.planStep(context);const prepared = await this.memberWorktrees.prepare(context, group, signal, step);- if (prepared?.fallback && step) this.workflows.merges.tookTurns(context, prepared.fallback);+ if (prepared?.fallback && step) {+ this.workflows.merges.tookTurns(context, prepared.fallback);+ // Taking turns means the run starts only after the sibling ahead of it in the folder.+ await this.memberWorktrees.waitTurn(context, signal);+ }}const workplace = frozen? await this.deps.local.tasks.workplace(context, signal)diff --git a/packages/workspaces/src/brain/groups/group-member-worktrees.ts b/packages/workspaces/src/brain/groups/group-member-worktrees.tsindex 987883d..a824adb 100644--- a/packages/workspaces/src/brain/groups/group-member-worktrees.ts+++ b/packages/workspaces/src/brain/groups/group-member-worktrees.ts@@ -9,9 +9,9 @@ import {createGitReader,createManagedFolders,createManagedGit,- ExecError,isManagedFolderRepository,} from "@pibot/execution";+import { containsPath } from "@pibot/policy";import {actualRootReferences,type GroupMemberWorkspace,@@ -35,7 +35,8 @@ import {} from "./group-step-cleanup.ts";import { mergeStep } from "./group-step-merge.ts";import { isPlanStepWorkspace } from "./group-step-output.ts";-import { prepareStepWorktree } from "./group-step-prepare.ts";+import { prepareFailureCode, prepareStepWorktree, SETUP_FAILED } from "./group-step-prepare.ts";+import { StepTurns } from "./group-step-turns.ts";import { createMemberWorktree } from "./group-worktree-create.ts";import { localWorktreeHost, remoteWorktreeHost, type WorktreeHost } from "./group-worktree-host.ts";import { integrateMemberWorktree } from "./group-worktree-integrate.ts";@@ -62,11 +63,17 @@ export class GroupMemberWorktrees {private readonly timer: ReturnType<typeof setInterval>;private flushing?: Promise<void>;private uncertain: unknown;+ /** Paths an uncertain cleanup still holds; only work there waits for a restart. */+ private readonly uncertainPaths: string[] = [];private readonly chains = new Map<string, Promise<void>>();/** Plan step runs whose prepare took turns in the shared folder, with the fixed reason. */private readonly fallbacks = new Map<string, string>();+ readonly turns: StepTurns;constructor(readonly service: GroupService) {const local = service.deps.local;+ this.turns = new StepTurns((groupId) =>+ local.deps.peer.emit("groups.changed", { groupId, reason: "updated" }),+ );this.repo = new GroupMemberWorkspacesRepo(local.deps.db);this.registry = new ManagedWorktreesRepo(local.deps.db);this.repo.interrupted();@@ -97,8 +104,10 @@ export class GroupMemberWorktrees {}, 5000);this.timer.unref();}+ /** A step whose workspace setup failed took turns instead: its task has no workspace. */workspace(taskId: string) {- return this.repo.get(taskId);+ const member = this.repo.get(taskId);+ return member?.state === "removed" && member.errorCode === SETUP_FAILED ? undefined : member;}serial<T>(key: string, signal: AbortSignal, operation: () => Promise<T>): Promise<T> {const prior = this.chains.get(key) ?? Promise.resolve();@@ -140,7 +149,10 @@ export class GroupMemberWorktrees {return await operation();} catch (error) {retained = isManagedCleanupFailure(error);- if (retained) this.uncertain = error;+ if (retained) {+ this.uncertain = error;+ this.uncertainPaths.push(...paths);+ }throw error;} finally {if (!retained) locks.release(id);@@ -149,8 +161,20 @@ export class GroupMemberWorktrees {signal(signal: AbortSignal) {return AbortSignal.any([signal, this.stop.signal, AbortSignal.timeout(120000)]);}+ /**+ * Whether an uncertain cleanup still holds any of `paths`. Its lock stays until a restart; work+ * in other folders and repositories goes on (it used to stop every group's workspaces).+ */+ cleanupPending(paths: readonly string[]) {+ const platform = this.service.deps.local.deps.platform;+ return this.uncertainPaths.some((held) =>+ paths.some(+ (path) => containsPath(held, path, platform) || containsPath(path, held, platform),+ ),+ );+ }current(context: ToolRunContext, member: GroupMemberWorkspace) {- if (this.uncertain) fail("group_workspace_cleanup_pending");+ if (this.cleanupPending([member.integrationPath])) fail("group_workspace_cleanup_pending");const group = this.service.active(member.groupId, context.botId, context.conversationId);if (group.conversationId !== member.sourceConversationId) fail("group_workspace_changed");const primary = group.folders?.find((f) => f.id === group.primaryFolderId);@@ -208,6 +232,9 @@ export class GroupMemberWorktrees {stage(runId: string, name: string) {this.stages.set(runId, name);}+ stageOf(runId: string) {+ return this.stages.get(runId) ?? "start";+ }async prepare(context: ToolRunContext,group: Group,@@ -229,15 +256,8 @@ export class GroupMemberWorktrees {event: "worktree_prepare_failed",groupId: group.id,runId: context.runId,- stage: this.stages.get(context.runId) ?? "start",- code:- error instanceof RpcError && /^[a-z0-9_.-]{1,80}$/i.test(error.message)- ? error.message- : error instanceof ExecError- ? `exec_${error.code}${error.reason ? `.${error.reason}` : ""}`- : error instanceof Error- ? error.name- : "unknown",+ stage: this.stageOf(context.runId),+ code: prepareFailureCode(error),}),);this.stages.delete(context.runId);@@ -245,15 +265,26 @@ export class GroupMemberWorktrees {throw error;}}- /** A plan step that cannot have its own workspace takes turns; the reason is shown to people. */- takeTurns(context: ToolRunContext, taskId: string, reason: string) {+ /**+ * A plan step that cannot have its own workspace takes turns; the reason is shown to people.+ * With `folder` it also joins that folder's line, and its run waits there (waitTurn).+ */+ takeTurns(context: ToolRunContext, taskId: string, reason: string, folder?: string) {const serialTask = this.service.tasks.serialFallback(taskId);if (serialTask) this.service.taskChanged(serialTask);this.fallbacks.set(context.runId, reason);+ if (folder) this.turns.join(context.runId, taskId, context.groupId, folder, reason);this.service.deps.local.deps.logger.info(JSON.stringify({ module: "group", event: "step_workspace_fallback", taskId, reason }),);}+ /** Waits until the steps ahead of this run in its folder's line have ended. */+ waitTurn(context: ToolRunContext, signal: AbortSignal) {+ return this.turns.wait(context.runId, signal);+ }+ waitingTurn(taskId: string) {+ return this.turns.waiting(taskId);+ }private async prepareWorktree(context: ToolRunContext,group: Group,@@ -362,6 +393,7 @@ export class GroupMemberWorktrees {return state === "preparing" || state === "working" || state === "integrating";}async settled(record: Run) {+ this.turns.release(record.id);const active = this.active.get(record.id);this.active.delete(record.id);if (@@ -518,6 +550,7 @@ export class GroupMemberWorktrees {cancel() {this.stop.abort();clearInterval(this.timer);+ this.turns.dispose();}async dispose() {this.cancel();diff --git a/packages/workspaces/src/brain/groups/group-step-merge.ts b/packages/workspaces/src/brain/groups/group-step-merge.tsindex c930794..00d97db 100644--- a/packages/workspaces/src/brain/groups/group-step-merge.ts+++ b/packages/workspaces/src/brain/groups/group-step-merge.ts@@ -90,7 +90,9 @@ export async function mergeStep(parent: AbortSignal,): Promise<StepMerge> {const member = owner.repo.get(taskId);- if (!member || member.state === "integrated") return { state: "merged" };+ // A step whose setup failed took turns: its work is already in the shared folder.+ if (!member || member.state === "integrated" || !owner.workspace(taskId))+ return { state: "merged" };if (member.state === "removed") return { state: "failed", code: "group_workspace_removed" };if (!owner.idle(member)) return { state: "pending" };const tree = owner.registry.get(member.worktreeId);diff --git a/packages/workspaces/src/brain/groups/group-step-prepare.ts b/packages/workspaces/src/brain/groups/group-step-prepare.tsindex b047aba..1f3cd65 100644--- a/packages/workspaces/src/brain/groups/group-step-prepare.ts+++ b/packages/workspaces/src/brain/groups/group-step-prepare.ts@@ -1,6 +1,7 @@import type { PlanStepWorkspace, ToolRunContext } from "@pibot/brain/kit";-import { ExecError, ManagedFolderError, managedFolderRepository } from "@pibot/execution";+import { ExecError, findGit, ManagedFolderError, managedFolderRepository } from "@pibot/execution";import { type Group, RpcError } from "@pibot/workspaces-contract/full";+import { isManagedCleanupFailure } from "../managed/managed-failure.ts";import type { groupWorkplace } from "../runtime.ts";import type { GroupMemberWorktrees } from "./group-member-worktrees.ts";import { seedStepOutput } from "./group-step-output.ts";@@ -16,6 +17,30 @@ const TURNS = new Set(["group_workspace_integration_dirty","group_workspace_layout_unsupported",]);+/**+ * Answers about this step's permission or its group, not about setting a workspace up: they end+ * the step as before. Any other setup failure takes turns (see setupFailed).+ */+const DECISIONS = new Set([+ "group_workspace_changed",+ "group_workspace_authority_changed",+ "group_workspace_readonly",+ "group_workspace_not_approved",+]);+/** Error code of a member row whose setup failed; the step took turns, so it has no workspace. */+export const SETUP_FAILED = "group_workspace_setup_failed";+const CLEANUP_PENDING = "group_workspace_cleanup_pending";++/** A fixed code for the log: RPC codes and ExecError codes, never messages or paths. */+export function prepareFailureCode(error: unknown) {+ return error instanceof RpcError && /^[a-z0-9_.-]{1,80}$/i.test(error.message)+ ? error.message+ : error instanceof ExecError+ ? `exec_${error.code}${error.reason ? `.${error.reason}` : ""}`+ : error instanceof Error+ ? error.name+ : "unknown";+}/*** Where a writing plan step works (maintainers 2026-11-14): a clean Git repository gets an ordinary@@ -36,7 +61,20 @@ export async function prepareStepWorktree(const remote = !!baseline.boundary.location && baseline.boundary.location.target !== "local";const location = remote ? (baseline.boundary.location?.target ?? null) : null;const primary = baseline.boundary.primaryPath;- const turns = (reason: string) => owner.takeTurns(context, task.id, reason);+ // One line per shared folder: steps taking turns there run one after another.+ const folder = `${location ?? "local"}\0${primary}`;+ const turns = (reason: string) => owner.takeTurns(context, task.id, reason, folder);+ const setupFailed = (error: unknown) => {+ // Only the prepare limit is a setup failure; a stop or shutdown ends the step as before, and+ // so does an approval nobody answered in time (that is the person's decision, not a setup).+ const timedOut = signal.reason instanceof Error && signal.reason.name === "TimeoutError";+ if (+ (signal.aborted && (!timedOut || owner.stageOf(context.runId) === "authority")) ||+ (error instanceof RpcError && DECISIONS.has(error.message))+ )+ throw error;+ return stepSetupFailed(owner, context, task.id, error, primary, turns);+ };owner.stage(context.runId, "host");let host: WorktreeHost;try {@@ -48,6 +86,22 @@ export async function prepareStepWorktree(const retained = owner.repo.get(task.id);if (retained && retained.state !== "integrated")return owner.reattach(context, group, task, retained, host, location, signal);+ // A sibling already takes turns here: its run holds the folder, so a setup here would only+ // wait on it until the prepare limit. The reason is the same for this step.+ const sharing = owner.turns.reason(folder);+ if (sharing) return turns(sharing);+ if (owner.cleanupPending([primary])) return turns(CLEANUP_PENDING);+ // Without Git nothing below can work. Checked first, so a step never waits for a folder lock+ // another step holds only to learn that Git is missing (B2: the 120 s prepare limit).+ if (+ !remote &&+ !(await findGit({+ platform: local.deps.platform,+ env: local.deps.env,+ resourcesDir: local.deps.resourcesDir,+ }))+ )+ return turns("git_unavailable");owner.stage(context.runId, "probe");const repository = (await host.isRepository(primary, signal).catch(() => false))? await host.inspect(primary, signal).catch(() => undefined)@@ -88,7 +142,7 @@ export async function prepareStepWorktree(// the shared folder instead of failing every one of them as an internal error.if (error instanceof ExecError && error.code === "git_unavailable")return turns("git_unavailable");- throw error;+ return setupFailed(error);}place = { ...baseline, cwd: managed };}@@ -97,7 +151,7 @@ export async function prepareStepWorktree(active = await createMemberWorktree(owner, host, context, group, place, signal);} catch (error) {if (error instanceof RpcError && TURNS.has(error.message)) return turns(error.message);- throw error;+ return setupFailed(error);}owner.active.set(context.runId, active);owner.stage(context.runId, "seed");@@ -108,3 +162,42 @@ export async function prepareStepWorktree(signal,);}++/**+ * The safety net for a workspace that could not be set up (a Git or process failure while+ * creating it): the step takes turns in the shared folder instead of ending as an internal error.+ * Only records change here. A half-created tree stays for the existing cleanup: inside Pi Bot's+ * folder repository it goes with the repository when the plan ends, and a tree whose cleanup+ * is uncertain keeps its lock until a restart (that folder then reports cleanup pending).+ */+function stepSetupFailed(+ owner: GroupMemberWorktrees,+ context: ToolRunContext,+ taskId: string,+ error: unknown,+ primary: string,+ turns: (reason: string) => void,+) {+ const code = prepareFailureCode(error);+ owner.service.deps.local.deps.logger.warn(+ JSON.stringify({+ module: "group",+ event: "step_workspace_setup_failed",+ groupId: context.groupId,+ runId: context.runId,+ taskId,+ stage: owner.stageOf(context.runId),+ code,+ }),+ );+ const member = owner.repo.get(taskId);+ // The row the failed create left (interrupted) would make the step look like it has its own+ // workspace to check and merge. Closed with this code, the task has none (workspace()).+ if (member && member.state !== "integrated" && member.state !== "removed")+ owner.state(member, "removed", SETUP_FAILED);+ turns(+ isManagedCleanupFailure(error) || code === CLEANUP_PENDING || owner.cleanupPending([primary])+ ? CLEANUP_PENDING+ : SETUP_FAILED,+ );+}diff --git a/packages/workspaces/src/brain/groups/group-step-turns.ts b/packages/workspaces/src/brain/groups/group-step-turns.tsnew file mode 100644index 0000000..251ea54--- /dev/null+++ b/packages/workspaces/src/brain/groups/group-step-turns.ts@@ -0,0 +1,77 @@+import { abortable } from "@pibot/brain/kit";++interface Hold {+ taskId: string;+ groupId: string | undefined;+ /** Settles when every earlier step taking turns in the same folder has ended. */+ prior: Promise<void>;+ release(): void;+ waiting: boolean;+}++/**+ * Plan steps that take turns in one shared folder run one after another. Flipping the task to+ * serial alone did not do it: both sibling runs had already started, and the folder write lock+ * only stopped the second at its first write (10 min wait), after it had read the folder while+ * the first was changing it. The turn is taken when prepare decides to take turns and is given+ * back when that run settles, so the order is the order the steps prepared in.+ */+export class StepTurns {+ private readonly folders = new Map<string, { tail: Promise<void>; reason: string }>();+ private readonly holds = new Map<string, Hold>();+ constructor(private readonly changed: (groupId: string) => void) {}++ /** Joins the folder's line; a run already in a line keeps its place. */+ join(runId: string, taskId: string, groupId: string | undefined, folder: string, reason: string) {+ if (this.holds.has(runId)) return;+ const prior = this.folders.get(folder)?.tail ?? Promise.resolve();+ let release = () => {};+ const mine = new Promise<void>((resolve) => {+ release = resolve;+ });+ const tail = Promise.all([prior, mine]).then(() => {});+ this.folders.set(folder, { tail, reason });+ this.holds.set(runId, { taskId, groupId, prior, release, waiting: false });+ void tail.then(() => {+ if (this.folders.get(folder)?.tail === tail) this.folders.delete(folder);+ });+ }++ /** Why the folder's current line takes turns, while one exists. */+ reason(folder: string) {+ return this.folders.get(folder)?.reason;+ }++ async wait(runId: string, signal: AbortSignal) {+ const hold = this.holds.get(runId);+ if (!hold) return;+ hold.waiting = true;+ if (hold.groupId) this.changed(hold.groupId);+ try {+ await abortable(hold.prior, signal);+ } catch (error) {+ // A stopped waiter never wrote anything; the steps behind it need not wait for its settle.+ this.release(runId);+ throw error;+ } finally {+ hold.waiting = false;+ if (hold.groupId) this.changed(hold.groupId);+ }+ }++ waiting(taskId: string) {+ for (const hold of this.holds.values()) if (hold.taskId === taskId && hold.waiting) return true;+ return false;+ }++ release(runId: string) {+ const hold = this.holds.get(runId);+ if (!hold) return;+ this.holds.delete(runId);+ hold.release();+ }++ dispose() {+ for (const runId of [...this.holds.keys()]) this.release(runId);+ }+}