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.
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-w18801vn.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.1",
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'
@@ -103,7 +104,7 @@ one.get('/widgets/*', c => {
103
104
  const id = c.req.param('id')
104
105
  const { name, file } = parseAppletTail(c.req.url, id, 'widgets')
105
106
  if (!name) return c.text('Not found', 404)
106
- return serveWidget(name, file, c.get('ws').path, apiBaseFor(id))
107
+ return serveWidget(name, file, c.get('ws').path, apiBaseFor(id), c.req.header('if-none-match'))
107
108
  })
108
109
 
109
110
  // Views — full-screen agent apps. Mirrors the widget pair above: the exact path
@@ -114,7 +115,7 @@ one.get('/views/*', c => {
114
115
  const id = c.req.param('id')
115
116
  const { name, file } = parseAppletTail(c.req.url, id, 'views')
116
117
  if (!name) return c.text('Not found', 404)
117
- return serveView(name, file, c.get('ws').path, apiBaseFor(id))
118
+ return serveView(name, file, c.get('ws').path, apiBaseFor(id), c.req.header('if-none-match'))
118
119
  })
119
120
 
120
121
  // Workspace file stream — an applet's `fileUrl(path)` resolves here. Streams a
@@ -125,7 +126,12 @@ one.get('/views/*', c => {
125
126
  one.get('/fs/*', c => {
126
127
  const id = c.req.param('id')
127
128
  const tail = new URL(c.req.url).pathname.split(`/api/workspaces/${id}/fs/`)[1] ?? ''
128
- return serveWorkspaceFile(c.get('ws').path, tail, c.req.header('range'))
129
+ return serveWorkspaceFile(
130
+ c.get('ws').path,
131
+ tail,
132
+ c.req.header('range'),
133
+ c.req.header('if-none-match')
134
+ )
129
135
  })
130
136
 
131
137
  // Applet RPC — the home for server-function calls from a bundle. The bundle's
@@ -389,6 +395,43 @@ one.put('/scratchpad', async c => {
389
395
  return c.body(null, 204)
390
396
  })
391
397
 
398
+ // Scratchpad assets: pasted/dropped image bytes live as content-addressed files
399
+ // in `.moi/.scratchpad/`, referenced from the snapshot by `asset:` srcs —
400
+ // never inlined as base64 in the JSON (see server/scratchpad-assets.ts). The
401
+ // browser's TLAssetStore POSTs the raw file here on paste and resolves `asset:`
402
+ // srcs back through the GET when rendering.
403
+ one.post('/scratchpad/assets', async c => {
404
+ const length = Number(c.req.header('content-length') ?? 0)
405
+ if (length > MAX_ASSET_BYTES) {
406
+ return c.text(`Asset too large (max ${MAX_ASSET_BYTES / (1024 * 1024)} MB)`, 413)
407
+ }
408
+ const bytes = new Uint8Array(await c.req.arrayBuffer())
409
+ if (bytes.length === 0) return c.text('Empty body', 400)
410
+ if (bytes.length > MAX_ASSET_BYTES) {
411
+ return c.text(`Asset too large (max ${MAX_ASSET_BYTES / (1024 * 1024)} MB)`, 413)
412
+ }
413
+ const mimeType = c.req.header('content-type') ?? 'application/octet-stream'
414
+ return c.json(await storeScratchpadAsset(c.get('ws').path, bytes, mimeType))
415
+ })
416
+
417
+ // The file name is content-addressed (sha256 of the bytes), so a hit is
418
+ // immutable — let the browser cache it indefinitely.
419
+ one.get('/scratchpad/assets/:file', async c => {
420
+ const resolved = scratchpadAssetFile(c.get('ws').path, c.req.param('file'))
421
+ if (!resolved || !(await resolved.file.exists())) return c.text('Not found', 404)
422
+ return new Response(resolved.file, {
423
+ headers: {
424
+ 'Content-Type': resolved.mimeType,
425
+ 'Cache-Control': 'public, max-age=31536000, immutable',
426
+ // Assets are only ever consumed via <img>/<video>/fetch (which all ignore
427
+ // this), so force a download on direct navigation and block MIME sniffing:
428
+ // a pasted/uploaded SVG must not execute as script in the app origin.
429
+ 'Content-Disposition': 'attachment',
430
+ 'X-Content-Type-Options': 'nosniff'
431
+ }
432
+ })
433
+ })
434
+
392
435
  // Workspace icon. PUT a raw image body (png/jpg/gif/webp) — the server resizes
393
436
  // it to a 128×128 transparent WebP and stores it as base64. DELETE resets to the
394
437
  // provider default. Both broadcast for a live refresh.
package/server/applets.ts CHANGED
@@ -12,7 +12,7 @@
12
12
  // `%%MOI_APPLET_API_BASE%%` sentinel (for RPC + `fileUrl`), swapped to the real
13
13
  // `/api/workspaces/<id>` base when served — so the on-disk bundle is
14
14
  // workspace-agnostic.
15
- import { realpathSync } from 'node:fs'
15
+ import { realpathSync, statSync } from 'node:fs'
16
16
  import { mkdir, readdir, rm } from 'node:fs/promises'
17
17
  import { dirname, join, resolve, sep } from 'path'
18
18
 
@@ -136,16 +136,44 @@ const CODE_FILE_RE = /\.js$/
136
136
  // can be requested; `..` is rejected separately.
137
137
  const ALLOWED_FILE_RE = /^[a-zA-Z0-9_-][a-zA-Z0-9._-]*$/
138
138
 
139
+ const JS_CONTENT_TYPE = 'text/javascript; charset=utf-8'
140
+ // A content-hashed url is a fingerprint of its bytes, so it's safe to cache
141
+ // without revalidation. But immutability here is INFERRED from the filename
142
+ // (HASHED_FILE_RE) rather than guaranteed by construction (unlike a sha256-named
143
+ // asset) — so we cap the TTL at a week instead of the usual year. If that
144
+ // inference ever misfires, a wrongly-pinned copy self-heals within a week at the
145
+ // edge and in the browser, rather than sticking around for a year.
146
+ const IMMUTABLE_CACHE = 'public, max-age=604800, immutable'
147
+
148
+ // Which build-dir files are safe to serve `immutable`. The build emits exactly
149
+ // two content-hashed shapes — Bun's `chunk-<hash>.js` and the runtime plugin's
150
+ // `<stem>-<hash>.<ext>` assets (hash = hex, see build-applet.ts) — alongside the
151
+ // ONE stable-named entry, `index.js`. We match those shapes POSITIVELY and
152
+ // default everything else (the entry, and anything unexpected) to revalidation:
153
+ // this fix exists to stop a shared cache pinning a stale copy at a stable url,
154
+ // so an unrecognized name must fail safe (revalidate), never fail stale
155
+ // (immutable). The hex-suffix arm rejects real words (`-sprite`, `-preview`) —
156
+ // they aren't hex — so only genuine hashes opt in.
157
+ const HASHED_FILE_RE = /^chunk-[0-9a-z]+\.\w+$|-[0-9a-f]{6,}\.\w+$/i
158
+
139
159
  // Serve one file from a compiled applet directory: the `index.js` entry, a code
140
160
  // chunk, or a bundled asset. `apiBase` is the workspace's `/api/workspaces/<id>`
141
161
  // prefix — substituted for the build-time sentinel in every `.js` so RPC and
142
162
  // `fileUrl` calls hit the right workspace. Assets stream untouched.
163
+ //
164
+ // Caching turns on the hashed-vs-stable split. A content-hashed chunk/asset gets
165
+ // a new url whenever its bytes change, so it's cached forever. The `index.js`
166
+ // entry (and anything not recognizably hashed) lives at ONE url across rebuilds,
167
+ // so a shared cache (e.g. Cloudflare) that stored it once would hand back a
168
+ // STALE copy after the next `moi bundle` — it gets an ETag (size+mtime) +
169
+ // `no-cache` instead, so an unchanged file costs a 304 and a rebuilt one busts.
143
170
  export async function serveApplet(
144
171
  kind: AppletKind,
145
172
  name: string,
146
173
  file: string,
147
174
  workspacePath: string,
148
- apiBase: string
175
+ apiBase: string,
176
+ ifNoneMatch?: string | null
149
177
  ): Promise<Response> {
150
178
  if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
151
179
  return new Response('Invalid name', { status: 400 })
@@ -160,11 +188,25 @@ export async function serveApplet(
160
188
  if (!(await bunFile.exists())) {
161
189
  return new Response(`"${name}" not built. Run: moi bundle`, { status: 404 })
162
190
  }
191
+
192
+ // Content-hashed → immutable. Everything else → revalidate (ETag + no-cache),
193
+ // short-circuiting to a bodyless 304 when the client's ETag still matches.
194
+ let cache: Record<string, string>
195
+ if (HASHED_FILE_RE.test(file)) {
196
+ cache = { 'Cache-Control': IMMUTABLE_CACHE }
197
+ } else {
198
+ const etag = `"${bunFile.size}-${Math.trunc(bunFile.lastModified)}"`
199
+ cache = { ETag: etag, 'Cache-Control': 'no-cache' }
200
+ if (ifNoneMatch === etag) return new Response(null, { status: 304, headers: cache })
201
+ }
202
+
163
203
  if (CODE_FILE_RE.test(file)) {
164
204
  const swapped = (await bunFile.text()).replaceAll(APPLET_API_BASE_SENTINEL, apiBase)
165
- return new Response(swapped, { headers: { 'Content-Type': 'text/javascript; charset=utf-8' } })
205
+ return new Response(swapped, { headers: { 'Content-Type': JS_CONTENT_TYPE, ...cache } })
166
206
  }
167
- return new Response(bunFile)
207
+ return new Response(bunFile, {
208
+ headers: { 'Content-Type': bunFile.type || 'application/octet-stream', ...cache }
209
+ })
168
210
  }
169
211
 
170
212
  // ---- route helpers ----------------------------------------------------------
@@ -255,23 +297,51 @@ export function resolveWorkspaceMediaFile(workspaceRoot: string, tail: string):
255
297
  // Range is handled explicitly (slice the BunFile, 206 + Content-Range): Bun's
256
298
  // implicit range handling for `new Response(Bun.file())` doesn't fire once any
257
299
  // headers object is attached, and <video>/<audio> seeking needs byte ranges.
300
+ //
301
+ // Caching: these are the user's own workspace files — private, and rewritten in
302
+ // place by the agent (a regenerated clip keeps its path). So they must NEVER be
303
+ // stored by a shared/edge cache sitting in front of moi, or one user's video
304
+ // could be served to the next, and an edited file could be served stale from a
305
+ // stable url (the applet-bundle incident, but with private bytes). `private`
306
+ // keeps them off the edge; a strong ETag (size + nanosecond mtime) + `no-cache`
307
+ // lets the browser revalidate cheaply (304) while re-fetching when it changes.
258
308
  export async function serveWorkspaceFile(
259
309
  workspaceRoot: string,
260
310
  tail: string,
261
- range?: string | null
311
+ range?: string | null,
312
+ ifNoneMatch?: string | null
262
313
  ): Promise<Response> {
263
314
  const realTarget = resolveWorkspaceMediaFile(workspaceRoot, tail)
264
315
  if (realTarget instanceof Response) return realTarget
265
316
  const file = Bun.file(realTarget)
266
317
 
267
- const size = file.size
318
+ let stat: ReturnType<typeof statSync>
319
+ try {
320
+ stat = statSync(realTarget, { bigint: true })
321
+ } catch {
322
+ return new Response('Not found', { status: 404 })
323
+ }
324
+ const size = Number(stat.size)
268
325
  const type = file.type || 'application/octet-stream'
326
+
327
+ // Validator = size + NANOSECOND mtime. This route serves agent-regenerated
328
+ // files at stable paths, so a weak validator that returns a false 304 pins
329
+ // stale media in the browser. Truncating mtime to whole milliseconds (or
330
+ // seconds) can collide when a same-length rewrite lands inside one tick; ns
331
+ // resolution closes that window without hashing the (possibly huge) file on
332
+ // every request. A tool that deliberately preserves mtime with same-size but
333
+ // different bytes could still collide — only a content hash defeats that, and
334
+ // it's not worth re-reading a video per request when agents rewrite normally.
335
+ const etag = `"${size}-${stat.mtimeNs}"`
336
+ const cache = { ETag: etag, 'Cache-Control': 'private, no-cache' }
337
+ if (ifNoneMatch === etag) return new Response(null, { status: 304, headers: cache })
338
+
269
339
  const parsed = range ? parseByteRange(range, size) : null
270
340
 
271
341
  if (parsed === 'invalid') {
272
342
  return new Response('Range Not Satisfiable', {
273
343
  status: 416,
274
- headers: { 'Content-Range': `bytes */${size}`, 'Accept-Ranges': 'bytes' }
344
+ headers: { ...cache, 'Content-Range': `bytes */${size}`, 'Accept-Ranges': 'bytes' }
275
345
  })
276
346
  }
277
347
  if (parsed) {
@@ -279,6 +349,7 @@ export async function serveWorkspaceFile(
279
349
  return new Response(file.slice(start, end + 1), {
280
350
  status: 206,
281
351
  headers: {
352
+ ...cache,
282
353
  'Content-Type': type,
283
354
  'Content-Length': String(end - start + 1),
284
355
  'Content-Range': `bytes ${start}-${end}/${size}`,
@@ -287,7 +358,12 @@ export async function serveWorkspaceFile(
287
358
  })
288
359
  }
289
360
  return new Response(file, {
290
- headers: { 'Content-Type': type, 'Content-Length': String(size), 'Accept-Ranges': 'bytes' }
361
+ headers: {
362
+ ...cache,
363
+ 'Content-Type': type,
364
+ 'Content-Length': String(size),
365
+ 'Accept-Ranges': 'bytes'
366
+ }
291
367
  })
292
368
  }
293
369
 
@@ -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
+ }