moi-computer 0.11.1-next.3 → 0.11.1-next.5
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.
- package/client/api/app-config.ts +7 -4
- package/client/app/AppRouter.tsx +2 -2
- package/client/app/routes/WorkspaceRoute.tsx +27 -19
- package/client/features/applets/{AppletMount.tsx → AppletContainer.tsx} +7 -5
- package/client/features/applets/WidgetShell.tsx +3 -3
- package/client/features/applets/applet-cache.ts +3 -5
- package/client/features/applets/applet-runtime.ts +27 -12
- package/client/features/applets/applet-thumbnail.ts +2 -1
- package/client/features/chat/applet-chat-intents.ts +14 -6
- package/client/features/chat/composer/ModelPicker.tsx +2 -15
- package/client/features/chat/messages/MarkdownContent.tsx +5 -2
- package/client/features/chat/sessions/browser-tab-state.ts +18 -0
- package/client/features/chat/sessions/useSelectedSession.ts +55 -21
- package/client/features/chat/useChat.ts +4 -0
- package/client/features/collab/applet-api.ts +34 -0
- package/client/features/collab/client.ts +239 -0
- package/client/features/collab/components/cursors.tsx +199 -0
- package/client/features/collab/components/presence-avatars.tsx +61 -0
- package/client/features/collab/components/presence-frame.tsx +126 -0
- package/client/features/collab/components/presence-group.tsx +23 -0
- package/client/features/collab/components/presence-helpers.ts +50 -0
- package/client/features/collab/components/user-avatar-group.tsx +22 -0
- package/client/features/collab/components/user-avatar.tsx +40 -0
- package/client/features/collab/components/user.tsx +50 -0
- package/client/features/collab/hooks.tsx +164 -0
- package/client/features/collab/host-state.ts +254 -0
- package/client/features/collab/index.ts +5 -0
- package/client/features/collab/local-user.ts +46 -0
- package/client/features/collab/presence-publisher.ts +30 -0
- package/client/features/collab/presence-target.ts +8 -0
- package/client/features/collab/provider.tsx +79 -0
- package/client/features/collab/proxy-user.ts +35 -0
- package/client/features/collab/store.ts +156 -0
- package/client/features/collab/testing/component-fixtures.tsx +54 -0
- package/client/features/collab/testing/fake-engine.ts +129 -0
- package/client/features/collab/users.ts +106 -0
- package/client/features/collab/workspace-users-menu.tsx +194 -0
- package/client/features/connectors/mcp-icons.ts +0 -2
- package/client/features/dev/DevIndexPage.tsx +5 -0
- package/client/features/dev/DevRoutes.tsx +16 -4
- package/client/features/dev/collab/collab-page.tsx +24 -0
- package/client/features/dev/collab/collab-playground.tsx +614 -0
- package/client/features/dev/collab/local-user-settings.tsx +166 -0
- package/client/features/dev/collab/playground-room.ts +33 -0
- package/client/features/dev/{UiComponentsPage.tsx → ui-components/ui-components-page.tsx} +1 -1
- package/client/features/overview/WidgetCanvas.tsx +3 -1
- package/client/features/views/ViewManager.tsx +12 -7
- package/client/features/views/api.ts +2 -2
- package/client/features/views/useViewBuilderActions.ts +3 -0
- package/client/features/workspace/WorkspaceContext.tsx +1 -1
- package/client/features/workspace/WorkspaceLayoutContext.tsx +8 -2
- package/client/features/workspace/WorkspaceScreen.tsx +19 -11
- package/client/features/workspace/WorkspaceTabs.tsx +3 -3
- package/client/features/workspace/api.ts +2 -1
- package/client/features/workspace/browser-tab-state.ts +44 -0
- package/client/features/workspace/layout-save.ts +13 -0
- package/client/features/workspace/moi-context.ts +2 -1
- package/client/features/workspace/useWorkspaceNavigation.ts +20 -8
- package/client/index.css +45 -0
- package/client/index.tsx +9 -4
- package/client/main.tsx +1 -11
- package/client/theme.css +4 -1
- package/dist/chunk-2jncyq65.js +1 -0
- package/dist/{chunk-brr0zbeh.js → chunk-3a48fyf7.js} +2 -2
- package/dist/{chunk-tzz101ea.js → chunk-97eg9mjn.js} +1 -1
- package/dist/chunk-9zpvdws4.js +68 -0
- package/dist/{chunk-zs4mte79.js → chunk-efdyz6xp.js} +1 -1
- package/dist/chunk-h2kj1ysj.js +1 -0
- package/dist/chunk-hvj7tp3y.js +1 -0
- package/dist/chunk-jf6czgrz.js +2 -0
- package/dist/chunk-nez8sdta.js +1 -0
- package/dist/chunk-nzwgm8vc.css +1 -0
- package/dist/chunk-ryg9z3kn.js +10 -0
- package/dist/chunk-tpn177bt.js +2 -0
- package/dist/chunk-vfpsc75k.js +2 -0
- package/dist/{chunk-m1fvqssh.js → chunk-z3byfve5.js} +2 -2
- package/dist/index.html +1 -1
- package/lib/collab/colors.ts +30 -0
- package/lib/collab/protocol.ts +84 -0
- package/lib/collab/types.ts +52 -0
- package/lib/experimental.ts +14 -0
- package/lib/moi-context.ts +11 -3
- package/lib/navigation.ts +25 -5
- package/lib/types.ts +22 -34
- package/package.json +2 -2
- package/server/AGENTS.md +1 -1
- package/server/api.ts +28 -5
- package/server/app-config.ts +127 -34
- package/server/applet-typecheck.ts +8 -3
- package/server/applets/applet-css.ts +1 -1
- package/server/applets/build-applet.ts +9 -3
- package/server/applets/declarations/base.d.ts +75 -0
- package/server/applets/declarations/collab.d.ts +88 -0
- package/server/applets/declarations.ts +46 -0
- package/server/applets/index.ts +8 -8
- package/server/applets/runtime/collab.ts +94 -0
- package/server/applets/runtime/moi.ts +12 -19
- package/server/applets/runtime/rpc.ts +2 -4
- package/server/chat-selection.ts +22 -0
- package/server/cli.ts +60 -15
- package/server/collab/cloudflare-access.ts +78 -0
- package/server/collab/config.ts +18 -0
- package/server/collab/manager.ts +407 -0
- package/server/collab/service.ts +136 -0
- package/server/collab/skill/index.ts +53 -0
- package/server/collab/worker-messages.ts +10 -0
- package/server/collab/worker.ts +52 -0
- package/server/layout.ts +10 -3
- package/server/moi-scaffold.ts +3 -64
- package/server/preview.ts +1 -1
- package/server/skill-update.ts +7 -9
- package/server/skills-template.ts +14 -2
- package/server/web.ts +65 -17
- package/ui-components/avatar.tsx +24 -11
- package/ui-components/button.tsx +9 -9
- package/ui-components/docs/avatar.md +11 -30
- package/workspace/.claude/skills/moi-workspace/SKILL.md +14 -11
- package/workspace/.claude/skills/moi-workspace/references/COLLAB.md +262 -0
- package/workspace/.claude/skills/moi-workspace/references/INTENTS.md +10 -7
- package/client/assets/mcp/agentation.png +0 -0
- package/dist/agentation-4s0nn45p.png +0 -0
- package/dist/chunk-1pp135b4.js +0 -1
- package/dist/chunk-2gs8jjx4.css +0 -1
- package/dist/chunk-94m3q9ce.js +0 -1
- package/dist/chunk-azkjzc7a.js +0 -68
- package/dist/chunk-p34hvqt3.js +0 -1
- package/dist/chunk-p83f0jnj.js +0 -2
- package/dist/chunk-xg01f6pn.js +0 -10
- /package/client/features/dev/{UiComponentPreviews.tsx → ui-components/ui-component-previews.tsx} +0 -0
- /package/server/applets/{runtime/base.ts → api-base.ts} +0 -0
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { JsonValue } from 'moi'
|
|
2
|
+
import { createContext, useContext, useLayoutEffect, useRef } from 'react'
|
|
3
|
+
import type { FocusEvent } from 'react'
|
|
4
|
+
import { presenceChannels, usePresenceChannel, usePresencePublisher } from '../hooks'
|
|
5
|
+
import { presenceTarget } from '../presence-target'
|
|
6
|
+
|
|
7
|
+
export const hasPresence = (value: JsonValue) => value !== false && value !== null
|
|
8
|
+
|
|
9
|
+
export const PresenceGroupContext = createContext<readonly string[]>([])
|
|
10
|
+
|
|
11
|
+
export function usePresenceTarget(id: string): string {
|
|
12
|
+
return presenceTarget(...useContext(PresenceGroupContext), id)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function useTargetPresence(target: string, present?: boolean) {
|
|
16
|
+
const automatic = present === undefined
|
|
17
|
+
const root = useRef<HTMLDivElement>(null)
|
|
18
|
+
const channel = presenceChannels.target(target)
|
|
19
|
+
const others = usePresenceChannel<boolean>(channel)
|
|
20
|
+
const publish = usePresencePublisher<boolean>(channel, false, hasPresence)
|
|
21
|
+
const ownsFocus = (element: EventTarget | null, owner: HTMLDivElement | null) =>
|
|
22
|
+
owner !== null &&
|
|
23
|
+
element instanceof Element &&
|
|
24
|
+
element.closest('[data-presence-target]') === owner
|
|
25
|
+
useLayoutEffect(() => {
|
|
26
|
+
publish(present ?? ownsFocus(document.activeElement, root.current))
|
|
27
|
+
}, [target, present, publish])
|
|
28
|
+
const users = new Map<string, { id: string; connectionId: string }>()
|
|
29
|
+
for (const entry of others) {
|
|
30
|
+
if (entry.value === true && !users.has(entry.userId)) {
|
|
31
|
+
users.set(entry.userId, { id: entry.userId, connectionId: entry.connectionId })
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return {
|
|
35
|
+
users: [...users.values()],
|
|
36
|
+
props: {
|
|
37
|
+
ref: root,
|
|
38
|
+
'data-collab-target': target,
|
|
39
|
+
'data-presence-target': automatic ? target : undefined,
|
|
40
|
+
onFocusCapture: automatic
|
|
41
|
+
? (event: FocusEvent<HTMLDivElement>) =>
|
|
42
|
+
publish(ownsFocus(event.target, event.currentTarget))
|
|
43
|
+
: undefined,
|
|
44
|
+
onBlurCapture: automatic
|
|
45
|
+
? (event: FocusEvent<HTMLDivElement>) =>
|
|
46
|
+
publish(ownsFocus(event.relatedTarget, event.currentTarget))
|
|
47
|
+
: undefined
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { UserAvatarGroupProps } from 'moi/collab'
|
|
2
|
+
import { AvatarGroup as AvatarGroupPrimitive, AvatarGroupCount } from '@/ui-components/avatar'
|
|
3
|
+
import { UserAvatar } from './user-avatar'
|
|
4
|
+
|
|
5
|
+
export function UserAvatarGroup({ ids, max = 3, size = 'sm', className }: UserAvatarGroupProps) {
|
|
6
|
+
const unique = [...new Set(ids)]
|
|
7
|
+
const shown = unique.slice(0, max)
|
|
8
|
+
const hidden = unique.length - shown.length
|
|
9
|
+
|
|
10
|
+
return (
|
|
11
|
+
<AvatarGroupPrimitive className={className} aria-label={`${unique.length} users`}>
|
|
12
|
+
{shown.map(id => (
|
|
13
|
+
<UserAvatar key={id} id={id} size={size} />
|
|
14
|
+
))}
|
|
15
|
+
{hidden > 0 && (
|
|
16
|
+
<AvatarGroupCount size={size} aria-label={`${hidden} more`}>
|
|
17
|
+
+{hidden}
|
|
18
|
+
</AvatarGroupCount>
|
|
19
|
+
)}
|
|
20
|
+
</AvatarGroupPrimitive>
|
|
21
|
+
)
|
|
22
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { UserAvatarProps } from 'moi/collab'
|
|
2
|
+
import { IconUser } from '@tabler/icons-react'
|
|
3
|
+
import { Blobatar } from '@blobatar/react'
|
|
4
|
+
import { Avatar, AvatarBadge, AvatarFallback, AvatarImage } from '@/ui-components/avatar'
|
|
5
|
+
import { useUser } from '../hooks'
|
|
6
|
+
import { userDisplayName } from '../users'
|
|
7
|
+
|
|
8
|
+
export function UserAvatar({ id, size = 'default', showStatusBadge, className }: UserAvatarProps) {
|
|
9
|
+
const user = useUser(id)
|
|
10
|
+
const name = user ? userDisplayName(user) : 'Unknown user'
|
|
11
|
+
|
|
12
|
+
return (
|
|
13
|
+
<Avatar
|
|
14
|
+
size={size}
|
|
15
|
+
aria-label={name}
|
|
16
|
+
data-collab-color={user?.color ?? 'unknown'}
|
|
17
|
+
className={className}
|
|
18
|
+
>
|
|
19
|
+
{user?.avatar && <AvatarImage src={user.avatar} alt="" />}
|
|
20
|
+
<AvatarFallback>
|
|
21
|
+
{user ? (
|
|
22
|
+
<Blobatar
|
|
23
|
+
name={id}
|
|
24
|
+
animate="hover"
|
|
25
|
+
background="circle"
|
|
26
|
+
traits={{ shape: 0, 'body.r': 1 }}
|
|
27
|
+
palette={{
|
|
28
|
+
bg: 'var(--collab)',
|
|
29
|
+
head: 'var(--collab)',
|
|
30
|
+
eye: 'var(--collab-foreground)'
|
|
31
|
+
}}
|
|
32
|
+
/>
|
|
33
|
+
) : (
|
|
34
|
+
<IconUser size={size === 'xs' || size === 'sm' ? 12 : 16} stroke={1.75} />
|
|
35
|
+
)}
|
|
36
|
+
</AvatarFallback>
|
|
37
|
+
{showStatusBadge && user?.status === 'active' && <AvatarBadge className="bg-success" />}
|
|
38
|
+
</Avatar>
|
|
39
|
+
)
|
|
40
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { UserProps } from 'moi/collab'
|
|
2
|
+
import { cn } from '@/client/lib/cn'
|
|
3
|
+
import { UserAvatar } from './user-avatar'
|
|
4
|
+
import { useMe, useUser } from '../hooks'
|
|
5
|
+
import { userDisplayName } from '../users'
|
|
6
|
+
|
|
7
|
+
const UNKNOWN_NAME = 'Unknown user'
|
|
8
|
+
|
|
9
|
+
export function User({
|
|
10
|
+
id,
|
|
11
|
+
size = 'default',
|
|
12
|
+
showStatusBadge,
|
|
13
|
+
showYouLabel,
|
|
14
|
+
description,
|
|
15
|
+
className
|
|
16
|
+
}: UserProps) {
|
|
17
|
+
const user = useUser(id)
|
|
18
|
+
const me = useMe()
|
|
19
|
+
const name = user ? userDisplayName(user) : UNKNOWN_NAME
|
|
20
|
+
const isSelf = user !== undefined && user.id === me?.id
|
|
21
|
+
|
|
22
|
+
return (
|
|
23
|
+
<span className={cn('inline-flex min-w-0 items-center gap-2', className)}>
|
|
24
|
+
<UserAvatar id={id} size={size} showStatusBadge={showStatusBadge} />
|
|
25
|
+
<span
|
|
26
|
+
className={cn('flex min-w-0 flex-1 text-sm', size === 'xs' ? 'items-baseline' : 'flex-col')}
|
|
27
|
+
>
|
|
28
|
+
<span className="flex min-w-0 items-baseline gap-1">
|
|
29
|
+
<span className={cn('truncate', !user && 'text-muted-foreground')}>{name}</span>
|
|
30
|
+
{showYouLabel && isSelf && <span className="shrink-0 text-muted-foreground">(You)</span>}
|
|
31
|
+
</span>
|
|
32
|
+
{description && (
|
|
33
|
+
<span
|
|
34
|
+
className={cn(
|
|
35
|
+
'truncate text-muted-foreground',
|
|
36
|
+
size === 'sm' && 'text-xs leading-tight'
|
|
37
|
+
)}
|
|
38
|
+
>
|
|
39
|
+
{size === 'xs' && (
|
|
40
|
+
<span aria-hidden="true" className="whitespace-pre">
|
|
41
|
+
{' · '}
|
|
42
|
+
</span>
|
|
43
|
+
)}
|
|
44
|
+
{description}
|
|
45
|
+
</span>
|
|
46
|
+
)}
|
|
47
|
+
</span>
|
|
48
|
+
</span>
|
|
49
|
+
)
|
|
50
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import {
|
|
2
|
+
useCallback,
|
|
3
|
+
useLayoutEffect,
|
|
4
|
+
useMemo,
|
|
5
|
+
useRef,
|
|
6
|
+
useState,
|
|
7
|
+
useSyncExternalStore
|
|
8
|
+
} from 'react'
|
|
9
|
+
import type { JsonValue } from 'moi'
|
|
10
|
+
import type { PresenceValue } from 'moi/collab'
|
|
11
|
+
|
|
12
|
+
import { useAppletPresence, useCollabEngine } from './provider'
|
|
13
|
+
import { resolvePeers, resolveUser, workspaceProfiles } from './users'
|
|
14
|
+
import type { WorkspaceUser, UsePeersOptions, UseWorkspaceUsersOptions } from './users'
|
|
15
|
+
import { createPresencePublisher } from './presence-publisher'
|
|
16
|
+
|
|
17
|
+
export type { WorkspaceUser, UsePeersOptions, UseWorkspaceUsersOptions } from './users'
|
|
18
|
+
|
|
19
|
+
export function useConnectionState() {
|
|
20
|
+
const engine = useCollabEngine()
|
|
21
|
+
return useSyncExternalStore(engine.subscribe, engine.getUsersSnapshot, engine.getUsersSnapshot)
|
|
22
|
+
}
|
|
23
|
+
export function useWorkspaceDirectory() {
|
|
24
|
+
const engine = useCollabEngine()
|
|
25
|
+
return useSyncExternalStore(
|
|
26
|
+
engine.subscribeWorkspaceUsers,
|
|
27
|
+
engine.getWorkspaceDirectory,
|
|
28
|
+
engine.getWorkspaceDirectory
|
|
29
|
+
)
|
|
30
|
+
}
|
|
31
|
+
function useUsersSource() {
|
|
32
|
+
const engine = useCollabEngine()
|
|
33
|
+
const state = useConnectionState()
|
|
34
|
+
const self = useSyncExternalStore(
|
|
35
|
+
engine.subscribeCurrentUser,
|
|
36
|
+
engine.getCurrentUser,
|
|
37
|
+
engine.getCurrentUser
|
|
38
|
+
)
|
|
39
|
+
const directory = useWorkspaceDirectory()
|
|
40
|
+
const users = useMemo(
|
|
41
|
+
() =>
|
|
42
|
+
workspaceProfiles(state.users, self, directory?.status === 'loading' ? [] : directory?.users),
|
|
43
|
+
[state.users, self, directory]
|
|
44
|
+
)
|
|
45
|
+
return { state, self, users, engine }
|
|
46
|
+
}
|
|
47
|
+
export function useUser(id: string): WorkspaceUser | undefined {
|
|
48
|
+
const { state, users } = useUsersSource()
|
|
49
|
+
return useMemo(() => resolveUser({ ...state, users }, id), [state, users, id])
|
|
50
|
+
}
|
|
51
|
+
export function useUsers(ids: readonly string[]): (WorkspaceUser | undefined)[] {
|
|
52
|
+
const { state, users } = useUsersSource()
|
|
53
|
+
return ids.map(id => resolveUser({ ...state, users }, id))
|
|
54
|
+
}
|
|
55
|
+
export function useWorkspaceUsers({ status }: UseWorkspaceUsersOptions = {}): WorkspaceUser[] {
|
|
56
|
+
const { state, users } = useUsersSource()
|
|
57
|
+
return useMemo(
|
|
58
|
+
() =>
|
|
59
|
+
users
|
|
60
|
+
.map(user => resolveUser({ ...state, users }, user.id)!)
|
|
61
|
+
.filter(user => !status || user.status === status),
|
|
62
|
+
[state, users, status]
|
|
63
|
+
)
|
|
64
|
+
}
|
|
65
|
+
export function useMe(): WorkspaceUser | undefined {
|
|
66
|
+
const { state, self, users } = useUsersSource()
|
|
67
|
+
return useMemo(
|
|
68
|
+
() => (self ? resolveUser({ ...state, users }, self.id) : undefined),
|
|
69
|
+
[state, self, users]
|
|
70
|
+
)
|
|
71
|
+
}
|
|
72
|
+
export function usePeers(options: UsePeersOptions = {}): WorkspaceUser[] {
|
|
73
|
+
const { state, self, users, engine } = useUsersSource()
|
|
74
|
+
const { scope, status } = options
|
|
75
|
+
return useMemo(
|
|
76
|
+
() => resolvePeers({ ...state, users }, self?.id, engine.getLocation(), { scope, status }),
|
|
77
|
+
[state, self, users, engine, scope, status]
|
|
78
|
+
)
|
|
79
|
+
}
|
|
80
|
+
export const presenceChannels = {
|
|
81
|
+
custom: (channel: string) => `custom:${channel}`,
|
|
82
|
+
cursor: (id: string) => `cursor:${id}`,
|
|
83
|
+
target: (target: string) => `field:${target}`
|
|
84
|
+
}
|
|
85
|
+
export type { PresenceValue } from 'moi/collab'
|
|
86
|
+
|
|
87
|
+
// Observation never allocates a registration or publishes a value.
|
|
88
|
+
export function usePresence<T extends JsonValue>(channel: string): PresenceValue<T>[] {
|
|
89
|
+
return usePresenceChannel<T>(presenceChannels.custom(channel))
|
|
90
|
+
}
|
|
91
|
+
export function usePresenceChannel<T extends JsonValue>(channel: string): PresenceValue<T>[] {
|
|
92
|
+
const { users, engine } = useUsersSource()
|
|
93
|
+
const presence = useAppletPresence()
|
|
94
|
+
const appletId = presence?.appletId ?? ''
|
|
95
|
+
const snapshot = useCallback(
|
|
96
|
+
() => engine.getPresenceSnapshot(appletId, channel),
|
|
97
|
+
[engine, appletId, channel]
|
|
98
|
+
)
|
|
99
|
+
const entries = useSyncExternalStore(engine.subscribe, snapshot, snapshot)
|
|
100
|
+
return useMemo(() => {
|
|
101
|
+
if (!presence?.active) return []
|
|
102
|
+
const known = new Set(users.map(user => user.id))
|
|
103
|
+
return entries
|
|
104
|
+
.filter(entry => known.has(entry.userId))
|
|
105
|
+
.map(entry => ({
|
|
106
|
+
connectionId: entry.connectionId,
|
|
107
|
+
userId: entry.userId,
|
|
108
|
+
value: entry.value as T
|
|
109
|
+
}))
|
|
110
|
+
}, [entries, users, presence])
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Internal imperative publisher for pointer/focus events. Ownership is per mount.
|
|
114
|
+
export function usePresencePublisher<T extends JsonValue>(
|
|
115
|
+
channel: string,
|
|
116
|
+
initialValue: T,
|
|
117
|
+
isPresent?: (value: T) => boolean
|
|
118
|
+
): (value: T) => void {
|
|
119
|
+
const engine = useCollabEngine()
|
|
120
|
+
const presence = useAppletPresence()
|
|
121
|
+
const [registrationId] = useState(() => crypto.randomUUID())
|
|
122
|
+
const valueRef = useRef(initialValue)
|
|
123
|
+
const live = useRef(false)
|
|
124
|
+
const appletId = presence?.appletId ?? ''
|
|
125
|
+
const registration = useMemo(
|
|
126
|
+
() => createPresencePublisher<T>(engine, { registrationId, appletId, channel }, isPresent),
|
|
127
|
+
[engine, registrationId, appletId, channel, isPresent]
|
|
128
|
+
)
|
|
129
|
+
const publish = useCallback(() => {
|
|
130
|
+
registration.publish(
|
|
131
|
+
valueRef.current,
|
|
132
|
+
presence?.active === true && document.visibilityState !== 'hidden'
|
|
133
|
+
)
|
|
134
|
+
}, [presence, registration])
|
|
135
|
+
useLayoutEffect(() => {
|
|
136
|
+
if (!presence?.active) return
|
|
137
|
+
live.current = true
|
|
138
|
+
publish()
|
|
139
|
+
document.addEventListener('visibilitychange', publish)
|
|
140
|
+
return () => {
|
|
141
|
+
live.current = false
|
|
142
|
+
document.removeEventListener('visibilitychange', publish)
|
|
143
|
+
registration.clear()
|
|
144
|
+
}
|
|
145
|
+
}, [presence, publish, registration])
|
|
146
|
+
return useCallback(
|
|
147
|
+
(value: T) => {
|
|
148
|
+
valueRef.current = value
|
|
149
|
+
if (live.current) publish()
|
|
150
|
+
},
|
|
151
|
+
[publish]
|
|
152
|
+
)
|
|
153
|
+
}
|
|
154
|
+
export function usePublishPresenceChannel<T extends JsonValue>(
|
|
155
|
+
channel: string,
|
|
156
|
+
value: T,
|
|
157
|
+
isPresent?: (value: T) => boolean
|
|
158
|
+
): void {
|
|
159
|
+
const publish = usePresencePublisher(channel, value, isPresent)
|
|
160
|
+
useLayoutEffect(() => publish(value), [publish, value])
|
|
161
|
+
}
|
|
162
|
+
export function usePublishPresence<T extends JsonValue>(channel: string, value: T): void {
|
|
163
|
+
usePublishPresenceChannel(presenceChannels.custom(channel), value)
|
|
164
|
+
}
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { isUserProfile } from '@/lib/collab/protocol'
|
|
2
|
+
import { colorForId, isUserColor } from '@/lib/collab/colors'
|
|
3
|
+
import type { AuthProvider, ProxyUserState, UserProfile } from '@/lib/collab/types'
|
|
4
|
+
import { createLocalUser } from './local-user'
|
|
5
|
+
|
|
6
|
+
export type UserProfileInput = Omit<UserProfile, 'color'> & { color?: UserProfile['color'] }
|
|
7
|
+
export type WorkspaceDirectory<Profile = UserProfile> =
|
|
8
|
+
| { readonly status: 'loading' }
|
|
9
|
+
| { readonly status: 'ready'; readonly users: readonly Profile[] }
|
|
10
|
+
type State<Profile> = {
|
|
11
|
+
readonly currentUser?: Profile
|
|
12
|
+
readonly workspaces: Readonly<Record<string, WorkspaceDirectory<Profile>>>
|
|
13
|
+
}
|
|
14
|
+
export type HostStateInput = State<UserProfileInput>
|
|
15
|
+
export type HostState = State<UserProfile>
|
|
16
|
+
export type HostApi = {
|
|
17
|
+
getHostState: () => HostState | undefined
|
|
18
|
+
setHostState: (state: HostStateInput) => void
|
|
19
|
+
subscribeHostState: (listener: (state: HostState | undefined) => void) => () => void
|
|
20
|
+
}
|
|
21
|
+
// Who supplies the current user: local setup, an outer host, or an auth proxy.
|
|
22
|
+
export type CurrentUserSource = 'local' | 'external' | AuthProvider
|
|
23
|
+
|
|
24
|
+
// Keep the existing key so local profiles survive the startup change.
|
|
25
|
+
const PROFILE_KEY = 'moi:collab:dev-profile'
|
|
26
|
+
let currentUser: UserProfile | undefined
|
|
27
|
+
let installed = false
|
|
28
|
+
let currentUserSource: CurrentUserSource | undefined
|
|
29
|
+
const listeners = new Set<() => void>()
|
|
30
|
+
const workspaceListeners = new Map<string, Set<() => void>>()
|
|
31
|
+
const hostListeners = new Set<() => void>()
|
|
32
|
+
const EMPTY_WORKSPACES = Object.freeze({})
|
|
33
|
+
const LOADING_DIRECTORY = Object.freeze({ status: 'loading' as const })
|
|
34
|
+
let hostState: HostState | undefined
|
|
35
|
+
|
|
36
|
+
export function normalizeUserProfile(value: UserProfileInput): UserProfile {
|
|
37
|
+
if (!value || typeof value.id !== 'string' || !value.id.trim())
|
|
38
|
+
throw new Error('A user profile needs an id.')
|
|
39
|
+
if (value.name !== undefined && typeof value.name !== 'string')
|
|
40
|
+
throw new Error('A user profile name must be a string when provided.')
|
|
41
|
+
if (value.color !== undefined && !isUserColor(value.color))
|
|
42
|
+
throw new Error('A user profile color must be one of the user palette names.')
|
|
43
|
+
const id = value.id.trim()
|
|
44
|
+
const name = value.name?.trim()
|
|
45
|
+
const normalized: UserProfile = {
|
|
46
|
+
id,
|
|
47
|
+
...(name ? { name } : {}),
|
|
48
|
+
color: value.color ?? colorForId(id),
|
|
49
|
+
...(value.avatar !== undefined ? { avatar: value.avatar } : {}),
|
|
50
|
+
...(value.email !== undefined ? { email: value.email } : {})
|
|
51
|
+
}
|
|
52
|
+
if (!isUserProfile(normalized)) throw new Error('Invalid user profile.')
|
|
53
|
+
return Object.freeze(normalized)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function normalizeWorkspaceUsers(
|
|
57
|
+
users: readonly UserProfileInput[]
|
|
58
|
+
): readonly UserProfile[] {
|
|
59
|
+
if (!Array.isArray(users)) throw new Error('Workspace 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('Workspace users must have unique ids.')
|
|
64
|
+
ids.add(normalized.id)
|
|
65
|
+
return normalized
|
|
66
|
+
})
|
|
67
|
+
return Object.freeze(snapshot)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function normalizeHostState(value: HostStateInput): HostState {
|
|
71
|
+
if (!value || typeof value !== 'object') throw new Error('Invalid host state.')
|
|
72
|
+
const current =
|
|
73
|
+
value.currentUser === undefined ? undefined : normalizeUserProfile(value.currentUser)
|
|
74
|
+
if (!value.workspaces || typeof value.workspaces !== 'object' || Array.isArray(value.workspaces))
|
|
75
|
+
throw new Error('Host workspaces must be a record.')
|
|
76
|
+
const entries = Object.entries(value.workspaces).map(([id, directory]) => {
|
|
77
|
+
if (!id.trim() || !directory || typeof directory !== 'object')
|
|
78
|
+
throw new Error('Invalid workspace directory.')
|
|
79
|
+
if (directory.status === 'loading') return [id, LOADING_DIRECTORY] as const
|
|
80
|
+
if (directory.status !== 'ready') throw new Error('Invalid workspace directory status.')
|
|
81
|
+
const profiles = normalizeWorkspaceUsers(directory.users)
|
|
82
|
+
// The viewer has one global profile; membership is still workspace-specific.
|
|
83
|
+
const users = Object.freeze(
|
|
84
|
+
profiles.map(user => (current && user.id === current.id ? current : user))
|
|
85
|
+
)
|
|
86
|
+
return [id, Object.freeze({ status: 'ready' as const, users })] as const
|
|
87
|
+
})
|
|
88
|
+
// Validate everything before discarding directories on sign-out.
|
|
89
|
+
return Object.freeze({
|
|
90
|
+
currentUser: current,
|
|
91
|
+
workspaces: current ? Object.freeze(Object.fromEntries(entries)) : EMPTY_WORKSPACES
|
|
92
|
+
})
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function getHostState(): HostState | undefined {
|
|
96
|
+
return hostState
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function getWorkspaceDirectory(workspaceId: string): WorkspaceDirectory | undefined {
|
|
100
|
+
if (!hostState) return undefined
|
|
101
|
+
const directory = Object.hasOwn(hostState.workspaces, workspaceId)
|
|
102
|
+
? hostState.workspaces[workspaceId]
|
|
103
|
+
: undefined
|
|
104
|
+
return directory ?? LOADING_DIRECTORY
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function setHostState(next: HostStateInput): void {
|
|
108
|
+
const normalized = normalizeHostState(next)
|
|
109
|
+
const previousDirectories = new Map(
|
|
110
|
+
[...workspaceListeners.keys()].map(id => [id, getWorkspaceDirectory(id)])
|
|
111
|
+
)
|
|
112
|
+
// Publish every field before notifying any observer, including transport listeners.
|
|
113
|
+
hostState = normalized
|
|
114
|
+
currentUserSource = 'external'
|
|
115
|
+
currentUser = normalized.currentUser
|
|
116
|
+
listeners.forEach(listener => listener())
|
|
117
|
+
for (const [id, subscriptions] of workspaceListeners) {
|
|
118
|
+
if (getWorkspaceDirectory(id) !== previousDirectories.get(id))
|
|
119
|
+
subscriptions.forEach(listener => listener())
|
|
120
|
+
}
|
|
121
|
+
hostListeners.forEach(listener => listener())
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function subscribeHostStateStore(listener: () => void): () => void {
|
|
125
|
+
hostListeners.add(listener)
|
|
126
|
+
return () => {
|
|
127
|
+
hostListeners.delete(listener)
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function subscribeHostState(listener: (state: HostState | undefined) => void): () => void {
|
|
132
|
+
const unsubscribe = subscribeHostStateStore(() => listener(getHostState()))
|
|
133
|
+
listener(getHostState())
|
|
134
|
+
return unsubscribe
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function subscribeWorkspaceUsersStore(
|
|
138
|
+
workspaceId: string,
|
|
139
|
+
listener: () => void
|
|
140
|
+
): () => void {
|
|
141
|
+
let subscriptions = workspaceListeners.get(workspaceId)
|
|
142
|
+
if (!subscriptions) {
|
|
143
|
+
subscriptions = new Set()
|
|
144
|
+
workspaceListeners.set(workspaceId, subscriptions)
|
|
145
|
+
}
|
|
146
|
+
subscriptions.add(listener)
|
|
147
|
+
return () => {
|
|
148
|
+
subscriptions.delete(listener)
|
|
149
|
+
if (!subscriptions.size) workspaceListeners.delete(workspaceId)
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function getCurrentUser(): UserProfile | undefined {
|
|
154
|
+
return currentUser
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function subscribeCurrentUserStore(listener: () => void): () => void {
|
|
158
|
+
listeners.add(listener)
|
|
159
|
+
return () => {
|
|
160
|
+
listeners.delete(listener)
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export function getCurrentUserSource(): CurrentUserSource | undefined {
|
|
165
|
+
return currentUserSource
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// An auth proxy takes precedence over local users; an outer host takes
|
|
169
|
+
// precedence over the proxy. A configured proxy with no user signs this tab out.
|
|
170
|
+
export function setProxyUserState({ provider, profile }: ProxyUserState): void {
|
|
171
|
+
if (currentUserSource === 'external') return
|
|
172
|
+
if (provider === undefined) {
|
|
173
|
+
if (currentUserSource === undefined || currentUserSource === 'local') return
|
|
174
|
+
currentUserSource = undefined
|
|
175
|
+
currentUser = undefined
|
|
176
|
+
} else {
|
|
177
|
+
const normalized = profile === undefined ? undefined : normalizeUserProfile(profile)
|
|
178
|
+
if (
|
|
179
|
+
currentUserSource === provider &&
|
|
180
|
+
JSON.stringify(currentUser) === JSON.stringify(normalized)
|
|
181
|
+
)
|
|
182
|
+
return
|
|
183
|
+
currentUserSource = provider
|
|
184
|
+
currentUser = normalized
|
|
185
|
+
}
|
|
186
|
+
listeners.forEach(listener => listener())
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function persistLocalUser(): void {
|
|
190
|
+
try {
|
|
191
|
+
sessionStorage.setItem(PROFILE_KEY, JSON.stringify(currentUser))
|
|
192
|
+
} catch {
|
|
193
|
+
/* Private browsing. */
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export function setLocalUser(next: UserProfile): void {
|
|
198
|
+
// A provider may take over between rendering the local user form and handling input.
|
|
199
|
+
if (currentUserSource !== undefined && currentUserSource !== 'local') return
|
|
200
|
+
const normalized = normalizeUserProfile(next)
|
|
201
|
+
currentUserSource = 'local'
|
|
202
|
+
currentUser = normalized
|
|
203
|
+
persistLocalUser()
|
|
204
|
+
listeners.forEach(listener => listener())
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// Called after startup config and proxy identity settle, before React mounts.
|
|
208
|
+
export function initializeLocalUser(enabled: boolean, proxyUser: ProxyUserState | undefined): void {
|
|
209
|
+
if (!enabled || !proxyUser || proxyUser.provider !== undefined || currentUserSource !== undefined)
|
|
210
|
+
return
|
|
211
|
+
try {
|
|
212
|
+
const saved = sessionStorage.getItem(PROFILE_KEY)
|
|
213
|
+
if (saved) {
|
|
214
|
+
setLocalUser(JSON.parse(saved) as UserProfile)
|
|
215
|
+
return
|
|
216
|
+
}
|
|
217
|
+
} catch {
|
|
218
|
+
/* Invalid or unavailable storage starts a fresh local profile. */
|
|
219
|
+
}
|
|
220
|
+
setLocalUser(createLocalUser())
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// A host supplies one initial atomic snapshot before loading moi's modules.
|
|
224
|
+
export function installHostApi(): void {
|
|
225
|
+
if (typeof window === 'undefined' || installed) return
|
|
226
|
+
installed = true
|
|
227
|
+
const host = window as Window & {
|
|
228
|
+
moi?: {
|
|
229
|
+
collab?: {
|
|
230
|
+
getHostState?: () => HostStateInput | undefined
|
|
231
|
+
}
|
|
232
|
+
[key: string]: unknown
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
const previous = host.moi?.collab
|
|
236
|
+
if (previous?.getHostState) {
|
|
237
|
+
try {
|
|
238
|
+
setHostState(previous.getHostState() ?? { workspaces: {} })
|
|
239
|
+
} catch {
|
|
240
|
+
// An unavailable host remains authoritative; never restore a local profile.
|
|
241
|
+
setHostState({ workspaces: {} })
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
host.moi ??= {}
|
|
245
|
+
const api: HostApi = {
|
|
246
|
+
getHostState,
|
|
247
|
+
setHostState,
|
|
248
|
+
subscribeHostState
|
|
249
|
+
}
|
|
250
|
+
host.moi.collab = api
|
|
251
|
+
if (typeof window.dispatchEvent === 'function') {
|
|
252
|
+
window.dispatchEvent(new CustomEvent('moi:collab-ready'))
|
|
253
|
+
}
|
|
254
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { CollabProvider, AppletPresenceProvider, useCollabEnabled } from './provider'
|
|
2
|
+
export { WorkspaceUsersMenu } from './workspace-users-menu'
|
|
3
|
+
export type { TabInfo } from './workspace-users-menu'
|
|
4
|
+
export { appletCollabApi } from './applet-api'
|
|
5
|
+
export type { AppletCollabApi } from './applet-api'
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { USER_COLORS } from '@/lib/collab/colors'
|
|
2
|
+
import type { UserColor } from '@/lib/collab/colors'
|
|
3
|
+
import type { UserProfile } from '@/lib/collab/types'
|
|
4
|
+
|
|
5
|
+
const LOCAL_USER_NAMES = [
|
|
6
|
+
'Curious Kiwi',
|
|
7
|
+
'Cheerful Cherry',
|
|
8
|
+
'Sleepy Peach',
|
|
9
|
+
'Excited Banana',
|
|
10
|
+
'Cosmic Mango',
|
|
11
|
+
'Velvet Lemon',
|
|
12
|
+
'Electric Plum',
|
|
13
|
+
'Wandering Pear',
|
|
14
|
+
'Dramatic Papaya',
|
|
15
|
+
'Suspicious Pineapple',
|
|
16
|
+
'Confused Coconut',
|
|
17
|
+
'Sneaky Tangerine',
|
|
18
|
+
'Gentle Fig',
|
|
19
|
+
'Quiet Apricot',
|
|
20
|
+
'Mellow Melon',
|
|
21
|
+
'Dreamy Guava'
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
export type LocalUserDraft = { name: string; color: UserColor }
|
|
25
|
+
|
|
26
|
+
function pick<T>(items: readonly T[], except?: T): T {
|
|
27
|
+
const pool = items.filter(item => item !== except)
|
|
28
|
+
return pool[Math.floor(Math.random() * pool.length)] ?? items[0]
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function randomLocalUser(current?: LocalUserDraft): LocalUserDraft {
|
|
32
|
+
return {
|
|
33
|
+
name: pick(LOCAL_USER_NAMES, current?.name),
|
|
34
|
+
color: pick(USER_COLORS, current?.color)
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function localUserProfile(id: string, draft: LocalUserDraft): UserProfile {
|
|
39
|
+
const name = draft.name.trim()
|
|
40
|
+
return { id, ...(name ? { name } : {}), color: draft.color }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// The id stays with the tab through renames, so peers keep seeing one user.
|
|
44
|
+
export function createLocalUser(): UserProfile {
|
|
45
|
+
return localUserProfile(`local-${crypto.randomUUID().slice(0, 8)}`, randomLocalUser())
|
|
46
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { JsonValue } from 'moi'
|
|
2
|
+
import type { PresenceRegistration } from '@/lib/collab/types'
|
|
3
|
+
|
|
4
|
+
import type { CollabEngineApi } from './client'
|
|
5
|
+
|
|
6
|
+
// A mounted control owns a registration only while it has something to show.
|
|
7
|
+
// Public custom publishers omit the predicate: false and null are valid values.
|
|
8
|
+
export function createPresencePublisher<T extends JsonValue>(
|
|
9
|
+
engine: Pick<CollabEngineApi, 'setPresence' | 'deletePresence'>,
|
|
10
|
+
registration: Omit<PresenceRegistration, 'value'>,
|
|
11
|
+
isPresent: (value: T) => boolean = () => true
|
|
12
|
+
) {
|
|
13
|
+
let registered = false
|
|
14
|
+
const clear = () => {
|
|
15
|
+
if (!registered) return
|
|
16
|
+
registered = false
|
|
17
|
+
engine.deletePresence(registration.registrationId)
|
|
18
|
+
}
|
|
19
|
+
return {
|
|
20
|
+
publish(value: T, active: boolean) {
|
|
21
|
+
if (!active || !isPresent(value)) {
|
|
22
|
+
clear()
|
|
23
|
+
return
|
|
24
|
+
}
|
|
25
|
+
registered = true
|
|
26
|
+
engine.setPresence({ ...registration, value })
|
|
27
|
+
},
|
|
28
|
+
clear
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Encode whole IDs before joining them, so a slash inside an ID cannot become
|
|
2
|
+
// a group boundary. React-generated IDs never form part of shared targets.
|
|
3
|
+
export function presenceTarget(...ids: string[]): string {
|
|
4
|
+
if (!ids.length || ids.some(id => typeof id !== 'string' || !id.trim())) {
|
|
5
|
+
throw new Error('PresenceGroup, PresenceFrame, and PresenceAvatars require a nonempty id.')
|
|
6
|
+
}
|
|
7
|
+
return ids.map(id => encodeURIComponent(id)).join('/')
|
|
8
|
+
}
|