moi-computer 0.3.1-next.1 → 0.4.1-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/README.md +85 -12
  2. package/bin/moi.mjs +11 -0
  3. package/client/api/workspace-keys.ts +1 -0
  4. package/client/app/AppRouter.tsx +5 -1
  5. package/client/app/routes/WorkspaceRoute.tsx +9 -5
  6. package/client/app/shell/SidebarLayout.tsx +9 -7
  7. package/client/components/shared/BottomPanel.tsx +24 -5
  8. package/client/components/shared/Composer.tsx +1 -1
  9. package/client/components/shared/PanelHeader.tsx +1 -1
  10. package/client/components/ui/button.tsx +5 -5
  11. package/client/components/ui/dropdown-menu.tsx +6 -6
  12. package/client/components/ui/hover-card.tsx +1 -1
  13. package/client/components/ui/input.tsx +1 -1
  14. package/client/components/ui/popover.tsx +1 -1
  15. package/client/components/ui/skeleton.tsx +1 -1
  16. package/client/components/ui/textarea.tsx +1 -1
  17. package/client/components/ui/tooltip.tsx +1 -1
  18. package/client/features/applets/applet-cache.ts +20 -1
  19. package/client/features/applets/applet-log.ts +10 -30
  20. package/client/features/applets/applet-runtime.ts +272 -0
  21. package/client/features/applets/useApplet.ts +36 -10
  22. package/client/features/chat/ChatComposer.tsx +1 -1
  23. package/client/features/chat/ChatEmptyState.tsx +186 -0
  24. package/client/features/chat/ChatPanel.tsx +95 -54
  25. package/client/features/chat/ChatPopup.tsx +3 -13
  26. package/client/features/chat/ChatPromptBubbles.tsx +74 -0
  27. package/client/features/chat/MarkdownContent.tsx +15 -3
  28. package/client/features/chat/ModelPicker.tsx +1 -1
  29. package/client/features/chat/TurnView.tsx +6 -17
  30. package/client/features/chat/chat-send.ts +26 -1
  31. package/client/features/chat/tool-group/CodeBlock.tsx +1 -1
  32. package/client/features/chat/tool-group/ReadImagePreview.tsx +1 -1
  33. package/client/features/chat/tool-group/SubagentCard.tsx +1 -1
  34. package/client/features/chat/tool-group/TimelineRow.tsx +4 -4
  35. package/client/features/chat/tool-group/ToolCallGroup.tsx +12 -5
  36. package/client/features/chat/tool-group/ToolOutput.tsx +2 -2
  37. package/client/features/chat/tool-group/format.ts +25 -4
  38. package/client/features/chat/useAppletChatMessage.ts +69 -0
  39. package/client/features/chat/useChat.ts +49 -14
  40. package/client/features/chat/useStickToBottom.ts +11 -1
  41. package/client/features/connectors/McpServerCards.tsx +3 -3
  42. package/client/features/dev/HarnessDebugPage.tsx +213 -77
  43. package/client/features/dev/PixelPainter.tsx +1 -1
  44. package/client/features/dev/PlaygroundPage.tsx +1 -1
  45. package/client/features/dev/ToolCallsPage.tsx +2 -2
  46. package/client/features/home/HomePage.tsx +17 -14
  47. package/client/features/home/WorkspacePreview.tsx +12 -13
  48. package/client/features/home/api.ts +8 -5
  49. package/client/features/home/workspace-presentation.tsx +1 -1
  50. package/client/features/home/workspace-setup/CreateWorkspaceDialog.tsx +1 -1
  51. package/client/features/home/workspace-setup/WorkspaceAgentStep.tsx +21 -8
  52. package/client/features/scratchpad/Scratchpad.tsx +41 -2
  53. package/client/features/scratchpad/ScratchpadControls.tsx +13 -13
  54. package/client/features/scratchpad/useScratchpadSnapshot.tsx +1 -1
  55. package/client/features/settings/EnvironmentSettings.tsx +1 -1
  56. package/client/features/settings/IconPicker.tsx +11 -11
  57. package/client/features/settings/SettingsLayout.tsx +1 -1
  58. package/client/features/settings/WorkspaceSettings.tsx +2 -2
  59. package/client/features/settings/api.ts +33 -1
  60. package/client/features/widgets/HiddenPanel.tsx +4 -3
  61. package/client/features/widgets/Widgets.tsx +1 -0
  62. package/client/features/workspace/CustomizePanel.tsx +96 -82
  63. package/client/features/workspace/WorkspaceScreen.tsx +129 -107
  64. package/client/features/workspace/WorkspaceSkillUpdateBanner.tsx +91 -0
  65. package/client/features/workspace/WorkspaceTabs.tsx +1 -1
  66. package/client/features/workspace/api.ts +52 -0
  67. package/client/features/workspace/moi-context.ts +63 -17
  68. package/client/features/workspace/tab-resolution.ts +75 -0
  69. package/client/features/workspace/useWorkspaceNavigation.ts +128 -0
  70. package/client/features/workspace/useWorkspaceSkillUpdates.ts +160 -0
  71. package/client/index.css +10 -15
  72. package/client/lib/app-icon-registry.ts +77 -70
  73. package/client/lib/rate-limit.ts +77 -0
  74. package/client/main.tsx +10 -2
  75. package/client/runtime/useWorkspaceEvents.ts +15 -2
  76. package/client/runtime/workspace-theme.ts +115 -0
  77. package/client/store/ui.ts +42 -17
  78. package/client/theme.css +20 -15
  79. package/dist/{chunk-1dfbr7n2.js → chunk-3m1xe1j3.js} +94 -94
  80. package/dist/chunk-5vaevt8z.js +2 -0
  81. package/dist/chunk-7bzpmtxp.js +50 -0
  82. package/dist/chunk-h0hk61pm.js +9 -0
  83. package/dist/{chunk-vkvb3hjm.js → chunk-h3evrtyp.js} +1 -1
  84. package/dist/chunk-k5sjx9s5.js +1 -0
  85. package/dist/{chunk-jen6xcm1.js → chunk-m9qja0nx.js} +1 -1
  86. package/dist/chunk-s7za1qsv.css +1 -0
  87. package/dist/{chunk-sxbfh73c.js → chunk-tcfa3vt3.js} +1 -1
  88. package/dist/chunk-v797g6ap.js +51 -0
  89. package/dist/chunk-xyrw8318.js +27 -0
  90. package/dist/index.html +1 -1
  91. package/lib/app-icons.ts +73 -0
  92. package/lib/moi-context.ts +104 -3
  93. package/lib/themes.ts +83 -45
  94. package/lib/types.ts +44 -9
  95. package/lib/workspace-tabs.ts +48 -0
  96. package/package.json +4 -1
  97. package/server/api.ts +57 -5
  98. package/server/app-settings.ts +65 -0
  99. package/server/applets.ts +132 -22
  100. package/server/bundler/build-applet.ts +74 -16
  101. package/server/cli.ts +144 -17
  102. package/server/control.ts +53 -7
  103. package/server/data-dir.ts +1 -1
  104. package/server/events.ts +1 -1
  105. package/server/functions-worker.ts +15 -1
  106. package/server/functions.ts +51 -6
  107. package/server/harness/claude-code/index.ts +2 -1
  108. package/server/harness/codex/adapter.ts +100 -9
  109. package/server/harness/codex/client.ts +34 -1
  110. package/server/harness/codex/index.ts +2 -1
  111. package/server/harness/codex/session.ts +32 -8
  112. package/server/layout.ts +9 -14
  113. package/server/moi-scaffold.ts +37 -3
  114. package/server/registry.ts +1 -1
  115. package/server/skill-update.ts +47 -0
  116. package/server/skill-version.ts +2 -11
  117. package/server/tabs.ts +59 -0
  118. package/server/theme.ts +8 -14
  119. package/server/view-builders.ts +6 -2
  120. package/workspace/.claude/skills/moi-workspace/DESIGN.md +265 -107
  121. package/workspace/.claude/skills/moi-workspace/SKILL.md +85 -11
  122. package/client/features/workspace/useWorkspaceTheme.ts +0 -82
  123. package/dist/chunk-339jds4x.js +0 -15
  124. package/dist/chunk-3xsvsnhr.css +0 -1
  125. package/dist/chunk-6c8cwpzc.js +0 -1
  126. package/dist/chunk-anqmsbjt.js +0 -2
  127. package/dist/chunk-hbvfb6sk.js +0 -63
  128. package/dist/chunk-qwm5f6qk.js +0 -48
  129. package/dist/chunk-yp4srgqt.js +0 -10
  130. package/workspace/.claude/skills/moi-workspace/VIEW-DESIGN.md +0 -22
package/server/api.ts CHANGED
@@ -5,6 +5,8 @@ import { existsSync } from 'node:fs'
5
5
  import { basename, join, resolve } from 'node:path'
6
6
 
7
7
  import type {
8
+ AppletKind,
9
+ AppSettings,
8
10
  HarnessAvailability,
9
11
  UploadInfo,
10
12
  ViewBuilderInput,
@@ -15,6 +17,7 @@ import type {
15
17
  import type { MoiContext } from '@/lib/moi-context'
16
18
  import { viewBuilderDirectives } from '@/lib/view-builder-directives'
17
19
 
20
+ import { getAppSettings, pickAppSettingsPatch, saveAppSettings } from './app-settings'
18
21
  import { appletForModule, recordAppletError } from './applet-log'
19
22
  import { apiBaseFor, parseAppletTail, serveWorkspaceFile } from './applets'
20
23
  import { applyEnvChanged } from './env-apply'
@@ -43,6 +46,7 @@ import {
43
46
  import { loadScratchpadDoc, saveScratchpadDoc } from './scratchpad'
44
47
  import { MAX_ASSET_BYTES, scratchpadAssetFile, storeScratchpadAsset } from './scratchpad-assets'
45
48
  import { DIST_DIR, prebuilt } from './static'
49
+ import { getWorkspaceSkillsStatus, updateWorkspaceSkills } from './skill-update'
46
50
  import { getThreadConfig, saveThreadConfig } from './thread-config'
47
51
  import type { ThreadConfigPatch } from './thread-config'
48
52
  import { serveWorkspaceImagePreview } from './preview'
@@ -339,14 +343,23 @@ one.post('/applet-log', async c => {
339
343
  message?: unknown
340
344
  stack?: unknown
341
345
  }
342
- if (e.source !== 'load' && e.source !== 'render' && e.source !== 'window') continue
343
- if (e.kind !== 'widget' && e.kind !== 'view') continue
344
- if (typeof e.name !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(e.name)) continue
346
+ if (
347
+ e.source !== 'load' &&
348
+ e.source !== 'render' &&
349
+ e.source !== 'window' &&
350
+ e.source !== 'runtime'
351
+ )
352
+ continue
353
+ // `runtime` entries may be unattributed (a stale link to a deleted view
354
+ // names no applet), so attribution is optional there and dropped when
355
+ // malformed — every other source must name the applet that broke.
356
+ const attributed = (e.kind === 'widget' || e.kind === 'view') && typeof e.name === 'string'
357
+ const named = attributed && /^[a-zA-Z0-9_-]+$/.test(e.name as string)
358
+ if (!named && e.source !== 'runtime') continue
345
359
  if (typeof e.message !== 'string' || !e.message) continue
346
360
  recordAppletError(c.get('ws').path, {
347
361
  source: e.source,
348
- kind: e.kind,
349
- name: e.name,
362
+ ...(named ? { kind: e.kind as AppletKind, name: e.name as string } : {}),
350
363
  message: e.message,
351
364
  ...(typeof e.stack === 'string' ? { stack: e.stack } : {})
352
365
  })
@@ -545,6 +558,17 @@ one.get('/availability', async c => {
545
558
  return c.json(availability satisfies HarnessAvailability)
546
559
  })
547
560
 
561
+ one.get('/skills', async c => {
562
+ const ws = c.get('ws')
563
+ return c.json(await getWorkspaceSkillsStatus(ws.path, ws.type))
564
+ })
565
+
566
+ one.post('/skills/update', async c => {
567
+ const ws = c.get('ws')
568
+ const result = await updateWorkspaceSkills(ws.path, ws.type ?? 'claude-code')
569
+ return c.json(result.status)
570
+ })
571
+
548
572
  // Models the workspace's agent backend can run, normalized across providers.
549
573
  // OpenClaw queries the gateway catalog; everything else (Claude Code) reads the
550
574
  // account-wide Agent SDK model list.
@@ -940,6 +964,34 @@ export const api = new Hono()
940
964
 
941
965
  api.route('/api/workspaces', workspaces)
942
966
 
967
+ // App-wide settings (settings.json in the data dir). GET returns every key
968
+ // with defaults applied; PATCH merges a partial body and returns the result.
969
+ api.get('/api/settings', c => c.json(getAppSettings()))
970
+
971
+ api.patch('/api/settings', async c => {
972
+ let body: unknown
973
+ try {
974
+ body = await c.req.json()
975
+ } catch {
976
+ return c.text('Invalid JSON body', 400)
977
+ }
978
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
979
+ return c.text('Settings patch must be an object', 400)
980
+ }
981
+ // app-settings whitelists the updatable fields; the conf schema validates
982
+ // the values on save, rejecting the whole patch before anything persists.
983
+ let settings: AppSettings
984
+ try {
985
+ settings = saveAppSettings(pickAppSettingsPatch(body as Record<string, unknown>))
986
+ } catch (error) {
987
+ return c.text(error instanceof Error ? error.message : 'Invalid settings patch', 400)
988
+ }
989
+ // Other open clients hold these in a query cache with no polling; broadcast
990
+ // the new value so an app-wide preference applies everywhere immediately.
991
+ publishEvent({ type: 'settings:updated', settings })
992
+ return c.json(settings)
993
+ })
994
+
943
995
  // Everything else: in production, serve the prebuilt client from `dist/` via
944
996
  // Hono's static handler (mime types, traversal-safe, optional precompression).
945
997
  // Hashed assets (`/chunk-….js`, `/favicon-….png`, …) are pinned immutable; the
@@ -0,0 +1,65 @@
1
+ import Conf from 'conf'
2
+
3
+ import type { AppSettings } from '@/lib/types'
4
+
5
+ import { DATA_DIR } from './data-dir'
6
+
7
+ // App-wide user settings, stored as `settings.json` in moi's data dir next to
8
+ // the workspace registry. Backed by `conf`: atomic writes, per-key JSON-schema
9
+ // validation, and migrations when the settings shape evolves. Adding a key
10
+ // means extending `AppSettings` (lib/types.ts) and the schema here — with a
11
+ // default, so GET /api/settings always returns a complete object — plus
12
+ // `API_UPDATABLE` if clients may change it.
13
+
14
+ export type AppSettingsPatch = Partial<AppSettings>
15
+
16
+ // Whitelist of fields the API may update. Type validation is NOT duplicated
17
+ // here — `saveAppSettings` validates the merged store against the conf schema
18
+ // before anything is written, so a bad value throws with nothing persisted.
19
+ const API_UPDATABLE = ['autoUpdateSkills'] as const satisfies readonly (keyof AppSettings)[]
20
+
21
+ // Pick the API-updatable fields out of an untrusted body; unknown keys are
22
+ // dropped. Values are intentionally unchecked — the conf schema rejects wrong
23
+ // types when the patch is saved.
24
+ export function pickAppSettingsPatch(body: Record<string, unknown>): AppSettingsPatch {
25
+ const picked: Record<string, unknown> = {}
26
+ for (const key of API_UPDATABLE) {
27
+ if (body[key] !== undefined) picked[key] = body[key]
28
+ }
29
+ // Not yet schema-validated; saveAppSettings is the enforcement point.
30
+ return picked as AppSettingsPatch
31
+ }
32
+
33
+ let _dir = DATA_DIR
34
+ let _store: Conf<AppSettings> | null = null
35
+
36
+ // Test seam: point the store at a scratch dir (mirrors setThreadConfigPath).
37
+ export function setAppSettingsDir(dir: string): void {
38
+ _dir = dir
39
+ _store = null
40
+ }
41
+
42
+ function store(): Conf<AppSettings> {
43
+ _store ??= new Conf<AppSettings>({
44
+ cwd: _dir,
45
+ configName: 'settings',
46
+ schema: {
47
+ autoUpdateSkills: { type: 'boolean', default: false }
48
+ }
49
+ })
50
+ return _store
51
+ }
52
+
53
+ export function getAppSettings(): AppSettings {
54
+ return store().store
55
+ }
56
+
57
+ // Merge a partial settings object over the stored one and return the result.
58
+ // The object-form `set` validates the whole merged store against the schema
59
+ // before writing, so an invalid patch throws (`Config schema violation: …`)
60
+ // and persists nothing.
61
+ export function saveAppSettings(patch: AppSettingsPatch): AppSettings {
62
+ const settings = store()
63
+ if (Object.keys(patch).length > 0) settings.set(patch)
64
+ return settings.store
65
+ }
package/server/applets.ts CHANGED
@@ -20,8 +20,7 @@ import {
20
20
  APPLET_API_BASE_SENTINEL,
21
21
  type AppletKind,
22
22
  buildApplet,
23
- scanAssetImports,
24
- scanServerImports
23
+ scanRelativeImports
25
24
  } from './bundler/build-applet'
26
25
 
27
26
  export type AppletPaths = {
@@ -40,12 +39,14 @@ export function getAppletPaths(workspacePath: string, kind: AppletKind): AppletP
40
39
  return { moiRoot, sourceDir, buildDir, manifestPath }
41
40
  }
42
41
 
43
- // Source module names in a kind's directory: `*.tsx`/`*.ts` minus `.server.ts`.
42
+ // Source module names in a kind's directory: `*.tsx`/`*.ts` minus `.server.ts`
43
+ // and minus `_`-prefixed files (`_utils.tsx`) — those are shared modules for
44
+ // entries to import, never entry points themselves.
44
45
  export async function scanSources(sourceDir: string): Promise<string[]> {
45
46
  try {
46
47
  const entries = await readdir(sourceDir)
47
48
  return entries
48
- .filter(f => /\.(tsx|ts)$/.test(f) && !f.endsWith('.server.ts'))
49
+ .filter(f => /\.(tsx|ts)$/.test(f) && !f.startsWith('_') && !f.endsWith('.server.ts'))
49
50
  .map(f => f.replace(/\.tsx?$/, ''))
50
51
  } catch {
51
52
  return []
@@ -60,30 +61,139 @@ async function resolveSource(sourceDir: string, name: string): Promise<string |
60
61
  return null
61
62
  }
62
63
 
63
- // A bundle is stale if its entry `index.js` is missing, or the source — or any
64
- // `.server.ts` it imports (RPC stubs are inlined) or asset it imports (emitted
65
- // into the bundle dir) — is newer than the built entry. The bundle itself is
66
- // React-mode-agnostic (see buildApplet), so it needs no rebuild when the server
67
- // switches between the development and production React.
64
+ // Backstop for pathological graphs: an applet wiring more distinct files than
65
+ // this is reported stale without walking further — stale-but-rebuilt is the
66
+ // safe degradation, and the cap keeps the per-bundle check bounded no matter
67
+ // what the imports look like. Counts every input, images and JSON included, so
68
+ // it sits well above what an asset-heavy applet reaches (the walk never enters
69
+ // node_modules); hitting it means something is off anyway.
70
+ const MAX_GRAPH_FILES = 256
71
+
72
+ // Files the walk keeps descending through — anything Bun treats as a module
73
+ // (`.ts`, `.mjs`, `.cts`, …). Everything else (`.json`, `.css`, images) is a
74
+ // leaf.
75
+ const MODULE_FILE_RE = /\.[mc]?[jt]sx?$/
76
+ // Which transpiler loader lexes a module's imports. Only `.ts`/`.mts`/`.cts`
77
+ // take the `ts` loader: angle-bracket casts (`<string>x`) parse there and are
78
+ // JSX everywhere else. `.js`/`.mjs`/`.cjs` go through `tsx`, which accepts both
79
+ // plain JS and the JSX some of them contain.
80
+ const TS_ONLY_FILE_RE = /\.[mc]?ts$/
81
+
82
+ // A bundle is stale if its entry `index.js` is missing, any file in its local
83
+ // import graph has an mtime >= the built entry's, or one of those imports no
84
+ // longer resolves to a file at all.
85
+ //
86
+ // The graph is one uniform walk over every RELATIVE import the entry reaches:
87
+ // shared `_utils.tsx`, `../lib/*.ts`, `./data.json`, `./logo.png`,
88
+ // `./db.server`. Each is resolved to a real path, mtime-checked, and descended
89
+ // into when it's a module — so an imported image and a transitively imported
90
+ // helper are the same case, not two mechanisms. Bare specifiers (node_modules)
91
+ // are not walked: after a dependency bump, `moi bundle --force`. The bundle
92
+ // itself is React-mode-agnostic (see buildApplet), so it needs no rebuild when
93
+ // the server switches between the development and production React.
94
+ //
95
+ // `.server.ts` modules are walked like anything else, which is deliberately
96
+ // MORE than the bundle needs: their code never ships to the client (only the
97
+ // export list, inlined as RPC stubs), so editing one — or anything it imports
98
+ // — cannot change a byte of `index.js`. We report stale anyway because 'built'
99
+ // is what drives the worker recycle downstream (see `reloadModules`, called
100
+ // from widgets.ts/views.ts for every rebuilt applet). Without it, editing a
101
+ // helper that only a server module imports would leave a live worker serving
102
+ // the old code with nothing to dislodge it. The redundant rebuild is the price
103
+ // of that signal; the alternative is a second staleness channel threaded
104
+ // through the build results.
68
105
  async function needsRebuild(buildDir: string, name: string, srcPath: string): Promise<boolean> {
69
106
  const built = Bun.file(join(buildDir, name, 'index.js'))
70
107
  if (!(await built.exists())) return true
71
- let sourceMtime = Bun.file(srcPath).lastModified
72
- const source = await Bun.file(srcPath).text()
73
- const dir = dirname(srcPath)
74
- for (const specifier of scanServerImports(source)) {
75
- const serverFile = Bun.file(join(dir, `${specifier}.server.ts`))
76
- if (await serverFile.exists()) {
77
- sourceMtime = Math.max(sourceMtime, serverFile.lastModified)
108
+ const builtMtime = built.lastModified
109
+
110
+ const queue = [srcPath]
111
+ const visited = new Set<string>()
112
+ while (queue.length > 0) {
113
+ const path = queue.pop()!
114
+ if (visited.has(path)) continue
115
+ visited.add(path)
116
+ if (visited.size > MAX_GRAPH_FILES) return true
117
+ const file = Bun.file(path)
118
+ if (!(await file.exists())) continue
119
+ if (file.lastModified >= builtMtime) return true
120
+ // Leaves stop at the mtime check above — an asset, JSON, or CSS file can't
121
+ // import anything.
122
+ if (!MODULE_FILE_RE.test(path)) continue
123
+ const source = await file.text()
124
+ const dir = dirname(path)
125
+ for (const specifier of scanRelativeImports(
126
+ source,
127
+ TS_ONLY_FILE_RE.test(path) ? 'ts' : 'tsx'
128
+ )) {
129
+ const resolved = await resolveModuleImport(dir, specifier)
130
+ // Nothing on disk answers this import, so the next build will fail on it.
131
+ // Report stale rather than skip: a helper deleted since the last build
132
+ // would otherwise leave `moi bundle` serving the last good bundle and
133
+ // never surfacing the missing-import error.
134
+ if (!resolved) return true
135
+ queue.push(resolved)
78
136
  }
79
137
  }
80
- for (const specifier of scanAssetImports(source)) {
81
- const assetFile = Bun.file(join(dir, specifier))
82
- if (await assetFile.exists()) {
83
- sourceMtime = Math.max(sourceMtime, assetFile.lastModified)
84
- }
138
+ return false
139
+ }
140
+
141
+ // Extensions Bun appends to an extensionless import, in its own preference
142
+ // order (`./data` finds `data.tsx` before `data.ts` before … `data.json`).
143
+ // Doubles as the directory-index set: `./helpers` → `helpers/index.jsx`.
144
+ const RESOLVE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.mjs', '.cjs', '.json', '.mts', '.cts']
145
+
146
+ // TypeScript's output-extension rewrite: an import written against the emitted
147
+ // file name resolves to the source that produces it. (`.cjs` → `.cts` is
148
+ // deliberately absent — Bun doesn't do that one.)
149
+ const TS_EXTENSION_REWRITES: Record<string, string[]> = {
150
+ '.js': ['.ts', '.tsx'],
151
+ '.jsx': ['.tsx'],
152
+ '.mjs': ['.mts']
153
+ }
154
+
155
+ // Resolve a relative import to the file the bundler will actually read. This
156
+ // mirrors Bun's resolution rather than delegating to `Bun.resolveSync`, which
157
+ // memoizes results for the life of the process: in the long-running server it
158
+ // keeps handing back the path of a dependency that has since been deleted or
159
+ // renamed, which is exactly the case this check has to catch. Every candidate
160
+ // is probed against the filesystem, in Bun's order — literal path, TS
161
+ // extension rewrite, appended extension, then directory (`package.json` main,
162
+ // else `index.*`). Returns null when nothing on disk answers the specifier.
163
+ async function resolveModuleImport(dir: string, specifier: string): Promise<string | null> {
164
+ const base = join(dir, specifier)
165
+ const candidates = [base]
166
+
167
+ // Extension of the final segment only — a dot in a directory name (`./v1.2/x`)
168
+ // is not one.
169
+ const ext = /\.[^./\\]+$/.exec(base)?.[0] ?? ''
170
+ for (const rewrite of TS_EXTENSION_REWRITES[ext] ?? []) {
171
+ candidates.push(base.slice(0, base.length - ext.length) + rewrite)
85
172
  }
86
- return sourceMtime >= built.lastModified
173
+ for (const e of RESOLVE_EXTENSIONS) candidates.push(base + e)
174
+
175
+ for (const candidate of candidates) {
176
+ if (await Bun.file(candidate).exists()) return candidate
177
+ }
178
+
179
+ // Directory import. `package.json` main wins over `index.*`, matching Bun;
180
+ // an unreadable or `main`-less manifest just falls through to the indexes.
181
+ const pkg: unknown = await Bun.file(join(base, 'package.json'))
182
+ .json()
183
+ .catch(() => null)
184
+ const main =
185
+ typeof pkg === 'object' && pkg !== null && 'main' in pkg && typeof pkg.main === 'string'
186
+ ? pkg.main
187
+ : null
188
+ if (main) {
189
+ const mainPath = join(base, main)
190
+ if (await Bun.file(mainPath).exists()) return mainPath
191
+ }
192
+ for (const e of RESOLVE_EXTENSIONS) {
193
+ const index = join(base, `index${e}`)
194
+ if (await Bun.file(index).exists()) return index
195
+ }
196
+ return null
87
197
  }
88
198
 
89
199
  // Built applet names: subdirectories of `buildDir` that hold an `index.js`
@@ -8,6 +8,7 @@ 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 { APP_ICON_IDS, isAppIconId } from '@/lib/app-icons'
11
12
  import type { AppletKind, ViewConfig, WidgetConfig } from '@/lib/types'
12
13
 
13
14
  import { scopeAppletCss } from './applet-css'
@@ -161,9 +162,19 @@ export async function extractViewConfig(srcPath: string): Promise<ViewConfig | n
161
162
  if (prop.type !== 'Property' || prop.key?.type !== 'Identifier') continue
162
163
  const key = prop.key.name as string
163
164
 
164
- if (key === 'title' || key === 'icon') {
165
+ if (key === 'title') {
165
166
  if (prop.value?.type === 'Literal' && typeof prop.value.value === 'string') {
166
- result[key] = prop.value.value
167
+ result.title = prop.value.value
168
+ }
169
+ continue
170
+ }
171
+ if (key === 'icon') {
172
+ if (prop.value?.type === 'Literal' && typeof prop.value.value === 'string') {
173
+ const icon = prop.value.value
174
+ if (!isAppIconId(icon)) {
175
+ throw new Error(`Unknown view icon id "${icon}". Use one of: ${APP_ICON_IDS.join(', ')}`)
176
+ }
177
+ result.icon = icon
167
178
  }
168
179
  continue
169
180
  }
@@ -231,18 +242,49 @@ export function rpc(module, name) {
231
242
  }
232
243
  `
233
244
 
234
- // The `moi` virtual module — the applet-facing runtime API. Today just
235
- // `fileUrl(path)`, which maps a workspace-relative path to its streaming URL
245
+ // The `moi` virtual module — the applet-facing runtime API.
246
+ //
247
+ // `fileUrl(path)` maps a workspace-relative path to its streaming URL
236
248
  // (`/api/workspaces/<id>/fs/<path>`). Same sentinel base as RPC; the path is
237
249
  // per-segment URL-encoded so spaces / unicode in filenames survive. A leading
238
250
  // slash is stripped so both `clips/a.mp4` and `/clips/a.mp4` work.
251
+ //
252
+ // `focusTab(tab, params?)` and `sendChatMessage(message, context?)` forward to
253
+ // this bundle's host-attached bridge — client-local replace-navigation to a
254
+ // workspace tab (params delivered to the target view via navigation state),
255
+ // and a chat message sent to the workspace's active chat as if the user had
256
+ // typed it. This virtual module is INLINED PER BUNDLE,
257
+ // so `bridge` is private to one applet: the host attaches it right after the
258
+ // dynamic import and neuters it on invalidation (see
259
+ // client/features/applets/applet-runtime.ts). Optional-chained so calls no-op
260
+ // before attach and outside the moi host. The `__` exports are host wiring,
261
+ // surfaced from the bundle entry below — they are deliberately NOT part of the
262
+ // author-facing `declare module 'moi'` ambient types (server/moi-scaffold.ts).
239
263
  const MOI_MODULE_SOURCE = `
240
264
  const BASE = ${JSON.stringify(APPLET_API_BASE_SENTINEL)};
241
265
 
266
+ let bridge = null;
267
+
268
+ export function __attachBridge(next) {
269
+ bridge = next;
270
+ }
271
+
272
+ export function __getBridge() {
273
+ return bridge;
274
+ }
275
+
242
276
  export function fileUrl(path) {
243
277
  const clean = String(path).replace(/^\\/+/, "");
244
278
  return BASE + "/fs/" + clean.split("/").map(encodeURIComponent).join("/");
245
279
  }
280
+
281
+ export function focusTab(tab, params) {
282
+ bridge?.focusTab(tab, params);
283
+ }
284
+
285
+ export function sendChatMessage(message, context) {
286
+ bridge?.sendChatMessage(message, context);
287
+ }
246
288
  `
247
289
 
248
290
  // Server modules are keyed by their path relative to the moi root
@@ -437,7 +479,13 @@ function widgetEntryPlugin(widgetPath: string, syntheticCssPath: string): BunPlu
437
479
  build.onLoad({ filter: /.*/, namespace: 'widget-entry' }, () => ({
438
480
  contents: [
439
481
  `import ${JSON.stringify(syntheticCssPath)};`,
440
- `export { default } from ${JSON.stringify(widgetPath)};`
482
+ `export { default } from ${JSON.stringify(widgetPath)};`,
483
+ // Surface the bridge wiring on every bundle's `index.js` so the host
484
+ // can attach after dynamic import. Bun dedupes the `moi` virtual
485
+ // module within a bundle, so this re-export and the applet's own
486
+ // `import { focusTab } from 'moi'` share one module instance — the
487
+ // attached bridge is the one focusTab reads.
488
+ `export { __attachBridge, __getBridge } from "moi";`
441
489
  ].join('\n'),
442
490
  loader: 'js'
443
491
  }))
@@ -488,18 +536,28 @@ export function scanServerImports(source: string): string[] {
488
536
  return specifiers
489
537
  }
490
538
 
491
- // Relative asset import specifiers in an applet source (`./logo.png`,
492
- // `../shared/icon.svg`). Used by the rebuild staleness check so editing an
493
- // imported image rebuilds the bundle even when the `.tsx` itself is untouched.
494
- const ASSET_IMPORT_RE =
495
- /from\s+['"](\.\.?\/[^'"]+?\.(?:png|jpe?g|gif|svg|webp|avif|ico|woff2?|ttf|otf))['"]/gi
496
- export function scanAssetImports(source: string): string[] {
497
- const specifiers: string[] = []
498
- let match
499
- while ((match = ASSET_IMPORT_RE.exec(source)) !== null) {
500
- specifiers.push(match[1])
539
+ // Every relative import specifier in an applet source — modules (`./_utils`,
540
+ // `../lib/data`), assets (`./logo.png`), `.server` stubs, JSON, CSS alike, in
541
+ // static, re-export, side-effect, and dynamic form. Lexed by Bun's own
542
+ // transpiler, so comments and string literals can't false-positive. Type-only
543
+ // imports are erased by the lexer — correct here, since they never affect the
544
+ // emitted bundle. Bare specifiers (node_modules) are filtered out: the
545
+ // staleness check doesn't walk them. A file that fails to lex contributes no
546
+ // imports — the build itself surfaces the syntax error. Used by the rebuild
547
+ // staleness check to walk the applet's local import graph, so editing anything
548
+ // it (transitively) pulls in marks every applet using it stale.
549
+ const IMPORT_SCANNERS = {
550
+ ts: new Bun.Transpiler({ loader: 'ts' }),
551
+ tsx: new Bun.Transpiler({ loader: 'tsx' })
552
+ }
553
+ export function scanRelativeImports(source: string, loader: 'ts' | 'tsx' = 'tsx'): string[] {
554
+ let imports: { path: string }[]
555
+ try {
556
+ imports = IMPORT_SCANNERS[loader].scanImports(source)
557
+ } catch {
558
+ return []
501
559
  }
502
- return specifiers
560
+ return imports.map(i => i.path).filter(p => /^\.\.?\//.test(p))
503
561
  }
504
562
 
505
563
  async function prevalidateServerFiles(entrypoint: string): Promise<void> {