moi-computer 0.3.0 → 0.3.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 (121) hide show
  1. package/client/api/workspace-keys.ts +2 -2
  2. package/client/app/AppRouter.tsx +0 -2
  3. package/client/app/routes/WorkspaceRoute.tsx +3 -1
  4. package/client/app/shell/SidebarLayout.tsx +3 -16
  5. package/client/assets/openai.svg +1 -3
  6. package/client/components/shared/Composer.tsx +112 -0
  7. package/client/components/ui/button.tsx +1 -1
  8. package/client/components/ui/dropdown-menu.tsx +3 -3
  9. package/client/components/ui/tooltip.tsx +12 -15
  10. package/client/features/applets/WidgetErrorBoundary.tsx +19 -3
  11. package/client/features/applets/WidgetShell.tsx +8 -1
  12. package/client/features/applets/applet-log.ts +100 -0
  13. package/client/features/applets/useApplet.ts +21 -7
  14. package/client/features/chat/ChatComposer.tsx +33 -30
  15. package/client/features/chat/ChatPanel.tsx +5 -2
  16. package/client/features/chat/MarkdownContent.tsx +20 -2
  17. package/client/features/chat/ModelPicker.tsx +29 -41
  18. package/client/features/chat/TurnView.tsx +2 -2
  19. package/client/features/chat/chat-frames.ts +14 -6
  20. package/client/features/chat/chat-send.ts +1 -1
  21. package/client/features/chat/chat-store.ts +22 -17
  22. package/client/features/chat/model-order.ts +47 -0
  23. package/client/features/chat/tool-group/ToolOutput.tsx +4 -12
  24. package/client/features/chat/tool-group/format.ts +0 -6
  25. package/client/features/chat/useChat.ts +15 -2
  26. package/client/features/connectors/McpServerCards.tsx +95 -0
  27. package/client/features/connectors/api.ts +0 -11
  28. package/client/features/home/HomePage.tsx +45 -42
  29. package/client/features/home/WorkspacePreview.tsx +179 -38
  30. package/client/features/home/api.ts +24 -12
  31. package/client/features/home/workspace-presentation.tsx +17 -15
  32. package/client/features/home/workspace-setup/CreateWorkspaceDialog.tsx +243 -0
  33. package/client/features/home/workspace-setup/ImportWorkspaceDialog.tsx +95 -0
  34. package/client/features/home/workspace-setup/WorkspaceAgentStep.tsx +230 -0
  35. package/client/features/home/workspace-setup/WorkspaceDialogContent.tsx +35 -0
  36. package/client/features/home/workspace-setup/useWorkspaceImport.ts +61 -0
  37. package/client/features/settings/ConnectorsSettings.tsx +89 -0
  38. package/client/features/settings/GeneralSettings.tsx +12 -0
  39. package/client/features/settings/SettingsLayout.tsx +2 -2
  40. package/client/features/settings/WorkspaceSettings.tsx +8 -4
  41. package/client/features/views/ViewBuilderTab.tsx +28 -29
  42. package/client/features/views/useViewBuilderActions.ts +1 -1
  43. package/client/features/widgets/WidgetFrame.tsx +3 -0
  44. package/client/features/widgets/WidgetGrid.tsx +1 -0
  45. package/client/features/widgets/Widgets.tsx +12 -3
  46. package/client/features/widgets/api.ts +47 -0
  47. package/client/features/widgets/useWidgetThumbnails.ts +107 -0
  48. package/client/features/widgets/widget-snapshot.ts +71 -0
  49. package/client/features/workspace/WorkspaceLayoutContext.tsx +3 -4
  50. package/client/features/workspace/WorkspaceScreen.tsx +19 -4
  51. package/client/features/workspace/api.ts +25 -3
  52. package/client/features/workspace/moi-context.ts +85 -0
  53. package/client/index.css +0 -5
  54. package/client/main.tsx +13 -4
  55. package/dist/{chunk-cs8vbert.js → chunk-1dfbr7n2.js} +2 -2
  56. package/dist/chunk-339jds4x.js +15 -0
  57. package/dist/chunk-3xsvsnhr.css +1 -0
  58. package/dist/{chunk-zpxrb1ce.js → chunk-anqmsbjt.js} +2 -2
  59. package/dist/chunk-hbvfb6sk.js +63 -0
  60. package/dist/chunk-jen6xcm1.js +14 -0
  61. package/dist/{chunk-kxmvv1ax.js → chunk-qwm5f6qk.js} +1 -1
  62. package/dist/{chunk-fjksw6xf.js → chunk-sxbfh73c.js} +1 -1
  63. package/dist/chunk-yp4srgqt.js +10 -0
  64. package/dist/index.html +1 -1
  65. package/dist/openai-ep9ht2pq.svg +1 -0
  66. package/lib/ids.ts +15 -0
  67. package/lib/moi-context.ts +170 -0
  68. package/lib/types.ts +95 -13
  69. package/lib/view-builder-directives.ts +16 -0
  70. package/lib/workspace-types.ts +12 -0
  71. package/package.json +4 -2
  72. package/server/api.ts +180 -34
  73. package/server/applet-log.ts +149 -0
  74. package/server/cli.ts +161 -7
  75. package/server/control.ts +81 -1
  76. package/server/functions.ts +44 -14
  77. package/server/harness/README.md +26 -9
  78. package/server/harness/claude-code/NOTES.md +20 -6
  79. package/server/harness/claude-code/adapter.ts +2 -2
  80. package/server/harness/claude-code/git-worktree.ts +32 -0
  81. package/server/harness/claude-code/index.ts +35 -13
  82. package/server/harness/claude-code/mcp.ts +16 -65
  83. package/server/harness/claude-code/models.ts +3 -0
  84. package/server/harness/claude-code/session.ts +196 -61
  85. package/server/harness/claude-code/sessions.ts +51 -0
  86. package/server/harness/codex/NOTES.md +41 -11
  87. package/server/harness/codex/adapter.ts +52 -6
  88. package/server/harness/codex/client.ts +69 -18
  89. package/server/harness/codex/discovery.ts +114 -0
  90. package/server/harness/codex/index.ts +12 -5
  91. package/server/harness/codex/probe.ts +4 -2
  92. package/server/harness/codex/session.ts +57 -5
  93. package/server/harness/executable.ts +82 -0
  94. package/server/harness/openclaw/adapter.ts +8 -1
  95. package/server/harness/openclaw/discovery.ts +139 -6
  96. package/server/harness/openclaw/gateway.ts +40 -18
  97. package/server/harness/openclaw/index.ts +12 -15
  98. package/server/harness/openclaw/session.ts +50 -10
  99. package/server/harness/openclaw/strip.ts +2 -2
  100. package/server/harness/shell-path.ts +79 -0
  101. package/server/harness/types.ts +37 -5
  102. package/server/layout.ts +81 -51
  103. package/server/registry.ts +57 -12
  104. package/server/scratchpad-assets.ts +41 -6
  105. package/server/scratchpad.ts +30 -0
  106. package/server/view-builders.ts +3 -2
  107. package/server/views.ts +5 -0
  108. package/server/web.ts +30 -8
  109. package/server/widgets.ts +23 -2
  110. package/server/workspace-import.ts +45 -0
  111. package/workspace/.claude/skills/moi-workspace/SKILL.md +27 -3
  112. package/client/features/connectors/ConnectorsPage.tsx +0 -92
  113. package/client/features/connectors/McpMenu.tsx +0 -145
  114. package/client/features/home/CreateWorkspaceDialog.tsx +0 -130
  115. package/client/features/home/CreateWorkspaceDialogSteps.tsx +0 -234
  116. package/dist/chunk-4vf1t6v1.js +0 -10
  117. package/dist/chunk-4z52b2av.css +0 -1
  118. package/dist/chunk-b4b276wx.js +0 -15
  119. package/dist/chunk-y82s1jxm.js +0 -61
  120. package/dist/openai-h13pza4b.svg +0 -3
  121. package/lib/view-builder-meta.ts +0 -35
package/server/api.ts CHANGED
@@ -4,19 +4,34 @@ import { createMiddleware } from 'hono/factory'
4
4
  import { existsSync } from 'node:fs'
5
5
  import { basename, join, resolve } from 'node:path'
6
6
 
7
- import type { UploadInfo, ViewBuilderInput, WorkspaceEntry, WorkspaceModels } from '@/lib/types'
8
- import { appendViewBuilderMeta } from '@/lib/view-builder-meta'
9
-
7
+ import type {
8
+ HarnessAvailability,
9
+ UploadInfo,
10
+ ViewBuilderInput,
11
+ WorkspaceEntry,
12
+ WorkspaceModels,
13
+ WorkspaceType
14
+ } from '@/lib/types'
15
+ import type { MoiContext } from '@/lib/moi-context'
16
+ import { viewBuilderDirectives } from '@/lib/view-builder-directives'
17
+
18
+ import { appletForModule, recordAppletError } from './applet-log'
10
19
  import { apiBaseFor, parseAppletTail, serveWorkspaceFile } from './applets'
11
20
  import { applyEnvChanged } from './env-apply'
12
21
  import { publishEvent } from './events'
13
22
  import { callFunction, parseFunctionPath } from './functions'
14
23
  import { processIcon } from './icon'
15
- import { getWorkspacePreview, loadLayout, mergeLayoutForSave, saveLayout } from './layout'
16
- import { getUserMcpStatus } from './harness/claude-code/mcp'
24
+ import {
25
+ getWorkspacePreview,
26
+ loadLayout,
27
+ mergeLayoutForSave,
28
+ saveLayout,
29
+ saveWidgetThumbnails
30
+ } from './layout'
17
31
  import { getClientFrameLog, getWireLog } from './harness/debug'
18
32
  import { allHarnesses, harnessFor, isHarnessType } from './harness/registry'
19
33
  import {
34
+ discoverWorkspace,
20
35
  discoverWorkspaces,
21
36
  getWorkspace,
22
37
  listWorkspaces,
@@ -50,6 +65,8 @@ import {
50
65
  provisionWorkspace,
51
66
  validateWorkspaceFolderName
52
67
  } from './workspace-init'
68
+ import { resolveWorkspaceImportMetadata } from './workspace-import'
69
+ import type { WorkspaceImportMetadata } from './workspace-import'
53
70
  import { getWorkspaceEnvView, isValidEnvKey, updateWorkspaceEnv } from './workspace-env'
54
71
  import type { EnvUpdate } from './workspace-env'
55
72
 
@@ -82,6 +99,15 @@ async function handleFunctionCall(
82
99
  })
83
100
  } catch (err) {
84
101
  const message = err instanceof Error ? err.message : 'Unknown error'
102
+ // Journal the failure so the agent can find it via `moi debug logs` — the
103
+ // 500 body below only reaches the browser (see docs/self-correction.md).
104
+ recordAppletError(workspacePath, {
105
+ source: 'rpc',
106
+ ...(appletForModule(module) ?? {}),
107
+ module,
108
+ fn: name,
109
+ message
110
+ })
85
111
  return new Response(message, { status: 500 })
86
112
  }
87
113
  }
@@ -101,7 +127,12 @@ const one = new Hono<ApiEnv>()
101
127
  one.use('*', withWorkspace)
102
128
 
103
129
  one.get('/preview', async c => {
104
- return c.json(await getWorkspacePreview(c.get('ws').path))
130
+ const ws = c.get('ws')
131
+ return c.json(
132
+ await getWorkspacePreview(ws.path, includeFirstUserMessage =>
133
+ harnessFor(ws).workspacePreview(ws, includeFirstUserMessage)
134
+ )
135
+ )
105
136
  })
106
137
 
107
138
  one.get('/widgets', c => listWidgets(c.get('ws').path))
@@ -145,7 +176,7 @@ one.get('/view-builders', async c => {
145
176
  const ws = c.get('ws')
146
177
  const activeSessionIds = new Set(
147
178
  allHarnesses()
148
- .flatMap(h => h.runningSessions())
179
+ .flatMap(h => h.activeSessions())
149
180
  .filter(session => session.workspaceId === ws.id)
150
181
  .map(session => session.sessionId)
151
182
  )
@@ -205,6 +236,8 @@ one.post('/view-builders/:builderId/submit', async c => {
205
236
  }
206
237
  const availableIcons = parseAvailableViewIcons(body.availableIcons)
207
238
  if (!availableIcons) return c.text('Available view icons are required', 400)
239
+ const availability = await workspaceTypeAvailability(ws.type ?? 'claude-code')
240
+ if (!availability.available) return c.text(availability.reason, 400)
208
241
  try {
209
242
  const builder = await beginViewBuilder(
210
243
  ws.id,
@@ -212,14 +245,21 @@ one.post('/view-builders/:builderId/submit', async c => {
212
245
  c.req.param('builderId'),
213
246
  body.input.requirements
214
247
  )
215
- const content = appendViewBuilderMeta(builder.input.requirements, builder.id, availableIcons)
248
+ // The bootstrap instructions ride the moi-context envelope, injected by
249
+ // the harness like any other ambient context; the user text stays bare.
250
+ // The user submits from the builder's own tab, so that's the active tab.
251
+ const context: MoiContext = {
252
+ activeTab: `view-builder:${builder.id}`,
253
+ directives: viewBuilderDirectives(builder.id, availableIcons)
254
+ }
216
255
  try {
217
256
  await harnessFor(ws).sendMessage({
218
257
  workspaceId: ws.id,
219
258
  workspacePath: ws.path,
220
259
  sessionId: builder.sessionId,
221
260
  isNew: true,
222
- content,
261
+ content: builder.input.requirements,
262
+ context,
223
263
  optimisticId: body.optimisticId,
224
264
  model: typeof body.model === 'string' ? body.model : undefined,
225
265
  effort: typeof body.effort === 'string' ? body.effort : undefined,
@@ -276,6 +316,44 @@ one.post('/rpc/*', c => {
276
316
  return handleFunctionCall(c.req.raw, tail, c.get('ws').path)
277
317
  })
278
318
 
319
+ // Browser-side applet errors (module load failures, render crashes, window
320
+ // errors attributed to a bundle) reported into the workspace's error journal —
321
+ // `moi debug logs` reads it back (docs/self-correction.md). Unauthenticated
322
+ // localhost route, so treat the payload as hostile: whitelist the browser-only
323
+ // sources (`build`/`rpc` are server-recorded and can't be spoofed by a tab),
324
+ // pattern-check the applet name, cap the batch size; applet-log.ts caps string
325
+ // lengths.
326
+ one.post('/applet-log', async c => {
327
+ let body: { events?: unknown }
328
+ try {
329
+ body = await c.req.json()
330
+ } catch {
331
+ return c.text('Invalid JSON', 400)
332
+ }
333
+ const events = Array.isArray(body.events) ? body.events.slice(0, 10) : []
334
+ for (const raw of events) {
335
+ const e = raw as {
336
+ source?: unknown
337
+ kind?: unknown
338
+ name?: unknown
339
+ message?: unknown
340
+ stack?: unknown
341
+ }
342
+ if (e.source !== 'load' && e.source !== 'render' && e.source !== 'window') continue
343
+ if (e.kind !== 'widget' && e.kind !== 'view') continue
344
+ if (typeof e.name !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(e.name)) continue
345
+ if (typeof e.message !== 'string' || !e.message) continue
346
+ recordAppletError(c.get('ws').path, {
347
+ source: e.source,
348
+ kind: e.kind,
349
+ name: e.name,
350
+ message: e.message,
351
+ ...(typeof e.stack === 'string' ? { stack: e.stack } : {})
352
+ })
353
+ }
354
+ return c.body(null, 204)
355
+ })
356
+
279
357
  // Downscaled image preview of a workspace file. The chat's expanded tool rows
280
358
  // use this to show the picture an agent `Read` — same guards as /fs/ above,
281
359
  // images only, resized server-side (see server/preview.ts).
@@ -459,15 +537,30 @@ one.put('/env', async c => {
459
537
  return c.json(await getWorkspaceEnvView(ws.path, requiredEnvFor(ws.path)))
460
538
  })
461
539
 
540
+ // Is the workspace's agent backend usable right now? (e.g. a codex workspace
541
+ // on a machine without the codex CLI). The chat surfaces the `reason` as a
542
+ // banner instead of letting the first send fail cold.
543
+ one.get('/availability', async c => {
544
+ const availability = await workspaceTypeAvailability(c.get('ws').type ?? 'claude-code')
545
+ return c.json(availability satisfies HarnessAvailability)
546
+ })
547
+
462
548
  // Models the workspace's agent backend can run, normalized across providers.
463
549
  // OpenClaw queries the gateway catalog; everything else (Claude Code) reads the
464
550
  // account-wide Agent SDK model list.
465
551
  one.get('/models', async c => {
466
552
  const ws = c.get('ws')
467
553
  const harness = harnessFor(ws)
554
+ // A backend that can't answer (codex CLI missing, gateway down) degrades to
555
+ // an empty catalog — the picker hides and chat surfaces the real problem via
556
+ // the availability banner, instead of this endpoint 500ing on page load.
557
+ const models = await harness.listModels(ws).catch(err => {
558
+ console.error(`[api] listModels failed for ${harness.id}`, err)
559
+ return []
560
+ })
468
561
  return c.json({
469
562
  provider: harness.id,
470
- models: await harness.listModels(ws),
563
+ models,
471
564
  supportsStreaming: harness.capabilities.supportsStreaming
472
565
  } satisfies WorkspaceModels)
473
566
  })
@@ -583,9 +676,16 @@ one.delete('/icon', async c => {
583
676
  // DELETE unregisters.
584
677
  one.get('/', async c => {
585
678
  const ws = c.get('ws')
586
- const layout = await loadLayout(ws.path)
679
+ // The thumbnail images are heavy (base64 WebPs) and have their own write
680
+ // path (PUT .../thumbnails); the layout ships `widgetThumbnails` without
681
+ // them — just `key`/`at`, which clients compare against the live grid to
682
+ // decide when to re-capture.
683
+ const { widgetThumbnails, ...layout } = await loadLayout(ws.path)
587
684
  return c.json({
588
685
  ...layout,
686
+ ...(widgetThumbnails && {
687
+ widgetThumbnails: { key: widgetThumbnails.key, at: widgetThumbnails.at }
688
+ }),
589
689
  // Resolved display name: the settings override, or the folder name.
590
690
  name: layout.name || basename(ws.path),
591
691
  cwd: ws.path,
@@ -594,6 +694,24 @@ one.get('/', async c => {
594
694
  })
595
695
  })
596
696
 
697
+ // Widget thumbnails: a separate write path from the layout PUT below, so grid
698
+ // and theme saves never round-trip the base64 map (and this save can't touch
699
+ // the grid). Still lands in `.workspace.json` under the hood. Entries merge
700
+ // over the stored map; `key` fingerprints the grid state they were captured
701
+ // from (see widgetThumbnailsKey() on the client).
702
+ one.put('/thumbnails', async c => {
703
+ const body: unknown = await c.req.json().catch(() => null)
704
+ if (!body || typeof body !== 'object') return c.text('Bad request', 400)
705
+ const { key, thumbnails } = body as { key?: unknown; thumbnails?: unknown }
706
+ const validMap =
707
+ thumbnails !== null &&
708
+ typeof thumbnails === 'object' &&
709
+ Object.values(thumbnails as Record<string, unknown>).every(v => typeof v === 'string')
710
+ if (typeof key !== 'string' || !validMap) return c.text('Bad request', 400)
711
+ await saveWidgetThumbnails(c.get('ws').path, key, thumbnails as Record<string, string>)
712
+ return c.body(null, 204)
713
+ })
714
+
597
715
  one.put('/', async c => {
598
716
  const ws = c.get('ws')
599
717
  const body = await c.req.json()
@@ -651,9 +769,19 @@ workspaces.put('/order', async c => {
651
769
  workspaces.post('/', async c => {
652
770
  const body = await c.req.json()
653
771
  if (!body?.path) return c.text('Missing path', 400)
654
- const rawType = body?.type
655
- const type = isHarnessType(rawType) ? rawType : undefined
772
+ const requestedType: unknown = body?.type ?? 'claude-code'
773
+ if (!isHarnessType(requestedType)) return c.text('Unknown workspace type', 400)
774
+ const type: WorkspaceType = requestedType
775
+ const availability = await workspaceTypeAvailability(type)
776
+ if (!availability.available) return c.text(availability.reason, 400)
656
777
  const path = resolve(String(body.path))
778
+ let metadata: WorkspaceImportMetadata
779
+ try {
780
+ metadata = await resolveWorkspaceImportMetadata(path, type)
781
+ } catch (err) {
782
+ const message = err instanceof Error ? err.message : String(err)
783
+ return c.text(message, 400)
784
+ }
657
785
  // Importing IS initializing: lay down the bundled skills (in the backend's
658
786
  // skills dir) and the `.moi/` scaffold, exactly like `moi init` — a workspace
659
787
  // added from the UI must be indistinguishable from one added via the CLI.
@@ -665,48 +793,70 @@ workspaces.post('/', async c => {
665
793
  }
666
794
  const entry = await registerWorkspace(path, {
667
795
  type,
668
- name: typeof body?.name === 'string' ? body.name : undefined,
669
- agentId: typeof body?.agentId === 'string' ? body.agentId : undefined,
670
- isDefault: typeof body?.isDefault === 'boolean' ? body.isDefault : undefined,
671
- lastRunAt: typeof body?.lastRunAt === 'string' ? body.lastRunAt : undefined
796
+ ...metadata
672
797
  })
673
798
  return c.json(entry, 201)
674
799
  })
675
800
 
676
801
  workspaces.get('/discover', async c => c.json(await discoverWorkspaces()))
677
802
 
803
+ // Backends the create dialog can provision from scratch. OpenClaw workspaces
804
+ // belong to their agents and arrive via discovery.
805
+ const CREATABLE_TYPES = new Set<WorkspaceType>(['claude-code', 'codex'])
806
+
807
+ async function workspaceTypeAvailability(type: WorkspaceType): Promise<HarnessAvailability> {
808
+ return (await harnessFor(type).availability?.()) ?? { available: true }
809
+ }
810
+
811
+ // Per-backend runtime availability, keyed by workspace type. Harnesses without
812
+ // the hook are always available.
813
+ async function harnessAvailability(): Promise<Record<string, HarnessAvailability>> {
814
+ const out: Record<string, HarnessAvailability> = {}
815
+ for (const h of allHarnesses()) {
816
+ out[h.id] = await workspaceTypeAvailability(h.id)
817
+ }
818
+ return out
819
+ }
820
+
678
821
  // Where `/workspace/create` places new folders — the client shows the resolved
679
822
  // location while the user types a name. `canChooseFolder` tells the UI whether
680
- // the native folder picker is available (macOS only for now).
681
- workspaces.get('/create', c =>
823
+ // the native folder picker is available (macOS only for now). `availability`
824
+ // lets the dialog disable backends whose runtime is missing.
825
+ workspaces.get('/create', async c =>
682
826
  c.json({
683
827
  root: CREATED_WORKSPACES_ROOT,
684
828
  displayRoot: tildify(CREATED_WORKSPACES_ROOT),
685
- canChooseFolder: process.platform === 'darwin'
829
+ canChooseFolder: process.platform === 'darwin',
830
+ availability: await harnessAvailability()
686
831
  })
687
832
  )
688
833
 
689
834
  // Create a brand-new workspace: a fresh folder under CREATED_WORKSPACES_ROOT,
690
- // provisioned (skills + `.moi/` scaffold) and registered. Claude Code only for
691
- // now — OpenClaw workspaces belong to their agents and arrive via discovery.
835
+ // provisioned (skills + `.moi/` scaffold) and registered.
692
836
  workspaces.post('/create', async c => {
693
837
  const body = await c.req.json()
694
- const type = body?.type ?? 'claude-code'
695
- if (type !== 'claude-code') {
696
- return c.text('Only Claude Code workspaces can be created for now', 400)
838
+ const requestedType: unknown = body?.type ?? 'claude-code'
839
+ if (!isHarnessType(requestedType)) {
840
+ return c.text('Unknown workspace type', 400)
697
841
  }
842
+ const type: WorkspaceType = requestedType
843
+ if (!CREATABLE_TYPES.has(type)) {
844
+ return c.text('Workspaces of this type arrive through discovery, not creation', 400)
845
+ }
846
+ const availability = await workspaceTypeAvailability(type)
847
+ if (!availability.available) return c.text(availability.reason, 400)
698
848
  const name = typeof body?.name === 'string' ? body.name.trim() : ''
699
849
  const invalid = validateWorkspaceFolderName(name)
700
850
  if (invalid) return c.text(invalid, 400)
701
851
  const path = join(CREATED_WORKSPACES_ROOT, name)
702
852
  if (existsSync(path)) return c.text('A folder with that name already exists', 409)
703
853
  try {
704
- await provisionWorkspace(path, 'claude-code')
854
+ await provisionWorkspace(path, type)
705
855
  } catch (err) {
706
856
  const message = err instanceof Error ? err.message : String(err)
707
857
  return c.text(`Could not create workspace: ${message}`, 500)
708
858
  }
709
- const entry = await registerWorkspace(path, { type: 'claude-code' })
859
+ const entry = await registerWorkspace(path, { type })
710
860
  // Nudge every connected client (the sidebar list) to refetch.
711
861
  publishEvent({ type: 'workspaces-list:updated' })
712
862
  return c.json(entry, 201)
@@ -740,8 +890,8 @@ export function isSameOriginRequest(req: Request): boolean {
740
890
  // Open the OS-native folder picker so the user can choose an existing folder to
741
891
  // import (the create dialog's "Use existing folder"). The server runs on the
742
892
  // user's machine, so it can drive the real system dialog — the browser can't.
743
- // Returns the chosen POSIX path, or `{ canceled: true }` if the dialog is
744
- // dismissed. macOS only for now (via `osascript`).
893
+ // Returns the same grouped provider discovery shape as `/discover`, or
894
+ // `{ canceled: true }` if the dialog is dismissed. macOS only for now.
745
895
  workspaces.post('/choose-folder', async c => {
746
896
  if (!isSameOriginRequest(c.req.raw)) return c.text('Forbidden', 403)
747
897
  if (process.platform !== 'darwin') {
@@ -771,7 +921,7 @@ workspaces.post('/choose-folder', async c => {
771
921
  if (exitCode !== 0) return c.json({ canceled: true })
772
922
  const path = (await new Response(proc.stdout).text()).trim()
773
923
  if (!path) return c.json({ canceled: true })
774
- return c.json({ path })
924
+ return c.json(await discoverWorkspace(path))
775
925
  } catch (err) {
776
926
  const message = err instanceof Error ? err.message : String(err)
777
927
  return c.text(`Could not open the folder picker: ${message}`, 500)
@@ -788,10 +938,6 @@ workspaces.route('/:id', one)
788
938
  // ---- top-level API ----------------------------------------------------------
789
939
  export const api = new Hono()
790
940
 
791
- api.get('/api/mcp', async c => {
792
- return c.json(await getUserMcpStatus())
793
- })
794
-
795
941
  api.route('/api/workspaces', workspaces)
796
942
 
797
943
  // Everything else: in production, serve the prebuilt client from `dist/` via
@@ -0,0 +1,149 @@
1
+ // Per-workspace, in-memory journal of applet runtime errors — the "feel" leg of
2
+ // the self-correction loop (docs/self-correction.md). The agent builds applets
3
+ // but never sees them run; this journal collects what breaks afterwards (module
4
+ // load failures, render crashes, window errors attributed to a bundle, RPC
5
+ // failures, standing build failures) so `moi debug logs` can answer "what's
6
+ // broken right now that I'd otherwise not know about?".
7
+ //
8
+ // Deliberately NOT observability: no persistence (a server restart starts
9
+ // clean — the journal describes the current runtime), no levels, bounded size.
10
+ // Entries hold the *standing* problems since each applet's last good build: a
11
+ // successful rebuild clears that applet's entries, because they describe a
12
+ // bundle that no longer exists.
13
+ import type { AppletKind, AppletLogEntry, AppletLogSource } from '@/lib/types'
14
+
15
+ const MAX_ENTRIES = 100
16
+ const MAX_MESSAGE_CHARS = 1000
17
+ const MAX_STACK_CHARS = 4000
18
+
19
+ // workspacePath -> entries, oldest → newest.
20
+ const journals = new Map<string, AppletLogEntry[]>()
21
+
22
+ export type AppletErrorInput = {
23
+ source: AppletLogSource
24
+ kind?: AppletKind
25
+ name?: string
26
+ module?: string
27
+ fn?: string
28
+ message: string
29
+ stack?: string
30
+ }
31
+
32
+ // Identity for dedup: a repeat of the same error (same source + attribution +
33
+ // message) bumps `count` instead of appending. Stack is deliberately excluded —
34
+ // minified column drift would defeat the dedup.
35
+ function dedupKey(e: {
36
+ source: string
37
+ kind?: string
38
+ name?: string
39
+ module?: string
40
+ fn?: string
41
+ message: string
42
+ }): string {
43
+ return [e.source, e.kind ?? '', e.name ?? '', e.module ?? '', e.fn ?? '', e.message].join('\0')
44
+ }
45
+
46
+ export function recordAppletError(workspacePath: string, input: AppletErrorInput): void {
47
+ const entries = journals.get(workspacePath) ?? []
48
+ const message = input.message.slice(0, MAX_MESSAGE_CHARS)
49
+ const key = dedupKey({ ...input, message })
50
+
51
+ const existingIdx = entries.findIndex(e => dedupKey(e) === key)
52
+ if (existingIdx !== -1) {
53
+ // Repeat: bump the counter, refresh the timestamp, move to the tail so the
54
+ // journal stays ordered by last occurrence.
55
+ const [existing] = entries.splice(existingIdx, 1)
56
+ existing.count++
57
+ existing.ts = Date.now()
58
+ entries.push(existing)
59
+ } else {
60
+ entries.push({
61
+ ts: Date.now(),
62
+ source: input.source,
63
+ ...(input.kind ? { kind: input.kind } : {}),
64
+ ...(input.name ? { name: input.name } : {}),
65
+ ...(input.module ? { module: input.module } : {}),
66
+ ...(input.fn ? { fn: input.fn } : {}),
67
+ message,
68
+ ...(input.stack ? { stack: input.stack.slice(0, MAX_STACK_CHARS) } : {}),
69
+ count: 1
70
+ })
71
+ if (entries.length > MAX_ENTRIES) entries.shift()
72
+ }
73
+ journals.set(workspacePath, entries)
74
+ }
75
+
76
+ // Snapshot, oldest → newest. Copies so callers can't mutate the journal.
77
+ export function getAppletLog(workspacePath: string): AppletLogEntry[] {
78
+ return (journals.get(workspacePath) ?? []).map(e => ({ ...e }))
79
+ }
80
+
81
+ export function getAppletLogCount(workspacePath: string): number {
82
+ return journals.get(workspacePath)?.length ?? 0
83
+ }
84
+
85
+ // Wipe the journal (`moi debug logs --clear`). Returns how many were dropped.
86
+ export function clearAppletLog(workspacePath: string): number {
87
+ const count = getAppletLogCount(workspacePath)
88
+ journals.delete(workspacePath)
89
+ return count
90
+ }
91
+
92
+ // Attribute an RPC module key to its applet: `widgets/hello` → widget "hello",
93
+ // `views/crm` → view "crm". Shared modules (`lib/db`) attribute to nothing —
94
+ // the entry still carries `module`/`fn`.
95
+ export function appletForModule(module: string): { kind: AppletKind; name: string } | null {
96
+ const m = module.match(/^(widgets|views)\/([^/]+)$/)
97
+ if (!m) return null
98
+ return { kind: m[1] === 'widgets' ? 'widget' : 'view', name: m[2] }
99
+ }
100
+
101
+ type BuildResultLike = {
102
+ name: string
103
+ status: 'built' | 'skipped' | 'failed'
104
+ error?: string
105
+ serverModules?: string[]
106
+ }
107
+
108
+ // Reconcile the journal with one kind's bundle results: a failure lands in the
109
+ // journal (so it stays on record turns later), a successful build clears the
110
+ // applet's standing entries — its browser-side errors describe a bundle that no
111
+ // longer exists — plus `rpc` entries for the server modules rebuilt with it.
112
+ // Every current source yields a result row (built/skipped/failed), so the
113
+ // result set doubles as the source list and entries for deleted applets are
114
+ // swept too.
115
+ export function syncAppletLogAfterBuild(
116
+ workspacePath: string,
117
+ kind: AppletKind,
118
+ results: BuildResultLike[]
119
+ ): void {
120
+ const rebuiltModules = new Set<string>()
121
+ const clearedNames = new Set<string>()
122
+ const present = new Set(results.map(r => r.name))
123
+
124
+ for (const r of results) {
125
+ if (r.status === 'failed') {
126
+ recordAppletError(workspacePath, {
127
+ source: 'build',
128
+ kind,
129
+ name: r.name,
130
+ message: r.error ?? 'Build failed'
131
+ })
132
+ }
133
+ if (r.status === 'built') {
134
+ clearedNames.add(r.name)
135
+ for (const m of r.serverModules ?? []) rebuiltModules.add(m)
136
+ }
137
+ }
138
+
139
+ const entries = journals.get(workspacePath)
140
+ if (!entries) return
141
+ const kept = entries.filter(e => {
142
+ if (e.kind === kind && e.name && (clearedNames.has(e.name) || !present.has(e.name))) {
143
+ return false
144
+ }
145
+ if (e.source === 'rpc' && e.module && rebuiltModules.has(e.module)) return false
146
+ return true
147
+ })
148
+ journals.set(workspacePath, kept)
149
+ }