moi-computer 0.11.0 → 0.11.1-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.
Files changed (196) hide show
  1. package/client/AGENTS.md +2 -2
  2. package/client/components/ui/button.tsx +1 -53
  3. package/client/components/ui/collapsible.tsx +1 -15
  4. package/client/components/ui/dialog.tsx +1 -58
  5. package/client/components/ui/dropdown-menu.tsx +1 -254
  6. package/client/components/ui/hover-card.tsx +1 -44
  7. package/client/components/ui/input.tsx +1 -21
  8. package/client/components/ui/popover.tsx +1 -88
  9. package/client/components/ui/resizable.tsx +1 -40
  10. package/client/components/ui/skeleton.tsx +1 -13
  11. package/client/components/ui/slider.tsx +1 -70
  12. package/client/components/ui/spinner.tsx +1 -18
  13. package/client/components/ui/switch.tsx +1 -23
  14. package/client/components/ui/tabs.tsx +1 -0
  15. package/client/components/ui/textarea.tsx +1 -18
  16. package/client/components/ui/tooltip.tsx +1 -51
  17. package/client/features/chat/ChatPanel.tsx +6 -6
  18. package/client/features/chat/ChatPopup.tsx +3 -4
  19. package/client/features/chat/TurnView.tsx +5 -4
  20. package/client/features/chat/api.ts +5 -14
  21. package/client/features/chat/chat-frames.ts +5 -2
  22. package/client/features/chat/composer/ChatComposer.tsx +5 -1
  23. package/client/features/chat/composer/ModelPicker.tsx +4 -3
  24. package/client/features/chat/composer/banners/ErrorBanner.tsx +20 -12
  25. package/client/features/chat/composer/useWorkspaceComposerState.tsx +15 -7
  26. package/client/features/chat/group-turns.ts +11 -0
  27. package/client/features/chat/session-view.ts +53 -0
  28. package/client/features/chat/useChat.ts +5 -1
  29. package/client/features/dev/ChatStatesPage.tsx +3 -1
  30. package/client/features/dev/DevIndexPage.tsx +5 -0
  31. package/client/features/dev/DevRoutes.tsx +2 -0
  32. package/client/features/dev/HarnessDebugPage.tsx +1 -1
  33. package/client/features/dev/UiComponentPreviews.tsx +834 -0
  34. package/client/features/dev/UiComponentsPage.tsx +60 -0
  35. package/client/features/home/WorkspacePreview.tsx +1 -1
  36. package/client/features/home/workspace-setup/DemoDialog.tsx +3 -2
  37. package/client/features/home/workspace-setup/ImportWorkspaceDialog.tsx +5 -8
  38. package/client/features/home/workspace-setup/WorkspaceDialogContent.tsx +7 -20
  39. package/client/features/settings/SettingsLayout.tsx +1 -1
  40. package/client/features/settings/WorkspaceSettings.tsx +4 -1
  41. package/client/features/views/ViewManager.tsx +14 -9
  42. package/client/features/widgets/WidgetFrame.tsx +1 -1
  43. package/client/features/widgets/Widgets.tsx +1 -3
  44. package/client/features/workspace/WorkspaceScreen.tsx +5 -1
  45. package/client/features/workspace/WorkspaceSplitLayout.tsx +6 -1
  46. package/client/features/workspace/api.ts +2 -4
  47. package/client/index.css +22 -29
  48. package/dist/{chunk-tny85yt2.js → chunk-4s15axjs.js} +2 -2
  49. package/dist/{chunk-c9pjqx9m.js → chunk-53a7pxcz.js} +1 -1
  50. package/dist/chunk-6664vxpk.css +1 -0
  51. package/dist/{chunk-104m57qw.js → chunk-87thzbtw.js} +2 -2
  52. package/dist/chunk-a6jad1a6.js +1 -0
  53. package/dist/chunk-dghwstd2.js +9 -0
  54. package/dist/chunk-eg120aca.js +1 -0
  55. package/dist/{chunk-v7wr1df4.js → chunk-j3wvxjr7.js} +1 -1
  56. package/dist/chunk-vwjeezeb.js +1 -0
  57. package/dist/chunk-w482ew2c.js +546 -0
  58. package/dist/chunk-yc471zah.js +70 -0
  59. package/dist/index.html +1 -1
  60. package/lib/format.ts +49 -1
  61. package/lib/themes.ts +6 -6
  62. package/lib/types.ts +5 -7
  63. package/package.json +17 -7
  64. package/registry.json +643 -0
  65. package/server/AGENTS.md +1 -0
  66. package/server/agent.ts +1 -1
  67. package/server/api.ts +25 -29
  68. package/server/applets.ts +30 -29
  69. package/server/bundler/applet-css.ts +6 -1
  70. package/server/bundler/build-applet.ts +5 -1
  71. package/server/bundler/build-worker.ts +178 -0
  72. package/server/cli-ui-components.ts +28 -33
  73. package/server/cli.ts +6 -11
  74. package/server/data-dir.ts +1 -1
  75. package/server/harness/README.md +13 -9
  76. package/server/harness/acp/NOTES.md +426 -0
  77. package/server/harness/acp/discovery.ts +27 -30
  78. package/server/harness/acp/model-state.ts +57 -0
  79. package/server/harness/acp/session.ts +18 -6
  80. package/server/harness/claude-code/NOTES.md +47 -12
  81. package/server/harness/claude-code/cli.ts +40 -0
  82. package/server/harness/claude-code/index.ts +11 -5
  83. package/server/harness/claude-code/models.ts +72 -19
  84. package/server/harness/claude-code/session.ts +408 -299
  85. package/server/harness/hermes/NOTES.md +18 -0
  86. package/server/harness/hermes/discovery.ts +20 -0
  87. package/server/harness/hermes/index.ts +9 -0
  88. package/server/harness/hermes/models.ts +28 -8
  89. package/server/harness/types.ts +4 -2
  90. package/server/moi-scaffold.ts +1 -1
  91. package/server/preview.ts +3 -1
  92. package/server/registry.ts +63 -41
  93. package/server/scratchpad-executor.ts +79 -56
  94. package/server/scratchpad-shape-defaults.ts +82 -0
  95. package/server/tldraw-package.d.ts +4 -0
  96. package/server/ui-components.ts +101 -434
  97. package/server/view-builders.ts +2 -1
  98. package/server/web.ts +9 -5
  99. package/server/workspace-env.ts +3 -2
  100. package/tsconfig.json +0 -1
  101. package/ui-components/accordion.tsx +71 -0
  102. package/ui-components/alert-dialog.tsx +165 -0
  103. package/ui-components/alert.tsx +68 -0
  104. package/ui-components/attachment.tsx +195 -0
  105. package/ui-components/avatar.tsx +90 -0
  106. package/ui-components/badge.tsx +49 -0
  107. package/ui-components/button-group.tsx +78 -0
  108. package/ui-components/button.tsx +55 -0
  109. package/ui-components/calendar.tsx +180 -0
  110. package/ui-components/card.tsx +84 -0
  111. package/ui-components/carousel.tsx +235 -0
  112. package/ui-components/chart.tsx +338 -0
  113. package/ui-components/checkbox.tsx +27 -0
  114. package/ui-components/collapsible.tsx +15 -0
  115. package/ui-components/combobox.tsx +265 -0
  116. package/ui-components/context-menu.tsx +244 -0
  117. package/ui-components/dialog.tsx +138 -0
  118. package/ui-components/docs/accordion.md +463 -0
  119. package/ui-components/docs/alert-dialog.md +481 -0
  120. package/ui-components/docs/alert.md +301 -0
  121. package/ui-components/docs/attachment.md +689 -0
  122. package/ui-components/docs/avatar.md +495 -0
  123. package/ui-components/docs/badge.md +258 -0
  124. package/ui-components/docs/button-group.md +879 -0
  125. package/ui-components/docs/button.md +26 -0
  126. package/ui-components/docs/calendar.md +862 -0
  127. package/ui-components/docs/card.md +265 -0
  128. package/ui-components/docs/carousel.md +627 -0
  129. package/ui-components/docs/chart.md +1256 -0
  130. package/ui-components/docs/checkbox.md +477 -0
  131. package/ui-components/docs/collapsible.md +446 -0
  132. package/ui-components/docs/combobox.md +1003 -0
  133. package/ui-components/docs/context-menu.md +860 -0
  134. package/ui-components/docs/data-table.md +1580 -0
  135. package/ui-components/docs/date-picker.md +614 -0
  136. package/ui-components/docs/dialog.md +414 -0
  137. package/ui-components/docs/drawer.md +51 -0
  138. package/ui-components/docs/dropdown-menu.md +1000 -0
  139. package/ui-components/docs/field.md +1192 -0
  140. package/ui-components/docs/hover-card.md +275 -0
  141. package/ui-components/docs/input-group.md +866 -0
  142. package/ui-components/docs/input.md +456 -0
  143. package/ui-components/docs/label.md +295 -0
  144. package/ui-components/docs/pagination.md +416 -0
  145. package/ui-components/docs/popover.md +348 -0
  146. package/ui-components/docs/progress.md +214 -0
  147. package/ui-components/docs/radio-group.md +389 -0
  148. package/ui-components/docs/resizable.md +265 -0
  149. package/ui-components/docs/select.md +616 -0
  150. package/ui-components/docs/separator.md +216 -0
  151. package/ui-components/docs/skeleton.md +205 -0
  152. package/ui-components/docs/slider.md +226 -0
  153. package/ui-components/docs/spinner.md +332 -0
  154. package/ui-components/docs/switch.md +236 -0
  155. package/ui-components/docs/table.md +551 -0
  156. package/ui-components/docs/tabs.md +379 -0
  157. package/ui-components/docs/textarea.md +187 -0
  158. package/ui-components/docs/toggle-group.md +370 -0
  159. package/ui-components/docs/toggle.md +91 -0
  160. package/ui-components/docs/tooltip.md +290 -0
  161. package/ui-components/drawer.tsx +213 -0
  162. package/ui-components/dropdown-menu.tsx +263 -0
  163. package/ui-components/field.tsx +224 -0
  164. package/ui-components/hover-card.tsx +46 -0
  165. package/ui-components/input-group.tsx +146 -0
  166. package/ui-components/input.tsx +20 -0
  167. package/ui-components/label.tsx +17 -0
  168. package/ui-components/pagination.tsx +124 -0
  169. package/ui-components/popover.tsx +81 -0
  170. package/ui-components/progress.tsx +63 -0
  171. package/ui-components/radio-group.tsx +37 -0
  172. package/ui-components/resizable.tsx +40 -0
  173. package/ui-components/scoped-portal.tsx +31 -0
  174. package/ui-components/select.tsx +195 -0
  175. package/ui-components/separator.tsx +18 -0
  176. package/ui-components/skeleton.tsx +15 -0
  177. package/ui-components/slider.tsx +75 -0
  178. package/ui-components/spinner.tsx +20 -0
  179. package/ui-components/switch.tsx +26 -0
  180. package/ui-components/table.tsx +86 -0
  181. package/ui-components/tabs.tsx +75 -0
  182. package/ui-components/textarea.tsx +17 -0
  183. package/ui-components/toggle-group.tsx +85 -0
  184. package/ui-components/toggle.tsx +42 -0
  185. package/ui-components/tooltip.tsx +61 -0
  186. package/ui-components/utils.ts +8 -0
  187. package/workspace/.claude/skills/moi-workspace/SKILL.md +11 -20
  188. package/workspace/.claude/skills/moi-workspace/references/DESIGN.md +4 -3
  189. package/workspace/.claude/skills/moi-workspace/references/UI-COMPONENTS.md +67 -203
  190. package/dist/chunk-59zf0m6n.js +0 -1
  191. package/dist/chunk-bj3akjs2.js +0 -1
  192. package/dist/chunk-j2w2vak4.js +0 -546
  193. package/dist/chunk-k2r9c95m.js +0 -10
  194. package/dist/chunk-kmbxhgwv.js +0 -1
  195. package/dist/chunk-p1yqa71k.js +0 -83
  196. package/dist/chunk-r5xrenjy.css +0 -1
package/server/api.ts CHANGED
@@ -149,7 +149,9 @@ async function handleFunctionCall(
149
149
  // the context. Mounted on the single-workspace sub-app so every nested route
150
150
  // shares the lookup instead of repeating `getWorkspace(...) ?? 404`.
151
151
  const withWorkspace = createMiddleware<ApiEnv>(async (c, next) => {
152
- const ws = await getWorkspace(c.req.param('id'))
152
+ const id = c.req.param('id')
153
+ if (!id) return c.text('Workspace not found', 404)
154
+ const ws = await getWorkspace(id)
153
155
  if (!ws) return c.text('Workspace not found', 404)
154
156
  c.set('ws', ws)
155
157
  await next()
@@ -161,7 +163,6 @@ one.use('*', withWorkspace)
161
163
 
162
164
  one.get('/preview', async c => {
163
165
  const ws = c.get('ws')
164
- const wsId = c.req.param('id')
165
166
  const views = await getViewList(ws.path)
166
167
  return c.json(
167
168
  await getWorkspacePreview(ws.path, {
@@ -169,7 +170,7 @@ one.get('/preview', async c => {
169
170
  harnessFor(ws).workspacePreview(ws, includeFirstUserMessage),
170
171
  viewIds: views.map(view => view.id),
171
172
  thumbnailUrl: (kind, id) =>
172
- `/api/workspaces/${wsId}/applet-thumbnails/${kind}/${encodeURIComponent(id)}`
173
+ `/api/workspaces/${ws.id}/applet-thumbnails/${kind}/${encodeURIComponent(id)}`
173
174
  })
174
175
  )
175
176
  })
@@ -181,10 +182,10 @@ one.get('/widgets', c => listWidgets(c.get('ws').path))
181
182
  // path lists, `/*` serves a file from the bundle dir (`<name>/<file>`:
182
183
  // index.js, a chunk, or a hashed asset).
183
184
  one.get('/widgets/*', c => {
184
- const id = c.req.param('id')
185
- const { name, file } = parseAppletTail(c.req.url, id, 'widgets')
185
+ const ws = c.get('ws')
186
+ const { name, file } = parseAppletTail(c.req.url, ws.id, 'widgets')
186
187
  if (!name) return c.text('Not found', 404)
187
- return serveWidget(name, file, c.get('ws').path, apiBaseFor(id), c.req.header('if-none-match'))
188
+ return serveWidget(name, file, ws.path, apiBaseFor(ws.id), c.req.header('if-none-match'))
188
189
  })
189
190
 
190
191
  // Views — full-screen agent apps. Mirrors the widget pair above: the exact path
@@ -192,10 +193,10 @@ one.get('/widgets/*', c => {
192
193
  one.get('/views', c => listViews(c.get('ws').path))
193
194
 
194
195
  one.get('/views/*', c => {
195
- const id = c.req.param('id')
196
- const { name, file } = parseAppletTail(c.req.url, id, 'views')
196
+ const ws = c.get('ws')
197
+ const { name, file } = parseAppletTail(c.req.url, ws.id, 'views')
197
198
  if (!name) return c.text('Not found', 404)
198
- return serveView(name, file, c.get('ws').path, apiBaseFor(id), c.req.header('if-none-match'))
199
+ return serveView(name, file, ws.path, apiBaseFor(ws.id), c.req.header('if-none-match'))
199
200
  })
200
201
 
201
202
  function viewBuilderError(err: unknown): { message: string; status: 400 | 404 | 409 } | null {
@@ -358,23 +359,18 @@ one.delete('/view-builders/:builderId', async c => {
358
359
  // are allowed — the workspace holds secrets, and this route is unauthenticated.
359
360
  // localhost binding is NOT the guard.
360
361
  one.get('/fs/*', c => {
361
- const id = c.req.param('id')
362
- const tail = new URL(c.req.url).pathname.split(`/api/workspaces/${id}/fs/`)[1] ?? ''
363
- return serveWorkspaceFile(
364
- c.get('ws').path,
365
- tail,
366
- c.req.header('range'),
367
- c.req.header('if-none-match')
368
- )
362
+ const ws = c.get('ws')
363
+ const tail = new URL(c.req.url).pathname.split(`/api/workspaces/${ws.id}/fs/`)[1] ?? ''
364
+ return serveWorkspaceFile(ws.path, tail, c.req.header('range'), c.req.header('if-none-match'))
369
365
  })
370
366
 
371
367
  // Applet RPC — the home for server-function calls from a bundle. The bundle's
372
368
  // sentinel base resolves to `/api/workspaces/<id>`, so it POSTs to
373
369
  // `…/rpc/<module>/<fn>`.
374
370
  one.post('/rpc/*', c => {
375
- const id = c.req.param('id')
376
- const tail = new URL(c.req.url).pathname.split(`/api/workspaces/${id}/rpc/`)[1] ?? ''
377
- return handleFunctionCall(c.req.raw, tail, c.get('ws').path)
371
+ const ws = c.get('ws')
372
+ const tail = new URL(c.req.url).pathname.split(`/api/workspaces/${ws.id}/rpc/`)[1] ?? ''
373
+ return handleFunctionCall(c.req.raw, tail, ws.path)
378
374
  })
379
375
 
380
376
  // Browser-side applet errors (module load failures, render crashes, window
@@ -428,9 +424,9 @@ one.post('/applet-log', async c => {
428
424
  // use this to show the picture an agent `Read` — same guards as /fs/ above,
429
425
  // images only, resized server-side (see server/preview.ts).
430
426
  one.get('/preview/*', c => {
431
- const id = c.req.param('id')
432
- const tail = new URL(c.req.url).pathname.split(`/api/workspaces/${id}/preview/`)[1] ?? ''
433
- return serveWorkspaceImagePreview(c.get('ws').path, tail, c.req.header('if-none-match'))
427
+ const ws = c.get('ws')
428
+ const tail = new URL(c.req.url).pathname.split(`/api/workspaces/${ws.id}/preview/`)[1] ?? ''
429
+ return serveWorkspaceImagePreview(ws.path, tail, c.req.header('if-none-match'))
434
430
  })
435
431
 
436
432
  // Chat attachments. The composer POSTs files here (drag/drop, paste, or the
@@ -439,7 +435,7 @@ one.get('/preview/*', c => {
439
435
  // vision blocks at send time; other files are referenced by a temp path. See
440
436
  // server/uploads.ts and dev/file-uploads.md.
441
437
  one.post('/uploads', async c => {
442
- const id = c.req.param('id')
438
+ const ws = c.get('ws')
443
439
  let form: FormData
444
440
  try {
445
441
  form = await c.req.formData()
@@ -459,7 +455,7 @@ one.post('/uploads', async c => {
459
455
  const bytes = Buffer.from(await file.arrayBuffer())
460
456
  out.push(
461
457
  await addUpload({
462
- workspaceId: id,
458
+ workspaceId: ws.id,
463
459
  filename: file.name || 'file',
464
460
  mediaType: file.type || 'application/octet-stream',
465
461
  bytes
@@ -478,9 +474,9 @@ one.post('/uploads', async c => {
478
474
  // is content-addressed (sha256), so the response is immutable while it lives —
479
475
  // let the browser cache it for the store's TTL.
480
476
  one.get('/uploads/:uploadId', c => {
481
- const u = getUpload(c.req.param('id'), c.req.param('uploadId'))
477
+ const u = getUpload(c.get('ws').id, c.req.param('uploadId'))
482
478
  if (!u) return c.text('Not found or expired', 404)
483
- const body: BodyInit | null = u.data ?? (u.path ? Bun.file(u.path) : null)
479
+ const body = u.data ? new Uint8Array(u.data) : u.path ? Bun.file(u.path) : null
484
480
  if (!body) return c.text('Not found or expired', 404)
485
481
  return new Response(body, {
486
482
  headers: {
@@ -771,7 +767,7 @@ one.put('/scratchpad', async c => {
771
767
  await saveScratchpadDoc(body.document, ws.path)
772
768
  publishEvent({
773
769
  type: 'scratchpad:updated',
774
- workspaceId: c.req.param('id'),
770
+ workspaceId: ws.id,
775
771
  origin: typeof body.origin === 'string' ? body.origin : undefined
776
772
  })
777
773
  return c.body(null, 204)
@@ -910,7 +906,7 @@ one.put('/', async c => {
910
906
  })
911
907
 
912
908
  one.delete('/', async c => {
913
- const ok = await removeWorkspace(c.req.param('id'))
909
+ const ok = await removeWorkspace(c.get('ws').id)
914
910
  if (!ok) return c.text('Workspace not found', 404)
915
911
  return c.body(null, 204)
916
912
  })
package/server/applets.ts CHANGED
@@ -20,9 +20,9 @@ import { dirname, join, resolve, sep } from 'path'
20
20
  import {
21
21
  APPLET_API_BASE_SENTINEL,
22
22
  type AppletKind,
23
- buildApplet,
24
23
  scanRelativeImports
25
24
  } from './bundler/build-applet'
25
+ import { buildAppletsInChild } from './bundler/build-worker'
26
26
  import { pruneAppletThumbnails } from './thumbnails'
27
27
 
28
28
  export type AppletPaths = {
@@ -609,35 +609,36 @@ export async function buildApplets<C>(
609
609
  })
610
610
  )
611
611
 
612
- const results = await Promise.all(
613
- jobs.map(async (job): Promise<AppletBuildResult<C>> => {
614
- if (job.status === 'failed') return { name: job.name, status: 'failed', error: job.error }
615
- if (job.status === 'skipped') return { name: job.name, status: 'skipped' }
616
- try {
617
- const artifact = await buildApplet(job.srcPath!, moiRoot, kind)
618
- // Clear the dir first so stale hashed assets from a prior build don't
619
- // accumulate, then write the fresh entry + chunks + assets.
620
- const dir = join(buildDir, job.name)
621
- await rm(dir, { recursive: true, force: true })
622
- await mkdir(dir, { recursive: true })
623
- for (const f of artifact.files) {
624
- await Bun.write(join(dir, f.name), f.data)
625
- }
626
- return {
627
- name: job.name,
628
- status: 'built',
629
- serverModules: artifact.serverModules.map(m => m.name),
630
- config: (artifact.config as C | null) ?? null
631
- }
632
- } catch (err) {
633
- return {
634
- name: job.name,
635
- status: 'failed',
636
- error: err instanceof Error ? err.message : 'Unknown error'
637
- }
638
- }
639
- })
612
+ // Compile the pending set in a fresh child process (see build-worker.ts:
613
+ // Bun's resolver cache is process-wide and never forgets a failed lookup, so
614
+ // an in-process build could not see packages installed after the server
615
+ // started). The child writes each bundle dir; only the per-job outcome comes
616
+ // back.
617
+ const built = new Map(
618
+ (
619
+ await buildAppletsInChild({
620
+ moiRoot,
621
+ kind,
622
+ jobs: jobs
623
+ .filter(job => job.status === 'pending')
624
+ .map(job => ({ name: job.name, srcPath: job.srcPath!, outDir: join(buildDir, job.name) }))
625
+ })
626
+ ).map(r => [r.name, r])
640
627
  )
641
628
 
629
+ const results = jobs.map((job): AppletBuildResult<C> => {
630
+ if (job.status === 'failed') return { name: job.name, status: 'failed', error: job.error }
631
+ if (job.status === 'skipped') return { name: job.name, status: 'skipped' }
632
+ const r = built.get(job.name)
633
+ if (!r) return { name: job.name, status: 'failed', error: 'Build worker returned no result' }
634
+ if (r.status === 'failed') return { name: job.name, status: 'failed', error: r.error }
635
+ return {
636
+ name: job.name,
637
+ status: 'built',
638
+ serverModules: r.serverModules,
639
+ config: (r.config as C | null) ?? null
640
+ }
641
+ })
642
+
642
643
  return { names, results, ms: Math.round(performance.now() - t0) }
643
644
  }
@@ -134,7 +134,12 @@ export function unqualifyNonSubjectHas(selector: string): string {
134
134
  }
135
135
 
136
136
  function insideKeyframes(parent: Container | Document | undefined): boolean {
137
- return parent?.type === 'atrule' && /keyframes$/i.test((parent as { name: string }).name)
137
+ return (
138
+ parent?.type === 'atrule' &&
139
+ 'name' in parent &&
140
+ typeof parent.name === 'string' &&
141
+ /keyframes$/i.test(parent.name)
142
+ )
138
143
  }
139
144
 
140
145
  export function scopeAppletCss(css: string, scope: string): string {
@@ -17,6 +17,8 @@ import { scopeAppletCss } from './applet-css'
17
17
  // canonical in lib/types; re-exported here for this pipeline's consumers.
18
18
  export type { AppletKind }
19
19
 
20
+ const APP_ICON_NAMES: readonly string[] = APP_ICON_IDS
21
+
20
22
  // Baked into the bundle wherever a runtime URL needs the workspace's API base
21
23
  // (RPC + workspace files). The serve route string-replaces it with the real
22
24
  // `/api/workspaces/<id>` in every `.js` it returns, so the on-disk bundle stays
@@ -163,7 +165,9 @@ export async function extractViewConfig(srcPath: string): Promise<ViewConfig | n
163
165
  if (prop.value.type === 'StringLiteral') {
164
166
  const icon = prop.value.value
165
167
  if (!isAppIconId(icon)) {
166
- throw new Error(`Unknown view icon id "${icon}". Use one of: ${APP_ICON_IDS.join(', ')}`)
168
+ throw new Error(
169
+ `Unknown view icon id "${icon}". Use one of: ${APP_ICON_NAMES.join(', ')}`
170
+ )
167
171
  }
168
172
  result.icon = icon
169
173
  }
@@ -0,0 +1,178 @@
1
+ // Out-of-process applet compiler.
2
+ //
3
+ // `Bun.build` shares one process-wide resolver cache with the runtime module
4
+ // loader: `node_modules` directory listings, `package.json` contents, and —
5
+ // crucially — FAILED bare-specifier lookups are memoized for the life of the
6
+ // process and never invalidated (still true in Bun 1.4). The moi server is
7
+ // long-lived, so an in-process build that once failed with `Could not resolve
8
+ // "pkg"` keeps failing for that specifier after the agent runs `bun add pkg`,
9
+ // and a workspace that gains its own `node_modules` (or bumps a package's
10
+ // `exports`) keeps resolving through the stale entry. Restarting the server
11
+ // was the only cure, and the agent isn't allowed to do that.
12
+ //
13
+ // So every build batch runs in a fresh `bun` child: the child imports this
14
+ // module as its entry, receives one `BuildRequest` over IPC, compiles each job
15
+ // with `buildApplet`, writes the bundle dirs, and replies with a
16
+ // `BuildResponse`. A cold child costs ~150ms, almost all of it importing this
17
+ // module's graph (bun-plugin-tailwind, applet-css, @babel/parser) — and a
18
+ // crash inside Bun's bundler no longer takes the server down with it.
19
+ //
20
+ // Lifecycle: the child never exits on its own after replying. `process.exit`
21
+ // right after `process.send` drops the message once it outgrows the IPC pipe
22
+ // buffer (~1MB — a handful of failed applets with long Bun diagnostics gets
23
+ // there), so the parent kills the child once the result has arrived. The
24
+ // child exits by itself only when the parent is gone: on IPC `disconnect`,
25
+ // or when its parent pid changes (a crashed/SIGKILLed server never sends
26
+ // disconnect, but the orphan is reparented). Live children are tracked so the
27
+ // server's shutdown path can kill them — an untracked build outliving a dev
28
+ // restart would keep rewriting `.build/` under the replacement server.
29
+ //
30
+ // `buildApplet` itself stays in-process-capable: tests call it directly, and
31
+ // nothing here changes its contract.
32
+ import { mkdir, rm } from 'node:fs/promises'
33
+ import { join } from 'path'
34
+
35
+ import type { AppletKind, ViewConfig, WidgetConfig } from '@/lib/types'
36
+
37
+ import { buildApplet } from './build-applet'
38
+
39
+ export type BuildJob = {
40
+ name: string
41
+ // Absolute path of the applet's entry source (`.moi/<kind>/<name>.tsx`).
42
+ srcPath: string
43
+ // Absolute bundle directory to (re)create: `.moi/.build/<kind>/<name>/`.
44
+ outDir: string
45
+ }
46
+
47
+ export type BuildJobResult = {
48
+ name: string
49
+ status: 'built' | 'failed'
50
+ error?: string
51
+ serverModules?: string[]
52
+ config?: WidgetConfig | ViewConfig | null
53
+ }
54
+
55
+ export type BuildRequest = {
56
+ type: 'build'
57
+ moiRoot: string
58
+ kind: AppletKind
59
+ jobs: BuildJob[]
60
+ }
61
+
62
+ export type BuildResponse = {
63
+ type: 'result'
64
+ results: BuildJobResult[]
65
+ }
66
+
67
+ const WORKER_PATH = join(import.meta.dir, 'build-worker.ts')
68
+
69
+ // Children currently compiling a batch, for `killBuildWorkers()`.
70
+ const liveWorkers = new Set<ReturnType<typeof Bun.spawn>>()
71
+
72
+ // How many build children are alive right now (tests assert none leak).
73
+ export function liveBuildWorkerCount(): number {
74
+ return liveWorkers.size
75
+ }
76
+
77
+ // Kill every in-flight build child. Called from the server's shutdown path
78
+ // (SIGTERM from the dev supervisor, Ctrl-C) alongside the function-worker pool
79
+ // so a half-done bundle can't keep writing after the server is gone. Pending
80
+ // batches settle as failed through `onExit`.
81
+ export function killBuildWorkers(): void {
82
+ for (const proc of liveWorkers) proc.kill()
83
+ liveWorkers.clear()
84
+ }
85
+
86
+ // Compile every job and write its bundle dir. Runs inside the child, but is a
87
+ // plain function so the batch semantics (parallel jobs, per-job failure
88
+ // isolation, clear-then-write) are testable without spawning.
89
+ export async function runBuildJobs(req: BuildRequest): Promise<BuildJobResult[]> {
90
+ return Promise.all(
91
+ req.jobs.map(async (job): Promise<BuildJobResult> => {
92
+ try {
93
+ const artifact = await buildApplet(job.srcPath, req.moiRoot, req.kind)
94
+ // Clear the dir first so stale hashed assets from a prior build don't
95
+ // accumulate, then write the fresh entry + chunks + assets.
96
+ await rm(job.outDir, { recursive: true, force: true })
97
+ await mkdir(job.outDir, { recursive: true })
98
+ for (const f of artifact.files) {
99
+ await Bun.write(join(job.outDir, f.name), f.data)
100
+ }
101
+ return {
102
+ name: job.name,
103
+ status: 'built',
104
+ serverModules: artifact.serverModules.map(m => m.name),
105
+ config: artifact.config
106
+ }
107
+ } catch (err) {
108
+ return {
109
+ name: job.name,
110
+ status: 'failed',
111
+ error: err instanceof Error ? err.message : 'Unknown error'
112
+ }
113
+ }
114
+ })
115
+ )
116
+ }
117
+
118
+ // Host side: spawn a fresh child for one batch and collect its results. The
119
+ // child inherits cwd and env, so resolution behaves exactly as the in-process
120
+ // build did (see the `devalue` and `serverCwd` notes in build-applet.ts) —
121
+ // minus the poisoned cache. A child that dies before replying fails every job
122
+ // in the batch with its exit code rather than hanging the caller.
123
+ export function buildAppletsInChild(req: Omit<BuildRequest, 'type'>): Promise<BuildJobResult[]> {
124
+ if (req.jobs.length === 0) return Promise.resolve([])
125
+ return new Promise(resolve => {
126
+ let settled = false
127
+ const settle = (results: BuildJobResult[]) => {
128
+ if (settled) return
129
+ settled = true
130
+ resolve(results)
131
+ }
132
+ const request: BuildRequest = { type: 'build', ...req }
133
+ const proc = Bun.spawn([process.execPath, WORKER_PATH], {
134
+ stdio: ['ignore', 'inherit', 'inherit'],
135
+ serialization: 'json',
136
+ ipc(message, child) {
137
+ const msg = message as Partial<BuildResponse>
138
+ if (msg.type !== 'result' || !Array.isArray(msg.results)) return
139
+ settle(msg.results)
140
+ // The result is in hand — the child has nothing left to do (see the
141
+ // lifecycle note above for why it doesn't exit on its own).
142
+ liveWorkers.delete(child)
143
+ child.kill()
144
+ },
145
+ onExit(child, code, signal) {
146
+ liveWorkers.delete(child)
147
+ const why = signal ? `signal ${signal}` : `code ${code}`
148
+ settle(
149
+ req.jobs.map(job => ({
150
+ name: job.name,
151
+ status: 'failed',
152
+ error: `Build worker exited (${why}) before reporting a result`
153
+ }))
154
+ )
155
+ }
156
+ })
157
+ liveWorkers.add(proc)
158
+ proc.send(request)
159
+ })
160
+ }
161
+
162
+ if (import.meta.main) {
163
+ // Orphan guards — the only ways the child ends itself. See the lifecycle
164
+ // note at the top: the parent kills us after it has read the result.
165
+ const parentPid = process.ppid
166
+ process.on('disconnect', () => process.exit(0))
167
+ setInterval(() => {
168
+ if (process.ppid !== parentPid) process.exit(0)
169
+ }, 500)
170
+
171
+ process.on('message', async message => {
172
+ const req = message as Partial<BuildRequest>
173
+ if (req.type !== 'build' || !Array.isArray(req.jobs)) return
174
+ const results = await runBuildJobs(req as BuildRequest)
175
+ const response: BuildResponse = { type: 'result', results }
176
+ process.send?.(response)
177
+ })
178
+ }
@@ -1,9 +1,9 @@
1
1
  // CLI face of `moi ui-components` (see server/ui-components.ts for the
2
- // engine and docs/moi-shadcn.md for the spec). Three verbs:
2
+ // engine and docs/ui-components.md for the spec). Three verbs:
3
3
  //
4
4
  // moi ui-components → the curated catalog + installed state
5
- // moi ui-components add <name…> → fetch, transform, write to .moi/ui/
6
- // moi ui-components docs <name…> → official docs as markdown, on stdout
5
+ // moi ui-components add <name…> → copy registry components to .moi/ui/
6
+ // moi ui-components docs <name…> → component docs as markdown, on stdout
7
7
  //
8
8
  // The command is deliberately not smart: add never rebuilds and never edits
9
9
  // existing files, and installs dependencies only when asked to (--install) —
@@ -17,15 +17,16 @@ import pc from './cli-pc'
17
17
  import { resolveCwdWorkspace } from './cli-env'
18
18
  import { MOI_PACKAGE_JSON } from './moi-scaffold'
19
19
  import {
20
+ type LoadedUiComponents,
20
21
  UI_COMPONENTS,
21
22
  UI_COMPONENT_NAMES,
22
- UI_DOCS_BASE,
23
- fetchUiComponents,
23
+ loadUiComponentDocs,
24
+ loadUiComponents,
24
25
  partitionUiWrites,
25
26
  planUiWrites,
26
27
  resolveUiComponentRequest,
27
28
  suggestUiComponents,
28
- transformUiComponentSource
29
+ uiComponentFiles
29
30
  } from './ui-components'
30
31
 
31
32
  function uiDirFor(workspacePath: string): string {
@@ -37,7 +38,7 @@ function exitUnknownNames(unknown: string[]): never {
37
38
  const hints = suggestUiComponents(name)
38
39
  console.error(
39
40
  pc.red('✗') +
40
- ` "${name}" is not in the moi component set.` +
41
+ ` "${name}" is not in the component catalog.` +
41
42
  (hints.length ? pc.dim(` Did you mean: ${hints.join(', ')}?`) : '')
42
43
  )
43
44
  }
@@ -48,7 +49,7 @@ function exitUnknownNames(unknown: string[]): never {
48
49
  const add = defineCommand({
49
50
  meta: {
50
51
  name: 'add',
51
- description: 'Fetch components from the shadcn registry into .moi/ui/'
52
+ description: 'Add components from the local registry to .moi/ui/'
52
53
  },
53
54
  args: {
54
55
  name: {
@@ -74,35 +75,34 @@ const add = defineCommand({
74
75
  const entry = await resolveCwdWorkspace()
75
76
  const uiDir = uiDirFor(entry.path)
76
77
 
77
- let fetched
78
+ let loaded: LoadedUiComponents
78
79
  try {
79
- fetched = await fetchUiComponents(request.registryItems)
80
+ loaded = await loadUiComponents(request.entries)
80
81
  } catch (err) {
81
82
  console.error(
82
83
  '\n' +
83
84
  pc.red('✗') +
84
- ' Could not reach the shadcn registry (ui.shadcn.com). ' +
85
- 'The command needs network access; offline use is not supported.\n' +
85
+ ' Could not load the requested components from the local registry.\n' +
86
86
  pc.dim(` ${(err as Error).message}\n`)
87
87
  )
88
88
  process.exit(1)
89
89
  }
90
90
 
91
91
  const plans = planUiWrites({
92
- files: fetched.files,
93
- requestedItems: request.registryItems,
92
+ files: loaded.files,
93
+ requestedFiles: request.entries.flatMap(uiComponentFiles),
94
94
  uiDir,
95
95
  exists: existsSync
96
96
  })
97
97
 
98
98
  // Hand-customized components are never silently overwritten: without
99
99
  // --force a requested file that already exists is skipped and reported, so
100
- // a bulk add still installs everything new. Only when every requested
101
- // component already exists does the add fail. Existing support files
102
- // (utils, applet-portal, registry deps that rode along) are kept as-is
100
+ // a bulk add still installs everything new. Only when nothing needs to be
101
+ // written does the add fail. Existing support files
102
+ // (utils, scoped-portal, registry deps that rode along) are kept as-is
103
103
  // either way, even under --force.
104
104
  const partition = partitionUiWrites(plans, args.force)
105
- if (partition.allInstalled) {
105
+ if (partition.write.length === 0) {
106
106
  console.error(
107
107
  '\n' +
108
108
  pc.red('✗') +
@@ -118,10 +118,7 @@ const add = defineCommand({
118
118
  await mkdir(uiDir, { recursive: true })
119
119
  const written: string[] = []
120
120
  for (const plan of partition.write) {
121
- const content = plan.name.endsWith('.tsx')
122
- ? await transformUiComponentSource(plan.name, plan.content)
123
- : plan.content
124
- await Bun.write(plan.path, content)
121
+ await Bun.write(plan.path, plan.content)
125
122
  written.push(plan.name)
126
123
  }
127
124
  const kept = partition.keepSupport.map(plan => plan.name)
@@ -131,7 +128,7 @@ const add = defineCommand({
131
128
  // registry specifiers may be versioned (`recharts@3.8.0`), so compare by
132
129
  // package name.
133
130
  const baseline = new Set(Object.keys(MOI_PACKAGE_JSON.dependencies))
134
- const deps = [...new Set([...fetched.dependencies, ...request.extraDeps])]
131
+ const deps = [...new Set(loaded.dependencies)]
135
132
  .filter(spec => !baseline.has(spec.replace(/@[^@/]+$/, '')))
136
133
  .sort()
137
134
 
@@ -200,7 +197,7 @@ const add = defineCommand({
200
197
  const docs = defineCommand({
201
198
  meta: {
202
199
  name: 'docs',
203
- description: 'Print official component docs as markdown'
200
+ description: 'Print component docs as markdown'
204
201
  },
205
202
  args: {
206
203
  name: {
@@ -213,18 +210,16 @@ const docs = defineCommand({
213
210
  const request = resolveUiComponentRequest(args._)
214
211
  if (request.unknown.length > 0) exitUnknownNames(request.unknown)
215
212
 
213
+ console.log(
214
+ '> Import components relatively from `../ui/<name>` and use `@tabler/icons-react` for icons.\n'
215
+ )
216
216
  for (const name of request.entries) {
217
- const slug = UI_COMPONENTS[name].docsSlug ?? name
218
- const url = `${UI_DOCS_BASE}/${slug}.md`
219
217
  try {
220
- const res = await fetch(url, { signal: AbortSignal.timeout(20_000) })
221
- if (!res.ok) throw new Error(`HTTP ${res.status}`)
218
+ const markdown = await loadUiComponentDocs(name)
222
219
  if (request.entries.length > 1) console.log(`\n---\n# ${name}\n`)
223
- console.log(await res.text())
220
+ console.log(markdown)
224
221
  } catch (err) {
225
- console.error(
226
- pc.red('✗') + ` Could not fetch docs for "${name}" (${url}): ${(err as Error).message}`
227
- )
222
+ console.error(pc.red('✗') + ` Could not load docs for "${name}": ${(err as Error).message}`)
228
223
  process.exitCode = 1
229
224
  }
230
225
  }
@@ -240,7 +235,7 @@ function renderCatalog(uiDir: string, query?: string): void {
240
235
  if (needle && !name.includes(needle) && !entry.description.toLowerCase().includes(needle)) {
241
236
  continue
242
237
  }
243
- const installed = entry.registryItems.every(item => existsSync(join(uiDir, `${item}.tsx`)))
238
+ const installed = uiComponentFiles(name).every(file => existsSync(join(uiDir, file)))
244
239
  rows.push(
245
240
  ' ' +
246
241
  (installed ? pc.green('✓ ') : ' ') +
package/server/cli.ts CHANGED
@@ -790,7 +790,7 @@ const refresh = defineCommand({
790
790
  }
791
791
  })
792
792
 
793
- function hexToRgb(hex: string): [number, number, number] {
793
+ function swatchHexToRgb(hex: string): [number, number, number] {
794
794
  const value = Number.parseInt(hex.slice(1), 16)
795
795
  return [(value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff]
796
796
  }
@@ -799,8 +799,8 @@ function hexToRgb(hex: string): [number, number, number] {
799
799
  // Falls back to blank spaces when stdout is not a TTY, keeping piped output clean.
800
800
  function swatch(bg?: string, fg?: string): string {
801
801
  if (!process.stdout.isTTY || !bg) return ' '
802
- const [br, bgg, bb] = hexToRgb(bg)
803
- const [fr, fgg, fb] = hexToRgb(fg ?? '#000000')
802
+ const [br, bgg, bb] = swatchHexToRgb(bg)
803
+ const [fr, fgg, fb] = swatchHexToRgb(fg ?? '#000000')
804
804
  return `\x1b[48;2;${br};${bgg};${bb}m\x1b[38;2;${fr};${fgg};${fb}m Aa \x1b[0m`
805
805
  }
806
806
 
@@ -2946,17 +2946,12 @@ const version = defineCommand({
2946
2946
  }
2947
2947
  })
2948
2948
 
2949
- // A static shell over ./cli-ui-components, which reaches `shadcn` and
2950
- // `ts-morph` — ~31 MB of JS that costs ~300 ms to parse and evaluate. The meta
2951
- // is inlined here (duplicating the real command's) because it is all the root
2952
- // help needs: both citty's usage renderer and printMainHelp read only
2953
- // `meta.description`, so a lazily-resolved subcommand would be imported by
2954
- // every `moi --help`. Keeping the shell static defers the module to the point
2955
- // where a subcommand actually runs.
2949
+ // A static shell over ./cli-ui-components. The meta is inlined here because it
2950
+ // is all the root help needs; the registry loader stays lazy until used.
2956
2951
  const uiComponents = defineCommand({
2957
2952
  meta: {
2958
2953
  name: 'ui-components',
2959
- description: 'Standard UI components for applets (curated shadcn set)'
2954
+ description: 'UI components for applets'
2960
2955
  },
2961
2956
  subCommands: () => import('./cli-ui-components').then(m => m.uiComponentsSubCommands),
2962
2957
  async run({ rawArgs }) {
@@ -6,4 +6,4 @@
6
6
  // spawned CLI would otherwise read the developer's real data dir.
7
7
  import envPaths from 'env-paths'
8
8
 
9
- export const DATA_DIR = process.env.MOI_DATA_DIR || envPaths('moi', { suffix: false }).data
9
+ export const DATA_DIR = process.env.MOI_DATA_DIR || envPaths('moi', { suffix: '' }).data