Skip to content

update_environment_directory commits the switch but strands the Pi tool call until manual interruption #3187

Closed

Description

@AmbitiousRealism2025

Summary

Calling the built-in update_environment_directory tool from an active Pi turn updates the thread's environment in the database almost immediately, but the tool result never reaches the provider. The turn remains active with no visible error until the user manually stops it; after interruption, subsequent turns can report the new bb environment while still executing tools from the old working directory.

Versions and environment

  • bb 0.41.0, PiBB desktop app
  • Pi provider, @earendil-works/pi-coding-agent 0.85.1 RPC mode
  • Arch Linux, kernel 7.1.6-1-1-ARCH, aarch64
  • Node 24.20.0
  • Local host, default PiBB data directory ~/.pibb
  • Source worktree created with Git before invoking the tool
  • Thread: thr_bkcz3fwu49
  • Project: proj_ft87efzim2
  • Source environment: env_r8juwgzwj6
  • Target environment: env_rrus573mi9

Steps to reproduce

  1. In an active Pi-backed thread, create a second checkout or worktree outside the current directory. In this reproduction it was:

    /home/ambitiousrealism/coding-projects/PiBB-issue-16
    
  2. Call the built-in tool from the agent turn:

    {
      "path": "/home/ambitiousrealism/coding-projects/PiBB-issue-16"
    }
  3. Wait. The tool remains pending and the thread stays active with no result.

  4. Manually stop/interupt the turn.

  5. Send another message and inspect both bb status --json and pwd.

The initial call reproduced once and remained pending for 4,233 seconds until interruption. Retrying the same tool call reproduced the hang for another 867 seconds until interruption.

Expected vs actual

Expected:
The tool returns a success result promptly, the current turn settles, and the next turn starts in /home/ambitiousrealism/coding-projects/PiBB-issue-16.

Actual tool result after manual interruption:
Tool call aborted

Actual state in a later turn:
bb status --json reports environment env_rrus573mi9 with path /home/ambitiousrealism/coding-projects/PiBB-issue-16.

pwd reports:
/home/ambitiousrealism/coding-projects/PiBB

The UI gave no timeout or failure while the tool was pending. The user had to notice that processing was stuck and manually interrupt it.

Evidence

The persisted event sequence shows that the mutation completed about 98 ms after the tool item started, while the turn remained active for another 4,233 seconds:

sequence 505  item/started               2026-09-06T19:56:58.935Z
sequence 506  system/operation           2026-09-06T19:56:59.033Z
              environment_directory_update completed
              Updated environment directory to /home/ambitiousrealism/coding-projects/PiBB-issue-16
sequence 507  system/thread/interrupted  2026-09-06T21:07:32.270Z
sequence 508  item/completed              2026-09-06T21:07:32.277Z
sequence 509  turn/completed interrupted  2026-09-06T21:07:32.277Z

The retry started at 21:07:48 UTC and emitted no successful operation or tool result before its manual interruption at 21:22:15 UTC.

Current main at accd5595926b080a1e17d1ea9b2fa2d7d0505ac6 updates the thread environment inside the tool handler before returning the success response:

  • Environment attachment and updateThread:
    function attachReadyEnvironment(
    deps: Pick<AppDeps, "db" | "hub">,
    args: {
    currentEnvironment: Environment;
    createdEnvironment: boolean;
    targetEnvironment: ReadyEnvironment;
    thread: Thread;
    turnId: string;
    },
    ): AttachEnvironmentResult {
    const result = deps.db.transaction(
    (tx): AttachEnvironmentResult => {
    const latestThread = getThread(tx, args.thread.id);
    if (!latestThread || latestThread.deletedAt !== null) {
    return {
    kind: "thread_unavailable",
    message: "Thread no longer exists.",
    };
    }
    const writableFailure = threadWritableFailure(latestThread);
    if (writableFailure) {
    return { kind: "thread_unavailable", message: writableFailure };
    }
    if (latestThread.environmentId === args.targetEnvironment.id) {
    return { kind: "attached", changed: false };
    }
    if (latestThread.environmentId !== args.currentEnvironment.id) {
    return { kind: "environment_changed" };
    }
    updateThread(tx, deps.hub, latestThread.id, {
    environmentId: args.targetEnvironment.id,
    });
    appendThreadEventInTransaction(tx, {
    threadId: latestThread.id,
    environmentId: args.targetEnvironment.id,
    type: "system/operation",
    scope: turnScope(args.turnId),
    data: {
    operation: "environment_directory_update",
    operationId: createEventId(),
    status: "completed",
    message: `Updated environment directory to ${args.targetEnvironment.path}`,
    metadata: {
    createdEnvironment: args.createdEnvironment,
    previousEnvironmentId: args.currentEnvironment.id,
    previousPath: args.currentEnvironment.path,
    nextEnvironmentId: args.targetEnvironment.id,
    nextPath: args.targetEnvironment.path,
    workspaceProvisionType:
    args.targetEnvironment.workspaceProvisionType,
    },
    },
    });
    return { kind: "attached", changed: true };
  • Success response is constructed only after attachment:
    const attachResult = attachReadyEnvironment(deps, {
    currentEnvironment: args.currentEnvironment,
    createdEnvironment,
    targetEnvironment,
    thread: args.thread,
    turnId: args.turnId,
    });
    switch (attachResult.kind) {
    case "attached":
    return toolCallSuccess(successMessage(targetEnvironment.path));
    case "environment_changed":
    return toolCallFailure(
  • Existing internal coverage checks the HTTP response and persisted environment but does not exercise delivery through a live provider turn:
    const responsePromise = postToolCall({
    harness,
    sessionId: session.id,
    threadId: thread.id,
    turnId: "turn-new-environment",
    tool: "update_environment_directory",
    arguments: { path: "/tmp/new-unmanaged-worktree" },
    });
    const provisionCommand = await waitForQueuedCommand(
    harness,
    ({ command }) =>
    command.type === "environment.provision" &&
    command.workspaceProvisionType === "unmanaged" &&
    command.path === "/tmp/new-unmanaged-worktree",
    );
    if (provisionCommand.command.type !== "environment.provision") {
    throw new Error("Expected environment.provision command");
    }
    expect(provisionCommand.command.initiator).toBeNull();
    await reportQueuedCommandSuccess(harness, provisionCommand, {
    path: "/tmp/new-unmanaged-worktree",
    isGitRepo: true,
    isWorktree: true,
    branchName: "feature/new-worktree",
    defaultBranch: "main",
    transcript: [],
    });
    const response = await responsePromise;
    expect(response.status).toBe(200);
    await expect(readJson(response)).resolves.toMatchObject({
    success: true,
    contentItems: [
    {
    type: "inputText",
    text: expect.stringContaining(
    "Environment directory updated to /tmp/new-unmanaged-worktree",
    ),
    },
    ],
    });
    const targetEnvironment = listEnvironments(harness.db, project.id).find(
    (environment) => environment.path === "/tmp/new-unmanaged-worktree",
    );
    expect(targetEnvironment).toMatchObject({
    hostId: host.id,
    projectId: project.id,
    status: "ready",
    workspaceProvisionType: "unmanaged",
    });
    expect(getThread(harness.db, thread.id)?.environmentId).toBe(
    targetEnvironment?.id,
    );

Observed fact: the environment mutation persisted, but the provider-facing tool call did not complete and the running turn required manual interruption.

Suspected cause: changing the thread environment invalidates or replaces the provider runtime that owns the in-flight dynamic tool request before its success response can be delivered. This is not yet confirmed with a source-level test.

What you ruled out

  • The target directory existed and was a valid Git worktree before either call.
  • The environment update itself did not fail: system/operation recorded completed, and bb environment status env_rrus573mi9 --json reports the target worktree as ready.
  • This was not a slow provisioning operation: the target environment was attached about 98 ms after the tool item started.
  • Retrying did not recover the turn; it produced the same pending behavior.
  • Searches of open and closed issues for update_environment_directory, environment-switch aborts, and provider cwd mismatches found no matching bug. Issue Shrink always-on context (~1.2k tokens/thread) to a 20-token line; load bb-dev context cwd-scoped via update_environment_directory #2709 mentions this tool as part of a feature workflow but does not report this failure.
  • The exact live-provider reproduction has not been run from source at current main; current-main source was inspected only.

Suggested priority and effort

High priority, medium effort. A built-in environment mutation reports no completion, can strand an agent indefinitely, and leaves bb's recorded environment inconsistent with the provider's observed working directory. Manual interruption is the only demonstrated workaround.

AGENT GENERATED

Activity

  1. added theissue type on Sep 6, 2026
  2. added
    workspaces
    provider-pi
    partial-repro
    on Sep 6, 2026
  3. bb-slop-cop commented on Sep 6, 2026

    @bb-slop-cop
    Contributor

    🚨 SLOP COP 🚨 · new-issue-autopilot

    Classification: Bug · High priority · Medium effort · workspaces, provider-pi

    Report: https://get-bb.github.io/reports/issues/3187.html

    Verdict: PARTIALLY REPRODUCED · confidence: medium · reproduction label: partial-repro

    Root cause: Pi resume prefers the persisted session-header working directory over the newly attached environment directory. Two clean full-stack runs completed the directory-update tool response normally, but both retained the prior working-directory attribution on the next turn.

    No pull request was opened: the reported response hang did not reproduce, and correcting the verified stale-directory path requires a Pi session-migration policy plus validation against actual command execution, so it is not a simple safe fix.

  4. 0xferrous commented on Sep 12, 2026

    @0xferrous
    Contributor

    the stranded part is fixed by #3095. I believe the tools will still work from same directory as before because that part is not yet fixed.

  5. SawyerHood commented on Sep 14, 2026

    @SawyerHood
    Collaborator

    Consolidating #3634 into this existing Pi environment-switch tracker, preserving its additional failure case. After switching from worktree A to B, Pi can still use A from the stored session header; after normal removal of A, resume fails with “Stored session working directory does not exist” even though B is valid. #3634's independent regression used the real repository-pinned Pi executable in two clean checkouts. Include all three acceptance cases in this work: the switching tool settles correctly, subsequent tools actually run in B while A still exists, and resume continues in B after A is removed. The original pending-tool-call defect may need a separate fix from durable session relocation; consolidation is not a claim that one patch solves both. No data migration or runtime change is performed by this consolidation.

    AGENT GENERATED

  6. brsbl commented on Sep 25, 2026

    @brsbl
    Collaborator

    Another user report hit this. The environment was different this time: the stored session cwd was a personal workspace, not a Git worktree. The failure is still present on main at 9870622.

    Command turn.submit failed
    pi exited (code 1, signal null): Stored session working directory does not exist: <data-dir>/plugins/environment-personal-workspace/host-data/workspaces/thr_<id>
    Session file: ~/.bb/pi-bridge-sessions/pi_<uuid>.jsonl
    Current working directory: <user's project checkout>
    

    What happened: the thread started in a personal workspace and later ran in a project checkout. The personal-workspace plugin deleted the old directory (host.ts#L49). After that, every turn fails. Only a new thread gets the user working again.

    Why the bridge's guard doesn't help:

    • The thread/resume handler rejects a resume only when both the stored cwd and the requested cwd are missing (bridge.ts#L561-L574). If the requested cwd exists, it assumes Pi can continue there.
    • Pi can't. rpc-session.ts still passes --session <file> with the old header (rpc-session.ts#L210-L215).
    • In every non-interactive mode, Pi 0.84.0 main.js exits 1 on a missing session cwd. Only interactive mode offers "continue in current cwd" (SessionManager.open(file, dir, selectedCwd)). RPC mode has no flag to override the cwd, so this combination always fails.
    • usablePersistedSessionCwd (bridge.ts#L792) records the fallback cwd only on BB's side. Pi never sees it.

    Suggested fix direction: before spawning, relocate the session when its header cwd is missing and the requested cwd exists. Either rewrite the header cwd, or copy the session to a new file with the new cwd, as thread/fork already does. That covers acceptance case 3 above. Personal workspaces make this more common than worktree switching, because they are deleted automatically.

    AGENT GENERATED

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    partial-reproprovider-piworkspaces

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions