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

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 (150) hide show
  1. package/bunfig.toml +5 -1
  2. package/client/AGENTS.md +15 -0
  3. package/client/accept-hmr-dependencies.ts +22 -0
  4. package/client/api/http.ts +31 -0
  5. package/client/api/query-options.ts +6 -0
  6. package/client/api/workspace-keys.ts +17 -0
  7. package/client/app/AppRouter.tsx +35 -0
  8. package/client/app/routes/HomeRoute.tsx +13 -0
  9. package/client/app/routes/WorkspaceRoute.tsx +89 -0
  10. package/client/app/shell/SidebarLayout.tsx +191 -0
  11. package/client/assets.d.ts +9 -0
  12. package/client/components/playground/PixelPainter.tsx +10 -21
  13. package/client/components/playground/PlaygroundPage.tsx +9 -11
  14. package/client/components/playground/ToolCallsPage.tsx +9 -11
  15. package/client/components/{BottomPanel.tsx → shared/BottomPanel.tsx} +1 -1
  16. package/client/components/shared/PanelHeader.tsx +9 -0
  17. package/client/components/shared/ReorderableList.tsx +199 -0
  18. package/client/components/ui/button.tsx +10 -7
  19. package/client/components/ui/collapsible.tsx +15 -0
  20. package/client/components/ui/dialog.tsx +2 -2
  21. package/client/components/ui/dropdown-menu.tsx +5 -5
  22. package/client/components/ui/hover-card.tsx +1 -1
  23. package/client/components/ui/popover.tsx +1 -1
  24. package/client/components/ui/skeleton.tsx +13 -0
  25. package/client/components/ui/tooltip.tsx +1 -1
  26. package/client/externalize-react.ts +7 -1
  27. package/client/{components → features/applets}/WidgetErrorBoundary.tsx +1 -1
  28. package/client/{components → features/applets}/WidgetShell.tsx +1 -1
  29. package/client/{hooks → features/applets}/useApplet.ts +6 -7
  30. package/client/{components/ChatInput.tsx → features/chat/ChatComposer.tsx} +29 -23
  31. package/client/features/chat/ChatPanel.tsx +188 -0
  32. package/client/{components → features/chat}/ChatPopup.tsx +23 -12
  33. package/client/{components → features/chat}/MarkdownContent.tsx +1 -1
  34. package/client/{components → features/chat}/ModelPicker.tsx +68 -17
  35. package/client/{components → features/chat}/ThreadSelector.tsx +11 -9
  36. package/client/{components → features/chat}/TurnView.tsx +16 -9
  37. package/client/features/chat/api.ts +78 -0
  38. package/client/features/chat/chat-connection.ts +107 -0
  39. package/client/features/chat/chat-frames.ts +131 -0
  40. package/client/{lib → features/chat}/preview-turn.ts +1 -1
  41. package/client/{components → features/chat}/tool-group/ReadImagePreview.tsx +1 -1
  42. package/client/{components → features/chat}/tool-group/SubagentCard.tsx +12 -10
  43. package/client/{components → features/chat}/tool-group/TimelineRow.tsx +5 -5
  44. package/client/{components → features/chat}/tool-group/ToolCallGroup.tsx +12 -4
  45. package/client/{components → features/chat}/tool-group/ToolOutput.tsx +12 -18
  46. package/client/{hooks → features/chat}/useChat.ts +7 -11
  47. package/client/features/connectors/ConnectorsPage.tsx +92 -0
  48. package/client/features/connectors/McpMenu.tsx +162 -0
  49. package/client/features/connectors/api.ts +28 -0
  50. package/client/features/home/CreateWorkspaceDialog.tsx +224 -0
  51. package/client/features/home/HomePage.tsx +220 -0
  52. package/client/{components → features/home}/WorkspacePreview.tsx +2 -2
  53. package/client/features/home/api.ts +148 -0
  54. package/client/features/home/workspace-presentation.tsx +44 -0
  55. package/client/features/scratchpad/Scratchpad.tsx +312 -0
  56. package/client/features/scratchpad/ScratchpadControls.tsx +503 -0
  57. package/client/features/scratchpad/useScratchpadSnapshot.tsx +115 -0
  58. package/client/features/settings/EnvironmentSettings.tsx +149 -0
  59. package/client/features/settings/GeneralSettings.tsx +90 -0
  60. package/client/{components → features}/settings/IconPicker.tsx +73 -222
  61. package/client/features/settings/SettingsLayout.tsx +53 -0
  62. package/client/{components → features}/settings/WorkspaceSettings.tsx +12 -16
  63. package/client/features/settings/api.ts +88 -0
  64. package/client/features/settings/icon-picker-options.ts +161 -0
  65. package/client/{hooks → features/settings}/useEnvVars.ts +4 -4
  66. package/client/{components → features/widgets}/HiddenPanel.tsx +3 -3
  67. package/client/{components → features/widgets}/WidgetFrame.tsx +3 -8
  68. package/client/{components → features/widgets}/WidgetGrid.tsx +2 -9
  69. package/client/features/widgets/Widgets.tsx +215 -0
  70. package/client/{lib/grid-pack.ts → features/widgets/grid.ts} +7 -1
  71. package/client/{hooks → features/widgets}/useGridReconcile.ts +1 -1
  72. package/client/{components → features/workspace}/CustomizePanel.tsx +5 -6
  73. package/client/{lib → features/workspace}/WorkspaceLayoutContext.tsx +15 -8
  74. package/client/features/workspace/WorkspaceScreen.tsx +536 -0
  75. package/client/features/workspace/WorkspaceTabs.tsx +205 -0
  76. package/client/features/workspace/api.ts +56 -0
  77. package/client/features/workspace/useFitsSplitLayout.ts +37 -0
  78. package/client/global.d.ts +5 -0
  79. package/client/index.css +6 -10
  80. package/client/index.html +1 -1
  81. package/client/index.tsx +14 -31
  82. package/client/lib/ws-url.ts +10 -0
  83. package/client/main.tsx +2 -2
  84. package/client/runtime/hmr-watchdog.ts +39 -0
  85. package/client/{hooks/useMeiEvents.ts → runtime/useWorkspaceEvents.ts} +11 -7
  86. package/client/store/ui.ts +5 -1
  87. package/client/theme.css +0 -2
  88. package/dist/chunk-11cab5dq.css +1 -0
  89. package/dist/chunk-23cgr1tz.css +1 -0
  90. package/dist/chunk-3hy3qy6d.js +10 -0
  91. package/dist/chunk-c4j722at.js +546 -0
  92. package/dist/chunk-dyfaffyz.js +119 -0
  93. package/dist/chunk-kpe40hm8.js +1 -0
  94. package/dist/chunk-p68fnz3q.js +2 -0
  95. package/dist/chunk-pcnahct1.js +5 -0
  96. package/dist/chunk-tqd3pkg8.css +1 -0
  97. package/dist/chunk-ty6dvda0.js +1 -0
  98. package/dist/index.html +2 -2
  99. package/lib/types.ts +18 -7
  100. package/lib/workspace-name.ts +14 -0
  101. package/package.json +3 -2
  102. package/server/api.ts +127 -17
  103. package/server/applets.ts +84 -8
  104. package/server/cli.ts +11 -5
  105. package/server/layout.ts +38 -7
  106. package/server/mcp.ts +72 -15
  107. package/server/moi-scaffold.ts +55 -10
  108. package/server/registry.ts +16 -0
  109. package/server/views.ts +0 -0
  110. package/server/web.ts +1 -0
  111. package/server/widgets.ts +3 -2
  112. package/server/workspace-init.ts +5 -19
  113. package/tsconfig.json +1 -1
  114. package/workspace/.claude/skills/moi-workspace/DESIGN.md +1 -1
  115. package/workspace/.claude/skills/moi-workspace/VIEW-DESIGN.md +1 -1
  116. package/client/api/workspaces.ts +0 -427
  117. package/client/components/App.tsx +0 -41
  118. package/client/components/ChatPanel.tsx +0 -275
  119. package/client/components/HomePage.tsx +0 -17
  120. package/client/components/McpMenu.tsx +0 -125
  121. package/client/components/Scratchpad.tsx +0 -935
  122. package/client/components/Widgets.tsx +0 -132
  123. package/client/components/WorkspacesPage.tsx +0 -245
  124. package/client/components/layout/SidebarLayout.tsx +0 -258
  125. package/client/components/routes/workspace/[id].tsx +0 -675
  126. package/client/components/routes/workspace/create.tsx +0 -155
  127. package/client/components/settings/SettingsPages.tsx +0 -255
  128. package/client/hooks/useFitsSidebar.ts +0 -34
  129. package/client/lib/connection.ts +0 -237
  130. package/dist/chunk-07qf2tv1.css +0 -1
  131. package/dist/chunk-c3zjp9ez.js +0 -672
  132. /package/client/components/{playground → shared}/LedLogo.tsx +0 -0
  133. /package/client/{lib → features/applets}/applet-cache.ts +0 -0
  134. /package/client/{components → features/chat}/ShimmerText.tsx +0 -0
  135. /package/client/{store/live.ts → features/chat/chat-store.ts} +0 -0
  136. /package/client/{lib → features/chat}/group-turns.ts +0 -0
  137. /package/client/{components → features/chat}/tool-group/CodeBlock.tsx +0 -0
  138. /package/client/{components → features/chat}/tool-group/Collapse.tsx +0 -0
  139. /package/client/{components → features/chat}/tool-group/detect.ts +0 -0
  140. /package/client/{components → features/chat}/tool-group/fixtures.ts +0 -0
  141. /package/client/{components → features/chat}/tool-group/format.ts +0 -0
  142. /package/client/{components → features/chat}/tool-group/index.ts +0 -0
  143. /package/client/{lib → features/chat}/uploads.ts +0 -0
  144. /package/client/{hooks → features/chat}/useStickToBottom.ts +0 -0
  145. /package/client/{components → features/connectors}/IconMcp.tsx +0 -0
  146. /package/client/{lib → features/connectors}/mcp-icons.ts +0 -0
  147. /package/client/{lib → features/scratchpad}/scratch-executor.ts +0 -0
  148. /package/client/{lib → features/settings}/render-icon.ts +0 -0
  149. /package/client/{lib → features/workspace}/WorkspaceContext.tsx +0 -0
  150. /package/client/{hooks → features/workspace}/useWorkspaceTheme.ts +0 -0
package/server/applets.ts CHANGED
@@ -12,7 +12,7 @@
12
12
  // `%%MOI_APPLET_API_BASE%%` sentinel (for RPC + `fileUrl`), swapped to the real
13
13
  // `/api/workspaces/<id>` base when served — so the on-disk bundle is
14
14
  // workspace-agnostic.
15
- import { realpathSync } from 'node:fs'
15
+ import { realpathSync, statSync } from 'node:fs'
16
16
  import { mkdir, readdir, rm } from 'node:fs/promises'
17
17
  import { dirname, join, resolve, sep } from 'path'
18
18
 
@@ -136,16 +136,44 @@ const CODE_FILE_RE = /\.js$/
136
136
  // can be requested; `..` is rejected separately.
137
137
  const ALLOWED_FILE_RE = /^[a-zA-Z0-9_-][a-zA-Z0-9._-]*$/
138
138
 
139
+ const JS_CONTENT_TYPE = 'text/javascript; charset=utf-8'
140
+ // A content-hashed url is a fingerprint of its bytes, so it's safe to cache
141
+ // without revalidation. But immutability here is INFERRED from the filename
142
+ // (HASHED_FILE_RE) rather than guaranteed by construction (unlike a sha256-named
143
+ // asset) — so we cap the TTL at a week instead of the usual year. If that
144
+ // inference ever misfires, a wrongly-pinned copy self-heals within a week at the
145
+ // edge and in the browser, rather than sticking around for a year.
146
+ const IMMUTABLE_CACHE = 'public, max-age=604800, immutable'
147
+
148
+ // Which build-dir files are safe to serve `immutable`. The build emits exactly
149
+ // two content-hashed shapes — Bun's `chunk-<hash>.js` and the runtime plugin's
150
+ // `<stem>-<hash>.<ext>` assets (hash = hex, see build-applet.ts) — alongside the
151
+ // ONE stable-named entry, `index.js`. We match those shapes POSITIVELY and
152
+ // default everything else (the entry, and anything unexpected) to revalidation:
153
+ // this fix exists to stop a shared cache pinning a stale copy at a stable url,
154
+ // so an unrecognized name must fail safe (revalidate), never fail stale
155
+ // (immutable). The hex-suffix arm rejects real words (`-sprite`, `-preview`) —
156
+ // they aren't hex — so only genuine hashes opt in.
157
+ const HASHED_FILE_RE = /^chunk-[0-9a-z]+\.\w+$|-[0-9a-f]{6,}\.\w+$/i
158
+
139
159
  // Serve one file from a compiled applet directory: the `index.js` entry, a code
140
160
  // chunk, or a bundled asset. `apiBase` is the workspace's `/api/workspaces/<id>`
141
161
  // prefix — substituted for the build-time sentinel in every `.js` so RPC and
142
162
  // `fileUrl` calls hit the right workspace. Assets stream untouched.
163
+ //
164
+ // Caching turns on the hashed-vs-stable split. A content-hashed chunk/asset gets
165
+ // a new url whenever its bytes change, so it's cached forever. The `index.js`
166
+ // entry (and anything not recognizably hashed) lives at ONE url across rebuilds,
167
+ // so a shared cache (e.g. Cloudflare) that stored it once would hand back a
168
+ // STALE copy after the next `moi bundle` — it gets an ETag (size+mtime) +
169
+ // `no-cache` instead, so an unchanged file costs a 304 and a rebuilt one busts.
143
170
  export async function serveApplet(
144
171
  kind: AppletKind,
145
172
  name: string,
146
173
  file: string,
147
174
  workspacePath: string,
148
- apiBase: string
175
+ apiBase: string,
176
+ ifNoneMatch?: string | null
149
177
  ): Promise<Response> {
150
178
  if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
151
179
  return new Response('Invalid name', { status: 400 })
@@ -160,11 +188,25 @@ export async function serveApplet(
160
188
  if (!(await bunFile.exists())) {
161
189
  return new Response(`"${name}" not built. Run: moi bundle`, { status: 404 })
162
190
  }
191
+
192
+ // Content-hashed → immutable. Everything else → revalidate (ETag + no-cache),
193
+ // short-circuiting to a bodyless 304 when the client's ETag still matches.
194
+ let cache: Record<string, string>
195
+ if (HASHED_FILE_RE.test(file)) {
196
+ cache = { 'Cache-Control': IMMUTABLE_CACHE }
197
+ } else {
198
+ const etag = `"${bunFile.size}-${Math.trunc(bunFile.lastModified)}"`
199
+ cache = { ETag: etag, 'Cache-Control': 'no-cache' }
200
+ if (ifNoneMatch === etag) return new Response(null, { status: 304, headers: cache })
201
+ }
202
+
163
203
  if (CODE_FILE_RE.test(file)) {
164
204
  const swapped = (await bunFile.text()).replaceAll(APPLET_API_BASE_SENTINEL, apiBase)
165
- return new Response(swapped, { headers: { 'Content-Type': 'text/javascript; charset=utf-8' } })
205
+ return new Response(swapped, { headers: { 'Content-Type': JS_CONTENT_TYPE, ...cache } })
166
206
  }
167
- return new Response(bunFile)
207
+ return new Response(bunFile, {
208
+ headers: { 'Content-Type': bunFile.type || 'application/octet-stream', ...cache }
209
+ })
168
210
  }
169
211
 
170
212
  // ---- route helpers ----------------------------------------------------------
@@ -255,23 +297,51 @@ export function resolveWorkspaceMediaFile(workspaceRoot: string, tail: string):
255
297
  // Range is handled explicitly (slice the BunFile, 206 + Content-Range): Bun's
256
298
  // implicit range handling for `new Response(Bun.file())` doesn't fire once any
257
299
  // headers object is attached, and <video>/<audio> seeking needs byte ranges.
300
+ //
301
+ // Caching: these are the user's own workspace files — private, and rewritten in
302
+ // place by the agent (a regenerated clip keeps its path). So they must NEVER be
303
+ // stored by a shared/edge cache sitting in front of moi, or one user's video
304
+ // could be served to the next, and an edited file could be served stale from a
305
+ // stable url (the applet-bundle incident, but with private bytes). `private`
306
+ // keeps them off the edge; a strong ETag (size + nanosecond mtime) + `no-cache`
307
+ // lets the browser revalidate cheaply (304) while re-fetching when it changes.
258
308
  export async function serveWorkspaceFile(
259
309
  workspaceRoot: string,
260
310
  tail: string,
261
- range?: string | null
311
+ range?: string | null,
312
+ ifNoneMatch?: string | null
262
313
  ): Promise<Response> {
263
314
  const realTarget = resolveWorkspaceMediaFile(workspaceRoot, tail)
264
315
  if (realTarget instanceof Response) return realTarget
265
316
  const file = Bun.file(realTarget)
266
317
 
267
- const size = file.size
318
+ let stat: ReturnType<typeof statSync>
319
+ try {
320
+ stat = statSync(realTarget, { bigint: true })
321
+ } catch {
322
+ return new Response('Not found', { status: 404 })
323
+ }
324
+ const size = Number(stat.size)
268
325
  const type = file.type || 'application/octet-stream'
326
+
327
+ // Validator = size + NANOSECOND mtime. This route serves agent-regenerated
328
+ // files at stable paths, so a weak validator that returns a false 304 pins
329
+ // stale media in the browser. Truncating mtime to whole milliseconds (or
330
+ // seconds) can collide when a same-length rewrite lands inside one tick; ns
331
+ // resolution closes that window without hashing the (possibly huge) file on
332
+ // every request. A tool that deliberately preserves mtime with same-size but
333
+ // different bytes could still collide — only a content hash defeats that, and
334
+ // it's not worth re-reading a video per request when agents rewrite normally.
335
+ const etag = `"${size}-${stat.mtimeNs}"`
336
+ const cache = { ETag: etag, 'Cache-Control': 'private, no-cache' }
337
+ if (ifNoneMatch === etag) return new Response(null, { status: 304, headers: cache })
338
+
269
339
  const parsed = range ? parseByteRange(range, size) : null
270
340
 
271
341
  if (parsed === 'invalid') {
272
342
  return new Response('Range Not Satisfiable', {
273
343
  status: 416,
274
- headers: { 'Content-Range': `bytes */${size}`, 'Accept-Ranges': 'bytes' }
344
+ headers: { ...cache, 'Content-Range': `bytes */${size}`, 'Accept-Ranges': 'bytes' }
275
345
  })
276
346
  }
277
347
  if (parsed) {
@@ -279,6 +349,7 @@ export async function serveWorkspaceFile(
279
349
  return new Response(file.slice(start, end + 1), {
280
350
  status: 206,
281
351
  headers: {
352
+ ...cache,
282
353
  'Content-Type': type,
283
354
  'Content-Length': String(end - start + 1),
284
355
  'Content-Range': `bytes ${start}-${end}/${size}`,
@@ -287,7 +358,12 @@ export async function serveWorkspaceFile(
287
358
  })
288
359
  }
289
360
  return new Response(file, {
290
- headers: { 'Content-Type': type, 'Content-Length': String(size), 'Accept-Ranges': 'bytes' }
361
+ headers: {
362
+ ...cache,
363
+ 'Content-Type': type,
364
+ 'Content-Length': String(size),
365
+ 'Accept-Ranges': 'bytes'
366
+ }
291
367
  })
292
368
  }
293
369
 
package/server/cli.ts CHANGED
@@ -248,8 +248,11 @@ const init = defineCommand({
248
248
  agent ? 'openclaw' : 'claude-code'
249
249
  )
250
250
  if (scaffold !== 'exists') {
251
- console.log(pc.dim(' Installed widget dependencies in .moi/'))
252
- if (scaffold !== 0) {
251
+ if (scaffold === 'installing') {
252
+ console.log(pc.dim(' Widget dependencies still installing in .moi/ (background)'))
253
+ } else if (scaffold === 0) {
254
+ console.log(pc.dim(' Installed widget dependencies in .moi/'))
255
+ } else {
253
256
  console.warn(pc.yellow(' bun install failed — run it manually in .moi/'))
254
257
  }
255
258
  }
@@ -914,9 +917,12 @@ const openclawInit = defineCommand({
914
917
  // the folder and its dependencies exist. Existing `.moi/` stays untouched.
915
918
  const { scaffold, skillsDir: skillsRoot } = await provisionWorkspace(target.path, 'openclaw')
916
919
  if (scaffold !== 'exists') {
917
- console.log('\n' + pc.dim(' Installed widget dependencies in .moi/'))
918
- if (scaffold !== 0) {
919
- console.warn(pc.yellow(' bun install failed — run it manually in .moi/'))
920
+ if (scaffold === 'installing') {
921
+ console.log('\n' + pc.dim(' Widget dependencies still installing in .moi/ (background)'))
922
+ } else if (scaffold === 0) {
923
+ console.log('\n' + pc.dim(' Installed widget dependencies in .moi/'))
924
+ } else {
925
+ console.warn('\n' + pc.yellow(' bun install failed — run it manually in .moi/'))
920
926
  }
921
927
  }
922
928
 
package/server/layout.ts CHANGED
@@ -1,12 +1,42 @@
1
1
  import { readdir } from 'node:fs/promises'
2
2
  import { join } from 'path'
3
3
 
4
- import type { WidgetConfig, WorkspaceLayout, WorkspacePreview } from '@/lib/types'
4
+ import type { WidgetConfig, WorkspaceLayout, WorkspacePreview, WorkspaceTabId } from '@/lib/types'
5
5
 
6
6
  const DEFAULT: WorkspaceLayout = {
7
7
  version: 1,
8
8
  widgetGrid: [],
9
- chatMode: 'sidebar'
9
+ layoutMode: 'fullscreen',
10
+ tabs: { open: ['agent'], active: 'agent' }
11
+ }
12
+
13
+ function isTabId(value: unknown): value is WorkspaceTabId {
14
+ return (
15
+ value === 'agent' ||
16
+ value === 'widgets' ||
17
+ value === 'scratchpad' ||
18
+ (typeof value === 'string' && /^view:.+/.test(value))
19
+ )
20
+ }
21
+
22
+ function normalizeTabs(value: unknown): WorkspaceLayout['tabs'] {
23
+ if (!value || typeof value !== 'object') return { ...DEFAULT.tabs, open: [...DEFAULT.tabs.open] }
24
+ const raw = value as Record<string, unknown>
25
+ const open = Array.isArray(raw.open)
26
+ ? raw.open.filter(isTabId).filter((tab, index, all) => all.indexOf(tab) === index)
27
+ : []
28
+ if (open.length === 0) return { ...DEFAULT.tabs, open: [...DEFAULT.tabs.open] }
29
+ const active = isTabId(raw.active) && open.includes(raw.active) ? raw.active : open[0]
30
+ return { open, active }
31
+ }
32
+
33
+ function normalizeLayout(parsed: Record<string, unknown>): WorkspaceLayout {
34
+ const layout = { ...DEFAULT, ...parsed } as Record<string, unknown>
35
+ if (layout.layoutMode !== 'split') layout.layoutMode = 'fullscreen'
36
+ layout.tabs = normalizeTabs(layout.tabs)
37
+ delete layout.sectionMode
38
+ delete layout.chatMode
39
+ return layout as unknown as WorkspaceLayout
10
40
  }
11
41
 
12
42
  const DEFAULT_WIDGET_CONFIG: WidgetConfig = { rowSpan: 1, colSpan: 2 }
@@ -21,7 +51,7 @@ export async function loadLayout(workspacePath: string): Promise<WorkspaceLayout
21
51
  try {
22
52
  const text = await Bun.file(getLayoutPath(workspacePath)).text()
23
53
  const parsed = JSON.parse(text)
24
- if (parsed?.version === 1) return parsed as WorkspaceLayout
54
+ if (parsed?.version === 1) return normalizeLayout(parsed)
25
55
  } catch {}
26
56
  return { ...DEFAULT }
27
57
  }
@@ -32,10 +62,11 @@ export async function saveLayout(layout: WorkspaceLayout, workspacePath: string)
32
62
 
33
63
  // Merge a client-submitted layout over the stored one for persistence.
34
64
  //
35
- // Everything (grid, chat mode, theme, AND identity) shares one `.workspace.json`,
36
- // but the grid editor and `moi config` own different fields. The client's layout
37
- // PUT is authoritative for the editor fields (widgetGrid, chatMode, theme,
38
- // selectedModel) — but it strips `name` and round-trips a possibly-stale `icon`.
65
+ // Everything (grid, layout mode, theme, AND identity) shares one
66
+ // `.workspace.json`, but the grid editor and `moi config` own different fields.
67
+ // The client's layout PUT is authoritative for the editor fields (widgetGrid,
68
+ // layoutMode, theme, selectedModel) — but it strips `name` and round-trips a
69
+ // possibly-stale `icon`.
39
70
  // A blind overwrite therefore erases a `moi config`-set name (and could revert an
40
71
  // icon). So drop whatever identity the body carries and re-apply the server-owned
41
72
  // `name`/`icon` from `existing` — conditionally, so an absent field never
package/server/mcp.ts CHANGED
@@ -1,8 +1,15 @@
1
1
  import { query } from '@anthropic-ai/claude-agent-sdk'
2
- import type { McpServerStatus, SDKUserMessage } from '@anthropic-ai/claude-agent-sdk'
2
+ import type {
3
+ McpServerConfig,
4
+ McpServerStatus,
5
+ SDKUserMessage
6
+ } from '@anthropic-ai/claude-agent-sdk'
7
+ import { join } from 'path'
3
8
 
4
9
  import { debugEnabled } from './debug'
5
10
 
11
+ export type McpScope = 'user' | 'project'
12
+
6
13
  // MCP server status probing. Intentionally decoupled from agent chat runs
7
14
  // (cc-session.ts): connecting to MCP servers and reading their status is a
8
15
  // metadata concern, not part of any conversation. Nothing here submits a user
@@ -31,9 +38,9 @@ function isSettled(status: McpServerStatus[]): boolean {
31
38
  // attention (failed / needs-auth / still-pending) called out by name. The full
32
39
  // per-server dump (every `connected` line too) is opt-in via `moi start --debug`.
33
40
  // `connected`/`disabled` are the boring majority, so they're folded into counts.
34
- function logMcpStatus(status: McpServerStatus[]): void {
41
+ function logMcpStatus(scope: McpScope, status: McpServerStatus[]): void {
35
42
  if (debugEnabled) {
36
- console.log('[mcp]', status.map(s => `${s.name}:${s.status}`).join(', '))
43
+ console.log(`[mcp:${scope}]`, status.map(s => `${s.name}:${s.status}`).join(', '))
37
44
  return
38
45
  }
39
46
  const connected = status.filter(s => s.status === 'connected').length
@@ -42,10 +49,41 @@ function logMcpStatus(status: McpServerStatus[]): void {
42
49
  const parts = [`${connected} connected`]
43
50
  if (disabled) parts.push(`${disabled} disabled`)
44
51
  for (const s of attention) parts.push(`${s.status}: ${s.name}`)
45
- console.log('[mcp]', parts.join(' · '))
52
+ console.log(`[mcp:${scope}]`, parts.join(' · '))
53
+ }
54
+
55
+ function isRecord(value: unknown): value is Record<string, unknown> {
56
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
57
+ }
58
+
59
+ async function projectMcpServers(workspacePath: string): Promise<Record<string, McpServerConfig>> {
60
+ const file = Bun.file(join(workspacePath, '.mcp.json'))
61
+ if (!(await file.exists())) return {}
62
+
63
+ const parsed = await file.json().catch(() => null)
64
+ if (!isRecord(parsed) || !isRecord(parsed.mcpServers)) return {}
65
+
66
+ const servers: Record<string, McpServerConfig> = {}
67
+ for (const [name, config] of Object.entries(parsed.mcpServers)) {
68
+ // The SDK owns the detailed MCP config union; here we only need to confirm
69
+ // the project JSON declares an object keyed by server name before passing it
70
+ // through unchanged.
71
+ if (isRecord(config)) servers[name] = config as unknown as McpServerConfig
72
+ }
73
+ return servers
46
74
  }
47
75
 
48
- async function probeMcpStatus(workspacePath: string): Promise<McpServerStatus[]> {
76
+ async function probeMcpStatus(workspacePath: string, scope: McpScope): Promise<McpServerStatus[]> {
77
+ // Known gap, revisit: the project probe covers only `.mcp.json` (strict), and
78
+ // the user probe runs from the server's cwd — so servers added via `claude
79
+ // mcp add` (user scope) or `.claude/settings(.local).json` never appear in
80
+ // the workspace connectors menu, even though chat sessions still load them
81
+ // (cc-session runs with settingSources ['user','project']). Surfacing those
82
+ // scopes here needs a per-workspace user+project probe without double-listing
83
+ // servers across the menu and the /connectors page.
84
+ const mcpServers = scope === 'project' ? await projectMcpServers(workspacePath) : undefined
85
+ if (scope === 'project' && Object.keys(mcpServers ?? {}).length === 0) return []
86
+
49
87
  // A prompt that never yields keeps the session alive without a model turn.
50
88
  let release!: () => void
51
89
  const done = new Promise<void>(r => (release = r))
@@ -61,7 +99,8 @@ async function probeMcpStatus(workspacePath: string): Promise<McpServerStatus[]>
61
99
  options: {
62
100
  cwd: workspacePath,
63
101
  persistSession: false,
64
- settingSources: ['user', 'project'],
102
+ settingSources: [scope],
103
+ ...(mcpServers && { mcpServers, strictMcpConfig: true }),
65
104
  env: { ...process.env, CLAUDECODE: undefined }
66
105
  }
67
106
  })
@@ -74,11 +113,17 @@ async function probeMcpStatus(workspacePath: string): Promise<McpServerStatus[]>
74
113
  if (isSettled(status)) break
75
114
  await new Promise(r => setTimeout(r, POLL_INTERVAL_MS))
76
115
  }
77
- logMcpStatus(status)
116
+ logMcpStatus(scope, status)
78
117
  return status
79
118
  } finally {
80
119
  release()
81
- await q.close()
120
+ // This metadata-only probe intentionally never submits a user turn, so the
121
+ // SDK may report that it was closed before receiving a response.
122
+ try {
123
+ q.close()
124
+ } catch {
125
+ // The connector status is already settled, so cleanup must not replace it.
126
+ }
82
127
  }
83
128
  }
84
129
 
@@ -105,21 +150,33 @@ const cache = new Map<string, CacheEntry>()
105
150
  // cheap insurance against parallel probes of the same workspace.
106
151
  const inflight = new Map<string, Promise<McpServerStatus[]>>()
107
152
 
108
- export async function getMcpStatus(workspacePath: string): Promise<McpServerStatus[]> {
109
- const cached = cache.get(workspacePath)
153
+ function cacheKey(scope: McpScope, workspacePath: string): string {
154
+ return `${scope}:${workspacePath}`
155
+ }
156
+
157
+ export async function getMcpStatus(
158
+ workspacePath: string,
159
+ scope: McpScope = 'project'
160
+ ): Promise<McpServerStatus[]> {
161
+ const key = cacheKey(scope, workspacePath)
162
+ const cached = cache.get(key)
110
163
  if (cached && cached.expiresAt > Date.now()) return cached.status
111
164
 
112
- const existing = inflight.get(workspacePath)
165
+ const existing = inflight.get(key)
113
166
  if (existing) return existing
114
167
 
115
- const probe = probeMcpStatus(workspacePath)
168
+ const probe = probeMcpStatus(workspacePath, scope)
116
169
  .then(status => {
117
170
  const ttl = ttlFor(status)
118
- if (ttl > 0) cache.set(workspacePath, { status, expiresAt: Date.now() + ttl })
171
+ if (ttl > 0) cache.set(key, { status, expiresAt: Date.now() + ttl })
119
172
  return status
120
173
  })
121
- .finally(() => inflight.delete(workspacePath))
174
+ .finally(() => inflight.delete(key))
122
175
 
123
- inflight.set(workspacePath, probe)
176
+ inflight.set(key, probe)
124
177
  return probe
125
178
  }
179
+
180
+ export async function getUserMcpStatus(): Promise<McpServerStatus[]> {
181
+ return getMcpStatus(process.cwd(), 'user')
182
+ }
@@ -23,6 +23,32 @@ export const MOI_PACKAGE_JSON = {
23
23
  }
24
24
  } as const
25
25
 
26
+ // Dependency installation is helpful for editor types and widget builds, but
27
+ // it's not critical — the agent installs on demand if it's missing. So it must
28
+ // never block workspace creation: we wait briefly, then let it finish in the
29
+ // background, with a hard kill as a backstop against a hung registry.
30
+ const INSTALL_WAIT_MS = 10_000
31
+ const INSTALL_TIMEOUT_MS = 120_000
32
+
33
+ type InstallDependencies = (moiDir: string) => Promise<number>
34
+
35
+ async function runBunInstall(moiDir: string): Promise<number> {
36
+ const install = Bun.spawn(['bun', 'install'], {
37
+ cwd: moiDir,
38
+ stdout: 'ignore',
39
+ stderr: 'inherit',
40
+ timeout: INSTALL_TIMEOUT_MS,
41
+ killSignal: 'SIGKILL'
42
+ })
43
+ // Don't hold the event loop open for a backgrounded install: a short-lived
44
+ // CLI (`moi init`) must exit after the wait, not linger until the child
45
+ // does. The child survives parent exit and finishes the install on its own
46
+ // (verified: orphaned bun processes complete; only the 2-minute kill is no
47
+ // longer enforced once the parent is gone).
48
+ install.unref()
49
+ return install.exited
50
+ }
51
+
26
52
  // Ambient types for applets (widgets & views). Editor DX only — the moi
27
53
  // bundler resolves the `moi` module and asset imports at build time without any
28
54
  // declarations. Lives at `.moi/` root, NOT inside widgets/views, so it isn't
@@ -55,8 +81,13 @@ declare module '*.svg' { const s: string; export default s }
55
81
  // Bootstraps `.moi/` ONLY when it doesn't exist yet. Re-running `moi init`
56
82
  // on an existing workspace overwrites skills but must leave the user's
57
83
  // `.moi/` (their deps, widgets, lockfile) completely untouched.
58
- // Returns 'exists' when skipped, otherwise the `bun install` exit code.
59
- export async function scaffoldMoiDir(workspacePath: string): Promise<'exists' | number> {
84
+ // Returns 'exists' when skipped, 'installing' when `bun install` outlived the
85
+ // wait and continues in the background, otherwise the install exit code.
86
+ export async function scaffoldMoiDir(
87
+ workspacePath: string,
88
+ installDependencies: InstallDependencies = runBunInstall,
89
+ installWaitMs: number = INSTALL_WAIT_MS
90
+ ): Promise<'exists' | 'installing' | number> {
60
91
  // Backstop against the nested-workspace bug: never scaffold a `.moi/` *inside*
61
92
  // another workspace's `.moi/` (which produces the junk `.moi/.moi`). Callers
62
93
  // (`moi init`) lift to the workspace root via `liftToWorkspaceRoot` first, so
@@ -68,18 +99,32 @@ export async function scaffoldMoiDir(workspacePath: string): Promise<'exists' |
68
99
  )
69
100
  }
70
101
  const moiDir = join(workspacePath, '.moi')
71
- if (await Bun.file(join(moiDir, 'package.json')).exists()) return 'exists'
102
+ const packagePath = join(moiDir, 'package.json')
103
+ if (await Bun.file(packagePath).exists()) return 'exists'
72
104
  // A bare `.moi/` dir without package.json counts as not-bootstrapped —
73
105
  // fill in the missing pieces.
74
106
 
75
107
  await mkdir(join(moiDir, 'widgets'), { recursive: true })
76
- await Bun.write(join(moiDir, 'package.json'), JSON.stringify(MOI_PACKAGE_JSON, null, 2) + '\n')
108
+ await Bun.write(packagePath, JSON.stringify(MOI_PACKAGE_JSON, null, 2) + '\n')
77
109
  await Bun.write(join(moiDir, 'applet-env.d.ts'), APPLET_ENV_DTS)
78
110
 
79
- const install = Bun.spawn(['bun', 'install'], {
80
- cwd: moiDir,
81
- stdout: 'ignore',
82
- stderr: 'inherit'
83
- })
84
- return await install.exited
111
+ const exited = installDependencies(moiDir)
112
+ let timer: ReturnType<typeof setTimeout> | undefined
113
+ const result = await Promise.race([
114
+ exited,
115
+ new Promise<'installing'>(r => (timer = setTimeout(() => r('installing'), installWaitMs)))
116
+ ])
117
+ clearTimeout(timer)
118
+
119
+ if (result === 'installing') {
120
+ console.log(`[scaffold] bun install in ${moiDir} still running — continuing in the background`)
121
+ exited.then(code => {
122
+ if (code === 0) console.log(`[scaffold] background bun install in ${moiDir} finished`)
123
+ else
124
+ console.warn(
125
+ `[scaffold] background bun install in ${moiDir} failed (exit ${code}) — the agent will install deps on demand`
126
+ )
127
+ })
128
+ }
129
+ return result
85
130
  }
@@ -92,6 +92,22 @@ export async function listWorkspaces(): Promise<WorkspaceEntry[]> {
92
92
  return entries.map(withDisplayPath)
93
93
  }
94
94
 
95
+ export async function reorderWorkspaces(ids: string[]): Promise<WorkspaceEntry[]> {
96
+ const entries = await readRegistry()
97
+ if (ids.length !== entries.length) throw new Error('Workspace order must include every workspace')
98
+
99
+ const unique = new Set(ids)
100
+ if (unique.size !== ids.length) throw new Error('Workspace order contains duplicate ids')
101
+
102
+ const byId = new Map(entries.map(e => [e.id, e]))
103
+ const next = ids.map(id => byId.get(id))
104
+ if (next.some(e => !e)) throw new Error('Workspace order contains unknown ids')
105
+
106
+ const ordered = next as WorkspaceEntry[]
107
+ await writeRegistry(ordered)
108
+ return ordered.map(withDisplayPath)
109
+ }
110
+
95
111
  // Resolve a path to the registered workspace that *contains* it: the entry
96
112
  // whose path equals `reqPath` or is its nearest ancestor (longest matching
97
113
  // prefix, git-style). This lets workspace-scoped commands (e.g. `moi bundle`)
package/server/views.ts CHANGED
Binary file
package/server/web.ts CHANGED
@@ -98,6 +98,7 @@ export const app = Bun.serve<WsData>({
98
98
 
99
99
  // Client-side routes — serve the SPA shell.
100
100
  '/': shell,
101
+ '/connectors': shell,
101
102
  '/playground': shell,
102
103
  '/playground/*': shell,
103
104
  '/workspace/*': shell,
package/server/widgets.ts CHANGED
@@ -158,7 +158,8 @@ export function serveWidget(
158
158
  name: string,
159
159
  file: string,
160
160
  workspacePath: string,
161
- apiBase: string
161
+ apiBase: string,
162
+ ifNoneMatch?: string | null
162
163
  ): Promise<Response> {
163
- return serveApplet('widget', name, file, workspacePath, apiBase)
164
+ return serveApplet('widget', name, file, workspacePath, apiBase, ifNoneMatch)
164
165
  }
@@ -8,6 +8,7 @@ import { homedir } from 'node:os'
8
8
  import { join } from 'node:path'
9
9
 
10
10
  import type { WorkspaceType } from '@/lib/types'
11
+ export { validateWorkspaceFolderName } from '@/lib/workspace-name'
11
12
 
12
13
  import { scaffoldMoiDir } from './moi-scaffold'
13
14
  import { installBundledSkills } from './skills-template'
@@ -29,9 +30,10 @@ export const CREATED_WORKSPACES_ROOT = join(homedir(), 'moi')
29
30
  export type ProvisionResult = {
30
31
  // Where the skills were installed (backend-dependent, see skillsDirFor).
31
32
  skillsDir: string
32
- // 'exists' when `.moi/` was already bootstrapped, else the bun install exit
33
- // code (non-zero means deps must be installed manually — not fatal).
34
- scaffold: 'exists' | number
33
+ // 'exists' when `.moi/` was already bootstrapped, 'installing' when bun
34
+ // install continues in the background, else the install exit code (non-zero
35
+ // means deps are missing — not fatal, the agent installs on demand).
36
+ scaffold: 'exists' | 'installing' | number
35
37
  }
36
38
 
37
39
  // Lay down everything a workspace needs: create the folder, copy the bundled
@@ -48,19 +50,3 @@ export async function provisionWorkspace(
48
50
  const scaffold = await scaffoldMoiDir(workspaceRoot)
49
51
  return { skillsDir, scaffold }
50
52
  }
51
-
52
- // Validate a folder name typed in the create-workspace form. Returns a
53
- // user-facing error, or null when the name is usable as a single path segment
54
- // under CREATED_WORKSPACES_ROOT. Leading dots are rejected so a name can never
55
- // be hidden or collide with `.moi` / `.claude`.
56
- export function validateWorkspaceFolderName(name: string): string | null {
57
- if (!name) return 'Folder name is required'
58
- if (name.length > 64) return 'Folder name is too long (max 64 characters)'
59
- if (!/^[A-Za-z0-9][A-Za-z0-9._ -]*$/.test(name)) {
60
- return 'Use letters, numbers, dots, dashes, underscores and spaces, starting with a letter or number'
61
- }
62
- if (name.endsWith('.') || name.endsWith(' ')) {
63
- return 'Folder name cannot end with a dot or space'
64
- }
65
- return null
66
- }
package/tsconfig.json CHANGED
@@ -17,5 +17,5 @@
17
17
  }
18
18
  },
19
19
  "include": ["**/*.ts", "**/*.tsx"],
20
- "exclude": ["node_modules"]
20
+ "exclude": ["node_modules", "server/test/__fixtures__"]
21
21
  }
@@ -9,7 +9,7 @@ A widget is **glanceable in under 2 seconds** — and earns **one signature mome
9
9
  - **Content-only root.** The root is a plain `w-full h-full` rectangle. The host card owns the shell — never put `rounded-*`, an outer `border`, `shadow-*`, or a card-surface background on the root. Use `flex flex-col` + `overflow-hidden`; push footers down with `mt-auto`.
10
10
  - **Three states, always.** Loading → skeleton (never a spinner). Error → one human sentence + a retry. Empty → a short prompt, never blank. (Patterns below.)
11
11
  - **Height is the hard constraint.** `height = rowSpan×160 + (rowSpan−1)×16`, exact. Width flexes with the viewport. Design for height first; clip risk → `overflow-hidden`, long text → `truncate` / `line-clamp`.
12
- - **Tailwind for static styling.** No custom CSS, no `@apply`, no *static* `style={{}}`. Icons only from `@tabler/icons-react` (no raw `<svg>`, no other icon packs). Widgets import only from their own folder.
12
+ - **Tailwind for static styling.** No custom CSS, no `@apply`, no *static* `style={{}}`. Icons only from `@tabler/icons-react` (no raw `<svg>`, no other icon packs). Use the host project icon rule when present (`.agents/rules/icons.md`) instead of duplicating size/stroke guidance. Widgets import only from their own folder.
13
13
  - **No auto-playing audio or video.** Media is always user-initiated.
14
14
  - **No page-level horizontal scroll.** A deliberate, bounded internal scroller (e.g. a Kanban board) is fine; the widget itself never makes the page scroll sideways.
15
15
 
@@ -9,7 +9,7 @@ A view is a **real app screen**, not a giant widget. Where a widget earns one gl
9
9
  - **Own the whole frame.** The root is `w-full h-full` and handles **its own scrolling** (`overflow-auto`) — there is no outer scroll container. Provide your own padding, header, and chrome.
10
10
  - **One view = one screen.** No client-side routing inside a view; cross-screen navigation is the workspace nav. Internal sub-navigation (tabs, a master/detail split) is yours to build.
11
11
  - **Three states, always.** Loading → a skeleton that mirrors the real layout (never a spinner). Error → one human sentence + a retry. Empty → a short prompt, never blank.
12
- - **Tailwind for static styling.** No custom CSS, no `@apply`, no static `style={{}}`. Icons only from `@tabler/icons-react`. Views import only from their own folder.
12
+ - **Tailwind for static styling.** No custom CSS, no `@apply`, no static `style={{}}`. Icons only from `@tabler/icons-react`; use the host project icon rule when present (`.agents/rules/icons.md`) instead of duplicating size/stroke guidance. Views import only from their own folder.
13
13
 
14
14
  ## Layout
15
15