Skip to content

feat(threads): add owner-scoped draft handoff storage - #664

Merged
nixuuu merged 1 commit into
devfrom
feat/thread-drafts-gateway
Nov 14, 2026
Merged

nixuuu merged 1 commit into
devfrom
feat/thread-drafts-gateway

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Change

Adds owner-scoped composer drafts with revision/idempotency fencing, paged handoff queries and event-driven notifications. Concurrent continuation has one winner; stale source devices fork their draft/send identity without losing content. Drafts stay on the owner's gateway, including remote targets, and reach workers only when sent.

Sending uses one SendMessage/CreateThread RPC without saving first. A short draft transaction claims the receipt, delivery runs outside that transaction, and a second short transaction records the outcome. The draft wrapper holds no pooled connection or thread lock across remote I/O, pump or steer. Identical concurrent retries wait outside SQL; conflicting payloads fail validation. Definite rejection releases the fence. Unknown outcomes retain send identity; GetComposerDraftDelivery checks the owner receipt, native thread_message_receipts for every SendMessage result (including /goal), and turn/steer admission before clients offer recovery. Recovery never resends the command. The pre-existing native admission transaction in core/message-receipt.ts is unchanged and remains a separate follow-up.

Receipts keep a request hash rather than contents and expire 30 days after sending. Unsaved receipts neither advance the draft clock nor wake watchers. Mirror removals and retention notify after commit. Lists omit sends in progress and resume from after_revision. The bounded local store writes only changed target keys and supports per-target subscriptions.

Migration 0140_composer_drafts.sql includes the thread index and follows visuals' 0139_thread_visuals.sql. Rebased with gh stack onto bcc07e0 after visuals merged. Item.visual=26, MovedThread.visuals_json=4 and all visuals contracts are preserved; generated contracts and buf build pass. Diagnostics accepts the expanded bounded method registry; aggregate memory budgets are unchanged.

Verification

  • Current /goal follow-up: draft integration 17/17, linked-send integration 2/2, affected gateway/integration typechecks, lint and format:check passed with nice. The new case failed with confirmed=false before the fix; after forcing settlement failure following /goal admission, recovery confirms the durable goal receipt, reports no active send and clears retained payload, with no turn or steer for that request. Both test files left clean temp directories. Migration 1/1 and schema 23/23 passed after the visuals rebase; neither changed in this follow-up.
  • Slow linked send: while B withholds delivery, a routed title write to the same thread completes within its 2-second deadline. The receipt row on A is writable under a 500-ms lock timeout, and A has zero idle SQL transactions. An identical retry returns the same turn; a different payload is rejected. Recovery confirms the message without sending again.
  • Retention covers recent/expired receipts and protected pending fences. Recovery covers missing receipts, interrupted settlement, request identity and partially created threads. A database-triggered settlement failure returns an unknown outcome, then recovery confirms one admitted turn and removes retained contents. Ordinary sends leave the draft clock and subscriptions unchanged.
  • Install, gen:check, monorepo typecheck, lint, format:check and production web build passed on each layer with nice.
  • Before the final /goal follow-up, full check:tmp passed: 2959 pass, 175 skip, 0 fail, 561 files; private temp directory clean. Diagnostics boundary tests passed 7/7. The focused current-head checks are listed above; the full suite was not repeated locally for this narrow SQL lookup fix.
  • CI and the final re-check of this follow-up are pending. The stack stays draft as requested.

Part of stack 667. Do not merge separately.

@nixuuu
nixuuu force-pushed the feat/thread-drafts-gateway branch from 49c9dae to 817b1de Compare November 14, 2026 02:50
@nixuuu
nixuuu marked this pull request as ready for review November 14, 2026 03:01
@nixuuu
nixuuu merged commit 9b56186 into dev Nov 14, 2026
11 checks passed
@nixuuu
nixuuu deleted the feat/thread-drafts-gateway branch November 14, 2026 03:02
nixuuu added a commit that referenced this pull request Nov 14, 2026
## Change

Thread/new-thread/side-thread composers retain bounded local drafts,
including mentions, citations/notes, uploaded IDs and explicit choices.
Per-target storage/subscriptions preserve other tabs' drafts and avoid
rerendering every sidebar row. Markers reserve their width. Generic
snapshot/restore preserves Edit from here / Swap drafts and workspace
tabs.

Open drafts lists other-device prompts. Continue here appends without
re-uploading; replacement is explicit. One shared page cache and
resumable stream serve mounted composers. Stream failures back off from
2 to 60 seconds without re-listing on reconnect. Newer hints compare
gateway clocks. Source conflicts fork draft/send IDs while preserving
text.

Send/create uses **one RPC instead of Save + Send (2 → 1)**. Navigation
does not abort the send. Acknowledged sends clear their captured durable
state even after navigation. Reopened pending drafts query
GetComposerDraftDelivery before showing recovery; confirmed
receipts/native admission clear them without resending. The unknown-send
banner and Edit/Discard actions stay hidden while this client sends or
the gateway reports an active attempt. Definite rejection preserves
editable text; a truly unknown outcome exposes explicit recovery.

## Verification

- Production browser review after rebasing onto visuals bcc07e0:
desktop/light and 390px/dark. Holding HTTP200, switching threads and
releasing the response left the request un-aborted and removed its
persisted draft. Reopening showed an empty editable composer.
- Reloading a persisted pending request after admission made one
read-only recovery call and zero message calls. The draft cleared
without the unknown-send banner. An injected unknown network outcome
exposed Edit/Discard only after reconciliation; Edit preserved the
prompt and restored editing. Phone layout had no horizontal overflow.
- Current gateway /goal recovery follow-up passed drafts **17/17**,
slow/lost linked send **2/2**, gateway/integration typechecks, lint and
format:check with nice. Recovery now checks every native SendMessage
receipt, including goals without turns/steers. Web sources are
unchanged. Migration/schema **1/23** passed before this follow-up. Each
layer previously passed install, gen:check, full typecheck, lint,
format:check and web build with nice.
- Before the final /goal follow-up, full check:tmp passed: **2959 pass,
175 skip, 0 fail**, 561 files; private temp directory clean. Diagnostics
boundary tests passed **7/7**. The full suite was not repeated locally
for the narrow follow-up.
- CI and final re-check of the gateway follow-up are pending. The stack
stays draft as requested. Native device coverage is tracked in #666.

## Copy audit (docs/copy.md §8)

- Draft, Open drafts, Continue here and Replace local draft use shared
terminology. Markers reserve width and do not rely on colour.
- Before: the unknown-send warning appeared on ordinary sends. After: it
appears only after recovery establishes an unknown outcome, without an
extra row during normal sends.
- Edit draft / Discard draft describe recovery. The warning states
possible prior delivery and that editing starts a new message. No
protocol or revision terms appear in product copy.
- Short/typical/long text and actions were reviewed at desktop and phone
widths, light/dark. No UI tests added.

Part of **stack 667**, depends on #664. Rebased onto **bcc07e0db**;
migration 0140. Do not merge separately.
nixuuu added a commit that referenced this pull request Nov 14, 2026
## What

`SendMessage` ran every check (thread state, attachments, quotes,
mentions, model, permission mode) inside the transaction that holds `FOR
UPDATE` on the thread row and a pooled connection. The send path now has
three steps:

1. **Checks without a lock**: read-only. A failed check still replays a
stored receipt first, so a retry to a thread archived since admission
returns its admission, and another owner still gets `NotFound`.
2. **Short admission transaction**: `FOR UPDATE` on the thread (a narrow
column read, not `threadSelect`), then one separate state statement (its
snapshot follows the lock, so it sees other tables committed while it
waited): the receipt, plus every input the checks read that a writer
changes under this thread's lock. That is archived/deleted, rewind,
worker, cwd, provider/profile, model, `pull_request_revision` (PR
citations), import mode and import in progress. Native dedupe also runs
again here. If anything changed, the checks run again under the lock.
Then the steer, the queued turn plus its `StartTurn`, or `/goal`,
committed together with the receipt.
3. **Delivery after commit**: unchanged. Worker commands, pump and
publishing are deferred by `ActionContext` and recorded by the existing
`CommandResult` handlers in their own short transactions.

Docs: `docs/threads.md` § "Przyjęcie wiadomości".

## The premise, measured

Worker and linked round trips were **not** inside the transaction.
`coreDispatch`/`coreDeliver`/`pump` already defer to after the commit,
and linked sends are forwarded by `routed()` before `messageReceipt`.
With a worker that answers `StartTurn` after 500 ms, the old transaction
still took ~5 ms. What the lock covered was the check reads. They are
fast normally, but any slow one blocked every write to the thread, and
every concurrent send waited behind it holding a connection. So this PR
moves the checks out and keeps the admission atomic. No new intermediate
durable state was needed: step 2 is still one transaction, and step 3
was already outbox-based.

## Numbers

Local Postgres via the test gateway, scripted worker, same host, old =
`dev` 76b5561, new = this branch. 30–40 sends per row after 5 warm-ups.
The host was shared with other agents, so the p95s are noisy.

**Thread row lock hold per send** (from `FOR UPDATE` until the end of
the transaction body), p50 / p95 ms:

| case | old | new |
|---|---|---|
| steer into a running turn | 3.99 / 7.31 | 2.89 / 4.14 |
| queue behind a running turn | 3.16 / 7.85 | 2.18 / 5.26 |
| first message to an idle (ready) thread | 4.38 / 6.44 | 3.95 / 10.41 |
| first message right after `CreateThread` | 3.84 / 8.58 | 5.22 / 11.48
¹ |

¹ Old: 0/35 of these turns were dispatched in the admission (the thread
was still `creating`, so the turn waited for `thread_ready` and a later
pump). New: 35/35. The ~1.5 ms of checks before the lock lets
`thread_ready` land first, so `StartTurn` is built under the lock and
the turn starts without waiting for the pump. More work under the lock,
earlier start.

**Another write to the same thread** (`SELECT … FOR UPDATE` issued 0 ms
after the send), wait p50 / p95 ms:

| case | old | new |
|---|---|---|
| idle | 3.48 / 4.84 | 0.76 / 1.00 |
| steer | 5.28 / 8.76 | 0.70 / 1.56 |
| queue | 4.21 / 9.96 | 0.68 / 1.42 |

**Pool usage with slow checks**: N sends to one thread with their checks
held open (the attachment-limits read paused), then another write to the
thread with `lock_timeout=1s`:

| paused sends | old: connections in a transaction | old: other write |
new: connections in a transaction | new: other write |
|---|---|---|---|---|
| 1 | 2 | lock timeout (1 s) | 0 | ok, 2.1 ms |
| 4 | 5 | lock timeout | 0 | ok, 1.8 ms |
| 8 | 9 | lock timeout | 0 | ok, 2.3 ms |

Old: only the first send reached its checks; the others queued on the
lock. New: all N check in parallel.

**Slow linked sends**: on the sending computer nothing changes (it never
held a transaction across the forward; the drafts path already verifies
this). On the home computer, the linked-send test shows 4 concurrent
paused sends hold 0 connections on either computer, and the home thread
stays writable.

**Send latency**, p50 / p95 ms: steer 5.09 / 8.55 → 5.11 / 9.93; queue
4.66 / 10.15 → 4.72 / 10.40; idle ready thread 6.23 / 8.69 → 6.51 /
14.04. A burst of 8 concurrent sends to one running thread: wall time
p50 33.3 → 26.7 ms. Single-send latency is unchanged within noise. The
steps add one indexed lock query, but the full `threadSelect` re-read
under the lock is gone.

## Guarantees and concurrency

- Idempotency: receipt under the lock in its own statement, plus native
dedupe (`turns`/`turn_steers` by `client_request_id`) before the checks
and again under the lock. Covered by concurrent identical sends and
concurrent identical `/goal`.
- Order and "turn already running": decided under the lock
(`steerTarget`, queue ordinal). Tests: 6 concurrent sends give ordinals
1–6 with exactly one `StartTurn`; 3 concurrent steers all join the
running turn.
- Archive, delete or rewind committed while the checks run: admission
sees the changed state under the lock, validates again, and refuses. One
test per case.
- Crash safety: admission, `StartTurn` in the outbox and the receipt
commit in one transaction. A failed receipt write leaves no turn and no
command, and a retry admits once. A gateway restart between admission
and delivery delivers the turn exactly once, and the same request
replays the same turn.
- Worker reconnect: unchanged outbox redelivery (`StartTurn` is
idempotent by `turn_id`).
- Drafts reconcile: unchanged. Receipts and native rows are written as
before (`composer-drafts` tests pass).
- Callers with their own transaction (bot actions, linked agent calls)
still run every step inside it.

## Review fix: inputs outside the thread row

PR citations were not revalidated after a concurrent unlink. The key now
includes `pull_request_revision`, which every link, unlink and
repository-account change bumps. It also includes whether an import is
in progress (import transactions lock the thread but write
`import_items`). Audit of every other input the checks read:
- **Attachments:** bound by a conditional `UPDATE … WHERE thread_id IS
NULL` during admission, under the lock.
- **Quote-source threads, mention targets, model catalogs, worker
capabilities, the full-access check:** their writers never locked this
thread's row, so the send's ordering against them is the same as before.

I kept an explicit key rather than a whole-row version (`xmin`): ingest
bumps `threads.last_seq` on every event batch, so steers during a
running turn would revalidate under the lock almost every time.

New test: `github-citations.test.ts` › an unlink that commits while a
checked citation waits for admission refuses the message. It fails on
the previous head (the message was accepted) and passes now.

The lock-ordering tests in `thread-range-send-locks.test.ts` now find
the blocked sender by `pg_blocking_pids` instead of its SQL text.

## Tests

- `tests/integration/message-admission.test.ts`: slow checks hold no
lock or connection; archive/delete/rewind races; concurrent queue/steer
ordering; concurrent `/goal`; receipt failure rollback; restart between
admission and delivery.
- `tests/integration/message-admission-linked.test.ts`: 4 slow linked
sends A→B; no held connection on A or B; the home thread stays writable.
- Against `dev`, the slow-check and race tests fail (lock timeout / the
race blocks on the held lock), so they catch the old behaviour.
- Existing `message-receipts` and `composer-drafts` tests pass
unchanged.

## Copy audit

No UI text changes. Error messages are unchanged.

Related: #664

## Checks (local)

`bun install`, `gen:check`, `typecheck`, `lint`, `format:check` and the
web build are clean. `check:tmp`: 2967 pass, 175 skip, 2 fail. Nothing
was left in the temp dir. The 2 failures were
`thread-range-send-locks.test.ts`, which finds the blocked sender by the
lock query's SQL text (`AND owner_user_id=`). The second commit restores
that query shape; both tests and `message-receipts` then pass. The full
suite was not re-run after that commit; CI covers it.
nixuuu added a commit that referenced this pull request Nov 14, 2026
nixuuu added a commit that referenced this pull request Nov 14, 2026
nixuuu added a commit that referenced this pull request Nov 14, 2026
Unsent composer drafts now sync after 1.5 seconds of idle typing and on
blur, backgrounding, or navigation. The receiving device chooses **Take
over**, including attachments and citations. The source clears only an
unchanged saved revision; later edits fork into a new draft and remain
editable.

The incoming indicator replaces the computer label in the existing
composer metadata slot. **Open drafts** moves to an icon in the sidebar
footer, removing the permanent action row on web and mobile. Sidebar
markers include drafts from other devices across every page. Nonempty
composers offer **Append draft** or explicit **Replace local draft**.

Related: #664

The additive protocol returns content-free take-over receipts and thread
IDs for sidebar markers. Migration 0142 stores receipts for 30 days,
scoped to owner and source device, so source reconciliation still works
after the receiver saves or sends. Existing CAS, fork-on-conflict, send
fencing, recovery, and short delivery transactions remain intact.
Cross-tab adoption retires stale composers; mobile refreshes again if an
invalidation arrives during an outstanding read.

Validation:

- `bun install`, `bun run gen:check`, full workspace typecheck, lint,
formatting check, and the production web build passed. Focused runs use
`nice` and private disk-backed temporary storage.
- 47 focused gateway/schema tests plus 4 local draft-store tests passed
through `check:tmp`, with no leftover test directories. Coverage
includes one save per typing burst, blur flush, delete, durable source
receipts, owner scoping, edit/send races, and invalidation during a page
read.
- Browser review used an isolated synthetic gateway and database:
light/dark, 1280 px desktop and 390 px phone, short and long prompts and
device names. Appending preserves local text. Two actual composers
confirmed that an unchanged source clears, later edits survive a
delayed-save race, and the source remains editable. No horizontal
overflow or page errors. The removed push action is absent.
- iOS and Android exports and mobile typecheck passed. Fingerprints
match the dev baseline: iOS `138e0c6b171c82b4933e86808cdfef56da73b8c6`;
Android `906dc944f94eb8333fa384ed9f198834fdd30d13`. Native configuration
and dependencies are unchanged. Device checks remain blocked as
specified.

Copy audit (§8): “Continue on another device” → automatic sync removes
an unnecessary decision. “Continue” / “Continue here” → “Take over”
makes the move explicit. “Append draft” / “Replace local draft” name the
nonempty-composer choices. “Draft taken over on …” and “Your edits are
kept here” explain the source outcome. Actions start with verbs, use
sentence case, and convey meaning without color. Long device names
truncate within one existing line; append/replace labels remain readable
at phone width. No new glossary term or decorative copy.

Review follow-up:

- Composer hints match the full thread/project/workspace/parent target;
take-over also rejects a mismatched target before claiming it.
- Source notices clear on the next edit, send or new incoming hint.
Mobile adds **Dismiss** within the same single line.
- Listing uses ordinary reads without row locks. Both clients cap source
receipt IDs at 100, newest first, and the gateway truncates oversized
requests.
- The threads documentation now states automatic sync, 30-day retention
and visibility restricted to the owner's devices.

Follow-up validation: 33 focused gateway/linked-draft/domain tests
passed through `check:tmp`, including full target isolation,
input-change detection, bounded receipt requests and sending while a
list transaction remains open. Workspace typecheck, lint, formatting,
web build, and iOS/Android exports passed. Both native fingerprints
still match the dev baseline recorded above. No new browser or device
review was performed for this follow-up; the browser evidence above is
from the original implementation. Device checks remain blocked.

Copy audit follow-up (§8): mobile source notice without an action →
source notice with **Dismiss**, matching web. The action uses a verb and
sentence case, has a visible text label and adds no explanatory copy or
extra row.
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