moi-computer 0.11.1-next.0 → 0.11.1-next.2

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 (211) hide show
  1. package/client/AGENTS.md +2 -2
  2. package/client/components/ui/button.tsx +1 -53
  3. package/client/components/ui/collapsible.tsx +1 -15
  4. package/client/components/ui/dialog.tsx +1 -58
  5. package/client/components/ui/dropdown-menu.tsx +1 -254
  6. package/client/components/ui/hover-card.tsx +1 -44
  7. package/client/components/ui/input.tsx +1 -21
  8. package/client/components/ui/popover.tsx +1 -88
  9. package/client/components/ui/resizable.tsx +1 -40
  10. package/client/components/ui/skeleton.tsx +1 -13
  11. package/client/components/ui/slider.tsx +1 -70
  12. package/client/components/ui/spinner.tsx +1 -18
  13. package/client/components/ui/switch.tsx +1 -23
  14. package/client/components/ui/tabs.tsx +1 -0
  15. package/client/components/ui/textarea.tsx +1 -18
  16. package/client/components/ui/tooltip.tsx +1 -51
  17. package/client/features/chat/ChatPanel.tsx +6 -6
  18. package/client/features/chat/ChatPopup.tsx +3 -4
  19. package/client/features/chat/TurnView.tsx +5 -4
  20. package/client/features/chat/api.ts +5 -14
  21. package/client/features/chat/chat-frames.ts +9 -7
  22. package/client/features/chat/chat-send.ts +13 -2
  23. package/client/features/chat/chat-store.ts +1 -3
  24. package/client/features/chat/composer/ChatComposer.tsx +5 -1
  25. package/client/features/chat/composer/ModelPicker.tsx +44 -44
  26. package/client/features/chat/composer/banners/ErrorBanner.tsx +20 -12
  27. package/client/features/chat/composer/model-order.ts +15 -0
  28. package/client/features/chat/composer/useWorkspaceComposerState.tsx +15 -7
  29. package/client/features/chat/group-turns.ts +12 -0
  30. package/client/features/chat/interleave-notices.ts +7 -11
  31. package/client/features/chat/session-view.ts +53 -0
  32. package/client/features/chat/tool-group/ToolCallGroup.tsx +1 -4
  33. package/client/features/chat/tool-group/format/codex.ts +4 -1
  34. package/client/features/chat/useChat.ts +10 -9
  35. package/client/features/dev/ChatStatesPage.tsx +3 -1
  36. package/client/features/dev/DevIndexPage.tsx +5 -0
  37. package/client/features/dev/DevRoutes.tsx +2 -0
  38. package/client/features/dev/HarnessDebugPage.tsx +1 -1
  39. package/client/features/dev/UiComponentPreviews.tsx +834 -0
  40. package/client/features/dev/UiComponentsPage.tsx +60 -0
  41. package/client/features/home/WorkspacePreview.tsx +1 -1
  42. package/client/features/home/workspace-setup/DemoDialog.tsx +3 -2
  43. package/client/features/home/workspace-setup/ImportWorkspaceDialog.tsx +5 -8
  44. package/client/features/home/workspace-setup/WorkspaceDialogContent.tsx +7 -20
  45. package/client/features/settings/SettingsLayout.tsx +1 -1
  46. package/client/features/settings/WorkspaceSettings.tsx +4 -1
  47. package/client/features/views/ViewManager.tsx +14 -9
  48. package/client/features/widgets/WidgetFrame.tsx +1 -1
  49. package/client/features/widgets/Widgets.tsx +1 -3
  50. package/client/features/workspace/WorkspaceScreen.tsx +5 -1
  51. package/client/features/workspace/WorkspaceSplitLayout.tsx +6 -1
  52. package/client/features/workspace/api.ts +2 -4
  53. package/client/index.css +22 -29
  54. package/dist/chunk-245wt82v.css +1 -0
  55. package/dist/{chunk-tny85yt2.js → chunk-4s15axjs.js} +2 -2
  56. package/dist/{chunk-c9pjqx9m.js → chunk-53a7pxcz.js} +1 -1
  57. package/dist/{chunk-104m57qw.js → chunk-87thzbtw.js} +2 -2
  58. package/dist/chunk-a6jad1a6.js +1 -0
  59. package/dist/chunk-dghwstd2.js +9 -0
  60. package/dist/chunk-eg120aca.js +1 -0
  61. package/dist/{chunk-v7wr1df4.js → chunk-j3wvxjr7.js} +1 -1
  62. package/dist/chunk-j7hh2ab4.js +70 -0
  63. package/dist/chunk-w482ew2c.js +546 -0
  64. package/dist/chunk-y8eyahwx.js +1 -0
  65. package/dist/index.html +1 -1
  66. package/lib/format.ts +55 -6
  67. package/lib/themes.ts +6 -6
  68. package/lib/types.ts +10 -9
  69. package/package.json +12 -5
  70. package/registry.json +643 -0
  71. package/server/agent.ts +1 -1
  72. package/server/api.ts +26 -30
  73. package/server/applets.ts +30 -29
  74. package/server/bundler/applet-css.ts +7 -107
  75. package/server/bundler/build-applet.ts +5 -1
  76. package/server/bundler/build-worker.ts +178 -0
  77. package/server/cli-ui-components.ts +28 -33
  78. package/server/cli.ts +6 -11
  79. package/server/data-dir.ts +1 -1
  80. package/server/harness/README.md +41 -48
  81. package/server/harness/acp/NOTES.md +426 -0
  82. package/server/harness/acp/discovery.ts +27 -30
  83. package/server/harness/acp/model-state.ts +57 -0
  84. package/server/harness/acp/session.ts +18 -6
  85. package/server/harness/claude-code/NOTES.md +47 -12
  86. package/server/harness/claude-code/cli.ts +40 -0
  87. package/server/harness/claude-code/index.ts +11 -5
  88. package/server/harness/claude-code/models.ts +72 -19
  89. package/server/harness/claude-code/session.ts +408 -299
  90. package/server/harness/codex/NOTES.md +222 -350
  91. package/server/harness/codex/adapter.ts +94 -45
  92. package/server/harness/codex/auth.ts +1 -3
  93. package/server/harness/codex/client.ts +169 -249
  94. package/server/harness/codex/discovery.ts +9 -17
  95. package/server/harness/codex/index.ts +2 -1
  96. package/server/harness/codex/pagination.ts +24 -0
  97. package/server/harness/codex/permissions.ts +31 -7
  98. package/server/harness/codex/probe.ts +10 -13
  99. package/server/harness/codex/session.ts +549 -136
  100. package/server/harness/codex/transport.ts +184 -0
  101. package/server/harness/debug.ts +1 -1
  102. package/server/harness/hermes/NOTES.md +18 -0
  103. package/server/harness/hermes/discovery.ts +20 -0
  104. package/server/harness/hermes/index.ts +9 -0
  105. package/server/harness/hermes/models.ts +28 -8
  106. package/server/harness/types.ts +4 -2
  107. package/server/moi-scaffold.ts +1 -1
  108. package/server/preview.ts +3 -1
  109. package/server/registry.ts +63 -41
  110. package/server/tldraw-package.d.ts +4 -0
  111. package/server/ui-components.ts +101 -434
  112. package/server/view-builders.ts +2 -1
  113. package/server/web.ts +12 -5
  114. package/server/workspace-env.ts +3 -2
  115. package/tsconfig.json +0 -1
  116. package/ui-components/accordion.tsx +71 -0
  117. package/ui-components/alert-dialog.tsx +165 -0
  118. package/ui-components/alert.tsx +68 -0
  119. package/ui-components/attachment.tsx +195 -0
  120. package/ui-components/avatar.tsx +90 -0
  121. package/ui-components/badge.tsx +49 -0
  122. package/ui-components/button-group.tsx +78 -0
  123. package/ui-components/button.tsx +55 -0
  124. package/ui-components/calendar.tsx +180 -0
  125. package/ui-components/card.tsx +84 -0
  126. package/ui-components/carousel.tsx +235 -0
  127. package/ui-components/chart.tsx +338 -0
  128. package/ui-components/checkbox.tsx +28 -0
  129. package/ui-components/collapsible.tsx +15 -0
  130. package/ui-components/combobox.tsx +267 -0
  131. package/ui-components/context-menu.tsx +244 -0
  132. package/ui-components/dialog.tsx +138 -0
  133. package/ui-components/docs/accordion.md +463 -0
  134. package/ui-components/docs/alert-dialog.md +481 -0
  135. package/ui-components/docs/alert.md +301 -0
  136. package/ui-components/docs/attachment.md +689 -0
  137. package/ui-components/docs/avatar.md +495 -0
  138. package/ui-components/docs/badge.md +258 -0
  139. package/ui-components/docs/button-group.md +879 -0
  140. package/ui-components/docs/button.md +26 -0
  141. package/ui-components/docs/calendar.md +862 -0
  142. package/ui-components/docs/card.md +265 -0
  143. package/ui-components/docs/carousel.md +627 -0
  144. package/ui-components/docs/chart.md +1256 -0
  145. package/ui-components/docs/checkbox.md +477 -0
  146. package/ui-components/docs/collapsible.md +446 -0
  147. package/ui-components/docs/combobox.md +1003 -0
  148. package/ui-components/docs/context-menu.md +860 -0
  149. package/ui-components/docs/data-table.md +1580 -0
  150. package/ui-components/docs/date-picker.md +614 -0
  151. package/ui-components/docs/dialog.md +414 -0
  152. package/ui-components/docs/drawer.md +51 -0
  153. package/ui-components/docs/dropdown-menu.md +1000 -0
  154. package/ui-components/docs/field.md +1192 -0
  155. package/ui-components/docs/hover-card.md +275 -0
  156. package/ui-components/docs/input-group.md +866 -0
  157. package/ui-components/docs/input.md +456 -0
  158. package/ui-components/docs/label.md +295 -0
  159. package/ui-components/docs/pagination.md +416 -0
  160. package/ui-components/docs/popover.md +348 -0
  161. package/ui-components/docs/progress.md +214 -0
  162. package/ui-components/docs/radio-group.md +389 -0
  163. package/ui-components/docs/resizable.md +265 -0
  164. package/ui-components/docs/select.md +616 -0
  165. package/ui-components/docs/separator.md +216 -0
  166. package/ui-components/docs/skeleton.md +205 -0
  167. package/ui-components/docs/slider.md +226 -0
  168. package/ui-components/docs/spinner.md +332 -0
  169. package/ui-components/docs/switch.md +236 -0
  170. package/ui-components/docs/table.md +551 -0
  171. package/ui-components/docs/tabs.md +379 -0
  172. package/ui-components/docs/textarea.md +187 -0
  173. package/ui-components/docs/toggle-group.md +370 -0
  174. package/ui-components/docs/toggle.md +91 -0
  175. package/ui-components/docs/tooltip.md +290 -0
  176. package/ui-components/drawer.tsx +213 -0
  177. package/ui-components/dropdown-menu.tsx +263 -0
  178. package/ui-components/field.tsx +224 -0
  179. package/ui-components/hover-card.tsx +46 -0
  180. package/ui-components/input-group.tsx +146 -0
  181. package/ui-components/input.tsx +20 -0
  182. package/ui-components/label.tsx +17 -0
  183. package/ui-components/pagination.tsx +124 -0
  184. package/ui-components/popover.tsx +81 -0
  185. package/ui-components/progress.tsx +63 -0
  186. package/ui-components/radio-group.tsx +38 -0
  187. package/ui-components/resizable.tsx +40 -0
  188. package/ui-components/scoped-portal.tsx +31 -0
  189. package/ui-components/select.tsx +195 -0
  190. package/ui-components/separator.tsx +18 -0
  191. package/ui-components/skeleton.tsx +15 -0
  192. package/ui-components/slider.tsx +75 -0
  193. package/ui-components/spinner.tsx +20 -0
  194. package/ui-components/switch.tsx +27 -0
  195. package/ui-components/table.tsx +86 -0
  196. package/ui-components/tabs.tsx +75 -0
  197. package/ui-components/textarea.tsx +17 -0
  198. package/ui-components/toggle-group.tsx +85 -0
  199. package/ui-components/toggle.tsx +42 -0
  200. package/ui-components/tooltip.tsx +61 -0
  201. package/ui-components/utils.ts +8 -0
  202. package/workspace/.claude/skills/moi-workspace/SKILL.md +11 -20
  203. package/workspace/.claude/skills/moi-workspace/references/DESIGN.md +4 -3
  204. package/workspace/.claude/skills/moi-workspace/references/UI-COMPONENTS.md +67 -203
  205. package/dist/chunk-59zf0m6n.js +0 -1
  206. package/dist/chunk-bj3akjs2.js +0 -1
  207. package/dist/chunk-j2w2vak4.js +0 -546
  208. package/dist/chunk-k2r9c95m.js +0 -10
  209. package/dist/chunk-kmbxhgwv.js +0 -1
  210. package/dist/chunk-p1yqa71k.js +0 -83
  211. package/dist/chunk-r5xrenjy.css +0 -1
@@ -1,20 +1,6 @@
1
- // Per-(workspaceId, sessionId) live Codex session adapter.
2
- //
3
- // One `codex app-server` process per workspace (see codex.ts) serves every
4
- // thread in it; this module owns the per-thread state: the durable in-memory
5
- // view, turn accounting for the processing spinner, and the mapping of
6
- // `item/*` notifications onto our `StreamEvent`s.
7
- //
8
- // Lifecycle notes:
9
- // - A brand-new thread is created under the client's temporary uuid, then
10
- // renamed to the Codex thread id (`session_renamed`) — same flow as the
11
- // Claude Code and OpenClaw paths.
12
- // - The app-server persists threads in ~/.codex/sessions and unloads idle
13
- // ones itself, so there is no eviction machinery here; a cold send
14
- // re-seeds via `thread/resume`.
15
- // - Codex natively echoes the user message back with our
16
- // `clientUserMessageId` as `clientId`, so the optimistic-id rendezvous is
17
- // first-class (no text matching like OpenClaw needs).
1
+ // Live state per (workspaceId, sessionId): display history, native lifecycle,
2
+ // and previews. client.ts owns the shared workspace process;
3
+ // Codex owns durable history. See NOTES.md for ordering and recovery rules.
18
4
  import { appendAttachmentNote } from '@/lib/attachment-note'
19
5
  import { buildSessionTitleSource } from '../session-title'
20
6
  import {
@@ -38,7 +24,14 @@ import {
38
24
  codexThreadToEvents,
39
25
  withCodexTurnDuration
40
26
  } from './adapter'
41
- import { type CodexClient, getCodexClient, interruptCodexTurn, readSubagentRecords } from './client'
27
+ import {
28
+ type CodexClient,
29
+ getCodexClient,
30
+ getCodexModelCatalog,
31
+ interruptCodexTurn,
32
+ readSubagentRecords
33
+ } from './client'
34
+ import { CodexRpcError } from './transport'
42
35
  import {
43
36
  CODEX_LOCAL_CONTROL_CONTEXT,
44
37
  CODEX_LOCAL_CONTROL_FALLBACK,
@@ -70,12 +63,17 @@ type ChildThread = {
70
63
  }
71
64
 
72
65
  type SessionRecord = {
66
+ client: CodexClient
67
+ lastTouched: number
73
68
  workspaceId: string
74
69
  workspacePath: string
75
70
  sessionId: string // real Codex thread id once known (rekeyed on rename)
76
71
  view: ViewState
77
72
  activeTurnId: string | null
78
73
  processing: boolean
74
+ waiting: boolean
75
+ activity: SessionActivity
76
+ model?: string
79
77
  // Live token streaming opt-in from the latest chat frame. Codex always
80
78
  // streams deltas; this gates whether we forward them as preview frames.
81
79
  stream: boolean
@@ -84,6 +82,13 @@ type SessionRecord = {
84
82
  // Usage from `thread/tokenUsage/updated`, folded into the last assistant
85
83
  // turn when the turn completes.
86
84
  lastUsage: CodexTokenUsage | null
85
+ usageTurnId: string | null
86
+ completedTurns: Set<string>
87
+ bufferedNotifications: [string, Record<string, unknown>][] | null
88
+ previewTimer: Timer | null
89
+ dirtyPreviews: Set<string>
90
+ commandOutput: Map<string, string>
91
+ commandOutputTimer: Timer | null
87
92
  // Child agent threads keyed by their thread id (see ChildThread).
88
93
  children: Map<string, ChildThread>
89
94
  refreshSessionsOnTurnComplete: boolean
@@ -93,8 +98,50 @@ type SessionRecord = {
93
98
  }
94
99
 
95
100
  const sessions = new Map<string, SessionRecord>() // key: `${workspaceId}:${sessionId}`
96
- // `${workspaceId}:${tempId}` -> real thread id (see cc-session.ts aliases).
101
+ // `${workspaceId}:${tempId}` -> native thread id after session_renamed.
97
102
  const aliases = new Map<string, string>()
103
+ const resumes = new Map<string, Promise<SessionRecord>>()
104
+ type SendLane = { tail: Promise<void>; generation: number }
105
+ const sendLanes = new Map<string, SendLane>()
106
+ const SESSION_IDLE_TTL_MS = 30 * 60_000
107
+
108
+ // The provider keeps durable history. Release transcript copies and listeners
109
+ // from chats that nobody has used recently; opening one subscribes again.
110
+ const evictionTimer = setInterval(() => {
111
+ const cutoff = Date.now() - SESSION_IDLE_TTL_MS
112
+ for (const [key, rec] of sessions) {
113
+ if (
114
+ rec.lastTouched > cutoff ||
115
+ rec.processing ||
116
+ rec.bufferedNotifications ||
117
+ rec.sessionTitleAbort
118
+ )
119
+ continue
120
+ rec.unsubscribe?.()
121
+ clearPreviews(rec)
122
+ sessions.delete(key)
123
+ const lane = sendLanes.get(key)
124
+ for (const [laneKey, candidate] of sendLanes) {
125
+ if (candidate === lane) sendLanes.delete(laneKey)
126
+ }
127
+ for (const [alias, sessionId] of aliases) {
128
+ if (recKey(rec.workspaceId, sessionId) === key && alias.startsWith(`${rec.workspaceId}:`))
129
+ aliases.delete(alias)
130
+ }
131
+ void rec.client.rpc('thread/unsubscribe', { threadId: rec.sessionId }).catch(() => {})
132
+ }
133
+ }, 60_000)
134
+ evictionTimer.unref()
135
+
136
+ function sendLane(workspaceId: string, sessionId: string): SendLane {
137
+ const key = liveKey(workspaceId, sessionId)
138
+ let lane = sendLanes.get(key)
139
+ if (!lane) {
140
+ lane = { tail: Promise.resolve(), generation: 0 }
141
+ sendLanes.set(key, lane)
142
+ }
143
+ return lane
144
+ }
98
145
 
99
146
  function recKey(workspaceId: string, sessionId: string): string {
100
147
  return `${workspaceId}:${sessionId}`
@@ -117,31 +164,78 @@ export type CodexActiveSession = {
117
164
  export function getCodexActiveSessions(): CodexActiveSession[] {
118
165
  const out: CodexActiveSession[] = []
119
166
  for (const s of sessions.values()) {
120
- // moi auto-accepts provider approval requests at the transport, so a
121
- // session never blocks on approvals; requires-action is not surfaced.
122
167
  if (s.processing) {
123
168
  out.push({
124
169
  workspaceId: s.workspaceId,
125
170
  workspacePath: s.workspacePath,
126
171
  sessionId: s.sessionId,
127
- activity: 'running'
172
+ activity: sessionActivity(s)
128
173
  })
129
174
  }
130
175
  }
131
176
  return out
132
177
  }
133
178
 
179
+ // The workspace connector panel has no selected-chat parameter. Use the most
180
+ // recently observed loaded chat to obtain runtime health instead of auth alone.
181
+ export function getLatestCodexSessionId(workspaceId: string): string | undefined {
182
+ let latest: SessionRecord | undefined
183
+ for (const rec of sessions.values()) {
184
+ if (
185
+ rec.workspaceId === workspaceId &&
186
+ !rec.bufferedNotifications &&
187
+ (!latest || rec.lastTouched >= latest.lastTouched)
188
+ )
189
+ latest = rec
190
+ }
191
+ return latest?.sessionId
192
+ }
193
+
134
194
  function setProcessing(rec: SessionRecord, processing: boolean, turnId: string | null) {
135
195
  rec.activeTurnId = turnId
136
- if (rec.processing === processing) return
137
196
  rec.processing = processing
197
+ if (!processing) rec.waiting = false
198
+ publishActivity(rec)
199
+ }
200
+
201
+ function sessionActivity(rec: SessionRecord): SessionActivity {
202
+ return rec.waiting ? 'requires-action' : rec.processing ? 'running' : 'idle'
203
+ }
204
+
205
+ function publishActivity(rec: SessionRecord) {
206
+ const activity = sessionActivity(rec)
207
+ if (rec.activity === activity) return
208
+ rec.activity = activity
138
209
  broadcast(rec.workspaceId, {
139
210
  type: 'status',
140
211
  sessionId: rec.sessionId,
141
- activity: processing ? 'running' : 'idle'
212
+ activity
142
213
  })
143
214
  }
144
215
 
216
+ function waitingOnInput(status: CodexThread['status']): boolean {
217
+ return (
218
+ status?.type === 'active' &&
219
+ Boolean(
220
+ status.activeFlags?.some(
221
+ flag => flag === 'waitingOnApproval' || flag === 'waitingOnUserInput'
222
+ )
223
+ )
224
+ )
225
+ }
226
+
227
+ function releaseSession(rec: SessionRecord, reason: string) {
228
+ flushCommandOutput(rec)
229
+ clearPreviews(rec)
230
+ settleTools(rec, reason)
231
+ setProcessing(rec, false, null)
232
+ rec.sessionTitleAbort?.abort()
233
+ rec.sessionTitleAbort = null
234
+ rec.unsubscribe?.()
235
+ const key = recKey(rec.workspaceId, rec.sessionId)
236
+ if (sessions.get(key) === rec) sessions.delete(key)
237
+ }
238
+
145
239
  function emitTurnEvent(rec: SessionRecord, ev: StreamEvent) {
146
240
  rec.view = applyEvent(rec.view, ev)
147
241
  broadcast(rec.workspaceId, { ...ev, sessionId: rec.sessionId })
@@ -150,6 +244,9 @@ function emitTurnEvent(rec: SessionRecord, ev: StreamEvent) {
150
244
  function ingestItem(rec: SessionRecord, item: CodexThreadItem) {
151
245
  const turn = codexItemToTurn(item, rec.sessionId)
152
246
  if (turn) {
247
+ turn.timestamp =
248
+ rec.view.turns.find(existing => existing.id === turn.id)?.timestamp ??
249
+ new Date().toISOString()
153
250
  // subAgentActivity announces a child agent thread: register it so its
154
251
  // item stream (arriving under `agentThreadId`) nests into this card's
155
252
  // SubagentRecord, CC-style.
@@ -241,19 +338,105 @@ function forwardPreview(
241
338
  const entry = rec.previews.get(itemId) ?? { kind, text: '' }
242
339
  entry.text += delta
243
340
  rec.previews.set(itemId, entry)
244
- broadcast(rec.workspaceId, {
245
- type: 'preview',
246
- sessionId: rec.sessionId,
247
- messageId: itemId,
248
- parentToolUseId: null,
249
- blocks: [{ index: 0, kind, text: entry.text }]
250
- })
341
+ rec.dirtyPreviews.add(itemId)
342
+ // Coalesce tokens to reduce repeated cumulative payloads and client updates.
343
+ rec.previewTimer ??= setTimeout(() => flushPreviews(rec), 40)
344
+ }
345
+
346
+ function flushPreviews(rec: SessionRecord) {
347
+ if (rec.previewTimer) clearTimeout(rec.previewTimer)
348
+ rec.previewTimer = null
349
+ for (const itemId of rec.dirtyPreviews) {
350
+ const entry = rec.previews.get(itemId)
351
+ if (!entry) continue
352
+ broadcast(rec.workspaceId, {
353
+ type: 'preview',
354
+ sessionId: rec.sessionId,
355
+ messageId: itemId,
356
+ parentToolUseId: null,
357
+ blocks: [{ index: 0, kind: entry.kind, text: entry.text }]
358
+ })
359
+ }
360
+ rec.dirtyPreviews.clear()
361
+ }
362
+
363
+ function clearPreviews(rec: SessionRecord) {
364
+ if (rec.previewTimer) clearTimeout(rec.previewTimer)
365
+ rec.previewTimer = null
366
+ rec.dirtyPreviews.clear()
367
+ rec.previews.clear()
368
+ }
369
+
370
+ const LIVE_OUTPUT_LIMIT = 64 * 1024
371
+
372
+ function flushCommandOutput(rec: SessionRecord) {
373
+ if (rec.commandOutputTimer) clearTimeout(rec.commandOutputTimer)
374
+ rec.commandOutputTimer = null
375
+ for (const [itemId, delta] of rec.commandOutput) {
376
+ const owner = rec.view.turns.find(turn =>
377
+ turn.parts.some(
378
+ part =>
379
+ part.type === 'tool-call' &&
380
+ part.call.toolCallId === itemId &&
381
+ part.call.name === 'exec' &&
382
+ part.call.state === 'running'
383
+ )
384
+ )
385
+ if (!owner) continue
386
+ const parts = owner.parts.map(part => {
387
+ if (
388
+ part.type !== 'tool-call' ||
389
+ part.call.toolCallId !== itemId ||
390
+ part.call.state !== 'running'
391
+ )
392
+ return part
393
+ const output = `${typeof part.call.output === 'string' ? part.call.output : ''}${delta}`
394
+ return {
395
+ ...part,
396
+ call: {
397
+ ...part.call,
398
+ output:
399
+ output.length > LIVE_OUTPUT_LIMIT
400
+ ? `[Earlier live output omitted]\n${output.slice(-LIVE_OUTPUT_LIMIT)}`
401
+ : output
402
+ }
403
+ }
404
+ })
405
+ emitTurnEvent(rec, { kind: 'turn', turn: { ...owner, parts } })
406
+ }
407
+ rec.commandOutput.clear()
408
+ }
409
+
410
+ function clearCommandOutput(rec: SessionRecord) {
411
+ if (rec.commandOutputTimer) clearTimeout(rec.commandOutputTimer)
412
+ rec.commandOutputTimer = null
413
+ rec.commandOutput.clear()
414
+ }
415
+
416
+ function settleTools(rec: SessionRecord, reason: string) {
417
+ for (const turn of rec.view.turns) {
418
+ let changed = false
419
+ const parts = turn.parts.map(part => {
420
+ if (
421
+ part.type !== 'tool-call' ||
422
+ !['running', 'pending', 'approval-pending'].includes(part.call.state)
423
+ )
424
+ return part
425
+ changed = true
426
+ return { ...part, call: { ...part.call, state: 'error' as const, errorText: reason } }
427
+ })
428
+ if (changed) emitTurnEvent(rec, { kind: 'turn', turn: { ...turn, parts } })
429
+ }
251
430
  }
252
431
 
253
432
  // Fold native completion metadata into the newest assistant turn so replay and
254
433
  // live rendering use the same display shape. Re-emits that turn (upsert-by-id).
255
- function applyCompletionMeta(rec: SessionRecord, durationMs: number | null | undefined) {
256
- const last = rec.lastUsage?.last
434
+ function applyCompletionMeta(
435
+ rec: SessionRecord,
436
+ turnId: string | undefined,
437
+ durationMs: number | null | undefined
438
+ ) {
439
+ const last = rec.usageTurnId === turnId ? rec.lastUsage?.last : undefined
257
440
  for (let i = rec.view.turns.length - 1; i >= 0; i--) {
258
441
  const t = rec.view.turns[i]
259
442
  if (t.role === 'user' && t.origin.kind === 'user-input') return
@@ -278,11 +461,7 @@ function applyCompletionMeta(rec: SessionRecord, durationMs: number | null | und
278
461
  }
279
462
  }
280
463
 
281
- // A send/turn failure can mean the account was signed out from outside moi —
282
- // a `codex logout` in a terminal, say — which the cached availability
283
- // snapshot won't reflect until its TTL expires. Force a fresh probe so the
284
- // composer's availability banner flips right away instead of the next send
285
- // failing the same way.
464
+ // A failed send may reflect an external logout. Refresh the cached banner now.
286
465
  function refreshAvailability(workspaceId: string, workspacePath: string) {
287
466
  void agentStore.refresh({ id: workspaceId, path: workspacePath, type: 'codex' })
288
467
  }
@@ -291,11 +470,42 @@ function handleNotification(rec: SessionRecord, method: string, params: Record<s
291
470
  if (method === '__exit') {
292
471
  // The app-server died (crash or env-change restart). Drop the record so
293
472
  // the next message re-resumes against a fresh process.
294
- setProcessing(rec, false, null)
295
- rec.sessionTitleAbort?.abort()
296
- rec.sessionTitleAbort = null
297
- rec.unsubscribe?.()
298
- sessions.delete(recKey(rec.workspaceId, rec.sessionId))
473
+ if (rec.processing)
474
+ broadcast(rec.workspaceId, {
475
+ kind: 'error',
476
+ sessionId: rec.sessionId,
477
+ content:
478
+ typeof params.message === 'string'
479
+ ? params.message
480
+ : 'Codex disconnected. Send another message to resume this chat.'
481
+ })
482
+ releaseSession(rec, 'Codex disconnected before this tool returned a result')
483
+ return
484
+ }
485
+ if (rec.bufferedNotifications) {
486
+ rec.bufferedNotifications.push([method, params])
487
+ return
488
+ }
489
+ const mcpFailure = method === 'mcpServer/startupStatus/updated' && params.status === 'failed'
490
+ if (
491
+ (method === 'warning' || method === 'configWarning' || mcpFailure) &&
492
+ (params.threadId == null || params.threadId === rec.sessionId)
493
+ ) {
494
+ const message = mcpFailure
495
+ ? `MCP ${String(params.name ?? 'server')} failed to start${typeof params.error === 'string' ? `: ${params.error}` : ''}`
496
+ : method === 'warning'
497
+ ? params.message
498
+ : params.summary
499
+ if (typeof message === 'string')
500
+ emitTurnEvent(rec, {
501
+ kind: 'notice',
502
+ notice: {
503
+ id: `codex:${rec.sessionId}:warning:${message}`,
504
+ kind: 'warning',
505
+ at: new Date().toISOString(),
506
+ message
507
+ }
508
+ })
299
509
  return
300
510
  }
301
511
  // Child agent threads stream on the same connection under their own ids —
@@ -306,16 +516,67 @@ function handleNotification(rec: SessionRecord, method: string, params: Record<s
306
516
  return
307
517
  }
308
518
  if (params.threadId !== rec.sessionId) return
519
+ rec.lastTouched = Date.now()
309
520
 
310
521
  switch (method) {
522
+ case 'model/rerouted': {
523
+ if (typeof params.toModel !== 'string') return
524
+ rec.model = params.toModel
525
+ emitTurnEvent(rec, {
526
+ kind: 'notice',
527
+ notice: {
528
+ id: `codex:${rec.sessionId}:model:${String(params.turnId)}`,
529
+ kind: 'model-change',
530
+ at: new Date().toISOString(),
531
+ model: params.toModel,
532
+ ...(typeof params.fromModel === 'string' ? { prev: params.fromModel } : {})
533
+ }
534
+ })
535
+ return
536
+ }
537
+ case 'turn/plan/updated': {
538
+ if (!Array.isArray(params.plan) || typeof params.turnId !== 'string') return
539
+ const steps = params.plan.flatMap((step: unknown) => {
540
+ if (!step || typeof step !== 'object' || !('step' in step) || typeof step.step !== 'string')
541
+ return []
542
+ const status = 'status' in step ? step.status : undefined
543
+ return [
544
+ `${status === 'completed' ? '[x]' : status === 'inProgress' ? '[→]' : '[ ]'} ${step.step}`
545
+ ]
546
+ })
547
+ ingestItem(rec, {
548
+ type: 'plan',
549
+ id: `${params.turnId}:plan`,
550
+ text: [typeof params.explanation === 'string' ? params.explanation : '', ...steps]
551
+ .filter(Boolean)
552
+ .join('\n')
553
+ })
554
+ return
555
+ }
311
556
  case 'item/started':
312
557
  case 'item/completed': {
313
558
  const item = params.item as CodexThreadItem | undefined
314
559
  if (!item) return
315
- if (method === 'item/completed') rec.previews.delete(item.id)
560
+ if (method === 'item/completed') {
561
+ rec.commandOutput.delete(item.id)
562
+ rec.previews.delete(item.id)
563
+ rec.dirtyPreviews.delete(item.id)
564
+ }
316
565
  ingestItem(rec, item)
317
566
  return
318
567
  }
568
+ case 'item/commandExecution/outputDelta': {
569
+ if (typeof params.itemId !== 'string' || typeof params.delta !== 'string') return
570
+ const output = (rec.commandOutput.get(params.itemId) ?? '') + params.delta
571
+ rec.commandOutput.set(
572
+ params.itemId,
573
+ output.length > LIVE_OUTPUT_LIMIT
574
+ ? `[Earlier live output omitted]\n${output.slice(-LIVE_OUTPUT_LIMIT)}`
575
+ : output
576
+ )
577
+ rec.commandOutputTimer ??= setTimeout(() => flushCommandOutput(rec), 40)
578
+ return
579
+ }
319
580
  case 'item/agentMessage/delta': {
320
581
  forwardPreview(rec, params.itemId as string, 'text', String(params.delta ?? ''))
321
582
  return
@@ -325,9 +586,7 @@ function handleNotification(rec: SessionRecord, method: string, params: Record<s
325
586
  return
326
587
  }
327
588
  case 'item/reasoning/summaryPartAdded': {
328
- // Each part is a new summary section; without a break the sections
329
- // concatenate into one run-on paragraph. Skip the first part (no
330
- // preview text yet) so the reasoning doesn't open with a blank line.
589
+ // Match replay's summary separator without adding a leading blank line.
331
590
  if (rec.previews.has(params.itemId as string)) {
332
591
  forwardPreview(rec, params.itemId as string, 'reasoning', '\n')
333
592
  }
@@ -335,17 +594,39 @@ function handleNotification(rec: SessionRecord, method: string, params: Record<s
335
594
  }
336
595
  case 'thread/tokenUsage/updated': {
337
596
  rec.lastUsage = (params.tokenUsage ?? null) as CodexTokenUsage | null
597
+ rec.usageTurnId = typeof params.turnId === 'string' ? params.turnId : rec.activeTurnId
338
598
  return
339
599
  }
340
600
  case 'turn/started': {
341
601
  const turn = params.turn as CodexTurn | undefined
602
+ if (turn?.id && rec.completedTurns.has(turn.id)) return
603
+ if (rec.activeTurnId !== turn?.id) {
604
+ rec.lastUsage = null
605
+ rec.usageTurnId = null
606
+ }
342
607
  setProcessing(rec, true, turn?.id ?? rec.activeTurnId)
343
608
  return
344
609
  }
345
610
  case 'turn/completed': {
346
611
  const turn = params.turn as CodexTurn | undefined
347
- rec.previews.clear()
348
- applyCompletionMeta(rec, turn?.durationMs)
612
+ if (turn?.id && rec.completedTurns.has(turn.id)) return
613
+ if (turn?.id) {
614
+ rec.completedTurns.add(turn.id)
615
+ if (rec.completedTurns.size > 64)
616
+ rec.completedTurns.delete(rec.completedTurns.values().next().value!)
617
+ }
618
+ // A delayed completion from an older turn must not stop a newer one.
619
+ if (rec.activeTurnId && turn?.id && rec.activeTurnId !== turn.id) return
620
+ flushCommandOutput(rec)
621
+ for (const item of turn?.items ?? []) ingestItem(rec, item)
622
+ settleTools(
623
+ rec,
624
+ turn?.status === 'interrupted'
625
+ ? 'Stopped'
626
+ : 'Codex ended the turn before this tool returned a result'
627
+ )
628
+ clearPreviews(rec)
629
+ applyCompletionMeta(rec, turn?.id, turn?.durationMs)
349
630
  setProcessing(rec, false, null)
350
631
  if (rec.refreshSessionsOnTurnComplete) {
351
632
  rec.refreshSessionsOnTurnComplete = false
@@ -369,6 +650,21 @@ function handleNotification(rec: SessionRecord, method: string, params: Record<s
369
650
  case 'error': {
370
651
  const err = params.error as { message?: string } | undefined
371
652
  const message = err?.message ?? (typeof params.message === 'string' ? params.message : '')
653
+ if (params.willRetry === true) {
654
+ // The provider still owns a running turn and will retry it. Do not
655
+ // expose a Retry button that would submit the user's message again.
656
+ emitTurnEvent(rec, {
657
+ kind: 'notice',
658
+ notice: {
659
+ id: `codex:${rec.sessionId}:retry:${String(params.turnId ?? rec.activeTurnId)}`,
660
+ kind: 'api-retry',
661
+ at: new Date().toISOString(),
662
+ error: message
663
+ }
664
+ })
665
+ return
666
+ }
667
+ if (params.turnId && rec.activeTurnId && params.turnId !== rec.activeTurnId) return
372
668
  if (message) {
373
669
  broadcast(rec.workspaceId, { kind: 'error', sessionId: rec.sessionId, content: message })
374
670
  refreshAvailability(rec.workspaceId, rec.workspacePath)
@@ -376,11 +672,38 @@ function handleNotification(rec: SessionRecord, method: string, params: Record<s
376
672
  // A top-level error without a following turn/completed would otherwise
377
673
  // leave the session busy forever — the error is terminal for the turn.
378
674
  setProcessing(rec, false, null)
675
+ clearPreviews(rec)
676
+ flushCommandOutput(rec)
677
+ settleTools(rec, message || 'Codex ended the turn before this tool returned a result')
678
+ return
679
+ }
680
+ case 'thread/status/changed': {
681
+ const status = params.status as CodexThread['status']
682
+ rec.waiting = waitingOnInput(status)
683
+ if (status?.type === 'active') setProcessing(rec, true, rec.activeTurnId)
684
+ else if (status?.type === 'notLoaded') {
685
+ releaseSession(rec, 'Codex unloaded this chat')
686
+ broadcast(rec.workspaceId, { type: 'sessions_changed', sessionId: rec.sessionId })
687
+ } else if (status?.type === 'idle' || status?.type === 'systemError') {
688
+ flushCommandOutput(rec)
689
+ setProcessing(rec, false, null)
690
+ clearPreviews(rec)
691
+ }
379
692
  return
380
693
  }
381
- // Codex hooks (~/.codex/hooks.json) — surface as hook notices, parity
382
- // with Claude Code's. started/completed share a notice id so the row
383
- // upserts from "started" to its outcome.
694
+ case 'thread/closed':
695
+ case 'thread/archived':
696
+ case 'thread/deleted': {
697
+ releaseSession(rec, 'Codex closed this chat')
698
+ broadcast(rec.workspaceId, { type: 'sessions_changed', sessionId: rec.sessionId })
699
+ return
700
+ }
701
+ case 'thread/unarchived':
702
+ case 'thread/name/updated': {
703
+ broadcast(rec.workspaceId, { type: 'sessions_changed', sessionId: rec.sessionId })
704
+ return
705
+ }
706
+ // Reuse the notice id so completion updates the hook's started row.
384
707
  case 'hook/started':
385
708
  case 'hook/completed': {
386
709
  const run = params.run as
@@ -414,28 +737,6 @@ function handleNotification(rec: SessionRecord, method: string, params: Record<s
414
737
  })
415
738
  return
416
739
  }
417
- // A per-thread MCP server that failed to start — surface it instead of
418
- // silently dropping (reuses the hook notice shape; a dedicated notice
419
- // kind isn't worth a lib/format extension yet).
420
- case 'mcpServer/startupStatus/updated': {
421
- if (params.status !== 'failed') return
422
- const name = typeof params.name === 'string' ? params.name : 'mcp'
423
- emitTurnEvent(rec, {
424
- kind: 'notice',
425
- notice: {
426
- id: `codex:${rec.sessionId}:mcp:${name}`,
427
- kind: 'hook',
428
- at: new Date().toISOString(),
429
- hookId: `mcp:${name}`,
430
- hookName: `MCP ${name}`,
431
- event: 'mcpServerStartup',
432
- status: 'response',
433
- outcome: 'error',
434
- ...(typeof params.error === 'string' ? { output: params.error } : {})
435
- }
436
- })
437
- return
438
- }
439
740
  }
440
741
  }
441
742
 
@@ -488,16 +789,27 @@ function createRecord(input: {
488
789
  sessionTitleSource?: string
489
790
  }): SessionRecord {
490
791
  const rec: SessionRecord = {
792
+ client: input.client,
793
+ lastTouched: Date.now(),
491
794
  workspaceId: input.workspaceId,
492
795
  workspacePath: input.workspacePath,
493
796
  sessionId: input.sessionId,
494
797
  view: emptyViewState(),
495
798
  activeTurnId: null,
496
799
  processing: false,
800
+ waiting: false,
801
+ activity: 'idle',
497
802
  stream: false,
498
803
  previews: new Map(),
499
804
  children: new Map(),
500
805
  lastUsage: null,
806
+ usageTurnId: null,
807
+ completedTurns: new Set(),
808
+ bufferedNotifications: null,
809
+ previewTimer: null,
810
+ dirtyPreviews: new Set(),
811
+ commandOutput: new Map(),
812
+ commandOutputTimer: null,
501
813
  refreshSessionsOnTurnComplete: input.refreshSessionsOnTurnComplete === true,
502
814
  sessionTitleSource: input.sessionTitleSource,
503
815
  sessionTitleAbort: null
@@ -517,35 +829,64 @@ function seedFromThread(
517
829
  ) {
518
830
  let view = emptyViewState()
519
831
  for (const ev of codexThreadToEvents(thread, subagents)) view = applyEvent(view, ev)
832
+ for (const notice of rec.view.notices) view = applyEvent(view, { kind: 'notice', notice })
520
833
  rec.view = view
521
834
  }
522
835
 
523
- async function resumeSession(input: {
524
- workspaceId: string
525
- workspacePath: string
526
- sessionId: string
527
- }): Promise<SessionRecord> {
528
- const existing = sessions.get(liveKey(input.workspaceId, input.sessionId))
836
+ type ResumeInput = { workspaceId: string; workspacePath: string; sessionId: string }
837
+
838
+ async function resumeSession(input: ResumeInput): Promise<SessionRecord> {
839
+ const key = liveKey(input.workspaceId, input.sessionId)
840
+ const pending = resumes.get(key)
841
+ if (pending) return pending
842
+ const existing = sessions.get(key)
529
843
  if (existing) return existing
530
- const client = await getCodexClient(input.workspacePath)
531
- const resumed = await client.rpc<{ thread: CodexThread }>('thread/resume', {
532
- threadId: input.sessionId,
533
- ...CODEX_THREAD_ACCESS
534
- })
535
- const rec = createRecord({ ...input, sessionId: resumed.thread.id, client })
536
- // Rebuild child-agent transcripts from their own threads and register them
537
- // as live children, so a mid-run resume keeps routing child frames into
538
- // the same records the replay attached.
539
- const subagents = await readSubagentRecords(client, resumed.thread)
540
- for (const [childId, sub] of subagents) rec.children.set(childId, sub)
541
- seedFromThread(rec, resumed.thread, subagents)
542
- return rec
844
+ const loading = (async () => {
845
+ const client = await getCodexClient(input.workspacePath)
846
+ // Subscribe before resuming. Live frames may arrive before the RPC reply,
847
+ // or while child transcripts are loading; replay them after the snapshot.
848
+ const rec = createRecord({ ...input, client })
849
+ rec.bufferedNotifications = []
850
+ try {
851
+ const resumed = await client.rpc<{ thread: CodexThread; model?: string }>('thread/resume', {
852
+ threadId: input.sessionId,
853
+ ...CODEX_THREAD_ACCESS
854
+ })
855
+ const subagents = await readSubagentRecords(client, resumed.thread)
856
+ rec.model = resumed.model
857
+ if (!client.isAlive()) throw new Error('Codex disconnected while resuming this chat')
858
+ for (const [childId, sub] of subagents) rec.children.set(childId, sub)
859
+ seedFromThread(rec, resumed.thread, subagents)
860
+ const active = resumed.thread.turns?.findLast(turn => turn.status === 'inProgress')
861
+ rec.waiting = waitingOnInput(resumed.thread.status)
862
+ setProcessing(
863
+ rec,
864
+ Boolean(active) || resumed.thread.status?.type === 'active',
865
+ active?.id ?? null
866
+ )
867
+ const buffered = rec.bufferedNotifications
868
+ rec.bufferedNotifications = null
869
+ for (const [method, params] of buffered) handleNotification(rec, method, params)
870
+ if (sessions.get(key) !== rec) throw new Error('Codex closed this chat while resuming it')
871
+ return rec
872
+ } catch (error) {
873
+ clearPreviews(rec)
874
+ clearCommandOutput(rec)
875
+ rec.unsubscribe?.()
876
+ if (sessions.get(key) === rec) sessions.delete(key)
877
+ throw error
878
+ }
879
+ })()
880
+ resumes.set(key, loading)
881
+ try {
882
+ return await loading
883
+ } finally {
884
+ if (resumes.get(key) === loading) resumes.delete(key)
885
+ }
543
886
  }
544
887
 
545
- // Turn a typed text + resolved uploads into Codex input items and the display
546
- // parts for the user's bubble. Images ride inline as data URLs (a documented
547
- // Codex input mode); other files are materialized to a temp path and
548
- // referenced in an attachment note the agent can read.
888
+ // Images send inline; other uploads become readable path notes. Display parts
889
+ // retain the original attachment metadata for the user's bubble.
549
890
  async function buildUserInput(
550
891
  text: string,
551
892
  uploads: StoredUpload[]
@@ -574,7 +915,7 @@ async function buildUserInput(
574
915
  return { input, parts }
575
916
  }
576
917
 
577
- export async function sendCodexMessage(input: {
918
+ type CodexSendInput = {
578
919
  workspaceId: string
579
920
  workspacePath: string
580
921
  sessionId: string
@@ -586,12 +927,28 @@ export async function sendCodexMessage(input: {
586
927
  effort?: string
587
928
  fastMode?: boolean
588
929
  stream?: boolean
589
- // Structured moi context (lib/moi-context.ts), rendered here. Servers
590
- // >= 0.135 take it via `additionalContext` (never enters userMessage
591
- // items); older ones get it appended to the text item, stripped from
592
- // echoes by the adapter.
930
+ // Rendered through native additionalContext or the legacy text envelope.
593
931
  context?: MoiContext
594
- }): Promise<void> {
932
+ }
933
+
934
+ export function sendCodexMessage(input: CodexSendInput): Promise<void> {
935
+ const lane = sendLane(input.workspaceId, input.sessionId)
936
+ const generation = lane.generation
937
+ const sent = lane.tail.then(async () => {
938
+ if (lane.generation !== generation) return
939
+ await sendMessage(input, lane, generation)
940
+ })
941
+ // Serialise acceptance, not entire model turns. A second send can steer as
942
+ // soon as the first start is acknowledged, and failures never poison a lane.
943
+ lane.tail = sent.catch(() => {})
944
+ return sent
945
+ }
946
+
947
+ async function sendMessage(
948
+ input: CodexSendInput,
949
+ lane: SendLane,
950
+ generation: number
951
+ ): Promise<void> {
595
952
  const uploads = input.attachments?.length
596
953
  ? resolveUploads(input.workspaceId, input.attachments)
597
954
  : []
@@ -608,9 +965,11 @@ export async function sendCodexMessage(input: {
608
965
 
609
966
  let rec: SessionRecord
610
967
  try {
611
- if (input.isNew) {
968
+ const existing = sessions.get(liveKey(input.workspaceId, input.sessionId))
969
+ if (existing && !existing.bufferedNotifications) rec = existing
970
+ else if (input.isNew && !aliases.has(recKey(input.workspaceId, input.sessionId))) {
612
971
  const client = await getCodexClient(input.workspacePath)
613
- const started = await client.rpc<{ thread: CodexThread }>('thread/start', {
972
+ const started = await client.rpc<{ thread: CodexThread; model?: string }>('thread/start', {
614
973
  cwd: input.workspacePath,
615
974
  ...CODEX_THREAD_ACCESS,
616
975
  ...(input.model ? { model: input.model } : {}),
@@ -619,6 +978,7 @@ export async function sendCodexMessage(input: {
619
978
  const realId = started.thread.id
620
979
  if (realId !== input.sessionId) {
621
980
  aliases.set(recKey(input.workspaceId, input.sessionId), realId)
981
+ sendLanes.set(recKey(input.workspaceId, realId), lane)
622
982
  await renameSessionConfig(input.workspacePath, input.sessionId, realId)
623
983
  await renameSelectedSession(input.workspacePath, input.sessionId, realId)
624
984
  // Builder tabs follow the same temporary-to-real session rename.
@@ -642,6 +1002,7 @@ export async function sendCodexMessage(input: {
642
1002
  refreshSessionsOnTurnComplete: true,
643
1003
  sessionTitleSource
644
1004
  })
1005
+ rec.model = started.model ?? input.model
645
1006
  if (
646
1007
  (input.model || input.effort || input.fastMode !== undefined) &&
647
1008
  !(await hasSessionConfig(input.workspacePath, realId))
@@ -653,7 +1014,10 @@ export async function sendCodexMessage(input: {
653
1014
  })
654
1015
  }
655
1016
  } else {
656
- rec = await resumeSession(input)
1017
+ rec = await resumeSession({
1018
+ ...input,
1019
+ sessionId: aliases.get(recKey(input.workspaceId, input.sessionId)) ?? input.sessionId
1020
+ })
657
1021
  }
658
1022
  } catch (err) {
659
1023
  // No session record exists to run setProcessing through — clear the
@@ -668,7 +1032,34 @@ export async function sendCodexMessage(input: {
668
1032
  return
669
1033
  }
670
1034
 
1035
+ if (lane.generation !== generation) return
1036
+ rec.lastTouched = Date.now()
671
1037
  rec.stream = input.stream === true
1038
+ if (!rec.stream) clearPreviews(rec)
1039
+
1040
+ if (userInput.some(item => item.type === 'image')) {
1041
+ try {
1042
+ // Steering keeps the running turn's model, regardless of picker changes.
1043
+ const models = await getCodexModelCatalog(input.workspacePath)
1044
+ const modelId = rec.activeTurnId ? rec.model : (input.model ?? rec.model)
1045
+ const model = models.find(model => model.model === modelId || model.id === modelId)
1046
+ if (model?.inputModalities && !model.inputModalities.includes('image')) {
1047
+ throw new Error(
1048
+ `${model.displayName} does not accept images. Choose a model that supports images.`
1049
+ )
1050
+ }
1051
+ } catch (error) {
1052
+ broadcast(rec.workspaceId, {
1053
+ kind: 'error',
1054
+ sessionId: rec.sessionId,
1055
+ content: error instanceof Error ? error.message : 'Could not check image support',
1056
+ terminal: !rec.activeTurnId
1057
+ })
1058
+ if (!rec.activeTurnId) setProcessing(rec, false, null)
1059
+ return
1060
+ }
1061
+ if (lane.generation !== generation) return
1062
+ }
672
1063
 
673
1064
  // Broadcast the user's bubble immediately so every connected tab shows it;
674
1065
  // the Codex echo (`userMessage` item) reuses this id via `clientId` and
@@ -687,11 +1078,9 @@ export async function sendCodexMessage(input: {
687
1078
 
688
1079
  setProcessing(rec, true, rec.activeTurnId)
689
1080
  try {
690
- const client = await getCodexClient(input.workspacePath)
691
- // Native context channel: diffed per key server-side (unchanged values
692
- // inject nothing) and never echoed back in userMessage items. The entry
693
- // key becomes the tag, so ship the unwrapped body. Older servers silently
694
- // drop the field, so append to the text item there instead.
1081
+ const client = rec.client
1082
+ // Native context keys become tags, so pass unwrapped bodies. The fallback
1083
+ // envelope is stripped from user echoes by adapter.ts.
695
1084
  const additionalContext = client.supportsAdditionalContext
696
1085
  ? {
697
1086
  ...CODEX_LOCAL_CONTROL_CONTEXT,
@@ -715,20 +1104,13 @@ export async function sendCodexMessage(input: {
715
1104
  input: userInput,
716
1105
  ...CODEX_TURN_ACCESS,
717
1106
  ...(additionalContext ? { additionalContext } : {}),
718
- // Without an explicit summary mode Codex still reasons but emits the
719
- // reasoning item with EMPTY summary/content (verified on the wire —
720
- // scripts/codex-probe.ts), so no thinking ever reaches the UI. 'detailed'
721
- // (vs 'auto') makes the summaries longer and stream in more frequent
722
- // item/reasoning/summaryTextDelta bursts while the model is still
723
- // thinking — 'auto' tends to emit one short blob near the end.
1107
+ // Request visible reasoning summaries instead of relying on CLI defaults.
724
1108
  summary: 'detailed',
725
1109
  ...(input.model ? { model: input.model } : {}),
726
1110
  ...(input.effort ? { effort: input.effort } : {}),
727
1111
  ...(serviceTier !== undefined ? { serviceTier } : {})
728
1112
  }
729
1113
  if (rec.activeTurnId) {
730
- // A turn is running — steer the new input into it. If the turn ended
731
- // in the race window, fall back to starting a fresh turn.
732
1114
  try {
733
1115
  await client.rpc('turn/steer', {
734
1116
  threadId: rec.sessionId,
@@ -737,45 +1119,76 @@ export async function sendCodexMessage(input: {
737
1119
  ...(additionalContext ? { additionalContext } : {}),
738
1120
  expectedTurnId: rec.activeTurnId
739
1121
  })
740
- } catch {
1122
+ } catch (error) {
1123
+ // Only a definitive no-active-turn rejection makes a fresh start safe.
1124
+ // Timeouts, auth failures and turn-id mismatches may have accepted the
1125
+ // input already, or refer to another active turn.
1126
+ if (
1127
+ !(error instanceof CodexRpcError) ||
1128
+ !/no active turn|not running|no turn in progress/i.test(error.message)
1129
+ )
1130
+ throw error
1131
+ if (lane.generation !== generation) return
1132
+ setProcessing(rec, true, null)
1133
+ rec.model = input.model ?? rec.model
741
1134
  const res = await client.rpc<{ turn: CodexTurn }>('turn/start', turnParams)
742
- setProcessing(rec, true, res.turn.id)
1135
+ acceptStartedTurn(rec, res.turn)
743
1136
  }
744
1137
  } else {
1138
+ rec.model = input.model ?? rec.model
745
1139
  const res = await client.rpc<{ turn: CodexTurn }>('turn/start', turnParams)
746
- setProcessing(rec, true, res.turn.id)
1140
+ acceptStartedTurn(rec, res.turn)
747
1141
  }
748
- if (input.isNew) startCodexSessionTitleJob(rec, client)
1142
+ if (lane.generation !== generation && rec.activeTurnId) {
1143
+ await interruptCodexTurn(client, rec.sessionId, rec.activeTurnId)
1144
+ }
1145
+ if (input.isNew && lane.generation === generation) startCodexSessionTitleJob(rec, client)
749
1146
  debug(`codex send ws=${rec.workspaceId} thread=${rec.sessionId} turn=${rec.activeTurnId}`)
750
1147
  } catch (err) {
751
- setProcessing(rec, false, null)
1148
+ // A failed steer does not terminate the turn it was trying to modify.
1149
+ // Likewise, a timed-out start can still produce authoritative lifecycle
1150
+ // notifications later. Keep a known active turn stoppable.
1151
+ if (!rec.activeTurnId) setProcessing(rec, false, null)
752
1152
  broadcast(rec.workspaceId, {
753
1153
  kind: 'error',
754
1154
  sessionId: rec.sessionId,
755
- content: err instanceof Error ? err.message : 'send failed'
1155
+ content: err instanceof Error ? err.message : 'send failed',
1156
+ terminal: !rec.activeTurnId
756
1157
  })
757
1158
  refreshAvailability(rec.workspaceId, rec.workspacePath)
758
1159
  }
759
1160
  }
760
1161
 
1162
+ function acceptStartedTurn(rec: SessionRecord, turn: CodexTurn) {
1163
+ if (rec.completedTurns.has(turn.id)) return
1164
+ if (turn.status === 'inProgress') setProcessing(rec, true, turn.id)
1165
+ else handleNotification(rec, 'turn/completed', { threadId: rec.sessionId, turn })
1166
+ }
1167
+
761
1168
  export async function interruptCodexRun(input: {
762
1169
  workspaceId: string
763
1170
  sessionId: string
764
1171
  }): Promise<void> {
1172
+ const lane = sendLane(input.workspaceId, input.sessionId)
1173
+ lane.generation++ // cancels queued sends, including a start still initializing
765
1174
  const rec = sessions.get(liveKey(input.workspaceId, input.sessionId))
766
- if (!rec) return
1175
+ if (!rec?.activeTurnId) {
1176
+ broadcast(input.workspaceId, { kind: 'stopped', sessionId: rec?.sessionId ?? input.sessionId })
1177
+ if (rec) setProcessing(rec, false, null)
1178
+ else
1179
+ broadcast(input.workspaceId, { type: 'status', sessionId: input.sessionId, activity: 'idle' })
1180
+ return
1181
+ }
767
1182
  try {
768
- if (rec.activeTurnId) {
769
- const client = await getCodexClient(rec.workspacePath)
770
- await interruptCodexTurn(client, rec.sessionId, rec.activeTurnId)
771
- }
772
- broadcast(rec.workspaceId, { kind: 'stopped', sessionId: rec.sessionId })
773
- setProcessing(rec, false, null)
1183
+ await interruptCodexTurn(rec.client, rec.sessionId, rec.activeTurnId)
1184
+ // turn/completed is authoritative. In particular, don't emit a second
1185
+ // stopped frame or claim idle while the command is still shutting down.
774
1186
  } catch (err) {
775
1187
  broadcast(rec.workspaceId, {
776
1188
  kind: 'error',
777
1189
  sessionId: rec.sessionId,
778
- content: err instanceof Error ? err.message : 'interrupt failed'
1190
+ content: err instanceof Error ? err.message : 'Interrupt failed',
1191
+ terminal: !rec.activeTurnId
779
1192
  })
780
1193
  throw err
781
1194
  }
@@ -788,11 +1201,11 @@ export function viewAsEvents(rec: SessionRecord): StreamEvent[] {
788
1201
  return evs
789
1202
  }
790
1203
 
791
- // Read-side hook for the REST events endpoint (mirrors the OpenClaw path):
792
- // return the live view when we hold one so REST + WS stay in agreement.
1204
+ // Serve the live display copy so REST and WebSocket events stay consistent.
793
1205
  export function getLiveCodexEvents(workspaceId: string, sessionId: string): StreamEvent[] | null {
794
1206
  const rec = sessions.get(liveKey(workspaceId, sessionId))
795
- return rec ? viewAsEvents(rec) : null
1207
+ if (rec) rec.lastTouched = Date.now()
1208
+ return rec && !rec.bufferedNotifications ? viewAsEvents(rec) : null
796
1209
  }
797
1210
 
798
1211
  // Cold-load: resume the thread (also subscribing it on our connection) and