Skip to content

🤖 feat: structural workspace mutations refuse while another backend uses the workspace - #4866

Merged
ThomasK33 merged 3 commits into
mainfrom
fix/4476-gate-structural-mutators
Sep 27, 2026
Merged

ThomasK33 merged 3 commits into
mainfrom
fix/4476-gate-structural-mutators

Conversation

@ThomasK33

@ThomasK33 ThomasK33 commented Sep 27, 2026 •

Copy link
Copy Markdown
Member

Summary

Rename, remove, an archive that deletes the checkout, unarchive with a snapshot restore, and managed-worktree deletion now refuse right away while another backend on the same Xum root has a turn, an open terminal or a background process in the workspace or in a sub-agent that shares its checkout. They never wait. Rename also refuses this backend's own running turn or background process. This is the last step of the use-lease plan.

Closes #4476
Closes #4478

Background

The desktop app and xum server can share one Xum root, and the owner decided that both may use one workspace at the same time. Each backend's rename/remove guards are in-memory, so one backend could move or delete a checkout under the other's live activity. The earlier steps built the pieces:

This PR makes the structural mutators take the gate.

Implementation

  • WorkspaceUseLeases.acquireMutationGate(ids, options) returns a release function, and withMutationGate now wraps it. Rename and archive already release their other locks in an existing finally, so they need a release function rather than a callback. A partial acquisition releases what it took. Release is idempotent and releases every gate even if one fails.
  • WorkspaceService.acquireStructuralMutationGate(id, own) gates the workspace plus every taskIsolation: "none" row on the same checkout path. It maps WorkspaceBusyError to Err. Other backends' leases, and background processes this backend does not track, always refuse. ignoreOwnKinds is per workspace: a mutator ignores its own activity only in the workspace it mutates, so its own activity in a shared sub-agent refuses too. How each mutator treats its own activity in the mutated workspace:
Mutator Own kinds ignored Own background processes Where
rename terminal (shells follow the moved dir) refuse (#4478 item 1) after validation, before the MCP-overrides lock and the move
remove turn, terminal (removal stops them) allowed (removal cleans them up) after the descendant check, before claimPendingRemoval
archive, only when archiveDeletesManagedWorktree turn, terminal (archive stops them) allowed (unchanged) before the untracked-files confirmation (metadata is re-read under the gate), held through the after-archive hook
unarchive with a snapshot row none refuse (nothing stops them) before unarchivedAt is written
deleteWorktree none refuse (nothing stops them) before the archived-state validation
  • archiveDeletesManagedWorktree moves the worktree archive hook's deletion rule into one predicate. Archive gates exactly when the hook would delete, so keep-mode archive is unaffected.
  • Docs: docs/config/server-access.mdx gains the guarantee and its limits. The one-app-per-workspace warning stays, because background process IDs are reserved only in-process (see 🤖 feat: workspace use leases for MCP servers, init hooks and executeBash #4857). The processLiveness.ts contract comment is updated to match.

Validation

  • workspaceService.mutationGate.test.ts uses two real service stacks on one root. Without the gate, 7 of its 8 tests fail; the 8th guards the "remove still ends its own turn and terminals" behavior. One test spawns a real child process that holds a terminal lease: remove names its pid, and after SIGKILL the retry succeeds with no lockout.
  • Dogfood: xum server (B) and the desktop app (A) on one root, built at b0e2650aa6. The head differs only in formatting, a test, and releasing every gate on error. A's calls went through the renderer's oRPC client because rename has no UI.
    1. Rename was refused while B had a terminal open, then succeeded after B closed it (recording below).
    2. Remove was refused while B ran a background sleep 300, even with force, then succeeded after B stopped it.
    3. Archive was refused under Delete and Snapshot while B had a terminal open. Keep succeeded, and unarchive worked.
    4. After kill -9 of B, the stale lease file stayed on disk, and A's rename and remove succeeded at once.
step1-rename-refusal-release-success.mp4

Rename refused while the server has a terminal open
Remove refused while the server runs a background process, even with force
Delete-mode archive refused while the server has a terminal open
Rename succeeds right after the server is SIGKILLed

Perf check: two backends on one 25 MB workspace (measurement, not a gate)

Both backends ran in mock mode, the same method as #4861. The history file is 25 MB with 10,966 rows. Values are medians over 5 opens, in ms.

Condition Chat open total History-lock wait partial.json writes/s Max gap
Server only 1433 0.5 (max 1.7) 8.0 141
Desktop also subscribed 1403 0.3 (max 1.4) 8.0 181
Both reopen at once 1416 / 1242 0.3 / 0.2 (max 2.3) – –
Desktop reopens 3× mid-stream 1142 0.0 8.1 161
  • The median gap between partial writes was 121 ms in every run.
  • Each turn creates and deletes one turn.lock. The mutation gate never appears during turns: it is held about 5 ms for a refusal, 72 ms for a rename and 208 ms for a remove.
  • Not from this branch: the cross-process history lock is taken 101–121 times per 20 s stream.

Risks

  • Single-backend behavior changes only for rename: a rename during the preparation phase of this backend's own turn, while its own background process runs, or while a shared sub-agent is active now refuses with a retry message. It used to run.
  • The following are unchanged: remove and archive stopping their own stream and terminals, keep-mode archive, and task clean-up. The broad service suites pass (workspaceService, taskService, projectService, leases, hooks).

Follow-ups


Generated with xum • Model: anthropic:claude-opus-5-5 • Thinking: high • Cost: $23.07

@mintlify

mintlify Bot commented Sep 27, 2026 •

Copy link
Copy Markdown

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
Mux 🟢 Ready View Preview Sep 27, 2026, 12:20 PM

💡 Tip: Enable Automations to automatically generate PRs for you.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 27, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-27T12:39:54.684343Z 24b498b New commits
🔒 Security Review ✅ Completed 2026-09-27T12:36:57.304274Z 24b498b New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f6a5c88f04

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/node/services/workspaceService.ts Resolved
Comment thread src/node/services/workspaceService.ts Resolved
Comment thread docs/config/server-access.mdx Resolved
Comment thread src/node/services/workspaceService.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bd2e080c83

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/node/services/workspaceService.ts Resolved
Comment thread src/node/services/workspaceService.ts Resolved
…ive; archive rereads metadata under the gate

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 24b498bcc3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/node/services/workspaceService.ts Resolved
Comment thread src/node/services/workspaceService.ts Resolved
@ThomasK33
ThomasK33 added this pull request to the merge queue Sep 27, 2026
Merged via the queue into main with commit 483c1d1 Sep 27, 2026
59 of 61 checks passed
@ThomasK33
ThomasK33 deleted the fix/4476-gate-structural-mutators branch September 27, 2026 12:54
yermakoffivan pushed a commit to yermakoffivan/mux that referenced this pull request Sep 27, 2026
## Summary

"Remove Current Workspace…" (and the palette's remove-workspace picker)
now shows the backend's refusal in the existing anchorless error popover
instead of failing silently.

## Background

The palette handler returned the `removeWorkspace` result without
showing it, and `WorkspaceContext.removeWorkspace` only logs failures.
The cross-backend structural-mutation gate (coder#4866) adds refusals such as
"in use by another Xum process: a terminal in pid N" that land on this
path.

## Implementation

`App.tsx` wraps the palette's `onRemoveWorkspace` with
`usePopoverError()` and renders a `PopoverError` ("Failed to remove
workspace"), the same component the sidebar and workspace menu use for
remove/archive errors. With no anchor it sits at the top right (desktop)
or left-aligned under the header (390px); it has a Dismiss button and
the hook's existing 5 s auto-dismiss. Rename has no palette UI and is
unchanged.

## Validation

New story `App/WorkspaceSwitcher/RemoveCurrentWorkspaceRefused`: the
mocked backend refuses, and the play runs the command from the palette,
confirms, and asserts the alert text. It failed on main (only the
renderer log line) and passes now. The story is excluded from Pixel
snapshots: the popover auto-dismisses, and the snapshot budget is full.

Desktop (1440×900):

![Refusal popover at desktop
width](https://github.com/user-attachments/assets/5d99eaf7-4450-465d-8624-7690860712d7)

Phone (390×844):

![Refusal popover at
390px](https://github.com/user-attachments/assets/e30a33d6-33c8-4938-888e-55f307353ca0)

Fixes coder#4865

---

_Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking:
`high`_

<!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high
costs= -->
yermakoffivan pushed a commit to yermakoffivan/mux that referenced this pull request Sep 27, 2026
…r#4886)

## Summary

The docs and the `processLiveness.ts` CONCURRENT BACKENDS comment no
longer tell users to pick one app per workspace. Using one workspace
from the desktop app and `xum server` at the same time is supported, and
the known gaps are listed.

## Background

The owner decided that two backends on one data directory may use one
workspace at the same time. The structural-mutation gate (coder#4844, coder#4852,
coder#4861, coder#4866) makes rename, delete and checkout-removing archives refuse
while the other backend is busy, and coder#4874 gives same-named background
commands separate records. The old warning was kept only until coder#4874
landed.

## Implementation

- `docs/config/server-access.mdx`: adds the background-record guarantee
(for commands running at the same time) to "What stays consistent" and
replaces the Warning with a Note that lists the gaps: MCP servers, init
hooks, one-off commands and non-host background records (coder#4857),
migrated background commands (coder#4878), reuse of a settled record the
other app still tracks (coder#4882), keep-mode unarchive and Coder
stop/delete archives (coder#4871). The sub-agent recovery Note and the
mixed-version line are unchanged.
- `processLiveness.ts`: the same statement and gaps in the CONCURRENT
BACKENDS comment. The attempt-fence guarantees and "not guaranteed" list
are unchanged.
- `builtInSkillContent.generated.ts`: regenerated from the docs.

Refs coder#4857

---

_Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking:
`high`_

<!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high
costs= -->
yermakoffivan pushed a commit to yermakoffivan/mux that referenced this pull request Sep 27, 2026
…ash (coder#4890)

## Summary

Another backend on the same Xum root (the desktop app beside a `xum
server`) now sees three more kinds of activity through workspace use
leases, so its rename, remove, checkout-deleting archive, snapshot
restore and worktree deletion refuse while they run:

- **stdio MCP servers** (`mcp`): held from before the spawn until the
server process exits.
- **init hooks** (`init`): held inside `runBackgroundInit` for the whole
init; released before the returned settlement resolves.
- **one-off commands** (`exec`, the `executeBash` RPC): one lease per
call, until the command settles.

Refs coder#4857 (the background-process gaps from its comments moved to
coder#4889).

## Background

coder#4476 added `WorkspaceUseLeases` and the structural mutation gate; coder#4861
leased turns and terminals and coder#4866 made the mutators refuse. The kinds
`mcp`, `init` and `exec` were declared but never held, so another
backend could still move or delete the checkout under them.

## Implementation

Same rules as turns and terminals: a lease is taken before the activity
starts; `WorkspaceMutationInProgressError` makes the start fail (MCP:
the server counts as failed; init: it fails through the init logger like
any init failure; exec: `Err`), and it is never swallowed into a start.

- **MCP** (`startStdioInstance`): released when `execStream.exitCode`
resolves, like a terminal's PTY exit. A rejected exit observation proves
nothing, so it kills the process and keeps the lease until this backend
exits (fail closed); `MCPStdioTransport` now handles that rejection
instead of leaving it unhandled. `close()` and the idle sweep only ask
the process to exit, so tying the lease to the instance maps would miss
servers that outlive them (timeouts, retired generations). Remote
(HTTP/SSE) servers do not run in the checkout and take no lease.
- **init** (`withInitUseLease`, used by `runBackgroundInit` and by
multi-project creation's per-project init loop): `runBackgroundInit`
takes a new required `useLeases` parameter, so every caller (create,
deferred checkout, fork, the two task-service inits) passes this
backend's leases.
- **exec** (`WorkspaceService.executeBash`): taken right after the
in-process admission guards and before the metadata read, released with
`await using`.

This backend's own activity, per mutator ("does this mutator stop it?"):

| Mutator | own `mcp` | own `init` | own `exec` |
| --- | --- | --- | --- |
| remove | ignored (stops servers) | ignored (aborts and awaits it) |
ignored (today's handling; `removingWorkspaces` refuses new ones) |
| checkout-deleting archive | ignored (stops servers) | refuses (already
aborted and awaited before the gate) | ignored (today's handling;
model-facing archives refuse it themselves) |
| rename | ignored (processes follow the moved directory, like own
terminals) | refuses (nothing stops it) | ignored (today's handling) |
| unarchive restore, worktree deletion, creation rollback | refuse
(unchanged empty sets) | refuse | refuse |

Other backends' leases always refuse. The docs Note in
`server-access.mdx` now lists only the remaining background-command gap
(coder#4889).

## Review decisions

- Not changed: keeping an `exec` lease after an unconfirmed remote exit.
The lease is scoped to the call, the same contract as the turn lease;
changing it needs a bash-tool exit-contract change for every runtime.
- Not changed: taking the MCP lease before callers resolve the workspace
path. A rename in that sub-second gap makes the spawn target a path that
no longer exists (a failed server); moving the hold into every caller is
new mechanism.

## Deferred

The two comment gaps on coder#4857 (background records of SSH/Docker/dev
container workspaces invisible to the gate; no cross-backend name claim
for multi-project and remote runtimes) need `BackgroundProcessManager`
changes, which another workspace is changing now for coder#4878/coder#4882. Filed
as coder#4889.

## Validation

Red → green: the new tests fail on `origin/main` (10 failures) and pass
with this change.

<details>
<summary>Pre-fix failures (tests run against main's production
code)</summary>

```
(fail) MCPServerManager workspace use leases > a running server refuses the other backend's mutation until its process exits [21.00ms]
(fail) MCPServerManager workspace use leases > a server whose process exits on its own releases its lease [1.00ms]
(fail) MCPServerManager workspace use leases > no server starts while the other backend mutates the workspace [3.00ms]
(fail) structural workspace mutations across two backends on one root > a one-off command of the other backend refuses rename until it fails [19.00ms]
(fail) structural workspace mutations across two backends on one root > a one-off command releases its lease when it succeeds [16.00ms]
(fail) structural workspace mutations across two backends on one root > no one-off command runs while the other backend mutates the workspace [15.00ms]
(fail) structural workspace mutations across two backends on one root > an init hook of the other backend refuses rename until it ends [16.00ms]
(fail) structural workspace mutations across two backends on one root > an init hook releases its lease when it fails or is aborted [8.00ms]
(fail) structural workspace mutations across two backends on one root > no init hook runs while the other backend mutates the workspace [5.00ms]
(fail) structural workspace mutations across two backends on one root > own MCP servers, init hook and one-off commands follow what each mutator ends [16.00ms]
 11 pass
 10 fail
```

</details>

- `mcpServerManager.useLeases.test.ts`: a running server makes the other
backend's gate refuse ("mcp"); release on stop, on process exit, on
failed handshake and on a startup abandoned at its deadline; no spawn
while the other backend holds the gate.
- `workspaceService.mutationGate.test.ts`: the other backend's in-flight
`executeBash` and init hook make rename refuse and release on success,
failure and abort; neither runs while the gate is held; own-kind policy
for rename and remove.
- Targeted suites (`workspaceService*`, `taskService*`,
`mcpServerManager*`, `terminalService*`, `workspaceUseLeases`,
`serviceContainer`, `runtimeFactory*`) and `make static-check`.

## Risks

Moderate, in the checks that make rename/remove/archive refuse. The new
refusals are for other backends' activity (intended) and own init hooks
during rename (nothing stopped them before). An `executeBash` issued
while this backend's own mutation holds the gate now fails fast instead
of racing it. A hung SSH exec whose exit never settles keeps its MCP
lease (fail closed), like a terminal.

---

_Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking:
`high` • Cost: `$6.62`_

<!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high
costs=6.62 -->
yermakoffivan pushed a commit to yermakoffivan/mux that referenced this pull request Sep 28, 2026
… backends (coder#4904)

## Summary

Closes the two cross-backend gaps left by coder#4866: a keep-mode
(non-snapshot) unarchive can no longer mark a workspace active while the
other backend deletes its worktree, and an archive that stops or deletes
a dedicated Coder workspace now takes the structural mutation gate like
a checkout-deleting archive.

Fixes coder#4871

## Background

Two backends (the desktop app and `xum server`) may use one workspace on
one Xum root at the same time. coder#4866 added the cross-process mutation
gate for rename, remove, checkout-deleting archive, snapshot-restoring
unarchive and worktree deletion. It left out:

1. A keep-mode unarchive: `deleteWorktree` in one backend passes its
archived check under the gate, then an unarchive in the other backend
commits `unarchivedAt`, leaving a visible workspace without a checkout.
2. Coder archive policies Stop/Delete for dedicated (Xum-created) Coder
workspaces: `archiveDeletesManagedWorktree` is false for SSH runtimes,
so `runBeforeArchive` could stop or delete the remote workspace under
the other backend's turn or terminal.

## Implementation

- **Unarchive.** The issue suggested probing the gate before the
`unarchivedAt` edit. A bare probe still races: the mutator can take the
gate after the probe and read "archived" before the edit lands. Instead,
a keep-mode unarchive holds a short-lived use lease (new kind
`unarchive`) across the commit only. The existing Dekker ordering in
`workspaceUseLeases.ts` then guarantees that either the unarchive sees
the live gate and refuses, or the mutator's lease scan sees the
unarchive and refuses. An unarchive of a workspace that is already
active returns before taking any lease or gate. Holding a lease never
checks other leases, so ordinary activity of the other backend (a turn,
a terminal) does not make unarchive fail. The lease is held from before
the commit until the unarchive finishes, including lifecycle startup
(for example starting a dedicated Coder workspace), so the other backend
cannot stop-and-archive the workspace under that startup. After the
lease is taken, the snapshot state is read again: a snapshot archive
that the other backend finished before the lease is visible then (and no
new one can start while the lease is held), so the unarchive drops the
lease and takes the gate to restore it. The snapshot-restoring path
otherwise keeps its gate unchanged.
- **Coder archive.** The archive gate condition is extended to
`stopsDedicatedCoderWorkspace` (Stop or Delete), with the same
own-activity policy as the checkout-deleting archive: this backend's own
turn, terminals, editors, MCP servers and one-off commands are still
stopped by the archive itself.
- Docs: removed the coder#4871 entry from the known-gaps Note in
`docs/config/server-access.mdx` and described the new refusals.

Decision (conservative): a hold failure other than a live gate (for
example a lock-file I/O error) also refuses the unarchive, matching the
editor-open path.

## Validation

New tests in `workspaceService.mutationGate.test.ts`, written from the
other backend's perspective, fail on `origin/main` (`4bd92ab38b`):

```
(fail) structural workspace mutations across two backends on one root > a keep-mode unarchive refuses while the other backend deletes the worktree, but not on its turn
(fail) structural workspace mutations across two backends on one root > worktree deletion refuses while the other backend commits a keep-mode unarchive
(fail) structural workspace mutations across two backends on one root > an archive that stops or deletes a dedicated Coder workspace refuses while the other backend uses it
 18 pass
 3 fail
```

Two more tests were added for review round 1 (snapshot appearing before
the lease; the other backend stopping and archiving a Coder workspace
while this backend starts it on unarchive). Both failed on the first PR
head `fe3cd7f960`:

```
(fail) structural workspace mutations across two backends on one root > a keep-mode unarchive restores a snapshot the other backend captured before it only under the gate
(fail) structural workspace mutations across two backends on one root > the other backend cannot stop and archive a Coder workspace while this backend starts it on unarchive
```

All of these failed with `expect(received).toBe(expected) Expected:
false Received: true` (the operation succeeded). With the fix: 24 pass
(round 2 added a test that a repeated unarchive of an already active
workspace is a no-op that takes no lease, so it neither refuses nor
blocks the other backend's mutation). Every unit test file that mentions
`unarchive` or `coderWorkspaceArchiveBehavior` (31 files) passes, plus
`tests/ipc/tasks/unrelatedMissingCheckout.test.ts` and
`tests/ui/workspaces/lifecycle.test.ts`.

## Risks

Low. Unarchive gains one lease-file publish and gate probe per call.
While another backend renames, removes or archives the workspace, or
deletes its worktree, unarchive now refuses with the gate holder named
(try again). A Coder archive with Stop/Delete now refuses while the
other backend uses the workspace, as checkout-deleting archives already
do.

---

_Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking:
`high`_

<!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high
costs= -->
yermakoffivan pushed a commit to yermakoffivan/mux that referenced this pull request Sep 28, 2026
…ackends (coder#4908)

## Summary

This PR finishes the cross-process removal work tracked in coder#4782: the
other backend can no longer create a child task under a workspace that
is being removed (or was removed), a removal now checks for descendants
after it claims its marker, and a removal marker with an empty identity
field is dropped at load instead of blocking the workspace. Item 1 (a
send into a live attempt) is already closed by the use leases and
mutation gate that landed in coder#4861 and coder#4866; see below.

Fixes coder#4782

## Background

coder#4776 added the durable `pendingRemoval` marker. The issue lists what it
left open:

1. **A send into a live attempt is admitted by a config read.** Backend
B could pass the `pendingRemoval` read and start a turn while backend A
commits the marker and deletes the checkout.
2. **Child creation does not check the parent's marker.**
`removeUnlocked` checked for descendants before its claim, and no
task-creation config write looked at the parent's marker, so B could
commit `TaskService.create` under a parent that A was removing and leave
an orphaned child row (and possibly an unmanaged checkout).
3. (comment) `PendingRemovalSchema` accepted empty identity strings.
`parseProcessIdentity()` turns `""` into `null`, and `judgeHolder()` on
Linux then treats the holder as an unknown PID domain that never dies,
so such a marker blocked admission and removal until someone edited
config.json.
4. (comment) Reactivation's marker check before it unarchives is a read,
so a removal could race the unarchive's checkout restore.

## Implementation

- **Item 2.** A shared `assertParentAdmitsChild` runs inside every
task-creation config write (`commitReservations` for `createMany`, and
both the queued and the direct write in `create`). It refuses while the
parent row carries `pendingRemoval`. `create` also refuses when the
parent row it found by id during preparation is gone at write time (the
direct path materializes a checkout in between, so a whole removal can
fit in that gap). `createMany` does the same with the parent row it
found by id when it revalidated the reservation (its checkpoint callback
runs before the commit, so a whole removal can fit there too). A parent
that was not found by id (an upgraded, id-less row that resolves only
through its session metadata) is not required. `removeUnlocked` now
checks for descendants after `claimPendingRemoval` instead of before the
gate. Config writes are serialized, so either the child's write sees the
marker and refuses, or the removal's post-claim read sees the child and
refuses (its `finally` releases the marker, as for any other refusal
after the claim). A refused direct create rolls its checkout back
through the existing launch-failure path.
- **Item 3.** The identity fields of `PendingRemovalSchema` are
`z.string().min(1).nullable()`, so `normalizePersistedWorkspace` drops
such a marker as malformed.
- **Item 1: no code change.** `removeUnlocked` takes the structural
mutation gate before it claims the marker and holds it until removal
settles (coder#4866), and every turn holds a `turn` use lease from
preparation and confirms it before the provider starts (coder#4861). By the
Dekker ordering in `workspaceUseLeases.ts`, either B's turn sees A's
gate and fails as a settled preparation failure, or A's lease scan sees
B's turn and the removal refuses before any effect. This also covers a
turn B started before A's claim. Covered by
`agentSession.useLease.test.ts` ("B's send while A's mutation runs fails
as a settled preparation failure", "a turn in B holds its lease from
preparation until it settles") and
`workspaceService.mutationGate.test.ts` (other-backend leases refuse
rename and remove before any effect).
- **Item 4: no code change.** Since coder#4904, a keep-mode unarchive holds
an `unarchive` use lease from before its commit to the end, and a
snapshot-restoring unarchive takes the mutation gate. Either one refuses
while a removal holds the gate, and a removal refuses while the
unarchive holds its lease.

## Out of scope

The removal marker and this fence find the row by id. An upgraded
workspace whose config row is still id-less gets no marker (as before
this PR), so creation under it is not fenced; tracked in coder#4914.

## Validation

New tests in `workspaceService.pendingRemoval.test.ts` (two backends on
one root) fail on `origin/main` (`25faf8f1c4`):

```
(fail) workspace removal across two backends on one root > a malformed removal marker (an empty identity field) is dropped instead of blocking the task
(fail) workspace removal across two backends on one root > a removal refuses when the other backend created a child just before it closed admission
(fail) workspace removal across two backends on one root > the other backend cannot create a child task under a workspace being removed
```

Review round 1 added a test that a batch creation under a parent
resolved only through metadata (legacy, no config row by id) still
commits; it failed on the first PR head `b6d58bcb49` (`parent workspace
legacy-parent was removed`).

Review round 2 added a test that a batch creation refuses when the other
backend finished removing the parent during the reservation checkpoint;
it failed on `9ed0343a94` (`Received: "created"`).

Before the fix, B's `create` under the parent being removed succeeded,
A's removal deleted a parent whose child had been committed just before
its claim, and the empty-identity marker refused the reawaken. With the
fix all pass, and so do every `taskService*`/`workspaceService*` unit
test file (1851 tests) and the 21 test files that mention
`pendingRemoval`, `createMany` or descendant checks (935 tests).

## Risks

Low to medium. `create` and `createMany` now refuse when the parent row
they found by id is missing at write time; before, such a child was
written as an orphan. A removal of a workspace with descendants now
takes the gate and briefly claims its marker before it refuses (the
marker is released in the same call), so another backend's task
admission can see a short refusal during that window.

---

_Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking:
`high`_

<!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high -->
yermakoffivan pushed a commit to yermakoffivan/mux that referenced this pull request Sep 28, 2026
…e is busy (coder#4921)

## Summary

Deleting a parent together with its sub-agents (the "Delete Workspace
and Descendants" confirmation) now takes the structural mutation gate of
the parent and every descendant in one sorted acquisition before it
removes anything. If either backend is using any workspace of the tree,
the whole delete refuses, naming the busy workspace and the activity,
and nothing is removed. Otherwise the gate stays held while descendants
are removed deepest-first through the existing `pendingRemoval` marker
path, then the parent.

Refs coder#4477 (PR 1 of 2: delete cascade; the archive cascade follows).

## Background

The acknowledged-descendant delete (coder#4171) removed descendants one by
one, and each removal took its own gate (coder#4866). A descendant busy in
another backend (the desktop app beside a `xum server`) was found only
when the cascade reached it, after the deeper descendants were already
deleted. The maintainer asked for this delete to preflight the whole
tree first.

## Implementation

- `acquireStructuralMutationGate` accepts several target workspaces.
Each target gets the same own-activity policy it would get alone, and
the shared `isolation: "none"` rows of each target are included, as
before. It still calls `WorkspaceUseLeases.acquireMutationGate`, which
sorts the ids, so two mutators over overlapping trees take the gates in
one order.
- `remove()` with `acknowledgedDescendantIds` gates `{parent} ∪
descendants` with the removal policy (now the shared
`REMOVAL_OWN_ACTIVITY_POLICY` constant), then passes the gated ids to
`TaskService.removeAcknowledgedDescendantsWhileTaskTreeLocked`. Each
gated descendant and the parent are removed with `mutationGateHeld`, so
`removeUnlocked` skips its own gate. Everything else in `removeUnlocked`
(marker claim, attempt binding, descendant re-check) is unchanged. The
tree gate is released in `finally`.
- A descendant that another backend adds after the listing is not in the
gated set. It is also outside the acknowledged scope, which already
refuses; the parent's post-claim descendant check stays as the last
line.
- The in-process "active descendant" check is unchanged (it runs after
the gate, before any removal). Lossy-work handling is unchanged: the UI
keeps its confirmation, and this path never refuses on lossy grounds.

Decision (conservative, per brief): the error names the busy workspace
by id, as every gate refusal does. The confirmation dialog already lists
each descendant's title next to its id.

## Validation

Red → green, two real service stacks (Config, WorkspaceService,
TaskService) on one root, real git worktrees, in
`workspaceService.removalCascade.test.ts`:

1. A child busy in backend B (a terminal lease) refuses A's parent
delete, and all three rows, checkouts and markers stay. **Failed before
the fix:**
   ```
   error: expect(received).toBeDefined()
   Received: undefined
(fail) parent removal cascades over its sub-agent tree across two
backends > a descendant in use by the other backend refuses the parent
delete before anything is removed
   ```
   (the grandchild had been removed before the busy child refused).
2. An idle tree is removed completely: no config rows, no checkouts.
This passed before the fix as well; it guards that holding the tree gate
does not block the cascade's own removals.

Also ran `workspaceService.remove`, `taskService.lifecycle`,
`workspaceService.mutationGate` and `workspaceService.pendingRemoval`
tests, and `make static-check`.

### Dogfood

`xum server` and the desktop app (Electron under Xvfb) on one temp
`XUM_ROOT`. The desktop log shows `API server already running at
http://localhost:43477, skipping`. The root was seeded with an archived
parent, a sub-agent child and a grandchild, each a real git worktree.

1. The server opened a terminal in the child (`xum api terminal create
--workspace-id child-4477`).
2. In the desktop app: Archived workspaces → Delete → "Delete Workspace
and Descendants". The dialog shows the refusal naming `child-4477`, the
server's pid and "a terminal". All three checkouts stayed on disk.
3. The server closed the terminal. Retrying in the desktop app deleted
all three workspaces: `config.json` has no rows, `src/repo/` is empty,
and `git worktree list` shows only `main`.

Refusal at desktop width:

![refusal, desktop
width](https://github.com/user-attachments/assets/3bc86c90-1e8e-4a92-9431-44543c36754f)

Refusal at 390 px:

![refusal, 390
px](https://github.com/user-attachments/assets/992769bb-d486-44fc-aaa5-20bcacda7f8e)

Recording of refusal → release → success. It is built from a 0.5 s
screenshot loop and played back at 3 fps. It includes the 390 px
viewport switch.

## Risks

Low to medium. The change only affects the acknowledged-descendant
delete, and single-workspace removal still takes its own gate. Worst
case is a false refusal: for example, another backend's idle stdio MCP
server in a descendant keeps it "in use" for up to 10 minutes, as for
any other structural mutation. While the delete runs, no backend can
start activity in any workspace of the tree, which is the intent.

---

_Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking:
`high` • Cost: `$2.56`_

<!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high
costs=2.56 -->


https://github.com/user-attachments/assets/ab19e639-88a8-417f-82f8-13598dcf57d9
yermakoffivan pushed a commit to yermakoffivan/mux that referenced this pull request Sep 28, 2026
… checkout (coder#4959)

## Summary

A model-driven `task_remove` now refuses while live writers exist in the
sub-agent's checkout, and blocks new ones from being admitted between
its lossy-work check and the forced removal. This handles gap 1
(live-writer TOCTOU) of coder#4761. The other gaps do not fit this pattern
and stay open on the issue.

## Background

PR coder#4744 made model-driven `task_remove` refuse to delete work that
nothing else preserves, using a git check in
`subagentRemovalWorkCheck.ts`. Between that check and the checkout
deletion, the removal awaits a number of steps: the tombstone, the
structural gate, the stream stop, the memory handover, and more. A
background bash process, an open terminal or an external editor could
write during those awaits. The removal then kills them and deletes the
checkout, and the model never sees that work. Same-backend removal
ignores this backend's own use leases (`REMOVAL_OWN_ACTIVITY_POLICY`),
so the coder#4866 gate does not cover this.

## Implementation

This reuses the archive path's admission hold, as the issue suggests. In
`removeInactiveDescendantAgentTaskWhileTaskTreeLocked`, and only for
`lossyWorkPolicy: "refuse"` (the model tool), under the tree and
patch-artifact locks and before the lossy check:

1. **Background processes.** `hasRunningBackgroundBashProcesses(taskId)`
runs first, as in model-driven archive. It refreshes exit statuses, so
an exited process does not block the removal, and it also counts
crash-orphaned processes.
2. **Admission hold.** `acquirePreInterruptionArchiveHold(taskId, {
queuedDelegatedTurnCount: 0, expectedDelegatedTurnCorrelations: [],
operation: "remove" })` refuses on the same live-activity labels as
model-driven archive: terminals, pending native terminal or editor
opens, in-flight sends, bash exec, staging, MCP discovery, queued
messages, workflows, desktop viewers, and so on. While it is held, no
new send, bash exec, terminal, open or turn is admitted. It is held with
`using` through the lossy check, the tombstone and
`removeWhileTaskTreeLocked`, and released on every exit.
3. **Untrackable apps.** `hasUntrackableExternalAppOpen(taskId)` refuses
when an editor or native terminal was opened earlier, because Xum cannot
track whether it still writes.

The new optional `operation: "remove"` option only changes the hold's
refusal text. Archive callers are unchanged.

All three checks apply only when removal deletes the checkout. They are
skipped for isolation `none` children and project-dir local runtimes,
the same cases the lossy-work check skips. There, removal loses no
files, and the sticky "an app was once opened" marker would otherwise
block removal forever.

The contract for model-driven lossy removal is kept. Refusals are
`status: "error"` with the reason, and lossy files still come with
`paths`. No acknowledgment field is added. The UI confirmation is
unchanged. Automatic cleanup and the user-confirmed cascade
(`removeAcknowledgedDescendantsWhileTaskTreeLocked`) never take the hold
and never refuse, and the test checks this.

## Validation

`taskService.lifecycle.test.ts` › "model-driven task removal refuses
live writers and holds admission through the check and removal" fails on
`main` at its first refusal:

```
AssertionError: live writers must refuse
  actual: false, expected: true
```

The test covers each refusal: a running background process (refused
before the hold is taken), live activity reported by the hold, and an
untrackable editor (the hold is released). It checks that a clean
removal runs in the order `hold → remove → release`, and that the user
cascade never calls the hold.

## Deferred

- coder#4965: `refinements.apply` is not gated by the admission hold. An
apply that starts after the lossy check can still write `.xum/skills`
files into the checkout. This predates this PR, and model-driven archive
has the same exposure.

## Remaining gaps (not in this PR)

Gaps 2–6 of coder#4761 do not fit the live-writer pattern and remain open
there: commits on other local branches, an unusable mbox, the `.git`
existence probe, scratch sub-agents, and the per-sub-agent removal UI.

Refs coder#4761

---

_Generated with `xum` • Model: `anthropic:claude-opus-5-5` • Thinking:
`high` • Cost: `$10.61`_

<!-- mux-attribution: model=anthropic:claude-opus-5-5 thinking=high
costs=10.61 -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

1 participant