You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix: stop stale project sockets from disabling chunk merging - #2774
Chunk merging (chat.messageMergingEnabled, #2760) has been on in production since 2026-11-15 23:07Z, with no drop in rows written per ingest call. One confirmed cause: the ProjectData Durable Object switched merging off for every session while any connected socket without message-append-v1 had no sessionId. Every web bundle older than #2760 keeps such a project-level socket open (the session list), and the SPA never reloads itself, so one stale tab or phone switched merging off for the whole project. Each admission of such a socket also cleared the open merge row of every session.
This PR:
Project sockets no longer get transcript frames.message.new, messages.batch and message.append go only to sockets subscribed to that session. No project-socket consumer has ever read them (audit below).
Project sockets no longer affect merging, and admitting one no longer seals anything.
A legacy session socket still switches merging off, for its own session only (unchanged).
message.append is checked against the socket's capability when it is sent. A legacy session socket can be admitted while a merged batch awaits its side effects (attention resolution, recalculateAlarm), after the batch-start check. Such a socket is now closed with code 4409 instead of receiving an append it would ignore. Pre-Merge streamed assistant chunks during message persistence #2760 clients reconnect on any close other than 1000 and re-read the newest messages, replacing rows by ID, so they end with the complete text without a reload. Re-admission seals the session, so later batches stay unmerged while it is connected.
Why close instead of sending something else: a pre-#2760 chat view has no frame that updates a row it already holds (its live merge skips known IDs). A synthetic delta row was rejected because the old client's window replace keeps rows at or after the window's newest timestamp, so it could duplicate text after a reconnect.
Socket admission, the merge gate and broadcast move to packages/project-data/src/do/session-sockets.ts (index.ts shrinks). sealMessageStream now requires a session ID; its all-sessions form had no other caller.
message.new, messages.batch; reconnects and re-reads on any non-1000 close
chat hook before 47ff45302 (2026-03-12)
unscoped
out of support (eight-month-old bundle; its send path is already rejected)
No other client (packages/acp-client, CLI, vm-agent, harness) uses the route. All transcript broadcasts pass a session ID (message-persistence.ts, durability-foundation.ts, idle-cleanup.ts, reconciliation.ts, reconciliation-episode.ts, wake-failure.ts).
Known residual (tracked)
A legacy chat tab that read the transcript over REST just before its first socket admission, with an append landing in between, keeps the shorter row until its next reconnect or reload: its first-open catch-up reads only newer rows. The brief scoped the guarantee to text arriving after the socket appears. Tracked in tasks/backlog/2026-11-16-legacy-chat-pre-admission-append-gap.md.
Validation
pnpm lint (full, exit 0)
pnpm typecheck (full, exit 0; pnpm build full exit 0)
pnpm test: targeted locally (project-data unit 539/539; 7 related workers files 50/50); full suite in CI on the ready head (all shards green)
New apps/api/tests/workers/project-data-socket-merge-gate.test.ts (6 tests) and packages/project-data/tests/unit/session-sockets.test.ts (5 failure-isolation tests). Sockets open through the authenticated GET /api/projects/:id/sessions/ws route with a real session cookie; chunks arrive through the reporter callback POST /api/workspaces/:id/messages on a reserved workspace:
Legacy project socket admitted mid-reply: the session still merges (one stored row), the socket receives no transcript frame and still receives session.updated.
Capable project socket: no transcript frames, still lifecycle.
Legacy chat socket: its session stores individual rows; another session that was mid-reply when it connected still merges (seal scoped).
Capable chat socket admitted mid-reply: does not seal, receives message.append, rebuilds the stored rows exactly, is not closed.
Race: the batch is held at its awaited recalculateAlarm midpoint after commit, a legacy chat socket is admitted, then released. It receives no append, is closed with 4409, and a model of the pre-Merge streamed assistant chunks during message persistence #2760 client ends with the complete text; a capable socket on the same chat still gets the append. Its reconnection keeps merging off; once it leaves, merging resumes. (The hold widens a real window: any await between commit and broadcast.)
Merging off: individual rows and frames as before, no append, no close.
Guards proven discriminating (each removed once, then restored byte-identical):
Guard removed
Tests that went red
no transcript frames to project sockets
1, 2
merge gate counts only session sockets
1
no seal on project-socket admission
1
session gate for legacy chat sockets
3, 5
send-time capability check on message.append
5
close for resync (append dropped silently instead)
5
gate counts only OPEN sockets (a resync-closed socket lingers in CLOSING)
5 (merging-resumes control)
Existing suites green: project-data-message-merge (incl. the billed-write snapshot, unchanged), workspace-message-merge-startup, project-data-message-merge-upgrade, acp-session-created-broadcast, session-access-changed-broadcast, session-access-expiry (50 tests); packages/project-data unit suite 534/534. project-data-broadcast.test.ts asserted the old contract (project socket gets message.new) and now asserts the new one.
Billed writes: unchanged on the ingest path (snapshot green). Admission of a legacy project socket no longer runs an all-sessions seal UPDATE, so it writes fewer rows.
Staging Verification (REQUIRED for all code changes — merge-blocking)
Staging deployment green (staging2, run 43787757440 on 0f104be17: deploy and smoke tests passed)
Live app verified via Playwright (staging2 staging2-agent-admin via workload identity; real Chromium)
Existing workflows confirmed working (project create, Instant chat start, follow-up prompts, chat page render at 1280 and 375)
New feature/fix verified on staging (below)
Infrastructure verification completed: N/A: no infra changes
Mobile and desktop verification notes added for UI changes: N/A: no UI changes
Staging Verification Evidence
staging2 (primary refuses main-based branches: DO migration tag v23 from unmerged #2721, run 43778055734). chat.messageMergingEnabled was at its default (off); set on for the run and reset to default afterwards. One Artifacts project, one Instant (cf-container) Claude Code session, no VM. Sockets opened by the real browser WebSocket against wss://api.sammy2.party/api/projects/:id/sessions/ws. Counts and hashes only:
Turn
Sockets connected
Assistant rows stored
Assistant chars
1
legacy project socket (no sessionId, no capability)
2 (86 + 2,525 chars): merged
2,611
3
legacy session socket on this session, capable session socket, legacy project socket
196: merging off for this session
2,492
Legacy project socket: 0 transcript frames over both turns; still received session.created/updated/activity, activity.new, mailbox.*. Never closed.
Legacy session socket (turn 3): 34 messages.batch + 1 message.new, 0 message.append, not closed; the text it received (old-client rebuild) hashes identically to the stored assistant text (1764a96e…), all row IDs present.
Capable session socket: same frames, open throughout.
Turn 2 was not measured: my wait helper ended early (script bug, not product behaviour); turn 3 repeats it with a corrected wait.
The 4409 resync close needs a socket admitted inside a batch's commit-to-broadcast window, which cannot be timed by hand on a live system; it is covered by the held-batch race test in real workerd.
Screenshots of the chat at 1280 and 375 reviewed: transcript renders normally.
Cleanup: session stopped, project deleted (GET 404), workspace and node GET 404, merge and row-usage settings source: default.
UI Compliance Checklist (Required for UI changes)
N/A: no apps/web, packages/ui or packages/acp-client changes.
End-to-End Verification (Required for multi-component changes)
Data flow traced from user input to final outcome with code path citations
Capability test exercises the complete happy path across system boundaries
All spec/doc assumptions about existing behavior verified against code
Gaps documented below
Data Flow Trace
Browser opens GET /api/projects/:id/sessions/ws → apps/api/src/routes/chat.ts (chatRoutes.get('/ws'), project access) → projectDataService.forwardWebSocket → ProjectData.fetch → admitBrowserSocket (session-sockets.ts): tags session:<id> and/or message-append-v1; legacy chat sockets seal their session.
Reporter posts chunks → POST /api/workspaces/:id/messages → ProjectData.persistMessageBatch → hasLegacySessionSocket(ctx, sessionId) → persistMessageBatchWithSideEffects → MessageStreamBatch (merge) → awaited side effects → broadcastEvent → broadcastToBrowserSockets: transcript frames to session sockets only; message.append only to capable sockets, legacy ones closed with 4409.
The pre-admission window above (tracked). The old-client behaviour is modelled in the test from the pre-#2760 source (7bea824b9^), not run from that bundle; staging verification uses a real socket without the capability.
Post-Mortem (Required for bug fix PRs)
What broke
With merging on in production, one browser tab or phone still running a pre-#2760 web bundle switched chunk merging off for every session in its project, so rows written per ingest call did not drop.
Root cause
#2760 (7bea824b9) treated an unscoped socket as watching every session ((!sessionTag || …) && !capable in persistMessageBatch), because broadcastEvent did send it every session's transcript frames, although no project-socket consumer reads them. It also checked capability only at batch start, leaving a race with sockets admitted during the batch's awaits.
Class of bug
A capability gate keyed on what the server sends rather than what the client consumes; and a check-then-act across an await in a Durable Object (rule 45).
Why it wasn't caught
Tests covered a legacy session socket but no project socket, and none admitted a socket between a batch's commit and its broadcast. The rollout's first production samples could not separate "merging refused" from "little eligible traffic" because no counter recorded refusals (#2773 adds them).
Process fix included in this PR
The contract is documented at the module that enforces it (session-sockets.ts) and in the public API reference; tests pin each guard. No new rule file: rule 45 (DO await interleaving) and rule 62 (reach the feature the way production does) already cover the class.
Specialist Review Evidence (Required for agent-authored PRs)
All local reviewers completed and findings addressed before merge
If any reviewer did NOT complete: needs-human-review label added and merge deferred to human (N/A: all completed)
Reviewer
Status
Outcome
security-auditor
ADDRESSED
PASS, 0 CRITICAL/HIGH. LOWs: repeated resync close/log per append (fixed: closing sockets skipped), uppercase sessionId tag mismatch (fixed: lowercased), doc frame split (fixed). Accepted: a project member can hold merging off for one session with a capability-less socket (cost only, already able to read the transcript; previously project-wide). 0f104be17
cloudflare-specialist
ADDRESSED
PASS, 0 CRITICAL/HIGH. MEDIUM: broadcast could throw after commit on a closing socket (fixed: per-socket isolation, unit tests). LOW: race-test hang/flake risk (fixed: try/finally, 10 s loud waits). Double close in webSocketClose made quiet. 0f104be17
test-engineer
ADDRESSED
No blockers. Added: capable admission mid-reply does not seal, seal scoped across sessions, capable socket during the race, merging-resumes control (which found the CLOSING-socket gate bug, fixed), loud settle, pinned close code, unit failure-isolation tests. 0f104be17
doc-sync-validator
ADDRESSED
PASS for api.md/admin-settings/route comment. Fixed stale useProjectWebSocket JSDoc; removed unused ProjectWebSocketEvent type that listed message.new; precision edits. 0f104be17
task-completion-validator
ADDRESSED
WARN (bookkeeping only): checklist ticked, discrimination table and residual path recorded in the task file, bundle audit note added. Staging pending. 0f104be17
CodeRabbit Review Evidence (Required for agent-authored PRs)
CodeRabbit requested when the PR was marked ready for review
Waited about 15 minutes (or until a skip, rate-limit or quota reply)
Either CodeRabbit reviewed and no CodeRabbit feedback is unresolved, or it did not review and the observed outcome is recorded below
CodeRabbit Notes
Requested at 2026-11-16T01:40:53Z by applying coderabbit-review when the PR was marked ready (trusted workflow run 43787665763 succeeded). CodeRabbit reviewed head 0f104be17 and submitted APPROVED at 01:51:49Z with 0 inline comments; no unresolved feedback. The later commit 5b21ad4a1 only moves the task file to tasks/archive/.
Exceptions (If any)
Scope: task file kept on the branch instead of a direct commit to main.
Rationale: a task-file-only push to main triggers main CI and a production deploy while other deploys are queued.
Expiration: this PR.
Agent Preflight (Required)
Preflight completed before code changes
Classification
external-api-change
cross-component-change
business-logic-change
public-surface-change
docs-sync-change
security-sensitive-change
ui-change
infra-change
External References
Cloudflare Durable Objects hibernatable WebSocket API (acceptWebSocket tags, getWebSockets(tag), getTags, WebSocket.close(code, reason); application close codes 3000-4999 per RFC 6455 §7.4.2). Behaviour verified in real workerd by the new tests.
Codebase Impact Analysis
packages/project-data (DO socket admission, merge gate, broadcast), packages/shared (close-code constant), apps/api (route comment, worker tests). Web clients are unchanged; both current hooks already send the capability, and the old ones are covered by the reconnect path. Public surface: project sockets stop receiving transcript frames (documented).
Principle XI: the close code is a wire-protocol constant beside the existing capability constant, not a tunable. No settings, defaults or migrations change; chat.messageMergingEnabled is untouched. Risk: a legacy chat tab sees one brief reconnect when it joins mid-reply. WebSocket trust boundary unchanged: route auth, session ID validation and project scoping are as before; the change only narrows what unscoped sockets receive.
Project-wide WebSocket connections now receive non-transcript events across sessions, while transcript messages are delivered only to connections subscribed to that session.
Chat message merging is scoped to individual sessions. Older chat connections that cannot receive merged updates are reconnected so they can reload the complete message.
Documentation
Updated the API and admin guidance to explain WebSocket event delivery, message merging, and browser compatibility behavior.
A browser tab running a web bundle from before chunk merging keeps a
project-level socket open without the message-append capability. The
ProjectData merge gate counted that socket as watching every session, so
one stale tab switched merging off for the whole project, and each
admission sealed every session's open row.
- Transcript frames (message.new, messages.batch, message.append) go only
to sockets subscribed to the session. No project-socket consumer has
ever read them.
- Only a session socket without the capability disables merging, for its
own session.
- message.append is filtered by capability at send time. A legacy session
socket admitted while a merged batch awaits its side effects is closed
with code 4409 instead; old clients reconnect on any non-1000 close and
re-read the newest messages, so they end with the complete text.
Socket admission and broadcast move to session-sockets.ts. Real-workerd
tests drive sockets through the authenticated sessions/ws route and
chunks through the reporter callback route, including a held-batch race.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.
Use the checkbox below for a quick retry:
Trigger review
No actionable comments were generated in the recent review.
Walkthrough
ProjectData now scopes transcript frames and merge gating to session sockets. Legacy session sockets close with code 4409 when they encounter an append frame. Tests and documentation cover project sockets, session sockets, merge behavior, and resynchronization.
Changes: Session Socket Flow
Layer / File(s)
Summary
Session admission and merge gating packages/project-data/src/do/session-sockets.ts, packages/project-data/src/do/message-stream-ingest.ts, packages/project-data/src/do/index.ts
WebSocket admission and stream sealing now use the session ID. An open legacy session socket disables merging for its session.
Transcript frames go only to sockets subscribed to the session. A legacy socket closes with code 4409 instead of receiving an append frame. Project sockets receive non-transcript events across sessions.
sequenceDiagram
participant ProjectDataDO
participant broadcastToBrowserSockets
participant CapableChatSocket
participant LegacyChatSocket
ProjectDataDO->>broadcastToBrowserSockets: Broadcast session message.append
alt Socket advertises message-append-v1
broadcastToBrowserSockets->>CapableChatSocket: Send append frame
else Socket lacks append capability
broadcastToBrowserSockets->>LegacyChatSocket: Close with resync code 4409
end
Loading
Suggested reviewers:raphaeltm
Merge Risk: Minimal · previous review 0f104
This change scopes chat transcript delivery and chunk-merge gating to the session sockets that need them. Stale project-level sockets no longer disable merging. Legacy chat tabs are resynchronized with a 4409 close and recover their messages on reconnect. No concrete merge-blocking defect was found; the one residual gap is documented as follow-up work.
Pre-merge checks: 4
Check name
Status
Explanation
Title check
The title names the main change: project-level (stale) WebSockets no longer cause chunk merging to be disabled. The changeset matches: project sockets stop receiving transcript frames and no longer af…
Description check
The description follows the template. It has a clear Summary with the problem, intended change, and implementation notes. It covers the validation list, a staging verification section (marked pending …
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Full details: Title check
Explanation
The title names the main change: project-level (stale) WebSockets no longer cause chunk merging to be disabled. The changeset matches: project sockets stop receiving transcript frames and no longer affect merging, and only legacy session sockets disable merging for their own session.
Full details: Description check
Explanation
The description follows the template. It has a clear Summary with the problem, intended change, and implementation notes. It covers the validation list, a staging verification section (marked pending with a reason), the data flow trace, untested gaps, the post-mortem, the specialist review table, and the CodeRabbit notes. Some template checkboxes remain unchecked (lint, typecheck, test, and staging items), and the staging, CodeRabbit, and UI evidence fields are not finished. The author explains these gaps, so the description is mostly complete.
Finishing Touches
Generate unit tests (beta)
Commit to this branch
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
A rabbit checks the socket stream, Where session frames now find their team. The legacy tab gets a fresh start, With resync code to play its part. The bunny thumps; the rows align.
Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.
- The merge gate counts only open sockets: a legacy socket closed for
resync stays listed while its close handshake is pending and kept
merging off after it left.
- Broadcast never throws after commit: tag reads and closes are isolated
per socket, and a socket already closing is not closed again.
- webSocketClose/webSocketError tolerate a double close.
- Socket session tags use the lowercase session ID.
- Tests: capable socket admitted mid-reply does not seal; seal stays scoped
to its session; a capable socket on the same chat during the race still
gets the append; merging resumes once the last legacy socket leaves;
settle() fails loudly; close code pinned; unit tests for failure
isolation.
- Docs: precise frame split for project and session sockets, the
pre-admission residual, the project hook JSDoc; remove the unused
ProjectWebSocketEvent type that listed message.new.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.
Resolve persistMessageBatch so the counters describe the new gate:
countLegacySockets() (session-sockets.ts) counts open sockets without the
append capability. Session-scoped ones gate merging and produce
refused.legacy_client; project-scoped ones never receive transcript frames
and are reported in legacyProjectSocketsMax for diagnostics only. The
metrics test and README follow; verified the unscoped expectation goes red
if project sockets gate again.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ve task
- Assert refused.legacy_client is absent for a legacy project socket
(toMatchObject with {} could not prove it).
- Comment why countLegacySockets skips a socket whose tags cannot be read.
- Task file: replace the pre-#2774 expectation that a project socket
refuses, add the staging2 counter results, move to archive.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Chunk merging (
chat.messageMergingEnabled, #2760) has been on in production since 2026-11-15 23:07Z, with no drop in rows written per ingest call. One confirmed cause: the ProjectData Durable Object switched merging off for every session while any connected socket withoutmessage-append-v1had nosessionId. Every web bundle older than #2760 keeps such a project-level socket open (the session list), and the SPA never reloads itself, so one stale tab or phone switched merging off for the whole project. Each admission of such a socket also cleared the open merge row of every session.This PR:
message.new,messages.batchandmessage.appendgo only to sockets subscribed to that session. No project-socket consumer has ever read them (audit below).message.appendis checked against the socket's capability when it is sent. A legacy session socket can be admitted while a merged batch awaits its side effects (attention resolution,recalculateAlarm), after the batch-start check. Such a socket is now closed with code4409instead of receiving an append it would ignore. Pre-Merge streamed assistant chunks during message persistence #2760 clients reconnect on any close other than 1000 and re-read the newest messages, replacing rows by ID, so they end with the complete text without a reload. Re-admission seals the session, so later batches stay unmerged while it is connected.Why close instead of sending something else: a pre-#2760 chat view has no frame that updates a row it already holds (its live merge skips known IDs). A synthetic delta row was rejected because the old client's window replace keeps rows at or after the window's newest timestamp, so it could duplicate text after a reconnect.
Socket admission, the merge gate and broadcast move to
packages/project-data/src/do/session-sockets.ts(index.ts shrinks).sealMessageStreamnow requires a session ID; its all-sessions form had no other caller.Consumer audit (
GET /api/projects/:projectId/sessions/ws)apps/webuseProjectWebSocket(main)session.*,attention.*,comment.thread.changed,session.access.changed624ff291a(2026-03-16)apps/webuseChatWebSocket(main)sessionId+ capablemessage.append, lifecyclesessionId, legacymessage.new,messages.batch; reconnects and re-reads on any non-1000 close47ff45302(2026-03-12)No other client (
packages/acp-client, CLI, vm-agent, harness) uses the route. All transcript broadcasts pass a session ID (message-persistence.ts,durability-foundation.ts,idle-cleanup.ts,reconciliation.ts,reconciliation-episode.ts,wake-failure.ts).Known residual (tracked)
A legacy chat tab that read the transcript over REST just before its first socket admission, with an append landing in between, keeps the shorter row until its next reconnect or reload: its first-open catch-up reads only newer rows. The brief scoped the guarantee to text arriving after the socket appears. Tracked in
tasks/backlog/2026-11-16-legacy-chat-pre-admission-append-gap.md.Validation
pnpm lint(full, exit 0)pnpm typecheck(full, exit 0;pnpm buildfull exit 0)pnpm test: targeted locally (project-data unit 539/539; 7 related workers files 50/50); full suite in CI on the ready head (all shards green)New
apps/api/tests/workers/project-data-socket-merge-gate.test.ts(6 tests) andpackages/project-data/tests/unit/session-sockets.test.ts(5 failure-isolation tests). Sockets open through the authenticatedGET /api/projects/:id/sessions/wsroute with a real session cookie; chunks arrive through the reporter callbackPOST /api/workspaces/:id/messageson a reserved workspace:session.updated.message.append, rebuilds the stored rows exactly, is not closed.recalculateAlarmmidpoint after commit, a legacy chat socket is admitted, then released. It receives no append, is closed with 4409, and a model of the pre-Merge streamed assistant chunks during message persistence #2760 client ends with the complete text; a capable socket on the same chat still gets the append. Its reconnection keeps merging off; once it leaves, merging resumes. (The hold widens a real window: any await between commit and broadcast.)Guards proven discriminating (each removed once, then restored byte-identical):
message.appendExisting suites green:
project-data-message-merge(incl. the billed-write snapshot, unchanged),workspace-message-merge-startup,project-data-message-merge-upgrade,acp-session-created-broadcast,session-access-changed-broadcast,session-access-expiry(50 tests);packages/project-dataunit suite 534/534.project-data-broadcast.test.tsasserted the old contract (project socket getsmessage.new) and now asserts the new one.Billed writes: unchanged on the ingest path (snapshot green). Admission of a legacy project socket no longer runs an all-sessions seal
UPDATE, so it writes fewer rows.Staging Verification (REQUIRED for all code changes — merge-blocking)
0f104be17: deploy and smoke tests passed)staging2-agent-adminvia workload identity; real Chromium)Staging Verification Evidence
staging2 (primary refuses main-based branches: DO migration tag v23 from unmerged #2721, run 43778055734).
chat.messageMergingEnabledwas at its default (off); set on for the run and reset to default afterwards. One Artifacts project, one Instant (cf-container) Claude Code session, no VM. Sockets opened by the real browserWebSocketagainstwss://api.sammy2.party/api/projects/:id/sessions/ws. Counts and hashes only:sessionId, no capability)session.created/updated/activity,activity.new,mailbox.*. Never closed.messages.batch+ 1message.new, 0message.append, not closed; the text it received (old-client rebuild) hashes identically to the stored assistant text (1764a96e…), all row IDs present.source: default.UI Compliance Checklist (Required for UI changes)
N/A: no
apps/web,packages/uiorpackages/acp-clientchanges.End-to-End Verification (Required for multi-component changes)
Data Flow Trace
GET /api/projects/:id/sessions/ws→apps/api/src/routes/chat.ts(chatRoutes.get('/ws'), project access) →projectDataService.forwardWebSocket→ProjectData.fetch→admitBrowserSocket(session-sockets.ts): tagssession:<id>and/ormessage-append-v1; legacy chat sockets seal their session.POST /api/workspaces/:id/messages→ProjectData.persistMessageBatch→hasLegacySessionSocket(ctx, sessionId)→persistMessageBatchWithSideEffects→MessageStreamBatch(merge) → awaited side effects →broadcastEvent→broadcastToBrowserSockets: transcript frames to session sockets only;message.appendonly to capable sockets, legacy ones closed with 4409.catchUpMessages→mergeReplace(ID replace) → complete row.Untested Gaps
The pre-admission window above (tracked). The old-client behaviour is modelled in the test from the pre-#2760 source (
7bea824b9^), not run from that bundle; staging verification uses a real socket without the capability.Post-Mortem (Required for bug fix PRs)
What broke
With merging on in production, one browser tab or phone still running a pre-#2760 web bundle switched chunk merging off for every session in its project, so rows written per ingest call did not drop.
Root cause
#2760 (
7bea824b9) treated an unscoped socket as watching every session ((!sessionTag || …) && !capableinpersistMessageBatch), becausebroadcastEventdid send it every session's transcript frames, although no project-socket consumer reads them. It also checked capability only at batch start, leaving a race with sockets admitted during the batch's awaits.Class of bug
A capability gate keyed on what the server sends rather than what the client consumes; and a check-then-act across an
awaitin a Durable Object (rule 45).Why it wasn't caught
Tests covered a legacy session socket but no project socket, and none admitted a socket between a batch's commit and its broadcast. The rollout's first production samples could not separate "merging refused" from "little eligible traffic" because no counter recorded refusals (#2773 adds them).
Process fix included in this PR
The contract is documented at the module that enforces it (
session-sockets.ts) and in the public API reference; tests pin each guard. No new rule file: rule 45 (DO await interleaving) and rule 62 (reach the feature the way production does) already cover the class.Post-mortem file
tasks/active/2026-11-16-stale-socket-merge-gate.mdSpecialist Review Evidence (Required for agent-authored PRs)
needs-human-reviewlabel added and merge deferred to human (N/A: all completed)sessionIdtag mismatch (fixed: lowercased), doc frame split (fixed). Accepted: a project member can hold merging off for one session with a capability-less socket (cost only, already able to read the transcript; previously project-wide).0f104be17webSocketClosemade quiet.0f104be17settle, pinned close code, unit failure-isolation tests.0f104be17useProjectWebSocketJSDoc; removed unusedProjectWebSocketEventtype that listedmessage.new; precision edits.0f104be170f104be17CodeRabbit Review Evidence (Required for agent-authored PRs)
CodeRabbit Notes
Requested at 2026-11-16T01:40:53Z by applying
coderabbit-reviewwhen the PR was marked ready (trusted workflow run 43787665763 succeeded). CodeRabbit reviewed head0f104be17and submitted APPROVED at 01:51:49Z with 0 inline comments; no unresolved feedback. The later commit5b21ad4a1only moves the task file totasks/archive/.Exceptions (If any)
main.maintriggers main CI and a production deploy while other deploys are queued.Agent Preflight (Required)
Classification
External References
Cloudflare Durable Objects hibernatable WebSocket API (
acceptWebSockettags,getWebSockets(tag),getTags,WebSocket.close(code, reason); application close codes 3000-4999 per RFC 6455 §7.4.2). Behaviour verified in real workerd by the new tests.Codebase Impact Analysis
packages/project-data(DO socket admission, merge gate, broadcast),packages/shared(close-code constant),apps/api(route comment, worker tests). Web clients are unchanged; both current hooks already send the capability, and the old ones are covered by the reconnect path. Public surface: project sockets stop receiving transcript frames (documented).Documentation & Specs
apps/www/src/content/docs/docs/reference/api.md(sessions/ws contract),apps/www/src/content/docs/docs/guides/admin-settings.md(legacy-browser note).Constitution & Risk Check
Principle XI: the close code is a wire-protocol constant beside the existing capability constant, not a tunable. No settings, defaults or migrations change;
chat.messageMergingEnabledis untouched. Risk: a legacy chat tab sees one brief reconnect when it joins mid-reply. WebSocket trust boundary unchanged: route auth, session ID validation and project scoping are as before; the change only narrows what unscoped sockets receive.🤖 Generated with Claude Code
Summary by CodeRabbit