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
@@ -12,7 +12,6 @@ import { requestJson } from './http'
12
12
 
13
13
  const DEFAULTS: ClientAppConfig = {
14
14
  environment: 'local',
15
- collab: false,
16
15
  demo: false,
17
16
  demoInstallUrl: 'https://moi.computer'
18
17
  }
@@ -0,0 +1,5 @@
1
+ import { QueryClient } from '@tanstack/query-core'
2
+
3
+ // Shared with the host API so it can populate workspace members before React mounts
4
+ // and clear cached members when the account changes.
5
+ export const queryClient = new QueryClient()
@@ -14,7 +14,7 @@ import { WorkspaceRoute } from './routes/workspace-route'
14
14
  // separate lazy chunk. The NODE_ENV gate is statically false in the prod
15
15
  // build (scripts/build-client.ts defines it), so the bundler drops the
16
16
  // dynamic import and none of features/dev is emitted into dist at all.
17
- // In prod /dev redirects home.
17
+ // In production /dev redirects home.
18
18
  const DevRoutes =
19
19
  process.env.NODE_ENV === 'development'
20
20
  ? lazy(() => import('@/client/features/dev/dev-routes'))
@@ -1,6 +1,7 @@
1
+ import { useWorkspaceMembers } from '@/client/features/collab/members/hooks'
1
2
  import { useWorkspaceHarnessChanges } from '@/client/features/workspace/harness-transition'
2
3
  import { useWorkspaceTheme } from '@/client/runtime/workspace-theme'
3
- import { CollabProvider, useCollabEnabled } from '@/client/features/collab'
4
+ import { CollabProvider } from '@/client/features/collab'
4
5
  import { useQueryClient } from '@tanstack/react-query'
5
6
 
6
7
  import { workspaceKeys } from '@/client/api/workspace-keys'
@@ -26,13 +27,14 @@ type WorkspaceRouteProps = {
26
27
  // Navigation reads the raw browser address so encoded paths and query params
27
28
  // are decoded exactly once; the route only owns the workspace ID.
28
29
  export function WorkspaceRoute({ id }: WorkspaceRouteProps) {
29
- const { collab } = useAppConfig()
30
+ useWorkspaceMembers(id)
31
+ const { environment } = useAppConfig()
30
32
 
31
33
  return (
32
34
  <SidebarLayout>
33
35
  <Workspace id={id}>
34
36
  <WorkspaceLayoutProvider id={id}>
35
- <CollabProvider workspaceId={id} enabled={collab}>
37
+ <CollabProvider workspaceId={id} enabled={environment === 'cloud'}>
36
38
  <WorkspaceContent id={id} />
37
39
  </CollabProvider>
38
40
  </WorkspaceLayoutProvider>
@@ -42,7 +44,6 @@ export function WorkspaceRoute({ id }: WorkspaceRouteProps) {
42
44
  }
43
45
 
44
46
  function WorkspaceContent({ id }: WorkspaceRouteProps) {
45
- const collabEnabled = useCollabEnabled()
46
47
  const queryClient = useQueryClient()
47
48
  const [selectedSessionId] = useSelectedSession()
48
49
  const { isLoading: layoutLoading, layout, provider } = useWorkspaceLayoutCtx()
@@ -73,9 +74,7 @@ function WorkspaceContent({ id }: WorkspaceRouteProps) {
73
74
  layoutLoading || selectedSessionId === undefined || widgets.isLoading || views.isLoading
74
75
 
75
76
  return (
76
- // Reset the screen when switching between shared and browser tab state.
77
77
  <WorkspaceScreen
78
- key={collabEnabled ? 'browser-tab' : 'shared'}
79
78
  contentPending={contentPending}
80
79
  widgets={widgets.data}
81
80
  views={views.data ?? []}
@@ -1,4 +1,5 @@
1
- import { createContext, useContext, useEffect, useState, useSyncExternalStore } from 'react'
1
+ import { useIdentity } from '../identity/use-identity'
2
+ import { createContext, useContext, useSyncExternalStore } from 'react'
2
3
  import type { ReactNode } from 'react'
3
4
  import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
4
5
  import { useAppConfig } from '@/client/api/app-config'
@@ -6,19 +7,18 @@ import {
6
7
  getCurrentUser,
7
8
  getCurrentUserSource,
8
9
  setLocalUser,
9
- subscribeCurrentUserStore,
10
- publishUsers
10
+ subscribeCurrentUserStore
11
11
  } from '@/client/features/collab/host-state'
12
+ import { setIdentity } from '../identity/store'
13
+ import { saveCloudProfile } from './profile-actions'
12
14
  import {
13
15
  accountKeys,
14
- CloudApiError,
15
- sessionQuery,
16
- teamQuery,
17
- updateCloudName,
16
+ identityRefreshQuery,
17
+ updateCloudProfile,
18
+ uploadCloudAvatar,
19
+ removeCloudAvatar,
18
20
  signOutCloud
19
21
  } from './api'
20
- import type { CloudSession } from './api'
21
- import { syncCloudIdentity } from './identity'
22
22
 
23
23
  function useAccountState() {
24
24
  const { environment, demo } = useAppConfig()
@@ -29,105 +29,56 @@ function useAccountState() {
29
29
  getCurrentUserSource,
30
30
  getCurrentUserSource
31
31
  )
32
+ const identity = useIdentity()
32
33
  const qc = useQueryClient()
33
- const session = useQuery({ ...sessionQuery, enabled: cloud && !demo })
34
- const registered = cloud && !demo && !!session.data && !session.data.user.isAnonymous
35
- const team = useQuery({ ...teamQuery(session.data?.user.id), enabled: registered })
36
- const [removingMemberIds, setRemovingMemberIds] = useState<string[]>([])
37
-
34
+ const query = useQuery({ ...identityRefreshQuery, enabled: cloud && !demo })
35
+ const registered = cloud && !demo && identity?.type === 'user' && !identity.isAnonymous
38
36
  const signOut = useMutation({
39
37
  mutationFn: signOutCloud,
40
38
  onSuccess: async () => {
41
39
  await qc.cancelQueries({ queryKey: accountKeys.all })
42
- publishUsers({ users: [] })
43
- qc.setQueryData(accountKeys.session, null)
44
- qc.removeQueries({ queryKey: accountKeys.team })
40
+ setIdentity(null)
45
41
  window.location.assign('/cloud/login')
46
42
  }
47
43
  })
48
- useEffect(() => {
49
- if (!cloud || demo || !session.isSuccess || signOut.isPending || signOut.isSuccess) return
50
- syncCloudIdentity(session.data, registered ? team.data : undefined)
51
- }, [
52
- cloud,
53
- demo,
54
- session.data,
55
- session.isSuccess,
56
- registered,
57
- team.data,
58
- signOut.isPending,
59
- signOut.isSuccess
60
- ])
61
- useEffect(() => {
62
- if (team.error instanceof CloudApiError && team.error.status === 401)
63
- void qc.invalidateQueries({ queryKey: accountKeys.session })
64
- }, [team.error, qc])
65
-
66
44
  async function saveName(value: string) {
67
45
  const name = value.trim()
68
46
  if (!name || name.length > 80) throw new Error('Enter a name of up to 80 characters')
69
47
  if (cloud) {
70
- if (!registered) throw new Error('Sign in to change your name')
71
- await qc.cancelQueries({ queryKey: accountKeys.session })
72
- await updateCloudName(name).catch(error => {
73
- if (error instanceof CloudApiError && error.status === 401)
74
- void qc.invalidateQueries({ queryKey: accountKeys.session })
75
- throw error
76
- })
77
- const latestSession = qc.getQueryData<CloudSession>(accountKeys.session)
78
- if (
79
- !latestSession ||
80
- latestSession.user.id !== session.data!.user.id ||
81
- latestSession.user.isAnonymous
82
- )
83
- throw new Error('Your account changed. Reload Moi to try again.')
84
- const next: CloudSession = { user: { ...latestSession.user, name } }
85
- qc.setQueryData(accountKeys.session, next)
86
- syncCloudIdentity(next, team.data)
87
- void qc.invalidateQueries({ queryKey: accountKeys.team })
48
+ await saveCloudProfile('name', () => updateCloudProfile({ name }))
88
49
  return name
89
50
  }
90
- const localProfile = getCurrentUser()
91
- if (getCurrentUserSource() !== 'local' || !localProfile || localProfile.id !== profile?.id)
51
+ const local = getCurrentUser()
52
+ if (getCurrentUserSource() !== 'local' || !local || local.id !== profile?.id)
92
53
  throw new Error('This profile is managed by your sign-in provider')
93
- setLocalUser({ ...localProfile, name })
54
+ setLocalUser({ ...local, name })
94
55
  return name
95
56
  }
96
-
57
+ async function saveAvatar(file: File | null) {
58
+ await saveCloudProfile('avatar', () => (file ? uploadCloudAvatar(file) : removeCloudAvatar()))
59
+ }
97
60
  function getStatus() {
98
61
  if (demo) return 'signed-out'
99
62
  if (!cloud) return profile ? 'ready' : 'error'
100
- if (session.isPending) return 'loading'
101
- if (session.isError) return 'error'
102
- if (!registered) return 'signed-out'
103
- if (profile?.id === session.data?.user.id && source === 'external') return 'ready'
104
- return 'loading'
63
+ if (identity === undefined) return query.isError ? 'error' : 'loading'
64
+ if (!identity || (identity.type === 'user' && identity.isAnonymous)) return 'signed-out'
65
+ return 'ready'
105
66
  }
106
-
107
67
  return {
108
68
  cloud,
109
- demo: demo || (cloud && session.data?.user.isAnonymous === true),
69
+ demo: demo || (identity?.type === 'user' && identity.isAnonymous),
110
70
  profile,
71
+ identity,
111
72
  status: getStatus(),
112
- email: registered ? session.data?.user.email : undefined,
73
+ email: registered && identity?.type === 'user' ? identity.email : undefined,
113
74
  canEdit: cloud ? registered : source === 'local',
114
75
  registered,
115
- team,
116
- removingMemberIds,
117
- setRemovingMemberIds,
118
76
  saveName,
77
+ saveAvatar,
119
78
  signOut,
120
- retry: () => {
121
- if (!cloud) {
122
- window.location.reload()
123
- return
124
- }
125
- void session.refetch()
126
- if (registered) void team.refetch()
127
- }
79
+ retry: () => (cloud ? void query.refetch() : window.location.reload())
128
80
  }
129
81
  }
130
-
131
82
  type AccountState = ReturnType<typeof useAccountState>
132
83
  const AccountContext = createContext<AccountState | undefined>(undefined)
133
84
  type AccountProviderProps = { children: ReactNode }
@@ -5,74 +5,50 @@ import * as layoutEffect from '@base-ui/utils/useIsoLayoutEffect'
5
5
  import { Router } from 'wouter'
6
6
  import { memoryLocation } from 'wouter/memory-location'
7
7
  import { parseHTML } from 'linkedom'
8
- import { QueryClient, QueryClientProvider, notifyManager } from '@tanstack/react-query'
8
+ import { QueryClientProvider, notifyManager } from '@tanstack/react-query'
9
9
  import * as config from '@/client/api/app-config'
10
- import { publishUsers } from '@/client/features/collab/host-state'
11
10
  import { AccountProvider, useAccount } from './account-provider'
12
- import { sessionQuery, teamQuery } from './api'
13
- import type { CloudSession, CloudTeam } from './api'
11
+ import { queryClient } from '@/client/api/query-client'
12
+ import type { WorkspaceMembers } from '../collab/members/types'
13
+ import { setIdentity } from '../identity/store'
14
+ import type { Identity } from '../identity/types'
14
15
 
15
- const session: CloudSession = {
16
- user: { id: 'me', name: 'Alex', email: 'alex@example.com', isAnonymous: false }
17
- }
18
- export const ownerTeam: CloudTeam = {
19
- id: 'team',
20
- name: 'Team',
21
- role: 'owner',
22
- members: [
23
- {
24
- id: 'member-me',
25
- userId: 'me',
26
- name: 'Alex',
27
- email: 'alex@example.com',
28
- role: 'owner',
29
- me: true
30
- },
31
- {
32
- id: 'member-ada',
33
- userId: 'ada',
34
- name: 'Ada',
35
- email: 'ada@example.com',
36
- role: 'admin',
37
- me: false
38
- }
39
- ],
40
- invitations: [
41
- { id: 'invite-1', email: 'grace@example.com', role: 'admin', expiresAt: '2030-01-01' }
42
- ]
16
+ const session: Identity = {
17
+ id: 'me',
18
+ type: 'user',
19
+ name: 'Alex',
20
+ email: 'alex@example.com',
21
+ isAnonymous: false,
22
+ avatar: 'https://example.com/avatar.png'
43
23
  }
44
24
  let cleanup = async () => {}
45
25
  export const cleanupAccount = () => cleanup()
46
26
 
47
27
  export type AccountFixtureOptions = {
48
28
  children?: ReactNode
49
- role?: string
50
29
  anonymous?: boolean
51
30
  signedOut?: boolean
52
31
  demo?: boolean
53
- failTeam?: boolean
54
32
  environment?: 'local' | 'cloud'
55
33
  failSession?: boolean
56
34
  loadingSession?: boolean
35
+ pendingMembership?: boolean
57
36
  pendingMutation?: boolean
58
37
  pendingMutationPaths?: string[]
59
38
  injected?: boolean
60
- loadingTeam?: boolean
61
39
  }
62
40
  export async function mountAccount({
63
41
  children = <AccountProbe />,
64
- role = 'owner',
65
42
  anonymous = false,
66
43
  signedOut = false,
67
44
  demo = false,
68
- failTeam = false,
69
45
  environment = 'cloud',
70
46
  failSession = false,
71
47
  loadingSession = false,
48
+ pendingMembership = false,
72
49
  pendingMutation = false,
73
50
  pendingMutationPaths = [],
74
- injected = true,
75
- loadingTeam = false
51
+ injected = true
76
52
  }: AccountFixtureOptions = {}) {
77
53
  const { window, document } = parseHTML('<html><body><div id="root"></div></body></html>')
78
54
  Object.defineProperty(document, 'oninput', { value: null, configurable: true })
@@ -80,6 +56,7 @@ export async function mountAccount({
80
56
  Object.defineProperty(window, 'location', {
81
57
  configurable: true,
82
58
  value: {
59
+ pathname: '/settings',
83
60
  assign: (href: string) => navigations.push(href),
84
61
  replace: (href: string) => navigations.push(href)
85
62
  }
@@ -88,6 +65,7 @@ export async function mountAccount({
88
65
  window,
89
66
  document,
90
67
  HTMLElement: window.HTMLElement,
68
+ CustomEvent: window.CustomEvent,
91
69
  Element: window.Element,
92
70
  requestAnimationFrame: (callback: FrameRequestCallback) =>
93
71
  Number(setTimeout(() => callback(performance.now()), 0)),
@@ -112,36 +90,47 @@ export async function mountAccount({
112
90
  const configSpy = spyOn(config, 'useAppConfig').mockReturnValue({
113
91
  environment,
114
92
  demo,
115
- collab: false,
116
93
  demoInstallUrl: '/'
117
94
  })
118
- let cloudSession: CloudSession = signedOut
95
+ let cloudSession: Identity | null = signedOut
119
96
  ? null
120
- : { user: { ...session!.user, isAnonymous: anonymous } }
121
- let team: CloudTeam = structuredClone({ ...ownerTeam, role })
122
- const failures = { signOut: false, mutation: false, team: failTeam, session: failSession }
97
+ : { ...session, type: 'user', email: 'alex@example.com', isAnonymous: anonymous }
98
+ const failures = { signOut: false, mutation: false, session: failSession, membership: false }
123
99
  const mutationRequest = Promise.withResolvers<void>()
124
- const teamResponse = Promise.withResolvers<Response>()
100
+ const membershipRequest = Promise.withResolvers<void>()
101
+ let membership: WorkspaceMembers = {
102
+ members: [{ ...session, membershipId: 'member-me' }],
103
+ invitations: []
104
+ }
125
105
  const calls: { path: string; body?: Record<string, unknown> }[] = []
126
106
  const fetchSpy = spyOn(globalThis, 'fetch').mockImplementation(
127
107
  Object.assign(
128
108
  async (input: RequestInfo | URL, init?: RequestInit) => {
129
109
  const path = String(input)
130
110
  const body = init?.body
131
- ? (JSON.parse(String(init.body)) as Record<string, string>)
111
+ ? init.body instanceof FormData
112
+ ? {}
113
+ : (JSON.parse(String(init.body)) as Record<string, string>)
132
114
  : undefined
133
115
  calls.push({ path, body })
134
- if (path.endsWith('/get-session')) {
116
+ if (path === '/api/workspaces')
117
+ return Response.json([
118
+ { id: 'one', name: 'First workspace' },
119
+ { id: 'two', name: 'Second workspace' }
120
+ ])
121
+ if (path.endsWith('/me') && (!init?.method || init.method === 'GET')) {
135
122
  if (loadingSession) return new Promise<Response>(() => {})
136
123
  return failures.session
137
124
  ? Response.json({ error: 'Session unavailable' }, { status: 503 })
138
- : Response.json(cloudSession)
125
+ : cloudSession
126
+ ? Response.json(cloudSession)
127
+ : Response.json({ error: 'No session' }, { status: 401 })
139
128
  }
140
- if (path.endsWith('/organization')) {
141
- if (loadingTeam) return teamResponse.promise
142
- return failures.team
143
- ? Response.json({ error: 'Team unavailable' }, { status: 503 })
144
- : Response.json(team)
129
+ if (path.endsWith('/members') && (!init?.method || init.method === 'GET')) {
130
+ if (pendingMembership) await membershipRequest.promise
131
+ return failures.membership
132
+ ? Response.json({ error: 'Members unavailable' }, { status: 503 })
133
+ : Response.json(membership)
145
134
  }
146
135
  if (path.endsWith('/sign-out')) {
147
136
  if (failures.signOut)
@@ -157,49 +146,62 @@ export async function mountAccount({
157
146
  await mutationRequest.promise
158
147
  if (failures.mutation)
159
148
  return Response.json({ error: 'Only the owner can do that.' }, { status: 403 })
149
+ if (init?.method === 'DELETE' && path.includes('/members/')) {
150
+ membership = {
151
+ ...membership,
152
+ members: membership.members.filter(
153
+ member => member.membershipId !== path.split('/').at(-1)
154
+ )
155
+ }
156
+ return new Response(null, { status: 204 })
157
+ }
158
+ if (init?.method === 'DELETE' && path.includes('/invitations/')) {
159
+ membership = {
160
+ ...membership,
161
+ invitations: membership.invitations.filter(
162
+ invitation => invitation.id !== path.split('/').at(-1)
163
+ )
164
+ }
165
+ return new Response(null, { status: 204 })
166
+ }
167
+ if (path.endsWith('/invitations')) {
168
+ membership = {
169
+ ...membership,
170
+ invitations: [
171
+ ...membership.invitations,
172
+ { id: 'invite-new', email: body!.email!, expiresAt: '2030-01-01' }
173
+ ]
174
+ }
175
+ return Response.json({ invitation: membership.invitations.at(-1) }, { status: 201 })
176
+ }
160
177
  if (path === '/api/settings') return Response.json({ autoUpdateSkills: false, ...body })
161
- if (path.endsWith('/profile')) {
162
- cloudSession = { user: { ...session!.user, name: body!.name! } }
163
- team.members[0]!.name = body!.name!
164
- return Response.json({ success: true, name: body!.name })
178
+ if ((path.endsWith('/me') || path.endsWith('/me/avatar')) && cloudSession) {
179
+ cloudSession = {
180
+ ...cloudSession,
181
+ ...(body?.name ? { name: body.name } : {}),
182
+ ...(path.endsWith('/avatar')
183
+ ? { avatar: init?.method === 'DELETE' ? undefined : 'https://example.com/new.png' }
184
+ : {})
185
+ }
186
+ membership = {
187
+ ...membership,
188
+ members: membership.members.map(member =>
189
+ member.id === cloudSession!.id ? { ...member, ...cloudSession! } : member
190
+ )
191
+ }
192
+ return Response.json(cloudSession)
165
193
  }
166
- if (path.endsWith('/members/remove'))
167
- team.members = team.members.filter(member => member.id !== body!.memberId)
168
- if (path.endsWith('/cancel')) team.invitations = []
169
- if (path.endsWith('/invite'))
170
- team.invitations.push({
171
- id: 'invite-new',
172
- email: body!.email!,
173
- role: 'admin',
174
- expiresAt: '2030-01-01'
175
- })
176
194
  return Response.json({ success: true })
177
195
  },
178
196
  { preconnect: fetch.preconnect }
179
197
  )
180
198
  )
181
- const qc = new QueryClient({
182
- defaultOptions: { queries: { retry: false }, mutations: { retry: false } }
183
- })
184
- if (!failSession && !loadingSession)
185
- qc.setQueryData(sessionQuery.queryKey, structuredClone(cloudSession))
186
- if (!failTeam && !loadingTeam)
187
- qc.setQueryData(teamQuery(cloudSession?.user.id).queryKey, structuredClone(team))
188
- publishUsers({ users: [] })
189
- if (injected)
190
- publishUsers({
191
- me: 'me',
192
- users: [
193
- {
194
- id: 'me',
195
- name: 'Alex',
196
- email: 'alex@example.com',
197
- color: 'blue',
198
- avatar: 'https://example.com/avatar.png'
199
- },
200
- { id: 'ada', name: 'Ada', email: 'ada@example.com', color: 'cyan' }
201
- ]
202
- })
199
+ const qc = queryClient
200
+ qc.clear()
201
+ qc.setDefaultOptions({ queries: { retry: false }, mutations: { retry: false } })
202
+ setIdentity(null)
203
+ if (!loadingSession && !failSession && environment === 'cloud') setIdentity(cloudSession)
204
+ if (injected && environment === 'local') setIdentity(session)
203
205
  const { createRoot } = await import('react-dom/client')
204
206
  const root = createRoot(document.getElementById('root')!)
205
207
  notifyManager.setNotifyFunction(callback => {
@@ -221,9 +223,13 @@ export async function mountAccount({
221
223
  })
222
224
  }
223
225
  cleanup = async () => {
224
- await act(async () => root.unmount())
226
+ await qc.cancelQueries()
227
+ await act(async () => {
228
+ root.unmount()
229
+ await new Promise(resolve => setTimeout(resolve, 20))
230
+ })
225
231
  qc.clear()
226
- publishUsers({ users: [] })
232
+ setIdentity(null)
227
233
  layoutEffectSpy.mockRestore()
228
234
  configSpy.mockRestore()
229
235
  fetchSpy.mockRestore()
@@ -239,14 +245,18 @@ export async function mountAccount({
239
245
  calls,
240
246
  failures,
241
247
  mutationRequest,
242
- teamResponse,
248
+ membershipRequest,
243
249
  qc,
250
+ setMembership: (next: WorkspaceMembers) => {
251
+ membership = next
252
+ },
244
253
  navigations,
245
254
  location,
246
255
  settle,
247
256
  async click(label: string) {
248
257
  const button = [...document.querySelectorAll<HTMLElement>('button, [role="menuitem"]')].find(
249
- button => button.getAttribute('aria-label') === label || button.textContent === label
258
+ button =>
259
+ button.getAttribute('aria-label') === label || button.textContent?.trim() === label
250
260
  )
251
261
  expect(button).toBeDefined()
252
262
  await act(async () => {