moi-computer 0.13.0 → 0.13.1-next.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 (51) hide show
  1. package/client/api/query-client.ts +5 -0
  2. package/client/app/app-router.tsx +1 -1
  3. package/client/app/routes/workspace-route.tsx +2 -0
  4. package/client/features/account/account-provider.tsx +28 -77
  5. package/client/features/account/account-test-utils.tsx +95 -93
  6. package/client/features/account/api.ts +32 -109
  7. package/client/features/account/profile-actions.ts +31 -0
  8. package/client/features/app-settings/settings-page.tsx +0 -4
  9. package/client/features/collab/client.ts +38 -13
  10. package/client/features/collab/hooks.tsx +9 -8
  11. package/client/features/collab/host-state.ts +45 -85
  12. package/client/features/collab/testing/fake-engine.ts +13 -1
  13. package/client/features/collab/users.ts +0 -12
  14. package/client/features/dev/cloud-avatar-upload.tsx +58 -0
  15. package/client/features/dev/cloud-page.tsx +363 -0
  16. package/client/features/dev/dev-index-page.tsx +6 -0
  17. package/client/features/dev/dev-routes.tsx +2 -0
  18. package/client/features/identity/host-api.ts +34 -0
  19. package/client/features/identity/store.ts +32 -0
  20. package/client/features/identity/types.ts +41 -0
  21. package/client/features/identity/use-identity.ts +6 -0
  22. package/client/features/workspace-members/api.ts +20 -0
  23. package/client/features/workspace-members/hooks.ts +127 -0
  24. package/client/features/workspace-members/keys.ts +6 -0
  25. package/client/features/workspace-members/store.ts +123 -0
  26. package/client/features/workspace-members/types.ts +53 -0
  27. package/client/index.html +1 -1
  28. package/client/index.tsx +5 -9
  29. package/client/main.tsx +2 -2
  30. package/dist/{chunk-cqt3s31j.js → chunk-00s35r33.js} +68 -68
  31. package/dist/{chunk-bncc7heg.js → chunk-7rz6g7g7.js} +1 -1
  32. package/dist/chunk-af2jyddf.js +2 -0
  33. package/dist/chunk-cekekc3f.css +1 -0
  34. package/dist/chunk-ep5vh16c.js +75 -0
  35. package/dist/{chunk-2y59vrxg.js → chunk-kdgk4dac.js} +1 -1
  36. package/dist/chunk-s5s1vzdw.js +2 -0
  37. package/dist/{chunk-58dyt9bk.js → chunk-svxhxfeq.js} +2 -2
  38. package/dist/chunk-t0r0bds1.js +1 -0
  39. package/dist/chunk-vp2qzc0d.js +1 -0
  40. package/dist/{chunk-q37knr3m.js → chunk-wz5qv1bn.js} +2 -2
  41. package/dist/index.html +2 -2
  42. package/package.json +5 -4
  43. package/server/app-config.ts +3 -1
  44. package/client/features/account/identity.ts +0 -23
  45. package/client/features/app-settings/users-settings.tsx +0 -195
  46. package/dist/chunk-dcmks9sm.js +0 -75
  47. package/dist/chunk-md45evr2.css +0 -1
  48. package/dist/chunk-n0nab26d.js +0 -1
  49. package/dist/chunk-nmzhgyp9.js +0 -2
  50. package/dist/chunk-s90m4qkz.js +0 -1
  51. package/dist/chunk-wjvd4byz.js +0 -2
@@ -0,0 +1,363 @@
1
+ import { useState } from 'react'
2
+ import { Link } from 'wouter'
3
+ import { IconArrowLeft, IconMail, IconUserPlus } from '@tabler/icons-react'
4
+ import { Button } from '@/client/components/ui/button'
5
+ import { Input } from '@/client/components/ui/input'
6
+ import { Skeleton } from '@/client/components/ui/skeleton'
7
+ import { Alert, AlertDescription } from '@/ui-components/alert'
8
+ import { Badge } from '@/ui-components/badge'
9
+ import {
10
+ AlertDialog,
11
+ AlertDialogAction,
12
+ AlertDialogCancel,
13
+ AlertDialogContent,
14
+ AlertDialogDescription,
15
+ AlertDialogFooter,
16
+ AlertDialogHeader,
17
+ AlertDialogTitle
18
+ } from '@/ui-components/alert-dialog'
19
+ import {
20
+ Select,
21
+ SelectContent,
22
+ SelectItem,
23
+ SelectTrigger,
24
+ SelectValue
25
+ } from '@/ui-components/select'
26
+ import { useAppConfig } from '@/client/api/app-config'
27
+ import { UserAvatar } from '../collab/components/user-avatar'
28
+ import { normalizeUserProfile } from '../collab/host-state'
29
+ import { collabIdentityId } from '../identity/types'
30
+ import { useIdentity } from '../identity/use-identity'
31
+ import { useWorkspaces } from '../home/api'
32
+ import {
33
+ useWorkspaceMembers,
34
+ useInviteMember,
35
+ useRemoveMember,
36
+ useRevokeInvitation
37
+ } from '../workspace-members/hooks'
38
+ import type { WorkspaceMember } from '../workspace-members/types'
39
+ import { CloudAvatarUpload } from './cloud-avatar-upload'
40
+
41
+ export function CloudPage() {
42
+ const { environment } = useAppConfig()
43
+ if (environment !== 'cloud')
44
+ return (
45
+ <main className="mx-auto max-w-xl space-y-4 px-6 py-10 text-sm">
46
+ <h1 className="text-xl font-medium">Share workspace</h1>
47
+ <p className="text-muted-foreground">
48
+ Workspace sharing is available when you sign in to Moi Run
49
+ </p>
50
+ <Button variant="outline" nativeButton={false} render={<Link href="/" />}>
51
+ Back to workspaces
52
+ </Button>
53
+ </main>
54
+ )
55
+ return <WorkspaceSharing />
56
+ }
57
+
58
+ function WorkspaceSharing() {
59
+ const workspaces = useWorkspaces()
60
+ const [selected, setSelected] = useState<string>()
61
+ const workspace = workspaces.data?.find(item => item.id === selected) ?? workspaces.data?.[0]
62
+ const name = workspace?.name || 'Workspace'
63
+ return (
64
+ <main className="mx-auto flex max-w-xl flex-col gap-8 px-5 py-8 text-sm sm:px-6 sm:py-12">
65
+ <header className="space-y-5">
66
+ <Button
67
+ variant="ghost"
68
+ size="sm"
69
+ className="-ml-2 w-fit"
70
+ nativeButton={false}
71
+ render={<Link href="/" />}
72
+ >
73
+ <IconArrowLeft stroke={1.75} /> Workspaces
74
+ </Button>
75
+ <div className="space-y-2">
76
+ <h1 className="text-xl font-medium">Share workspace</h1>
77
+ <p className="text-muted-foreground">Invite people to work alongside you</p>
78
+ </div>
79
+ </header>
80
+ <section className="space-y-2" aria-label="Choose workspace">
81
+ <label className="font-medium" id="sharing-workspace-label">
82
+ Workspace
83
+ </label>
84
+ {workspaces.isError ? (
85
+ <Alert variant="destructive">
86
+ <AlertDescription>{workspaces.error.message}</AlertDescription>
87
+ </Alert>
88
+ ) : workspaces.isPending ? (
89
+ <Skeleton className="h-10 w-full" />
90
+ ) : !workspace ? (
91
+ <p className="text-muted-foreground">Create a workspace to invite people</p>
92
+ ) : (
93
+ <Select value={workspace.id} onValueChange={value => setSelected(value ?? undefined)}>
94
+ <SelectTrigger className="w-full" aria-labelledby="sharing-workspace-label">
95
+ <SelectValue>{name}</SelectValue>
96
+ </SelectTrigger>
97
+ <SelectContent align="start">
98
+ {workspaces.data.map(item => (
99
+ <SelectItem key={item.id} value={item.id}>
100
+ {item.name || 'Workspace'}
101
+ </SelectItem>
102
+ ))}
103
+ </SelectContent>
104
+ </Select>
105
+ )}
106
+ </section>
107
+ {workspace && (
108
+ <SharingMembers key={workspace.id} workspaceId={workspace.id} workspaceName={name} />
109
+ )}
110
+ </main>
111
+ )
112
+ }
113
+
114
+ type SharingMembersProps = { workspaceId: string; workspaceName: string }
115
+ type Removal =
116
+ | { type: 'member'; id: string; name: string }
117
+ | { type: 'invitation'; id: string; email: string }
118
+ function SharingMembers({ workspaceId, workspaceName }: SharingMembersProps) {
119
+ const identity = useIdentity()
120
+ const snapshot = useWorkspaceMembers(workspaceId)
121
+ const invite = useInviteMember(workspaceId)
122
+ const remove = useRemoveMember(workspaceId)
123
+ const revoke = useRevokeInvitation(workspaceId)
124
+ const [email, setEmail] = useState('')
125
+ const [removal, setRemoval] = useState<Removal>()
126
+ const [notice, setNotice] = useState<string>()
127
+ const removing = remove.isPending || revoke.isPending
128
+ const removalError = remove.error ?? revoke.error
129
+ async function sendInvitation() {
130
+ setNotice(undefined)
131
+ try {
132
+ await invite.mutateAsync({ email })
133
+ setEmail('')
134
+ setNotice(`Invitation sent to ${email.trim().toLowerCase()}`)
135
+ } catch {
136
+ /* Keep the address so the invitation can be retried. */
137
+ }
138
+ }
139
+ function chooseRemoval(next: Removal) {
140
+ remove.reset()
141
+ revoke.reset()
142
+ setRemoval(next)
143
+ }
144
+ async function confirmRemoval() {
145
+ if (!removal) return
146
+ try {
147
+ if (removal.type === 'member') await remove.mutateAsync({ membershipId: removal.id })
148
+ else await revoke.mutateAsync({ invitationId: removal.id })
149
+ setNotice(removal.type === 'member' ? 'Member removed' : 'Invitation revoked')
150
+ setRemoval(undefined)
151
+ } catch {
152
+ /* The dialog keeps the error visible and allows retry. */
153
+ }
154
+ }
155
+ const inviteError = invite.error ?? snapshot.error
156
+ return (
157
+ <>
158
+ <section className="space-y-3" aria-labelledby="invite-heading">
159
+ <h2 className="font-medium" id="invite-heading">
160
+ Invite someone
161
+ </h2>
162
+ <form
163
+ className="flex flex-col gap-2 sm:flex-row"
164
+ onSubmit={event => {
165
+ event.preventDefault()
166
+ void sendInvitation()
167
+ }}
168
+ >
169
+ <Input
170
+ type="email"
171
+ required
172
+ aria-label="Email address"
173
+ placeholder="Email address"
174
+ autoComplete="email"
175
+ value={email}
176
+ className="min-w-0 flex-1"
177
+ onChange={event => {
178
+ setEmail(event.target.value)
179
+ setNotice(undefined)
180
+ }}
181
+ disabled={invite.isPending || !snapshot.data}
182
+ />
183
+ <Button type="submit" disabled={invite.isPending || !snapshot.data || !email.trim()}>
184
+ <IconUserPlus stroke={1.5} /> {invite.isPending ? 'Sending…' : 'Send invite'}
185
+ </Button>
186
+ </form>
187
+ <p className="text-muted-foreground">
188
+ Members can view and edit everything in this workspace
189
+ </p>
190
+ {notice && <p role="status">{notice}</p>}
191
+ {inviteError && (
192
+ <Alert variant="destructive">
193
+ <AlertDescription>{inviteError.message}</AlertDescription>
194
+ </Alert>
195
+ )}
196
+ {snapshot.isError && (
197
+ <Button size="sm" variant="outline" onClick={() => void snapshot.refetch()}>
198
+ Try again
199
+ </Button>
200
+ )}
201
+ </section>
202
+ <section aria-labelledby="members-heading" className="space-y-3">
203
+ <h2 id="members-heading" className="flex items-center gap-2 font-medium">
204
+ Members{' '}
205
+ {snapshot.members && (
206
+ <span className="font-normal text-muted-foreground">{snapshot.members.length}</span>
207
+ )}
208
+ </h2>
209
+ {snapshot.isPending ? (
210
+ <div className="space-y-4" aria-label="Loading members">
211
+ {[0, 1].map(row => (
212
+ <div key={row} className="flex items-center gap-3">
213
+ <Skeleton className="size-8 rounded-full" />
214
+ <Skeleton className="h-4 w-40" />
215
+ </div>
216
+ ))}
217
+ </div>
218
+ ) : (
219
+ <ul className="divide-y divide-border">
220
+ {snapshot.members?.map(member => {
221
+ const isMe = identity?.type === member.type && identity.id === member.id
222
+ const displayName = member.name || (member.type === 'user' ? member.email : 'Agent')
223
+ return (
224
+ <li
225
+ key={`${member.type}:${member.id}`}
226
+ className="flex min-w-0 items-center gap-3 py-3"
227
+ >
228
+ {isMe && identity?.type === 'user' ? (
229
+ <CloudAvatarUpload>
230
+ <MemberAvatar member={{ ...member, ...identity }} />
231
+ </CloudAvatarUpload>
232
+ ) : (
233
+ <MemberAvatar member={member} />
234
+ )}
235
+ <div className="min-w-0 flex-1">
236
+ <p className="truncate font-medium">
237
+ {displayName}
238
+ {isMe && <span className="font-normal text-muted-foreground"> (you)</span>}
239
+ </p>
240
+ {member.type === 'user' && (
241
+ <p className="truncate text-muted-foreground">{member.email}</p>
242
+ )}
243
+ {member.type === 'agent' && <p className="text-muted-foreground">Agent</p>}
244
+ </div>
245
+ {!member.membershipId ? (
246
+ <Badge variant="secondary">Owner</Badge>
247
+ ) : (
248
+ <Button
249
+ size="sm"
250
+ variant="ghost"
251
+ onClick={() =>
252
+ chooseRemoval({
253
+ type: 'member',
254
+ id: member.membershipId!,
255
+ name: displayName
256
+ })
257
+ }
258
+ >
259
+ Remove
260
+ </Button>
261
+ )}
262
+ </li>
263
+ )
264
+ })}
265
+ </ul>
266
+ )}
267
+ </section>
268
+ {!!snapshot.invitations?.length && (
269
+ <section aria-labelledby="invitations-heading" className="space-y-3">
270
+ <h2 id="invitations-heading" className="flex items-center gap-2 font-medium">
271
+ Pending invitations{' '}
272
+ <span className="font-normal text-muted-foreground">{snapshot.invitations.length}</span>
273
+ </h2>
274
+ <ul className="divide-y divide-border">
275
+ {snapshot.invitations.map(invitation => (
276
+ <li key={invitation.id} className="flex min-w-0 items-center gap-3 py-3">
277
+ <span className="flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground">
278
+ <IconMail size={16} stroke={1.75} />
279
+ </span>
280
+ <div className="min-w-0 flex-1">
281
+ <p className="truncate font-medium">{invitation.email}</p>
282
+ <p className="text-muted-foreground">
283
+ {invitation.pending
284
+ ? 'Sending invitation…'
285
+ : `Invited · Expires ${new Date(invitation.expiresAt).toLocaleDateString(undefined, { month: 'short', day: 'numeric' })}`}
286
+ </p>
287
+ </div>
288
+ {!invitation.pending && (
289
+ <Button
290
+ size="sm"
291
+ variant="ghost"
292
+ onClick={() =>
293
+ chooseRemoval({
294
+ type: 'invitation',
295
+ id: invitation.id,
296
+ email: invitation.email
297
+ })
298
+ }
299
+ >
300
+ Revoke
301
+ </Button>
302
+ )}
303
+ </li>
304
+ ))}
305
+ </ul>
306
+ </section>
307
+ )}
308
+ <AlertDialog
309
+ open={!!removal}
310
+ onOpenChange={open => {
311
+ if (!open && !removing) setRemoval(undefined)
312
+ }}
313
+ >
314
+ <AlertDialogContent>
315
+ <AlertDialogHeader>
316
+ <AlertDialogTitle>
317
+ {removal?.type === 'member' ? `Remove ${removal.name}?` : 'Revoke invitation?'}
318
+ </AlertDialogTitle>
319
+ <AlertDialogDescription>
320
+ {removal?.type === 'member'
321
+ ? `They’ll lose access to ${workspaceName}. You can invite them again later.`
322
+ : `The invitation for ${removal?.email ?? ''} will no longer work.`}
323
+ </AlertDialogDescription>
324
+ </AlertDialogHeader>
325
+ {removalError && (
326
+ <Alert variant="destructive">
327
+ <AlertDescription>{removalError.message}</AlertDescription>
328
+ </Alert>
329
+ )}
330
+ <AlertDialogFooter>
331
+ <AlertDialogCancel disabled={removing}>Cancel</AlertDialogCancel>
332
+ <AlertDialogAction
333
+ variant="destructive"
334
+ disabled={removing}
335
+ onClick={() => void confirmRemoval()}
336
+ >
337
+ {removing
338
+ ? 'Saving…'
339
+ : removal?.type === 'member'
340
+ ? 'Remove member'
341
+ : 'Revoke invitation'}
342
+ </AlertDialogAction>
343
+ </AlertDialogFooter>
344
+ </AlertDialogContent>
345
+ </AlertDialog>
346
+ </>
347
+ )
348
+ }
349
+
350
+ type MemberAvatarProps = { member: WorkspaceMember }
351
+ function MemberAvatar({ member }: MemberAvatarProps) {
352
+ return (
353
+ <UserAvatar
354
+ profile={normalizeUserProfile({
355
+ id: collabIdentityId(member),
356
+ name: member.name || undefined,
357
+ avatar: member.avatar,
358
+ email: member.type === 'user' ? member.email : undefined
359
+ })}
360
+ size="default"
361
+ />
362
+ )
363
+ }
@@ -7,6 +7,12 @@ type DevRouteEntry = {
7
7
  }
8
8
 
9
9
  const DEV_ROUTES: DevRouteEntry[] = [
10
+ {
11
+ path: '/dev/cloud',
12
+ title: 'Workspace sharing',
13
+ description:
14
+ 'Inspect identity and workspace members, update your profile, and test invitations.'
15
+ },
10
16
  {
11
17
  path: '/dev/onboarding',
12
18
  title: 'Onboarding ideas',
@@ -10,6 +10,7 @@ import { TextureLabPage } from './texture-lab-page'
10
10
  import { ToolCallsPage } from './tool-calls-page'
11
11
  import { UiComponentsPage } from './ui-components/ui-components-page'
12
12
  import { OnboardingPreviewPage } from './onboarding-preview-page'
13
+ import { CloudPage } from './cloud-page'
13
14
 
14
15
  // All /dev/* routes live with their pages here and load only in development;
15
16
  // see the dynamic import in AppRouter. /dev itself is the index; list new
@@ -21,6 +22,7 @@ const CollabPage = lazy(() =>
21
22
  export default function DevRoutes() {
22
23
  return (
23
24
  <Switch>
25
+ <Route path="/dev/cloud" component={CloudPage} />
24
26
  <Route path="/dev/onboarding" component={OnboardingPreviewPage} />
25
27
  <Route path="/dev/collab-kit">
26
28
  <Redirect to="/dev/collab" />
@@ -0,0 +1,34 @@
1
+ import { setIdentity, getIdentityRevision } from './store'
2
+ import {
3
+ setWorkspaceMembers,
4
+ setAllWorkspaceMembers,
5
+ removeWorkspaceMembers,
6
+ clearWorkspaceMembers,
7
+ getWorkspaceMembersRevision
8
+ } from '../workspace-members/store'
9
+ import type { Identity } from './types'
10
+ import type { WorkspaceMembers, WorkspaceMembersSnapshot } from '../workspace-members/types'
11
+
12
+ export type IdentityHostApi = {
13
+ identity: { set: (identity: Identity | null) => void; getRevision: () => number }
14
+ workspaceMembers: {
15
+ set: (workspaceId: string, data: WorkspaceMembers) => void
16
+ setAll: (workspaces: WorkspaceMembersSnapshot[]) => void
17
+ remove: (workspaceId: string) => void
18
+ clear: () => void
19
+ getRevision: () => number
20
+ }
21
+ }
22
+ export function installIdentityHostApi() {
23
+ if (typeof window === 'undefined') return
24
+ const host = window as Window & { moi?: Partial<IdentityHostApi> & Record<string, unknown> }
25
+ host.moi ??= {}
26
+ host.moi.identity = { set: setIdentity, getRevision: getIdentityRevision }
27
+ host.moi.workspaceMembers = {
28
+ set: setWorkspaceMembers,
29
+ setAll: setAllWorkspaceMembers,
30
+ remove: removeWorkspaceMembers,
31
+ clear: clearWorkspaceMembers,
32
+ getRevision: getWorkspaceMembersRevision
33
+ }
34
+ }
@@ -0,0 +1,32 @@
1
+ import { queryClient } from '@/client/api/query-client'
2
+ import { memberKeys } from '../workspace-members/keys'
3
+ import { identityKey, parseIdentity } from './types'
4
+ import type { Identity } from './types'
5
+
6
+ let current: Identity | null | undefined
7
+ // Changes only when the account changes; guards requests from a previous account.
8
+ let accountGeneration = 0
9
+ // Changes on every identity write; guards against older profile responses.
10
+ let identityRevision = 0
11
+ const listeners = new Set<() => void>()
12
+ export const getIdentity = () => current
13
+ export const getIdentityRevision = () => identityRevision
14
+ export const getAccountGeneration = () => accountGeneration
15
+ export function subscribeIdentity(listener: () => void) {
16
+ listeners.add(listener)
17
+ return () => {
18
+ listeners.delete(listener)
19
+ }
20
+ }
21
+ export function setIdentity(value: Identity | null): void {
22
+ const next = value === null ? null : parseIdentity(value)
23
+ const changedAccount = (current && identityKey(current)) !== (next && identityKey(next))
24
+ if (changedAccount) {
25
+ accountGeneration++
26
+ void queryClient.cancelQueries({ queryKey: memberKeys.all })
27
+ queryClient.removeQueries({ queryKey: memberKeys.all })
28
+ }
29
+ identityRevision++
30
+ current = next
31
+ listeners.forEach(listener => listener())
32
+ }
@@ -0,0 +1,41 @@
1
+ import { isRecord } from '@/lib/collab/protocol'
2
+
3
+ export type Identity =
4
+ | { id: string; type: 'user'; name: string; email: string; avatar?: string; isAnonymous: boolean }
5
+ | { id: string; type: 'agent'; name: string; avatar?: string }
6
+
7
+ function text(value: unknown, max: number): value is string {
8
+ return typeof value === 'string' && value.length <= max && !value.includes('\0')
9
+ }
10
+ function isAvatar(value: unknown): value is string {
11
+ if (!text(value, 2048)) return false
12
+ try {
13
+ return ['http:', 'https:'].includes(new URL(value).protocol)
14
+ } catch {
15
+ return false
16
+ }
17
+ }
18
+ export function parseIdentity(value: unknown): Identity {
19
+ if (
20
+ !isRecord(value) ||
21
+ !text(value.id, 240) ||
22
+ !value.id.trim() ||
23
+ value.id !== value.id.trim() ||
24
+ !text(value.name, 256) ||
25
+ (value.avatar !== undefined && !isAvatar(value.avatar))
26
+ )
27
+ throw new Error('Invalid identity')
28
+ const common = {
29
+ id: value.id,
30
+ name: value.name,
31
+ ...(value.avatar !== undefined ? { avatar: value.avatar } : {})
32
+ }
33
+ if (value.type === 'agent') return { ...common, type: 'agent' }
34
+ if (value.type === 'user' && text(value.email, 320) && typeof value.isAnonymous === 'boolean')
35
+ return { ...common, type: 'user', email: value.email, isAnonymous: value.isAnonymous }
36
+ throw new Error('Invalid identity')
37
+ }
38
+ export const identityKey = (identity: Identity) => `${identity.type}:${identity.id}`
39
+ // Existing human collaboration ids stay compatible; agent ids cannot collide.
40
+ export const collabIdentityId = (identity: Identity) =>
41
+ identity.type === 'agent' ? `agent:${identity.id}` : identity.id
@@ -0,0 +1,6 @@
1
+ import { useSyncExternalStore } from 'react'
2
+ import { subscribeIdentity, getIdentity } from './store'
3
+
4
+ export function useIdentity() {
5
+ return useSyncExternalStore(subscribeIdentity, getIdentity, getIdentity)
6
+ }
@@ -0,0 +1,20 @@
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) =>
12
+ cloudRequest(`${workspaceMembersPath(id)}/invitations`, jsonRequest('POST', { email }))
13
+ export const removeWorkspaceMember = (id: string, membershipId: string) =>
14
+ cloudRequest(`${workspaceMembersPath(id)}/members/${encodeURIComponent(membershipId)}`, {
15
+ method: 'DELETE'
16
+ })
17
+ export const revokeWorkspaceInvitation = (id: string, invitationId: string) =>
18
+ cloudRequest(`${workspaceMembersPath(id)}/invitations/${encodeURIComponent(invitationId)}`, {
19
+ method: 'DELETE'
20
+ })
@@ -0,0 +1,127 @@
1
+ import { useMutation, useMutationState, useQuery, useQueryClient } from '@tanstack/react-query'
2
+ import { getAccountGeneration } from '../identity/store'
3
+ import { useIdentity } from '../identity/use-identity'
4
+ import { ownerOnlyWorkspaceMembers } from './store'
5
+ import { memberKeys } from './keys'
6
+ import { identityKey } from '../identity/types'
7
+ import {
8
+ fetchWorkspaceMembers,
9
+ inviteWorkspaceMember,
10
+ removeWorkspaceMember,
11
+ revokeWorkspaceInvitation
12
+ } from './api'
13
+ import type { WorkspaceMembers } from './types'
14
+
15
+ export type MembershipAction =
16
+ | { type: 'invite'; email: string }
17
+ | { type: 'remove'; membershipId: string }
18
+ | { type: 'revoke'; invitationId: string }
19
+
20
+ type PendingAction = { id: number; action: MembershipAction }
21
+ export function applyPendingMembership(
22
+ data: WorkspaceMembers | undefined,
23
+ actions: PendingAction[]
24
+ ) {
25
+ if (!data) return undefined
26
+ let { members, invitations } = data
27
+ for (const { id, action } of actions) {
28
+ if (action.type === 'remove')
29
+ members = members.filter(member => member.membershipId !== action.membershipId)
30
+ else if (action.type === 'revoke')
31
+ invitations = invitations.filter(invitation => invitation.id !== action.invitationId)
32
+ else if (!invitations.some(invitation => invitation.email === action.email))
33
+ invitations = [
34
+ ...invitations,
35
+ { id: `pending:${id}`, email: action.email, expiresAt: '', pending: true }
36
+ ]
37
+ }
38
+ return { members, invitations }
39
+ }
40
+ export function useWorkspaceMembers(workspaceId: string | undefined) {
41
+ const identity = useIdentity()
42
+ const accountId = identity ? identityKey(identity) : undefined
43
+ const enabled = !!workspaceId && identity?.type === 'user' && !identity.isAnonymous
44
+ const accountGeneration = getAccountGeneration()
45
+ const mutationKey = ['workspace-members-action', accountGeneration, workspaceId]
46
+ const query = useQuery({
47
+ queryKey: memberKeys.workspace(accountId, workspaceId ?? ''),
48
+ initialData: ownerOnlyWorkspaceMembers,
49
+ queryFn: async ({ signal }) => {
50
+ const snapshot = await fetchWorkspaceMembers(workspaceId!, signal)
51
+ if (signal.aborted || accountGeneration !== getAccountGeneration())
52
+ throw new Error('Identity changed')
53
+ return snapshot
54
+ },
55
+ enabled,
56
+ retry: false,
57
+ staleTime: 30_000
58
+ })
59
+ const pending = useMutationState({
60
+ filters: { mutationKey, status: 'pending', exact: true },
61
+ select: mutation => ({
62
+ id: mutation.state.submittedAt,
63
+ action: mutation.state.variables as MembershipAction
64
+ })
65
+ })
66
+ const data = applyPendingMembership(query.data, pending)
67
+ return { ...query, data, members: data?.members, invitations: data?.invitations }
68
+ }
69
+ function useMembershipAction(workspaceId: string) {
70
+ const identity = useIdentity()
71
+ const accountId = identity ? identityKey(identity) : undefined
72
+ const accountGeneration = getAccountGeneration()
73
+ const client = useQueryClient()
74
+ return useMutation({
75
+ mutationKey: ['workspace-members-action', accountGeneration, workspaceId],
76
+ mutationFn: async (action: MembershipAction) => {
77
+ if (
78
+ !identity ||
79
+ identity.type !== 'user' ||
80
+ identity.isAnonymous ||
81
+ accountGeneration !== getAccountGeneration()
82
+ )
83
+ throw new Error('Sign in to manage workspace members')
84
+ if (action.type === 'invite') return inviteWorkspaceMember(workspaceId, action.email)
85
+ if (action.type === 'remove') return removeWorkspaceMember(workspaceId, action.membershipId)
86
+ return revokeWorkspaceInvitation(workspaceId, action.invitationId)
87
+ },
88
+ onSuccess: async () => {
89
+ if (accountGeneration !== getAccountGeneration()) return
90
+ // Keep the optimistic overlay until the canonical snapshot has caught up.
91
+ await client.invalidateQueries({
92
+ queryKey: memberKeys.workspace(accountId, workspaceId),
93
+ exact: true
94
+ })
95
+ }
96
+ })
97
+ }
98
+ export function useInviteMember(workspaceId: string) {
99
+ const mutation = useMembershipAction(workspaceId)
100
+ return {
101
+ ...mutation,
102
+ mutate: ({ email }: { email: string }) =>
103
+ mutation.mutate({ type: 'invite', email: email.trim().toLowerCase() }),
104
+ mutateAsync: ({ email }: { email: string }) =>
105
+ mutation.mutateAsync({ type: 'invite', email: email.trim().toLowerCase() })
106
+ }
107
+ }
108
+ export function useRemoveMember(workspaceId: string) {
109
+ const mutation = useMembershipAction(workspaceId)
110
+ return {
111
+ ...mutation,
112
+ mutate: ({ membershipId }: { membershipId: string }) =>
113
+ mutation.mutate({ type: 'remove', membershipId }),
114
+ mutateAsync: ({ membershipId }: { membershipId: string }) =>
115
+ mutation.mutateAsync({ type: 'remove', membershipId })
116
+ }
117
+ }
118
+ export function useRevokeInvitation(workspaceId: string) {
119
+ const mutation = useMembershipAction(workspaceId)
120
+ return {
121
+ ...mutation,
122
+ mutate: ({ invitationId }: { invitationId: string }) =>
123
+ mutation.mutate({ type: 'revoke', invitationId }),
124
+ mutateAsync: ({ invitationId }: { invitationId: string }) =>
125
+ mutation.mutateAsync({ type: 'revoke', invitationId })
126
+ }
127
+ }
@@ -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
+ }