moi-computer 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/client/api/workspace-keys.ts +1 -2
  2. package/client/app/AppRouter.tsx +10 -3
  3. package/client/app/routes/HomeRoute.tsx +1 -1
  4. package/client/app/shell/SidebarLayout.tsx +2 -14
  5. package/client/components/shared/Composer.tsx +20 -7
  6. package/client/components/shared/PanelHeader.tsx +8 -1
  7. package/client/components/ui/button.tsx +3 -3
  8. package/client/components/ui/dialog.tsx +1 -1
  9. package/client/components/ui/dropdown-menu.tsx +2 -2
  10. package/client/components/ui/hover-card.tsx +1 -1
  11. package/client/components/ui/popover.tsx +1 -1
  12. package/client/components/ui/resizable.tsx +40 -0
  13. package/client/features/chat/ChatEmptyState.tsx +9 -11
  14. package/client/features/chat/ChatPanel.tsx +76 -48
  15. package/client/features/chat/ChatPopup.tsx +16 -2
  16. package/client/features/chat/ChatPromptBubbles.tsx +6 -8
  17. package/client/features/chat/ChatSelector.tsx +24 -7
  18. package/client/features/chat/MarkdownContent.tsx +1 -1
  19. package/client/features/chat/ModelPicker.tsx +5 -4
  20. package/client/features/chat/TurnView.tsx +108 -13
  21. package/client/features/chat/api.ts +1 -18
  22. package/client/features/chat/chat-send.ts +2 -2
  23. package/client/features/chat/{ChatComposer.tsx → composer/ChatComposer.tsx} +6 -5
  24. package/client/features/chat/composer/banners/ChatErrorBanner.tsx +28 -0
  25. package/client/features/chat/composer/banners/ComposerBanner.tsx +30 -0
  26. package/client/features/chat/composer/banners/WorkspaceAgentAvailabilityBanner.tsx +91 -0
  27. package/client/features/{workspace → chat/composer/banners}/WorkspaceSkillUpdateBanner.tsx +9 -7
  28. package/client/features/chat/composer/useWorkspaceComposerState.tsx +74 -0
  29. package/client/features/{workspace → chat/composer}/useWorkspaceSkillUpdates.ts +1 -1
  30. package/client/features/chat/group-turns.ts +46 -28
  31. package/client/features/chat/interleave-notices.ts +84 -0
  32. package/client/features/chat/model-order.ts +9 -3
  33. package/client/features/chat/tool-group/TimelineRow.tsx +23 -11
  34. package/client/features/chat/tool-group/ToolCallGroup.tsx +38 -3
  35. package/client/features/chat/tool-group/format.ts +51 -10
  36. package/client/features/chat/useAppletChatMessage.ts +11 -16
  37. package/client/features/chat/useChat.ts +3 -7
  38. package/client/features/dev/ChatStatesPage.tsx +466 -0
  39. package/client/features/dev/DevIndexPage.tsx +52 -0
  40. package/client/features/dev/DevRoutes.tsx +6 -3
  41. package/client/features/dev/HarnessDebugPage.tsx +3 -3
  42. package/client/features/dev/chat-states-fixtures.ts +744 -0
  43. package/client/features/scratchpad/Scratchpad.tsx +4 -0
  44. package/client/features/scratchpad/scratch-session.ts +71 -0
  45. package/client/features/views/ViewBuilderTab.tsx +5 -4
  46. package/client/features/views/useViewBuilderActions.ts +2 -2
  47. package/client/features/workspace/WorkspaceLayoutContext.tsx +4 -2
  48. package/client/features/workspace/WorkspaceScreen.tsx +128 -146
  49. package/client/features/workspace/WorkspaceSplitLayout.tsx +111 -0
  50. package/client/features/workspace/api.ts +33 -8
  51. package/client/features/workspace/useFitsSplitLayout.ts +31 -5
  52. package/client/index.css +1 -1
  53. package/client/lib/flags.ts +4 -3
  54. package/client/runtime/useWorkspaceEvents.ts +18 -1
  55. package/client/store/ui.ts +5 -1
  56. package/dist/{chunk-0pcdwjkp.js → chunk-2vaafjp4.js} +1 -1
  57. package/dist/{chunk-9y2zbzqz.js → chunk-35fq49qa.js} +1 -1
  58. package/dist/{chunk-h9h8f176.js → chunk-3b3rkjet.js} +1 -1
  59. package/dist/chunk-gt7n06ef.js +1 -0
  60. package/dist/{chunk-r5ce5cdg.js → chunk-kkj86722.js} +75 -75
  61. package/dist/chunk-ty1sqbmn.js +80 -0
  62. package/dist/chunk-xeyxk7ep.js +10 -0
  63. package/dist/chunk-yz6wd5vc.css +1 -0
  64. package/dist/index.html +1 -1
  65. package/lib/format.ts +37 -7
  66. package/lib/themes.ts +2 -2
  67. package/lib/types.ts +38 -8
  68. package/lib/workspace-layout.ts +2 -2
  69. package/package.json +6 -4
  70. package/server/agent.ts +199 -0
  71. package/server/api.ts +36 -17
  72. package/server/bundler/build-applet.ts +35 -44
  73. package/server/cli-env.ts +2 -2
  74. package/server/cli.ts +39 -53
  75. package/server/constants.ts +8 -0
  76. package/server/control-client.ts +124 -0
  77. package/server/control.ts +2 -2
  78. package/server/env-apply.ts +4 -0
  79. package/server/harness/README.md +32 -12
  80. package/server/harness/claude-code/auth.ts +54 -0
  81. package/server/harness/claude-code/index.ts +6 -1
  82. package/server/harness/codex/adapter.ts +9 -1
  83. package/server/harness/codex/auth.ts +50 -0
  84. package/server/harness/codex/index.ts +6 -1
  85. package/server/harness/codex/session.ts +33 -14
  86. package/server/harness/openclaw/NOTES.md +619 -186
  87. package/server/harness/openclaw/adapter.ts +121 -54
  88. package/server/harness/openclaw/compat.ts +95 -0
  89. package/server/harness/openclaw/cron-view.ts +78 -0
  90. package/server/harness/openclaw/discovery.ts +145 -52
  91. package/server/harness/openclaw/gateway.ts +224 -36
  92. package/server/harness/openclaw/index.ts +56 -21
  93. package/server/harness/openclaw/session.ts +1002 -67
  94. package/server/harness/openclaw/strip.ts +71 -23
  95. package/server/harness/openclaw/thinking.ts +150 -0
  96. package/server/harness/types.ts +10 -5
  97. package/server/layout.ts +5 -2
  98. package/server/service.ts +2 -2
  99. package/workspace/.claude/skills/moi-workspace/SKILL.md +6 -6
  100. package/workspace/.claude/skills/moi-workspace/{DESIGN.md → references/DESIGN.md} +19 -9
  101. package/client/features/dev/PixelPainter.tsx +0 -94
  102. package/client/features/dev/PlaygroundPage.tsx +0 -69
  103. package/dist/chunk-0k7brsms.js +0 -9
  104. package/dist/chunk-dfs36zgc.js +0 -1
  105. package/dist/chunk-dtwxpxbg.js +0 -51
  106. package/dist/chunk-ga7t9qsk.js +0 -2
  107. package/dist/chunk-tey2nq7c.js +0 -31
  108. package/dist/chunk-z73xpsa0.js +0 -50
  109. package/dist/chunk-zzgredta.css +0 -1
  110. /package/workspace/.claude/skills/moi-workspace/{SCRATCHPAD.md → references/SCRATCHPAD.md} +0 -0
@@ -1,21 +1,34 @@
1
- // Per-(workspaceId, sessionId) live OpenClaw session adapter.
1
+ // Per-(workspaceId, sessionId) live OpenClaw session.
2
2
  //
3
- // Owns the durable in-memory view for a session and converts each
4
- // `session.message` frame into our `StreamEvent`s. One instance is created
5
- // the first time the workspace's UI asks for its events (via the REST
6
- // endpoint) or sends a chat into it; thereafter it stays subscribed so the
7
- // view is up to date for reattach without re-fetching `sessions.get`.
3
+ // Holds the in-memory view for one session and keeps it current from the
4
+ // gateway's event stream: `session.message` rows build the turns, `chat` frames
5
+ // drive the streaming preview, tool frames drive the tool cards, and the
6
+ // run-end reconcile against `sessions.get` catches anything the wire dropped.
7
+ // The gateway is the source of truth — nothing is persisted here, so a cold
8
+ // open just re-seeds.
8
9
  //
9
- // What this module does NOT do:
10
- // - Token-delta streaming from `agent`/`chat` events (v2 — we use durable
11
- // `session.message` rows only, per the design call).
12
- // - Disk persistence — the gateway is the source of truth; we re-seed from
13
- // `sessions.get` on cold start.
10
+ // The frame families and the order they arrive in are documented in NOTES.md
11
+ // §6; the rules that follow from it (who owns a tool card, why identity is
12
+ // decided once) are worth reading before changing anything here.
14
13
  import { appendAttachmentNote } from '@/lib/attachment-note'
15
- import { type MoiContext, appendMoiContext, renderMoiContext } from '@/lib/moi-context'
16
- import { applyEvent, emptyViewState } from '@/lib/format'
14
+ import {
15
+ type MoiContext,
16
+ appendMoiContext,
17
+ renderMoiContext,
18
+ stripMoiContext
19
+ } from '@/lib/moi-context'
20
+ import {
21
+ type PreviewBlock,
22
+ type ToolCall,
23
+ type ToolState,
24
+ type Turn,
25
+ applyEvent,
26
+ emptyViewState
27
+ } from '@/lib/format'
17
28
  import type { SessionActivity, StreamEvent, ViewState } from '@/lib/types'
18
29
 
30
+ import { messageIdempotencyKey } from './compat'
31
+
19
32
  import {
20
33
  type OpenClawMessage,
21
34
  type OpenClawSessionDetail,
@@ -25,10 +38,17 @@ import { renameSelectedSession } from '../../selected-session'
25
38
  import {
26
39
  type ToolResultInfo,
27
40
  findToolCallOwners,
41
+ flattenToolResultContent,
28
42
  messageToTurn,
29
43
  toolResultFromMessage
30
44
  } from './adapter'
31
- import { getGateway, onGatewayReconnected } from './gateway'
45
+ import {
46
+ currentGatewayHandle,
47
+ getGateway,
48
+ onGatewayReconnected,
49
+ releaseSessionSubscriptionRef
50
+ } from './gateway'
51
+ import { recordOpenClawThinkingProfile, recordOpenClawThinkingRejection } from './thinking'
32
52
  import { broadcast } from '../../state'
33
53
  import { materializeToPath, resolveUploads } from '../../uploads'
34
54
  import {
@@ -57,15 +77,78 @@ type SessionRecord = {
57
77
  seeded: boolean
58
78
  pendingFrames: OpenClawMessage[]
59
79
  // Optimistic id rendezvous: when the client sends a message we push the
60
- // optimistic id + text onto this FIFO. The next matching durable user-row
61
- // consumes the head entry and is re-emitted with that id (preventing a
62
- // duplicate bubble). A queue rather than a single slot so two rapid sends
63
- // don't lose the first rendezvous when the gateway echo lags ~6s behind.
64
- pendingUserEchoes: { optimisticId: string; text: string }[]
80
+ // optimistic id + text onto this FIFO. The durable user-row is matched by
81
+ // its idempotency key (`<runId>:user`, exact) when the send's runId is
82
+ // known, else by text. A queue rather than a single slot so two rapid sends
83
+ // don't lose the first rendezvous when the gateway echo lags behind.
84
+ pendingUserEchoes: { optimisticId: string; text: string; runId?: string }[]
85
+ // Whether the client asked for token previews on the latest send.
86
+ streamEnabled: boolean
87
+ // Which frame family owns the current run's streaming preview. The first of
88
+ // `chat` / `agent` to emit a delta claims the run so a gateway emitting both
89
+ // doesn't double-broadcast (see claimPreviewSource).
90
+ previewRunId?: string
91
+ previewSource?: 'chat' | 'agent'
92
+ // Streaming reasoning for the current run, and the last text blocks painted
93
+ // with it. The `chat`/`agent` arbitration above decides who owns the TEXT,
94
+ // but reasoning is not a duplicate of that text — on claude-cli it arrives on
95
+ // its own `agent`/thinking stream while `chat` owns the text — so it bypasses
96
+ // the claim and is merged into the same preview here instead. Both are
97
+ // per-run and cleared when the run terminalizes.
98
+ previewReasoning?: { runId: string; text: string }
99
+ previewTextBlocks?: { runId: string; blocks: PreviewBlock[] }
100
+ // Calls rendered as their own turn because no durable row owned them when the
101
+ // tool started, keyed by toolCallId. Permanent for the session: durable rows
102
+ // suppress these ids (adapter `omitToolCallIds`) so a row that later grows the
103
+ // matching block can't render the call twice. A broadcast turn can never be
104
+ // retracted, so ownership is decided once and then respected.
105
+ liveTools: Map<string, { name: string; input: unknown; seq: number }>
106
+ // Live reasoning spans from `agent`/item frames of kind `analysis`, keyed by
107
+ // itemId. Timing only — those frames carry no reasoning text (see
108
+ // handleReasoningItemFrame).
109
+ liveThinking: Map<string, { startedAt: number; endedAt?: number; seq?: number }>
110
+ // Highest `__openclaw.seq` ingested, and a monotonic tick for the synthetic
111
+ // turns that hang off it. Together they place a live card between the
112
+ // durable row that preceded it and the one that follows (see liveTurnSeq).
113
+ lastDurableSeq: number
114
+ liveTurnTick: number
115
+ // The model ref we last asked the gateway for, and the `provider/model` the
116
+ // last row reported. They differ only when something outside moi moved the
117
+ // session, which is the whole point of keeping both.
118
+ requestedModel?: string
119
+ wireModel?: string
120
+ appliedThinking?: string
121
+ // Last `reasoningLevel` applied. The gateway defaults this to `off`, which
122
+ // suppresses reasoning output entirely on providers that would emit it.
123
+ appliedReasoning?: string
124
+ // Model of the most recent assistant row seen (seed scan + live ingest). Lets
125
+ // ingest detect a mid-session model switch without re-scanning the whole
126
+ // messagesById map each frame; the model-change notice reads its `prev` here.
127
+ lastAssistantModel?: string
128
+ // Idle-eviction timer, armed when the session goes idle and cleared when it
129
+ // goes busy or is torn down. OpenClaw holds only WS listeners (no subprocess),
130
+ // so eviction just drops the record and releases the subscription.
131
+ idleTimer?: ReturnType<typeof setTimeout> | null
132
+ // In-flight reconcile, so the two run-end signals (sessions.changed + agent
133
+ // lifecycle) coalesce onto one transcript fetch instead of racing two.
134
+ reconcilePromise?: Promise<void>
135
+ // The run whose failure we already told the user about. A dying run reports
136
+ // itself on several frames with several wordings; the first with text wins
137
+ // and the rest are echoes (see reportRunError).
138
+ reportedErrorRunId?: string
65
139
  }
66
140
 
67
141
  const MAX_PENDING_USER_ECHOES = 16
68
142
 
143
+ // OpenClaw sessions hold only WebSocket listeners — no subprocess, unlike Claude
144
+ // Code — so eviction is cheap to redo and a looser TTL avoids churning the
145
+ // cold-reopen re-seed. 10 minutes rather than Claude Code's 5.
146
+ const IDLE_TTL_MS = 10 * 60_000
147
+ // Soft cap on concurrently-held live records. Each is just a subscription +
148
+ // in-memory view, so the cap is generous; the oldest idle record is evicted
149
+ // when a new one would exceed it (a busy record is never evicted).
150
+ const MAX_LIVE_SESSIONS = 32
151
+
69
152
  const sessions = new Map<string, SessionRecord>() // key: `${workspaceId}:${sessionId}`
70
153
  const openclawAgents = new Map<
71
154
  string,
@@ -139,6 +222,10 @@ function setProcessing(rec: SessionRecord, processing: boolean, runId: string |
139
222
  sessionKey: rec.sessionKey,
140
223
  activeRunId: runId
141
224
  })
225
+ // Idle eviction must never fire mid-run: hold the timer off while busy, and
226
+ // (re)arm it whenever the session is idle.
227
+ if (processing) clearIdleTimer(rec)
228
+ else armIdleTimer(rec)
142
229
  if (existing?.processing === processing) return
143
230
  broadcast(rec.workspaceId, {
144
231
  type: 'status',
@@ -152,21 +239,141 @@ function setProcessing(rec: SessionRecord, processing: boolean, runId: string |
152
239
  }
153
240
  }
154
241
 
155
- // On run end the gateway has flushed every durable row — including
156
- // `toolResult` messages, which the live `session.message` stream does NOT
157
- // emit (verified empirically). Pull a fresh transcript and merge any new
158
- // toolResult rows so our tool-call cards flip from `pending` to
159
- // `success`/`error` with output. Idempotent.
160
- async function reconcileAfterRun(rec: SessionRecord): Promise<void> {
242
+ function clearIdleTimer(rec: SessionRecord): void {
243
+ if (rec.idleTimer) {
244
+ clearTimeout(rec.idleTimer)
245
+ rec.idleTimer = null
246
+ }
247
+ }
248
+
249
+ function armIdleTimer(rec: SessionRecord): void {
250
+ clearIdleTimer(rec)
251
+ rec.idleTimer = setTimeout(() => {
252
+ rec.idleTimer = null
253
+ // A run may have started after the timer was armed — re-check and never
254
+ // evict a busy session.
255
+ if (isOpenClawProcessing(rec.workspaceId, rec.sessionId)) return
256
+ teardownOpenClawSession(rec)
257
+ }, IDLE_TTL_MS)
258
+ }
259
+
260
+ // Drop a live session: stop consuming its frames, release the gateway
261
+ // subscription, and forget it. Idempotent — a record already removed from the
262
+ // map is a no-op. REST reads (`sessionEvents`/`ensureOpenClawSessionLive`) still
263
+ // work afterward: `getOrCreateOpenClawSession` cold-reopens and re-seeds from
264
+ // `sessions.get` (or synthesizes cron turns), so eviction only costs a re-seed.
265
+ export function teardownOpenClawSession(rec: SessionRecord): void {
266
+ const k = recKey(rec.workspaceId, rec.sessionId)
267
+ if (sessions.get(k) !== rec) return
268
+ clearIdleTimer(rec)
269
+ rec.ingestUnsubscribe?.()
270
+ rec.ingestUnsubscribe = undefined
271
+ // Release the refcounted subscription. When connected, go through the handle
272
+ // (drops demand + issues the wire unsubscribe on the last holder); never force
273
+ // a connect from teardown. With no live handle (disconnected, or a test
274
+ // without a gateway) still drop the demand so a reconnect won't replay a dead
275
+ // key — the wire is already down.
276
+ const gw = currentGatewayHandle()
277
+ if (gw) {
278
+ void gw
279
+ .releaseSessionSubscription(rec.sessionKey)
280
+ .catch(err => console.error('[openclaw-session] releaseSessionSubscription failed', err))
281
+ } else {
282
+ releaseSessionSubscriptionRef(rec.sessionKey)
283
+ }
284
+ // Clear this workspace's trailing list-refresh timer only when no other live
285
+ // session remains for it — otherwise a sibling still needs it.
286
+ const workspaceHasOtherLive = [...sessions.values()].some(
287
+ r => r !== rec && r.workspaceId === rec.workspaceId
288
+ )
289
+ if (!workspaceHasOtherLive) {
290
+ const entry = lastListRefresh.get(rec.workspaceId)
291
+ if (entry?.trailing) clearTimeout(entry.trailing)
292
+ lastListRefresh.delete(rec.workspaceId)
293
+ }
294
+ const wasProcessing = isOpenClawProcessing(rec.workspaceId, rec.sessionId)
295
+ sessions.delete(k)
296
+ openclawAgents.delete(k)
297
+ // If it was mid-run, mirror setProcessing(rec, false, null)'s client-visible
298
+ // effect so no spinner is left hanging.
299
+ if (wasProcessing) {
300
+ broadcast(rec.workspaceId, { type: 'status', sessionId: rec.sessionId, activity: 'idle' })
301
+ }
302
+ }
303
+
304
+ // Server shutdown: tear down every live record so no session keeps consuming
305
+ // frames. We deliberately do NOT stop the shared gateway client — process exit
306
+ // drops it, and discovery may still need it during the same run. A cold reopen
307
+ // re-seeds from `sessions.get`.
308
+ export function killAllOpenClawSessions(): void {
309
+ for (const rec of [...sessions.values()]) teardownOpenClawSession(rec)
310
+ }
311
+
312
+ // Run-end reconcile against the canonical transcript. `toolResult` rows never
313
+ // stream (NOTES.md §6) and a row can grow content after it streams, so this is
314
+ // how the view catches up. Idempotent.
315
+ function reconcileAfterRun(rec: SessionRecord): Promise<void> {
316
+ // Both sessions.changed and agent lifecycle can end a run; coalesce onto one
317
+ // in-flight transcript fetch rather than racing two.
318
+ if (rec.reconcilePromise) return rec.reconcilePromise
319
+ const p = reconcileAfterRunImpl(rec).finally(() => {
320
+ if (rec.reconcilePromise === p) rec.reconcilePromise = undefined
321
+ })
322
+ rec.reconcilePromise = p
323
+ return p
324
+ }
325
+
326
+ async function reconcileAfterRunImpl(rec: SessionRecord): Promise<void> {
327
+ // Snapshot the unfinished cards BEFORE the fetch: `rec.liveTools` is
328
+ // session-wide, and a follow-up run starting during the round-trip would
329
+ // otherwise have its fresh cards swept by this run's reconcile.
330
+ const stale = unfinishedLiveTools(rec)
161
331
  const detail = await getOpenClawSessionMessages(rec.sessionId, rec.workspacePath, rec.agentId)
162
332
  if (!detail?.messages) return
333
+ mergeTranscript(rec, detail.messages, stale)
334
+ }
335
+
336
+ // Tool calls with a live card that has not reported a result yet.
337
+ function unfinishedLiveTools(rec: SessionRecord): string[] {
338
+ return [...rec.liveTools.keys()].filter(id => rec.results.get(id)?.running)
339
+ }
340
+
341
+ // Test seam: the merge half of the reconcile, against a transcript the caller
342
+ // supplies instead of one fetched over the gateway.
343
+ export function reconcileForTest(rec: SessionRecord, messages: OpenClawMessage[]): void {
344
+ mergeTranscript(rec, messages, unfinishedLiveTools(rec))
345
+ }
346
+
347
+ // Test seam: the two halves of the reconcile split, so a test can interleave a
348
+ // follow-up run's frames between the snapshot and the merge the way the real
349
+ // transcript round-trip does.
350
+ export function reconcileSnapshotForTest(rec: SessionRecord): string[] {
351
+ return unfinishedLiveTools(rec)
352
+ }
353
+
354
+ export function reconcileWithStaleForTest(
355
+ rec: SessionRecord,
356
+ messages: OpenClawMessage[],
357
+ stale: string[]
358
+ ): void {
359
+ mergeTranscript(rec, messages, stale)
360
+ }
361
+
362
+ // Fold a canonical transcript into the live view: adopt rows we're missing or
363
+ // behind on, refresh tool results, and end the cards in `stale` that the run
364
+ // left running.
365
+ function mergeTranscript(rec: SessionRecord, messages: OpenClawMessage[], stale: string[]): void {
163
366
  const owners = new Set<OpenClawMessage>()
164
- for (const msg of detail.messages) {
367
+ for (const msg of messages) {
165
368
  const result = toolResultFromMessage(msg)
166
369
  if (result) {
167
370
  const existing = rec.results.get(result.id)
168
371
  if (
169
372
  !existing ||
373
+ // A live `session.tool` start whose result frame was lost (disconnect)
374
+ // must be finalized even when the durable output is identical-empty —
375
+ // otherwise the card spins forever.
376
+ existing.running ||
170
377
  existing.output !== result.info.output ||
171
378
  existing.isError !== result.info.isError
172
379
  ) {
@@ -180,11 +387,36 @@ async function reconcileAfterRun(rec: SessionRecord): Promise<void> {
180
387
  if (msg.role !== 'user' && msg.role !== 'assistant') continue
181
388
  const id = msg.__openclaw?.id
182
389
  if (typeof id !== 'string') continue
183
- if (!rec.messagesById.has(id)) {
390
+ // Adopt rows we never saw AND rows whose content grew after they streamed.
391
+ // Both happen on the live wire: a row that fans out several tool calls is
392
+ // pushed as text and gains its `toolCall` blocks silently afterwards, so a
393
+ // has-the-id check alone leaves the view permanently behind the transcript.
394
+ const known = rec.messagesById.get(id)
395
+ if (!known || !sameContent(known, msg)) {
184
396
  rec.messagesById.set(id, msg)
397
+ rememberSeq(rec, msg)
185
398
  owners.add(msg)
186
399
  }
187
400
  }
401
+ // Cards still running when this run ended: nothing more is coming for them, so
402
+ // end them rather than leaving a permanent spinner. `stale` is captured before
403
+ // the transcript fetch — a follow-up run can start during it and add its own
404
+ // live cards, and finalizing those would strand the NEW run's tools.
405
+ //
406
+ // They end as errors, not successes. All we know is that no result arrived;
407
+ // reading that as "succeeded, with no output" would show a command that may
408
+ // well have failed as if it had worked.
409
+ for (const toolCallId of stale) {
410
+ const result = rec.results.get(toolCallId)
411
+ if (!result?.running) continue
412
+ rec.results.set(toolCallId, {
413
+ ...result,
414
+ running: false,
415
+ isError: true,
416
+ output: result.output || 'No result was reported before the run ended.'
417
+ })
418
+ emitLiveToolTurn(rec, toolCallId)
419
+ }
188
420
  if (owners.size === 0) return
189
421
  let idx = 0
190
422
  for (const m of rec.messagesById.values()) {
@@ -193,54 +425,506 @@ async function reconcileAfterRun(rec: SessionRecord): Promise<void> {
193
425
  }
194
426
  }
195
427
 
428
+ // Do two versions of the same durable row carry the same content? Structural
429
+ // compare on the blocks only — the fields around them (usage, stopReason) can
430
+ // be filled in later without changing what the turn renders.
431
+ function sameContent(a: OpenClawMessage, b: OpenClawMessage): boolean {
432
+ return JSON.stringify(a.content) === JSON.stringify(b.content)
433
+ }
434
+
196
435
  // Re-derive the view from the current messages + results map. Cheaper than
197
436
  // it sounds because we keep the materialized `view` and re-build only when
198
437
  // a tool-result update forces a re-emit.
199
438
  function rebuildView(rec: SessionRecord): void {
200
439
  let view: ViewState = emptyViewState()
201
440
  let i = 0
441
+ // Mirror the cold path (adapter.toStreamEvents): reconstruct model-change
442
+ // notices from the durable rows so a seeded live view replays the same
443
+ // notices the static transcript would show. Same ids as the live emitter,
444
+ // so a notice seen live upserts instead of duplicating.
445
+ let prevModel: string | undefined
202
446
  for (const msg of rec.messagesById.values()) {
203
- const turn = messageToTurn(msg, rec.sessionKey, i++, rec.results)
447
+ if (msg.role === 'assistant') {
448
+ const model = (msg as { model?: unknown }).model
449
+ if (typeof model === 'string') {
450
+ if (prevModel !== undefined && prevModel !== model) {
451
+ view = applyEvent(view, {
452
+ kind: 'notice',
453
+ notice: {
454
+ id: `openclaw:model-change:${msg.__openclaw?.id ?? i}`,
455
+ kind: 'model-change',
456
+ at:
457
+ typeof msg.timestamp === 'number'
458
+ ? new Date(msg.timestamp).toISOString()
459
+ : new Date().toISOString(),
460
+ model,
461
+ prev: prevModel
462
+ }
463
+ })
464
+ }
465
+ prevModel = model
466
+ }
467
+ }
468
+ const turn = messageToTurn(msg, rec.sessionKey, i++, rec.results, liveToolIds(rec))
204
469
  if (turn) view = applyEvent(view, { kind: 'turn', turn })
205
470
  }
471
+ // Compaction notices have no durable twin in `sessions.get` — they exist
472
+ // only while a live record witnesses the compact frame (known gap; the
473
+ // gateway's `sessions.compaction.list` could backfill them).
206
474
  rec.view = view
475
+ // Seed the model cache so live ingest can detect the next switch off the last
476
+ // assistant model without re-scanning the transcript.
477
+ rec.lastAssistantModel = prevModel
478
+ }
479
+
480
+ // The preview slot for a run. Doubles as `meta.apiMessageId` on the run's
481
+ // committed assistant turns so the client's native preview reconciliation
482
+ // clears the live text the instant the durable turn lands.
483
+ function previewMessageId(sessionKey: string, runId: string): string {
484
+ return `openclaw:${sessionKey}:${runId}`
485
+ }
486
+
487
+ // Compare the optimistic send text against the durable user-row text
488
+ // tolerantly: drop any moi-context envelope (defensive — the optimistic side
489
+ // shouldn't carry it) and collapse all whitespace runs so newline/trim drift
490
+ // between what we sent and what the gateway stored can't defeat the match.
491
+ export function normalizeEchoText(text: string | undefined): string {
492
+ if (typeof text !== 'string') return ''
493
+ return stripMoiContext(text).replace(/\s+/g, ' ').trim()
494
+ }
495
+
496
+ // Synthetic turns (live tool cards, live thinking spans) have no transcript
497
+ // row, so they get a fractional position just past the last durable row we
498
+ // ingested. That keeps them after the text that introduced them and before
499
+ // whatever the backend commits next, without ever colliding with a real seq.
500
+ function liveTurnSeq(rec: SessionRecord): number {
501
+ rec.liveTurnTick += 1
502
+ return rec.lastDurableSeq + rec.liveTurnTick / 1000
503
+ }
504
+
505
+ // Tool calls owned by a live card, for the adapter to leave out of durable
506
+ // rows. `undefined` when there are none, so the common path allocates nothing.
507
+ function liveToolIds(rec: SessionRecord): ReadonlySet<string> | undefined {
508
+ return rec.liveTools.size > 0 ? new Set(rec.liveTools.keys()) : undefined
207
509
  }
208
510
 
209
511
  function emitTurn(rec: SessionRecord, msg: OpenClawMessage, idx: number): void {
210
- const turn = messageToTurn(msg, rec.sessionKey, idx, rec.results)
512
+ const turn = messageToTurn(msg, rec.sessionKey, idx, rec.results, liveToolIds(rec))
211
513
  if (!turn) return
212
- // Optimistic-id rendezvous: if this is the first user-text turn that
213
- // matches what the client just sent, re-id it to the optimistic id so the
214
- // optimistic bubble upserts in place instead of duplicating.
514
+ // Optimistic-id rendezvous: re-id the durable user row to the bubble the
515
+ // client already drew, so it upserts in place instead of duplicating.
215
516
  if (rec.pendingUserEchoes.length > 0 && turn.role === 'user') {
216
- const text = turn.parts.find(p => p.type === 'text')?.text?.trim()
217
- if (text !== undefined) {
218
- const idx = rec.pendingUserEchoes.findIndex(e => e.text.trim() === text)
219
- if (idx >= 0) {
220
- turn.id = rec.pendingUserEchoes[idx].optimisticId
221
- rec.pendingUserEchoes.splice(idx, 1)
222
- }
517
+ const idem = messageIdempotencyKey(msg)
518
+ // Three ways in, cheapest first: the send's own `<runId>:user` key; the
519
+ // same key with the runId read off the row (the echo can beat the
520
+ // `sessions.send` response); and normalized text, for rows carrying
521
+ // neither.
522
+ const idemRunId = idem?.endsWith(':user') ? idem.slice(0, -':user'.length) : undefined
523
+ let at = idem
524
+ ? rec.pendingUserEchoes.findIndex(
525
+ e => (e.runId && `${e.runId}:user` === idem) || (idemRunId && e.runId === idemRunId)
526
+ )
527
+ : -1
528
+ if (at < 0) {
529
+ const text = normalizeEchoText(turn.parts.find(p => p.type === 'text')?.text)
530
+ if (text) at = rec.pendingUserEchoes.findIndex(e => normalizeEchoText(e.text) === text)
531
+ }
532
+ if (at >= 0) {
533
+ turn.id = rec.pendingUserEchoes[at].optimisticId
534
+ rec.pendingUserEchoes.splice(at, 1)
535
+ }
536
+ }
537
+ // Stamp the run's preview slot id so the client clears the streaming
538
+ // preview when this turn upserts (chat deltas can trail the durable row).
539
+ // Only FRESH turns get the current run's slot — a re-emitted older turn
540
+ // (tool-result fold-in, reconcile) keeps whatever it was stamped with, so
541
+ // it can never clear a newer run's live preview.
542
+ if (turn.role === 'assistant') {
543
+ const prior = rec.view.turns.find(t => t.id === turn.id)
544
+ if (prior) {
545
+ const kept = prior.meta?.apiMessageId
546
+ if (kept) turn.meta = { ...turn.meta, apiMessageId: kept }
547
+ } else if (rec.activeRunId) {
548
+ turn.meta = { ...turn.meta, apiMessageId: previewMessageId(rec.sessionKey, rec.activeRunId) }
223
549
  }
224
550
  }
225
551
  rec.view = applyEvent(rec.view, { kind: 'turn', turn })
226
552
  broadcast(rec.workspaceId, { kind: 'turn', turn, sessionId: rec.sessionId })
227
553
  }
228
554
 
229
- function ingest(rec: SessionRecord, msg: OpenClawMessage): void {
555
+ // Re-emit every assistant turn that references `toolCallId` so its tool card
556
+ // reflects the latest entry in `rec.results`.
557
+ function reemitToolCallOwners(rec: SessionRecord, toolCallId: string): void {
558
+ const owners = findToolCallOwners(rec.messagesById.values(), toolCallId)
559
+ const ownerSet = new Set(owners)
560
+ let idx = 0
561
+ for (const m of rec.messagesById.values()) {
562
+ if (ownerSet.has(m)) emitTurn(rec, m, idx)
563
+ idx++
564
+ }
565
+ }
566
+
567
+ // A `chat` delta frame carries the whole in-progress message; map its blocks to
568
+ // cumulative PreviewBlocks. Text and thinking only — tool calls have their own
569
+ // cards. Exported for tests.
570
+ export function chatPreviewBlocks(content: unknown): PreviewBlock[] {
571
+ if (typeof content === 'string') {
572
+ return content ? [{ index: 0, kind: 'text', text: content }] : []
573
+ }
574
+ if (!Array.isArray(content)) return []
575
+ const blocks: PreviewBlock[] = []
576
+ content.forEach((block, index) => {
577
+ if (!block || typeof block !== 'object') return
578
+ const b = block as { type?: unknown; text?: unknown; thinking?: unknown }
579
+ if (b.type === 'text' && typeof b.text === 'string' && b.text) {
580
+ blocks.push({ index, kind: 'text', text: b.text })
581
+ } else if (b.type === 'thinking' && typeof b.thinking === 'string' && b.thinking) {
582
+ blocks.push({ index, kind: 'reasoning', text: b.thinking })
583
+ }
584
+ })
585
+ return blocks
586
+ }
587
+
588
+ // A gateway streams the assistant text on BOTH `chat` state=delta and `agent`
589
+ // stream=assistant, for the same run, in the same millisecond. Whichever emits
590
+ // first claims the run so the two cumulative snapshots can't race into a
591
+ // flicker; a gateway sending only one of them still streams.
592
+ type PreviewSource = 'chat' | 'agent'
593
+ // Exported for tests: only reads/writes the two preview-source fields.
594
+ export function claimPreviewSource(
595
+ rec: Pick<SessionRecord, 'previewRunId' | 'previewSource'>,
596
+ runId: string,
597
+ source: PreviewSource
598
+ ): boolean {
599
+ if (rec.previewRunId !== runId) {
600
+ rec.previewRunId = runId
601
+ rec.previewSource = source
602
+ return true
603
+ }
604
+ return rec.previewSource === source
605
+ }
606
+
607
+ function broadcastPreview(rec: SessionRecord, messageId: string, blocks: PreviewBlock[]): void {
608
+ broadcast(rec.workspaceId, {
609
+ type: 'preview',
610
+ sessionId: rec.sessionId,
611
+ messageId,
612
+ parentToolUseId: null,
613
+ blocks
614
+ })
615
+ }
616
+
617
+ // Repaint the preview from both streams at once: reasoning first (it precedes
618
+ // the answer), then the text. A preview replaces every block for its messageId,
619
+ // so broadcasting the two separately would erase one with the other. Keyed by
620
+ // runId rather than by the claim, so reasoning can never lock the text source
621
+ // out of its own run.
622
+ function emitMergedPreview(rec: SessionRecord, runId: string, messageId: string): void {
623
+ const blocks: PreviewBlock[] = []
624
+ const reasoning = rec.previewReasoning?.runId === runId ? rec.previewReasoning.text : ''
625
+ if (reasoning) blocks.push({ index: 0, kind: 'reasoning', text: reasoning })
626
+ if (rec.previewTextBlocks?.runId === runId) {
627
+ for (const block of rec.previewTextBlocks.blocks)
628
+ blocks.push({ ...block, index: blocks.length })
629
+ }
630
+ broadcastPreview(rec, messageId, blocks)
631
+ }
632
+
633
+ // Drop the per-run preview state once the run terminalizes, so the next run
634
+ // starts clean instead of inheriting the previous run's reasoning.
635
+ function clearPreviewState(rec: SessionRecord): void {
636
+ rec.previewReasoning = undefined
637
+ rec.previewTextBlocks = undefined
638
+ }
639
+
640
+ // `agent` stream=assistant / reasoning frames carry the cumulative in-progress
641
+ // text in `data.text` — the fallback streaming source for gateways that don't
642
+ // emit `chat` delta frames.
643
+ function handleAgentStreamFrame(rec: SessionRecord, payload: Record<string, unknown>): void {
644
+ if (!rec.streamEnabled) return
645
+ const stream = payload.stream
646
+ // `thinking` is a second wire name for the reasoning stream, carrying the
647
+ // same `{ text, delta }` shape as `assistant`. Matching only `reasoning`
648
+ // dropped it on the floor. Verified on the wire from the `openai-codex`
649
+ // responses transport (`…:skill-workshop-review:*` sessions stream real
650
+ // reasoning text under `stream: 'thinking'`). Note this does NOT light up
651
+ // the claude-cli backend: its `thinking` frames are bare
652
+ // `{ progressTokens }` heartbeats with no text at all, so they fall out on
653
+ // the empty-text check below — that backend simply never ships the words.
654
+ const kind: PreviewBlock['kind'] | null =
655
+ stream === 'assistant'
656
+ ? 'text'
657
+ : stream === 'reasoning' || stream === 'thinking'
658
+ ? 'reasoning'
659
+ : null
660
+ if (!kind) return
661
+ const runId = typeof payload.runId === 'string' ? payload.runId : rec.activeRunId
662
+ if (!runId) return
663
+ const data = payload.data as { text?: unknown } | undefined
664
+ const text = typeof data?.text === 'string' ? data.text : ''
665
+ if (!text) return
666
+ if (kind === 'reasoning') {
667
+ // Reasoning bypasses the text claim entirely — see `previewReasoning`.
668
+ rec.previewReasoning = { runId, text }
669
+ } else {
670
+ if (!claimPreviewSource(rec, runId, 'agent')) return
671
+ rec.previewTextBlocks = { runId, blocks: [{ index: 0, kind, text }] }
672
+ }
673
+ emitMergedPreview(rec, runId, previewMessageId(rec.sessionKey, runId))
674
+ }
675
+
676
+ // A dying run says why on three different frames with three different wordings
677
+ // (NOTES.md §6), and the reason is something the user can act on. Report the
678
+ // first that carries text; the rest are echoes. Without this the chat just
679
+ // stops — spinner off, nothing said.
680
+ export function reportRunError(rec: SessionRecord, runId: string, message: unknown): void {
681
+ if (rec.reportedErrorRunId === runId) return
682
+ const text = typeof message === 'string' ? message.trim() : ''
683
+ if (!text) return
684
+ rec.reportedErrorRunId = runId
685
+ broadcast(rec.workspaceId, { kind: 'error', sessionId: rec.sessionId, content: text })
686
+ }
687
+
688
+ function handleChatFrame(rec: SessionRecord, payload: Record<string, unknown>): void {
689
+ const runId = typeof payload.runId === 'string' ? payload.runId : rec.activeRunId
690
+ if (!runId) return
691
+ // Errors are reported whether or not the client asked for token streaming —
692
+ // the toggle governs previews, not whether failures are visible.
693
+ if (payload.state === 'error') reportRunError(rec, runId, payload.errorMessage)
694
+ if (!rec.streamEnabled) return
695
+ const messageId = previewMessageId(rec.sessionKey, runId)
696
+ const state = payload.state
697
+ if (state === 'delta') {
698
+ const message = payload.message as { content?: unknown } | undefined
699
+ const blocks = chatPreviewBlocks(message?.content)
700
+ if (blocks.length === 0) return
701
+ if (!claimPreviewSource(rec, runId, 'chat')) return
702
+ rec.previewTextBlocks = { runId, blocks }
703
+ // Merged, not raw: on claude-cli the reasoning arrives on a separate
704
+ // stream, and a bare broadcast here would wipe it off the preview.
705
+ emitMergedPreview(rec, runId, messageId)
706
+ } else if (state === 'final' || state === 'error' || state === 'aborted') {
707
+ clearPreviewState(rec)
708
+ // Belt-and-braces clear: the durable turn's apiMessageId already clears
709
+ // the slot, but a trailing delta after the durable row would repaint it.
710
+ // 'aborted' arrives when a steer/abort interrupts the run mid-stream —
711
+ // without the clear the dead preview would linger (verified live).
712
+ broadcastPreview(rec, messageId, [])
713
+ }
714
+ }
715
+
716
+ // The id of the live tool turn for a toolCallId. Stable for the session, so
717
+ // every later frame for that call upserts the same card.
718
+ function liveToolTurnId(sessionKey: string, toolCallId: string): string {
719
+ return `openclaw:${sessionKey}:livetool:${toolCallId}`
720
+ }
721
+
722
+ // Build (and broadcast) a synthetic assistant turn holding a single tool card,
723
+ // from the live tool state in `rec.liveTools` + `rec.results`. Used when a
724
+ // tool executes before its durable owner row exists.
725
+ function emitLiveToolTurn(rec: SessionRecord, toolCallId: string): void {
726
+ const meta = rec.liveTools.get(toolCallId)
727
+ if (!meta) return
728
+ const result = rec.results.get(toolCallId)
729
+ let state: ToolState = 'pending'
730
+ if (result) state = result.running ? 'running' : result.isError ? 'error' : 'success'
731
+ const call: ToolCall = {
732
+ toolCallId,
733
+ name: meta.name,
734
+ caller: 'model',
735
+ provider: 'openclaw',
736
+ state,
737
+ input: meta.input
738
+ }
739
+ if (result && !result.running) {
740
+ if (result.isError) call.errorText = result.output
741
+ else call.output = result.output
742
+ }
743
+ const turn: Turn = {
744
+ id: liveToolTurnId(rec.sessionKey, toolCallId),
745
+ role: 'assistant',
746
+ origin: { kind: 'user-input' },
747
+ parts: [{ type: 'tool-call', call }],
748
+ seq: meta.seq
749
+ }
750
+ rec.view = applyEvent(rec.view, { kind: 'turn', turn })
751
+ broadcast(rec.workspaceId, { kind: 'turn', turn, sessionId: rec.sessionId })
752
+ }
753
+
754
+ // A run can die during admission, before it reports any lifecycle phase. The
755
+ // gateway announces that only as `sessions.changed { reason:
756
+ // 'chat.dispatch-error' }` — no runId, no error text — so the runId-keyed
757
+ // clauses never fire and the composer would spin forever. With no cause on the
758
+ // wire, say the one thing the user can act on.
759
+ export function handleDispatchError(rec: SessionRecord): void {
760
+ setProcessing(rec, false, null)
761
+ broadcast(rec.workspaceId, {
762
+ kind: 'error',
763
+ sessionId: rec.sessionId,
764
+ content: 'OpenClaw could not start the run. Send the message again.'
765
+ })
766
+ }
767
+
768
+ // The id of the run-scoped live thinking turn for a reasoning item.
769
+ function liveThinkingTurnId(sessionKey: string, itemId: string): string {
770
+ return `openclaw:${sessionKey}:livethink:${itemId}`
771
+ }
772
+
773
+ // Some runtimes report reasoning as an `agent`/item frame of `kind: 'analysis'`
774
+ // (emitted by `extensions/codex`) — presence and timing, never text. Render
775
+ // what they do give: a "Thinking" row that becomes "Thought for 1.2s", instead
776
+ // of a silent gap before the first token. Not durable — nothing in the
777
+ // transcript backs it, so a cold reload drops the row.
778
+ export function handleReasoningItemFrame(
779
+ rec: SessionRecord,
780
+ payload: Record<string, unknown>
781
+ ): void {
782
+ const data = payload.data as
783
+ | { itemId?: unknown; phase?: unknown; kind?: unknown; title?: unknown }
784
+ | undefined
785
+ if (!data || typeof data.itemId !== 'string') return
786
+ // Only the analysis/Reasoning item; other item kinds are tool lifecycle.
787
+ const isReasoning =
788
+ data.kind === 'analysis' || String(data.title ?? '').toLowerCase() === 'reasoning'
789
+ if (!isReasoning) return
790
+ const itemId = data.itemId
791
+ const at = typeof payload.ts === 'number' ? payload.ts : Date.now()
792
+
793
+ if (data.phase === 'start') {
794
+ rec.liveThinking.set(itemId, { startedAt: at })
795
+ } else if (data.phase === 'end') {
796
+ const started = rec.liveThinking.get(itemId)
797
+ if (!started) return
798
+ rec.liveThinking.set(itemId, { ...started, endedAt: at })
799
+ } else {
800
+ return
801
+ }
802
+ emitLiveThinkingTurn(rec, itemId)
803
+ }
804
+
805
+ function emitLiveThinkingTurn(rec: SessionRecord, itemId: string): void {
806
+ const span = rec.liveThinking.get(itemId)
807
+ if (!span) return
808
+ const duration = span.endedAt !== undefined ? span.endedAt - span.startedAt : undefined
809
+ const turn: Turn = {
810
+ id: liveThinkingTurnId(rec.sessionKey, itemId),
811
+ role: 'assistant',
812
+ origin: { kind: 'user-input' },
813
+ // Placed once, on the `start` frame — the `end` frame upserts the same
814
+ // turn, so the row must not hop to a new position when it finishes.
815
+ seq: (span.seq ??= liveTurnSeq(rec)),
816
+ parts: [
817
+ {
818
+ type: 'reasoning',
819
+ text: '',
820
+ redacted: true,
821
+ ...(duration !== undefined && duration >= 0 ? { durationMs: duration } : {})
822
+ }
823
+ ]
824
+ }
825
+ rec.view = applyEvent(rec.view, { kind: 'turn', turn })
826
+ broadcast(rec.workspaceId, { kind: 'turn', turn, sessionId: rec.sessionId })
827
+ }
828
+
829
+ // Live tool state, from either frame family: `session.tool` and `agent`/tool
830
+ // are the same payload sent to disjoint audiences (NOTES.md §6), so one
831
+ // handler serves both. start/update → running, result → success/error with
832
+ // output. Exported for tests.
833
+ export function handleToolFrame(rec: SessionRecord, payload: Record<string, unknown>): void {
834
+ const data = payload.data as
835
+ | {
836
+ phase?: unknown
837
+ name?: unknown
838
+ toolCallId?: unknown
839
+ isError?: unknown
840
+ result?: unknown
841
+ args?: unknown
842
+ }
843
+ | undefined
844
+ if (!data || typeof data.toolCallId !== 'string') return
845
+ const id = data.toolCallId
846
+ const name = typeof data.name === 'string' ? data.name : undefined
847
+ const toolName = name ? { toolName: name } : {}
848
+ if (data.phase === 'start' || data.phase === 'update') {
849
+ // Does a durable row already own this call? If so it renders the card. If
850
+ // not, this frame is the only evidence the call exists, so give it a turn of
851
+ // its own. Which case applies is a property of the run, not of the backend
852
+ // (NOTES.md §6) — asking the messages map is exact and needs no guess.
853
+ if (
854
+ name &&
855
+ !rec.liveTools.has(id) &&
856
+ findToolCallOwners(rec.messagesById.values(), id).length === 0
857
+ ) {
858
+ rec.liveTools.set(id, { name, input: data.args, seq: liveTurnSeq(rec) })
859
+ }
860
+ const existing = rec.results.get(id)
861
+ if (existing && !existing.running) return // final result already landed
862
+ rec.results.set(id, { output: '', isError: false, running: true, ...toolName })
863
+ } else if (data.phase === 'result') {
864
+ // Two result shapes on the wire: `{ content: [...] }` from the exec-style
865
+ // tools, and a bare string from CLI-backed runtimes. Reading `.content` off
866
+ // a string yields undefined, which rendered those cards with an empty body.
867
+ const raw = data.result
868
+ const content =
869
+ typeof raw === 'string' ? raw : ((raw as { content?: unknown } | undefined)?.content ?? '')
870
+ rec.results.set(id, {
871
+ output: flattenToolResultContent(content as OpenClawMessage['content']),
872
+ isError: data.isError === true,
873
+ ...toolName
874
+ })
875
+ } else {
876
+ return
877
+ }
878
+ const owners = findToolCallOwners(rec.messagesById.values(), id)
879
+ if (owners.length > 0) reemitToolCallOwners(rec, id)
880
+ else if (rec.liveTools.has(id)) emitLiveToolTurn(rec, id)
881
+ }
882
+
883
+ // Debounced session-list refresh. `sessions.changed` fires for every session
884
+ // under the agent and several records can hold subscriptions for one workspace,
885
+ // so bursts are the norm; the trailing flush catches the tail of one (a create
886
+ // followed straight away by the title patch).
887
+ const lastListRefresh = new Map<string, { at: number; trailing?: ReturnType<typeof setTimeout> }>()
888
+ const LIST_REFRESH_MIN_MS = 400
889
+ const LIST_REFRESH_REASONS = new Set([
890
+ 'chat.title',
891
+ 'create',
892
+ 'delete',
893
+ 'patch',
894
+ 'label',
895
+ 'compact',
896
+ 'send',
897
+ 'steer',
898
+ 'subagent-status'
899
+ ])
900
+ function broadcastSessionsChanged(rec: SessionRecord): void {
901
+ const now = Date.now()
902
+ const entry = lastListRefresh.get(rec.workspaceId)
903
+ if (entry && now - entry.at < LIST_REFRESH_MIN_MS) {
904
+ if (!entry.trailing) {
905
+ entry.trailing = setTimeout(
906
+ () => {
907
+ lastListRefresh.set(rec.workspaceId, { at: Date.now() })
908
+ broadcast(rec.workspaceId, { type: 'sessions_changed', sessionId: rec.sessionId })
909
+ },
910
+ LIST_REFRESH_MIN_MS - (now - entry.at)
911
+ )
912
+ }
913
+ return
914
+ }
915
+ if (entry?.trailing) clearTimeout(entry.trailing)
916
+ lastListRefresh.set(rec.workspaceId, { at: now })
917
+ broadcast(rec.workspaceId, { type: 'sessions_changed', sessionId: rec.sessionId })
918
+ }
919
+
920
+ // Exported for tests (the live subscription is the only production caller).
921
+ export function ingest(rec: SessionRecord, msg: OpenClawMessage): void {
230
922
  // toolResult: update the results map and re-emit each owner turn so the
231
923
  // tool-call card gets `state: 'success'/'error'` + output folded in.
232
924
  const result = toolResultFromMessage(msg)
233
925
  if (result) {
234
926
  rec.results.set(result.id, result.info)
235
- const owners = findToolCallOwners(rec.messagesById.values(), result.id)
236
- const i = 0
237
- const ownerSet = new Set(owners)
238
- let idx = 0
239
- for (const m of rec.messagesById.values()) {
240
- if (ownerSet.has(m)) emitTurn(rec, m, idx)
241
- idx++
242
- }
243
- void i
927
+ reemitToolCallOwners(rec, result.id)
244
928
  return
245
929
  }
246
930
 
@@ -249,8 +933,39 @@ function ingest(rec: SessionRecord, msg: OpenClawMessage): void {
249
933
  // `__openclaw.id`. The durable row arrives ~6s later with id + envelope.
250
934
  const id = msg.__openclaw?.id
251
935
  if (typeof id !== 'string') return
252
- const wasUpdate = rec.messagesById.has(id)
936
+ // A durable assistant row on a different model than the previous one marks
937
+ // a mid-session model switch (sessions.patch here or anywhere else) —
938
+ // surface it as a notice instead of letting it pass silently.
939
+ if (msg.role === 'assistant') {
940
+ const model = (msg as { model?: unknown }).model
941
+ if (typeof model === 'string') {
942
+ // Compare against the cached last assistant model instead of re-scanning
943
+ // the whole messagesById map each frame. Same notice id (`__openclaw.id`)
944
+ // as the cold rebuildView path, so live and cold agree on upsert.
945
+ const prev = rec.lastAssistantModel
946
+ if (prev !== undefined && prev !== model) {
947
+ const notice = {
948
+ id: `openclaw:model-change:${id}`,
949
+ kind: 'model-change' as const,
950
+ // The switching turn's own timestamp, so live and cold placement
951
+ // agree (the client sorts equal-time notices before the turn).
952
+ at:
953
+ typeof msg.timestamp === 'number'
954
+ ? new Date(msg.timestamp).toISOString()
955
+ : new Date().toISOString(),
956
+ model,
957
+ prev
958
+ }
959
+ // Fold into the view too — the REST events replay must agree with
960
+ // the WS frames the client already saw.
961
+ rec.view = applyEvent(rec.view, { kind: 'notice', notice })
962
+ broadcast(rec.workspaceId, { kind: 'notice', sessionId: rec.sessionId, notice })
963
+ }
964
+ rec.lastAssistantModel = model
965
+ }
966
+ }
253
967
  rec.messagesById.set(id, msg)
968
+ rememberSeq(rec, msg)
254
969
  // Compute idx as insertion order — for an update use the existing position,
255
970
  // for a new message it's the last slot.
256
971
  let idx = 0
@@ -258,10 +973,16 @@ function ingest(rec: SessionRecord, msg: OpenClawMessage): void {
258
973
  if (k === id) break
259
974
  idx++
260
975
  }
261
- void wasUpdate
262
976
  emitTurn(rec, msg, idx)
263
977
  }
264
978
 
979
+ // Track the furthest transcript position we've ingested, so synthetic turns
980
+ // can be placed just past it (liveTurnSeq).
981
+ function rememberSeq(rec: SessionRecord, msg: OpenClawMessage): void {
982
+ const seq = msg.__openclaw?.seq
983
+ if (typeof seq === 'number' && seq > rec.lastDurableSeq) rec.lastDurableSeq = seq
984
+ }
985
+
265
986
  async function seed(rec: SessionRecord): Promise<void> {
266
987
  const detail: OpenClawSessionDetail | null = await getOpenClawSessionMessages(
267
988
  rec.sessionId,
@@ -280,6 +1001,7 @@ async function seed(rec: SessionRecord): Promise<void> {
280
1001
  const id = msg.__openclaw?.id
281
1002
  if (typeof id !== 'string') continue
282
1003
  rec.messagesById.set(id, msg)
1004
+ rememberSeq(rec, msg)
283
1005
  }
284
1006
  rebuildView(rec)
285
1007
  }
@@ -311,34 +1033,88 @@ async function ensureSubscribed(rec: SessionRecord): Promise<void> {
311
1033
  return
312
1034
  }
313
1035
  ingest(rec, message)
1036
+ } else if (event === 'chat') {
1037
+ if (payload.sessionKey !== rec.sessionKey) return
1038
+ handleChatFrame(rec, payload)
1039
+ } else if (event === 'session.tool') {
1040
+ if (payload.sessionKey !== rec.sessionKey) return
1041
+ handleToolFrame(rec, payload)
314
1042
  } else if (event === 'sessions.changed') {
1043
+ // List refreshes apply to ANY session of the workspace's agent — cron
1044
+ // spawns, subagents, titles, patches. (2026.6.x never emits
1045
+ // `chat.title`; the other reasons cover title refreshes there.)
1046
+ const reason = typeof payload.reason === 'string' ? payload.reason : undefined
1047
+ if (reason && LIST_REFRESH_REASONS.has(reason)) broadcastSessionsChanged(rec)
315
1048
  if (payload.sessionKey !== rec.sessionKey) return
316
- if (payload.reason === 'chat.title') {
317
- broadcast(rec.workspaceId, { type: 'sessions_changed', sessionId: rec.sessionId })
318
- return
1049
+ if (reason === 'compact') {
1050
+ const notice = {
1051
+ id: `openclaw:compact:${typeof payload.ts === 'number' ? payload.ts : Date.now()}`,
1052
+ kind: 'compact' as const,
1053
+ at: new Date().toISOString()
1054
+ }
1055
+ rec.view = applyEvent(rec.view, { kind: 'notice', notice })
1056
+ broadcast(rec.workspaceId, { kind: 'notice', sessionId: rec.sessionId, notice })
1057
+ }
1058
+ // Frames embed the fresh session row — keep the applied-model cache
1059
+ // truthful even when the session is patched outside moi. Run-phase frames
1060
+ // nest it under `session`; `reason` frames flatten it onto the payload.
1061
+ const row = (payload.session ?? payload) as
1062
+ | { model?: unknown; modelProvider?: unknown; thinkingLevel?: unknown }
1063
+ | undefined
1064
+ if (row && typeof row.model === 'string' && typeof row.modelProvider === 'string') {
1065
+ rec.wireModel = `${row.modelProvider}/${row.model}`
319
1066
  }
1067
+ if (row && typeof row.thinkingLevel === 'string') rec.appliedThinking = row.thinkingLevel
1068
+ // Every row carries the model's resolved thinking menu — the only source
1069
+ // the effort picker has for it (thinking.ts).
1070
+ if (row) recordOpenClawThinkingProfile(row)
320
1071
  const phase = payload.phase as string | undefined
321
1072
  const runId = payload.runId as string | undefined
322
- if (phase === 'start' && runId) {
1073
+ if (reason === 'chat.dispatch-error') {
1074
+ handleDispatchError(rec)
1075
+ } else if (phase === 'start' && runId) {
323
1076
  setProcessing(rec, true, runId)
324
1077
  } else if ((phase === 'end' || phase === 'error') && runId) {
325
1078
  if (rec.activeRunId === runId) {
326
1079
  setProcessing(rec, false, null)
327
- // Pick up any toolResult rows the live stream did not push.
1080
+ // Safety net: pick up any toolResult rows the live stream missed.
328
1081
  reconcileAfterRun(rec).catch(err =>
329
1082
  console.error('[openclaw-session] reconcile failed', err)
330
1083
  )
331
1084
  }
332
1085
  }
333
1086
  } else if (event === 'agent') {
334
- // Backstop for run lifecycle — `sessions.changed` should already cover
335
- // this, but `agent` lifecycle frames are the authoritative signal.
336
1087
  if (payload.sessionKey !== rec.sessionKey) return
337
1088
  const stream = payload.stream as string | undefined
1089
+ // Streaming text/reasoning fallback for gateways that don't emit `chat`
1090
+ // delta frames (handleAgentStreamFrame no-ops when `chat` already owns
1091
+ // the run's TEXT; reasoning is merged in alongside it). `thinking` is a
1092
+ // second wire name for the reasoning stream — text-bearing on some
1093
+ // runtimes, a bare `{ progressTokens }` heartbeat on others, which the
1094
+ // empty-text check drops.
1095
+ if (stream === 'assistant' || stream === 'reasoning' || stream === 'thinking') {
1096
+ handleAgentStreamFrame(rec, payload)
1097
+ return
1098
+ }
1099
+ // Tool activity for runs WE started (see handleToolFrame for why the
1100
+ // same payload also arrives as `session.tool` for runs we only watch).
1101
+ if (stream === 'tool') {
1102
+ handleToolFrame(rec, payload)
1103
+ return
1104
+ }
1105
+ // Reasoning also surfaces as an `item` frame of kind `analysis` —
1106
+ // timing, no text.
1107
+ if (stream === 'item') {
1108
+ handleReasoningItemFrame(rec, payload)
1109
+ return
1110
+ }
1111
+ // Backstop for run lifecycle — `sessions.changed` should already cover
1112
+ // this, but `agent` lifecycle frames are the authoritative signal.
338
1113
  if (stream !== 'lifecycle') return
339
1114
  const runId = payload.runId as string | undefined
340
- const data = payload.data as { phase?: string } | undefined
1115
+ const data = payload.data as { phase?: string; error?: unknown } | undefined
341
1116
  const phase = data?.phase
1117
+ if (phase === 'error' && runId) reportRunError(rec, runId, data?.error)
342
1118
  if (phase === 'start' && runId) setProcessing(rec, true, runId)
343
1119
  else if ((phase === 'end' || phase === 'error') && runId) {
344
1120
  if (rec.activeRunId === runId) {
@@ -375,6 +1151,7 @@ export async function getOrCreateOpenClawSession(input: {
375
1151
  const sessionKey = resolved?.key
376
1152
  if (!sessionKey) throw new Error(`unable to resolve session ${input.sessionId}`)
377
1153
 
1154
+ evictIdleIfNeeded()
378
1155
  rec = {
379
1156
  ...input,
380
1157
  sessionKey,
@@ -383,8 +1160,16 @@ export async function getOrCreateOpenClawSession(input: {
383
1160
  view: emptyViewState(),
384
1161
  activeRunId: null,
385
1162
  seeded: false,
1163
+ // Default to whole-block delivery like the other harnesses: a cold-opened
1164
+ // (REST-ensured) live session must not broadcast previews until a send opts
1165
+ // in (send sets `streamEnabled = input.stream === true`).
1166
+ streamEnabled: false,
386
1167
  pendingFrames: [],
387
- pendingUserEchoes: []
1168
+ pendingUserEchoes: [],
1169
+ liveTools: new Map(),
1170
+ liveThinking: new Map(),
1171
+ lastDurableSeq: 0,
1172
+ liveTurnTick: 0
388
1173
  }
389
1174
  sessions.set(k, rec)
390
1175
  await ensureSubscribed(rec)
@@ -392,6 +1177,19 @@ export async function getOrCreateOpenClawSession(input: {
392
1177
  return rec
393
1178
  }
394
1179
 
1180
+ // Evict one idle record to stay under the soft cap. A processing session is
1181
+ // never evicted; if every record is busy we allow a temporary overflow rather
1182
+ // than tearing down a live run.
1183
+ function evictIdleIfNeeded(): void {
1184
+ if (sessions.size < MAX_LIVE_SESSIONS) return
1185
+ for (const rec of sessions.values()) {
1186
+ if (!isOpenClawProcessing(rec.workspaceId, rec.sessionId)) {
1187
+ teardownOpenClawSession(rec)
1188
+ return
1189
+ }
1190
+ }
1191
+ }
1192
+
395
1193
  // Cold-load helper for the REST events endpoint. If we already have a live
396
1194
  // session, return its current view materialized as StreamEvents (so it stays
397
1195
  // in sync with WS deltas the client will receive moments later). Otherwise
@@ -420,6 +1218,12 @@ export async function sendOpenClawMessage(input: {
420
1218
  // (see dev/file-uploads.md).
421
1219
  attachments?: string[]
422
1220
  optimisticId?: string
1221
+ // Picker selections, applied to the gateway session via `sessions.patch`
1222
+ // before the send (see applySessionSettings).
1223
+ model?: string
1224
+ effort?: string
1225
+ // Client's live-typing toggle; previews are only broadcast when on.
1226
+ stream?: boolean
423
1227
  // Structured moi context (lib/moi-context.ts), rendered and appended at
424
1228
  // the gateway send only — `content` stays clean so the optimistic-id echo
425
1229
  // rendezvous keeps matching on the user's text.
@@ -444,6 +1248,61 @@ export async function sendOpenClawMessage(input: {
444
1248
  return sendOpenClawMessageImpl({ ...input, content })
445
1249
  }
446
1250
 
1251
+ // Apply the picker's model/effort to the gateway session before the send. The
1252
+ // effort comes from that model's own learned menu (thinking.ts), so a rejection
1253
+ // means the menu is stale — relearn from the error rather than failing the send.
1254
+ // `reasoningLevel` rides along because it is the gateway's gate on emitting
1255
+ // reasoning at all; it is only set when the user asked to think, so a session
1256
+ // left at `off` keeps the gateway's default.
1257
+ async function applySessionSettings(
1258
+ rec: SessionRecord,
1259
+ model: string | undefined,
1260
+ effort: string | undefined
1261
+ ): Promise<void> {
1262
+ const patch: Record<string, unknown> = {}
1263
+ // Patch the model only on a real change — `sessions.patch { model }` writes
1264
+ // agent config, so it is not free.
1265
+ //
1266
+ // Both comparisons are exact: rows echo back the provider of the ref that was
1267
+ // patched, and `anthropic/claude-sonnet-5` and `claude-cli/claude-sonnet-5`
1268
+ // are separate catalog entries a user can pick between, so a switch between
1269
+ // them has to reach the gateway.
1270
+ const moved = rec.wireModel !== undefined && rec.wireModel !== rec.requestedModel
1271
+ if (model && (model !== rec.requestedModel || moved)) patch.model = model
1272
+ if (effort && effort !== rec.appliedThinking) patch.thinkingLevel = effort
1273
+ const reasoning = effort && effort !== 'off' ? 'stream' : undefined
1274
+ if (reasoning && reasoning !== rec.appliedReasoning) patch.reasoningLevel = reasoning
1275
+ if (Object.keys(patch).length === 0) return
1276
+ const gw = await getGateway()
1277
+ try {
1278
+ await gw.rpc('sessions.patch', { key: rec.sessionKey, ...patch })
1279
+ } catch (err) {
1280
+ // A level outside the model's menu is rejected by name; learn the real menu
1281
+ // from the message so the picker self-corrects, then degrade rather than
1282
+ // block the send. A rejected MODEL still throws — running on the wrong
1283
+ // model is worse than not sending.
1284
+ const relearned = recordOpenClawThinkingRejection(err)
1285
+ if (typeof patch.thinkingLevel === 'string') {
1286
+ console.warn(
1287
+ `[openclaw-session] thinkingLevel "${patch.thinkingLevel}" rejected${
1288
+ relearned ? ' (menu relearned from the gateway)' : ''
1289
+ }; sending at the session's current level`,
1290
+ err
1291
+ )
1292
+ const { thinkingLevel: _dropped, ...rest } = patch
1293
+ if (Object.keys(rest).length === 0) return
1294
+ await gw.rpc('sessions.patch', { key: rec.sessionKey, ...rest })
1295
+ if (typeof rest.model === 'string') rec.requestedModel = rest.model
1296
+ if (typeof rest.reasoningLevel === 'string') rec.appliedReasoning = rest.reasoningLevel
1297
+ return
1298
+ }
1299
+ throw err
1300
+ }
1301
+ if (typeof patch.model === 'string') rec.requestedModel = patch.model
1302
+ if (typeof patch.thinkingLevel === 'string') rec.appliedThinking = patch.thinkingLevel
1303
+ if (typeof patch.reasoningLevel === 'string') rec.appliedReasoning = patch.reasoningLevel
1304
+ }
1305
+
447
1306
  async function sendOpenClawMessageImpl(input: {
448
1307
  workspaceId: string
449
1308
  workspacePath: string
@@ -452,6 +1311,9 @@ async function sendOpenClawMessageImpl(input: {
452
1311
  isNew: boolean
453
1312
  content: string
454
1313
  optimisticId?: string
1314
+ model?: string
1315
+ effort?: string
1316
+ stream?: boolean
455
1317
  context?: MoiContext
456
1318
  }): Promise<void> {
457
1319
  // New threads: ask the gateway to create one, then rename the client's
@@ -463,7 +1325,22 @@ async function sendOpenClawMessageImpl(input: {
463
1325
  if (input.isNew) {
464
1326
  const gw = await getGateway()
465
1327
  const created = await gw.rpc<{ key?: string; sessionId?: string }>('sessions.create', {
466
- agentId: input.agentId
1328
+ agentId: input.agentId,
1329
+ // Carry the model IN the create rather than patching it just before
1330
+ // the send. `sessions.patch { model }` persists the pick into the
1331
+ // agent's effective `model.primary`, and on 2026.7.2-beta.x that config
1332
+ // write bumps the prepared-model-runtime generation and supersedes a run
1333
+ // being admitted right then: `sessions.send` answers `status: 'started'`
1334
+ // with a runId and the run is dead 2s later with `chat.dispatch-error`,
1335
+ // so the first message of a new chat fails and the resend works.
1336
+ //
1337
+ // Re-tested on the pinned 2026.7.1 and the race does NOT reproduce
1338
+ // there. Kept regardless: it is a round-trip fewer, the model belongs to
1339
+ // the session from the start, and it keeps new chats working on the beta
1340
+ // line. Only `model` may ride along — `sessions.create` rejects
1341
+ // `thinkingLevel` (`unexpected property`, verified live), and effort is
1342
+ // session-scoped anyway, so it stays a patch.
1343
+ ...(input.model ? { model: input.model } : {})
467
1344
  })
468
1345
  if (created?.sessionId && created.sessionId !== input.sessionId) {
469
1346
  realSessionId = created.sessionId
@@ -487,6 +1364,13 @@ async function sendOpenClawMessageImpl(input: {
487
1364
  agentId: input.agentId,
488
1365
  sessionId: realSessionId
489
1366
  })
1367
+ // The create already carried the model, so record it as applied — otherwise
1368
+ // `applySessionSettings` sees an empty cache on this brand-new record and
1369
+ // issues exactly the pre-send `sessions.patch { model }` we just avoided.
1370
+ // A fresh session has no wire row to seed the cache from (that path only
1371
+ // fires once a row reports `modelProvider`/`model`), so this is the only
1372
+ // thing standing between the fix and the race coming straight back.
1373
+ if (input.isNew && input.model) rec.requestedModel = input.model
490
1374
  } catch (err) {
491
1375
  const message = err instanceof Error ? err.message : 'failed to start session'
492
1376
  broadcast(input.workspaceId, {
@@ -503,11 +1387,14 @@ async function sendOpenClawMessageImpl(input: {
503
1387
  throw err
504
1388
  }
505
1389
 
506
- if (input.optimisticId) {
507
- rec.pendingUserEchoes.push({
508
- optimisticId: input.optimisticId,
509
- text: input.content
510
- })
1390
+ // Omitted means whole-block delivery, same as the other harnesses.
1391
+ rec.streamEnabled = input.stream === true
1392
+
1393
+ const echo: { optimisticId: string; text: string; runId?: string } | null = input.optimisticId
1394
+ ? { optimisticId: input.optimisticId, text: input.content }
1395
+ : null
1396
+ if (echo) {
1397
+ rec.pendingUserEchoes.push(echo)
511
1398
  if (rec.pendingUserEchoes.length > MAX_PENDING_USER_ECHOES) {
512
1399
  rec.pendingUserEchoes.shift()
513
1400
  }
@@ -517,6 +1404,7 @@ async function sendOpenClawMessageImpl(input: {
517
1404
  setProcessing(rec, true, rec.activeRunId)
518
1405
 
519
1406
  try {
1407
+ await applySessionSettings(rec, input.model, input.effort)
520
1408
  const gw = await getGateway()
521
1409
  const resp = await gw.rpc<{ runId?: string; status?: string }>('sessions.send', {
522
1410
  key: rec.sessionKey,
@@ -524,7 +1412,11 @@ async function sendOpenClawMessageImpl(input: {
524
1412
  ? appendMoiContext(input.content, renderMoiContext(input.context))
525
1413
  : input.content
526
1414
  })
527
- if (resp?.runId) setProcessing(rec, true, resp.runId)
1415
+ if (resp?.runId) {
1416
+ setProcessing(rec, true, resp.runId)
1417
+ // The durable user echo carries `<runId>:user` — arm the exact match.
1418
+ if (echo) echo.runId = resp.runId
1419
+ }
528
1420
  } catch (err) {
529
1421
  setProcessing(rec, false, null)
530
1422
  if (input.optimisticId) {
@@ -597,3 +1489,46 @@ export async function ensureOpenClawSessionLive(input: {
597
1489
  const rec = await getOrCreateOpenClawSession(input)
598
1490
  return viewAsEvents(rec)
599
1491
  }
1492
+
1493
+ // Test seam. The README sanctions tests importing harness internals; the live
1494
+ // `sessions` map is otherwise private and creating a real record needs a
1495
+ // gateway. This seeds a minimal live record so teardown/idle behavior can be
1496
+ // exercised in unit tests without a connection.
1497
+ export function createOpenClawSessionForTest(input: {
1498
+ workspaceId: string
1499
+ sessionId: string
1500
+ sessionKey: string
1501
+ }): SessionRecord {
1502
+ const rec: SessionRecord = {
1503
+ workspaceId: input.workspaceId,
1504
+ workspacePath: '/test-workspace',
1505
+ agentId: 'test-agent',
1506
+ sessionId: input.sessionId,
1507
+ sessionKey: input.sessionKey,
1508
+ messagesById: new Map(),
1509
+ results: new Map(),
1510
+ view: emptyViewState(),
1511
+ activeRunId: null,
1512
+ seeded: true,
1513
+ streamEnabled: false,
1514
+ pendingFrames: [],
1515
+ pendingUserEchoes: [],
1516
+ liveTools: new Map(),
1517
+ liveThinking: new Map(),
1518
+ lastDurableSeq: 0,
1519
+ liveTurnTick: 0
1520
+ }
1521
+ sessions.set(recKey(input.workspaceId, input.sessionId), rec)
1522
+ return rec
1523
+ }
1524
+
1525
+ // Test seam: put a record into the processing state a send would leave it in,
1526
+ // so a test can assert that a terminal frame clears it.
1527
+ export function markProcessingForTest(rec: SessionRecord, runId: string): void {
1528
+ setProcessing(rec, true, runId)
1529
+ }
1530
+
1531
+ // Test seam: is a live record held for this (workspaceId, sessionId)?
1532
+ export function hasOpenClawLiveSessionForTest(workspaceId: string, sessionId: string): boolean {
1533
+ return sessions.has(recKey(workspaceId, sessionId))
1534
+ }