moi-computer 0.3.0-next.2 → 0.3.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 (125) hide show
  1. package/README.md +1 -1
  2. package/client/AGENTS.md +2 -2
  3. package/client/api/http.ts +1 -1
  4. package/client/api/workspace-keys.ts +1 -0
  5. package/client/app/AppRouter.tsx +14 -5
  6. package/client/app/routes/HomeRoute.tsx +1 -1
  7. package/client/app/routes/WorkspaceRoute.tsx +8 -2
  8. package/client/app/shell/SidebarLayout.tsx +10 -5
  9. package/client/assets/openai.svg +3 -0
  10. package/client/components/shared/BottomPanel.tsx +2 -2
  11. package/client/components/ui/button.tsx +3 -2
  12. package/client/components/ui/input.tsx +1 -1
  13. package/client/features/applets/AppletMount.tsx +44 -0
  14. package/client/features/applets/WidgetShell.tsx +4 -1
  15. package/client/features/applets/applet-cache.ts +8 -0
  16. package/client/features/applets/applet-styles.ts +61 -0
  17. package/client/features/chat/ChatComposer.tsx +2 -2
  18. package/client/features/chat/ChatPanel.tsx +8 -25
  19. package/client/features/chat/ChatPopup.tsx +3 -3
  20. package/client/features/chat/{ThreadSelector.tsx → ChatSelector.tsx} +4 -4
  21. package/client/features/chat/TurnView.tsx +8 -9
  22. package/client/features/chat/api.ts +1 -1
  23. package/client/features/chat/chat-send.ts +57 -0
  24. package/client/features/chat/tool-group/ToolCallGroup.tsx +2 -1
  25. package/client/features/chat/tool-group/format.ts +117 -0
  26. package/client/features/chat/useChat.ts +10 -34
  27. package/client/features/connectors/McpMenu.tsx +4 -21
  28. package/client/features/dev/DevRoutes.tsx +18 -0
  29. package/client/features/dev/HarnessDebugPage.tsx +468 -0
  30. package/client/{components/playground → features/dev}/PlaygroundPage.tsx +1 -1
  31. package/client/features/home/CreateWorkspaceDialog.tsx +64 -158
  32. package/client/features/home/CreateWorkspaceDialogSteps.tsx +234 -0
  33. package/client/features/home/HomeLogo.tsx +344 -0
  34. package/client/features/home/HomePage.tsx +15 -21
  35. package/client/features/home/WorkspacePreview.tsx +12 -5
  36. package/client/features/home/api.ts +11 -3
  37. package/client/features/home/workspace-presentation.tsx +4 -4
  38. package/client/features/settings/GeneralSettings.tsx +3 -3
  39. package/client/features/settings/IconPicker.tsx +4 -3
  40. package/client/features/settings/icon-picker-options.ts +0 -131
  41. package/client/features/views/ViewBuilderTab.tsx +153 -0
  42. package/client/features/views/api.ts +124 -0
  43. package/client/features/views/useViewBuilderActions.ts +72 -0
  44. package/client/features/widgets/WidgetGrid.tsx +36 -20
  45. package/client/features/widgets/Widgets.tsx +140 -90
  46. package/client/features/workspace/WorkspaceLayoutContext.tsx +3 -9
  47. package/client/features/workspace/WorkspaceScreen.tsx +179 -40
  48. package/client/features/workspace/WorkspaceTabs.tsx +4 -4
  49. package/client/index.css +0 -35
  50. package/client/index.html +1 -1
  51. package/client/lib/app-icon-registry.ts +145 -0
  52. package/client/runtime/useWorkspaceEvents.ts +3 -1
  53. package/client/theme.css +1 -1
  54. package/dist/chunk-4vf1t6v1.js +10 -0
  55. package/dist/chunk-4z52b2av.css +1 -0
  56. package/dist/chunk-6c8cwpzc.js +1 -0
  57. package/dist/chunk-b4b276wx.js +15 -0
  58. package/dist/{chunk-c4j722at.js → chunk-cs8vbert.js} +2 -2
  59. package/dist/chunk-fjksw6xf.js +1 -0
  60. package/dist/chunk-kxmvv1ax.js +48 -0
  61. package/dist/{chunk-p68fnz3q.js → chunk-vkvb3hjm.js} +1 -1
  62. package/dist/chunk-y82s1jxm.js +61 -0
  63. package/dist/chunk-zpxrb1ce.js +2 -0
  64. package/dist/index.html +2 -2
  65. package/dist/openai-h13pza4b.svg +3 -0
  66. package/lib/format.ts +2 -2
  67. package/lib/types.ts +38 -2
  68. package/lib/view-builder-meta.ts +35 -0
  69. package/lib/workspace-layout.ts +14 -0
  70. package/package.json +2 -1
  71. package/server/AGENTS.md +3 -3
  72. package/server/api.ts +165 -51
  73. package/server/applets.ts +1 -1
  74. package/server/bundle-queue.ts +19 -0
  75. package/server/bundler/applet-css.ts +50 -0
  76. package/server/{build-applet.ts → bundler/build-applet.ts} +36 -26
  77. package/server/cli.ts +79 -2
  78. package/server/control.ts +106 -8
  79. package/server/env-apply.ts +2 -2
  80. package/server/harness/README.md +228 -0
  81. package/server/harness/claude-code/NOTES.md +578 -0
  82. package/{lib/claude-adapter.ts → server/harness/claude-code/adapter.ts} +67 -5
  83. package/server/harness/claude-code/index.ts +124 -0
  84. package/server/{mcp.ts → harness/claude-code/mcp.ts} +1 -1
  85. package/server/{cc-session.ts → harness/claude-code/session.ts} +42 -14
  86. package/server/harness/claude-code/sessions.ts +42 -0
  87. package/server/harness/codex/NOTES.md +326 -0
  88. package/server/harness/codex/adapter.ts +414 -0
  89. package/server/harness/codex/client.ts +343 -0
  90. package/server/harness/codex/index.ts +68 -0
  91. package/server/harness/codex/probe.ts +186 -0
  92. package/server/harness/codex/session.ts +617 -0
  93. package/server/harness/debug.ts +57 -0
  94. package/server/harness/openclaw/NOTES.md +316 -0
  95. package/server/{openclaw-adapter.ts → harness/openclaw/adapter.ts} +2 -2
  96. package/server/harness/openclaw/index.ts +93 -0
  97. package/server/{openclaw-session.ts → harness/openclaw/session.ts} +44 -9
  98. package/server/{openclaw-strip.ts → harness/openclaw/strip.ts} +3 -1
  99. package/server/harness/registry.ts +36 -0
  100. package/server/harness/types.ts +87 -0
  101. package/server/layout.ts +6 -12
  102. package/server/moi-scaffold.ts +1 -1
  103. package/server/registry.ts +14 -52
  104. package/server/state.ts +5 -38
  105. package/server/status.ts +7 -46
  106. package/server/vendor.ts +1 -1
  107. package/server/view-builders.ts +428 -0
  108. package/server/views.ts +0 -0
  109. package/server/web.ts +18 -40
  110. package/server/workspace-init.ts +6 -6
  111. package/workspace/.claude/skills/moi-workspace/DESIGN.md +1 -0
  112. package/workspace/.claude/skills/moi-workspace/SKILL.md +28 -7
  113. package/client/assets/hermes-nous.png +0 -0
  114. package/client/hooks/useScrollFade.ts +0 -38
  115. package/dist/chunk-23cgr1tz.css +0 -1
  116. package/dist/chunk-3hy3qy6d.js +0 -10
  117. package/dist/chunk-dyfaffyz.js +0 -119
  118. package/dist/chunk-kpe40hm8.js +0 -1
  119. package/dist/chunk-ty6dvda0.js +0 -1
  120. package/dist/hermes-nous-pznd63x9.png +0 -0
  121. /package/client/{components/playground → features/dev}/PixelPainter.tsx +0 -0
  122. /package/client/{components/playground → features/dev}/ToolCallsPage.tsx +0 -0
  123. /package/server/{agent.ts → harness/claude-code/models.ts} +0 -0
  124. /package/server/{openclaw.ts → harness/openclaw/discovery.ts} +0 -0
  125. /package/server/{openclaw-gateway.ts → harness/openclaw/gateway.ts} +0 -0
@@ -8,13 +8,16 @@ import tailwind from 'bun-plugin-tailwind'
8
8
  import { realpathSync } from 'node:fs'
9
9
  import { basename, dirname, join, relative, sep } from 'path'
10
10
 
11
- import type { ViewConfig, WidgetConfig } from '@/lib/types'
11
+ import type { AppletKind, ViewConfig, WidgetConfig } from '@/lib/types'
12
+
13
+ import { scopeAppletCss } from './applet-css'
12
14
 
13
15
  // An **applet** is any custom UI unit embedded in a workspace; `widget` and
14
16
  // `view` are its kinds (more may follow). All compile through this pipeline —
15
17
  // `kind` only diverges at the edges: which `config` schema is parsed, the
16
- // synthetic-CSS filename, and the injected `<style>` id namespace.
17
- export type AppletKind = 'widget' | 'view'
18
+ // synthetic-CSS filename, and the CSS scope/registry namespace. The type is
19
+ // canonical in lib/types; re-exported here for this pipeline's consumers.
20
+ export type { AppletKind }
18
21
 
19
22
  // Baked into the bundle wherever a runtime URL needs the workspace's API base
20
23
  // (RPC + workspace files). The serve route string-replaces it with the real
@@ -144,8 +147,8 @@ export async function extractWidgetConfig(srcPath: string): Promise<WidgetConfig
144
147
  return { ...DEFAULT_CONFIG, ...result }
145
148
  }
146
149
 
147
- // A view's config: just `title` (string) + advisory `requiredEnv`. No sizing —
148
- // views are full-screen. Returns null when no `config` export is present.
150
+ // A view's config: `title` + app icon registry id + advisory `requiredEnv`.
151
+ // No sizing — views are full-screen. Returns null when no `config` export is present.
149
152
  export async function extractViewConfig(srcPath: string): Promise<ViewConfig | null> {
150
153
  const source = await Bun.file(srcPath).text()
151
154
 
@@ -158,9 +161,9 @@ export async function extractViewConfig(srcPath: string): Promise<ViewConfig | n
158
161
  if (prop.type !== 'Property' || prop.key?.type !== 'Identifier') continue
159
162
  const key = prop.key.name as string
160
163
 
161
- if (key === 'title') {
164
+ if (key === 'title' || key === 'icon') {
162
165
  if (prop.value?.type === 'Literal' && typeof prop.value.value === 'string') {
163
- result.title = prop.value.value
166
+ result[key] = prop.value.value
164
167
  }
165
168
  continue
166
169
  }
@@ -373,7 +376,7 @@ function appletRuntimePlugin(
373
376
  // Path to the host's `@theme inline` block — shared with `client/index.css`.
374
377
  // Inlined into the widget's synthetic CSS at build time so Tailwind sees the
375
378
  // theme tokens.
376
- const HOST_THEME_PATH = join(import.meta.dir, '..', 'client', 'theme.css')
379
+ const HOST_THEME_PATH = join(import.meta.dir, '..', '..', 'client', 'theme.css')
377
380
 
378
381
  // Three things matter for widget styling:
379
382
  // 1. The umbrella `@import 'tailwindcss'` brings in @layer theme + base +
@@ -411,6 +414,11 @@ async function writeSyntheticTailwindCss(
411
414
  const contents = [
412
415
  `@import 'tailwindcss';`,
413
416
  await Bun.file(HOST_THEME_PATH).text(),
417
+ // Mirror the host's class-based dark mode (client/index.css) so an applet's
418
+ // `dark:` variants flip with the app theme. Without this Tailwind falls
419
+ // back to `@media (prefers-color-scheme: dark)`, which diverges from the
420
+ // host and injects OS-preference media queries into the page.
421
+ `@custom-variant dark (&:is(.dark *));`,
414
422
  `@source "${sourceDir}";`
415
423
  ].join('\n')
416
424
  await Bun.write(cssPath, contents)
@@ -437,21 +445,22 @@ function widgetEntryPlugin(widgetPath: string, syntheticCssPath: string): BunPlu
437
445
  }
438
446
  }
439
447
 
440
- function injectCss(js: string, css: string, widgetName: string): string {
448
+ // Hand the bundle's (scoped) CSS to the host instead of mutating the DOM. The
449
+ // module side effect only registers the text under a stable key — the path of
450
+ // the bundle dir, derived from import.meta.url so it self-locates per workspace
451
+ // (`/api/workspaces/<id>/<segment>/<name>`), matching `appletStyleKey` on the
452
+ // client. The host mounts a <style> for that key only while the applet is on
453
+ // screen and removes it on unmount (client/features/applets/applet-styles.ts) —
454
+ // the old direct-append left every applet's rules in <head> forever, because a
455
+ // cached ES module is never re-evaluated, let alone disposed.
456
+ function injectCss(js: string, css: string): string {
441
457
  if (!css.trim()) return js
442
458
 
443
- // After `moi bundle` rebuilds the widget, the new JS module re-runs in the
444
- // browser. Always replace any prior <style data-widget="<id>"> tag so the
445
- // freshly-built CSS takes effect; the previous "skip if already present"
446
- // guard left stale rules in place after edits.
447
459
  const injection = [
448
- `((css, id) => {`,
449
- ` document.querySelector(\`style[data-widget="\${id}"]\`)?.remove();`,
450
- ` const s = document.createElement("style");`,
451
- ` s.dataset.widget = id;`,
452
- ` s.textContent = css;`,
453
- ` document.head.appendChild(s);`,
454
- `})(${JSON.stringify(css)}, ${JSON.stringify(widgetName)});`
460
+ `(css => {`,
461
+ ` const key = new URL(".", import.meta.url).pathname.replace(/\\/$/, "");`,
462
+ ` (window.__moiAppletCss ||= new Map()).set(key, css);`,
463
+ `})(${JSON.stringify(css)});`
455
464
  ].join('\n')
456
465
 
457
466
  return injection + '\n' + js
@@ -508,7 +517,7 @@ async function prevalidateServerFiles(entrypoint: string): Promise<void> {
508
517
  // `moiRoot` is the directory server-module keys are relative to (the
509
518
  // workspace's `.moi/`). Defaults to the entrypoint's own directory, which keeps
510
519
  // basename keys for callers that build a file directly (tests, fixtures).
511
- // `kind` selects the config schema, synthetic-CSS filename, and `<style>` id
520
+ // `kind` selects the config schema, synthetic-CSS filename, and CSS scope
512
521
  // namespace; it defaults to 'widget' so existing callers are unaffected.
513
522
  export async function buildApplet(
514
523
  entrypoint: string,
@@ -588,11 +597,12 @@ export async function buildApplet(
588
597
  let js = await entryOutput.text()
589
598
 
590
599
  if (cssOutput) {
591
- const css = await cssOutput.text()
592
- // Namespace the injected <style> id by kind so a widget and a view sharing
593
- // a name don't overwrite each other's rules.
594
- const styleId = kind === 'widget' ? widgetName : `${kind}:${widgetName}`
595
- js = injectCss(js, css, styleId)
600
+ // Scope every rule to the applet's mount container (`[data-applet=
601
+ // "<kind>:<name>"]`, see applet-css.ts) so the bundle's Tailwind never
602
+ // leaks into the host page. Kind-namespaced so a widget and a view sharing
603
+ // a name scope independently.
604
+ const css = scopeAppletCss(await cssOutput.text(), `${kind}:${widgetName}`)
605
+ js = injectCss(js, css)
596
606
  }
597
607
 
598
608
  const files: AppletFile[] = [{ name: 'index.js', data: js, kind: 'code' }]
package/server/cli.ts CHANGED
@@ -27,7 +27,7 @@ import {
27
27
  } from './cli-env'
28
28
  import { columns } from './cli-ui'
29
29
  import { CONTROL_PORT, PORT } from './constants'
30
- import { type OpenClawAgent, discoverOpenClawAgents } from './openclaw'
30
+ import { type OpenClawAgent, discoverOpenClawAgents } from './harness/openclaw/discovery'
31
31
  import { liftToWorkspaceRoot, registerWorkspace } from './registry'
32
32
  import { serverCwd } from './server-cwd'
33
33
  import {
@@ -403,6 +403,11 @@ const bundle = defineCommand({
403
403
  only: {
404
404
  type: 'string',
405
405
  description: 'Narrow the build to "widgets" or "views" (default: both)'
406
+ },
407
+ status: {
408
+ type: 'boolean',
409
+ description: 'Advance a view builder to ready on success (use --no-status to skip)',
410
+ default: true
406
411
  }
407
412
  },
408
413
  async run({ args }) {
@@ -413,7 +418,15 @@ const bundle = defineCommand({
413
418
  const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
414
419
 
415
420
  ws.onopen = () =>
416
- ws.send(JSON.stringify({ type: 'bundle', path, force: args.force, only: args.only }))
421
+ ws.send(
422
+ JSON.stringify({
423
+ type: 'bundle',
424
+ path,
425
+ force: args.force,
426
+ only: args.only,
427
+ noStatus: !args.status
428
+ })
429
+ )
417
430
 
418
431
  ws.onmessage = event => {
419
432
  const res = JSON.parse(String(event.data))
@@ -480,6 +493,69 @@ const bundle = defineCommand({
480
493
  }
481
494
  })
482
495
 
496
+ const builderSet = defineCommand({
497
+ meta: { name: 'set', description: 'Set a view or widget builder id, status, title, and icon' },
498
+ args: {
499
+ id: { type: 'positional', required: true, description: 'View or widget id' },
500
+ dir: {
501
+ type: 'positional',
502
+ default: '.',
503
+ description: 'Workspace directory (default: current)'
504
+ },
505
+ kind: { type: 'string', default: 'view', description: '"view" or "widget"' },
506
+ status: { type: 'string', description: 'Report build state: "building" or "waiting"' },
507
+ title: { type: 'string', description: 'Display title' },
508
+ icon: { type: 'string', description: 'App icon registry id' },
509
+ builder: {
510
+ type: 'string',
511
+ description: 'Builder handle for a pending view builder (from its request)'
512
+ }
513
+ },
514
+ run({ args }) {
515
+ const path = resolve(args.dir)
516
+ const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
517
+ ws.onopen = () =>
518
+ ws.send(
519
+ JSON.stringify({
520
+ type: 'builder:set',
521
+ path,
522
+ id: args.id,
523
+ kind: args.kind,
524
+ status: args.status,
525
+ title: args.title,
526
+ icon: args.icon,
527
+ builder: args.builder
528
+ })
529
+ )
530
+ ws.onmessage = event => {
531
+ const result = JSON.parse(String(event.data))
532
+ if (result.error) {
533
+ console.error('\n' + pc.red(pc.bold('Error:')) + ' ' + result.error + '\n')
534
+ ws.close()
535
+ process.exit(1)
536
+ }
537
+ console.log(
538
+ '\n' +
539
+ pc.green('✓') +
540
+ ' Builder set ' +
541
+ pc.bold(String(result.builder?.viewId ?? args.id)) +
542
+ '\n'
543
+ )
544
+ ws.close()
545
+ process.exit(0)
546
+ }
547
+ ws.onerror = () => {
548
+ console.error('Could not connect to control server. Is the main process running?')
549
+ process.exit(1)
550
+ }
551
+ }
552
+ })
553
+
554
+ const builder = defineCommand({
555
+ meta: { name: 'builder', description: 'Manage a view or widget builder' },
556
+ subCommands: { set: builderSet }
557
+ })
558
+
483
559
  const refresh = defineCommand({
484
560
  meta: {
485
561
  name: 'refresh',
@@ -1730,6 +1806,7 @@ const main = defineCommand({
1730
1806
  init,
1731
1807
  start,
1732
1808
  bundle,
1809
+ builder,
1733
1810
  refresh,
1734
1811
  theme,
1735
1812
  config,
package/server/control.ts CHANGED
@@ -2,6 +2,7 @@ import { resolve } from 'path'
2
2
 
3
3
  import type { WorkspaceEntry } from '@/lib/types'
4
4
 
5
+ import { serializeWorkspaceBundle } from './bundle-queue'
5
6
  import { CONTROL_PORT } from './constants'
6
7
  import { applyEnvChanged } from './env-apply'
7
8
  import { processIcon } from './icon'
@@ -14,7 +15,13 @@ import { relayScratchOp } from './scratchpad-relay'
14
15
  import { broadcastAll } from './state'
15
16
  import { applyThemeUpdate, matchColorTheme } from './theme'
16
17
  import { handleBundle } from './widgets'
17
- import { handleBundleViews } from './views'
18
+ import { getViewList, handleBundleViews, hasViewId } from './views'
19
+ import {
20
+ ViewBuilderError,
21
+ listViewBuilders,
22
+ reconcileViewBuilders,
23
+ setBuilder
24
+ } from './view-builders'
18
25
  import { getWorkspaceConfig, setWorkspaceConfig } from './workspace-config'
19
26
 
20
27
  type ControlSocket = { send(data: string): void }
@@ -82,6 +89,9 @@ export const control = Bun.serve({
82
89
  if (!match) return
83
90
  const workspacePath = match.path
84
91
  const force = !!data.force
92
+ // `--no-status`: compile without advancing any view builder to `ready`
93
+ // (status stays whatever the agent last reported).
94
+ const skipStatus = data.noStatus === true
85
95
  // `only` narrows to one kind; default builds both. Results carry a
86
96
  // `kind` so the CLI can label each row.
87
97
  const only = data.only === 'widgets' || data.only === 'views' ? data.only : undefined
@@ -91,17 +101,85 @@ export const control = Bun.serve({
91
101
  status: string
92
102
  error?: string
93
103
  }[] = []
94
- if (only !== 'views') {
95
- for (const r of await handleBundle(publishEvent, workspacePath, force)) {
96
- results.push({ kind: 'widget', name: r.name, status: r.status, error: r.error })
104
+ await serializeWorkspaceBundle(workspacePath, async () => {
105
+ if (only !== 'views') {
106
+ for (const r of await handleBundle(publishEvent, workspacePath, force)) {
107
+ results.push({ kind: 'widget', name: r.name, status: r.status, error: r.error })
108
+ }
97
109
  }
110
+ if (only !== 'widgets') {
111
+ for (const r of await handleBundleViews(
112
+ publishEvent,
113
+ match.id,
114
+ workspacePath,
115
+ force,
116
+ skipStatus
117
+ )) {
118
+ results.push({ kind: 'view', name: r.name, status: r.status, error: r.error })
119
+ }
120
+ }
121
+ })
122
+ ws.send(JSON.stringify({ ok: true, workspacePath, results }))
123
+ return
124
+ }
125
+
126
+ if (data.type === 'builder:set') {
127
+ const match = await resolveWorkspace(ws, data.path)
128
+ if (!match) return
129
+ const appletId = typeof data.id === 'string' ? data.id.trim() : ''
130
+ const builderId = typeof data.builder === 'string' ? data.builder.trim() : ''
131
+ const kind = data.kind === 'widget' ? 'widget' : 'view'
132
+ const status =
133
+ data.status === 'building' || data.status === 'waiting' ? data.status : undefined
134
+ const title = typeof data.title === 'string' ? data.title.trim() : undefined
135
+ const icon = typeof data.icon === 'string' ? data.icon.trim() : undefined
136
+ if (!appletId) {
137
+ ws.send(JSON.stringify({ error: 'A view or widget id is required' }))
138
+ return
139
+ }
140
+ if (!/^[a-z0-9][a-z0-9_-]*$/.test(appletId)) {
141
+ ws.send(
142
+ JSON.stringify({
143
+ error: 'Id must start with a lowercase letter or number and use a-z, 0-9, _, or -'
144
+ })
145
+ )
146
+ return
147
+ }
148
+ if (icon && !/^[a-z0-9][a-z0-9-]*$/.test(icon)) {
149
+ ws.send(
150
+ JSON.stringify({
151
+ error: 'Icon must start with a lowercase letter or number and use a-z, 0-9, or -'
152
+ })
153
+ )
154
+ return
98
155
  }
99
- if (only !== 'widgets') {
100
- for (const r of await handleBundleViews(publishEvent, workspacePath, force)) {
101
- results.push({ kind: 'view', name: r.name, status: r.status, error: r.error })
156
+ try {
157
+ // A view can't claim an id that already exists on disk (unless this
158
+ // builder already owns it). Widgets live in a separate namespace.
159
+ if (kind === 'view') {
160
+ const current = (await listViewBuilders(match.path)).find(builder =>
161
+ builderId ? builder.id === builderId : builder.viewId === appletId
162
+ )
163
+ if (current?.viewId !== appletId && (await hasViewId(match.path, appletId))) {
164
+ ws.send(JSON.stringify({ error: `View id "${appletId}" already exists` }))
165
+ return
166
+ }
102
167
  }
168
+ const builder = await setBuilder(match.id, match.path, appletId, {
169
+ builderId: builderId || undefined,
170
+ kind,
171
+ status,
172
+ title,
173
+ icon
174
+ })
175
+ ws.send(JSON.stringify({ ok: true, builder, workspacePath: match.path }))
176
+ } catch (err) {
177
+ ws.send(
178
+ JSON.stringify({
179
+ error: err instanceof ViewBuilderError ? err.message : 'Could not set builder'
180
+ })
181
+ )
103
182
  }
104
- ws.send(JSON.stringify({ ok: true, workspacePath, results }))
105
183
  return
106
184
  }
107
185
 
@@ -254,3 +332,23 @@ export const control = Bun.serve({
254
332
  }
255
333
  }
256
334
  })
335
+
336
+ // On boot, correct any builder a previous process left mid-flight. With no live
337
+ // sessions yet, a persisted `building` record is by definition stale, so
338
+ // reconcile hands it back to `waiting` — or promotes it to `ready` if its view
339
+ // actually reached disk. GET-time reconcile would eventually do this too, but
340
+ // only once a client reopens the workspace; this makes the stored state correct
341
+ // even if no one does.
342
+ async function reconcileBuildersOnBoot(): Promise<void> {
343
+ const workspaces = await listWorkspaces()
344
+ await Promise.all(
345
+ workspaces.map(async entry => {
346
+ try {
347
+ await reconcileViewBuilders(entry.id, entry.path, await getViewList(entry.path), new Set())
348
+ } catch (err) {
349
+ console.error('[control] boot reconcile failed', entry.path, err)
350
+ }
351
+ })
352
+ )
353
+ }
354
+ void reconcileBuildersOnBoot()
@@ -3,14 +3,14 @@
3
3
  // relayed over the control port — the workspace's processes must be reaped and
4
4
  // every connected client told to refetch. Both entry points call this so the
5
5
  // side effects can never drift apart.
6
- import { restartWorkspaceSessions } from './cc-session'
7
6
  import { publishEvent } from './events'
8
7
  import { restartWorker } from './functions'
8
+ import { allHarnesses } from './harness/registry'
9
9
 
10
10
  export function applyEnvChanged(workspace: { id: string; path: string }): void {
11
11
  // Kill the cached widget worker (next RPC respawns with fresh env) and tear
12
12
  // down idle agent sessions (busy ones keep their snapshot until turn end).
13
13
  restartWorker(workspace.path)
14
- restartWorkspaceSessions(workspace.path)
14
+ for (const h of allHarnesses()) h.onEnvChanged?.(workspace.path)
15
15
  publishEvent({ type: 'env:updated', workspaceId: workspace.id })
16
16
  }
@@ -0,0 +1,228 @@
1
+ # Harnesses
2
+
3
+ A **harness** is an agent backend moi can drive: it receives user messages,
4
+ runs an agentic loop (model + tools) in a workspace, and streams back events
5
+ that moi normalizes into its agent-agnostic display format.
6
+
7
+ ## The layers
8
+
9
+ Message types flow through four layers; each has one home:
10
+
11
+ ```
12
+ 1. wire the backend's native protocol per-harness, server-only
13
+ │ CC: Agent SDK messages (SDK types) harness/claude-code/NOTES.md
14
+ │ OpenClaw: gateway frames harness/openclaw/{discovery.ts,NOTES.md}
15
+ │ Codex: app-server JSON-RPC harness/codex/{adapter.ts,NOTES.md}
16
+ ▼
17
+ 2. display Turn / Part / ToolCall / SystemNotice / lib/format.ts (shared client+server)
18
+ │ StreamEvent (+ ephemeral StreamPreview)
19
+ │ produced by each harness/<name>/adapter.ts
20
+ ▼
21
+ 3. socket ClientMessage / ServerMessage over /ws, lib/types.ts (wraps layer 2 and
22
+ │ REST payloads (SessionInfo, Models, …) re-exports it)
23
+ ▼
24
+ 4. client React Query cache of StreamEvents + client/features/chat/*
25
+ ephemeral preview store → ViewState → (tool-group/format.ts holds the
26
+ TurnView rendering per-provider labels/briefs)
27
+ ```
28
+
29
+ Rules: **adapters are the only code that sees layer 1** — everything above
30
+ speaks layers 2/3 only. `lib/format.ts` and `lib/types.ts` never move into
31
+ this folder: the client imports them; they are the shared contract.
32
+
33
+ Socket-protocol notes the layers rely on (all defined in `lib/types.ts`):
34
+
35
+ - **`session_renamed`** — a new thread is created under the client's temporary
36
+ uuid, then rekeyed to the backend's real session/thread id.
37
+ - **Optimistic-id rendezvous** — the client sends `optimisticId` with each
38
+ chat; the user's bubble must upsert under that id. Backends differ: Codex
39
+ echoes it natively (`clientUserMessageId` → `clientId`), Claude Code never
40
+ echoes (the server synthesizes the turn), OpenClaw echoes lagged (matched
41
+ by text).
42
+ - **`status` / `status_snapshot`** — busy/idle per session; the snapshot on
43
+ connect is authoritative (clears spinners for missed transitions).
44
+ - **`preview`** — live token frames, cumulative text, never persisted;
45
+ cleared when the turn with matching `meta.apiMessageId` lands.
46
+
47
+ ## Folder layout & conventions
48
+
49
+ ```
50
+ server/harness/
51
+ README.md this file
52
+ debug.ts shared debug taps (wire + client-frame rings) for /dev/harness
53
+ <name>/
54
+ adapter.ts pure wire → display mapping (layer 1 → 2); owns the
55
+ hand-written wire types it consumes
56
+ session.ts live per-thread state machine (send/interrupt/turn
57
+ accounting/preview forwarding)
58
+ <transport>.ts process/connection management, named for what it is:
59
+ codex/client.ts, openclaw/gateway.ts (CC has none — the
60
+ Agent SDK is the transport)
61
+ discovery.ts / models.ts / sessions.ts / mcp.ts as needed
62
+ NOTES.md the backend's wire protocol, empirically verified
63
+ *.test.ts tests live next to the code they cover
64
+ ```
65
+
66
+ - Nothing inside one harness folder imports from a sibling harness.
67
+ - Outside code imports only this folder's top level. Documented exceptions:
68
+ `cli.ts` (`moi openclaw init` provisioning) imports
69
+ `harness/openclaw/discovery.ts`; tests may import harness internals.
70
+
71
+ Current harnesses:
72
+
73
+ | Harness | Session module | Adapter | Status |
74
+ | ----------------------- | ------------------------ | ------------------------ | --------------------- |
75
+ | Claude Code (Agent SDK) | `claude-code/session.ts` | `claude-code/adapter.ts` | shipped, primary |
76
+ | OpenClaw (gateway) | `openclaw/session.ts` | `openclaw/adapter.ts` | shipped, experimental |
77
+ | Codex (app-server) | `codex/session.ts` | `codex/adapter.ts` | shipped, experimental |
78
+
79
+ Dev tooling: `/dev/harness` (live wire log + client frames + trigger
80
+ scenarios for any workspace, backed by `GET /api/workspaces/:id/harness/debug`
81
+ and the taps in `debug.ts`) and `codex/probe.ts` (drive the raw codex
82
+ app-server protocol without moi).
83
+
84
+ ## Implementation status
85
+
86
+ **Claude Code — shipped, primary harness.** Full chat integration: long-lived
87
+ streaming-input sessions with mid-turn message queueing, resume after idle
88
+ eviction/restart, interrupt, per-thread model + effort picker (backed by
89
+ `supportedModels()`), opt-in live token streaming, image/file attachments,
90
+ subagent lanes, MCP status probe, and session list/history replay from the
91
+ SDK's `.jsonl` files, with per-turn token usage folded into the final
92
+ assistant turn. Known gaps: runs with `bypassPermissions` only (no
93
+ interactive approval flow), and effort/streaming changes require a
94
+ teardown-and-resume because the SDK has no live setter for them.
95
+
96
+ **OpenClaw — shipped, experimental.** Chat over the local gateway's WebSocket
97
+ JSON-RPC: sessions seeded cold from `sessions.get` then updated from live
98
+ `session.message` frames, abort via `sessions.abort`, per-turn usage (tokens +
99
+ cost) into `TurnMeta`, optimistic user-echo rendezvous (the gateway echoes
100
+ sends with lag), uploads materialized to file paths. Known gaps: no
101
+ token-delta streaming (durable message rows only — deliberate v2 cut), no
102
+ model/effort selection, and the gateway is the sole source of truth (no local
103
+ persistence; cold restarts re-seed).
104
+
105
+ **Codex — shipped, experimental.** Chat over `codex app-server` (stdio
106
+ JSON-RPC, one process per workspace so `workspaceEnv` injects at spawn —
107
+ `codex/client.ts`): thread create/resume with temp-id rename, per-turn model +
108
+ effort overrides (both live — no rebuild dance), opt-in token streaming from
109
+ `item/*/delta`, reasoning summaries via `summary: 'auto'`, mid-turn sends
110
+ steered into the running turn (`turn/steer` with `turn/start` fallback),
111
+ interrupt, per-turn token usage folded into `TurnMeta`, native optimistic-id
112
+ rendezvous, session list via `thread/list` (cwd-filtered) and history replay
113
+ via `thread/read`, subagent (collab) child threads nested as live
114
+ SubagentRecord transcripts on the parent card, semantic exec labels from
115
+ `commandActions`, MCP status via `mcpServerStatus/list`, and hook / failed
116
+ MCP-startup notices. Runs `danger-full-access` + `approvalPolicy: never` to
117
+ match moi's bypass-permissions trust model. Known gaps: no interactive
118
+ approval flow (server→client approval requests are auto-accepted
119
+ defensively), and images ride inline as data URLs only (no `localImage` path
120
+ mode).
121
+
122
+ ## What a harness adapter must support
123
+
124
+ The checklist below is distilled from what the Claude Code integration
125
+ actually uses today, plus gaps the OpenClaw and Codex adapters surfaced. It
126
+ doubles as the evaluation rubric for new harnesses.
127
+
128
+ ### Core lifecycle
129
+
130
+ - **Create session / send message** — accept a user message into a
131
+ (workspace, session) pair. CC runs one long-lived streaming-input `query()`
132
+ per session with an in-memory input queue so follow-ups are queued, not
133
+ rejected; Codex steers follow-ups into the running turn.
134
+ - **Resume** — recreate a session from a persisted id after idle eviction or
135
+ server restart. Implies the adapter must learn the backend's _real_ session
136
+ id (CC reports it on `system/init`; we rekey and alias the client's temp id).
137
+ - **Interrupt / cancel** — stop the current turn without killing the session,
138
+ and drop queued messages.
139
+ - **Teardown** — graceful close on idle TTL, LRU eviction, server shutdown.
140
+ - **Turn accounting** — know when a turn ends (CC: `result` message; Codex:
141
+ `turn/completed`) to drive busy/idle state and the processing spinner.
142
+
143
+ ### Per-request configuration
144
+
145
+ - **List supported models**, including per-model metadata such as supported
146
+ effort levels (drives the picker).
147
+ - **Set model** — ideally live mid-session.
148
+ - **Set reasoning effort** — CC has no live setter, so `claude-code/session.ts`
149
+ does a drain-then-teardown-then-resume dance; Codex takes it per turn.
150
+ - **Thinking/reasoning display mode** (Codex: `summary: 'auto'` is required or
151
+ reasoning items arrive empty).
152
+ - **Token streaming opt-in** (CC: `includePartialMessages`, construct-time;
153
+ Codex: always streams, moi gates forwarding).
154
+ - **Permissions / tool policy** — allowed tools, permission mode; backends
155
+ with interactive approvals need a prompt-callback path.
156
+ - **Env injection + cwd** — per-workspace env for the agent's shell, frozen at
157
+ spawn; idle sessions/processes restart to pick up changes.
158
+
159
+ ### Output stream
160
+
161
+ - Assistant text, thinking, tool calls + results → `StreamEvent`s, including
162
+ subagent lanes.
163
+ - Live token preview as an ephemeral sibling frame, never persisted.
164
+ - Images/documents/citations in output.
165
+ - System notices: compaction, rate-limit, API retry, hook output.
166
+ - Errors, distinguishing user aborts from real failures.
167
+ - **User-echo semantics** — see the socket-protocol notes above; the
168
+ optimistic-id rendezvous is a first-class adapter concern.
169
+
170
+ ### Input capabilities
171
+
172
+ - Images (base64 blocks vs data URLs vs file paths — a capability, not a given).
173
+ - File attachments (path-note fallback via `lib/attachment-note.ts`).
174
+ - Rich content blocks vs plain-string prompts.
175
+
176
+ ### Discovery / metadata
177
+
178
+ - List sessions + replay history for cold-loading a thread.
179
+ - MCP server status / configuration pass-through.
180
+ - Init metadata: available tools, slash commands, skills, model in use.
181
+ - Session summary/title for the thread list.
182
+
183
+ ### Worth adding to the contract
184
+
185
+ - **Capability introspection** — a static per-adapter `capabilities` object
186
+ (images inline vs by path? live model switch? token streaming? steering?
187
+ queued input? MCP? subagents?) so session orchestration stays generic.
188
+ - Permission requests as events (interactive approvals).
189
+ - Compaction trigger/observe.
190
+ - Queued-message semantics: does the backend queue natively or must the
191
+ server?
192
+ - Health/auth status events.
193
+
194
+ ## Capability comparison
195
+
196
+ Legend: ✅ supported · ⚠️ partial/workaround · ❌ missing.
197
+
198
+ | Feature | Claude Agent SDK | OpenClaw gateway | Codex app-server |
199
+ | ------------------------ | --------------------------------------------------- | ------------------------- | ------------------------------------- |
200
+ | Long-lived session | ✅ subprocess per session | ✅ gateway-side | ✅ server-side, N threads/process |
201
+ | Queue/steer mid-turn | ⚠️ queued next turn | ⚠️ | ✅ `turn/steer` into live turn |
202
+ | Resume | ✅ | ✅ | ✅ + fork |
203
+ | Interrupt | ✅ `interrupt()` | ✅ | ✅ `turn/interrupt` |
204
+ | List models | ✅ `supportedModels()` | ❌ | ✅ `model/list` |
205
+ | Live model switch | ✅ `setModel()` | ❌ | ✅ per-turn override |
206
+ | Live effort switch | ❌ rebuild | ❌ | ✅ per-turn |
207
+ | Token deltas | ✅ opt-in | ❌ (v2) | ✅ `item/*/delta` |
208
+ | Images in input | ✅ base64 blocks | ⚠️ materialize to path | ✅ data URL or path |
209
+ | Interactive approvals | ⚠️ (we bypass) | ✅ | ✅ server→client requests (we bypass) |
210
+ | Session list/history API | ✅ `listSessions()` + jsonl | ✅ `sessions.get` | ✅ `thread/list`/`read` |
211
+ | MCP status | ✅ `mcpServerStatus()` | n/a | ✅ `mcpServerStatus/list` |
212
+ | Usage reporting | ⚠️ cost/duration on `result` (adapter drops tokens) | ✅ tokens + cost per turn | ✅ live + rate limits |
213
+ | Structured output | ❌ | ❌ | ✅ per turn |
214
+
215
+ ## Design lessons so far
216
+
217
+ - Half of `claude-code/session.ts` exists because some settings are
218
+ live-settable (`setModel`) and some are construct-time (effort, streaming).
219
+ Encode that distinction per-setting in the adapter interface instead of
220
+ hardcoding the drain-then-rebuild machinery.
221
+ - Harnesses split into two topologies: **held-open** (CC subprocess, OpenClaw
222
+ gateway, Codex app-server) and **spawn-per-turn** (Codex exec SDK — see
223
+ `codex/NOTES.md` §1 for why we rejected it). The session manager should
224
+ support both.
225
+ - Event vocabularies differ in kind, not just names: CC emits raw
226
+ tool_use/tool_result pairs; Codex emits semantic items (a patch, a command)
227
+ with their own lifecycle. The adapter layer is where that converges on
228
+ `ToolCall` parts.