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,79 @@
1
+ import { createContext, useContext, useEffect, useMemo, useSyncExternalStore } from 'react'
2
+ import type { ReactNode } from 'react'
3
+ import { useRouter } from 'wouter'
4
+ import { usePathname } from 'wouter/use-browser-location'
5
+
6
+ import { legacyTabFromPath, tabFromPath, workspacePath } from '@/lib/navigation'
7
+
8
+ import { CollabClient, NO_ENGINE } from './client'
9
+ import type { CollabEngineApi } from './client'
10
+
11
+ type AppletPresence = { active: boolean; appletId: string }
12
+ export const CollabContext = createContext<CollabEngineApi>(NO_ENGINE)
13
+ const AppletPresenceContext = createContext<AppletPresence | null>(null)
14
+
15
+ export function pageFromPath(path: string, workspaceId: string, base = ''): string {
16
+ const prefix = workspacePath(workspaceId, base) + '/'
17
+ const page = path.startsWith(prefix) ? path.slice(prefix.length) : ''
18
+ return tabFromPath(page) ?? legacyTabFromPath(page) ?? (page || 'overview')
19
+ }
20
+
21
+ export type CollabProviderProps = {
22
+ workspaceId: string
23
+ enabled: boolean
24
+ children: ReactNode
25
+ }
26
+ export function CollabProvider({ workspaceId, enabled, children }: CollabProviderProps) {
27
+ const engine = useMemo(() => new CollabClient(workspaceId, enabled), [workspaceId, enabled])
28
+ const router = useRouter()
29
+ const path = usePathname(router)
30
+ const { base } = router
31
+ useEffect(() => engine.start(), [engine])
32
+ useEffect(() => {
33
+ const update = () =>
34
+ engine.setLocation({
35
+ page: pageFromPath(window.location.pathname, workspaceId, base),
36
+ status: document.visibilityState === 'hidden' ? 'away' : 'active'
37
+ })
38
+ update()
39
+ document.addEventListener('visibilitychange', update)
40
+ return () => document.removeEventListener('visibilitychange', update)
41
+ }, [base, engine, path, workspaceId])
42
+ return <CollabContext value={engine}>{children}</CollabContext>
43
+ }
44
+
45
+ export type AppletPresenceProviderProps = {
46
+ appletId: string
47
+ active?: boolean
48
+ children: ReactNode
49
+ }
50
+ export function AppletPresenceProvider({
51
+ appletId,
52
+ active = true,
53
+ children
54
+ }: AppletPresenceProviderProps) {
55
+ const { enabled } = useCollabEngine()
56
+ const presence = useMemo(
57
+ () => ({ active: enabled && active, appletId }),
58
+ [enabled, active, appletId]
59
+ )
60
+ return <AppletPresenceContext value={presence}>{children}</AppletPresenceContext>
61
+ }
62
+
63
+ export function useCollabEngine(): CollabEngineApi {
64
+ return useContext(CollabContext)
65
+ }
66
+ export function useAppletPresence(): AppletPresence | null {
67
+ return useContext(AppletPresenceContext)
68
+ }
69
+
70
+ // Collab controls and browser-tab selection require both runtime support and a current user.
71
+ export function useCollabEnabled(): boolean {
72
+ const engine = useCollabEngine()
73
+ const currentUser = useSyncExternalStore(
74
+ engine.subscribeCurrentUser,
75
+ engine.getCurrentUser,
76
+ engine.getCurrentUser
77
+ )
78
+ return engine.enabled && currentUser !== undefined
79
+ }
@@ -0,0 +1,35 @@
1
+ import type { ProxyUserState } from '@/lib/collab/types'
2
+
3
+ import { requestJson } from '@/client/api/http'
4
+ import { onWorkspaceEventsReconnect } from '@/client/runtime/useWorkspaceEvents'
5
+
6
+ import { setProxyUserState } from './host-state'
7
+
8
+ // GET /api/proxy-user: the viewer as verified by a proxy in front of moi, such as
9
+ // Cloudflare Access. A failed request keeps the current user.
10
+ async function fetchProxyUser(): Promise<ProxyUserState | undefined> {
11
+ try {
12
+ const state = await requestJson<ProxyUserState>('/api/proxy-user')
13
+ if (
14
+ !state ||
15
+ typeof state !== 'object' ||
16
+ Array.isArray(state) ||
17
+ (state.provider !== undefined && state.provider !== 'cloudflare-access') ||
18
+ (state.provider === undefined && state.profile !== undefined)
19
+ )
20
+ return undefined
21
+ setProxyUserState(state)
22
+ return state
23
+ } catch {}
24
+ }
25
+
26
+ // Loaded before the app mounts, like startup config, so workspaces choose
27
+ // between shared and browser-tab navigation with the inherited user already
28
+ // in place. A server restart can change the proxy config, so reconnects refetch.
29
+ export async function loadProxyUser(): Promise<ProxyUserState | undefined> {
30
+ const state = await fetchProxyUser()
31
+ onWorkspaceEventsReconnect(() => {
32
+ void fetchProxyUser()
33
+ })
34
+ return state
35
+ }
@@ -0,0 +1,156 @@
1
+ import type { JsonValue } from 'moi'
2
+ import type {
3
+ CollabClientMessage,
4
+ UserProfile,
5
+ ConnectionLocation,
6
+ Connection,
7
+ PresenceRegistration,
8
+ CollabServerMessage
9
+ } from '@/lib/collab/types'
10
+
11
+ export type ClientState = {
12
+ status: 'connecting' | 'connected' | 'disconnected'
13
+ connectionId: string | null
14
+ connections: Connection[]
15
+ // Current live profiles only. The host owns the full workspace directory.
16
+ users: readonly UserProfile[]
17
+ error: string | null
18
+ }
19
+
20
+ export const DISCONNECTED_STATE: ClientState = {
21
+ status: 'disconnected',
22
+ connectionId: null,
23
+ connections: [],
24
+ users: [],
25
+ error: null
26
+ }
27
+
28
+ export type PresenceEntry = {
29
+ registrationId: string
30
+ connectionId: string
31
+ userId: string
32
+ value: JsonValue
33
+ }
34
+
35
+ const EMPTY_PRESENCE: readonly PresenceEntry[] = []
36
+ const channelKey = (appletId: string, channel: string) => JSON.stringify([appletId, channel])
37
+
38
+ // Sockets and timers live in client.ts; this model owns ephemeral registrations.
39
+ export class CollabStore {
40
+ private state: ClientState = DISCONNECTED_STATE
41
+ private usersState: ClientState = DISCONNECTED_STATE
42
+ private channels = new Map<string, readonly PresenceEntry[]>()
43
+ private listeners = new Set<() => void>()
44
+ private registrations = new Map<string, PresenceRegistration>()
45
+ private location: ConnectionLocation | null = null
46
+ private send: (message: CollabClientMessage) => void = () => {}
47
+
48
+ getSnapshot = (): ClientState => this.state
49
+ // User hooks never need cursor coordinates or other publication payloads.
50
+ getUsersSnapshot = (): ClientState => this.usersState
51
+ getPresenceSnapshot = (appletId: string, channel: string): readonly PresenceEntry[] =>
52
+ this.channels.get(channelKey(appletId, channel)) ?? EMPTY_PRESENCE
53
+ subscribe = (listener: () => void): (() => void) => {
54
+ this.listeners.add(listener)
55
+ return () => {
56
+ this.listeners.delete(listener)
57
+ }
58
+ }
59
+ setSender(send: (message: CollabClientMessage) => void): void {
60
+ this.send = send
61
+ }
62
+ connecting(): void {
63
+ this.publish({ status: 'connecting', error: null })
64
+ }
65
+ disconnect(message?: string): void {
66
+ this.publish({ ...DISCONNECTED_STATE, error: message ?? null })
67
+ }
68
+ setLocation(location: ConnectionLocation | null): void {
69
+ if (JSON.stringify(this.location) === JSON.stringify(location)) return
70
+ this.location = location
71
+ // Page filters update immediately, without waiting for the server echo.
72
+ this.publish({}, true)
73
+ if (this.state.status === 'connected') this.send({ type: 'location', location })
74
+ }
75
+ getLocation(): ConnectionLocation | null {
76
+ return this.location
77
+ }
78
+ setPresence(registration: PresenceRegistration): void {
79
+ const previous = this.registrations.get(registration.registrationId)
80
+ if (previous && JSON.stringify(previous) === JSON.stringify(registration)) return
81
+ this.registrations.set(registration.registrationId, registration)
82
+ if (this.state.status === 'connected') this.send({ type: 'presence:set', ...registration })
83
+ }
84
+ deletePresence(registrationId: string): void {
85
+ this.registrations.delete(registrationId)
86
+ if (this.state.status === 'connected') this.send({ type: 'presence:delete', registrationId })
87
+ }
88
+ receive(message: CollabServerMessage): void {
89
+ switch (message.type) {
90
+ case 'welcome':
91
+ this.publish({
92
+ status: 'connected',
93
+ connectionId: message.connectionId,
94
+ connections: message.connections,
95
+ users: message.users,
96
+ error: null
97
+ })
98
+ for (const registration of this.registrations.values()) {
99
+ this.send({ type: 'presence:set', ...registration })
100
+ }
101
+ break
102
+ case 'connections':
103
+ this.publish({ connections: message.connections, users: message.users })
104
+ break
105
+ case 'error':
106
+ this.publish({ error: message.message })
107
+ break
108
+ case 'pong':
109
+ break
110
+ }
111
+ }
112
+ private publish(patch: Partial<ClientState>, locationChanged = false): void {
113
+ this.state = { ...this.state, ...patch }
114
+ const users = {
115
+ ...this.state,
116
+ connections: this.state.connections.map(connection => ({ ...connection, presence: [] }))
117
+ }
118
+ if (locationChanged || JSON.stringify(users) !== JSON.stringify(this.usersState)) {
119
+ this.usersState = users
120
+ }
121
+ const channels = new Map<string, PresenceEntry[]>()
122
+ if (this.location?.status === 'active') {
123
+ for (const connection of this.state.connections) {
124
+ if (
125
+ connection.connectionId === this.state.connectionId ||
126
+ connection.location?.page !== this.location.page ||
127
+ connection.location.status !== 'active'
128
+ )
129
+ continue
130
+ for (const registration of connection.presence) {
131
+ const key = channelKey(registration.appletId, registration.channel)
132
+ const entries = channels.get(key) ?? []
133
+ entries.push({
134
+ registrationId: registration.registrationId,
135
+ connectionId: connection.connectionId,
136
+ userId: connection.userId,
137
+ value: registration.value
138
+ })
139
+ channels.set(key, entries)
140
+ }
141
+ }
142
+ }
143
+ // Keep references for unchanged channels. Only current nonempty channels are
144
+ // retained, so navigating through many records does not grow a selector cache.
145
+ this.channels = new Map(
146
+ [...channels].map(([key, entries]) => {
147
+ const previous = this.channels.get(key)
148
+ return [
149
+ key,
150
+ previous && JSON.stringify(previous) === JSON.stringify(entries) ? previous : entries
151
+ ]
152
+ })
153
+ )
154
+ this.listeners.forEach(listener => listener())
155
+ }
156
+ }
@@ -0,0 +1,54 @@
1
+ import type { ReactNode } from 'react'
2
+ import { renderToStaticMarkup } from 'react-dom/server'
3
+
4
+ import type { PresenceRegistration, UserProfile } from '@/lib/collab/types'
5
+
6
+ import { AppletPresenceProvider, CollabContext } from '../provider'
7
+ import { presenceChannels } from '../hooks'
8
+ import { presenceTarget } from '../presence-target'
9
+ import { createFakeEngine } from './fake-engine'
10
+ import type { FakeEngine } from './fake-engine'
11
+
12
+ export const me: UserProfile = { id: 'me', name: 'Me', color: 'blue' }
13
+ export const peer: UserProfile = { id: 'peer', name: 'Ada', color: 'cyan' }
14
+ export const namelessUsers = [
15
+ [{ id: 'user-id', color: 'cyan' }, 'user-id'],
16
+ [{ id: 'user-id', name: ' ', email: 'user@example.test', color: 'cyan' }, 'user@example.test']
17
+ ] satisfies Array<[UserProfile, string]>
18
+
19
+ export function createRoom(profile: UserProfile = peer, presence: PresenceRegistration[] = []) {
20
+ return createFakeEngine({
21
+ self: me,
22
+ page: 'board',
23
+ users: [me, profile],
24
+ otherConnections: [
25
+ {
26
+ connectionId: 'remote',
27
+ userId: profile.id,
28
+ location: { page: 'board', status: 'active' },
29
+ presence
30
+ }
31
+ ]
32
+ })
33
+ }
34
+
35
+ export function createFocusRoom(target = presenceTarget('task:42:title'), profile = peer) {
36
+ return createRoom(profile, [
37
+ {
38
+ registrationId: 'focus',
39
+ appletId: 'views/board',
40
+ channel: presenceChannels.target(target),
41
+ value: true
42
+ }
43
+ ])
44
+ }
45
+
46
+ export function renderCollab(backend: FakeEngine, children: ReactNode, active = true) {
47
+ return renderToStaticMarkup(
48
+ <CollabContext value={backend}>
49
+ <AppletPresenceProvider appletId="views/board" active={active}>
50
+ {children}
51
+ </AppletPresenceProvider>
52
+ </CollabContext>
53
+ )
54
+ }
@@ -0,0 +1,129 @@
1
+ import type { UserProfile, Connection, PresenceRegistration } from '@/lib/collab/types'
2
+ import { COLLAB_PROTOCOL_VERSION } from '@/lib/collab/protocol'
3
+ import type { CollabEngineApi } from '../client'
4
+ import { normalizeWorkspaceUsers } from '../host-state'
5
+ import type { WorkspaceDirectory } from '../host-state'
6
+ import { CollabStore } from '../store'
7
+
8
+ export type FakeEngineOptions = {
9
+ self: UserProfile | undefined
10
+ page?: string
11
+ otherConnections?: Connection[]
12
+ // Full fixture directory, including users who are offline.
13
+ users?: readonly UserProfile[]
14
+ directoryStatus?: WorkspaceDirectory['status']
15
+ }
16
+ export type FakeEngine = CollabEngineApi & {
17
+ setOtherConnections: (otherConnections: Connection[]) => void
18
+ setUsers: (users: readonly UserProfile[] | undefined) => void
19
+ setDirectoryStatus: (status: WorkspaceDirectory['status'] | undefined) => void
20
+ }
21
+
22
+ export function createFakeEngine({
23
+ self,
24
+ page = 'preview',
25
+ otherConnections = [],
26
+ users,
27
+ directoryStatus = users === undefined ? undefined : 'ready'
28
+ }: FakeEngineOptions): FakeEngine {
29
+ const store = new CollabStore()
30
+ const presence = new Map<string, PresenceRegistration>()
31
+ const userListeners = new Set<() => void>()
32
+ const directory = users === undefined ? undefined : normalizeWorkspaceUsers(users)
33
+ let profiles = directory ?? (self ? [self] : [])
34
+ let directorySnapshot: WorkspaceDirectory | undefined =
35
+ directoryStatus === 'ready'
36
+ ? { status: directoryStatus, users: directory ?? [] }
37
+ : directoryStatus === 'loading'
38
+ ? { status: directoryStatus }
39
+ : undefined
40
+ let currentOtherConnections = otherConnections
41
+ let location: Connection['location'] = { page, status: 'active' }
42
+ const connections = (): Connection[] => [
43
+ ...(self
44
+ ? [{ connectionId: 'local', userId: self.id, location, presence: [...presence.values()] }]
45
+ : []),
46
+ ...currentOtherConnections
47
+ ]
48
+ const liveUsers = () => {
49
+ const connected = new Set(connections().map(connection => connection.userId))
50
+ return profiles.filter(user => connected.has(user.id))
51
+ }
52
+ const announce = () =>
53
+ store.receive({ type: 'connections', connections: connections(), users: liveUsers() })
54
+ store.setSender(message => {
55
+ switch (message.type) {
56
+ case 'location':
57
+ location = message.location
58
+ announce()
59
+ break
60
+ case 'presence:set': {
61
+ const { type: _type, ...registration } = message
62
+ presence.set(registration.registrationId, registration)
63
+ announce()
64
+ break
65
+ }
66
+ case 'presence:delete':
67
+ presence.delete(message.registrationId)
68
+ announce()
69
+ break
70
+ default:
71
+ break
72
+ }
73
+ })
74
+ store.setLocation(location)
75
+ store.receive({
76
+ type: 'welcome',
77
+ version: COLLAB_PROTOCOL_VERSION,
78
+ connectionId: 'local',
79
+ connections: connections(),
80
+ users: liveUsers()
81
+ })
82
+ return {
83
+ workspaceId: 'preview',
84
+ enabled: true,
85
+ start: () => () => {},
86
+ getSnapshot: store.getSnapshot,
87
+ getUsersSnapshot: store.getUsersSnapshot,
88
+ getPresenceSnapshot: store.getPresenceSnapshot,
89
+ subscribe: store.subscribe,
90
+ getCurrentUser: () => self,
91
+ subscribeCurrentUser: () => () => {},
92
+ getWorkspaceDirectory: () => directorySnapshot,
93
+ subscribeWorkspaceUsers: listener => {
94
+ userListeners.add(listener)
95
+ return () => {
96
+ userListeners.delete(listener)
97
+ }
98
+ },
99
+ getLocation: () => store.getLocation(),
100
+ setLocation: location => store.setLocation(location),
101
+ setPresence: registration => {
102
+ if (self) store.setPresence(registration)
103
+ },
104
+ deletePresence: registrationId => {
105
+ if (self) store.deletePresence(registrationId)
106
+ },
107
+ setOtherConnections: next => {
108
+ currentOtherConnections = next
109
+ announce()
110
+ },
111
+ setUsers: next => {
112
+ const directory = next === undefined ? undefined : normalizeWorkspaceUsers(next)
113
+ directorySnapshot =
114
+ directory === undefined ? undefined : { status: 'ready', users: directory }
115
+ if (directory) profiles = directory
116
+ userListeners.forEach(listener => listener())
117
+ announce()
118
+ },
119
+ setDirectoryStatus: status => {
120
+ directorySnapshot =
121
+ status === 'ready'
122
+ ? { status, users: profiles }
123
+ : status === 'loading'
124
+ ? { status }
125
+ : undefined
126
+ userListeners.forEach(listener => listener())
127
+ }
128
+ }
129
+ }
@@ -0,0 +1,106 @@
1
+ import type { UserProfile, ConnectionLocation, Connection } from '@/lib/collab/types'
2
+
3
+ import type { UserStatus, WorkspaceUser, UsePeersOptions } from 'moi/collab'
4
+
5
+ export type {
6
+ UserStatus,
7
+ WorkspaceUser,
8
+ UsePeersOptions,
9
+ UseWorkspaceUsersOptions
10
+ } from 'moi/collab'
11
+ export type UsersSource = {
12
+ connections: readonly Connection[]
13
+ users: readonly UserProfile[]
14
+ }
15
+
16
+ // Presentation only: keep the supplied profile unchanged in applet APIs.
17
+ export function userDisplayName(user: UserProfile): string {
18
+ return user.name?.trim() || user.email?.trim() || user.id
19
+ }
20
+
21
+ export function userStatus(connections: readonly Connection[], id: string): UserStatus {
22
+ const userConnections = connections.filter(connection => connection.userId === id)
23
+ return userConnections.some(connection => connection.location?.status === 'active')
24
+ ? 'active'
25
+ : userConnections.length
26
+ ? 'away'
27
+ : 'offline'
28
+ }
29
+
30
+ // A supplied host directory is authoritative, including an empty list/removals.
31
+ export function workspaceProfiles(
32
+ liveUsers: readonly UserProfile[],
33
+ self: UserProfile | undefined,
34
+ directory: readonly UserProfile[] | undefined
35
+ ): readonly UserProfile[] {
36
+ if (directory !== undefined) return directory
37
+ const users = new Map(liveUsers.map(user => [user.id, user]))
38
+ if (self) users.set(self.id, self)
39
+ return [...users.values()]
40
+ }
41
+
42
+ export function resolveUser(source: UsersSource, id: string): WorkspaceUser | undefined {
43
+ const profile = source.users.find(user => user.id === id)
44
+ return profile ? { ...profile, status: userStatus(source.connections, id) } : undefined
45
+ }
46
+
47
+ export function resolvePeers(
48
+ source: UsersSource,
49
+ selfId: string | undefined,
50
+ location: ConnectionLocation | null,
51
+ { scope = 'page', status }: UsePeersOptions = {}
52
+ ): WorkspaceUser[] {
53
+ const peers: WorkspaceUser[] = []
54
+ const ids = new Set(
55
+ source.connections
56
+ .filter(
57
+ connection =>
58
+ connection.userId !== selfId &&
59
+ (scope === 'workspace' ||
60
+ (location !== null && connection.location?.page === location.page))
61
+ )
62
+ .map(connection => connection.userId)
63
+ )
64
+ for (const id of ids) {
65
+ const user = resolveUser(source, id)
66
+ if (user && (!status || user.status === status)) peers.push(user)
67
+ }
68
+ return peers
69
+ }
70
+
71
+ export type WorkspaceUserInfo = {
72
+ profile: UserProfile
73
+ self: boolean
74
+ pages: string[]
75
+ status: UserStatus
76
+ }
77
+ export type CurrentUserContext = {
78
+ currentUser: UserProfile | undefined
79
+ connectionId: string | null
80
+ page: string | null
81
+ users: readonly UserProfile[]
82
+ }
83
+ export function summarizeWorkspaceUsers(
84
+ connections: Connection[],
85
+ context: CurrentUserContext
86
+ ): WorkspaceUserInfo[] {
87
+ const users = [...context.users].sort(
88
+ (a, b) => Number(b.id === context.currentUser?.id) - Number(a.id === context.currentUser?.id)
89
+ )
90
+ return users.map(profile => {
91
+ const pages = new Set<string>()
92
+ for (const connection of connections) {
93
+ if (connection.userId !== profile.id || connection.connectionId === context.connectionId)
94
+ continue
95
+ if (connection.location) pages.add(connection.location.page)
96
+ }
97
+ const isSelf = profile.id === context.currentUser?.id
98
+ if (isSelf && context.page) pages.add(context.page)
99
+ return {
100
+ profile,
101
+ self: isSelf,
102
+ pages: [...pages],
103
+ status: userStatus(connections, profile.id)
104
+ }
105
+ })
106
+ }