moi-computer 0.11.1-next.2 → 0.11.1-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 (222) hide show
  1. package/README.md +2 -2
  2. package/client/app/AppRouter.tsx +2 -2
  3. package/client/app/routes/WorkspaceRoute.tsx +7 -9
  4. package/client/app/shell/SidebarLayout.tsx +18 -15
  5. package/client/components/shared/BottomPanel.tsx +26 -14
  6. package/client/components/shared/PanelHeader.tsx +1 -1
  7. package/client/components/shared/ReorderableList.tsx +7 -2
  8. package/client/components/shared/WorkspaceIcon.tsx +92 -0
  9. package/client/components/ui/alert-dialog.tsx +1 -0
  10. package/client/components/ui/checkbox.tsx +1 -0
  11. package/client/components/ui/inline-input.tsx +84 -0
  12. package/client/components/ui/toast.tsx +2 -2
  13. package/client/features/applets/AppletMount.tsx +1 -1
  14. package/client/features/applets/applet-cache.ts +3 -3
  15. package/client/features/applets/applet-runtime.ts +147 -108
  16. package/client/features/applets/applet-styles.ts +2 -2
  17. package/client/features/applets/applet-thumbnail.ts +6 -8
  18. package/client/features/applets/useApplet.ts +10 -9
  19. package/client/features/chat/ChatPanel.tsx +19 -10
  20. package/client/features/chat/ChatPopup.tsx +7 -2
  21. package/client/features/chat/applet-chat-intents.ts +170 -0
  22. package/client/features/chat/chat-send.ts +103 -62
  23. package/client/features/chat/chat-store.ts +50 -59
  24. package/client/features/chat/composer/ChatComposer.tsx +43 -132
  25. package/client/features/chat/composer/ModelPicker.tsx +1 -1
  26. package/client/features/chat/composer/attachments/AttachmentChip.tsx +99 -0
  27. package/client/features/chat/composer/attachments/DrawingAttachmentChip.tsx +37 -0
  28. package/client/features/chat/composer/attachments/FileAttachmentChip.tsx +22 -0
  29. package/client/features/chat/composer/attachments/TextAttachmentChip.tsx +11 -0
  30. package/client/features/chat/composer/attachments/draft-attachments.ts +168 -0
  31. package/client/features/chat/composer/attachments/types.ts +25 -0
  32. package/client/features/chat/composer/attachments/uploads.ts +26 -0
  33. package/client/features/chat/{chat-connection.ts → connection/chat-connection.ts} +1 -1
  34. package/client/features/chat/{chat-frames.ts → connection/chat-frames.ts} +2 -2
  35. package/client/features/chat/{ChatEmptyState.tsx → messages/ChatEmptyState.tsx} +16 -11
  36. package/client/features/chat/{MarkdownContent.tsx → messages/MarkdownContent.tsx} +16 -1
  37. package/client/features/chat/{TurnView.tsx → messages/TurnView.tsx} +22 -15
  38. package/client/features/chat/{tool-group → messages/tool-group}/SubagentCard.tsx +1 -1
  39. package/client/features/chat/{tool-group → messages/tool-group}/TimelineRow.tsx +2 -2
  40. package/client/features/chat/{tool-group → messages/tool-group}/ToolCallGroup.tsx +1 -1
  41. package/client/features/chat/{ChatSelector.tsx → sessions/ChatSelector.tsx} +3 -3
  42. package/client/features/chat/{api.ts → sessions/api.ts} +1 -1
  43. package/client/features/chat/useChat.ts +32 -15
  44. package/client/features/dev/ChatStatesPage.tsx +5 -6
  45. package/client/features/dev/HarnessDebugPage.tsx +10 -7
  46. package/client/features/dev/ToolCallsPage.tsx +1 -1
  47. package/client/features/dev/UiComponentPreviews.tsx +21 -0
  48. package/client/features/dev/chat-states-fixtures.ts +13 -2
  49. package/client/features/drawings/useChatAnnotation.ts +17 -17
  50. package/client/features/drawings/useDrawingLayer.ts +7 -9
  51. package/client/features/drawings/useViewBuilderSketch.ts +18 -15
  52. package/client/features/home/HomePage.tsx +8 -7
  53. package/client/features/home/WorkspacePreview.tsx +1 -1
  54. package/client/features/home/workspace-presentation.tsx +1 -11
  55. package/client/features/home/workspace-setup/WorkspaceAgentStep.tsx +2 -4
  56. package/client/features/overview/HiddenPanel.tsx +109 -0
  57. package/client/features/overview/Overview.tsx +302 -0
  58. package/client/features/overview/WidgetCanvas.tsx +164 -0
  59. package/client/features/{widgets → overview}/WidgetFrame.tsx +24 -16
  60. package/client/features/overview/WorkspaceName.tsx +60 -0
  61. package/client/features/overview/api.ts +30 -0
  62. package/client/features/overview/default/ViewsWidget.tsx +252 -0
  63. package/client/features/overview/default/registry.tsx +36 -0
  64. package/client/features/{widgets → overview}/grid.ts +36 -0
  65. package/client/features/overview/useGridReconcile.ts +94 -0
  66. package/client/features/scratchpad/Scratchpad.tsx +7 -8
  67. package/client/features/scratchpad/ScratchpadControls.tsx +0 -1
  68. package/client/features/scratchpad/useScratchpadSnapshot.tsx +23 -13
  69. package/client/features/settings/GeneralSettings.tsx +55 -58
  70. package/client/features/settings/SettingsLayout.tsx +2 -2
  71. package/client/features/settings/WorkspaceIconPicker.tsx +318 -0
  72. package/client/features/settings/WorkspaceSettingsDialog.tsx +65 -0
  73. package/client/features/settings/api.ts +48 -24
  74. package/client/features/views/ViewBuilder.tsx +5 -4
  75. package/client/features/views/ViewManager.tsx +11 -13
  76. package/client/features/views/api.ts +36 -2
  77. package/client/features/views/useViewBuilderActions.ts +8 -5
  78. package/client/features/views/useViewBuilderDrafts.ts +23 -21
  79. package/client/features/views/view-presentation.ts +13 -0
  80. package/client/features/workspace/{CustomizePanel.tsx → ThemePanel.tsx} +26 -31
  81. package/client/features/workspace/UnavailablePage.tsx +21 -0
  82. package/client/features/workspace/WorkspaceLayoutContext.tsx +4 -7
  83. package/client/features/workspace/WorkspaceScreen.tsx +205 -161
  84. package/client/features/workspace/WorkspaceSplitLayout.tsx +1 -1
  85. package/client/features/workspace/WorkspaceTabs.tsx +2 -0
  86. package/client/features/workspace/api.ts +0 -26
  87. package/client/features/workspace/moi-context.ts +8 -9
  88. package/client/features/workspace/tab-resolution.ts +10 -33
  89. package/client/features/workspace/useWorkspaceNavigation.ts +164 -101
  90. package/client/index.css +1 -1
  91. package/client/lib/app-icon-registry.ts +2 -0
  92. package/client/lib/use-latest-ref.ts +11 -0
  93. package/client/main.tsx +1 -1
  94. package/client/runtime/useWorkspaceEvents.ts +59 -14
  95. package/client/theme.css +5 -5
  96. package/dist/chunk-1pp135b4.js +1 -0
  97. package/dist/chunk-2gs8jjx4.css +1 -0
  98. package/dist/chunk-94m3q9ce.js +1 -0
  99. package/dist/chunk-azkjzc7a.js +68 -0
  100. package/dist/{chunk-w482ew2c.js → chunk-brr0zbeh.js} +73 -73
  101. package/dist/chunk-m1fvqssh.js +2 -0
  102. package/dist/chunk-p34hvqt3.js +1 -0
  103. package/dist/{chunk-4s15axjs.js → chunk-p83f0jnj.js} +2 -2
  104. package/dist/{chunk-j3wvxjr7.js → chunk-tzz101ea.js} +1 -1
  105. package/dist/chunk-xg01f6pn.js +10 -0
  106. package/dist/{chunk-53a7pxcz.js → chunk-zs4mte79.js} +1 -1
  107. package/dist/index.html +1 -1
  108. package/lib/app-icons.ts +1 -0
  109. package/lib/applet-selector.ts +24 -0
  110. package/lib/chat-title.ts +6 -1
  111. package/lib/default-widgets.ts +32 -0
  112. package/lib/format.ts +12 -1
  113. package/lib/message-attachments.ts +40 -0
  114. package/lib/moi-attachments.ts +204 -0
  115. package/lib/moi-context.ts +20 -35
  116. package/lib/navigation.ts +84 -0
  117. package/lib/types.ts +79 -24
  118. package/lib/workspace-icon.ts +20 -0
  119. package/lib/workspace-layout.ts +22 -2
  120. package/lib/workspace-tabs.ts +9 -33
  121. package/package.json +27 -27
  122. package/registry.json +13 -0
  123. package/server/AGENTS.md +1 -0
  124. package/server/api.ts +114 -37
  125. package/server/applet-typecheck.ts +95 -0
  126. package/server/{bundler → applets}/build-applet.ts +13 -246
  127. package/server/applets/config.ts +226 -0
  128. package/server/applets/dependencies.ts +206 -0
  129. package/server/{applets.ts → applets/index.ts} +15 -161
  130. package/server/applets/runtime/base.ts +4 -0
  131. package/server/applets/runtime/moi.ts +42 -0
  132. package/server/applets/runtime/rpc.ts +17 -0
  133. package/server/applets/view-source.ts +67 -0
  134. package/server/attachment-message.ts +95 -0
  135. package/server/cli.ts +163 -97
  136. package/server/control.ts +63 -42
  137. package/server/harness/README.md +4 -2
  138. package/server/harness/acp/adapter.ts +7 -21
  139. package/server/harness/acp/session.ts +31 -50
  140. package/server/harness/claude-code/NOTES.md +8 -2
  141. package/server/harness/claude-code/adapter.ts +8 -25
  142. package/server/harness/claude-code/index.ts +2 -0
  143. package/server/harness/claude-code/session.ts +42 -47
  144. package/server/harness/claude-code/sessions.ts +9 -4
  145. package/server/harness/codex/adapter.ts +8 -7
  146. package/server/harness/codex/index.ts +1 -0
  147. package/server/harness/codex/permissions.ts +1 -1
  148. package/server/harness/codex/session.ts +20 -47
  149. package/server/harness/hermes/NOTES.md +1 -1
  150. package/server/harness/hermes/index.ts +4 -0
  151. package/server/harness/openclaw/NOTES.md +1 -1
  152. package/server/harness/openclaw/adapter.ts +22 -4
  153. package/server/harness/openclaw/gateway.ts +5 -3
  154. package/server/harness/openclaw/session.ts +27 -27
  155. package/server/harness/types.ts +5 -3
  156. package/server/layout.ts +9 -14
  157. package/server/moi-scaffold.ts +21 -13
  158. package/server/navigation-relay.ts +110 -0
  159. package/server/registry.ts +8 -0
  160. package/server/selected-session.ts +24 -4
  161. package/server/skill-update.ts +5 -3
  162. package/server/skill-version.ts +4 -7
  163. package/server/skills-template.ts +48 -9
  164. package/server/tabs.ts +19 -33
  165. package/server/uploads.ts +0 -0
  166. package/server/view-builders.ts +18 -1
  167. package/server/views.ts +126 -6
  168. package/server/web.ts +35 -9
  169. package/server/widgets.ts +12 -5
  170. package/server/workspace-config.ts +13 -9
  171. package/ui-components/button.tsx +2 -2
  172. package/ui-components/docs/kbd.md +191 -0
  173. package/ui-components/dropdown-menu.tsx +1 -1
  174. package/ui-components/kbd.tsx +32 -0
  175. package/ui-components/slider.tsx +1 -1
  176. package/ui-components/switch.tsx +1 -1
  177. package/ui-components/tabs.tsx +1 -1
  178. package/workspace/.claude/skills/moi-workspace/SKILL.md +284 -228
  179. package/workspace/.claude/skills/moi-workspace/references/DESIGN.md +100 -153
  180. package/workspace/.claude/skills/moi-workspace/references/INTENTS.md +156 -0
  181. package/client/features/chat/attachment-staging.ts +0 -153
  182. package/client/features/chat/uploads.ts +0 -18
  183. package/client/features/chat/useAppletChatMessage.ts +0 -68
  184. package/client/features/settings/IconPicker.tsx +0 -442
  185. package/client/features/settings/WorkspaceSettings.tsx +0 -95
  186. package/client/features/settings/render-icon.ts +0 -173
  187. package/client/features/widgets/HiddenPanel.tsx +0 -80
  188. package/client/features/widgets/WidgetGrid.tsx +0 -123
  189. package/client/features/widgets/Widgets.tsx +0 -262
  190. package/client/features/widgets/useGridReconcile.ts +0 -73
  191. package/dist/chunk-245wt82v.css +0 -1
  192. package/dist/chunk-87thzbtw.js +0 -2
  193. package/dist/chunk-a6jad1a6.js +0 -1
  194. package/dist/chunk-dghwstd2.js +0 -9
  195. package/dist/chunk-eg120aca.js +0 -1
  196. package/dist/chunk-j7hh2ab4.js +0 -70
  197. package/dist/chunk-y8eyahwx.js +0 -1
  198. /package/client/features/chat/{ChatPromptBubbles.tsx → messages/ChatPromptBubbles.tsx} +0 -0
  199. /package/client/features/chat/{ShimmerText.tsx → messages/ShimmerText.tsx} +0 -0
  200. /package/client/features/chat/{group-turns.ts → messages/group-turns.ts} +0 -0
  201. /package/client/features/chat/{interleave-notices.ts → messages/interleave-notices.ts} +0 -0
  202. /package/client/features/chat/{preview-turn.ts → messages/preview-turn.ts} +0 -0
  203. /package/client/features/chat/{tool-group → messages/tool-group}/CodeBlock.tsx +0 -0
  204. /package/client/features/chat/{tool-group → messages/tool-group}/Collapse.tsx +0 -0
  205. /package/client/features/chat/{tool-group → messages/tool-group}/ReadImagePreview.tsx +0 -0
  206. /package/client/features/chat/{tool-group → messages/tool-group}/ToolOutput.tsx +0 -0
  207. /package/client/features/chat/{tool-group → messages/tool-group}/detect.ts +0 -0
  208. /package/client/features/chat/{tool-group → messages/tool-group}/fixtures.ts +0 -0
  209. /package/client/features/chat/{tool-group → messages/tool-group}/format/claude.ts +0 -0
  210. /package/client/features/chat/{tool-group → messages/tool-group}/format/codex.ts +0 -0
  211. /package/client/features/chat/{tool-group → messages/tool-group}/format/hermes.ts +0 -0
  212. /package/client/features/chat/{tool-group → messages/tool-group}/format/index.ts +0 -0
  213. /package/client/features/chat/{tool-group → messages/tool-group}/format/mcp.ts +0 -0
  214. /package/client/features/chat/{tool-group → messages/tool-group}/format/openclaw.ts +0 -0
  215. /package/client/features/chat/{tool-group → messages/tool-group}/format/shared.ts +0 -0
  216. /package/client/features/chat/{tool-group → messages/tool-group}/format/shell.ts +0 -0
  217. /package/client/features/chat/{tool-group → messages/tool-group}/index.ts +0 -0
  218. /package/client/features/chat/{useStickToBottom.ts → messages/useStickToBottom.ts} +0 -0
  219. /package/client/features/chat/{session-view.ts → sessions/session-view.ts} +0 -0
  220. /package/client/features/chat/{useSelectedSession.ts → sessions/useSelectedSession.ts} +0 -0
  221. /package/server/{bundler → applets}/applet-css.ts +0 -0
  222. /package/server/{bundler → applets}/build-worker.ts +0 -0
@@ -1,14 +1,12 @@
1
- import { parse } from '@babel/parser'
2
- import type { ObjectProperty, StringLiteral } from '@babel/types'
3
1
  import type { BunPlugin } from 'bun'
4
2
  import tailwind from 'bun-plugin-tailwind'
5
3
  import { realpathSync } from 'node:fs'
6
4
  import { basename, dirname, join, relative, sep } from 'path'
7
5
 
8
- import { APP_ICON_IDS, isAppIconId } from '@/lib/app-icons'
9
6
  import type { AppletKind, ViewConfig, WidgetConfig } from '@/lib/types'
10
7
 
11
8
  import { scopeAppletCss } from './applet-css'
9
+ import { extractViewConfig, extractWidgetConfig } from './config'
12
10
 
13
11
  // An **applet** is any custom UI unit embedded in a workspace; `widget` and
14
12
  // `view` are its kinds (more may follow). All compile through this pipeline —
@@ -17,16 +15,6 @@ import { scopeAppletCss } from './applet-css'
17
15
  // canonical in lib/types; re-exported here for this pipeline's consumers.
18
16
  export type { AppletKind }
19
17
 
20
- const APP_ICON_NAMES: readonly string[] = APP_ICON_IDS
21
-
22
- // Baked into the bundle wherever a runtime URL needs the workspace's API base
23
- // (RPC + workspace files). The serve route string-replaces it with the real
24
- // `/api/workspaces/<id>` in every `.js` it returns, so the on-disk bundle stays
25
- // workspace-agnostic. Survives the build because we never minify — it lives as
26
- // a plain string literal. Assets don't use it: they self-locate via
27
- // `import.meta.url` (see the asset loader below).
28
- export const APPLET_API_BASE_SENTINEL = '%%MOI_APPLET_API_BASE%%'
29
-
30
18
  // Extensions an applet may `import` as a bundled asset. Each is emitted as a
31
19
  // content-hashed sibling of `index.js` and the import resolves to its URL via
32
20
  // `import.meta.url`. Deliberately images + fonts only: large media (video/audio)
@@ -42,6 +30,9 @@ const EXTERNAL_MODULES = [
42
30
  'react-dom/client'
43
31
  ]
44
32
 
33
+ const RPC_MODULE_PATH = join(import.meta.dir, 'runtime', 'rpc.ts')
34
+ const MOI_MODULE_PATH = join(import.meta.dir, 'runtime', 'moi.ts')
35
+
45
36
  type ServerModule = {
46
37
  name: string
47
38
  exports: string[]
@@ -67,121 +58,6 @@ export type AppletArtifact = {
67
58
  config: WidgetConfig | ViewConfig | null
68
59
  }
69
60
 
70
- const DEFAULT_CONFIG: WidgetConfig = { rowSpan: 1, colSpan: 2 }
71
- const VALID_SPANS = [1, 2, 3, 4] as const
72
-
73
- // The properties of an exported `const config = { … }` object literal, or null
74
- // when the file declares no such export. Shared by the widget and view config
75
- // extractors — they each interpret the properties under their own schema.
76
- // Parsed with @babel/parser: it handles TS + JSX with no peer dependencies, so
77
- // it always resolves from moi's own tree. A parser that peer-depends on
78
- // `typescript` breaks under bun's shared global tree, where another globally
79
- // installed package controls which `typescript` sits at the hoisted root.
80
- function findConfigProperties(source: string) {
81
- const ast = parse(source, { sourceType: 'module', plugins: ['typescript', 'jsx'] })
82
-
83
- for (const node of ast.program.body) {
84
- if (node.type !== 'ExportNamedDeclaration') continue
85
- if (node.declaration?.type !== 'VariableDeclaration') continue
86
- const decl = node.declaration.declarations.find(
87
- d => d.id.type === 'Identifier' && d.id.name === 'config'
88
- )
89
- if (!decl) continue
90
-
91
- const rawInit = decl.init
92
- // Unwrap `as const` — AST wraps the object in TSAsExpression
93
- const init = rawInit?.type === 'TSAsExpression' ? rawInit.expression : rawInit
94
- if (init?.type !== 'ObjectExpression') return null
95
- return init.properties
96
- }
97
-
98
- return null
99
- }
100
-
101
- // `requiredEnv`: an array of string literals naming env vars the bundle needs.
102
- // Advisory only — surfaced in the env UI, never enforced at build/load.
103
- function readRequiredEnv(propValue: ObjectProperty['value']): string[] | undefined {
104
- if (propValue.type !== 'ArrayExpression') return undefined
105
- const names = propValue.elements
106
- .filter((el): el is StringLiteral => el?.type === 'StringLiteral')
107
- .map(el => el.value)
108
- return names.length ? names : undefined
109
- }
110
-
111
- export async function extractWidgetConfig(srcPath: string): Promise<WidgetConfig | null> {
112
- const source = await Bun.file(srcPath).text()
113
- const widgetName = basename(srcPath).replace(/\.tsx?$/, '')
114
-
115
- const properties = findConfigProperties(source)
116
- if (!properties) return null
117
-
118
- const result: Partial<WidgetConfig> = {}
119
-
120
- for (const prop of properties) {
121
- if (prop.type !== 'ObjectProperty' || prop.key.type !== 'Identifier') continue
122
- const key = prop.key.name
123
-
124
- if (key === 'requiredEnv') {
125
- const names = readRequiredEnv(prop.value)
126
- if (names) result.requiredEnv = names
127
- continue
128
- }
129
-
130
- if (key !== 'rowSpan' && key !== 'colSpan') continue
131
- if (prop.value.type !== 'NumericLiteral') continue
132
-
133
- const val = prop.value.value
134
- if (!(VALID_SPANS as readonly number[]).includes(val)) {
135
- console.warn(`[mei] "${widgetName}": config.${key}=${val} is out of 1–4 range, using default`)
136
- continue
137
- }
138
- result[key] = val as 1 | 2 | 3 | 4
139
- }
140
-
141
- return { ...DEFAULT_CONFIG, ...result }
142
- }
143
-
144
- // A view's config: `title` + app icon registry id + advisory `requiredEnv`.
145
- // No sizing — views are full-screen. Returns null when no `config` export is present.
146
- export async function extractViewConfig(srcPath: string): Promise<ViewConfig | null> {
147
- const source = await Bun.file(srcPath).text()
148
-
149
- const properties = findConfigProperties(source)
150
- if (!properties) return null
151
-
152
- const result: ViewConfig = {}
153
-
154
- for (const prop of properties) {
155
- if (prop.type !== 'ObjectProperty' || prop.key.type !== 'Identifier') continue
156
- const key = prop.key.name
157
-
158
- if (key === 'title') {
159
- if (prop.value.type === 'StringLiteral') {
160
- result.title = prop.value.value
161
- }
162
- continue
163
- }
164
- if (key === 'icon') {
165
- if (prop.value.type === 'StringLiteral') {
166
- const icon = prop.value.value
167
- if (!isAppIconId(icon)) {
168
- throw new Error(
169
- `Unknown view icon id "${icon}". Use one of: ${APP_ICON_NAMES.join(', ')}`
170
- )
171
- }
172
- result.icon = icon
173
- }
174
- continue
175
- }
176
- if (key === 'requiredEnv') {
177
- const names = readRequiredEnv(prop.value)
178
- if (names) result.requiredEnv = names
179
- }
180
- }
181
-
182
- return result
183
- }
184
-
185
61
  function escapeRegex(s: string): string {
186
62
  return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
187
63
  }
@@ -215,73 +91,6 @@ async function validateServerExports(filePath: string): Promise<string[]> {
215
91
  return runtimeExports
216
92
  }
217
93
 
218
- // The mei:rpc virtual module — contains the RPC call logic with devalue
219
- // serialization. Bundled into the applet output once, shared by all server
220
- // function stubs. The base is the sentinel the serve route rewrites to
221
- // `/api/workspaces/<id>`, so a bundle carries no workspace id of its own.
222
- const RPC_MODULE_SOURCE = `
223
- import { stringify, parse } from "devalue";
224
-
225
- const BASE = ${JSON.stringify(APPLET_API_BASE_SENTINEL)};
226
-
227
- export function rpc(module, name) {
228
- return async (...args) => {
229
- const res = await fetch(BASE + "/rpc/" + module + "/" + name, {
230
- method: "POST",
231
- headers: { "Content-Type": "application/json" },
232
- body: stringify(args),
233
- });
234
- if (!res.ok) throw new Error(await res.text());
235
- return parse(await res.text());
236
- };
237
- }
238
- `
239
-
240
- // The `moi` virtual module — the applet-facing runtime API.
241
- //
242
- // `fileUrl(path)` maps a workspace-relative path to its streaming URL
243
- // (`/api/workspaces/<id>/fs/<path>`). Same sentinel base as RPC; the path is
244
- // per-segment URL-encoded so spaces / unicode in filenames survive. A leading
245
- // slash is stripped so both `clips/a.mp4` and `/clips/a.mp4` work.
246
- //
247
- // `focusTab(tab, params?)` and `sendChatMessage(message, context?)` forward to
248
- // this bundle's host-attached bridge — client-local replace-navigation to a
249
- // workspace tab (params delivered to the target view via navigation state),
250
- // and a chat message sent to the workspace's active chat as if the user had
251
- // typed it. This virtual module is INLINED PER BUNDLE,
252
- // so `bridge` is private to one applet: the host attaches it right after the
253
- // dynamic import and neuters it on invalidation (see
254
- // client/features/applets/applet-runtime.ts). Optional-chained so calls no-op
255
- // before attach and outside the moi host. The `__` exports are host wiring,
256
- // surfaced from the bundle entry below — they are deliberately NOT part of the
257
- // author-facing `declare module 'moi'` ambient types (server/moi-scaffold.ts).
258
- const MOI_MODULE_SOURCE = `
259
- const BASE = ${JSON.stringify(APPLET_API_BASE_SENTINEL)};
260
-
261
- let bridge = null;
262
-
263
- export function __attachBridge(next) {
264
- bridge = next;
265
- }
266
-
267
- export function __getBridge() {
268
- return bridge;
269
- }
270
-
271
- export function fileUrl(path) {
272
- const clean = String(path).replace(/^\\/+/, "");
273
- return BASE + "/fs/" + clean.split("/").map(encodeURIComponent).join("/");
274
- }
275
-
276
- export function focusTab(tab, params) {
277
- bridge?.focusTab(tab, params);
278
- }
279
-
280
- export function sendChatMessage(message, context) {
281
- bridge?.sendChatMessage(message, context);
282
- }
283
- `
284
-
285
94
  // Server modules are keyed by their path relative to the moi root
286
95
  // (`.moi/widgets/hello.server.ts` → `"widgets/hello"`), posix-normalized so
287
96
  // keys are stable across platforms. Throws when the file escapes the root.
@@ -308,8 +117,8 @@ function serverModuleKey(serverPath: string, moiRoot: string): string {
308
117
  }
309
118
 
310
119
  // The applet runtime plugin wires the three I/O transports into the bundle:
311
- // • `.server` imports → RPC stubs (via the `mei:rpc` virtual module)
312
- // • `moi` import → the `fileUrl` runtime
120
+ // • `.server` imports → RPC stubs (via the `mei:rpc` runtime module)
121
+ // • `moi` import → the applet-facing runtime module
313
122
  // • asset imports → content-hashed sibling files, referenced by URL
314
123
  // It returns the collected server modules (for hot-reload + env aggregation)
315
124
  // and the asset files the caller must emit next to `index.js`.
@@ -327,35 +136,17 @@ function appletRuntimePlugin(
327
136
  const plugin: BunPlugin = {
328
137
  name: 'applet-runtime',
329
138
  setup(build) {
330
- // Resolve mei:rpc virtual module
331
- build.onResolve({ filter: /^mei:rpc$/ }, () => ({
332
- path: 'mei:rpc',
333
- namespace: 'mei-rpc'
334
- }))
335
-
336
- build.onLoad({ filter: /.*/, namespace: 'mei-rpc' }, () => ({
337
- contents: RPC_MODULE_SOURCE,
338
- loader: 'js'
339
- }))
139
+ build.onResolve({ filter: /^mei:rpc$/ }, () => ({ path: RPC_MODULE_PATH }))
340
140
 
341
141
  // `devalue` is moi's OWN dependency, injected into every applet bundle via
342
- // the mei:rpc virtual module above. A virtual module has no on-disk
343
- // location, so Bun resolves the bare `devalue` specifier against the
344
- // process cwd's node_modules — which breaks when the server runs from a
345
- // neutral cwd (a prebuilt/global install; see serverCwd in cli.ts). A
346
- // resolveDir on the onLoad is ignored for bare specifiers in Bun 1.3, so
347
- // pin it to an absolute path inside moi's OWN package (this file's dir
348
- // walks up to moi's node_modules), making the applet build cwd-independent.
142
+ // the mei:rpc runtime above. Pin it to moi's package so applet builds stay
143
+ // independent of the server cwd and workspace dependencies.
349
144
  build.onResolve({ filter: /^devalue$/ }, () => ({
350
145
  path: Bun.resolveSync('devalue', import.meta.dir)
351
146
  }))
352
147
 
353
- // The `moi` runtime module (fileUrl). A bare specifier, so match it exactly.
354
- build.onResolve({ filter: /^moi$/ }, () => ({ path: 'moi', namespace: 'moi-runtime' }))
355
- build.onLoad({ filter: /.*/, namespace: 'moi-runtime' }, () => ({
356
- contents: MOI_MODULE_SOURCE,
357
- loader: 'js'
358
- }))
148
+ // The applet-facing runtime. A bare specifier, so match it exactly.
149
+ build.onResolve({ filter: /^moi$/ }, () => ({ path: MOI_MODULE_PATH }))
359
150
 
360
151
  // Asset imports (images/fonts): emit a content-hashed sibling and resolve
361
152
  // the import to its module-relative URL. Self-locating via import.meta.url,
@@ -510,8 +301,8 @@ function widgetEntryPlugin(widgetPath: string, syntheticCssPath: string): BunPlu
510
301
  // Surface the bridge wiring on every bundle's `index.js` so the host
511
302
  // can attach after dynamic import. Bun dedupes the `moi` virtual
512
303
  // module within a bundle, so this re-export and the applet's own
513
- // `import { focusTab } from 'moi'` share one module instance — the
514
- // attached bridge is the one focusTab reads.
304
+ // `import { navigate } from 'moi'` share one module instance — the
305
+ // attached bridge is the one navigate reads.
515
306
  `export { __attachBridge, __getBridge } from "moi";`
516
307
  ].join('\n'),
517
308
  loader: 'js'
@@ -563,30 +354,6 @@ export function scanServerImports(source: string): string[] {
563
354
  return specifiers
564
355
  }
565
356
 
566
- // Every relative import specifier in an applet source — modules (`./_utils`,
567
- // `../lib/data`), assets (`./logo.png`), `.server` stubs, JSON, CSS alike, in
568
- // static, re-export, side-effect, and dynamic form. Lexed by Bun's own
569
- // transpiler, so comments and string literals can't false-positive. Type-only
570
- // imports are erased by the lexer — correct here, since they never affect the
571
- // emitted bundle. Bare specifiers (node_modules) are filtered out: the
572
- // staleness check doesn't walk them. A file that fails to lex contributes no
573
- // imports — the build itself surfaces the syntax error. Used by the rebuild
574
- // staleness check to walk the applet's local import graph, so editing anything
575
- // it (transitively) pulls in marks every applet using it stale.
576
- const IMPORT_SCANNERS = {
577
- ts: new Bun.Transpiler({ loader: 'ts' }),
578
- tsx: new Bun.Transpiler({ loader: 'tsx' })
579
- }
580
- export function scanRelativeImports(source: string, loader: 'ts' | 'tsx' = 'tsx'): string[] {
581
- let imports: { path: string }[]
582
- try {
583
- imports = IMPORT_SCANNERS[loader].scanImports(source)
584
- } catch {
585
- return []
586
- }
587
- return imports.map(i => i.path).filter(p => /^\.\.?\//.test(p))
588
- }
589
-
590
357
  async function prevalidateServerFiles(entrypoint: string): Promise<void> {
591
358
  const sourceDir = dirname(entrypoint)
592
359
  const source = await Bun.file(entrypoint).text()
@@ -0,0 +1,226 @@
1
+ import { parse } from '@babel/parser'
2
+ import type { ObjectExpression, ObjectProperty, StringLiteral } from '@babel/types'
3
+ import { basename } from 'node:path'
4
+
5
+ import { APP_ICON_IDS, isAppIconId } from '@/lib/app-icons'
6
+ import type { ViewConfig, WidgetConfig } from '@/lib/types'
7
+
8
+ const APP_ICON_NAMES: readonly string[] = APP_ICON_IDS
9
+
10
+ const DEFAULT_CONFIG: WidgetConfig = { rowSpan: 1, colSpan: 2 }
11
+ const VALID_SPANS = [1, 2, 3, 4] as const
12
+
13
+ type SourceRange = { start: number; end: number }
14
+ type SourceEdit = SourceRange & { text: string }
15
+ type ParsedConfig = {
16
+ // undefined: no export; null: an export whose value isn't an object literal.
17
+ object: ObjectExpression | null | undefined
18
+ commas: number[]
19
+ }
20
+
21
+ // Static config analysis, shared by compilation and source editing. Never
22
+ // evaluate workspace code to resolve variables, spreads, or function calls.
23
+ // Parsed with @babel/parser: it handles TS + JSX with no peer dependencies, so
24
+ // it always resolves from moi's own tree. A parser that peer-depends on
25
+ // `typescript` breaks under bun's shared global tree, where another globally
26
+ // installed package controls which `typescript` sits at the hoisted root.
27
+ function parseConfig(source: string, editing = false): ParsedConfig {
28
+ const ast = parse(source, {
29
+ sourceType: 'module',
30
+ plugins: ['typescript', 'jsx'],
31
+ tokens: editing
32
+ })
33
+ // Token positions distinguish separator commas from commas inside comments.
34
+ const tokens: SourceRange[] = ast.tokens ?? []
35
+ const commas = tokens
36
+ .filter(token => token.end === token.start + 1 && source[token.start] === ',')
37
+ .map(token => token.start)
38
+
39
+ for (const node of ast.program.body) {
40
+ if (node.type !== 'ExportNamedDeclaration') continue
41
+ if (node.declaration?.type !== 'VariableDeclaration') continue
42
+ const decl = node.declaration.declarations.find(
43
+ d => d.id.type === 'Identifier' && d.id.name === 'config'
44
+ )
45
+ if (!decl) continue
46
+
47
+ let init = decl.init
48
+ while (init?.type === 'TSAsExpression' || init?.type === 'TSSatisfiesExpression') {
49
+ init = init.expression
50
+ }
51
+ return { object: init?.type === 'ObjectExpression' ? init : null, commas }
52
+ }
53
+
54
+ return { object: undefined, commas }
55
+ }
56
+
57
+ function findConfigProperties(source: string) {
58
+ return parseConfig(source).object?.properties ?? null
59
+ }
60
+
61
+ function propertyName(property: ObjectExpression['properties'][number]): string | null {
62
+ if (property.type === 'SpreadElement') return null
63
+ if (property.key.type === 'StringLiteral') return property.key.value
64
+ if (!property.computed && property.key.type === 'Identifier') return property.key.name
65
+ return null
66
+ }
67
+
68
+ // `requiredEnv`: an array of string literals naming env vars the bundle needs.
69
+ // Advisory only — surfaced in the env UI, never enforced at build/load.
70
+ function readRequiredEnv(propValue: ObjectProperty['value']): string[] | undefined {
71
+ if (propValue.type !== 'ArrayExpression') return undefined
72
+ const names = propValue.elements
73
+ .filter((el): el is StringLiteral => el?.type === 'StringLiteral')
74
+ .map(el => el.value)
75
+ return names.length ? names : undefined
76
+ }
77
+
78
+ export async function extractWidgetConfig(srcPath: string): Promise<WidgetConfig | null> {
79
+ const source = await Bun.file(srcPath).text()
80
+ const widgetName = basename(srcPath).replace(/\.tsx?$/, '')
81
+
82
+ const properties = findConfigProperties(source)
83
+ if (!properties) return null
84
+
85
+ const result: Partial<WidgetConfig> = {}
86
+
87
+ for (const prop of properties) {
88
+ if (prop.type !== 'ObjectProperty') continue
89
+ const key = propertyName(prop)
90
+
91
+ if (key === 'requiredEnv') {
92
+ const names = readRequiredEnv(prop.value)
93
+ if (names) result.requiredEnv = names
94
+ continue
95
+ }
96
+
97
+ if (key !== 'rowSpan' && key !== 'colSpan') continue
98
+ if (prop.value.type !== 'NumericLiteral') continue
99
+
100
+ const val = prop.value.value
101
+ if (!(VALID_SPANS as readonly number[]).includes(val)) {
102
+ console.warn(`[mei] "${widgetName}": config.${key}=${val} is out of 1–4 range, using default`)
103
+ continue
104
+ }
105
+ result[key] = val as 1 | 2 | 3 | 4
106
+ }
107
+
108
+ return { ...DEFAULT_CONFIG, ...result }
109
+ }
110
+
111
+ // A view's config: `title` + app icon registry id + advisory `requiredEnv`.
112
+ // No sizing — views are full-screen. Returns null when no `config` export is present.
113
+ export async function extractViewConfig(srcPath: string): Promise<ViewConfig | null> {
114
+ const source = await Bun.file(srcPath).text()
115
+
116
+ const properties = findConfigProperties(source)
117
+ if (!properties) return null
118
+
119
+ const result: ViewConfig = {}
120
+
121
+ for (const prop of properties) {
122
+ if (prop.type !== 'ObjectProperty') continue
123
+ const key = propertyName(prop)
124
+
125
+ if (key === 'title') {
126
+ if (prop.value.type === 'StringLiteral') {
127
+ result.title = prop.value.value
128
+ }
129
+ continue
130
+ }
131
+ if (key === 'icon') {
132
+ if (prop.value.type === 'StringLiteral') {
133
+ const icon = prop.value.value
134
+ if (!isAppIconId(icon)) {
135
+ throw new Error(
136
+ `Unknown view icon id "${icon}". Use one of: ${APP_ICON_NAMES.join(', ')}`
137
+ )
138
+ }
139
+ result.icon = icon
140
+ }
141
+ continue
142
+ }
143
+ if (key === 'requiredEnv') {
144
+ const names = readRequiredEnv(prop.value)
145
+ if (names) result.requiredEnv = names
146
+ }
147
+ }
148
+
149
+ return result
150
+ }
151
+
152
+ function nodeRange(node: { start?: number | null; end?: number | null }): SourceRange {
153
+ const { start, end } = node
154
+ if (start === null || start === undefined || end === null || end === undefined) {
155
+ throw new Error('Could not locate the view config in its source')
156
+ }
157
+ return { start, end }
158
+ }
159
+
160
+ export function setViewSourceTitle(source: string, title: string): string {
161
+ const { object, commas } = parseConfig(source, true)
162
+ if (object === null) {
163
+ throw new Error('View config must be an exported object literal to rename this view')
164
+ }
165
+ const value = JSON.stringify(title)
166
+ if (object === undefined) {
167
+ return `export const config = { title: ${value} }\n\n${source}`
168
+ }
169
+
170
+ // Find the last property that could determine the runtime title. A spread
171
+ // or an unknown computed key can override an earlier explicit title.
172
+ const lastOverride = [...object.properties]
173
+ .reverse()
174
+ .find(
175
+ property =>
176
+ property.type === 'SpreadElement' ||
177
+ propertyName(property) === 'title' ||
178
+ (property.computed && propertyName(property) === null)
179
+ )
180
+ if (lastOverride && propertyName(lastOverride) === 'title') {
181
+ const replaceValue = lastOverride.type === 'ObjectProperty' && !lastOverride.shorthand
182
+ const { start, end } = nodeRange(replaceValue ? lastOverride.value : lastOverride)
183
+ return source.slice(0, start) + (replaceValue ? value : `title: ${value}`) + source.slice(end)
184
+ }
185
+
186
+ const edits: SourceEdit[] = []
187
+ // Remove earlier title properties before appending the final one, avoiding
188
+ // duplicate keys. Keep surrounding comments and other properties intact.
189
+ for (let i = 0; i < object.properties.length; i++) {
190
+ const property = object.properties[i]
191
+ if (propertyName(property) !== 'title') continue
192
+ const range = nodeRange(property)
193
+ const next = nodeRange(object.properties[i + 1])
194
+ const comma = commas.find(position => position >= range.end && position < next.start)
195
+ if (comma === undefined) throw new Error('Could not locate the title separator')
196
+ edits.push({ ...range, text: '' }, { start: comma, end: comma + 1, text: '' })
197
+ }
198
+
199
+ const { start, end } = nodeRange(object)
200
+ const close = end - 1
201
+ const lineStart = source.lastIndexOf('\n', close - 1) + 1
202
+ const closingIndent = source.slice(lineStart, close)
203
+ const multiline = lineStart > start && /^[\t ]*$/.test(closingIndent)
204
+ const first = object.properties[0]
205
+ const firstStart = first ? nodeRange(first).start : start
206
+ const firstIndent = source.slice(source.lastIndexOf('\n', firstStart - 1) + 1, firstStart)
207
+ const indent = /^[\t ]*$/.test(firstIndent) ? firstIndent : closingIndent + ' '
208
+ const position = multiline ? lineStart : close
209
+ const newline = source.includes('\r\n') ? '\r\n' : '\n'
210
+ edits.push({
211
+ start: position,
212
+ end: position,
213
+ text: multiline ? `${indent}title: ${value},${newline}` : ` title: ${value} `
214
+ })
215
+
216
+ const last = object.properties.at(-1)
217
+ if (last && typeof object.extra?.trailingComma !== 'number') {
218
+ const { end: lastEnd } = nodeRange(last)
219
+ edits.push({ start: lastEnd, end: lastEnd, text: ',' })
220
+ }
221
+ // Apply from the end so the parser's offsets remain valid for every edit.
222
+ for (const edit of edits.sort((a, b) => b.start - a.start)) {
223
+ source = source.slice(0, edit.start) + edit.text + source.slice(edit.end)
224
+ }
225
+ return source
226
+ }