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
@@ -0,0 +1,380 @@
1
+ import { basename } from 'path'
2
+ import sharp from 'sharp'
3
+
4
+ import {
5
+ type IndexKey,
6
+ type TLPageId,
7
+ type TLRecord,
8
+ type TLStore,
9
+ AssetRecordType,
10
+ ZERO_INDEX_KEY,
11
+ createBindingId,
12
+ createShapeId,
13
+ createTLStore,
14
+ defaultBindingUtils,
15
+ defaultShapeUtils,
16
+ getIndexAbove,
17
+ getSnapshot,
18
+ loadSnapshot,
19
+ toRichText
20
+ } from 'tldraw'
21
+
22
+ import type { ScratchImageQuality, ScratchOp, ScratchOpResult, ScratchStyle } from '@/lib/types'
23
+
24
+ import { publishEvent } from './events'
25
+ import { type ScratchpadDoc, loadScratchpadDoc, saveScratchpadDoc } from './scratchpad'
26
+
27
+ // Server-side Scratchpad writer. The browser is no longer required to draw: we run
28
+ // the same ops against a *headless* tldraw store here, persist the snapshot, and
29
+ // broadcast `scratchpad:updated` so any open tab reloads from disk. Only `view`
30
+ // (rendering pixels) still needs a live tab; `read` is served straight off disk.
31
+ // See docs/moi-scratchpad.md.
32
+ //
33
+ // We drive the store directly rather than an `Editor`, because the Editor needs a
34
+ // DOM + text measurement that don't exist in the server runtime. The store
35
+ // validates every `put`, so a malformed record throws instead of corrupting the
36
+ // file — that validation is what keeps hand-built records honest.
37
+
38
+ // Each shape type's default props, read once from its ShapeUtil. `getDefaultProps`
39
+ // is an instance method but doesn't touch the editor for the shapes we create, so a
40
+ // throwaway instance is enough; the result is static per type, so we cache it.
41
+ const shapeDefaults = new Map<string, Record<string, unknown>>()
42
+ function defaultProps(type: string): Record<string, unknown> {
43
+ let cached = shapeDefaults.get(type)
44
+ if (!cached) {
45
+ const Util = defaultShapeUtils.find(u => (u as unknown as { type: string }).type === type)
46
+ if (!Util) throw new Error(`Unknown shape type "${type}"`)
47
+ // eslint-disable-next-line new-cap -- Util is a class constructor pulled from a list
48
+ const util = new (Util as unknown as new (editor: unknown) => {
49
+ getDefaultProps(): Record<string, unknown>
50
+ })({})
51
+ cached = util.getDefaultProps()
52
+ shapeDefaults.set(type, cached)
53
+ }
54
+ return { ...cached }
55
+ }
56
+
57
+ // Map an op's optional color/size/fill onto tldraw shape props (omitted → tldraw default).
58
+ function styleProps(style: ScratchStyle): Record<string, unknown> {
59
+ return {
60
+ ...(style.color ? { color: style.color } : {}),
61
+ ...(style.size ? { size: style.size } : {}),
62
+ ...(style.fill ? { fill: style.fill } : {})
63
+ }
64
+ }
65
+
66
+ // A fresh headless store hydrated from the saved snapshot (or empty). The
67
+ // snapshot shape (`{ document }`) matches what the browser PUTs and loads.
68
+ function buildStore(doc: ScratchpadDoc | null): TLStore {
69
+ const store = createTLStore({ shapeUtils: defaultShapeUtils, bindingUtils: defaultBindingUtils })
70
+ if (doc?.store) {
71
+ loadSnapshot(store, { document: doc } as unknown as Parameters<typeof loadSnapshot>[1])
72
+ }
73
+ // Seed the document/page records a fresh (or partial) store needs to be valid.
74
+ store.ensureStoreIsUsable()
75
+ return store
76
+ }
77
+
78
+ function firstPageId(store: TLStore): TLPageId {
79
+ for (const record of store.allRecords()) {
80
+ if (record.typeName === 'page') return record.id
81
+ }
82
+ // ensureStoreIsUsable always leaves a page; this is unreachable in practice.
83
+ throw new Error('Scratchpad has no page')
84
+ }
85
+
86
+ // The next fractional index above every shape on the page, so a new shape lands on
87
+ // top. IndexKeys sort lexicographically, so a string max is a valid ordering.
88
+ function nextIndex(store: TLStore, pageId: TLPageId): IndexKey {
89
+ let max: IndexKey = ZERO_INDEX_KEY
90
+ for (const record of store.allRecords()) {
91
+ if (record.typeName === 'shape' && record.parentId === pageId && record.index > max) {
92
+ max = record.index
93
+ }
94
+ }
95
+ return getIndexAbove(max)
96
+ }
97
+
98
+ // Hand-build a shape record. TS can't correlate `type` with its matching props
99
+ // variant across the TLRecord union, so we assert — `store.put` validates the
100
+ // result at runtime, which is the real guarantee.
101
+ function shapeRecord(fields: {
102
+ id: ReturnType<typeof createShapeId>
103
+ type: string
104
+ x: number
105
+ y: number
106
+ index: IndexKey
107
+ parentId: TLPageId
108
+ props: Record<string, unknown>
109
+ }): TLRecord {
110
+ return {
111
+ typeName: 'shape',
112
+ rotation: 0,
113
+ isLocked: false,
114
+ opacity: 1,
115
+ meta: {},
116
+ ...fields
117
+ } as unknown as TLRecord
118
+ }
119
+
120
+ // Bind one arrow terminal to a target shape, so the arrow follows when it moves.
121
+ function arrowBinding(
122
+ arrowId: ReturnType<typeof createShapeId>,
123
+ targetId: ReturnType<typeof createShapeId>,
124
+ terminal: 'start' | 'end'
125
+ ): TLRecord {
126
+ return {
127
+ id: createBindingId(),
128
+ typeName: 'binding',
129
+ type: 'arrow',
130
+ fromId: arrowId,
131
+ toId: targetId,
132
+ meta: {},
133
+ props: {
134
+ terminal,
135
+ normalizedAnchor: { x: 0.5, y: 0.5 },
136
+ isPrecise: false,
137
+ isExact: false,
138
+ snap: 'none'
139
+ }
140
+ } as unknown as TLRecord
141
+ }
142
+
143
+ // Resize an image file to fit the canvas and embed it as a webp data URL, never
144
+ // enlarging — so a 10MB paste becomes a lightweight asset. `quality` picks the
145
+ // preset: 'lo' caps the long side smaller (default), 'hi' keeps more pixels.
146
+ // `.rotate()` bakes in EXIF orientation (phone photos).
147
+ const IMAGE_PRESETS: Record<ScratchImageQuality, { dim: number; quality: number }> = {
148
+ lo: { dim: 768, quality: 78 },
149
+ hi: { dim: 2048, quality: 88 }
150
+ }
151
+ const MAX_IMAGE_BYTES = 50 * 1024 * 1024
152
+
153
+ async function processCanvasImage(
154
+ path: string,
155
+ quality: ScratchImageQuality
156
+ ): Promise<{ src: string; w: number; h: number; mimeType: string; name: string }> {
157
+ const file = Bun.file(path)
158
+ if (!(await file.exists())) throw new Error(`Image file not found: ${path}`)
159
+ const bytes = new Uint8Array(await file.arrayBuffer())
160
+ if (bytes.length === 0) throw new Error(`Image file is empty: ${path}`)
161
+ if (bytes.length > MAX_IMAGE_BYTES) {
162
+ throw new Error(`Image is too large (${Math.round(bytes.length / 1e6)}MB, max 50MB): ${path}`)
163
+ }
164
+ const preset = IMAGE_PRESETS[quality]
165
+ const { data, info } = await sharp(bytes)
166
+ .rotate()
167
+ .resize(preset.dim, preset.dim, { fit: 'inside', withoutEnlargement: true })
168
+ .webp({ quality: preset.quality })
169
+ .toBuffer({ resolveWithObject: true })
170
+ return {
171
+ src: `data:image/webp;base64,${data.toString('base64')}`,
172
+ w: info.width,
173
+ h: info.height,
174
+ mimeType: 'image/webp',
175
+ name: basename(path)
176
+ }
177
+ }
178
+
179
+ // Create an image shape and its backing asset from a file. Async — unlike the
180
+ // other ops — because it decodes and resizes the image first.
181
+ async function applyAddImage(
182
+ store: TLStore,
183
+ op: Extract<ScratchOp, { kind: 'add-image' }>
184
+ ): Promise<ScratchOpResult> {
185
+ const pageId = firstPageId(store)
186
+ const { src, w, h, mimeType, name } = await processCanvasImage(op.path, op.quality ?? 'lo')
187
+ const assetId = AssetRecordType.createId()
188
+ store.put([
189
+ {
190
+ id: assetId,
191
+ typeName: 'asset',
192
+ type: 'image',
193
+ meta: {},
194
+ props: { name, src, w, h, mimeType, isAnimated: false }
195
+ } as unknown as TLRecord
196
+ ])
197
+ store.put([
198
+ shapeRecord({
199
+ id: createShapeId(op.name),
200
+ type: 'image',
201
+ x: op.x,
202
+ y: op.y,
203
+ index: nextIndex(store, pageId),
204
+ parentId: pageId,
205
+ props: { ...defaultProps('image'), w, h, assetId }
206
+ })
207
+ ])
208
+ return { name: op.name }
209
+ }
210
+
211
+ // Apply one mutating op to the store. `read` and `view` are handled elsewhere
212
+ // (disk / browser) and never reach here. Returns the op's result.
213
+ function applyOp(store: TLStore, op: ScratchOp): ScratchOpResult {
214
+ const pageId = firstPageId(store)
215
+ const requireShape = (name: string) => {
216
+ const shape = store.get(createShapeId(name))
217
+ if (!shape || shape.typeName !== 'shape') throw new Error(`No shape named "${name}"`)
218
+ return shape
219
+ }
220
+
221
+ switch (op.kind) {
222
+ case 'add-rect': {
223
+ store.put([
224
+ shapeRecord({
225
+ id: createShapeId(op.name),
226
+ type: 'geo',
227
+ x: op.x,
228
+ y: op.y,
229
+ index: nextIndex(store, pageId),
230
+ parentId: pageId,
231
+ props: {
232
+ ...defaultProps('geo'),
233
+ geo: 'rectangle',
234
+ w: op.w,
235
+ h: op.h,
236
+ ...styleProps(op),
237
+ ...(op.text ? { richText: toRichText(op.text) } : {})
238
+ }
239
+ })
240
+ ])
241
+ return { name: op.name }
242
+ }
243
+ case 'add-text': {
244
+ store.put([
245
+ shapeRecord({
246
+ id: createShapeId(op.name),
247
+ type: 'text',
248
+ x: op.x,
249
+ y: op.y,
250
+ index: nextIndex(store, pageId),
251
+ parentId: pageId,
252
+ props: { ...defaultProps('text'), richText: toRichText(op.text), ...styleProps(op) }
253
+ })
254
+ ])
255
+ return { name: op.name }
256
+ }
257
+ case 'add-note': {
258
+ store.put([
259
+ shapeRecord({
260
+ id: createShapeId(op.name),
261
+ type: 'note',
262
+ x: op.x,
263
+ y: op.y,
264
+ index: nextIndex(store, pageId),
265
+ parentId: pageId,
266
+ props: { ...defaultProps('note'), richText: toRichText(op.text), ...styleProps(op) }
267
+ })
268
+ ])
269
+ return { name: op.name }
270
+ }
271
+ case 'add-arrow': {
272
+ // Validate named endpoints up front — better a clear error than a dangling
273
+ // binding that corrupts the snapshot.
274
+ if ('name' in op.from) requireShape(op.from.name)
275
+ if ('name' in op.to) requireShape(op.to.name)
276
+ const arrowId = createShapeId(op.name)
277
+ // Point endpoints carry absolute coords; bound endpoints get placeholders the
278
+ // binding then drives. `elbow` routes with right angles; default is a curved arc.
279
+ store.put([
280
+ shapeRecord({
281
+ id: arrowId,
282
+ type: 'arrow',
283
+ x: 0,
284
+ y: 0,
285
+ index: nextIndex(store, pageId),
286
+ parentId: pageId,
287
+ props: {
288
+ ...defaultProps('arrow'),
289
+ ...styleProps(op),
290
+ ...(op.elbow ? { kind: 'elbow' } : {}),
291
+ start: 'name' in op.from ? { x: 0, y: 0 } : { x: op.from.x, y: op.from.y },
292
+ end: 'name' in op.to ? { x: 100, y: 0 } : { x: op.to.x, y: op.to.y }
293
+ }
294
+ })
295
+ ])
296
+ const bindings: TLRecord[] = []
297
+ if ('name' in op.from)
298
+ bindings.push(arrowBinding(arrowId, createShapeId(op.from.name), 'start'))
299
+ if ('name' in op.to) bindings.push(arrowBinding(arrowId, createShapeId(op.to.name), 'end'))
300
+ if (bindings.length > 0) store.put(bindings)
301
+ return { name: op.name }
302
+ }
303
+ case 'move': {
304
+ const shape = requireShape(op.name)
305
+ store.put([{ ...shape, x: op.x, y: op.y }])
306
+ return { ok: true }
307
+ }
308
+ case 'set': {
309
+ const shape = requireShape(op.name)
310
+ store.put([
311
+ { ...shape, props: { ...shape.props, richText: toRichText(op.text) } } as TLRecord
312
+ ])
313
+ return { ok: true }
314
+ }
315
+ case 'delete': {
316
+ const id = createShapeId(op.name)
317
+ // Remove the shape plus any binding that references it, or the leftover
318
+ // binding would dangle and invalidate the snapshot.
319
+ const ids = [id, ...bindingsTouching(store, op.name)]
320
+ store.remove(ids)
321
+ return { ok: true }
322
+ }
323
+ case 'clear': {
324
+ const ids = store
325
+ .allRecords()
326
+ .filter(r => r.typeName === 'shape' || r.typeName === 'binding')
327
+ .map(r => r.id)
328
+ if (ids.length > 0) store.remove(ids)
329
+ return { ok: true }
330
+ }
331
+ default:
332
+ // 'read' (disk) and 'view' (browser) are routed before this; anything else
333
+ // is an unknown op kind.
334
+ throw new Error(`Cannot execute op "${op.kind}" on the server`)
335
+ }
336
+ }
337
+
338
+ // Ids of bindings whose start/end is the named shape.
339
+ function bindingsTouching(store: TLStore, name: string): TLRecord['id'][] {
340
+ const target = createShapeId(name)
341
+ const ids: TLRecord['id'][] = []
342
+ for (const record of store.allRecords()) {
343
+ if (record.typeName !== 'binding') continue
344
+ const b = record as unknown as { fromId?: string; toId?: string }
345
+ if (b.fromId === target || b.toId === target) ids.push(record.id)
346
+ }
347
+ return ids
348
+ }
349
+
350
+ // Serialize writes per workspace so two concurrent ops can't load-load-save-save
351
+ // and lose one. Each op reads the latest disk snapshot, mutates, and writes back.
352
+ const chains = new Map<string, Promise<unknown>>()
353
+ function withLock<T>(key: string, fn: () => Promise<T>): Promise<T> {
354
+ const prev = (chains.get(key) ?? Promise.resolve()).catch(() => {})
355
+ const run = prev.then(fn)
356
+ chains.set(
357
+ key,
358
+ run.catch(() => {})
359
+ )
360
+ return run
361
+ }
362
+
363
+ // Execute a mutating Scratchpad op headlessly: load the snapshot, apply, persist,
364
+ // and notify open tabs to reload. No browser tab required.
365
+ export function executeScratchOp(
366
+ workspacePath: string,
367
+ workspaceId: string,
368
+ op: ScratchOp
369
+ ): Promise<ScratchOpResult> {
370
+ return withLock(workspacePath, async () => {
371
+ const { document } = await loadScratchpadDoc(workspacePath)
372
+ const store = buildStore(document)
373
+ // add-image decodes/resizes the file first, so it's the one async op.
374
+ const result = op.kind === 'add-image' ? await applyAddImage(store, op) : applyOp(store, op)
375
+ const next = getSnapshot(store).document as unknown as ScratchpadDoc
376
+ await saveScratchpadDoc(next, workspacePath)
377
+ publishEvent({ type: 'scratchpad:updated', workspaceId })
378
+ return result
379
+ })
380
+ }
@@ -0,0 +1,45 @@
1
+ import type { ScratchOp, ScratchOpResult } from '@/lib/types'
2
+
3
+ import { broadcastAll } from './state'
4
+
5
+ // Bridges `moi scratch` (control port) to a live tldraw editor in a browser tab.
6
+ // The control server runs in the same process as the app server, so it calls
7
+ // `relayScratchOp` directly: we broadcast the op over the app chat socket tagged
8
+ // with `workspaceId`, the tab showing that workspace's canvas runs it against
9
+ // tldraw, and replies with a `scratchpad:op-result` that settles our promise.
10
+
11
+ type Pending = {
12
+ resolve: (result: ScratchOpResult) => void
13
+ reject: (err: Error) => void
14
+ timer: ReturnType<typeof setTimeout>
15
+ }
16
+
17
+ const pendingOps = new Map<string, Pending>()
18
+ const RELAY_TIMEOUT_MS = 10_000
19
+
20
+ // Relay one op and await the first tab's reply. Rejects after a timeout when no
21
+ // tab answers — i.e. no tab is showing this workspace's Scratchpad. (Add ops
22
+ // must already carry a `name`, assigned by the caller, so execution is
23
+ // idempotent if more than one tab is open.)
24
+ export function relayScratchOp(workspaceId: string, op: ScratchOp): Promise<ScratchOpResult> {
25
+ const opId = crypto.randomUUID()
26
+ return new Promise<ScratchOpResult>((resolve, reject) => {
27
+ const timer = setTimeout(() => {
28
+ pendingOps.delete(opId)
29
+ reject(new Error('No live canvas — open the Scratchpad tab for this workspace.'))
30
+ }, RELAY_TIMEOUT_MS)
31
+ pendingOps.set(opId, { resolve, reject, timer })
32
+ broadcastAll({ type: 'scratchpad:op', workspaceId, opId, op })
33
+ })
34
+ }
35
+
36
+ // Settle a pending relay from a tab's reply. A second tab answering the same op
37
+ // (or any late/unknown reply) finds no entry and is ignored — first reply wins.
38
+ export function resolveScratchOp(opId: string, result?: ScratchOpResult, error?: string): void {
39
+ const pending = pendingOps.get(opId)
40
+ if (!pending) return
41
+ pendingOps.delete(opId)
42
+ clearTimeout(pending.timer)
43
+ if (error) pending.reject(new Error(error))
44
+ else pending.resolve(result ?? { ok: true })
45
+ }
@@ -0,0 +1,171 @@
1
+ import { join } from 'path'
2
+
3
+ // The Scratchpad is a shared tldraw canvas per workspace, persisted as a tldraw
4
+ // *document* snapshot here (the per-tab `session` is intentionally dropped). Two
5
+ // writers: the browser autosaves on user edits, and the server writes on agent
6
+ // draws (see scratchpad-executor.ts). This module owns the on-disk shape: load,
7
+ // save, and the `moi scratch read` parser. See docs/moi-scratchpad.md.
8
+
9
+ // A tldraw document snapshot: `getSnapshot(store).document`. Opaque to us apart
10
+ // from `.store` (the record map) which `read` walks. `null` means empty canvas.
11
+ export type ScratchpadDoc = { store?: Record<string, unknown>; schema?: unknown }
12
+ export type ScratchpadSnapshot = { document: ScratchpadDoc | null }
13
+
14
+ // One shape as surfaced by `moi scratch read` — a compact, agent-friendly view.
15
+ export type ScratchShape = {
16
+ id: string
17
+ type: string
18
+ x: number
19
+ y: number
20
+ w?: number
21
+ h?: number
22
+ text?: string
23
+ // Image/asset src. Base64 data URLs are omitted (see omitBase64) — the agent
24
+ // calls `moi scratch view` to actually see pixels; only the URL kind passes through.
25
+ src?: string
26
+ }
27
+
28
+ // The snapshot is a hidden dotfile (like `.moi/.workspace.json`): it's moi-internal
29
+ // state, and the agent must read it only through `moi scratch read`, never by
30
+ // opening the file.
31
+ export function getScratchpadPath(workspacePath: string): string {
32
+ return join(workspacePath, '.moi', '.scratchpad.json')
33
+ }
34
+
35
+ export async function loadScratchpadDoc(workspacePath: string): Promise<ScratchpadSnapshot> {
36
+ try {
37
+ const text = await Bun.file(getScratchpadPath(workspacePath)).text()
38
+ const parsed = JSON.parse(text)
39
+ if (parsed && typeof parsed === 'object' && parsed.document) {
40
+ return { document: parsed.document as ScratchpadDoc }
41
+ }
42
+ } catch {}
43
+ return { document: null }
44
+ }
45
+
46
+ export async function saveScratchpadDoc(
47
+ document: ScratchpadDoc,
48
+ workspacePath: string
49
+ ): Promise<void> {
50
+ await Bun.write(getScratchpadPath(workspacePath), JSON.stringify({ document }, null, 2))
51
+ }
52
+
53
+ // tldraw embeds pasted/dropped images as `data:<mime>;base64,<blob>` URLs (on
54
+ // asset records, and occasionally inline in rich text). Those blobs are huge and
55
+ // useless for reasoning about structure, so we replace each one with a short
56
+ // marker — the agent calls `moi scratch view` when it actually needs the pixels.
57
+ // Non-base64 srcs (e.g. https URLs) pass through untouched.
58
+ const BASE64_DATA_URL_RE = /data:[\w.+-]*\/?[\w.+-]*;base64,[A-Za-z0-9+/=]+/g
59
+ function omitBase64(text: string): string {
60
+ return text.replace(BASE64_DATA_URL_RE, 'base64:omitted')
61
+ }
62
+
63
+ // Pull readable text out of a shape's props. tldraw stores labels as `richText`
64
+ // (a ProseMirror-style doc) on most shapes; older/simple shapes may use a flat
65
+ // `text` string. Best-effort — never throw on an unexpected shape.
66
+ function extractText(props: unknown): string | undefined {
67
+ if (!props || typeof props !== 'object') return undefined
68
+ const p = props as { text?: unknown; richText?: unknown }
69
+ if (typeof p.text === 'string' && p.text.length > 0) return p.text
70
+ if (p.richText) {
71
+ const out: string[] = []
72
+ const walk = (node: unknown) => {
73
+ if (!node || typeof node !== 'object') return
74
+ const n = node as { type?: string; text?: unknown; content?: unknown }
75
+ if (n.type === 'text' && typeof n.text === 'string') out.push(n.text)
76
+ if (Array.isArray(n.content)) n.content.forEach(walk)
77
+ }
78
+ walk(p.richText)
79
+ const joined = out.join('').trim()
80
+ if (joined.length > 0) return joined
81
+ }
82
+ return undefined
83
+ }
84
+
85
+ // Resolve a single image shape's source by id, straight off the disk snapshot —
86
+ // no browser. The shape references an `asset` record by `props.assetId`; we return
87
+ // that asset's `src` (a `data:` URL for pasted/dropped images, or an `https:` URL).
88
+ // `moi scratch read` deliberately omits these blobs, so this is how the agent pulls
89
+ // the actual pixels for one image. Ids match with or without the `shape:` prefix
90
+ // (read surfaces them stripped).
91
+ export async function readScratchpadImage(
92
+ workspacePath: string,
93
+ id: string
94
+ ): Promise<{ src: string } | { error: string }> {
95
+ const { document } = await loadScratchpadDoc(workspacePath)
96
+ const store = document?.store
97
+ if (!store || typeof store !== 'object') return { error: `No shape named "${id}"` }
98
+
99
+ const target = id.replace(/^shape:/, '')
100
+ let assetId: string | undefined
101
+ let found = false
102
+ for (const record of Object.values(store)) {
103
+ if (!record || typeof record !== 'object') continue
104
+ const r = record as { typeName?: string; id?: string; props?: { assetId?: unknown } }
105
+ if (r.typeName !== 'shape' || (r.id ?? '').replace(/^shape:/, '') !== target) continue
106
+ found = true
107
+ if (typeof r.props?.assetId === 'string') assetId = r.props.assetId
108
+ break
109
+ }
110
+ if (!found) return { error: `No shape named "${id}"` }
111
+ if (!assetId) return { error: `Shape "${id}" is not an image` }
112
+
113
+ for (const record of Object.values(store)) {
114
+ if (!record || typeof record !== 'object') continue
115
+ const a = record as { typeName?: string; id?: string; props?: { src?: unknown } }
116
+ if (a.typeName === 'asset' && a.id === assetId && typeof a.props?.src === 'string') {
117
+ return { src: a.props.src }
118
+ }
119
+ }
120
+ return { error: `Image "${id}" has no stored data` }
121
+ }
122
+
123
+ // no browser needed. Ids are reported without tldraw's `shape:` prefix so they
124
+ // round-trip with `createShapeId(name)` on the draw side.
125
+ export async function readScratchpadShapes(workspacePath: string): Promise<ScratchShape[]> {
126
+ const { document } = await loadScratchpadDoc(workspacePath)
127
+ const store = document?.store
128
+ if (!store || typeof store !== 'object') return []
129
+
130
+ // Images live as `asset` records (typeName 'asset'); a shape references one by
131
+ // `props.assetId`. Index asset src first so we can surface it on the shape —
132
+ // with base64 blobs omitted — without dumping the asset record itself.
133
+ const assetSrc = new Map<string, string>()
134
+ for (const record of Object.values(store)) {
135
+ if (!record || typeof record !== 'object') continue
136
+ const a = record as { typeName?: string; id?: string; props?: { src?: unknown } }
137
+ if (a.typeName !== 'asset' || typeof a.id !== 'string') continue
138
+ if (typeof a.props?.src === 'string') assetSrc.set(a.id, a.props.src)
139
+ }
140
+
141
+ const shapes: ScratchShape[] = []
142
+ for (const record of Object.values(store)) {
143
+ if (!record || typeof record !== 'object') continue
144
+ const r = record as {
145
+ typeName?: string
146
+ id?: string
147
+ type?: string
148
+ x?: number
149
+ y?: number
150
+ props?: { w?: unknown; h?: unknown; assetId?: unknown }
151
+ }
152
+ if (r.typeName !== 'shape') continue
153
+ const w = typeof r.props?.w === 'number' ? r.props.w : undefined
154
+ const h = typeof r.props?.h === 'number' ? r.props.h : undefined
155
+ const rawSrc = typeof r.props?.assetId === 'string' ? assetSrc.get(r.props.assetId) : undefined
156
+ shapes.push({
157
+ id: (r.id ?? '').replace(/^shape:/, ''),
158
+ type: r.type ?? 'unknown',
159
+ x: typeof r.x === 'number' ? r.x : 0,
160
+ y: typeof r.y === 'number' ? r.y : 0,
161
+ ...(w !== undefined ? { w } : {}),
162
+ ...(h !== undefined ? { h } : {}),
163
+ ...(() => {
164
+ const text = extractText(r.props)
165
+ return text !== undefined ? { text: omitBase64(text) } : {}
166
+ })(),
167
+ ...(rawSrc !== undefined ? { src: omitBase64(rawSrc) } : {})
168
+ })
169
+ }
170
+ return shapes
171
+ }