moi-computer 0.3.0 → 0.3.1-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/client/app/routes/WorkspaceRoute.tsx +3 -1
  2. package/client/components/shared/Composer.tsx +61 -0
  3. package/client/components/ui/dropdown-menu.tsx +3 -3
  4. package/client/features/applets/WidgetErrorBoundary.tsx +19 -3
  5. package/client/features/applets/WidgetShell.tsx +8 -1
  6. package/client/features/applets/applet-log.ts +100 -0
  7. package/client/features/applets/useApplet.ts +21 -7
  8. package/client/features/chat/ChatComposer.tsx +9 -16
  9. package/client/features/chat/ModelPicker.tsx +26 -40
  10. package/client/features/chat/chat-frames.ts +1 -0
  11. package/client/features/chat/model-order.ts +47 -0
  12. package/client/features/chat/useChat.ts +4 -0
  13. package/client/features/home/HomePage.tsx +13 -15
  14. package/client/features/home/WorkspacePreview.tsx +179 -38
  15. package/client/features/settings/GeneralSettings.tsx +12 -0
  16. package/client/features/views/ViewBuilderTab.tsx +10 -15
  17. package/client/features/widgets/WidgetFrame.tsx +3 -0
  18. package/client/features/widgets/WidgetGrid.tsx +1 -0
  19. package/client/features/widgets/Widgets.tsx +12 -3
  20. package/client/features/widgets/api.ts +47 -0
  21. package/client/features/widgets/useWidgetThumbnails.ts +107 -0
  22. package/client/features/widgets/widget-snapshot.ts +71 -0
  23. package/client/features/workspace/WorkspaceScreen.tsx +8 -1
  24. package/client/features/workspace/api.ts +6 -2
  25. package/client/index.css +0 -5
  26. package/client/main.tsx +6 -0
  27. package/dist/{chunk-fjksw6xf.js → chunk-axszxe4c.js} +1 -1
  28. package/dist/chunk-b3ynfk4g.js +62 -0
  29. package/dist/chunk-jen6xcm1.js +14 -0
  30. package/dist/chunk-npwq6jmr.css +1 -0
  31. package/dist/index.html +1 -1
  32. package/lib/types.ts +66 -2
  33. package/package.json +3 -2
  34. package/server/api.ts +87 -3
  35. package/server/applet-log.ts +149 -0
  36. package/server/cli.ts +161 -7
  37. package/server/control.ts +81 -1
  38. package/server/functions.ts +44 -14
  39. package/server/harness/README.md +1 -0
  40. package/server/harness/claude-code/index.ts +3 -1
  41. package/server/harness/claude-code/sessions.ts +51 -0
  42. package/server/harness/codex/adapter.ts +32 -0
  43. package/server/harness/codex/client.ts +36 -1
  44. package/server/harness/codex/index.ts +3 -0
  45. package/server/harness/openclaw/discovery.ts +139 -6
  46. package/server/harness/openclaw/gateway.ts +40 -18
  47. package/server/harness/openclaw/index.ts +4 -1
  48. package/server/harness/types.ts +15 -0
  49. package/server/layout.ts +81 -51
  50. package/server/scratchpad-assets.ts +41 -6
  51. package/server/scratchpad.ts +30 -0
  52. package/server/views.ts +5 -0
  53. package/server/web.ts +6 -0
  54. package/server/widgets.ts +23 -2
  55. package/workspace/.claude/skills/moi-workspace/SKILL.md +24 -0
  56. package/dist/chunk-4z52b2av.css +0 -1
  57. package/dist/chunk-y82s1jxm.js +0 -61
package/dist/index.html CHANGED
@@ -21,7 +21,7 @@
21
21
  }
22
22
  </script>
23
23
 
24
- <link rel="stylesheet" crossorigin href="/chunk-4z52b2av.css"><script type="module" crossorigin src="/chunk-fjksw6xf.js"></script></head>
24
+ <link rel="stylesheet" crossorigin href="/chunk-npwq6jmr.css"><script type="module" crossorigin src="/chunk-axszxe4c.js"></script></head>
25
25
  <body>
26
26
  <div id="root"></div>
27
27
 
package/lib/types.ts CHANGED
@@ -12,6 +12,11 @@ export type WidgetConfig = {
12
12
  export type WidgetInfo = {
13
13
  id: string
14
14
  config: WidgetConfig
15
+ // Content tag of the built bundle (`<size>-<mtime>` of its index.js) —
16
+ // changes whenever the widget is rebundled. Clients compare it against
17
+ // `WidgetThumbnail.tag` to decide which thumbnails are stale. Absent when
18
+ // the build output can't be statted.
19
+ tag?: string
15
20
  }
16
21
 
17
22
  // A view is a full-screen, agent-authored "app" (`.moi/views/<name>.tsx`),
@@ -60,6 +65,40 @@ export type ViewBuilder = {
60
65
  updatedAt: number
61
66
  }
62
67
 
68
+ // ---- Applet error journal (see docs/self-correction.md) ------------------
69
+
70
+ // Where an applet error was observed. `build` and `rpc` are recorded
71
+ // server-side (bundle pipeline, RPC route); `load`/`render`/`window` are
72
+ // browser-side and reach the journal via POST /api/workspaces/:id/applet-log.
73
+ export type AppletLogSource = 'build' | 'load' | 'render' | 'window' | 'rpc'
74
+
75
+ // One journal entry, as returned to `moi debug logs`. `kind`/`name` attribute
76
+ // the applet when known; `module`/`fn` pin down the server function for `rpc`
77
+ // entries. `count` dedups repeats of the identical error (crash loops are one
78
+ // line, not a hundred); `ts` is the LAST occurrence.
79
+ export type AppletLogEntry = {
80
+ ts: number
81
+ source: AppletLogSource
82
+ kind?: AppletKind
83
+ name?: string
84
+ module?: string
85
+ fn?: string
86
+ message: string
87
+ stack?: string
88
+ count: number
89
+ }
90
+
91
+ // The browser-reported subset (the server-side sources can't be spoofed by a
92
+ // tab — the POST route rejects them).
93
+ export type AppletClientErrorSource = 'load' | 'render' | 'window'
94
+ export type AppletClientError = {
95
+ source: AppletClientErrorSource
96
+ kind: AppletKind
97
+ name: string
98
+ message: string
99
+ stack?: string
100
+ }
101
+
63
102
  // A Scratchpad draw/view operation issued by `moi scratch`. Mutations run
64
103
  // server-side against a headless tldraw store; `view` relays to a live tab. The
65
104
  // server assigns each add op a `name` (the `--id`, or a generated one) so the
@@ -427,11 +466,36 @@ export type WorkspaceLayout = {
427
466
  background?: string
428
467
  foreground?: string
429
468
  }
469
+ // Widget thumbnails captured client-side from the live grid, used for
470
+ // home-screen previews. Saved through their own endpoint (PUT
471
+ // .../thumbnails), never through the layout PUT.
472
+ widgetThumbnails?: WidgetThumbnails
473
+ }
474
+
475
+ export type WidgetThumbnails = {
476
+ // Fingerprint of the grid state the set was captured from (visible widget
477
+ // ids + their bundle tags — see widgetThumbnailsKey()). A mismatch with the
478
+ // live grid re-captures the whole set.
479
+ key?: string
480
+ // Server-stamped ISO time of the last save. Widget DATA drifts even when
481
+ // bundles don't (a dashboard captured in January still shows January), so
482
+ // an old-enough set re-captures despite a matching key.
483
+ at?: string
484
+ // Widget id → WebP data URL (white background, the widget's own aspect
485
+ // ratio). Entries merge, never prune: a removed widget keeps its last image
486
+ // in case it comes back. Heavy — the layout GET strips this field; images
487
+ // reach the home screen via the preview endpoint.
488
+ images?: Record<string, string>
430
489
  }
431
490
 
491
+ // Home-screen workspace card preview: a few captured widget thumbnails (WebP
492
+ // data URLs) from the stored layout, rendered as a loose stack, plus the latest
493
+ // provider session activity. A workspace with no widgets may instead carry its
494
+ // oldest thread's first user message.
432
495
  export type WorkspacePreview = {
433
- cols: number
434
- items: { x: number; y: number; w: number; h: number }[]
496
+ thumbnails: string[]
497
+ firstUserMessage?: string
498
+ updatedAt?: number
435
499
  }
436
500
 
437
501
  // One effective env var, as surfaced by GET /api/workspaces/:id/env. Values are
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "moi-computer",
3
- "version": "0.3.0",
3
+ "version": "0.3.1-next.0",
4
4
  "description": "Local AI workspace powered by the Claude Agent SDK, Bun, React, and Tailwind. Requires Bun.",
5
5
  "license": "Elastic-2.0",
6
6
  "type": "module",
@@ -75,6 +75,7 @@
75
75
  "highlight.js": "^10.7.3",
76
76
  "hono": "^4.12.26",
77
77
  "lru-cache": "^11.3.5",
78
+ "modern-screenshot": "^4.7.0",
78
79
  "motion": "^12.35.1",
79
80
  "pathe": "^2.0.3",
80
81
  "picocolors": "^1.1.1",
@@ -98,7 +99,7 @@
98
99
  "zustand": "^5.0.12"
99
100
  },
100
101
  "optionalDependencies": {
101
- "openclaw": "2026.4.22"
102
+ "openclaw": "2026.7.1"
102
103
  },
103
104
  "devDependencies": {
104
105
  "@types/bun": "latest",
package/server/api.ts CHANGED
@@ -7,12 +7,19 @@ import { basename, join, resolve } from 'node:path'
7
7
  import type { UploadInfo, ViewBuilderInput, WorkspaceEntry, WorkspaceModels } from '@/lib/types'
8
8
  import { appendViewBuilderMeta } from '@/lib/view-builder-meta'
9
9
 
10
+ import { appletForModule, recordAppletError } from './applet-log'
10
11
  import { apiBaseFor, parseAppletTail, serveWorkspaceFile } from './applets'
11
12
  import { applyEnvChanged } from './env-apply'
12
13
  import { publishEvent } from './events'
13
14
  import { callFunction, parseFunctionPath } from './functions'
14
15
  import { processIcon } from './icon'
15
- import { getWorkspacePreview, loadLayout, mergeLayoutForSave, saveLayout } from './layout'
16
+ import {
17
+ getWorkspacePreview,
18
+ loadLayout,
19
+ mergeLayoutForSave,
20
+ saveLayout,
21
+ saveWidgetThumbnails
22
+ } from './layout'
16
23
  import { getUserMcpStatus } from './harness/claude-code/mcp'
17
24
  import { getClientFrameLog, getWireLog } from './harness/debug'
18
25
  import { allHarnesses, harnessFor, isHarnessType } from './harness/registry'
@@ -82,6 +89,15 @@ async function handleFunctionCall(
82
89
  })
83
90
  } catch (err) {
84
91
  const message = err instanceof Error ? err.message : 'Unknown error'
92
+ // Journal the failure so the agent can find it via `moi debug logs` — the
93
+ // 500 body below only reaches the browser (see docs/self-correction.md).
94
+ recordAppletError(workspacePath, {
95
+ source: 'rpc',
96
+ ...(appletForModule(module) ?? {}),
97
+ module,
98
+ fn: name,
99
+ message
100
+ })
85
101
  return new Response(message, { status: 500 })
86
102
  }
87
103
  }
@@ -101,7 +117,12 @@ const one = new Hono<ApiEnv>()
101
117
  one.use('*', withWorkspace)
102
118
 
103
119
  one.get('/preview', async c => {
104
- return c.json(await getWorkspacePreview(c.get('ws').path))
120
+ const ws = c.get('ws')
121
+ return c.json(
122
+ await getWorkspacePreview(ws.path, includeFirstUserMessage =>
123
+ harnessFor(ws).workspacePreview(ws, includeFirstUserMessage)
124
+ )
125
+ )
105
126
  })
106
127
 
107
128
  one.get('/widgets', c => listWidgets(c.get('ws').path))
@@ -276,6 +297,44 @@ one.post('/rpc/*', c => {
276
297
  return handleFunctionCall(c.req.raw, tail, c.get('ws').path)
277
298
  })
278
299
 
300
+ // Browser-side applet errors (module load failures, render crashes, window
301
+ // errors attributed to a bundle) reported into the workspace's error journal —
302
+ // `moi debug logs` reads it back (docs/self-correction.md). Unauthenticated
303
+ // localhost route, so treat the payload as hostile: whitelist the browser-only
304
+ // sources (`build`/`rpc` are server-recorded and can't be spoofed by a tab),
305
+ // pattern-check the applet name, cap the batch size; applet-log.ts caps string
306
+ // lengths.
307
+ one.post('/applet-log', async c => {
308
+ let body: { events?: unknown }
309
+ try {
310
+ body = await c.req.json()
311
+ } catch {
312
+ return c.text('Invalid JSON', 400)
313
+ }
314
+ const events = Array.isArray(body.events) ? body.events.slice(0, 10) : []
315
+ for (const raw of events) {
316
+ const e = raw as {
317
+ source?: unknown
318
+ kind?: unknown
319
+ name?: unknown
320
+ message?: unknown
321
+ stack?: unknown
322
+ }
323
+ if (e.source !== 'load' && e.source !== 'render' && e.source !== 'window') continue
324
+ if (e.kind !== 'widget' && e.kind !== 'view') continue
325
+ if (typeof e.name !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(e.name)) continue
326
+ if (typeof e.message !== 'string' || !e.message) continue
327
+ recordAppletError(c.get('ws').path, {
328
+ source: e.source,
329
+ kind: e.kind,
330
+ name: e.name,
331
+ message: e.message,
332
+ ...(typeof e.stack === 'string' ? { stack: e.stack } : {})
333
+ })
334
+ }
335
+ return c.body(null, 204)
336
+ })
337
+
279
338
  // Downscaled image preview of a workspace file. The chat's expanded tool rows
280
339
  // use this to show the picture an agent `Read` — same guards as /fs/ above,
281
340
  // images only, resized server-side (see server/preview.ts).
@@ -583,9 +642,16 @@ one.delete('/icon', async c => {
583
642
  // DELETE unregisters.
584
643
  one.get('/', async c => {
585
644
  const ws = c.get('ws')
586
- const layout = await loadLayout(ws.path)
645
+ // The thumbnail images are heavy (base64 WebPs) and have their own write
646
+ // path (PUT .../thumbnails); the layout ships `widgetThumbnails` without
647
+ // them — just `key`/`at`, which clients compare against the live grid to
648
+ // decide when to re-capture.
649
+ const { widgetThumbnails, ...layout } = await loadLayout(ws.path)
587
650
  return c.json({
588
651
  ...layout,
652
+ ...(widgetThumbnails && {
653
+ widgetThumbnails: { key: widgetThumbnails.key, at: widgetThumbnails.at }
654
+ }),
589
655
  // Resolved display name: the settings override, or the folder name.
590
656
  name: layout.name || basename(ws.path),
591
657
  cwd: ws.path,
@@ -594,6 +660,24 @@ one.get('/', async c => {
594
660
  })
595
661
  })
596
662
 
663
+ // Widget thumbnails: a separate write path from the layout PUT below, so grid
664
+ // and theme saves never round-trip the base64 map (and this save can't touch
665
+ // the grid). Still lands in `.workspace.json` under the hood. Entries merge
666
+ // over the stored map; `key` fingerprints the grid state they were captured
667
+ // from (see widgetThumbnailsKey() on the client).
668
+ one.put('/thumbnails', async c => {
669
+ const body: unknown = await c.req.json().catch(() => null)
670
+ if (!body || typeof body !== 'object') return c.text('Bad request', 400)
671
+ const { key, thumbnails } = body as { key?: unknown; thumbnails?: unknown }
672
+ const validMap =
673
+ thumbnails !== null &&
674
+ typeof thumbnails === 'object' &&
675
+ Object.values(thumbnails as Record<string, unknown>).every(v => typeof v === 'string')
676
+ if (typeof key !== 'string' || !validMap) return c.text('Bad request', 400)
677
+ await saveWidgetThumbnails(c.get('ws').path, key, thumbnails as Record<string, string>)
678
+ return c.body(null, 204)
679
+ })
680
+
597
681
  one.put('/', async c => {
598
682
  const ws = c.get('ws')
599
683
  const body = await c.req.json()
@@ -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
+ }
package/server/cli.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env bun
2
2
  import './cli-colors' // must precede citty: sets NO_COLOR before its color flag is computed
3
3
  import { defineCommand, runMain, showUsage } from 'citty'
4
+ import { parse as devalueParse } from 'devalue'
4
5
  import { existsSync, readFileSync } from 'node:fs'
5
6
  import { tmpdir } from 'node:os'
6
7
  import { join, resolve } from 'path'
@@ -9,13 +10,15 @@ import pc from './cli-pc'
9
10
  import { COLOR_THEMES, FONT_THEMES } from '@/lib/themes'
10
11
  import type { ColorTheme, FontTheme } from '@/lib/themes'
11
12
  import type {
13
+ AppletLogEntry,
12
14
  ScratchArrowEnd,
13
15
  ScratchColor,
14
16
  ScratchFill,
15
17
  ScratchImageQuality,
16
18
  ScratchOp,
17
19
  ScratchSize,
18
- ScratchStyle
20
+ ScratchStyle,
21
+ WorkspaceEntry
19
22
  } from '@/lib/types'
20
23
 
21
24
  import {
@@ -481,6 +484,16 @@ const bundle = defineCommand({
481
484
  console.log(' ' + f.error + '\n')
482
485
  }
483
486
 
487
+ // Runtime errors still standing after the rebuild's clear-on-success
488
+ // sweep — point the agent at the journal while it's paying attention.
489
+ const logCount = typeof res.logCount === 'number' ? res.logCount : 0
490
+ if (logCount > 0) {
491
+ console.log(
492
+ pc.yellow(`ℹ ${logCount} applet runtime error(s) on record — run \`moi debug logs\`.`) +
493
+ '\n'
494
+ )
495
+ }
496
+
484
497
  if (notice) console.log(pc.yellow(notice) + '\n')
485
498
  ws.close()
486
499
  process.exit(failed.length > 0 ? 1 : 0)
@@ -741,7 +754,7 @@ const status = defineCommand({
741
754
 
742
755
  ws.onmessage = event => {
743
756
  const res = JSON.parse(String(event.data))
744
- const workspaces: { id: string; path: string; addedAt: string }[] = res.workspaces ?? []
757
+ const workspaces: WorkspaceEntry[] = res.workspaces ?? []
745
758
  const n = workspaces.length
746
759
  console.log(pc.dim(` ${n} workspace${n === 1 ? '' : 's'} registered\n`))
747
760
 
@@ -1319,15 +1332,16 @@ function styleArgs(args: {
1319
1332
 
1320
1333
  type ScratchCliOp = ScratchOp | { kind: 'read' } | { kind: 'read-image'; name: string }
1321
1334
 
1322
- // Round-trip one op through the control port and hand the reply to `onResult`.
1323
- // Mirrors the `bundle`/`theme` commands: one socket per invocation, print, exit.
1324
- function sendScratch(
1335
+ // Round-trip one request through the control port and hand the reply to
1336
+ // `onResult`. Mirrors the `bundle`/`theme` commands: one socket per invocation,
1337
+ // print, exit. Shared by `scratch`, `call-server-fn`, and `debug logs`.
1338
+ function sendControl(
1325
1339
  path: string,
1326
- op: ScratchCliOp,
1340
+ payload: Record<string, unknown>,
1327
1341
  onResult: (res: Record<string, unknown>) => void | Promise<void>
1328
1342
  ) {
1329
1343
  const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
1330
- ws.onopen = () => ws.send(JSON.stringify({ type: 'scratch', path, op }))
1344
+ ws.onopen = () => ws.send(JSON.stringify(payload))
1331
1345
  ws.onmessage = async event => {
1332
1346
  const res = JSON.parse(String(event.data))
1333
1347
  if (res.error) {
@@ -1349,6 +1363,14 @@ function sendScratch(
1349
1363
  }
1350
1364
  }
1351
1365
 
1366
+ function sendScratch(
1367
+ path: string,
1368
+ op: ScratchCliOp,
1369
+ onResult: (res: Record<string, unknown>) => void | Promise<void>
1370
+ ) {
1371
+ sendControl(path, { type: 'scratch', path, op }, onResult)
1372
+ }
1373
+
1352
1374
  // Print the name a draw op landed on, so the agent can address it later.
1353
1375
  function printAdded(res: Record<string, unknown>) {
1354
1376
  const result = res.result as { name?: string } | undefined
@@ -1677,6 +1699,136 @@ const scratch = defineCommand({
1677
1699
  }
1678
1700
  })
1679
1701
 
1702
+ // ---- self-correction commands (docs/self-correction.md) ---------------------
1703
+
1704
+ const callServerFn = defineCommand({
1705
+ meta: {
1706
+ name: 'call-server-fn',
1707
+ description: 'Invoke an applet .server.ts function in an isolated one-shot worker (smoke test)'
1708
+ },
1709
+ args: {
1710
+ fn: {
1711
+ type: 'positional',
1712
+ required: true,
1713
+ description: 'Function path: <module>/<fn>, e.g. widgets/hello/getGreeting'
1714
+ },
1715
+ args: {
1716
+ type: 'positional',
1717
+ required: false,
1718
+ description: 'Arguments as one JSON array, e.g. \'["ann", 10]\' (default [])'
1719
+ },
1720
+ dir: dirArg
1721
+ },
1722
+ run({ args }) {
1723
+ const path = resolve(args.dir)
1724
+ sendControl(
1725
+ path,
1726
+ { type: 'call-server-fn', path, fn: args.fn, args: args.args ?? '[]' },
1727
+ res => {
1728
+ // The worker replies devalue-encoded (same wire format the browser RPC
1729
+ // parses), so Map/Set/Date render readably through Bun.inspect.
1730
+ const value = devalueParse(String(res.result))
1731
+ console.log(Bun.inspect(value, { depth: 8, colors: process.stdout.isTTY }))
1732
+ // Duration on stderr: stdout stays clean data, and a slow call is a
1733
+ // warning sign worth surfacing (browser RPC times out at 30s).
1734
+ console.error(pc.dim(`↩ ${res.ms}ms`))
1735
+ }
1736
+ )
1737
+ }
1738
+ })
1739
+
1740
+ // Compact relative age for a journal row: "just now", "4m ago", "2h ago", …
1741
+ function agoLabel(ts: number): string {
1742
+ const s = Math.max(0, Math.round((Date.now() - ts) / 1000))
1743
+ if (s < 60) return 'just now'
1744
+ if (s < 3600) return `${Math.round(s / 60)}m ago`
1745
+ if (s < 86400) return `${Math.round(s / 3600)}h ago`
1746
+ return `${Math.round(s / 86400)}d ago`
1747
+ }
1748
+
1749
+ // Where a journal entry points: the server function for rpc rows, else the applet.
1750
+ function logSubject(e: {
1751
+ source: string
1752
+ kind?: string
1753
+ name?: string
1754
+ module?: string
1755
+ fn?: string
1756
+ }): string {
1757
+ if (e.module) return `${e.module}/${e.fn ?? '?'}`
1758
+ if (e.name) return `${e.kind ?? 'applet'} ${e.name}`
1759
+ return 'unattributed'
1760
+ }
1761
+
1762
+ const MAX_LOG_MESSAGE_LINES = 12
1763
+
1764
+ const debugLogs = defineCommand({
1765
+ meta: {
1766
+ name: 'logs',
1767
+ description: 'Applet runtime errors on record (load / render / rpc / build failures)'
1768
+ },
1769
+ args: {
1770
+ dir: dirArg,
1771
+ json: {
1772
+ type: 'boolean',
1773
+ default: false,
1774
+ description: 'Machine-readable output, includes stacks and epoch timestamps'
1775
+ },
1776
+ clear: { type: 'boolean', default: false, description: 'Wipe the journal' }
1777
+ },
1778
+ run({ args }) {
1779
+ const path = resolve(args.dir)
1780
+ if (args.clear) {
1781
+ sendControl(path, { type: 'debug:logs', path, clear: true }, res => {
1782
+ console.log('\n' + pc.green('✓') + ` cleared ${res.cleared ?? 0} entries\n`)
1783
+ })
1784
+ return
1785
+ }
1786
+ sendControl(path, { type: 'debug:logs', path }, res => {
1787
+ const entries = (Array.isArray(res.entries) ? res.entries : []) as AppletLogEntry[]
1788
+ if (args.json) {
1789
+ console.log(JSON.stringify(entries, null, 2))
1790
+ return
1791
+ }
1792
+ if (entries.length === 0) {
1793
+ console.log(
1794
+ '\n' + pc.bold('moi debug logs') + pc.dim(' — no applet errors on record') + '\n'
1795
+ )
1796
+ return
1797
+ }
1798
+ console.log(
1799
+ '\n' + pc.bold('moi debug logs') + pc.dim(` — ${entries.length} error(s) on record`) + '\n'
1800
+ )
1801
+ for (const e of entries) {
1802
+ const count = e.count > 1 ? pc.dim(` ×${e.count}`) : ''
1803
+ console.log(
1804
+ ` ${pc.dim(agoLabel(e.ts).padEnd(10))} ${e.source.padEnd(7)} ${pc.bold(logSubject(e))}${count}`
1805
+ )
1806
+ const lines = e.message.split('\n')
1807
+ for (const line of lines.slice(0, MAX_LOG_MESSAGE_LINES)) {
1808
+ console.log(' ' + line)
1809
+ }
1810
+ if (lines.length > MAX_LOG_MESSAGE_LINES) {
1811
+ console.log(pc.dim(` … ${lines.length - MAX_LOG_MESSAGE_LINES} more lines (--json)`))
1812
+ }
1813
+ console.log()
1814
+ }
1815
+ console.log(
1816
+ pc.dim(' Entries clear when their applet next builds successfully, or via --clear.') + '\n'
1817
+ )
1818
+ })
1819
+ }
1820
+ })
1821
+
1822
+ // Experimental workspace-debugging toolbox. One subcommand for now (`logs`);
1823
+ // more introspection (worker state, RPC traces, …) may hang off it later.
1824
+ const debug = defineCommand({
1825
+ meta: {
1826
+ name: 'debug',
1827
+ description: 'Debug the workspace (experimental) — `moi debug logs` for applet errors'
1828
+ },
1829
+ subCommands: { logs: debugLogs }
1830
+ })
1831
+
1680
1832
  // Re-copy bundled skills into a workspace, then report what changed. Pure
1681
1833
  // filesystem op — no running server needed. Resolves the workspace root the
1682
1834
  // same way `moi bundle` does, so it works from `.moi/` or any subdirectory.
@@ -1808,6 +1960,8 @@ const main = defineCommand({
1808
1960
  bundle,
1809
1961
  builder,
1810
1962
  refresh,
1963
+ 'call-server-fn': callServerFn,
1964
+ debug,
1811
1965
  theme,
1812
1966
  config,
1813
1967
  env,