moi-computer 0.11.1-next.4 → 0.12.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 (131) hide show
  1. package/client/api/app-config.ts +7 -4
  2. package/client/app/AppRouter.tsx +2 -2
  3. package/client/app/routes/WorkspaceRoute.tsx +27 -19
  4. package/client/features/applets/{AppletMount.tsx → AppletContainer.tsx} +7 -5
  5. package/client/features/applets/WidgetShell.tsx +3 -3
  6. package/client/features/applets/applet-cache.ts +3 -5
  7. package/client/features/applets/applet-runtime.ts +27 -12
  8. package/client/features/applets/applet-thumbnail.ts +2 -1
  9. package/client/features/chat/applet-chat-intents.ts +14 -6
  10. package/client/features/chat/composer/attachments/draft-attachments.ts +21 -4
  11. package/client/features/chat/messages/MarkdownContent.tsx +5 -2
  12. package/client/features/chat/sessions/browser-tab-state.ts +18 -0
  13. package/client/features/chat/sessions/useSelectedSession.ts +55 -21
  14. package/client/features/chat/useChat.ts +4 -0
  15. package/client/features/collab/applet-api.ts +34 -0
  16. package/client/features/collab/client.ts +239 -0
  17. package/client/features/collab/components/cursors.tsx +199 -0
  18. package/client/features/collab/components/presence-avatars.tsx +61 -0
  19. package/client/features/collab/components/presence-frame.tsx +126 -0
  20. package/client/features/collab/components/presence-group.tsx +23 -0
  21. package/client/features/collab/components/presence-helpers.ts +50 -0
  22. package/client/features/collab/components/user-avatar-group.tsx +22 -0
  23. package/client/features/collab/components/user-avatar.tsx +40 -0
  24. package/client/features/collab/components/user.tsx +50 -0
  25. package/client/features/collab/hooks.tsx +164 -0
  26. package/client/features/collab/host-state.ts +254 -0
  27. package/client/features/collab/index.ts +5 -0
  28. package/client/features/collab/local-user.ts +46 -0
  29. package/client/features/collab/presence-publisher.ts +30 -0
  30. package/client/features/collab/presence-target.ts +8 -0
  31. package/client/features/collab/provider.tsx +79 -0
  32. package/client/features/collab/proxy-user.ts +35 -0
  33. package/client/features/collab/store.ts +156 -0
  34. package/client/features/collab/testing/component-fixtures.tsx +54 -0
  35. package/client/features/collab/testing/fake-engine.ts +129 -0
  36. package/client/features/collab/users.ts +106 -0
  37. package/client/features/collab/workspace-users-menu.tsx +194 -0
  38. package/client/features/connectors/mcp-icons.ts +0 -2
  39. package/client/features/dev/DevIndexPage.tsx +5 -0
  40. package/client/features/dev/DevRoutes.tsx +16 -4
  41. package/client/features/dev/collab/collab-page.tsx +24 -0
  42. package/client/features/dev/collab/collab-playground.tsx +614 -0
  43. package/client/features/dev/collab/local-user-settings.tsx +166 -0
  44. package/client/features/dev/collab/playground-room.ts +33 -0
  45. package/client/features/dev/{UiComponentsPage.tsx → ui-components/ui-components-page.tsx} +1 -1
  46. package/client/features/overview/WidgetCanvas.tsx +3 -1
  47. package/client/features/views/ViewManager.tsx +12 -7
  48. package/client/features/views/api.ts +2 -2
  49. package/client/features/views/useViewBuilderActions.ts +3 -0
  50. package/client/features/workspace/WorkspaceContext.tsx +1 -1
  51. package/client/features/workspace/WorkspaceLayoutContext.tsx +8 -2
  52. package/client/features/workspace/WorkspaceScreen.tsx +19 -11
  53. package/client/features/workspace/WorkspaceTabs.tsx +3 -3
  54. package/client/features/workspace/api.ts +2 -1
  55. package/client/features/workspace/browser-tab-state.ts +44 -0
  56. package/client/features/workspace/layout-save.ts +13 -0
  57. package/client/features/workspace/moi-context.ts +2 -1
  58. package/client/features/workspace/useWorkspaceNavigation.ts +20 -8
  59. package/client/index.css +45 -0
  60. package/client/index.tsx +9 -4
  61. package/client/main.tsx +1 -11
  62. package/client/theme.css +4 -1
  63. package/dist/chunk-2jncyq65.js +1 -0
  64. package/dist/{chunk-brr0zbeh.js → chunk-3a48fyf7.js} +2 -2
  65. package/dist/{chunk-tzz101ea.js → chunk-97eg9mjn.js} +1 -1
  66. package/dist/chunk-e2q5ken7.js +68 -0
  67. package/dist/{chunk-zs4mte79.js → chunk-efdyz6xp.js} +1 -1
  68. package/dist/chunk-h2kj1ysj.js +1 -0
  69. package/dist/chunk-jf6czgrz.js +2 -0
  70. package/dist/chunk-nez8sdta.js +1 -0
  71. package/dist/chunk-nzwgm8vc.css +1 -0
  72. package/dist/chunk-ph0h6h86.js +1 -0
  73. package/dist/chunk-ryg9z3kn.js +10 -0
  74. package/dist/chunk-tpn177bt.js +2 -0
  75. package/dist/chunk-vfpsc75k.js +2 -0
  76. package/dist/{chunk-m1fvqssh.js → chunk-z3byfve5.js} +2 -2
  77. package/dist/index.html +1 -1
  78. package/lib/collab/colors.ts +30 -0
  79. package/lib/collab/protocol.ts +84 -0
  80. package/lib/collab/types.ts +52 -0
  81. package/lib/experimental.ts +14 -0
  82. package/lib/moi-context.ts +11 -3
  83. package/lib/navigation.ts +25 -5
  84. package/lib/types.ts +20 -33
  85. package/package.json +2 -2
  86. package/server/AGENTS.md +1 -1
  87. package/server/api.ts +28 -5
  88. package/server/app-config.ts +127 -34
  89. package/server/applet-typecheck.ts +8 -3
  90. package/server/applets/applet-css.ts +1 -1
  91. package/server/applets/build-applet.ts +9 -3
  92. package/server/applets/declarations/base.d.ts +75 -0
  93. package/server/applets/declarations/collab.d.ts +88 -0
  94. package/server/applets/declarations.ts +46 -0
  95. package/server/applets/index.ts +8 -8
  96. package/server/applets/runtime/collab.ts +94 -0
  97. package/server/applets/runtime/moi.ts +12 -19
  98. package/server/applets/runtime/rpc.ts +2 -4
  99. package/server/chat-selection.ts +22 -0
  100. package/server/cli.ts +86 -21
  101. package/server/collab/cloudflare-access.ts +78 -0
  102. package/server/collab/config.ts +18 -0
  103. package/server/collab/manager.ts +407 -0
  104. package/server/collab/service.ts +136 -0
  105. package/server/collab/skill/index.ts +53 -0
  106. package/server/collab/worker-messages.ts +10 -0
  107. package/server/collab/worker.ts +52 -0
  108. package/server/layout.ts +10 -3
  109. package/server/moi-scaffold.ts +55 -84
  110. package/server/preview.ts +1 -1
  111. package/server/skill-update.ts +7 -9
  112. package/server/skills-template.ts +14 -2
  113. package/server/web.ts +65 -17
  114. package/server/workspace-init.ts +6 -3
  115. package/ui-components/avatar.tsx +24 -11
  116. package/ui-components/button.tsx +9 -9
  117. package/ui-components/docs/avatar.md +11 -30
  118. package/workspace/.claude/skills/moi-workspace/SKILL.md +14 -11
  119. package/workspace/.claude/skills/moi-workspace/references/COLLAB.md +262 -0
  120. package/workspace/.claude/skills/moi-workspace/references/INTENTS.md +10 -7
  121. package/client/assets/mcp/agentation.png +0 -0
  122. package/dist/agentation-4s0nn45p.png +0 -0
  123. package/dist/chunk-2gs8jjx4.css +0 -1
  124. package/dist/chunk-7vvg5fyz.js +0 -68
  125. package/dist/chunk-94m3q9ce.js +0 -1
  126. package/dist/chunk-by2wqgak.js +0 -1
  127. package/dist/chunk-p34hvqt3.js +0 -1
  128. package/dist/chunk-p83f0jnj.js +0 -2
  129. package/dist/chunk-xg01f6pn.js +0 -10
  130. /package/client/features/dev/{UiComponentPreviews.tsx → ui-components/ui-component-previews.tsx} +0 -0
  131. /package/server/applets/{runtime/base.ts → api-base.ts} +0 -0
@@ -1,7 +1,8 @@
1
1
  import { readFileSync } from 'node:fs'
2
2
  import { join } from 'path'
3
3
 
4
- import type { ClientAppConfig } from '@/lib/types'
4
+ import type { ClientAppConfig, ExperimentalFeatures } from '@/lib/types'
5
+ import { EXPERIMENTAL_DEFAULTS } from '@/lib/experimental'
5
6
 
6
7
  import { DATA_DIR } from './data-dir'
7
8
 
@@ -11,23 +12,37 @@ import { DATA_DIR } from './data-dir'
11
12
  // runtime): config.json describes the deployment itself — nothing here changes
12
13
  // without a server restart, and no API writes it.
13
14
  //
14
- // Resolution: defaults < config.json < env. A missing file is the normal local
15
- // case; a malformed file or wrong-typed key warns on stderr and falls back
16
- // per-key, so a broken config never takes the CLI or server down with it.
15
+ // Resolution: defaults < config.json < env. Experimental features are enabled
16
+ // only by explicit CLI flags.
17
+ // A missing file is the normal local case; a malformed file or wrong-typed key
18
+ // warns on stderr and falls back per-key, so a broken config never takes the
19
+ // CLI or server down with it.
17
20
  export type AppConfig = {
18
21
  // Cloud demo deployment: workspace creation is blocked (UI shows the
19
22
  // cloud-demo promo dialog instead) and `moi` system commands are disabled.
20
23
  cloudDemo: boolean
21
- // Gated experimental features, checked by slug.
22
- experiments: string[]
24
+ experimental: ExperimentalFeatures
23
25
  // Link target for the cloud-demo promo dialog.
24
26
  demoInstallUrl: string
27
+ // Cloudflare Access (Zero Trust) in front of this deployment: each viewer
28
+ // inherits the user profile from Access's signed token. Null trusts no proxy.
29
+ cloudflareAccess: CloudflareAccessConfig | null
25
30
  }
26
31
 
32
+ export type CloudflareAccessConfig = {
33
+ // Token issuer and signing-key host, e.g. https://acme.cloudflareaccess.com.
34
+ teamDomain: string
35
+ // Application audience (AUD) tags; a token must be issued for one of them.
36
+ audience: readonly string[]
37
+ }
38
+
39
+ type DeploymentConfig = Omit<AppConfig, 'experimental'>
40
+
27
41
  const DEFAULTS: AppConfig = {
28
42
  cloudDemo: false,
29
- experiments: [],
30
- demoInstallUrl: 'https://moi.computer'
43
+ experimental: { ...EXPERIMENTAL_DEFAULTS },
44
+ demoInstallUrl: 'https://moi.computer',
45
+ cloudflareAccess: null
31
46
  }
32
47
 
33
48
  export const APP_CONFIG_FILE = join(DATA_DIR, 'config.json')
@@ -46,22 +61,91 @@ function parseBool(raw: string | undefined): boolean | undefined {
46
61
  return undefined
47
62
  }
48
63
 
49
- // "a, b,c" → ['a','b','c']; empty entries dropped. An empty string clears the
50
- // list (explicitly setting MOI_EXPERIMENTS= disables file-set experiments).
51
- function parseList(raw: string | undefined): string[] | undefined {
52
- if (raw === undefined) return undefined
53
- return raw
54
- .split(',')
55
- .map(item => item.trim())
56
- .filter(Boolean)
57
- }
58
-
59
64
  function parseString(raw: string | undefined): string | undefined {
60
65
  if (raw === undefined || raw.trim() === '') return undefined
61
66
  return raw.trim()
62
67
  }
63
68
 
64
- function fileValues(file: string): Partial<AppConfig> {
69
+ // `acme`, `acme.cloudflareaccess.com`, or its https URL → the token issuer
70
+ // origin. Anything with a path, query, or credentials is rejected.
71
+ function parseTeamDomain(raw: string): string | undefined {
72
+ const value = raw.trim()
73
+ if (!value) return undefined
74
+ const host = /^[a-z0-9-]+$/i.test(value) ? `${value}.cloudflareaccess.com` : value
75
+ try {
76
+ const url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(host) ? host : `https://${host}`)
77
+ if (url.protocol !== 'https:' || url.pathname !== '/' || url.search || url.hash)
78
+ return undefined
79
+ if (url.username || url.password) return undefined
80
+ return url.origin
81
+ } catch {
82
+ return undefined
83
+ }
84
+ }
85
+
86
+ // One AUD tag, a comma-separated list, or (in config.json) an array of tags.
87
+ function parseAudience(raw: unknown): string[] | undefined {
88
+ const items = typeof raw === 'string' ? raw.split(',') : raw
89
+ if (!Array.isArray(items) || !items.every(item => typeof item === 'string')) return undefined
90
+ const tags = items.map(item => item.trim()).filter(Boolean)
91
+ return tags.length ? tags : undefined
92
+ }
93
+
94
+ function fileCloudflareAccess(value: unknown): Partial<CloudflareAccessConfig> {
95
+ if (value === undefined || value === null) return {}
96
+ if (typeof value !== 'object' || Array.isArray(value)) {
97
+ warn('ignoring "cloudflareAccess" — expected an object')
98
+ return {}
99
+ }
100
+ const { teamDomain, audience } = value as Record<string, unknown>
101
+ const out: Partial<CloudflareAccessConfig> = {}
102
+ if (teamDomain !== undefined) {
103
+ const parsed = typeof teamDomain === 'string' ? parseTeamDomain(teamDomain) : undefined
104
+ if (parsed) out.teamDomain = parsed
105
+ else warn('ignoring "cloudflareAccess.teamDomain" — expected <team>.cloudflareaccess.com')
106
+ }
107
+ if (audience !== undefined) {
108
+ const parsed = parseAudience(audience)
109
+ if (parsed) out.audience = parsed
110
+ else warn('ignoring "cloudflareAccess.audience" — expected an AUD tag or an array of tags')
111
+ }
112
+ return out
113
+ }
114
+
115
+ function envCloudflareAccess(
116
+ env: Record<string, string | undefined>
117
+ ): Partial<CloudflareAccessConfig> {
118
+ const out: Partial<CloudflareAccessConfig> = {}
119
+ const teamDomain = parseString(env.MOI_CLOUDFLARE_ACCESS_TEAM_DOMAIN)
120
+ if (teamDomain !== undefined) {
121
+ const parsed = parseTeamDomain(teamDomain)
122
+ if (parsed) out.teamDomain = parsed
123
+ else warn('ignoring MOI_CLOUDFLARE_ACCESS_TEAM_DOMAIN — expected <team>.cloudflareaccess.com')
124
+ }
125
+ const audience = parseAudience(parseString(env.MOI_CLOUDFLARE_ACCESS_AUD))
126
+ if (audience) out.audience = audience
127
+ return out
128
+ }
129
+
130
+ // Per field, env wins over config.json. Verification needs both the issuer and
131
+ // an audience, so half a configuration trusts nothing rather than guessing.
132
+ function resolveCloudflareAccess(
133
+ fileValue: unknown,
134
+ env: Record<string, string | undefined>
135
+ ): CloudflareAccessConfig | null {
136
+ const { teamDomain, audience } = {
137
+ ...fileCloudflareAccess(fileValue),
138
+ ...envCloudflareAccess(env)
139
+ }
140
+ if (!teamDomain && !audience) return null
141
+ if (!teamDomain || !audience) {
142
+ warn('ignoring Cloudflare Access — it needs both a team domain and an audience (AUD) tag')
143
+ return null
144
+ }
145
+ return Object.freeze({ teamDomain, audience: Object.freeze(audience) })
146
+ }
147
+
148
+ function readConfigFile(file: string): Record<string, unknown> {
65
149
  let text: string
66
150
  try {
67
151
  text = readFileSync(file, 'utf8')
@@ -87,17 +171,15 @@ function fileValues(file: string): Partial<AppConfig> {
87
171
  warn(`ignoring ${file} — expected a JSON object`)
88
172
  return {}
89
173
  }
90
- const raw = parsed as Record<string, unknown>
91
- const out: Partial<AppConfig> = {}
174
+ return parsed as Record<string, unknown>
175
+ }
176
+
177
+ function fileValues(raw: Record<string, unknown>): Partial<DeploymentConfig> {
178
+ const out: Partial<DeploymentConfig> = {}
92
179
  if (raw.cloudDemo !== undefined) {
93
180
  if (typeof raw.cloudDemo === 'boolean') out.cloudDemo = raw.cloudDemo
94
181
  else warn('ignoring "cloudDemo" — expected a boolean')
95
182
  }
96
- if (raw.experiments !== undefined) {
97
- if (Array.isArray(raw.experiments) && raw.experiments.every(item => typeof item === 'string')) {
98
- out.experiments = raw.experiments
99
- } else warn('ignoring "experiments" — expected an array of strings')
100
- }
101
183
  if (raw.demoInstallUrl !== undefined) {
102
184
  if (typeof raw.demoInstallUrl === 'string') out.demoInstallUrl = raw.demoInstallUrl
103
185
  else warn('ignoring "demoInstallUrl" — expected a string')
@@ -108,23 +190,34 @@ function fileValues(file: string): Partial<AppConfig> {
108
190
  // Pure resolver, exported for tests. `getAppConfig` is the cached entrypoint.
109
191
  export function loadAppConfig(
110
192
  file: string = APP_CONFIG_FILE,
111
- env: Record<string, string | undefined> = process.env
193
+ env: Record<string, string | undefined> = process.env,
194
+ cliExperimental: Partial<ExperimentalFeatures> = {}
112
195
  ): AppConfig {
113
- const fromFile = fileValues(file)
114
- const fromEnv: Partial<AppConfig> = {
196
+ const raw = readConfigFile(file)
197
+ const fromFile = fileValues(raw)
198
+ const fromEnv: Partial<DeploymentConfig> = {
115
199
  cloudDemo: parseBool(env.MOI_CLOUD_DEMO),
116
- experiments: parseList(env.MOI_EXPERIMENTS),
117
200
  demoInstallUrl: parseString(env.MOI_DEMO_INSTALL_URL)
118
201
  }
119
202
  const merged = { ...DEFAULTS, ...fromFile }
120
- for (const key of Object.keys(fromEnv) as (keyof AppConfig)[]) {
203
+ for (const key of Object.keys(fromEnv) as (keyof DeploymentConfig)[]) {
121
204
  if (fromEnv[key] === undefined) delete fromEnv[key]
122
205
  }
123
- return Object.freeze({ ...merged, ...fromEnv })
206
+ const cloudflareAccess = resolveCloudflareAccess(raw.cloudflareAccess, env)
207
+ const experimental = Object.freeze({
208
+ ...DEFAULTS.experimental,
209
+ ...cliExperimental
210
+ })
211
+ return Object.freeze({ ...merged, ...fromEnv, cloudflareAccess, experimental })
124
212
  }
125
213
 
126
214
  let _config: AppConfig | null = null
127
215
 
216
+ // The CLI supplies explicit startup flags before importing the web server.
217
+ export function initializeAppConfig(experimental: Partial<ExperimentalFeatures> = {}): void {
218
+ _config = loadAppConfig(undefined, undefined, experimental)
219
+ }
220
+
128
221
  export function getAppConfig(): AppConfig {
129
222
  _config ??= loadAppConfig()
130
223
  return _config
@@ -139,6 +232,6 @@ export function resetAppConfig(): void {
139
232
  // The only shape that reaches the browser (GET /api/config). Server-only keys
140
233
  // added to AppConfig later stay out unless explicitly forwarded here.
141
234
  export function clientAppConfig(): ClientAppConfig {
142
- const { cloudDemo, experiments, demoInstallUrl } = getAppConfig()
143
- return { cloudDemo, experiments: [...experiments], demoInstallUrl }
235
+ const { cloudDemo, experimental, demoInstallUrl } = getAppConfig()
236
+ return { cloudDemo, experimental: { ...experimental }, demoInstallUrl }
144
237
  }
@@ -4,7 +4,7 @@ import ts from 'typescript'
4
4
 
5
5
  import type { AppletSelector } from '@/lib/applet-selector'
6
6
 
7
- import { writeAppletEnvDts } from './moi-scaffold'
7
+ import { appletDeclarationPath, syncAppletDeclarations } from './applets/declarations'
8
8
 
9
9
  export type AppletTypecheckResult = {
10
10
  files: string[]
@@ -63,9 +63,14 @@ export async function typecheckApplets(
63
63
  .sort()
64
64
  if (files.length === 0) return { files, diagnostics: [] }
65
65
 
66
- await writeAppletEnvDts(workspaceRoot)
66
+ await syncAppletDeclarations(workspaceRoot)
67
+ const collabTypes = appletDeclarationPath(workspaceRoot, 'collab.d.ts')
67
68
  const program = ts.createProgram({
68
- rootNames: [join(moiRoot, 'applet-env.d.ts'), ...files],
69
+ rootNames: [
70
+ appletDeclarationPath(workspaceRoot, 'base.d.ts'),
71
+ ...(existsSync(collabTypes) ? [collabTypes] : []),
72
+ ...files
73
+ ],
69
74
  options: {
70
75
  allowImportingTsExtensions: true,
71
76
  esModuleInterop: true,
@@ -10,7 +10,7 @@
10
10
  //
11
11
  // The transform prefixes each selector with `[data-applet="<scope>"]` — the
12
12
  // attribute the client puts on the applet's mount container (see
13
- // client/features/applets/AppletMount.tsx). Selectors that address the page
13
+ // client/features/applets/AppletContainer.tsx). Selectors that address the page
14
14
  // root (`:root`, `:host`, `html`, `body`) are mapped onto the container
15
15
  // itself, so theme variables and preflight inheritance (line-height, font)
16
16
  // land there and inherit down. Rules inside `@keyframes` are left alone —
@@ -18,7 +18,7 @@ export type { AppletKind }
18
18
  // Extensions an applet may `import` as a bundled asset. Each is emitted as a
19
19
  // content-hashed sibling of `index.js` and the import resolves to its URL via
20
20
  // `import.meta.url`. Deliberately images + fonts only: large media (video/audio)
21
- // belongs in the workspace and should stream via `fileUrl()`, not bloat the
21
+ // belongs in the workspace and should stream via `resolveUrl()`, not bloat the
22
22
  // bundle dir.
23
23
  const ASSET_EXTENSIONS = /\.(png|jpe?g|gif|svg|webp|avif|ico|woff2?|ttf|otf)$/i
24
24
 
@@ -32,6 +32,7 @@ const EXTERNAL_MODULES = [
32
32
 
33
33
  const RPC_MODULE_PATH = join(import.meta.dir, 'runtime', 'rpc.ts')
34
34
  const MOI_MODULE_PATH = join(import.meta.dir, 'runtime', 'moi.ts')
35
+ const COLLAB_MODULE_PATH = join(import.meta.dir, 'runtime', 'collab.ts')
35
36
 
36
37
  type ServerModule = {
37
38
  name: string
@@ -145,6 +146,10 @@ function appletRuntimePlugin(
145
146
  path: Bun.resolveSync('devalue', import.meta.dir)
146
147
  }))
147
148
 
149
+ // Collaboration forwards to the same host bridge as the applet runtime.
150
+ build.onResolve({ filter: /^moi\/collab$/ }, () => ({
151
+ path: COLLAB_MODULE_PATH
152
+ }))
148
153
  // The applet-facing runtime. A bare specifier, so match it exactly.
149
154
  build.onResolve({ filter: /^moi$/ }, () => ({ path: MOI_MODULE_PATH }))
150
155
 
@@ -450,10 +455,11 @@ export async function buildApplet(
450
455
 
451
456
  if (cssOutput) {
452
457
  // Scope every rule to the applet's mount container (`[data-applet=
453
- // "<kind>:<name>"]`, see applet-css.ts) so the bundle's Tailwind never
458
+ // "<widgets|views>/<name>"]`, see applet-css.ts) so the bundle's Tailwind never
454
459
  // leaks into the host page. Kind-namespaced so a widget and a view sharing
455
460
  // a name scope independently.
456
- const css = scopeAppletCss(await cssOutput.text(), `${kind}:${widgetName}`)
461
+ const segment = kind === 'widget' ? 'widgets' : 'views'
462
+ const css = scopeAppletCss(await cssOutput.text(), `${segment}/${widgetName}`)
457
463
  js = injectCss(js, css)
458
464
  }
459
465
 
@@ -0,0 +1,75 @@
1
+ // Public moi contract, reused internally and installed as `.moi/base.d.ts`.
2
+ // Editor/`tsc` only — the moi bundler needs no declarations.
3
+
4
+ declare module 'moi' {
5
+ export type JsonValue =
6
+ | null
7
+ | boolean
8
+ | number
9
+ | string
10
+ | JsonValue[]
11
+ | { [key: string]: JsonValue }
12
+
13
+ // Resolve moi:/views/..., moi:/files/... or an HTTP(S) address for the browser.
14
+ // moi addresses become root-relative URLs using the current page's origin.
15
+ // Workspace files use the server's media/asset stream.
16
+ export function resolveUrl(url: string): string
17
+ // Navigate to a workspace page, file, or HTTP(S) address in the current tab.
18
+ // Workspace pages add browser history; their query strings become view params.
19
+ export function navigate(url: string): void
20
+ export type AttachmentInput =
21
+ | { type: 'text'; label: string; text: string }
22
+ | { type: 'file'; file: File; path?: never }
23
+ | { type: 'file'; path: string; file?: never }
24
+ // Stage an attachment in the current chat draft; does not send a message.
25
+ export function addChatAttachment(input: AttachmentInput): void
26
+ // Prepare optional attachments and send to the active chat without changing
27
+ // its draft. Call from event handlers; each call starts an agent run and is
28
+ // rate-limited. Preparation failure or navigation cancels the whole send.
29
+ export type ChatMessageInput = { message: string; attachments?: AttachmentInput[] }
30
+ export function sendChatMessage(input: ChatMessageInput): void
31
+ export type WidgetConfig = {
32
+ rowSpan: 1 | 2 | 3 | 4
33
+ colSpan: 1 | 2 | 3 | 4
34
+ // Advisory env hints for server functions; never blocks loading.
35
+ requiredEnv?: string[]
36
+ }
37
+ export type ViewConfig = {
38
+ // Nav tab label; defaults to the file name.
39
+ title?: string
40
+ // App icon registry id used by workspace tabs.
41
+ icon?: string
42
+ // Advisory env hints for server functions; never blocks loading.
43
+ requiredEnv?: string[]
44
+ }
45
+ }
46
+
47
+ // Bundled asset imports (`import logo from './logo.png'`) resolve to a URL string.
48
+ declare module '*.png' {
49
+ const s: string
50
+ export default s
51
+ }
52
+ declare module '*.jpg' {
53
+ const s: string
54
+ export default s
55
+ }
56
+ declare module '*.jpeg' {
57
+ const s: string
58
+ export default s
59
+ }
60
+ declare module '*.gif' {
61
+ const s: string
62
+ export default s
63
+ }
64
+ declare module '*.webp' {
65
+ const s: string
66
+ export default s
67
+ }
68
+ declare module '*.avif' {
69
+ const s: string
70
+ export default s
71
+ }
72
+ declare module '*.svg' {
73
+ const s: string
74
+ export default s
75
+ }
@@ -0,0 +1,88 @@
1
+ // Public collab contract, reused internally and installed as `.moi/collab.d.ts`.
2
+ declare module 'moi/collab' {
3
+ import type { ReactElement, ReactNode } from 'react'
4
+ import type { JsonValue } from 'moi'
5
+
6
+ export type UserColor =
7
+ | 'pink'
8
+ | 'orange'
9
+ | 'amber'
10
+ | 'lime'
11
+ | 'emerald'
12
+ | 'cyan'
13
+ | 'blue'
14
+ | 'violet'
15
+ export type UserProfile = {
16
+ id: string
17
+ color: UserColor
18
+ name?: string
19
+ email?: string
20
+ avatar?: string
21
+ }
22
+ export type ConnectionStatus = 'active' | 'away'
23
+ export type UserStatus = ConnectionStatus | 'offline'
24
+ export type WorkspaceUser = UserProfile & { status: UserStatus }
25
+ export type UsePeersOptions = { scope?: 'page' | 'workspace'; status?: ConnectionStatus }
26
+ export type UseWorkspaceUsersOptions = { status?: UserStatus }
27
+
28
+ // Peers are connected users, deduplicated across tabs, excluding your own user.
29
+ export function useMe(): WorkspaceUser | undefined
30
+ export function useUser(id: string): WorkspaceUser | undefined
31
+ export function usePeers(options?: UsePeersOptions): WorkspaceUser[]
32
+ // Full workspace directory, including your own user and offline users.
33
+ export function useWorkspaceUsers(options?: UseWorkspaceUsersOptions): WorkspaceUser[]
34
+
35
+ export type PresenceValue<T> = { connectionId: string; userId: string; value: T }
36
+ // Reading never registers or publishes presence. Values belong to connections.
37
+ export function usePresence<T extends JsonValue>(channel: string): PresenceValue<T>[]
38
+ // Publishes the current value reactively, releasing it on hide or unmount.
39
+ export function usePublishPresence<T extends JsonValue>(channel: string, value: T): void
40
+
41
+ // Identifies a cursor area within the applet; defaults to 'default'.
42
+ export type CursorsProps = { id?: string; children: ReactNode; className?: string }
43
+ export function Cursors(props: CursorsProps): ReactElement
44
+
45
+ // Stable local IDs compose with enclosing PresenceGroup IDs across browsers.
46
+ // Without present, each wrapper tracks focus anywhere inside its children.
47
+ // With present, publication is controlled; false clears your presence, not peers.
48
+ export type PresenceFrameProps = {
49
+ id: string
50
+ present?: boolean
51
+ // Name badge alignment above the frame. Defaults to 'end'.
52
+ align?: 'start' | 'end'
53
+ children: ReactNode
54
+ className?: string
55
+ }
56
+ export function PresenceFrame(props: PresenceFrameProps): ReactElement
57
+ export type PresenceAvatarsProps = Omit<PresenceFrameProps, 'align'> & {
58
+ // Vertical alignment in the left gutter. Defaults to 'center'.
59
+ align?: 'start' | 'center' | 'end'
60
+ }
61
+ export function PresenceAvatars(props: PresenceAvatarsProps): ReactElement
62
+ // Adds a namespace and a local gutter animation group; no DOM or publication.
63
+ export type PresenceGroupProps = { id: string; children: ReactNode }
64
+ export function PresenceGroup(props: PresenceGroupProps): ReactElement
65
+ export type UserAvatarProps = {
66
+ id: string
67
+ size?: 'xs' | 'sm' | 'default' | 'lg'
68
+ // Show a status dot when active. Defaults to false.
69
+ showStatusBadge?: boolean
70
+ className?: string
71
+ }
72
+ export function UserAvatar(props: UserAvatarProps): ReactElement
73
+ export type UserProps = Pick<UserAvatarProps, 'id' | 'showStatusBadge' | 'className'> & {
74
+ size?: 'xs' | 'sm' | 'default'
75
+ // Show a "(You)" label beside the current user's name. Defaults to false.
76
+ showYouLabel?: boolean
77
+ // Secondary text alongside or below the name.
78
+ description?: ReactNode
79
+ }
80
+ export function User(props: UserProps): ReactElement
81
+ export type UserAvatarGroupProps = {
82
+ ids: readonly string[]
83
+ max?: number
84
+ size?: UserAvatarProps['size']
85
+ className?: string
86
+ }
87
+ export function UserAvatarGroup(props: UserAvatarGroupProps): ReactElement
88
+ }
@@ -0,0 +1,46 @@
1
+ import { mkdir, stat } from 'node:fs/promises'
2
+ import { dirname, join } from 'node:path'
3
+
4
+ export const BASE_DECLARATION_SOURCE_PATH = join(import.meta.dir, 'declarations', 'base.d.ts')
5
+ export const COLLAB_DECLARATION_SOURCE_PATH = join(import.meta.dir, 'declarations', 'collab.d.ts')
6
+
7
+ export type AppletDeclarationFile = 'base.d.ts' | 'collab.d.ts'
8
+
9
+ export function appletDeclarationPath(workspacePath: string, file: AppletDeclarationFile): string {
10
+ return join(workspacePath, '.moi', file)
11
+ }
12
+
13
+ async function writeDeclaration(
14
+ workspacePath: string,
15
+ file: AppletDeclarationFile
16
+ ): Promise<boolean> {
17
+ const sourcePath = join(import.meta.dir, 'declarations', file)
18
+ const targetPath = appletDeclarationPath(workspacePath, file)
19
+ const contents = await Bun.file(sourcePath).text()
20
+ const target = Bun.file(targetPath)
21
+ if ((await target.exists()) && (await target.text()) === contents) return false
22
+ await mkdir(dirname(targetPath), { recursive: true })
23
+ await Bun.write(targetPath, contents)
24
+ return true
25
+ }
26
+
27
+ export async function syncAppletDeclarations(
28
+ workspacePath: string
29
+ ): Promise<AppletDeclarationFile[]> {
30
+ const moiDir = join(workspacePath, '.moi')
31
+ if (!(await stat(moiDir).catch(() => null))?.isDirectory()) return []
32
+
33
+ const updated: AppletDeclarationFile[] = []
34
+ if (await writeDeclaration(workspacePath, 'base.d.ts')) updated.push('base.d.ts')
35
+
36
+ // Only an explicit collab install creates this optional declaration.
37
+ if (await Bun.file(appletDeclarationPath(workspacePath, 'collab.d.ts')).exists()) {
38
+ if (await writeDeclaration(workspacePath, 'collab.d.ts')) updated.push('collab.d.ts')
39
+ }
40
+ return updated
41
+ }
42
+
43
+ export async function installCollabDeclaration(workspacePath: string): Promise<void> {
44
+ await writeDeclaration(workspacePath, 'base.d.ts')
45
+ await writeDeclaration(workspacePath, 'collab.d.ts')
46
+ }
@@ -10,7 +10,7 @@
10
10
  // images/fonts). The client dynamic-imports that entry at `<name>/module` — an
11
11
  // extensionless alias, see `ENTRY_ROUTE_FILE` — and assets and chunks resolve
12
12
  // module-relative from there. `.js` files carry the
13
- // `%%MOI_APPLET_API_BASE%%` sentinel (for RPC + `fileUrl`), swapped to the real
13
+ // `%%MOI_APPLET_API_BASE%%` sentinel (for RPC + file resolution), swapped to the real
14
14
  // `/api/workspaces/<id>` base when served — so the on-disk bundle is
15
15
  // workspace-agnostic.
16
16
  import { realpathSync, statSync } from 'node:fs'
@@ -20,7 +20,7 @@ import { join, resolve, sep } from 'path'
20
20
  import { analyzeDependencies, resolveSource, scanSources } from './dependencies'
21
21
  import type { AppletKind } from './build-applet'
22
22
  import { buildAppletsInChild } from './build-worker'
23
- import { APPLET_API_BASE_SENTINEL } from './runtime/base'
23
+ import { APPLET_API_BASE_SENTINEL } from './api-base'
24
24
  import { pruneAppletThumbnails } from '../thumbnails'
25
25
 
26
26
  export { scanSources } from './dependencies'
@@ -137,7 +137,7 @@ const HASHED_FILE_RE = /^chunk-[0-9a-z]+\.\w+$|-[0-9a-f]{6,}\.\w+$/i
137
137
  // Serve one file from a compiled applet directory: the `index.js` entry, a code
138
138
  // chunk, or a bundled asset. `apiBase` is the workspace's `/api/workspaces/<id>`
139
139
  // prefix — substituted for the build-time sentinel in every `.js` so RPC and
140
- // `fileUrl` calls hit the right workspace. Assets stream untouched.
140
+ // file addresses resolved by `resolveUrl` hit the right workspace. Assets stream untouched.
141
141
  //
142
142
  // `file` is the ON-DISK name (the route's extensionless entry alias is already
143
143
  // mapped back to `index.js` by `parseAppletTail`), so the content-type and
@@ -197,11 +197,11 @@ export async function serveApplet(
197
197
  }
198
198
 
199
199
  // ---- route helpers ----------------------------------------------------------
200
- // Pure helpers behind the applet/fs/rpc HTTP routes, kept here (not web.ts) so
200
+ // Pure helpers behind the applet/files/rpc HTTP routes, kept here (not web.ts) so
201
201
  // they're unit-testable without importing web.ts — which binds ports on load.
202
202
 
203
- // The API base a served bundle's sentinel is rewritten to. RPC + `fileUrl`
204
- // hang off it, matching what the compiled `rpc()` / `fileUrl()` prepend.
203
+ // The API base a served bundle's sentinel is rewritten to. RPC and workspace
204
+ // file addresses resolved by `resolveUrl()` use this prefix.
205
205
  export function apiBaseFor(id: string): string {
206
206
  return `/api/workspaces/${id}`
207
207
  }
@@ -251,13 +251,13 @@ export function parseAppletTail(
251
251
  }
252
252
  }
253
253
 
254
- // Extensions `fileUrl()` may stream from the workspace. Media + image/doc
254
+ // Extensions served for `moi:/files/...` addresses. Media + image/doc
255
255
  // assets only — deliberately excludes text/data (`.json`, `.env`, `.md`,
256
256
  // source) so the route can't be used to exfiltrate arbitrary workspace data.
257
257
  const FS_MEDIA_RE =
258
258
  /\.(mp4|webm|mov|m4v|mkv|mp3|wav|ogg|oga|m4a|flac|aac|opus|png|jpe?g|gif|webp|avif|svg|ico|pdf|vtt|srt)$/i
259
259
 
260
- // Resolve a `/fs/`-style tail to a real on-disk path inside the workspace root,
260
+ // Resolve a `/files/`-style tail to a real on-disk path inside the workspace root,
261
261
  // or an error Response. Hard guards (defense in depth): reject empty/`.`/`..`/
262
262
  // dotfile segments and anything resolving outside the root, and require a media
263
263
  // extension. The workspace holds secrets (`.env`, `.moi/`) and the routes built
@@ -0,0 +1,94 @@
1
+ // Browser-only runtime. State and React contexts belong to the host feature.
2
+ import { createElement } from 'react'
3
+ import type { JsonValue } from 'moi'
4
+ import type {
5
+ CursorsProps,
6
+ UserAvatarGroupProps,
7
+ PresenceFrameProps,
8
+ PresenceGroupProps,
9
+ PresenceAvatarsProps,
10
+ PresenceValue,
11
+ UserProps,
12
+ UserAvatarProps,
13
+ UsePeersOptions,
14
+ UseWorkspaceUsersOptions
15
+ } from 'moi/collab'
16
+ import type { AppletCollabApi } from '../../../client/features/collab/applet-api'
17
+
18
+ import { __getBridge } from './moi'
19
+
20
+ type Bridge = { readonly collab?: AppletCollabApi }
21
+
22
+ function empty(): never[] {
23
+ return []
24
+ }
25
+ const nothing = () => null
26
+ const fallback = {
27
+ useMe: () => undefined,
28
+ useUser: () => undefined,
29
+ usePeers: empty,
30
+ useWorkspaceUsers: empty,
31
+ usePresence<T extends JsonValue>(_channel: string): PresenceValue<T>[] {
32
+ return []
33
+ },
34
+ usePublishPresence() {},
35
+ Cursors: nothing,
36
+ User: nothing,
37
+ UserAvatar: nothing,
38
+ UserAvatarGroup: nothing,
39
+ PresenceFrame: nothing,
40
+ PresenceGroup: nothing,
41
+ PresenceAvatars: nothing
42
+ }
43
+ let warned = false
44
+ function api() {
45
+ const collab = (__getBridge() as Bridge | null)?.collab
46
+ if (collab) return collab
47
+ if (!warned) {
48
+ warned = true
49
+ console.warn(
50
+ '[moi/collab] Collaboration API is unavailable. Hooks return empty values and components render nothing.'
51
+ )
52
+ }
53
+ return fallback
54
+ }
55
+
56
+ export function useMe() {
57
+ return api().useMe()
58
+ }
59
+ export function usePeers(options?: UsePeersOptions) {
60
+ return api().usePeers(options)
61
+ }
62
+ export function useUser(id: string) {
63
+ return api().useUser(id)
64
+ }
65
+ export function useWorkspaceUsers(options?: UseWorkspaceUsersOptions) {
66
+ return api().useWorkspaceUsers(options)
67
+ }
68
+ export function usePresence<T extends JsonValue>(channel: string) {
69
+ return api().usePresence<T>(channel)
70
+ }
71
+ export function usePublishPresence<T extends JsonValue>(channel: string, value: T) {
72
+ return api().usePublishPresence(channel, value)
73
+ }
74
+ export function Cursors(props: CursorsProps) {
75
+ return createElement(api().Cursors, props)
76
+ }
77
+ export function User(props: UserProps) {
78
+ return createElement(api().User, props)
79
+ }
80
+ export function UserAvatar(props: UserAvatarProps) {
81
+ return createElement(api().UserAvatar, props)
82
+ }
83
+ export function UserAvatarGroup(props: UserAvatarGroupProps) {
84
+ return createElement(api().UserAvatarGroup, props)
85
+ }
86
+ export function PresenceFrame(props: PresenceFrameProps) {
87
+ return createElement(api().PresenceFrame, props)
88
+ }
89
+ export function PresenceGroup(props: PresenceGroupProps) {
90
+ return createElement(api().PresenceGroup, props)
91
+ }
92
+ export function PresenceAvatars(props: PresenceAvatarsProps) {
93
+ return createElement(api().PresenceAvatars, props)
94
+ }