moi-computer 0.2.0 → 0.3.0-next.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.
@@ -35,6 +35,7 @@ import {
35
35
  loadScratchpadDoc,
36
36
  saveScratchpadDoc
37
37
  } from './scratchpad'
38
+ import { storeScratchpadAsset } from './scratchpad-assets'
38
39
 
39
40
  // Server-side Scratchpad writer. The browser is no longer required to draw: we run
40
41
  // the same ops against a *headless* tldraw store here, persist the snapshot, and
@@ -173,10 +174,10 @@ function arrowBinding(
173
174
  } as unknown as TLRecord
174
175
  }
175
176
 
176
- // Resize an image file to fit the canvas and embed it as a webp data URL, never
177
- // enlarging — so a 10MB paste becomes a lightweight asset. `quality` picks the
178
- // preset: 'lo' caps the long side smaller (default), 'hi' keeps more pixels.
179
- // `.rotate()` bakes in EXIF orientation (phone photos).
177
+ // Resize an image file to fit the canvas, never enlarging — so a 10MB paste
178
+ // becomes a lightweight asset. `quality` picks the preset: 'lo' caps the long
179
+ // side smaller (default), 'hi' keeps more pixels. `.rotate()` bakes in EXIF
180
+ // orientation (phone photos).
180
181
  const IMAGE_PRESETS: Record<ScratchImageQuality, { dim: number; quality: number }> = {
181
182
  lo: { dim: 768, quality: 78 },
182
183
  hi: { dim: 2048, quality: 88 }
@@ -186,7 +187,7 @@ const MAX_IMAGE_BYTES = 50 * 1024 * 1024
186
187
  async function processCanvasImage(
187
188
  path: string,
188
189
  quality: ScratchImageQuality
189
- ): Promise<{ src: string; w: number; h: number; mimeType: string; name: string }> {
190
+ ): Promise<{ data: Buffer; w: number; h: number; mimeType: string; name: string }> {
190
191
  const file = Bun.file(path)
191
192
  if (!(await file.exists())) throw new Error(`Image file not found: ${path}`)
192
193
  const bytes = new Uint8Array(await file.arrayBuffer())
@@ -200,23 +201,27 @@ async function processCanvasImage(
200
201
  .resize(preset.dim, preset.dim, { fit: 'inside', withoutEnlargement: true })
201
202
  .webp({ quality: preset.quality })
202
203
  .toBuffer({ resolveWithObject: true })
203
- return {
204
- src: `data:image/webp;base64,${data.toString('base64')}`,
205
- w: info.width,
206
- h: info.height,
207
- mimeType: 'image/webp',
208
- name: basename(path)
209
- }
204
+ return { data, w: info.width, h: info.height, mimeType: 'image/webp', name: basename(path) }
210
205
  }
211
206
 
212
- // Create an image shape and its backing asset from a file. Async — unlike the
213
- // other ops — because it decodes and resizes the image first.
207
+ // Create an image shape and its backing asset from a file. The resized bytes go
208
+ // to `.moi/.scratchpad/` and the asset record holds the `asset:` file
209
+ // reference — never a base64 blob (see scratchpad-assets.ts). Async — unlike
210
+ // the other ops — because it decodes and resizes the image first.
214
211
  async function applyAddImage(
215
212
  store: TLStore,
213
+ workspacePath: string,
216
214
  op: Extract<ScratchOp, { kind: 'add-image' }>
217
215
  ): Promise<ScratchOpResult> {
218
216
  const pageId = firstPageId(store)
219
- const { src, w, h, mimeType, name } = await processCanvasImage(op.path, op.quality ?? 'lo')
217
+ // Re-adding under an existing id replaces that shape; note its current asset so
218
+ // we can drop it below once nothing else references it (else its file leaks).
219
+ const prev = store.get(createShapeId(op.name)) as unknown as
220
+ | { props?: { assetId?: unknown } }
221
+ | undefined
222
+ const prevAssetId = typeof prev?.props?.assetId === 'string' ? prev.props.assetId : undefined
223
+ const { data, w, h, mimeType, name } = await processCanvasImage(op.path, op.quality ?? 'lo')
224
+ const { src } = await storeScratchpadAsset(workspacePath, data, mimeType)
220
225
  const assetId = AssetRecordType.createId()
221
226
  store.put([
222
227
  {
@@ -238,6 +243,11 @@ async function applyAddImage(
238
243
  props: { ...defaultProps('image'), w, h, assetId }
239
244
  })
240
245
  ])
246
+ // The replaced shape's old asset is now unreachable — drop it so the sweep can
247
+ // reclaim its file.
248
+ if (prevAssetId && prevAssetId !== assetId && !anyShapeUsesAsset(store, prevAssetId)) {
249
+ store.remove([prevAssetId as unknown as TLRecord['id']])
250
+ }
241
251
  return { name: op.name }
242
252
  }
243
253
 
@@ -347,16 +357,25 @@ function applyOp(store: TLStore, op: ScratchOp): ScratchOpResult {
347
357
  }
348
358
  case 'delete': {
349
359
  const id = createShapeId(op.name)
360
+ const shape = store.get(id) as unknown as { props?: { assetId?: unknown } } | undefined
361
+ const assetId = typeof shape?.props?.assetId === 'string' ? shape.props.assetId : undefined
350
362
  // Remove the shape plus any binding that references it, or the leftover
351
363
  // binding would dangle and invalidate the snapshot.
352
364
  const ids = [id, ...bindingsTouching(store, op.name)]
353
365
  store.remove(ids)
366
+ // If that was the last shape using the image's asset, drop the asset record
367
+ // too so the post-save sweep can reclaim its file (mirrors `clear`).
368
+ if (assetId && !anyShapeUsesAsset(store, assetId)) {
369
+ store.remove([assetId as unknown as TLRecord['id']])
370
+ }
354
371
  return { ok: true }
355
372
  }
356
373
  case 'clear': {
374
+ // Assets go too — with every shape gone they're unreachable, and dropping
375
+ // the records lets the post-save sweep reclaim their files on disk.
357
376
  const ids = store
358
377
  .allRecords()
359
- .filter(r => r.typeName === 'shape' || r.typeName === 'binding')
378
+ .filter(r => r.typeName === 'shape' || r.typeName === 'binding' || r.typeName === 'asset')
360
379
  .map(r => r.id)
361
380
  if (ids.length > 0) store.remove(ids)
362
381
  return { ok: true }
@@ -368,6 +387,18 @@ function applyOp(store: TLStore, op: ScratchOp): ScratchOpResult {
368
387
  }
369
388
  }
370
389
 
390
+ // True if any shape still references the given asset id. tldraw lets several
391
+ // shapes share one asset (e.g. a duplicated image), so delete/replace only drops
392
+ // the asset record when its last user is gone — leaving the file for the sweep.
393
+ function anyShapeUsesAsset(store: TLStore, assetId: string): boolean {
394
+ for (const record of store.allRecords()) {
395
+ if (record.typeName !== 'shape') continue
396
+ const props = (record as unknown as { props?: { assetId?: unknown } }).props
397
+ if (props?.assetId === assetId) return true
398
+ }
399
+ return false
400
+ }
401
+
371
402
  // Ids of bindings whose start/end is the named shape.
372
403
  function bindingsTouching(store: TLStore, name: string): TLRecord['id'][] {
373
404
  const target = createShapeId(name)
@@ -404,7 +435,8 @@ export function executeScratchOp(
404
435
  const { document, writer } = await loadScratchpadDoc(workspacePath)
405
436
  const store = buildStore(document, writer)
406
437
  // add-image decodes/resizes the file first, so it's the one async op.
407
- const result = op.kind === 'add-image' ? await applyAddImage(store, op) : applyOp(store, op)
438
+ const result =
439
+ op.kind === 'add-image' ? await applyAddImage(store, workspacePath, op) : applyOp(store, op)
408
440
  const next = getSnapshot(store).document as unknown as ScratchpadDoc
409
441
  await saveScratchpadDoc(next, workspacePath)
410
442
  publishEvent({ type: 'scratchpad:updated', workspaceId })
@@ -5,12 +5,19 @@ import tldrawPkg from 'tldraw/package.json'
5
5
  import type { ScratchpadWriter } from '@/lib/types'
6
6
 
7
7
  import moiPkg from '../package.json'
8
+ import {
9
+ assetSrcFileName,
10
+ extractInlineAssets,
11
+ scratchpadAssetFile,
12
+ sweepOrphanAssets
13
+ } from './scratchpad-assets'
8
14
 
9
15
  // The Scratchpad is a shared tldraw canvas per workspace, persisted as a tldraw
10
16
  // *document* snapshot here (the per-tab `session` is intentionally dropped). Two
11
17
  // writers: the browser autosaves on user edits, and the server writes on agent
12
18
  // draws (see scratchpad-executor.ts). This module owns the on-disk shape: load,
13
- // save, and the `moi scratch read` parser. See docs/moi-scratchpad.md.
19
+ // save, and the `moi scratch read` parser. Image bytes live beside the snapshot
20
+ // as files, not inside it (see scratchpad-assets.ts). See docs/moi-scratchpad.md.
14
21
 
15
22
  // A tldraw document snapshot: `getSnapshot(store).document`. Opaque to us apart
16
23
  // from `.store` (the record map) which `read` walks. `null` means empty canvas.
@@ -36,9 +43,15 @@ export type ScratchShape = {
36
43
  w?: number
37
44
  h?: number
38
45
  text?: string
39
- // Image/asset src. Base64 data URLs are omitted (see omitBase64) — the agent
40
- // calls `moi scratch view` to actually see pixels; only the URL kind passes through.
46
+ // Image/asset src: an `asset:` file reference or an https URL, passed through
47
+ // as-is. A legacy inline base64 blob is omitted (see omitBase64) — the agent
48
+ // calls `moi scratch read-image`/`view` to actually see pixels.
41
49
  src?: string
50
+ // True when the shape references an asset that can't be resolved to pixels: an
51
+ // `asset:` file gone from .moi/.scratchpad (sidecar dir lost or pruned), or the
52
+ // asset record absent entirely — `read-image` will error and the canvas shows a
53
+ // broken image. Absent otherwise.
54
+ missing?: true
42
55
  }
43
56
 
44
57
  // The snapshot is a hidden dotfile (like `.moi/.workspace.json`): it's moi-internal
@@ -73,8 +86,17 @@ export async function saveScratchpadDoc(
73
86
  workspacePath: string
74
87
  ): Promise<void> {
75
88
  const path = getScratchpadPath(workspacePath)
89
+ // Every writer funnels through here, so this is where inline base64 assets
90
+ // (legacy snapshots, or a stale tab still holding blobs in its live store)
91
+ // get extracted to `.moi/.scratchpad/` files — the snapshot on disk
92
+ // never carries image bytes. The sweep after the write reclaims files the
93
+ // saved document no longer references (see scratchpad-assets.ts).
94
+ document = await extractInlineAssets(document, workspacePath)
76
95
  await backupOnSchemaChange(path, document)
77
96
  await Bun.write(path, JSON.stringify({ document, writer: SCRATCHPAD_WRITER }, null, 2))
97
+ // The `.bak` path keeps the sweep from orphaning the schema-change backup's
98
+ // images — a restored .bak should still render.
99
+ await sweepOrphanAssets(workspacePath, document, `${path}.bak`)
78
100
  }
79
101
 
80
102
  // When a save is about to overwrite a snapshot with a *different* schema (i.e.
@@ -91,11 +113,12 @@ async function backupOnSchemaChange(path: string, document: ScratchpadDoc): Prom
91
113
  } catch {}
92
114
  }
93
115
 
94
- // tldraw embeds pasted/dropped images as `data:<mime>;base64,<blob>` URLs (on
95
- // asset records, and occasionally inline in rich text). Those blobs are huge and
116
+ // Asset records now reference image bytes as `asset:` files (see
117
+ // scratchpad-assets.ts), but base64 data URLs can still appear — in a legacy
118
+ // snapshot not yet re-saved, or inline in rich text. Those blobs are huge and
96
119
  // useless for reasoning about structure, so we replace each one with a short
97
- // marker — the agent calls `moi scratch view` when it actually needs the pixels.
98
- // Non-base64 srcs (e.g. https URLs) pass through untouched.
120
+ // marker — the agent calls `moi scratch read-image`/`view` when it actually
121
+ // needs the pixels. Every other src (`asset:`, https) passes through untouched.
99
122
  const BASE64_DATA_URL_RE = /data:[\w.+-]*\/?[\w.+-]*;base64,[A-Za-z0-9+/=]+/g
100
123
  function omitBase64(text: string): string {
101
124
  return text.replace(BASE64_DATA_URL_RE, 'base64:omitted')
@@ -124,11 +147,13 @@ function extractText(props: unknown): string | undefined {
124
147
  }
125
148
 
126
149
  // Resolve a single image shape's source by id, straight off the disk snapshot —
127
- // no browser. The shape references an `asset` record by `props.assetId`; we return
128
- // that asset's `src` (a `data:` URL for pasted/dropped images, or an `https:` URL).
129
- // `moi scratch read` deliberately omits these blobs, so this is how the agent pulls
130
- // the actual pixels for one image. Ids match with or without the `shape:` prefix
131
- // (read surfaces them stripped).
150
+ // no browser. The shape references an `asset` record by `props.assetId`; that
151
+ // asset's `src` is an `asset:` file reference (read back off disk and returned
152
+ // as a `data:` URL so the CLI's decoding keeps working), an `https:` URL
153
+ // (returned as-is), or — in a legacy snapshot — an inline `data:` URL.
154
+ // `moi scratch read` never carries the pixels, so this is how the agent pulls
155
+ // them for one image. Ids match with or without the `shape:` prefix (read
156
+ // surfaces them stripped).
132
157
  export async function readScratchpadImage(
133
158
  workspacePath: string,
134
159
  id: string
@@ -155,7 +180,14 @@ export async function readScratchpadImage(
155
180
  if (!record || typeof record !== 'object') continue
156
181
  const a = record as { typeName?: string; id?: string; props?: { src?: unknown } }
157
182
  if (a.typeName === 'asset' && a.id === assetId && typeof a.props?.src === 'string') {
158
- return { src: a.props.src }
183
+ const fileName = assetSrcFileName(a.props.src)
184
+ if (!fileName) return { src: a.props.src }
185
+ const resolved = scratchpadAssetFile(workspacePath, fileName)
186
+ if (!resolved || !(await resolved.file.exists())) {
187
+ return { error: `Image "${id}" file is missing from .moi/.scratchpad` }
188
+ }
189
+ const bytes = Buffer.from(await resolved.file.arrayBuffer())
190
+ return { src: `data:${resolved.mimeType};base64,${bytes.toString('base64')}` }
159
191
  }
160
192
  }
161
193
  return { error: `Image "${id}" has no stored data` }
@@ -170,13 +202,23 @@ export async function readScratchpadShapes(workspacePath: string): Promise<Scrat
170
202
 
171
203
  // Images live as `asset` records (typeName 'asset'); a shape references one by
172
204
  // `props.assetId`. Index asset src first so we can surface it on the shape —
173
- // with base64 blobs omitted — without dumping the asset record itself.
205
+ // with base64 blobs omitted — without dumping the asset record itself. A
206
+ // file-backed src whose file is gone is flagged so the agent learns it's
207
+ // dangling from `read` instead of from a failing `read-image` later.
174
208
  const assetSrc = new Map<string, string>()
209
+ const assetGone = new Set<string>()
175
210
  for (const record of Object.values(store)) {
176
211
  if (!record || typeof record !== 'object') continue
177
212
  const a = record as { typeName?: string; id?: string; props?: { src?: unknown } }
178
213
  if (a.typeName !== 'asset' || typeof a.id !== 'string') continue
179
- if (typeof a.props?.src === 'string') assetSrc.set(a.id, a.props.src)
214
+ if (typeof a.props?.src === 'string') {
215
+ assetSrc.set(a.id, a.props.src)
216
+ const fileName = assetSrcFileName(a.props.src)
217
+ if (fileName) {
218
+ const resolved = scratchpadAssetFile(workspacePath, fileName)
219
+ if (!resolved || !(await resolved.file.exists())) assetGone.add(a.id)
220
+ }
221
+ }
180
222
  }
181
223
 
182
224
  const shapes: ScratchShape[] = []
@@ -193,7 +235,13 @@ export async function readScratchpadShapes(workspacePath: string): Promise<Scrat
193
235
  if (r.typeName !== 'shape') continue
194
236
  const w = typeof r.props?.w === 'number' ? r.props.w : undefined
195
237
  const h = typeof r.props?.h === 'number' ? r.props.h : undefined
196
- const rawSrc = typeof r.props?.assetId === 'string' ? assetSrc.get(r.props.assetId) : undefined
238
+ const assetId = typeof r.props?.assetId === 'string' ? r.props.assetId : undefined
239
+ const rawSrc = assetId !== undefined ? assetSrc.get(assetId) : undefined
240
+ // Flag `missing` when a shape references an asset we can't resolve to pixels:
241
+ // its backing file is gone (assetGone), or the asset record is absent / has a
242
+ // non-string src (rawSrc undefined). Either way `read-image` can't return
243
+ // bytes, so warn from `read` rather than let it fail later.
244
+ const missing = assetId !== undefined && (assetGone.has(assetId) || rawSrc === undefined)
197
245
  shapes.push({
198
246
  id: (r.id ?? '').replace(/^shape:/, ''),
199
247
  type: r.type ?? 'unknown',
@@ -205,7 +253,8 @@ export async function readScratchpadShapes(workspacePath: string): Promise<Scrat
205
253
  const text = extractText(r.props)
206
254
  return text !== undefined ? { text: omitBase64(text) } : {}
207
255
  })(),
208
- ...(rawSrc !== undefined ? { src: omitBase64(rawSrc) } : {})
256
+ ...(rawSrc !== undefined ? { src: omitBase64(rawSrc) } : {}),
257
+ ...(missing ? { missing: true as const } : {})
209
258
  })
210
259
  }
211
260
  return shapes
package/server/views.ts CHANGED
Binary file
package/server/widgets.ts CHANGED
@@ -158,7 +158,8 @@ export function serveWidget(
158
158
  name: string,
159
159
  file: string,
160
160
  workspacePath: string,
161
- apiBase: string
161
+ apiBase: string,
162
+ ifNoneMatch?: string | null
162
163
  ): Promise<Response> {
163
- return serveApplet('widget', name, file, workspacePath, apiBase)
164
+ return serveApplet('widget', name, file, workspacePath, apiBase, ifNoneMatch)
164
165
  }
@@ -12,9 +12,11 @@ tldraw's and shifts without notice, blobs are stripped, and `moi scratch read` a
12
12
  clean, agent-friendly view. Treat it exactly like `.moi/.workspace.json` — CLI only.
13
13
 
14
14
  - `moi scratch read` — dump the canvas as JSON: each shape's `id`, `type`, position, size, and
15
- text. Off disk, so it works whether or not a browser tab is open.
16
- - `moi scratch read-image <id>` — save one image shape to a file (its actual bytes; `read` omits
17
- the blob). Off disk too.
15
+ text. Off disk, so it works whether or not a browser tab is open. An image shape's `src` is a
16
+ reference (`asset:...` or a URL), never the pixels; `missing: true` on a shape means its image
17
+ file is gone, so don't bother calling `read-image` on it.
18
+ - `moi scratch read-image <id>` — save one image shape to a file (its actual bytes; `read` only
19
+ carries the reference). Off disk too.
18
20
  - `moi scratch view` — render the whole canvas to a PNG. Needs an open Scratchpad tab.
19
21
 
20
22
  `read` is for logic; `view` / `read-image` are for vision.
@@ -84,6 +84,7 @@ my-agent-folder/
84
84
  package.json <- Applet dependencies that you manage
85
85
  .workspace.json <- Auto-generated. Do NOT read, edit, or `cat` this file. Use Moi CLI instead.
86
86
  .scratchpad.json <- Scratchpad canvas snapshot. Internal — inspect only via `moi scratch read`, never open it.
87
+ .scratchpad/ <- Scratchpad image files. Internal — pull pixels via `moi scratch read-image`, never open it.
87
88
  ```
88
89
 
89
90
  # Build environment