moi-computer 0.12.1-next.1 → 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 (123) hide show
  1. package/client/AGENTS.md +3 -2
  2. package/client/api/app-config.ts +3 -9
  3. package/client/api/workspace-keys.ts +2 -1
  4. package/client/app/app-provider.tsx +25 -0
  5. package/client/app/app-router.tsx +2 -0
  6. package/client/app/routes/settings-route.tsx +10 -0
  7. package/client/app/routes/workspace-route.tsx +4 -0
  8. package/client/app/shell/sidebar-layout.tsx +38 -51
  9. package/client/dev/index.html +5 -5
  10. package/client/features/account/account-menu.tsx +96 -0
  11. package/client/features/account/account-provider.tsx +142 -0
  12. package/client/features/account/account-test-utils.tsx +293 -0
  13. package/client/features/account/api.ts +142 -0
  14. package/client/features/account/identity.ts +23 -0
  15. package/client/features/applets/api.ts +1 -1
  16. package/client/features/chat/connection/chat-frames.ts +2 -2
  17. package/client/features/chat/sessions/api.ts +1 -1
  18. package/client/features/chat/use-chat.ts +1 -1
  19. package/client/features/collab/applet-api.ts +15 -14
  20. package/client/features/collab/components/cursors.tsx +61 -24
  21. package/client/features/collab/components/presence-avatars.tsx +25 -12
  22. package/client/features/collab/components/presence-frame.tsx +20 -24
  23. package/client/features/collab/components/presence-group.tsx +15 -7
  24. package/client/features/collab/components/user-avatar-group.tsx +21 -8
  25. package/client/features/collab/components/user-avatar.tsx +38 -7
  26. package/client/features/collab/components/user.tsx +31 -12
  27. package/client/features/collab/host-state.ts +24 -7
  28. package/client/features/collab/local-user.ts +1 -1
  29. package/client/features/collab/proxy-user.ts +4 -9
  30. package/client/features/collab/users.ts +0 -5
  31. package/client/features/collab/workspace-users-menu.tsx +3 -3
  32. package/client/features/demo/demo-dialog.tsx +25 -79
  33. package/client/features/dev/collab/collab-playground.tsx +7 -7
  34. package/client/features/dev/collab/local-user-settings.tsx +7 -53
  35. package/client/features/dev/workspace-setup-preview.tsx +43 -16
  36. package/client/features/harness/device-login-steps.tsx +2 -2
  37. package/client/features/home/api.ts +29 -9
  38. package/client/features/home/home-page.tsx +7 -4
  39. package/client/features/scratchpad/scratchpad.tsx +3 -6
  40. package/client/features/settings/api.ts +14 -8
  41. package/client/features/settings/connectors-settings.tsx +3 -3
  42. package/client/features/settings/environment-settings.tsx +3 -3
  43. package/client/features/settings/general-settings.tsx +1 -1
  44. package/client/features/settings/profile-settings.tsx +95 -0
  45. package/client/features/settings/settings-page.tsx +44 -0
  46. package/client/features/settings/settings-section.tsx +26 -0
  47. package/client/features/settings/users-settings.tsx +195 -0
  48. package/client/features/update/update-control.tsx +1 -1
  49. package/client/features/workspace/add/create-workspace-dialog.tsx +5 -2
  50. package/client/features/workspace/api.ts +12 -16
  51. package/client/features/workspace/setup/workspace-login-state.tsx +4 -4
  52. package/client/features/workspace/setup/workspace-setup.tsx +2 -1
  53. package/client/features/workspace/workspace-content.tsx +12 -52
  54. package/client/features/workspace/workspace-frame.tsx +76 -0
  55. package/client/features/workspace/workspace-layout-context.tsx +2 -0
  56. package/client/features/workspace/workspace-pending-screen.tsx +26 -0
  57. package/client/features/workspace/workspace-screen.tsx +3 -3
  58. package/client/index.html +28 -9
  59. package/client/index.tsx +7 -2
  60. package/client/lib/browser-tab-id.ts +4 -0
  61. package/client/lib/user-display-name.ts +6 -0
  62. package/client/main.tsx +12 -6
  63. package/client/runtime/app-context.ts +20 -0
  64. package/client/runtime/use-workspace-events.ts +29 -153
  65. package/client/runtime/workspace-events.ts +151 -0
  66. package/dist/chunk-20ynagd4.js +2 -0
  67. package/dist/chunk-42tde9a6.js +1 -0
  68. package/dist/chunk-9w543s0r.js +2 -0
  69. package/dist/{chunk-q0gbdts4.js → chunk-a5372n61.js} +71 -71
  70. package/dist/chunk-aja9y1vn.js +68 -0
  71. package/dist/chunk-fvcvrh3d.css +1 -0
  72. package/dist/chunk-gtfjw3nx.js +1 -0
  73. package/dist/{chunk-hvh9f5h0.js → chunk-j39y2aky.js} +1 -1
  74. package/dist/chunk-pja30km3.js +1 -0
  75. package/dist/{chunk-d7cbm65e.js → chunk-rm894bc2.js} +1 -1
  76. package/dist/chunk-tevvtfbk.js +10 -0
  77. package/dist/{chunk-jvyvwwv3.js → chunk-tgt9zd0r.js} +1 -1
  78. package/dist/chunk-tv5k5z00.js +1 -0
  79. package/dist/chunk-zq2ae5dx.js +2 -0
  80. package/dist/index.html +29 -10
  81. package/lib/ids.ts +2 -2
  82. package/lib/types.ts +1 -1
  83. package/package.json +1 -1
  84. package/server/api/index.ts +43 -28
  85. package/server/app-config.ts +7 -0
  86. package/server/applets/thumbnails.ts +8 -5
  87. package/server/harness/codex/thread-list.ts +4 -0
  88. package/server/static.ts +4 -2
  89. package/server/vendor.ts +23 -30
  90. package/server/web.ts +4 -2
  91. package/server/workspaces/init.ts +0 -10
  92. package/server/workspaces/layout.ts +11 -6
  93. package/server/workspaces/registry.ts +31 -9
  94. package/dist/chunk-08ndj2rg.js +0 -2
  95. package/dist/chunk-2x040tmg.js +0 -68
  96. package/dist/chunk-3smxq0ts.js +0 -1
  97. package/dist/chunk-68ch5hs8.js +0 -2
  98. package/dist/chunk-9vg3xa81.js +0 -2
  99. package/dist/chunk-c2p00p9j.css +0 -1
  100. package/dist/chunk-cs833y9j.js +0 -1
  101. package/dist/chunk-nwevqe86.js +0 -10
  102. package/dist/chunk-rt30jbcm.js +0 -1
  103. package/dist/chunk-y5y3kj67.js +0 -1
  104. /package/client/vendor/react/{development → 19.2.4/development}/_impl/react-dom-client.js +0 -0
  105. /package/client/vendor/react/{development → 19.2.4/development}/_impl/react-dom.js +0 -0
  106. /package/client/vendor/react/{development → 19.2.4/development}/_impl/react-jsx-dev-runtime.js +0 -0
  107. /package/client/vendor/react/{development → 19.2.4/development}/_impl/react-jsx-runtime.js +0 -0
  108. /package/client/vendor/react/{development → 19.2.4/development}/_impl/react.js +0 -0
  109. /package/client/vendor/react/{development → 19.2.4/development}/react-dom-client.js +0 -0
  110. /package/client/vendor/react/{development → 19.2.4/development}/react-dom.js +0 -0
  111. /package/client/vendor/react/{development → 19.2.4/development}/react-jsx-dev-runtime.js +0 -0
  112. /package/client/vendor/react/{development → 19.2.4/development}/react-jsx-runtime.js +0 -0
  113. /package/client/vendor/react/{development → 19.2.4/development}/react.js +0 -0
  114. /package/client/vendor/react/{production → 19.2.4/production}/_impl/react-dom-client.js +0 -0
  115. /package/client/vendor/react/{production → 19.2.4/production}/_impl/react-dom.js +0 -0
  116. /package/client/vendor/react/{production → 19.2.4/production}/_impl/react-jsx-dev-runtime.js +0 -0
  117. /package/client/vendor/react/{production → 19.2.4/production}/_impl/react-jsx-runtime.js +0 -0
  118. /package/client/vendor/react/{production → 19.2.4/production}/_impl/react.js +0 -0
  119. /package/client/vendor/react/{production → 19.2.4/production}/react-dom-client.js +0 -0
  120. /package/client/vendor/react/{production → 19.2.4/production}/react-dom.js +0 -0
  121. /package/client/vendor/react/{production → 19.2.4/production}/react-jsx-dev-runtime.js +0 -0
  122. /package/client/vendor/react/{production → 19.2.4/production}/react-jsx-runtime.js +0 -0
  123. /package/client/vendor/react/{production → 19.2.4/production}/react.js +0 -0
package/client/AGENTS.md CHANGED
@@ -19,9 +19,9 @@ Before editing host-app UI, read `../DESIGN.md` and the relevant rules in `../.a
19
19
 
20
20
  ## Vendored React
21
21
 
22
- React is not bundled into the app. It ships as locally-vendored ESM in `vendor/react/` (development and production builds, generated by `scripts/build-vendor.ts`) and is served at `/vendor/react/*`, so Moi runs fully offline — no CDN fetch.
22
+ React is not bundled into the app. It ships as locally-vendored ESM in `vendor/react/<version>/` (development and production builds, generated by `scripts/build-vendor.ts`) and is served at `/vendor/react/<version>/<mode>/*`, so Moi runs fully offline — no CDN fetch. The version and build mode in the URL are why the server serves these files as `immutable` in every mode, and why a prebuilt `moi` and `bun run dev` on one port cannot poison each other's cache; the shell (`index.html`) and hashed chunks carry their own cache headers, so nothing unhashed is ever given a `max-age`.
23
23
 
24
- - An importmap in `index.html` maps `react`, `react-dom`, and the jsx runtimes to the `/vendor/react/*` URLs. A preload script in the same file imports them, stores the modules on `globalThis.__esm`, and only then calls `__init` to mount the app — this load order is load-bearing.
24
+ - An importmap in `index.html` maps `react`, `react-dom`, and the jsx runtimes to the `/vendor/react/<version>/development/*` URLs (`bun run vendor:react` rewrites the version on a bump; `scripts/build-client.ts` switches the mode to `production` in `dist/`). A preload script in the same file imports them, stores the modules on `globalThis.__esm`, and only then calls `__init` to mount the app — this load order is load-bearing.
25
25
  - `externalize-react.ts` is a Bun bundler plugin that replaces those specifiers in bundled code with reads from `globalThis.__esm`. The point is ONE shared React instance across the host app and every applet/widget bundle (which resolve the same importmap); bundling React in would give each its own copy and break hooks.
26
26
  - `structured-clone-shim.ts` must be the first import in `index.tsx`, before any tldraw module loads.
27
27
  - HMR works across the bundle/vendor boundary; the `import.meta.hot.accept()` in `externalize-react.ts` is what stops every edit from escalating to a full page reload. See the comment in `index.tsx` before touching any of this.
@@ -34,6 +34,7 @@ React is not bundled into the app. It ships as locally-vendored ESM in `vendor/r
34
34
  - `components/ui/` contains host facades for shared UI primitives. `components/shared/` contains reusable app components with no feature knowledge.
35
35
  - `api/` contains shared request helpers, query keys, and query policies. Feature endpoints stay in the feature's `api.ts`.
36
36
  - `runtime/` contains browser-wide lifecycle code such as HMR and shared workspace events.
37
+ - `app/app-provider.tsx` owns app-wide services that live exactly as long as the app, such as the workspace events socket; `runtime/app-context.ts` exposes them to hooks. Put state there when it must survive route switches. Hooks that read it do nothing outside the provider, so sandboxes and component tests open no connections.
37
38
  - `lib/` contains small feature-neutral utilities. Do not use it as a catch-all for components or feature state.
38
39
  - App code may compose features. Shared components and primitives must not import from `features/` or `app/`.
39
40
  - Keep tests next to the code they cover. Extract a component, hook, or pure helper when a file starts mixing multiple responsibilities.
@@ -3,15 +3,13 @@ import { useSyncExternalStore } from 'react'
3
3
  import type { ClientAppConfig } from '@/lib/types'
4
4
  import { EXPERIMENTAL_DEFAULTS } from '@/lib/experimental'
5
5
 
6
- import { onWorkspaceEventsReconnect } from '@/client/runtime/use-workspace-events'
7
-
8
6
  import { requestJson } from './http'
9
7
 
10
8
  // Startup config (GET /api/config): frozen for the server process lifetime,
11
9
  // so it is fetched once before the app mounts (see init() in index.tsx) and
12
10
  // read synchronously everywhere after that — no query, no loading states.
13
- // The one thing that can change it is a server restart; the events socket
14
- // reconnecting is that signal, so the store re-fetches there.
11
+ // Only a server restart can change it, and a restart is picked up on the next
12
+ // page load.
15
13
 
16
14
  const DEFAULTS: ClientAppConfig = {
17
15
  environment: 'local',
@@ -43,11 +41,7 @@ async function fetchAppConfig(): Promise<ClientAppConfig | undefined> {
43
41
  // Called once from init() before the app mounts; never rejects, so a config
44
42
  // hiccup cannot block the app from starting.
45
43
  export async function loadAppConfig(): Promise<ClientAppConfig | undefined> {
46
- const config = await fetchAppConfig()
47
- onWorkspaceEventsReconnect(() => {
48
- void fetchAppConfig()
49
- })
50
- return config
44
+ return fetchAppConfig()
51
45
  }
52
46
 
53
47
  export function useAppConfig(): ClientAppConfig {
@@ -2,7 +2,8 @@ export const workspaceKeys = {
2
2
  all: ['workspaces'] as const,
3
3
  discover: ['workspaces', 'discover'] as const,
4
4
  creationInfo: ['workspaces', 'creation-info'] as const,
5
- preview: (id: string) => ['workspaces', 'preview', id] as const,
5
+ // Every workspace's home-card preview, fetched in one batch.
6
+ previews: ['workspaces', 'previews'] as const,
6
7
  layout: (id: string) => ['workspaces', 'layout', id] as const,
7
8
  widgets: (id: string) => ['workspaces', 'widgets', id] as const,
8
9
  appletThumbnails: (id: string) => ['workspaces', 'applet-thumbnails', id] as const,
@@ -0,0 +1,25 @@
1
+ import { type ReactNode, useEffect, useState } from 'react'
2
+
3
+ import { wsUrl } from '@/client/lib/ws-url'
4
+ import { AppContext, type AppContextValue } from '@/client/runtime/app-context'
5
+ import { WorkspaceEventsClient } from '@/client/runtime/workspace-events'
6
+
7
+ type AppProviderProps = {
8
+ children: ReactNode
9
+ }
10
+
11
+ // App-wide services, mounted once at the root (main.tsx). Opens the workspace
12
+ // events socket when the app mounts and closes it when the app unmounts, so
13
+ // the connection outlives every route.
14
+ export function AppProvider({ children }: AppProviderProps) {
15
+ const [value] = useState<AppContextValue>(() => ({
16
+ events: new WorkspaceEventsClient(wsUrl('/api/workspaces/ws'))
17
+ }))
18
+
19
+ useEffect(() => {
20
+ value.events.connect()
21
+ return () => value.events.close()
22
+ }, [value])
23
+
24
+ return <AppContext value={value}>{children}</AppContext>
25
+ }
@@ -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
+ }
@@ -16,6 +16,7 @@ import { WorkspaceScreen } from '@/client/features/workspace/workspace-screen'
16
16
  import { useViews } from '@/client/features/views/api'
17
17
  import { useWidgets } from '@/client/features/overview/api'
18
18
  import { useWorkspaceEvent } from '@/client/runtime/use-workspace-events'
19
+ import { BROWSER_TAB_ID } from '@/client/lib/browser-tab-id'
19
20
 
20
21
  type WorkspaceRouteProps = {
21
22
  id: string
@@ -49,6 +50,9 @@ function WorkspaceContent({ id }: WorkspaceRouteProps) {
49
50
 
50
51
  useWorkspaceEvent(event => {
51
52
  if (event.type === 'theme:updated' || event.type === 'workspace:updated') {
53
+ // Skip our own save: the cache already holds it, and the refetch could
54
+ // land an older value over a newer optimistic change.
55
+ if (event.origin === BROWSER_TAB_ID) return
52
56
  queryClient.invalidateQueries({ queryKey: workspaceKeys.layout(id) })
53
57
  } else if (event.type === 'widget-layout:updated' || event.type === 'widget:updated') {
54
58
  // widget:updated too: a rebundle bumps the widget's content revision, and
@@ -1,20 +1,21 @@
1
1
  import { type ReactNode } from 'react'
2
2
 
3
- import {
4
- IconAlertSquareRoundedFilled,
5
- IconMessage2Share,
6
- IconPlus,
7
- IconSmartHome
8
- } from '@tabler/icons-react'
3
+ import { IconPlus, IconSandbox, IconSmartHome } from '@tabler/icons-react'
9
4
  import { useQueryClient } from '@tanstack/react-query'
10
5
  import { Link, useLocation } from 'wouter'
11
6
 
12
7
  import { useAppConfig } from '@/client/api/app-config'
13
8
  import { useReorderWorkspaces, useWorkspaces } from '@/client/features/home/api'
14
- import { UpdateButton, useUpdateControl } from '@/client/features/update/update-control'
9
+ import { BROWSER_TAB_ID } from '@/client/lib/browser-tab-id'
10
+ import {
11
+ UpdateButton as UpdateButtonComponent,
12
+ useUpdateControl
13
+ } from '@/client/features/update/update-control'
15
14
  import { workspaceKeys } from '@/client/api/workspace-keys'
16
15
  import { useWorkspaceEvent } from '@/client/runtime/use-workspace-events'
17
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'
18
19
  import { DemoDialog } from '@/client/features/demo/demo-dialog'
19
20
  import { ReorderableList } from '@/client/components/shared/reorderable-list'
20
21
  import type { ReorderableRenderState } from '@/client/components/shared/reorderable-list'
@@ -30,11 +31,9 @@ import { workspaceDisplayName } from '@/client/features/workspace/workspace-pres
30
31
  import { cn } from '@/client/lib/cn'
31
32
  import type { WorkspaceEntry } from '@/lib/types'
32
33
 
33
- const FEEDBACK_URL = 'https://mlfrg.notion.site/3c678a44b6788042b734d775dd2e935e?pvs=105'
34
-
35
34
  function sidebarNavButtonClass(active: boolean): string {
36
35
  return cn(
37
- buttonVariants({ variant: 'ghost', size: 'icon' }),
36
+ buttonVariants({ variant: 'ghost', size: 'icon-lg' }),
38
37
  active && 'bg-accent text-accent-foreground'
39
38
  )
40
39
  }
@@ -63,6 +62,9 @@ export function SidebarLayout({ children, showWorkspaces = true }: SidebarLayout
63
62
  e.type === 'theme:updated' ||
64
63
  e.type === 'workspaces-list:updated'
65
64
  ) {
65
+ // Our own icon and order changes are already in the list cache. Own theme
66
+ // saves still refetch: only the layout cache holds those optimistically.
67
+ if (e.type !== 'theme:updated' && e.origin === BROWSER_TAB_ID) return
66
68
  qc.invalidateQueries({ queryKey: workspaceKeys.all, exact: true })
67
69
  }
68
70
  })
@@ -80,6 +82,8 @@ type SidebarProps = {
80
82
  }
81
83
 
82
84
  function Sidebar({ workspaces }: SidebarProps) {
85
+ const { environment } = useAppConfig()
86
+ const { demo } = useAccount()
83
87
  const reorder = useReorderWorkspaces()
84
88
 
85
89
  return (
@@ -138,55 +142,38 @@ function Sidebar({ workspaces }: SidebarProps) {
138
142
  )}
139
143
  </nav>
140
144
 
141
- <div className="size-8 shrink-0">
142
- <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
+ )}
143
165
  </div>
144
166
  </aside>
145
167
  </TooltipProvider>
146
168
  )
147
169
  }
148
170
 
149
- function SidebarFooterAction() {
150
- const { demo } = useAppConfig()
171
+ function UpdateButton() {
151
172
  const updateControl = useUpdateControl()
152
173
 
153
- if (demo) {
154
- return (
155
- <DemoDialog
156
- trigger={
157
- <Button size="icon" aria-label="Unlock all features" title="Unlock all features">
158
- <IconAlertSquareRoundedFilled stroke={1.5} />
159
- </Button>
160
- }
161
- />
162
- )
163
- }
164
-
165
- if (updateControl.status === 'loading') return null
166
- if (updateControl.status === 'available') return <UpdateButton {...updateControl.button} />
167
-
168
- return <FeedbackLink />
169
- }
170
-
171
- function FeedbackLink() {
172
- return (
173
- <Tooltip>
174
- <TooltipTrigger
175
- render={
176
- <Button
177
- render={<a href={FEEDBACK_URL} target="_blank" rel="noreferrer" />}
178
- variant="ghost"
179
- size="icon"
180
- aria-label="Leave feedback"
181
- className="text-muted-foreground hover:text-foreground"
182
- >
183
- <IconMessage2Share stroke={1.5} />
184
- </Button>
185
- }
186
- />
187
- <TooltipContent side="right">Leave feedback</TooltipContent>
188
- </Tooltip>
189
- )
174
+ return updateControl.status === 'available' ? (
175
+ <UpdateButtonComponent {...updateControl.button} />
176
+ ) : null
190
177
  }
191
178
 
192
179
  type WorkspaceButtonProps = {
@@ -9,11 +9,11 @@
9
9
  <script type="importmap">
10
10
  {
11
11
  "imports": {
12
- "react": "/vendor/react/react.js",
13
- "react/jsx-runtime": "/vendor/react/react-jsx-runtime.js",
14
- "react/jsx-dev-runtime": "/vendor/react/react-jsx-dev-runtime.js",
15
- "react-dom": "/vendor/react/react-dom.js",
16
- "react-dom/client": "/vendor/react/react-dom-client.js"
12
+ "react": "/vendor/react/19.2.4/development/react.js",
13
+ "react/jsx-runtime": "/vendor/react/19.2.4/development/react-jsx-runtime.js",
14
+ "react/jsx-dev-runtime": "/vendor/react/19.2.4/development/react-jsx-dev-runtime.js",
15
+ "react-dom": "/vendor/react/19.2.4/development/react-dom.js",
16
+ "react-dom/client": "/vendor/react/19.2.4/development/react-dom-client.js"
17
17
  }
18
18
  }
19
19
  </script>
@@ -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
+ }