@chroxy/server 0.10.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 (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  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 +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  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 +74 -9
  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 +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
@@ -1,7 +1,12 @@
1
+ import { ServerSessionStatusSchema, ServerActivityDeltaSchema } from '@chroxy/protocol'
1
2
  import { createLogger } from './logger.js'
2
- import { getDefaultModelId, getRegistryForProvider } from './models.js'
3
+ import { getRegistryForProvider, resolveRosterProvider } from './models.js'
3
4
  import { settlePush } from './push.js'
4
5
  import { terminalMirrorRecipient } from './handler-utils.js'
6
+ import { isBoundClient } from './environments/authority.js'
7
+ import { broadcastRosterPerRecipient } from './roster-broadcast.js'
8
+ import { getProviderRuntimeInfo } from './providers.js'
9
+ import { MODEL_UNSUPPORTED_CODE } from './codex-model-rejections.js'
5
10
 
6
11
  const log = createLogger('ws-forwarding')
7
12
 
@@ -78,6 +83,22 @@ function safeForward(label, fn) {
78
83
  * @param {Function} ctx.broadcast - (message, filter?) => void
79
84
  * @param {Function} ctx.broadcastToSession - (sessionId, message, filter?) => void
80
85
  */
86
+ /**
87
+ * Events the LEGACY single-CLI path forwards through the normalizer.
88
+ *
89
+ * Exported so tests can iterate the real list rather than a copy — a hand-maintained
90
+ * duplicate in a test cannot fail when this list grows, which is exactly the false
91
+ * assurance #7096's first attempt shipped.
92
+ */
93
+ export const FORWARDED_CLI_EVENTS = Object.freeze([
94
+ 'ready', 'stream_start', 'stream_delta', 'stream_end',
95
+ 'message', 'tool_start', 'tool_result', 'result', 'error',
96
+ 'user_question', 'agent_spawned', 'agent_completed',
97
+ 'plan_started', 'plan_ready', 'mcp_servers',
98
+ 'permission_expired', 'skill_changed', 'skill_trust_request', 'skill_trust_granted',
99
+ 'stopped',
100
+ ])
101
+
81
102
  export function setupForwarding(ctx) {
82
103
  const {
83
104
  normalizer,
@@ -89,12 +110,17 @@ export function setupForwarding(ctx) {
89
110
 
90
111
  // Wire the normalizer's timer-based delta flush to broadcast
91
112
  normalizer.onFlush = (entries) => {
92
- for (const { sessionId, messageId, delta, emitMonoMs } of entries) {
113
+ for (const { sessionId, messageId, delta, emitMonoMs, thinking } of entries) {
93
114
  recordEmitToBroadcast(emitMonoMs)
115
+ // #6818: stamp `thinking: true` back on so a coalesced reasoning frame
116
+ // routes to the thinking bubble, not the response slot. Absent for
117
+ // response text (byte-identical to pre-#6818).
118
+ const msg = { type: 'stream_delta', messageId, delta }
119
+ if (thinking) msg.thinking = true
94
120
  if (sessionId) {
95
- broadcastToSession(sessionId, withServerTs({ type: 'stream_delta', messageId, delta }))
121
+ broadcastToSession(sessionId, withServerTs(msg))
96
122
  } else {
97
- broadcast(withServerTs({ type: 'stream_delta', messageId, delta }))
123
+ broadcast(withServerTs(msg))
98
124
  }
99
125
  }
100
126
  }
@@ -121,7 +147,81 @@ function terminalSubscriberFilter(sessionId) {
121
147
 
122
148
  /** Multi-session forwarding via normalizer */
123
149
  function setupSessionForwarding(normalizer, ctx) {
124
- const { sessionManager, devPreview, checkpointManager, broadcast, broadcastToSession } = ctx
150
+ const { sessionManager, devPreview, checkpointManager, broadcast, broadcastToSession, defaultProvider = null } = ctx
151
+
152
+ // #8497: sessions whose turn a `result` ended in the CURRENT synchronous turn
153
+ // end. A provider that finishes a requested Stop with a `result` and then a
154
+ // `stopped` (claude-cli) emits both back to back in one call stack, so the
155
+ // `stopped` that follows must not announce idle a second time. Cleared on a
156
+ // microtask rather than on the next stream_start: a Stop pressed before the
157
+ // next turn produced any output forwards nothing in between, and a flag that
158
+ // outlived the tick would swallow that turn's idle (the stuck-busy bug this
159
+ // exists to fix). The failure mode of the tick scope is a repeated idle, which
160
+ // is idempotent on every client; the failure mode of a longer scope is a
161
+ // session that stays busy forever.
162
+ const idledByResultThisTick = new Set()
163
+
164
+ // #8502: sessions whose turn-end `session_list` is already queued for this
165
+ // synchronous turn end. A `result` and a `stopped` that coincide (claude-sdk's
166
+ // quiet acknowledgement of a Stop, claude-cli's close handler) share ONE list.
167
+ const turnEndListQueued = new Set()
168
+
169
+ // The `session_list` a turn end refreshes, built AFTER the provider's
170
+ // synchronous teardown rather than inside the emit. claude-sdk, ACP and Codex
171
+ // app-server emit `result` / `stopped` and only then clear `_isBusy`
172
+ // (_clearMessageState), so a list built inside the emit publishes the finished
173
+ // session as busy. `agent_idle` reaches viewers only, and the clients re-derive
174
+ // `isIdle` from this list's rows, so a client that is not viewing the session
175
+ // would end the turn busy. A microtask runs once the emitting call stack
176
+ // unwinds and before any later await; the providers clear busy synchronously in
177
+ // that same stack (checked per provider in #8502).
178
+ //
179
+ // `afterBusyCleared` marks the list the provider itself asked for once its busy
180
+ // window really ended (`busy_cleared`). Every other trigger is skipped while the
181
+ // session reports `busyClearedOwed`: its busy flag outlives the `result` (the
182
+ // jsonl-subprocess family clears it in the child's close handler, a later
183
+ // event-loop turn), so a list built now would publish the finished session as
184
+ // busy AFTER the viewer's agent_idle, and the clients, which re-derive isIdle
185
+ // from the list row even for the active session, would flip back to Working
186
+ // until the child exits. The session states this itself; it is not guessed
187
+ // from `isRunning`, which is also true for a restarted queued turn and for
188
+ // background shells, where the list is correct and wanted.
189
+ const queueTurnEndSessionList = (sessionId, { afterBusyCleared = false } = {}) => {
190
+ if (turnEndListQueued.has(sessionId)) return
191
+ turnEndListQueued.add(sessionId)
192
+ queueMicrotask(() => {
193
+ turnEndListQueued.delete(sessionId)
194
+ if (!afterBusyCleared && sessionManager.getSession?.(sessionId)?.session?.busyClearedOwed === true) return
195
+ try {
196
+ executeSideEffects([{ type: 'session_list' }], sessionId, ctx)
197
+ } catch (err) {
198
+ log.error(`deferred session_list after turn end threw for session ${sessionId}: ${err?.message || err}`)
199
+ }
200
+ })
201
+ }
202
+
203
+ // #8873: the `session_list` a provider start's outcome refreshes
204
+ // (`session_restore_failed`, `session_start_settled`), coalesced so a burst of
205
+ // outcomes costs one `listSessions()` and one send per client rather than one
206
+ // each. Restored sessions start together at boot, so their failures (and the
207
+ // #8876 deadline timers) arrive together. They arrive as separate timer or I/O
208
+ // callbacks, and Node drains microtasks between callbacks, so a microtask
209
+ // would coalesce only outcomes emitted in one call stack. `setImmediate` runs
210
+ // once per event-loop turn, after every callback of that turn. The list is
211
+ // built when it fires, so it reflects every outcome in the burst.
212
+ let startOutcomeListQueued = false
213
+ const queueStartOutcomeSessionList = () => {
214
+ if (!ctx.broadcastSessionList || startOutcomeListQueued) return
215
+ startOutcomeListQueued = true
216
+ setImmediate(() => {
217
+ startOutcomeListQueued = false
218
+ try {
219
+ ctx.broadcastSessionList()
220
+ } catch (err) {
221
+ log.error(`deferred session_list after a provider start outcome threw: ${err?.message || err}`)
222
+ }
223
+ })
224
+ }
125
225
 
126
226
  sessionManager.on('session_event', ({ sessionId, event, data }) => {
127
227
  // #5313 (WP-1.3): this listener runs synchronously inside the
@@ -131,30 +231,54 @@ function setupSessionForwarding(normalizer, ctx) {
131
231
  // Contain it: wrap the body, log with the session id, and swallow so a
132
232
  // single malformed event can't bring down the process.
133
233
  try {
134
- // models_updated is global — broadcast to ALL clients, not per-session.
234
+ // models_updated is global — not scoped to viewers of one session (unlike
235
+ // broadcastToSession). #7895: it is no longer sent to every client
236
+ // unconditionally either — broadcastRosterPerRecipient fans it out so
237
+ // each connected client receives it only when the tag names a registry
238
+ // their own active session actually uses (see that function's docstring,
239
+ // ./roster-broadcast.js, for the exact per-tag recipient rule).
135
240
  // Look up the session's provider so clients receive the provider-scoped
136
241
  // defaultModel rather than the Claude-only global. Falls back to the
137
- // Claude default registry when the session is not found (e.g. already
138
- // destroyed). Includes the provider name in the payload so clients can
139
- // route the model list to the correct session type. (#2993)
242
+ // daemon's resolved default when the session is not found (e.g. already
243
+ // destroyed) — same resolution `ws-history.js`'s connect path uses
244
+ // (`resolveRosterProvider`), so a roster this event produces is tagged the
245
+ // same way whether a client learns of it via reconnect or via this live
246
+ // push. (#2993)
247
+ //
248
+ // #7895 — this used to hardcode the fallback tag to `'claude-sdk'` and
249
+ // broadcast ONE message. A claude-cli/claude-tui/claude-byok client keys
250
+ // its roster by the EXACT tag it arrives under
251
+ // (`packages/store-core/src/models-by-provider.ts`), so that single
252
+ // `claude-sdk`-tagged message was delivered and discarded by every other
253
+ // Claude-family client — the same #7756 bug the overlay-reload path was
254
+ // fixed for. `broadcastRosterPerRecipient` (`./roster-broadcast.js`) is
255
+ // that same per-recipient re-tagging, shared rather than re-implemented a
256
+ // third time: a default-registry roster is re-sent once per known
257
+ // Claude-family tag, each copy filtered to the clients that resolve to it;
258
+ // a non-Claude roster (codex, gemini, …) is sent once, unchanged, to its
259
+ // exact-match clients only — untouched from pre-#7895 behaviour.
140
260
  if (event === 'models_updated' && data?.models) {
141
261
  const sessionEntry = sessionManager.getSession(sessionId)
142
262
  const providerName = sessionEntry?.provider ?? null
143
- const registry = providerName ? getRegistryForProvider(providerName) : null
144
- const defaultModel = registry ? registry.getDefaultModelId() : getDefaultModelId()
145
- // When the session is not found (race with teardown) providerName is null
146
- // but we still fall back to the Claude default registry, so advertise
147
- // 'claude-sdk' rather than null so clients can route the model list
148
- // consistently. (#2993)
149
- const resolvedProvider = providerName ?? 'claude-sdk'
150
- broadcast({ type: 'available_models', models: data.models, defaultModel, provider: resolvedProvider })
263
+ const rosterProvider = resolveRosterProvider(providerName, defaultProvider)
264
+ // getRegistryForProvider never returns a falsy value (unknown/null names
265
+ // fall back to defaultRegistry), and resolveRosterProvider never returns
266
+ // a falsy tag either — so this always resolves to a real registry.
267
+ const defaultModel = getRegistryForProvider(rosterProvider).getDefaultModelId()
268
+ broadcastRosterPerRecipient({
269
+ broadcast,
270
+ sessionManager,
271
+ defaultProvider,
272
+ message: { type: 'available_models', models: data.models, defaultModel, provider: rosterProvider },
273
+ })
151
274
  return
152
275
  }
153
276
 
154
277
  // #5665: monthly programmatic-credit meter is machine-wide — broadcast to
155
278
  // ALL authenticated clients, not per-session.
156
279
  if (event === 'monthly_budget') {
157
- broadcast({ type: 'monthly_budget', ...data })
280
+ // The host's spend meter: not for a session-scoped connection.
281
+ broadcast({ type: 'monthly_budget', ...data }, (client) => !isBoundClient(client))
158
282
  return
159
283
  }
160
284
 
@@ -185,45 +309,179 @@ function setupSessionForwarding(normalizer, ctx) {
185
309
  return
186
310
  }
187
311
 
188
- // Sidebar activity feed: lightweight status broadcast to ALL authenticated clients
189
- if (event === 'stream_start') {
312
+ // #8301: a DAEMON-authored user turn (the CI-completion wake, recorded by
313
+ // SessionManager.recordDaemonUserInput). Same wire shape input-handlers.js
314
+ // broadcasts for a typed input, minus `clientId` — there is no sending
315
+ // client, so every viewer of the session renders it. Transient here: the
316
+ // history entry was recorded at the source, which is what a reconnecting
317
+ // client replays. Not routed through the normalizer — like terminal_output
318
+ // above, it is a straight relay with no per-provider shape to normalise.
319
+ if (event === 'user_input') {
320
+ broadcastToSession(sessionId, {
321
+ type: 'user_input',
322
+ sessionId,
323
+ text: typeof data?.text === 'string' ? data.text : '',
324
+ messageId: data?.messageId,
325
+ timestamp: typeof data?.timestamp === 'number' ? data.timestamp : Date.now(),
326
+ // The daemon wrote this turn, not a person. Optional and additive: an
327
+ // older client ignores it and renders the bubble as it always did.
328
+ ...(data?.source === 'daemon' ? { source: 'daemon' } : {}),
329
+ })
330
+ return
331
+ }
332
+
333
+ // #8502: a provider whose `result` precedes the end of its busy window (the
334
+ // jsonl-subprocess family: the child is still exiting when the result line is
335
+ // parsed) says so when busy actually clears. Nothing to normalise or relay to
336
+ // a viewer: it exists to refresh the list the clients re-derive busy from.
337
+ if (event === 'busy_cleared') {
338
+ queueTurnEndSessionList(sessionId, { afterBusyCleared: true })
339
+ return
340
+ }
341
+
342
+ // Sidebar activity feed: lightweight status broadcast to ALL authenticated clients.
343
+ // #7393: not for a `late` thinking stream_start (claude-tui shows a reasoning
344
+ // block that reached the transcript after its turn's `result`). That is a
345
+ // finished turn being decorated, not the session starting work, and nothing
346
+ // would send idle again until the next `result`.
347
+ if (event === 'stream_start' && data?.late !== true) {
190
348
  broadcast({ type: 'session_activity', sessionId, isBusy: true, lastCost: null })
191
349
  } else if (event === 'result') {
192
350
  broadcast({ type: 'session_activity', sessionId, isBusy: false, lastCost: data?.cost ?? null })
351
+ idledByResultThisTick.add(sessionId)
352
+ queueMicrotask(() => idledByResultThisTick.delete(sessionId))
353
+ queueTurnEndSessionList(sessionId)
193
354
  }
194
355
 
195
- // Dev server preview: scan tool_result events for localhost server patterns
196
- if (event === 'tool_result' && data?.result) {
197
- devPreview.handleToolResult(sessionId, data.result)
356
+ // #8497: a requested Stop ends the turn with `stopped` and, on most
357
+ // providers (ACP, Codex app-server, the jsonl-subprocess family), NO
358
+ // `result`. Both clients leave busy on `agent_idle` / `session_activity`,
359
+ // which only a `result` produced, so those sessions stayed busy for good.
360
+ // Announcing idle here covers every provider at the one place they all meet
361
+ // the wire, and `stopped` stays the quiet confirmation: no `result` is
362
+ // minted, so no marker or chip can follow. Skipped when the same turn end
363
+ // already went idle through a `result`.
364
+ let announceIdle = false
365
+ if (event === 'stopped' && !idledByResultThisTick.has(sessionId)) {
366
+ announceIdle = true
367
+ broadcast({ type: 'session_activity', sessionId, isBusy: false, lastCost: null })
198
368
  }
369
+ // Every turn end refreshes the list, including a `stopped` the idle frames
370
+ // were deduped against: the `result` that deduped it queued the list, and the
371
+ // queue is idempotent per synchronous turn end.
372
+ if (event === 'stopped') queueTurnEndSessionList(sessionId)
373
+ // A turn can also end with only an `error` (an SDK query that threw, a BYOK
374
+ // `_emitTurnError`, ACP / Codex `_failTurn`): no `result`, no `stopped`, so no
375
+ // agent_idle or idle ping, and the clients leave busy on nothing else. The
376
+ // list is the one signal left. An `error` that does not end a turn costs one
377
+ // list that reports the session's true state, which is still busy.
378
+ if (event === 'error') queueTurnEndSessionList(sessionId)
199
379
 
200
380
  const normCtx = {
201
381
  sessionId,
202
382
  mode: 'multi',
203
383
  getSessionEntry: () => sessionManager.getSession(sessionId),
384
+ announceIdle,
204
385
  }
205
386
  const result = normalizer.normalize(event, data, normCtx)
206
387
  if (!result) return
207
388
 
389
+ // #7745/#7835: creation/subscription can replay before an async provider
390
+ // handshake and project-policy compilation finish. Ready is the first
391
+ // generic event after those facts settle, so refresh the same bounded
392
+ // session-scoped snapshot used by sendSessionInfo. This is deliberately a
393
+ // separate frame: existing ready and boolean capability semantics stay
394
+ // unchanged, while the creating tab converges without a reselect.
395
+ if (event === 'ready') {
396
+ const entry = sessionManager.getSession(sessionId)
397
+ if (entry?.session) {
398
+ result.messages.push({
399
+ msg: {
400
+ type: 'provider_runtime_info',
401
+ sessionId,
402
+ ...getProviderRuntimeInfo(entry.provider, entry.session),
403
+ },
404
+ })
405
+ }
406
+ }
407
+
208
408
  // Handle delta buffering
209
409
  if (result.buffer) {
210
- normalizer.bufferDelta(sessionId, data.messageId, data.delta, data._emitMonoMs)
410
+ // #6818: forward the thinking flag so the coalesced frame reconstructs as
411
+ // a thinking stream_delta on flush.
412
+ normalizer.bufferDelta(sessionId, data.messageId, data.delta, data._emitMonoMs, result.thinking === true)
211
413
  return
212
414
  }
213
415
 
214
416
  // Execute side effects before messages (flush_deltas must happen before stream_end broadcast)
215
- executeSideEffects(result.sideEffects, sessionId, ctx)
417
+ // #8502: a `result`'s own `session_list` is the queued turn-end one (above),
418
+ // built after the provider's teardown. Running it here too would publish the
419
+ // stale busy row first and a second list straight after it.
420
+ executeSideEffects(
421
+ event === 'result' ? result.sideEffects?.filter((effect) => effect.type !== 'session_list') : result.sideEffects,
422
+ sessionId,
423
+ ctx,
424
+ )
216
425
  executeRegistrations(result.registrations, sessionId, ctx)
217
426
 
218
427
  // Broadcast messages
219
428
  for (const { msg, filter } of result.messages) {
220
429
  const stamped = withServerTs(msg)
221
- if (filter) {
430
+ // Bounded session attention is visible with the session roster, even
431
+ // when the operator is viewing another session. The broadcaster retains
432
+ // its central bound-session recipient check. All other work stays scoped.
433
+ if (msg.type === 'session_status') {
434
+ const parsed = ServerSessionStatusSchema.safeParse({ ...stamped, sessionId })
435
+ if (parsed.success) broadcast(parsed.data)
436
+ } else if (msg.type === 'activity_delta' && msg.entry?.id === 'decision:session' && msg.entry?.kind === 'decision') {
437
+ const parsed = ServerActivityDeltaSchema.safeParse({ ...stamped, sessionId })
438
+ if (parsed.success && parsed.data.entry.label.length <= 280) {
439
+ const { id, kind, label, status, startedAt, endedAt } = parsed.data.entry
440
+ broadcast({ ...parsed.data, entry: { id, kind, label, status, startedAt, ...(endedAt !== undefined ? { endedAt } : {}) } })
441
+ }
442
+ } else if (filter) {
222
443
  broadcastToSession(sessionId, stamped, filter)
223
444
  } else {
224
445
  broadcastToSession(sessionId, stamped)
225
446
  }
226
447
  }
448
+
449
+ // #8909: a backend model refusal changes the ledger every session on the same
450
+ // codex client reads live, so resend each same-provider session's runtime frame
451
+ // (this one included) and let its picker disable the model. After the event's
452
+ // own messages, so the error reaches clients first. One failing session must
453
+ // not stop the rest, and a failure to enumerate sessions must not abort the
454
+ // rest of this listener, including the afterEffects step below.
455
+ if (event === 'error' && data?.code === MODEL_UNSUPPORTED_CODE) {
456
+ try {
457
+ const provider = sessionManager.getSession(sessionId)?.provider
458
+ const rows = provider ? sessionManager.listSessions() || [] : []
459
+ for (const row of rows) {
460
+ const sid = row?.sessionId
461
+ if (!sid) continue
462
+ try {
463
+ const peer = sessionManager.getSession(sid)
464
+ if (!peer?.session || peer.provider !== provider) continue
465
+ broadcastToSession(sid, withServerTs({
466
+ type: 'provider_runtime_info',
467
+ sessionId: sid,
468
+ ...getProviderRuntimeInfo(peer.provider, peer.session),
469
+ }))
470
+ } catch (err) {
471
+ log.error(`provider_runtime_info refresh after model rejection failed for session ${sid}: ${err?.message || err}`)
472
+ }
473
+ }
474
+ } catch (err) {
475
+ log.error(`provider_runtime_info refresh after model rejection failed: ${err?.message || err}`)
476
+ }
477
+ }
478
+
479
+ // #7379: AFTER the broadcast, deliberately. Releasing a permission runs
480
+ // ws-permissions' cleanup() -> tearDownRoute, which unsubscribes the
481
+ // permission-induced viewers of this session — so anything released here
482
+ // must already have been told. Same executor as sideEffects so the two
483
+ // buckets can never grow divergent handling.
484
+ executeSideEffects(result.afterEffects, sessionId, ctx)
227
485
  } catch (err) {
228
486
  // #5313 (WP-1.3): see the try at the top of this listener.
229
487
  const message = err?.message || String(err)
@@ -242,6 +500,20 @@ function setupSessionForwarding(normalizer, ctx) {
242
500
  // (#2954). History stays on disk; client shows a retry affordance.
243
501
  sessionManager.on('session_restore_failed', safeForward('session_restore_failed', (payload) => {
244
502
  broadcast({ type: 'session_restore_failed', ...payload })
503
+ // #8861 / #8092: a session re-parked after an ASYNC start failure was already
504
+ // in the last `session_list` (it was live when that went out), and the
505
+ // restore-branch teardown in `_handleAsyncStartFailure` never emits
506
+ // `session_destroyed`, so without a refresh every client's sidebar keeps a
507
+ // clickable entry for a session that no longer exists ("Session not found").
508
+ // Re-sending the list is what removes it.
509
+ queueStartOutcomeSessionList()
510
+ }))
511
+
512
+ // #8872: a session whose async start() was still settling went out in
513
+ // `session_list` as `starting`; once the start resolves, re-send the list so
514
+ // every client can open it.
515
+ sessionManager.on('session_start_settled', safeForward('session_start_settled', () => {
516
+ queueStartOutcomeSessionList()
245
517
  }))
246
518
 
247
519
  // Persist failures — surface to clients so the user knows a session-list
@@ -268,12 +540,23 @@ function setupSessionForwarding(normalizer, ctx) {
268
540
  broadcastToSession(sessionId, {
269
541
  type: 'session_error',
270
542
  code: errorCode || 'SESSION_START_FAILED',
543
+ // #8981: lets clients tell a refused fresh session apart from every other
544
+ // session_error and record it as a coded chat error. Mirrored by
545
+ // SESSION_CREATE_FAILED_CATEGORY in store-core.
546
+ category: 'create_failed',
271
547
  sessionId,
272
548
  recoverable: false,
273
549
  message: errorMessage
274
550
  ? `The session failed to start: ${errorMessage}`
275
551
  : `The session failed to start${provider ? ` (${provider})` : ''}.`,
276
552
  })
553
+ // #8981: nothing else announces the removal. `session_destroyed` listeners
554
+ // never send a `session_list`, and clients drop a session (and its messages)
555
+ // only when a list omits it, so the failed session would linger in sidebars
556
+ // and a coded entry parked for it would never land. The setImmediate inside
557
+ // fires after the synchronous destroySession that follows this emit, so the
558
+ // list omits the session.
559
+ queueStartOutcomeSessionList()
277
560
  }))
278
561
 
279
562
  // #5731 (T3): a checkpoint create/delete that couldn't be flushed to disk will
@@ -296,8 +579,11 @@ function setupSessionForwarding(normalizer, ctx) {
296
579
  }
297
580
 
298
581
  // Dev server preview: broadcast tunnel start/stop to clients
299
- devPreview.on('dev_preview_started', safeForward('dev_preview_started', ({ sessionId, port, url }) => {
300
- broadcastToSession(sessionId, { type: 'dev_preview', port, url })
582
+ devPreview.on('dev_preview_status', safeForward('dev_preview_status', ({ sessionId, ...message }) => {
583
+ broadcastToSession(sessionId, message)
584
+ }))
585
+ devPreview.on('dev_preview_started', safeForward('dev_preview_started', ({ sessionId, port, url, target, exposure }) => {
586
+ broadcastToSession(sessionId, { type: 'dev_preview', port, url, ...(target ? { target, exposure } : {}) })
301
587
  }))
302
588
  devPreview.on('dev_preview_stopped', safeForward('dev_preview_stopped', ({ sessionId, port }) => {
303
589
  broadcastToSession(sessionId, { type: 'dev_preview_stopped', port })
@@ -306,7 +592,7 @@ function setupSessionForwarding(normalizer, ctx) {
306
592
  // (and the exposed local port) may still be live. Surface it as a per-session
307
593
  // error banner (reusing `session_error`, like the checkpoint/persist failure
308
594
  // paths) so the user can verify / kill cloudflared instead of assuming the
309
- // port is closed. recoverable:true — informational; the slot is already freed.
595
+ // port is closed. The slot stays tracked until child exit is confirmed.
310
596
  devPreview.on('dev_preview_stop_failed', safeForward('dev_preview_stop_failed', ({ sessionId, port, error }) => {
311
597
  if (!sessionId) return
312
598
  broadcastToSession(sessionId, {
@@ -327,7 +613,7 @@ function setupSessionForwarding(normalizer, ctx) {
327
613
 
328
614
  /** Legacy single CLI session forwarding via normalizer */
329
615
  function setupCliForwarding(normalizer, ctx) {
330
- const { cliSession, devPreview, broadcast } = ctx
616
+ const { cliSession, devPreview, broadcast, defaultProvider = null } = ctx
331
617
 
332
618
  // #3240: `skill_changed` is forwarded so legacy single-CLI users get the
333
619
  // same trust-mismatch broadcast as multi-session mode. The normaliser
@@ -339,14 +625,14 @@ function setupCliForwarding(normalizer, ctx) {
339
625
  // session-manager.js `_wireSessionEvents` builtinTransient) so the legacy
340
626
  // single-CLI path also surfaces the user-initiated Stop confirmation via
341
627
  // the normalizer's `session_stopped` wire message.
342
- const FORWARDED_EVENTS = [
343
- 'ready', 'stream_start', 'stream_delta', 'stream_end',
344
- 'message', 'tool_start', 'tool_result', 'result', 'error',
345
- 'user_question', 'agent_spawned', 'agent_completed',
346
- 'plan_started', 'plan_ready', 'mcp_servers',
347
- 'permission_expired', 'skill_changed', 'skill_trust_request', 'skill_trust_granted',
348
- 'stopped',
349
- ]
628
+ // #7096 HAZARD: this path normalises with `sessionId: null` (see normCtx below), and
629
+ // several server schemas declare `sessionId: z.string().optional()` — so `undefined`
630
+ // is legal but `null` is NOT. Before adding an event here, check that its normalizer
631
+ // mapping either omits `sessionId` when absent (the `mcp_servers` / `permission_expired`
632
+ // pattern) or that its schema accepts null (`result`, `skill_changed`,
633
+ // `skill_trust_request` do). An unguarded `sessionId: ctx.sessionId` stamp on a
634
+ // null-rejecting schema makes every frame on this path wire-illegal.
635
+ const FORWARDED_EVENTS = FORWARDED_CLI_EVENTS
350
636
  for (const event of FORWARDED_EVENTS) {
351
637
  cliSession.on(event, (data) => {
352
638
  // #5313 (WP-1.3): same crash shape as the multi-session listener — a
@@ -365,7 +651,9 @@ function setupCliForwarding(normalizer, ctx) {
365
651
  if (!result) return
366
652
 
367
653
  if (result.buffer) {
368
- normalizer.bufferDelta(null, data.messageId, data.delta, data._emitMonoMs)
654
+ // #6818: forward the thinking flag (legacy-CLI path) so a coalesced
655
+ // reasoning frame reconstructs as a thinking stream_delta on flush.
656
+ normalizer.bufferDelta(null, data.messageId, data.delta, data._emitMonoMs, result.thinking === true)
369
657
  return
370
658
  }
371
659
 
@@ -380,6 +668,12 @@ function setupCliForwarding(normalizer, ctx) {
380
668
  broadcast(stamped)
381
669
  }
382
670
  }
671
+
672
+ // #7379: after the broadcast — see the multi-session path. This path
673
+ // broadcasts globally rather than per-session, so the unsubscribe hazard
674
+ // does not bite here; the ordering is mirrored anyway so the two paths
675
+ // cannot drift into different semantics for the same effect.
676
+ executeSideEffects(result.afterEffects, null, ctx)
383
677
  } catch (err) {
384
678
  const message = err?.message || String(err)
385
679
  log.error(`legacy-cli forwarding threw (event=${event}): ${message}${err?.stack ? '\n' + err.stack : ''}`)
@@ -387,16 +681,12 @@ function setupCliForwarding(normalizer, ctx) {
387
681
  })
388
682
  }
389
683
 
390
- // Dev server preview: scan tool_result events for localhost server patterns (legacy CLI)
391
- // #5313 (WP-1.3): safeForward — a throw here must not unwind CliSession's emit().
392
- cliSession.on('tool_result', safeForward('cli:tool_result', (data) => {
393
- if (data?.result) {
394
- devPreview.handleToolResult('__legacy__', data.result)
395
- }
684
+ devPreview.on('dev_preview_status', safeForward('cli:dev_preview_status', ({ sessionId, ...message }) => {
685
+ if (sessionId === '__legacy__') broadcast({ ...message, sessionId })
396
686
  }))
397
- devPreview.on('dev_preview_started', safeForward('cli:dev_preview_started', ({ sessionId, port, url }) => {
687
+ devPreview.on('dev_preview_started', safeForward('cli:dev_preview_started', ({ sessionId, port, url, target, exposure }) => {
398
688
  if (sessionId === '__legacy__') {
399
- broadcast({ type: 'dev_preview', port, url })
689
+ broadcast({ type: 'dev_preview', port, url, ...(target ? { target, exposure } : {}) })
400
690
  }
401
691
  }))
402
692
  devPreview.on('dev_preview_stopped', safeForward('cli:dev_preview_stopped', ({ sessionId, port }) => {
@@ -419,12 +709,23 @@ function setupCliForwarding(normalizer, ctx) {
419
709
  }
420
710
  }))
421
711
 
422
- // models_updated bypasses normalizer — global broadcast.
423
- // CLI mode is always a Claude session; include provider so clients can
424
- // route the model list consistently with the multi-session path. (#2993)
712
+ // models_updated bypasses normalizer — global broadcast. Legacy single-CLI
713
+ // mode has no sessionManager and exactly one running session, so — unlike
714
+ // the multi-session path above — there is no per-client provider variance
715
+ // to fan out over; every connected client sees the SAME roster tag. Tag it
716
+ // with whatever `ws-history.js`'s legacy connect path
717
+ // (`resolveRosterProvider(null, billingCanary?.defaultProvider)`) would send
718
+ // for this daemon, rather than the literal `'claude-cli'` (#7895): a
719
+ // claude-tui or claude-byok client — or a daemon started with a non-default
720
+ // `config.provider` — keys its roster by that EXACT tag
721
+ // (`packages/store-core/src/models-by-provider.ts`), so a hardcoded
722
+ // `'claude-cli'` was delivered and discarded whenever the connect-time tag
723
+ // disagreed.
425
724
  cliSession.on('models_updated', safeForward('cli:models_updated', (data) => {
426
725
  if (data?.models) {
427
- broadcast({ type: 'available_models', models: data.models, defaultModel: getDefaultModelId(), provider: 'claude-cli' })
726
+ const legacyProvider = resolveRosterProvider(null, defaultProvider)
727
+ const legacyRegistry = getRegistryForProvider(legacyProvider)
728
+ broadcast({ type: 'available_models', models: data.models, defaultModel: legacyRegistry.getDefaultModelId(), provider: legacyProvider })
428
729
  }
429
730
  }))
430
731
  }
@@ -432,7 +733,7 @@ function setupCliForwarding(normalizer, ctx) {
432
733
  /** Execute side effect descriptors returned by the normalizer */
433
734
  function executeSideEffects(sideEffects, sessionId, ctx) {
434
735
  if (!sideEffects) return
435
- const { normalizer, sessionManager, pushManager, broadcast, broadcastToSession, broadcastSessionList } = ctx
736
+ const { normalizer, sessionManager, pushManager, broadcast, broadcastToSession, broadcastSessionList, releasePermission } = ctx
436
737
  for (const effect of sideEffects) {
437
738
  switch (effect.type) {
438
739
  case 'session_list':
@@ -444,6 +745,20 @@ function executeSideEffects(sideEffects, sessionId, ctx) {
444
745
  }
445
746
  }
446
747
  break
748
+ case 'release_permission':
749
+ // #7379: the session says the turn behind this prompt is dead, so the
750
+ // daemon must stop holding (and re-sending) its pending entry. Optional
751
+ // in ctx so a harness that does not wire permissions still forwards
752
+ // events; a no-op when the requestId was never in the HTTP map, which is
753
+ // the normal case for the SDK path and for a hook that closed cleanly.
754
+ if (releasePermission) {
755
+ try {
756
+ releasePermission(effect.requestId, sessionId)
757
+ } catch (err) {
758
+ log.warn(`Failed to release abandoned permission ${effect.requestId}: ${err?.message || err}`)
759
+ }
760
+ }
761
+ break
447
762
  case 'refresh_context':
448
763
  if (sessionManager) {
449
764
  sessionManager.getSessionContext(effect.sessionId || sessionId).then((ctxData) => {
@@ -467,12 +782,15 @@ function executeSideEffects(sideEffects, sessionId, ctx) {
467
782
  case 'flush_deltas': {
468
783
  const sid = effect.sessionId ?? sessionId
469
784
  const entries = normalizer.flushSession(sid)
470
- for (const { sessionId: eSid, messageId, delta, emitMonoMs } of entries) {
785
+ for (const { sessionId: eSid, messageId, delta, emitMonoMs, thinking } of entries) {
471
786
  recordEmitToBroadcast(emitMonoMs)
787
+ // #6818: preserve the thinking flag through the pre-stream_end flush.
788
+ const msg = { type: 'stream_delta', messageId, delta }
789
+ if (thinking) msg.thinking = true
472
790
  if (eSid) {
473
- broadcastToSession(eSid, withServerTs({ type: 'stream_delta', messageId, delta }))
791
+ broadcastToSession(eSid, withServerTs(msg))
474
792
  } else {
475
- broadcast(withServerTs({ type: 'stream_delta', messageId, delta }))
793
+ broadcast(withServerTs(msg))
476
794
  }
477
795
  }
478
796
  break