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
@@ -0,0 +1,407 @@
1
+ import { realpath } from 'node:fs/promises'
2
+ import { tmpdir } from 'node:os'
3
+ import { join, resolve } from 'node:path'
4
+
5
+ import { COLLAB_MAX_MESSAGE_BYTES, isCollabClientMessage } from '@/lib/collab/protocol'
6
+ import type { CollabClientMessage, CollabServerMessage, UserProfile } from '@/lib/collab/types'
7
+
8
+ import { isCollabEnabled } from './config'
9
+ import type { ParentMessage, WorkerMessage } from './worker-messages'
10
+
11
+ export type ClientSocket = {
12
+ send: (message: string) => number
13
+ close: (code?: number, reason?: string) => void
14
+ getBufferedAmount?: () => number
15
+ }
16
+
17
+ type Binding = {
18
+ socket: ClientSocket
19
+ workspacePaths: Set<string>
20
+ connectionId: string
21
+ closed: boolean
22
+ lastSeen: number
23
+ joined: boolean
24
+ // Set when a proxy (Cloudflare Access) verified who opened this socket.
25
+ verifiedProfile?: UserProfile
26
+ slot?: Slot
27
+ queue: Promise<void>
28
+ }
29
+
30
+ type Slot = {
31
+ workspacePath: string
32
+ workspacePaths: Set<string>
33
+ generation: string
34
+ child: ReturnType<typeof Bun.spawn>
35
+ ready: Promise<void>
36
+ resolveReady: () => void
37
+ rejectReady: (error: Error) => void
38
+ readyTimer: ReturnType<typeof setTimeout>
39
+ stopping: boolean
40
+ clients: Map<string, Binding>
41
+ idleTimer?: ReturnType<typeof setTimeout>
42
+ }
43
+
44
+ type ManagerOptions = {
45
+ enabled?: (workspacePath: string) => Promise<boolean>
46
+ workerPath?: string
47
+ startupTimeoutMs?: number
48
+ idleTimeoutMs?: number
49
+ livenessTimeoutMs?: number
50
+ }
51
+
52
+ export class CollabRuntimeError extends Error {
53
+ constructor(
54
+ public code: string,
55
+ message: string
56
+ ) {
57
+ super(message)
58
+ }
59
+ }
60
+
61
+ // A proxy-verified socket speaks only as the verified viewer. Another id, such
62
+ // as an outer host's current user, is refused rather than rewritten, so peers
63
+ // never see someone other than the person the browser shows.
64
+ function verifiedMessage(
65
+ message: CollabClientMessage,
66
+ verifiedProfile: UserProfile | undefined
67
+ ): CollabClientMessage | null {
68
+ if (!verifiedProfile || (message.type !== 'join' && message.type !== 'profile')) return message
69
+ return message.profile.id === verifiedProfile.id ? { ...message, profile: verifiedProfile } : null
70
+ }
71
+
72
+ // One owner map per moi server. No LRU: active workspaces cannot be evicted.
73
+ export class CollabManager {
74
+ private slots = new Map<string, Slot>()
75
+ private bindings = new Map<ClientSocket, Binding>()
76
+ private failures = new Map<string, { count: number; retryAfter: number }>()
77
+ private livenessTimer: ReturnType<typeof setInterval> | null = null
78
+ private closed = false
79
+
80
+ constructor(private options: ManagerOptions = {}) {}
81
+
82
+ private emit(binding: Binding, message: CollabServerMessage) {
83
+ if (binding.closed) return
84
+ const buffered = binding.socket.getBufferedAmount?.() ?? 0
85
+ if (buffered > 1024 * 1024) {
86
+ // A final leave or focus-clear snapshot might never be followed by another
87
+ // update. Rejoining must repair state even if the buffer drains before ping.
88
+ this.disconnect(binding, 'Collab updates need a fresh connection')
89
+ return
90
+ }
91
+ try {
92
+ if (binding.socket.send(JSON.stringify(message)) === 0)
93
+ this.disconnect(binding, 'Connection lost')
94
+ } catch {
95
+ this.disconnect(binding, 'Connection lost')
96
+ }
97
+ }
98
+
99
+ private send(slot: Slot, message: ParentMessage) {
100
+ if (slot.stopping) throw new CollabRuntimeError('restarting', 'Collab is restarting')
101
+ slot.child.send(message)
102
+ }
103
+
104
+ private async getSlot(workspacePath: string, binding: Binding): Promise<Slot> {
105
+ if (this.closed || binding.closed)
106
+ throw new CollabRuntimeError('unavailable', 'Collab connection closed')
107
+ const canonicalPath = await realpath(workspacePath)
108
+ binding.workspacePaths.add(canonicalPath)
109
+ if (binding.closed) throw new CollabRuntimeError('unavailable', 'Collab connection closed')
110
+ if (!(await (this.options.enabled ?? isCollabEnabled)(canonicalPath))) {
111
+ throw new CollabRuntimeError('unavailable', 'Start moi with --experimental-collab')
112
+ }
113
+ if (this.closed || binding.closed)
114
+ throw new CollabRuntimeError('unavailable', 'Collab connection closed')
115
+ const current = this.slots.get(canonicalPath)
116
+ if (current) {
117
+ if (current.stopping) {
118
+ await current.child.exited
119
+ if (this.slots.get(canonicalPath) === current) this.slots.delete(canonicalPath)
120
+ return this.getSlot(canonicalPath, binding)
121
+ }
122
+ if (current.idleTimer) clearTimeout(current.idleTimer)
123
+ current.idleTimer = undefined
124
+ current.workspacePaths.add(resolve(workspacePath))
125
+ return current
126
+ }
127
+ const failure = this.failures.get(canonicalPath)
128
+ if (failure && failure.retryAfter > Date.now()) {
129
+ throw new CollabRuntimeError('restarting', 'Collab is recovering; reconnect shortly')
130
+ }
131
+ const slot = this.spawn(canonicalPath)
132
+ slot.workspacePaths.add(resolve(workspacePath))
133
+ return slot
134
+ }
135
+
136
+ private spawn(workspacePath: string): Slot {
137
+ let resolveReady: () => void = () => {}
138
+ let rejectReady: (error: Error) => void = () => {}
139
+ const ready = new Promise<void>((resolve, reject) => {
140
+ resolveReady = resolve
141
+ rejectReady = reject
142
+ })
143
+ // Startup failure can precede a caller's await; callers still observe the original rejection.
144
+ void ready.catch(() => {})
145
+ const generation = crypto.randomUUID()
146
+ const slot: Slot = {
147
+ workspacePath,
148
+ workspacePaths: new Set([workspacePath]),
149
+ generation,
150
+ child: undefined as never,
151
+ ready,
152
+ resolveReady,
153
+ rejectReady,
154
+ readyTimer: setTimeout(() => {
155
+ slot.rejectReady(new CollabRuntimeError('startup_timeout', 'Collab did not start in time'))
156
+ this.stopSlot(slot, 'Collab startup timed out')
157
+ }, this.options.startupTimeoutMs ?? 10_000),
158
+ stopping: false,
159
+ clients: new Map()
160
+ }
161
+ try {
162
+ slot.child = Bun.spawn(
163
+ [process.execPath, this.options.workerPath ?? join(import.meta.dir, 'worker.ts')],
164
+ {
165
+ cwd: tmpdir(),
166
+ env: {
167
+ PATH: process.env.PATH,
168
+ MOI_COLLAB_WORKSPACE: workspacePath,
169
+ MOI_COLLAB_GENERATION: generation
170
+ },
171
+ stdout: 'inherit',
172
+ stderr: 'inherit',
173
+ ipc: (raw: unknown) => this.receive(slot, raw as WorkerMessage),
174
+ onExit: () => this.exited(slot)
175
+ }
176
+ )
177
+ this.slots.set(workspacePath, slot)
178
+ } catch (error) {
179
+ clearTimeout(slot.readyTimer)
180
+ rejectReady(error instanceof Error ? error : new Error('Collab could not start'))
181
+ throw error
182
+ }
183
+ return slot
184
+ }
185
+
186
+ private receive(slot: Slot, message: WorkerMessage) {
187
+ if (slot.stopping || message.generation !== slot.generation) return
188
+ if (message.type === 'ready') {
189
+ clearTimeout(slot.readyTimer)
190
+ slot.resolveReady()
191
+ return
192
+ }
193
+ if (message.type === 'client') {
194
+ const binding = slot.clients.get(message.connectionId)
195
+ if (binding) this.emit(binding, message.message)
196
+ return
197
+ }
198
+ }
199
+
200
+ private exited(slot: Slot) {
201
+ const expected = slot.stopping
202
+ slot.stopping = true
203
+ clearTimeout(slot.readyTimer)
204
+ if (slot.idleTimer) clearTimeout(slot.idleTimer)
205
+ const error = new CollabRuntimeError(
206
+ 'worker_exited',
207
+ 'Collab restarted; reconnect to restore presence'
208
+ )
209
+ slot.rejectReady(error)
210
+ for (const binding of [...slot.clients.values()]) this.disconnect(binding, error.message)
211
+ if (this.slots.get(slot.workspacePath) === slot) this.slots.delete(slot.workspacePath)
212
+ if (!expected) {
213
+ const count = (this.failures.get(slot.workspacePath)?.count ?? 0) + 1
214
+ this.failures.set(slot.workspacePath, {
215
+ count,
216
+ retryAfter: Date.now() + Math.min(250 * 2 ** Math.min(count - 1, 7), 30_000)
217
+ })
218
+ }
219
+ }
220
+
221
+ private scheduleIdle(slot: Slot) {
222
+ if (slot.stopping || slot.clients.size || slot.idleTimer) return
223
+ slot.idleTimer = setTimeout(
224
+ () => this.stopSlot(slot, 'Collab workspace is idle'),
225
+ this.options.idleTimeoutMs ?? 60_000
226
+ )
227
+ slot.idleTimer.unref()
228
+ }
229
+
230
+ private stopSlot(slot: Slot, reason: string) {
231
+ if (slot.stopping) return
232
+ slot.stopping = true
233
+ clearTimeout(slot.readyTimer)
234
+ slot.rejectReady(new CollabRuntimeError('restarting', reason))
235
+ for (const binding of [...slot.clients.values()]) this.disconnect(binding, reason)
236
+ try {
237
+ slot.child.send({ type: 'shutdown' } satisfies ParentMessage)
238
+ } catch {}
239
+ const deadline = setTimeout(() => slot.child.kill('SIGKILL'), 2000)
240
+ deadline.unref()
241
+ void slot.child.exited.finally(() => clearTimeout(deadline))
242
+ }
243
+
244
+ private disconnect(binding: Binding, reason: string) {
245
+ if (binding.closed) return
246
+ this.close(binding.socket)
247
+ binding.socket.close(1012, reason.slice(0, 120))
248
+ }
249
+
250
+ open(socket: ClientSocket, workspacePath: string, verifiedProfile?: UserProfile) {
251
+ const binding: Binding = {
252
+ socket,
253
+ workspacePaths: new Set([resolve(workspacePath)]),
254
+ connectionId: crypto.randomUUID(),
255
+ closed: false,
256
+ lastSeen: Date.now(),
257
+ joined: false,
258
+ verifiedProfile,
259
+ queue: Promise.resolve()
260
+ }
261
+ this.bindings.set(socket, binding)
262
+ binding.queue = this.getSlot(workspacePath, binding)
263
+ .then(async slot => {
264
+ if (binding.closed) {
265
+ this.scheduleIdle(slot)
266
+ return
267
+ }
268
+ binding.slot = slot
269
+ slot.clients.set(binding.connectionId, binding)
270
+ await slot.ready
271
+ })
272
+ .catch(error => {
273
+ this.emit(binding, {
274
+ type: 'error',
275
+ code: 'unavailable',
276
+ message: error instanceof Error ? error.message : 'Collab unavailable'
277
+ })
278
+ this.disconnect(binding, 'Collab unavailable')
279
+ })
280
+ this.livenessTimer ??= setInterval(() => {
281
+ const now = Date.now()
282
+ for (const client of this.bindings.values()) {
283
+ const timeout = client.joined ? (this.options.livenessTimeoutMs ?? 60_000) : 15_000
284
+ if (now - client.lastSeen > timeout) this.disconnect(client, 'Collab connection timed out')
285
+ }
286
+ }, 5000)
287
+ this.livenessTimer.unref()
288
+ }
289
+
290
+ message(socket: ClientSocket, raw: string | Uint8Array) {
291
+ const binding = this.bindings.get(socket)
292
+ if (!binding || binding.closed) return
293
+ const size = typeof raw === 'string' ? new TextEncoder().encode(raw).length : raw.byteLength
294
+ if (size > COLLAB_MAX_MESSAGE_BYTES) {
295
+ this.disconnect(binding, 'Collab message is too large')
296
+ return
297
+ }
298
+ let message: unknown
299
+ try {
300
+ message = JSON.parse(typeof raw === 'string' ? raw : new TextDecoder().decode(raw))
301
+ } catch {}
302
+ if (!isCollabClientMessage(message)) {
303
+ this.emit(binding, {
304
+ type: 'error',
305
+ code: 'invalid_message',
306
+ message: 'Invalid collab message'
307
+ })
308
+ return
309
+ }
310
+ binding.lastSeen = Date.now()
311
+ const validated = verifiedMessage(message, binding.verifiedProfile)
312
+ if (!validated) {
313
+ this.emit(binding, {
314
+ type: 'error',
315
+ code: 'user_mismatch',
316
+ message: 'Presence here uses your Cloudflare Access user'
317
+ })
318
+ this.disconnect(binding, 'User does not match Cloudflare Access')
319
+ return
320
+ }
321
+ binding.queue = binding.queue
322
+ .then(() => {
323
+ if (binding.closed || !binding.slot) return
324
+ if (validated.type === 'join') binding.joined = true
325
+ this.send(binding.slot, {
326
+ type: 'client',
327
+ connectionId: binding.connectionId,
328
+ message: validated
329
+ })
330
+ })
331
+ .catch(() => this.disconnect(binding, 'Collab restarted'))
332
+ }
333
+
334
+ close(socket: ClientSocket) {
335
+ const binding = this.bindings.get(socket)
336
+ if (!binding) return
337
+ binding.closed = true
338
+ this.bindings.delete(socket)
339
+ if (!this.bindings.size && this.livenessTimer) {
340
+ clearInterval(this.livenessTimer)
341
+ this.livenessTimer = null
342
+ }
343
+ const slot = binding.slot
344
+ if (!slot) return
345
+ slot.clients.delete(binding.connectionId)
346
+ if (!slot.stopping) {
347
+ try {
348
+ this.send(slot, { type: 'leave', connectionId: binding.connectionId })
349
+ } catch {}
350
+ }
351
+ this.scheduleIdle(slot)
352
+ }
353
+
354
+ async stopWorkspace(workspacePath: string) {
355
+ // Remember aliases so removing a missing directory or symlink can still stop its room.
356
+ const knownPath = resolve(workspacePath)
357
+ let slot = [...this.slots.values()].find(slot => slot.workspacePaths.has(knownPath))
358
+ const disconnectPending = (path: string) => {
359
+ for (const binding of this.bindings.values()) {
360
+ if (binding.workspacePaths.has(path)) {
361
+ this.disconnect(binding, 'Collab stopped for this workspace')
362
+ }
363
+ }
364
+ }
365
+ disconnectPending(knownPath)
366
+ if (slot) disconnectPending(slot.workspacePath)
367
+ if (!slot) {
368
+ try {
369
+ const canonicalPath = await realpath(workspacePath)
370
+ disconnectPending(canonicalPath)
371
+ slot = this.slots.get(canonicalPath)
372
+ } catch (error) {
373
+ if (
374
+ error instanceof Error &&
375
+ 'code' in error &&
376
+ (error.code === 'ENOENT' || error.code === 'ENOTDIR')
377
+ )
378
+ return
379
+ throw error
380
+ }
381
+ }
382
+ if (!slot) return
383
+ this.stopSlot(slot, 'Collab stopped for this workspace')
384
+ await slot.child.exited
385
+ }
386
+
387
+ async shutdown() {
388
+ this.closed = true
389
+ if (this.livenessTimer) clearInterval(this.livenessTimer)
390
+ this.livenessTimer = null
391
+ const slots = [...this.slots.values()]
392
+ for (const slot of slots) this.stopSlot(slot, 'moi is shutting down')
393
+ await Promise.allSettled(slots.map(slot => slot.child.exited))
394
+ }
395
+
396
+ debugSnapshot() {
397
+ return [...this.slots.values()].map(slot => ({
398
+ workspacePath: slot.workspacePath,
399
+ pid: slot.child.pid,
400
+ generation: slot.generation,
401
+ connections: slot.clients.size,
402
+ stopping: slot.stopping
403
+ }))
404
+ }
405
+ }
406
+
407
+ export const collabManager = new CollabManager()
@@ -0,0 +1,136 @@
1
+ import {
2
+ COLLAB_MAX_CONNECTIONS,
3
+ COLLAB_MAX_REGISTRATIONS,
4
+ COLLAB_PROTOCOL_VERSION
5
+ } from '@/lib/collab/protocol'
6
+ import type {
7
+ CollabClientMessage,
8
+ CollabServerMessage,
9
+ Connection,
10
+ UserProfile
11
+ } from '@/lib/collab/types'
12
+
13
+ type Emit = (connectionId: string, message: CollabServerMessage) => void
14
+ type Client = {
15
+ profile: UserProfile
16
+ connection: Connection
17
+ }
18
+
19
+ function cleanProfile(profile: UserProfile): UserProfile {
20
+ return {
21
+ id: profile.id,
22
+ ...(profile.name !== undefined ? { name: profile.name } : {}),
23
+ color: profile.color,
24
+ ...(profile.avatar !== undefined ? { avatar: profile.avatar } : {}),
25
+ ...(profile.email !== undefined ? { email: profile.email } : {})
26
+ }
27
+ }
28
+
29
+ // One process owns this ephemeral room. No workspace data is read or written.
30
+ export class CollabService {
31
+ private clients = new Map<string, Client>()
32
+ private presenceTimer: ReturnType<typeof setTimeout> | null = null
33
+
34
+ constructor(private emit: Emit) {}
35
+
36
+ private snapshot() {
37
+ const users = new Map<string, UserProfile>()
38
+ const connections: Connection[] = []
39
+ for (const { profile, connection } of this.clients.values()) {
40
+ users.set(profile.id, profile)
41
+ connections.push(connection)
42
+ }
43
+ return { connections, users: [...users.values()] }
44
+ }
45
+
46
+ private publishConnections() {
47
+ if (this.presenceTimer) clearTimeout(this.presenceTimer)
48
+ this.presenceTimer = null
49
+ const message: CollabServerMessage = { type: 'connections', ...this.snapshot() }
50
+ for (const id of this.clients.keys()) this.emit(id, message)
51
+ }
52
+
53
+ private scheduleConnections() {
54
+ this.presenceTimer ??= setTimeout(() => this.publishConnections(), 50)
55
+ }
56
+
57
+ receive(connectionId: string, message: CollabClientMessage) {
58
+ if (message.type === 'join') {
59
+ if (this.clients.has(connectionId)) throw new Error('This connection already joined')
60
+ if (this.clients.size >= COLLAB_MAX_CONNECTIONS)
61
+ throw new Error('This workspace has too many connections')
62
+ const profile = cleanProfile(message.profile)
63
+ // Keep one current profile across a user's tabs, without sharing their presence.
64
+ for (const client of this.clients.values()) {
65
+ if (client.profile.id === profile.id) client.profile = profile
66
+ }
67
+ this.clients.set(connectionId, {
68
+ profile,
69
+ connection: {
70
+ connectionId,
71
+ userId: profile.id,
72
+ location: message.location ?? null,
73
+ presence: []
74
+ }
75
+ })
76
+ this.emit(connectionId, {
77
+ type: 'welcome',
78
+ version: COLLAB_PROTOCOL_VERSION,
79
+ connectionId,
80
+ ...this.snapshot()
81
+ })
82
+ this.publishConnections()
83
+ return
84
+ }
85
+
86
+ const client = this.clients.get(connectionId)
87
+ if (!client) throw new Error('Join the workspace before sending collab messages')
88
+ const { connection } = client
89
+ switch (message.type) {
90
+ case 'profile': {
91
+ if (message.profile.id !== connection.userId) throw new Error('Reconnect to change user ID')
92
+ const profile = cleanProfile(message.profile)
93
+ for (const other of this.clients.values()) {
94
+ if (other.profile.id === profile.id) other.profile = profile
95
+ }
96
+ this.publishConnections()
97
+ return
98
+ }
99
+ case 'location':
100
+ connection.location = message.location
101
+ this.scheduleConnections()
102
+ return
103
+ case 'presence:set': {
104
+ const presence = connection.presence
105
+ const index = presence.findIndex(item => item.registrationId === message.registrationId)
106
+ if (index < 0 && presence.length >= COLLAB_MAX_REGISTRATIONS)
107
+ throw new Error('Too many presence registrations')
108
+ const { registrationId, appletId, channel, value } = message
109
+ const registration = { registrationId, appletId, channel, value }
110
+ if (index >= 0) presence[index] = registration
111
+ else presence.push(registration)
112
+ this.scheduleConnections()
113
+ return
114
+ }
115
+ case 'presence:delete':
116
+ connection.presence = connection.presence.filter(
117
+ item => item.registrationId !== message.registrationId
118
+ )
119
+ this.scheduleConnections()
120
+ return
121
+ case 'ping':
122
+ this.emit(connectionId, { type: 'pong' })
123
+ return
124
+ }
125
+ }
126
+
127
+ leave(connectionId: string) {
128
+ if (this.clients.delete(connectionId)) this.publishConnections()
129
+ }
130
+
131
+ close() {
132
+ if (this.presenceTimer) clearTimeout(this.presenceTimer)
133
+ this.presenceTimer = null
134
+ this.clients.clear()
135
+ }
136
+ }
@@ -0,0 +1,53 @@
1
+ import { mkdir, rm } from 'node:fs/promises'
2
+ import { dirname, join } from 'node:path'
3
+
4
+ import type { WorkspaceType } from '@/lib/types'
5
+
6
+ import { appletDeclarationPath, installCollabDeclaration } from '../../applets/declarations'
7
+ import { COLLAB_REFERENCE_SOURCE_PATH } from '../../skills-template'
8
+ import { skillsDirFor } from '../../workspace-init'
9
+
10
+ export type SkillPaths = { referencePath: string; typesPath: string }
11
+
12
+ export function collabSkillReferencePath(workspacePath: string, type?: WorkspaceType): string {
13
+ return join(skillsDirFor(workspacePath, type), 'moi-workspace', 'references', 'COLLAB.md')
14
+ }
15
+
16
+ function targetPaths(workspacePath: string, type?: WorkspaceType): SkillPaths {
17
+ return {
18
+ referencePath: collabSkillReferencePath(workspacePath, type),
19
+ typesPath: appletDeclarationPath(workspacePath, 'collab.d.ts')
20
+ }
21
+ }
22
+
23
+ async function writeChanged(path: string, contents: string): Promise<void> {
24
+ const file = Bun.file(path)
25
+ if ((await file.exists()) && (await file.text()) === contents) return
26
+ await mkdir(dirname(path), { recursive: true })
27
+ await Bun.write(path, contents)
28
+ }
29
+
30
+ // Only an explicit `moi init --experimental-collab` installs the guide and types.
31
+ export async function installCollabSkill(
32
+ workspacePath: string,
33
+ type?: WorkspaceType
34
+ ): Promise<SkillPaths> {
35
+ const source = Bun.file(COLLAB_REFERENCE_SOURCE_PATH)
36
+ if (!(await source.exists())) {
37
+ throw new Error('The collab guide is unavailable in this build: COLLAB.md is missing.')
38
+ }
39
+ const reference = await source.text()
40
+ const paths = targetPaths(workspacePath, type)
41
+ await writeChanged(paths.referencePath, reference)
42
+ await installCollabDeclaration(workspacePath)
43
+ return paths
44
+ }
45
+
46
+ export async function removeCollabSkill(
47
+ workspacePath: string,
48
+ type?: WorkspaceType
49
+ ): Promise<void> {
50
+ const paths = targetPaths(workspacePath, type)
51
+ await rm(paths.referencePath, { force: true })
52
+ await rm(paths.typesPath, { force: true })
53
+ }
@@ -0,0 +1,10 @@
1
+ import type { CollabClientMessage, CollabServerMessage } from '@/lib/collab/types'
2
+
3
+ export type ParentMessage =
4
+ | { type: 'client'; connectionId: string; message: CollabClientMessage }
5
+ | { type: 'leave'; connectionId: string }
6
+ | { type: 'shutdown' }
7
+
8
+ export type WorkerMessage =
9
+ | { type: 'ready'; generation: string }
10
+ | { type: 'client'; generation: string; connectionId: string; message: CollabServerMessage }
@@ -0,0 +1,52 @@
1
+ import type { CollabServerMessage } from '@/lib/collab/types'
2
+
3
+ import type { ParentMessage, WorkerMessage } from './worker-messages'
4
+ import { CollabService } from './service'
5
+
6
+ const workspacePath = process.env.MOI_COLLAB_WORKSPACE
7
+ const generation = process.env.MOI_COLLAB_GENERATION
8
+ if (!workspacePath || !generation || !process.send) throw new Error('Missing collab worker context')
9
+
10
+ function send(message: WorkerMessage) {
11
+ process.send?.(message)
12
+ }
13
+
14
+ const service = new CollabService((connectionId, message) => {
15
+ send({ type: 'client', generation, connectionId, message })
16
+ })
17
+
18
+ function errorInfo(error: unknown): { code: string; message: string } {
19
+ return {
20
+ code: error instanceof Error && 'code' in error ? String(error.code) : 'invalid_request',
21
+ message: error instanceof Error ? error.message : 'Collab request failed'
22
+ }
23
+ }
24
+
25
+ process.on('message', (message: ParentMessage) => {
26
+ if (message.type === 'shutdown') return shutdown()
27
+ if (message.type === 'leave') return service.leave(message.connectionId)
28
+ if (message.type === 'client') {
29
+ try {
30
+ service.receive(message.connectionId, message.message)
31
+ } catch (error) {
32
+ const response: CollabServerMessage = {
33
+ type: 'error',
34
+ ...errorInfo(error)
35
+ }
36
+ send({ type: 'client', generation, connectionId: message.connectionId, message: response })
37
+ }
38
+ return
39
+ }
40
+ })
41
+
42
+ let shuttingDown = false
43
+ function shutdown() {
44
+ if (shuttingDown) return
45
+ shuttingDown = true
46
+ service.close()
47
+ process.exit(0)
48
+ }
49
+ process.on('disconnect', shutdown)
50
+ process.on('SIGTERM', shutdown)
51
+ process.on('SIGINT', shutdown)
52
+ send({ type: 'ready', generation })
package/server/layout.ts CHANGED
@@ -1,6 +1,11 @@
1
1
  import { join } from 'path'
2
2
 
3
- import type { AppletKind, WorkspaceLayout, WorkspacePreview } from '@/lib/types'
3
+ import type {
4
+ AppletKind,
5
+ WorkspaceLayout,
6
+ WorkspaceLayoutSave,
7
+ WorkspacePreview
8
+ } from '@/lib/types'
4
9
  import { createDefaultWorkspaceLayout, normalizeWorkspaceTabs } from '@/lib/workspace-layout'
5
10
  import { isWorkspaceIcon } from '@/lib/workspace-icon'
6
11
 
@@ -59,7 +64,7 @@ export async function saveLayout(layout: WorkspaceLayout, workspacePath: string)
59
64
  // as `name: undefined`.
60
65
  export function mergeLayoutForSave(
61
66
  existing: WorkspaceLayout,
62
- body: WorkspaceLayout
67
+ body: WorkspaceLayoutSave
63
68
  ): WorkspaceLayout {
64
69
  const { name: _name, icon: _icon, ...editor } = body
65
70
  // Stale clients may still round-trip the pre-`.cache` thumbnail records;
@@ -67,7 +72,9 @@ export function mergeLayoutForSave(
67
72
  delete (editor as Record<string, unknown>).appletThumbnails
68
73
  return {
69
74
  ...editor,
70
- tabs: normalizeWorkspaceTabs(editor.tabs),
75
+ // Personal navigation never writes tabs. Other layout edits must not
76
+ // round-trip a stale copy of the workspace's authored defaults.
77
+ tabs: editor.tabs === undefined ? existing.tabs : normalizeWorkspaceTabs(editor.tabs),
71
78
  ...(existing.name !== undefined && { name: existing.name }),
72
79
  ...(existing.icon !== undefined && { icon: existing.icon })
73
80
  }