Skip to content

fix(threads): keep every client's live thread in sync - #350

Merged
nixuuu merged 1 commit into
devfrom
fix/desktop-mobile-desync
Nov 7, 2026
Merged

nixuuu merged 1 commit into
devfrom
fix/desktop-mobile-desync

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 7, 2026

Copy link
Copy Markdown
Member

An old thread watch could silently disconnect the desktop's replacement watch while a paired phone continued receiving replies. Abort and generator cleanup both removed the old subscription; the second close deleted the thread's map entry even when reconnect had already created a new subscriber set. A phone opening afterward got a new live set, while the desktop's orphaned stream still received BFF heartbeats. Messages were stored and executed, but its timeline stopped updating.

Make removal idempotent and conditional on the registered set's identity, and detach abort listeners when thread/overview generators finish. The regression predates the recent paging, bus-consumption and reconnect PRs; no recent introducing PR was established.

Validation:

  • Real PostgreSQL + gateway + scripted gRPC worker, coalesced BFF-side stream, and a separately paired mobile API client over pinned Network access TLS. The controlled late-cleanup reproduction failed before the fix: the phone saw the new reply and the desktop timed out. Both abort/return orderings now pass.
  • Disk-backed DesktopHistoryCache reload while a phone remains active, with a steer, a child ask_user routed to its parent, parent interruption, an answer, and phone reconnect. Restored desktop and phone converge on the same items and turns and both show a subsequent desktop reply. No permanently stuck cache was reproduced; existing cursor/snapshot repair remains in place.
  • T3 browser against an isolated local BFF: desktop composer sends and renders its reply alongside the paired mobile-equivalent client; phone messages and reconnect remain visible, with no observed Syncing flashes during steady-state operation. Checked light/dark and desktop/phone widths. The fixture intentionally has no linked-computer runtime, so its optional /api/computers polling returns 409; thread streams and message actions succeed. Packaged macOS/iPhone apps were not run.
  • Local gates: bun install, bun run gen:check, bun run typecheck (including mobile), bun run lint, bun run format:check, and the web build passed. Full bun run check:tmp passed: 1767 pass, 161 skipped opt-in/platform tests, 0 fail across 317 files; no test temp directories left. Test temp files stay under the worktree; GIT_CEILING_DIRECTORIES stops ordinary temp folders inheriting the checkout's Git origin.
  • Copy audit: not applicable; no UI text changed. No proto or schema changes. No UI test suite added.

For an already frozen running app, restarting Canopy Desktop resets the subscriber registry and resumes from its saved checkpoint; this is a temporary workaround on affected versions, and clearing desktop history is unnecessary. After updating the desktop gateway with this fix, desktop and iPhone can keep the same thread open and exchange messages concurrently.

Keep late cleanup of an old subscription from deleting the subscriber set created by a reconnect. Remove watch abort listeners on generator completion. Cover concurrent paired mobile and desktop streams plus disk cache resume across parent questions, steers and cancellation.
@nixuuu
nixuuu merged commit bbe0acc into dev Nov 7, 2026
10 checks passed
@nixuuu
nixuuu deleted the fix/desktop-mobile-desync branch November 7, 2026 23:04
nixuuu added a commit that referenced this pull request Nov 8, 2026
Report inputs could appear after newer answers, leave empty cancelled
work, and repeat for the same child result. Desktop and phone could
retain different projections after consumption or reconnect. This keeps
report delivery unique per recipient and child turn and preserves the
loaded timeline window across recovery.

### Causes and evidence

1. In the supplied recording, repeated purple reports with 4-hop and
2-hop badges sit beside empty cancelled work while newer 03:33 and 03:35
turns appear below during scrolling. Web appended turns without
transcript elements after all event-backed rows. Those turns now keep
their canonical ordinal position; transcript/background events retain
event sequence order.
2. A spawn and subsequent admitted steers can share a target turn.
Completion previously notified once per call: the gateway/worker
reproduction produced three reports for one result. Delivery now claims
the result once per recipient under its existing thread lock. Different
hop counts are consistent with distinct calls; the original call IDs are
unavailable, so the recording alone cannot establish the precise relay
path.
3. Consuming pending bus inputs cancelled them without withdrawing their
timeline rows or broadcasting the changed projections. Consumption now
withdraws them and publishes turn/steer updates. Migration 0096 repairs
historical consumed inputs while preserving started/dispatched work and
genuine cancellations. Explicit-message consumption was introduced by
#338; per-call completion notifications and the empty-turn layout
predate it.
4. Real-browser paging exposed another jump: report-bearing threads
conservatively fall back to a full snapshot on reconnect, replacing an
expanded window with its last 24 turns. Additive UI field `from_turn_id`
preserves the inclusive oldest loaded turn on both clients, with
authoritative reset for invalid history. Late old turn updates stay
outside a loaded tail. Fork ancestry keeps chain order.

`nightly.100` includes #350 and was published at 00:21:46 Warsaw on
November 8, before the reported 03:33 observation. Installation on the
reporting Mac is unconfirmed. These paths reproduce on a base containing
#350 and explain persistence either way. No linked-computer topology is
needed.

### Validation

- Gateway↔scripted-worker/Postgres regressions cover admitted steers,
fallback/consumption, wait_threads progress, idle report delivery,
distinct results with identical text, repeated sweeps, late old
projections, disk-cache restore, expanded history, and gateway restart.
A paired mobile client uses Connect over pinned Network access with the
same device credential after restart; its projection matches the
BFF-coalesced desktop path. Before the fix, duplicate delivery was 3
instead of 1 and consumed inputs never updated live.
- Migration upgrade regression preserves genuine, started and dispatched
cancellations. History integration covers full-snapshot resume and
invalid window/version resets.
- Gates passed: `bun install`, `bun run gen:check`, `bun run typecheck`
(including mobile), `bun run lint`, `bun run format:check`, and the web
build. The complete `bun run check:tmp` ran in four sequential native
shards (`--shard=1/4` through `4/4`, `--timeout 30000`): **1780 pass,
161 skip, 0 fail across all 320 files**, with a clean test temp
directory after each shard. Two monolithic attempts were interrupted by
SIGTERM, so sharding completed the full gate. The existing steering
regression now expects one shared-result report instead of two.
- Real browser: light/dark at 1280×800 and 390×844, long labels,
older-page loading/reconnect, genuine cancellation placement,
consumed-report removal, jump to latest, and composer reply also
observed by the paired mobile client. Test servers and tabs were closed.
Packaged macOS/iPhone apps and the optional Android emulator were not
run. The isolated fixture lacks linked-computer runtime, producing an
unrelated `/api/computers` 409.
- Copy audit (§8): no UI strings added or changed; consumed inputs no
longer render misleading empty cancelled work. Existing cancellation
copy remains for real cancellations.

CI: static checks, all four CI test shards, and Web/Linux builds passed
on this head. Windows packaging reached the prepared runtime and
electron-builder, then failed with HTTP 504; its failed job was retried
once. No external review yet; inline self-review found no outstanding
issues.

Fixes: #338
Related: #350
nixuuu added a commit that referenced this pull request Nov 9, 2026
…386)

## Change

A linked thread could remain on its last snapshot while its computer
link and BFF SSE heartbeats stayed healthy. Peer watches had no
application-level deadline. Live thread events also accepted sequence
gaps. Restarting the receiving gateway recreated these streams, but a
healthy transport alone could not repair them. Watches now validate
durable revisions, resubscribe automatically, and surface a
stale/unavailable state if recovery fails.

### Trace and evidence

- `REMOTE_THREADS` forwards a qualified thread ID through the pinned
computer link to the home's owner-scoped `WatchThread`. Each client
watch owns an independent remote call. The home subscribes to Hub before
reading its snapshot. Re-opening already creates a fresh watch; no
shared client consumer-count leak was found.
- `THREAD_MIRROR` separately maintains one background subscription per
peer. Committed snapshots/cursors live in the owner-scoped mirror
tables; staged reset generations remain invisible until commit. The
runtime's existing subscription entry could remain occupied indefinitely
by an open stream without progress. Existing mirror predecessor,
delta-base, epoch, generation and subscription fences already rejected
inconsistent updates; they lacked a deadline for missing final frames.
- Web and desktop receive the forwarded watch over the BFF's
linked-subscription HTTP/2 pool and SSE. Four BFF pools isolate
local/linked unary calls and subscriptions. SSE heartbeats prove BFF
reachability; they do not prove upstream thread freshness. The browser
cache keeps an atomic checkpoint and reopens through the gateway.
`linked-snapshot` retains aggregate linked rows and applies presence
separately; it does not deduplicate thread watches.
- #348's peer HTTP/2 PING (15-second interval, 10-second pong budget),
link heartbeats, circuit breaker and reconnect handling remain intact.
Transport loss terminates calls and reconnect resumes from committed
cursors. These checks cannot detect lost application fan-out while the
transport still responds.
- The new gateway-to-gateway tests failed before the fix for live-watch
stalls, accepted event gaps, a mirror missing its final checkpoint, and
an older peer without heartbeat recovery. Re-opening already passed.
#350 fixed an earlier Hub cleanup race consistent with the report, but
the inaccessible affected app's cause cannot be established from the
available logs. A home event-loop pause alone does not erase the durable
journal; the tests additionally suppress fan-out while changing durable
metadata.

### Recovery

- Negotiate `thread_watch_liveness`. The home sends an independent
durable revision heartbeat every 5 seconds. A changed revision
revalidates the snapshot checkpoint, using existing deltas for
incremental clients. The owner-wide revision can conservatively
revalidate another open thread too.
- Missing initial snapshots/heartbeats expire after 15 seconds. An
established live watch enters the existing syncing state and retries
once with an empty cursor. A failed repair returns a computer-scoped
unavailable error to the existing client reconnect path. Live event gaps
and invalid delta bases also force a full snapshot. Sequence checks run
before BFF text-delta coalescing, which intentionally skips sequence
numbers. Loaded history boundaries are retained.
- Mirror heartbeats must match the receiver's committed cursor and
arrive outside partial projections. A gap or 15-second stall clears the
cursor and restarts from a full generation on the next link tick (within
5 seconds). The last committed generation remains readable. A sync
failure projects the existing unreachable state; a commit or matching
checkpoint heartbeat clears it. Ordinary transport loss retains the
checkpoint for resume.
- Older peers are revalidated every 30 seconds without requiring new
frames: reopen the live read from its supported checkpoint, and refresh
the mirror generation. Only reads are retried. Bounds assume the
receiving event loop can run.
- Subscribe/end/resubscribe diagnostics use debug; unexpected stalls,
gaps, probe failures and stream failures use warn. Both sides log IDs
and safe protocol metadata only, without hosts, names, thread content,
credentials or raw errors.

All protobuf changes are additive. The frozen update protocol, worker
link compatibility, schema and mobile/web source are unchanged. The
Polish linked-computers document now describes the liveness and recovery
rules.

## Verification

- `bun install`, `bun run gen:check`, `bun run typecheck`, `bun run
lint`, `bun run format:check`, and `bun run --filter @canopy/web build`
passed.
- New gateway-to-gateway suite: 11 passed. Covers open stalls, missing
heartbeat frames, event gaps, invalid bases, missed metadata fan-out,
re-opening with a stale mirror, lost mirror checkpoints,
unreachable/recovered status, idle reconnect confirmation, and an older
home without new frames.
- Existing mirror suites ran one file at a time: 19 durable mirror tests
and 12 incremental mirror tests passed, including restart, fencing,
owner scoping and legacy negotiation. The existing linked-list retention
test also passed in isolation after distinguishing ordinary transport
loss from application-stream failure.
- Full `bun run check:tmp --timeout 20000`: **1,865 passed, 161 skipped,
0 failed across 330 files** (982.07 seconds), with nothing left in the
test temp directory. This includes all 11 new liveness tests and the
existing linked-list retention regression. Multi-gateway files ran
sequentially.
- The preceding full attempt had one updater handover test fail with
`ENOSPC` on the shared temp filesystem (1,864 passed, 161 skipped).
Repeating the full gate with a disk-backed private `TMPDIR` passed,
including that test; no updater code was changed.
- No UI tests added. No web or mobile source changes; no browser/device
run was required. Packaged apps and the originally affected computer
were not exercised.

Copy audit: uses existing Syncing/reconnect/unreachable states and the
existing computer unavailable reason; no new frontend copy.

Related: #348
Related: #350
Related: #265
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
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