moi-computer 0.12.1-next.2 → 0.12.1-next.3

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 (60) hide show
  1. package/client/app/app-router.tsx +2 -0
  2. package/client/app/routes/settings-route.tsx +10 -0
  3. package/client/app/shell/sidebar-layout.tsx +34 -53
  4. package/client/features/account/account-menu.tsx +96 -0
  5. package/client/features/account/account-provider.tsx +142 -0
  6. package/client/features/account/account-test-utils.tsx +293 -0
  7. package/client/features/account/api.ts +142 -0
  8. package/client/features/account/identity.ts +23 -0
  9. package/client/features/collab/applet-api.ts +15 -14
  10. package/client/features/collab/components/cursors.tsx +61 -24
  11. package/client/features/collab/components/presence-avatars.tsx +25 -12
  12. package/client/features/collab/components/presence-frame.tsx +20 -24
  13. package/client/features/collab/components/presence-group.tsx +15 -7
  14. package/client/features/collab/components/user-avatar-group.tsx +21 -8
  15. package/client/features/collab/components/user-avatar.tsx +38 -7
  16. package/client/features/collab/components/user.tsx +31 -12
  17. package/client/features/collab/users.ts +0 -5
  18. package/client/features/collab/workspace-users-menu.tsx +3 -3
  19. package/client/features/dev/collab/collab-playground.tsx +7 -7
  20. package/client/features/dev/collab/local-user-settings.tsx +7 -53
  21. package/client/features/settings/connectors-settings.tsx +3 -3
  22. package/client/features/settings/environment-settings.tsx +3 -3
  23. package/client/features/settings/general-settings.tsx +1 -1
  24. package/client/features/settings/profile-settings.tsx +95 -0
  25. package/client/features/settings/settings-page.tsx +44 -0
  26. package/client/features/settings/settings-section.tsx +26 -0
  27. package/client/features/settings/users-settings.tsx +195 -0
  28. package/client/features/update/update-control.tsx +1 -1
  29. package/client/features/workspace/add/create-workspace-dialog.tsx +5 -2
  30. package/client/lib/user-display-name.ts +6 -0
  31. package/client/main.tsx +4 -1
  32. package/dist/{chunk-vt6zybej.js → chunk-20ynagd4.js} +2 -2
  33. package/dist/chunk-42tde9a6.js +1 -0
  34. package/dist/{chunk-hmka9rt5.js → chunk-9w543s0r.js} +2 -2
  35. package/dist/{chunk-y8nbwp21.js → chunk-a5372n61.js} +2 -2
  36. package/dist/chunk-aja9y1vn.js +68 -0
  37. package/dist/chunk-fvcvrh3d.css +1 -0
  38. package/dist/{chunk-ysfdcew7.js → chunk-gtfjw3nx.js} +1 -1
  39. package/dist/{chunk-hvh9f5h0.js → chunk-j39y2aky.js} +1 -1
  40. package/dist/chunk-pja30km3.js +1 -0
  41. package/dist/{chunk-d7cbm65e.js → chunk-rm894bc2.js} +1 -1
  42. package/dist/chunk-tevvtfbk.js +10 -0
  43. package/dist/{chunk-am4agx6v.js → chunk-tgt9zd0r.js} +1 -1
  44. package/dist/chunk-tv5k5z00.js +1 -0
  45. package/dist/chunk-zq2ae5dx.js +2 -0
  46. package/dist/index.html +1 -1
  47. package/lib/types.ts +1 -1
  48. package/package.json +1 -1
  49. package/server/api/index.ts +2 -6
  50. package/server/app-config.ts +7 -0
  51. package/server/web.ts +1 -0
  52. package/server/workspaces/init.ts +0 -10
  53. package/server/workspaces/registry.ts +31 -9
  54. package/dist/chunk-00rh9df4.js +0 -2
  55. package/dist/chunk-4nh7y1hq.css +0 -1
  56. package/dist/chunk-hbpdv7vd.js +0 -1
  57. package/dist/chunk-mjjregkn.js +0 -10
  58. package/dist/chunk-rt30jbcm.js +0 -1
  59. package/dist/chunk-wbkwf6cc.js +0 -68
  60. package/dist/chunk-xjyfyz64.js +0 -1
@@ -4,6 +4,7 @@ import { Redirect, Route, Switch, useLocation } from 'wouter'
4
4
 
5
5
  import { setWorkspaceSwitchHandler } from '@/client/features/chat/connection/chat-connection'
6
6
 
7
+ import { SettingsRoute } from './routes/settings-route'
7
8
  import { HomeRoute } from './routes/home-route'
8
9
  import { WorkspaceRoute } from './routes/workspace-route'
9
10
 
@@ -41,6 +42,7 @@ export function AppRouter() {
41
42
  <Switch>
42
43
  <Route path="/dev/*?" component={DevLazy} />
43
44
  <Route path="/" component={HomeRoute} />
45
+ <Route path="/settings" component={SettingsRoute} />
44
46
  {/* The wildcard is the destination path (`views/orders`, `overview`, …) —
45
47
  the URL is the tab address, read downstream with `useParams`. This
46
48
  pattern is its only definition. Keyed by workspace id only, so tab
@@ -0,0 +1,10 @@
1
+ import { SidebarLayout } from '@/client/app/shell/sidebar-layout'
2
+ import { SettingsPage } from '@/client/features/settings/settings-page'
3
+
4
+ export function SettingsRoute() {
5
+ return (
6
+ <SidebarLayout showWorkspaces={false}>
7
+ <SettingsPage />
8
+ </SidebarLayout>
9
+ )
10
+ }
@@ -1,16 +1,21 @@
1
1
  import { type ReactNode } from 'react'
2
2
 
3
- import { IconMessage2Share, IconPlus, IconSandbox, IconSmartHome } from '@tabler/icons-react'
3
+ import { IconPlus, IconSandbox, IconSmartHome } from '@tabler/icons-react'
4
4
  import { useQueryClient } from '@tanstack/react-query'
5
5
  import { Link, useLocation } from 'wouter'
6
6
 
7
7
  import { useAppConfig } from '@/client/api/app-config'
8
8
  import { useReorderWorkspaces, useWorkspaces } from '@/client/features/home/api'
9
9
  import { BROWSER_TAB_ID } from '@/client/lib/browser-tab-id'
10
- import { UpdateButton, useUpdateControl } from '@/client/features/update/update-control'
10
+ import {
11
+ UpdateButton as UpdateButtonComponent,
12
+ useUpdateControl
13
+ } from '@/client/features/update/update-control'
11
14
  import { workspaceKeys } from '@/client/api/workspace-keys'
12
15
  import { useWorkspaceEvent } from '@/client/runtime/use-workspace-events'
13
16
  import { CreateWorkspaceDialog } from '@/client/features/workspace/add/create-workspace-dialog'
17
+ import { useAccount } from '@/client/features/account/account-provider'
18
+ import { AccountMenu } from '@/client/features/account/account-menu'
14
19
  import { DemoDialog } from '@/client/features/demo/demo-dialog'
15
20
  import { ReorderableList } from '@/client/components/shared/reorderable-list'
16
21
  import type { ReorderableRenderState } from '@/client/components/shared/reorderable-list'
@@ -26,11 +31,9 @@ import { workspaceDisplayName } from '@/client/features/workspace/workspace-pres
26
31
  import { cn } from '@/client/lib/cn'
27
32
  import type { WorkspaceEntry } from '@/lib/types'
28
33
 
29
- const FEEDBACK_URL = 'https://mlfrg.notion.site/3c678a44b6788042b734d775dd2e935e?pvs=105'
30
-
31
34
  function sidebarNavButtonClass(active: boolean): string {
32
35
  return cn(
33
- buttonVariants({ variant: 'ghost', size: 'icon' }),
36
+ buttonVariants({ variant: 'ghost', size: 'icon-lg' }),
34
37
  active && 'bg-accent text-accent-foreground'
35
38
  )
36
39
  }
@@ -79,6 +82,8 @@ type SidebarProps = {
79
82
  }
80
83
 
81
84
  function Sidebar({ workspaces }: SidebarProps) {
85
+ const { environment } = useAppConfig()
86
+ const { demo } = useAccount()
82
87
  const reorder = useReorderWorkspaces()
83
88
 
84
89
  return (
@@ -137,62 +142,38 @@ function Sidebar({ workspaces }: SidebarProps) {
137
142
  )}
138
143
  </nav>
139
144
 
140
- <div className="size-8 shrink-0">
141
- <SidebarFooterAction />
145
+ <div className="flex shrink-0 flex-col items-center gap-4">
146
+ {environment === 'local' && <UpdateButton />}
147
+ {demo ? (
148
+ <Tooltip>
149
+ <DemoDialog
150
+ trigger={
151
+ <TooltipTrigger
152
+ render={
153
+ <Button size="icon" aria-label="Set up Moi">
154
+ <IconSandbox stroke={1.5} />
155
+ </Button>
156
+ }
157
+ />
158
+ }
159
+ />
160
+ <TooltipContent side="right">Set up Moi</TooltipContent>
161
+ </Tooltip>
162
+ ) : (
163
+ <AccountMenu />
164
+ )}
142
165
  </div>
143
166
  </aside>
144
167
  </TooltipProvider>
145
168
  )
146
169
  }
147
170
 
148
- function SidebarFooterAction() {
149
- const { demo } = useAppConfig()
171
+ function UpdateButton() {
150
172
  const updateControl = useUpdateControl()
151
173
 
152
- if (demo) {
153
- return (
154
- <Tooltip>
155
- <DemoDialog
156
- trigger={
157
- <TooltipTrigger
158
- render={
159
- <Button size="icon" aria-label="Set up Moi">
160
- <IconSandbox stroke={1.5} />
161
- </Button>
162
- }
163
- />
164
- }
165
- />
166
- <TooltipContent side="right">Set up Moi</TooltipContent>
167
- </Tooltip>
168
- )
169
- }
170
-
171
- if (updateControl.status === 'loading') return null
172
- if (updateControl.status === 'available') return <UpdateButton {...updateControl.button} />
173
-
174
- return <FeedbackLink />
175
- }
176
-
177
- function FeedbackLink() {
178
- return (
179
- <Tooltip>
180
- <TooltipTrigger
181
- render={
182
- <Button
183
- render={<a href={FEEDBACK_URL} target="_blank" rel="noreferrer" />}
184
- variant="ghost"
185
- size="icon"
186
- aria-label="Leave feedback"
187
- className="text-muted-foreground hover:text-foreground"
188
- >
189
- <IconMessage2Share stroke={1.5} />
190
- </Button>
191
- }
192
- />
193
- <TooltipContent side="right">Leave feedback</TooltipContent>
194
- </Tooltip>
195
- )
174
+ return updateControl.status === 'available' ? (
175
+ <UpdateButtonComponent {...updateControl.button} />
176
+ ) : null
196
177
  }
197
178
 
198
179
  type WorkspaceButtonProps = {
@@ -0,0 +1,96 @@
1
+ import { Link } from 'wouter'
2
+ import { IconLogout, IconMessage2Share, IconSettings } from '@tabler/icons-react'
3
+ import { Button } from '@/client/components/ui/button'
4
+ import { Skeleton } from '@/client/components/ui/skeleton'
5
+ import { toast } from '@/client/components/ui/toast'
6
+ import {
7
+ DropdownMenu,
8
+ DropdownMenuContent,
9
+ DropdownMenuGroup,
10
+ DropdownMenuItem,
11
+ DropdownMenuSeparator,
12
+ DropdownMenuTrigger
13
+ } from '@/client/components/ui/dropdown-menu'
14
+ import { UserAvatar } from '@/client/features/collab/components/user-avatar'
15
+ import { User } from '@/client/features/collab/components/user'
16
+ import { useAccount } from './account-provider'
17
+
18
+ const FEEDBACK_URL = 'https://mlfrg.notion.site/3c678a44b6788042b734d775dd2e935e?pvs=105'
19
+
20
+ export function AccountMenu() {
21
+ const account = useAccount()
22
+
23
+ if (account.status === 'loading')
24
+ return (
25
+ <div className="flex size-10 items-center justify-center">
26
+ <Skeleton className="size-8 rounded-full" aria-label="Loading account" />
27
+ </div>
28
+ )
29
+
30
+ if (account.status === 'error') return null
31
+
32
+ if (account.status === 'signed-out' || !account.profile) return null
33
+
34
+ return (
35
+ <DropdownMenu>
36
+ <DropdownMenuTrigger
37
+ render={<Button variant="ghost" size="icon-lg" aria-label="User menu" />}
38
+ >
39
+ <UserAvatar profile={account.profile} size="sm" />
40
+ </DropdownMenuTrigger>
41
+
42
+ <DropdownMenuContent side="right" align="end" sideOffset={8} className="w-52">
43
+ <div className="px-2 py-1">
44
+ <User
45
+ profile={account.profile}
46
+ size="sm"
47
+ description={
48
+ account.cloud
49
+ ? account.profile.name?.trim()
50
+ ? account.email
51
+ : undefined
52
+ : 'This computer'
53
+ }
54
+ />
55
+ </div>
56
+
57
+ <DropdownMenuSeparator />
58
+
59
+ <DropdownMenuGroup>
60
+ <DropdownMenuItem render={<a href={FEEDBACK_URL} target="_blank" rel="noreferrer" />}>
61
+ <IconMessage2Share stroke={1.75} />
62
+ Leave feedback
63
+ </DropdownMenuItem>
64
+ <DropdownMenuItem render={<Link href="/settings" />}>
65
+ <IconSettings stroke={1.75} />
66
+ Settings
67
+ </DropdownMenuItem>
68
+ </DropdownMenuGroup>
69
+
70
+ {account.registered && (
71
+ <>
72
+ <DropdownMenuSeparator />
73
+ <DropdownMenuGroup>
74
+ <DropdownMenuItem
75
+ disabled={account.signOut.isPending}
76
+ onClick={() =>
77
+ account.signOut.mutate(undefined, {
78
+ onError: error =>
79
+ toast.add({
80
+ title: 'Couldn’t sign out',
81
+ description: error.message,
82
+ type: 'error'
83
+ })
84
+ })
85
+ }
86
+ >
87
+ <IconLogout stroke={1.75} />
88
+ Sign out
89
+ </DropdownMenuItem>
90
+ </DropdownMenuGroup>
91
+ </>
92
+ )}
93
+ </DropdownMenuContent>
94
+ </DropdownMenu>
95
+ )
96
+ }
@@ -0,0 +1,142 @@
1
+ import { createContext, useContext, useEffect, useState, useSyncExternalStore } from 'react'
2
+ import type { ReactNode } from 'react'
3
+ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
4
+ import { useAppConfig } from '@/client/api/app-config'
5
+ import {
6
+ getCurrentUser,
7
+ getCurrentUserSource,
8
+ setLocalUser,
9
+ subscribeCurrentUserStore,
10
+ publishUsers
11
+ } from '@/client/features/collab/host-state'
12
+ import {
13
+ accountKeys,
14
+ CloudApiError,
15
+ sessionQuery,
16
+ teamQuery,
17
+ updateCloudName,
18
+ signOutCloud
19
+ } from './api'
20
+ import type { CloudSession } from './api'
21
+ import { syncCloudIdentity } from './identity'
22
+
23
+ function useAccountState() {
24
+ const { environment, demo } = useAppConfig()
25
+ const cloud = environment === 'cloud'
26
+ const profile = useSyncExternalStore(subscribeCurrentUserStore, getCurrentUser, getCurrentUser)
27
+ const source = useSyncExternalStore(
28
+ subscribeCurrentUserStore,
29
+ getCurrentUserSource,
30
+ getCurrentUserSource
31
+ )
32
+ 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
+
38
+ const signOut = useMutation({
39
+ mutationFn: signOutCloud,
40
+ onSuccess: async () => {
41
+ await qc.cancelQueries({ queryKey: accountKeys.all })
42
+ publishUsers({ users: [] })
43
+ qc.setQueryData(accountKeys.session, null)
44
+ qc.removeQueries({ queryKey: accountKeys.team })
45
+ window.location.assign('/cloud/login')
46
+ }
47
+ })
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
+ async function saveName(value: string) {
67
+ const name = value.trim()
68
+ if (!name || name.length > 80) throw new Error('Enter a name of up to 80 characters')
69
+ 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 })
88
+ return name
89
+ }
90
+ const localProfile = getCurrentUser()
91
+ if (getCurrentUserSource() !== 'local' || !localProfile || localProfile.id !== profile?.id)
92
+ throw new Error('This profile is managed by your sign-in provider')
93
+ setLocalUser({ ...localProfile, name })
94
+ return name
95
+ }
96
+
97
+ function getStatus() {
98
+ if (demo) return 'signed-out'
99
+ 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'
105
+ }
106
+
107
+ return {
108
+ cloud,
109
+ demo: demo || (cloud && session.data?.user.isAnonymous === true),
110
+ profile,
111
+ status: getStatus(),
112
+ email: registered ? session.data?.user.email : undefined,
113
+ canEdit: cloud ? registered : source === 'local',
114
+ registered,
115
+ team,
116
+ removingMemberIds,
117
+ setRemovingMemberIds,
118
+ saveName,
119
+ signOut,
120
+ retry: () => {
121
+ if (!cloud) {
122
+ window.location.reload()
123
+ return
124
+ }
125
+ void session.refetch()
126
+ if (registered) void team.refetch()
127
+ }
128
+ }
129
+ }
130
+
131
+ type AccountState = ReturnType<typeof useAccountState>
132
+ const AccountContext = createContext<AccountState | undefined>(undefined)
133
+ type AccountProviderProps = { children: ReactNode }
134
+ export function AccountProvider({ children }: AccountProviderProps) {
135
+ const account = useAccountState()
136
+ return <AccountContext value={account}>{children}</AccountContext>
137
+ }
138
+ export function useAccount() {
139
+ const account = useContext(AccountContext)
140
+ if (!account) throw new Error('AccountProvider is required')
141
+ return account
142
+ }
@@ -0,0 +1,293 @@
1
+ import { expect, spyOn } from 'bun:test'
2
+ import { act, useLayoutEffect } from 'react'
3
+ import type { ReactNode } from 'react'
4
+ import * as layoutEffect from '@base-ui/utils/useIsoLayoutEffect'
5
+ import { Router } from 'wouter'
6
+ import { memoryLocation } from 'wouter/memory-location'
7
+ import { parseHTML } from 'linkedom'
8
+ import { QueryClient, QueryClientProvider, notifyManager } from '@tanstack/react-query'
9
+ import * as config from '@/client/api/app-config'
10
+ import { publishUsers } from '@/client/features/collab/host-state'
11
+ import { AccountProvider, useAccount } from './account-provider'
12
+ import { sessionQuery, teamQuery } from './api'
13
+ import type { CloudSession, CloudTeam } from './api'
14
+
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
+ ]
43
+ }
44
+ let cleanup = async () => {}
45
+ export const cleanupAccount = () => cleanup()
46
+
47
+ export type AccountFixtureOptions = {
48
+ children?: ReactNode
49
+ role?: string
50
+ anonymous?: boolean
51
+ signedOut?: boolean
52
+ demo?: boolean
53
+ failTeam?: boolean
54
+ environment?: 'local' | 'cloud'
55
+ failSession?: boolean
56
+ loadingSession?: boolean
57
+ pendingMutation?: boolean
58
+ pendingMutationPaths?: string[]
59
+ injected?: boolean
60
+ loadingTeam?: boolean
61
+ }
62
+ export async function mountAccount({
63
+ children = <AccountProbe />,
64
+ role = 'owner',
65
+ anonymous = false,
66
+ signedOut = false,
67
+ demo = false,
68
+ failTeam = false,
69
+ environment = 'cloud',
70
+ failSession = false,
71
+ loadingSession = false,
72
+ pendingMutation = false,
73
+ pendingMutationPaths = [],
74
+ injected = true,
75
+ loadingTeam = false
76
+ }: AccountFixtureOptions = {}) {
77
+ const { window, document } = parseHTML('<html><body><div id="root"></div></body></html>')
78
+ Object.defineProperty(document, 'oninput', { value: null, configurable: true })
79
+ const navigations: string[] = []
80
+ Object.defineProperty(window, 'location', {
81
+ configurable: true,
82
+ value: {
83
+ assign: (href: string) => navigations.push(href),
84
+ replace: (href: string) => navigations.push(href)
85
+ }
86
+ })
87
+ const globals = {
88
+ window,
89
+ document,
90
+ HTMLElement: window.HTMLElement,
91
+ Element: window.Element,
92
+ requestAnimationFrame: (callback: FrameRequestCallback) =>
93
+ Number(setTimeout(() => callback(performance.now()), 0)),
94
+ cancelAnimationFrame: (id: number) => clearTimeout(id),
95
+ getComputedStyle: (element: HTMLElement) =>
96
+ new Proxy(element.style, { get: (style, key) => Reflect.get(style, key) ?? '' }),
97
+ Node: window.Node,
98
+ KeyboardEvent: class extends window.Event {},
99
+ FocusEvent: class extends window.Event {},
100
+ MouseEvent: class extends window.Event {},
101
+ IS_REACT_ACT_ENVIRONMENT: true
102
+ }
103
+ const descriptors = new Map(
104
+ Object.keys(globals).map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])
105
+ )
106
+ for (const [key, value] of Object.entries(globals))
107
+ Object.defineProperty(globalThis, key, { configurable: true, value })
108
+ // Base UI was imported before this fixture installed a DOM. Enable its browser effects.
109
+ const layoutEffectSpy = spyOn(layoutEffect, 'useIsoLayoutEffect').mockImplementation(
110
+ useLayoutEffect
111
+ )
112
+ const configSpy = spyOn(config, 'useAppConfig').mockReturnValue({
113
+ environment,
114
+ demo,
115
+ demoInstallUrl: '/',
116
+ experimental: { collab: true }
117
+ })
118
+ let cloudSession: CloudSession = signedOut
119
+ ? 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 }
123
+ const mutationRequest = Promise.withResolvers<void>()
124
+ const teamResponse = Promise.withResolvers<Response>()
125
+ const calls: { path: string; body?: Record<string, string> }[] = []
126
+ const fetchSpy = spyOn(globalThis, 'fetch').mockImplementation(
127
+ Object.assign(
128
+ async (input: RequestInfo | URL, init?: RequestInit) => {
129
+ const path = String(input)
130
+ const body = init?.body
131
+ ? (JSON.parse(String(init.body)) as Record<string, string>)
132
+ : undefined
133
+ calls.push({ path, body })
134
+ if (path.endsWith('/get-session')) {
135
+ if (loadingSession) return new Promise<Response>(() => {})
136
+ return failures.session
137
+ ? Response.json({ error: 'Session unavailable' }, { status: 503 })
138
+ : Response.json(cloudSession)
139
+ }
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)
145
+ }
146
+ if (path.endsWith('/sign-out')) {
147
+ if (failures.signOut)
148
+ return Response.json({ error: 'Try signing out again.' }, { status: 503 })
149
+ cloudSession = null
150
+ return Response.json({ success: true })
151
+ }
152
+ if (
153
+ pendingMutation &&
154
+ (pendingMutationPaths.length === 0 ||
155
+ pendingMutationPaths.some(suffix => path.endsWith(suffix)))
156
+ )
157
+ await mutationRequest.promise
158
+ if (failures.mutation)
159
+ return Response.json({ error: 'Only the owner can do that.' }, { status: 403 })
160
+ if (path.endsWith('/profile')) {
161
+ cloudSession = { user: { ...session!.user, name: body!.name! } }
162
+ team.members[0]!.name = body!.name!
163
+ return Response.json({ success: true, name: body!.name })
164
+ }
165
+ if (path.endsWith('/members/remove'))
166
+ team.members = team.members.filter(member => member.id !== body!.memberId)
167
+ if (path.endsWith('/cancel')) team.invitations = []
168
+ if (path.endsWith('/invite'))
169
+ team.invitations.push({
170
+ id: 'invite-new',
171
+ email: body!.email!,
172
+ role: 'admin',
173
+ expiresAt: '2030-01-01'
174
+ })
175
+ return Response.json({ success: true })
176
+ },
177
+ { preconnect: fetch.preconnect }
178
+ )
179
+ )
180
+ const qc = new QueryClient({
181
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } }
182
+ })
183
+ if (!failSession && !loadingSession)
184
+ qc.setQueryData(sessionQuery.queryKey, structuredClone(cloudSession))
185
+ if (!failTeam && !loadingTeam)
186
+ qc.setQueryData(teamQuery(cloudSession?.user.id).queryKey, structuredClone(team))
187
+ publishUsers({ users: [] })
188
+ if (injected)
189
+ publishUsers({
190
+ me: 'me',
191
+ users: [
192
+ {
193
+ id: 'me',
194
+ name: 'Alex',
195
+ email: 'alex@example.com',
196
+ color: 'blue',
197
+ avatar: 'https://example.com/avatar.png'
198
+ },
199
+ { id: 'ada', name: 'Ada', email: 'ada@example.com', color: 'cyan' }
200
+ ]
201
+ })
202
+ const { createRoot } = await import('react-dom/client')
203
+ const root = createRoot(document.getElementById('root')!)
204
+ notifyManager.setNotifyFunction(callback => {
205
+ act(callback)
206
+ })
207
+ const location = memoryLocation({ path: '/settings', record: true })
208
+ await act(async () =>
209
+ root.render(
210
+ <QueryClientProvider client={qc}>
211
+ <Router hook={location.hook}>
212
+ <AccountProvider>{children}</AccountProvider>
213
+ </Router>
214
+ </QueryClientProvider>
215
+ )
216
+ )
217
+ async function settle() {
218
+ await act(async () => {
219
+ await new Promise(resolve => setTimeout(resolve, 5))
220
+ })
221
+ }
222
+ cleanup = async () => {
223
+ await act(async () => root.unmount())
224
+ qc.clear()
225
+ publishUsers({ users: [] })
226
+ layoutEffectSpy.mockRestore()
227
+ configSpy.mockRestore()
228
+ fetchSpy.mockRestore()
229
+ notifyManager.setNotifyFunction(callback => callback())
230
+ for (const [key, descriptor] of descriptors) {
231
+ if (descriptor) Object.defineProperty(globalThis, key, descriptor)
232
+ else Reflect.deleteProperty(globalThis, key)
233
+ }
234
+ }
235
+ return {
236
+ document,
237
+ window,
238
+ calls,
239
+ failures,
240
+ mutationRequest,
241
+ teamResponse,
242
+ qc,
243
+ navigations,
244
+ location,
245
+ settle,
246
+ async click(label: string) {
247
+ const button = [...document.querySelectorAll<HTMLElement>('button, [role="menuitem"]')].find(
248
+ button => button.getAttribute('aria-label') === label || button.textContent === label
249
+ )
250
+ expect(button).toBeDefined()
251
+ await act(async () => {
252
+ const event = new window.Event('mousedown', { bubbles: true, cancelable: true })
253
+ Object.defineProperty(event, 'button', { value: 0 })
254
+ button!.dispatchEvent(event)
255
+ button!.click()
256
+ })
257
+ await settle()
258
+ },
259
+ async type(input: HTMLInputElement, value: string) {
260
+ await act(async () => {
261
+ input.type = input.id === 'invite-email' ? 'email' : 'text'
262
+ // React may have loaded before a DOM in the full suite; also exercise its
263
+ // legacy input-event fallback through real focus and keyboard events.
264
+ Object.assign(input, { attachEvent() {}, detachEvent() {} })
265
+ input.dispatchEvent(new window.Event('focusin', { bubbles: true }))
266
+ Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')!.set!.call(
267
+ input,
268
+ value
269
+ )
270
+ input.dispatchEvent(new window.Event('input', { bubbles: true }))
271
+ input.dispatchEvent(new window.Event('keyup', { bubbles: true }))
272
+ })
273
+ }
274
+ }
275
+ }
276
+
277
+ type AccountProbeProps = { children?: ReactNode }
278
+ export function AccountProbe({ children }: AccountProbeProps) {
279
+ const account = useAccount()
280
+ return (
281
+ <>
282
+ <p data-account-status>{account.status}</p>
283
+ <p data-account-name>{account.profile?.name}</p>
284
+ {account.status === 'ready' && children}
285
+ {account.registered && (
286
+ <button disabled={account.signOut.isPending} onClick={() => account.signOut.mutate()}>
287
+ Sign out
288
+ </button>
289
+ )}
290
+ {account.signOut.error && <p role="alert">{account.signOut.error.message}</p>}
291
+ </>
292
+ )
293
+ }