moi-computer 0.0.3 → 0.1.1

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 (216) hide show
  1. package/README.md +2 -2
  2. package/bunfig.toml +4 -0
  3. package/client/api/workspaces.ts +277 -6
  4. package/client/assets/mcp/agentation.png +0 -0
  5. package/client/assets/mcp/airtable.png +0 -0
  6. package/client/assets/mcp/apollo.png +0 -0
  7. package/client/assets/mcp/asana.png +0 -0
  8. package/client/assets/mcp/box.png +0 -0
  9. package/client/assets/mcp/chrome.svg +33 -0
  10. package/client/assets/mcp/clickup.png +0 -0
  11. package/client/assets/mcp/cloudflare.png +0 -0
  12. package/client/assets/mcp/context7.png +0 -0
  13. package/client/assets/mcp/datadog.png +0 -0
  14. package/client/assets/mcp/dropbox.png +0 -0
  15. package/client/assets/mcp/elevenlabs.png +0 -0
  16. package/client/assets/mcp/exa.png +0 -0
  17. package/client/assets/mcp/firecrawl.png +0 -0
  18. package/client/assets/mcp/gmail.png +0 -0
  19. package/client/assets/mcp/googlecalendar.png +0 -0
  20. package/client/assets/mcp/googledrive.png +0 -0
  21. package/client/assets/mcp/grafana.png +0 -0
  22. package/client/assets/mcp/huggingface.png +0 -0
  23. package/client/assets/mcp/intercom.png +0 -0
  24. package/client/assets/mcp/monday.png +0 -0
  25. package/client/assets/mcp/mongodb.png +0 -0
  26. package/client/assets/mcp/paper.png +0 -0
  27. package/client/assets/mcp/paypal.png +0 -0
  28. package/client/assets/mcp/perplexity.png +0 -0
  29. package/client/assets/mcp/postgresql.png +0 -0
  30. package/client/assets/mcp/posthog.png +0 -0
  31. package/client/assets/mcp/puppeteer.png +0 -0
  32. package/client/assets/mcp/railway.png +0 -0
  33. package/client/assets/mcp/redis.png +0 -0
  34. package/client/assets/mcp/salesforce.png +0 -0
  35. package/client/assets/mcp/shopify.png +0 -0
  36. package/client/assets/mcp/snowflake.png +0 -0
  37. package/client/assets/mcp/telegram.png +0 -0
  38. package/client/assets/mcp/twilio.png +0 -0
  39. package/client/assets/mcp/zapier.png +0 -0
  40. package/client/components/App.tsx +7 -1
  41. package/client/components/ChatInput.tsx +194 -13
  42. package/client/components/ChatPanel.tsx +116 -47
  43. package/client/components/ChatPopup.tsx +1 -1
  44. package/client/components/IconMcp.tsx +21 -0
  45. package/client/components/McpMenu.tsx +125 -0
  46. package/client/components/ModelPicker.tsx +147 -0
  47. package/client/components/Scratchpad.tsx +775 -0
  48. package/client/components/ShimmerText.tsx +20 -0
  49. package/client/components/ThreadSelector.tsx +2 -2
  50. package/client/components/TurnView.tsx +111 -531
  51. package/client/components/WidgetShell.tsx +1 -1
  52. package/client/components/WorkspacesPage.tsx +12 -4
  53. package/client/components/layout/SidebarLayout.tsx +18 -9
  54. package/client/components/playground/ToolCallsPage.tsx +81 -0
  55. package/client/components/routes/workspace/[id].tsx +534 -141
  56. package/client/components/routes/workspace/create.tsx +155 -0
  57. package/client/components/settings/IconPicker.tsx +590 -0
  58. package/client/components/settings/SettingsPages.tsx +307 -0
  59. package/client/components/settings/WorkspaceSettings.tsx +92 -0
  60. package/client/components/tool-group/CodeBlock.tsx +41 -0
  61. package/client/components/tool-group/Collapse.tsx +28 -0
  62. package/client/components/tool-group/ReadImagePreview.tsx +46 -0
  63. package/client/components/tool-group/SubagentCard.tsx +135 -0
  64. package/client/components/tool-group/TimelineRow.tsx +147 -0
  65. package/client/components/tool-group/ToolCallGroup.tsx +231 -0
  66. package/client/components/tool-group/ToolOutput.tsx +139 -0
  67. package/client/components/tool-group/detect.ts +93 -0
  68. package/client/components/tool-group/fixtures.ts +315 -0
  69. package/client/components/tool-group/format.ts +211 -0
  70. package/client/components/tool-group/index.ts +9 -0
  71. package/client/components/ui/dialog.tsx +58 -0
  72. package/client/components/ui/hover-card.tsx +44 -0
  73. package/client/components/ui/switch.tsx +23 -0
  74. package/client/components/ui/tooltip.tsx +54 -0
  75. package/client/externalize-react.ts +6 -0
  76. package/client/hooks/useApplet.ts +117 -0
  77. package/client/hooks/useChat.ts +162 -62
  78. package/client/hooks/useMeiEvents.ts +9 -2
  79. package/client/hooks/useStickToBottom.ts +86 -0
  80. package/client/hooks/useWorkspaceTheme.ts +8 -2
  81. package/client/index.css +48 -2
  82. package/client/index.html +9 -5
  83. package/client/index.tsx +29 -2
  84. package/client/lib/WorkspaceContext.tsx +5 -8
  85. package/client/lib/WorkspaceLayoutContext.tsx +30 -10
  86. package/client/lib/applet-cache.ts +54 -0
  87. package/client/lib/connection.ts +237 -0
  88. package/client/lib/flags.ts +10 -0
  89. package/client/lib/mcp-icons.ts +142 -10
  90. package/client/lib/preview-turn.ts +37 -0
  91. package/client/lib/render-icon.ts +173 -0
  92. package/client/lib/scratch-executor.ts +20 -0
  93. package/client/lib/uploads.ts +18 -0
  94. package/client/main.tsx +5 -0
  95. package/client/store/live.ts +282 -0
  96. package/client/structured-clone-shim.ts +14 -0
  97. package/client/theme.css +2 -2
  98. package/client/vendor/emojibase/en/data.json +1 -0
  99. package/client/vendor/emojibase/en/messages.json +1 -0
  100. package/client/vendor/react/development/_impl/react-dom-client.js +15871 -0
  101. package/client/vendor/react/development/_impl/react-dom.js +223 -0
  102. package/client/vendor/react/development/_impl/react-jsx-dev-runtime.js +256 -0
  103. package/client/vendor/react/development/_impl/react-jsx-runtime.js +260 -0
  104. package/client/vendor/react/development/_impl/react.js +863 -0
  105. package/client/vendor/react/development/react-dom-client.js +6 -0
  106. package/client/vendor/react/development/react-dom.js +17 -0
  107. package/client/vendor/react/development/react-jsx-dev-runtime.js +5 -0
  108. package/client/vendor/react/development/react-jsx-runtime.js +6 -0
  109. package/client/vendor/react/development/react.js +47 -0
  110. package/client/vendor/react/production/_impl/react-dom-client.js +10361 -0
  111. package/client/vendor/react/production/_impl/react-dom.js +184 -0
  112. package/client/vendor/react/production/_impl/react-jsx-dev-runtime.js +37 -0
  113. package/client/vendor/react/production/_impl/react-jsx-runtime.js +60 -0
  114. package/client/vendor/react/production/_impl/react.js +428 -0
  115. package/client/vendor/react/production/react-dom-client.js +6 -0
  116. package/client/vendor/react/production/react-dom.js +17 -0
  117. package/client/vendor/react/production/react-jsx-dev-runtime.js +5 -0
  118. package/client/vendor/react/production/react-jsx-runtime.js +6 -0
  119. package/client/vendor/react/production/react.js +47 -0
  120. package/dist/agentation-4s0nn45p.png +0 -0
  121. package/dist/airtable-hsa66v6q.png +0 -0
  122. package/dist/apollo-2ed5dy2d.png +0 -0
  123. package/dist/asana-tvgtwbx2.png +0 -0
  124. package/dist/box-w3n36t5g.png +0 -0
  125. package/dist/chrome-tspm94rw.svg +33 -0
  126. package/dist/chunk-kc6e9nd4.css +1 -0
  127. package/dist/chunk-yf3p7qg7.js +673 -0
  128. package/dist/clickup-qqrqqvqb.png +0 -0
  129. package/dist/cloudflare-j9p931v6.png +0 -0
  130. package/dist/context7-8ht0xjfy.png +0 -0
  131. package/dist/datadog-70ne3yzt.png +0 -0
  132. package/dist/dropbox-4m5s9mgr.png +0 -0
  133. package/dist/elevenlabs-2nzzej1t.png +0 -0
  134. package/dist/exa-qqj3vr0x.png +0 -0
  135. package/dist/firecrawl-w2t8nehx.png +0 -0
  136. package/dist/gmail-sg6a5v3x.png +0 -0
  137. package/dist/googlecalendar-nqhh2v7r.png +0 -0
  138. package/dist/googledrive-6s8xyab7.png +0 -0
  139. package/dist/grafana-1yfsnwr6.png +0 -0
  140. package/dist/huggingface-kxzaxj83.png +0 -0
  141. package/dist/index.html +10 -6
  142. package/dist/intercom-td763jt8.png +0 -0
  143. package/dist/monday-jdbs4wwf.png +0 -0
  144. package/dist/mongodb-emzxvhd5.png +0 -0
  145. package/dist/paper-zbt34fab.png +0 -0
  146. package/dist/paypal-kwwf7xsc.png +0 -0
  147. package/dist/perplexity-4y63rxvj.png +0 -0
  148. package/dist/postgresql-qsspbsr1.png +0 -0
  149. package/dist/posthog-sphppc4w.png +0 -0
  150. package/dist/puppeteer-2xjt1a9b.png +0 -0
  151. package/dist/railway-834de8d2.png +0 -0
  152. package/dist/redis-spm6w2m1.png +0 -0
  153. package/dist/salesforce-1mk56v4z.png +0 -0
  154. package/dist/shopify-90dadaav.png +0 -0
  155. package/dist/snowflake-hfpykpgy.png +0 -0
  156. package/dist/telegram-v6tjyrs7.png +0 -0
  157. package/dist/twilio-dpyjdwpj.png +0 -0
  158. package/dist/zapier-p67qfch0.png +0 -0
  159. package/lib/attachment-note.ts +48 -0
  160. package/lib/claude-adapter.ts +219 -29
  161. package/lib/format.ts +32 -0
  162. package/lib/types.ts +314 -6
  163. package/package.json +11 -5
  164. package/server/CLAUDE.md +4 -1
  165. package/server/agent.ts +25 -118
  166. package/server/api.ts +593 -0
  167. package/server/applets.ts +396 -0
  168. package/server/build-applet.ts +580 -0
  169. package/server/cc-session.ts +611 -0
  170. package/server/cli-colors.ts +17 -0
  171. package/server/cli-ui.ts +52 -0
  172. package/server/cli.ts +965 -73
  173. package/server/constants.ts +1 -1
  174. package/server/control.ts +166 -19
  175. package/server/debug.ts +10 -0
  176. package/server/events.ts +24 -0
  177. package/server/functions-worker.ts +18 -2
  178. package/server/functions.ts +59 -12
  179. package/server/icon.ts +13 -0
  180. package/server/layout.ts +25 -3
  181. package/server/mcp.ts +125 -0
  182. package/server/moi-scaffold.ts +85 -0
  183. package/server/openclaw-session.ts +41 -10
  184. package/server/openclaw.ts +22 -0
  185. package/server/preview.ts +70 -0
  186. package/server/registry.ts +32 -2
  187. package/server/scratchpad-executor.ts +380 -0
  188. package/server/scratchpad-relay.ts +45 -0
  189. package/server/scratchpad.ts +171 -0
  190. package/server/skill-version.ts +146 -0
  191. package/server/skills-template.ts +6 -1
  192. package/server/state.ts +22 -36
  193. package/server/static.ts +23 -0
  194. package/server/status.ts +94 -0
  195. package/server/thread-config.ts +125 -0
  196. package/server/uploads.ts +0 -0
  197. package/server/vendor.ts +63 -0
  198. package/server/views.ts +0 -0
  199. package/server/web.ts +108 -253
  200. package/server/widgets.ts +52 -142
  201. package/server/workspace-config.ts +37 -0
  202. package/server/workspace-env.ts +407 -0
  203. package/server/workspace-init.ts +66 -0
  204. package/workspace/.claude/skills/moi-workspace/DESIGN.md +109 -0
  205. package/workspace/.claude/skills/moi-workspace/SCRATCHPAD.md +57 -0
  206. package/workspace/.claude/skills/moi-workspace/SKILL.md +252 -0
  207. package/workspace/.claude/skills/moi-workspace/VIEW-DESIGN.md +22 -0
  208. package/client/hooks/useWidget.ts +0 -72
  209. package/client/hooks/useWidgetList.ts +0 -30
  210. package/client/lib/ws.ts +0 -129
  211. package/client/store/chat.tsx +0 -162
  212. package/dist/chunk-4615fa69.js +0 -67
  213. package/dist/chunk-582xmy05.css +0 -1
  214. package/server/build-widget.ts +0 -343
  215. package/workspace/.claude/skills/widgets/DESIGN.md +0 -630
  216. package/workspace/.claude/skills/widgets/SKILL.md +0 -176
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
package/dist/index.html CHANGED
@@ -5,19 +5,23 @@
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>moi.computer</title>
7
7
  <link rel="icon" type="image/png" href="/favicon-nbmyjfjh.png" />
8
+ <!-- React is vendored locally (client/vendor/react, generated by
9
+ scripts/build-vendor.ts) and served by the /vendor/react route, so Moi
10
+ runs fully offline — no CDN fetch. The server picks the development or
11
+ production build per environment behind these stable URLs. -->
8
12
  <script type="importmap">
9
13
  {
10
14
  "imports": {
11
- "react": "https://esm.sh/react@19?dev",
12
- "react/jsx-runtime": "https://esm.sh/react@19/jsx-runtime?dev",
13
- "react/jsx-dev-runtime": "https://esm.sh/react@19/jsx-dev-runtime?dev",
14
- "react-dom": "https://esm.sh/react-dom@19?dev",
15
- "react-dom/client": "https://esm.sh/react-dom@19/client?dev"
15
+ "react": "/vendor/react/react.js",
16
+ "react/jsx-runtime": "/vendor/react/react-jsx-runtime.js",
17
+ "react/jsx-dev-runtime": "/vendor/react/react-jsx-dev-runtime.js",
18
+ "react-dom": "/vendor/react/react-dom.js",
19
+ "react-dom/client": "/vendor/react/react-dom-client.js"
16
20
  }
17
21
  }
18
22
  </script>
19
23
 
20
- <link rel="stylesheet" crossorigin href="/chunk-582xmy05.css"><script type="module" crossorigin src="/chunk-4615fa69.js"></script></head>
24
+ <link rel="stylesheet" crossorigin href="/chunk-kc6e9nd4.css"><script type="module" crossorigin src="/chunk-yf3p7qg7.js"></script></head>
21
25
  <body>
22
26
  <div id="root"></div>
23
27
 
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,48 @@
1
+ // The file-path note appended to the agent-facing text when a message carries
2
+ // non-image attachments (the agent Reads them from a temp path — see
3
+ // dev/file-uploads.md). Shared between the senders (cc-session, openclaw) and
4
+ // the replay adapter: the SDK persists the appended text verbatim into the
5
+ // session `.jsonl`, so on cold reload the adapter strips the note back out and
6
+ // re-renders the files as chips — keeping the reloaded bubble identical to the
7
+ // live one instead of leaking temp paths into it.
8
+
9
+ export const ATTACHMENT_NOTE_HEADER =
10
+ 'The user attached the following file(s); read them as needed:'
11
+
12
+ // The stand-in prompt for a message that is *only* attachments (an Anthropic
13
+ // message must end with a non-empty text block). The adapter drops it on
14
+ // replay so the reloaded bubble shows just the attachments, like the live one.
15
+ export const ATTACHMENT_ONLY_PLACEHOLDER = '(see attached files)'
16
+
17
+ export type AttachmentNoteFile = { filename: string; path: string }
18
+
19
+ // `text` plus the note listing each attachment as `- <filename>: <path>`.
20
+ // Filenames are sanitized at upload time (no colons/newlines), so the line
21
+ // format is unambiguous for `splitAttachmentNote`.
22
+ export function appendAttachmentNote(text: string, files: AttachmentNoteFile[]): string {
23
+ if (files.length === 0) return text
24
+ const list = files.map(f => `- ${f.filename}: ${f.path}`).join('\n')
25
+ return `${text}\n\n${ATTACHMENT_NOTE_HEADER}\n${list}`.trim()
26
+ }
27
+
28
+ // Inverse of `appendAttachmentNote`. Returns the user's original text and the
29
+ // listed files; if the text carries no note (or the tail doesn't parse as one),
30
+ // it is returned untouched.
31
+ export function splitAttachmentNote(text: string): {
32
+ text: string
33
+ files: AttachmentNoteFile[]
34
+ } {
35
+ const idx = text.lastIndexOf(ATTACHMENT_NOTE_HEADER)
36
+ if (idx === -1) return { text, files: [] }
37
+ const files: AttachmentNoteFile[] = []
38
+ for (const raw of text.slice(idx + ATTACHMENT_NOTE_HEADER.length).split('\n')) {
39
+ const line = raw.trim()
40
+ if (!line) continue
41
+ const m = /^- (.+?): (.+)$/.exec(line)
42
+ // Any non-matching line means this isn't our note — leave the text as-is.
43
+ if (!m) return { text, files: [] }
44
+ files.push({ filename: m[1], path: m[2] })
45
+ }
46
+ if (files.length === 0) return { text, files: [] }
47
+ return { text: text.slice(0, idx).trimEnd(), files }
48
+ }
@@ -1,5 +1,7 @@
1
1
  import type {
2
+ AdapterEmit,
2
3
  Part,
4
+ PreviewBlock,
3
5
  ResultSummary,
4
6
  SessionSnapshot,
5
7
  StreamEvent,
@@ -8,9 +10,12 @@ import type {
8
10
  ToolCall,
9
11
  ToolCaller,
10
12
  Turn,
13
+ TurnMeta,
11
14
  TurnOrigin
12
15
  } from './format'
13
16
 
17
+ import { ATTACHMENT_ONLY_PLACEHOLDER, splitAttachmentNote } from './attachment-note'
18
+
14
19
  // Loose SDK message shape — we don't pull in the full SDK type tree; the
15
20
  // adapter tolerates missing fields. Reference: dev/sdk-message-spec.md.
16
21
  type ContentBlock = {
@@ -31,12 +36,33 @@ type ContentBlock = {
31
36
  media_type?: string
32
37
  filename?: string
33
38
  source_id?: string
39
+ // Image/document blocks carry their payload here (base64) or as a bare `url`.
40
+ source?: {
41
+ type?: string
42
+ media_type?: string
43
+ data?: string
44
+ url?: string
45
+ }
46
+ }
47
+
48
+ // A raw Anthropic Messages-API SSE event, as forwarded by the SDK's
49
+ // `stream_event` messages (only when `includePartialMessages` is on). Loosely
50
+ // typed — we read just the fields we render. `message.id` is present only on
51
+ // `message_start`; the block deltas carry `index` but no message id, so we
52
+ // track the active message per lane (see `currentMsgByParent`).
53
+ type RawStreamEvent = {
54
+ type?: string
55
+ message?: { id?: string }
56
+ index?: number
57
+ content_block?: { type?: string; text?: string; thinking?: string }
58
+ delta?: { type?: string; text?: string; thinking?: string }
34
59
  }
35
60
 
36
61
  type SdkMessage = {
37
62
  type: string
38
63
  subtype?: string
39
- message?: { role?: string; content?: unknown }
64
+ message?: { role?: string; content?: unknown; model?: string; id?: string }
65
+ event?: RawStreamEvent
40
66
  parent_tool_use_id?: string | null
41
67
  tool_use_id?: string
42
68
  isSynthetic?: boolean
@@ -125,6 +151,11 @@ function turnId(msg: SdkMessage): string {
125
151
  return `fallback:${Math.random().toString(36).slice(2)}`
126
152
  }
127
153
 
154
+ // Lane key for the top-level (non-subagent) assistant stream. Deltas carry no
155
+ // message id, so we key "which message is currently streaming" by lane —
156
+ // `parent_tool_use_id` for a subagent, this sentinel for the root.
157
+ const ROOT_LANE = '__root__'
158
+
128
159
  export class ClaudeAdapter {
129
160
  private turns: Turn[] = []
130
161
  // toolCallId → the Turn that contains the tool call + its position
@@ -132,10 +163,24 @@ export class ClaudeAdapter {
132
163
  // toolCallId of an Agent (subagent) tool_use → top-level Turn that owns it
133
164
  private subagentOwners = new Map<string, Turn>()
134
165
  private snapshot?: SessionSnapshot
135
- // Client-chosen id to use for the next matching user-input echo, so the
136
- // optimistic turn the client already rendered gets upserted instead of
137
- // duplicated. Cleared once consumed.
138
- private pendingUserEcho: { id: string; text: string } | null = null
166
+ // Client-chosen ids to use for matching user-input echoes, so optimistic
167
+ // turns the client already rendered get upserted instead of duplicated. A
168
+ // FIFO (not a single slot) because a streaming session can have several
169
+ // queued user messages in flight at once; each echo consumes its match.
170
+ private pendingUserEchoes: { id: string; text: string }[] = []
171
+
172
+ // --- live streaming previews (only when includePartialMessages is on) ------
173
+ // One accumulator PER message id (`msg_...`) so concurrent streams — parallel
174
+ // subagents, or a root message and a subagent's — never bleed into each other.
175
+ // Each holds the cumulative text of every open content block, keyed by index.
176
+ private previewBuffers = new Map<
177
+ string,
178
+ { parentToolUseId: string | null; blocks: Map<number, PreviewBlock> }
179
+ >()
180
+ // Which message id is currently streaming on each lane (root / per-subagent).
181
+ // Block deltas carry only `index`, no message id, so this routes them to the
182
+ // right buffer. Set on message_start, cleared on message_stop / finalize.
183
+ private currentMsgByLane = new Map<string, string>()
139
184
 
140
185
  /**
141
186
  * Tell the adapter that a user input with this text has already been
@@ -144,12 +189,19 @@ export class ClaudeAdapter {
144
189
  * `id` instead of the SDK's own uuid.
145
190
  */
146
191
  expectUserEcho(id: string, text: string) {
147
- this.pendingUserEcho = { id, text: text.trim() }
192
+ this.pendingUserEchoes.push({ id, text: text.trim() })
193
+ // Bound the queue so a stream of non-matching sends can't grow it forever.
194
+ if (this.pendingUserEchoes.length > 32) this.pendingUserEchoes.shift()
148
195
  }
149
196
 
150
- ingest(raw: unknown): StreamEvent[] {
197
+ ingest(raw: unknown): AdapterEmit[] {
151
198
  const msg = raw as SdkMessage
152
- const events: StreamEvent[] = []
199
+ const events: AdapterEmit[] = []
200
+
201
+ // --- stream_event → live preview (never persisted) --------------------
202
+ if (msg.type === 'stream_event') {
203
+ return this.ingestStreamEvent(msg)
204
+ }
153
205
 
154
206
  // --- system/init → SessionSnapshot ------------------------------------
155
207
  if (msg.type === 'system' && msg.subtype === 'init') {
@@ -208,6 +260,10 @@ export class ClaudeAdapter {
208
260
 
209
261
  // --- result -----------------------------------------------------------
210
262
  if (msg.type === 'result') {
263
+ // The turn is fully done; any live preview buffers left open are stale
264
+ // (each assistant message deletes its own on finalize — this is belt).
265
+ this.previewBuffers.clear()
266
+ this.currentMsgByLane.clear()
211
267
  const subtype = (msg.subtype ?? 'success') as ResultSummary['subtype']
212
268
  events.push({
213
269
  kind: 'result',
@@ -221,11 +277,91 @@ export class ClaudeAdapter {
221
277
  return events
222
278
  }
223
279
 
224
- // stream_event, tool_progress, tool_use_summary, auth_status,
225
- // prompt_suggestion — dropped for display-only mode.
280
+ // tool_progress, tool_use_summary, auth_status, prompt_suggestion —
281
+ // dropped for display-only mode.
226
282
  return events
227
283
  }
228
284
 
285
+ // -----------------------------------------------------------------------
286
+ // Live streaming previews (stream_event → StreamPreview)
287
+ // -----------------------------------------------------------------------
288
+
289
+ private ingestStreamEvent(msg: SdkMessage): AdapterEmit[] {
290
+ const ev = msg.event
291
+ if (!ev || typeof ev.type !== 'string') return []
292
+ const parent = msg.parent_tool_use_id ?? null
293
+ const lane = parent ?? ROOT_LANE
294
+
295
+ switch (ev.type) {
296
+ case 'message_start': {
297
+ const id = ev.message?.id
298
+ if (!id) return []
299
+ // A fresh message on this lane supersedes any prior unfinished one.
300
+ const stale = this.currentMsgByLane.get(lane)
301
+ if (stale && stale !== id) this.previewBuffers.delete(stale)
302
+ this.previewBuffers.set(id, { parentToolUseId: parent, blocks: new Map() })
303
+ this.currentMsgByLane.set(lane, id)
304
+ return []
305
+ }
306
+ case 'content_block_start': {
307
+ const cbType = ev.content_block?.type
308
+ const kind = cbType === 'thinking' ? 'reasoning' : cbType === 'text' ? 'text' : null
309
+ if (kind === null || typeof ev.index !== 'number') return []
310
+ const buf = this.currentBuffer(lane)
311
+ if (!buf) return []
312
+ const seed = kind === 'reasoning' ? ev.content_block?.thinking : ev.content_block?.text
313
+ buf.blocks.set(ev.index, { index: ev.index, kind, text: seed ?? '' })
314
+ return this.emitPreview(lane)
315
+ }
316
+ case 'content_block_delta': {
317
+ if (typeof ev.index !== 'number') return []
318
+ const d = ev.delta
319
+ let add: string | null = null
320
+ let kind: 'text' | 'reasoning' = 'text'
321
+ if (d?.type === 'text_delta' && typeof d.text === 'string') {
322
+ add = d.text
323
+ kind = 'text'
324
+ } else if (d?.type === 'thinking_delta' && typeof d.thinking === 'string') {
325
+ add = d.thinking
326
+ kind = 'reasoning'
327
+ }
328
+ // signature_delta / input_json_delta / unknown carry no visible text.
329
+ if (add === null) return []
330
+ const buf = this.currentBuffer(lane)
331
+ if (!buf) return []
332
+ const existing = buf.blocks.get(ev.index)
333
+ if (existing) existing.text += add
334
+ else buf.blocks.set(ev.index, { index: ev.index, kind, text: add })
335
+ return this.emitPreview(lane)
336
+ }
337
+ case 'message_stop': {
338
+ const id = this.currentMsgByLane.get(lane)
339
+ if (id) this.previewBuffers.delete(id)
340
+ this.currentMsgByLane.delete(lane)
341
+ return []
342
+ }
343
+ // content_block_stop, message_delta, ping — no visible text change.
344
+ default:
345
+ return []
346
+ }
347
+ }
348
+
349
+ private currentBuffer(lane: string) {
350
+ const id = this.currentMsgByLane.get(lane)
351
+ return id ? this.previewBuffers.get(id) : undefined
352
+ }
353
+
354
+ private emitPreview(lane: string): AdapterEmit[] {
355
+ const id = this.currentMsgByLane.get(lane)
356
+ if (!id) return []
357
+ const buf = this.previewBuffers.get(id)
358
+ if (!buf) return []
359
+ const blocks = [...buf.blocks.values()].sort((a, b) => a.index - b.index).map(b => ({ ...b }))
360
+ return [
361
+ { kind: 'preview', preview: { messageId: id, parentToolUseId: buf.parentToolUseId, blocks } }
362
+ ]
363
+ }
364
+
229
365
  // Returns the current snapshot + turns + notices + result as events — used
230
366
  // when a new client connects and needs to rebuild the view from scratch.
231
367
  hello(): StreamEvent[] {
@@ -241,6 +377,18 @@ export class ClaudeAdapter {
241
377
 
242
378
  private ingestConversationMessage(msg: SdkMessage): StreamEvent[] {
243
379
  const events: StreamEvent[] = []
380
+
381
+ // This message is now authoritative for its id — drop its live preview
382
+ // buffer so no trailing stream_event can re-emit stale text. The client
383
+ // clears the on-screen preview keyed by the same id when the turn lands.
384
+ if (msg.type === 'assistant' && msg.message?.id) {
385
+ const id = msg.message.id
386
+ this.previewBuffers.delete(id)
387
+ for (const [lane, mid] of this.currentMsgByLane) {
388
+ if (mid === id) this.currentMsgByLane.delete(lane)
389
+ }
390
+ }
391
+
244
392
  const blocks = contentAsArray(msg.message?.content)
245
393
  if (blocks.length === 0) return events
246
394
 
@@ -303,8 +451,33 @@ export class ClaudeAdapter {
303
451
  switch (b.type) {
304
452
  case 'text':
305
453
  if (b.text) {
306
- parts.push({ type: 'text', text: b.text })
307
- if (!firstText) firstText = b.text
454
+ let text = b.text
455
+ if (msg.type === 'user' && !msg.isSynthetic) {
456
+ // Non-image attachments reach the agent as a temp-path note
457
+ // appended to the user's text (see lib/attachment-note.ts). The
458
+ // SDK persists that appended text, so fold the note back into
459
+ // file chips here — a reloaded bubble matches the live one
460
+ // instead of leaking temp paths into it.
461
+ const split = splitAttachmentNote(text)
462
+ text = split.text
463
+ for (const f of split.files) {
464
+ parts.push({
465
+ type: 'file',
466
+ mediaType: 'application/octet-stream',
467
+ url: f.path,
468
+ filename: f.filename
469
+ })
470
+ }
471
+ // An attachment-only message carries a synthesized placeholder
472
+ // prompt; the bubble should show just the attachments.
473
+ if (text === ATTACHMENT_ONLY_PLACEHOLDER && parts.some(p => p.type === 'file')) {
474
+ text = ''
475
+ }
476
+ }
477
+ if (text) {
478
+ parts.push({ type: 'text', text })
479
+ if (!firstText) firstText = text
480
+ }
308
481
  }
309
482
  break
310
483
  case 'thinking':
@@ -336,16 +509,26 @@ export class ClaudeAdapter {
336
509
  }
337
510
  case 'file':
338
511
  case 'image':
339
- case 'document':
340
- if (b.url) {
341
- parts.push({
342
- type: 'file',
343
- mediaType: b.media_type ?? b.type,
344
- url: b.url,
345
- filename: b.filename
346
- })
512
+ case 'document': {
513
+ // A bare `url` (legacy) or an Anthropic source block: base64 → data
514
+ // URL so the persisted attachment re-renders on cold load, or a
515
+ // source `url` passed through as-is.
516
+ const src = b.source
517
+ let url = b.url
518
+ let mediaType = b.media_type ?? src?.media_type ?? b.type
519
+ if (!url && src) {
520
+ if (src.type === 'base64' && src.data && src.media_type) {
521
+ url = `data:${src.media_type};base64,${src.data}`
522
+ mediaType = src.media_type
523
+ } else if (src.url) {
524
+ url = src.url
525
+ }
526
+ }
527
+ if (url) {
528
+ parts.push({ type: 'file', mediaType, url, filename: b.filename })
347
529
  }
348
530
  break
531
+ }
349
532
  }
350
533
  }
351
534
 
@@ -381,23 +564,30 @@ export class ClaudeAdapter {
381
564
  // If this is the user echo of an optimistic send, reuse the client-chosen
382
565
  // id so the optimistic bubble upserts in place.
383
566
  let id = turnId(msg)
384
- if (
385
- role === 'user' &&
386
- origin.kind === 'user-input' &&
387
- this.pendingUserEcho &&
388
- firstText.trim() === this.pendingUserEcho.text
389
- ) {
390
- id = this.pendingUserEcho.id
391
- this.pendingUserEcho = null
567
+ if (role === 'user' && origin.kind === 'user-input') {
568
+ const text = firstText.trim()
569
+ const idx = this.pendingUserEchoes.findIndex(e => e.text === text)
570
+ if (idx >= 0) {
571
+ id = this.pendingUserEchoes[idx].id
572
+ this.pendingUserEchoes.splice(idx, 1)
573
+ }
392
574
  }
393
575
 
576
+ // The model that actually produced this turn (BetaMessage.model). Present
577
+ // on assistant messages; the most recent one is "the latest model used".
578
+ // `apiMessageId` lets the client reconcile a live preview against this turn.
579
+ const meta: TurnMeta = {}
580
+ if (msg.message?.model) meta.model = msg.message.model
581
+ if (msg.message?.id) meta.apiMessageId = msg.message.id
582
+
394
583
  return {
395
584
  id,
396
585
  role,
397
586
  origin,
398
587
  parentTaskId: msg.parent_tool_use_id ?? undefined,
399
588
  parts,
400
- timestamp: msg.timestamp
589
+ timestamp: msg.timestamp,
590
+ meta: Object.keys(meta).length > 0 ? meta : undefined
401
591
  }
402
592
  }
403
593
 
package/lib/format.ts CHANGED
@@ -74,6 +74,11 @@ export type TurnMeta = {
74
74
  provider?: string
75
75
  stopReason?: string
76
76
  usage?: { inputTokens?: number; outputTokens?: number; totalTokens?: number; costUsd?: number }
77
+ // The API message id (`msg_...`) that produced this assistant turn, when the
78
+ // backend reports one. NOT the Turn `id`. Used to reconcile a live streaming
79
+ // preview against its finalized turn — the client clears the preview keyed by
80
+ // this id the instant the real turn lands (see PreviewFrame).
81
+ apiMessageId?: string
77
82
  }
78
83
 
79
84
  export type Turn = {
@@ -165,12 +170,39 @@ export type ResultSummary = {
165
170
 
166
171
  // Stream events emitted by the adapter.
167
172
  // Semantics: upsert-by-id for `turn` and `snapshot`; append for `notice`; replace for `result`.
173
+ // This is the PERSISTED, replayable union — `getSessionEvents` reconstructs it
174
+ // from disk, so anything reconnect-healing trusts must be here. Live-only
175
+ // previews (below) are deliberately NOT part of it.
168
176
  export type StreamEvent =
169
177
  | { kind: 'snapshot'; snapshot: SessionSnapshot }
170
178
  | { kind: 'turn'; turn: Turn }
171
179
  | { kind: 'notice'; notice: SystemNotice }
172
180
  | { kind: 'result'; result: ResultSummary }
173
181
 
182
+ // One open content block within a live streaming message. `text` is the
183
+ // CUMULATIVE text so far (not a diff) — a preview is always a full snapshot, so
184
+ // a dropped or reordered frame is simply overwritten by the next one and can
185
+ // never desync into corrupted text.
186
+ export type PreviewBlock = { index: number; kind: 'text' | 'reasoning'; text: string }
187
+
188
+ // A live, token-by-token snapshot of an assistant message still being generated.
189
+ // Ephemeral and non-persisted: it never enters `StreamEvent`, never touches the
190
+ // durable transcript, and is discarded the moment the real `turn` lands. Keyed
191
+ // by `messageId` (the API `msg_...` id) so concurrent streams — e.g. parallel
192
+ // subagents — accumulate independently and never collide.
193
+ export type StreamPreview = {
194
+ messageId: string
195
+ // null = top-level assistant stream; a tool_use id = a subagent's nested
196
+ // stream. Routes the preview to the right UI slot; not part of its identity.
197
+ parentToolUseId: string | null
198
+ blocks: PreviewBlock[]
199
+ }
200
+
201
+ // What the adapter emits per ingested raw message: the persisted stream events,
202
+ // plus the live-only preview. Callers that persist/replay filter previews out;
203
+ // the live session layer forwards them as PreviewFrames over the socket.
204
+ export type AdapterEmit = StreamEvent | { kind: 'preview'; preview: StreamPreview }
205
+
174
206
  // Materialized view state the UI renders from.
175
207
  export type ViewState = {
176
208
  snapshot?: SessionSnapshot