moi-computer 0.3.0-next.2 → 0.3.0-next.3

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 +2 -2
  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-6c24yndg.js +61 -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-cwqmay73.css +1 -0
  60. package/dist/chunk-kxmvv1ax.js +48 -0
  61. package/dist/chunk-rq0ar7vp.js +1 -0
  62. package/dist/{chunk-p68fnz3q.js → chunk-vkvb3hjm.js} +1 -1
  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 +239 -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
package/server/api.ts CHANGED
@@ -4,19 +4,18 @@ 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, WorkspaceEntry, WorkspaceModels, WorkspaceType } from '@/lib/types'
7
+ import type { UploadInfo, ViewBuilderInput, WorkspaceEntry, WorkspaceModels } from '@/lib/types'
8
+ import { appendViewBuilderMeta } from '@/lib/view-builder-meta'
8
9
 
9
- import { getClaudeModels } from './agent'
10
10
  import { apiBaseFor, parseAppletTail, serveWorkspaceFile } from './applets'
11
11
  import { applyEnvChanged } from './env-apply'
12
+ import { publishEvent } from './events'
12
13
  import { callFunction, parseFunctionPath } from './functions'
13
14
  import { processIcon } from './icon'
14
15
  import { getWorkspacePreview, loadLayout, mergeLayoutForSave, saveLayout } from './layout'
15
- import { getMcpStatus, getUserMcpStatus } from './mcp'
16
- import { publishEvent } from './events'
17
- import { getOpenClawModels, getOpenClawSessionMessages, getOpenClawSessions } from './openclaw'
18
- import { toSessionInfo, toStreamEvents } from './openclaw-adapter'
19
- import { ensureOpenClawSessionLive, getLiveOpenClawEvents } from './openclaw-session'
16
+ import { getUserMcpStatus } from './harness/claude-code/mcp'
17
+ import { getClientFrameLog, getWireLog } from './harness/debug'
18
+ import { allHarnesses, harnessFor, isHarnessType } from './harness/registry'
20
19
  import {
21
20
  discoverWorkspaces,
22
21
  getWorkspace,
@@ -29,13 +28,21 @@ import {
29
28
  import { loadScratchpadDoc, saveScratchpadDoc } from './scratchpad'
30
29
  import { MAX_ASSET_BYTES, scratchpadAssetFile, storeScratchpadAsset } from './scratchpad-assets'
31
30
  import { DIST_DIR, prebuilt } from './static'
32
- import { getSessionEvents, getSessions } from './state'
33
31
  import { getThreadConfig, saveThreadConfig } from './thread-config'
34
32
  import type { ThreadConfigPatch } from './thread-config'
35
33
  import { serveWorkspaceImagePreview } from './preview'
36
34
  import { MAX_UPLOAD_BYTES, addUpload, getUpload } from './uploads'
37
35
  import { requiredEnvFor } from './required-env'
38
- import { listViews, serveView } from './views'
36
+ import { getViewList, listViews, serveView } from './views'
37
+ import {
38
+ ViewBuilderError,
39
+ beginViewBuilder,
40
+ createViewBuilder,
41
+ deleteViewBuilder,
42
+ markViewBuilderWaiting,
43
+ reconcileViewBuilders,
44
+ updateViewBuilderInput
45
+ } from './view-builders'
39
46
  import { listWidgets, serveWidget } from './widgets'
40
47
  import { getWorkspaceConfig, setWorkspaceConfig } from './workspace-config'
41
48
  import {
@@ -121,6 +128,129 @@ one.get('/views/*', c => {
121
128
  return serveView(name, file, c.get('ws').path, apiBaseFor(id), c.req.header('if-none-match'))
122
129
  })
123
130
 
131
+ function viewBuilderError(err: unknown): { message: string; status: 400 | 404 | 409 } | null {
132
+ return err instanceof ViewBuilderError ? { message: err.message, status: err.status } : null
133
+ }
134
+
135
+ function parseAvailableViewIcons(value: unknown): string[] | null {
136
+ if (!Array.isArray(value)) return null
137
+ const icons = value.filter(
138
+ (icon): icon is string =>
139
+ typeof icon === 'string' && /^[a-z0-9][a-z0-9-]*$/.test(icon) && icon.length <= 64
140
+ )
141
+ return icons.length > 0 ? [...new Set(icons)] : null
142
+ }
143
+
144
+ one.get('/view-builders', async c => {
145
+ const ws = c.get('ws')
146
+ const activeSessionIds = new Set(
147
+ allHarnesses()
148
+ .flatMap(h => h.runningSessions())
149
+ .filter(session => session.workspaceId === ws.id)
150
+ .map(session => session.sessionId)
151
+ )
152
+ const builders = await reconcileViewBuilders(
153
+ ws.id,
154
+ ws.path,
155
+ await getViewList(ws.path),
156
+ activeSessionIds
157
+ )
158
+ // Widget builders are record-only for now — reconciled server-side but kept
159
+ // out of the host's view-builder tab list until their UI lands.
160
+ return c.json({ builders: builders.filter(builder => builder.kind !== 'widget') })
161
+ })
162
+
163
+ one.post('/view-builders', async c => {
164
+ const ws = c.get('ws')
165
+ return c.json(await createViewBuilder(ws.id, ws.path), 201)
166
+ })
167
+
168
+ one.patch('/view-builders/:builderId', async c => {
169
+ const ws = c.get('ws')
170
+ const body = await c.req.json<{ input?: Partial<ViewBuilderInput> }>()
171
+ if (typeof body?.input?.requirements !== 'string') {
172
+ return c.text('Expected { input: { requirements: string } }', 400)
173
+ }
174
+ try {
175
+ return c.json(
176
+ await updateViewBuilderInput(
177
+ ws.id,
178
+ ws.path,
179
+ c.req.param('builderId'),
180
+ body.input.requirements
181
+ )
182
+ )
183
+ } catch (err) {
184
+ const known = viewBuilderError(err)
185
+ if (known) return c.text(known.message, known.status)
186
+ throw err
187
+ }
188
+ })
189
+
190
+ one.post('/view-builders/:builderId/submit', async c => {
191
+ const ws = c.get('ws')
192
+ const body = await c.req.json<{
193
+ input?: Partial<ViewBuilderInput>
194
+ optimisticId?: string
195
+ model?: string
196
+ effort?: string
197
+ stream?: boolean
198
+ availableIcons?: unknown
199
+ }>()
200
+ if (typeof body?.input?.requirements !== 'string') {
201
+ return c.text('Expected { input: { requirements: string } }', 400)
202
+ }
203
+ if (body.optimisticId !== undefined && typeof body.optimisticId !== 'string') {
204
+ return c.text('Invalid optimisticId', 400)
205
+ }
206
+ const availableIcons = parseAvailableViewIcons(body.availableIcons)
207
+ if (!availableIcons) return c.text('Available view icons are required', 400)
208
+ try {
209
+ const builder = await beginViewBuilder(
210
+ ws.id,
211
+ ws.path,
212
+ c.req.param('builderId'),
213
+ body.input.requirements
214
+ )
215
+ const content = appendViewBuilderMeta(builder.input.requirements, builder.id, availableIcons)
216
+ try {
217
+ await harnessFor(ws).sendMessage({
218
+ workspaceId: ws.id,
219
+ workspacePath: ws.path,
220
+ sessionId: builder.sessionId,
221
+ isNew: true,
222
+ content,
223
+ optimisticId: body.optimisticId,
224
+ model: typeof body.model === 'string' ? body.model : undefined,
225
+ effort: typeof body.effort === 'string' ? body.effort : undefined,
226
+ stream: body.stream === true ? true : undefined,
227
+ agentId: ws.agentId
228
+ })
229
+ } catch (err) {
230
+ const message = err instanceof Error ? err.message : 'Could not start view builder'
231
+ await markViewBuilderWaiting(ws.id, ws.path, builder.id, message)
232
+ return c.text(message, 500)
233
+ }
234
+ return c.json(builder)
235
+ } catch (err) {
236
+ const known = viewBuilderError(err)
237
+ if (known) return c.text(known.message, known.status)
238
+ throw err
239
+ }
240
+ })
241
+
242
+ one.delete('/view-builders/:builderId', async c => {
243
+ const ws = c.get('ws')
244
+ try {
245
+ await deleteViewBuilder(ws.id, ws.path, c.req.param('builderId'))
246
+ return c.body(null, 204)
247
+ } catch (err) {
248
+ const known = viewBuilderError(err)
249
+ if (known) return c.text(known.message, known.status)
250
+ throw err
251
+ }
252
+ })
253
+
124
254
  // Workspace file stream — an applet's `fileUrl(path)` resolves here. Streams a
125
255
  // media file from the workspace root (range-enabled). Guarded: traversal and
126
256
  // dotfiles (`.env`, `.moi`, `.git`) are rejected and only media/asset extensions
@@ -215,41 +345,12 @@ one.get('/uploads/:uploadId', c => {
215
345
 
216
346
  one.get('/sessions', async c => {
217
347
  const ws = c.get('ws')
218
- if (ws.type === 'openclaw') {
219
- const rows = await getOpenClawSessions(ws.path, ws.agentId)
220
- return c.json(rows.map(r => toSessionInfo(r, ws.path)))
221
- }
222
- return c.json(await getSessions(ws.path))
348
+ return c.json(await harnessFor(ws).listSessions(ws))
223
349
  })
224
350
 
225
351
  one.get('/sessions/:sessionId/events', async c => {
226
352
  const ws = c.get('ws')
227
- const id = c.req.param('id')
228
- const sessionId = c.req.param('sessionId')
229
- if (ws.type === 'openclaw') {
230
- // Prefer the live view if we already hold one — keeps REST + WS in
231
- // agreement for any reload that lands while a run is active. The first cold
232
- // call also primes the live subscription so subsequent WS frames upsert into
233
- // the same view.
234
- const live = getLiveOpenClawEvents(id, sessionId)
235
- if (live) return c.json(live)
236
- if (ws.agentId) {
237
- try {
238
- const evs = await ensureOpenClawSessionLive({
239
- workspaceId: id,
240
- workspacePath: ws.path,
241
- agentId: ws.agentId,
242
- sessionId
243
- })
244
- return c.json(evs)
245
- } catch {
246
- // fall through to static path
247
- }
248
- }
249
- const preview = await getOpenClawSessionMessages(sessionId, ws.path, ws.agentId)
250
- return c.json(toStreamEvents(preview))
251
- }
252
- return c.json(await getSessionEvents(sessionId, ws.path))
353
+ return c.json(await harnessFor(ws).sessionEvents(ws, c.req.param('sessionId')))
253
354
  })
254
355
 
255
356
  // Per-thread agent settings (model + reasoning effort). GET returns the stored
@@ -279,7 +380,25 @@ one.put('/sessions/:sessionId/config', async c => {
279
380
  })
280
381
 
281
382
  one.get('/mcp', async c => {
282
- return c.json(await getMcpStatus(c.get('ws').path, 'project'))
383
+ const ws = c.get('ws')
384
+ return c.json((await harnessFor(ws).mcpStatus?.(ws)) ?? [])
385
+ })
386
+
387
+ // Harness debug tap for /playground/harness: the backend's native wire frames
388
+ // (Codex: app-server JSON-RPC, both directions; Claude Code: raw SDK messages
389
+ // + enqueued inputs) and the exact frames the server pushed to chat clients.
390
+ // `sinceWire`/`sinceBroadcast` are seq cursors so the page can poll deltas.
391
+ one.get('/harness/debug', async c => {
392
+ const ws = c.get('ws')
393
+ const harness = harnessFor(ws)
394
+ const sinceWire = Number(c.req.query('sinceWire') ?? 0) || 0
395
+ const sinceBroadcast = Number(c.req.query('sinceBroadcast') ?? 0) || 0
396
+ return c.json({
397
+ provider: harness.id,
398
+ process: (await harness.debugInfo?.(ws)) ?? null,
399
+ wire: getWireLog(harness.wireScope?.(ws) ?? ws.id, sinceWire),
400
+ broadcasts: getClientFrameLog(ws.id, sinceBroadcast)
401
+ })
283
402
  })
284
403
 
285
404
  // Per-workspace env vars. GET returns the effective view (discovered `.env` + UI
@@ -345,16 +464,11 @@ one.put('/env', async c => {
345
464
  // account-wide Agent SDK model list.
346
465
  one.get('/models', async c => {
347
466
  const ws = c.get('ws')
348
- const provider: WorkspaceType = ws.type ?? 'claude-code'
349
- const models =
350
- provider === 'openclaw' ? await getOpenClawModels() : await getClaudeModels(ws.path)
351
- // Claude Code streams live tokens via `includePartialMessages`; OpenClaw
352
- // uses durable rows only (no token deltas), so it opts out.
353
- const supportsStreaming = provider !== 'openclaw'
467
+ const harness = harnessFor(ws)
354
468
  return c.json({
355
- provider,
356
- models,
357
- supportsStreaming
469
+ provider: harness.id,
470
+ models: await harness.listModels(ws),
471
+ supportsStreaming: harness.capabilities.supportsStreaming
358
472
  } satisfies WorkspaceModels)
359
473
  })
360
474
 
@@ -538,7 +652,7 @@ workspaces.post('/', async c => {
538
652
  const body = await c.req.json()
539
653
  if (!body?.path) return c.text('Missing path', 400)
540
654
  const rawType = body?.type
541
- const type = rawType === 'claude-code' || rawType === 'openclaw' ? rawType : undefined
655
+ const type = isHarnessType(rawType) ? rawType : undefined
542
656
  const path = resolve(String(body.path))
543
657
  // Importing IS initializing: lay down the bundled skills (in the backend's
544
658
  // skills dir) and the `.moi/` scaffold, exactly like `moi init` — a workspace
package/server/applets.ts CHANGED
@@ -22,7 +22,7 @@ import {
22
22
  buildApplet,
23
23
  scanAssetImports,
24
24
  scanServerImports
25
- } from './build-applet'
25
+ } from './bundler/build-applet'
26
26
 
27
27
  export type AppletPaths = {
28
28
  moiRoot: string
@@ -0,0 +1,19 @@
1
+ const bundleChains = new Map<string, Promise<unknown>>()
2
+
3
+ export function serializeWorkspaceBundle<T>(
4
+ workspacePath: string,
5
+ run: () => Promise<T>
6
+ ): Promise<T> {
7
+ const previous = bundleChains.get(workspacePath) ?? Promise.resolve()
8
+ const current = previous.then(run, run)
9
+ bundleChains.set(workspacePath, current)
10
+ void current.then(
11
+ () => {
12
+ if (bundleChains.get(workspacePath) === current) bundleChains.delete(workspacePath)
13
+ },
14
+ () => {
15
+ if (bundleChains.get(workspacePath) === current) bundleChains.delete(workspacePath)
16
+ }
17
+ )
18
+ return current
19
+ }
@@ -0,0 +1,50 @@
1
+ // Scopes a compiled applet stylesheet to its mount container.
2
+ //
3
+ // Applet bundles compile with the full `@import 'tailwindcss'` — preflight,
4
+ // theme variables, utilities — and the result is injected into the host
5
+ // document at runtime. Unscoped, those rules are page-global: the widget's
6
+ // preflight resets host elements, its theme layer redefines variables on
7
+ // `:root`, and its utilities (arriving later in the document than the host
8
+ // stylesheet) win cascade ties against the host's — most visibly for
9
+ // media-query variants. Scoping pins every rule to the applet's own subtree.
10
+ //
11
+ // The transform prefixes each selector with `[data-applet="<scope>"]` — the
12
+ // attribute the client puts on the applet's mount container (see
13
+ // client/features/applets/AppletMount.tsx). Selectors that address the page
14
+ // root (`:root`, `:host`, `html`, `body`) are mapped onto the container
15
+ // itself, so theme variables and preflight inheritance (line-height, font)
16
+ // land there and inherit down. Rules inside `@keyframes` are left alone —
17
+ // keyframe step selectors (`0%`, `to`) aren't element selectors.
18
+ //
19
+ // The uniform `+1 attribute` specificity bump preserves the stylesheet's
20
+ // internal cascade and makes applet rules beat same-layer host rules inside
21
+ // the container — which is exactly the priority we want.
22
+ //
23
+ // Known limitation: content the applet portals outside its container
24
+ // (e.g. to document.body) escapes the scope and won't receive applet styles.
25
+ import postcss, { type Container, type Document } from 'postcss'
26
+
27
+ // A selector's leading page-root token, if any. `(?![\w-])` keeps `body` from
28
+ // matching an unrelated tag/class prefix like `bodycopy`.
29
+ const PAGE_ROOT_RE = /^(:root|:host|html|body)(?![\w-])/
30
+
31
+ function insideKeyframes(parent: Container | Document | undefined): boolean {
32
+ return parent?.type === 'atrule' && /keyframes$/i.test((parent as { name: string }).name)
33
+ }
34
+
35
+ export function scopeAppletCss(css: string, scope: string): string {
36
+ const container = `[data-applet=${JSON.stringify(scope)}]`
37
+ const root = postcss.parse(css)
38
+
39
+ root.walkRules(rule => {
40
+ if (insideKeyframes(rule.parent)) return
41
+ rule.selectors = rule.selectors.map(selector => {
42
+ const s = selector.trim()
43
+ const rootToken = PAGE_ROOT_RE.exec(s)
44
+ if (rootToken) return container + s.slice(rootToken[0].length)
45
+ return `${container} ${s}`
46
+ })
47
+ })
48
+
49
+ return root.toString()
50
+ }
@@ -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,