moi-computer 0.2.0 → 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.
package/dist/index.html CHANGED
@@ -21,7 +21,7 @@
21
21
  }
22
22
  </script>
23
23
 
24
- <link rel="stylesheet" crossorigin href="/chunk-9mezmjpz.css"><script type="module" crossorigin src="/chunk-90bceh8y.js"></script></head>
24
+ <link rel="stylesheet" crossorigin href="/chunk-07qf2tv1.css"><script type="module" crossorigin src="/chunk-c3zjp9ez.js"></script></head>
25
25
  <body>
26
26
  <div id="root"></div>
27
27
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "moi-computer",
3
- "version": "0.2.0",
3
+ "version": "0.3.0-next.0",
4
4
  "description": "Local AI workspace powered by the Claude Agent SDK, Bun, React, and Tailwind. Requires Bun.",
5
5
  "license": "Elastic-2.0",
6
6
  "type": "module",
package/server/api.ts CHANGED
@@ -26,6 +26,7 @@ import {
26
26
  tildify
27
27
  } from './registry'
28
28
  import { loadScratchpadDoc, saveScratchpadDoc } from './scratchpad'
29
+ import { MAX_ASSET_BYTES, scratchpadAssetFile, storeScratchpadAsset } from './scratchpad-assets'
29
30
  import { DIST_DIR, prebuilt } from './static'
30
31
  import { getSessionEvents, getSessions } from './state'
31
32
  import { getThreadConfig, saveThreadConfig } from './thread-config'
@@ -389,6 +390,43 @@ one.put('/scratchpad', async c => {
389
390
  return c.body(null, 204)
390
391
  })
391
392
 
393
+ // Scratchpad assets: pasted/dropped image bytes live as content-addressed files
394
+ // in `.moi/.scratchpad/`, referenced from the snapshot by `asset:` srcs —
395
+ // never inlined as base64 in the JSON (see server/scratchpad-assets.ts). The
396
+ // browser's TLAssetStore POSTs the raw file here on paste and resolves `asset:`
397
+ // srcs back through the GET when rendering.
398
+ one.post('/scratchpad/assets', async c => {
399
+ const length = Number(c.req.header('content-length') ?? 0)
400
+ if (length > MAX_ASSET_BYTES) {
401
+ return c.text(`Asset too large (max ${MAX_ASSET_BYTES / (1024 * 1024)} MB)`, 413)
402
+ }
403
+ const bytes = new Uint8Array(await c.req.arrayBuffer())
404
+ if (bytes.length === 0) return c.text('Empty body', 400)
405
+ if (bytes.length > MAX_ASSET_BYTES) {
406
+ return c.text(`Asset too large (max ${MAX_ASSET_BYTES / (1024 * 1024)} MB)`, 413)
407
+ }
408
+ const mimeType = c.req.header('content-type') ?? 'application/octet-stream'
409
+ return c.json(await storeScratchpadAsset(c.get('ws').path, bytes, mimeType))
410
+ })
411
+
412
+ // The file name is content-addressed (sha256 of the bytes), so a hit is
413
+ // immutable — let the browser cache it indefinitely.
414
+ one.get('/scratchpad/assets/:file', async c => {
415
+ const resolved = scratchpadAssetFile(c.get('ws').path, c.req.param('file'))
416
+ if (!resolved || !(await resolved.file.exists())) return c.text('Not found', 404)
417
+ return new Response(resolved.file, {
418
+ headers: {
419
+ 'Content-Type': resolved.mimeType,
420
+ 'Cache-Control': 'public, max-age=31536000, immutable',
421
+ // Assets are only ever consumed via <img>/<video>/fetch (which all ignore
422
+ // this), so force a download on direct navigation and block MIME sniffing:
423
+ // a pasted/uploaded SVG must not execute as script in the app origin.
424
+ 'Content-Disposition': 'attachment',
425
+ 'X-Content-Type-Options': 'nosniff'
426
+ }
427
+ })
428
+ })
429
+
392
430
  // Workspace icon. PUT a raw image body (png/jpg/gif/webp) — the server resizes
393
431
  // it to a 128×128 transparent WebP and stores it as base64. DELETE resets to the
394
432
  // provider default. Both broadcast for a live refresh.
@@ -8,9 +8,12 @@
8
8
  // module is imported *first* in `cli.ts` so it runs before citty's module is
9
9
  // evaluated (citty computes its `noColor` flag once, at import time).
10
10
  //
11
- // picocolors (our own coloring) already auto-detects `isTTY`, so this only
12
- // closes citty's gap. `FORCE_COLOR` and an explicit `NO_COLOR` are honored: if
13
- // the user opted in or out of color, we leave their choice untouched.
11
+ // This only closes citty's gap. Our own coloring goes through `cli-pc.ts`,
12
+ // which computes enablement directly (picocolors' auto-detection enables color
13
+ // on `CI` even through a pipe, and Bun evaluates picocolors too early for this
14
+ // `NO_COLOR` mutation to reach it). `FORCE_COLOR` and an explicit `NO_COLOR`
15
+ // are honored: if the user opted in or out of color, we leave their choice
16
+ // untouched.
14
17
 
15
18
  if (!process.stdout.isTTY && !process.env.FORCE_COLOR && process.env.NO_COLOR == null) {
16
19
  process.env.NO_COLOR = '1'
package/server/cli-env.ts CHANGED
@@ -5,10 +5,9 @@
5
5
  // Secret VALUES never pass through here except on their way into a spawned
6
6
  // process (`execWithEnv`) or the secret store (`set` reads stdin/argv). Nothing
7
7
  // in this module prints a value.
8
- import pc from 'picocolors'
9
-
10
8
  import type { WorkspaceEntry, WorkspaceEnvView } from '@/lib/types'
11
9
 
10
+ import pc from './cli-pc'
12
11
  import { columns } from './cli-ui'
13
12
  import { CONTROL_PORT } from './constants'
14
13
  import { findWorkspaceForPath, listWorkspaces } from './registry'
@@ -0,0 +1,20 @@
1
+ // Our picocolors instance, with color-enablement we compute ourselves instead
2
+ // of trusting picocolors' auto-detection.
3
+ //
4
+ // picocolors decides `isColorSupported` once, at module-evaluation time, and
5
+ // enables color whenever `CI` is set — regardless of whether stdout is a TTY.
6
+ // That is wrong for us: `moi env` is captured through a pipe by agents and by
7
+ // CI test runners, which must see plain text. We also can't fix it by setting
8
+ // `NO_COLOR` first, because Bun evaluates picocolors early enough that the env
9
+ // mutation doesn't reach it (the `NO_COLOR` trick in `cli-colors.ts` only ever
10
+ // worked for citty, and locally only because the non-TTY path already disabled
11
+ // color when `CI` was absent).
12
+ //
13
+ // So we build colors explicitly: honor `NO_COLOR` / `FORCE_COLOR`, otherwise
14
+ // key off `isTTY` alone. Import this instead of `picocolors` anywhere the CLI
15
+ // colors its own output.
16
+ import { createColors } from 'picocolors'
17
+
18
+ const enabled = !process.env.NO_COLOR && (!!process.env.FORCE_COLOR || !!process.stdout.isTTY)
19
+
20
+ export default createColors(enabled)
package/server/cli.ts CHANGED
@@ -4,7 +4,7 @@ import { defineCommand, runMain, showUsage } from 'citty'
4
4
  import { existsSync, readFileSync } from 'node:fs'
5
5
  import { tmpdir } from 'node:os'
6
6
  import { join, resolve } from 'path'
7
- import pc from 'picocolors'
7
+ import pc from './cli-pc'
8
8
 
9
9
  import { COLOR_THEMES, FONT_THEMES } from '@/lib/themes'
10
10
  import type { ColorTheme, FontTheme } from '@/lib/themes'
@@ -1310,14 +1310,21 @@ const scratchView = defineCommand({
1310
1310
  }
1311
1311
  })
1312
1312
 
1313
- // Image data URL mime → file extension, for naming the saved file.
1313
+ // Image/video data URL mime → file extension, for naming the saved file. Kept in
1314
+ // sync with the server's MIME_EXT (scratchpad-assets.ts) so avif/apng/video assets
1315
+ // round-trip through `read-image` with a real extension instead of `.bin`.
1314
1316
  const IMAGE_EXT: Record<string, string> = {
1315
1317
  'image/png': 'png',
1316
1318
  'image/jpeg': 'jpg',
1317
1319
  'image/jpg': 'jpg',
1318
1320
  'image/webp': 'webp',
1319
1321
  'image/gif': 'gif',
1320
- 'image/svg+xml': 'svg'
1322
+ 'image/svg+xml': 'svg',
1323
+ 'image/avif': 'avif',
1324
+ 'image/apng': 'apng',
1325
+ 'video/mp4': 'mp4',
1326
+ 'video/webm': 'webm',
1327
+ 'video/quicktime': 'mov'
1321
1328
  }
1322
1329
 
1323
1330
  const scratchReadImage = defineCommand({
@@ -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
+ }
@@ -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 })