@chroxy/server 0.11.0 → 0.11.10

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 (317) hide show
  1. package/CONFIG.md +204 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1203 -36
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +19 -0
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +11 -5
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +69 -5
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +92 -7
  37. package/src/byok-mcp-config.js +628 -121
  38. package/src/byok-mcp-fleet.js +49 -7
  39. package/src/byok-mcp-oauth-store.js +18 -16
  40. package/src/byok-mcp-trust.js +3 -3
  41. package/src/byok-session.js +650 -175
  42. package/src/byok-tool-executor.js +2662 -26
  43. package/src/byok-tools.js +9 -2
  44. package/src/channels/chroxy-channel-server.js +2 -3
  45. package/src/checkpoint-manager.js +64 -46
  46. package/src/claude-channel-session.js +16 -10
  47. package/src/claude-model-catalog.js +131 -16
  48. package/src/claude-model-refresh.js +385 -0
  49. package/src/claude-model-request.js +103 -0
  50. package/src/claude-stream-parser.js +53 -3
  51. package/src/claude-tui/diagnostic-tail.js +83 -0
  52. package/src/claude-tui/form-driver.js +44 -7
  53. package/src/claude-tui/model-error.js +41 -0
  54. package/src/claude-tui/pty-driver.js +211 -88
  55. package/src/claude-tui/sanitize-question-payload.js +109 -0
  56. package/src/claude-tui/usage-limit.js +239 -0
  57. package/src/claude-tui-session.js +3513 -287
  58. package/src/claude-tui-tool-response.js +300 -0
  59. package/src/cli/agent-control-cmd.js +65 -0
  60. package/src/cli/config-cmd.js +4 -4
  61. package/src/cli/config-dir-cmd.js +234 -0
  62. package/src/cli/deploy-cmd.js +45 -10
  63. package/src/cli/doctor-cmd.js +7 -3
  64. package/src/cli/init-cmd.js +15 -16
  65. package/src/cli/providers-cmd.js +3 -3
  66. package/src/cli/schedule-cmd.js +68 -39
  67. package/src/cli/server-cmd.js +48 -1
  68. package/src/cli/service-cmd.js +33 -10
  69. package/src/cli/session-cmd.js +227 -74
  70. package/src/cli/shared.js +162 -11
  71. package/src/cli/tokens-cmd.js +4 -5
  72. package/src/cli/tunnel-cmd.js +255 -24
  73. package/src/cli/worktree-gc-cmd.js +2 -2
  74. package/src/cli-session.js +1066 -121
  75. package/src/cli.js +4 -0
  76. package/src/codex-app-server-client.js +36 -3
  77. package/src/codex-app-server-session.js +1454 -79
  78. package/src/codex-bundled-client.js +66 -0
  79. package/src/codex-model-catalog.js +548 -0
  80. package/src/codex-model-rejections.js +87 -0
  81. package/src/codex-native-resume.js +104 -0
  82. package/src/codex-protocol-capabilities.js +188 -0
  83. package/src/codex-session.js +450 -27
  84. package/src/config-dir-migration.js +444 -0
  85. package/src/config-dir.js +108 -0
  86. package/src/config.js +286 -26
  87. package/src/connection-authority.js +48 -0
  88. package/src/connection-info.js +5 -9
  89. package/src/connection-locality.js +60 -0
  90. package/src/container-liveness-monitor.js +189 -0
  91. package/src/continuation-metadata-worker.js +17 -0
  92. package/src/continuations.js +114 -0
  93. package/src/control-room/host-prune.js +5 -0
  94. package/src/control-room/integrations.js +7 -20
  95. package/src/control-room/skills-inventory.js +2 -2
  96. package/src/conversation-scanner.js +40 -18
  97. package/src/conversation-scope.js +59 -39
  98. package/src/conversation-search.js +24 -22
  99. package/src/credential-store.js +23 -19
  100. package/src/daemon-commit.js +92 -0
  101. package/src/daemon-idle-state.js +171 -0
  102. package/src/daemon-update-status.js +314 -0
  103. package/src/dashboard-build.js +70 -0
  104. package/src/declared-status.js +90 -0
  105. package/src/deepseek-credentials.js +2 -3
  106. package/src/dev-preview.js +169 -182
  107. package/src/device-preferences.js +2 -2
  108. package/src/diff-parser.js +87 -0
  109. package/src/discord-credentials.js +2 -3
  110. package/src/docker-byok-pool.js +3 -1
  111. package/src/docker-byok-session.js +678 -78
  112. package/src/docker-image-allowlist.js +23 -1
  113. package/src/docker-sdk-session.js +172 -3
  114. package/src/docker-session.js +284 -10
  115. package/src/doctor.js +767 -61
  116. package/src/edited-input.js +264 -0
  117. package/src/environment-manager.js +175 -36
  118. package/src/environments/authority.js +95 -0
  119. package/src/environments/backends/container-claude-spawn.js +94 -0
  120. package/src/environments/backends/docker.js +31 -10
  121. package/src/environments/backends/k8s.js +49 -24
  122. package/src/environments/destroy-with-sessions.js +142 -0
  123. package/src/event-ingest.js +118 -13
  124. package/src/event-normalizer.js +151 -233
  125. package/src/gemini-session.js +81 -5
  126. package/src/handler-utils.js +535 -68
  127. package/src/handlers/checkpoint-handlers.js +39 -4
  128. package/src/handlers/control-room-handlers.js +51 -11
  129. package/src/handlers/conversation-handlers.js +469 -56
  130. package/src/handlers/daemon-update-handlers.js +81 -0
  131. package/src/handlers/evaluator-handlers.js +14 -1
  132. package/src/handlers/feature-handlers.js +186 -69
  133. package/src/handlers/file-handlers.js +57 -13
  134. package/src/handlers/input-handlers.js +685 -48
  135. package/src/handlers/orchestration-handlers.js +3 -3
  136. package/src/handlers/scheduler-handlers.js +88 -14
  137. package/src/handlers/session-handlers.js +542 -20
  138. package/src/handlers/session-pr-status-handlers.js +283 -0
  139. package/src/handlers/session-pr-threads-handlers.js +247 -0
  140. package/src/handlers/settings-handlers.js +330 -42
  141. package/src/handlers/skills-handlers.js +13 -4
  142. package/src/handlers/summarize-handlers.js +32 -1
  143. package/src/handlers/survey-throttle.js +380 -0
  144. package/src/health-proof.js +40 -0
  145. package/src/history-page.js +104 -0
  146. package/src/http-routes.js +127 -8
  147. package/src/ide/search.js +24 -6
  148. package/src/ide/symbols.js +20 -6
  149. package/src/input-context.js +117 -0
  150. package/src/instruction-policy-compiler.js +229 -0
  151. package/src/instruction-policy.js +250 -0
  152. package/src/jsonl-reader.js +289 -82
  153. package/src/jsonl-subprocess-session.js +92 -8
  154. package/src/keychain.js +1 -1
  155. package/src/logger.js +63 -17
  156. package/src/mailbox-route.js +11 -22
  157. package/src/message-wire.js +386 -0
  158. package/src/model-discovery.js +43 -3
  159. package/src/models.js +1276 -174
  160. package/src/notification-prefs.js +12 -4
  161. package/src/notifications/discord-billing-sink.js +22 -5
  162. package/src/notifications/discord-ci-sink.js +243 -0
  163. package/src/notifications/discord-webhook-client.js +71 -0
  164. package/src/notifications/discord-webhook-sink.js +64 -23
  165. package/src/notifications/expo-push-sink.js +85 -6
  166. package/src/notifications/ready-body.js +16 -5
  167. package/src/ollama-session.js +34 -2
  168. package/src/orchestration/build-manager.js +9 -2
  169. package/src/orchestration/git-ops.js +41 -7
  170. package/src/orchestration/orchestration-manager.js +80 -33
  171. package/src/orchestration/permission-gate.js +13 -1
  172. package/src/orchestration/run-model.js +2 -1
  173. package/src/orchestration/turn-driver.js +44 -20
  174. package/src/orphan-reaper.js +413 -0
  175. package/src/outgoing-policy.js +183 -0
  176. package/src/pairing.js +92 -13
  177. package/src/path-hash-trust-ledger.js +642 -25
  178. package/src/permission-deadlines.js +82 -0
  179. package/src/permission-floor.js +1357 -42
  180. package/src/permission-hook.js +180 -69
  181. package/src/permission-manager.js +712 -83
  182. package/src/permission-mode-support.js +35 -0
  183. package/src/permission-resolver.js +122 -8
  184. package/src/permission-scope.js +43 -0
  185. package/src/platform.js +159 -43
  186. package/src/preview-ingress.js +54 -0
  187. package/src/preview-target.js +213 -0
  188. package/src/prompt-evaluator.js +34 -4
  189. package/src/provider-customization.js +180 -0
  190. package/src/providers.js +207 -4
  191. package/src/push.js +30 -4
  192. package/src/question-route-map.js +130 -0
  193. package/src/redaction.js +360 -8
  194. package/src/roster-broadcast.js +186 -0
  195. package/src/scheduled-task-store.js +318 -26
  196. package/src/scheduler.js +73 -3
  197. package/src/sdk-session.js +2060 -187
  198. package/src/server-cli/preview-shutdown.js +22 -0
  199. package/src/server-cli/push-notification-handler.js +11 -2
  200. package/src/server-cli/server-orchestrator.js +28 -5
  201. package/src/server-cli-child.js +33 -18
  202. package/src/server-cli.js +524 -38
  203. package/src/server-identity.js +15 -11
  204. package/src/service.js +396 -25
  205. package/src/session-archive-limits.js +15 -0
  206. package/src/session-archive.js +1029 -0
  207. package/src/session-busy-state.js +72 -0
  208. package/src/session-ci-watcher.js +926 -0
  209. package/src/session-context.js +7 -2
  210. package/src/session-manager.js +3491 -312
  211. package/src/session-message-history.js +722 -16
  212. package/src/session-pr-status.js +654 -0
  213. package/src/session-pr-threads.js +271 -0
  214. package/src/session-preset-trust.js +3 -3
  215. package/src/session-preset.js +10 -5
  216. package/src/session-state-persistence.js +94 -17
  217. package/src/session-timeout-manager.js +20 -0
  218. package/src/session-token-store.js +17 -8
  219. package/src/session-wake.js +240 -0
  220. package/src/shell-approval-info.js +2 -2
  221. package/src/shell-approval-store.js +3 -1
  222. package/src/skills-loader.js +7 -4
  223. package/src/skills-manager.js +2 -2
  224. package/src/skills-trust.js +95 -13
  225. package/src/skills-usage.js +2 -3
  226. package/src/snapshots-store.js +2 -3
  227. package/src/statusline.js +23 -11
  228. package/src/summarize-session.js +51 -4
  229. package/src/supervisor.js +22 -11
  230. package/src/sweep-stale-provider-dirs.js +95 -0
  231. package/src/thinking-level-wire.js +39 -0
  232. package/src/thinking-stream.js +179 -0
  233. package/src/tool-result.js +61 -0
  234. package/src/transcript-sources.js +109 -0
  235. package/src/transcript-tasks.js +372 -25
  236. package/src/trusted-file-read.js +302 -0
  237. package/src/tunnel/base.js +0 -8
  238. package/src/tunnel/cloudflare.js +34 -31
  239. package/src/tunnel/index.js +9 -0
  240. package/src/tunnel/preview.js +64 -0
  241. package/src/turn-outcome.js +137 -0
  242. package/src/usage-normalize.js +9 -5
  243. package/src/user-shell-session.js +59 -5
  244. package/src/utils/agent-sdk-version.js +107 -0
  245. package/src/utils/argv-safety.js +741 -0
  246. package/src/utils/auth-cause.js +60 -0
  247. package/src/utils/binary-package-manifest.js +597 -0
  248. package/src/utils/binary-version.js +224 -0
  249. package/src/utils/bounded-regex-worker.js +25 -0
  250. package/src/utils/bounded-regex.js +153 -0
  251. package/src/utils/claude-binary.js +43 -0
  252. package/src/utils/claude-config-dir.js +245 -0
  253. package/src/utils/claude-login-command.js +16 -0
  254. package/src/utils/claude-native-route.js +81 -0
  255. package/src/utils/componentwise-resolver.js +133 -37
  256. package/src/utils/deploy-control-files.js +87 -0
  257. package/src/utils/exec-failure-reason.js +21 -0
  258. package/src/utils/git-repo.js +42 -0
  259. package/src/utils/is-entry-point.js +137 -0
  260. package/src/utils/node-pty-probe.js +95 -0
  261. package/src/utils/node-pty-support.js +118 -0
  262. package/src/utils/opened-file-path.js +167 -0
  263. package/src/utils/path-containment.js +165 -0
  264. package/src/utils/permission-mode-sidecar.js +51 -0
  265. package/src/utils/preflight.js +360 -16
  266. package/src/utils/read-limiter.js +217 -0
  267. package/src/utils/regular-file.js +375 -0
  268. package/src/utils/safe-regex.js +113 -0
  269. package/src/utils/small-file.js +129 -0
  270. package/src/utils/spawn-env.js +189 -4
  271. package/src/utils/stale-session-dirs.js +182 -0
  272. package/src/utils/stat-identity.js +43 -0
  273. package/src/utils/verify-provenance.js +406 -13
  274. package/src/web-task-manager.js +256 -16
  275. package/src/worktree-gc.js +7 -2
  276. package/src/ws-auth.js +69 -21
  277. package/src/ws-broadcaster.js +14 -2
  278. package/src/ws-client-manager.js +16 -1
  279. package/src/ws-client-sender.js +7 -0
  280. package/src/ws-file-ops/browser.js +331 -58
  281. package/src/ws-file-ops/common.js +320 -14
  282. package/src/ws-file-ops/git.js +395 -42
  283. package/src/ws-file-ops/index.js +2 -0
  284. package/src/ws-file-ops/memory.js +137 -35
  285. package/src/ws-file-ops/open-nofollow.js +354 -0
  286. package/src/ws-file-ops/reader.js +571 -113
  287. package/src/ws-forwarding.js +329 -39
  288. package/src/ws-handler-context.js +70 -2
  289. package/src/ws-history.js +940 -172
  290. package/src/ws-message-handlers.js +17 -1
  291. package/src/ws-permissions.js +307 -37
  292. package/src/ws-schemas.js +5 -0
  293. package/src/ws-server.js +643 -96
  294. package/sidecar/node_modules/.package-lock.json +0 -29
  295. package/sidecar/node_modules/ws/LICENSE +0 -20
  296. package/sidecar/node_modules/ws/README.md +0 -548
  297. package/sidecar/node_modules/ws/browser.js +0 -8
  298. package/sidecar/node_modules/ws/index.js +0 -22
  299. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  300. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  301. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  302. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  303. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  304. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  305. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  306. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  307. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  308. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  309. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  310. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  311. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  312. package/sidecar/node_modules/ws/package.json +0 -70
  313. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  314. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  315. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  316. package/src/dashboard-next/dist/index.html +0 -13
  317. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
package/src/ws-history.js CHANGED
@@ -4,23 +4,34 @@
4
4
  * Extracted from ws-server.js to separate the post-authentication
5
5
  * handshake and history replay concerns from core server orchestration.
6
6
  */
7
- import { toShortModelId, getRegistryForProvider } from './models.js'
7
+ import { toShortModelId, getRegistryForProvider, resolveRosterProvider } from './models.js'
8
8
  import { getPermissionModes } from './handler-utils.js'
9
- import { listProviders, getProvider } from './providers.js'
9
+ import { buildThinkingLevelChanged } from './thinking-level-wire.js'
10
+ import { listProviders, getProvider, getProviderRuntimeInfo, resolveDaemonDefaultProvider } from './providers.js'
10
11
  import { createLogger } from './logger.js'
12
+ import { isBoundClient } from './environments/authority.js'
13
+ import { streamKindOf, permissionOutcomeDecision } from './session-message-history.js'
11
14
  import { createKeyPair, deriveSharedKey, deriveConnectionKey, signExchangeKey } from '@chroxy/store-core/crypto'
12
15
  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'
16
+ import { MAX_SANE_DURATION_MS, REPLAY_BACKPRESSURE_MAX_WAIT_MS } from '@chroxy/protocol'
14
17
 
15
18
  const log = createLogger('ws')
16
19
 
17
- // #4833 — back-pressure pause for chunked replay/flush loops.
20
+ function permissionModesForProvider(provider) {
21
+ let ProviderClass
22
+ try { ProviderClass = provider ? getProvider(provider) : undefined } catch { /* unknown provider */ }
23
+ return getPermissionModes(provider, ProviderClass)
24
+ }
25
+
26
+ // #4833 — back-pressure pause for the chunked send loop.
18
27
  //
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.
28
+ // `sendChunkedWithBackpressure` emits messages in 20-entry chunks separated by
29
+ // setImmediate yields, on behalf of every path that streams a batch to one
30
+ // client: replayHistory, flushPostAuthQueue, and the two conversation-handler
31
+ // replays. On sessions with fat tool_result payloads (200KB+ each), a single
32
+ // chunk can push ws.bufferedAmount past the 1MB EVICT_THRESHOLD in
33
+ // ws-client-sender.js, tripping a post-send 4008 close and surfacing as a
34
+ // "Reconnecting…" loop in the dashboard.
24
35
  //
25
36
  // Before scheduling the next chunk, the loop now polls bufferedAmount and
26
37
  // pauses (via setTimeout, every BACKPRESSURE_POLL_INTERVAL_MS) until it falls
@@ -29,7 +40,7 @@ const log = createLogger('ws')
29
40
  // links. The poll interval (20ms) is short enough to keep the replay
30
41
  // responsive but long enough to give the socket time to actually flush.
31
42
  //
32
- // Both helpers abort the poll once ws.readyState leaves OPEN (client
43
+ // The loop aborts the poll once ws.readyState leaves OPEN (client
33
44
  // disconnected while paused), so the poll chain terminates on socket close
34
45
  // without sending to a closed socket.
35
46
  //
@@ -42,9 +53,18 @@ const log = createLogger('ws')
42
53
  // from scratch, rather than silently leaking a timer against a dead peer. The
43
54
  // cap is comfortably longer than a healthy slow-link drain but far short of
44
55
  // "forever".
56
+ //
57
+ // #7496: the cap is single-sourced in @chroxy/protocol because a client reads it
58
+ // too. While parked this loop emits NOTHING for the stream, so the dashboard's
59
+ // transcript inactivity watchdog (derived from this value there) must be longer
60
+ // than the longest park or it reports a timeout against a healthy replay.
61
+ // A keepalive frame is not the answer: it would queue behind the bytes that are
62
+ // not draining and arrive only after the park had ended. Do not hardcode a
63
+ // number here — `tests/ws-history-backpressure-cap.test.js` pins that the socket
64
+ // is closed at exactly the shared value.
45
65
  const BACKPRESSURE_PAUSE_THRESHOLD = 256 * 1024
46
66
  const BACKPRESSURE_POLL_INTERVAL_MS = 20
47
- const BACKPRESSURE_MAX_WAIT_MS = 30_000
67
+ const BACKPRESSURE_MAX_WAIT_MS = REPLAY_BACKPRESSURE_MAX_WAIT_MS
48
68
 
49
69
  // #5622 — bound the eager X25519 key derivations done SYNCHRONOUSLY per
50
70
  // event-loop iteration.
@@ -156,6 +176,309 @@ export function scheduleAfterDrain(ws, fn) {
156
176
  setTimeout(poll, BACKPRESSURE_POLL_INTERVAL_MS)
157
177
  }
158
178
 
179
+ // #7460 / #7480 / #7485 — THE implementation of the #4833 chunk-and-drain loop.
180
+ // Every path in the server that streams a batch of frames to one client goes
181
+ // through it: `replayHistory` (connect / session-switch), `flushPostAuthQueue`
182
+ // (below), `handleRequestFullHistory` ("Sync Full History") and
183
+ // `handleRequestConversationTranscript` (the read-only transcript viewer), the
184
+ // last two in conversation-handlers.js.
185
+ //
186
+ // They were four hand-copied variants of the same twelve lines, and every
187
+ // copied piece drifted at least once: the `_seq` -> `historySeq` map (#7454),
188
+ // the `result` -> `agent_idle` synthesis (#7459), the bufferedAmount gating on
189
+ // the full-history replay (#7460) and again on the transcript replay (#7480),
190
+ // and a second chunk-size constant with the same value four lines from this
191
+ // one (#7485). A second copy of this loop is how that divergence started, so
192
+ // there is deliberately only one — and `tests/one-chunk-and-drain-loop.test.js`
193
+ // re-derives that claim from this source on every run rather than trusting
194
+ // this sentence, because a comment beside a set that can grow is exactly the
195
+ // shape docs/false-safety-guards.md catalogues.
196
+ const REPLAY_CHUNK_SIZE = 20
197
+
198
+ /**
199
+ * Send `entries` to `ws` in REPLAY_CHUNK_SIZE batches, yielding the event loop
200
+ * between chunks and pausing whenever `ws.bufferedAmount` climbs past
201
+ * BACKPRESSURE_PAUSE_THRESHOLD (#4833). Three gates, of which TWO carry
202
+ * behaviour on their own:
203
+ *
204
+ * - chunk ENTRY (load-bearing) — the first chunk can land on a socket that is
205
+ * already congested from a preceding burst (post-auth info,
206
+ * session_switched), so it is deferred before anything is written. The
207
+ * mid-chunk break only fires *after* a send, so without this gate one fat
208
+ * payload still lands on a near-eviction buffer.
209
+ * - MID-chunk (load-bearing) — REPLAY_CHUNK_SIZE was sized for short messages;
210
+ * two 200KB tool_results blow past the threshold inside a single chunk, so
211
+ * the loop breaks out and resumes from the next UNSENT entry.
212
+ * - chunk SCHEDULING — pauses before queueing the next chunk. Retained as the
213
+ * inherited #4833 shape, but it is NOT independently load-bearing: replacing
214
+ * it with a bare `setImmediate` is an equivalent mutation, because the next
215
+ * `sendChunk` re-checks the chunk-ENTRY gate and enters the same drain wait
216
+ * (with the same #5328 max-wait cap) one tick later. Established by mutation
217
+ * testing and a 48-scenario differential during review of PR #7479; do not
218
+ * read this line as a third independent guard.
219
+ *
220
+ * `emit(entry, index)` writes one entry; `onDone()` runs once every entry has
221
+ * been written. Neither runs after `ws.readyState` leaves OPEN — a client that
222
+ * disconnects mid-replay gets no further frames and no end marker, which is
223
+ * the behaviour every replay caller already relied on.
224
+ *
225
+ * #7485 — three OPTIONAL hooks let a caller carry state across the gate, which
226
+ * is what `flushPostAuthQueue` needs and what kept it a separate copy of this
227
+ * loop until now. Callers that pass none behave exactly as before:
228
+ *
229
+ * - `onPause()` — fires immediately before the loop parks on a drain (the
230
+ * chunk-entry gate, the mid-chunk break, and the between-chunks yield all
231
+ * park through one place).
232
+ * - `onResume()` — fires each time the loop is CLEAR to write, including the
233
+ * first chunk and including the empty slice, which never enters a chunk
234
+ * body. A hook that only fired after a real pause would leave the
235
+ * empty-queue case latched.
236
+ * - `onAbort()` — fires instead of `onDone` when the loop stops because
237
+ * `ws.readyState` left OPEN. It does NOT fire when the socket dies while
238
+ * parked inside `scheduleAfterDrain` (that chain exits silently, as it
239
+ * always has) or when the #5328 max-wait cap closes the socket.
240
+ *
241
+ * @param {WebSocket} ws - The client socket.
242
+ * @param {Array} entries - The full slice to deliver.
243
+ * @param {{startOffset?: number, emit: (entry: any, index: number) => void, onDone: () => void, onPause?: () => void, onResume?: () => void, onAbort?: () => void}} opts
244
+ */
245
+ export function sendChunkedWithBackpressure(ws, entries, { startOffset = 0, emit, onDone, onPause, onResume, onAbort }) {
246
+ const park = (offset) => {
247
+ if (onPause) onPause()
248
+ scheduleAfterDrain(ws, () => sendChunk(offset))
249
+ }
250
+ const abort = () => { if (onAbort) onAbort() }
251
+ const sendChunk = (offset) => {
252
+ if (ws.readyState !== 1) {
253
+ abort()
254
+ return
255
+ }
256
+ if ((ws.bufferedAmount || 0) > BACKPRESSURE_PAUSE_THRESHOLD) {
257
+ park(offset)
258
+ return
259
+ }
260
+ if (onResume) onResume()
261
+ const end = Math.min(offset + REPLAY_CHUNK_SIZE, entries.length)
262
+ let nextOffset = end
263
+ for (let i = offset; i < end; i++) {
264
+ emit(entries[i], i)
265
+ if (i + 1 < end && (ws.bufferedAmount || 0) > BACKPRESSURE_PAUSE_THRESHOLD) {
266
+ nextOffset = i + 1
267
+ break
268
+ }
269
+ }
270
+ if (nextOffset < entries.length) {
271
+ park(nextOffset)
272
+ } else {
273
+ onDone()
274
+ }
275
+ }
276
+ // Both entry paths are gated on OPEN, not just the chunking one. `sendChunk`
277
+ // re-checks readyState itself (it is also the resume point for every
278
+ // scheduled continuation), but the EMPTY-slice path below reaches `onDone`
279
+ // without going through it — so without this check a client that vanished
280
+ // before an already-current replay still had its `history_replay_end` and
281
+ // re-seed burst written at a dead socket, contradicting the contract stated
282
+ // above. That is the comment-stronger-than-code class
283
+ // (docs/false-safety-guards.md), and it hid in the path taken MOST often:
284
+ // the already-current reconnect (Copilot review, PR #7479).
285
+ if (ws.readyState !== 1) {
286
+ abort()
287
+ return
288
+ }
289
+ // An already-current client (startOffset === entries.length) still gets
290
+ // `onDone` — the empty-slice path, and the most common replay of all.
291
+ if (startOffset >= entries.length) {
292
+ if (onResume) onResume()
293
+ onDone()
294
+ } else {
295
+ sendChunk(startOffset)
296
+ }
297
+ }
298
+
299
+ /**
300
+ * #8374: the client capability that says "I can label a `permission_outcome` whose
301
+ * outcome is `stopped`". Advertised in the auth handshake (CLIENT_CAPABILITIES in
302
+ * @chroxy/protocol).
303
+ */
304
+ const CAPABILITY_PERMISSION_OUTCOME_STOPPED = 'permission_outcome_stopped_v1'
305
+
306
+ /**
307
+ * #6630: the client capability that says "a replayed `error` entry is safe to
308
+ * send me". Errors became part of the transcript (they used to be live-only), and
309
+ * a client build from before that raises its usage-limit alert for a rate-limit
310
+ * error even when it arrives in a replay, so an old app would pop the modal on
311
+ * every session switch for a quota that recovered long ago. Only a client that
312
+ * advertises this (the replay-aware builds) is sent the recorded errors; the rest
313
+ * get the transcript as it was, errors absent.
314
+ */
315
+ export const CAPABILITY_HISTORY_ERROR_REPLAY = 'history_error_replay_v1'
316
+
317
+ /**
318
+ * #6630: the client capability that says "a replayed reasoning entry with NO text is
319
+ * safe to send me". Current Claude models send a thinking block with only its
320
+ * signature, and the server records that as a response entry with `kind: 'thinking'`
321
+ * and empty content. A client build from before `kind` was understood renders it as
322
+ * an empty assistant bubble, one per turn, so only a client that advertises this is
323
+ * sent one. A reasoning entry WITH text is unchanged for everyone (older builds
324
+ * showed reasoning as an answer already).
325
+ */
326
+ export const CAPABILITY_HISTORY_THINKING_REPLAY = 'history_thinking_replay_v1'
327
+
328
+ /**
329
+ * #8470: the client capability that says "a replayed `user_question` carrying
330
+ * `superseded: true` is safe to send me". A newer question replaced it while it
331
+ * was open, so nobody answered it. A client build from before the flag was
332
+ * understood ignores the field and builds the question as a LIVE card: its answer
333
+ * controls are enabled until `history_replay_end` (a replay yields between chunks
334
+ * and can pause under backpressure), and it is then stamped "(resolved)", which
335
+ * reads as answered. Neither is true, and there is no older shape that says
336
+ * "replaced": so such a client is not sent the question at all (the `tool_start`
337
+ * for its tool is still replayed). Only the replay-aware builds get the verdict.
338
+ */
339
+ export const CAPABILITY_HISTORY_QUESTION_SUPERSEDED = 'history_question_superseded_v1'
340
+
341
+ /**
342
+ * #9022: the client capability that says "the text an open stream has produced so far
343
+ * may be replayed to me as an unnumbered `response` entry". A client build from before
344
+ * it reconciles that entry by id only: after a tool split it keeps the snapshot AND
345
+ * its own live `-cont-` bubble, and shows the text twice. It keeps main's behaviour
346
+ * (no snapshot) instead.
347
+ */
348
+ export const CAPABILITY_HISTORY_INFLIGHT_REPLY = 'history_inflight_reply_v1'
349
+
350
+ /**
351
+ * Write ONE history entry to a client, the way BOTH replay paths must.
352
+ *
353
+ * Two things happen per entry, and both were forgotten by the second copy of
354
+ * this loop — which is the whole reason this is a function (#7454, #7459):
355
+ *
356
+ * 1. #5555.3 — surface the server-internal `_seq` as `historySeq` (and strip
357
+ * the underscore-prefixed internal field) so the client can advance its
358
+ * per-session cursor as it applies each entry. #7420's live-vs-replayed
359
+ * discriminator keys on that field's PRESENCE, so a missing stamp reads as
360
+ * a live racer — and a fabricated one is just as wrong.
361
+ * 2. #4628 — mirror the live `result` → `agent_idle` fan-out from
362
+ * event-normalizer.js. `agent_idle` is the frame that clears a zombie
363
+ * "Running X" chip left by an orphan tool_start (a dropped PostToolUse
364
+ * hook, the #4628 root cause): the mobile app has no `activeTools` reader
365
+ * at all, and the dashboard's own `case 'result'` sweep is a redundant
366
+ * second copy of the same wipe rather than an independent one. The
367
+ * companion `_emitResult` sweep in BaseSession stops new orphans being
368
+ * persisted; this heals the sessions already wedged, on every replay path
369
+ * a user can reach.
370
+ *
371
+ * THIS PAIRING IS A WIRE CONTRACT, not an implementation detail (#7515).
372
+ * Until #7515 this comment claimed the clients' `case 'result'` was
373
+ * replay-gated "precisely so a replayed result cannot wipe" what
374
+ * `history_replay_start` preserves — which made the two halves of the
375
+ * paragraph contradict each other, since the very next frame wiped it
376
+ * regardless. The dashboard's gate is gone and its `result` sweep is
377
+ * unconditional again; both clients now depend on this synthesis being
378
+ * the authority. Removing it is a client-visible behaviour change, and
379
+ * `tests/ws-history.test.js`'s "emits synthetic agent_idle after each
380
+ * `result` entry …(#4628)" — which asserts the exact frame ORDER — is the
381
+ * test that must go red first if anyone tries.
382
+ *
383
+ * @param {(ws: WebSocket, payload: object) => void} send
384
+ * @param {WebSocket} ws
385
+ * @param {string} sessionId
386
+ * @param {object} entry - A ring-buffer entry, possibly carrying `_seq`.
387
+ * @param {{clientCapabilities?: Set<string>}|null} [client] - The client RECORD
388
+ * (`clients.get(ws)`), which is where the auth handshake stores the capabilities
389
+ * it advertised. NOT `ws`: that is the raw socket and carries none (#8374).
390
+ */
391
+ export function sendHistoryEntry(send, ws, sessionId, entry, client = null, isSessionBusy = () => false) {
392
+ // #6630: a recorded error goes only to a client that said it can take one in a
393
+ // replay (see CAPABILITY_HISTORY_ERROR_REPLAY). Skipped, not downgraded: there is
394
+ // no older shape of an error bubble that is safe. Nothing else about the entry
395
+ // changes, and the stored entry is untouched for the clients that do advertise it.
396
+ if (
397
+ entry && entry.type === 'message' && entry.messageType === 'error'
398
+ && !(client?.clientCapabilities?.has?.(CAPABILITY_HISTORY_ERROR_REPLAY) ?? false)
399
+ ) {
400
+ return
401
+ }
402
+ // #6630: a text-less reasoning entry goes only to a client that can render it (see
403
+ // CAPABILITY_HISTORY_THINKING_REPLAY). Skipped for the same reason as the error: an
404
+ // older build has no safe shape for it.
405
+ if (
406
+ entry && streamKindOf(entry) === 'thinking'
407
+ && (typeof entry.content !== 'string' || entry.content.length === 0)
408
+ && !(client?.clientCapabilities?.has?.(CAPABILITY_HISTORY_THINKING_REPLAY) ?? false)
409
+ ) {
410
+ return
411
+ }
412
+ // #8470: a question a newer one replaced goes only to a client that can read the
413
+ // flag; see CAPABILITY_HISTORY_QUESTION_SUPERSEDED. Both the in-place entry and the
414
+ // tail copy carry it, so both are skipped.
415
+ if (
416
+ entry && entry.type === 'user_question' && entry.superseded === true
417
+ && !(client?.clientCapabilities?.has?.(CAPABILITY_HISTORY_QUESTION_SUPERSEDED) ?? false)
418
+ ) {
419
+ return
420
+ }
421
+ // `sourceToolUseId` (#8336) is server-internal: it lets the restore-time sweep
422
+ // pair a recorded question with its tool_start, and no client reads it. Live
423
+ // broadcasts never carry it (the event normalizer picks fields), so the replay
424
+ // frame must not either.
425
+ // `answered` (#8362) is likewise server-only: the restore-time sweep reads it to
426
+ // leave an answered question unmarked, and a replayed question reads as resolved
427
+ // on the client already.
428
+ const { _seq, sourceToolUseId: _sourceToolUseId, answered: _answered, ...wireEntry } = entry
429
+ // #8374: a client build from before `stopped` existed drops a `permission_outcome`
430
+ // whose outcome it cannot parse, and a full rebuild then loses the record
431
+ // altogether. Say `expired` to a client that did not advertise it can label the
432
+ // new value: the record survives, only its label degrades. The stored entry is
433
+ // untouched (`wireEntry` is a copy), so a capable client still gets `stopped`.
434
+ // #6630: say on the frame that a recorded response was reasoning, including an
435
+ // entry an older run wrote without the field (classified by its message id),
436
+ // so the client rebuilds the thinking bubble the live stream showed rather than
437
+ // an answer. One classifier; the client reads the field and derives nothing.
438
+ if (streamKindOf(entry) === 'thinking') wireEntry.kind = 'thinking'
439
+ // #8503: a `permission_outcome` carries the tool input its prompt was shown with
440
+ // (already sanitized and capped when recorded). A restored entry whose `input`
441
+ // is not a plain object (a damaged or hand-edited state file) is sent without
442
+ // it rather than as something a client would have to defend against.
443
+ if (wireEntry.type === 'permission_outcome' && 'input' in wireEntry
444
+ && !(wireEntry.input && typeof wireEntry.input === 'object' && !Array.isArray(wireEntry.input))) {
445
+ delete wireEntry.input
446
+ }
447
+ // #8503: the decision token an `allowed` outcome carries; a restored entry whose
448
+ // token is not one the recorder would keep is sent without it.
449
+ if (wireEntry.type === 'permission_outcome' && 'decision' in wireEntry
450
+ && permissionOutcomeDecision(wireEntry.outcome, wireEntry.decision) === undefined) {
451
+ delete wireEntry.decision
452
+ }
453
+ if (wireEntry.type === 'permission_outcome' && wireEntry.outcome === 'stopped'
454
+ && !(client?.clientCapabilities?.has?.(CAPABILITY_PERMISSION_OUTCOME_STOPPED) ?? false)) {
455
+ wireEntry.outcome = 'expired'
456
+ }
457
+ // `replayed: true` on a result is the explicit "this is history" mark (#8965): a
458
+ // JSONL full-history slice strips `_seq` (so no historySeq) yet still carries the
459
+ // daemon-written interrupted-turn result, and a client must not read that as the
460
+ // live turn ending.
461
+ send(ws, {
462
+ ...wireEntry,
463
+ sessionId,
464
+ ...(typeof _seq === 'number' ? { historySeq: _seq } : {}),
465
+ ...(entry && entry.type === 'result' ? { replayed: true } : {}),
466
+ })
467
+ // The synthesized `agent_idle` mirrors the live fan-out so a client clears the
468
+ // turn-scoped state a dropped event left behind (#4628). It must NOT be sent
469
+ // while the session is BUSY (#8965): the entry is an OLD turn's result, the
470
+ // client has nothing to clear for the turn that is still running, and the frame
471
+ // flips the client's isIdle to true -- where nothing sets it back until the next
472
+ // stream_start -- so the Send button shows during a run and a second replay of
473
+ // the same turn sees an idle session. Busy is asked per result, because a replay
474
+ // is chunked and a turn can start part-way through it. The JSONL heal
475
+ // (conversation-handlers.js) already holds the same line. An idle session still
476
+ // gets it.
477
+ if (entry && entry.type === 'result' && !isSessionBusy()) {
478
+ send(ws, { type: 'agent_idle', sessionId })
479
+ }
480
+ }
481
+
159
482
  /**
160
483
  * Send all post-authentication info to a newly authenticated client.
161
484
  * This includes auth_ok, server mode, session list, model/permission state,
@@ -167,7 +490,7 @@ export function scheduleAfterDrain(ws, fn) {
167
490
  export function sendPostAuthInfo(ctx, ws, extra = {}) {
168
491
  const {
169
492
  clients, sessionManager, cliSession, defaultSessionId,
170
- serverMode, serverVersion, latestVersion, gitInfo,
493
+ serverMode, serverVersion, latestVersion, dashboardBuildId, gitInfo,
171
494
  encryptionEnabled, localhostBypass, tunnelActive, keyExchangeTimeoutMs,
172
495
  protocolVersion, minProtocolVersion, webTaskManager,
173
496
  // #5721: `send` MUST be `WsServer._send` (which returns the delivery
@@ -190,6 +513,11 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
190
513
  // surfaced as the `orchestration` capability so the dashboard reveals the
191
514
  // Runs surface. Optional — absent → false (fail-closed) for old servers.
192
515
  orchestrationEnabled,
516
+ // #8619: whether `allowAutoPermissionMode: true` is set in the local
517
+ // config, surfaced as the `autoPermissionMode` capability so clients can
518
+ // disable Auto in their mode pickers and say why. Optional — absent →
519
+ // false (fail-closed) for old callers / test harnesses.
520
+ autoPermissionModeAllowed,
193
521
  // #6006: whether the server has a rotating TokenManager (i.e. auth is on),
194
522
  // so the operator panic button (`revoke_token`) can fire. Surfaced as the
195
523
  // `tokenRevoke` capability, gated to primary-token clients below. Optional —
@@ -212,6 +540,12 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
212
540
  billingCanary,
213
541
  // #5536: long-lived identity keypair for signing the eager exchange key.
214
542
  serverIdentity,
543
+ // #8331: the daily-daemon update status; sent below to strict-primary,
544
+ // unbound clients only. Optional — absent on old callers and test harnesses.
545
+ daemonUpdate,
546
+ // #7821: configured explicit agent routes. Kept on the history context so
547
+ // auth_ok feature derivation and auth_bootstrap use the same live config.
548
+ agentConnections,
215
549
  } = ctx
216
550
  const client = clients.get(ws)
217
551
 
@@ -219,7 +553,11 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
219
553
  let sessionInfo = {}
220
554
  // #6638: the active session's provider, captured for the auth_ok permission-mode
221
555
  // copy (Codex gets codex-tuned descriptions). `entry` below is block-scoped, so
222
- // hoist the provider to function scope.
556
+ // hoist the provider to function scope. #7811: this is `null` when there is no
557
+ // active session, so it is resolved through `resolveRosterProvider` at the
558
+ // send site below (same as `rosterProvider` further down this function)
559
+ // rather than used directly — otherwise a codex-default daemon would fold
560
+ // the CLAUDE mode copy into auth_ok for a client that has no session yet.
223
561
  let authOkProvider = null
224
562
  if (sessionManager) {
225
563
  // #6687: resolve the active session with the SAME precedence block 2 uses to
@@ -250,7 +588,7 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
250
588
  }
251
589
  // If client is bound to a specific session, use that session's cwd
252
590
  // instead of the server default to avoid leaking unrelated session info.
253
- if (client.boundSessionId) {
591
+ if (isBoundClient(client)) {
254
592
  const boundEntry = sessionManager.getSession(client.boundSessionId)
255
593
  if (boundEntry) {
256
594
  entry = boundEntry
@@ -373,7 +711,7 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
373
711
  client.eagerKeyExchange = null
374
712
  }
375
713
 
376
- const providers = listProviders()
714
+ const providers = listProviders({ agentConnections })
377
715
  const features = {
378
716
  environments: providers.some(p => p.capabilities?.containerized),
379
717
  }
@@ -405,6 +743,17 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
405
743
  // (older server) fall back to requesting the three lists as before. The
406
744
  // request handlers stay live either way for post-connect refreshes.
407
745
  authBootstrap: true,
746
+ // #7821 — provider_list/auth_bootstrap include versioned, non-secret agent
747
+ // connection descriptors and create_session accepts an explicit connectionId.
748
+ // New clients require this flag before presenting strong route selection;
749
+ // older clients keep provider-only creation and receive a legacy descriptor.
750
+ agentConnections: true,
751
+ // #8303 — `list_directory` accepts an optional `requestId` and `directory_listing`
752
+ // echoes it. The New Session browsability probe sends only to a server that
753
+ // advertises this: an older one answers untagged, and an untagged reply lands
754
+ // in the shared listing slot (autocomplete / the picker), where an error wipes
755
+ // autocomplete's suggestions.
756
+ directoryListingRequestIdV1: true,
408
757
  // #6481 (epic #6469): the opt-in IDE feature surface (file navigator, symbol
409
758
  // navigation, go-to-definition, find-references, edit-in-place) is enabled on
410
759
  // THIS server (config.features.ide / CHROXY_ENABLE_IDE). Clients gate ALL IDE
@@ -417,6 +766,13 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
417
766
  // Clients gate the Runs surface on this flag; absent/false (default, or older
418
767
  // servers) → no orchestration chrome (fail-closed).
419
768
  orchestration: orchestrationEnabled === true,
769
+ // #8619: the operator's `allowAutoPermissionMode` opt-in. Server-wide, not
770
+ // token-scoped, and NOT a promise that any one session can switch: a
771
+ // paired (bound) client is still refused (AUTO_MODE_FORBIDDEN_BOUND_CLIENT)
772
+ // and an adapter without `autoPermissionMode` still has no Auto. It tells
773
+ // a client only whether the config gate would admit a switch, so it can
774
+ // disable Auto with the real reason instead of a generic tooltip.
775
+ autoPermissionMode: autoPermissionModeAllowed === true,
420
776
  // #6871 (epic #6784): this server has the scheduled-tasks WS surface
421
777
  // (scheduled_tasks_request / scheduled_task_action / set_scheduler_enabled +
422
778
  // the `scheduled_tasks` snapshot). CONSTANT true — deliberately NOT tied to
@@ -425,6 +781,18 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
425
781
  // hide exactly the banner that tells an operator their saved tasks will never
426
782
  // fire. Clients read the real gate state off the snapshot's `scheduler` block.
427
783
  scheduledTasks: true,
784
+ // #7822 — this server validates a versioned selected-context envelope,
785
+ // correlates acceptance with clientMessageId, and rejects unsupported
786
+ // kinds/lifetimes instead of letting an older passthrough schema drop them.
787
+ // New clients must gate context sends on this flag; old clients omit the
788
+ // envelope and continue through the legacy input path.
789
+ inputContextV1: true,
790
+ // #7977 — `create_session` accepts a client `requestId` and echoes it on the
791
+ // create-confirm `session_switched` and every error for that create. A client
792
+ // that needs the correlation (agent-control) must refuse to create on a daemon
793
+ // that lacks this flag: an older daemon would create the session and never
794
+ // echo, orphaning it behind a timeout.
795
+ createRequestIdV1: true,
428
796
  // #5986 (epic #5982) — the embedded user-shell terminal is available to THIS
429
797
  // client: the server has it enabled (userShell.enabled) AND this connection
430
798
  // holds the primary token. Both conditions of the create gate are reflected
@@ -488,28 +856,42 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
488
856
  ? streamStallTimeoutMs
489
857
  : DEFAULT_STREAM_STALL_TIMEOUT_MS
490
858
 
859
+ // #7811: same fallback the roster send further down this function applies —
860
+ // fold in the daemon's resolved default when there is no active session,
861
+ // instead of the CLAUDE default copy that `permissionModesForProvider(null)`
862
+ // returns. Otherwise a codex-default daemon's auth_ok would carry Claude's
863
+ // mode picker text.
864
+ const authOkRosterProvider = resolveRosterProvider(authOkProvider, billingCanary?.defaultProvider)
491
865
  const authOkDelivered = send(ws, {
492
866
  type: 'auth_ok',
493
867
  clientId: client.id,
494
868
  serverMode,
495
869
  serverVersion,
496
870
  latestVersion,
871
+ // #8268: id of the dashboard bundle the daemon serves now; a page that loaded a
872
+ // different one is stale. Omitted (not null) when no dist is built.
873
+ ...(dashboardBuildId ? { dashboardBuildId } : {}),
497
874
  serverCommit: gitInfo.commit,
498
875
  cwd: sessionInfo.cwd,
499
- defaultCwd: sessionManager?.defaultCwd || null,
500
- connectedClients: getConnectedClientList(),
876
+ // A session-scoped connection is told about its own session only: not the
877
+ // host's default working directory, and only the peers sharing its session.
878
+ defaultCwd: isBoundClient(client) ? null : (sessionManager?.defaultCwd || null),
879
+ connectedClients: getConnectedClientList(client),
501
880
  encryption: requireEncryption ? 'required' : 'disabled',
502
881
  protocolVersion,
503
882
  minProtocolVersion,
504
883
  maxProtocolVersion: protocolVersion,
505
884
  webFeatures: webTaskManager.getFeatureStatus(),
506
885
  features,
507
- capabilities,
886
+ capabilities: { ...capabilities, ...(extra.sessionToken ? { pairedCredentialConfirmation: true } : {}) },
508
887
  // #5555 — fold the static permission-mode enum into auth_ok so a new
509
888
  // client never has to wait for (or react to) the discrete
510
889
  // `available_permission_modes` burst frame. The discrete frame is still
511
890
  // sent below for older clients that read the enum only from it.
512
- availablePermissionModes: getPermissionModes(authOkProvider),
891
+ availablePermissionModes: permissionModesForProvider(authOkRosterProvider),
892
+ // #8224 — the roster is a fact about a provider; name it so the client files
893
+ // it under that provider instead of in a slot the next session inherits.
894
+ availablePermissionModesProvider: authOkRosterProvider,
513
895
  resultTimeoutMs: effectiveResultTimeoutMs,
514
896
  hardTimeoutMs: effectiveHardTimeoutMs,
515
897
  streamStallTimeoutMs: effectiveStreamStallTimeoutMs,
@@ -539,6 +921,8 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
539
921
  ? { newIdentityKey: serverIdentity.publicKey, rotationCert: serverIdentity.rotationCert }
540
922
  : {}),
541
923
  ...extra,
924
+ ...(extra.sessionToken && client.clientCapabilities?.has('paired_credential_confirmation_v1')
925
+ ? { sessionToken: undefined } : {}),
542
926
  })
543
927
 
544
928
  // #5555: now that the plaintext auth_ok (carrying serverPublicKey) has been
@@ -593,13 +977,30 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
593
977
  }, keyExchangeTimeoutMs)
594
978
  }
595
979
 
980
+ // Confirm the credential through the completed transport independently of catalogs.
981
+ if (extra.sessionToken && client.clientCapabilities?.has('paired_credential_confirmation_v1')) {
982
+ send(ws, { type: 'auth_bootstrap', credentialConfirmation: true, sessionToken: extra.sessionToken })
983
+ }
984
+
596
985
  send(ws, { type: 'server_mode', mode: serverMode })
597
986
  send(ws, { type: 'status', connected: true })
598
987
 
988
+ // #8331: the "update ready" banner's data. The SAME bar as the
989
+ // `daemon_update_action` it exists to drive: strict primary token AND unbound.
990
+ // A paired phone (an unbound pairing token) must not be told which commits are
991
+ // queued for the owner's machine, and a bound client sees nothing host-level.
992
+ if (daemonUpdate && client?.isPrimaryToken === true && !isBoundClient(client)) {
993
+ try {
994
+ send(ws, { type: 'daemon_update_status', ...daemonUpdate.getStatus() })
995
+ } catch (err) {
996
+ log.warn(`daemon_update_status failed for ${client.id}: ${err?.message || err}`)
997
+ }
998
+ }
999
+
599
1000
  // Multi-session mode
600
1001
  if (sessionManager) {
601
1002
  let sessions = sessionManager.listSessions()
602
- if (client.boundSessionId) {
1003
+ if (isBoundClient(client)) {
603
1004
  sessions = sessions.filter(s => s.sessionId === client.boundSessionId)
604
1005
  }
605
1006
  send(ws, { type: 'session_list', sessions })
@@ -607,7 +1008,8 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
607
1008
  // #5665: send the current monthly programmatic-credit meter snapshot so a
608
1009
  // freshly-connected dashboard shows it immediately, not only after the next
609
1010
  // billed turn. Machine-wide, so it's sent regardless of boundSessionId.
610
- if (typeof sessionManager.getMonthlyBudgetStatus === 'function') {
1011
+ // Not sent to a session-scoped connection: it is the host's spend, not the session's.
1012
+ if (typeof sessionManager.getMonthlyBudgetStatus === 'function' && !isBoundClient(client)) {
611
1013
  send(ws, { type: 'monthly_budget', ...sessionManager.getMonthlyBudgetStatus() })
612
1014
  }
613
1015
 
@@ -616,12 +1018,13 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
616
1018
  // reconnect after the event fired.
617
1019
  if (typeof sessionManager.getFailedRestores === 'function') {
618
1020
  for (const failed of sessionManager.getFailedRestores()) {
619
- if (client.boundSessionId && failed.sessionId !== client.boundSessionId) continue
1021
+ if (isBoundClient(client) && failed.sessionId !== client.boundSessionId) continue
620
1022
  send(ws, {
621
1023
  type: 'session_restore_failed',
622
1024
  sessionId: failed.sessionId,
623
1025
  name: failed.name,
624
1026
  provider: failed.provider,
1027
+ agentConnection: failed.agentConnection,
625
1028
  cwd: failed.cwd,
626
1029
  model: failed.model,
627
1030
  permissionMode: failed.permissionMode,
@@ -674,7 +1077,7 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
674
1077
  // any persisted per-device preference. Fail closed: if the bound session
675
1078
  // no longer exists, clear the active session rather than silently falling
676
1079
  // back to a different session (or inheriting an unrelated persisted pref).
677
- if (client.boundSessionId) {
1080
+ if (isBoundClient(client)) {
678
1081
  const boundEntry = sessionManager.getSession(client.boundSessionId)
679
1082
  if (boundEntry) {
680
1083
  activeId = client.boundSessionId
@@ -724,17 +1127,39 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
724
1127
  // class — getRegistryForProvider returns a provider-scoped registry
725
1128
  // seeded from that list. Claude providers share the default registry
726
1129
  // that is fed by `supportedModels()` on each SDK init.
1130
+ // #7728/#7759 — `activeProvider` is null on any post-auth connect with no
1131
+ // active session, and a null TAG is filed in the client's UNTAGGED bucket,
1132
+ // which it serves to a session of any provider while it is the only roster
1133
+ // it knows — a Claude roster labelled "could be anyone's". So the roster is
1134
+ // tagged with the daemon's resolved default instead, and its registry is
1135
+ // resolved from that SAME name (`resolveRosterProvider`) so the tag names
1136
+ // the registry that actually produced the rows.
1137
+ //
1138
+ // `activeProvider` itself is deliberately left as-is for the discovery
1139
+ // refresh below: that must keep no-opping for a client that has no
1140
+ // session. The permission-mode copy is a DIFFERENT statement — #7811: it
1141
+ // used to also read `activeProvider` (null with no session), so a
1142
+ // codex-default daemon paired the correctly-tagged `rosterProvider` roster
1143
+ // above with the CLAUDE mode-picker copy. It now reads `rosterProvider`
1144
+ // too, same as the roster it describes.
727
1145
  const activeProvider = entry?.provider || null
728
- const activeRegistry = getRegistryForProvider(activeProvider)
729
- send(ws, { type: 'available_models', models: activeRegistry.getModels(), defaultModel: activeRegistry.getDefaultModelId(), provider: activeProvider })
1146
+ const rosterProvider = resolveRosterProvider(activeProvider, billingCanary?.defaultProvider)
1147
+ const activeRegistry = getRegistryForProvider(rosterProvider)
1148
+ send(ws, { type: 'available_models', models: activeRegistry.getModels(), defaultModel: activeRegistry.getDefaultModelId(), provider: rosterProvider })
730
1149
  // #5421/#5555: dynamic-discovery refresh (ollama /api/tags). `sendSessionInfo`
731
1150
  // above was told to skip its own `available_models` push (de-dupe on connect),
732
1151
  // so it also skipped scheduling the refresh — this path now owns the single
733
1152
  // schedule. With no active session activeProvider is null and there is nothing
734
1153
  // to refresh (scheduleProviderModelsRefresh no-ops on a null provider).
735
1154
  scheduleProviderModelsRefresh(ctx, ws, activeProvider)
736
- send(ws, { type: 'available_permission_modes', modes: getPermissionModes(activeProvider) })
737
- permissions.resendPendingPermissions(ws, client)
1155
+ send(ws, { type: 'available_permission_modes', modes: permissionModesForProvider(rosterProvider), provider: rosterProvider })
1156
+ // #9015: the active session's prompts are NOT sent here. `replayHistory`
1157
+ // above always ends in `resendPendingPermissionsForSession` (its empty-history
1158
+ // early return and its `finishReplay` both call it), which delivers them
1159
+ // after `history_replay_end`; sending them here too put two copies on the
1160
+ // wire ~1 ms apart. Every other session, and ownerless hook-held prompts,
1161
+ // still go out through this unfiltered call.
1162
+ permissions.resendPendingPermissions(ws, client, entry ? { excludeSessionId: activeId } : undefined)
738
1163
  // #5555: fire the connect-time bootstrap burst (providers + slash commands
739
1164
  // + agents) so a new client never sends its 3-request list_* round trip.
740
1165
  // Fire-and-forget — the slash/agent compute is async (disk scans) and the
@@ -744,7 +1169,7 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
744
1169
  const bootMcpPrompts = typeof entry?.session?.getMcpPromptCommands === 'function'
745
1170
  ? entry.session.getMcpPromptCommands()
746
1171
  : []
747
- sendAuthBootstrap(ctx, ws, { cwd: entry?.cwd || null, provider: activeProvider, sessionId: activeId, mcpPrompts: bootMcpPrompts })
1172
+ sendAuthBootstrap(ctx, ws, { scoped: isBoundClient(client), cwd: entry?.cwd || null, provider: activeProvider, sessionId: activeId, mcpPrompts: bootMcpPrompts, sessionToken: client.clientCapabilities?.has('paired_credential_confirmation_v1') ? undefined : extra.sessionToken })
748
1173
  return
749
1174
  }
750
1175
 
@@ -767,23 +1192,27 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
767
1192
  // #6368: scope the legacy single-session model list to the ACTIVE provider's
768
1193
  // registry (the cliSession is the default-provider session) instead of the
769
1194
  // Claude-only module-level getModels(). billingCanary.defaultProvider is the
770
- // resolved `config.provider || DEFAULT_PROVIDER`; for Claude (or a null/absent
771
- // canary on old ctx) getRegistryForProvider falls back to the default Claude
772
- // registry, so behaviour is unchanged today.
773
- const legacyProvider = billingCanary?.defaultProvider || null
1195
+ // resolved `config.provider || DEFAULT_PROVIDER`.
1196
+ //
1197
+ // #7759 — an absent canary (old ctx / test fixture) used to leave this
1198
+ // `null`, which resolves to the default Claude registry and then tags the
1199
+ // roster it produced as UNTAGGED at the client. The registry is the same
1200
+ // one either way — DEFAULT_PROVIDER is Claude-family — so what changes is
1201
+ // only that the send now NAMES it.
1202
+ const legacyProvider = resolveRosterProvider(null, billingCanary?.defaultProvider)
774
1203
  const legacyRegistry = getRegistryForProvider(legacyProvider)
775
1204
  send(ws, { type: 'available_models', models: legacyRegistry.getModels(), defaultModel: legacyRegistry.getDefaultModelId(), provider: legacyProvider })
776
1205
  send(ws, {
777
1206
  type: 'permission_mode_changed',
778
1207
  mode: cliSession.permissionMode || 'approve',
779
1208
  })
780
- send(ws, { type: 'available_permission_modes', modes: getPermissionModes(legacyProvider) })
1209
+ send(ws, { type: 'available_permission_modes', modes: permissionModesForProvider(legacyProvider), provider: legacyProvider })
781
1210
  }
782
1211
 
783
- permissions.resendPendingPermissions(ws)
1212
+ permissions.resendPendingPermissions(ws, client)
784
1213
  // #5555: legacy single-session bootstrap burst — providers + slash commands
785
1214
  // + agents for the cliSession's cwd (no provider scoping in legacy mode).
786
- sendAuthBootstrap(ctx, ws, { cwd: cliSession?.cwd || null, provider: null, sessionId: null })
1215
+ sendAuthBootstrap(ctx, ws, { scoped: isBoundClient(client), cwd: cliSession?.cwd || null, provider: null, sessionId: null, sessionToken: client.clientCapabilities?.has('paired_credential_confirmation_v1') ? undefined : extra.sessionToken })
787
1216
  }
788
1217
 
789
1218
  /**
@@ -814,8 +1243,18 @@ export function sendPostAuthInfo(ctx, ws, extra = {}) {
814
1243
  * @param {{ cwd: string|null, provider: string|null, sessionId: string|null }} info
815
1244
  */
816
1245
  function sendAuthBootstrap(ctx, ws, info = {}) {
817
- const { send, services } = ctx
1246
+ const { send, services, agentConnections } = ctx
818
1247
  const fileOps = ctx.fileOps || services?.fileOps || null
1248
+ // #8151 round-2 review (Critical 1) — the real WsServer's `_historyCtx`
1249
+ // carries `config` FLAT (matching `fileOps`/`tunnelUrl` above), never
1250
+ // nested under `services` (that nesting is `_handlerCtx`'s shape, used by
1251
+ // settings-handlers.js's list_providers). Reading ONLY `services?.config`
1252
+ // here silently resolved to `undefined` on every real connection — never
1253
+ // caught because the round-2 test built its ctx by hand, with exactly
1254
+ // the `services.config` shape the (buggy) code expected. Same
1255
+ // either-shape fallback as `fileOps`, so a differently-shaped test ctx
1256
+ // (or a future caller) still works.
1257
+ const config = ctx.config || services?.config || null
819
1258
  const cwd = info.cwd || null
820
1259
  const provider = info.provider || null
821
1260
  // #6823: MCP prompts to fold into the bootstrap slash-command list (empty for
@@ -824,9 +1263,15 @@ function sendAuthBootstrap(ctx, ws, info = {}) {
824
1263
 
825
1264
  // providers is a cheap synchronous read off the registry — same source as
826
1265
  // the list_providers handler.
1266
+ // A session-scoped connection gets neither: the provider list carries the
1267
+ // host's credential readiness and configured connections, and the slash-command
1268
+ // and agent catalogs fall back to the user-level directories when no session
1269
+ // directory resolves. Both still arrive per request for what the connection is
1270
+ // allowed to ask (its own session's catalogs).
1271
+ const scoped = info.scoped === true
827
1272
  let providers = []
828
1273
  try {
829
- providers = listProviders()
1274
+ providers = scoped ? [] : listProviders({ agentConnections })
830
1275
  } catch (err) {
831
1276
  log.warn(`auth_bootstrap: listProviders failed: ${err.message}`)
832
1277
  providers = []
@@ -834,17 +1279,20 @@ function sendAuthBootstrap(ctx, ws, info = {}) {
834
1279
 
835
1280
  // slash commands + agents are async disk scans; compute in parallel and
836
1281
  // tolerate either failing on its own.
837
- const slashP = fileOps && typeof fileOps.computeSlashCommands === 'function'
838
- ? fileOps.computeSlashCommands(cwd, provider, mcpPrompts).catch(err => {
1282
+ const catalogsAllowed = !scoped || cwd !== null
1283
+ const slashP = catalogsAllowed && fileOps && typeof fileOps.computeSlashCommands === 'function'
1284
+ ? fileOps.computeSlashCommands(cwd, provider, mcpPrompts, { projectOnly: scoped }).catch(err => {
839
1285
  log.warn(`auth_bootstrap: computeSlashCommands failed: ${err.message}`)
840
1286
  return []
841
1287
  })
842
1288
  : Promise.resolve([])
843
1289
  const userAgentsDirs = ctx.userAgentsDirs
844
- const agentsOpts = Array.isArray(userAgentsDirs) && userAgentsDirs.length > 0
845
- ? { userAgentsDirs }
846
- : {}
847
- const agentsP = fileOps && typeof fileOps.computeAgents === 'function'
1290
+ const agentsOpts = {
1291
+ ...(Array.isArray(userAgentsDirs) && userAgentsDirs.length > 0 ? { userAgentsDirs } : {}),
1292
+ // A session-scoped connection is bootstrapped with the project's agents only.
1293
+ projectOnly: scoped,
1294
+ }
1295
+ const agentsP = catalogsAllowed && fileOps && typeof fileOps.computeAgents === 'function'
848
1296
  ? fileOps.computeAgents(cwd, agentsOpts).catch(err => {
849
1297
  log.warn(`auth_bootstrap: computeAgents failed: ${err.message}`)
850
1298
  return []
@@ -857,7 +1305,11 @@ function sendAuthBootstrap(ctx, ws, info = {}) {
857
1305
  if (ws.readyState !== 1) return
858
1306
  send(ws, {
859
1307
  type: 'auth_bootstrap',
1308
+ ...(info.sessionToken ? { sessionToken: info.sessionToken } : {}),
860
1309
  providers,
1310
+ // #8151 (C3) — same field/derivation as list_providers' response; see
1311
+ // handleListProviders (settings-handlers.js).
1312
+ defaultProvider: resolveDaemonDefaultProvider(config),
861
1313
  slashCommands,
862
1314
  agents,
863
1315
  ...(info.sessionId ? { sessionId: info.sessionId } : {}),
@@ -891,6 +1343,25 @@ function sendAuthBootstrap(ctx, ws, info = {}) {
891
1343
  * Advisory only — this path feeds the picker; model VALIDATION for ollama
892
1344
  * stays unrestricted via getAllowedModels() returning null (a user can
893
1345
  * `ollama pull` mid-session or use an alias the tag list doesn't spell out).
1346
+ *
1347
+ * #8036 — this is also the ONLY production call site that reaches
1348
+ * `CodexSession.refreshModels()` with no live client: `probeCodexCatalog`
1349
+ * (codex-model-catalog.js) then spawns a short-lived `codex app-server` from
1350
+ * `ProviderClass.resolvedBinary` — a fresh, UNVERIFIED resolve — to answer
1351
+ * `model/list` on every post-auth `available_models` push. A `bin` thunk built
1352
+ * from `SessionManager.verifyOneShotExecutable(ProviderClass)` (#8030's
1353
+ * verified one-shot gate, generalized to take a provider class) is threaded
1354
+ * into `refreshModels(deps)` so that spawn is refused exactly like a fresh
1355
+ * codex chat session would be in `binaryProvenance.mode: 'block'`. Harmless
1356
+ * for every OTHER `refreshModels` implementation (ollama's HTTP `/api/tags`
1357
+ * probe, the anthropic-compatible catalog probe) — neither reads a `bin` key
1358
+ * from `deps`, so the extra property is simply ignored.
1359
+ *
1360
+ * Fails CLOSED when `ctx.sessionManager` is unavailable or too old to expose
1361
+ * `verifyOneShotExecutable` (a stubbed/minimal ctx in a test, or a future
1362
+ * refactor): the `bin` thunk still refuses rather than silently falling back
1363
+ * to `ProviderClass`'s own unverified default — same convention
1364
+ * `summarize-handlers.js` uses for the #8030 summarizer gate.
894
1365
  */
895
1366
  export function scheduleProviderModelsRefresh(ctx, ws, providerName) {
896
1367
  if (!providerName) return
@@ -901,8 +1372,16 @@ export function scheduleProviderModelsRefresh(ctx, ws, providerName) {
901
1372
  return // unknown provider — nothing to refresh
902
1373
  }
903
1374
  if (typeof ProviderClass?.refreshModels !== 'function') return
1375
+ const sessionManager = ctx?.sessionManager
1376
+ const verifyBin = typeof sessionManager?.verifyOneShotExecutable === 'function'
1377
+ ? () => sessionManager.verifyOneShotExecutable(ProviderClass)
1378
+ : () => {
1379
+ const err = new Error(`model refresh for provider ${providerName}: sessionManager.verifyOneShotExecutable is unavailable — refusing an unverified spawn (#8036)`)
1380
+ err.code = 'PROVIDER_BINARY_UNVERIFIED'
1381
+ throw err
1382
+ }
904
1383
  Promise.resolve()
905
- .then(() => ProviderClass.refreshModels())
1384
+ .then(() => ProviderClass.refreshModels({ bin: verifyBin }))
906
1385
  .then((models) => {
907
1386
  if (!Array.isArray(models) || models.length === 0) return
908
1387
  if (ws.readyState !== undefined && ws.readyState !== 1) return // client gone
@@ -933,33 +1412,74 @@ export function scheduleProviderModelsRefresh(ctx, ws, providerName) {
933
1412
  * re-tags the dashboard's provider.
934
1413
  */
935
1414
  export function sendSessionInfo(ctx, ws, sessionId, opts = {}) {
936
- const { sessionManager, send } = ctx
1415
+ const { sessionManager, send, billingCanary, clients } = ctx
937
1416
  const entry = sessionManager?.getSession(sessionId)
938
1417
  if (!entry) return
939
1418
  const session = entry.session
940
1419
 
1420
+ if (entry.declaredStatus) send(ws, { type: 'session_status', sessionId, declaredStatus: { ...entry.declaredStatus } })
1421
+
1422
+ send(ws, {
1423
+ type: 'provider_runtime_info',
1424
+ sessionId,
1425
+ ...getProviderRuntimeInfo(entry.provider, session),
1426
+ })
1427
+
941
1428
  if (session.isReady) {
942
1429
  send(ws, { type: 'claude_ready', sessionId })
943
1430
  }
944
1431
  // #4302: push the new session's provider-scoped model list on every
945
- // switch. Without this, the dashboard's `availableModelsProvider` stays
946
- // tagged with whichever provider the client saw last (set on auth via
947
- // `sendPostAuthInfo`), and `modelsMatchProvider` in App.tsx suppresses
948
- // the model picker for any session whose provider differs from the
949
- // initial one — most visibly, a claude-cli session created after a
950
- // TUI/SDK session loses its picker entirely.
1432
+ // switch. Without this a client never learns the roster of a provider it
1433
+ // did not see at auth time (`sendPostAuthInfo`) — pre-#7728 that showed up
1434
+ // as the dashboard's single `availableModelsProvider` tag staying pinned to
1435
+ // the provider seen last, suppressing the picker for every other session;
1436
+ // since #7728 each roster is keyed by provider, so what a missing push
1437
+ // leaves behind is an EMPTY roster for that provider — no picker, and no
1438
+ // ids belonging to a provider that TAGGED its broadcast.
1439
+ //
1440
+ // #7759 — and no UNTAGGED roster either, on any send path: an entry that
1441
+ // reports no provider (and `sendPostAuthInfo`'s no-active-session case) used
1442
+ // to tag `null`, which the client files in the bucket that means "a
1443
+ // pre-provider daemon" and then serves to a session of any provider. The tag
1444
+ // is the daemon's resolved default in that case, and the registry is
1445
+ // resolved from that same name.
951
1446
  if (!opts.skipModels) {
952
- const activeProvider = entry.provider || null
953
- const activeRegistry = getRegistryForProvider(activeProvider)
1447
+ const rosterProvider = resolveRosterProvider(entry.provider, billingCanary?.defaultProvider)
1448
+ const activeRegistry = getRegistryForProvider(rosterProvider)
954
1449
  send(ws, {
955
1450
  type: 'available_models',
956
1451
  models: activeRegistry.getModels(),
957
1452
  defaultModel: activeRegistry.getDefaultModelId(),
958
- provider: activeProvider,
1453
+ provider: rosterProvider,
959
1454
  })
1455
+ // #8224 — and the permission-mode roster for that same provider. Plan,
1456
+ // Auto and the mode copy differ per provider (claude-tui cannot plan,
1457
+ // claude-sdk can), and this is the one call every path that makes a session
1458
+ // the client's ACTIVE one already makes — create, switch, destroy re-home,
1459
+ // conversation resume, checkpoint rewind of another client — where
1460
+ // `switch_session` used to be the only one that sent it, so a
1461
+ // create-and-auto-switch left the PREVIOUS session's roster in place
1462
+ // ("Plan (unavailable)" on a fresh claude-sdk session beside an active
1463
+ // claude-tui one). Tagged with the provider, so a client keys it by provider.
1464
+ //
1465
+ // Sent ONLY for the client's active session. `handleSubscribeSessions` calls
1466
+ // this for every background session on every `session_list`; a client older
1467
+ // than #8224 keeps one flat roster slot and would end each connect on a
1468
+ // BACKGROUND session's roster. Clients that key by provider lose nothing: the
1469
+ // connect burst, create and switch each cover the active session. (The
1470
+ // connect burst passes `skipModels` and sends its own tagged roster.)
1471
+ if (clients?.get(ws)?.activeSessionId === sessionId) {
1472
+ send(ws, {
1473
+ type: 'available_permission_modes',
1474
+ modes: getPermissionModes(rosterProvider, session.constructor),
1475
+ provider: rosterProvider,
1476
+ })
1477
+ }
960
1478
  // #5421: background dynamic-discovery refresh (ollama /api/tags); a
961
- // changed list is re-pushed to this client when the probe lands.
962
- scheduleProviderModelsRefresh(ctx, ws, activeProvider)
1479
+ // changed list is re-pushed to this client when the probe lands. Keyed on
1480
+ // the session's OWN provider, not the roster tag — a session that reports
1481
+ // none has nothing to probe.
1482
+ scheduleProviderModelsRefresh(ctx, ws, entry.provider || null)
963
1483
  }
964
1484
  send(ws, {
965
1485
  type: 'model_changed',
@@ -979,13 +1499,9 @@ export function sendSessionInfo(ctx, ws, sessionId, opts = {}) {
979
1499
  sessionId,
980
1500
  })
981
1501
  // Always sync thinking level on reconnect so stale dashboard state is overwritten
982
- const thinkingLevel = session.thinkingLevel
983
- if (thinkingLevel !== undefined) {
984
- send(ws, {
985
- type: 'thinking_level_changed',
986
- level: thinkingLevel || 'default',
987
- sessionId,
988
- })
1502
+ const thinkingLevelMsg = buildThinkingLevelChanged(session)
1503
+ if (thinkingLevelMsg) {
1504
+ send(ws, { ...thinkingLevelMsg, sessionId })
989
1505
  }
990
1506
  // Replay permission rules so reconnecting clients have current whitelist.
991
1507
  // #6771 — also replay durable per-project rules (persistentRules) so the
@@ -1134,6 +1650,198 @@ export function resolveReplayPlan(sessionManager, history, sessionId, lastSeq, l
1134
1650
  return { fullHistory: false, startOffset }
1135
1651
  }
1136
1652
 
1653
+ /**
1654
+ * #7509 F7 -- read a list off a provider session for a replay follow-up, and turn
1655
+ * a provider that cannot answer into a LOGGED, empty result instead of a throw.
1656
+ *
1657
+ * `getActiveAgents()` and `getPendingQuestions()` are defined on BaseSession, but
1658
+ * `validateProviderClass` (providers.js) only requires six prototype methods, so
1659
+ * a custom provider that does not extend BaseSession can lack either -- and both
1660
+ * follow-ups run inside `finishReplay`, a `setImmediate` continuation, where a
1661
+ * throw is an uncaught exception that also skips every follow-up after it.
1662
+ *
1663
+ * This is deliberately NOT a feature-detect: the method is still called, so a
1664
+ * provider that lacks it or throws is reported (session id, method, cause) at
1665
+ * error level rather than treated as "nothing to send". It is the ONE place both
1666
+ * follow-ups read through, so a third caller inherits it.
1667
+ *
1668
+ * @param {object} session
1669
+ * @param {string} sessionId
1670
+ * @param {'getActiveAgents' | 'getPendingQuestions'} method
1671
+ * @returns {Array}
1672
+ */
1673
+ function readProviderList(session, sessionId, method) {
1674
+ try {
1675
+ const list = session[method]()
1676
+ if (!Array.isArray(list)) {
1677
+ throw new TypeError(`${method}() returned ${list === null ? 'null' : typeof list}, expected an array`)
1678
+ }
1679
+ return list
1680
+ } catch (err) {
1681
+ log.error(`Replay follow-up ${method}() failed on session ${sessionId}: ${err?.message || err} -- skipping it, the replay still finishes`)
1682
+ return []
1683
+ }
1684
+ }
1685
+
1686
+ /**
1687
+ * #7340 — re-seed a client's `activeAgents` after a history replay.
1688
+ *
1689
+ * Both clients WIPE `activeAgents` on `history_replay_start` (dashboard
1690
+ * `message-handler.ts`, app `message-handler.ts`) because `agent_spawned` /
1691
+ * `agent_completed` are transient and never replayed from history, so anything
1692
+ * they still held could be stale from before the disconnect. That wipe is
1693
+ * correct and is KEPT — it is the only thing that drops a completion the
1694
+ * client missed while offline. What was missing is the other half: nothing
1695
+ * re-asserted the subagents that ARE still running, so a reconnect or a tab
1696
+ * switch silently emptied the badge list.
1697
+ *
1698
+ * Sending the live set here turns the pair into a snapshot REPLACE, mirroring
1699
+ * `activity_snapshot`'s snapshot-on-subscribe and `background_work_changed`'s
1700
+ * full-snapshot philosophy. It runs AFTER `history_replay_end` deliberately:
1701
+ * `sendSessionInfo` is called BEFORE `replayHistory` on both the connect
1702
+ * handshake and the session-switch path, so anything seeded there is erased by
1703
+ * the wipe that follows it.
1704
+ *
1705
+ * Idempotent — both clients dedupe `agent_spawned` by `toolUseId`, so a client
1706
+ * that never lost the entry sees no change.
1707
+ *
1708
+ * Before #7340 this was reachable but pointless (nothing survived a turn end,
1709
+ * so the live set was empty on every replay); with the turn-end exemption a
1710
+ * confirmed-backgrounded subagent is exactly what is in it.
1711
+ */
1712
+ export function reseedActiveAgents(ctx, ws, sessionId) {
1713
+ const { sessionManager, send } = ctx
1714
+ // No `typeof session.getActiveAgents === 'function'` guard: it is defined on
1715
+ // BaseSession, which every provider extends, so it can never be missing --
1716
+ // and a feature-detect that can never fail turns a future regression into a
1717
+ // silent no-op instead of a crash ("cannot check this" read as "nothing to
1718
+ // check", docs/false-safety-guards.md).
1719
+ //
1720
+ // What `readProviderList` adds is the opposite of a feature-detect: the call
1721
+ // is still made, and a provider that lacks it or throws is LOGGED loudly
1722
+ // (#7509 F7), never swallowed -- and never allowed to escape a `setImmediate`
1723
+ // continuation as an uncaught exception that skips the follow-ups after it.
1724
+ const session = sessionManager?.getSession(sessionId)?.session
1725
+ if (!session) return
1726
+ for (const agent of readProviderList(session, sessionId, 'getActiveAgents')) {
1727
+ send(ws, { type: 'agent_spawned', sessionId, ...agent })
1728
+ }
1729
+ }
1730
+
1731
+ /**
1732
+ * #7457 -- re-send the AskUserQuestion prompts a session is still BLOCKED on,
1733
+ * as LIVE frames, immediately after a replay's `history_replay_end`.
1734
+ *
1735
+ * The bug this closes is the non-racing half of #7420. `history_replay_end`
1736
+ * stamps `answered: '(resolved)'` on every unanswered `prompt` the sweep is
1737
+ * entitled to touch, on the premise that anything in history is already
1738
+ * resolved. #7453 carved out the question that arrived LIVE during the replay
1739
+ * and deliberately could not carve out the still-pending one: `user_question`
1740
+ * is not in `builtinTransient`, so it IS in the ring buffer, so the replay
1741
+ * re-delivers it carrying `historySeq` -- correctly classified as
1742
+ * replay-delivered by the only discriminator there is. Background the phone
1743
+ * mid-question, reopen it, and the prompt is a resolved pill with the agent
1744
+ * still blocked on the resolver until it times out.
1745
+ *
1746
+ * Two properties make this the fix rather than a mitigation, and BOTH are why
1747
+ * it lives in `finishReplay` rather than beside `resendPendingPermissions` in
1748
+ * the post-auth block (the issue's own suggestion):
1749
+ *
1750
+ * 1. ORDER. `replayHistory` is chunked and yields the event loop between
1751
+ * chunks, so a call placed after `replayHistory(...)` RETURNS still runs
1752
+ * before `history_replay_end` reaches the client -- which is precisely why
1753
+ * the sweep's own comment can say `resendPendingPermissions` runs "after
1754
+ * replayHistory has already sent its first chunk". Permissions do not care
1755
+ * (they are excluded from the sweep by `requestId`); a question's whole
1756
+ * defence is landing after the end frame, so it must be sequenced by the
1757
+ * replay's completion, not by its invocation.
1758
+ * 2. COVERAGE. `finishReplay` is the ONE exit both replay paths share (#7340),
1759
+ * and `replayHistory` serves connect, `switch_session` (forceFull rebuild),
1760
+ * `subscribe_sessions` and the checkpoint restore alike. Bolted onto the
1761
+ * post-auth block instead, every one of those but connect stays broken.
1762
+ *
1763
+ * The frame carries NO `historySeq`, which is what makes the client treat it as
1764
+ * live: `dispatchUserQuestion` keys #7420's discriminator on that field's
1765
+ * presence. It is otherwise byte-identical to the dispatch-time frame -- no
1766
+ * wire-shape change, no protocol bump, and both clients supersede the copy they
1767
+ * already hold by `toolUseId` rather than stacking a duplicate bubble.
1768
+ *
1769
+ * `getPendingQuestions()` carries no feature-detect for the same reason
1770
+ * `getActiveAgents()` above does not: BaseSession defines it, so a detect here
1771
+ * could never fail and would only convert a future regression into a silent
1772
+ * no-op. It IS read through `readProviderList` (#7509 F7), so a custom provider
1773
+ * that lacks it or throws is logged with the session id and method rather than
1774
+ * escaping `finishReplay`'s `setImmediate` as an uncaught exception.
1775
+ *
1776
+ * No route registration: `_questionSessionMap` entries are pruned only when the
1777
+ * question resolves or its session is destroyed, so a still-pending question is
1778
+ * still mapped, and `handleUserQuestionResponse`'s viewer check is the same
1779
+ * predicate `_broadcastToSession` uses -- a client being replayed this session
1780
+ * necessarily passes it.
1781
+ *
1782
+ * @param {object} ctx
1783
+ * @param {WebSocket} ws
1784
+ * @param {string} sessionId
1785
+ */
1786
+ export function resendPendingQuestions(ctx, ws, sessionId) {
1787
+ const { sessionManager, send } = ctx
1788
+ const session = sessionManager?.getSession(sessionId)?.session
1789
+ if (!session) return
1790
+ for (const { toolUseId, questions } of readProviderList(session, sessionId, 'getPendingQuestions')) {
1791
+ // An entry with no id is unanswerable: `handleUserQuestionResponse` routes
1792
+ // strictly by `toolUseId` and fails closed on one it cannot find. Skip it
1793
+ // rather than send a prompt whose answer can only be dropped -- and skip
1794
+ // only IT, so a malformed entry can't strand the valid ones behind it
1795
+ // (#6054's per-entry isolation, same reason).
1796
+ if (typeof toolUseId !== 'string' || toolUseId.length === 0) {
1797
+ log.warn(`Skipping pending question with no toolUseId on session ${sessionId}`)
1798
+ continue
1799
+ }
1800
+ send(ws, { type: 'user_question', sessionId, toolUseId, questions })
1801
+ }
1802
+ }
1803
+
1804
+ /**
1805
+ * #8328 — re-assert the permission prompts a session is still blocked on, to
1806
+ * ONE client, after a replay of that session.
1807
+ *
1808
+ * `permission_request` is in `builtinTransient`: never in the ring buffer, so a
1809
+ * replay cannot deliver it, and a FULL-rebuild replay (`switch_session`'s
1810
+ * `forceFull`, `subscribe_sessions`) swaps in a message list built from history
1811
+ * alone — dropping the prompt card the client appended LIVE while the session
1812
+ * was a background one. The turn then sits at "Running Bash..." with no card
1813
+ * until the request's timeout denies it. Same shape as `resendPendingQuestions`
1814
+ * above, same fix, and the same reason it hangs off the replay's exit rather
1815
+ * than off `switch_session`: every replay path needs it.
1816
+ *
1817
+ * It delegates to `permissions.resendPendingPermissions` — the ONE
1818
+ * implementation, which the connect-time (unfiltered) resend also uses — and
1819
+ * covers both the SDK-held and the hook-held (claude-tui, the default
1820
+ * provider) pending sets.
1821
+ *
1822
+ * `ctx.permissions` is the permission handler; ctx fixtures that never built
1823
+ * one have nothing to re-send, hence the optional chain on it alone — the
1824
+ * method on a real handler is called unguarded so drift fails loudly.
1825
+ *
1826
+ * Connect (#9015): `sendPostAuthInfo` also does an unfiltered resend, but it
1827
+ * EXCLUDES the active session it is about to replay — this replay-exit call owns
1828
+ * that session's prompts, so they arrive exactly once, after `history_replay_end`.
1829
+ * The unfiltered call still delivers every other session's prompts (and
1830
+ * ownerless hook-held ones); a BACKGROUND session's later `subscribe_sessions`
1831
+ * full-rebuild replay re-asserts its card via this function, which is the
1832
+ * intended second delivery there (clients update in place by `requestId`).
1833
+ *
1834
+ * @param {object} ctx
1835
+ * @param {WebSocket} ws
1836
+ * @param {string} sessionId
1837
+ */
1838
+ export function resendPendingPermissionsForSession(ctx, ws, sessionId) {
1839
+ const { permissions, clients } = ctx
1840
+ if (!permissions) return
1841
+ const client = clients && typeof clients.get === 'function' ? clients.get(ws) : undefined
1842
+ permissions.resendPendingPermissions(ws, client, { sessionId })
1843
+ }
1844
+
1137
1845
  /**
1138
1846
  * Replay message history for a session to a single client.
1139
1847
  * Sends the retained ring buffer in batches to yield the event loop.
@@ -1160,7 +1868,15 @@ export function replayHistory(ctx, ws, sessionId, opts = {}) {
1160
1868
  const { sessionManager, send, clients } = ctx
1161
1869
  if (!sessionManager) return
1162
1870
  const history = sessionManager.getHistory(sessionId)
1163
- if (history.length === 0) return
1871
+ if (history.length === 0) {
1872
+ // #8328: no replay frames means the client does not rebuild this session's
1873
+ // messages, so nothing it holds is dropped here — but a client that never
1874
+ // received the live broadcast (it was not subscribed when the request was
1875
+ // raised) still needs the prompt, and an in-place update by `requestId`
1876
+ // makes the re-send free for one that did.
1877
+ resendPendingPermissionsForSession(ctx, ws, sessionId)
1878
+ return
1879
+ }
1164
1880
 
1165
1881
  const truncated = sessionManager.isHistoryTruncated(sessionId)
1166
1882
 
@@ -1191,134 +1907,186 @@ export function replayHistory(ctx, ws, sessionId, opts = {}) {
1191
1907
 
1192
1908
  send(ws, { type: 'history_replay_start', sessionId, truncated, fullHistory, latestSeq })
1193
1909
 
1194
- const CHUNK_SIZE = 20
1195
- const sendChunk = (offset) => {
1196
- if (ws.readyState !== 1) return
1197
- // #4833 follow-up: gate chunk *entry* on bufferedAmount too, not just
1198
- // chunk *scheduling*. The recursive setImmediate-via-scheduleAfterDrain
1199
- // path is already gated, but the very first sendChunk(0) call can land
1200
- // on a socket that's already congested from the preceding
1201
- // sendPostAuthInfo / session_switched burst. Without this check, the
1202
- // first history entry would be sent unconditionally and the mid-chunk
1203
- // break (which only fires *after* a send) wouldn't trip until i=1 —
1204
- // meaning we still push one fat tool_result onto an already-congested
1205
- // socket and can trip the 1MB EVICT_THRESHOLD.
1206
- if ((ws.bufferedAmount || 0) > BACKPRESSURE_PAUSE_THRESHOLD) {
1207
- scheduleAfterDrain(ws, () => sendChunk(offset))
1208
- return
1209
- }
1210
- const end = Math.min(offset + CHUNK_SIZE, history.length)
1211
- let nextOffset = end
1212
- for (let i = offset; i < end; i++) {
1213
- const entry = history[i]
1214
- // #5555.3 — surface the server-internal `_seq` to the client as
1215
- // `historySeq` (and strip the underscore-prefixed internal field) so the
1216
- // client can advance its per-session cursor as it applies each entry.
1217
- const { _seq, ...wireEntry } = entry
1218
- send(ws, { ...wireEntry, sessionId, ...(typeof _seq === 'number' ? { historySeq: _seq } : {}) })
1219
- // #4628: mirror the live `result → agent_idle` fan-out from
1220
- // event-normalizer.js. The dashboard's handler dispatch table has
1221
- // no `result` entry — only `agent_idle` — so a raw `result` in
1222
- // history-replay is silently dropped, and `handleAgentIdle`
1223
- // (which clears activeTools as the #4308 safety net) never fires.
1224
- // Without this, a session that completed cleanly but had an
1225
- // orphan tool_start in history (e.g. dropped PostToolUse hook,
1226
- // #4628 root cause) shows a zombie "Running X" chip every time
1227
- // the dashboard reconnects, until the next chroxy restart. The
1228
- // companion `_emitResult` sweep in BaseSession prevents new
1229
- // orphans from being persisted; this heals the existing wedged
1230
- // sessions on reconnect without requiring a restart.
1231
- if (entry && entry.type === 'result') {
1232
- send(ws, { type: 'agent_idle', sessionId })
1233
- }
1234
- // #4833: break out of the chunk early if bufferedAmount already
1235
- // crossed the pause threshold mid-burst. The CHUNK_SIZE=20 cap was
1236
- // designed for short messages; a session with fat tool_result
1237
- // payloads (200KB+) can blow past the 1MB EVICT_THRESHOLD inside
1238
- // a single chunk, before the post-chunk scheduleAfterDrain ever
1239
- // gets to inspect bufferedAmount. Pause + resume from the next
1240
- // unsent entry instead.
1241
- if (i + 1 < end && (ws.bufferedAmount || 0) > BACKPRESSURE_PAUSE_THRESHOLD) {
1242
- nextOffset = i + 1
1243
- break
1244
- }
1245
- }
1246
- if (nextOffset < history.length) {
1247
- // #4833: pause if the socket is already congested before scheduling
1248
- // the next chunk. Without this, every setImmediate fires another
1249
- // burst regardless of buffer pressure, blowing past the 1MB
1250
- // EVICT_THRESHOLD in ws-client-sender.js on sessions with fat
1251
- // tool_result payloads.
1252
- scheduleAfterDrain(ws, () => sendChunk(nextOffset))
1253
- } else {
1910
+ // #7340: ONE exit from the replay, because there are two ways out of it (an
1911
+ // empty slice and a drained final chunk) and the re-seed must follow BOTH.
1912
+ // Two `history_replay_end` sends with the follow-up bolted onto only one of
1913
+ // them leaves the empty-slice path — the quick reconnect, the most common
1914
+ // replay of all — silently unfixed.
1915
+ const finishReplay = () => {
1916
+ // #9015: the permission re-send is the ONLY delivery of the active
1917
+ // session's pending prompt on connect (the post-auth resend excludes it), so
1918
+ // it runs in a `finally`: a throw from the end frame or the agent re-seed
1919
+ // must not drop the sole copy. The success path still sends it exactly once.
1920
+ //
1921
+ // #8357: PERMISSIONS BEFORE QUESTIONS. A question card is withheld until its
1922
+ // own AskUserQuestion permission is allowed, and the client can only know
1923
+ // that permission exists once it has arrived. Sent the other way round, a
1924
+ // reconnecting client holds the re-sent question with no permission to gate
1925
+ // it, and can show and answer it before the permission lands: not a
1926
+ // millisecond race, a whole resend apart.
1927
+ try {
1254
1928
  send(ws, { type: 'history_replay_end', sessionId, latestSeq })
1929
+ reseedActiveAgents(ctx, ws, sessionId)
1930
+ } finally {
1931
+ try {
1932
+ // #8328: AFTER the end frame. A full-rebuild replay swaps in a
1933
+ // history-only message list at `history_replay_end`, dropping the live
1934
+ // permission card the client held for this session; `permission_request`
1935
+ // is transient, so the replay itself cannot restore it. Sent after the
1936
+ // swap, the re-send lands on the rebuilt list and is kept.
1937
+ resendPendingPermissionsForSession(ctx, ws, sessionId)
1938
+ } finally {
1939
+ // #7457: AFTER the end frame, never before it. The client's replay-end
1940
+ // sweep has already run by the time this lands, which is the entire
1941
+ // reason a still-pending question survives the reconnect. In its own
1942
+ // `finally` so a failed permission re-send cannot lose the question.
1943
+ resendPendingQuestions(ctx, ws, sessionId)
1944
+ }
1255
1945
  }
1256
1946
  }
1947
+
1948
+ // A manager that cannot answer reads as idle, as in the JSONL heal's own check
1949
+ // (conversation-handlers.js); asked again for each replayed result.
1950
+ const isSessionBusy = () => typeof sessionManager.isSessionBusy === 'function'
1951
+ ? sessionManager.isSessionBusy(sessionId)
1952
+ : false
1953
+
1257
1954
  // #5555.3 — start at the resolved offset: 0 for a full replay, the
1258
1955
  // first-newer-than-cursor index for a delta replay. When the client is
1259
- // already current (startOffset === history.length) this immediately falls
1260
- // through to the empty-slice path and emits start+end with nothing between.
1261
- if (startOffset >= history.length) {
1262
- send(ws, { type: 'history_replay_end', sessionId, latestSeq })
1263
- } else {
1264
- sendChunk(startOffset)
1956
+ // already current (startOffset === history.length) sendChunkedWithBackpressure
1957
+ // falls straight through to the empty-slice path and emits start+end with
1958
+ // nothing between.
1959
+ //
1960
+ // #7460 — the chunk-and-drain machinery and the per-entry wire mapping both
1961
+ // live in ONE place now (above), because `handleRequestFullHistory` is the
1962
+ // second caller of exactly this loop and every hand-copied piece of it has
1963
+ // drifted: the `_seq` map (#7454), the `result` → `agent_idle` synthesis
1964
+ // (#7459), and the bufferedAmount gating (#7460) were each missing there.
1965
+ // #9022 -- a reply is recorded only when its stream closes, so a turn paused
1966
+ // mid-stream (on a permission prompt) has its text in no entry. Splice what has
1967
+ // streamed so far in, at its place in the transcript. The position matters for a
1968
+ // DELTA replay, which appends in arrival order; a full replay's provenance sort
1969
+ // puts the (unnumbered) snapshot after the numbered entries (#9024).
1970
+ const pending = client?.clientCapabilities?.has?.(CAPABILITY_HISTORY_INFLIGHT_REPLY)
1971
+ ? pendingStreamEntries(sessionManager, sessionId)
1972
+ : []
1973
+ const replayEntries = pending.length > 0
1974
+ ? spliceInPendingStreams(history.slice(startOffset), pending)
1975
+ : history
1976
+ sendChunkedWithBackpressure(ws, replayEntries, {
1977
+ startOffset: pending.length > 0 ? 0 : startOffset,
1978
+ // #9015: a throwing entry ABORTS the replay and never claims completion (no
1979
+ // `history_replay_end` carrying `latestSeq` — the client would commit a
1980
+ // partial transcript and its cursor). Permission recovery is independent of
1981
+ // replay success, though: the connect-time resend excludes the active
1982
+ // session, so this abort path delivers its pending prompt (once — the loop
1983
+ // stops and `finishReplay` never runs) and then rethrows, as before.
1984
+ emit: (entry) => {
1985
+ try {
1986
+ sendHistoryEntry(send, ws, sessionId, entry, client, isSessionBusy)
1987
+ } catch (err) {
1988
+ try {
1989
+ resendPendingPermissionsForSession(ctx, ws, sessionId)
1990
+ } catch (resendErr) {
1991
+ log.warn(`Permission re-send after an aborted replay of ${sessionId} failed: ${resendErr?.message ?? resendErr}`)
1992
+ }
1993
+ throw err
1994
+ }
1995
+ },
1996
+ onDone: finishReplay,
1997
+ })
1998
+ }
1999
+
2000
+ /**
2001
+ * #9022 -- the still-open reply streams of a session as replayable entries.
2002
+ *
2003
+ * Sent on a delta replay too, whatever the client's cursor: the client dedups a
2004
+ * reply it already holds by id, completes one it holds only the start of (#8444's
2005
+ * `completeHeldResponseStream`, which also refills deltas missed in a dropped
2006
+ * connection), and keeps one that has run ahead of the snapshot. A cursor filter
2007
+ * would not be a sound "did the client see this stream start" test anyway: live
2008
+ * frames carry no `historySeq`, so a cursor says nothing about a stream's start.
2009
+ *
2010
+ * The entries carry no `_seq`, so a client advances no cursor off them, and no
2011
+ * field the stream's own completed entry lacks: when the stream closes, the
2012
+ * recorded entry has the same `messageId`, so a client that kept this one dedups.
2013
+ */
2014
+ function pendingStreamEntries(sessionManager, sessionId) {
2015
+ if (typeof sessionManager.getPendingResponseStreams !== 'function') return []
2016
+ const streams = sessionManager.getPendingResponseStreams(sessionId)
2017
+ const now = Date.now()
2018
+ return streams.map((s) => ({
2019
+ startSeq: s.startSeq,
2020
+ entry: {
2021
+ type: 'message',
2022
+ messageType: 'response',
2023
+ content: s.content,
2024
+ messageId: s.messageId,
2025
+ timestamp: now,
2026
+ },
2027
+ }))
2028
+ }
2029
+
2030
+ /**
2031
+ * Put each pending-stream entry before the first recorded entry that came after
2032
+ * its stream opened (the end, when none did). Returns a new array; `entries` is
2033
+ * the ring buffer's own and is not touched.
2034
+ */
2035
+ function spliceInPendingStreams(entries, pending) {
2036
+ const out = entries.slice()
2037
+ // Latest-opened first, so an earlier splice never shifts the index a later one
2038
+ // was computed for.
2039
+ const ordered = [...pending].sort((a, b) => b.startSeq - a.startSeq)
2040
+ for (const { startSeq, entry } of ordered) {
2041
+ let at = out.findIndex((e) => typeof e._seq === 'number' && e._seq >= startSeq)
2042
+ if (at === -1) at = out.length
2043
+ out.splice(at, 0, entry)
1265
2044
  }
2045
+ return out
1266
2046
  }
1267
2047
 
1268
2048
  /**
1269
- * Flush queued post-auth messages in batches to yield the event loop.
1270
- * Same chunking pattern as replayHistory.
2049
+ * Flush queued post-auth messages to a client through the shared chunk +
2050
+ * back-pressure loop.
2051
+ *
2052
+ * #7485 — this was the last hand-copied instance of that loop: its own
2053
+ * `CHUNK_SIZE = 20` four lines from `REPLAY_CHUNK_SIZE`, its own readyState
2054
+ * exit, its own chunk-entry gate, its own mid-chunk break and its own
2055
+ * scheduling gate, all maintained in parallel since #4845. What kept it
2056
+ * separate is the queue state it owns on top of the loop, and each piece maps
2057
+ * onto one of the hooks `sendChunkedWithBackpressure` now takes:
2058
+ *
2059
+ * - `_flushing` is the gate ws-client-sender.js reads. It must be TRUE
2060
+ * whenever this flush is parked, so a concurrent `send` lands in
2061
+ * `_flushOverflow` behind the queued messages instead of overtaking them,
2062
+ * and FALSE while a chunk is actually being written — which is exactly
2063
+ * onPause / onResume.
2064
+ * - a socket that leaves OPEN mid-flush must drop BOTH `_flushing` (or every
2065
+ * later send is swallowed by a gate nothing will ever release) and
2066
+ * `_flushOverflow` (nothing will drain it) — onAbort.
2067
+ * - the terminal branch recurses into whatever arrived while we were parked,
2068
+ * rather than sending an end frame — onDone.
1271
2069
  */
1272
2070
  export function flushPostAuthQueue(ctx, ws, queue) {
1273
2071
  const { clients, send } = ctx
1274
2072
  const client = clients.get(ws)
1275
2073
  if (client) client._flushing = true
1276
- const CHUNK_SIZE = 20
1277
- const drainChunk = (offset) => {
1278
- if (ws.readyState !== 1) {
2074
+ sendChunkedWithBackpressure(ws, queue, {
2075
+ emit: (message) => send(ws, message),
2076
+ onPause: () => { if (client) client._flushing = true },
2077
+ onResume: () => { if (client) client._flushing = false },
2078
+ onAbort: () => {
1279
2079
  if (client) {
1280
2080
  client._flushing = false
1281
2081
  client._flushOverflow = null
1282
2082
  }
1283
- return
1284
- }
1285
- // #4833 follow-up: gate chunk *entry* on bufferedAmount too — same
1286
- // rationale as replayHistory.sendChunk above. drainChunk(0) is invoked
1287
- // synchronously from flushPostAuthQueue, so the very first queued
1288
- // message can land on an already-congested socket (e.g. fat post-auth
1289
- // payloads that were queued during the encryption handshake) before the
1290
- // mid-chunk break (which only fires after a send) gets a chance to
1291
- // pause. Keep _flushing = true so any callers using ws-client-sender's
1292
- // _flushing buffer still queue overflow instead of blasting past us.
1293
- if ((ws.bufferedAmount || 0) > BACKPRESSURE_PAUSE_THRESHOLD) {
1294
- if (client) client._flushing = true
1295
- scheduleAfterDrain(ws, () => drainChunk(offset))
1296
- return
1297
- }
1298
- const end = Math.min(offset + CHUNK_SIZE, queue.length)
1299
- if (client) client._flushing = false
1300
- let nextOffset = end
1301
- for (let i = offset; i < end; i++) {
1302
- send(ws, queue[i])
1303
- // #4833: break early if a fat queued message just tipped bufferedAmount
1304
- // past the pause threshold — same rationale as replayHistory above.
1305
- if (i + 1 < end && (ws.bufferedAmount || 0) > BACKPRESSURE_PAUSE_THRESHOLD) {
1306
- nextOffset = i + 1
1307
- break
1308
- }
1309
- }
1310
- if (nextOffset < queue.length) {
1311
- if (client) client._flushing = true
1312
- // #4833: pause if the socket is already congested before scheduling
1313
- // the next chunk — same rationale as replayHistory above.
1314
- scheduleAfterDrain(ws, () => drainChunk(nextOffset))
1315
- } else if (client) {
1316
- if (client._flushOverflow?.length) {
2083
+ },
2084
+ onDone: () => {
2085
+ if (client?._flushOverflow?.length) {
1317
2086
  const overflow = client._flushOverflow
1318
2087
  client._flushOverflow = null
1319
2088
  flushPostAuthQueue(ctx, ws, overflow)
1320
2089
  }
1321
- }
1322
- }
1323
- drainChunk(0)
2090
+ },
2091
+ })
1324
2092
  }