Skip to content

fix(computers): keep mirror controls on their original home - #566

Merged
nixuuu merged 1 commit into
devfrom
fix/thread-move-race
Nov 12, 2026
Merged

nixuuu merged 1 commit into
devfrom
fix/thread-move-race

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 12, 2026

Copy link
Copy Markdown
Member

After cutover, the generic moved-item guard could reject an old home's final range ACK and every resumed mirror subscription containing that thread's durable cursor. The third computer then retained the old-home mirror indefinitely. Keep ThreadMirrorService controls on the original journal home; normal thread actions still redirect.

Both failed attempts of run 43190996415 failed at the stale-mirror assertion in computer-moves.test.ts: Expected: 0, Received: 1 (attempt 1: repetition 2/20; attempt 2: 1/20). Both logs show AckThreadRange failing with code 9 followed by repeated WatchThreadMirror failures with code 9. Neither contains 40P01. History, file transfer, redirects and the visible new owner had already passed.

#539 introduced per-thread mirror cursors and durable ACKs into a path whose generic redirect guard scans request IDs. #562 exposed this separate race through repetition; it did not introduce it.

Add real linked-gateway regression coverage with an ACK barrier after durable apply and before source cutover. Cover final ACK/removal, resumed old cursors, and old-epoch range repair. Keep the existing 20 repetitions unchanged and document journal routing in Polish.

Validation: changed-file oxfmt/oxlint and git diff --check passed. No local tests or builds were run while the host measurement is active. Remote required checks and two consecutive complete CI passes on the final head are pending.

Fixes: #539
Related: #562

Keep durable range ACKs, resumed subscriptions and range repairs on the original journal after thread cutover. Add a deterministic linked-gateway regression with a commit-before-ACK barrier.

Fixes: #539
Related: #562
@nixuuu
nixuuu marked this pull request as ready for review November 12, 2026 10:19
@nixuuu
nixuuu merged commit 78c9c66 into dev Nov 12, 2026
24 of 26 checks passed
@nixuuu
nixuuu deleted the fix/thread-move-race branch November 12, 2026 10:29
nixuuu added a commit that referenced this pull request Nov 12, 2026
The late-cleanup integration test compared two live readers' sequence
numbers as soon as each contained the answer text. The worker publishes
that item before `turnFinished`, so an independently scheduled reader
can already be at the final sequence while the other still has only the
answer. Run 43196187406, attempt 2, job Tests (4/4) failed at
`thread-multiclient.test.ts:169` with `Expected: 4n`, `Received: 3n`;
both answer-presence waits had succeeded.

Wait for completion of the specific sent turn and sequence convergence
before comparing readers. Make the timing difference deterministic:
publish an in-progress answer through the real scripted worker, pause
the desktop reader after applying it, let the paired phone consume
completion, assert that the desktop legitimately lags, then release it
and verify convergence. Both abort/return cleanup orderings still run
over real gateway/worker and paired-phone transports. The gate is
released in cleanup, and no production hook or timed sleep is added.

This test uses the legacy local watch path (`sequence` is unset), not
#541's sequence-resume reader. The premature equality assertion dates to
#350; the captured failure does not show shared-subscription teardown.
There are no production changes and no `Fixes:` link. The existing 20
repeated move tests remain unchanged.

Validation: changed-file oxfmt/oxlint and `git diff --check` passed. No
local tests, installs, typechecks or builds while the host measurement
is running. All required checks and two consecutive complete CI passes
on the final head are pending remotely.

Related: #350, #541, #566
nixuuu added a commit that referenced this pull request Nov 12, 2026
Bots currently choose permissions when starting threads, and Full access
is downgraded for subagents. New subagents now inherit the parent's
effective permissions, including Full access where the computer allows
it. Bots use the owner's default thread permissions or a per-bot
override; models no longer choose a creation mode.

## Changes

- Add Settings → Threads → Subagents: **Same as parent** by default, or
a fixed mode capped by the parent. Resolve and record the mode in the
gateway creation transaction. Existing children keep their mode;
lowering the parent's default limits new children immediately, and a
running turn's narrower permissions remain a ceiling.
- Default bot thread permissions to **Inherit default**, with all five
explicit overrides. Apply the configured choice to direct starts, forks,
schedules, and linked-computer starts. Remove model-facing creation
parameters; legacy `spawn_thread.permission_mode` can only narrow
access.
- Enforce owner scoping before execution and replay. Persist the
worker's authenticated Full access capability and clamp automated
creation to Full auto where bypass is unavailable. Scheduled new threads
retain their sandbox ceiling. Show clamp explanations and recorded
permissions in web/mobile thread details.
- Add gateway integration coverage for inheritance, parent changes,
fixed settings, escalation, owner scoping, worker ceilings, bot
defaults/overrides, and mode propagation into Codex, Claude, and Grok
native adapters. Add migration coverage and update Polish docs.

## Contracts and migration

Additive protobuf fields only:
`ThreadDefaults.subagent_permission_mode`,
`Thread.permission_mode_note`, and
`NewThreadSchedule.permission_mode_note`; generated code is included.
Worker link protocol is unchanged.

Migration **0125_inherited_access_mode** converts missing/legacy
inherited bot settings to `user_default`, preserving explicit choices,
including Ask first retained by migration 0090. It also includes clamp
explanations in the lightweight thread-settings projection used by lists
and details. Registration and schema expectations are updated.

Rebased onto `origin/dev` at `f7ad51ccc`, including #562 (migration
**0124_thread_range_lock_order**) and #566. This PR adds
**0125_inherited_access_mode**; registration and schema expectations
list 0124 followed by 0125.

Related: #562

Mobile changes are TypeScript/JavaScript only. No dependencies, Expo/EAS
configuration, or native files change.

## Verification

The initial implementation passed local `bun install --frozen-lockfile`,
`bun run gen:check`, `bun run typecheck`, `bun run lint`, `bun run
format:check`, and `git diff --check`. Subsequent fixes use CI logs for
runtime evidence; only `nice -n 19` formatting/lint on changed files and
`git diff --check` run locally while measurement continues. Current-head
CI results are shown by the PR checks.

After the maintainer opened the local verification window, `bun install`
and `bun run gen:check` passed on head
`ef33469656f17e4255f35e519cb1d37e4c9c3ee4`. Focused tests passed: **20
tests, 0 failures, 135 assertions** across `full-access-mode.test.ts`,
`bot-approval-rules.test.ts`, `bot-approval-review.test.ts`, and
`inherited-access-upgrade.test.ts`. The full local `check:tmp` was
intentionally omitted at the maintainer's request because CI runs the
full suite. Web/Linux builds and static checks passed in current-head
CI; other CI results are shown by the PR checks. Adapter coverage feeds
the child mode received over the worker link into native permission
adapters; it does not claim a live provider run.

Real-browser review passed in light and dark at desktop (1280/1440 px)
and phone (390 px) widths: Settings → Threads → Subagents, saved mode
after reload, bot Inherit default and fixed override after
saving/reopening, Full access confirmation, and the child clamp
explanation beside its effective mode. Long project, bot, parent, and
child names wrap or truncate cleanly; no horizontal page overflow. The
dark phone dropdown was checked after transitions settled: its
background is opaque and its copy remains legible. The isolated gateway
used a scripted worker; no live model or external account was contacted.
Review servers and their test database were stopped, and the browser tab
was closed.

Expo/EAS runtime fingerprints generated with `expo-updates
fingerprint:generate` are unchanged against `origin/dev`, using the same
checkout path and dependencies for both snapshots: iOS
`74705db3a68907bc28379bb9b1080a227bc0755b`, Android
`7d38be8f5c9bf842d62060c75820a206f99c87e3`. No native/config/dependency
changes are included.

## Copy audit — docs/copy.md §8

| Before → after | Reason |
| --- | --- |
| “Same as the bot’s approvals” → “Inherit default”; “Uses your default
permissions from Settings → Threads.” | Match the owner's new-thread
default and identify where to change it. |
| No subagent permission control → “Subagents”, “Permissions”, “Same as
parent”; “New subagents keep their mode when the parent’s permissions
change.” / “A fixed mode can limit access, up to the parent’s current
permissions.” | Describe inheritance, persistence, and the fixed-mode
ceiling beside the control. |
| No bot Full access override → “Full access”; “Thread tools run without
asking or a sandbox, where the computer allows it.” | Use the existing
mode name and confirmation; name the computer restriction. |
| No clamp explanation → “This computer limits Full access to Full auto.
Choose another mode or enable Full access on this computer.” / “The
parent’s mode limits subagent permissions. Change permissions in the
parent thread to allow more access.” / “Scheduled threads limit Full
access to Full auto. Keep this mode or choose one that asks.” | State
the effective limit and a next action; show it with the saved mode in
thread details. |
| Schedule standing-rule labels mentioning Ask first/Read only →
“creating schedules” / “updating schedules” | Permissions now come from
owner configuration, so the old qualifier was misleading. |

Static audit: sentence case, existing glossary terms, short
descriptions, and active wording; controls use the shared kit, and
actions retain existing verb labels. Clamp explanations include a next
action, avoid internal protocol names, and convey meaning in text rather
than color alone. Existing Full access confirmations remain. No new
empty states or humorous copy. The permission descriptions and clamp
explanation serve separate purposes. **Visual audit passed in light/dark
on desktop and phone widths, including long names, narrow picker
overlays, and the clamp hint; labels and descriptions stay readable
without horizontal page overflow.**
nixuuu added a commit that referenced this pull request Nov 12, 2026
An update or restart can surface an authentication failure as “Pair
again” even when the saved computer identity has not changed. Reconnect
now treats RPC authentication failures as retryable and requires
repeated, locally verified TLS pin mismatches before requesting new
trust. A successful handshake with the saved identity clears stale
pairing state.

## Investigation

- The dial catch classified **every**
`ConnectError(Code.Unauthenticated)` as a pin mismatch. That includes
invalid certificate validity, a peer rejecting the client pin, and hello
validation; on a manual route it persisted `pairing_required`, and on
LAN it deleted the route. This behavior exists in the original linking
implementation (#13), before the reported release range.
- Reviewed `v0.2.0-nightly.120..v0.2.0-nightly.137` and the `.133` →
`.137` diff, including #547, #548, #559, #562, #565, #566 and #546. The
full desktop hello grew from 32 capabilities to 33 in #559; both
releases reject more than 32 as `Unauthenticated: Invalid computer
identity` after pinned TLS succeeds. Merged #574 fixes this capability
overflow, including compatibility with the older validator. This branch
is rebased onto that fix in `dev`. Full source evidence:
#573 (comment).
- Identity and the 20-year certificate are persisted in
`computer_identity`; the private key uses the existing encrypted secrets
key. Desktop keeps the same Canopy data directory, database,
app/keychain name and `secrets.enc` across versions and channel changes.
Keychain/decryption failure stops startup rather than replacing the
identity. Reinstalling while preserving that data preserves trust;
deleting it creates a new identity.
- Production starts computer links, including loading identity and
peers, before opening Network access. There is no demonstrated
listener-before-store race in that path. The new readiness guard also
makes an early or stopping link service explicitly return `Unavailable`.
- `manual` means entered by the user, including a LAN/Tailscale address;
it is separate from the network's address type. A bad manual path must
not override another route or an incoming connection proving the saved
pin. The capability-count rejection is source-proven for the reported
version pair's full desktop configuration; incident logs would still be
needed to attribute every earlier report or explain successful
re-pairing.

## Changes

- Use a local `CertificatePinMismatch` signal emitted only after TLS
proof of possession and validation of a different self-signed
certificate. Override ConnectError's inherited structural
`Symbol.hasInstance` check so ordinary RPC errors cannot impersonate
this local class. Without this override the new LAN test correctly
caught a real route-deletion bug, not test timing. Invalid/expired
certificates remain rejected without declaring an identity change.
- Exhaust routes first. Require the same different certificate at the
same manual route in two consecutive failed rounds. A matching pinned
TLS connection or ready incoming link outweighs stale addresses. Only a
verified pin mismatch removes a discovered LAN route. Saved pins are
never replaced automatically.
- Clear confirmation evidence after pinned TLS verification, a
successful handshake, explicit pairing, route edits and unlink. Existing
successful handshake recovery also clears a persisted `pairing_required`
after restart.
- Use the shared reason “{name}'s identity changed. Pair again to trust
it.” for linked computer availability and app updates, including the
relay's name when its identity changed. Remove the contradictory
automatic-retry explanation for that state. Add stable auth-failure
classifications to diagnostics without logging certificates, keys,
addresses or RPC payloads.
- Document persistence and recovery. No proto changes, protocol bump or
migration.

## Regression coverage

Added gateway↔gateway integration scenarios using independent databases
and real TLS listeners:

1. Repeated startup `Unauthenticated` on manual and LAN routes preserves
trust and resumes; verify the LAN route remains after each attempt. RPC
error text cannot impersonate a local pin mismatch, and failed TLS
connections cannot confirm a manual route's identity change.
2. An early listener returns `Unavailable` for both `Pair` and `Connect`
until ready.
3. Both gateway/core restarts reuse persisted identities/certificates
and reconnect; a protocol-1 `.133` hello without new capabilities links
with a `.137` hello and resumes after upgrading.
4. A real new key requires confirmed pairing, receives no RPC, never
replaces the pin, and has consistent availability/update explanations.
5. A persisted stale pairing state heals after restart; a valid
alternate route outweighs a stale manual address with another key.

The older-version scenario exercises the compatible wire
hello/capability set, not archived app binaries. Installer and OS
keychain behavior was inspected in source, not exercised on
macOS/Windows.

## Validation

- After maintainer clearance, ran only the two authorized test files,
sequentially, at `nice -n 19`, using `TMPDIR=/var/tmp` and `bun run
check:tmp`: `linked-pairing-recovery.test.ts` **10 pass**,
`linked-capability-compatibility.test.ts` **3 pass**. Both
temp-directory checks passed. The original LAN failure reproduced before
the fix (8 pass / 1 fail); the strengthened assertion confirmed deletion
immediately after the first auth failure.
- Changed-file formatting and lint passed; `git diff --check` is clean.
Earlier dependency install and repository formatting/lint checks passed
before the original push.
- CI validates generation, full typechecking, all test shards and builds
for the rebased head. Browser verification remains pending; the UI
change reuses existing components and only changes status explanations.

## Copy audit (§8)

“{name} must be paired again” / “Link it again…” / “unavailable, trying
again automatically” → “{name}'s identity changed. Pair again to trust
it.” The text states the verified problem and the explicit trust action,
uses two short sentences and avoids TLS jargon. The compact action badge
remains “Pair again”. Names are interpolated as whole values and
existing wrapping/layout remains in place; short/long-name checks at
desktop/phone widths have not been run yet.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant