moi-computer 0.3.0-next.2 → 0.3.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 (125) hide show
  1. package/README.md +1 -1
  2. package/client/AGENTS.md +2 -2
  3. package/client/api/http.ts +1 -1
  4. package/client/api/workspace-keys.ts +1 -0
  5. package/client/app/AppRouter.tsx +14 -5
  6. package/client/app/routes/HomeRoute.tsx +1 -1
  7. package/client/app/routes/WorkspaceRoute.tsx +8 -2
  8. package/client/app/shell/SidebarLayout.tsx +10 -5
  9. package/client/assets/openai.svg +3 -0
  10. package/client/components/shared/BottomPanel.tsx +2 -2
  11. package/client/components/ui/button.tsx +3 -2
  12. package/client/components/ui/input.tsx +1 -1
  13. package/client/features/applets/AppletMount.tsx +44 -0
  14. package/client/features/applets/WidgetShell.tsx +4 -1
  15. package/client/features/applets/applet-cache.ts +8 -0
  16. package/client/features/applets/applet-styles.ts +61 -0
  17. package/client/features/chat/ChatComposer.tsx +2 -2
  18. package/client/features/chat/ChatPanel.tsx +8 -25
  19. package/client/features/chat/ChatPopup.tsx +3 -3
  20. package/client/features/chat/{ThreadSelector.tsx → ChatSelector.tsx} +4 -4
  21. package/client/features/chat/TurnView.tsx +8 -9
  22. package/client/features/chat/api.ts +1 -1
  23. package/client/features/chat/chat-send.ts +57 -0
  24. package/client/features/chat/tool-group/ToolCallGroup.tsx +2 -1
  25. package/client/features/chat/tool-group/format.ts +117 -0
  26. package/client/features/chat/useChat.ts +10 -34
  27. package/client/features/connectors/McpMenu.tsx +4 -21
  28. package/client/features/dev/DevRoutes.tsx +18 -0
  29. package/client/features/dev/HarnessDebugPage.tsx +468 -0
  30. package/client/{components/playground → features/dev}/PlaygroundPage.tsx +1 -1
  31. package/client/features/home/CreateWorkspaceDialog.tsx +64 -158
  32. package/client/features/home/CreateWorkspaceDialogSteps.tsx +234 -0
  33. package/client/features/home/HomeLogo.tsx +344 -0
  34. package/client/features/home/HomePage.tsx +15 -21
  35. package/client/features/home/WorkspacePreview.tsx +12 -5
  36. package/client/features/home/api.ts +11 -3
  37. package/client/features/home/workspace-presentation.tsx +4 -4
  38. package/client/features/settings/GeneralSettings.tsx +3 -3
  39. package/client/features/settings/IconPicker.tsx +4 -3
  40. package/client/features/settings/icon-picker-options.ts +0 -131
  41. package/client/features/views/ViewBuilderTab.tsx +153 -0
  42. package/client/features/views/api.ts +124 -0
  43. package/client/features/views/useViewBuilderActions.ts +72 -0
  44. package/client/features/widgets/WidgetGrid.tsx +36 -20
  45. package/client/features/widgets/Widgets.tsx +140 -90
  46. package/client/features/workspace/WorkspaceLayoutContext.tsx +3 -9
  47. package/client/features/workspace/WorkspaceScreen.tsx +179 -40
  48. package/client/features/workspace/WorkspaceTabs.tsx +4 -4
  49. package/client/index.css +0 -35
  50. package/client/index.html +1 -1
  51. package/client/lib/app-icon-registry.ts +145 -0
  52. package/client/runtime/useWorkspaceEvents.ts +3 -1
  53. package/client/theme.css +1 -1
  54. package/dist/chunk-4vf1t6v1.js +10 -0
  55. package/dist/chunk-4z52b2av.css +1 -0
  56. package/dist/chunk-6c8cwpzc.js +1 -0
  57. package/dist/chunk-b4b276wx.js +15 -0
  58. package/dist/{chunk-c4j722at.js → chunk-cs8vbert.js} +2 -2
  59. package/dist/chunk-fjksw6xf.js +1 -0
  60. package/dist/chunk-kxmvv1ax.js +48 -0
  61. package/dist/{chunk-p68fnz3q.js → chunk-vkvb3hjm.js} +1 -1
  62. package/dist/chunk-y82s1jxm.js +61 -0
  63. package/dist/chunk-zpxrb1ce.js +2 -0
  64. package/dist/index.html +2 -2
  65. package/dist/openai-h13pza4b.svg +3 -0
  66. package/lib/format.ts +2 -2
  67. package/lib/types.ts +38 -2
  68. package/lib/view-builder-meta.ts +35 -0
  69. package/lib/workspace-layout.ts +14 -0
  70. package/package.json +2 -1
  71. package/server/AGENTS.md +3 -3
  72. package/server/api.ts +165 -51
  73. package/server/applets.ts +1 -1
  74. package/server/bundle-queue.ts +19 -0
  75. package/server/bundler/applet-css.ts +50 -0
  76. package/server/{build-applet.ts → bundler/build-applet.ts} +36 -26
  77. package/server/cli.ts +79 -2
  78. package/server/control.ts +106 -8
  79. package/server/env-apply.ts +2 -2
  80. package/server/harness/README.md +228 -0
  81. package/server/harness/claude-code/NOTES.md +578 -0
  82. package/{lib/claude-adapter.ts → server/harness/claude-code/adapter.ts} +67 -5
  83. package/server/harness/claude-code/index.ts +124 -0
  84. package/server/{mcp.ts → harness/claude-code/mcp.ts} +1 -1
  85. package/server/{cc-session.ts → harness/claude-code/session.ts} +42 -14
  86. package/server/harness/claude-code/sessions.ts +42 -0
  87. package/server/harness/codex/NOTES.md +326 -0
  88. package/server/harness/codex/adapter.ts +414 -0
  89. package/server/harness/codex/client.ts +343 -0
  90. package/server/harness/codex/index.ts +68 -0
  91. package/server/harness/codex/probe.ts +186 -0
  92. package/server/harness/codex/session.ts +617 -0
  93. package/server/harness/debug.ts +57 -0
  94. package/server/harness/openclaw/NOTES.md +316 -0
  95. package/server/{openclaw-adapter.ts → harness/openclaw/adapter.ts} +2 -2
  96. package/server/harness/openclaw/index.ts +93 -0
  97. package/server/{openclaw-session.ts → harness/openclaw/session.ts} +44 -9
  98. package/server/{openclaw-strip.ts → harness/openclaw/strip.ts} +3 -1
  99. package/server/harness/registry.ts +36 -0
  100. package/server/harness/types.ts +87 -0
  101. package/server/layout.ts +6 -12
  102. package/server/moi-scaffold.ts +1 -1
  103. package/server/registry.ts +14 -52
  104. package/server/state.ts +5 -38
  105. package/server/status.ts +7 -46
  106. package/server/vendor.ts +1 -1
  107. package/server/view-builders.ts +428 -0
  108. package/server/views.ts +0 -0
  109. package/server/web.ts +18 -40
  110. package/server/workspace-init.ts +6 -6
  111. package/workspace/.claude/skills/moi-workspace/DESIGN.md +1 -0
  112. package/workspace/.claude/skills/moi-workspace/SKILL.md +28 -7
  113. package/client/assets/hermes-nous.png +0 -0
  114. package/client/hooks/useScrollFade.ts +0 -38
  115. package/dist/chunk-23cgr1tz.css +0 -1
  116. package/dist/chunk-3hy3qy6d.js +0 -10
  117. package/dist/chunk-dyfaffyz.js +0 -119
  118. package/dist/chunk-kpe40hm8.js +0 -1
  119. package/dist/chunk-ty6dvda0.js +0 -1
  120. package/dist/hermes-nous-pznd63x9.png +0 -0
  121. /package/client/{components/playground → features/dev}/PixelPainter.tsx +0 -0
  122. /package/client/{components/playground → features/dev}/ToolCallsPage.tsx +0 -0
  123. /package/server/{agent.ts → harness/claude-code/models.ts} +0 -0
  124. /package/server/{openclaw.ts → harness/openclaw/discovery.ts} +0 -0
  125. /package/server/{openclaw-gateway.ts → harness/openclaw/gateway.ts} +0 -0
@@ -0,0 +1,617 @@
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).
18
+ import { appendAttachmentNote } from '@/lib/attachment-note'
19
+ import { type Part, type SubagentRecord, type Turn, applyEvent, emptyViewState } from '@/lib/format'
20
+ import type { StreamEvent, ViewState } from '@/lib/types'
21
+
22
+ import {
23
+ type CodexThread,
24
+ type CodexThreadItem,
25
+ type CodexTokenUsage,
26
+ type CodexTurn,
27
+ codexItemToNotice,
28
+ codexItemToTurn,
29
+ codexThreadToEvents
30
+ } from './adapter'
31
+ import { type CodexClient, getCodexClient } from './client'
32
+ import { debug } from '../../debug'
33
+ import { broadcast } from '../../state'
34
+ import { hasThreadConfig, renameThreadConfig, saveThreadConfig } from '../../thread-config'
35
+ import {
36
+ type StoredUpload,
37
+ materializeToPath,
38
+ resolveUploads,
39
+ uploadToDisplayPart
40
+ } from '../../uploads'
41
+
42
+ // moi's trust model matches Claude Code's `bypassPermissions`: the agent acts
43
+ // autonomously in the workspace. Codex expresses that as full sandbox access
44
+ // with approvals disabled (approval prompts would otherwise arrive as
45
+ // server→client requests we have no UI for yet).
46
+ const SANDBOX_MODE = 'danger-full-access'
47
+ const APPROVAL_POLICY = 'never'
48
+
49
+ type CodexUserInputItem = { type: 'text'; text: string } | { type: 'image'; url: string }
50
+
51
+ // A child agent thread nested under this session (Codex multi-agent): the
52
+ // child's items stream on the same connection under its own threadId, and we
53
+ // fold them into a SubagentRecord on the parent's `subagent_activity` card.
54
+ type ChildThread = {
55
+ toolCallId: string // the parent card carrying the nested transcript
56
+ record: SubagentRecord
57
+ }
58
+
59
+ type SessionRecord = {
60
+ workspaceId: string
61
+ workspacePath: string
62
+ sessionId: string // real Codex thread id once known (rekeyed on rename)
63
+ view: ViewState
64
+ activeTurnId: string | null
65
+ processing: boolean
66
+ // Live token streaming opt-in from the latest chat frame. Codex always
67
+ // streams deltas; this gates whether we forward them as preview frames.
68
+ stream: boolean
69
+ // Cumulative preview text per item id (agentMessage / reasoning summary).
70
+ previews: Map<string, { kind: 'text' | 'reasoning'; text: string }>
71
+ // Usage from `thread/tokenUsage/updated`, folded into the last assistant
72
+ // turn when the turn completes.
73
+ lastUsage: CodexTokenUsage | null
74
+ // Child agent threads keyed by their thread id (see ChildThread).
75
+ children: Map<string, ChildThread>
76
+ unsubscribe?: () => void
77
+ }
78
+
79
+ const sessions = new Map<string, SessionRecord>() // key: `${workspaceId}:${sessionId}`
80
+ // `${workspaceId}:${tempId}` -> real thread id (see cc-session.ts aliases).
81
+ const aliases = new Map<string, string>()
82
+
83
+ function recKey(workspaceId: string, sessionId: string): string {
84
+ return `${workspaceId}:${sessionId}`
85
+ }
86
+
87
+ function liveKey(workspaceId: string, sessionId: string): string {
88
+ const direct = recKey(workspaceId, sessionId)
89
+ if (sessions.has(direct)) return direct
90
+ const real = aliases.get(direct)
91
+ return real ? recKey(workspaceId, real) : direct
92
+ }
93
+
94
+ export function getCodexRunningSessions(): { workspaceId: string; sessionId: string }[] {
95
+ const out: { workspaceId: string; sessionId: string }[] = []
96
+ for (const s of sessions.values()) {
97
+ if (s.processing) out.push({ workspaceId: s.workspaceId, sessionId: s.sessionId })
98
+ }
99
+ return out
100
+ }
101
+
102
+ function setProcessing(rec: SessionRecord, processing: boolean, turnId: string | null) {
103
+ rec.activeTurnId = turnId
104
+ if (rec.processing === processing) return
105
+ rec.processing = processing
106
+ broadcast(rec.workspaceId, { type: 'status', sessionId: rec.sessionId, processing })
107
+ }
108
+
109
+ function emitTurnEvent(rec: SessionRecord, ev: StreamEvent) {
110
+ rec.view = applyEvent(rec.view, ev)
111
+ broadcast(rec.workspaceId, { ...ev, sessionId: rec.sessionId })
112
+ }
113
+
114
+ function ingestItem(rec: SessionRecord, item: CodexThreadItem) {
115
+ const turn = codexItemToTurn(item, rec.sessionId)
116
+ if (turn) {
117
+ // subAgentActivity announces a child agent thread: register it so its
118
+ // item stream (arriving under `agentThreadId`) nests into this card's
119
+ // SubagentRecord, CC-style.
120
+ if (item.type === 'subAgentActivity' && item.agentThreadId) {
121
+ const existing = rec.children.get(item.agentThreadId)
122
+ const child: ChildThread = existing ?? {
123
+ toolCallId: item.id,
124
+ record: {
125
+ taskId: item.agentThreadId,
126
+ description: item.agentPath?.split('/').pop() || 'sub-agent',
127
+ progress: [],
128
+ status: 'running',
129
+ transcript: []
130
+ }
131
+ }
132
+ if (item.kind === 'completed' || item.kind === 'closed') child.record.status = 'completed'
133
+ if (item.kind === 'failed') child.record.status = 'failed'
134
+ rec.children.set(item.agentThreadId, child)
135
+ attachSubagent(turn, child.record)
136
+ }
137
+ emitTurnEvent(rec, { kind: 'turn', turn })
138
+ return
139
+ }
140
+ const notice = codexItemToNotice(item, rec.sessionId)
141
+ if (notice) emitTurnEvent(rec, { kind: 'notice', notice })
142
+ }
143
+
144
+ // Fold the child's SubagentRecord into the tool-call part of its parent card.
145
+ function attachSubagent(turn: Turn, record: SubagentRecord) {
146
+ const part = turn.parts.find(p => p.type === 'tool-call')
147
+ if (part?.type === 'tool-call') part.call.subagent = record
148
+ }
149
+
150
+ // A child-thread notification: upsert the child's items into its
151
+ // SubagentRecord transcript and re-emit the parent card so the nested lane
152
+ // updates live.
153
+ function handleChildNotification(
154
+ rec: SessionRecord,
155
+ child: ChildThread,
156
+ childThreadId: string,
157
+ method: string,
158
+ params: Record<string, unknown>
159
+ ) {
160
+ if (method === 'item/started' || method === 'item/completed') {
161
+ const item = params.item as CodexThreadItem | undefined
162
+ if (!item) return
163
+ const turn = codexItemToTurn(item, childThreadId)
164
+ if (!turn) return
165
+ const idx = child.record.transcript.findIndex(t => t.id === turn.id)
166
+ if (idx >= 0) child.record.transcript[idx] = turn
167
+ else child.record.transcript.push(turn)
168
+ // Progress: keep the latest assistant text as the "what it's doing" line.
169
+ if (method === 'item/completed' && item.type === 'agentMessage' && item.text) {
170
+ child.record.progress = [item.text.slice(0, 200)]
171
+ }
172
+ } else if (method === 'thread/tokenUsage/updated') {
173
+ const usage = (params.tokenUsage ?? null) as CodexTokenUsage | null
174
+ if (usage?.total?.totalTokens !== undefined) {
175
+ child.record.usage = { ...child.record.usage, totalTokens: usage.total.totalTokens }
176
+ }
177
+ } else if (method === 'turn/completed') {
178
+ const turn = params.turn as CodexTurn | undefined
179
+ if (turn?.status === 'failed') child.record.status = 'failed'
180
+ else if (child.record.status === 'running') child.record.status = 'completed'
181
+ } else {
182
+ return
183
+ }
184
+ // Re-emit the parent card so the nested transcript renders live.
185
+ const owner = rec.view.turns.find(t =>
186
+ t.parts.some(p => p.type === 'tool-call' && p.call.toolCallId === child.toolCallId)
187
+ )
188
+ if (owner) {
189
+ attachSubagent(owner, child.record)
190
+ emitTurnEvent(rec, { kind: 'turn', turn: owner })
191
+ }
192
+ }
193
+
194
+ function forwardPreview(
195
+ rec: SessionRecord,
196
+ itemId: string,
197
+ kind: 'text' | 'reasoning',
198
+ delta: string
199
+ ) {
200
+ if (!rec.stream) return
201
+ const entry = rec.previews.get(itemId) ?? { kind, text: '' }
202
+ entry.text += delta
203
+ rec.previews.set(itemId, entry)
204
+ broadcast(rec.workspaceId, {
205
+ type: 'preview',
206
+ sessionId: rec.sessionId,
207
+ messageId: itemId,
208
+ parentToolUseId: null,
209
+ blocks: [{ index: 0, kind, text: entry.text }]
210
+ })
211
+ }
212
+
213
+ // Fold the thread's latest per-turn usage into the newest assistant turn so
214
+ // the meta strip can show tokens. Re-emits that turn (upsert-by-id).
215
+ function applyUsage(rec: SessionRecord) {
216
+ const last = rec.lastUsage?.last
217
+ if (!last) return
218
+ for (let i = rec.view.turns.length - 1; i >= 0; i--) {
219
+ const t = rec.view.turns[i]
220
+ if (t.role !== 'assistant') continue
221
+ const updated = {
222
+ ...t,
223
+ meta: {
224
+ ...t.meta,
225
+ usage: {
226
+ inputTokens: last.inputTokens,
227
+ outputTokens: last.outputTokens,
228
+ totalTokens: last.totalTokens
229
+ }
230
+ }
231
+ }
232
+ emitTurnEvent(rec, { kind: 'turn', turn: updated })
233
+ return
234
+ }
235
+ }
236
+
237
+ function handleNotification(rec: SessionRecord, method: string, params: Record<string, unknown>) {
238
+ if (method === '__exit') {
239
+ // The app-server died (crash or env-change restart). Drop the record so
240
+ // the next message re-resumes against a fresh process.
241
+ setProcessing(rec, false, null)
242
+ rec.unsubscribe?.()
243
+ sessions.delete(recKey(rec.workspaceId, rec.sessionId))
244
+ return
245
+ }
246
+ // Child agent threads stream on the same connection under their own ids —
247
+ // route them into the parent's SubagentRecord.
248
+ if (typeof params.threadId === 'string' && params.threadId !== rec.sessionId) {
249
+ const child = rec.children.get(params.threadId)
250
+ if (child) handleChildNotification(rec, child, params.threadId, method, params)
251
+ return
252
+ }
253
+ if (params.threadId !== rec.sessionId) return
254
+
255
+ switch (method) {
256
+ case 'item/started':
257
+ case 'item/completed': {
258
+ const item = params.item as CodexThreadItem | undefined
259
+ if (!item) return
260
+ if (method === 'item/completed') rec.previews.delete(item.id)
261
+ ingestItem(rec, item)
262
+ return
263
+ }
264
+ case 'item/agentMessage/delta': {
265
+ forwardPreview(rec, params.itemId as string, 'text', String(params.delta ?? ''))
266
+ return
267
+ }
268
+ case 'item/reasoning/summaryTextDelta': {
269
+ forwardPreview(rec, params.itemId as string, 'reasoning', String(params.delta ?? ''))
270
+ return
271
+ }
272
+ case 'thread/tokenUsage/updated': {
273
+ rec.lastUsage = (params.tokenUsage ?? null) as CodexTokenUsage | null
274
+ return
275
+ }
276
+ case 'turn/started': {
277
+ const turn = params.turn as CodexTurn | undefined
278
+ setProcessing(rec, true, turn?.id ?? rec.activeTurnId)
279
+ return
280
+ }
281
+ case 'turn/completed': {
282
+ const turn = params.turn as CodexTurn | undefined
283
+ rec.previews.clear()
284
+ applyUsage(rec)
285
+ setProcessing(rec, false, null)
286
+ if (turn?.status === 'failed' && turn.error?.message) {
287
+ broadcast(rec.workspaceId, {
288
+ kind: 'error',
289
+ sessionId: rec.sessionId,
290
+ content: turn.error.message
291
+ })
292
+ }
293
+ return
294
+ }
295
+ case 'error': {
296
+ const err = params.error as { message?: string } | undefined
297
+ const message = err?.message ?? (typeof params.message === 'string' ? params.message : '')
298
+ if (message) {
299
+ broadcast(rec.workspaceId, { kind: 'error', sessionId: rec.sessionId, content: message })
300
+ }
301
+ return
302
+ }
303
+ // Codex hooks (~/.codex/hooks.json) — surface as hook notices, parity
304
+ // with Claude Code's. started/completed share a notice id so the row
305
+ // upserts from "started" to its outcome.
306
+ case 'hook/started':
307
+ case 'hook/completed': {
308
+ const run = params.run as
309
+ | {
310
+ id?: string
311
+ eventName?: string
312
+ status?: string
313
+ entries?: { kind?: string; text?: string }[]
314
+ }
315
+ | undefined
316
+ if (!run?.id) return
317
+ const output = (run.entries ?? [])
318
+ .map(e => e.text)
319
+ .filter(Boolean)
320
+ .join('\n')
321
+ emitTurnEvent(rec, {
322
+ kind: 'notice',
323
+ notice: {
324
+ id: `codex:${rec.sessionId}:hook:${run.id}`,
325
+ kind: 'hook',
326
+ at: new Date().toISOString(),
327
+ hookId: run.id,
328
+ hookName: run.eventName ?? 'hook',
329
+ event: run.eventName ?? '',
330
+ status: method === 'hook/started' ? 'started' : 'response',
331
+ ...(output ? { output } : {}),
332
+ ...(method === 'hook/completed'
333
+ ? { outcome: run.status === 'failed' ? ('error' as const) : ('success' as const) }
334
+ : {})
335
+ }
336
+ })
337
+ return
338
+ }
339
+ // A per-thread MCP server that failed to start — surface it instead of
340
+ // silently dropping (reuses the hook notice shape; a dedicated notice
341
+ // kind isn't worth a lib/format extension yet).
342
+ case 'mcpServer/startupStatus/updated': {
343
+ if (params.status !== 'failed') return
344
+ const name = typeof params.name === 'string' ? params.name : 'mcp'
345
+ emitTurnEvent(rec, {
346
+ kind: 'notice',
347
+ notice: {
348
+ id: `codex:${rec.sessionId}:mcp:${name}`,
349
+ kind: 'hook',
350
+ at: new Date().toISOString(),
351
+ hookId: `mcp:${name}`,
352
+ hookName: `MCP ${name}`,
353
+ event: 'mcpServerStartup',
354
+ status: 'response',
355
+ outcome: 'error',
356
+ ...(typeof params.error === 'string' ? { output: params.error } : {})
357
+ }
358
+ })
359
+ return
360
+ }
361
+ }
362
+ }
363
+
364
+ function createRecord(input: {
365
+ workspaceId: string
366
+ workspacePath: string
367
+ sessionId: string
368
+ client: CodexClient
369
+ }): SessionRecord {
370
+ const rec: SessionRecord = {
371
+ workspaceId: input.workspaceId,
372
+ workspacePath: input.workspacePath,
373
+ sessionId: input.sessionId,
374
+ view: emptyViewState(),
375
+ activeTurnId: null,
376
+ processing: false,
377
+ stream: false,
378
+ previews: new Map(),
379
+ children: new Map(),
380
+ lastUsage: null
381
+ }
382
+ rec.unsubscribe = input.client.onNotification((method, params) =>
383
+ handleNotification(rec, method, params)
384
+ )
385
+ sessions.set(recKey(rec.workspaceId, rec.sessionId), rec)
386
+ return rec
387
+ }
388
+
389
+ // Seed a record's view from a resumed thread payload (turns included).
390
+ function seedFromThread(rec: SessionRecord, thread: CodexThread) {
391
+ let view = emptyViewState()
392
+ for (const ev of codexThreadToEvents(thread)) view = applyEvent(view, ev)
393
+ rec.view = view
394
+ }
395
+
396
+ async function resumeSession(input: {
397
+ workspaceId: string
398
+ workspacePath: string
399
+ sessionId: string
400
+ }): Promise<SessionRecord> {
401
+ const existing = sessions.get(liveKey(input.workspaceId, input.sessionId))
402
+ if (existing) return existing
403
+ const client = await getCodexClient(input.workspacePath)
404
+ const resumed = await client.rpc<{ thread: CodexThread }>('thread/resume', {
405
+ threadId: input.sessionId
406
+ })
407
+ const rec = createRecord({ ...input, sessionId: resumed.thread.id, client })
408
+ seedFromThread(rec, resumed.thread)
409
+ return rec
410
+ }
411
+
412
+ // Turn a typed text + resolved uploads into Codex input items and the display
413
+ // parts for the user's bubble. Images ride inline as data URLs (a documented
414
+ // Codex input mode); other files are materialized to a temp path and
415
+ // referenced in an attachment note the agent can read.
416
+ async function buildUserInput(
417
+ text: string,
418
+ uploads: StoredUpload[]
419
+ ): Promise<{ input: CodexUserInputItem[]; parts: Part[] }> {
420
+ const parts: Part[] = []
421
+ for (const u of uploads) {
422
+ const part = uploadToDisplayPart(u)
423
+ if (part) parts.push(part)
424
+ }
425
+ if (text) parts.push({ type: 'text', text })
426
+
427
+ const input: CodexUserInputItem[] = []
428
+ for (const u of uploads) {
429
+ if (u.kind === 'image' && u.data) {
430
+ input.push({ type: 'image', url: `data:${u.mediaType};base64,${u.data.toString('base64')}` })
431
+ }
432
+ }
433
+ const files: { filename: string; path: string }[] = []
434
+ for (const u of uploads) {
435
+ if (u.kind !== 'file') continue
436
+ const p = await materializeToPath(u)
437
+ if (p) files.push({ filename: u.filename, path: p })
438
+ }
439
+ const agentText = appendAttachmentNote(text, files)
440
+ if (agentText) input.push({ type: 'text', text: agentText })
441
+ return { input, parts }
442
+ }
443
+
444
+ export async function sendCodexMessage(input: {
445
+ workspaceId: string
446
+ workspacePath: string
447
+ sessionId: string
448
+ isNew: boolean
449
+ content: string
450
+ attachments?: string[]
451
+ optimisticId?: string
452
+ model?: string
453
+ effort?: string
454
+ stream?: boolean
455
+ }): Promise<void> {
456
+ const uploads = input.attachments?.length
457
+ ? resolveUploads(input.workspaceId, input.attachments)
458
+ : []
459
+ if (!input.content && uploads.length === 0) return
460
+ const { input: userInput, parts } = await buildUserInput(input.content, uploads)
461
+ if (userInput.length === 0) return
462
+
463
+ let rec: SessionRecord
464
+ try {
465
+ if (input.isNew) {
466
+ const client = await getCodexClient(input.workspacePath)
467
+ const started = await client.rpc<{ thread: CodexThread }>('thread/start', {
468
+ cwd: input.workspacePath,
469
+ sandbox: SANDBOX_MODE,
470
+ approvalPolicy: APPROVAL_POLICY,
471
+ ...(input.model ? { model: input.model } : {})
472
+ })
473
+ const realId = started.thread.id
474
+ if (realId !== input.sessionId) {
475
+ aliases.set(recKey(input.workspaceId, input.sessionId), realId)
476
+ broadcast(input.workspaceId, {
477
+ type: 'session_renamed',
478
+ from: input.sessionId,
479
+ to: realId
480
+ })
481
+ await renameThreadConfig(input.workspacePath, input.sessionId, realId)
482
+ }
483
+ rec = createRecord({
484
+ workspaceId: input.workspaceId,
485
+ workspacePath: input.workspacePath,
486
+ sessionId: realId,
487
+ client
488
+ })
489
+ if ((input.model || input.effort) && !(await hasThreadConfig(input.workspacePath, realId))) {
490
+ await saveThreadConfig(input.workspacePath, realId, {
491
+ model: input.model,
492
+ effort: input.effort
493
+ })
494
+ }
495
+ } else {
496
+ rec = await resumeSession(input)
497
+ }
498
+ } catch (err) {
499
+ broadcast(input.workspaceId, {
500
+ kind: 'error',
501
+ sessionId: input.sessionId,
502
+ content: err instanceof Error ? err.message : 'failed to start codex session'
503
+ })
504
+ return
505
+ }
506
+
507
+ rec.stream = input.stream === true
508
+
509
+ // Broadcast the user's bubble immediately so every connected tab shows it;
510
+ // the Codex echo (`userMessage` item) reuses this id via `clientId` and
511
+ // upserts in place.
512
+ const turnId = input.optimisticId ?? crypto.randomUUID()
513
+ emitTurnEvent(rec, {
514
+ kind: 'turn',
515
+ turn: {
516
+ id: turnId,
517
+ role: 'user',
518
+ origin: { kind: 'user-input' },
519
+ parts,
520
+ timestamp: new Date().toISOString()
521
+ }
522
+ })
523
+
524
+ setProcessing(rec, true, rec.activeTurnId)
525
+ try {
526
+ const client = await getCodexClient(input.workspacePath)
527
+ const turnParams = {
528
+ threadId: rec.sessionId,
529
+ clientUserMessageId: turnId,
530
+ input: userInput,
531
+ // Without an explicit summary mode Codex still reasons but emits the
532
+ // reasoning item with EMPTY summary/content (verified on the wire —
533
+ // scripts/codex-probe.ts), so no thinking ever reaches the UI. 'auto'
534
+ // makes summaries stream via item/reasoning/summaryTextDelta and land
535
+ // populated on item/completed.
536
+ summary: 'auto',
537
+ ...(input.model ? { model: input.model } : {}),
538
+ ...(input.effort ? { effort: input.effort } : {})
539
+ }
540
+ if (rec.activeTurnId) {
541
+ // A turn is running — steer the new input into it. If the turn ended
542
+ // in the race window, fall back to starting a fresh turn.
543
+ try {
544
+ await client.rpc('turn/steer', {
545
+ threadId: rec.sessionId,
546
+ clientUserMessageId: turnId,
547
+ input: userInput,
548
+ expectedTurnId: rec.activeTurnId
549
+ })
550
+ } catch {
551
+ const res = await client.rpc<{ turn: CodexTurn }>('turn/start', turnParams)
552
+ setProcessing(rec, true, res.turn.id)
553
+ }
554
+ } else {
555
+ const res = await client.rpc<{ turn: CodexTurn }>('turn/start', turnParams)
556
+ setProcessing(rec, true, res.turn.id)
557
+ }
558
+ debug(`codex send ws=${rec.workspaceId} thread=${rec.sessionId} turn=${rec.activeTurnId}`)
559
+ } catch (err) {
560
+ setProcessing(rec, false, null)
561
+ broadcast(rec.workspaceId, {
562
+ kind: 'error',
563
+ sessionId: rec.sessionId,
564
+ content: err instanceof Error ? err.message : 'send failed'
565
+ })
566
+ }
567
+ }
568
+
569
+ export async function interruptCodexRun(input: {
570
+ workspaceId: string
571
+ sessionId: string
572
+ }): Promise<void> {
573
+ const rec = sessions.get(liveKey(input.workspaceId, input.sessionId))
574
+ if (!rec) return
575
+ try {
576
+ if (rec.activeTurnId) {
577
+ const client = await getCodexClient(rec.workspacePath)
578
+ await client.rpc('turn/interrupt', {
579
+ threadId: rec.sessionId,
580
+ turnId: rec.activeTurnId
581
+ })
582
+ }
583
+ broadcast(rec.workspaceId, { kind: 'stopped', sessionId: rec.sessionId })
584
+ setProcessing(rec, false, null)
585
+ } catch (err) {
586
+ broadcast(rec.workspaceId, {
587
+ kind: 'error',
588
+ sessionId: rec.sessionId,
589
+ content: err instanceof Error ? err.message : 'interrupt failed'
590
+ })
591
+ }
592
+ }
593
+
594
+ export function viewAsEvents(rec: SessionRecord): StreamEvent[] {
595
+ const evs: StreamEvent[] = []
596
+ for (const turn of rec.view.turns) evs.push({ kind: 'turn', turn })
597
+ for (const notice of rec.view.notices) evs.push({ kind: 'notice', notice })
598
+ return evs
599
+ }
600
+
601
+ // Read-side hook for the REST events endpoint (mirrors the OpenClaw path):
602
+ // return the live view when we hold one so REST + WS stay in agreement.
603
+ export function getLiveCodexEvents(workspaceId: string, sessionId: string): StreamEvent[] | null {
604
+ const rec = sessions.get(liveKey(workspaceId, sessionId))
605
+ return rec ? viewAsEvents(rec) : null
606
+ }
607
+
608
+ // Cold-load: resume the thread (also subscribing it on our connection) and
609
+ // return its events, so subsequent WS frames upsert into the same view.
610
+ export async function ensureCodexSessionLive(input: {
611
+ workspaceId: string
612
+ workspacePath: string
613
+ sessionId: string
614
+ }): Promise<StreamEvent[]> {
615
+ const rec = await resumeSession(input)
616
+ return viewAsEvents(rec)
617
+ }
@@ -0,0 +1,57 @@
1
+ // Shared debug taps for the /playground/harness page.
2
+ //
3
+ // Two channels of ring buffers, kept module-global so they survive session
4
+ // teardowns and process-client restarts:
5
+ // - wire: the harness's native protocol frames, per backend scope
6
+ // (Codex: JSON-RPC frames keyed by workspacePath; Claude Code:
7
+ // raw SDK messages keyed by workspaceId).
8
+ // - client: every frame `broadcast()` pushes to chat clients, keyed by
9
+ // workspaceId — provider-agnostic, tapped in state.ts.
10
+ //
11
+ // Read by GET /api/workspaces/:id/harness/debug with `seq` cursors so the
12
+ // page can poll deltas.
13
+
14
+ export type DebugFrame = {
15
+ seq: number
16
+ ts: number
17
+ // 'send' = moi → harness (wire) / n.a. (client); 'recv' = harness → moi.
18
+ dir: 'send' | 'recv'
19
+ frame: unknown
20
+ }
21
+
22
+ const RING_CAP = 1000
23
+ let seq = 0
24
+
25
+ const logs = new Map<string, DebugFrame[]>() // key: `${channel}:${scope}`
26
+
27
+ function tap(channel: 'wire' | 'client', scope: string, dir: 'send' | 'recv', frame: unknown) {
28
+ const key = `${channel}:${scope}`
29
+ let log = logs.get(key)
30
+ if (!log) {
31
+ log = []
32
+ logs.set(key, log)
33
+ }
34
+ log.push({ seq: ++seq, ts: Date.now(), dir, frame })
35
+ if (log.length > RING_CAP) log.splice(0, log.length - RING_CAP)
36
+ }
37
+
38
+ function read(channel: 'wire' | 'client', scope: string, sinceSeq: number): DebugFrame[] {
39
+ const log = logs.get(`${channel}:${scope}`) ?? []
40
+ return sinceSeq > 0 ? log.filter(f => f.seq > sinceSeq) : log
41
+ }
42
+
43
+ export function tapWire(scope: string, dir: 'send' | 'recv', frame: unknown): void {
44
+ tap('wire', scope, dir, frame)
45
+ }
46
+
47
+ export function getWireLog(scope: string, sinceSeq = 0): DebugFrame[] {
48
+ return read('wire', scope, sinceSeq)
49
+ }
50
+
51
+ export function tapClientFrame(workspaceId: string, frame: unknown): void {
52
+ tap('client', workspaceId, 'send', frame)
53
+ }
54
+
55
+ export function getClientFrameLog(workspaceId: string, sinceSeq = 0): DebugFrame[] {
56
+ return read('client', workspaceId, sinceSeq)
57
+ }