moi-computer 0.1.4 → 0.3.0-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 (40) hide show
  1. package/README.md +26 -52
  2. package/client/api/workspaces.ts +3 -5
  3. package/client/components/Scratchpad.tsx +169 -9
  4. package/client/components/layout/SidebarLayout.tsx +1 -12
  5. package/client/components/settings/SettingsPages.tsx +8 -60
  6. package/client/components/tool-group/fixtures.ts +60 -66
  7. package/client/hooks/useEnvVars.ts +20 -0
  8. package/client/hooks/useMeiEvents.ts +2 -0
  9. package/dist/chunk-07qf2tv1.css +1 -0
  10. package/dist/chunk-c3zjp9ez.js +672 -0
  11. package/dist/index.html +1 -1
  12. package/lib/scratchpad-skew.ts +64 -0
  13. package/lib/types.ts +5 -7
  14. package/package.json +3 -3
  15. package/server/api.ts +53 -54
  16. package/server/cc-session.ts +1 -1
  17. package/server/cli-colors.ts +6 -3
  18. package/server/cli-env.ts +237 -0
  19. package/server/cli-pc.ts +20 -0
  20. package/server/cli.ts +182 -3
  21. package/server/control.ts +11 -0
  22. package/server/data-dir.ts +9 -0
  23. package/server/env-apply.ts +16 -0
  24. package/server/functions-worker.ts +2 -0
  25. package/server/functions.ts +101 -3
  26. package/server/registry.ts +1 -2
  27. package/server/required-env.ts +19 -0
  28. package/server/scratchpad-assets.ts +223 -0
  29. package/server/scratchpad-executor.ts +88 -23
  30. package/server/scratchpad.ts +110 -20
  31. package/server/status.ts +54 -3
  32. package/server/thread-config.ts +2 -3
  33. package/server/vendor.ts +15 -8
  34. package/server/workspace-env.ts +69 -80
  35. package/workspace/.claude/skills/moi-workspace/SCRATCHPAD.md +5 -3
  36. package/workspace/.claude/skills/moi-workspace/SKILL.md +40 -6
  37. package/dist/chunk-kc6e9nd4.css +0 -1
  38. package/dist/chunk-yf3p7qg7.js +0 -673
  39. /package/client/{CLAUDE.md → AGENTS.md} +0 -0
  40. /package/server/{CLAUDE.md → AGENTS.md} +0 -0
@@ -0,0 +1,223 @@
1
+ import { readdir, rename, stat, unlink } from 'node:fs/promises'
2
+ import { join } from 'node:path'
3
+
4
+ import type { ScratchpadDoc } from './scratchpad'
5
+
6
+ // Scratchpad image/video bytes live as content-addressed files here, NOT as
7
+ // base64 data URLs inside `.moi/.scratchpad.json`. The snapshot is rewritten on
8
+ // every autosave (~500ms after each user edit) and shipped whole over GET/PUT,
9
+ // so a few pasted screenshots inlined as base64 would make every save and every
10
+ // tab reload carry megabytes of pixels. Instead an asset record's `src` is
11
+ // `asset:<sha256>.<ext>` — a tldraw-valid src protocol — pointing at a file in
12
+ // `.moi/.scratchpad/` (a hidden sidecar dir next to `.moi/.scratchpad.json`,
13
+ // moi-internal like the snapshot itself). The browser uploads/resolves through
14
+ // the `/scratchpad/assets` routes (see its TLAssetStore in Scratchpad.tsx); the
15
+ // server's `add image` writes files directly; `read-image` reads them back.
16
+ //
17
+ // Content addressing (the file name is the sha256 of the bytes) buys dedup —
18
+ // the same image pasted twice is one file — and makes every write idempotent,
19
+ // so re-extracting a stale tab's base64 PUT converges on the same file.
20
+
21
+ export function getScratchpadAssetsDir(workspacePath: string): string {
22
+ return join(workspacePath, '.moi', '.scratchpad')
23
+ }
24
+
25
+ // Matches executor-side MAX_IMAGE_BYTES — the most anyone can hand us.
26
+ export const MAX_ASSET_BYTES = 50 * 1024 * 1024
27
+
28
+ const ASSET_SRC_PREFIX = 'asset:'
29
+
30
+ // The only file names we ever create or serve: `asset-<sha256 hex>.<short ext>`.
31
+ // The `asset-` prefix marks the files as canvas assets, keeping the sidecar dir
32
+ // unambiguous if it ever holds anything else. Anything else (traversal attempts
33
+ // included) is rejected at the boundary. The core pattern is shared with the
34
+ // `.bak` scanner below (BAK_SRC_RE) so the two can never drift — a drift would
35
+ // let the sweep delete files the schema-change backup still references.
36
+ const ASSET_NAME_PATTERN = 'asset-[0-9a-f]{64}\\.[a-z0-9]{1,8}'
37
+ const ASSET_FILE_RE = new RegExp(`^${ASSET_NAME_PATTERN}$`)
38
+
39
+ const MIME_EXT: Record<string, string> = {
40
+ 'image/png': 'png',
41
+ 'image/jpeg': 'jpg',
42
+ 'image/webp': 'webp',
43
+ 'image/gif': 'gif',
44
+ 'image/svg+xml': 'svg',
45
+ 'image/avif': 'avif',
46
+ 'image/apng': 'apng',
47
+ 'video/mp4': 'mp4',
48
+ 'video/webm': 'webm',
49
+ 'video/quicktime': 'mov'
50
+ }
51
+ const EXT_MIME: Record<string, string> = Object.fromEntries(
52
+ Object.entries(MIME_EXT).map(([mime, ext]) => [ext, mime])
53
+ )
54
+
55
+ // The stored file name behind an `asset:` src, or null when the src is a
56
+ // different scheme (http, data) or malformed.
57
+ export function assetSrcFileName(src: string): string | null {
58
+ if (!src.startsWith(ASSET_SRC_PREFIX)) return null
59
+ const name = src.slice(ASSET_SRC_PREFIX.length)
60
+ return ASSET_FILE_RE.test(name) ? name : null
61
+ }
62
+
63
+ // A served asset file by (validated) name — the GET route and `read-image`
64
+ // resolve through this. Null for a name we'd never have written.
65
+ export function scratchpadAssetFile(
66
+ workspacePath: string,
67
+ fileName: string
68
+ ): { file: ReturnType<typeof Bun.file>; mimeType: string } | null {
69
+ if (!ASSET_FILE_RE.test(fileName)) return null
70
+ const ext = fileName.slice(fileName.lastIndexOf('.') + 1)
71
+ return {
72
+ file: Bun.file(join(getScratchpadAssetsDir(workspacePath), fileName)),
73
+ mimeType: EXT_MIME[ext] ?? 'application/octet-stream'
74
+ }
75
+ }
76
+
77
+ // Persist one asset's bytes and return the `asset:` src to store on the record.
78
+ // Idempotent: identical bytes land on the same file. (Bun.write creates the
79
+ // directory tree as needed.)
80
+ export async function storeScratchpadAsset(
81
+ workspacePath: string,
82
+ bytes: Uint8Array,
83
+ mimeType: string
84
+ ): Promise<{ src: string }> {
85
+ const hasher = new Bun.CryptoHasher('sha256')
86
+ hasher.update(bytes)
87
+ const ext = MIME_EXT[mimeType.split(';')[0].trim().toLowerCase()] ?? 'bin'
88
+ const fileName = `asset-${hasher.digest('hex')}.${ext}`
89
+ const dir = getScratchpadAssetsDir(workspacePath)
90
+ const path = join(dir, fileName)
91
+ // Content-addressed, so an existing file already holds these exact bytes.
92
+ // Write through a temp sibling + atomic rename: a crash or full disk mid-write
93
+ // must never leave a truncated file at `path`, whose name would then claim a
94
+ // hash its bytes don't match and be served forever by the exists() skip above.
95
+ if (!(await Bun.file(path).exists())) {
96
+ const tmp = join(dir, `.tmp-${crypto.randomUUID()}`)
97
+ await Bun.write(tmp, bytes)
98
+ await rename(tmp, path)
99
+ }
100
+ return { src: `${ASSET_SRC_PREFIX}${fileName}` }
101
+ }
102
+
103
+ // A base64 data URL on an asset record — the shape tldraw's default (inline)
104
+ // asset store produces, and what legacy snapshots hold.
105
+ const INLINE_SRC_RE = /^data:([\w.+-]+\/[\w.+-]+);base64,([A-Za-z0-9+/=]+)$/
106
+
107
+ // Rewrite every asset record whose src is an inline base64 data URL to an
108
+ // `asset:` file reference, writing the bytes out. This is the migration path
109
+ // for snapshots written before file-backed assets AND the safety net for a
110
+ // stale tab whose live store still holds base64 and PUTs it back — every
111
+ // writer funnels through saveScratchpadDoc, which calls this. Returns the same
112
+ // document when nothing needed rewriting; never throws on a malformed record
113
+ // (a bad asset is left as-is rather than blocking the save).
114
+ export async function extractInlineAssets(
115
+ document: ScratchpadDoc,
116
+ workspacePath: string
117
+ ): Promise<ScratchpadDoc> {
118
+ const store = document?.store
119
+ if (!store || typeof store !== 'object') return document
120
+
121
+ let rewritten: Record<string, unknown> | null = null
122
+ for (const [key, record] of Object.entries(store)) {
123
+ if (!record || typeof record !== 'object') continue
124
+ const r = record as { typeName?: string; props?: { src?: unknown } }
125
+ if (r.typeName !== 'asset' || typeof r.props?.src !== 'string') continue
126
+ const m = r.props.src.match(INLINE_SRC_RE)
127
+ if (!m) continue
128
+ try {
129
+ const bytes = new Uint8Array(Buffer.from(m[2], 'base64'))
130
+ if (bytes.length === 0) continue
131
+ const { src } = await storeScratchpadAsset(workspacePath, bytes, m[1])
132
+ // Records off getSnapshot may be frozen — replace, don't mutate.
133
+ rewritten ??= { ...store }
134
+ rewritten[key] = { ...r, props: { ...r.props, src } }
135
+ } catch {}
136
+ }
137
+ return rewritten ? { ...document, store: rewritten } : document
138
+ }
139
+
140
+ // A file is reclaimed only after it has stayed unreferenced for this long. The
141
+ // clock starts when the sweep FIRST observes the file unreferenced — NOT when
142
+ // the file was written — so every reference drop gets the same recovery window a
143
+ // fresh upload gets. (Keying on file mtime instead gave a long-referenced image
144
+ // zero grace the instant it went unreferenced — e.g. `clear` racing an open
145
+ // tab's pending autosave — letting the sweep permanently delete a file the
146
+ // surviving snapshot still pointed at.) The window covers the upload→autosave
147
+ // gap and a stale tab that re-PUTs an old, still-referencing document alike.
148
+ const SWEEP_GRACE_MS = 5 * 60_000
149
+
150
+ // When each still-unreferenced asset file was first seen unreferenced, keyed by
151
+ // absolute path. In-memory and per-process: a restart just restarts the clock
152
+ // (delaying cleanup, never losing data). Entries drop as soon as a file is
153
+ // referenced again or unlinked, so this only ever holds currently-unreferenced
154
+ // files within their grace window.
155
+ const firstUnreferencedAt = new Map<string, number>()
156
+
157
+ // Asset file names referenced by the schema-change backup (`.scratchpad.json.bak`
158
+ // — see backupOnSchemaChange in scratchpad.ts). The sweep must not eat those:
159
+ // the .bak is the manual escape hatch after a downgrade, and restoring it with
160
+ // its images gone would defeat the point. A raw regex scan (no JSON parse — the
161
+ // .bak may be a huge legacy file), cached by mtime since the file only changes
162
+ // on a schema upgrade. Built from the same ASSET_NAME_PATTERN as ASSET_FILE_RE.
163
+ const BAK_SRC_RE = new RegExp(`asset:(${ASSET_NAME_PATTERN})`, 'g')
164
+ const bakRefsCache = new Map<string, { mtimeMs: number; refs: Set<string> }>()
165
+ async function bakReferencedAssets(bakFile: string): Promise<Set<string>> {
166
+ try {
167
+ const { mtimeMs } = await stat(bakFile)
168
+ const cached = bakRefsCache.get(bakFile)
169
+ if (cached && cached.mtimeMs === mtimeMs) return cached.refs
170
+ const refs = new Set<string>()
171
+ for (const m of (await Bun.file(bakFile).text()).matchAll(BAK_SRC_RE)) refs.add(m[1])
172
+ bakRefsCache.set(bakFile, { mtimeMs, refs })
173
+ return refs
174
+ } catch {
175
+ return new Set()
176
+ }
177
+ }
178
+
179
+ // Delete asset files that neither the (just-saved) document nor the snapshot's
180
+ // `.bak` backup references. Runs after every save; best-effort — a sweep
181
+ // failure must never surface into the save.
182
+ export async function sweepOrphanAssets(
183
+ workspacePath: string,
184
+ document: ScratchpadDoc,
185
+ bakFile?: string,
186
+ now: number = Date.now()
187
+ ): Promise<void> {
188
+ try {
189
+ const dir = getScratchpadAssetsDir(workspacePath)
190
+ const files = await readdir(dir).catch(() => [] as string[])
191
+ if (files.length === 0) return
192
+
193
+ const referenced = new Set<string>()
194
+ for (const record of Object.values(document?.store ?? {})) {
195
+ if (!record || typeof record !== 'object') continue
196
+ const r = record as { typeName?: string; props?: { src?: unknown } }
197
+ if (r.typeName !== 'asset' || typeof r.props?.src !== 'string') continue
198
+ const name = assetSrcFileName(r.props.src)
199
+ if (name) referenced.add(name)
200
+ }
201
+ if (bakFile) for (const name of await bakReferencedAssets(bakFile)) referenced.add(name)
202
+
203
+ for (const name of files) {
204
+ if (!ASSET_FILE_RE.test(name)) continue
205
+ const path = join(dir, name)
206
+ if (referenced.has(name)) {
207
+ firstUnreferencedAt.delete(path) // referenced (again) — reset its clock
208
+ continue
209
+ }
210
+ const since = firstUnreferencedAt.get(path)
211
+ if (since === undefined) {
212
+ firstUnreferencedAt.set(path, now) // first seen unreferenced — start clock
213
+ continue
214
+ }
215
+ if (now - since > SWEEP_GRACE_MS) {
216
+ try {
217
+ await unlink(path)
218
+ firstUnreferencedAt.delete(path)
219
+ } catch {}
220
+ }
221
+ }
222
+ } catch {}
223
+ }
@@ -19,10 +19,23 @@ import {
19
19
  toRichText
20
20
  } from 'tldraw'
21
21
 
22
- import type { ScratchImageQuality, ScratchOp, ScratchOpResult, ScratchStyle } from '@/lib/types'
22
+ import { describeNewerWriter, sequencesAhead } from '@/lib/scratchpad-skew'
23
+ import type {
24
+ ScratchImageQuality,
25
+ ScratchOp,
26
+ ScratchOpResult,
27
+ ScratchStyle,
28
+ ScratchpadWriter
29
+ } from '@/lib/types'
23
30
 
24
31
  import { publishEvent } from './events'
25
- import { type ScratchpadDoc, loadScratchpadDoc, saveScratchpadDoc } from './scratchpad'
32
+ import {
33
+ SCRATCHPAD_WRITER,
34
+ type ScratchpadDoc,
35
+ loadScratchpadDoc,
36
+ saveScratchpadDoc
37
+ } from './scratchpad'
38
+ import { storeScratchpadAsset } from './scratchpad-assets'
26
39
 
27
40
  // Server-side Scratchpad writer. The browser is no longer required to draw: we run
28
41
  // the same ops against a *headless* tldraw store here, persist the snapshot, and
@@ -65,10 +78,31 @@ function styleProps(style: ScratchStyle): Record<string, unknown> {
65
78
 
66
79
  // A fresh headless store hydrated from the saved snapshot (or empty). The
67
80
  // snapshot shape (`{ document }`) matches what the browser PUTs and loads.
68
- function buildStore(doc: ScratchpadDoc | null): TLStore {
81
+ // A failed load is inspected for version skew: tldraw has no down-migrations,
82
+ // so a snapshot written by a newer tldraw is unreadable here — but intact.
83
+ // That gets a loud, actionable error instead of tldraw's bare `migration-error`
84
+ // (which surfaces verbatim through the control port to the `moi scratch` CLI).
85
+ function buildStore(doc: ScratchpadDoc | null, writer: ScratchpadWriter | undefined): TLStore {
69
86
  const store = createTLStore({ shapeUtils: defaultShapeUtils, bindingUtils: defaultBindingUtils })
70
87
  if (doc?.store) {
71
- loadSnapshot(store, { document: doc } as unknown as Parameters<typeof loadSnapshot>[1])
88
+ try {
89
+ loadSnapshot(store, { document: doc } as unknown as Parameters<typeof loadSnapshot>[1])
90
+ } catch (err) {
91
+ const ahead = sequencesAhead(doc.schema, store.schema.serialize().sequences)
92
+ if (ahead.length > 0) {
93
+ throw new Error(
94
+ `Scratchpad was written by a newer moi (${describeNewerWriter(writer, ahead)}); ` +
95
+ `this server has tldraw ${SCRATCHPAD_WRITER.tldraw}. Restart the newer server or ` +
96
+ `update this install (bun install -g moi-computer@latest). ` +
97
+ `The canvas file is intact — do not reset it.`
98
+ )
99
+ }
100
+ // Not skew — the snapshot itself is bad. Keep the original cause visible.
101
+ throw new Error(
102
+ `Scratchpad snapshot failed to load (not a version mismatch — the file may be ` +
103
+ `corrupted): ${err instanceof Error ? err.message : String(err)}`
104
+ )
105
+ }
72
106
  }
73
107
  // Seed the document/page records a fresh (or partial) store needs to be valid.
74
108
  store.ensureStoreIsUsable()
@@ -140,10 +174,10 @@ function arrowBinding(
140
174
  } as unknown as TLRecord
141
175
  }
142
176
 
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).
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).
147
181
  const IMAGE_PRESETS: Record<ScratchImageQuality, { dim: number; quality: number }> = {
148
182
  lo: { dim: 768, quality: 78 },
149
183
  hi: { dim: 2048, quality: 88 }
@@ -153,7 +187,7 @@ const MAX_IMAGE_BYTES = 50 * 1024 * 1024
153
187
  async function processCanvasImage(
154
188
  path: string,
155
189
  quality: ScratchImageQuality
156
- ): Promise<{ src: string; w: number; h: number; mimeType: string; name: string }> {
190
+ ): Promise<{ data: Buffer; w: number; h: number; mimeType: string; name: string }> {
157
191
  const file = Bun.file(path)
158
192
  if (!(await file.exists())) throw new Error(`Image file not found: ${path}`)
159
193
  const bytes = new Uint8Array(await file.arrayBuffer())
@@ -167,23 +201,27 @@ async function processCanvasImage(
167
201
  .resize(preset.dim, preset.dim, { fit: 'inside', withoutEnlargement: true })
168
202
  .webp({ quality: preset.quality })
169
203
  .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
- }
204
+ return { data, w: info.width, h: info.height, mimeType: 'image/webp', name: basename(path) }
177
205
  }
178
206
 
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.
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.
181
211
  async function applyAddImage(
182
212
  store: TLStore,
213
+ workspacePath: string,
183
214
  op: Extract<ScratchOp, { kind: 'add-image' }>
184
215
  ): Promise<ScratchOpResult> {
185
216
  const pageId = firstPageId(store)
186
- 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)
187
225
  const assetId = AssetRecordType.createId()
188
226
  store.put([
189
227
  {
@@ -205,6 +243,11 @@ async function applyAddImage(
205
243
  props: { ...defaultProps('image'), w, h, assetId }
206
244
  })
207
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
+ }
208
251
  return { name: op.name }
209
252
  }
210
253
 
@@ -314,16 +357,25 @@ function applyOp(store: TLStore, op: ScratchOp): ScratchOpResult {
314
357
  }
315
358
  case 'delete': {
316
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
317
362
  // Remove the shape plus any binding that references it, or the leftover
318
363
  // binding would dangle and invalidate the snapshot.
319
364
  const ids = [id, ...bindingsTouching(store, op.name)]
320
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
+ }
321
371
  return { ok: true }
322
372
  }
323
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.
324
376
  const ids = store
325
377
  .allRecords()
326
- .filter(r => r.typeName === 'shape' || r.typeName === 'binding')
378
+ .filter(r => r.typeName === 'shape' || r.typeName === 'binding' || r.typeName === 'asset')
327
379
  .map(r => r.id)
328
380
  if (ids.length > 0) store.remove(ids)
329
381
  return { ok: true }
@@ -335,6 +387,18 @@ function applyOp(store: TLStore, op: ScratchOp): ScratchOpResult {
335
387
  }
336
388
  }
337
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
+
338
402
  // Ids of bindings whose start/end is the named shape.
339
403
  function bindingsTouching(store: TLStore, name: string): TLRecord['id'][] {
340
404
  const target = createShapeId(name)
@@ -368,10 +432,11 @@ export function executeScratchOp(
368
432
  op: ScratchOp
369
433
  ): Promise<ScratchOpResult> {
370
434
  return withLock(workspacePath, async () => {
371
- const { document } = await loadScratchpadDoc(workspacePath)
372
- const store = buildStore(document)
435
+ const { document, writer } = await loadScratchpadDoc(workspacePath)
436
+ const store = buildStore(document, writer)
373
437
  // 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)
438
+ const result =
439
+ op.kind === 'add-image' ? await applyAddImage(store, workspacePath, op) : applyOp(store, op)
375
440
  const next = getSnapshot(store).document as unknown as ScratchpadDoc
376
441
  await saveScratchpadDoc(next, workspacePath)
377
442
  publishEvent({ type: 'scratchpad:updated', workspaceId })
@@ -1,15 +1,38 @@
1
1
  import { join } from 'path'
2
2
 
3
+ import tldrawPkg from 'tldraw/package.json'
4
+
5
+ import type { ScratchpadWriter } from '@/lib/types'
6
+
7
+ import moiPkg from '../package.json'
8
+ import {
9
+ assetSrcFileName,
10
+ extractInlineAssets,
11
+ scratchpadAssetFile,
12
+ sweepOrphanAssets
13
+ } from './scratchpad-assets'
14
+
3
15
  // The Scratchpad is a shared tldraw canvas per workspace, persisted as a tldraw
4
16
  // *document* snapshot here (the per-tab `session` is intentionally dropped). Two
5
17
  // writers: the browser autosaves on user edits, and the server writes on agent
6
18
  // 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.
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.
8
21
 
9
22
  // A tldraw document snapshot: `getSnapshot(store).document`. Opaque to us apart
10
23
  // from `.store` (the record map) which `read` walks. `null` means empty canvas.
11
24
  export type ScratchpadDoc = { store?: Record<string, unknown>; schema?: unknown }
12
- export type ScratchpadSnapshot = { document: ScratchpadDoc | null }
25
+ export type ScratchpadSnapshot = { document: ScratchpadDoc | null; writer?: ScratchpadWriter }
26
+
27
+ // This process's identity as a snapshot writer. The tldraw version is what
28
+ // matters for compatibility (the snapshot embeds its schema); the moi version is
29
+ // what a user can actually act on ("update moi"). Both resolve from this
30
+ // install's own package.json files, so they're correct in the repo-source and
31
+ // installed layouts alike.
32
+ export const SCRATCHPAD_WRITER: ScratchpadWriter = {
33
+ moi: moiPkg.version,
34
+ tldraw: tldrawPkg.version
35
+ }
13
36
 
14
37
  // One shape as surfaced by `moi scratch read` — a compact, agent-friendly view.
15
38
  export type ScratchShape = {
@@ -20,9 +43,15 @@ export type ScratchShape = {
20
43
  w?: number
21
44
  h?: number
22
45
  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.
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.
25
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
26
55
  }
27
56
 
28
57
  // The snapshot is a hidden dotfile (like `.moi/.workspace.json`): it's moi-internal
@@ -32,12 +61,21 @@ export function getScratchpadPath(workspacePath: string): string {
32
61
  return join(workspacePath, '.moi', '.scratchpad.json')
33
62
  }
34
63
 
64
+ // The writer stamp is trusted only off disk — we wrote it (saveScratchpadDoc
65
+ // stamps every save); a client PUT body never carries one through.
66
+ function parseWriter(value: unknown): ScratchpadWriter | undefined {
67
+ if (!value || typeof value !== 'object') return undefined
68
+ const w = value as { moi?: unknown; tldraw?: unknown }
69
+ if (typeof w.moi !== 'string' || typeof w.tldraw !== 'string') return undefined
70
+ return { moi: w.moi, tldraw: w.tldraw }
71
+ }
72
+
35
73
  export async function loadScratchpadDoc(workspacePath: string): Promise<ScratchpadSnapshot> {
36
74
  try {
37
75
  const text = await Bun.file(getScratchpadPath(workspacePath)).text()
38
76
  const parsed = JSON.parse(text)
39
77
  if (parsed && typeof parsed === 'object' && parsed.document) {
40
- return { document: parsed.document as ScratchpadDoc }
78
+ return { document: parsed.document as ScratchpadDoc, writer: parseWriter(parsed.writer) }
41
79
  }
42
80
  } catch {}
43
81
  return { document: null }
@@ -47,14 +85,40 @@ export async function saveScratchpadDoc(
47
85
  document: ScratchpadDoc,
48
86
  workspacePath: string
49
87
  ): Promise<void> {
50
- await Bun.write(getScratchpadPath(workspacePath), JSON.stringify({ document }, null, 2))
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)
95
+ await backupOnSchemaChange(path, document)
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`)
100
+ }
101
+
102
+ // When a save is about to overwrite a snapshot with a *different* schema (i.e.
103
+ // the first write after a tldraw upgrade), keep the old file as `.bak` — the
104
+ // manual escape hatch after a downgrade, since the new file won't open in the
105
+ // older tldraw. One .bak, replaced on each schema change. Best-effort: a backup
106
+ // failure must never block the save.
107
+ async function backupOnSchemaChange(path: string, document: ScratchpadDoc): Promise<void> {
108
+ try {
109
+ const existing = JSON.parse(await Bun.file(path).text()) as { document?: ScratchpadDoc }
110
+ const oldSchema = existing?.document?.schema
111
+ if (!oldSchema || JSON.stringify(oldSchema) === JSON.stringify(document.schema)) return
112
+ await Bun.write(`${path}.bak`, Bun.file(path))
113
+ } catch {}
51
114
  }
52
115
 
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
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
55
119
  // 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.
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.
58
122
  const BASE64_DATA_URL_RE = /data:[\w.+-]*\/?[\w.+-]*;base64,[A-Za-z0-9+/=]+/g
59
123
  function omitBase64(text: string): string {
60
124
  return text.replace(BASE64_DATA_URL_RE, 'base64:omitted')
@@ -83,11 +147,13 @@ function extractText(props: unknown): string | undefined {
83
147
  }
84
148
 
85
149
  // 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).
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).
91
157
  export async function readScratchpadImage(
92
158
  workspacePath: string,
93
159
  id: string
@@ -114,7 +180,14 @@ export async function readScratchpadImage(
114
180
  if (!record || typeof record !== 'object') continue
115
181
  const a = record as { typeName?: string; id?: string; props?: { src?: unknown } }
116
182
  if (a.typeName === 'asset' && a.id === assetId && typeof a.props?.src === 'string') {
117
- 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')}` }
118
191
  }
119
192
  }
120
193
  return { error: `Image "${id}" has no stored data` }
@@ -129,13 +202,23 @@ export async function readScratchpadShapes(workspacePath: string): Promise<Scrat
129
202
 
130
203
  // Images live as `asset` records (typeName 'asset'); a shape references one by
131
204
  // `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.
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.
133
208
  const assetSrc = new Map<string, string>()
209
+ const assetGone = new Set<string>()
134
210
  for (const record of Object.values(store)) {
135
211
  if (!record || typeof record !== 'object') continue
136
212
  const a = record as { typeName?: string; id?: string; props?: { src?: unknown } }
137
213
  if (a.typeName !== 'asset' || typeof a.id !== 'string') continue
138
- 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
+ }
139
222
  }
140
223
 
141
224
  const shapes: ScratchShape[] = []
@@ -152,7 +235,13 @@ export async function readScratchpadShapes(workspacePath: string): Promise<Scrat
152
235
  if (r.typeName !== 'shape') continue
153
236
  const w = typeof r.props?.w === 'number' ? r.props.w : undefined
154
237
  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
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)
156
245
  shapes.push({
157
246
  id: (r.id ?? '').replace(/^shape:/, ''),
158
247
  type: r.type ?? 'unknown',
@@ -164,7 +253,8 @@ export async function readScratchpadShapes(workspacePath: string): Promise<Scrat
164
253
  const text = extractText(r.props)
165
254
  return text !== undefined ? { text: omitBase64(text) } : {}
166
255
  })(),
167
- ...(rawSrc !== undefined ? { src: omitBase64(rawSrc) } : {})
256
+ ...(rawSrc !== undefined ? { src: omitBase64(rawSrc) } : {}),
257
+ ...(missing ? { missing: true as const } : {})
168
258
  })
169
259
  }
170
260
  return shapes