moi-computer 0.12.1-next.4 → 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 (74) 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/chat/messages/tool-group/subagent-card.tsx +1 -0
  10. package/client/features/collab/client.ts +38 -13
  11. package/client/features/collab/components/user-avatar.tsx +4 -10
  12. package/client/features/collab/hooks.tsx +9 -8
  13. package/client/features/collab/host-state.ts +45 -85
  14. package/client/features/collab/testing/fake-engine.ts +13 -1
  15. package/client/features/collab/users.ts +0 -12
  16. package/client/features/connectors/api.ts +12 -4
  17. package/client/features/connectors/mcp-server-cards.tsx +17 -7
  18. package/client/features/connectors/read-connectors.ts +35 -0
  19. package/client/features/dev/cloud-avatar-upload.tsx +58 -0
  20. package/client/features/dev/cloud-page.tsx +363 -0
  21. package/client/features/dev/collab/local-user-settings.tsx +1 -1
  22. package/client/features/dev/dev-index-page.tsx +6 -0
  23. package/client/features/dev/dev-routes.tsx +2 -0
  24. package/client/features/identity/host-api.ts +34 -0
  25. package/client/features/identity/store.ts +32 -0
  26. package/client/features/identity/types.ts +41 -0
  27. package/client/features/identity/use-identity.ts +6 -0
  28. package/client/features/workspace/harness-transition.ts +1 -0
  29. package/client/features/workspace/settings/connectors-settings.tsx +31 -10
  30. package/client/features/workspace/settings/general-settings.tsx +17 -14
  31. package/client/features/workspace-members/api.ts +20 -0
  32. package/client/features/workspace-members/hooks.ts +127 -0
  33. package/client/features/workspace-members/keys.ts +6 -0
  34. package/client/features/workspace-members/store.ts +123 -0
  35. package/client/features/workspace-members/types.ts +53 -0
  36. package/client/index.html +1 -1
  37. package/client/index.tsx +5 -9
  38. package/client/main.tsx +2 -2
  39. package/dist/{chunk-71fn6rmj.js → chunk-00s35r33.js} +68 -68
  40. package/dist/{chunk-g0tcwqxc.js → chunk-7rz6g7g7.js} +1 -1
  41. package/dist/chunk-af2jyddf.js +2 -0
  42. package/dist/chunk-cekekc3f.css +1 -0
  43. package/dist/chunk-ep5vh16c.js +75 -0
  44. package/dist/{chunk-2y59vrxg.js → chunk-kdgk4dac.js} +1 -1
  45. package/dist/chunk-s5s1vzdw.js +2 -0
  46. package/dist/{chunk-58dyt9bk.js → chunk-svxhxfeq.js} +2 -2
  47. package/dist/chunk-t0r0bds1.js +1 -0
  48. package/dist/chunk-vp2qzc0d.js +1 -0
  49. package/dist/chunk-wz5qv1bn.js +2 -0
  50. package/dist/index.html +2 -2
  51. package/lib/types.ts +4 -2
  52. package/package.json +7 -4
  53. package/server/api/index.ts +26 -1
  54. package/server/app-config.ts +3 -1
  55. package/server/harness/claude-code/index.ts +3 -6
  56. package/server/harness/claude-code/mcp.ts +17 -0
  57. package/server/harness/codex/NOTES.md +9 -2
  58. package/server/harness/codex/client.ts +8 -5
  59. package/server/harness/codex/connectors.ts +92 -0
  60. package/server/harness/codex/index.ts +2 -1
  61. package/server/harness/codex/pagination.ts +8 -5
  62. package/server/harness/codex/transport.ts +13 -6
  63. package/server/harness/types.ts +4 -1
  64. package/server/onboarding/prompt.md +2 -2
  65. package/skill/references/DESIGN.md +22 -3
  66. package/client/features/account/identity.ts +0 -23
  67. package/client/features/app-settings/users-settings.tsx +0 -195
  68. package/dist/chunk-0mjzg20x.js +0 -2
  69. package/dist/chunk-5aj040e5.css +0 -1
  70. package/dist/chunk-7yg1m8hx.js +0 -2
  71. package/dist/chunk-825hys3h.js +0 -1
  72. package/dist/chunk-9bb8m9rx.js +0 -2
  73. package/dist/chunk-n0nab26d.js +0 -1
  74. package/dist/chunk-v88n1bay.js +0 -74
@@ -0,0 +1,31 @@
1
+ import { queryClient } from '@/client/api/query-client'
2
+ import { getIdentity, setIdentity, getAccountGeneration } from '../identity/store'
3
+ import { identityKey } from '../identity/types'
4
+ import type { Identity } from '../identity/types'
5
+ import { memberKeys } from '../workspace-members/keys'
6
+
7
+ export async function saveCloudProfile(field: 'name' | 'avatar', update: () => Promise<Identity>) {
8
+ const before = getIdentity()
9
+ const accountGeneration = getAccountGeneration()
10
+ if (!before || before.type !== 'user' || before.isAnonymous)
11
+ throw new Error('Sign in to change your profile')
12
+ const saved = await update()
13
+ const current = getIdentity()
14
+ if (
15
+ accountGeneration !== getAccountGeneration() ||
16
+ !current ||
17
+ current.type !== 'user' ||
18
+ current.id !== before.id
19
+ )
20
+ throw new Error('Your account changed. Reload Moi to try again.')
21
+ // A newer server-pushed value wins. Apply only fields still equal to their original value.
22
+ setIdentity({
23
+ ...current,
24
+ ...(field === 'name' && current.name === before.name ? { name: saved.name } : {}),
25
+ ...(field === 'avatar' && current.avatar === before.avatar ? { avatar: saved.avatar } : {})
26
+ })
27
+ // Our identity write can supersede the event bridge's in-flight snapshot.
28
+ // Refresh active lists now and mark inactive lists stale for their next mount.
29
+ if (accountGeneration === getAccountGeneration())
30
+ await queryClient.invalidateQueries({ queryKey: memberKeys.account(identityKey(current)) })
31
+ }
@@ -4,12 +4,9 @@ import { Button } from '@/client/components/ui/button'
4
4
  import { Skeleton } from '@/client/components/ui/skeleton'
5
5
  import { useAccount } from '../account/account-provider'
6
6
  import { ProfileSettings } from './profile-settings'
7
- import { UsersSettings } from './users-settings'
8
- import { useAppConfig } from '@/client/api/app-config'
9
7
  import { GeneralSettings } from './general-settings'
10
8
 
11
9
  export function SettingsPage() {
12
- const { collab } = useAppConfig()
13
10
  const account = useAccount()
14
11
  useEffect(() => {
15
12
  if (account.cloud && !account.demo && account.status === 'signed-out') {
@@ -38,7 +35,6 @@ export function SettingsPage() {
38
35
  ) : (
39
36
  <div className="flex w-full max-w-xl min-w-0 flex-col gap-4">
40
37
  <ProfileSettings />
41
- {collab && account.registered && <UsersSettings />}
42
38
  <GeneralSettings />
43
39
  </div>
44
40
  )}
@@ -24,6 +24,7 @@ const SPORT_ICONS = [IconPlayBasketball, IconPlayVolleyball, IconPlayFootball]
24
24
  function RunningSportNode() {
25
25
  const [i, setI] = useState(0)
26
26
  useEffect(() => {
27
+ if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return
27
28
  const t = setInterval(() => setI(n => (n + 1) % SPORT_ICONS.length), 600)
28
29
  return () => clearInterval(t)
29
30
  }, [])
@@ -1,3 +1,4 @@
1
+ import { getWorkspaceDirectory, subscribeWorkspaceDirectory } from '../workspace-members/store'
1
2
  import { wsUrl } from '@/client/lib/ws-url'
2
3
  import { COLLAB_PROTOCOL_VERSION } from '@/lib/collab/protocol'
3
4
  import type {
@@ -8,12 +9,7 @@ import type {
8
9
  PresenceRegistration
9
10
  } from '@/lib/collab/types'
10
11
 
11
- import {
12
- getCurrentUser,
13
- getDirectory,
14
- subscribeCurrentUserStore,
15
- subscribeDirectoryStore
16
- } from './host-state'
12
+ import { getCurrentUser, subscribeCurrentUserStore, getCurrentUserSource } from './host-state'
17
13
  import { CollabStore, DISCONNECTED_STATE } from './store'
18
14
  import type { ClientState, PresenceEntry } from './store'
19
15
 
@@ -31,8 +27,7 @@ export type CollabEngineApi = {
31
27
  subscribe: (listener: () => void) => Unsubscribe
32
28
  getCurrentUser: () => UserProfile | undefined
33
29
  subscribeCurrentUser: (listener: () => void) => Unsubscribe
34
- // Everyone an outer host published. Undefined without a host, in which
35
- // case live users stand in.
30
+ // Authoritative members of this workspace; never an app-wide directory.
36
31
  getDirectory: () => readonly UserProfile[] | undefined
37
32
  subscribeDirectory: (listener: () => void) => Unsubscribe
38
33
  getLocation: () => ConnectionLocation | null
@@ -54,8 +49,8 @@ export const NO_ENGINE: CollabEngineApi = {
54
49
  subscribe: () => noop,
55
50
  getCurrentUser,
56
51
  subscribeCurrentUser: subscribeCurrentUserStore,
57
- getDirectory,
58
- subscribeDirectory: subscribeDirectoryStore,
52
+ getDirectory: () => undefined,
53
+ subscribeDirectory: () => noop,
59
54
  getLocation: () => null,
60
55
  setLocation: noop,
61
56
  setPresence: noop,
@@ -68,12 +63,14 @@ export class CollabClient implements CollabEngineApi {
68
63
  private socket: WebSocket | null = null
69
64
  private retry: ReturnType<typeof setTimeout> | undefined
70
65
  private heartbeat: ReturnType<typeof setInterval> | undefined
66
+ private unsubscribeMembers: (() => void) | undefined
71
67
  private unsubscribeCurrentUser: (() => void) | undefined
72
68
  private presenceTimer: ReturnType<typeof setTimeout> | undefined
73
69
  private queuedPresence = new Map<string, CollabClientMessage>()
74
70
  private stopped = true
75
71
  private attempts = 0
76
72
  private lastMessageAt = 0
73
+ private localDirectory: readonly UserProfile[] | undefined
77
74
  private userId = getCurrentUser()?.id
78
75
 
79
76
  constructor(
@@ -92,8 +89,23 @@ export class CollabClient implements CollabEngineApi {
92
89
  this.enabled ? this.store.subscribe(listener) : noop
93
90
  getCurrentUser = getCurrentUser
94
91
  subscribeCurrentUser = subscribeCurrentUserStore
95
- getDirectory = getDirectory
96
- subscribeDirectory = subscribeDirectoryStore
92
+ getDirectory = () => {
93
+ const members = getWorkspaceDirectory(this.workspaceId)
94
+ if (members !== undefined) return members
95
+ // Standalone Moi has one local viewer. Cloud membership never falls back.
96
+ const local = getCurrentUserSource() !== 'external' ? getCurrentUser() : undefined
97
+ if (!local) return undefined
98
+ if (this.localDirectory?.[0] !== local) this.localDirectory = [local]
99
+ return this.localDirectory
100
+ }
101
+ subscribeDirectory = (listener: () => void) => {
102
+ const members = subscribeWorkspaceDirectory(listener)
103
+ const identity = subscribeCurrentUserStore(listener)
104
+ return () => {
105
+ members()
106
+ identity()
107
+ }
108
+ }
97
109
  getLocation = (): ConnectionLocation | null => (this.enabled ? this.store.getLocation() : null)
98
110
  setLocation = (location: ConnectionLocation | null): void => {
99
111
  this.store.setLocation(location)
@@ -120,12 +132,24 @@ export class CollabClient implements CollabEngineApi {
120
132
  else this.connect()
121
133
  } else if (profile) this.send({ type: 'profile', profile })
122
134
  })
135
+ this.unsubscribeMembers = subscribeWorkspaceDirectory(() => {
136
+ if (!this.wantsConnection()) {
137
+ clearTimeout(this.retry)
138
+ this.socket?.close()
139
+ this.store.disconnect()
140
+ } else this.connect()
141
+ })
123
142
  this.connect()
124
143
  return () => this.stop()
125
144
  }
126
145
 
127
146
  private wantsConnection(): boolean {
128
- return !this.stopped && getCurrentUser() !== undefined
147
+ const viewer = getCurrentUser()
148
+ return (
149
+ !this.stopped &&
150
+ viewer !== undefined &&
151
+ this.getDirectory()?.some(member => member.id === viewer.id) === true
152
+ )
129
153
  }
130
154
 
131
155
  private connect(): void {
@@ -226,6 +250,7 @@ export class CollabClient implements CollabEngineApi {
226
250
  private stop(): void {
227
251
  this.stopped = true
228
252
  this.unsubscribeCurrentUser?.()
253
+ this.unsubscribeMembers?.()
229
254
  clearTimeout(this.retry)
230
255
  clearTimeout(this.presenceTimer)
231
256
  this.presenceTimer = undefined
@@ -40,12 +40,7 @@ export function UserAvatar({
40
40
  const name = user ? userDisplayName(user) : 'Unknown user'
41
41
 
42
42
  return (
43
- <Avatar
44
- size={size}
45
- aria-label={name}
46
- data-collab-color={user?.color ?? 'unknown'}
47
- className={cn('after:border-0', className)}
48
- >
43
+ <Avatar size={size} aria-label={name} className={cn('after:border-0', className)}>
49
44
  {user?.avatar && <AvatarImage src={user.avatar} alt="" />}
50
45
  <AvatarFallback>
51
46
  {user ? (
@@ -54,11 +49,10 @@ export function UserAvatar({
54
49
  name={user.id}
55
50
  animate="hover"
56
51
  background="circle"
57
- traits={{ 'eye.rx': 1 }}
58
52
  palette={{
59
- bg: 'var(--collab)',
60
- head: 'var(--collab)',
61
- eye: 'var(--collab-foreground)'
53
+ bg: 'color-mix(in srgb, var(--muted) 85%, var(--foreground))',
54
+ head: 'color-mix(in srgb, var(--muted) 85%, var(--foreground))',
55
+ eye: 'var(--foreground)'
62
56
  }}
63
57
  />
64
58
  ) : (
@@ -7,15 +7,18 @@ import {
7
7
  useSyncExternalStore
8
8
  } from 'react'
9
9
  import type { JsonValue } from 'moi'
10
+ import type { UserProfile } from '@/lib/collab/types'
10
11
  import type { PresenceValue } from 'moi/collab'
11
12
 
12
13
  import { useAppletPresence, useCollabEngine } from './provider'
13
- import { resolvePeers, resolveUser, workspaceProfiles } from './users'
14
+ import { resolvePeers, resolveUser, userStatus } from './users'
14
15
  import type { WorkspaceUser, UsePeersOptions, UseWorkspaceUsersOptions } from './users'
15
16
  import { createPresencePublisher } from './presence-publisher'
16
17
 
17
18
  export type { WorkspaceUser, UsePeersOptions, UseWorkspaceUsersOptions } from './users'
18
19
 
20
+ const EMPTY_USERS: readonly UserProfile[] = []
21
+
19
22
  export function useConnectionState() {
20
23
  const engine = useCollabEngine()
21
24
  return useSyncExternalStore(engine.subscribe, engine.getUsersSnapshot, engine.getUsersSnapshot)
@@ -33,10 +36,8 @@ function useUsersSource() {
33
36
  engine.getDirectory,
34
37
  engine.getDirectory
35
38
  )
36
- const users = useMemo(
37
- () => workspaceProfiles(state.users, self, directory),
38
- [state.users, self, directory]
39
- )
39
+ // Live connections describe activity; only the directory establishes membership.
40
+ const users = directory ?? EMPTY_USERS
40
41
  return { state, self, users, engine }
41
42
  }
42
43
  export function useUser(id: string): WorkspaceUser | undefined {
@@ -58,10 +59,10 @@ export function useWorkspaceUsers({ status }: UseWorkspaceUsersOptions = {}): Wo
58
59
  )
59
60
  }
60
61
  export function useMe(): WorkspaceUser | undefined {
61
- const { state, self, users } = useUsersSource()
62
+ const { state, self } = useUsersSource()
62
63
  return useMemo(
63
- () => (self ? resolveUser({ ...state, users }, self.id) : undefined),
64
- [state, self, users]
64
+ () => (self ? { ...self, status: userStatus(state.connections, self.id) } : undefined),
65
+ [state, self]
65
66
  )
66
67
  }
67
68
  export function usePeers(options: UsePeersOptions = {}): WorkspaceUser[] {
@@ -1,34 +1,18 @@
1
+ import { getIdentity, subscribeIdentity } from '../identity/store'
2
+ import { collabIdentityId } from '../identity/types'
1
3
  import { isUserProfile } from '@/lib/collab/protocol'
2
4
  import { colorForId, isUserColor } from '@/lib/collab/colors'
3
5
  import type { AuthProvider, ProxyUserState, UserProfile } from '@/lib/collab/types'
4
6
  import { createLocalUser } from './local-user'
5
7
 
6
8
  export type UserProfileInput = Omit<UserProfile, 'color'> & { color?: UserProfile['color'] }
7
- // What an outer host publishes: the viewer's id and everyone moi may show.
8
- // `me` must be listed in `users`; leave it out when nobody is signed in.
9
- export type HostUsers = {
10
- me?: string | null
11
- users: readonly UserProfileInput[]
12
- }
13
- // `window.moi.collab`. An outer host calls it from a module script placed after
14
- // moi's bundle, once at startup and again whenever a user or the viewer changes.
15
- // A classic inline script runs before the bundle and finds nothing here.
16
- //
17
- // window.moi.collab.publishUsers({ me: 'alex', users: [{ id: 'alex', name: 'Alex' }] })
18
- export type HostApi = { publishUsers: (next: HostUsers) => void }
19
9
  // Who supplies the current user: local setup, an outer host, or an auth proxy.
20
10
  export type CurrentUserSource = 'local' | 'external' | AuthProvider
21
11
 
22
12
  const PROFILE_KEY = 'moi:local-profile'
23
- const NO_USERS: readonly UserProfile[] = Object.freeze([])
24
13
  let currentUser: UserProfile | undefined
25
14
  let currentUserSource: CurrentUserSource | undefined
26
- // One list for the whole app. Undefined until a host publishes; from then on it
27
- // is authoritative, including when it is empty.
28
- let directory: readonly UserProfile[] | undefined
29
- let installed = false
30
15
  const listeners = new Set<() => void>()
31
- const directoryListeners = new Set<() => void>()
32
16
 
33
17
  // Normalized profiles list their fields in one order, so text equality is exact.
34
18
  function sameProfile(a: UserProfile | undefined, b: UserProfile | undefined): boolean {
@@ -55,73 +39,55 @@ export function normalizeUserProfile(value: UserProfileInput): UserProfile {
55
39
  return Object.freeze(normalized)
56
40
  }
57
41
 
58
- export function normalizeUsers(users: readonly UserProfileInput[]): readonly UserProfile[] {
59
- if (!Array.isArray(users)) throw new Error('Users must be an array.')
60
- const ids = new Set<string>()
61
- const snapshot = users.map(user => {
62
- const normalized = normalizeUserProfile(user)
63
- if (ids.has(normalized.id)) throw new Error('Users must have unique ids.')
64
- ids.add(normalized.id)
65
- return normalized
66
- })
67
- return Object.freeze(snapshot)
68
- }
69
-
70
- // Replaces the viewer and the whole directory in one step. The host sends the
71
- // full list every time, so a removal is simply an id that is no longer there.
72
- // Invalid input throws and publishes nothing.
73
- export function publishUsers(next: HostUsers): void {
74
- if (!next || typeof next !== 'object') throw new Error('Users must be published as an object.')
75
- const users = normalizeUsers(next.users)
76
- let user: UserProfile | undefined
77
- if (next.me !== undefined && next.me !== null) {
78
- if (typeof next.me !== 'string') throw new Error('The current user id must be a string.')
79
- const id = next.me.trim()
80
- user = users.find(candidate => candidate.id === id)
81
- if (!user) throw new Error('The current user must be listed in users.')
82
- }
83
- // An unchanged viewer keeps its profile object and stays quiet: every notice
84
- // makes each open workspace resend that profile to its room.
85
- const changed = currentUserSource !== 'external' || !sameProfile(currentUser, user)
86
- // Publish every field before notifying any observer, including transport listeners.
87
- currentUserSource = 'external'
88
- if (changed) currentUser = user
89
- // A signed-out viewer sees no one, whatever the host still lists.
90
- directory = user ? users : NO_USERS
91
- if (changed) listeners.forEach(listener => listener())
92
- directoryListeners.forEach(listener => listener())
93
- }
94
-
95
- export function getDirectory(): readonly UserProfile[] | undefined {
96
- return directory
97
- }
98
-
99
- export function subscribeDirectoryStore(listener: () => void): () => void {
100
- directoryListeners.add(listener)
101
- return () => {
102
- directoryListeners.delete(listener)
103
- }
104
- }
105
-
42
+ // This is a memoized projection of cloud identity, never a separately writable profile.
43
+ let cloudProfile: UserProfile | undefined
44
+ let cloudIdentity: ReturnType<typeof getIdentity>
106
45
  export function getCurrentUser(): UserProfile | undefined {
107
- return currentUser
46
+ const identity = getIdentity()
47
+ if (identity === undefined) return currentUser
48
+ if (identity !== cloudIdentity) {
49
+ cloudIdentity = identity
50
+ const next =
51
+ !identity || (identity.type === 'user' && identity.isAnonymous)
52
+ ? undefined
53
+ : normalizeUserProfile({
54
+ id: collabIdentityId(identity),
55
+ name: identity.name || undefined,
56
+ avatar: identity.avatar,
57
+ email: identity.type === 'user' ? identity.email || undefined : undefined
58
+ })
59
+ if (!sameProfile(cloudProfile, next)) cloudProfile = next
60
+ }
61
+ return cloudProfile
108
62
  }
109
63
 
110
64
  export function subscribeCurrentUserStore(listener: () => void): () => void {
111
- listeners.add(listener)
65
+ let profile = getCurrentUser()
66
+ let source = getCurrentUserSource()
67
+ const notify = () => {
68
+ const nextProfile = getCurrentUser()
69
+ const nextSource = getCurrentUserSource()
70
+ if (profile === nextProfile && source === nextSource) return
71
+ profile = nextProfile
72
+ source = nextSource
73
+ listener()
74
+ }
75
+ listeners.add(notify)
76
+ const unsubscribeIdentity = subscribeIdentity(notify)
112
77
  return () => {
113
- listeners.delete(listener)
78
+ listeners.delete(notify)
79
+ unsubscribeIdentity()
114
80
  }
115
81
  }
116
82
 
117
83
  export function getCurrentUserSource(): CurrentUserSource | undefined {
118
- return currentUserSource
84
+ return getIdentity() !== undefined ? 'external' : currentUserSource
119
85
  }
120
86
 
121
87
  // An auth proxy takes precedence over local users; an outer host takes
122
88
  // precedence over the proxy. A configured proxy with no user signs this tab out.
123
89
  export function setProxyUserState({ provider, profile }: ProxyUserState): void {
124
- if (currentUserSource === 'external') return
90
+ if (getCurrentUserSource() === 'external') return
125
91
  if (provider === undefined) {
126
92
  if (currentUserSource === undefined || currentUserSource === 'local') return
127
93
  currentUserSource = undefined
@@ -145,7 +111,7 @@ function persistLocalUser(): void {
145
111
 
146
112
  export function setLocalUser(next: UserProfile): void {
147
113
  // A provider may take over between rendering the local user form and handling input.
148
- if (currentUserSource !== undefined && currentUserSource !== 'local') return
114
+ if (getCurrentUserSource() !== undefined && getCurrentUserSource() !== 'local') return
149
115
  const normalized = normalizeUserProfile(next)
150
116
  currentUserSource = 'local'
151
117
  currentUser = normalized
@@ -156,7 +122,12 @@ export function setLocalUser(next: UserProfile): void {
156
122
  // Called after startup config and proxy identity settle, before React mounts.
157
123
  // A host that has already published keeps the viewer it chose, signed in or not.
158
124
  export function initializeLocalUser(local: boolean, proxyUser: ProxyUserState | undefined): void {
159
- if (!local || !proxyUser || proxyUser.provider !== undefined || currentUserSource !== undefined)
125
+ if (
126
+ !local ||
127
+ !proxyUser ||
128
+ proxyUser.provider !== undefined ||
129
+ getCurrentUserSource() !== undefined
130
+ )
160
131
  return
161
132
  try {
162
133
  const saved = localStorage.getItem(PROFILE_KEY)
@@ -170,20 +141,9 @@ export function initializeLocalUser(local: boolean, proxyUser: ProxyUserState |
170
141
  setLocalUser(createLocalUser())
171
142
  }
172
143
 
173
- // Runs while moi's bundle evaluates, so a host script placed after the bundle
174
- // finds `publishUsers` at once and can publish before the app mounts.
175
- export function installHostApi(): void {
176
- if (typeof window === 'undefined' || installed) return
177
- installed = true
178
- const host = window as Window & { moi?: { collab?: HostApi; [key: string]: unknown } }
179
- host.moi ??= {}
180
- const api: HostApi = { publishUsers }
181
- host.moi.collab = api
182
- }
183
-
184
144
  // Storage events update this tab without writing back and triggering another event.
185
145
  export function receiveLocalProfile(event: Pick<StorageEvent, 'key' | 'newValue'>): void {
186
- if (event.key !== PROFILE_KEY || !event.newValue || currentUserSource !== 'local') return
146
+ if (event.key !== PROFILE_KEY || !event.newValue || getCurrentUserSource() !== 'local') return
187
147
  try {
188
148
  const profile = normalizeUserProfile(JSON.parse(event.newValue) as UserProfile)
189
149
  if (sameProfile(profile, currentUser)) return
@@ -1,9 +1,21 @@
1
1
  import type { UserProfile, Connection, PresenceRegistration } from '@/lib/collab/types'
2
2
  import { COLLAB_PROTOCOL_VERSION } from '@/lib/collab/protocol'
3
3
  import type { CollabEngineApi } from '../client'
4
- import { normalizeUsers } from '../host-state'
4
+ import { normalizeUserProfile } from '../host-state'
5
5
  import { CollabStore } from '../store'
6
6
 
7
+ function normalizeUsers(users: readonly UserProfile[]): readonly UserProfile[] {
8
+ if (!Array.isArray(users)) throw new Error('Users must be an array.')
9
+ const ids = new Set<string>()
10
+ const snapshot = users.map(user => {
11
+ const normalized = normalizeUserProfile(user)
12
+ if (ids.has(normalized.id)) throw new Error('Users must have unique ids.')
13
+ ids.add(normalized.id)
14
+ return normalized
15
+ })
16
+ return Object.freeze(snapshot)
17
+ }
18
+
7
19
  export type FakeEngineOptions = {
8
20
  self: UserProfile | undefined
9
21
  page?: string
@@ -22,18 +22,6 @@ export function userStatus(connections: readonly Connection[], id: string): User
22
22
  : 'offline'
23
23
  }
24
24
 
25
- // A supplied host directory is authoritative, including an empty list/removals.
26
- export function workspaceProfiles(
27
- liveUsers: readonly UserProfile[],
28
- self: UserProfile | undefined,
29
- directory: readonly UserProfile[] | undefined
30
- ): readonly UserProfile[] {
31
- if (directory !== undefined) return directory
32
- const users = new Map(liveUsers.map(user => [user.id, user]))
33
- if (self) users.set(self.id, self)
34
- return [...users.values()]
35
- }
36
-
37
25
  export function resolveUser(source: UsersSource, id: string): WorkspaceUser | undefined {
38
26
  const profile = source.users.find(user => user.id === id)
39
27
  return profile ? { ...profile, status: userStatus(source.connections, id) } : undefined
@@ -1,17 +1,25 @@
1
- import { useQuery } from '@tanstack/react-query'
1
+ import { useQuery, useQueryClient } from '@tanstack/react-query'
2
2
 
3
- import { requestJson } from '@/client/api/http'
3
+ import { readConnectors } from './read-connectors'
4
4
  import { workspaceKeys } from '@/client/api/workspace-keys'
5
5
  import type { McpServer } from '@/lib/types'
6
6
 
7
7
  export function useWorkspaceMcp(workspaceId: string, enabled: boolean) {
8
+ const queryClient = useQueryClient()
8
9
  return useQuery<McpServer[]>({
9
10
  queryKey: workspaceKeys.mcp(workspaceId),
10
- queryFn: () => requestJson(`/api/workspaces/${workspaceId}/mcp`),
11
+ queryFn: async ({ signal }) =>
12
+ readConnectors(
13
+ await fetch(`/api/workspaces/${workspaceId}/mcp?stream=true`, { signal }),
14
+ connectors => {
15
+ if (!signal.aborted) queryClient.setQueryData(workspaceKeys.mcp(workspaceId), connectors)
16
+ }
17
+ ),
18
+ retry: false,
11
19
  enabled,
12
20
  staleTime: Infinity,
13
21
  gcTime: Infinity,
14
- refetchOnMount: false,
22
+ refetchOnMount: 'always',
15
23
  refetchOnWindowFocus: false
16
24
  })
17
25
  }
@@ -1,4 +1,4 @@
1
- import type { ReactNode } from 'react'
1
+ import { useState, type ReactNode } from 'react'
2
2
 
3
3
  import { IconAlertCircleFilled } from '@tabler/icons-react'
4
4
 
@@ -15,16 +15,18 @@ function statusLabel(status: McpServer['status']): string {
15
15
  type McpServerIconProps = {
16
16
  name: string
17
17
  status: McpServer['status']
18
+ iconUrl?: string
18
19
  }
19
20
 
20
- function McpServerIcon({ name, status }: McpServerIconProps) {
21
- const icon = getMcpIcon(name)
21
+ function McpServerIcon({ name, status, iconUrl }: McpServerIconProps) {
22
+ const [failedIcon, setFailedIcon] = useState<string>()
23
+ const icon = iconUrl ?? getMcpIcon(name)
22
24
  const className = 'size-full rounded-lg ring-2 ring-background'
23
25
 
24
26
  return (
25
27
  <span className="relative size-10 shrink-0">
26
- {icon ? (
27
- <img src={icon} alt="" className={className} />
28
+ {icon && icon !== failedIcon ? (
29
+ <img src={icon} alt="" className={className} onError={() => setFailedIcon(icon)} />
28
30
  ) : (
29
31
  <span className="flex size-full items-center justify-center rounded-lg bg-muted text-muted-foreground ring-2 ring-background">
30
32
  <IconMcp className="size-5" />
@@ -68,9 +70,17 @@ function McpServerCardLayout({ icon, children }: McpServerCardLayoutProps) {
68
70
 
69
71
  export function McpServerCard({ server }: McpServerCardProps) {
70
72
  return (
71
- <McpServerCardLayout icon={<McpServerIcon name={server.name} status={server.status} />}>
73
+ <McpServerCardLayout
74
+ icon={
75
+ <McpServerIcon
76
+ name={server.displayName ?? server.name}
77
+ status={server.status}
78
+ iconUrl={server.iconUrl}
79
+ />
80
+ }
81
+ >
72
82
  <div className="truncate text-sm font-medium text-foreground">
73
- {formatMcpServerName(server.name)}
83
+ {server.displayName ?? formatMcpServerName(server.name)}
74
84
  </div>
75
85
  <span className="text-sm text-muted-foreground">{statusLabel(server.status)}</span>
76
86
  </McpServerCardLayout>
@@ -0,0 +1,35 @@
1
+ import type { McpServer } from '@/lib/types'
2
+
3
+ export async function readConnectors(
4
+ response: Response,
5
+ onProgress: (connectors: McpServer[]) => void
6
+ ): Promise<McpServer[]> {
7
+ if (!response.ok || !response.body) throw new Error('Could not load connectors')
8
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader()
9
+ let buffer = ''
10
+ try {
11
+ while (true) {
12
+ const chunk = await reader.read()
13
+ if (chunk.done) throw new Error('Connector discovery ended before completion')
14
+ buffer += chunk.value
15
+ let newline: number
16
+ while ((newline = buffer.indexOf('\n')) !== -1) {
17
+ const line = buffer.slice(0, newline)
18
+ buffer = buffer.slice(newline + 1)
19
+ if (!line.trim()) continue
20
+ const frame = JSON.parse(line) as {
21
+ connectors?: McpServer[]
22
+ done?: boolean
23
+ error?: string
24
+ }
25
+ if (frame.error) throw new Error(frame.error)
26
+ if (!frame.connectors) continue
27
+ if (frame.done) return frame.connectors
28
+ onProgress(frame.connectors)
29
+ }
30
+ }
31
+ } finally {
32
+ await reader.cancel().catch(() => {})
33
+ reader.releaseLock()
34
+ }
35
+ }
@@ -0,0 +1,58 @@
1
+ import { useRef, type ReactNode } from 'react'
2
+ import { useMutation } from '@tanstack/react-query'
3
+ import { IconLoader } from '@tabler/icons-react'
4
+ import { Button } from '@/client/components/ui/button'
5
+ import { toast } from '@/client/components/ui/toast'
6
+ import { Tooltip, TooltipContent, TooltipTrigger } from '@/client/components/ui/tooltip'
7
+ import { useAccount } from '../account/account-provider'
8
+
9
+ type CloudAvatarUploadProps = { children: ReactNode }
10
+
11
+ export function CloudAvatarUpload({ children }: CloudAvatarUploadProps) {
12
+ const account = useAccount()
13
+ const input = useRef<HTMLInputElement>(null)
14
+ const upload = useMutation({
15
+ mutationFn: (file: File) => account.saveAvatar(file),
16
+ onSuccess: () => toast.add({ title: 'Avatar updated', type: 'success' }),
17
+ onError: error =>
18
+ toast.add({ title: 'Couldn’t update avatar', description: error.message, type: 'error' })
19
+ })
20
+
21
+ return (
22
+ <>
23
+ <input
24
+ ref={input}
25
+ type="file"
26
+ accept="image/*"
27
+ aria-label="Choose an avatar file"
28
+ className="hidden"
29
+ disabled={upload.isPending}
30
+ onChange={event => {
31
+ const file = event.currentTarget.files?.[0]
32
+ event.currentTarget.value = ''
33
+ if (file) upload.mutate(file)
34
+ }}
35
+ />
36
+ <Tooltip>
37
+ <TooltipTrigger
38
+ render={
39
+ <Button
40
+ variant="ghost"
41
+ size="icon"
42
+ className="rounded-full"
43
+ aria-label="Change your avatar"
44
+ aria-busy={upload.isPending}
45
+ disabled={upload.isPending || !account.registered}
46
+ onClick={() => input.current?.click()}
47
+ />
48
+ }
49
+ >
50
+ {upload.isPending ? <IconLoader className="animate-spin" stroke={1.5} /> : children}
51
+ </TooltipTrigger>
52
+ <TooltipContent>
53
+ {upload.isPending ? 'Updating avatar…' : 'Change your avatar'}
54
+ </TooltipContent>
55
+ </Tooltip>
56
+ </>
57
+ )
58
+ }