moi-computer 0.8.1-next.0 → 0.9.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 (103) hide show
  1. package/client/assets/hermes.png +0 -0
  2. package/client/components/shared/IconGhost.tsx +15 -18
  3. package/client/components/ui/button.tsx +2 -2
  4. package/client/components/ui/hover-card.tsx +1 -1
  5. package/client/components/ui/popover.tsx +3 -1
  6. package/client/features/chat/ChatEmptyState.tsx +25 -7
  7. package/client/features/chat/ChatPanel.tsx +70 -28
  8. package/client/features/chat/ChatPopup.tsx +3 -2
  9. package/client/features/chat/ChatPromptBubbles.tsx +1 -1
  10. package/client/features/chat/MarkdownContent.tsx +1 -1
  11. package/client/features/chat/attachment-staging.ts +153 -0
  12. package/client/features/chat/chat-send.ts +55 -0
  13. package/client/features/chat/chat-store.ts +32 -8
  14. package/client/features/chat/composer/ChatComposer.tsx +190 -77
  15. package/client/features/chat/{ModelPicker.tsx → composer/ModelPicker.tsx} +29 -25
  16. package/client/features/chat/composer/banners/ComposerBanner.tsx +1 -1
  17. package/client/features/chat/composer/banners/WorkspaceAgentAvailabilityBanner.tsx +4 -13
  18. package/client/features/chat/{model-order.ts → composer/model-order.ts} +16 -0
  19. package/client/features/chat/composer/useWorkspaceComposerState.tsx +9 -4
  20. package/client/features/chat/tool-group/format/claude.ts +48 -0
  21. package/client/features/chat/tool-group/format/codex.ts +126 -0
  22. package/client/features/chat/tool-group/format/hermes.ts +68 -0
  23. package/client/features/chat/tool-group/format/index.ts +34 -0
  24. package/client/features/chat/tool-group/format/mcp.ts +64 -0
  25. package/client/features/chat/tool-group/format/openclaw.ts +116 -0
  26. package/client/features/chat/tool-group/format/shared.ts +49 -0
  27. package/client/features/chat/useChat.ts +5 -10
  28. package/client/features/dev/ChatStatesPage.tsx +40 -2
  29. package/client/features/drawings/DrawingLayer.tsx +49 -0
  30. package/client/features/drawings/DrawingToolbar.tsx +95 -0
  31. package/client/features/drawings/annotation-availability.ts +10 -0
  32. package/client/features/drawings/capture-element.ts +45 -0
  33. package/client/features/drawings/useChatAnnotation.ts +222 -0
  34. package/client/features/drawings/useDrawingLayer.ts +758 -0
  35. package/client/features/drawings/useViewBuilderSketch.ts +151 -0
  36. package/client/features/home/workspace-presentation.tsx +6 -2
  37. package/client/features/home/workspace-setup/WorkspaceAgentStep.tsx +12 -6
  38. package/client/features/scratchpad/ScratchpadControls.tsx +19 -5
  39. package/client/features/views/ViewBuilder.tsx +224 -0
  40. package/client/features/views/api.ts +1 -0
  41. package/client/features/views/useViewBuilderActions.ts +24 -3
  42. package/client/features/views/useViewBuilderDrafts.ts +66 -0
  43. package/client/features/widgets/Widgets.tsx +23 -39
  44. package/client/features/workspace/CustomizePanel.tsx +1 -1
  45. package/client/features/workspace/WorkspaceScreen.tsx +157 -57
  46. package/client/features/workspace/WorkspaceTabs.tsx +3 -3
  47. package/client/features/workspace/useFitsSplitLayout.ts +14 -8
  48. package/client/index.css +8 -0
  49. package/client/store/ui.ts +19 -0
  50. package/client/theme.css +33 -8
  51. package/dist/chunk-3becmq75.js +81 -0
  52. package/dist/{chunk-kkj86722.js → chunk-6w6j9g4b.js} +78 -78
  53. package/dist/{chunk-xeyxk7ep.js → chunk-8ew39cvq.js} +4 -4
  54. package/dist/chunk-c8gtrjwp.js +1 -0
  55. package/dist/{chunk-2vaafjp4.js → chunk-pp62fnxh.js} +1 -1
  56. package/dist/{chunk-35fq49qa.js → chunk-sxc24vfp.js} +1 -1
  57. package/dist/{chunk-xzx7c9hq.js → chunk-v964b5g7.js} +1 -1
  58. package/dist/chunk-zx33ts9d.css +1 -0
  59. package/dist/hermes-pznd63x9.png +0 -0
  60. package/dist/index.html +1 -1
  61. package/lib/format.ts +21 -7
  62. package/lib/themes.ts +8 -8
  63. package/lib/types.ts +8 -1
  64. package/lib/workspace-types.ts +2 -1
  65. package/package.json +6 -4
  66. package/server/api.ts +21 -2
  67. package/server/bundler/build-applet.ts +35 -44
  68. package/server/cli-env.ts +2 -2
  69. package/server/cli.ts +227 -56
  70. package/server/constants.ts +8 -0
  71. package/server/control-client.ts +124 -0
  72. package/server/control.ts +2 -2
  73. package/server/harness/README.md +74 -23
  74. package/server/harness/acp/adapter.ts +220 -0
  75. package/server/harness/acp/archived.ts +88 -0
  76. package/server/harness/acp/client.ts +328 -0
  77. package/server/harness/acp/discovery.ts +130 -0
  78. package/server/harness/acp/run-durations.ts +68 -0
  79. package/server/harness/acp/session.ts +788 -0
  80. package/server/harness/acp/wire.ts +132 -0
  81. package/server/harness/executable.ts +15 -1
  82. package/server/harness/hermes/NOTES.md +815 -0
  83. package/server/harness/hermes/discovery.ts +155 -0
  84. package/server/harness/hermes/index.ts +155 -0
  85. package/server/harness/hermes/models.ts +79 -0
  86. package/server/harness/openclaw/NOTES.md +196 -94
  87. package/server/harness/openclaw/adapter.ts +28 -55
  88. package/server/harness/openclaw/compat.ts +4 -8
  89. package/server/harness/openclaw/session.ts +257 -238
  90. package/server/harness/openclaw/strip.ts +10 -34
  91. package/server/harness/openclaw/thinking.ts +5 -53
  92. package/server/harness/registry.ts +3 -1
  93. package/server/service.ts +2 -2
  94. package/server/view-builders.ts +4 -2
  95. package/server/workspace-import.ts +30 -1
  96. package/workspace/.claude/skills/moi-workspace/SKILL.md +6 -6
  97. package/client/features/chat/tool-group/format.ts +0 -359
  98. package/client/features/views/ViewBuilderTab.tsx +0 -152
  99. package/dist/chunk-gny990qx.css +0 -1
  100. package/dist/chunk-gt7n06ef.js +0 -1
  101. package/dist/chunk-n7pga5x3.js +0 -80
  102. /package/workspace/.claude/skills/moi-workspace/{DESIGN.md → references/DESIGN.md} +0 -0
  103. /package/workspace/.claude/skills/moi-workspace/{SCRATCHPAD.md → references/SCRATCHPAD.md} +0 -0
@@ -0,0 +1,788 @@
1
+ // Per-(workspaceId, sessionId) live ACP session adapter.
2
+ //
3
+ // One agent process per workspace (see ./client.ts) serves every session in
4
+ // it; this module owns the per-session state: the durable in-memory view, turn
5
+ // accounting for the processing spinner, and the mapping of `session/update`
6
+ // notifications onto moi's `StreamEvent`s.
7
+ //
8
+ // Provider-agnostic — `AcpProviderConfig` supplies the spawn spec and the few
9
+ // per-backend knobs (no-prompt mode id, MCP servers). Backend quirks that are
10
+ // NOT protocol are handled in the provider's own folder.
11
+ //
12
+ // Lifecycle notes:
13
+ // - A brand-new session is created under the client's temporary uuid, then
14
+ // renamed to the agent's real session id (`session_renamed`) — same flow
15
+ // as the Claude Code, OpenClaw and Codex paths.
16
+ // - ACP has no steer: a send that lands mid-turn is queued and flushed when
17
+ // the running turn resolves.
18
+ // - `session/prompt` is a long-running request that resolves at end of turn,
19
+ // so its promise IS the turn's lifetime — activity is mirrored from it,
20
+ // never derived by counting frames.
21
+ import { appendAttachmentNote } from '@/lib/attachment-note'
22
+ import { type MoiContext, appendMoiContext, renderMoiContext } from '@/lib/moi-context'
23
+ import { type Part, applyEvent, emptyViewState } from '@/lib/format'
24
+ import type { Model, SessionActivity, StreamEvent, ViewState, WorkspaceType } from '@/lib/types'
25
+
26
+ import {
27
+ type AcpProviderId,
28
+ AssistantTurnAccumulator,
29
+ acpToolCallToTurn,
30
+ acpUsageToTurnMeta,
31
+ replayedUserParts,
32
+ toolTurnId
33
+ } from './adapter'
34
+ import { type AcpClient, type AcpSpawnSpec, getAcpClient } from './client'
35
+ import { appendRunDuration, runDurations } from './run-durations'
36
+ import {
37
+ type AcpModelInfo,
38
+ type AcpNewSessionResult,
39
+ type AcpPromptBlock,
40
+ type ContentChunk,
41
+ type PromptResponse,
42
+ type SessionUpdate,
43
+ type ToolCallUpdate,
44
+ isTextBlock
45
+ } from './wire'
46
+ import { agentStore } from '../../agent'
47
+ import { debug } from '../../debug'
48
+ import { broadcast } from '../../state'
49
+ import { renameSelectedSession } from '../../selected-session'
50
+ import { hasSessionConfig, renameSessionConfig, saveSessionConfig } from '../../session-config'
51
+ import { renameViewBuilderSession } from '../../view-builders'
52
+ import {
53
+ type StoredUpload,
54
+ materializeToPath,
55
+ resolveUploads,
56
+ uploadToDisplayPart
57
+ } from '../../uploads'
58
+
59
+ export type AcpSpawnContext = {
60
+ workspaceId: string
61
+ workspacePath: string
62
+ agentId?: string
63
+ }
64
+
65
+ export type AcpProviderConfig = {
66
+ id: WorkspaceType
67
+ provider: AcpProviderId
68
+ spawn: (ctx: AcpSpawnContext) => Promise<AcpSpawnSpec>
69
+ // Session mode that disables approval prompts, matching moi's
70
+ // bypass-permissions trust model. Applied to every new and resumed session.
71
+ noPromptModeId?: string
72
+ // Does the backend send images as base64 content blocks?
73
+ supportsImages?: boolean
74
+ // How the backend's model catalog becomes picker rows. ACP says nothing
75
+ // about how `name`/`description` are formatted, so a backend that packs
76
+ // extra structure into them (Hermes: the provider) unpacks it here.
77
+ // Defaults to a straight passthrough.
78
+ mapModels?: (models: AcpModelInfo[]) => Model[]
79
+ }
80
+
81
+ type QueuedSend = { blocks: AcpPromptBlock[]; turnId: string }
82
+
83
+ type SessionRecord = {
84
+ workspaceId: string
85
+ workspacePath: string
86
+ agentId?: string
87
+ sessionId: string
88
+ view: ViewState
89
+ processing: boolean
90
+ // Live token streaming opt-in from the latest chat frame. ACP always
91
+ // streams; this gates whether we forward previews.
92
+ stream: boolean
93
+ // Suppress preview forwarding while replaying history through the same
94
+ // notification path.
95
+ replaying: boolean
96
+ acc: AssistantTurnAccumulator
97
+ // Open user-message run, only ever populated during replay (ACP does not
98
+ // echo live sends).
99
+ userChunk: string
100
+ // Image blocks of the open replayed user message. An image-only send has no
101
+ // user text besides the envelope, so these are what keep its replayed turn
102
+ // alive once the envelope strips away.
103
+ userImageParts: Part[]
104
+ // Tool calls seen this turn that never reached a terminal status — closed
105
+ // at turn end so their cards don't hang (see ../hermes/NOTES.md §3.4).
106
+ // Holds aliased ids (see toolCallSeq).
107
+ openToolCalls: Set<string>
108
+ // How many times each wire toolCallId has STARTED. Hermes replay ids are
109
+ // `functions.<tool>:<index>` with the index scoped to one assistant message
110
+ // (NOTES.md §3.4), so a session calling the same tool from several messages
111
+ // repeats the id — upsert-by-id would collapse every occurrence into the
112
+ // first turn. Each start past the first gets an aliased id; updates attach
113
+ // to the latest start. Live `tc-<hash>` ids are unique, so the alias is a
114
+ // no-op there.
115
+ toolCallSeq: Map<string, number>
116
+ model?: string
117
+ queue: QueuedSend[]
118
+ unsubscribe?: () => void
119
+ }
120
+
121
+ const sessions = new Map<string, SessionRecord>() // key: `${workspaceId}:${sessionId}`
122
+ const aliases = new Map<string, string>() // `${workspaceId}:${tempId}` -> real id
123
+
124
+ function recKey(workspaceId: string, sessionId: string): string {
125
+ return `${workspaceId}:${sessionId}`
126
+ }
127
+
128
+ function liveKey(workspaceId: string, sessionId: string): string {
129
+ const direct = recKey(workspaceId, sessionId)
130
+ if (sessions.has(direct)) return direct
131
+ const real = aliases.get(direct)
132
+ return real ? recKey(workspaceId, real) : direct
133
+ }
134
+
135
+ export function getAcpActiveSessions(): {
136
+ workspaceId: string
137
+ sessionId: string
138
+ activity: SessionActivity
139
+ }[] {
140
+ const out: { workspaceId: string; sessionId: string; activity: SessionActivity }[] = []
141
+ for (const s of sessions.values()) {
142
+ // ACP approvals are designed out (no-prompt mode + transport auto-approve
143
+ // in client.ts), so `requires-action` never occurs. If that policy is
144
+ // relaxed, `session/request_permission` is the signal to map to it.
145
+ if (s.processing) {
146
+ out.push({ workspaceId: s.workspaceId, sessionId: s.sessionId, activity: 'running' })
147
+ }
148
+ }
149
+ return out
150
+ }
151
+
152
+ function setProcessing(rec: SessionRecord, processing: boolean) {
153
+ if (rec.processing === processing) return
154
+ rec.processing = processing
155
+ broadcast(rec.workspaceId, {
156
+ type: 'status',
157
+ sessionId: rec.sessionId,
158
+ activity: processing ? 'running' : 'idle'
159
+ })
160
+ }
161
+
162
+ function emitTurnEvent(rec: SessionRecord, ev: StreamEvent) {
163
+ // ACP replay updates carry no timestamps, so replayed turns would get
164
+ // stamped with replay-time `new Date()`s — and the client's duration label
165
+ // (groupTurns: assistant timestamp minus the preceding user turn's) would
166
+ // report how long the REPLAY took, "Worked for 1s" on every reloaded run.
167
+ // The real duration is unrecoverable, so drop the timestamp instead; the
168
+ // client falls back to a plain "Worked" label.
169
+ if (ev.kind === 'turn' && rec.replaying && ev.turn.timestamp !== undefined) {
170
+ const turn = { ...ev.turn }
171
+ delete turn.timestamp
172
+ ev = { kind: 'turn', turn }
173
+ }
174
+ rec.view = applyEvent(rec.view, ev)
175
+ broadcast(rec.workspaceId, { ...ev, sessionId: rec.sessionId })
176
+ }
177
+
178
+ function forwardPreview(rec: SessionRecord) {
179
+ if (!rec.stream || rec.replaying) return
180
+ broadcast(rec.workspaceId, {
181
+ type: 'preview',
182
+ sessionId: rec.sessionId,
183
+ messageId: rec.acc.currentId,
184
+ parentToolUseId: null,
185
+ blocks: rec.acc.previewBlocks()
186
+ })
187
+ }
188
+
189
+ function flushAssistant(
190
+ rec: SessionRecord,
191
+ meta?: Parameters<AssistantTurnAccumulator['flush']>[0]
192
+ ) {
193
+ const turn = rec.acc.flush(meta)
194
+ if (turn) emitTurnEvent(rec, { kind: 'turn', turn })
195
+ }
196
+
197
+ function flushUserChunk(rec: SessionRecord) {
198
+ if (!rec.userChunk && rec.userImageParts.length === 0) return
199
+ // The chunk is the persisted prompt verbatim; fold the appended machinery
200
+ // (moi-context envelope, attachment note) back out before the text becomes
201
+ // a bubble. Replayed images render above the text like the live bubble, and
202
+ // a turn with nothing left (no typed text, no images) drops entirely.
203
+ const parts = [...rec.userImageParts, ...replayedUserParts(rec.userChunk)]
204
+ rec.userChunk = ''
205
+ rec.userImageParts = []
206
+ if (parts.length === 0) return
207
+ emitTurnEvent(rec, {
208
+ kind: 'turn',
209
+ turn: {
210
+ id: `${rec.sessionId}:user:${rec.view.turns.length}`,
211
+ role: 'user',
212
+ origin: { kind: 'user-input' },
213
+ parts,
214
+ timestamp: new Date().toISOString()
215
+ }
216
+ })
217
+ }
218
+
219
+ function ingestToolCall(
220
+ rec: SessionRecord,
221
+ update: ToolCallUpdate,
222
+ provider: AcpProviderId,
223
+ isStart: boolean
224
+ ) {
225
+ // A tool call closes the open assistant run: text before it and text after
226
+ // it are separate turns, so the transcript reads in execution order.
227
+ flushAssistant(rec)
228
+ flushUserChunk(rec)
229
+ // Repeated wire ids (see toolCallSeq) get a per-occurrence alias so each
230
+ // start is its own turn; a `tool_call_update` reuses the latest one.
231
+ if (isStart) {
232
+ rec.toolCallSeq.set(update.toolCallId, (rec.toolCallSeq.get(update.toolCallId) ?? 0) + 1)
233
+ }
234
+ const seen = rec.toolCallSeq.get(update.toolCallId) ?? 1
235
+ const aliasedId = seen > 1 ? `${update.toolCallId}#${seen}` : update.toolCallId
236
+ const aliased = aliasedId === update.toolCallId ? update : { ...update, toolCallId: aliasedId }
237
+ const id = toolTurnId(rec.sessionId, aliasedId)
238
+ const previous = rec.view.turns.find(t => t.id === id)
239
+ const turn = acpToolCallToTurn({ update: aliased, sessionId: rec.sessionId, provider, previous })
240
+ const state = turn.parts.find(p => p.type === 'tool-call')
241
+ const settled =
242
+ state?.type === 'tool-call' && (state.call.state === 'success' || state.call.state === 'error')
243
+ if (settled) rec.openToolCalls.delete(aliasedId)
244
+ else rec.openToolCalls.add(aliasedId)
245
+ emitTurnEvent(rec, { kind: 'turn', turn })
246
+ }
247
+
248
+ // Some backends never send a terminal `tool_call_update` for certain tools
249
+ // (Hermes drops it for file read/write — NOTES.md §3.4), which would leave the
250
+ // card spinning forever. The turn ending is proof the call finished.
251
+ function closeOpenToolCalls(rec: SessionRecord) {
252
+ for (const toolCallId of rec.openToolCalls) {
253
+ const id = toolTurnId(rec.sessionId, toolCallId)
254
+ const turn = rec.view.turns.find(t => t.id === id)
255
+ if (!turn) continue
256
+ const part = turn.parts.find(p => p.type === 'tool-call')
257
+ if (
258
+ part?.type !== 'tool-call' ||
259
+ part.call.state === 'success' ||
260
+ part.call.state === 'error'
261
+ ) {
262
+ continue
263
+ }
264
+ emitTurnEvent(rec, {
265
+ kind: 'turn',
266
+ turn: {
267
+ ...turn,
268
+ parts: turn.parts.map(p =>
269
+ p.type === 'tool-call' ? { ...p, call: { ...p.call, state: 'success' as const } } : p
270
+ )
271
+ }
272
+ })
273
+ }
274
+ rec.openToolCalls.clear()
275
+ }
276
+
277
+ function handleSessionUpdate(rec: SessionRecord, update: SessionUpdate, provider: AcpProviderId) {
278
+ switch (update.sessionUpdate) {
279
+ case 'agent_message_chunk': {
280
+ flushUserChunk(rec)
281
+ const block = (update as { content?: { text?: string } }).content
282
+ rec.acc.append('text', block?.text ?? '')
283
+ forwardPreview(rec)
284
+ return
285
+ }
286
+ case 'agent_thought_chunk': {
287
+ flushUserChunk(rec)
288
+ const block = (update as { content?: { text?: string } }).content
289
+ rec.acc.append('reasoning', block?.text ?? '')
290
+ forwardPreview(rec)
291
+ return
292
+ }
293
+ case 'user_message_chunk': {
294
+ // Replay only — live sends are echoed by moi itself.
295
+ flushAssistant(rec)
296
+ const content = (update as Partial<ContentChunk>).content
297
+ if (isTextBlock(content)) {
298
+ rec.userChunk += content.text
299
+ } else if (content?.type === 'image' && content.data) {
300
+ // Rebuilt as a data URL — the cold-reload fallback (live bubbles point
301
+ // at moi's served upload URL, but that store is gone after a restart).
302
+ rec.userImageParts.push({
303
+ type: 'file',
304
+ mediaType: content.mimeType,
305
+ url: `data:${content.mimeType};base64,${content.data}`
306
+ })
307
+ }
308
+ return
309
+ }
310
+ case 'tool_call':
311
+ case 'tool_call_update': {
312
+ ingestToolCall(
313
+ rec,
314
+ update as unknown as ToolCallUpdate,
315
+ provider,
316
+ update.sessionUpdate === 'tool_call'
317
+ )
318
+ return
319
+ }
320
+ case 'session_info_update': {
321
+ // The backend generated or refreshed a session title.
322
+ if (!rec.replaying) {
323
+ broadcast(rec.workspaceId, { type: 'sessions_changed', sessionId: rec.sessionId })
324
+ }
325
+ return
326
+ }
327
+ case 'current_mode_update':
328
+ case 'available_commands_update':
329
+ case 'plan':
330
+ case 'usage_update':
331
+ // Not rendered yet: modes/commands have no UI, the plan lane is Codex's
332
+ // and the context meter is not wired to a widget.
333
+ return
334
+ }
335
+ }
336
+
337
+ function handleNotification(
338
+ rec: SessionRecord,
339
+ config: AcpProviderConfig,
340
+ method: string,
341
+ params: Record<string, unknown>
342
+ ) {
343
+ if (method === '__exit') {
344
+ // The agent died (crash or env-change restart). Drop the record so the
345
+ // next message re-resumes against a fresh process.
346
+ setProcessing(rec, false)
347
+ rec.unsubscribe?.()
348
+ sessions.delete(recKey(rec.workspaceId, rec.sessionId))
349
+ return
350
+ }
351
+ if (method !== 'session/update') return
352
+ if (params.sessionId !== rec.sessionId) return
353
+ const update = params.update as SessionUpdate | undefined
354
+ if (!update || typeof update.sessionUpdate !== 'string') return
355
+ handleSessionUpdate(rec, update, config.provider)
356
+ }
357
+
358
+ // A send/turn failure can mean the backend lost its credentials outside moi,
359
+ // which the cached availability snapshot won't reflect until its TTL expires.
360
+ // Force a fresh probe so the composer's banner flips right away.
361
+ function refreshAvailability(
362
+ rec: Pick<SessionRecord, 'workspaceId' | 'workspacePath'>,
363
+ id: WorkspaceType
364
+ ) {
365
+ void agentStore.refresh({ id: rec.workspaceId, path: rec.workspacePath, type: id })
366
+ }
367
+
368
+ function createRecord(input: {
369
+ workspaceId: string
370
+ workspacePath: string
371
+ agentId?: string
372
+ sessionId: string
373
+ client: AcpClient
374
+ config: AcpProviderConfig
375
+ model?: string
376
+ }): SessionRecord {
377
+ const rec: SessionRecord = {
378
+ workspaceId: input.workspaceId,
379
+ workspacePath: input.workspacePath,
380
+ agentId: input.agentId,
381
+ sessionId: input.sessionId,
382
+ view: emptyViewState(),
383
+ processing: false,
384
+ stream: false,
385
+ replaying: false,
386
+ acc: new AssistantTurnAccumulator(input.sessionId, input.model, input.config.id),
387
+ userChunk: '',
388
+ userImageParts: [],
389
+ openToolCalls: new Set(),
390
+ toolCallSeq: new Map(),
391
+ model: input.model,
392
+ queue: []
393
+ }
394
+ rec.unsubscribe = input.client.onNotification((method, params) =>
395
+ handleNotification(rec, input.config, method, params)
396
+ )
397
+ sessions.set(recKey(rec.workspaceId, rec.sessionId), rec)
398
+ return rec
399
+ }
400
+
401
+ // Apply the no-prompt mode so tool approvals never block a turn.
402
+ async function applyNoPromptMode(client: AcpClient, config: AcpProviderConfig, sessionId: string) {
403
+ if (!config.noPromptModeId) return
404
+ try {
405
+ await client.rpc('session/set_mode', { sessionId, modeId: config.noPromptModeId })
406
+ } catch (err) {
407
+ debug(
408
+ `${config.id} set_mode failed session=${sessionId}: ${err instanceof Error ? err.message : err}`
409
+ )
410
+ }
411
+ }
412
+
413
+ async function resumeSession(
414
+ config: AcpProviderConfig,
415
+ input: AcpSpawnContext & { sessionId: string }
416
+ ): Promise<SessionRecord> {
417
+ const existing = sessions.get(liveKey(input.workspaceId, input.sessionId))
418
+ if (existing) return existing
419
+ const client = await getAcpClient(await config.spawn(input))
420
+ const rec = createRecord({ ...input, client, config })
421
+ // `session/load` replays the whole transcript as session/update
422
+ // notifications on this connection — they flow through the same handler,
423
+ // so flag the record as replaying to suppress previews and title events.
424
+ rec.replaying = true
425
+ try {
426
+ await client.rpc('session/load', {
427
+ sessionId: input.sessionId,
428
+ cwd: input.workspacePath,
429
+ mcpServers: []
430
+ })
431
+ } catch (err) {
432
+ // The record is already registered, and a live record makes every later
433
+ // send skip `session/load` and prompt a session this process never
434
+ // resumed. Drop it so the next send retries the replay.
435
+ rec.unsubscribe?.()
436
+ sessions.delete(recKey(rec.workspaceId, rec.sessionId))
437
+ throw err
438
+ } finally {
439
+ flushAssistant(rec)
440
+ flushUserChunk(rec)
441
+ rec.replaying = false
442
+ }
443
+ await attachReplayDurations(rec)
444
+ await applyNoPromptMode(client, config, input.sessionId)
445
+ return rec
446
+ }
447
+
448
+ // Re-attach the live-recorded run durations to a replayed transcript: split
449
+ // it into runs at user turns and stamp each run's FINAL turn — groupTurns'
450
+ // meta merge carries the last turn's `durationMs` onto the merged run, which
451
+ // is where the "Worked for Xs" label reads it. Only applied when the replayed
452
+ // run count matches the recording exactly: a session also driven outside moi,
453
+ // or a replayed user turn that folded to nothing, would misalign every later
454
+ // run — and a missing label beats a wrong one.
455
+ async function attachReplayDurations(rec: SessionRecord): Promise<void> {
456
+ const durations = await runDurations(rec.workspacePath, rec.sessionId)
457
+ if (durations.length === 0) return
458
+ const runEnds: number[] = []
459
+ let openRun = false
460
+ rec.view.turns.forEach((turn, i) => {
461
+ if (turn.role === 'user') {
462
+ openRun = true
463
+ return
464
+ }
465
+ // Every non-user turn (text, reasoning, tool call) extends the run that
466
+ // the last user turn opened; turns before any user turn belong to none.
467
+ if (openRun) {
468
+ runEnds.push(i)
469
+ openRun = false
470
+ } else if (runEnds.length > 0) {
471
+ runEnds[runEnds.length - 1] = i
472
+ }
473
+ })
474
+ if (runEnds.length !== durations.length) return
475
+ runEnds.forEach((endIndex, run) => {
476
+ const turn = rec.view.turns[endIndex]
477
+ emitTurnEvent(rec, {
478
+ kind: 'turn',
479
+ turn: { ...turn, meta: { ...turn.meta, durationMs: durations[run] } }
480
+ })
481
+ })
482
+ }
483
+
484
+ // Turn typed text + resolved uploads into ACP prompt blocks and the display
485
+ // parts for the user's bubble. Images ride inline as base64 blocks; other
486
+ // files are materialized to a temp path and referenced in an attachment note.
487
+ async function buildPrompt(
488
+ text: string,
489
+ uploads: StoredUpload[],
490
+ supportsImages: boolean
491
+ ): Promise<{ blocks: AcpPromptBlock[]; parts: Part[] }> {
492
+ const parts: Part[] = []
493
+ for (const u of uploads) {
494
+ const part = uploadToDisplayPart(u)
495
+ if (part) parts.push(part)
496
+ }
497
+ if (text) parts.push({ type: 'text', text })
498
+
499
+ const blocks: AcpPromptBlock[] = []
500
+ const files: { filename: string; path: string }[] = []
501
+ for (const u of uploads) {
502
+ if (u.kind === 'image' && u.data && supportsImages) {
503
+ blocks.push({ type: 'image', mimeType: u.mediaType, data: u.data.toString('base64') })
504
+ } else if (u.kind === 'file' || (u.kind === 'image' && !supportsImages)) {
505
+ const p = await materializeToPath(u)
506
+ if (p) files.push({ filename: u.filename, path: p })
507
+ }
508
+ }
509
+ const agentText = appendAttachmentNote(text, files)
510
+ if (agentText) blocks.unshift({ type: 'text', text: agentText })
511
+ return { blocks, parts }
512
+ }
513
+
514
+ // Run one prompt to completion, then drain anything queued behind it.
515
+ async function runPrompt(
516
+ config: AcpProviderConfig,
517
+ rec: SessionRecord,
518
+ blocks: AcpPromptBlock[]
519
+ ): Promise<void> {
520
+ setProcessing(rec, true)
521
+ // The prompt promise IS the run, so its wall time is the "Worked for Xs"
522
+ // duration — recorded (settled or errored) for replay, which has no
523
+ // timestamps of its own (see ./run-durations.ts).
524
+ const startedAt = Date.now()
525
+ try {
526
+ const client = await getAcpClient(
527
+ await config.spawn({
528
+ workspaceId: rec.workspaceId,
529
+ workspacePath: rec.workspacePath,
530
+ agentId: rec.agentId
531
+ })
532
+ )
533
+ const res = await client.rpc<PromptResponse>('session/prompt', {
534
+ sessionId: rec.sessionId,
535
+ prompt: blocks
536
+ })
537
+ closeOpenToolCalls(rec)
538
+ flushAssistant(rec, {
539
+ ...(res.stopReason ? { stopReason: res.stopReason } : {}),
540
+ ...(acpUsageToTurnMeta(res.usage) ? { usage: acpUsageToTurnMeta(res.usage) } : {})
541
+ })
542
+ if (res.stopReason === 'cancelled') {
543
+ broadcast(rec.workspaceId, { kind: 'stopped', sessionId: rec.sessionId })
544
+ }
545
+ debug(
546
+ `${config.id} turn done ws=${rec.workspaceId} session=${rec.sessionId} stop=${res.stopReason}`
547
+ )
548
+ } catch (err) {
549
+ closeOpenToolCalls(rec)
550
+ flushAssistant(rec)
551
+ broadcast(rec.workspaceId, {
552
+ kind: 'error',
553
+ sessionId: rec.sessionId,
554
+ content: err instanceof Error ? err.message : 'send failed'
555
+ })
556
+ refreshAvailability(rec, config.id)
557
+ } finally {
558
+ void appendRunDuration(rec.workspacePath, rec.sessionId, Date.now() - startedAt)
559
+ const next = rec.queue.shift()
560
+ if (next) {
561
+ void runPrompt(config, rec, next.blocks)
562
+ } else {
563
+ setProcessing(rec, false)
564
+ }
565
+ }
566
+ }
567
+
568
+ export async function sendAcpMessage(
569
+ config: AcpProviderConfig,
570
+ input: {
571
+ workspaceId: string
572
+ workspacePath: string
573
+ agentId?: string
574
+ sessionId: string
575
+ isNew: boolean
576
+ content: string
577
+ attachments?: string[]
578
+ optimisticId?: string
579
+ model?: string
580
+ stream?: boolean
581
+ context?: MoiContext
582
+ }
583
+ ): Promise<void> {
584
+ const uploads = input.attachments?.length
585
+ ? resolveUploads(input.workspaceId, input.attachments)
586
+ : []
587
+ if (!input.content && uploads.length === 0) return
588
+ const { blocks, parts } = await buildPrompt(
589
+ input.content,
590
+ uploads,
591
+ config.supportsImages !== false
592
+ )
593
+ if (blocks.length === 0) return
594
+
595
+ // ACP has no native ambient-context channel, so the envelope rides in the
596
+ // text block. The backend persists that text verbatim and echoes it on
597
+ // `session/load`, so the replay side strips it back out (replayedUserParts
598
+ // via flushUserChunk) before the text reaches a bubble.
599
+ if (input.context) {
600
+ const envelope = renderMoiContext(input.context)
601
+ const first = blocks[0]
602
+ if (first?.type === 'text') first.text = appendMoiContext(first.text, envelope)
603
+ else blocks.unshift({ type: 'text', text: envelope })
604
+ }
605
+
606
+ let rec: SessionRecord
607
+ try {
608
+ if (input.isNew) {
609
+ const client = await getAcpClient(await config.spawn(input))
610
+ const created = await client.rpc<AcpNewSessionResult>('session/new', {
611
+ cwd: input.workspacePath,
612
+ mcpServers: []
613
+ })
614
+ const realId = created.sessionId
615
+ const model = input.model ?? created.models?.currentModelId
616
+ if (realId !== input.sessionId) {
617
+ aliases.set(recKey(input.workspaceId, input.sessionId), realId)
618
+ await renameSessionConfig(input.workspacePath, input.sessionId, realId)
619
+ await renameSelectedSession(input.workspacePath, input.sessionId, realId)
620
+ await renameViewBuilderSession(
621
+ input.workspaceId,
622
+ input.workspacePath,
623
+ input.sessionId,
624
+ realId
625
+ )
626
+ broadcast(input.workspaceId, { type: 'session_renamed', from: input.sessionId, to: realId })
627
+ }
628
+ rec = createRecord({
629
+ workspaceId: input.workspaceId,
630
+ workspacePath: input.workspacePath,
631
+ agentId: input.agentId,
632
+ sessionId: realId,
633
+ client,
634
+ config,
635
+ model
636
+ })
637
+ await applyNoPromptMode(client, config, realId)
638
+ if (input.model) await setSessionModel(config, rec, client, input.model)
639
+ if (input.model && !(await hasSessionConfig(input.workspacePath, realId))) {
640
+ await saveSessionConfig(input.workspacePath, realId, { model: input.model })
641
+ }
642
+ } else {
643
+ rec = await resumeSession(config, input)
644
+ if (input.model && input.model !== rec.model) {
645
+ const client = await getAcpClient(await config.spawn(input))
646
+ await setSessionModel(config, rec, client, input.model)
647
+ }
648
+ }
649
+ } catch (err) {
650
+ broadcast(input.workspaceId, { type: 'status', sessionId: input.sessionId, activity: 'idle' })
651
+ broadcast(input.workspaceId, {
652
+ kind: 'error',
653
+ sessionId: input.sessionId,
654
+ content: err instanceof Error ? err.message : `failed to start ${config.id} session`
655
+ })
656
+ refreshAvailability(
657
+ { workspaceId: input.workspaceId, workspacePath: input.workspacePath },
658
+ config.id
659
+ )
660
+ return
661
+ }
662
+
663
+ rec.stream = input.stream === true
664
+
665
+ // Broadcast the user's bubble immediately so every connected tab shows it.
666
+ // ACP never echoes the send back, so this turn is the only record of it —
667
+ // same as the Claude Code path.
668
+ const turnId = input.optimisticId ?? crypto.randomUUID()
669
+ emitTurnEvent(rec, {
670
+ kind: 'turn',
671
+ turn: {
672
+ id: turnId,
673
+ role: 'user',
674
+ origin: { kind: 'user-input' },
675
+ parts,
676
+ timestamp: new Date().toISOString()
677
+ }
678
+ })
679
+
680
+ // No steer in ACP: queue behind a running turn instead of racing it.
681
+ if (rec.processing) {
682
+ rec.queue.push({ blocks, turnId })
683
+ debug(`${config.id} queued send ws=${rec.workspaceId} session=${rec.sessionId}`)
684
+ return
685
+ }
686
+ await runPrompt(config, rec, blocks)
687
+ }
688
+
689
+ // Model switches rebuild the agent on some backends; providers that need a
690
+ // post-switch fixup (e.g. re-registering MCP servers) do it in their own
691
+ // folder by wrapping this.
692
+ async function setSessionModel(
693
+ config: AcpProviderConfig,
694
+ rec: SessionRecord,
695
+ client: AcpClient,
696
+ modelId: string
697
+ ): Promise<void> {
698
+ try {
699
+ await client.rpc('session/set_model', { sessionId: rec.sessionId, modelId })
700
+ rec.model = modelId
701
+ rec.acc.setModel(modelId)
702
+ } catch (err) {
703
+ debug(
704
+ `${config.id} set_model failed session=${rec.sessionId}: ${err instanceof Error ? err.message : err}`
705
+ )
706
+ }
707
+ }
708
+
709
+ export async function interruptAcpRun(
710
+ config: AcpProviderConfig,
711
+ input: { workspaceId: string; sessionId: string }
712
+ ): Promise<void> {
713
+ const rec = sessions.get(liveKey(input.workspaceId, input.sessionId))
714
+ if (!rec) return
715
+ // Drop anything queued behind the running turn — an interrupt means "stop",
716
+ // not "skip to the next message".
717
+ rec.queue.length = 0
718
+ try {
719
+ const client = await getAcpClient(
720
+ await config.spawn({
721
+ workspaceId: rec.workspaceId,
722
+ workspacePath: rec.workspacePath,
723
+ agentId: rec.agentId
724
+ })
725
+ )
726
+ // `session/cancel` is a notification: the in-flight `session/prompt`
727
+ // resolves with stopReason "cancelled", which is where the stop is
728
+ // broadcast from (runPrompt).
729
+ client.notify('session/cancel', { sessionId: rec.sessionId })
730
+ } catch (err) {
731
+ broadcast(rec.workspaceId, {
732
+ kind: 'error',
733
+ sessionId: rec.sessionId,
734
+ content: err instanceof Error ? err.message : 'interrupt failed'
735
+ })
736
+ throw err
737
+ }
738
+ }
739
+
740
+ export function viewAsEvents(rec: SessionRecord): StreamEvent[] {
741
+ const evs: StreamEvent[] = []
742
+ for (const turn of rec.view.turns) evs.push({ kind: 'turn', turn })
743
+ for (const notice of rec.view.notices) evs.push({ kind: 'notice', notice })
744
+ return evs
745
+ }
746
+
747
+ // Read-side hook for the REST events endpoint: return the live view when we
748
+ // hold one so REST + WS stay in agreement.
749
+ export function getLiveAcpEvents(workspaceId: string, sessionId: string): StreamEvent[] | null {
750
+ const rec = sessions.get(liveKey(workspaceId, sessionId))
751
+ return rec ? viewAsEvents(rec) : null
752
+ }
753
+
754
+ // Cold-load: resume the session (also subscribing it on our connection) and
755
+ // return its events, so subsequent WS frames upsert into the same view.
756
+ export async function ensureAcpSessionLive(
757
+ config: AcpProviderConfig,
758
+ input: AcpSpawnContext & { sessionId: string }
759
+ ): Promise<StreamEvent[]> {
760
+ const rec = await resumeSession(config, input)
761
+ return viewAsEvents(rec)
762
+ }
763
+
764
+ // Drop one live session record — used when a chat is archived, so its view and
765
+ // notification subscription go away instead of lingering for the process's life.
766
+ export function forgetAcpSession(workspaceId: string, sessionId: string): void {
767
+ const key = liveKey(workspaceId, sessionId)
768
+ const rec = sessions.get(key)
769
+ if (!rec) return
770
+ rec.unsubscribe?.()
771
+ sessions.delete(key)
772
+ }
773
+
774
+ // Drop every in-memory session for a workspace (its process is going away).
775
+ export function forgetAcpWorkspaceSessions(workspacePath: string): void {
776
+ for (const [key, rec] of sessions) {
777
+ if (rec.workspacePath !== workspacePath) continue
778
+ rec.unsubscribe?.()
779
+ sessions.delete(key)
780
+ }
781
+ }
782
+
783
+ export function forgetAllAcpSessions(): void {
784
+ for (const [key, rec] of sessions) {
785
+ rec.unsubscribe?.()
786
+ sessions.delete(key)
787
+ }
788
+ }