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
@@ -2,9 +2,12 @@
2
2
  // `moi openclaw init`). Creates `.moi/widgets/`, writes the widget
3
3
  // dependency manifest, and installs dependencies — so the agent never has to
4
4
  // bootstrap the folder itself.
5
- import { mkdir, stat } from 'node:fs/promises'
5
+ import { appendFile, mkdir, open, stat } from 'node:fs/promises'
6
+ import { tmpdir } from 'node:os'
6
7
  import { join, resolve, sep } from 'node:path'
7
8
 
9
+ import { syncAppletDeclarations } from './applets/declarations'
10
+
8
11
  // Dependency set available to widgets. `react`/`react-dom` are stubs — at
9
12
  // runtime they resolve to moi's locally-vendored ESM via the browser importmap
10
13
  // (/vendor/react); they're listed so editors pick up the correct types.
@@ -38,23 +41,51 @@ export const MOI_PACKAGE_JSON = {
38
41
  const INSTALL_WAIT_MS = 10_000
39
42
  const INSTALL_TIMEOUT_MS = 120_000
40
43
 
41
- type InstallDependencies = (moiDir: string) => Promise<number>
44
+ type InstallDependencies = (moiDir: string, logPath: string) => Promise<number>
45
+
46
+ export function createDependencyInstallLogPath(): string {
47
+ return join(tmpdir(), `moi-bun-install-${crypto.randomUUID()}.log`)
48
+ }
42
49
 
43
- async function runBunInstall(moiDir: string): Promise<number> {
44
- const install = Bun.spawn(['bun', 'install'], {
45
- cwd: moiDir,
46
- stdout: 'ignore',
47
- stderr: 'inherit',
48
- timeout: INSTALL_TIMEOUT_MS,
49
- killSignal: 'SIGKILL'
50
- })
51
- // Don't hold the event loop open for a backgrounded install: a short-lived
52
- // CLI (`moi init`) must exit after the wait, not linger until the child
53
- // does. The child survives parent exit and finishes the install on its own
54
- // (verified: orphaned bun processes complete; only the 2-minute kill is no
55
- // longer enforced once the parent is gone).
50
+ async function runBunInstall(moiDir: string, logPath: string): Promise<number> {
51
+ const log = await open(logPath, 'wx', 0o600)
52
+ let install: Bun.Subprocess<'ignore', number, number>
53
+ try {
54
+ await log.writeFile(
55
+ `bun install started at ${new Date().toISOString()}\nWorking directory: ${moiDir}\n\n`
56
+ )
57
+ install = Bun.spawn(['bun', 'install'], {
58
+ cwd: moiDir,
59
+ stdin: 'ignore',
60
+ // Direct file descriptors keep capturing both streams after a
61
+ // short-lived CLI exits; parent-owned pipes would lose that output.
62
+ stdout: log.fd,
63
+ stderr: log.fd
64
+ })
65
+ } catch (err) {
66
+ await log.writeFile(
67
+ `\nbun install error: ${err instanceof Error ? err.message : String(err)}\n`
68
+ )
69
+ return 1
70
+ } finally {
71
+ // The child owns duplicated descriptors now. Closing the parent's handle
72
+ // also lets a short-lived CLI exit while the install is still running.
73
+ await log.close()
74
+ }
75
+ // Bun.spawn's built-in timeout keeps the parent alive even after unref().
76
+ // Unref both the child and our timer so a short-lived CLI can exit after
77
+ // its brief wait. The timeout still applies while the parent is running;
78
+ // after parent exit the orphaned install finishes on its own.
79
+ const timeout = setTimeout(() => install.kill('SIGKILL'), INSTALL_TIMEOUT_MS)
80
+ timeout.unref()
56
81
  install.unref()
57
- return install.exited
82
+ try {
83
+ const code = await install.exited
84
+ await appendFile(logPath, `\nbun install exited with code ${code}\n`)
85
+ return code
86
+ } finally {
87
+ clearTimeout(timeout)
88
+ }
58
89
  }
59
90
 
60
91
  // Keep machine-local state out of workspaces that are git repos: build output,
@@ -87,69 +118,6 @@ export async function ensureMoiGitignore(workspacePath: string): Promise<void> {
87
118
  await Bun.write(path, `${text.replace(/\n*$/, '\n')}${missing.join('\n')}\n`)
88
119
  }
89
120
 
90
- // Ambient types for applets (widgets & views). Editor DX only — the moi
91
- // bundler provides the `moi` module and asset imports at build time without any
92
- // declarations. Lives at `.moi/` root, NOT inside widgets/views, so it isn't
93
- // picked up by the `.ts` build glob and compiled as an applet.
94
- export const APPLET_ENV_DTS = `// Auto-generated by \`moi init\`. Ambient types for widgets & views.
95
- // Editor/\`tsc\` only — the moi bundler needs no declarations.
96
-
97
- declare module 'moi' {
98
- // Absolute URL to a workspace file, streamed by the server. Pass a
99
- // workspace-relative path (e.g. 'clips/001.mp4'). Media/asset files only.
100
- export function fileUrl(path: string): string
101
- // Navigate within this workspace. Query strings are delivered as view params.
102
- // Navigation adds a browser history entry. Include view params in the URL.
103
- export function navigate(href: string): void
104
- // Resolve a portable moi:/ address to a real browser href for an anchor.
105
- export function resolveHref(href: string): string
106
- export type AttachmentInput =
107
- | { type: 'text'; label: string; text: string }
108
- | { type: 'file'; file: File; path?: never }
109
- | { type: 'file'; path: string; file?: never }
110
- // Stage an attachment in the current chat draft; does not send a message.
111
- export function addChatAttachment(input: AttachmentInput): void
112
- // Prepare optional attachments and send to the active chat without changing
113
- // its draft. Call from event handlers; each call starts an agent run and is
114
- // rate-limited. Preparation failure or navigation cancels the whole send.
115
- export function sendChatMessage(input: { message: string; attachments?: AttachmentInput[] }): void
116
- export type WidgetConfig = {
117
- rowSpan: 1 | 2 | 3 | 4
118
- colSpan: 1 | 2 | 3 | 4
119
- requiredEnv?: string[]
120
- }
121
- export type ViewConfig = { title?: string; icon?: string; requiredEnv?: string[] }
122
- }
123
-
124
- // Bundled asset imports (\`import logo from './logo.png'\`) resolve to a URL string.
125
- declare module '*.png' { const s: string; export default s }
126
- declare module '*.jpg' { const s: string; export default s }
127
- declare module '*.jpeg' { const s: string; export default s }
128
- declare module '*.gif' { const s: string; export default s }
129
- declare module '*.webp' { const s: string; export default s }
130
- declare module '*.avif' { const s: string; export default s }
131
- declare module '*.svg' { const s: string; export default s }
132
- `
133
-
134
- // Write `.moi/applet-env.d.ts` from the template this CLI ships, overwriting
135
- // whatever is there. The file is auto-generated and declares the `moi` module's
136
- // public API, so it drifts the moment the CLI grows an applet-facing function
137
- // (`navigate`, `sendChatMessage`) while a workspace keeps the copy written at
138
- // `moi init` time — leaving the agent's editor and `tsc` insisting a real API
139
- // doesn't exist. Regenerated alongside skills, the other agent-facing contract
140
- // moi ships. Refreshes an existing `.moi/` only — never creates one, so a
141
- // directory that was never scaffolded doesn't sprout a `.moi/` holding nothing
142
- // but a declaration file. Returns whether it wrote.
143
- export async function writeAppletEnvDts(workspacePath: string): Promise<boolean> {
144
- const moiDir = join(workspacePath, '.moi')
145
- if (!(await isDirectory(moiDir))) return false
146
- const path = join(moiDir, 'applet-env.d.ts')
147
- const file = Bun.file(path)
148
- if ((await file.exists()) && (await file.text()) === APPLET_ENV_DTS) return false
149
- await Bun.write(path, APPLET_ENV_DTS)
150
- return true
151
- }
152
-
153
121
  async function isDirectory(path: string): Promise<boolean> {
154
122
  try {
155
123
  return (await stat(path)).isDirectory()
@@ -166,7 +134,8 @@ async function isDirectory(path: string): Promise<boolean> {
166
134
  export async function scaffoldMoiDir(
167
135
  workspacePath: string,
168
136
  installDependencies: InstallDependencies = runBunInstall,
169
- installWaitMs: number = INSTALL_WAIT_MS
137
+ installWaitMs: number = INSTALL_WAIT_MS,
138
+ installLogPath: string = createDependencyInstallLogPath()
170
139
  ): Promise<'exists' | 'installing' | number> {
171
140
  // Backstop against the nested-workspace bug: never scaffold a `.moi/` *inside*
172
141
  // another workspace's `.moi/` (which produces the junk `.moi/.moi`). Callers
@@ -192,9 +161,9 @@ export async function scaffoldMoiDir(
192
161
  await mkdir(join(moiDir, 'widgets'), { recursive: true })
193
162
  await Bun.write(packagePath, JSON.stringify(MOI_PACKAGE_JSON, null, 2) + '\n')
194
163
  await ensureMoiGitignore(workspacePath)
195
- await writeAppletEnvDts(workspacePath)
164
+ await syncAppletDeclarations(workspacePath)
196
165
 
197
- const exited = installDependencies(moiDir)
166
+ const exited = installDependencies(moiDir, installLogPath)
198
167
  let timer: ReturnType<typeof setTimeout> | undefined
199
168
  const result = await Promise.race([
200
169
  exited,
@@ -203,12 +172,14 @@ export async function scaffoldMoiDir(
203
172
  clearTimeout(timer)
204
173
 
205
174
  if (result === 'installing') {
206
- console.log(`[scaffold] bun install in ${moiDir} still running — continuing in the background`)
175
+ console.log(
176
+ `[scaffold] bun install in ${moiDir} still running — continuing in the background; log: ${installLogPath}`
177
+ )
207
178
  exited.then(code => {
208
179
  if (code === 0) console.log(`[scaffold] background bun install in ${moiDir} finished`)
209
180
  else
210
181
  console.warn(
211
- `[scaffold] background bun install in ${moiDir} failed (exit ${code}) — the agent will install deps on demand`
182
+ `[scaffold] background bun install in ${moiDir} failed (exit ${code}) — the agent will install deps on demand; log: ${installLogPath}`
212
183
  )
213
184
  })
214
185
  }
package/server/preview.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  // Backs GET /api/workspaces/:id/preview/<path>, used by the chat's expanded
4
4
  // tool rows: when the agent `Read`s an image from the workspace, the row shows
5
5
  // the actual picture instead of just the path. Same hard guards as the raw
6
- // `/fs/` stream (resolveWorkspaceMediaFile), but scoped to image extensions and
6
+ // `/files/` stream (resolveWorkspaceMediaFile), but scoped to image extensions and
7
7
  // resized server-side so a huge screenshot doesn't ship megabytes to render a
8
8
  // 300px-tall preview.
9
9
  //
@@ -1,6 +1,7 @@
1
1
  import type { WorkspaceSkillsStatus, WorkspaceSkillStatus, WorkspaceType } from '@/lib/types'
2
2
 
3
- import { writeAppletEnvDts } from './moi-scaffold'
3
+ import type { AppletDeclarationFile } from './applets/declarations'
4
+ import { syncAppletDeclarations } from './applets/declarations'
4
5
  import { isBehind, skillStatuses } from './skill-version'
5
6
  import { installBundledSkills } from './skills-template'
6
7
  import { skillsDirFor } from './workspace-init'
@@ -9,8 +10,7 @@ export type WorkspaceSkillUpdateResult = {
9
10
  before: WorkspaceSkillStatus[]
10
11
  status: WorkspaceSkillsStatus
11
12
  changedSkills: string[]
12
- // False when the workspace has no `.moi/` to refresh — nothing was written.
13
- appletTypesWritten: boolean
13
+ updatedAppletTypes: AppletDeclarationFile[]
14
14
  }
15
15
 
16
16
  export function summarizeSkillStatuses(skills: WorkspaceSkillStatus[]): WorkspaceSkillsStatus {
@@ -33,17 +33,15 @@ export async function updateWorkspaceSkills(
33
33
  ): Promise<WorkspaceSkillUpdateResult> {
34
34
  const before = await skillStatuses(workspaceRoot, type)
35
35
  const changedSkills = await installBundledSkills(skillsDirFor(workspaceRoot, type))
36
- // The ambient applet types ship with the CLI just like the skills do, and go
37
- // stale the same way — refresh both in one operation so `moi skill update`
38
- // (and the UI's update button) leaves nothing behind. Skipped when the
39
- // workspace has no `.moi/`: skills stand on their own, applet types don't.
40
- const appletTypesWritten = await writeAppletEnvDts(workspaceRoot)
36
+ // Applet declarations ship with the CLI, so refresh installed copies along
37
+ // with skills. The optional collab declaration is only updated if present.
38
+ const updatedAppletTypes = await syncAppletDeclarations(workspaceRoot)
41
39
  const skills = await skillStatuses(workspaceRoot, type)
42
40
 
43
41
  return {
44
42
  before,
45
43
  status: summarizeSkillStatuses(skills),
46
44
  changedSkills,
47
- appletTypesWritten
45
+ updatedAppletTypes
48
46
  }
49
47
  }
@@ -14,6 +14,18 @@ export const TEMPLATE_DIR = join(import.meta.dir, '..', 'workspace')
14
14
  // for what `moi skill update` copies and what versions it compares against.
15
15
  export const BUNDLED_SKILLS_DIR = join(TEMPLATE_DIR, '.claude', 'skills')
16
16
 
17
+ export const COLLAB_REFERENCE_SOURCE_PATH = join(
18
+ BUNDLED_SKILLS_DIR,
19
+ 'moi-workspace',
20
+ 'references',
21
+ 'COLLAB.md'
22
+ )
23
+
24
+ // The guide lives beside the other references, but only explicit collab init installs it.
25
+ function isDefaultSkillFile(source: string): boolean {
26
+ return source !== COLLAB_REFERENCE_SOURCE_PATH
27
+ }
28
+
17
29
  async function matchesBundledPath(source: string, target: string): Promise<boolean> {
18
30
  const sourceStat = await lstat(source)
19
31
  const targetStat = await lstat(target).catch(() => null)
@@ -21,7 +33,7 @@ async function matchesBundledPath(source: string, target: string): Promise<boole
21
33
 
22
34
  if (sourceStat.isDirectory()) {
23
35
  if (!targetStat.isDirectory()) return false
24
- const entries = await readdir(source)
36
+ const entries = (await readdir(source)).filter(entry => isDefaultSkillFile(join(source, entry)))
25
37
  const matches = await Promise.all(
26
38
  entries.map(entry => matchesBundledPath(join(source, entry), join(target, entry)))
27
39
  )
@@ -62,7 +74,7 @@ export async function installBundledSkills(targetSkillsDir: string): Promise<str
62
74
  const target = join(targetSkillsDir, entry.name)
63
75
  if (await matchesBundledPath(source, target)) continue
64
76
 
65
- await cp(source, target, { recursive: true, force: true })
77
+ await cp(source, target, { recursive: true, force: true, filter: isDefaultSkillFile })
66
78
  changedSkills.push(entry.name)
67
79
  }
68
80
 
package/server/web.ts CHANGED
@@ -1,13 +1,18 @@
1
+ import type { UserProfile } from '@/lib/collab/types'
1
2
  import { isMessageAttachments } from '@/lib/message-attachments'
2
3
  import type { ClientMessage, StatusSnapshotMessage } from '@/lib/types'
3
- import { isMoiContext } from '@/lib/moi-context'
4
+ import { isMoiContext, type MoiContext } from '@/lib/moi-context'
4
5
 
5
6
  import index from '../client/index.html'
6
7
  import { api } from './api'
7
8
  import { AttachmentUploadError } from './attachment-message'
8
9
  import { PORT } from './constants'
9
10
  import { control } from './control'
10
- import { EVENTS_TOPIC, publishEvent, setEventServer } from './events'
11
+ import { proxyUserState } from './collab/cloudflare-access'
12
+ import { getCollabReferencePath, isCollabEnabled } from './collab/config'
13
+ import { selectChatSession } from './chat-selection'
14
+ import { collabManager } from './collab/manager'
15
+ import { EVENTS_TOPIC, setEventServer } from './events'
11
16
  import { killBuildWorkers } from './applets/build-worker'
12
17
  import { killAllWorkers } from './functions'
13
18
  import { startScratchpadSweeper } from './scratchpad'
@@ -15,7 +20,6 @@ import { navigationRelay } from './navigation-relay'
15
20
  import { resolveScratchOp } from './scratchpad-relay'
16
21
  import { allHarnesses, harnessFor } from './harness/registry'
17
22
  import { getWorkspace } from './registry'
18
- import { saveSelectedSession } from './selected-session'
19
23
  import {
20
24
  addClient,
21
25
  broadcast,
@@ -29,7 +33,13 @@ import { distShell, prebuilt } from './static'
29
33
  import { renderStatus } from './status'
30
34
  import { serveVendorEmojibase, serveVendorReact } from './vendor'
31
35
 
32
- type WsData = { channel: 'chat' | 'events'; workspaceId: string }
36
+ type WsData = {
37
+ channel: 'chat' | 'events' | 'collab'
38
+ workspaceId: string
39
+ workspacePath?: string
40
+ // The collab profile a proxy (Cloudflare Access) verified for the upgrade.
41
+ verifiedProfile?: UserProfile
42
+ }
33
43
 
34
44
  function isClientMessage(value: unknown): value is ClientMessage {
35
45
  if (typeof value !== 'object' || value === null || !('type' in value)) return false
@@ -39,6 +49,7 @@ function isClientMessage(value: unknown): value is ClientMessage {
39
49
  sessionId?: unknown
40
50
  content?: unknown
41
51
  isNew?: unknown
52
+ selectedSessionScope?: unknown
42
53
  optimisticId?: unknown
43
54
  model?: unknown
44
55
  effort?: unknown
@@ -54,6 +65,9 @@ function isClientMessage(value: unknown): value is ClientMessage {
54
65
  typeof v.content === 'string' &&
55
66
  typeof v.sessionId === 'string' &&
56
67
  typeof v.isNew === 'boolean' &&
68
+ (v.selectedSessionScope === undefined ||
69
+ v.selectedSessionScope === 'shared' ||
70
+ v.selectedSessionScope === 'browser-tab') &&
57
71
  (v.optimisticId === undefined || typeof v.optimisticId === 'string') &&
58
72
  (v.model === undefined || typeof v.model === 'string') &&
59
73
  (v.effort === undefined || typeof v.effort === 'string') &&
@@ -129,14 +143,38 @@ export const app = Bun.serve<WsData>({
129
143
  // routes it ahead of the Hono-served `/api/workspaces/:id`; the upgrade
130
144
  // happens in-handler via the route's `server` argument.
131
145
  '/api/workspaces/ws': (req: Request, server: Bun.Server<WsData>) =>
132
- upgrade(server, req, { channel: 'events', workspaceId: '' })
146
+ upgrade(server, req, { channel: 'events', workspaceId: '' }),
147
+
148
+ '/api/workspaces/:id/collab/ws': async (req: Request, server: Bun.Server<WsData>) => {
149
+ const workspaceId = decodeURIComponent(new URL(req.url).pathname.split('/')[3] ?? '')
150
+ const workspace = await getWorkspace(workspaceId)
151
+ if (!workspace) return new Response('Workspace not found', { status: 404 })
152
+ if (!isCollabEnabled()) {
153
+ return new Response('Collab is not enabled for this workspace', { status: 403 })
154
+ }
155
+ // Behind Cloudflare Access, presence is joined only as the verified viewer.
156
+ const { provider, profile } = await proxyUserState(req)
157
+ if (provider && !profile) {
158
+ return new Response('Sign in through Cloudflare Access to join', { status: 401 })
159
+ }
160
+ return upgrade(server, req, {
161
+ channel: 'collab',
162
+ workspaceId,
163
+ workspacePath: workspace.path,
164
+ ...(profile ? { verifiedProfile: profile } : {})
165
+ })
166
+ }
133
167
  },
134
168
  // Anything not matched above (the whole HTTP API + prod static assets + 404)
135
169
  // is handled by Hono.
136
170
  fetch: req => api.fetch(req),
137
171
  websocket: {
138
172
  open(ws) {
139
- if (ws.data.channel === 'chat') {
173
+ if (ws.data.channel === 'collab') {
174
+ if (ws.data.workspacePath)
175
+ collabManager.open(ws, ws.data.workspacePath, ws.data.verifiedProfile)
176
+ else ws.close(1008, 'Missing workspace')
177
+ } else if (ws.data.channel === 'chat') {
140
178
  addClient(ws)
141
179
  // Authoritative snapshot of every non-idle session across all
142
180
  // harnesses so the client can light/clear spinners correctly even for
@@ -147,6 +185,10 @@ export const app = Bun.serve<WsData>({
147
185
  }
148
186
  },
149
187
  async message(ws, message) {
188
+ if (ws.data.channel === 'collab') {
189
+ collabManager.message(ws, message)
190
+ return
191
+ }
150
192
  if (ws.data.channel === 'events') {
151
193
  try {
152
194
  navigationRelay.receive(ws, JSON.parse(String(message)))
@@ -161,15 +203,16 @@ export const app = Bun.serve<WsData>({
161
203
  if (data.type === 'chat' && (data.content?.trim() || data.attachments?.length)) {
162
204
  const workspace = await getWorkspace(data.workspaceId)
163
205
  if (!workspace) return
206
+ const collabReference = await getCollabReferencePath(workspace.path, workspace.type)
207
+ const context: MoiContext | undefined =
208
+ data.context || collabReference
209
+ ? {
210
+ ...(data.context ?? { activeTab: 'agent' }),
211
+ collabReference
212
+ }
213
+ : undefined
164
214
  if (data.isNew) {
165
- const selection = await saveSelectedSession(workspace.path, data.sessionId, null)
166
- if (selection.changed) {
167
- publishEvent({
168
- type: 'selected-session:updated',
169
- workspaceId: workspace.id,
170
- sessionId: selection.sessionId
171
- })
172
- }
215
+ await selectChatSession(workspace, data.sessionId, data.selectedSessionScope, null)
173
216
  }
174
217
  // Harnesses ignore fields they don't support (see SendMessageInput).
175
218
  // Their failures surface internally; attachment resolution happens
@@ -187,7 +230,7 @@ export const app = Bun.serve<WsData>({
187
230
  effort: data.effort,
188
231
  fastMode: data.fastMode,
189
232
  stream: data.stream,
190
- context: data.context,
233
+ context,
191
234
  agentId: workspace.agentId
192
235
  })
193
236
  .catch(error => {
@@ -214,7 +257,8 @@ export const app = Bun.serve<WsData>({
214
257
  } catch {}
215
258
  },
216
259
  close(ws) {
217
- if (ws.data.channel === 'chat') removeClient(ws)
260
+ if (ws.data.channel === 'collab') collabManager.close(ws)
261
+ else if (ws.data.channel === 'chat') removeClient(ws)
218
262
  else {
219
263
  navigationRelay.remove(ws)
220
264
  ws.unsubscribe(EVENTS_TOPIC)
@@ -248,7 +292,10 @@ startServiceLogMaintenance()
248
292
  // changes; in any context Ctrl-C sends SIGINT. Close both servers and kill the
249
293
  // per-workspace function workers and any in-flight applet build child so no
250
294
  // child processes are orphaned.
251
- function shutdown() {
295
+ let shuttingDown = false
296
+ async function shutdown() {
297
+ if (shuttingDown) return
298
+ shuttingDown = true
252
299
  try {
253
300
  app.stop(true)
254
301
  } catch {}
@@ -258,6 +305,7 @@ function shutdown() {
258
305
  for (const h of allHarnesses()) h.shutdown?.()
259
306
  killAllWorkers()
260
307
  killBuildWorkers()
308
+ await collabManager.shutdown()
261
309
  process.exit()
262
310
  }
263
311
  process.on('SIGTERM', shutdown)
@@ -11,7 +11,7 @@ import type { WorkspaceType } from '@/lib/types'
11
11
  export { validateWorkspaceFolderName } from '@/lib/workspace-name'
12
12
 
13
13
  import { harnessFor } from './harness/registry'
14
- import { scaffoldMoiDir } from './moi-scaffold'
14
+ import { createDependencyInstallLogPath, scaffoldMoiDir } from './moi-scaffold'
15
15
  import { installBundledSkills } from './skills-template'
16
16
 
17
17
  // Where each backend loads skills from — the harness owns the answer
@@ -34,6 +34,8 @@ export type ProvisionResult = {
34
34
  // install continues in the background, else the install exit code (non-zero
35
35
  // means deps are missing — not fatal, the agent installs on demand).
36
36
  scaffold: 'exists' | 'installing' | number
37
+ // Unique temporary log for this install attempt; unused when scaffold exists.
38
+ installLogPath: string
37
39
  }
38
40
 
39
41
  // Lay down everything a workspace needs: create the folder, copy the bundled
@@ -47,6 +49,7 @@ export async function provisionWorkspace(
47
49
  const skillsDir = skillsDirFor(workspaceRoot, type)
48
50
  await mkdir(workspaceRoot, { recursive: true })
49
51
  await installBundledSkills(skillsDir)
50
- const scaffold = await scaffoldMoiDir(workspaceRoot)
51
- return { skillsDir, scaffold }
52
+ const installLogPath = createDependencyInstallLogPath()
53
+ const scaffold = await scaffoldMoiDir(workspaceRoot, undefined, undefined, installLogPath)
54
+ return { skillsDir, scaffold, installLogPath }
52
55
  }
@@ -7,14 +7,17 @@ function Avatar({
7
7
  size = 'default',
8
8
  ...props
9
9
  }: AvatarPrimitive.Root.Props & {
10
- size?: 'default' | 'sm' | 'lg'
10
+ size?: 'default' | 'sm' | 'lg' | 'xs'
11
11
  }) {
12
12
  return (
13
13
  <AvatarPrimitive.Root
14
14
  data-slot="avatar"
15
15
  data-size={size}
16
16
  className={cn(
17
- 'group/avatar relative flex size-8 shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:border-border after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 dark:after:mix-blend-lighten',
17
+ 'group/avatar relative isolate flex shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:border-border after:mix-blend-darken data-[size=default]:size-8 data-[size=lg]:size-10 data-[size=sm]:size-6 data-[size=xs]:size-5 dark:after:mix-blend-lighten',
18
+ '[--avatar-badge-size:--spacing(2.5)] data-[size=sm]:[--avatar-badge-size:--spacing(2)] data-[size=xs]:[--avatar-badge-size:--spacing(1.5)]',
19
+ // Cut a transparent gap around the badge in the face and its outline.
20
+ 'has-[>[data-slot=avatar-badge]]:[&::after,&>:where([data-slot=avatar-image],[data-slot=avatar-fallback])]:mask-[radial-gradient(circle_at_calc(100%_-_var(--avatar-badge-size)/2)_calc(100%_-_var(--avatar-badge-size)/2),transparent_calc(var(--avatar-badge-size)/2_+_2px),black_calc(var(--avatar-badge-size)/2_+_2.5px))]',
18
21
  className
19
22
  )}
20
23
  {...props}
@@ -37,7 +40,7 @@ function AvatarFallback({ className, ...props }: AvatarPrimitive.Fallback.Props)
37
40
  <AvatarPrimitive.Fallback
38
41
  data-slot="avatar-fallback"
39
42
  className={cn(
40
- 'flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs',
43
+ 'flex size-full items-center justify-center overflow-hidden rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs group-data-[size=xs]/avatar:text-xs',
41
44
  className
42
45
  )}
43
46
  {...props}
@@ -45,15 +48,12 @@ function AvatarFallback({ className, ...props }: AvatarPrimitive.Fallback.Props)
45
48
  )
46
49
  }
47
50
 
48
- function AvatarBadge({ className, ...props }: React.ComponentProps<'span'>) {
51
+ function AvatarBadge({ className, ...props }: Omit<React.ComponentProps<'span'>, 'children'>) {
49
52
  return (
50
53
  <span
51
54
  data-slot="avatar-badge"
52
55
  className={cn(
53
- 'absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground bg-blend-color ring-2 ring-background select-none',
54
- 'group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden',
55
- 'group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2',
56
- 'group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2',
56
+ 'absolute right-0 bottom-0 size-(--avatar-badge-size) rounded-full bg-primary select-none',
57
57
  className
58
58
  )}
59
59
  {...props}
@@ -66,7 +66,10 @@ function AvatarGroup({ className, ...props }: React.ComponentProps<'div'>) {
66
66
  <div
67
67
  data-slot="avatar-group"
68
68
  className={cn(
69
- 'group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2 *:data-[slot=avatar]:ring-background',
69
+ 'group/avatar-group flex items-center -space-x-2 [--avatar-radius:--spacing(4)]',
70
+ '*:data-[size=lg]:[--avatar-radius:--spacing(5)] *:data-[size=sm]:[--avatar-radius:--spacing(3)] *:data-[size=xs]:[--avatar-radius:--spacing(2.5)]',
71
+ // Leave a transparent gap around the next avatar, including an overflow count.
72
+ '[&>[data-slot=avatar]:not(:last-child)]:mask-[radial-gradient(circle_at_calc(100%_+_var(--avatar-radius)_-_--spacing(2))_50%,transparent_calc(var(--avatar-radius)_+_2px),black_calc(var(--avatar-radius)_+_2.5px))]',
70
73
  className
71
74
  )}
72
75
  {...props}
@@ -74,12 +77,22 @@ function AvatarGroup({ className, ...props }: React.ComponentProps<'div'>) {
74
77
  )
75
78
  }
76
79
 
77
- function AvatarGroupCount({ className, ...props }: React.ComponentProps<'div'>) {
80
+ function AvatarGroupCount({
81
+ className,
82
+ size = 'default',
83
+ ...props
84
+ }: React.ComponentProps<'div'> & {
85
+ size?: React.ComponentProps<typeof Avatar>['size']
86
+ }) {
78
87
  return (
79
88
  <div
80
89
  data-slot="avatar-group-count"
90
+ data-size={size}
81
91
  className={cn(
82
- 'relative flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-sm text-muted-foreground ring-2 ring-background [&>svg]:size-4 [:where([class~="group/avatar-group"]):has([data-size=lg])_&]:size-10 [:where([class~="group/avatar-group"]):has([data-size=lg])_&]:[&>svg]:size-5 [:where([class~="group/avatar-group"]):has([data-size=sm])_&]:size-6 [:where([class~="group/avatar-group"]):has([data-size=sm])_&]:[&>svg]:size-3',
92
+ 'relative flex shrink-0 items-center justify-center rounded-full bg-accent text-sm text-muted-foreground [&>svg]:size-4',
93
+ 'data-[size=default]:size-8 data-[size=lg]:size-10 data-[size=sm]:size-6 data-[size=xs]:size-5',
94
+ 'data-[size=sm]:text-[11px] data-[size=xs]:text-[11px]',
95
+ 'data-[size=lg]:[&>svg]:size-5 data-[size=sm]:[&>svg]:size-3 data-[size=xs]:[&>svg]:size-3',
83
96
  className
84
97
  )}
85
98
  {...props}
@@ -4,7 +4,7 @@ import { type VariantProps, cva } from 'class-variance-authority'
4
4
  import { cn } from './utils'
5
5
 
6
6
  const buttonVariants = cva(
7
- 'inline-flex shrink-0 cursor-pointer items-center justify-center gap-1.5 rounded-lg text-sm font-medium whitespace-nowrap transition-all duration-100 outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0',
7
+ 'inline-flex shrink-0 cursor-pointer items-center justify-center gap-1.5 rounded-lg text-sm font-medium whitespace-nowrap transition-all duration-100 outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 [&>svg]:pointer-events-none [&>svg]:shrink-0',
8
8
  {
9
9
  variants: {
10
10
  variant: {
@@ -19,15 +19,15 @@ const buttonVariants = cva(
19
19
  'bg-destructive text-white inset-shadow-[0_0_8px_color-mix(in_oklab,var(--color-white)_20%,transparent)] hover:bg-destructive/90 focus-visible:border-destructive/40 focus-visible:ring-destructive/20'
20
20
  },
21
21
  size: {
22
- xs: 'h-6 gap-1 rounded-md px-2 text-xs has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg]:size-3',
23
- sm: 'h-7 gap-1.5 rounded-md px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2 [&_svg]:size-4',
22
+ xs: 'h-6 gap-1 rounded-md px-2 text-xs has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&>svg]:size-3',
23
+ sm: 'h-7 gap-1.5 rounded-md px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2 [&>svg]:size-4',
24
24
  default:
25
- 'h-8 px-3 has-data-[icon=inline-end]:pr-2.5 has-data-[icon=inline-start]:pl-2.5 [&_svg]:size-5',
26
- lg: 'h-9 rounded-xl px-3.5 has-data-[icon=inline-end]:pr-2.5 has-data-[icon=inline-start]:pl-2.5 [&_svg]:size-5',
27
- 'icon-xs': 'size-6 rounded-md [&_svg]:size-3',
28
- 'icon-sm': 'size-7 rounded-md [&_svg]:size-4',
29
- icon: 'size-8 [&_svg]:size-5',
30
- 'icon-lg': 'size-9 rounded-xl [&_svg]:size-5'
25
+ 'h-8 px-3 has-data-[icon=inline-end]:pr-2.5 has-data-[icon=inline-start]:pl-2.5 [&>svg]:size-5',
26
+ lg: 'h-9 rounded-xl px-3.5 has-data-[icon=inline-end]:pr-2.5 has-data-[icon=inline-start]:pl-2.5 [&>svg]:size-5',
27
+ 'icon-xs': 'size-6 rounded-md [&>svg]:size-3',
28
+ 'icon-sm': 'size-7 rounded-md [&>svg]:size-4',
29
+ icon: 'size-8 [&>svg]:size-5',
30
+ 'icon-lg': 'size-9 rounded-xl [&>svg]:size-5'
31
31
  }
32
32
  },
33
33
  defaultVariants: {