moi-computer 0.13.0 → 0.13.1-next.1

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 (91) hide show
  1. package/client/api/app-config.ts +0 -1
  2. package/client/api/query-client.ts +5 -0
  3. package/client/app/app-router.tsx +1 -1
  4. package/client/app/routes/workspace-route.tsx +5 -6
  5. package/client/features/account/account-provider.tsx +28 -77
  6. package/client/features/account/account-test-utils.tsx +103 -93
  7. package/client/features/account/api.ts +36 -111
  8. package/client/features/account/profile-actions.ts +31 -0
  9. package/client/features/app-settings/avatar-upload.tsx +62 -0
  10. package/client/features/app-settings/profile-settings.tsx +10 -0
  11. package/client/features/app-settings/settings-page.tsx +0 -4
  12. package/client/features/chat/applet-chat-intents.ts +4 -4
  13. package/client/features/chat/sessions/api.ts +5 -5
  14. package/client/features/chat/sessions/use-selected-session.ts +3 -3
  15. package/client/features/chat/use-chat.ts +4 -4
  16. package/client/features/collab/applet-api.ts +1 -1
  17. package/client/features/collab/components/cursors.tsx +6 -1
  18. package/client/features/collab/components/presence-avatars.tsx +1 -1
  19. package/client/features/collab/components/presence-frame.tsx +1 -1
  20. package/client/features/collab/components/presence-group.tsx +1 -1
  21. package/client/features/collab/components/presence-helpers.ts +2 -2
  22. package/client/features/collab/components/user-avatar-group.tsx +1 -1
  23. package/client/features/collab/components/user-avatar.tsx +1 -1
  24. package/client/features/collab/components/user.tsx +1 -1
  25. package/client/features/collab/host-state.ts +45 -85
  26. package/client/features/collab/index.ts +3 -3
  27. package/client/features/collab/members/api.ts +23 -0
  28. package/client/features/collab/members/hooks.ts +103 -0
  29. package/client/features/collab/members/keys.ts +6 -0
  30. package/client/features/collab/members/store.ts +123 -0
  31. package/client/features/collab/members/types.ts +53 -0
  32. package/client/features/collab/{client.ts → presence/client.ts} +38 -13
  33. package/client/features/collab/{hooks.tsx → presence/hooks.tsx} +9 -8
  34. package/client/features/collab/{provider.tsx → presence/provider.tsx} +1 -12
  35. package/client/features/collab/{users.ts → presence/users.ts} +19 -33
  36. package/client/features/collab/sharing/agent-invite.tsx +30 -0
  37. package/client/features/collab/sharing/workspace-members.tsx +277 -0
  38. package/client/features/collab/sharing/workspace-sharing-menu.tsx +179 -0
  39. package/client/features/collab/testing/component-fixtures.tsx +3 -3
  40. package/client/features/collab/testing/fake-engine.ts +15 -3
  41. package/client/features/dev/collab/collab-playground.tsx +2 -2
  42. package/client/features/dev/workspace-setup-mocks.ts +0 -1
  43. package/client/features/identity/host-api.ts +34 -0
  44. package/client/features/identity/store.ts +32 -0
  45. package/client/features/identity/types.ts +41 -0
  46. package/client/features/identity/use-identity.ts +6 -0
  47. package/client/features/views/use-view-actions.ts +3 -3
  48. package/client/features/workspace/browser-tab-state.ts +6 -6
  49. package/client/features/workspace/workspace-content.tsx +10 -6
  50. package/client/index.html +1 -1
  51. package/client/index.tsx +5 -9
  52. package/client/main.tsx +2 -2
  53. package/dist/{chunk-cqt3s31j.js → chunk-3smkkcfw.js} +86 -86
  54. package/dist/chunk-47h9c2qy.js +2 -0
  55. package/dist/chunk-8qed2gqp.js +75 -0
  56. package/dist/{chunk-bncc7heg.js → chunk-8zy3vesm.js} +1 -1
  57. package/dist/chunk-a47zy276.js +2 -0
  58. package/dist/chunk-g4c1nte9.css +1 -0
  59. package/dist/chunk-kcactdr4.js +2 -0
  60. package/dist/chunk-m8bhx6tw.js +1 -0
  61. package/dist/{chunk-58dyt9bk.js → chunk-pf19zcrn.js} +2 -2
  62. package/dist/{chunk-2y59vrxg.js → chunk-th91xfnp.js} +1 -1
  63. package/dist/chunk-ygzxah0e.js +1 -0
  64. package/dist/index.html +2 -2
  65. package/lib/types.ts +0 -1
  66. package/package.json +5 -4
  67. package/server/app-config.ts +2 -5
  68. package/server/applets/declarations.ts +6 -7
  69. package/server/cli/commands/init.ts +0 -11
  70. package/server/collab/config.ts +1 -5
  71. package/server/collab/manager.ts +5 -2
  72. package/server/collab/skill/index.ts +1 -47
  73. package/server/skills/template.ts +3 -2
  74. package/server/skills/update.ts +1 -1
  75. package/server/skills/workspace.ts +0 -2
  76. package/server/web.ts +1 -2
  77. package/server/workspaces/scaffold.ts +1 -0
  78. package/skill/SKILL.md +1 -1
  79. package/client/features/account/identity.ts +0 -23
  80. package/client/features/app-settings/users-settings.tsx +0 -195
  81. package/client/features/collab/workspace-users-menu.tsx +0 -190
  82. package/dist/chunk-dcmks9sm.js +0 -75
  83. package/dist/chunk-md45evr2.css +0 -1
  84. package/dist/chunk-n0nab26d.js +0 -1
  85. package/dist/chunk-nmzhgyp9.js +0 -2
  86. package/dist/chunk-q37knr3m.js +0 -2
  87. package/dist/chunk-s90m4qkz.js +0 -1
  88. package/dist/chunk-wjvd4byz.js +0 -2
  89. /package/client/features/collab/{presence-publisher.ts → presence/presence-publisher.ts} +0 -0
  90. /package/client/features/collab/{presence-target.ts → presence/presence-target.ts} +0 -0
  91. /package/client/features/collab/{store.ts → presence/store.ts} +0 -0
@@ -1,34 +1,18 @@
1
+ import { getIdentity, subscribeIdentity } from '../identity/store'
2
+ import { collabIdentityId } from '../identity/types'
1
3
  import { isUserProfile } from '@/lib/collab/protocol'
2
4
  import { colorForId, isUserColor } from '@/lib/collab/colors'
3
5
  import type { AuthProvider, ProxyUserState, UserProfile } from '@/lib/collab/types'
4
6
  import { createLocalUser } from './local-user'
5
7
 
6
8
  export type UserProfileInput = Omit<UserProfile, 'color'> & { color?: UserProfile['color'] }
7
- // What an outer host publishes: the viewer's id and everyone moi may show.
8
- // `me` must be listed in `users`; leave it out when nobody is signed in.
9
- export type HostUsers = {
10
- me?: string | null
11
- users: readonly UserProfileInput[]
12
- }
13
- // `window.moi.collab`. An outer host calls it from a module script placed after
14
- // moi's bundle, once at startup and again whenever a user or the viewer changes.
15
- // A classic inline script runs before the bundle and finds nothing here.
16
- //
17
- // window.moi.collab.publishUsers({ me: 'alex', users: [{ id: 'alex', name: 'Alex' }] })
18
- export type HostApi = { publishUsers: (next: HostUsers) => void }
19
9
  // Who supplies the current user: local setup, an outer host, or an auth proxy.
20
10
  export type CurrentUserSource = 'local' | 'external' | AuthProvider
21
11
 
22
12
  const PROFILE_KEY = 'moi:local-profile'
23
- const NO_USERS: readonly UserProfile[] = Object.freeze([])
24
13
  let currentUser: UserProfile | undefined
25
14
  let currentUserSource: CurrentUserSource | undefined
26
- // One list for the whole app. Undefined until a host publishes; from then on it
27
- // is authoritative, including when it is empty.
28
- let directory: readonly UserProfile[] | undefined
29
- let installed = false
30
15
  const listeners = new Set<() => void>()
31
- const directoryListeners = new Set<() => void>()
32
16
 
33
17
  // Normalized profiles list their fields in one order, so text equality is exact.
34
18
  function sameProfile(a: UserProfile | undefined, b: UserProfile | undefined): boolean {
@@ -55,73 +39,55 @@ export function normalizeUserProfile(value: UserProfileInput): UserProfile {
55
39
  return Object.freeze(normalized)
56
40
  }
57
41
 
58
- export function normalizeUsers(users: readonly UserProfileInput[]): readonly UserProfile[] {
59
- if (!Array.isArray(users)) throw new Error('Users must be an array.')
60
- const ids = new Set<string>()
61
- const snapshot = users.map(user => {
62
- const normalized = normalizeUserProfile(user)
63
- if (ids.has(normalized.id)) throw new Error('Users must have unique ids.')
64
- ids.add(normalized.id)
65
- return normalized
66
- })
67
- return Object.freeze(snapshot)
68
- }
69
-
70
- // Replaces the viewer and the whole directory in one step. The host sends the
71
- // full list every time, so a removal is simply an id that is no longer there.
72
- // Invalid input throws and publishes nothing.
73
- export function publishUsers(next: HostUsers): void {
74
- if (!next || typeof next !== 'object') throw new Error('Users must be published as an object.')
75
- const users = normalizeUsers(next.users)
76
- let user: UserProfile | undefined
77
- if (next.me !== undefined && next.me !== null) {
78
- if (typeof next.me !== 'string') throw new Error('The current user id must be a string.')
79
- const id = next.me.trim()
80
- user = users.find(candidate => candidate.id === id)
81
- if (!user) throw new Error('The current user must be listed in users.')
82
- }
83
- // An unchanged viewer keeps its profile object and stays quiet: every notice
84
- // makes each open workspace resend that profile to its room.
85
- const changed = currentUserSource !== 'external' || !sameProfile(currentUser, user)
86
- // Publish every field before notifying any observer, including transport listeners.
87
- currentUserSource = 'external'
88
- if (changed) currentUser = user
89
- // A signed-out viewer sees no one, whatever the host still lists.
90
- directory = user ? users : NO_USERS
91
- if (changed) listeners.forEach(listener => listener())
92
- directoryListeners.forEach(listener => listener())
93
- }
94
-
95
- export function getDirectory(): readonly UserProfile[] | undefined {
96
- return directory
97
- }
98
-
99
- export function subscribeDirectoryStore(listener: () => void): () => void {
100
- directoryListeners.add(listener)
101
- return () => {
102
- directoryListeners.delete(listener)
103
- }
104
- }
105
-
42
+ // This is a memoized projection of cloud identity, never a separately writable profile.
43
+ let cloudProfile: UserProfile | undefined
44
+ let cloudIdentity: ReturnType<typeof getIdentity>
106
45
  export function getCurrentUser(): UserProfile | undefined {
107
- return currentUser
46
+ const identity = getIdentity()
47
+ if (identity === undefined) return currentUser
48
+ if (identity !== cloudIdentity) {
49
+ cloudIdentity = identity
50
+ const next =
51
+ !identity || (identity.type === 'user' && identity.isAnonymous)
52
+ ? undefined
53
+ : normalizeUserProfile({
54
+ id: collabIdentityId(identity),
55
+ name: identity.name || undefined,
56
+ avatar: identity.avatar,
57
+ email: identity.type === 'user' ? identity.email || undefined : undefined
58
+ })
59
+ if (!sameProfile(cloudProfile, next)) cloudProfile = next
60
+ }
61
+ return cloudProfile
108
62
  }
109
63
 
110
64
  export function subscribeCurrentUserStore(listener: () => void): () => void {
111
- listeners.add(listener)
65
+ let profile = getCurrentUser()
66
+ let source = getCurrentUserSource()
67
+ const notify = () => {
68
+ const nextProfile = getCurrentUser()
69
+ const nextSource = getCurrentUserSource()
70
+ if (profile === nextProfile && source === nextSource) return
71
+ profile = nextProfile
72
+ source = nextSource
73
+ listener()
74
+ }
75
+ listeners.add(notify)
76
+ const unsubscribeIdentity = subscribeIdentity(notify)
112
77
  return () => {
113
- listeners.delete(listener)
78
+ listeners.delete(notify)
79
+ unsubscribeIdentity()
114
80
  }
115
81
  }
116
82
 
117
83
  export function getCurrentUserSource(): CurrentUserSource | undefined {
118
- return currentUserSource
84
+ return getIdentity() !== undefined ? 'external' : currentUserSource
119
85
  }
120
86
 
121
87
  // An auth proxy takes precedence over local users; an outer host takes
122
88
  // precedence over the proxy. A configured proxy with no user signs this tab out.
123
89
  export function setProxyUserState({ provider, profile }: ProxyUserState): void {
124
- if (currentUserSource === 'external') return
90
+ if (getCurrentUserSource() === 'external') return
125
91
  if (provider === undefined) {
126
92
  if (currentUserSource === undefined || currentUserSource === 'local') return
127
93
  currentUserSource = undefined
@@ -145,7 +111,7 @@ function persistLocalUser(): void {
145
111
 
146
112
  export function setLocalUser(next: UserProfile): void {
147
113
  // A provider may take over between rendering the local user form and handling input.
148
- if (currentUserSource !== undefined && currentUserSource !== 'local') return
114
+ if (getCurrentUserSource() !== undefined && getCurrentUserSource() !== 'local') return
149
115
  const normalized = normalizeUserProfile(next)
150
116
  currentUserSource = 'local'
151
117
  currentUser = normalized
@@ -156,7 +122,12 @@ export function setLocalUser(next: UserProfile): void {
156
122
  // Called after startup config and proxy identity settle, before React mounts.
157
123
  // A host that has already published keeps the viewer it chose, signed in or not.
158
124
  export function initializeLocalUser(local: boolean, proxyUser: ProxyUserState | undefined): void {
159
- if (!local || !proxyUser || proxyUser.provider !== undefined || currentUserSource !== undefined)
125
+ if (
126
+ !local ||
127
+ !proxyUser ||
128
+ proxyUser.provider !== undefined ||
129
+ getCurrentUserSource() !== undefined
130
+ )
160
131
  return
161
132
  try {
162
133
  const saved = localStorage.getItem(PROFILE_KEY)
@@ -170,20 +141,9 @@ export function initializeLocalUser(local: boolean, proxyUser: ProxyUserState |
170
141
  setLocalUser(createLocalUser())
171
142
  }
172
143
 
173
- // Runs while moi's bundle evaluates, so a host script placed after the bundle
174
- // finds `publishUsers` at once and can publish before the app mounts.
175
- export function installHostApi(): void {
176
- if (typeof window === 'undefined' || installed) return
177
- installed = true
178
- const host = window as Window & { moi?: { collab?: HostApi; [key: string]: unknown } }
179
- host.moi ??= {}
180
- const api: HostApi = { publishUsers }
181
- host.moi.collab = api
182
- }
183
-
184
144
  // Storage events update this tab without writing back and triggering another event.
185
145
  export function receiveLocalProfile(event: Pick<StorageEvent, 'key' | 'newValue'>): void {
186
- if (event.key !== PROFILE_KEY || !event.newValue || currentUserSource !== 'local') return
146
+ if (event.key !== PROFILE_KEY || !event.newValue || getCurrentUserSource() !== 'local') return
187
147
  try {
188
148
  const profile = normalizeUserProfile(JSON.parse(event.newValue) as UserProfile)
189
149
  if (sameProfile(profile, currentUser)) return
@@ -1,5 +1,5 @@
1
- export { CollabProvider, AppletPresenceProvider, useCollabEnabled } from './provider'
2
- export { WorkspaceUsersMenu } from './workspace-users-menu'
3
- export type { TabInfo } from './workspace-users-menu'
1
+ export { CollabProvider, AppletPresenceProvider } from './presence/provider'
2
+ export { WorkspaceSharingMenu } from './sharing/workspace-sharing-menu'
3
+ export type { TabInfo } from './sharing/workspace-sharing-menu'
4
4
  export { appletCollabApi } from './applet-api'
5
5
  export type { AppletCollabApi } from './applet-api'
@@ -0,0 +1,23 @@
1
+ import { cloudRequest } from '../../account/api'
2
+ import { jsonRequest } from '@/client/api/http'
3
+ import { parseWorkspaceMembers, validWorkspaceId } from './types'
4
+
5
+ const workspaceMembersPath = (id: string) =>
6
+ `workspaces/${encodeURIComponent(validWorkspaceId(id))}`
7
+ export async function fetchWorkspaceMembers(id: string, signal?: AbortSignal) {
8
+ const response = await cloudRequest(`${workspaceMembersPath(id)}/members`, { signal })
9
+ return parseWorkspaceMembers(await response.json())
10
+ }
11
+ export const inviteWorkspaceMember = (id: string, email: string, workspaceName?: string) =>
12
+ cloudRequest(
13
+ `${workspaceMembersPath(id)}/invitations`,
14
+ jsonRequest('POST', { email, workspaceName })
15
+ )
16
+ export const removeWorkspaceMember = (id: string, membershipId: string) =>
17
+ cloudRequest(`${workspaceMembersPath(id)}/members/${encodeURIComponent(membershipId)}`, {
18
+ method: 'DELETE'
19
+ })
20
+ export const revokeWorkspaceInvitation = (id: string, invitationId: string) =>
21
+ cloudRequest(`${workspaceMembersPath(id)}/invitations/${encodeURIComponent(invitationId)}`, {
22
+ method: 'DELETE'
23
+ })
@@ -0,0 +1,103 @@
1
+ import { useMutation, useMutationState, useQuery, useQueryClient } from '@tanstack/react-query'
2
+ import { useWorkspaces } from '../../home/api'
3
+ import { getAccountGeneration } from '../../identity/store'
4
+ import { useIdentity } from '../../identity/use-identity'
5
+ import { ownerOnlyWorkspaceMembers } from './store'
6
+ import { memberKeys } from './keys'
7
+ import { identityKey } from '../../identity/types'
8
+ import {
9
+ fetchWorkspaceMembers,
10
+ inviteWorkspaceMember,
11
+ removeWorkspaceMember,
12
+ revokeWorkspaceInvitation
13
+ } from './api'
14
+ import type { WorkspaceMembers } from './types'
15
+
16
+ export type MembershipAction =
17
+ | { type: 'invite'; email: string }
18
+ | { type: 'remove'; membershipId: string }
19
+ | { type: 'revoke'; invitationId: string }
20
+
21
+ type PendingAction = { id: number; action: MembershipAction }
22
+ export function applyPendingMembership(
23
+ data: WorkspaceMembers | undefined,
24
+ actions: PendingAction[]
25
+ ) {
26
+ if (!data) return undefined
27
+ let { members, invitations } = data
28
+ for (const { id, action } of actions) {
29
+ if (action.type === 'remove')
30
+ members = members.filter(member => member.membershipId !== action.membershipId)
31
+ else if (action.type === 'revoke')
32
+ invitations = invitations.filter(invitation => invitation.id !== action.invitationId)
33
+ else if (!invitations.some(invitation => invitation.email === action.email))
34
+ invitations = [
35
+ ...invitations,
36
+ { id: `pending:${id}`, email: action.email, expiresAt: '', pending: true }
37
+ ]
38
+ }
39
+ return { members, invitations }
40
+ }
41
+ export function useWorkspaceMembers(workspaceId: string | undefined) {
42
+ const identity = useIdentity()
43
+ const accountId = identity ? identityKey(identity) : undefined
44
+ const enabled = !!workspaceId && identity?.type === 'user' && !identity.isAnonymous
45
+ const accountGeneration = getAccountGeneration()
46
+ const mutationKey = ['workspace-members-action', accountGeneration, workspaceId]
47
+ const query = useQuery({
48
+ queryKey: memberKeys.workspace(accountId, workspaceId ?? ''),
49
+ initialData: ownerOnlyWorkspaceMembers,
50
+ queryFn: async ({ signal }) => {
51
+ const snapshot = await fetchWorkspaceMembers(workspaceId!, signal)
52
+ if (signal.aborted || accountGeneration !== getAccountGeneration())
53
+ throw new Error('Identity changed')
54
+ return snapshot
55
+ },
56
+ enabled,
57
+ retry: false,
58
+ staleTime: 30_000
59
+ })
60
+ const pending = useMutationState({
61
+ filters: { mutationKey, status: 'pending', exact: true },
62
+ select: mutation => ({
63
+ id: mutation.state.submittedAt,
64
+ action: mutation.state.variables as MembershipAction
65
+ })
66
+ })
67
+ const data = applyPendingMembership(query.data, pending)
68
+ return { ...query, data, members: data?.members, invitations: data?.invitations }
69
+ }
70
+ export function useMembershipAction(workspaceId: string) {
71
+ const workspaces = useWorkspaces()
72
+
73
+ const identity = useIdentity()
74
+ const accountId = identity ? identityKey(identity) : undefined
75
+ const accountGeneration = getAccountGeneration()
76
+ const client = useQueryClient()
77
+ return useMutation({
78
+ mutationKey: ['workspace-members-action', accountGeneration, workspaceId],
79
+ mutationFn: async (action: MembershipAction) => {
80
+ if (
81
+ !identity ||
82
+ identity.type !== 'user' ||
83
+ identity.isAnonymous ||
84
+ accountGeneration !== getAccountGeneration()
85
+ )
86
+ throw new Error('Sign in to manage workspace members')
87
+ if (action.type === 'invite') {
88
+ const name = workspaces.data?.find(workspace => workspace.id === workspaceId)?.name
89
+ return inviteWorkspaceMember(workspaceId, action.email, name?.trim() || undefined)
90
+ }
91
+ if (action.type === 'remove') return removeWorkspaceMember(workspaceId, action.membershipId)
92
+ return revokeWorkspaceInvitation(workspaceId, action.invitationId)
93
+ },
94
+ onSuccess: async () => {
95
+ if (accountGeneration !== getAccountGeneration()) return
96
+ // Keep the optimistic overlay until the canonical snapshot has caught up.
97
+ await client.invalidateQueries({
98
+ queryKey: memberKeys.workspace(accountId, workspaceId),
99
+ exact: true
100
+ })
101
+ }
102
+ })
103
+ }
@@ -0,0 +1,6 @@
1
+ export const memberKeys = {
2
+ all: ['workspace-members'] as const,
3
+ account: (accountId: string | undefined) => [...memberKeys.all, accountId ?? 'unknown'] as const,
4
+ workspace: (accountId: string | undefined, workspaceId: string) =>
5
+ [...memberKeys.account(accountId), workspaceId] as const
6
+ }
@@ -0,0 +1,123 @@
1
+ import { memberKeys } from './keys'
2
+ import { queryClient } from '@/client/api/query-client'
3
+ import { getIdentity, getAccountGeneration } from '../../identity/store'
4
+ import type { Identity } from '../../identity/types'
5
+ import { collabIdentityId, identityKey } from '../../identity/types'
6
+ import { normalizeUserProfile } from '../host-state'
7
+ import type { UserProfile } from '@/lib/collab/types'
8
+ import { parseWorkspaceMembers, validWorkspaceId } from './types'
9
+ import type { WorkspaceMembers, WorkspaceMembersSnapshot } from './types'
10
+
11
+ // Host-published memberships remain authoritative until replaced or cleared,
12
+ // including for workspaces that have no mounted React observer yet.
13
+ queryClient.setQueryDefaults(memberKeys.all, { gcTime: Infinity })
14
+
15
+ // Revisions track membership writes so older cloud snapshots cannot replace them.
16
+ let membersRevision = 0
17
+ let membersLoadedForAccountGeneration: number | undefined
18
+ const collectionListeners = new Set<() => void>()
19
+ const ownerSnapshots = new WeakMap<Identity, WorkspaceMembers>()
20
+ queryClient.getQueryCache().subscribe(event => {
21
+ if (event.query.queryKey[0] !== memberKeys.all[0]) return
22
+ if (event.type === 'removed' || (event.type === 'updated' && event.action.type === 'success')) {
23
+ membersRevision++
24
+ }
25
+ })
26
+ export const getWorkspaceMembersRevision = () => membersRevision
27
+ const directoryCache = new WeakMap<WorkspaceMembers, readonly UserProfile[]>()
28
+ // Cloud routing currently opens the owner's machine. No sharing record means
29
+ // owner-only; Moi's own workspace registry decides whether that workspace exists.
30
+ export function ownerOnlyWorkspaceMembers(): WorkspaceMembers | undefined {
31
+ const owner = getIdentity()
32
+ if (
33
+ membersLoadedForAccountGeneration !== getAccountGeneration() ||
34
+ owner?.type !== 'user' ||
35
+ owner.isAnonymous
36
+ )
37
+ return undefined
38
+ let snapshot = ownerSnapshots.get(owner)
39
+ if (!snapshot) {
40
+ snapshot = { members: [owner], invitations: [] }
41
+ ownerSnapshots.set(owner, snapshot)
42
+ }
43
+ return snapshot
44
+ }
45
+ export function setWorkspaceMembers(workspaceId: string, value: WorkspaceMembers): void {
46
+ const identity = getIdentity()
47
+ const queryKey = memberKeys.workspace(identity ? identityKey(identity) : undefined, workspaceId)
48
+ validWorkspaceId(workspaceId)
49
+ const data = parseWorkspaceMembers(value)
50
+ // A push supersedes any older in-flight GET for this snapshot.
51
+ void queryClient.cancelQueries({ queryKey, exact: true })
52
+ queryClient.setQueryData(queryKey, data)
53
+ }
54
+ export function setAllWorkspaceMembers(value: WorkspaceMembersSnapshot[]): void {
55
+ if (!Array.isArray(value)) throw new Error('Invalid workspace members')
56
+ const snapshots = value.map(workspace => ({
57
+ id: validWorkspaceId(workspace.id),
58
+ data: parseWorkspaceMembers(workspace)
59
+ }))
60
+ const ids = new Set(snapshots.map(workspace => workspace.id))
61
+ if (ids.size !== snapshots.length) throw new Error('Duplicate workspace id')
62
+ membersLoadedForAccountGeneration = getAccountGeneration()
63
+ const identity = getIdentity()
64
+ const accountId = identity ? identityKey(identity) : undefined
65
+ const prefix = memberKeys.account(accountId)
66
+ void queryClient.cancelQueries({ queryKey: prefix })
67
+ for (const query of queryClient.getQueryCache().findAll({ queryKey: prefix })) {
68
+ if (!ids.has(query.queryKey[2] as string)) forgetWorkspaceMembers(query.queryKey)
69
+ }
70
+ for (const workspace of snapshots)
71
+ queryClient.setQueryData(memberKeys.workspace(accountId, workspace.id), workspace.data)
72
+ membersRevision++
73
+ collectionListeners.forEach(listener => listener())
74
+ }
75
+ export function removeWorkspaceMembers(workspaceId: string) {
76
+ const identity = getIdentity()
77
+ const queryKey = memberKeys.workspace(identity ? identityKey(identity) : undefined, workspaceId)
78
+ validWorkspaceId(workspaceId)
79
+ void queryClient.cancelQueries({ queryKey, exact: true })
80
+ forgetWorkspaceMembers(queryKey)
81
+ }
82
+ export function clearWorkspaceMembers() {
83
+ void queryClient.cancelQueries({ queryKey: memberKeys.all })
84
+ for (const query of queryClient.getQueryCache().findAll({ queryKey: memberKeys.all }))
85
+ forgetWorkspaceMembers(query.queryKey)
86
+ }
87
+ function forgetWorkspaceMembers(queryKey: readonly unknown[]) {
88
+ // Removing an observed query leaves its current UI snapshot intact. Publish
89
+ // the replacement so mounted views and the presence engine update together.
90
+ queryClient.setQueryData<WorkspaceMembers>(
91
+ queryKey,
92
+ ownerOnlyWorkspaceMembers() ?? { members: [], invitations: [] }
93
+ )
94
+ }
95
+ export function getWorkspaceDirectory(workspaceId: string): readonly UserProfile[] | undefined {
96
+ const identity = getIdentity()
97
+ const queryKey = memberKeys.workspace(identity ? identityKey(identity) : undefined, workspaceId)
98
+ const data = queryClient.getQueryData<WorkspaceMembers>(queryKey) ?? ownerOnlyWorkspaceMembers()
99
+ if (!data) return undefined
100
+ let profiles = directoryCache.get(data)
101
+ if (!profiles) {
102
+ profiles = data.members.map(member =>
103
+ normalizeUserProfile({
104
+ id: collabIdentityId(member),
105
+ name: member.name || undefined,
106
+ avatar: member.avatar,
107
+ email: member.type === 'user' ? member.email || undefined : undefined
108
+ })
109
+ )
110
+ directoryCache.set(data, profiles)
111
+ }
112
+ return profiles
113
+ }
114
+ export function subscribeWorkspaceDirectory(listener: () => void) {
115
+ collectionListeners.add(listener)
116
+ const unsubscribe = queryClient.getQueryCache().subscribe(event => {
117
+ if (event.query.queryKey[0] === memberKeys.all[0]) listener()
118
+ })
119
+ return () => {
120
+ collectionListeners.delete(listener)
121
+ unsubscribe()
122
+ }
123
+ }
@@ -0,0 +1,53 @@
1
+ import { isRecord } from '@/lib/collab/protocol'
2
+ import { identityKey, parseIdentity } from '../../identity/types'
3
+ import type { Identity } from '../../identity/types'
4
+
5
+ export type WorkspaceMember = Identity & { membershipId?: string }
6
+ export type WorkspaceInvitation = {
7
+ id: string
8
+ email: string
9
+ expiresAt: string
10
+ pending?: boolean
11
+ }
12
+ export type WorkspaceMembers = { members: WorkspaceMember[]; invitations: WorkspaceInvitation[] }
13
+ export type WorkspaceMembersSnapshot = WorkspaceMembers & { id: string }
14
+ export function parseWorkspaceMembers(value: unknown): WorkspaceMembers {
15
+ if (!isRecord(value) || !Array.isArray(value.members) || !Array.isArray(value.invitations))
16
+ throw new Error('Invalid workspace members')
17
+ const members = value.members.map(member => {
18
+ const identity = parseIdentity(member)
19
+ if (isRecord(member) && member.membershipId !== undefined) {
20
+ if (
21
+ typeof member.membershipId !== 'string' ||
22
+ !member.membershipId ||
23
+ member.membershipId.length > 240
24
+ )
25
+ throw new Error('Invalid membership id')
26
+ return { ...identity, membershipId: member.membershipId }
27
+ }
28
+ return identity
29
+ })
30
+ const invitations = value.invitations.map(invitation => {
31
+ if (
32
+ !isRecord(invitation) ||
33
+ typeof invitation.id !== 'string' ||
34
+ !invitation.id ||
35
+ typeof invitation.email !== 'string' ||
36
+ !invitation.email ||
37
+ typeof invitation.expiresAt !== 'string' ||
38
+ !Number.isFinite(Date.parse(invitation.expiresAt))
39
+ )
40
+ throw new Error('Invalid invitation')
41
+ return { id: invitation.id, email: invitation.email, expiresAt: invitation.expiresAt }
42
+ })
43
+ if (
44
+ new Set(members.map(identityKey)).size !== members.length ||
45
+ new Set(invitations.map(invitation => invitation.id)).size !== invitations.length
46
+ )
47
+ throw new Error('Duplicate workspace member or invitation')
48
+ return { members, invitations }
49
+ }
50
+ export function validWorkspaceId(id: string): string {
51
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(id)) throw new Error('Invalid workspace id')
52
+ return id
53
+ }
@@ -1,3 +1,4 @@
1
+ import { getWorkspaceDirectory, subscribeWorkspaceDirectory } from '../members/store'
1
2
  import { wsUrl } from '@/client/lib/ws-url'
2
3
  import { COLLAB_PROTOCOL_VERSION } from '@/lib/collab/protocol'
3
4
  import type {
@@ -8,12 +9,7 @@ import type {
8
9
  PresenceRegistration
9
10
  } from '@/lib/collab/types'
10
11
 
11
- import {
12
- getCurrentUser,
13
- getDirectory,
14
- subscribeCurrentUserStore,
15
- subscribeDirectoryStore
16
- } from './host-state'
12
+ import { getCurrentUser, subscribeCurrentUserStore, getCurrentUserSource } from '../host-state'
17
13
  import { CollabStore, DISCONNECTED_STATE } from './store'
18
14
  import type { ClientState, PresenceEntry } from './store'
19
15
 
@@ -31,8 +27,7 @@ export type CollabEngineApi = {
31
27
  subscribe: (listener: () => void) => Unsubscribe
32
28
  getCurrentUser: () => UserProfile | undefined
33
29
  subscribeCurrentUser: (listener: () => void) => Unsubscribe
34
- // Everyone an outer host published. Undefined without a host, in which
35
- // case live users stand in.
30
+ // Authoritative members of this workspace; never an app-wide directory.
36
31
  getDirectory: () => readonly UserProfile[] | undefined
37
32
  subscribeDirectory: (listener: () => void) => Unsubscribe
38
33
  getLocation: () => ConnectionLocation | null
@@ -54,8 +49,8 @@ export const NO_ENGINE: CollabEngineApi = {
54
49
  subscribe: () => noop,
55
50
  getCurrentUser,
56
51
  subscribeCurrentUser: subscribeCurrentUserStore,
57
- getDirectory,
58
- subscribeDirectory: subscribeDirectoryStore,
52
+ getDirectory: () => undefined,
53
+ subscribeDirectory: () => noop,
59
54
  getLocation: () => null,
60
55
  setLocation: noop,
61
56
  setPresence: noop,
@@ -68,12 +63,14 @@ export class CollabClient implements CollabEngineApi {
68
63
  private socket: WebSocket | null = null
69
64
  private retry: ReturnType<typeof setTimeout> | undefined
70
65
  private heartbeat: ReturnType<typeof setInterval> | undefined
66
+ private unsubscribeMembers: (() => void) | undefined
71
67
  private unsubscribeCurrentUser: (() => void) | undefined
72
68
  private presenceTimer: ReturnType<typeof setTimeout> | undefined
73
69
  private queuedPresence = new Map<string, CollabClientMessage>()
74
70
  private stopped = true
75
71
  private attempts = 0
76
72
  private lastMessageAt = 0
73
+ private localDirectory: readonly UserProfile[] | undefined
77
74
  private userId = getCurrentUser()?.id
78
75
 
79
76
  constructor(
@@ -92,8 +89,23 @@ export class CollabClient implements CollabEngineApi {
92
89
  this.enabled ? this.store.subscribe(listener) : noop
93
90
  getCurrentUser = getCurrentUser
94
91
  subscribeCurrentUser = subscribeCurrentUserStore
95
- getDirectory = getDirectory
96
- subscribeDirectory = subscribeDirectoryStore
92
+ getDirectory = () => {
93
+ const members = getWorkspaceDirectory(this.workspaceId)
94
+ if (members !== undefined) return members
95
+ // Standalone Moi has one local viewer. Cloud membership never falls back.
96
+ const local = getCurrentUserSource() !== 'external' ? getCurrentUser() : undefined
97
+ if (!local) return undefined
98
+ if (this.localDirectory?.[0] !== local) this.localDirectory = [local]
99
+ return this.localDirectory
100
+ }
101
+ subscribeDirectory = (listener: () => void) => {
102
+ const members = subscribeWorkspaceDirectory(listener)
103
+ const identity = subscribeCurrentUserStore(listener)
104
+ return () => {
105
+ members()
106
+ identity()
107
+ }
108
+ }
97
109
  getLocation = (): ConnectionLocation | null => (this.enabled ? this.store.getLocation() : null)
98
110
  setLocation = (location: ConnectionLocation | null): void => {
99
111
  this.store.setLocation(location)
@@ -120,12 +132,24 @@ export class CollabClient implements CollabEngineApi {
120
132
  else this.connect()
121
133
  } else if (profile) this.send({ type: 'profile', profile })
122
134
  })
135
+ this.unsubscribeMembers = subscribeWorkspaceDirectory(() => {
136
+ if (!this.wantsConnection()) {
137
+ clearTimeout(this.retry)
138
+ this.socket?.close()
139
+ this.store.disconnect()
140
+ } else this.connect()
141
+ })
123
142
  this.connect()
124
143
  return () => this.stop()
125
144
  }
126
145
 
127
146
  private wantsConnection(): boolean {
128
- return !this.stopped && getCurrentUser() !== undefined
147
+ const viewer = getCurrentUser()
148
+ return (
149
+ !this.stopped &&
150
+ viewer !== undefined &&
151
+ this.getDirectory()?.some(member => member.id === viewer.id) === true
152
+ )
129
153
  }
130
154
 
131
155
  private connect(): void {
@@ -226,6 +250,7 @@ export class CollabClient implements CollabEngineApi {
226
250
  private stop(): void {
227
251
  this.stopped = true
228
252
  this.unsubscribeCurrentUser?.()
253
+ this.unsubscribeMembers?.()
229
254
  clearTimeout(this.retry)
230
255
  clearTimeout(this.presenceTimer)
231
256
  this.presenceTimer = undefined
@@ -7,15 +7,18 @@ import {
7
7
  useSyncExternalStore
8
8
  } from 'react'
9
9
  import type { JsonValue } from 'moi'
10
+ import type { UserProfile } from '@/lib/collab/types'
10
11
  import type { PresenceValue } from 'moi/collab'
11
12
 
12
13
  import { useAppletPresence, useCollabEngine } from './provider'
13
- import { resolvePeers, resolveUser, workspaceProfiles } from './users'
14
+ import { resolvePeers, resolveUser, userStatus } from './users'
14
15
  import type { WorkspaceUser, UsePeersOptions, UseWorkspaceUsersOptions } from './users'
15
16
  import { createPresencePublisher } from './presence-publisher'
16
17
 
17
18
  export type { WorkspaceUser, UsePeersOptions, UseWorkspaceUsersOptions } from './users'
18
19
 
20
+ const EMPTY_USERS: readonly UserProfile[] = []
21
+
19
22
  export function useConnectionState() {
20
23
  const engine = useCollabEngine()
21
24
  return useSyncExternalStore(engine.subscribe, engine.getUsersSnapshot, engine.getUsersSnapshot)
@@ -33,10 +36,8 @@ function useUsersSource() {
33
36
  engine.getDirectory,
34
37
  engine.getDirectory
35
38
  )
36
- const users = useMemo(
37
- () => workspaceProfiles(state.users, self, directory),
38
- [state.users, self, directory]
39
- )
39
+ // Live connections describe activity; only the directory establishes membership.
40
+ const users = directory ?? EMPTY_USERS
40
41
  return { state, self, users, engine }
41
42
  }
42
43
  export function useUser(id: string): WorkspaceUser | undefined {
@@ -58,10 +59,10 @@ export function useWorkspaceUsers({ status }: UseWorkspaceUsersOptions = {}): Wo
58
59
  )
59
60
  }
60
61
  export function useMe(): WorkspaceUser | undefined {
61
- const { state, self, users } = useUsersSource()
62
+ const { state, self } = useUsersSource()
62
63
  return useMemo(
63
- () => (self ? resolveUser({ ...state, users }, self.id) : undefined),
64
- [state, self, users]
64
+ () => (self ? { ...self, status: userStatus(state.connections, self.id) } : undefined),
65
+ [state, self]
65
66
  )
66
67
  }
67
68
  export function usePeers(options: UsePeersOptions = {}): WorkspaceUser[] {