moi-computer 0.8.0 → 0.8.1-next.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 (100) 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/ModelPicker.tsx +5 -4
  19. package/client/features/chat/TurnView.tsx +108 -13
  20. package/client/features/chat/api.ts +1 -18
  21. package/client/features/chat/chat-send.ts +2 -2
  22. package/client/features/chat/{ChatComposer.tsx → composer/ChatComposer.tsx} +6 -5
  23. package/client/features/chat/composer/banners/ChatErrorBanner.tsx +28 -0
  24. package/client/features/chat/composer/banners/ComposerBanner.tsx +30 -0
  25. package/client/features/chat/composer/banners/WorkspaceAgentAvailabilityBanner.tsx +91 -0
  26. package/client/features/{workspace → chat/composer/banners}/WorkspaceSkillUpdateBanner.tsx +9 -7
  27. package/client/features/chat/composer/useWorkspaceComposerState.tsx +74 -0
  28. package/client/features/{workspace → chat/composer}/useWorkspaceSkillUpdates.ts +1 -1
  29. package/client/features/chat/group-turns.ts +46 -28
  30. package/client/features/chat/interleave-notices.ts +84 -0
  31. package/client/features/chat/model-order.ts +9 -3
  32. package/client/features/chat/tool-group/TimelineRow.tsx +23 -11
  33. package/client/features/chat/tool-group/ToolCallGroup.tsx +38 -3
  34. package/client/features/chat/tool-group/format.ts +23 -7
  35. package/client/features/chat/useAppletChatMessage.ts +11 -16
  36. package/client/features/chat/useChat.ts +3 -7
  37. package/client/features/dev/ChatStatesPage.tsx +428 -0
  38. package/client/features/dev/DevIndexPage.tsx +52 -0
  39. package/client/features/dev/DevRoutes.tsx +6 -3
  40. package/client/features/dev/HarnessDebugPage.tsx +3 -3
  41. package/client/features/dev/chat-states-fixtures.ts +744 -0
  42. package/client/features/scratchpad/Scratchpad.tsx +4 -0
  43. package/client/features/scratchpad/scratch-session.ts +71 -0
  44. package/client/features/views/ViewBuilderTab.tsx +5 -4
  45. package/client/features/views/useViewBuilderActions.ts +2 -2
  46. package/client/features/workspace/WorkspaceLayoutContext.tsx +4 -2
  47. package/client/features/workspace/WorkspaceScreen.tsx +128 -146
  48. package/client/features/workspace/WorkspaceSplitLayout.tsx +111 -0
  49. package/client/features/workspace/api.ts +33 -8
  50. package/client/features/workspace/useFitsSplitLayout.ts +31 -5
  51. package/client/index.css +1 -1
  52. package/client/lib/flags.ts +4 -3
  53. package/client/runtime/useWorkspaceEvents.ts +18 -1
  54. package/client/store/ui.ts +5 -1
  55. package/dist/{chunk-0pcdwjkp.js → chunk-2vaafjp4.js} +1 -1
  56. package/dist/{chunk-9y2zbzqz.js → chunk-35fq49qa.js} +1 -1
  57. package/dist/chunk-gny990qx.css +1 -0
  58. package/dist/chunk-gt7n06ef.js +1 -0
  59. package/dist/{chunk-r5ce5cdg.js → chunk-kkj86722.js} +75 -75
  60. package/dist/chunk-n7pga5x3.js +80 -0
  61. package/dist/chunk-xeyxk7ep.js +10 -0
  62. package/dist/{chunk-h9h8f176.js → chunk-xzx7c9hq.js} +1 -1
  63. package/dist/index.html +1 -1
  64. package/lib/format.ts +17 -1
  65. package/lib/themes.ts +2 -2
  66. package/lib/types.ts +38 -8
  67. package/lib/workspace-layout.ts +2 -2
  68. package/package.json +2 -1
  69. package/server/agent.ts +199 -0
  70. package/server/api.ts +36 -17
  71. package/server/env-apply.ts +4 -0
  72. package/server/harness/README.md +28 -12
  73. package/server/harness/claude-code/auth.ts +54 -0
  74. package/server/harness/claude-code/index.ts +6 -1
  75. package/server/harness/codex/adapter.ts +9 -1
  76. package/server/harness/codex/auth.ts +50 -0
  77. package/server/harness/codex/index.ts +6 -1
  78. package/server/harness/codex/session.ts +33 -14
  79. package/server/harness/openclaw/NOTES.md +518 -187
  80. package/server/harness/openclaw/adapter.ts +125 -31
  81. package/server/harness/openclaw/compat.ts +99 -0
  82. package/server/harness/openclaw/cron-view.ts +78 -0
  83. package/server/harness/openclaw/discovery.ts +145 -52
  84. package/server/harness/openclaw/gateway.ts +224 -36
  85. package/server/harness/openclaw/index.ts +56 -21
  86. package/server/harness/openclaw/session.ts +971 -55
  87. package/server/harness/openclaw/strip.ts +87 -15
  88. package/server/harness/openclaw/thinking.ts +198 -0
  89. package/server/harness/types.ts +10 -5
  90. package/server/layout.ts +5 -2
  91. package/workspace/.claude/skills/moi-workspace/DESIGN.md +19 -9
  92. package/client/features/dev/PixelPainter.tsx +0 -94
  93. package/client/features/dev/PlaygroundPage.tsx +0 -69
  94. package/dist/chunk-0k7brsms.js +0 -9
  95. package/dist/chunk-dfs36zgc.js +0 -1
  96. package/dist/chunk-dtwxpxbg.js +0 -51
  97. package/dist/chunk-ga7t9qsk.js +0 -2
  98. package/dist/chunk-tey2nq7c.js +0 -31
  99. package/dist/chunk-z73xpsa0.js +0 -50
  100. package/dist/chunk-zzgredta.css +0 -1
@@ -6,16 +6,35 @@
6
6
  // endpoint) or sends a chat into it; thereafter it stays subscribed so the
7
7
  // view is up to date for reattach without re-fetching `sessions.get`.
8
8
  //
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.
9
+ // Live layers on top of the durable rows (all verified against gateways
10
+ // 2026.7.1 and 2026.6.33 — same wire shapes on both):
11
+ // - `chat` frames (state delta/final/error, cumulative partial message) →
12
+ // StreamPreview broadcasts; cleared by the client when the durable turn
13
+ // lands carrying the matching `meta.apiMessageId`.
14
+ // - `session.tool` frames (phase start/update/result with full output) →
15
+ // tool cards flip pending→running→success/error mid-run;
16
+ // `reconcileAfterRun` remains the safety net for anything missed.
17
+ // - Disk persistence stays out — the gateway is the source of truth; we
18
+ // re-seed from `sessions.get` on cold start.
14
19
  import { appendAttachmentNote } from '@/lib/attachment-note'
15
- import { type MoiContext, appendMoiContext, renderMoiContext } from '@/lib/moi-context'
16
- import { applyEvent, emptyViewState } from '@/lib/format'
20
+ import {
21
+ type MoiContext,
22
+ appendMoiContext,
23
+ renderMoiContext,
24
+ stripMoiContext
25
+ } from '@/lib/moi-context'
26
+ import {
27
+ type PreviewBlock,
28
+ type ToolCall,
29
+ type ToolState,
30
+ type Turn,
31
+ applyEvent,
32
+ emptyViewState
33
+ } from '@/lib/format'
17
34
  import type { SessionActivity, StreamEvent, ViewState } from '@/lib/types'
18
35
 
36
+ import { messageIdempotencyKey } from './compat'
37
+
19
38
  import {
20
39
  type OpenClawMessage,
21
40
  type OpenClawSessionDetail,
@@ -25,10 +44,21 @@ import { renameSelectedSession } from '../../selected-session'
25
44
  import {
26
45
  type ToolResultInfo,
27
46
  findToolCallOwners,
47
+ flattenToolResultContent,
28
48
  messageToTurn,
29
49
  toolResultFromMessage
30
50
  } from './adapter'
31
- import { getGateway, onGatewayReconnected } from './gateway'
51
+ import {
52
+ currentGatewayHandle,
53
+ getGateway,
54
+ onGatewayReconnected,
55
+ releaseSessionSubscriptionRef
56
+ } from './gateway'
57
+ import {
58
+ openClawModelRefsEquivalent,
59
+ recordOpenClawThinkingProfile,
60
+ recordOpenClawThinkingRejection
61
+ } from './thinking'
32
62
  import { broadcast } from '../../state'
33
63
  import { materializeToPath, resolveUploads } from '../../uploads'
34
64
  import {
@@ -57,15 +87,77 @@ type SessionRecord = {
57
87
  seeded: boolean
58
88
  pendingFrames: OpenClawMessage[]
59
89
  // 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 }[]
90
+ // optimistic id + text onto this FIFO. The durable user-row is matched by
91
+ // its idempotency key (`<runId>:user`, exact) when the send's runId is
92
+ // known, else by text. A queue rather than a single slot so two rapid sends
93
+ // don't lose the first rendezvous when the gateway echo lags behind.
94
+ pendingUserEchoes: { optimisticId: string; text: string; runId?: string }[]
95
+ // Whether the client asked for token previews on the latest send.
96
+ streamEnabled: boolean
97
+ // Which frame family owns the current run's streaming preview. The first of
98
+ // `chat` / `agent` to emit a delta claims the run so a gateway emitting both
99
+ // doesn't double-broadcast (see claimPreviewSource).
100
+ previewRunId?: string
101
+ previewSource?: 'chat' | 'agent'
102
+ // Streaming reasoning for the current run, and the last text blocks painted
103
+ // with it. The `chat`/`agent` arbitration above decides who owns the TEXT,
104
+ // but reasoning is not a duplicate of that text — on claude-cli it arrives on
105
+ // its own `agent`/thinking stream while `chat` owns the text — so it bypasses
106
+ // the claim and is merged into the same preview here instead. Both are
107
+ // per-run and cleared when the run terminalizes.
108
+ previewReasoning?: { runId: string; text: string }
109
+ previewTextBlocks?: { runId: string; blocks: PreviewBlock[] }
110
+ // True once we've seen a `codex_app_server.*` frame on this session — the
111
+ // positive signal (only the codex backend emits it, and it precedes the
112
+ // run's tool frames) that gates live tool synthesis below. Native-loop
113
+ // providers (Anthropic, ollama, …) never set it, so they keep the plain
114
+ // durable-row rendering and never grow orphan live cards.
115
+ codexBackend?: boolean
116
+ // Live tool cards rendered from `agent/tool` frames before the durable owner
117
+ // row exists — ONLY on the codex-app-server backend, which batches durable
118
+ // rows at run end so tools would otherwise appear all at once after the text.
119
+ // Keyed by toolCallId → the tool name + input captured off the start frame;
120
+ // the matching durable row merges into the live turn by re-iding to
121
+ // `livetool:<toolCallId>` (see emitTurn). Populated only when `codexBackend`,
122
+ // so on other backends it stays empty and neither synthesis nor merge fires
123
+ // (their start/result/durable toolCallIds don't always correlate, which would
124
+ // strand the live card as a duplicate — and broadcast turns can't be retracted).
125
+ liveTools: Map<string, { name: string; input: unknown }>
126
+ // Live reasoning spans from the codex app-server's `analysis`/`Reasoning`
127
+ // item frames, keyed by itemId. Timing only — that backend never sends the
128
+ // reasoning text (see handleReasoningItemFrame).
129
+ liveThinking: Map<string, { startedAt: number; endedAt?: number }>
130
+ // Last model/thinking applied via sessions.patch, in `provider/model` form —
131
+ // avoids a patch round-trip per send when nothing changed.
132
+ appliedModel?: string
133
+ appliedThinking?: string
134
+ // Last `reasoningLevel` applied. The gateway defaults this to `off`, which
135
+ // suppresses reasoning output entirely on providers that would emit it.
136
+ appliedReasoning?: string
137
+ // Model of the most recent assistant row seen (seed scan + live ingest). Lets
138
+ // ingest detect a mid-session model switch without re-scanning the whole
139
+ // messagesById map each frame; the model-change notice reads its `prev` here.
140
+ lastAssistantModel?: string
141
+ // Idle-eviction timer, armed when the session goes idle and cleared when it
142
+ // goes busy or is torn down. OpenClaw holds only WS listeners (no subprocess),
143
+ // so eviction just drops the record and releases the subscription.
144
+ idleTimer?: ReturnType<typeof setTimeout> | null
145
+ // In-flight reconcile, so the two run-end signals (sessions.changed + agent
146
+ // lifecycle) coalesce onto one transcript fetch instead of racing two.
147
+ reconcilePromise?: Promise<void>
65
148
  }
66
149
 
67
150
  const MAX_PENDING_USER_ECHOES = 16
68
151
 
152
+ // OpenClaw sessions hold only WebSocket listeners — no subprocess, unlike Claude
153
+ // Code — so eviction is cheap to redo and a looser TTL avoids churning the
154
+ // cold-reopen re-seed. 10 minutes rather than Claude Code's 5.
155
+ const IDLE_TTL_MS = 10 * 60_000
156
+ // Soft cap on concurrently-held live records. Each is just a subscription +
157
+ // in-memory view, so the cap is generous; the oldest idle record is evicted
158
+ // when a new one would exceed it (a busy record is never evicted).
159
+ const MAX_LIVE_SESSIONS = 32
160
+
69
161
  const sessions = new Map<string, SessionRecord>() // key: `${workspaceId}:${sessionId}`
70
162
  const openclawAgents = new Map<
71
163
  string,
@@ -139,6 +231,10 @@ function setProcessing(rec: SessionRecord, processing: boolean, runId: string |
139
231
  sessionKey: rec.sessionKey,
140
232
  activeRunId: runId
141
233
  })
234
+ // Idle eviction must never fire mid-run: hold the timer off while busy, and
235
+ // (re)arm it whenever the session is idle.
236
+ if (processing) clearIdleTimer(rec)
237
+ else armIdleTimer(rec)
142
238
  if (existing?.processing === processing) return
143
239
  broadcast(rec.workspaceId, {
144
240
  type: 'status',
@@ -152,12 +248,95 @@ function setProcessing(rec: SessionRecord, processing: boolean, runId: string |
152
248
  }
153
249
  }
154
250
 
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
251
+ function clearIdleTimer(rec: SessionRecord): void {
252
+ if (rec.idleTimer) {
253
+ clearTimeout(rec.idleTimer)
254
+ rec.idleTimer = null
255
+ }
256
+ }
257
+
258
+ function armIdleTimer(rec: SessionRecord): void {
259
+ clearIdleTimer(rec)
260
+ rec.idleTimer = setTimeout(() => {
261
+ rec.idleTimer = null
262
+ // A run may have started after the timer was armed — re-check and never
263
+ // evict a busy session.
264
+ if (isOpenClawProcessing(rec.workspaceId, rec.sessionId)) return
265
+ teardownOpenClawSession(rec)
266
+ }, IDLE_TTL_MS)
267
+ }
268
+
269
+ // Drop a live session: stop consuming its frames, release the gateway
270
+ // subscription, and forget it. Idempotent — a record already removed from the
271
+ // map is a no-op. REST reads (`sessionEvents`/`ensureOpenClawSessionLive`) still
272
+ // work afterward: `getOrCreateOpenClawSession` cold-reopens and re-seeds from
273
+ // `sessions.get` (or synthesizes cron turns), so eviction only costs a re-seed.
274
+ export function teardownOpenClawSession(rec: SessionRecord): void {
275
+ const k = recKey(rec.workspaceId, rec.sessionId)
276
+ if (sessions.get(k) !== rec) return
277
+ clearIdleTimer(rec)
278
+ rec.ingestUnsubscribe?.()
279
+ rec.ingestUnsubscribe = undefined
280
+ // Release the refcounted subscription. When connected, go through the handle
281
+ // (drops demand + issues the wire unsubscribe on the last holder); never force
282
+ // a connect from teardown. With no live handle (disconnected, or a test
283
+ // without a gateway) still drop the demand so a reconnect won't replay a dead
284
+ // key — the wire is already down.
285
+ const gw = currentGatewayHandle()
286
+ if (gw) {
287
+ void gw
288
+ .releaseSessionSubscription(rec.sessionKey)
289
+ .catch(err => console.error('[openclaw-session] releaseSessionSubscription failed', err))
290
+ } else {
291
+ releaseSessionSubscriptionRef(rec.sessionKey)
292
+ }
293
+ // Clear this workspace's trailing list-refresh timer only when no other live
294
+ // session remains for it — otherwise a sibling still needs it.
295
+ const workspaceHasOtherLive = [...sessions.values()].some(
296
+ r => r !== rec && r.workspaceId === rec.workspaceId
297
+ )
298
+ if (!workspaceHasOtherLive) {
299
+ const entry = lastListRefresh.get(rec.workspaceId)
300
+ if (entry?.trailing) clearTimeout(entry.trailing)
301
+ lastListRefresh.delete(rec.workspaceId)
302
+ }
303
+ const wasProcessing = isOpenClawProcessing(rec.workspaceId, rec.sessionId)
304
+ sessions.delete(k)
305
+ openclawAgents.delete(k)
306
+ // If it was mid-run, mirror setProcessing(rec, false, null)'s client-visible
307
+ // effect so no spinner is left hanging.
308
+ if (wasProcessing) {
309
+ broadcast(rec.workspaceId, { type: 'status', sessionId: rec.sessionId, activity: 'idle' })
310
+ }
311
+ }
312
+
313
+ // Server shutdown: tear down every live record so no session keeps consuming
314
+ // frames. We deliberately do NOT stop the shared gateway client — process exit
315
+ // drops it, and discovery may still need it during the same run. A cold reopen
316
+ // re-seeds from `sessions.get`.
317
+ export function killAllOpenClawSessions(): void {
318
+ for (const rec of [...sessions.values()]) teardownOpenClawSession(rec)
319
+ }
320
+
321
+ // Safety net for `toolResult` rows the live stream missed. `toolResult`
322
+ // messages DO stream on `session.message` (and `session.tool` carries the same
323
+ // output inline — NOTES §6), so this is not the only path; it covers gaps from
324
+ // a disconnect, a dropped frame, or a start/result race. On run end the gateway
325
+ // has flushed every durable row, so pulling a fresh transcript and merging any
326
+ // new toolResult rows flips lingering tool-call cards from `pending` to
159
327
  // `success`/`error` with output. Idempotent.
160
- async function reconcileAfterRun(rec: SessionRecord): Promise<void> {
328
+ function reconcileAfterRun(rec: SessionRecord): Promise<void> {
329
+ // Both sessions.changed and agent lifecycle can end a run; coalesce onto one
330
+ // in-flight transcript fetch rather than racing two.
331
+ if (rec.reconcilePromise) return rec.reconcilePromise
332
+ const p = reconcileAfterRunImpl(rec).finally(() => {
333
+ if (rec.reconcilePromise === p) rec.reconcilePromise = undefined
334
+ })
335
+ rec.reconcilePromise = p
336
+ return p
337
+ }
338
+
339
+ async function reconcileAfterRunImpl(rec: SessionRecord): Promise<void> {
161
340
  const detail = await getOpenClawSessionMessages(rec.sessionId, rec.workspacePath, rec.agentId)
162
341
  if (!detail?.messages) return
163
342
  const owners = new Set<OpenClawMessage>()
@@ -167,6 +346,10 @@ async function reconcileAfterRun(rec: SessionRecord): Promise<void> {
167
346
  const existing = rec.results.get(result.id)
168
347
  if (
169
348
  !existing ||
349
+ // A live `session.tool` start whose result frame was lost (disconnect)
350
+ // must be finalized even when the durable output is identical-empty —
351
+ // otherwise the card spins forever.
352
+ existing.running ||
170
353
  existing.output !== result.info.output ||
171
354
  existing.isError !== result.info.isError
172
355
  ) {
@@ -199,48 +382,523 @@ async function reconcileAfterRun(rec: SessionRecord): Promise<void> {
199
382
  function rebuildView(rec: SessionRecord): void {
200
383
  let view: ViewState = emptyViewState()
201
384
  let i = 0
385
+ // Mirror the cold path (adapter.toStreamEvents): reconstruct model-change
386
+ // notices from the durable rows so a seeded live view replays the same
387
+ // notices the static transcript would show. Same ids as the live emitter,
388
+ // so a notice seen live upserts instead of duplicating.
389
+ let prevModel: string | undefined
202
390
  for (const msg of rec.messagesById.values()) {
391
+ if (msg.role === 'assistant') {
392
+ const model = (msg as { model?: unknown }).model
393
+ if (typeof model === 'string') {
394
+ if (prevModel !== undefined && prevModel !== model) {
395
+ view = applyEvent(view, {
396
+ kind: 'notice',
397
+ notice: {
398
+ id: `openclaw:model-change:${msg.__openclaw?.id ?? i}`,
399
+ kind: 'model-change',
400
+ at:
401
+ typeof msg.timestamp === 'number'
402
+ ? new Date(msg.timestamp).toISOString()
403
+ : new Date().toISOString(),
404
+ model,
405
+ prev: prevModel
406
+ }
407
+ })
408
+ }
409
+ prevModel = model
410
+ }
411
+ }
203
412
  const turn = messageToTurn(msg, rec.sessionKey, i++, rec.results)
204
413
  if (turn) view = applyEvent(view, { kind: 'turn', turn })
205
414
  }
415
+ // Compaction notices have no durable twin in `sessions.get` — they exist
416
+ // only while a live record witnesses the compact frame (known gap; the
417
+ // gateway's `sessions.compaction.list` could backfill them).
206
418
  rec.view = view
419
+ // Seed the model cache so live ingest can detect the next switch off the last
420
+ // assistant model without re-scanning the transcript.
421
+ rec.lastAssistantModel = prevModel
422
+ }
423
+
424
+ // The preview slot for a run. Doubles as `meta.apiMessageId` on the run's
425
+ // committed assistant turns so the client's native preview reconciliation
426
+ // clears the live text the instant the durable turn lands.
427
+ function previewMessageId(sessionKey: string, runId: string): string {
428
+ return `openclaw:${sessionKey}:${runId}`
429
+ }
430
+
431
+ // Compare the optimistic send text against the durable user-row text
432
+ // tolerantly: drop any moi-context envelope (defensive — the optimistic side
433
+ // shouldn't carry it) and collapse all whitespace runs so newline/trim drift
434
+ // between what we sent and what the gateway stored can't defeat the match.
435
+ export function normalizeEchoText(text: string | undefined): string {
436
+ if (typeof text !== 'string') return ''
437
+ return stripMoiContext(text).replace(/\s+/g, ' ').trim()
207
438
  }
208
439
 
209
440
  function emitTurn(rec: SessionRecord, msg: OpenClawMessage, idx: number): void {
210
441
  const turn = messageToTurn(msg, rec.sessionKey, idx, rec.results)
211
442
  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.
443
+ // Optimistic-id rendezvous: prefer the exact idempotency-key match
444
+ // (`<runId>:user`; nested under `__openclaw` on 2026.7.x, message-level on
445
+ // 2026.6.x), fall back to first-matching-text for old rows and unknown
446
+ // runIds. Re-id to the optimistic id so the optimistic bubble upserts in
447
+ // place instead of duplicating.
215
448
  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
- }
449
+ const idem = messageIdempotencyKey(msg)
450
+ // 1. Exact idempotency-key match (`<runId>:user`) when the send's runId is
451
+ // already known. 2. Same key with the runId extracted from the durable
452
+ // row itself, covering the race where the echo lands before the
453
+ // `sessions.send` response set `echo.runId`. 3. Normalized-text match
454
+ // as the version-agnostic fallback: strip the moi-context envelope from
455
+ // both sides (the durable row is already stripped for display; the
456
+ // optimistic text never carries it) and collapse whitespace, so a
457
+ // trailing newline or metadata difference can't split the bubble.
458
+ const idemRunId = idem?.endsWith(':user') ? idem.slice(0, -':user'.length) : undefined
459
+ let at = idem
460
+ ? rec.pendingUserEchoes.findIndex(
461
+ e => (e.runId && `${e.runId}:user` === idem) || (idemRunId && e.runId === idemRunId)
462
+ )
463
+ : -1
464
+ if (at < 0) {
465
+ const text = normalizeEchoText(turn.parts.find(p => p.type === 'text')?.text)
466
+ if (text) at = rec.pendingUserEchoes.findIndex(e => normalizeEchoText(e.text) === text)
223
467
  }
468
+ if (at >= 0) {
469
+ turn.id = rec.pendingUserEchoes[at].optimisticId
470
+ rec.pendingUserEchoes.splice(at, 1)
471
+ }
472
+ }
473
+ // Live-tool rendezvous: a durable assistant row carrying a toolCall we
474
+ // already rendered as a live tool turn re-ids to that live turn so the card
475
+ // upserts in place (the codex-app-server backend delivers the durable owner
476
+ // only in the run-end batch, after the live card is already on screen).
477
+ if (turn.role === 'assistant' && rec.liveTools.size > 0) {
478
+ const toolPart = turn.parts.find(p => p.type === 'tool-call')
479
+ const toolCallId = toolPart?.type === 'tool-call' ? toolPart.call.toolCallId : undefined
480
+ // Keep the mapping (don't delete): the run-end reconcile re-emits the same
481
+ // durable row, and it must re-id to the SAME live turn every time or it
482
+ // lands as a second card.
483
+ if (toolCallId && rec.liveTools.has(toolCallId)) {
484
+ turn.id = liveToolTurnId(rec.sessionKey, toolCallId)
485
+ }
486
+ }
487
+ // Stamp the run's preview slot id so the client clears the streaming
488
+ // preview when this turn upserts (chat deltas can trail the durable row).
489
+ // Only FRESH turns get the current run's slot — a re-emitted older turn
490
+ // (tool-result fold-in, reconcile) keeps whatever it was stamped with, so
491
+ // it can never clear a newer run's live preview.
492
+ if (turn.role === 'assistant') {
493
+ const prior = rec.view.turns.find(t => t.id === turn.id)
494
+ if (prior) {
495
+ const kept = prior.meta?.apiMessageId
496
+ if (kept) turn.meta = { ...turn.meta, apiMessageId: kept }
497
+ } else if (rec.activeRunId) {
498
+ turn.meta = { ...turn.meta, apiMessageId: previewMessageId(rec.sessionKey, rec.activeRunId) }
499
+ }
500
+ }
501
+ rec.view = applyEvent(rec.view, { kind: 'turn', turn })
502
+ broadcast(rec.workspaceId, { kind: 'turn', turn, sessionId: rec.sessionId })
503
+ }
504
+
505
+ // Re-emit every assistant turn that references `toolCallId` so its tool card
506
+ // reflects the latest entry in `rec.results`.
507
+ function reemitToolCallOwners(rec: SessionRecord, toolCallId: string): void {
508
+ const owners = findToolCallOwners(rec.messagesById.values(), toolCallId)
509
+ const ownerSet = new Set(owners)
510
+ let idx = 0
511
+ for (const m of rec.messagesById.values()) {
512
+ if (ownerSet.has(m)) emitTurn(rec, m, idx)
513
+ idx++
514
+ }
515
+ }
516
+
517
+ // `chat` delta frames carry the full in-progress assistant message; map its
518
+ // content blocks onto cumulative PreviewBlocks (text + thinking only — tool
519
+ // calls surface through `session.tool`, not the preview). Exported for tests.
520
+ export function chatPreviewBlocks(content: unknown): PreviewBlock[] {
521
+ if (typeof content === 'string') {
522
+ return content ? [{ index: 0, kind: 'text', text: content }] : []
523
+ }
524
+ if (!Array.isArray(content)) return []
525
+ const blocks: PreviewBlock[] = []
526
+ content.forEach((block, index) => {
527
+ if (!block || typeof block !== 'object') return
528
+ const b = block as { type?: unknown; text?: unknown; thinking?: unknown; reasoning?: unknown }
529
+ if (b.type === 'text' && typeof b.text === 'string' && b.text) {
530
+ blocks.push({ index, kind: 'text', text: b.text })
531
+ } else if (b.type === 'thinking' || b.type === 'reasoning') {
532
+ // Same field drift as the durable path (adapter.blockToPart): the text
533
+ // lives in `thinking`, `reasoning`, or `text` depending on the line.
534
+ const text =
535
+ (typeof b.thinking === 'string' && b.thinking) ||
536
+ (typeof b.reasoning === 'string' && b.reasoning) ||
537
+ (typeof b.text === 'string' && b.text) ||
538
+ ''
539
+ if (text) blocks.push({ index, kind: 'reasoning', text })
540
+ }
541
+ })
542
+ return blocks
543
+ }
544
+
545
+ // Two frame families carry the streaming assistant text, and which one a
546
+ // gateway emits has drifted: 2026.7.x sends `chat` state=delta frames, while
547
+ // other lines stream via `agent` stream=assistant frames (cumulative `text`).
548
+ // The first source to produce a delta for a run wins it, so a gateway that
549
+ // emits both doesn't double-broadcast (which would flicker as the two
550
+ // cumulative snapshots race), and a gateway that emits only `agent` frames
551
+ // still streams instead of dumping the whole reply at run end.
552
+ type PreviewSource = 'chat' | 'agent'
553
+ // Exported for tests: only reads/writes the two preview-source fields.
554
+ export function claimPreviewSource(
555
+ rec: Pick<SessionRecord, 'previewRunId' | 'previewSource'>,
556
+ runId: string,
557
+ source: PreviewSource
558
+ ): boolean {
559
+ if (rec.previewRunId !== runId) {
560
+ rec.previewRunId = runId
561
+ rec.previewSource = source
562
+ return true
563
+ }
564
+ return rec.previewSource === source
565
+ }
566
+
567
+ function broadcastPreview(rec: SessionRecord, messageId: string, blocks: PreviewBlock[]): void {
568
+ broadcast(rec.workspaceId, {
569
+ type: 'preview',
570
+ sessionId: rec.sessionId,
571
+ messageId,
572
+ parentToolUseId: null,
573
+ blocks
574
+ })
575
+ }
576
+
577
+ // Repaint the run's preview from the two independent streams: reasoning first
578
+ // (it precedes the answer), then whichever source owns the text. A preview
579
+ // replaces all blocks for its messageId, so the two can't be broadcast
580
+ // separately without erasing each other — they must be emitted together.
581
+ // Indices are renumbered sequentially because the reasoning block is prepended.
582
+ // Both halves are keyed by runId rather than pinned on `previewRunId`, so
583
+ // reasoning can never consume the text source's claim (that would lock `chat`
584
+ // out of its own run and stop the answer from streaming at all).
585
+ function emitMergedPreview(rec: SessionRecord, runId: string, messageId: string): void {
586
+ const blocks: PreviewBlock[] = []
587
+ const reasoning = rec.previewReasoning?.runId === runId ? rec.previewReasoning.text : ''
588
+ if (reasoning) blocks.push({ index: 0, kind: 'reasoning', text: reasoning })
589
+ if (rec.previewTextBlocks?.runId === runId) {
590
+ for (const block of rec.previewTextBlocks.blocks)
591
+ blocks.push({ ...block, index: blocks.length })
592
+ }
593
+ broadcastPreview(rec, messageId, blocks)
594
+ }
595
+
596
+ // Drop the per-run preview state once the run terminalizes, so the next run
597
+ // starts clean instead of inheriting the previous run's reasoning.
598
+ function clearPreviewState(rec: SessionRecord): void {
599
+ rec.previewReasoning = undefined
600
+ rec.previewTextBlocks = undefined
601
+ }
602
+
603
+ // `agent` stream=assistant / reasoning frames carry the cumulative in-progress
604
+ // text in `data.text` — the fallback streaming source for gateways that don't
605
+ // emit `chat` delta frames.
606
+ function handleAgentStreamFrame(rec: SessionRecord, payload: Record<string, unknown>): void {
607
+ if (!rec.streamEnabled) return
608
+ const stream = payload.stream
609
+ // `thinking` is a second wire name for the reasoning stream, carrying the
610
+ // same `{ text, delta }` shape as `assistant`. Matching only `reasoning`
611
+ // dropped it on the floor. Verified on the wire from the `openai-codex`
612
+ // responses transport (`…:skill-workshop-review:*` sessions stream real
613
+ // reasoning text under `stream: 'thinking'`). Note this does NOT light up
614
+ // the claude-cli backend: its `thinking` frames are bare
615
+ // `{ progressTokens }` heartbeats with no text at all, so they fall out on
616
+ // the empty-text check below — that backend simply never ships the words.
617
+ const kind: PreviewBlock['kind'] | null =
618
+ stream === 'assistant'
619
+ ? 'text'
620
+ : stream === 'reasoning' || stream === 'thinking'
621
+ ? 'reasoning'
622
+ : null
623
+ if (!kind) return
624
+ const runId = typeof payload.runId === 'string' ? payload.runId : rec.activeRunId
625
+ if (!runId) return
626
+ const data = payload.data as { text?: unknown } | undefined
627
+ const text = typeof data?.text === 'string' ? data.text : ''
628
+ if (!text) return
629
+ if (kind === 'reasoning') {
630
+ // Reasoning bypasses the text claim entirely — see `previewReasoning`.
631
+ rec.previewReasoning = { runId, text }
632
+ } else {
633
+ if (!claimPreviewSource(rec, runId, 'agent')) return
634
+ rec.previewTextBlocks = { runId, blocks: [{ index: 0, kind, text }] }
635
+ }
636
+ emitMergedPreview(rec, runId, previewMessageId(rec.sessionKey, runId))
637
+ }
638
+
639
+ function handleChatFrame(rec: SessionRecord, payload: Record<string, unknown>): void {
640
+ if (!rec.streamEnabled) return
641
+ const runId = typeof payload.runId === 'string' ? payload.runId : rec.activeRunId
642
+ if (!runId) return
643
+ const messageId = previewMessageId(rec.sessionKey, runId)
644
+ const state = payload.state
645
+ if (state === 'delta') {
646
+ const message = payload.message as { content?: unknown } | undefined
647
+ const blocks = chatPreviewBlocks(message?.content)
648
+ if (blocks.length === 0) return
649
+ if (!claimPreviewSource(rec, runId, 'chat')) return
650
+ rec.previewTextBlocks = { runId, blocks }
651
+ // Merged, not raw: on claude-cli the reasoning arrives on a separate
652
+ // stream, and a bare broadcast here would wipe it off the preview.
653
+ emitMergedPreview(rec, runId, messageId)
654
+ } else if (state === 'final' || state === 'error' || state === 'aborted') {
655
+ clearPreviewState(rec)
656
+ // Belt-and-braces clear: the durable turn's apiMessageId already clears
657
+ // the slot, but a trailing delta after the durable row would repaint it.
658
+ // 'aborted' arrives when a steer/abort interrupts the run mid-stream —
659
+ // without the clear the dead preview would linger (verified live).
660
+ broadcastPreview(rec, messageId, [])
661
+ }
662
+ }
663
+
664
+ // The id of the run-scoped live tool turn for a toolCallId. The durable owner
665
+ // row re-ids to this so the live card upserts in place instead of duplicating.
666
+ function liveToolTurnId(sessionKey: string, toolCallId: string): string {
667
+ return `openclaw:${sessionKey}:livetool:${toolCallId}`
668
+ }
669
+
670
+ // Build (and broadcast) a synthetic assistant turn holding a single tool card,
671
+ // from the live tool state in `rec.liveTools` + `rec.results`. Used when a
672
+ // tool executes before its durable owner row exists.
673
+ function emitLiveToolTurn(rec: SessionRecord, toolCallId: string): void {
674
+ const meta = rec.liveTools.get(toolCallId)
675
+ if (!meta) return
676
+ const result = rec.results.get(toolCallId)
677
+ let state: ToolState = 'pending'
678
+ if (result) state = result.running ? 'running' : result.isError ? 'error' : 'success'
679
+ const call: ToolCall = {
680
+ toolCallId,
681
+ name: meta.name,
682
+ caller: 'model',
683
+ provider: 'openclaw',
684
+ state,
685
+ input: meta.input
686
+ }
687
+ if (result && !result.running) {
688
+ if (result.isError) call.errorText = result.output
689
+ else call.output = result.output
690
+ }
691
+ const turn: Turn = {
692
+ id: liveToolTurnId(rec.sessionKey, toolCallId),
693
+ role: 'assistant',
694
+ origin: { kind: 'user-input' },
695
+ parts: [{ type: 'tool-call', call }]
696
+ }
697
+ rec.view = applyEvent(rec.view, { kind: 'turn', turn })
698
+ broadcast(rec.workspaceId, { kind: 'turn', turn, sessionId: rec.sessionId })
699
+ }
700
+
701
+ // A run can die before it ever reports a lifecycle phase. When the gateway
702
+ // terminalizes the admission itself, it announces the death ONLY as
703
+ // `sessions.changed { reason: 'chat.dispatch-error' }` — no runId and no
704
+ // `phase: 'error'`, so the runId-keyed lifecycle clause never fires and the
705
+ // composer spins forever with nothing on screen.
706
+ //
707
+ // Verified live on 2026.7.2-beta.7: `sessions.patch { model }` makes OpenClaw
708
+ // persist the pick into the agent's effective `model.primary`, and that config
709
+ // write bumps the agent's prepared-model-runtime generation while the run is
710
+ // being admitted — the run dies with "prepared model runtime catalog
711
+ // generation was superseded" after `sessions.send` already returned
712
+ // `status: 'started'` and a runId. The frame carries no error text on this
713
+ // path, so the message says what the user can act on instead of inventing a
714
+ // cause. Resending works: the model is already applied, so no second write.
715
+ export function handleDispatchError(rec: SessionRecord): void {
716
+ setProcessing(rec, false, null)
717
+ broadcast(rec.workspaceId, {
718
+ kind: 'error',
719
+ sessionId: rec.sessionId,
720
+ content: 'OpenClaw could not start the run. Send the message again.'
721
+ })
722
+ }
723
+
724
+ // The id of the run-scoped live thinking turn for a reasoning item.
725
+ function liveThinkingTurnId(sessionKey: string, itemId: string): string {
726
+ return `openclaw:${sessionKey}:livethink:${itemId}`
727
+ }
728
+
729
+ // The codex app-server reports reasoning as an `agent`/item frame with
730
+ // `kind:'analysis', title:'Reasoning'` and phases start→end — presence and
731
+ // timing, never text (verified on the wire: the item frames carry no content,
732
+ // and the durable row that follows has only a `text` block; the plugin's one
733
+ // text-bearing reasoning path is channel-progress formatting with no item id).
734
+ // So we render what the backend does give: a "Thinking" row that becomes
735
+ // "Thought for 1.2s". Without this a codex run shows a silent gap between the
736
+ // send and the first token, even though the model is visibly reasoning.
737
+ //
738
+ // Deliberately NOT durable: nothing in the transcript backs it, so a cold
739
+ // reload (re-seed from `sessions.get`) drops the row. Same tradeoff as the live
740
+ // tool cards — `applyEvent` upserts and can never retract.
741
+ export function handleReasoningItemFrame(
742
+ rec: SessionRecord,
743
+ payload: Record<string, unknown>
744
+ ): void {
745
+ const data = payload.data as
746
+ | { itemId?: unknown; phase?: unknown; kind?: unknown; title?: unknown }
747
+ | undefined
748
+ if (!data || typeof data.itemId !== 'string') return
749
+ // Only the analysis/Reasoning item; other item kinds are tool lifecycle.
750
+ const isReasoning =
751
+ data.kind === 'analysis' || String(data.title ?? '').toLowerCase() === 'reasoning'
752
+ if (!isReasoning) return
753
+ const itemId = data.itemId
754
+ const at = typeof payload.ts === 'number' ? payload.ts : Date.now()
755
+
756
+ if (data.phase === 'start') {
757
+ rec.liveThinking.set(itemId, { startedAt: at })
758
+ } else if (data.phase === 'end') {
759
+ const started = rec.liveThinking.get(itemId)
760
+ if (!started) return
761
+ rec.liveThinking.set(itemId, { ...started, endedAt: at })
762
+ } else {
763
+ return
764
+ }
765
+ emitLiveThinkingTurn(rec, itemId)
766
+ }
767
+
768
+ function emitLiveThinkingTurn(rec: SessionRecord, itemId: string): void {
769
+ const span = rec.liveThinking.get(itemId)
770
+ if (!span) return
771
+ const duration = span.endedAt !== undefined ? span.endedAt - span.startedAt : undefined
772
+ const turn: Turn = {
773
+ id: liveThinkingTurnId(rec.sessionKey, itemId),
774
+ role: 'assistant',
775
+ origin: { kind: 'user-input' },
776
+ parts: [
777
+ {
778
+ type: 'reasoning',
779
+ text: '',
780
+ redacted: true,
781
+ ...(duration !== undefined && duration >= 0 ? { durationMs: duration } : {})
782
+ }
783
+ ]
224
784
  }
225
785
  rec.view = applyEvent(rec.view, { kind: 'turn', turn })
226
786
  broadcast(rec.workspaceId, { kind: 'turn', turn, sessionId: rec.sessionId })
227
787
  }
228
788
 
229
- function ingest(rec: SessionRecord, msg: OpenClawMessage): void {
789
+ // `session.tool` and `agent`/tool frames flip tool cards live: start/update →
790
+ // running, result → success/error with output. When the durable owner row
791
+ // already exists we re-emit it; otherwise (codex-app-server batches durable
792
+ // rows at run end) we render a live tool turn so tools appear during the run,
793
+ // before the streaming text — not all at once after it. `reconcileAfterRun`
794
+ // stays as the safety net. Exported for tests.
795
+ export function handleToolFrame(
796
+ rec: SessionRecord,
797
+ payload: Record<string, unknown>,
798
+ opts?: { fromAgentStream?: boolean }
799
+ ): void {
800
+ const data = payload.data as
801
+ | {
802
+ phase?: unknown
803
+ name?: unknown
804
+ toolCallId?: unknown
805
+ isError?: unknown
806
+ result?: unknown
807
+ args?: unknown
808
+ }
809
+ | undefined
810
+ if (!data || typeof data.toolCallId !== 'string') return
811
+ const id = data.toolCallId
812
+ const name = typeof data.name === 'string' ? data.name : undefined
813
+ const toolName = name ? { toolName: name } : {}
814
+ if (data.phase === 'start' || data.phase === 'update') {
815
+ // Synthetic live cards are for backends that don't commit durable tool
816
+ // rows during the run — exactly the ones that report tools on the `agent`
817
+ // /tool stream (codex, and claude-cli). Backends that use `session.tool`
818
+ // (Anthropic native loop, ollama) already have durable rows arriving live,
819
+ // and synthesizing there stranded a duplicate card that can never be
820
+ // retracted — hence the stream, not the model, is the signal.
821
+ //
822
+ // claude-cli is the harder case: its tool calls are never persisted AT ALL
823
+ // (verified live — the run's durable transcript is user + assistant[text],
824
+ // with no toolCall/toolResult row ever committing), so without this the
825
+ // chat just sits frozen for the whole tool call. These cards are therefore
826
+ // live-only by nature and drop on a cold re-seed, same as the codex ones.
827
+ if ((rec.codexBackend || opts?.fromAgentStream) && name && !rec.liveTools.has(id)) {
828
+ rec.liveTools.set(id, { name, input: data.args })
829
+ }
830
+ const existing = rec.results.get(id)
831
+ if (existing && !existing.running) return // final result already landed
832
+ rec.results.set(id, { output: '', isError: false, running: true, ...toolName })
833
+ } else if (data.phase === 'result') {
834
+ // Two result shapes on the wire: `session.tool` and codex send
835
+ // `{ content: [...] }`, claude-cli sends `result` as a bare string. Reading
836
+ // `.content` off a string yields undefined, which rendered every claude-cli
837
+ // tool card with an empty body.
838
+ const raw = data.result
839
+ const content =
840
+ typeof raw === 'string' ? raw : ((raw as { content?: unknown } | undefined)?.content ?? '')
841
+ rec.results.set(id, {
842
+ output: flattenToolResultContent(content as OpenClawMessage['content']),
843
+ isError: data.isError === true,
844
+ ...toolName
845
+ })
846
+ } else {
847
+ return
848
+ }
849
+ const owners = findToolCallOwners(rec.messagesById.values(), id)
850
+ if (owners.length > 0) reemitToolCallOwners(rec, id)
851
+ else if (rec.liveTools.has(id)) emitLiveToolTurn(rec, id)
852
+ }
853
+
854
+ // Debounced workspace session-list refresh — `sessions.changed` fires for
855
+ // every session under the agent (cron spawns, subagents, patches), and
856
+ // several records can hold subscriptions for the same workspace. `send` is in
857
+ // the set because 2026.6.x never emits `chat.title` — the post-send refresh
858
+ // is what keeps titles/previews fresh there. A trailing flush covers bursts
859
+ // (create immediately followed by the title patch) that a leading-edge-only
860
+ // throttle would drop.
861
+ const lastListRefresh = new Map<string, { at: number; trailing?: ReturnType<typeof setTimeout> }>()
862
+ const LIST_REFRESH_MIN_MS = 400
863
+ const LIST_REFRESH_REASONS = new Set([
864
+ 'chat.title',
865
+ 'create',
866
+ 'delete',
867
+ 'patch',
868
+ 'label',
869
+ 'compact',
870
+ 'send',
871
+ 'steer',
872
+ 'subagent-status'
873
+ ])
874
+ function broadcastSessionsChanged(rec: SessionRecord): void {
875
+ const now = Date.now()
876
+ const entry = lastListRefresh.get(rec.workspaceId)
877
+ if (entry && now - entry.at < LIST_REFRESH_MIN_MS) {
878
+ if (!entry.trailing) {
879
+ entry.trailing = setTimeout(
880
+ () => {
881
+ lastListRefresh.set(rec.workspaceId, { at: Date.now() })
882
+ broadcast(rec.workspaceId, { type: 'sessions_changed', sessionId: rec.sessionId })
883
+ },
884
+ LIST_REFRESH_MIN_MS - (now - entry.at)
885
+ )
886
+ }
887
+ return
888
+ }
889
+ if (entry?.trailing) clearTimeout(entry.trailing)
890
+ lastListRefresh.set(rec.workspaceId, { at: now })
891
+ broadcast(rec.workspaceId, { type: 'sessions_changed', sessionId: rec.sessionId })
892
+ }
893
+
894
+ // Exported for tests (the live subscription is the only production caller).
895
+ export function ingest(rec: SessionRecord, msg: OpenClawMessage): void {
230
896
  // toolResult: update the results map and re-emit each owner turn so the
231
897
  // tool-call card gets `state: 'success'/'error'` + output folded in.
232
898
  const result = toolResultFromMessage(msg)
233
899
  if (result) {
234
900
  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
901
+ reemitToolCallOwners(rec, result.id)
244
902
  return
245
903
  }
246
904
 
@@ -249,7 +907,37 @@ function ingest(rec: SessionRecord, msg: OpenClawMessage): void {
249
907
  // `__openclaw.id`. The durable row arrives ~6s later with id + envelope.
250
908
  const id = msg.__openclaw?.id
251
909
  if (typeof id !== 'string') return
252
- const wasUpdate = rec.messagesById.has(id)
910
+ // A durable assistant row on a different model than the previous one marks
911
+ // a mid-session model switch (sessions.patch here or anywhere else) —
912
+ // surface it as a notice instead of letting it pass silently.
913
+ if (msg.role === 'assistant') {
914
+ const model = (msg as { model?: unknown }).model
915
+ if (typeof model === 'string') {
916
+ // Compare against the cached last assistant model instead of re-scanning
917
+ // the whole messagesById map each frame. Same notice id (`__openclaw.id`)
918
+ // as the cold rebuildView path, so live and cold agree on upsert.
919
+ const prev = rec.lastAssistantModel
920
+ if (prev !== undefined && prev !== model) {
921
+ const notice = {
922
+ id: `openclaw:model-change:${id}`,
923
+ kind: 'model-change' as const,
924
+ // The switching turn's own timestamp, so live and cold placement
925
+ // agree (the client sorts equal-time notices before the turn).
926
+ at:
927
+ typeof msg.timestamp === 'number'
928
+ ? new Date(msg.timestamp).toISOString()
929
+ : new Date().toISOString(),
930
+ model,
931
+ prev
932
+ }
933
+ // Fold into the view too — the REST events replay must agree with
934
+ // the WS frames the client already saw.
935
+ rec.view = applyEvent(rec.view, { kind: 'notice', notice })
936
+ broadcast(rec.workspaceId, { kind: 'notice', sessionId: rec.sessionId, notice })
937
+ }
938
+ rec.lastAssistantModel = model
939
+ }
940
+ }
253
941
  rec.messagesById.set(id, msg)
254
942
  // Compute idx as insertion order — for an update use the existing position,
255
943
  // for a new message it's the last slot.
@@ -258,7 +946,6 @@ function ingest(rec: SessionRecord, msg: OpenClawMessage): void {
258
946
  if (k === id) break
259
947
  idx++
260
948
  }
261
- void wasUpdate
262
949
  emitTurn(rec, msg, idx)
263
950
  }
264
951
 
@@ -311,30 +998,95 @@ async function ensureSubscribed(rec: SessionRecord): Promise<void> {
311
998
  return
312
999
  }
313
1000
  ingest(rec, message)
1001
+ } else if (event === 'chat') {
1002
+ if (payload.sessionKey !== rec.sessionKey) return
1003
+ handleChatFrame(rec, payload)
1004
+ } else if (event === 'session.tool') {
1005
+ if (payload.sessionKey !== rec.sessionKey) return
1006
+ handleToolFrame(rec, payload)
314
1007
  } else if (event === 'sessions.changed') {
1008
+ // List refreshes apply to ANY session of the workspace's agent — cron
1009
+ // spawns, subagents, titles, patches. (2026.6.x never emits
1010
+ // `chat.title`; the other reasons cover title refreshes there.)
1011
+ const reason = typeof payload.reason === 'string' ? payload.reason : undefined
1012
+ if (reason && LIST_REFRESH_REASONS.has(reason)) broadcastSessionsChanged(rec)
315
1013
  if (payload.sessionKey !== rec.sessionKey) return
316
- if (payload.reason === 'chat.title') {
317
- broadcast(rec.workspaceId, { type: 'sessions_changed', sessionId: rec.sessionId })
318
- return
1014
+ if (reason === 'compact') {
1015
+ const notice = {
1016
+ id: `openclaw:compact:${typeof payload.ts === 'number' ? payload.ts : Date.now()}`,
1017
+ kind: 'compact' as const,
1018
+ at: new Date().toISOString()
1019
+ }
1020
+ rec.view = applyEvent(rec.view, { kind: 'notice', notice })
1021
+ broadcast(rec.workspaceId, { kind: 'notice', sessionId: rec.sessionId, notice })
319
1022
  }
1023
+ // Frames embed the fresh session row — keep the applied-model cache
1024
+ // truthful even when the session is patched outside moi. Run-phase frames
1025
+ // nest it under `session`; `reason` frames flatten it onto the payload.
1026
+ const row = (payload.session ?? payload) as
1027
+ | { model?: unknown; modelProvider?: unknown; thinkingLevel?: unknown }
1028
+ | undefined
1029
+ if (row && typeof row.model === 'string' && typeof row.modelProvider === 'string') {
1030
+ rec.appliedModel = `${row.modelProvider}/${row.model}`
1031
+ }
1032
+ if (row && typeof row.thinkingLevel === 'string') rec.appliedThinking = row.thinkingLevel
1033
+ // Every row carries the model's resolved thinking menu — the only source
1034
+ // the effort picker has for it (thinking.ts).
1035
+ if (row) recordOpenClawThinkingProfile(row)
320
1036
  const phase = payload.phase as string | undefined
321
1037
  const runId = payload.runId as string | undefined
322
- if (phase === 'start' && runId) {
1038
+ if (reason === 'chat.dispatch-error') {
1039
+ handleDispatchError(rec)
1040
+ } else if (phase === 'start' && runId) {
323
1041
  setProcessing(rec, true, runId)
324
1042
  } else if ((phase === 'end' || phase === 'error') && runId) {
325
1043
  if (rec.activeRunId === runId) {
326
1044
  setProcessing(rec, false, null)
327
- // Pick up any toolResult rows the live stream did not push.
1045
+ // Safety net: pick up any toolResult rows the live stream missed.
328
1046
  reconcileAfterRun(rec).catch(err =>
329
1047
  console.error('[openclaw-session] reconcile failed', err)
330
1048
  )
331
1049
  }
332
1050
  }
333
1051
  } 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
1052
  if (payload.sessionKey !== rec.sessionKey) return
337
1053
  const stream = payload.stream as string | undefined
1054
+ // `codex*` frames (`codex_app_server.lifecycle|item|hook|usage`, and any
1055
+ // future `codex.*` rename) are emitted only by the codex backend and
1056
+ // precede its tool frames within a run — the positive signal that live
1057
+ // tool synthesis is warranted for this session (see handleToolFrame). No
1058
+ // native stream name starts with `codex`, so this never false-positives.
1059
+ if (typeof stream === 'string' && stream.startsWith('codex')) {
1060
+ rec.codexBackend = true
1061
+ return
1062
+ }
1063
+ // Streaming text/reasoning fallback for gateways that don't emit `chat`
1064
+ // delta frames (handleAgentStreamFrame no-ops when `chat` already owns
1065
+ // the run's TEXT; reasoning is merged in alongside it). `thinking` is a
1066
+ // second wire name for the reasoning stream — text-bearing on the
1067
+ // `openai-codex` responses transport, text-free (`{ progressTokens }`)
1068
+ // on claude-cli.
1069
+ if (stream === 'assistant' || stream === 'reasoning' || stream === 'thinking') {
1070
+ handleAgentStreamFrame(rec, payload)
1071
+ return
1072
+ }
1073
+ // The codex-app-server backend (OpenAI models) and claude-cli (Claude
1074
+ // models) both stream tool activity as `agent`/tool frames instead of
1075
+ // `session.tool`, so route them through the shared handler. Neither
1076
+ // commits durable tool rows mid-run, which is what `fromAgentStream`
1077
+ // tells the handler: synthesize a live card, because nothing else will
1078
+ // render this tool.
1079
+ if (stream === 'tool') {
1080
+ handleToolFrame(rec, payload, { fromAgentStream: true })
1081
+ return
1082
+ }
1083
+ // Same backend reports reasoning as an `item` frame — timing, no text.
1084
+ if (stream === 'item') {
1085
+ handleReasoningItemFrame(rec, payload)
1086
+ return
1087
+ }
1088
+ // Backstop for run lifecycle — `sessions.changed` should already cover
1089
+ // this, but `agent` lifecycle frames are the authoritative signal.
338
1090
  if (stream !== 'lifecycle') return
339
1091
  const runId = payload.runId as string | undefined
340
1092
  const data = payload.data as { phase?: string } | undefined
@@ -375,6 +1127,7 @@ export async function getOrCreateOpenClawSession(input: {
375
1127
  const sessionKey = resolved?.key
376
1128
  if (!sessionKey) throw new Error(`unable to resolve session ${input.sessionId}`)
377
1129
 
1130
+ evictIdleIfNeeded()
378
1131
  rec = {
379
1132
  ...input,
380
1133
  sessionKey,
@@ -383,8 +1136,14 @@ export async function getOrCreateOpenClawSession(input: {
383
1136
  view: emptyViewState(),
384
1137
  activeRunId: null,
385
1138
  seeded: false,
1139
+ // Default to whole-block delivery like the other harnesses: a cold-opened
1140
+ // (REST-ensured) live session must not broadcast previews until a send opts
1141
+ // in (send sets `streamEnabled = input.stream === true`).
1142
+ streamEnabled: false,
386
1143
  pendingFrames: [],
387
- pendingUserEchoes: []
1144
+ pendingUserEchoes: [],
1145
+ liveTools: new Map(),
1146
+ liveThinking: new Map()
388
1147
  }
389
1148
  sessions.set(k, rec)
390
1149
  await ensureSubscribed(rec)
@@ -392,6 +1151,19 @@ export async function getOrCreateOpenClawSession(input: {
392
1151
  return rec
393
1152
  }
394
1153
 
1154
+ // Evict one idle record to stay under the soft cap. A processing session is
1155
+ // never evicted; if every record is busy we allow a temporary overflow rather
1156
+ // than tearing down a live run.
1157
+ function evictIdleIfNeeded(): void {
1158
+ if (sessions.size < MAX_LIVE_SESSIONS) return
1159
+ for (const rec of sessions.values()) {
1160
+ if (!isOpenClawProcessing(rec.workspaceId, rec.sessionId)) {
1161
+ teardownOpenClawSession(rec)
1162
+ return
1163
+ }
1164
+ }
1165
+ }
1166
+
395
1167
  // Cold-load helper for the REST events endpoint. If we already have a live
396
1168
  // session, return its current view materialized as StreamEvents (so it stays
397
1169
  // in sync with WS deltas the client will receive moments later). Otherwise
@@ -420,6 +1192,12 @@ export async function sendOpenClawMessage(input: {
420
1192
  // (see dev/file-uploads.md).
421
1193
  attachments?: string[]
422
1194
  optimisticId?: string
1195
+ // Picker selections, applied to the gateway session via `sessions.patch`
1196
+ // before the send (see applySessionSettings).
1197
+ model?: string
1198
+ effort?: string
1199
+ // Client's live-typing toggle; previews are only broadcast when on.
1200
+ stream?: boolean
423
1201
  // Structured moi context (lib/moi-context.ts), rendered and appended at
424
1202
  // the gateway send only — `content` stays clean so the optimistic-id echo
425
1203
  // rendezvous keeps matching on the user's text.
@@ -444,6 +1222,68 @@ export async function sendOpenClawMessage(input: {
444
1222
  return sendOpenClawMessageImpl({ ...input, content })
445
1223
  }
446
1224
 
1225
+ // Apply the picker's model/effort onto the gateway session before the send.
1226
+ // `sessions.patch {model, thinkingLevel}` exists on both supported lines
1227
+ // (verified live on 2026.7.1 and 2026.6.33); the model comes from `models.list`
1228
+ // and the effort from that model's own menu (thinking.ts), so a rejection means
1229
+ // our learned menu is stale — we relearn it from the error and move on.
1230
+ //
1231
+ // `reasoningLevel` rides along because it is the gateway's gate on emitting
1232
+ // reasoning at all (`reasoningMode = reasoningLevel ?? 'off'`, and
1233
+ // `canShowReasoning = thinkingLevel !== 'off'`). Without it a provider that
1234
+ // *can* stream thinking never does. It is patched only when the user asked to
1235
+ // think, so a session left at `off` keeps the gateway's default behavior.
1236
+ async function applySessionSettings(
1237
+ rec: SessionRecord,
1238
+ model: string | undefined,
1239
+ effort: string | undefined
1240
+ ): Promise<void> {
1241
+ const patch: Record<string, unknown> = {}
1242
+ // Patch the model only on a real change. `sessions.patch { model }` is not
1243
+ // free: OpenClaw persists the pick into the agent's effective
1244
+ // `model.primary`, and that config write bumps the agent's prepared-model-
1245
+ // runtime generation, which can supersede a run being admitted right then
1246
+ // (see the `chat.dispatch-error` handling in ensureSubscribed). The cache
1247
+ // holds the ref the WIRE reports, which collapses a claude-cli-routed model
1248
+ // onto its runtime provider — comparing raw strings would miss on every
1249
+ // Claude model and re-patch on every single send.
1250
+ if (model && !(rec.appliedModel && openClawModelRefsEquivalent(model, rec.appliedModel))) {
1251
+ patch.model = model
1252
+ }
1253
+ if (effort && effort !== rec.appliedThinking) patch.thinkingLevel = effort
1254
+ const reasoning = effort && effort !== 'off' ? 'stream' : undefined
1255
+ if (reasoning && reasoning !== rec.appliedReasoning) patch.reasoningLevel = reasoning
1256
+ if (Object.keys(patch).length === 0) return
1257
+ const gw = await getGateway()
1258
+ try {
1259
+ await gw.rpc('sessions.patch', { key: rec.sessionKey, ...patch })
1260
+ } catch (err) {
1261
+ // A level outside the model's menu is rejected by name; learn the real menu
1262
+ // from the message so the picker self-corrects, then degrade rather than
1263
+ // block the send. A rejected MODEL still throws — running on the wrong
1264
+ // model is worse than not sending.
1265
+ const relearned = recordOpenClawThinkingRejection(err)
1266
+ if (typeof patch.thinkingLevel === 'string') {
1267
+ console.warn(
1268
+ `[openclaw-session] thinkingLevel "${patch.thinkingLevel}" rejected${
1269
+ relearned ? ' (menu relearned from the gateway)' : ''
1270
+ }; sending at the session's current level`,
1271
+ err
1272
+ )
1273
+ const { thinkingLevel: _dropped, ...rest } = patch
1274
+ if (Object.keys(rest).length === 0) return
1275
+ await gw.rpc('sessions.patch', { key: rec.sessionKey, ...rest })
1276
+ if (typeof rest.model === 'string') rec.appliedModel = rest.model
1277
+ if (typeof rest.reasoningLevel === 'string') rec.appliedReasoning = rest.reasoningLevel
1278
+ return
1279
+ }
1280
+ throw err
1281
+ }
1282
+ if (typeof patch.model === 'string') rec.appliedModel = patch.model
1283
+ if (typeof patch.thinkingLevel === 'string') rec.appliedThinking = patch.thinkingLevel
1284
+ if (typeof patch.reasoningLevel === 'string') rec.appliedReasoning = patch.reasoningLevel
1285
+ }
1286
+
447
1287
  async function sendOpenClawMessageImpl(input: {
448
1288
  workspaceId: string
449
1289
  workspacePath: string
@@ -452,6 +1292,9 @@ async function sendOpenClawMessageImpl(input: {
452
1292
  isNew: boolean
453
1293
  content: string
454
1294
  optimisticId?: string
1295
+ model?: string
1296
+ effort?: string
1297
+ stream?: boolean
455
1298
  context?: MoiContext
456
1299
  }): Promise<void> {
457
1300
  // New threads: ask the gateway to create one, then rename the client's
@@ -463,7 +1306,24 @@ async function sendOpenClawMessageImpl(input: {
463
1306
  if (input.isNew) {
464
1307
  const gw = await getGateway()
465
1308
  const created = await gw.rpc<{ key?: string; sessionId?: string }>('sessions.create', {
466
- agentId: input.agentId
1309
+ agentId: input.agentId,
1310
+ // Carry the model IN the create — never as a patch issued just before
1311
+ // the send. `sessions.patch { model }` persists the pick into the
1312
+ // agent's effective `model.primary`, and that config write bumps the
1313
+ // prepared-model-runtime generation; a run admitted inside that window
1314
+ // is superseded and dies during admission. Verified on the wire: the
1315
+ // patch resolved and `sessions.send` went out in the SAME millisecond,
1316
+ // `sessions.send` answered `status: 'started'` with a runId, and the
1317
+ // run was dead 2.0s later with `chat.dispatch-error` — which is why the
1318
+ // first message of a new chat failed and the resend always worked.
1319
+ //
1320
+ // Only `model` is safe to pass here: `sessions.create` accepts it on
1321
+ // both supported lines, but `thinkingLevel` exists on the create schema
1322
+ // in 2026.7.x ONLY and both lines validate with
1323
+ // `additionalProperties: false`, so sending it would hard-reject every
1324
+ // new chat on 2026.6.x. Effort stays a patch — it is session-scoped,
1325
+ // writes no config, and so cannot supersede the run.
1326
+ ...(input.model ? { model: input.model } : {})
467
1327
  })
468
1328
  if (created?.sessionId && created.sessionId !== input.sessionId) {
469
1329
  realSessionId = created.sessionId
@@ -487,6 +1347,13 @@ async function sendOpenClawMessageImpl(input: {
487
1347
  agentId: input.agentId,
488
1348
  sessionId: realSessionId
489
1349
  })
1350
+ // The create already carried the model, so record it as applied — otherwise
1351
+ // `applySessionSettings` sees an empty cache on this brand-new record and
1352
+ // issues exactly the pre-send `sessions.patch { model }` we just avoided.
1353
+ // A fresh session has no wire row to seed the cache from (that path only
1354
+ // fires once a row reports `modelProvider`/`model`), so this is the only
1355
+ // thing standing between the fix and the race coming straight back.
1356
+ if (input.isNew && input.model) rec.appliedModel = input.model
490
1357
  } catch (err) {
491
1358
  const message = err instanceof Error ? err.message : 'failed to start session'
492
1359
  broadcast(input.workspaceId, {
@@ -503,11 +1370,14 @@ async function sendOpenClawMessageImpl(input: {
503
1370
  throw err
504
1371
  }
505
1372
 
506
- if (input.optimisticId) {
507
- rec.pendingUserEchoes.push({
508
- optimisticId: input.optimisticId,
509
- text: input.content
510
- })
1373
+ // Omitted means whole-block delivery, same as the other harnesses.
1374
+ rec.streamEnabled = input.stream === true
1375
+
1376
+ const echo: { optimisticId: string; text: string; runId?: string } | null = input.optimisticId
1377
+ ? { optimisticId: input.optimisticId, text: input.content }
1378
+ : null
1379
+ if (echo) {
1380
+ rec.pendingUserEchoes.push(echo)
511
1381
  if (rec.pendingUserEchoes.length > MAX_PENDING_USER_ECHOES) {
512
1382
  rec.pendingUserEchoes.shift()
513
1383
  }
@@ -517,6 +1387,7 @@ async function sendOpenClawMessageImpl(input: {
517
1387
  setProcessing(rec, true, rec.activeRunId)
518
1388
 
519
1389
  try {
1390
+ await applySessionSettings(rec, input.model, input.effort)
520
1391
  const gw = await getGateway()
521
1392
  const resp = await gw.rpc<{ runId?: string; status?: string }>('sessions.send', {
522
1393
  key: rec.sessionKey,
@@ -524,7 +1395,11 @@ async function sendOpenClawMessageImpl(input: {
524
1395
  ? appendMoiContext(input.content, renderMoiContext(input.context))
525
1396
  : input.content
526
1397
  })
527
- if (resp?.runId) setProcessing(rec, true, resp.runId)
1398
+ if (resp?.runId) {
1399
+ setProcessing(rec, true, resp.runId)
1400
+ // The durable user echo carries `<runId>:user` — arm the exact match.
1401
+ if (echo) echo.runId = resp.runId
1402
+ }
528
1403
  } catch (err) {
529
1404
  setProcessing(rec, false, null)
530
1405
  if (input.optimisticId) {
@@ -597,3 +1472,44 @@ export async function ensureOpenClawSessionLive(input: {
597
1472
  const rec = await getOrCreateOpenClawSession(input)
598
1473
  return viewAsEvents(rec)
599
1474
  }
1475
+
1476
+ // Test seam. The README sanctions tests importing harness internals; the live
1477
+ // `sessions` map is otherwise private and creating a real record needs a
1478
+ // gateway. This seeds a minimal live record so teardown/idle behavior can be
1479
+ // exercised in unit tests without a connection.
1480
+ export function createOpenClawSessionForTest(input: {
1481
+ workspaceId: string
1482
+ sessionId: string
1483
+ sessionKey: string
1484
+ }): SessionRecord {
1485
+ const rec: SessionRecord = {
1486
+ workspaceId: input.workspaceId,
1487
+ workspacePath: '/test-workspace',
1488
+ agentId: 'test-agent',
1489
+ sessionId: input.sessionId,
1490
+ sessionKey: input.sessionKey,
1491
+ messagesById: new Map(),
1492
+ results: new Map(),
1493
+ view: emptyViewState(),
1494
+ activeRunId: null,
1495
+ seeded: true,
1496
+ streamEnabled: false,
1497
+ pendingFrames: [],
1498
+ pendingUserEchoes: [],
1499
+ liveTools: new Map(),
1500
+ liveThinking: new Map()
1501
+ }
1502
+ sessions.set(recKey(input.workspaceId, input.sessionId), rec)
1503
+ return rec
1504
+ }
1505
+
1506
+ // Test seam: put a record into the processing state a send would leave it in,
1507
+ // so a test can assert that a terminal frame clears it.
1508
+ export function markProcessingForTest(rec: SessionRecord, runId: string): void {
1509
+ setProcessing(rec, true, runId)
1510
+ }
1511
+
1512
+ // Test seam: is a live record held for this (workspaceId, sessionId)?
1513
+ export function hasOpenClawLiveSessionForTest(workspaceId: string, sessionId: string): boolean {
1514
+ return sessions.has(recKey(workspaceId, sessionId))
1515
+ }