@chroxy/server 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
@@ -0,0 +1,1251 @@
1
+ /**
2
+ * History replay and post-auth state delivery for WsServer.
3
+ *
4
+ * Extracted from ws-server.js to separate the post-authentication
5
+ * handshake and history replay concerns from core server orchestration.
6
+ */
7
+ import { toShortModelId, getRegistryForProvider } from './models.js'
8
+ import { PERMISSION_MODES } from './handler-utils.js'
9
+ import { listProviders, getProvider } from './providers.js'
10
+ import { createLogger } from './logger.js'
11
+ import { createKeyPair, deriveSharedKey, deriveConnectionKey, signExchangeKey } from '@chroxy/store-core/crypto'
12
+ import { DEFAULT_RESULT_TIMEOUT_MS, DEFAULT_HARD_TIMEOUT_MS, DEFAULT_STREAM_STALL_TIMEOUT_MS } from './base-session.js'
13
+ import { MAX_SANE_DURATION_MS } from '@chroxy/protocol'
14
+
15
+ const log = createLogger('ws')
16
+
17
+ // #4833 — back-pressure pause for chunked replay/flush loops.
18
+ //
19
+ // Both replayHistory and flushPostAuthQueue emit messages in 20-entry chunks
20
+ // separated by setImmediate yields. On sessions with fat tool_result payloads
21
+ // (200KB+ each), a single chunk can push ws.bufferedAmount past the 1MB
22
+ // EVICT_THRESHOLD in ws-client-sender.js, tripping a post-send 4008 close and
23
+ // surfacing as a "Reconnecting…" loop in the dashboard.
24
+ //
25
+ // Before scheduling the next chunk, the loop now polls bufferedAmount and
26
+ // pauses (via setTimeout, every BACKPRESSURE_POLL_INTERVAL_MS) until it falls
27
+ // back below BACKPRESSURE_PAUSE_THRESHOLD. The threshold (256KB) is well
28
+ // below the 1MB eviction line so the next chunk has headroom even on slow
29
+ // links. The poll interval (20ms) is short enough to keep the replay
30
+ // responsive but long enough to give the socket time to actually flush.
31
+ //
32
+ // Both helpers abort the poll once ws.readyState leaves OPEN (client
33
+ // disconnected while paused), so the poll chain terminates on socket close
34
+ // without sending to a closed socket.
35
+ //
36
+ // #5328 (WP-5.6): the readyState check alone is NOT enough to bound the poll —
37
+ // a half-open TCP connection that stays stuck in OPEN, never drains, and never
38
+ // errors would keep re-scheduling setTimeout(poll) forever, leaking one timer
39
+ // chain per stuck replay/flush. BACKPRESSURE_MAX_WAIT_MS is a hard cap: once a
40
+ // drain has been blocked that long we stop polling and close the socket (1013
41
+ // "Try Again Later") so the client reconnects cleanly and re-runs the replay
42
+ // from scratch, rather than silently leaking a timer against a dead peer. The
43
+ // cap is comfortably longer than a healthy slow-link drain but far short of
44
+ // "forever".
45
+ const BACKPRESSURE_PAUSE_THRESHOLD = 256 * 1024
46
+ const BACKPRESSURE_POLL_INTERVAL_MS = 20
47
+ const BACKPRESSURE_MAX_WAIT_MS = 30_000
48
+
49
+ // #5622 — bound the eager X25519 key derivations done SYNCHRONOUSLY per
50
+ // event-loop iteration.
51
+ //
52
+ // The #5590 eager fold concentrates createKeyPair + DH (deriveSharedKey) + HKDF
53
+ // (deriveConnectionKey) into the synchronous auth-frame handler (sendPostAuthInfo
54
+ // below) for every connect. A reconnect storm delivers N auth frames in a single
55
+ // poll phase, so the N scalar-mults run back-to-back on the event loop and can
56
+ // delay the timer phase past the 15s keepalive sweep (#5594) — event-loop
57
+ // starvation that bites only at fan-out scale (swarm-audit round 3, Tunneler).
58
+ //
59
+ // A classic async semaphore is meaningless here: the crypto is synchronous, so
60
+ // no two derivations ever truly overlap — the cost is serialization within one
61
+ // loop iteration, not concurrency. The correct analog of a concurrency cap for
62
+ // synchronous work is therefore a per-iteration budget: run at most
63
+ // MAX_EAGER_DERIVATIONS_PER_TICK derivations inline, and let any further connects
64
+ // in the same iteration fall back to the DISCRETE key_exchange handshake. That
65
+ // fallback is already wired (the `!eagerServerPublicKey` branch below engages
66
+ // encryptionPending + the post-auth queue) and its derivation lands on a later
67
+ // frame/tick, which de-concentrates the work so the timer phase — and the
68
+ // keepalive sweep — gets to run between iterations.
69
+ //
70
+ // The counter resets on each setImmediate (fires once per loop iteration, in the
71
+ // check phase, after timers), so the budget is genuinely per-iteration. Under
72
+ // normal load (< CAP connects per iteration) the eager path is unchanged; only a
73
+ // storm degrades, and only to the pre-#5590 discrete handshake (one extra RTT),
74
+ // never to a failed connection.
75
+ const MAX_EAGER_DERIVATIONS_PER_TICK = 8
76
+ let _eagerDerivationsThisTick = 0
77
+ let _eagerResetScheduled = false
78
+ let _eagerResetHandle = null
79
+
80
+ /**
81
+ * Reserve a slot for one synchronous eager key derivation in the current
82
+ * event-loop iteration. Returns true if under the per-iteration budget (caller
83
+ * should derive inline), false if the budget is spent (caller should skip the
84
+ * eager fold and let the client use the discrete handshake). Schedules a
85
+ * one-shot reset of the counter for the next iteration on first use.
86
+ *
87
+ * Exported for direct unit testing of the budget + reset behaviour.
88
+ */
89
+ export function _reserveEagerDerivationSlot() {
90
+ if (_eagerDerivationsThisTick >= MAX_EAGER_DERIVATIONS_PER_TICK) return false
91
+ _eagerDerivationsThisTick++
92
+ if (!_eagerResetScheduled) {
93
+ _eagerResetScheduled = true
94
+ // Retain the handle so the test reset helper can cancel a still-pending
95
+ // reset and keep test isolation tight (#5764 review).
96
+ _eagerResetHandle = setImmediate(() => {
97
+ _eagerDerivationsThisTick = 0
98
+ _eagerResetScheduled = false
99
+ _eagerResetHandle = null
100
+ })
101
+ }
102
+ return true
103
+ }
104
+
105
+ /**
106
+ * Reset the per-iteration eager-derivation budget synchronously. Test-only — the
107
+ * module-global counter is reset by setImmediate in production, but node:test can
108
+ * run several synchronous test bodies within one macrotask, so a test that
109
+ * exhausts the budget would otherwise leak into the next. Call in a `beforeEach`.
110
+ */
111
+ export function _resetEagerDerivationBudgetForTests() {
112
+ // Cancel any reset still queued from a prior test/tick so it can't fire mid
113
+ // test (after an `await`) and mutate the budget unexpectedly (#5764 review).
114
+ if (_eagerResetHandle) {
115
+ clearImmediate(_eagerResetHandle)
116
+ _eagerResetHandle = null
117
+ }
118
+ _eagerDerivationsThisTick = 0
119
+ _eagerResetScheduled = false
120
+ }
121
+
122
+ /**
123
+ * Schedule `fn` once ws.bufferedAmount falls below BACKPRESSURE_PAUSE_THRESHOLD,
124
+ * or immediately (via setImmediate) if the buffer is already drained. Polls
125
+ * with setTimeout(BACKPRESSURE_POLL_INTERVAL_MS) while paused. Bails out
126
+ * silently if ws.readyState transitions away from OPEN — the caller's first
127
+ * action in `fn` already re-checks readyState so the bailout is safe.
128
+ *
129
+ * If the drain stays blocked for BACKPRESSURE_MAX_WAIT_MS (a half-open socket
130
+ * that never drains), stop polling and close the socket so the client
131
+ * reconnects cleanly — `fn` is then never called (#5328).
132
+ *
133
+ * Exported for direct unit testing of the max-wait cap.
134
+ */
135
+ export function scheduleAfterDrain(ws, fn) {
136
+ if (ws.readyState !== 1) return
137
+ const buffered = ws.bufferedAmount || 0
138
+ if (buffered <= BACKPRESSURE_PAUSE_THRESHOLD) {
139
+ setImmediate(fn)
140
+ return
141
+ }
142
+ const start = Date.now()
143
+ const poll = () => {
144
+ if (ws.readyState !== 1) return
145
+ if ((ws.bufferedAmount || 0) <= BACKPRESSURE_PAUSE_THRESHOLD) {
146
+ setImmediate(fn)
147
+ return
148
+ }
149
+ if (Date.now() - start >= BACKPRESSURE_MAX_WAIT_MS) {
150
+ log.warn(`replay/flush drain stalled >${BACKPRESSURE_MAX_WAIT_MS}ms (bufferedAmount=${ws.bufferedAmount}) — closing socket so the client reconnects`)
151
+ try { ws.close(1013, 'Replay backpressure timeout') } catch (_) { /* already closing */ }
152
+ return
153
+ }
154
+ setTimeout(poll, BACKPRESSURE_POLL_INTERVAL_MS)
155
+ }
156
+ setTimeout(poll, BACKPRESSURE_POLL_INTERVAL_MS)
157
+ }
158
+
159
+ /**
160
+ * Send all post-authentication info to a newly authenticated client.
161
+ * This includes auth_ok, server mode, session list, model/permission state,
162
+ * and history replay.
163
+ *
164
+ * @param {object} ctx - Server context
165
+ * @param {WebSocket} ws - The client WebSocket
166
+ */
167
+ export function sendPostAuthInfo(ctx, ws, extra = {}) {
168
+ const {
169
+ clients, sessionManager, cliSession, defaultSessionId,
170
+ serverMode, serverVersion, latestVersion, gitInfo,
171
+ encryptionEnabled, localhostBypass, tunnelActive, keyExchangeTimeoutMs,
172
+ protocolVersion, minProtocolVersion, webTaskManager,
173
+ // #5721: `send` MUST be `WsServer._send` (which returns the delivery
174
+ // boolean from the client-sender), NOT a wrapper that drops the return —
175
+ // the eager-handshake gate below reads `authOkDelivered` to decide whether
176
+ // to mark E2E established. A ctx-wiring refactor that swallows the return
177
+ // would silently re-open the swallowed-send wedge this fix closes.
178
+ send, broadcast, getConnectedClientList, permissions,
179
+ resultTimeoutMs, hardTimeoutMs, streamStallTimeoutMs,
180
+ // #5986 (epic #5982): whether the embedded user-shell terminal is enabled,
181
+ // surfaced as the `userShell` capability so the dashboard gates its "New
182
+ // shell" affordance. Optional — absent → false (fail-closed) for old servers.
183
+ userShellEnabled,
184
+ // #6481 (epic #6469): whether the opt-in IDE feature surface is enabled
185
+ // (config.features.ide / CHROXY_ENABLE_IDE). Surfaced as the `ide` capability
186
+ // so clients reveal IDE navigation/editing UI. Optional — absent → false
187
+ // (fail-closed) for old servers / callers.
188
+ ideEnabled,
189
+ // #6006: whether the server has a rotating TokenManager (i.e. auth is on),
190
+ // so the operator panic button (`revoke_token`) can fire. Surfaced as the
191
+ // `tokenRevoke` capability, gated to primary-token clients below. Optional —
192
+ // absent → false (fail-closed) for --no-auth servers and old callers.
193
+ tokenRevocable,
194
+ // #4835: per-device active-session memory. Consulted below before
195
+ // falling back to defaultSessionId / firstSessionId so a reconnect
196
+ // restores whatever session the client was actually viewing instead
197
+ // of silently snapping them back to "session 1" on every WS drop.
198
+ // Optional — older callers (and most tests) leave this undefined and
199
+ // get the legacy default/first behavior.
200
+ devicePreferences,
201
+ // #5356: exposure snapshot ({ lanBind, bindHost, quickTunnel }) — null /
202
+ // undefined when the server hasn't bound a socket (test harnesses) or the
203
+ // ctx predates the field; the auth_ok field is omitted in that case.
204
+ exposure,
205
+ // #5821: current billing-canary snapshot ({ eraStarted, defaultProvider,
206
+ // defaultBillingClass, warnings }) — null when no provider is wired; the
207
+ // auth_ok field is omitted in that case.
208
+ billingCanary,
209
+ // #5536: long-lived identity keypair for signing the eager exchange key.
210
+ serverIdentity,
211
+ } = ctx
212
+ const client = clients.get(ws)
213
+
214
+ // Get initial session info for auth_ok payload
215
+ let sessionInfo = {}
216
+ if (sessionManager) {
217
+ let activeId = defaultSessionId
218
+ let entry = activeId ? sessionManager.getSession(activeId) : null
219
+ if (!entry) {
220
+ activeId = sessionManager.firstSessionId
221
+ entry = activeId ? sessionManager.getSession(activeId) : null
222
+ }
223
+ // If client is bound to a specific session, use that session's cwd
224
+ // instead of the server default to avoid leaking unrelated session info.
225
+ if (client.boundSessionId) {
226
+ const boundEntry = sessionManager.getSession(client.boundSessionId)
227
+ if (boundEntry) {
228
+ entry = boundEntry
229
+ } else {
230
+ entry = null
231
+ }
232
+ }
233
+ if (entry) {
234
+ sessionInfo.cwd = entry.cwd
235
+ }
236
+ } else if (cliSession) {
237
+ sessionInfo.cwd = cliSession.cwd
238
+ }
239
+ if (!sessionInfo.cwd) {
240
+ sessionInfo.cwd = null
241
+ }
242
+
243
+ // Skip encryption for localhost connections.
244
+ //
245
+ // #6562: the loopback socket-IP check alone is NOT sufficient — cloudflared
246
+ // forwards tunnel traffic to 127.0.0.1, so a REMOTE client over a Quick Tunnel
247
+ // arrives with socketIp 127.0.0.1 and would be silently downgraded to plaintext,
248
+ // which a paired (identity-pinned) mobile client correctly refuses ("did not
249
+ // negotiate encryption"). Additionally require `client.localPeer` — the
250
+ // upgrade-time locality CLASSIFICATION (unspoofable socket peer + proxy-header
251
+ // ABSENCE), which is FALSE when proxy headers (cf-connecting-ip /
252
+ // x-forwarded-for) are present. So a genuine local dashboard (loopback socket,
253
+ // no proxy headers) is still bypassed, but a tunneled connection to 127.0.0.1 is
254
+ // not — it does the full key_exchange. NB: header absence is a WEAK positive
255
+ // "local" signal (a non-Cloudflare loopback-forwarding proxy that omits these
256
+ // headers would classify local — see #6564), but an attacker cannot STRIP
257
+ // cloudflared's edge-stamped cf-connecting-ip to GAIN the bypass, so the
258
+ // security-relevant direction is safe.
259
+ //
260
+ // #6564: harden the residual operator-misconfiguration hole. When a tunnel is
261
+ // running (`tunnelActive`), an UNKNOWN reverse proxy could be forwarding remote
262
+ // traffic to the loopback listener without setting cf-connecting-ip /
263
+ // x-forwarded-for — which would classify as localPeer and get the plaintext
264
+ // bypass. So the bypass is DEFAULT-OFF while a tunnel is active: a genuine
265
+ // same-host dashboard simply does the (cheap, already-supported) key exchange in
266
+ // that window. With no tunnel there is no unknown edge, so the fast loopback
267
+ // bypass still applies. Operators can force encryption on loopback unconditionally
268
+ // with `encryptLocalhost: true` (CHROXY_ENCRYPT_LOCALHOST=1), which sets
269
+ // `localhostBypass=false`. Trust assumption documented in
270
+ // docs/security/encryption-threat-model.md.
271
+ const isLoopbackSocket = client.socketIp === '127.0.0.1' || client.socketIp === '::1' || client.socketIp === '::ffff:127.0.0.1'
272
+ const isLocalhost = localhostBypass && isLoopbackSocket && client.localPeer === true && !tunnelActive
273
+ const requireEncryption = encryptionEnabled && !isLocalhost
274
+
275
+ // #5555 (eager key exchange) — if the client supplied its ephemeral public
276
+ // key + salt in the auth message (stashed as client.eagerKeyExchange in
277
+ // handleAuthMessage), derive the shared key inline NOW and return the
278
+ // server's public key in auth_ok below. This collapses the discrete
279
+ // `key_exchange` round trip: the post-auth queue never has to gate, so
280
+ // replay starts a full RTT earlier.
281
+ //
282
+ // Crypto is identical to handleKeyExchange's discrete path:
283
+ // deriveSharedKey (X25519 DH) → deriveConnectionKey (per-connection sub-key
284
+ // from the client salt, so the nonce counter can restart at 0 safely on
285
+ // reconnect without reusing a (key, nonce) pair). Only the transport timing
286
+ // differs — the eager path folds the second handshake leg into auth_ok
287
+ // instead of a separate frame, so the TOFU exposure (#5536: no server
288
+ // identity pinning) is unchanged: the server's public key still travels in
289
+ // the clear over the same TLS-protected tunnel, just one frame earlier.
290
+ //
291
+ // Any failure to derive (malformed eager public key) falls back to the
292
+ // discrete handshake rather than failing the connection — the client still
293
+ // has its keypair and will send `key_exchange` when auth_ok arrives without
294
+ // a serverPublicKey.
295
+ //
296
+ // IMPORTANT ordering: the derived encryptionState is NOT assigned to the
297
+ // client yet. The auth_ok frame that carries serverPublicKey must go out in
298
+ // PLAINTEXT — the client can't decrypt it because it derives the shared key
299
+ // *from* that serverPublicKey. We assign client.encryptionState only AFTER
300
+ // auth_ok is sent (see below), so the subsequent burst (server_mode, status,
301
+ // session_list, …) is encrypted. This mirrors the discrete path, where
302
+ // key_exchange_ok is plaintext and encryptionState is set right after.
303
+ let eagerServerPublicKey = null
304
+ let eagerServerKeySig = null
305
+ let eagerEncryptionState = null
306
+ if (client.eagerKeyExchange) {
307
+ // #5622: only run the eager derivation inline while under the per-iteration
308
+ // budget. Over budget (reconnect storm) we skip the fold and leave
309
+ // eagerServerPublicKey null, so the `requireEncryption && !eagerServerPublicKey`
310
+ // branch below transparently engages the discrete key_exchange handshake —
311
+ // its scalar-mult lands on a later tick, keeping this iteration short enough
312
+ // for the keepalive sweep to run.
313
+ if (requireEncryption && _reserveEagerDerivationSlot()) {
314
+ try {
315
+ const serverKp = createKeyPair()
316
+ const rawSharedKey = deriveSharedKey(client.eagerKeyExchange.publicKey, serverKp.secretKey)
317
+ const encryptionKey = deriveConnectionKey(rawSharedKey, client.eagerKeyExchange.salt)
318
+ eagerEncryptionState = { sharedKey: encryptionKey, sendNonce: 0, recvNonce: 0 }
319
+ eagerServerPublicKey = serverKp.publicKey
320
+ // #5536 — sign the eager exchange key with the long-lived identity so a
321
+ // client that pinned our identity can verify it BEFORE keying off the
322
+ // serverPublicKey in auth_ok. Same crypto binding as the discrete path
323
+ // (key_exchange_ok.serverKeySig); only the carrying frame differs. Absent
324
+ // when pinning is unavailable — old clients ignore it, exchange stays TOFU.
325
+ if (serverIdentity?.secretKey) {
326
+ try {
327
+ eagerServerKeySig = signExchangeKey(serverKp.publicKey, serverIdentity.secretKey, { domainSeparated: true })
328
+ } catch (sigErr) {
329
+ log.warn(`Failed to sign eager exchange key for ${client.id}: ${sigErr.message}`)
330
+ eagerServerKeySig = null
331
+ }
332
+ }
333
+ } catch (err) {
334
+ log.warn(`Eager key exchange failed for ${client.id}, falling back to discrete handshake: ${err.message}`)
335
+ eagerEncryptionState = null
336
+ eagerServerPublicKey = null
337
+ eagerServerKeySig = null
338
+ }
339
+ }
340
+ // Consumed (encryption required), unused (encryption disabled / localhost
341
+ // bypass), or failed — never leave it set so a later discrete key_exchange
342
+ // isn't shadowed by stale eager state and no handshake material lingers on
343
+ // the client object longer than the one auth pass that could use it.
344
+ client.eagerKeyExchange = null
345
+ }
346
+
347
+ const providers = listProviders()
348
+ const features = {
349
+ environments: providers.some(p => p.capabilities?.containerized),
350
+ }
351
+
352
+ // #3272: server-advertised capability map. Dashboard / app gate UI
353
+ // affordances on these flags so older servers don't silently no-op
354
+ // a click against an unknown WS message type. Add new flags here
355
+ // when shipping a dashboard-facing feature whose handler depends on
356
+ // a specific server build and could run against mixed versions.
357
+ const capabilities = {
358
+ // #3235/#3269 — `skill_trust_accept` handler + `skill_trust_accepted`
359
+ // broadcast. Gates the SkillsPanel 'Accept new content' button (#3270).
360
+ skillTrustAccept: true,
361
+ // #3297 — `skill_trust_grant` handler + `skill_trust_granted` broadcast.
362
+ // Gates the community-skill first-activation trust-grant UI.
363
+ skillTrustGrant: true,
364
+ // #4560 — `notification_prefs_get` / `notification_prefs_set` handlers
365
+ // + `notification_prefs` snapshot broadcast (added in #4541). Gates the
366
+ // Notifications section in SettingsPanel / SettingsScreen so a client
367
+ // connecting to a pre-#4541 server doesn't sit on "Loading
368
+ // preferences…" indefinitely waiting for a snapshot that will never
369
+ // arrive — instead the section either hides itself or surfaces a
370
+ // "not supported on this server" message.
371
+ notificationPrefs: true,
372
+ // #5555 — this server emits an `auth_bootstrap` burst frame carrying the
373
+ // provider / slash-command / agent lists right after auth_ok, so a new
374
+ // client can SKIP its 3-request connect-time round trip (list_providers /
375
+ // list_slash_commands / list_agents). Clients that don't see this flag
376
+ // (older server) fall back to requesting the three lists as before. The
377
+ // request handlers stay live either way for post-connect refreshes.
378
+ authBootstrap: true,
379
+ // #6481 (epic #6469): the opt-in IDE feature surface (file navigator, symbol
380
+ // navigation, go-to-definition, find-references, edit-in-place) is enabled on
381
+ // THIS server (config.features.ide / CHROXY_ENABLE_IDE). Clients gate ALL IDE
382
+ // UI on this flag; absent/false (default, or older servers) → no IDE chrome
383
+ // (fail-closed). A server-wide feature gate, not token-scoped — available to
384
+ // every client when the operator opts in.
385
+ ide: ideEnabled === true,
386
+ // #5986 (epic #5982) — the embedded user-shell terminal is available to THIS
387
+ // client: the server has it enabled (userShell.enabled) AND this connection
388
+ // holds the primary token. Both conditions of the create gate are reflected
389
+ // here (config gate #5985a + primary-token gate #5985b) so a paired
390
+ // (non-primary) device never sees a "New shell" affordance it would only get
391
+ // a PRIMARY_TOKEN_REQUIRED rejection from. The provider is hidden from
392
+ // listProviders(), so this flag is the only signal that creating a
393
+ // `user-shell` session will succeed. Absent / false on servers without it, on
394
+ // hosts with it disabled, or for paired clients → the affordance stays hidden
395
+ // (fail-closed). The server gates remain the authority regardless.
396
+ userShell: userShellEnabled === true && client?.isPrimaryToken === true,
397
+ // #6006 — the operator panic button (revoke_token) is available to THIS
398
+ // client: the server has a rotating TokenManager (auth on) AND this
399
+ // connection holds the primary token. Mirrors the server-side gate in
400
+ // token-handlers.js (isPrimaryToken === true) so a paired (non-primary)
401
+ // device never sees a "Revoke token" affordance it would only get a
402
+ // NOT_AUTHORIZED rejection from. Fail-closed: absent/false otherwise.
403
+ tokenRevoke: tokenRevocable === true && client?.isPrimaryToken === true,
404
+ }
405
+
406
+ // #3760, #3905: surface the effective inactivity timeouts so clients
407
+ // (e.g. the ActivityIndicator's "approaching timeout" warning + the check-in
408
+ // chip's countdown to hard kill) can render against the real configured
409
+ // values instead of assuming the BaseSession defaults. Older clients
410
+ // ignore the fields; new clients fall back to a hardcoded 30-min / 2h
411
+ // default when the server omits them (older servers).
412
+ //
413
+ // Require Number.isSafeInteger here — the protocol schema enforces
414
+ // `int().positive().finite()` on both fields, so a fractional config
415
+ // value (e.g. `CHROXY_HARD_TIMEOUT_MS=7200000.5` via `parseFloat`)
416
+ // would silently fail client-side schema validation on the auth_ok
417
+ // payload. Falling back to the default lets the wire stay valid.
418
+ //
419
+ // #4484: also enforce the `<= MAX_SANE_DURATION_MS` (24h) ceiling that the
420
+ // protocol schemas apply via `.max(MAX_SANE_DURATION_MS)`. Without this
421
+ // check an operator value like `CHROXY_HARD_TIMEOUT_MS=99999999999`
422
+ // (>24h) would pass isSafeInteger here, hit the wire, and fail the
423
+ // client-side schema's `.max()` gate — silently breaking the auth_ok
424
+ // parse for every connecting client. Mirroring the ceiling here lets
425
+ // the server degrade gracefully to the default instead.
426
+ const effectiveResultTimeoutMs =
427
+ Number.isSafeInteger(resultTimeoutMs) && resultTimeoutMs > 0 && resultTimeoutMs <= MAX_SANE_DURATION_MS
428
+ ? resultTimeoutMs
429
+ : DEFAULT_RESULT_TIMEOUT_MS
430
+ const effectiveHardTimeoutMs =
431
+ Number.isSafeInteger(hardTimeoutMs) && hardTimeoutMs > 0 && hardTimeoutMs <= MAX_SANE_DURATION_MS
432
+ ? hardTimeoutMs
433
+ : DEFAULT_HARD_TIMEOUT_MS
434
+ // #4477: stream-stall window. Semantics differ from the two timeouts above —
435
+ // 0 is a meaningful operator-set value ("explicitly disabled") that must
436
+ // survive intact to the dashboard so the chip (#4476) can hide instead of
437
+ // rendering against a disabled timer. Use `>= 0` here, not `> 0`.
438
+ // Negative / fractional / NaN / Infinity / string inputs fail
439
+ // isSafeInteger and fall back to the default — they'd otherwise fail the
440
+ // protocol schema's int().nonnegative().max(MAX_SANE_DURATION_MS) gate at
441
+ // the client and silently break dashboard message handling.
442
+ // #4484: ceiling check mirrors the protocol schema's `.max()` gate; see
443
+ // resultTimeoutMs above for the asymmetry rationale.
444
+ const effectiveStreamStallTimeoutMs =
445
+ Number.isSafeInteger(streamStallTimeoutMs) && streamStallTimeoutMs >= 0 && streamStallTimeoutMs <= MAX_SANE_DURATION_MS
446
+ ? streamStallTimeoutMs
447
+ : DEFAULT_STREAM_STALL_TIMEOUT_MS
448
+
449
+ const authOkDelivered = send(ws, {
450
+ type: 'auth_ok',
451
+ clientId: client.id,
452
+ serverMode,
453
+ serverVersion,
454
+ latestVersion,
455
+ serverCommit: gitInfo.commit,
456
+ cwd: sessionInfo.cwd,
457
+ defaultCwd: sessionManager?.defaultCwd || null,
458
+ connectedClients: getConnectedClientList(),
459
+ encryption: requireEncryption ? 'required' : 'disabled',
460
+ protocolVersion,
461
+ minProtocolVersion,
462
+ maxProtocolVersion: protocolVersion,
463
+ webFeatures: webTaskManager.getFeatureStatus(),
464
+ features,
465
+ capabilities,
466
+ // #5555 — fold the static permission-mode enum into auth_ok so a new
467
+ // client never has to wait for (or react to) the discrete
468
+ // `available_permission_modes` burst frame. The discrete frame is still
469
+ // sent below for older clients that read the enum only from it.
470
+ availablePermissionModes: PERMISSION_MODES,
471
+ resultTimeoutMs: effectiveResultTimeoutMs,
472
+ hardTimeoutMs: effectiveHardTimeoutMs,
473
+ streamStallTimeoutMs: effectiveStreamStallTimeoutMs,
474
+ // #5356: exposure snapshot for the dashboard warning banner. Optional on
475
+ // the wire — older servers omit it and clients treat that as "unknown".
476
+ ...(exposure ? { exposure } : {}),
477
+ // #5821: current billing-canary snapshot, so a freshly-connected client
478
+ // renders the billing banner immediately. Optional — omitted when no
479
+ // provider is wired (older servers / tests); live changes arrive via the
480
+ // `billing_canary` broadcast.
481
+ ...(billingCanary ? { billingCanary } : {}),
482
+ // #5555: when the eager handshake succeeded, carry the server's public key
483
+ // so the client derives the shared key immediately. Absent otherwise (no
484
+ // eager fields / encryption disabled / derivation failed) → client falls
485
+ // back to the discrete key_exchange.
486
+ ...(eagerServerPublicKey ? { serverPublicKey: eagerServerPublicKey } : {}),
487
+ // #5536: identity signature over the eager exchange key, so a pinned client
488
+ // can verify it before keying off serverPublicKey. Absent when pinning is
489
+ // unavailable; old clients ignore it.
490
+ ...(eagerServerKeySig ? { serverKeySig: eagerServerKeySig } : {}),
491
+ // #5616/#5976 — identity-rotation continuity cert. Present only alongside a
492
+ // live exchange signature (the consume side needs BOTH the cert AND the new
493
+ // identity's live serverKeySig to chain forward), and only when the daemon
494
+ // was rotated (cert loaded at startup). Absent for un-rotated daemons / old
495
+ // clients ignore it; a pin-mismatched client with no cert still refuses.
496
+ ...(eagerServerKeySig && serverIdentity?.rotationCert
497
+ ? { newIdentityKey: serverIdentity.publicKey, rotationCert: serverIdentity.rotationCert }
498
+ : {}),
499
+ ...extra,
500
+ })
501
+
502
+ // #5555: now that the plaintext auth_ok (carrying serverPublicKey) has been
503
+ // flushed, activate encryption for this client so every subsequent frame in
504
+ // the post-auth burst is encrypted. The client derives the same shared key
505
+ // from auth_ok.serverPublicKey + its own secret, so both sides start at
506
+ // nonce 0 in lockstep. This is the un-gated eager path — no postAuthQueue.
507
+ if (eagerEncryptionState) {
508
+ // #5721: gate the crypto activation on the auth_ok ACTUALLY reaching the
509
+ // wire. `send` (_clientSend) swallows a send throw internally, so without
510
+ // this check a failed/half-open auth_ok would still flip encryptionState —
511
+ // the server would then encrypt the whole post-auth burst with a key the
512
+ // client never received (it never got serverPublicKey), wedging the session
513
+ // until the 15–30s heartbeat sweep reaps it. Mirror the discrete-path
514
+ // rollback (#5702 8b / ws-auth.js key_exchange_ok): on non-delivery, do NOT
515
+ // mark E2E established, and close so the client reconnects and retries.
516
+ if (!authOkDelivered) {
517
+ log.error(`Failed to deliver eager auth_ok to ${client.id} — aborting handshake (client never received serverPublicKey)`)
518
+ client.encryptionState = null
519
+ try { ws.close(1011, 'Handshake failed') } catch { /* socket already gone */ }
520
+ return
521
+ }
522
+ client.encryptionState = eagerEncryptionState
523
+ log.info(`E2E encryption established eagerly with ${client.id}`)
524
+ }
525
+
526
+ // #5555: the eager handshake already established the shared key above, so
527
+ // the post-auth queue must NOT gate — it's un-gated immediately and the
528
+ // burst frames flow encrypted right after auth_ok. Only fall into the
529
+ // discrete-handshake gating below when encryption is required AND the eager
530
+ // path did not run (old client, or derivation failed).
531
+ // If encryption required, queue all subsequent messages until key exchange completes
532
+ if (requireEncryption && !eagerServerPublicKey) {
533
+ client.encryptionPending = true
534
+ client.postAuthQueue = []
535
+ client._keyExchangeTimeout = setTimeout(() => {
536
+ if (client.encryptionPending) {
537
+ log.error(`Key exchange timeout for ${client.id} — disconnecting (encryption required)`)
538
+ client.encryptionPending = false
539
+ client.postAuthQueue = null
540
+ try {
541
+ ws.send(JSON.stringify({ type: 'server_error', message: 'Encryption required but key exchange timed out. Please reconnect.', recoverable: false }))
542
+ } catch (_) {}
543
+ // Guard close() too: if the socket is already CLOSING/CLOSED when this
544
+ // timer fires (a race with a concurrent client disconnect), a bare
545
+ // ws.close() can throw — and the uncaught error would escape this setTimeout
546
+ // callback. Mirrors the guarded close() at the other timeout/error sites.
547
+ try {
548
+ ws.close(1008, 'Key exchange timeout')
549
+ } catch (_) {}
550
+ }
551
+ }, keyExchangeTimeoutMs)
552
+ }
553
+
554
+ send(ws, { type: 'server_mode', mode: serverMode })
555
+ send(ws, { type: 'status', connected: true })
556
+
557
+ // Multi-session mode
558
+ if (sessionManager) {
559
+ let sessions = sessionManager.listSessions()
560
+ if (client.boundSessionId) {
561
+ sessions = sessions.filter(s => s.sessionId === client.boundSessionId)
562
+ }
563
+ send(ws, { type: 'session_list', sessions })
564
+
565
+ // #5665: send the current monthly programmatic-credit meter snapshot so a
566
+ // freshly-connected dashboard shows it immediately, not only after the next
567
+ // billed turn. Machine-wide, so it's sent regardless of boundSessionId.
568
+ if (typeof sessionManager.getMonthlyBudgetStatus === 'function') {
569
+ send(ws, { type: 'monthly_budget', ...sessionManager.getMonthlyBudgetStatus() })
570
+ }
571
+
572
+ // Surface any sessions that failed to restore at startup (#2954) so newly
573
+ // connecting clients see the "needs attention" state without having to
574
+ // reconnect after the event fired.
575
+ if (typeof sessionManager.getFailedRestores === 'function') {
576
+ for (const failed of sessionManager.getFailedRestores()) {
577
+ if (client.boundSessionId && failed.sessionId !== client.boundSessionId) continue
578
+ send(ws, {
579
+ type: 'session_restore_failed',
580
+ sessionId: failed.sessionId,
581
+ name: failed.name,
582
+ provider: failed.provider,
583
+ cwd: failed.cwd,
584
+ model: failed.model,
585
+ permissionMode: failed.permissionMode,
586
+ errorCode: failed.errorCode,
587
+ errorMessage: failed.errorMessage,
588
+ originalHistoryPreserved: true,
589
+ historyLength: failed.historyLength,
590
+ })
591
+ }
592
+ }
593
+
594
+ // #4835: prefer the per-device persisted active session over the server
595
+ // default. We only consult this for non-bound clients (boundSessionId
596
+ // remains the security override below). The original snap-to-default
597
+ // behavior was an infinite trap when combined with #4833's
598
+ // backpressure eviction: every retry of the user's actually-active
599
+ // session got bounced back to defaultSessionId.
600
+ //
601
+ // Restore order:
602
+ // 1. devicePreferences[client.deviceInfo.deviceId] — if it still exists
603
+ // 2. defaultSessionId — config-driven server default
604
+ // 3. firstSessionId — last-resort "any session beats no session"
605
+ //
606
+ // A stale persisted id (session destroyed between connects) falls
607
+ // through to step 2 without throwing — see #4835 acceptance criteria.
608
+ let activeId = null
609
+ let entry = null
610
+ const persistedDeviceId = client.deviceInfo?.deviceId
611
+ if (devicePreferences && persistedDeviceId) {
612
+ const persistedId = devicePreferences.getActiveSessionId(persistedDeviceId)
613
+ if (persistedId) {
614
+ const persistedEntry = sessionManager.getSession(persistedId)
615
+ if (persistedEntry) {
616
+ activeId = persistedId
617
+ entry = persistedEntry
618
+ }
619
+ }
620
+ }
621
+ if (!entry) {
622
+ activeId = defaultSessionId
623
+ entry = activeId ? sessionManager.getSession(activeId) : null
624
+ }
625
+ if (!entry) {
626
+ activeId = sessionManager.firstSessionId
627
+ entry = activeId ? sessionManager.getSession(activeId) : null
628
+ }
629
+
630
+ // If the client is bound to a specific session (via session token), enforce
631
+ // that they can only view that session regardless of the server default or
632
+ // any persisted per-device preference. Fail closed: if the bound session
633
+ // no longer exists, clear the active session rather than silently falling
634
+ // back to a different session (or inheriting an unrelated persisted pref).
635
+ if (client.boundSessionId) {
636
+ const boundEntry = sessionManager.getSession(client.boundSessionId)
637
+ if (boundEntry) {
638
+ activeId = client.boundSessionId
639
+ entry = boundEntry
640
+ } else {
641
+ log.warn(`Bound session ${client.boundSessionId} not found for client ${client.id} — clearing active session`)
642
+ activeId = null
643
+ entry = null
644
+ }
645
+ }
646
+
647
+ // #5563: route through the index-maintaining helper so the post-auth
648
+ // restore keeps the sessionId→clients reverse index in sync. Falls back to
649
+ // a bare assignment for test fixtures whose ctx predates the helper.
650
+ if (typeof ctx.setActiveSession === 'function') {
651
+ ctx.setActiveSession(client, activeId)
652
+ } else {
653
+ // lint-ignore-ws-index-mutation: guarded fixture fallback. This else-branch
654
+ // only runs for legacy test fixtures whose ctx predates the #5563
655
+ // index-maintaining setActiveSession helper; production always takes the
656
+ // helper path above, so this bare write can't drift the reverse index.
657
+ client.activeSessionId = activeId
658
+ }
659
+
660
+ if (entry) {
661
+ send(ws, { type: 'session_switched', sessionId: activeId, name: entry.name, cwd: entry.cwd, conversationId: entry.session.resumeSessionId || null })
662
+ // #5555: `sendSessionInfo` normally pushes `available_models` (the
663
+ // tab-switch path, #4302). On the connect handshake the post-auth block
664
+ // below already pushes one provider-scoped `available_models` snapshot
665
+ // (and, for the no-active-session case, the ONLY snapshot), so skip the
666
+ // duplicate here to avoid sending `available_models` twice per connect.
667
+ // The post-auth block owns the refresh schedule in this path (below).
668
+ sendSessionInfo(ctx, ws, activeId, { skipModels: true })
669
+ replayHistory(ctx, ws, activeId)
670
+ }
671
+
672
+ if (activeId) {
673
+ broadcast(
674
+ { type: 'client_focus_changed', clientId: client.id, sessionId: activeId, timestamp: Date.now() },
675
+ (c) => c.id !== client.id
676
+ )
677
+ }
678
+
679
+ // Use the active session's provider to source available models so
680
+ // Codex/Gemini sessions never see Claude-only entries (#2956). Non-
681
+ // Claude providers expose static `getFallbackModels()` via their
682
+ // class — getRegistryForProvider returns a provider-scoped registry
683
+ // seeded from that list. Claude providers share the default registry
684
+ // that is fed by `supportedModels()` on each SDK init.
685
+ const activeProvider = entry?.provider || null
686
+ const activeRegistry = getRegistryForProvider(activeProvider)
687
+ send(ws, { type: 'available_models', models: activeRegistry.getModels(), defaultModel: activeRegistry.getDefaultModelId(), provider: activeProvider })
688
+ // #5421/#5555: dynamic-discovery refresh (ollama /api/tags). `sendSessionInfo`
689
+ // above was told to skip its own `available_models` push (de-dupe on connect),
690
+ // so it also skipped scheduling the refresh — this path now owns the single
691
+ // schedule. With no active session activeProvider is null and there is nothing
692
+ // to refresh (scheduleProviderModelsRefresh no-ops on a null provider).
693
+ scheduleProviderModelsRefresh(ctx, ws, activeProvider)
694
+ send(ws, { type: 'available_permission_modes', modes: PERMISSION_MODES })
695
+ permissions.resendPendingPermissions(ws, client)
696
+ // #5555: fire the connect-time bootstrap burst (providers + slash commands
697
+ // + agents) so a new client never sends its 3-request list_* round trip.
698
+ // Fire-and-forget — the slash/agent compute is async (disk scans) and the
699
+ // synchronous post-auth burst above must not block on it.
700
+ sendAuthBootstrap(ctx, ws, { cwd: entry?.cwd || null, provider: activeProvider, sessionId: activeId })
701
+ return
702
+ }
703
+
704
+ // Legacy single-session mode
705
+ if (cliSession) {
706
+ if (cliSession.isReady) {
707
+ send(ws, { type: 'claude_ready' })
708
+ }
709
+ send(ws, {
710
+ type: 'model_changed',
711
+ // #3687: prefer the user's explicit override (`model`) so a later
712
+ // `setModel()` isn't masked by a stale `bootedModel` (SdkSession's
713
+ // setModel doesn't restart, so bootedModel only refreshes on the
714
+ // next init). Fall back to bootedModel when no override was set so
715
+ // the dashboard sees the real running model, not `null`.
716
+ model: (cliSession.model || cliSession.bootedModel)
717
+ ? toShortModelId(cliSession.model || cliSession.bootedModel)
718
+ : null,
719
+ })
720
+ // #6368: scope the legacy single-session model list to the ACTIVE provider's
721
+ // registry (the cliSession is the default-provider session) instead of the
722
+ // Claude-only module-level getModels(). billingCanary.defaultProvider is the
723
+ // resolved `config.provider || DEFAULT_PROVIDER`; for Claude (or a null/absent
724
+ // canary on old ctx) getRegistryForProvider falls back to the default Claude
725
+ // registry, so behaviour is unchanged today.
726
+ const legacyProvider = billingCanary?.defaultProvider || null
727
+ const legacyRegistry = getRegistryForProvider(legacyProvider)
728
+ send(ws, { type: 'available_models', models: legacyRegistry.getModels(), defaultModel: legacyRegistry.getDefaultModelId(), provider: legacyProvider })
729
+ send(ws, {
730
+ type: 'permission_mode_changed',
731
+ mode: cliSession.permissionMode || 'approve',
732
+ })
733
+ send(ws, { type: 'available_permission_modes', modes: PERMISSION_MODES })
734
+ }
735
+
736
+ permissions.resendPendingPermissions(ws)
737
+ // #5555: legacy single-session bootstrap burst — providers + slash commands
738
+ // + agents for the cliSession's cwd (no provider scoping in legacy mode).
739
+ sendAuthBootstrap(ctx, ws, { cwd: cliSession?.cwd || null, provider: null, sessionId: null })
740
+ }
741
+
742
+ /**
743
+ * #5555 (auth_bootstrap) — compute the provider / slash-command / agent lists
744
+ * and push them in a single `auth_bootstrap` burst frame right after the
745
+ * post-auth sync block. This is the server half of the round-trip collapse:
746
+ * a new client (one that saw `capabilities.authBootstrap` in auth_ok) consumes
747
+ * these payloads and SKIPS its connect-time `list_providers` /
748
+ * `list_slash_commands` / `list_agents` requests.
749
+ *
750
+ * Fire-and-forget by design: the slash-command and agent computes scan disk
751
+ * (project + user `.claude/{commands,agents}`), so awaiting them inline would
752
+ * stall the synchronous post-auth burst. We compute in the background and emit
753
+ * the frame when ready; if the socket has since closed, the send is a no-op.
754
+ *
755
+ * The payloads are byte-identical to the `provider_list` / `slash_commands` /
756
+ * `agent_list` request responses (same `listProviders()` and the shared
757
+ * `computeSlashCommands` / `computeAgents` used by the request handlers), so
758
+ * the client reuses its existing per-message handlers to consume them.
759
+ *
760
+ * Resilient: each list is computed independently; a failure in one (e.g. an
761
+ * unreadable agents dir) still ships the others. A total failure ships an
762
+ * empty bootstrap so the client doesn't sit waiting for data that never comes
763
+ * — it can always refresh later via the (still-live) list_* request paths.
764
+ *
765
+ * @param {object} ctx
766
+ * @param {WebSocket} ws
767
+ * @param {{ cwd: string|null, provider: string|null, sessionId: string|null }} info
768
+ */
769
+ function sendAuthBootstrap(ctx, ws, info = {}) {
770
+ const { send, services } = ctx
771
+ const fileOps = ctx.fileOps || services?.fileOps || null
772
+ const cwd = info.cwd || null
773
+ const provider = info.provider || null
774
+
775
+ // providers is a cheap synchronous read off the registry — same source as
776
+ // the list_providers handler.
777
+ let providers = []
778
+ try {
779
+ providers = listProviders()
780
+ } catch (err) {
781
+ log.warn(`auth_bootstrap: listProviders failed: ${err.message}`)
782
+ providers = []
783
+ }
784
+
785
+ // slash commands + agents are async disk scans; compute in parallel and
786
+ // tolerate either failing on its own.
787
+ const slashP = fileOps && typeof fileOps.computeSlashCommands === 'function'
788
+ ? fileOps.computeSlashCommands(cwd, provider).catch(err => {
789
+ log.warn(`auth_bootstrap: computeSlashCommands failed: ${err.message}`)
790
+ return []
791
+ })
792
+ : Promise.resolve([])
793
+ const userAgentsDirs = ctx.userAgentsDirs
794
+ const agentsOpts = Array.isArray(userAgentsDirs) && userAgentsDirs.length > 0
795
+ ? { userAgentsDirs }
796
+ : {}
797
+ const agentsP = fileOps && typeof fileOps.computeAgents === 'function'
798
+ ? fileOps.computeAgents(cwd, agentsOpts).catch(err => {
799
+ log.warn(`auth_bootstrap: computeAgents failed: ${err.message}`)
800
+ return []
801
+ })
802
+ : Promise.resolve([])
803
+
804
+ Promise.all([slashP, agentsP]).then(([slashCommands, agents]) => {
805
+ // Socket may have closed while the disk scans were in flight — bail out
806
+ // rather than sending to a dead peer.
807
+ if (ws.readyState !== 1) return
808
+ send(ws, {
809
+ type: 'auth_bootstrap',
810
+ providers,
811
+ slashCommands,
812
+ agents,
813
+ ...(info.sessionId ? { sessionId: info.sessionId } : {}),
814
+ // #5555 (sub-item 7): the live public tunnel URL, so a reconnecting
815
+ // client re-learns it on every connect — durable recovery for the case
816
+ // where a quick-tunnel rotation happened while the client was offline
817
+ // and it could not receive the live `tunnel_url_changed` push. Omitted
818
+ // for LAN / no-tunnel deployments (tunnelUrl is null).
819
+ ...(ctx.tunnelUrl ? { tunnelUrl: ctx.tunnelUrl } : {}),
820
+ })
821
+ }).catch(err => {
822
+ // Defensive: Promise.all here can only reject if one of the .catch handlers
823
+ // above itself threw, which they don't — but never let a bootstrap failure
824
+ // surface as an unhandled rejection.
825
+ log.warn(`auth_bootstrap: burst failed for ${ctx.clients?.get(ws)?.id || 'client'}: ${err.message}`)
826
+ })
827
+ }
828
+
829
+ /**
830
+ * #5421: fire-and-forget dynamic model discovery for providers that opt in
831
+ * via a static `refreshModels()` (currently ollama, which probes GET
832
+ * /api/tags for the locally installed tag list). Called right after an
833
+ * `available_models` snapshot goes out: when the refresh resolves with a
834
+ * CHANGED list (non-null), the registry has already been updated, so we
835
+ * re-push `available_models` to the same client. A null resolution means
836
+ * the snapshot already sent is still accurate (probe failed / no change /
837
+ * TTL-cached) and nothing further is emitted — Ollama being down costs one
838
+ * debug log line, never an error or a retry storm (the provider caches
839
+ * failures for its TTL window).
840
+ *
841
+ * Advisory only — this path feeds the picker; model VALIDATION for ollama
842
+ * stays unrestricted via getAllowedModels() returning null (a user can
843
+ * `ollama pull` mid-session or use an alias the tag list doesn't spell out).
844
+ */
845
+ export function scheduleProviderModelsRefresh(ctx, ws, providerName) {
846
+ if (!providerName) return
847
+ let ProviderClass = null
848
+ try {
849
+ ProviderClass = getProvider(providerName)
850
+ } catch {
851
+ return // unknown provider — nothing to refresh
852
+ }
853
+ if (typeof ProviderClass?.refreshModels !== 'function') return
854
+ Promise.resolve()
855
+ .then(() => ProviderClass.refreshModels())
856
+ .then((models) => {
857
+ if (!Array.isArray(models) || models.length === 0) return
858
+ if (ws.readyState !== undefined && ws.readyState !== 1) return // client gone
859
+ const registry = getRegistryForProvider(providerName)
860
+ ctx.send(ws, {
861
+ type: 'available_models',
862
+ models: registry.getModels(),
863
+ defaultModel: registry.getDefaultModelId(),
864
+ provider: providerName,
865
+ })
866
+ })
867
+ .catch((err) => {
868
+ // refreshModels contracts never to throw, but a provider bug must not
869
+ // become an unhandled rejection in the post-auth path.
870
+ log.debug(`model refresh for provider ${providerName} failed: ${err?.message || err}`)
871
+ })
872
+ }
873
+
874
+ /**
875
+ * Send session-specific info (model, permission, ready status) to a client.
876
+ *
877
+ * @param {object} [opts]
878
+ * @param {boolean} [opts.skipModels] - #5555: skip the `available_models` push
879
+ * (and its paired refresh schedule). Set by `sendPostAuthInfo` on connect,
880
+ * where the post-auth block sends a single `available_models` snapshot itself
881
+ * — without this the same client would receive `available_models` twice per
882
+ * connect. The tab-switch path (#4302) leaves it false so a switch still
883
+ * re-tags the dashboard's provider.
884
+ */
885
+ export function sendSessionInfo(ctx, ws, sessionId, opts = {}) {
886
+ const { sessionManager, send } = ctx
887
+ const entry = sessionManager?.getSession(sessionId)
888
+ if (!entry) return
889
+ const session = entry.session
890
+
891
+ if (session.isReady) {
892
+ send(ws, { type: 'claude_ready', sessionId })
893
+ }
894
+ // #4302: push the new session's provider-scoped model list on every
895
+ // switch. Without this, the dashboard's `availableModelsProvider` stays
896
+ // tagged with whichever provider the client saw last (set on auth via
897
+ // `sendPostAuthInfo`), and `modelsMatchProvider` in App.tsx suppresses
898
+ // the model picker for any session whose provider differs from the
899
+ // initial one — most visibly, a claude-cli session created after a
900
+ // TUI/SDK session loses its picker entirely.
901
+ if (!opts.skipModels) {
902
+ const activeProvider = entry.provider || null
903
+ const activeRegistry = getRegistryForProvider(activeProvider)
904
+ send(ws, {
905
+ type: 'available_models',
906
+ models: activeRegistry.getModels(),
907
+ defaultModel: activeRegistry.getDefaultModelId(),
908
+ provider: activeProvider,
909
+ })
910
+ // #5421: background dynamic-discovery refresh (ollama /api/tags); a
911
+ // changed list is re-pushed to this client when the probe lands.
912
+ scheduleProviderModelsRefresh(ctx, ws, activeProvider)
913
+ }
914
+ send(ws, {
915
+ type: 'model_changed',
916
+ // #3687: prefer the user's explicit override (`model`) so a later
917
+ // `setModel()` isn't masked by a stale `bootedModel` (SdkSession's
918
+ // setModel doesn't restart, so bootedModel only refreshes on the
919
+ // next init). Fall back to bootedModel when no override was set so
920
+ // tab switches / reconnects see the real running model, not `null`.
921
+ model: (session.model || session.bootedModel)
922
+ ? toShortModelId(session.model || session.bootedModel)
923
+ : null,
924
+ sessionId,
925
+ })
926
+ send(ws, {
927
+ type: 'permission_mode_changed',
928
+ mode: session.permissionMode || 'approve',
929
+ sessionId,
930
+ })
931
+ // Always sync thinking level on reconnect so stale dashboard state is overwritten
932
+ const thinkingLevel = session.thinkingLevel
933
+ if (thinkingLevel !== undefined) {
934
+ send(ws, {
935
+ type: 'thinking_level_changed',
936
+ level: thinkingLevel || 'default',
937
+ sessionId,
938
+ })
939
+ }
940
+ // Replay permission rules so reconnecting clients have current whitelist
941
+ if (typeof session.getPermissionRules === 'function') {
942
+ const rules = session.getPermissionRules()
943
+ if (rules.length > 0) {
944
+ send(ws, { type: 'permission_rules_updated', rules, sessionId })
945
+ }
946
+ }
947
+
948
+ // #5731 T5 / #5623 / #5613: re-sync the session's primary owner so the
949
+ // presence badge ("Observing" / "Take over" / driver name) doesn't go
950
+ // stale across a reconnect or tab switch. `session_role` is otherwise only
951
+ // broadcast on an actual primary change (_announcePrimary), so a client
952
+ // that dropped while a role was assigned would never re-learn it — mirroring
953
+ // the model / permission-mode / thinking-level re-sync above. When the ctx
954
+ // exposes getPrimary (always true for production wiring; a legacy/direct
955
+ // caller without it simply skips this), send unconditionally — including the
956
+ // unclaimed case as `primaryClientId: null`, a valid payload the client uses
957
+ // to CLEAR a stale role. Both clients' `session_role` handlers are pure
958
+ // state-setters (no toast), so re-emitting on every reconnect is idempotent.
959
+ if (typeof ctx.getPrimary === 'function') {
960
+ send(ws, {
961
+ type: 'session_role',
962
+ sessionId,
963
+ primaryClientId: ctx.getPrimary(sessionId) ?? null,
964
+ })
965
+ }
966
+
967
+ // #5160: snapshot-on-subscribe for the Control Room activity tree. A fresh
968
+ // subscriber (new client, tab switch, reconnect) gets the full current tree
969
+ // in one `activity_snapshot` so it reaches canonical state without replaying
970
+ // the `activity_delta` stream — mirroring the `background_work_changed`
971
+ // full-snapshot philosophy. Always sent (empty `entries` is the valid "no
972
+ // in-flight activity" state) so a client can clear any stale tree from a
973
+ // previous session on switch. We stamp the canonical `sessionId` here
974
+ // (matching the live-broadcast path's normalizer injection) rather than
975
+ // trusting whatever internal id the session held.
976
+ if (typeof session.getActivitySnapshot === 'function') {
977
+ const snapshot = session.getActivitySnapshot()
978
+ send(ws, { ...snapshot, sessionId })
979
+ }
980
+ }
981
+
982
+ /**
983
+ * #5555.3 — resolve a client's history cursor for a session into a replay plan.
984
+ *
985
+ * Given the client's `lastSeq` for this session (the highest `historySeq` it
986
+ * has already applied), decide:
987
+ * - `fullHistory`: true → replay the WHOLE retained ring buffer; the client
988
+ * must REBUILD (swap) its message set. This is the
989
+ * backward-compatible default and the fallback for
990
+ * every case we can't honour a cursor.
991
+ * - `fullHistory`: false → CURSOR replay; replay only entries with
992
+ * `_seq > lastSeq`. Naturally append-only on the
993
+ * client; near-zero on a quick reconnect.
994
+ * - `startOffset`: index into `history` of the first entry to send.
995
+ *
996
+ * Fallback to full replay (fullHistory: true, startOffset 0) when:
997
+ * - no cursor supplied (old client, or first connect),
998
+ * - cursor <= 0 (client has nothing yet),
999
+ * - cursor > latestSeq — the client's cursor is numerically AHEAD of the
1000
+ * newest retained entry. This is the server-restart reassignment trap:
1001
+ * `_seq` is server-internal and reassigned 1..N on state restore, so a
1002
+ * client reconnecting after a restart can hold a cursor (e.g. 500) far
1003
+ * above the freshly-reassigned latest (e.g. 300). The trim-gap check below
1004
+ * does NOT catch this (oldest is 1, not `> 501`), and a delta replay would
1005
+ * hand the client an EMPTY slice while it keeps stale messages and never
1006
+ * rebuilds — and the cursor (500) would never recover past latest (300).
1007
+ * Force a full rebuild so the client re-syncs to the authoritative set.
1008
+ * - the oldest RETAINED entry's seq is `> lastSeq + 1` — i.e. the entry the
1009
+ * cursor pointed just-after has been trimmed off the front (or the seqs
1010
+ * reset on a server restart), so a delta replay would leave a gap. The
1011
+ * client can't append across a gap, so it must rebuild.
1012
+ *
1013
+ * When `lastSeq === latestSeq` the client is already current: cursor replay with
1014
+ * an empty slice (startOffset === history.length). The caller still emits the
1015
+ * start/end frames so the client clears its `receivingHistoryReplay` flag and
1016
+ * resolves any stale prompts — just with nothing to append.
1017
+ *
1018
+ * @param {object} sessionManager
1019
+ * @param {Array} history - the retained ring buffer (already fetched)
1020
+ * @param {string} sessionId
1021
+ * @param {number|null|undefined} lastSeq - client cursor, if any
1022
+ * @param {number} [latestSeq] - seq of the newest retained entry (0 when empty)
1023
+ * @returns {{ fullHistory: boolean, startOffset: number }}
1024
+ */
1025
+ export function resolveReplayPlan(sessionManager, history, sessionId, lastSeq, latestSeq) {
1026
+ // No cursor / nothing applied yet → full replay (backward compatible).
1027
+ if (typeof lastSeq !== 'number' || !Number.isFinite(lastSeq) || lastSeq <= 0) {
1028
+ return { fullHistory: true, startOffset: 0 }
1029
+ }
1030
+ // Cursor ahead of the newest retained entry (server-restart seq reassignment,
1031
+ // or any seq regression): a delta replay would yield an empty slice and leave
1032
+ // the client wedged on stale messages with a cursor that never recovers. Force
1033
+ // a full rebuild. `latestSeq` is sourced by the caller from
1034
+ // getLatestHistorySeq; fall back to a fetch here so a direct caller / test
1035
+ // that omits it still gets the guard.
1036
+ const resolvedLatest = typeof latestSeq === 'number' && Number.isFinite(latestSeq)
1037
+ ? latestSeq
1038
+ : (typeof sessionManager.getLatestHistorySeq === 'function'
1039
+ ? sessionManager.getLatestHistorySeq(sessionId)
1040
+ : 0)
1041
+ if (lastSeq > resolvedLatest) {
1042
+ return { fullHistory: true, startOffset: 0 }
1043
+ }
1044
+ const oldestSeq = typeof sessionManager.getOldestHistorySeq === 'function'
1045
+ ? sessionManager.getOldestHistorySeq(sessionId)
1046
+ : null
1047
+ // Empty history can't happen here (caller guards history.length), but be safe.
1048
+ if (oldestSeq === null) return { fullHistory: true, startOffset: 0 }
1049
+ // Trim gap (or post-restart seq reset): the entry just after the cursor is
1050
+ // gone, so a delta replay would skip entries. Rebuild instead.
1051
+ if (oldestSeq > lastSeq + 1) {
1052
+ return { fullHistory: true, startOffset: 0 }
1053
+ }
1054
+ // Cursor honoured — find the first entry strictly newer than lastSeq. The
1055
+ // ring buffer is seq-ordered, so a linear scan from the front is fine (and
1056
+ // typically lands on the tail for a quick reconnect).
1057
+ let startOffset = 0
1058
+ while (startOffset < history.length && (history[startOffset]._seq || 0) <= lastSeq) {
1059
+ startOffset++
1060
+ }
1061
+ return { fullHistory: false, startOffset }
1062
+ }
1063
+
1064
+ /**
1065
+ * Replay message history for a session to a single client.
1066
+ * Sends the retained ring buffer in batches to yield the event loop.
1067
+ *
1068
+ * #5555.3 — honours an optional per-session client cursor
1069
+ * (`client.historyCursors[sessionId]`). When the cursor can be honoured the
1070
+ * replay is INCREMENTAL: only entries newer than the cursor are sent and the
1071
+ * `history_replay_start` frame carries `fullHistory: false`, telling the client
1072
+ * to APPEND (no message wipe, no blank flash). When the cursor can't be honoured
1073
+ * (no cursor / trimmed past / seq reset) the replay falls back to FULL, with
1074
+ * `fullHistory: true` — the long-standing rebuild path.
1075
+ *
1076
+ * Each replayed entry carries its `historySeq` (the server-internal monotonic
1077
+ * seq) so the client can advance its cursor for the next reconnect.
1078
+ *
1079
+ * The `fullHistory: true` flag is why every reconnect doesn't stack duplicate
1080
+ * ring buffers: without it, the client would append a fresh copy on top of what
1081
+ * it already had. `isReplayDuplicate` cannot save us when ring-buffer entries
1082
+ * and live-broadcast entries have different messageIds — the user-visible
1083
+ * failure is duplicated assistant turns and scrambled order (#3743; discovered
1084
+ * during the v0.7.16 dogfood smoke-test in #3741).
1085
+ */
1086
+ export function replayHistory(ctx, ws, sessionId, opts = {}) {
1087
+ const { sessionManager, send, clients } = ctx
1088
+ if (!sessionManager) return
1089
+ const history = sessionManager.getHistory(sessionId)
1090
+ if (history.length === 0) return
1091
+
1092
+ const truncated = sessionManager.isHistoryTruncated(sessionId)
1093
+
1094
+ // #5555.3 — resolve the client's cursor into a replay plan. clients map may
1095
+ // be absent in some test fixtures → treat as no cursor (full replay).
1096
+ //
1097
+ // `opts.forceFull` short-circuits the cursor and forces a FULL rebuild. The
1098
+ // CONNECT handshake (sendPostAuthInfo) honours the cursor — the client was
1099
+ // fully disconnected, so no background live messages arrived to desync it.
1100
+ // SESSION SWITCH (session-handlers.js) passes forceFull: a background session
1101
+ // streams live broadcasts into the client's per-session messages WHILE it's
1102
+ // viewed elsewhere, so the cursor lags behind those live appends and a delta
1103
+ // replay would re-send (and, with mismatched ids, duplicate) them. Forcing a
1104
+ // full rebuild on switch keeps the long-standing authoritative-replace
1105
+ // semantics and the atomic swap (#5555.4) hides the rebuild with no flash.
1106
+ const client = clients && typeof clients.get === 'function' ? clients.get(ws) : null
1107
+ const lastSeq = opts.forceFull ? undefined : client?.historyCursors?.[sessionId]
1108
+
1109
+ // `latestSeq` rides the start frame so the client can advance its cursor even
1110
+ // when the slice is empty (already-current reconnect) — there'd be no entry
1111
+ // to read a `historySeq` off otherwise. Defensive against legacy ctx fixtures
1112
+ // whose manager predates the seq helper. Computed BEFORE resolveReplayPlan so
1113
+ // the cursor-ahead-of-latest guard (#5555.3 server-restart trap) can use it.
1114
+ const latestSeq = typeof sessionManager.getLatestHistorySeq === 'function'
1115
+ ? sessionManager.getLatestHistorySeq(sessionId)
1116
+ : 0
1117
+ const { fullHistory, startOffset } = resolveReplayPlan(sessionManager, history, sessionId, lastSeq, latestSeq)
1118
+
1119
+ send(ws, { type: 'history_replay_start', sessionId, truncated, fullHistory, latestSeq })
1120
+
1121
+ const CHUNK_SIZE = 20
1122
+ const sendChunk = (offset) => {
1123
+ if (ws.readyState !== 1) return
1124
+ // #4833 follow-up: gate chunk *entry* on bufferedAmount too, not just
1125
+ // chunk *scheduling*. The recursive setImmediate-via-scheduleAfterDrain
1126
+ // path is already gated, but the very first sendChunk(0) call can land
1127
+ // on a socket that's already congested from the preceding
1128
+ // sendPostAuthInfo / session_switched burst. Without this check, the
1129
+ // first history entry would be sent unconditionally and the mid-chunk
1130
+ // break (which only fires *after* a send) wouldn't trip until i=1 —
1131
+ // meaning we still push one fat tool_result onto an already-congested
1132
+ // socket and can trip the 1MB EVICT_THRESHOLD.
1133
+ if ((ws.bufferedAmount || 0) > BACKPRESSURE_PAUSE_THRESHOLD) {
1134
+ scheduleAfterDrain(ws, () => sendChunk(offset))
1135
+ return
1136
+ }
1137
+ const end = Math.min(offset + CHUNK_SIZE, history.length)
1138
+ let nextOffset = end
1139
+ for (let i = offset; i < end; i++) {
1140
+ const entry = history[i]
1141
+ // #5555.3 — surface the server-internal `_seq` to the client as
1142
+ // `historySeq` (and strip the underscore-prefixed internal field) so the
1143
+ // client can advance its per-session cursor as it applies each entry.
1144
+ const { _seq, ...wireEntry } = entry
1145
+ send(ws, { ...wireEntry, sessionId, ...(typeof _seq === 'number' ? { historySeq: _seq } : {}) })
1146
+ // #4628: mirror the live `result → agent_idle` fan-out from
1147
+ // event-normalizer.js. The dashboard's handler dispatch table has
1148
+ // no `result` entry — only `agent_idle` — so a raw `result` in
1149
+ // history-replay is silently dropped, and `handleAgentIdle`
1150
+ // (which clears activeTools as the #4308 safety net) never fires.
1151
+ // Without this, a session that completed cleanly but had an
1152
+ // orphan tool_start in history (e.g. dropped PostToolUse hook,
1153
+ // #4628 root cause) shows a zombie "Running X" chip every time
1154
+ // the dashboard reconnects, until the next chroxy restart. The
1155
+ // companion `_emitResult` sweep in BaseSession prevents new
1156
+ // orphans from being persisted; this heals the existing wedged
1157
+ // sessions on reconnect without requiring a restart.
1158
+ if (entry && entry.type === 'result') {
1159
+ send(ws, { type: 'agent_idle', sessionId })
1160
+ }
1161
+ // #4833: break out of the chunk early if bufferedAmount already
1162
+ // crossed the pause threshold mid-burst. The CHUNK_SIZE=20 cap was
1163
+ // designed for short messages; a session with fat tool_result
1164
+ // payloads (200KB+) can blow past the 1MB EVICT_THRESHOLD inside
1165
+ // a single chunk, before the post-chunk scheduleAfterDrain ever
1166
+ // gets to inspect bufferedAmount. Pause + resume from the next
1167
+ // unsent entry instead.
1168
+ if (i + 1 < end && (ws.bufferedAmount || 0) > BACKPRESSURE_PAUSE_THRESHOLD) {
1169
+ nextOffset = i + 1
1170
+ break
1171
+ }
1172
+ }
1173
+ if (nextOffset < history.length) {
1174
+ // #4833: pause if the socket is already congested before scheduling
1175
+ // the next chunk. Without this, every setImmediate fires another
1176
+ // burst regardless of buffer pressure, blowing past the 1MB
1177
+ // EVICT_THRESHOLD in ws-client-sender.js on sessions with fat
1178
+ // tool_result payloads.
1179
+ scheduleAfterDrain(ws, () => sendChunk(nextOffset))
1180
+ } else {
1181
+ send(ws, { type: 'history_replay_end', sessionId, latestSeq })
1182
+ }
1183
+ }
1184
+ // #5555.3 — start at the resolved offset: 0 for a full replay, the
1185
+ // first-newer-than-cursor index for a delta replay. When the client is
1186
+ // already current (startOffset === history.length) this immediately falls
1187
+ // through to the empty-slice path and emits start+end with nothing between.
1188
+ if (startOffset >= history.length) {
1189
+ send(ws, { type: 'history_replay_end', sessionId, latestSeq })
1190
+ } else {
1191
+ sendChunk(startOffset)
1192
+ }
1193
+ }
1194
+
1195
+ /**
1196
+ * Flush queued post-auth messages in batches to yield the event loop.
1197
+ * Same chunking pattern as replayHistory.
1198
+ */
1199
+ export function flushPostAuthQueue(ctx, ws, queue) {
1200
+ const { clients, send } = ctx
1201
+ const client = clients.get(ws)
1202
+ if (client) client._flushing = true
1203
+ const CHUNK_SIZE = 20
1204
+ const drainChunk = (offset) => {
1205
+ if (ws.readyState !== 1) {
1206
+ if (client) {
1207
+ client._flushing = false
1208
+ client._flushOverflow = null
1209
+ }
1210
+ return
1211
+ }
1212
+ // #4833 follow-up: gate chunk *entry* on bufferedAmount too — same
1213
+ // rationale as replayHistory.sendChunk above. drainChunk(0) is invoked
1214
+ // synchronously from flushPostAuthQueue, so the very first queued
1215
+ // message can land on an already-congested socket (e.g. fat post-auth
1216
+ // payloads that were queued during the encryption handshake) before the
1217
+ // mid-chunk break (which only fires after a send) gets a chance to
1218
+ // pause. Keep _flushing = true so any callers using ws-client-sender's
1219
+ // _flushing buffer still queue overflow instead of blasting past us.
1220
+ if ((ws.bufferedAmount || 0) > BACKPRESSURE_PAUSE_THRESHOLD) {
1221
+ if (client) client._flushing = true
1222
+ scheduleAfterDrain(ws, () => drainChunk(offset))
1223
+ return
1224
+ }
1225
+ const end = Math.min(offset + CHUNK_SIZE, queue.length)
1226
+ if (client) client._flushing = false
1227
+ let nextOffset = end
1228
+ for (let i = offset; i < end; i++) {
1229
+ send(ws, queue[i])
1230
+ // #4833: break early if a fat queued message just tipped bufferedAmount
1231
+ // past the pause threshold — same rationale as replayHistory above.
1232
+ if (i + 1 < end && (ws.bufferedAmount || 0) > BACKPRESSURE_PAUSE_THRESHOLD) {
1233
+ nextOffset = i + 1
1234
+ break
1235
+ }
1236
+ }
1237
+ if (nextOffset < queue.length) {
1238
+ if (client) client._flushing = true
1239
+ // #4833: pause if the socket is already congested before scheduling
1240
+ // the next chunk — same rationale as replayHistory above.
1241
+ scheduleAfterDrain(ws, () => drainChunk(nextOffset))
1242
+ } else if (client) {
1243
+ if (client._flushOverflow?.length) {
1244
+ const overflow = client._flushOverflow
1245
+ client._flushOverflow = null
1246
+ flushPostAuthQueue(ctx, ws, overflow)
1247
+ }
1248
+ }
1249
+ }
1250
+ drainChunk(0)
1251
+ }