Skip to content

feat(computers): mirror linked threads for offline reading - #27

Merged
nixuuu merged 2 commits into
feat/linked-computers-2from
feat/linked-computers-3
Nov 4, 2026
Merged

nixuuu merged 2 commits into
feat/linked-computers-2from
feat/linked-computers-3

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 3, 2026

Copy link
Copy Markdown
Member

Stage 3 of linked computers (stacked on #20; the whole stack merges into dev together when the plan is complete).

Keep linked-computer threads listed and readable offline using durable read-only mirrors: owner-scoped change journal on the home, separate mirror tables keyed by origin node, epoch/revision cursor replay, generation-based atomic full resync on a stale or mismatched cursor, deletion/archive reconciliation, thread_mirror capability with stage-2 fallback for older peers, and unlink purging the mirror. Online reads stay live-routed; offline reads come from the mirror; writes always require the home and are never queued. Blob metadata is mirrored, bytes load when the home is connected. Secrets and provider credentials are never mirrored.

  • Migration 0049 (renumber at merge if dev moved).
  • Additive proto; link protocol stays 1.
  • UI: greyed offline threads with "Last seen", read-only banner, attachments "available when … is connected".
  • Tests: 16 mirror scenarios with two gateways + separate databases (initial sync, live changes, offline read, resume from cursor, stale cursor resync, deletions/archival, unlink purge, capability fallback, restart durability) + schema tests; check:tmp 702 pass / 0 fail.
  • Docs: docs/linked-computers.md → "Konkretny protokół etapu 3".

@nixuuu
nixuuu force-pushed the feat/linked-computers-3 branch from 764c5d0 to 6d2b89d Compare November 3, 2026 22:29
@nixuuu
nixuuu marked this pull request as ready for review November 4, 2026 05:57
@nixuuu
nixuuu merged commit 17add15 into dev Nov 4, 2026
4 of 5 checks passed
@nixuuu
nixuuu deleted the feat/linked-computers-3 branch November 4, 2026 05:58
nixuuu added a commit that referenced this pull request Nov 4, 2026
Stage 4 of docs/linked-computers.md (stacked on #27; the whole stack
merges into `dev` together when the plan is complete).

Opt-in "Share with linked computers" for provider instances (API keys
and secret variables re-encrypted with each computer's own key; only for
shared items), model lists, settings sections (appearance, thread
defaults, time zone, text generation) and projects (one id on every
computer, workspaces per machine). Version vectors per item: concurrent
offline edits become durable questions with both versions ("Keep this
computer's / Keep Laptop B's"), never last-writer-wins; non-conflicting
changes merge. Unshare or delete leaves a local copy everywhere with a
note. Local-only: CLI paths, logins, workspaces, connector accounts,
desktop settings.

- New capability `shared_config` over the stage-2 transport; additive
proto, link protocol stays 1; migration 0050 (renumber at merge if `dev`
moved).
- UI: "All linked computers" / "This computer" badges, share switches,
question dialog, notes for connectors and desktop.
- Tests: `tests/integration/shared-config.test.ts` (8; two gateways,
separate databases and secrets keys: key re-encryption and no leak, sync
and local-only, conflicts both ways, merge, restart durability,
unshare/archive, capability fallback, unlink) + schema test; check:tmp
711 pass / 0 fail.
- Docs: "Konkretny protokół etapu 4", ui-api, data-model.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Linked thread lists read and protobuf-decoded every complete mirrored
history to obtain the small `ui.Thread` row. Lists and header reads now
use the existing atomic metadata projection, with a backfill that makes
it mandatory. Healthy aggregate lists use the bounded live-read cache;
the mirror remains the loading/offline/failure fallback.

## Evidence

- The home log repeatedly executes `SELECT t.snapshot ...
computer_mirror_threads ... ORDER BY t.thread_id`, followed by
connection resets/broken pipes. The supplied client's PostgreSQL log has
no matching statement: the expensive direction is the home listing the
client's mirrored threads.
- Call path: sidebar/overview `ListThreads` → `gather` → `forward` →
`ThreadMirror.threads()`. Qualified project lists use the metadata
mirror directly. Web and mobile reload on reconnect and linked-read
completion; no independent fixed sidebar polling timer was found. Live
results refresh after 5 s, reads have a 10 s budget, failed refreshes
cool down for 30 s.
- No SQL read/query deadline is configured on this path. The SQL driver
pinned in nightly.108 (4.1.1) rejects backend messages above 16 MiB and
fatally closes the socket. The integration test reproduces its parser
failure with a 17 MiB snapshot row while metadata listing succeeds. This
is consistent with the observed resets; the historical row sizes and
client-side SQL errors are unavailable, so their exact cause remains
unproven. Synchronous full-history decodes also add event-loop pressure.

## Cost

| Path | Before | After | How measured |
| --- | --- | --- | --- |
| Mirror list, 100 threads × 3 MiB | 314,583,794 bytes, 378 ms | 9,294
bytes, 4 ms | Real PostgreSQL integration fixture, query plus protobuf
decode; representative run |
| Healthy aggregate linked list | Re-read the mirror for every call |
Bounded cached live result; no mirror call | Linked-gateway regression
test |

Migration 0097 extracts the protobuf header inside PostgreSQL, handles
reordered fields, then sets `thread_metadata NOT NULL`. Existing writes
already update metadata and snapshot in one transaction.
Owner/project/archive/sidebar filtering remains enforced. Cache bounds
remain 128 keys/16 MiB and four active reads per peer. Slow metadata
lists log duration, count and bytes above 250 ms, without content or
hosts.

## Validation

Focused metadata/backfill/oversized-row and healthy-cache tests pass.
Top-of-stack validation passed: `bun install`, `bun run gen:check`, `bun
run typecheck`, `bun run lint`, `bun run format:check`, `bun run
check:tmp`, and the web production build. The full test run finished
with **1,904 passed, 161 skipped, 0 failed across 339 files** (982.19
s), with nothing left in the private disk-backed temp directory.
Multi-gateway files ran sequentially. All three stack heads have green
CI; the stack is ready for review and has not been merged.

Copy audit §8: no UI text changes.

Fixes: #348
Related: #27
Related: #386
nixuuu added a commit that referenced this pull request Nov 16, 2026
## Change

Streaming events currently create unnecessary notice invalidations and
retain duplicate text, sync revisions, and unused files indefinitely.
This change reduces write amplification and adds bounded, resumable
cleanup for both existing and newly written data.

- Filter notice replication triggers to actual notices, including kind
transitions and deletion tombstones.
- Batch adjacent delta projection writes and store exact duplicate raw
text as lossless references to the same event payload. SQL compaction
preserves numeric precision and reconstructs provider metadata; bounded
maintenance also compacts eligible historical events.
- Retain a contiguous 10,000-record sync replay suffix with a one-hour
grace period and active-reader protection. Clean obsolete epochs/content
while preserving current lazy content and rebuilding expired readers
safely.
- Permanently clean manually deleted thread history after 31 days,
independently of optional archive retention. Preserve fork dependencies,
active work, owner boundaries, deduplication state, and shared
attachment references.
- Collect abandoned unbound uploads after 30 days and unreferenced
non-exempt blobs after seven days. Protect composer, bot, and rewind
drafts, including conservatively handled legacy drafts.
- Add capability-gated worker cleanup after completed database purge,
with durable grants, admission/restart safety, managed-path
restrictions, and import/session protections. Gateway and worker must
both be updated for local file cleanup; workspace files remain intact.
- Preserve exact Codex image bytes before compacting new inline raw
data, protect pending journal references, and keep three update releases
plus current/rollback/staged versions.
- Add read-only `storage inspect` and explicit `storage reclaim
--offline --table ...`. Ordinary maintenance frees PostgreSQL space for
reuse; physical disk reclamation is never automatic.
- Fix a Claude startup race found by the live restart/fork test: idle
cleanup now waits for first-turn admission.

Migrations 0153–0157 are additive. Historical journal rows receive a
fresh one-hour protection period. Existing inline image history remains
until thread purge, and legacy retention-exempt blobs remain protected.
Cleanup starts automatically with the gateway and proceeds in bounded
transactions.

Fixes: #27

## Verification

Selective local verification passed during implementation:

- Fresh PostgreSQL 17 migrations/schema: 23 tests.
- Notice replication/schema: 27 tests, plus real worker↔gateway sequence
regression.
- Ingest, lossless transcript storage, event storage, and
recovery/schema: 46 tests. Coverage includes exact numeric raw
reconstruction, fork/restart integrity, and three projection writes for
start/delta-run/completion.
- Replication retention: four tests, including 12,512 → 10,000 journal
records and removal of 16 MiB orphan content; existing
range/window/remote/lock/compatibility coverage also passed.
- Deleted/archive retention, attachment/blob GC, and worker cleanup:
focused PostgreSQL, filesystem, durable journal, admission, and real
WorkerLink tests passed. Storage CLI: five tests. Update-cache retention
tests passed.
- Live Codex + Claude through CLIProxyAPI on a fresh schema: two tests,
68 assertions. Full 320-line output, exact image/raw reconstruction,
cold restart, resume, fork, and owner scope passed. Codex raw saved
25,801 bytes (34.3% of raw JSON in that fixture); this is not a
whole-database reduction. Claude raw remained unchanged. Physical
relation files did not shrink.
- Worker, gateway, integration, DB, and updater scoped typechecks;
edited-file lint/format; proto generation; diff checks passed.

Copy audit (§8): PASS. Delete confirmation previously mentioned
immediate deletion and brief Undo; it now states the 31-day history
cleanup and preserves the workspace-file warning. Settings explain the
fixed recovery window. Browser inspection passed in light/dark themes at
desktop and phone widths with short, typical, and 200-character names.
Native mobile was not run.

Rebased onto current `dev`; only two documentation status paragraphs
required conflict resolution, preserving both descriptions. Full
repository checks/builds and generated-code verification are left to
required CI. No production data or files were modified, and offline
reclamation was not run.

CI follow-up: resolved lint spacing and size limits by extracting
command replay policy and Welcome construction. Scoped lint/format and
gateway/worker typechecks pass; WorkerLink and worker cleanup regression
tests pass (22 tests, 67 assertions; clean `check:tmp`).

Retention test synchronization: wait for the initial turn to be durably
completed before using its history; initial `idle` can precede worker
admission. Deleted-retention suite passes (five tests, 23 assertions;
clean `check:tmp`). On the preceding revision all CI checks except that
test shard and its aggregate gate passed.
nixuuu added a commit that referenced this pull request Nov 27, 2026
## Problem

On the production gateway (0.11.0-nightly.14), Postgres wrote ~285 GB in
6 days. Measured with `pg_stat_*`:

| | 6 days since stats reset | 60 s sample |
|---|---|---|
| `thread_replication_clock` UPDATEs (1744 rows) | 51.2 M | 7238
(~120/s) |
| all other tables | far fewer | < 1500 |
| WAL | 80 GB (6.3 M full-page images) | 9.5 MB |
| commits | 46 M (~86/s) | |

Cause: a worker heartbeat runs `UPDATE workers SET last_seen_at=now()`
about every 20 s. The constraint trigger `computer_worker_change` (0049)
treats every UPDATE of `workers` as a metadata change, which has no
`thread_id`. Each heartbeat therefore:
1. runs `thread_replication_changed` over every thread on that worker
and its forks. That is 904 and 581 clock updates for the two largest
workers, in one transaction.
2. counts as relevant for every watched thread in `threadWatchRevision`,
so every thread watch and the BFF warmer re-read.
3. makes mirrors revalidate.

Nothing reads `last_seen_at` from the change log: `ui.Thread` only
carries `worker_id`, and worker lists get changes through the overview.

## Change

- Migration `0223_worker_heartbeat_changes` splits the trigger.
`computer_worker_change` keeps INSERT and DELETE. A new
`computer_worker_update` fires on UPDATE only when anything other than
`last_seen_at` changed.
- `docs/linked-computers.md` described heartbeat revisions as expected
behaviour; it now describes the new rule.

The trigger dates from #27 and has always behaved this way, so this is
not linked as a fix.

## Verification

- New case in `packages/db/test/notice-replication.test.ts`: a
`last_seen_at`-only update records no `workers` change and leaves the
thread's replication clock unchanged. A rename still records the change
and moves the clock. Without the migration the case fails (5 `workers`
changes recorded).
- `notice-replication` and `schema` tests: 31 pass.
`local-thread-liveness`, `thread-read-cost`, `ui-thread-deltas` and
`thread-mirror-deltas` via `check:tmp`: 29 pass.
- oxlint on edited files is clean. CI runs the full gate.

Not addressed here: Postgres reports 71 GB of temporary files (22.5k
files) over the same period. A 4-minute sample saw none, so they come in
bursts, likely from periodic maintenance. `log_temp_files` is off on
that server, so the query isn't identified yet.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
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