@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
@@ -8,31 +8,76 @@
8
8
  import { realpathSync } from 'fs'
9
9
  import { scanConversations as defaultScanConversations } from '../conversation-scanner.js'
10
10
  import { searchConversations as defaultSearchConversations } from '../conversation-search.js'
11
- import { resolveJsonlPath, readConversationHistoryAsync as defaultReadConversationHistoryAsync } from '../jsonl-reader.js'
11
+ import { readConversationTranscriptStrictAsync as defaultReadConversationTranscript, transcriptReadLimiter } from '../jsonl-reader.js'
12
+ import { resolveTranscriptSource } from '../transcript-sources.js'
13
+ import { projectSlug } from '../jsonl-reader.js'
12
14
  import { validateCwdAllowed, broadcastFocusChanged, resolveSession, autoSubscribeOtherClients, buildSessionTokenMismatchPayload, sendSessionError } from '../handler-utils.js'
13
- import { scopeConversationsToClient } from '../conversation-scope.js'
15
+ import { scopeConversationsToClient, boundConversationId } from '../conversation-scope.js'
16
+ import { isBoundClient, markConversationFrame } from '../environments/authority.js'
17
+ import { ReadLimitError, ReadCancelledError, admissionFor } from '../utils/read-limiter.js'
18
+ import { sendChunkedWithBackpressure, sendHistoryEntry } from '../ws-history.js'
14
19
  import { createLogger, loggerForSession } from '../logger.js'
15
20
 
16
21
  const log = createLogger('ws')
17
22
 
23
+ // Transcript reads are admitted through the one limiter that sits under every
24
+ // transcript reader (jsonl-reader.js `transcriptReadLimiter`).
25
+ const defaultTranscriptReadLimiter = transcriptReadLimiter
26
+
27
+ // An AbortSignal that fires when `ws` closes. `dispose` removes the listener.
28
+ function signalOnClose(ws) {
29
+ const ac = new AbortController()
30
+ if (ws?.readyState === 2 || ws?.readyState === 3) ac.abort()
31
+ const onClose = () => ac.abort()
32
+ if (typeof ws?.once === 'function') ws.once('close', onClose)
33
+ return {
34
+ signal: ac.signal,
35
+ dispose: () => { if (typeof ws?.removeListener === 'function') ws.removeListener('close', onClose) },
36
+ }
37
+ }
38
+
18
39
  // UUID v4-ish shape guard shared by resume_conversation and the read-only
19
40
  // transcript handler — rejects anything that isn't a canonical conversation id
20
41
  // before it reaches the filesystem, closing path-traversal via the id segment.
21
42
  const CONVERSATION_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
22
43
 
44
+ // Prefer the provider-TAGGED sources (#7828) so every discovered conversation
45
+ // carries its provider; fall back to bare dirs (untagged), then the scanner
46
+ // default (~/.claude/projects).
47
+ function scanOptsFor(ctx) {
48
+ const tagged = ctx.runtime.transcriptSources
49
+ if (Array.isArray(tagged) && tagged.length > 0) return { projectsDirs: tagged }
50
+ return ctx.runtime.projectsDirs ? { projectsDirs: ctx.runtime.projectsDirs } : {}
51
+ }
52
+
23
53
  async function handleListConversations(ws, client, msg, ctx) {
24
54
  // ctx.scanConversations override allows tests to inject a stub and skip real fs.
25
55
  const scan = ctx.scanConversations || defaultScanConversations
26
56
  try {
27
- // Pass provider-driven projectsDirs when available (#2965); falls back to
28
- // the scanner's default (~/.claude/projects) when not set.
29
- const scanOpts = ctx.runtime.projectsDirs ? { projectsDirs: ctx.runtime.projectsDirs } : {}
30
- const all = await scan(scanOpts)
57
+ // Pass provider-driven sources when available (#2965, #7828).
58
+ const scanOpts = scanOptsFor(ctx)
59
+ // Scanning reads the head of every transcript in the store, so it is admitted
60
+ // through the same limiter as every other transcript read.
61
+ const closing = signalOnClose(ws)
62
+ let all
63
+ try {
64
+ all = await (ctx.transcriptReadLimiter || defaultTranscriptReadLimiter).submit(
65
+ { key: `scan\0${JSON.stringify(scanOpts)}`, ...admissionFor(client, isBoundClient), signal: closing.signal },
66
+ () => scan(scanOpts),
67
+ )
68
+ } finally {
69
+ closing.dispose()
70
+ }
31
71
  // Adversary A8: scope results so a bound pairing-issued client
32
72
  // cannot enumerate conversations outside its session cwd.
33
73
  const conversations = scopeConversationsToClient(all, client, ctx)
34
74
  ctx.transport.send(ws, { type: 'conversations_list', conversations })
35
75
  } catch (err) {
76
+ if (err instanceof ReadCancelledError) return
77
+ if (err instanceof ReadLimitError) {
78
+ sendSessionError(ws, ctx, `${err.message}. Try again shortly.`)
79
+ return
80
+ }
36
81
  log.warn(`Failed to scan conversations: ${err.message}`)
37
82
  ctx.transport.send(ws, { type: 'conversations_list', conversations: [] })
38
83
  }
@@ -41,16 +86,38 @@ async function handleListConversations(ws, client, msg, ctx) {
41
86
  async function handleSearchConversations(ws, client, msg, ctx) {
42
87
  const { query, maxResults } = msg
43
88
  const search = ctx.searchConversations || defaultSearchConversations
89
+ const closing = signalOnClose(ws)
44
90
  try {
45
- const all = await search(query, { maxResults })
46
- // Adversary A8: scope the search result set to the bound session's
47
- // cwd. Without this, a mobile client could substring-grep every
48
- // JSONL on disk for secrets-in-transcripts.
91
+ // A session-scoped connection searches only the conversation its own session
92
+ // is running: the source is chosen BEFORE anything is read, ranked or
93
+ // truncated, so what other conversations contain cannot change the answer.
94
+ const scoped = isBoundClient(client)
95
+ const own = scoped ? boundConversationId(client, ctx) : null
96
+ const ownCwd = scoped ? ctx.sessions.sessionManager?.getSession?.(client.boundSessionId)?.cwd : null
97
+ // Source selection needs BOTH the conversation association and the project
98
+ // that association lives in (the daemon's own derivation from the session's cwd).
99
+ const searchOpts = scoped
100
+ ? { maxResults, conversationId: own, projectDirName: typeof ownCwd === 'string' && ownCwd ? projectSlug(ownCwd) : null }
101
+ : { maxResults }
102
+ const all = scoped && (!own || !searchOpts.projectDirName)
103
+ ? []
104
+ : await (ctx.transcriptReadLimiter || defaultTranscriptReadLimiter).submit(
105
+ { key: `search\0${query}\0${maxResults ?? ''}\0${own ?? ''}`, ...admissionFor(client, isBoundClient), signal: closing.signal },
106
+ () => search(query, searchOpts),
107
+ )
108
+ // The cwd check still applies to what comes back.
49
109
  const results = scopeConversationsToClient(all, client, ctx)
50
110
  ctx.transport.send(ws, { type: 'search_results', query, results })
51
111
  } catch (err) {
112
+ if (err instanceof ReadCancelledError) return
113
+ if (err instanceof ReadLimitError) {
114
+ sendSessionError(ws, ctx, `${err.message}. Try again shortly.`)
115
+ return
116
+ }
52
117
  log.warn(`Failed to search conversations: ${err.message}`)
53
118
  ctx.transport.send(ws, { type: 'search_results', query, results: [] })
119
+ } finally {
120
+ closing.dispose()
54
121
  }
55
122
  }
56
123
 
@@ -128,12 +195,14 @@ async function handleResumeConversation(ws, client, msg, ctx) {
128
195
  * `capabilities.resume === false` (BYOK, Codex, Gemini, user-shell) for which
129
196
  * `resume_conversation` is refused outright.
130
197
  *
131
- * Access follows the same cwd-scoping as `list_conversations`/`search_conversations`
198
+ * Access follows the same scoping as `list_conversations`/`search_conversations`
132
199
  * (`scopeConversationsToClient`): an UNBOUND client (primary token / dashboard)
133
- * may read any conversation; a BOUND pairing-issued client may only read
134
- * conversations recorded under its bound session's cwd — anything else is
135
- * rejected. This mirrors bearer-token-authority.md: read-only history is the
136
- * same authority class as other session-state reads.
200
+ * may read any conversation; a session-scoped client may read only the
201
+ * conversation its own session is running (conversation-scope.js) — anything
202
+ * else, or any case where the daemon does not know that association, is
203
+ * rejected. Reads go through a shared limiter (daemon-wide and per-connection
204
+ * caps, a bounded queue, coalescing of identical in-flight reads, and
205
+ * cancellation when the connection closes).
137
206
  *
138
207
  * The response reuses the existing `history_replay_start` / `message` /
139
208
  * `history_replay_end` server→client frames (identical to `handleRequestFullHistory`,
@@ -142,6 +211,11 @@ async function handleResumeConversation(ws, client, msg, ctx) {
142
211
  * is no live session, and a resumed session always gets a fresh id distinct from
143
212
  * the conversationId, so this cannot collide with or clobber a live session's
144
213
  * transcript.
214
+ *
215
+ * `history_replay_start` carries `truncated` for the slice actually sent (#7501),
216
+ * from the same meta reader `getFullHistoryAsync` uses — this path is subject to
217
+ * jsonl-reader's `MAX_MESSAGES` / `MAX_TRANSCRIPT_BYTES` caps exactly as the
218
+ * full-history path is, and used to omit the field entirely.
145
219
  */
146
220
  async function handleRequestConversationTranscript(ws, client, msg, ctx) {
147
221
  const { conversationId } = msg
@@ -155,28 +229,78 @@ async function handleRequestConversationTranscript(ws, client, msg, ctx) {
155
229
  return
156
230
  }
157
231
 
232
+ // Every failure from here on names the conversation it answers, with a
233
+ // stable code, so a viewer waiting on THIS conversation can settle on the
234
+ // reason instead of waiting out its inactivity timer.
235
+ const fail = (message) => ctx.transport.send(ws, {
236
+ type: 'session_error',
237
+ message,
238
+ code: 'TRANSCRIPT_UNAVAILABLE',
239
+ conversationId,
240
+ })
241
+
242
+ // A session-scoped connection may read only the conversation its own session
243
+ // is running. Decided from the daemon's association between the session and
244
+ // its conversation — before any scan or file access, and without consulting
245
+ // anything the client supplied. No known association means no access.
246
+ const scoped = isBoundClient(client)
247
+ if (scoped && conversationId !== boundConversationId(client, ctx)) {
248
+ fail('Not authorized to view this conversation')
249
+ return
250
+ }
251
+
158
252
  // Resolve the conversation's recorded cwd authoritatively from the persisted
159
253
  // store (the scanner reads the same JSONL layer list_conversations does). Only
160
254
  // fall back to a client-provided cwd hint when the scan can't find it (e.g. a
161
255
  // tiny conversation below the scanner's MIN_FILE_SIZE floor).
162
256
  const scan = ctx.scanConversations || defaultScanConversations
163
- let conv = null
257
+ //
258
+ // The same conversation id can exist under more than one provider's store.
259
+ // Collect EVERY match; the optional `provider` on the request selects one. An
260
+ // id that matches several providers with no selector is refused rather than
261
+ // resolved by whichever the scanner happened to list first (#7828).
262
+ let matches = []
164
263
  try {
165
- const scanOpts = ctx.runtime.projectsDirs ? { projectsDirs: ctx.runtime.projectsDirs } : {}
166
- const all = await scan(scanOpts)
167
- conv = Array.isArray(all) ? all.find((c) => c?.conversationId === conversationId) || null : null
264
+ const all = await scan(scanOptsFor(ctx))
265
+ matches = Array.isArray(all) ? all.filter((c) => c?.conversationId === conversationId) : []
168
266
  } catch (err) {
169
267
  // Scan failure is non-fatal — fall through to the client-provided cwd hint.
170
268
  log.warn(`Transcript scan failed for ${conversationId}: ${err.message}`)
171
269
  }
270
+ const wantedProvider = typeof msg.provider === 'string' && msg.provider ? msg.provider : null
271
+ // Authorization comes BEFORE any answer that depends on how many records
272
+ // exist or which providers hold them: a bound client is shown only the
273
+ // records it may see, and when every record is outside its scope it gets the
274
+ // same response a single out-of-scope record always got.
275
+ if (matches.length > 0) {
276
+ matches = scopeConversationsToClient(matches, client, ctx)
277
+ if (matches.length === 0) {
278
+ fail('Not authorized to view this conversation')
279
+ return
280
+ }
281
+ }
282
+ if (wantedProvider) matches = matches.filter((c) => c?.provider === wantedProvider)
283
+ if (matches.length > 1) {
284
+ const providers = new Set(matches.map((c) => c?.provider))
285
+ fail(providers.size > 1
286
+ ? 'This conversation id exists under more than one provider and cannot be opened unambiguously from here. Open it from its provider\'s own session list.'
287
+ : 'Conversation id has more than one record for this provider, so it cannot be read unambiguously')
288
+ return
289
+ }
290
+ const conv = matches[0] || null
172
291
 
173
292
  let cwd = conv?.cwd || null
174
- if (!cwd && typeof msg.cwd === 'string' && msg.cwd) {
293
+ if (!cwd && scoped) {
294
+ // The directory comes from the daemon's own record of the session, never
295
+ // from the request.
296
+ const ownCwd = ctx.sessions.sessionManager?.getSession?.(client.boundSessionId)?.cwd
297
+ cwd = typeof ownCwd === 'string' && ownCwd ? ownCwd : null
298
+ } else if (!cwd && typeof msg.cwd === 'string' && msg.cwd) {
175
299
  // Client-supplied fallback: validate it against the same path hygiene the
176
300
  // create/resume paths enforce before trusting it to resolve a filesystem path.
177
301
  const cwdError = validateCwdAllowed(msg.cwd, ctx.services.config)
178
302
  if (cwdError) {
179
- sendSessionError(ws, ctx, cwdError)
303
+ fail(cwdError)
180
304
  return
181
305
  }
182
306
  // Defense-in-depth: validateCwdAllowed already resolved + vetted the realpath
@@ -186,51 +310,155 @@ async function handleRequestConversationTranscript(ws, client, msg, ctx) {
186
310
  try {
187
311
  cwd = realpathSync(msg.cwd)
188
312
  } catch {
189
- sendSessionError(ws, ctx, `Cannot resolve path: ${msg.cwd}`)
313
+ fail(`Cannot resolve path: ${msg.cwd}`)
190
314
  return
191
315
  }
192
316
  }
193
317
 
194
318
  if (!cwd) {
195
- sendSessionError(ws, ctx, `Conversation not found: ${conversationId}`)
319
+ fail(`Conversation not found: ${conversationId}`)
196
320
  return
197
321
  }
198
322
 
199
323
  // Scope enforcement — reuse the guard list_conversations/search_conversations
200
324
  // use. A bound client that can't see this cwd gets an empty set → reject.
201
- const scoped = scopeConversationsToClient([{ conversationId, cwd }], client, ctx)
202
- if (scoped.length === 0) {
203
- sendSessionError(ws, ctx, 'Not authorized to view this conversation')
325
+ const inScope = scopeConversationsToClient([{ conversationId, cwd }], client, ctx)
326
+ if (inScope.length === 0) {
327
+ fail('Not authorized to view this conversation')
204
328
  return
205
329
  }
206
330
 
207
331
  // Read the transcript from disk. NO createSession, NO provider spawn. Reader is
208
332
  // injectable for tests so the suite never touches the real ~/.claude/projects.
209
- const readTranscript = ctx.readConversationTranscript || defaultReadConversationHistoryAsync
333
+ //
334
+ // #7501 — through the META reader, not the array-returning sibling one line
335
+ // away. This path is subject to jsonl-reader's OWN two caps (the 500
336
+ // most-recent `MAX_MESSAGES` window and the `MAX_TRANSCRIPT_BYTES` tail read),
337
+ // and the array alone cannot express either: 500 entries back is equally the
338
+ // shape of a complete 500-message conversation. This is the SAME reader
339
+ // `getFullHistoryAsync` uses for the full-history path (#7484) rather than a
340
+ // second meta implementation, so both replays report the same caps from one
341
+ // place and cannot drift apart.
342
+ //
343
+ // #7828 — the file is chosen by the conversation's OWN provider and locator,
344
+ // never by assuming Claude's layout. A refusal (unknown/unsupported provider,
345
+ // mismatched or escaping locator) is a session_error; nothing is retried
346
+ // against another provider's store.
347
+ const source = resolveTranscriptSource({
348
+ // A conversation the scan found carries its provider (absent => unknown).
349
+ // The cwd-hint path has no scan record and is Claude-only unless the
350
+ // request names another provider, which then reports its own refusal.
351
+ provider: conv ? conv.provider : (wantedProvider || 'claude'),
352
+ conversationId,
353
+ cwd,
354
+ sourceLocator: conv?.sourceLocator ?? null,
355
+ sources: ctx.runtime.transcriptSources,
356
+ })
357
+ if (!source.ok) {
358
+ fail(source.reason)
359
+ return
360
+ }
361
+ const readTranscript = ctx.readConversationTranscript || defaultReadConversationTranscript
210
362
  let messages = []
363
+ let truncated = false
364
+ const limiter = ctx.transcriptReadLimiter || defaultTranscriptReadLimiter
365
+ const closing = signalOnClose(ws)
211
366
  try {
212
- messages = await readTranscript(resolveJsonlPath(cwd, conversationId))
367
+ // Duplicate in-flight requests for the same file share one read.
368
+ const readKey = `${source.path}\0${source.identity ? `${source.identity.dev}:${source.identity.ino}` : ''}`
369
+ const read = await limiter.submit(
370
+ { key: readKey, ...admissionFor(client, isBoundClient), signal: closing.signal },
371
+ (signal) => readTranscript(source.path, undefined, { expectedIdentity: source.identity, signal, admitted: true }),
372
+ )
373
+ if (Array.isArray(read)) {
374
+ // The pre-#7501 reader shape. `ctx.readConversationTranscript` is a
375
+ // TEST-ONLY injection seam — nothing in production injects it, so this
376
+ // branch is unreachable outside the suite — and a legacy fixture still
377
+ // supplies a bare array, accepted and reported as untruncated rather than
378
+ // throwing on a shape that used to work. `false` over omitting the field:
379
+ // omitting it puts the frame back into the exact absent-vs-false ambiguity
380
+ // #7501 removes, and gives the wire two shapes to pin instead of one. Same
381
+ // posture handleRequestFullHistory takes toward a descriptor-less legacy
382
+ // manager.
383
+ messages = read
384
+ } else if (read && Array.isArray(read.messages)) {
385
+ messages = read.messages
386
+ // Strict boolean, matching how both clients read this family of field.
387
+ truncated = read.truncated === true
388
+ }
213
389
  } catch (err) {
214
- // A read error is graceful — surface an empty transcript rather than a crash.
390
+ // The connection went away while the read waited or ran: nobody to answer.
391
+ if (err instanceof ReadCancelledError || err?.code === 'cancelled') return
392
+ if (err instanceof ReadLimitError) {
393
+ fail(`${err.message}. Try again shortly.`)
394
+ return
395
+ }
396
+ // #7828 — a missing/unreadable file or a corrupt record is a DATA error, not
397
+ // an empty successful transcript: say so, and send no replay frames.
215
398
  log.warn(`Failed to read transcript for ${conversationId}: ${err.message}`)
216
- messages = []
399
+ fail(err?.name === 'TranscriptDataError' ? err.message : 'Transcript could not be read. Try again.')
400
+ return
401
+ } finally {
402
+ closing.dispose()
217
403
  }
218
404
 
219
405
  // Stream back using the SAME wire shape as request_full_history so existing
220
406
  // renderers light up. `sessionId` carries the conversationId (read-only; no
221
407
  // live session exists for a closed conversation).
222
- ctx.transport.send(ws, { type: 'history_replay_start', sessionId: conversationId, fullHistory: true, conversationId })
223
- for (const entry of messages) {
224
- ctx.transport.send(ws, {
225
- type: 'message',
226
- messageType: entry.type,
227
- content: entry.content,
228
- tool: entry.tool,
229
- timestamp: entry.timestamp,
230
- sessionId: conversationId,
231
- })
232
- }
233
- ctx.transport.send(ws, { type: 'history_replay_end', sessionId: conversationId })
408
+ //
409
+ // Route through ctx.transport so a method-style sender keeps its receiver;
410
+ // the shared loop only ever needs a (ws, payload) callable.
411
+ // Frames of this replay name the conversation in `sessionId`; the conversation
412
+ // was authorised above, so they are marked as conversation frames (see
413
+ // markConversationFrame) and the delivery rule for other-session tags skips them.
414
+ const send = (target, payload) => ctx.transport.send(target, markConversationFrame(payload))
415
+
416
+ // #7501 — `truncated` describes the collection ACTUALLY SENT, and is emitted
417
+ // unconditionally: absence reads to a client exactly like `truncated: false`,
418
+ // which is what let this path hand the viewer the last 500 messages of a
419
+ // 5,000-message conversation with nothing on the wire saying so.
420
+ send(ws, { type: 'history_replay_start', sessionId: conversationId, truncated, fullHistory: true, conversationId })
421
+
422
+ // #7480 — the THIRD path through the #4833 chunk-and-drain loop, and the
423
+ // second one that had no `bufferedAmount` check at all: it pushed the whole
424
+ // transcript onto the socket in one turn of the event loop.
425
+ // `MAX_TRANSCRIPT_BYTES` caps the transcript, not how much of it is buffered
426
+ // on the socket at once, so a large transcript on a slow link could still
427
+ // sail past the 1MB EVICT_THRESHOLD in ws-client-sender.js — which CLOSES
428
+ // the client. Measured on the pre-fix code, a 30-entry fat transcript peaked
429
+ // at 6,148,308 bytes buffered: 5.9x the eviction line.
430
+ sendChunkedWithBackpressure(ws, messages, {
431
+ emit: (entry) => {
432
+ send(ws, {
433
+ type: 'message',
434
+ messageType: entry.type,
435
+ content: entry.content,
436
+ tool: entry.tool,
437
+ timestamp: entry.timestamp,
438
+ sessionId: conversationId,
439
+ })
440
+ },
441
+ onDone: () => {
442
+ send(ws, { type: 'history_replay_end', sessionId: conversationId })
443
+ // #7340: defence-in-depth. The dashboard normally DIVERTS this frame — it
444
+ // routes `history_replay_start`/`message`/`history_replay_end` for a pending
445
+ // transcript id into the transcript viewer, which never touches
446
+ // `sessionStates`, so no wipe happens — and the mobile app has no transcript
447
+ // surface at all. This covers the fail-safe branch where the diversion is not
448
+ // armed (a raw client, or a frame that arrives without a pending request), in
449
+ // which case the client wipes its ACTIVE session's badge list because
450
+ // `conversationId` is a closed transcript with no live session behind it.
451
+ // Idempotent either way: both clients dedupe `agent_spawned` by `toolUseId`.
452
+ //
453
+ // The re-seed is CONDITIONAL, so it stays inside onDone rather than being
454
+ // hoisted out of the now-asynchronous loop: hoisting it would fire it
455
+ // before the replay frames it repairs, which is exactly the ordering the
456
+ // #7340 fix exists to establish.
457
+ if (client?.activeSessionId) {
458
+ ctx.transport.reseedActiveAgents(ws, client.activeSessionId)
459
+ }
460
+ },
461
+ })
234
462
  }
235
463
 
236
464
  async function handleRequestFullHistory(ws, client, msg, ctx) {
@@ -242,23 +470,208 @@ async function handleRequestFullHistory(ws, client, msg, ctx) {
242
470
  sendSessionError(ws, ctx, message)
243
471
  return
244
472
  }
245
- const fullHistory = await ctx.sessions.sessionManager.getFullHistoryAsync(targetId)
246
- ctx.transport.send(ws, { type: 'history_replay_start', sessionId: targetId, fullHistory: true })
473
+ const sessionManager = ctx.sessions.sessionManager
474
+ // Same admission as the strict transcript endpoint: the read is capped
475
+ // daemon-wide and per connection, and stops when the connection closes.
476
+ const closing = signalOnClose(ws)
477
+ let history
478
+ try {
479
+ history = await sessionManager.getFullHistoryAsync(targetId, { ...admissionFor(client, isBoundClient), signal: closing.signal })
480
+ } catch (err) {
481
+ if (err instanceof ReadLimitError) {
482
+ sendSessionError(ws, ctx, `${err.message}. Try again shortly.`)
483
+ return
484
+ }
485
+ throw err
486
+ } finally {
487
+ closing.dispose()
488
+ }
489
+ if (closing.signal.aborted) return
490
+ // #7484 — `getFullHistoryAsync` returns a descriptor: WHICH source it read
491
+ // (the on-disk JSONL transcript or the ring buffer) alongside the entries and
492
+ // that source's own truncation. Both decisions below turn on it, and neither
493
+ // can be recovered from the entries: a JSONL slice and a ring slice are the
494
+ // same shape of array.
495
+ //
496
+ // A bare array is the pre-#7484 shape. Accepted, and read as the ring buffer
497
+ // it always was, so a legacy ctx fixture keeps replaying rather than throwing
498
+ // — the same posture as the `typeof === 'function'` probes below. The REAL
499
+ // manager's shape is pinned at the producer
500
+ // (tests/session-manager-full-history-source.test.js), because every test on
501
+ // this side stubs the manager and so cannot witness it.
502
+ const hasDescriptor = !!history && !Array.isArray(history) && Array.isArray(history.entries)
503
+ const fullHistory = hasDescriptor ? history.entries : (Array.isArray(history) ? history : [])
504
+ const source = hasDescriptor && history.source === 'jsonl' ? 'jsonl' : 'ring'
505
+ // Route through ctx.transport so a method-style sender keeps its receiver;
506
+ // the shared loop only ever needs a (ws, payload) callable.
507
+ const send = (target, payload) => ctx.transport.send(target, payload)
508
+
509
+ // #7460 — frame parity with replayHistory. `truncated` is how a client learns
510
+ // history was dropped on this replay.
511
+ //
512
+ // #7484 — and it must describe the collection ACTUALLY SENT. `isHistoryTruncated`
513
+ // reports the RING BUFFER's overflow, while this handler usually sends the JSONL
514
+ // transcript, which has its own entirely separate caps (500 most-recent
515
+ // messages / a 25MB tail read, jsonl-reader.js). So `truncated: false` could
516
+ // accompany a slice that silently dropped everything before the last 500.
517
+ // Sourced from the descriptor it follows the slice; the probe survives only for
518
+ // the legacy array shape, where the ring IS the slice.
519
+ const truncated = hasDescriptor && typeof history.truncated === 'boolean'
520
+ ? history.truncated
521
+ : (typeof sessionManager.isHistoryTruncated === 'function'
522
+ ? sessionManager.isHistoryTruncated(targetId)
523
+ : false)
524
+ // `latestSeq` must describe what THIS replay actually DELIVERS, not what the
525
+ // ring buffer happens to hold. `getFullHistoryAsync` PREFERS the JSONL
526
+ // transcript whenever `resumeSessionId` is set, and jsonl-reader.js emits only
527
+ // user_input/response/tool_use — none of which carry `_seq`. Sourcing the
528
+ // counter from the buffer there advertises a cursor the client never received:
529
+ // `reconcileReplayEnd` hands it to `recordHistorySeq`, so the NEXT reconnect
530
+ // resolves as already-current and replays NOTHING, stranding the client on the
531
+ // lossy JSONL rebuild. Derived from the entries themselves this is unchanged on
532
+ // the ring-buffer path — that slice is the whole buffer, so its max `_seq` IS
533
+ // `getLatestHistorySeq()` — and correctly advertises nothing on the JSONL path.
534
+ let latestSeq
247
535
  for (const entry of fullHistory) {
248
- if (entry.type === 'user_input' || entry.type === 'response' || entry.type === 'tool_use') {
249
- ctx.transport.send(ws, {
250
- type: 'message',
251
- messageType: entry.type,
252
- content: entry.content,
253
- tool: entry.tool,
254
- timestamp: entry.timestamp,
255
- sessionId: targetId,
256
- })
257
- } else {
258
- ctx.transport.send(ws, { ...entry, sessionId: targetId })
536
+ if (entry && typeof entry._seq === 'number' && (latestSeq === undefined || entry._seq > latestSeq)) {
537
+ latestSeq = entry._seq
259
538
  }
260
539
  }
261
- ctx.transport.send(ws, { type: 'history_replay_end', sessionId: targetId })
540
+ // Omitted, never zeroed: absence means "this replay carried no cursor", while
541
+ // `latestSeq: 0` is a real seq the client would happily record.
542
+ const seqFrame = latestSeq === undefined ? {} : { latestSeq }
543
+
544
+ send(ws, { type: 'history_replay_start', sessionId: targetId, truncated, fullHistory: true, ...seqFrame })
545
+
546
+ // #7460 — the SAME chunk + bufferedAmount loop replayHistory uses, from the
547
+ // one implementation of it. Sending a 1000-entry ring buffer synchronously
548
+ // could push the socket past the 1MB EVICT_THRESHOLD in ws-client-sender.js
549
+ // and CLOSE the client: "Sync Full History" — the button a user presses
550
+ // BECAUSE the view looks wrong — was the action that could drop the
551
+ // connection.
552
+ // #8965: no synthesized agent_idle for a replayed result while the session runs.
553
+ const replayBusy = () => typeof sessionManager.isSessionBusy === 'function'
554
+ ? sessionManager.isSessionBusy(targetId)
555
+ : false
556
+ sendChunkedWithBackpressure(ws, fullHistory, {
557
+ emit: (entry) => {
558
+ if (entry.type === 'user_input' || entry.type === 'response' || entry.type === 'tool_use') {
559
+ send(ws, {
560
+ type: 'message',
561
+ messageType: entry.type,
562
+ content: entry.content,
563
+ tool: entry.tool,
564
+ timestamp: entry.timestamp,
565
+ sessionId: targetId,
566
+ })
567
+ } else {
568
+ // This is the SECOND replay path, and both per-entry duties — the
569
+ // `_seq` → `historySeq` map (#7454) and the `result` → `agent_idle`
570
+ // synthesis (#7459 / #4628) — come from ws-history.js's shared emitter
571
+ // rather than a copy that can drift away from it again.
572
+ sendHistoryEntry(send, ws, targetId, entry, client, replayBusy)
573
+ }
574
+ },
575
+ onDone: () => {
576
+ // #7484 — the JSONL path's heal. `sendHistoryEntry` synthesizes
577
+ // `agent_idle` from a replayed `result`, and a JSONL slice has none:
578
+ // jsonl-reader.js emits user_input/response/tool_use only. Since
579
+ // `getFullHistoryAsync` PREFERS that transcript for any session with a
580
+ // `resumeSessionId` — the normal state of a live claude-family session —
581
+ // the #4628 heal could not fire on the source almost every "Sync Full
582
+ // History" press actually reads.
583
+ //
584
+ // The stale chip is CLIENT-side state: a live `tool_start` whose
585
+ // `tool_result` never arrived (a dropped PostToolUse hook).
586
+ // `history_replay_start` deliberately PRESERVES that set (#4466) and
587
+ // nothing in a JSONL slice can clear it — those entries rebuild as
588
+ // `message` frames, which touch no tool state. `agent_idle` is the only
589
+ // frame that clears it and is not replay-gated.
590
+ //
591
+ // ONE heal, at the end, rather than a per-entry synthesis: JSONL rows
592
+ // carry no dependable turn boundary to hang one on, and landing after the
593
+ // last entry is what makes it unable to wipe an activeTools set
594
+ // MID-replay. Before `history_replay_end`, so it stays inside the window
595
+ // where the #4466 reasoning holds.
596
+ //
597
+ // NOT while `isSessionBusy` reports the session LIVE. `agent_idle` sets
598
+ // isIdle, clears streamingMessageId (hiding the stop button) and clears
599
+ // activeTools — all true after a finished turn, and no `agent_busy` is
600
+ // coming to undo it before the next turn starts.
601
+ //
602
+ // #7507 — "live" here is deliberately WIDER than mid-turn, and the comment
603
+ // this replaced described only the narrow half. `isSessionBusy` is
604
+ // `entry.session.isRunning`, which BaseSession defines as
605
+ // `_isBusy || _backgroundShellTracker.size > 0`: a session whose turn has
606
+ // ENDED but which still holds an un-polled `Bash(run_in_background: true)`
607
+ // shell reads busy (#4307; the 60s advisory sweep must not flip liveness,
608
+ // #5247, so release comes only from BashOutput / destroy / the 4h hard
609
+ // quiesce). Do NOT "simplify" this to `_isBusy`.
610
+ //
611
+ // The reason is CONSISTENCY WITH THE SERVER'S SINGLE BUSY AUTHORITY, not
612
+ // mid-turn correctness. `listSessions()` publishes that same `isRunning` as
613
+ // each entry's `isBusy`, and BOTH clients re-derive `isIdle` from it on
614
+ // every `session_list` and `session_activity` (#4639 for the dashboard;
615
+ // #7518 gave the mobile app the same two paths, via the shared store-core
616
+ // `isIdlePatches` derivation and the shared `session_activity` dispatch
617
+ // entry). A narrower `_isBusy` guard would emit an `agent_idle` that the
618
+ // very next broadcast reverts — a flicker, not a heal, on either client.
619
+ // Pinned by behaviour in
620
+ // tests/conversation-full-history-replay.test.js (a real SessionManager +
621
+ // BaseSession) and at the producer in
622
+ // tests/session-manager-full-history-source.test.js.
623
+ //
624
+ // Until #7518 that argument held for the dashboard ALONE: the app had
625
+ // neither path, so the suppression was a pure false negative there — this
626
+ // synthesized `agent_idle` was the only thing that could clear a stale
627
+ // chip (#7479 N2), and a session holding an un-polled background shell
628
+ // kept one. That is why the fix went to the CLIENT rather than forking
629
+ // this guard per client, and why the guard did not change: with both
630
+ // clients consuming the same authority, one rule is now right on both.
631
+ //
632
+ // One consequence still worth recording:
633
+ // - The LIVE path is LESS conservative than this. event-normalizer.js
634
+ // appends `agent_idle` to every `result` unconditionally, without
635
+ // consulting `isRunning`; the replay heal mirrors that fan-out
636
+ // (ws-history.js) everywhere except this state.
637
+ //
638
+ // A manager that cannot answer is treated as idle: "cannot tell" must not
639
+ // silently become "never heal", which is the defect this fixes.
640
+ const busy = typeof sessionManager.isSessionBusy === 'function'
641
+ ? sessionManager.isSessionBusy(targetId)
642
+ : false
643
+ if (source === 'jsonl' && !busy) {
644
+ send(ws, { type: 'agent_idle', sessionId: targetId })
645
+ }
646
+ send(ws, { type: 'history_replay_end', sessionId: targetId, ...seqFrame })
647
+ // #7340: same wipe, same repair — `request_full_history` targets a LIVE
648
+ // session, so its confirmed-backgrounded subagents must be re-asserted
649
+ // after the replay that cleared them.
650
+ ctx.transport.reseedActiveAgents(ws, targetId)
651
+ // #7457: same sweep, same repair. This end frame runs the client's
652
+ // unanswered-prompt sweep exactly as `replayHistory`'s does, so "Sync
653
+ // Full History" — the button a user presses BECAUSE the view looks
654
+ // wrong — would otherwise resolve the very question they are blocked on.
655
+ // The sibling `request_conversation_transcript` replay is exempt: its
656
+ // frames carry a conversationId in `sessionId`, which is never a live
657
+ // session id, so both clients' `updateSession` no-ops and the sweep
658
+ // touches nothing.
659
+ // #8357: PERMISSIONS FIRST, as `replayHistory`'s `finishReplay` does -- a
660
+ // question card is gated by its own permission, which the client must
661
+ // already hold when the question lands.
662
+ // #8340 / #8328: the permission card. `permission_request` is
663
+ // transient, so this full rebuild swaps the live Allow/Deny card away and
664
+ // the replay cannot restore it; `replayHistory` re-sends after its own end
665
+ // frame, and this path ends its own, so it must too. Same single
666
+ // implementation (ws-history's resendPendingPermissionsForSession), which
667
+ // keeps the #8342 session-bound-client guard.
668
+ try {
669
+ ctx.transport.resendPendingPermissions(ws, targetId)
670
+ } finally {
671
+ ctx.transport.resendPendingQuestions(ws, targetId)
672
+ }
673
+ },
674
+ })
262
675
  }
263
676
 
264
677
  async function handleRequestSessionContext(ws, client, msg, ctx) {