Skip to content

feat(web): opt-in device priority for multi-device sessions - #864

Open
HadrienKerlero wants to merge 2 commits into
Ark0N:masterfrom
HadrienKerlero:feat/device-priority
Open

HadrienKerlero wants to merge 2 commits into
Ark0N:masterfrom
HadrienKerlero:feat/device-priority

Conversation

@HadrienKerlero

Copy link
Copy Markdown
Contributor

Problem

When a session is open on a computer and the same Codeman is then opened on a phone, both browsers send resizes and keystrokes into the same tmux panes. The phone shrinks the terminal under the computer, and the two devices fight over the geometry for as long as both are open.

Change

An opt-in Device priority setting under Settings → System → Device priority (synced uiPriorityEnabled, off by default).

While it is on, one browser tab per user holds the UI priority lease. Only that tab types into and resizes the terminals, across all sessions:

  • Opening Codeman somewhere else asks "Codeman is open in another window – Take priority here?". "Not now" leaves the tab behind a Take priority overlay.
  • Taking priority pauses the other tab behind "Another window has priority" with Take back priority, and the terminal snaps to the new device's size.
  • Each browser tab is its own device. A pop-out opened from Codeman shares its opener's priority.
  • Reloading the holder keeps priority. Closing it frees the lease after 45 s.

While it is off, every gate takes its legacy untagged path: no prompt, no overlay, every window types and resizes as in 1.52.0. Switching it applies immediately to every open window, without a reload.

Server

  • src/web/ui-priority.ts: UiPriorityRegistry, one in-memory lease per username (one global lease in single-user mode). setEnabled clears holders and broadcasts a neutral { holder: null, enabled } state to every SSE client.
  • GET /api/ui-priority, POST /api/ui-priority/claim, SSE ui:priorityChanged, and error code NOT_PRIORITY_HOLDER (409).
  • Gated only for tagged browser callers (X-Codeman-Tab on HTTP, tab= on WS/SSE): session /input, /send-key, /resize, and approval /answer.
  • A refused sequenced WS frame closes the socket with 1013 and applies no later frame, so no later seq can move the dedup watermark past the refused one. The browser reconnects and resends in order.
  • Mux input that loses priority after its paste but before Enter answers 409 with "input was partially applied and Enter was withheld", and its seq stays consumed. That way a replay never types it twice.

Client

  • src/web/public/ui-priority.js: tab identity is frozen (sessionStorage + BroadcastChannel duplicate check) before any transport starts, and reliable-input storage and dedup are scoped per tab.
  • A refusal triggers a refetch, never a blind queue clear. Refused input stays queued and undrained until an accepted snapshot resolves it.
  • The HTTP drainer owns transport handover until its outstanding POST settles.

Not gated

API scripts, CLI automation, MCP, service-worker actions, and codeman tui attach send no tab id and behave exactly as before. This is cooperative UX between your own tabs, not a security boundary (documented as such).

Docs

docs/api-reference.md, docs/architecture-invariants.md (#per-tab-ui-priority), docs/wiki/{Settings-Reference,Mobile-Guide,Multi-User-Mode,HTTP-API}.md, CLAUDE.md, src/web/CLAUDE.md, a README feature bullet, and a minor changeset. No version bump, no CHANGELOG.md edit.

Verification (on 6db166f3, current master)

  • npm run typecheck, lint, format:check, check:frontend-syntax, check:browser-excludes, and npm run build pass.
  • npm test: 17,913 passed, 4 failed, 13 skipped.
    • frontend-public-tooling ("Spreadsheet preview assets are missing") and spreadsheet-preview-worker also fail on unmodified 6db166f3 on this machine.
    • tui-e2e timed out once under full-suite load. It passed 3/3 on this branch and 2/2 on 6db166f3 when run alone.
    • terminal-pty-geometry broke because Prettier reflowed the session.resize(...) call that it pins as text. The call is back on one line; that file and the other 24 that read the changed sources as text pass (856 tests).
  • New or updated tests: registry enable/disable transitions, routes, settings schema/UI/zh-CN, SSE backpressure retention for priority frames, WS stale-pass and arrival-refusal barriers, frontend disabled/enabled snapshots, and refusal recovery after a failed refetch.
  • Two-tab headless browser check (computer-size and phone-size): prompt, overlay, take back, reload keeps priority, the settings switch on and off, keyboard focus kept in the dialog. In that run the geometry went 165×37 → 62×47 → 165×37.

Known limits

  • codeman tui attaches to tmux directly, so it can still type and resize.
  • In multi-user mode each account has its own lease.

Add a synced Settings → System → Device priority switch (`uiPriorityEnabled`, off by default).
While on, one browser tab per user holds a lease that gates tagged terminal input and resizes
across all sessions, so a phone no longer shrinks the sessions open on a computer; other tabs
pause behind a Take priority overlay. While off, every gate takes its legacy untagged path.

- Server: UiPriorityRegistry (src/web/ui-priority.ts), GET /api/ui-priority, POST /api/ui-priority/claim,
  ui:priorityChanged SSE, NOT_PRIORITY_HOLDER (409) on input, send-key, resize and approval answers.
- A refused sequenced WS frame stalls the socket (1013) so no later seq can pass the dedup watermark.
- Client: per-tab identity frozen before transports start, pop-outs inherit their opener, refused
  input stays queued until an accepted snapshot resolves it.
- Untagged API callers, CLI automation and `codeman tui` are never gated.
@Ark0N

Ark0N commented Nov 28, 2026

Copy link
Copy Markdown
Owner

Thanks for this, Hadrien. The PR adds an opt-in Device priority setting: only one browser tab per user types into and resizes the terminals, so a phone no longer shrinks the sessions open on a computer.

The server side is well built. Stalling the WS and closing it with 1013 after a refused seq is a sound answer, because no later frame can then move the dedup watermark past it. The partial-paste outcome and the revalidation in the wake buffer and the SubmitVerifier are handled with care, and the test suite is thorough. Typecheck, lint, format, the frontend checks and the full npm test gate pass here. The one red test is a sandbox chown issue in file-write-routes and is unrelated to this PR.

Separately from the review, one question is still open on my side. This is a large new subsystem that did not go through an issue or Discussion first, so whether it ships as a built-in feature is still my decision to make. The points below apply either way.

Needs a fix before merge

  1. Reliable input with the setting off (src/web/public/app.js:4642, :4661, :1019, :1023; src/web/public/ui-priority.js:72). The durable queue now lives under codeman:pendingInput:<tabId>, and the tab id comes from sessionStorage. A page that starts with empty sessionStorage gets a fresh id, which covers a new tab and a phone PWA that the OS killed and the user relaunched. UnACKed input from a closed tab or a killed PWA is therefore never redelivered, where 1.52.0 delivered it on the next load. On top of that, pagehide and visibilitychange persist unconditionally, so every tab leaves behind a key that nothing removes, and localStorage grows without bound. All of this happens with uiPriorityEnabled off.

    Please keep the per-tab dedup id, but make the store recoverable and bounded. One way to do it is to keep the entries under one key with a last-seen stamp per tab id. On boot, adopt any entry whose tab id nobody answers for on your existing who probe, then delete it. Drop a tab's entry once its queue is empty (the server's dup/last watermark already recovers a reset counter), and prune stale entries by age. One test for close-then-reopen redelivery and one for pruning would pin it down.

Smaller items

  1. Startup wait (src/web/public/ui-priority.js:53, app.js:1230, api-client.js:24). acquireTabId() always sleeps for the full 200 ms probe window, and SSE, WS, tiles and every _api() call wait on it. Input and resizes are then held until the first snapshot arrives, and the disabled snapshot does not resend a resize that was dropped in that window (terminal-ui.js:7166). Please start the transports with the stored id while the probe runs, re-keying only on a collision as your bfcache path already does. For resizes, treat "no snapshot yet" like "disabled", since the server refuses a non-holder anyway.
  2. Please add a @fileoverview to src/web/ui-priority.ts and src/web/routes/ui-priority-routes.ts, since the route discovery grep in CLAUDE.md relies on it. The wire types (UiPriorityState, UiPriorityHolder, UiPriorityClaim) should also move into a src/types/ file.
  3. Docs and changeset. docs/reliable-input-delivery.md:24-29 and the Input paragraph of the root CLAUDE.md still describe the browser-wide codeman:clientId dedup id and the single codeman:pendingInput key. The changeset says nothing changes while the setting is off, but these changes ship to everyone, so please name them there: the per-page SSE clientId (a welcome fix for the cross-tab SSE eviction), the per-tab dedup id and storage, the Stop button's Ctrl+C moving to _sendInputEphemeral, and tile Shift+Enter going through the input FIFO.
  4. In src/web/public/gesture/gesture-codeman.js:5, a comment now names ../.codeman/app/node_modules/... from a local rebuild. Please revert that line.
  5. The new section in docs/architecture-invariants.md:9 sits at the top of the file. It belongs next to the input-delivery and WS-resilience section it extends.

Item 1 is the one that blocks the merge, and once it is fixed this is ready for another review. Items 2 to 6 are small. If you would rather leave 5 and 6, I can apply them at merge time.

- Add @fileoverview to src/web/ui-priority.ts and src/web/routes/ui-priority-routes.ts.
- Move the UI priority wire types to src/types/ui-priority.ts (barrel re-export).
- Send resizes before the first priority snapshot (_uiMaySendResize) at all eight resize gates;
  input still waits for the snapshot.
- Docs: per-tab dedup id and storage in reliable-input-delivery.md and CLAUDE.md; move the
  invariants section next to input delivery; list the always-on changes in the changeset.
- Revert the local-path comment in gesture-codeman.js.
@HadrienKerlero

HadrienKerlero commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the review, Ark0N. I pushed 75f39af with items 3 to 6 and the resize half of item 2. For item 1, and the startup wait that depends on it, I'd like your call before building, because the safe version is bigger than the sketch suggests. Details below.

Fixed in 75f39af

  • 3. @fileoverview and types. src/web/ui-priority.ts and src/web/routes/ui-priority-routes.ts now have @fileoverview blocks, so the route discovery grep finds them. UiPriorityState, UiPriorityHolder, UiPriorityClaim and UiViewport moved to src/types/ui-priority.ts, re-exported from the src/types barrel and listed in its module table.
  • 4. Docs and changeset. docs/reliable-input-delivery.md and the root CLAUDE.md Input paragraph now describe the per-tab dedup id (<clientId>.<tabId>) and the codeman:pendingInput:<tabId> key. The changeset now lists the changes that ship with the setting off: the per-tab dedup id and storage, the per-page SSE clientId, the Stop button's Ctrl+C moving to _sendInputEphemeral, and tile Shift+Enter going through the input FIFO. If item 1 changes the store, I'll update both again.
  • 5. The gesture-codeman.js line is reverted to master.
  • 6. The section moved under "Session data and lifecycle", right after "Input delivery and WS resilience", as ### Per-tab UI priority. The #per-tab-ui-priority anchor is unchanged.
  • 2, resizes. A new _uiMaySendResize() treats "no snapshot yet" like "disabled". All eight resize gates use it: _startMobileResizeRetry, throttledResize, sendResize, tile fit and _sendResize, runShell, attachDiscoveredSession, and the _api resize path. A first resize is no longer dropped while the page waits for its snapshot. Input keeps the stricter _uiHoldsPriority().

Checks on 75f39af: typecheck, lint, format:check, check:frontend-syntax and check:browser-excludes pass. The 112 test files that touch the changed code pass, except frontend-public-tooling, which also fails on unmodified master on my machine ("Spreadsheet preview assets are missing"). That includes a new test for the resize rule, in test/ui-priority-frontend.test.ts.

Item 1: a question before I build it

You're right on all counts: a fresh tab id strands the unACKed input of a closed tab or a killed PWA, and the per-tab keys are never removed. Before writing it, I had the fix designed and then reviewed twice. Done literally, the sketch can type a command twice or lose input. Here is why:

  1. Restored records and the dup branch. Records reloaded from storage get tries: 0. If the original frame was applied and only its ACK was lost, the first resend gets dup:true, and _onWsInputAck treats tries <= 1 as genuinely lost and resends the text under a new seq. The command runs twice. (1.52.0 has this across a reload too, but adopting another tab's queue makes it the normal recovery path.) So recovered records must keep their original (clientId, seq) and must not go through that branch. Replaying them over POST is the simplest way, since a POST completion maps to exactly one record; merging them into the current tab's WS queue would need per-clientId ACK routing, because WS ACKs carry no clientId.
  2. Dropping a tab's entry when its queue empties. That resets the counters, and only WS has dup/last to recover. A POST duplicate answers 200 {} without the watermark, so the client deletes fresh input that the server skipped. The counters have to stay, which is a few bytes per tab, pruned by age.
  3. Two tabs opening at once can both "adopt" the same orphan, since neither answers who for it yet. A localStorage read-check-write is not atomic across tabs, and recovering while the old tab writes can erase input it just queued. Web Locks would fix this, but WebKit releases them when a page is suspended or goes into the bfcache, and they don't exist on plain-HTTP LAN origins. So they can't carry correctness.
  4. Two recoverers replaying the same tuple over POST is safe only while the first attempt has finished: POST /input consumes the watermark before its awaited write. A concurrent duplicate gets 200 and drops the record, and then the first write can still fail and refund the seq.

That leaves two shapes:

  • A, close to your sketch: keep the per-tab dedup id; keep compact counters; on boot, replay unanswered orphans' records over POST with their original (clientId, seq) before draining that session's new input; delete the payload once it is delivered; prune by age. Residual risk: the races in 3 and 4. Two tabs opening at the same instant over the same orphan, or a suspended Safari tab waking after its queue was taken, could resend one unconfirmed batch.
  • B, transactionally coordinated: the same, plus a transactional claim (IndexedDB) for orphan ownership, staging and the aggregate size bound, and a small server guard in POST /input. A second tagged POST for the same (clientId, session) while one is in flight would answer retryable 409 instead of duplicate 200, and a failed tagged write would not answer 200. Normal WS pipelining stays as it is. This closes the races in A, but keeps the limits 1.52.0 already has: the server's dedup watermark is in memory (lost on restart, and capped at 256 clients per session), and a mux write whose outcome tmux itself can't report stays ambiguous. It is noticeably more code.

Which would you prefer? Or would you rather keep item 1 out of this PR, or have this ship as something other than a built-in feature, given your open question about that? Once you choose, I'll build it with the close-then-reopen and pruning tests you asked for, and the remaining part of item 2: starting SSE, WS, tiles and _api while the who probe runs. That part depends on how the store settles the identity, which is why I haven't done it yet.

@Ark0N

Ark0N commented Nov 29, 2026

Copy link
Copy Markdown
Owner

Thanks for the quick follow-up, Hadrien. This PR adds an opt-in Device priority setting, so only one browser tab per user types into and resizes the terminals.

75f39af covers what you listed. Item 3 has the @fileoverview blocks and the move to src/types/ui-priority.ts, item 4 the docs and changeset, item 5 the gesture-codeman.js revert and item 6 the invariants section next to input delivery. _uiMaySendResize() handles the resize half of item 2. Typecheck, lint, format, the frontend checks and the full npm test gate pass here, and CI is green. One test failed in my run, file-write-routes (a sandbox chown), and it fails the same way on master.

About your question on item 1: two decisions are still open on my side. One is from my earlier comment: whether Device priority ships as a built-in feature. The other is the shape of the item 1 store: A, B, or keeping it out of this PR. I checked your points 1, 2 and 4 against the code and they are accurate. _onWsInputAck resends a dup with tries <= 1 under a new seq, a POST duplicate answers 200 {} with no watermark, and POST /input consumes the seq before its awaited write and refunds it on failure. Whichever shape it takes, the merged PR must not keep what happens today with the setting off: the unACKed input of a closed tab or a killed PWA is never redelivered (src/web/public/app.js:4642), and the codeman:pendingInput:<tabId> keys are never removed (app.js:1019). The rest of item 2 is the 200 ms who wait before SSE, WS, tiles and _api() start (src/web/public/ui-priority.js:74, app.js:1230, api-client.js:24). It depends on that identity, so it waits for the same decision.

Three small things from this pass. They can go in the same push:

  1. A pop-out shares its opener's reliable-input identity (ui-priority.js:59, app.js:4642, app.js:4658). Both pages persist to the same codeman:pendingInput:<tabId> key, so the last writer wins. After a re-dock, the opener's seq counter for that session collides with the pop-out's watermark, and a POST fallback answers that with 200 {} and drops the input. Please use the inherited id only for the lease (X-Codeman-Tab, tab=) and keep a per-page id for the reliable store and _inputClientId, or cover pop-outs in the item 1 store. Either way, the changeset line "Each browser tab now has its own reliable-input identity" should match what lands.
  2. On the first load after the upgrade, app.js:4661 deletes the 1.52.0 codeman:pendingInput queue, and any input that was unACKed at that moment is lost. Deleting is safer than replaying it under the new id. The item 1 store can instead treat it as one more orphan and replay it over POST with the bare legacy clientId it was sequenced under. If it stays a plain delete, please name the one-time drop in the changeset.
  3. The Approvals drawer sits outside <main>, so a paused tab can still press Answer. _api() refuses that client-side (api-client.js:27), and answerApproval then shows "Could not answer, the prompt may already be resolved" (approvals-ui.js:131), which points at the wrong cause. Please say that another window has priority instead, for approval answers and for the Read My Mind send.

Item 1 still blocks the merge. When the open decisions are made and item 1 plus the rest of item 2 are in, this is ready for another review.

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.

2 participants