moi-computer 0.11.1-next.4 → 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.
Files changed (129) hide show
  1. package/client/api/app-config.ts +7 -4
  2. package/client/app/AppRouter.tsx +2 -2
  3. package/client/app/routes/WorkspaceRoute.tsx +27 -19
  4. package/client/features/applets/{AppletMount.tsx → AppletContainer.tsx} +7 -5
  5. package/client/features/applets/WidgetShell.tsx +3 -3
  6. package/client/features/applets/applet-cache.ts +3 -5
  7. package/client/features/applets/applet-runtime.ts +27 -12
  8. package/client/features/applets/applet-thumbnail.ts +2 -1
  9. package/client/features/chat/applet-chat-intents.ts +14 -6
  10. package/client/features/chat/messages/MarkdownContent.tsx +5 -2
  11. package/client/features/chat/sessions/browser-tab-state.ts +18 -0
  12. package/client/features/chat/sessions/useSelectedSession.ts +55 -21
  13. package/client/features/chat/useChat.ts +4 -0
  14. package/client/features/collab/applet-api.ts +34 -0
  15. package/client/features/collab/client.ts +239 -0
  16. package/client/features/collab/components/cursors.tsx +199 -0
  17. package/client/features/collab/components/presence-avatars.tsx +61 -0
  18. package/client/features/collab/components/presence-frame.tsx +126 -0
  19. package/client/features/collab/components/presence-group.tsx +23 -0
  20. package/client/features/collab/components/presence-helpers.ts +50 -0
  21. package/client/features/collab/components/user-avatar-group.tsx +22 -0
  22. package/client/features/collab/components/user-avatar.tsx +40 -0
  23. package/client/features/collab/components/user.tsx +50 -0
  24. package/client/features/collab/hooks.tsx +164 -0
  25. package/client/features/collab/host-state.ts +254 -0
  26. package/client/features/collab/index.ts +5 -0
  27. package/client/features/collab/local-user.ts +46 -0
  28. package/client/features/collab/presence-publisher.ts +30 -0
  29. package/client/features/collab/presence-target.ts +8 -0
  30. package/client/features/collab/provider.tsx +79 -0
  31. package/client/features/collab/proxy-user.ts +35 -0
  32. package/client/features/collab/store.ts +156 -0
  33. package/client/features/collab/testing/component-fixtures.tsx +54 -0
  34. package/client/features/collab/testing/fake-engine.ts +129 -0
  35. package/client/features/collab/users.ts +106 -0
  36. package/client/features/collab/workspace-users-menu.tsx +194 -0
  37. package/client/features/connectors/mcp-icons.ts +0 -2
  38. package/client/features/dev/DevIndexPage.tsx +5 -0
  39. package/client/features/dev/DevRoutes.tsx +16 -4
  40. package/client/features/dev/collab/collab-page.tsx +24 -0
  41. package/client/features/dev/collab/collab-playground.tsx +614 -0
  42. package/client/features/dev/collab/local-user-settings.tsx +166 -0
  43. package/client/features/dev/collab/playground-room.ts +33 -0
  44. package/client/features/dev/{UiComponentsPage.tsx → ui-components/ui-components-page.tsx} +1 -1
  45. package/client/features/overview/WidgetCanvas.tsx +3 -1
  46. package/client/features/views/ViewManager.tsx +12 -7
  47. package/client/features/views/api.ts +2 -2
  48. package/client/features/views/useViewBuilderActions.ts +3 -0
  49. package/client/features/workspace/WorkspaceContext.tsx +1 -1
  50. package/client/features/workspace/WorkspaceLayoutContext.tsx +8 -2
  51. package/client/features/workspace/WorkspaceScreen.tsx +19 -11
  52. package/client/features/workspace/WorkspaceTabs.tsx +3 -3
  53. package/client/features/workspace/api.ts +2 -1
  54. package/client/features/workspace/browser-tab-state.ts +44 -0
  55. package/client/features/workspace/layout-save.ts +13 -0
  56. package/client/features/workspace/moi-context.ts +2 -1
  57. package/client/features/workspace/useWorkspaceNavigation.ts +20 -8
  58. package/client/index.css +45 -0
  59. package/client/index.tsx +9 -4
  60. package/client/main.tsx +1 -11
  61. package/client/theme.css +4 -1
  62. package/dist/chunk-2jncyq65.js +1 -0
  63. package/dist/{chunk-brr0zbeh.js → chunk-3a48fyf7.js} +2 -2
  64. package/dist/{chunk-tzz101ea.js → chunk-97eg9mjn.js} +1 -1
  65. package/dist/chunk-9zpvdws4.js +68 -0
  66. package/dist/{chunk-zs4mte79.js → chunk-efdyz6xp.js} +1 -1
  67. package/dist/chunk-h2kj1ysj.js +1 -0
  68. package/dist/chunk-hvj7tp3y.js +1 -0
  69. package/dist/chunk-jf6czgrz.js +2 -0
  70. package/dist/chunk-nez8sdta.js +1 -0
  71. package/dist/chunk-nzwgm8vc.css +1 -0
  72. package/dist/chunk-ryg9z3kn.js +10 -0
  73. package/dist/chunk-tpn177bt.js +2 -0
  74. package/dist/chunk-vfpsc75k.js +2 -0
  75. package/dist/{chunk-m1fvqssh.js → chunk-z3byfve5.js} +2 -2
  76. package/dist/index.html +1 -1
  77. package/lib/collab/colors.ts +30 -0
  78. package/lib/collab/protocol.ts +84 -0
  79. package/lib/collab/types.ts +52 -0
  80. package/lib/experimental.ts +14 -0
  81. package/lib/moi-context.ts +11 -3
  82. package/lib/navigation.ts +25 -5
  83. package/lib/types.ts +20 -33
  84. package/package.json +2 -2
  85. package/server/AGENTS.md +1 -1
  86. package/server/api.ts +28 -5
  87. package/server/app-config.ts +127 -34
  88. package/server/applet-typecheck.ts +8 -3
  89. package/server/applets/applet-css.ts +1 -1
  90. package/server/applets/build-applet.ts +9 -3
  91. package/server/applets/declarations/base.d.ts +75 -0
  92. package/server/applets/declarations/collab.d.ts +88 -0
  93. package/server/applets/declarations.ts +46 -0
  94. package/server/applets/index.ts +8 -8
  95. package/server/applets/runtime/collab.ts +94 -0
  96. package/server/applets/runtime/moi.ts +12 -19
  97. package/server/applets/runtime/rpc.ts +2 -4
  98. package/server/chat-selection.ts +22 -0
  99. package/server/cli.ts +60 -15
  100. package/server/collab/cloudflare-access.ts +78 -0
  101. package/server/collab/config.ts +18 -0
  102. package/server/collab/manager.ts +407 -0
  103. package/server/collab/service.ts +136 -0
  104. package/server/collab/skill/index.ts +53 -0
  105. package/server/collab/worker-messages.ts +10 -0
  106. package/server/collab/worker.ts +52 -0
  107. package/server/layout.ts +10 -3
  108. package/server/moi-scaffold.ts +3 -64
  109. package/server/preview.ts +1 -1
  110. package/server/skill-update.ts +7 -9
  111. package/server/skills-template.ts +14 -2
  112. package/server/web.ts +65 -17
  113. package/ui-components/avatar.tsx +24 -11
  114. package/ui-components/button.tsx +9 -9
  115. package/ui-components/docs/avatar.md +11 -30
  116. package/workspace/.claude/skills/moi-workspace/SKILL.md +14 -11
  117. package/workspace/.claude/skills/moi-workspace/references/COLLAB.md +262 -0
  118. package/workspace/.claude/skills/moi-workspace/references/INTENTS.md +10 -7
  119. package/client/assets/mcp/agentation.png +0 -0
  120. package/dist/agentation-4s0nn45p.png +0 -0
  121. package/dist/chunk-2gs8jjx4.css +0 -1
  122. package/dist/chunk-7vvg5fyz.js +0 -68
  123. package/dist/chunk-94m3q9ce.js +0 -1
  124. package/dist/chunk-by2wqgak.js +0 -1
  125. package/dist/chunk-p34hvqt3.js +0 -1
  126. package/dist/chunk-p83f0jnj.js +0 -2
  127. package/dist/chunk-xg01f6pn.js +0 -10
  128. /package/client/features/dev/{UiComponentPreviews.tsx → ui-components/ui-component-previews.tsx} +0 -0
  129. /package/server/applets/{runtime/base.ts → api-base.ts} +0 -0
@@ -1,6 +1,7 @@
1
1
  import { useSyncExternalStore } from 'react'
2
2
 
3
3
  import type { ClientAppConfig } from '@/lib/types'
4
+ import { EXPERIMENTAL_DEFAULTS } from '@/lib/experimental'
4
5
 
5
6
  import { onWorkspaceEventsReconnect } from '@/client/runtime/useWorkspaceEvents'
6
7
 
@@ -14,7 +15,7 @@ import { requestJson } from './http'
14
15
 
15
16
  const DEFAULTS: ClientAppConfig = {
16
17
  cloudDemo: false,
17
- experiments: [],
18
+ experimental: { ...EXPERIMENTAL_DEFAULTS },
18
19
  demoInstallUrl: 'https://moi.computer'
19
20
  }
20
21
 
@@ -30,20 +31,22 @@ function subscribe(listener: () => void): () => void {
30
31
 
31
32
  // Failures keep the last known value (defaults on the very first fetch):
32
33
  // non-demo is the safe presentation, and the server still enforces its gates.
33
- async function fetchAppConfig(): Promise<void> {
34
+ async function fetchAppConfig(): Promise<ClientAppConfig | undefined> {
34
35
  try {
35
36
  current = await requestJson<ClientAppConfig>('/api/config')
36
37
  for (const listener of listeners) listener()
38
+ return current
37
39
  } catch {}
38
40
  }
39
41
 
40
42
  // Called once from init() before the app mounts; never rejects, so a config
41
43
  // hiccup cannot block the app from starting.
42
- export async function loadAppConfig(): Promise<void> {
43
- await fetchAppConfig()
44
+ export async function loadAppConfig(): Promise<ClientAppConfig | undefined> {
45
+ const config = await fetchAppConfig()
44
46
  onWorkspaceEventsReconnect(() => {
45
47
  void fetchAppConfig()
46
48
  })
49
+ return config
47
50
  }
48
51
 
49
52
  export function useAppConfig(): ClientAppConfig {
@@ -10,8 +10,8 @@ import { WorkspaceRoute } from './routes/WorkspaceRoute'
10
10
  // Dev-only playground routes: colocated in features/dev and loaded as a
11
11
  // separate lazy chunk. The NODE_ENV gate is statically false in the prod
12
12
  // build (scripts/build-client.ts defines it), so the bundler drops the
13
- // dynamic import and none of features/dev is emitted into dist at all —
14
- // same mechanism as DevAgentation in main.tsx. In prod /dev redirects home.
13
+ // dynamic import and none of features/dev is emitted into dist at all.
14
+ // In prod /dev redirects home.
15
15
  const DevRoutes =
16
16
  process.env.NODE_ENV === 'development'
17
17
  ? lazy(() => import('@/client/features/dev/DevRoutes'))
@@ -1,6 +1,8 @@
1
+ import { CollabProvider, useCollabEnabled } from '@/client/features/collab'
1
2
  import { useQueryClient } from '@tanstack/react-query'
2
3
 
3
4
  import { workspaceKeys } from '@/client/api/workspace-keys'
5
+ import { useAppConfig } from '@/client/api/app-config'
4
6
  import { LedLogo } from '@/client/components/shared/LedLogo'
5
7
  import { SidebarLayout } from '@/client/app/shell/SidebarLayout'
6
8
  import { useSelectedSession } from '@/client/features/chat/sessions/useSelectedSession'
@@ -19,19 +21,24 @@ type WorkspaceRouteProps = {
19
21
  id: string
20
22
  }
21
23
 
22
- // The URL's tab segment is not threaded down — useWorkspaceNavigation reads it
23
- // off the matched route with wouter's `useParams`.
24
+ // Navigation reads the raw browser address so encoded paths and query params
25
+ // are decoded exactly once; the route only owns the workspace ID.
24
26
  export function WorkspaceRoute({ id }: WorkspaceRouteProps) {
27
+ const { experimental } = useAppConfig()
28
+
25
29
  return (
26
30
  <Workspace id={id}>
27
31
  <WorkspaceLayoutProvider id={id}>
28
- <WorkspaceLoader id={id} />
32
+ <CollabProvider workspaceId={id} enabled={experimental.collab}>
33
+ <WorkspaceContent id={id} />
34
+ </CollabProvider>
29
35
  </WorkspaceLayoutProvider>
30
36
  </Workspace>
31
37
  )
32
38
  }
33
39
 
34
- function WorkspaceLoader({ id }: WorkspaceRouteProps) {
40
+ function WorkspaceContent({ id }: WorkspaceRouteProps) {
41
+ const collabEnabled = useCollabEnabled()
35
42
  const queryClient = useQueryClient()
36
43
  const [selectedSessionId] = useSelectedSession()
37
44
  const { isLoading: layoutLoading } = useWorkspaceLayoutCtx()
@@ -62,20 +69,21 @@ function WorkspaceLoader({ id }: WorkspaceRouteProps) {
62
69
  builders.isLoading
63
70
 
64
71
  return (
65
- <>
66
- <SidebarLayout>
67
- {fresh ? (
68
- <div className="flex h-full items-center justify-center">
69
- <LedLogo sprite="moi" effect="chaos" />
70
- </div>
71
- ) : (
72
- <WorkspaceScreen
73
- widgets={widgets.data}
74
- views={views.data ?? []}
75
- builders={builders.data ?? []}
76
- />
77
- )}
78
- </SidebarLayout>
79
- </>
72
+ <SidebarLayout>
73
+ {fresh ? (
74
+ <div className="flex h-full items-center justify-center">
75
+ <LedLogo sprite="moi" effect="chaos" />
76
+ </div>
77
+ ) : (
78
+ // Browser tab state is read when the screen mounts. Reset the screen
79
+ // when it switches between shared workspace tabs and browser tab state.
80
+ <WorkspaceScreen
81
+ key={collabEnabled ? 'browser-tab' : 'shared'}
82
+ widgets={widgets.data}
83
+ views={views.data ?? []}
84
+ builders={builders.data ?? []}
85
+ />
86
+ )}
87
+ </SidebarLayout>
80
88
  )
81
89
  }
@@ -1,11 +1,12 @@
1
1
  import { type ReactNode } from 'react'
2
2
 
3
+ import { AppletPresenceProvider } from '@/client/features/collab'
3
4
  import { useWorkspaceId } from '@/client/features/workspace/WorkspaceContext'
4
5
 
5
- import { type AppletSegment, appletScope, appletStyleKey } from './applet-cache'
6
+ import { type AppletSegment, appletId, appletStyleKey } from './applet-cache'
6
7
  import { useAppletStyle } from './applet-styles'
7
8
 
8
- type AppletMountProps = {
9
+ type AppletContainerProps = {
9
10
  segment: AppletSegment
10
11
  name: string
11
12
  version: number
@@ -19,13 +20,14 @@ type AppletMountProps = {
19
20
  // page. This is the widget path. Views don't use it: ViewManager parks a view's
20
21
  // DOM offscreen instead of unmounting it, so it holds the styles itself, above
21
22
  // the boundary that hides the view.
22
- export function AppletMount({ segment, name, version, children }: AppletMountProps) {
23
+ export function AppletContainer({ segment, name, version, children }: AppletContainerProps) {
23
24
  const workspaceId = useWorkspaceId()
25
+ const id = appletId(segment, name)
24
26
  useAppletStyle(appletStyleKey(segment, workspaceId, name), version)
25
27
 
26
28
  return (
27
- <div data-applet={appletScope(segment, name)} className="size-full">
28
- {children}
29
+ <div data-applet={id} className="size-full">
30
+ <AppletPresenceProvider appletId={id}>{children}</AppletPresenceProvider>
29
31
  </div>
30
32
  )
31
33
  }
@@ -1,6 +1,6 @@
1
1
  import { AnimatePresence, motion } from 'motion/react'
2
2
 
3
- import { AppletMount } from '@/client/features/applets/AppletMount'
3
+ import { AppletContainer } from '@/client/features/applets/AppletContainer'
4
4
  import { useWidget } from '@/client/features/applets/useApplet'
5
5
  import { useWorkspaceId } from '@/client/features/workspace/WorkspaceContext'
6
6
 
@@ -31,9 +31,9 @@ export function WidgetShell({ name }: WidgetShellProps) {
31
31
  workspaceId={workspaceId}
32
32
  resetKey={widget.version}
33
33
  >
34
- <AppletMount segment="widgets" name={name} version={widget.version}>
34
+ <AppletContainer segment="widgets" name={name} version={widget.version}>
35
35
  <widget.Component />
36
- </AppletMount>
36
+ </AppletContainer>
37
37
  </WidgetErrorBoundary>
38
38
  </motion.div>
39
39
  )}
@@ -54,11 +54,9 @@ export function appletStyleKey(segment: AppletSegment, workspaceId: string, name
54
54
  return `/api/workspaces/${workspaceId}/${segment}/${name}`
55
55
  }
56
56
 
57
- // The `data-applet` value the bundle's scoped CSS selectors key off (see
58
- // server/applets/applet-css.ts). It goes on the container wrapping a mounted
59
- // applet — AppletMount for widgets, the view slot for views.
60
- export function appletScope(segment: AppletSegment, name: string): string {
61
- return `${segment === 'widgets' ? 'widget' : 'view'}:${name}`
57
+ // Stable applet identity used by scoped CSS, presence, and thumbnail capture.
58
+ export function appletId(segment: AppletSegment, name: string): string {
59
+ return `${segment}/${name}`
62
60
  }
63
61
 
64
62
  export function getCachedApplet(key: string): Promise<unknown> | undefined {
@@ -14,12 +14,18 @@
14
14
  // — no central handlers object assembled by the screen. Applet → host only;
15
15
  // if a host → applet direction is ever added (`moi.on(...)`), `dispose` must
16
16
  // also unbind those listeners or a disposed module leaks.
17
+ import { appletCollabApi, type AppletCollabApi } from '@/client/features/collab/applet-api'
17
18
  import {
18
19
  MAX_ATTACHMENT_LABEL_CHARS,
19
20
  MAX_TEXT_ATTACHMENT_CHARS,
20
21
  snapshotTextAttachment
21
22
  } from '@/lib/moi-attachments'
22
- import type { AppletBridge, AppletKind, AttachmentInput, AttachmentOrigin } from '@/lib/types'
23
+ import type {
24
+ AppletBridge as SharedAppletBridge,
25
+ AppletKind,
26
+ AttachmentInput,
27
+ AttachmentOrigin
28
+ } from '@/lib/types'
23
29
  import { isWorkspaceAttachmentPath, MAX_UPLOAD_BYTES } from '@/lib/message-attachments'
24
30
  import { useEffect } from 'react'
25
31
 
@@ -30,9 +36,11 @@ import { toast } from '@/client/components/ui/toast'
30
36
  import { createRateLimiter, type RateLimiter } from '@/client/lib/rate-limit'
31
37
  import { useLatestRef } from '@/client/lib/use-latest-ref'
32
38
  import { isParamsRecord } from '@/lib/workspace-tabs'
33
- import { resolveWorkspaceHref } from '@/lib/navigation'
39
+ import { resolveUrl, workspacePath } from '@/lib/navigation'
34
40
 
35
- export type { AppletBridge } from '@/lib/types'
41
+ type HostAppletBridge = SharedAppletBridge & {
42
+ readonly collab: AppletCollabApi | undefined
43
+ }
36
44
 
37
45
  // Which applet a bridge belongs to, supplied by the host at attach time.
38
46
  export type AppletIdentity = { kind: AppletKind; name: string }
@@ -118,7 +126,14 @@ function createRuntime(workspaceId: string) {
118
126
  connect(identity: AppletIdentity, base = '') {
119
127
  let alive = true
120
128
  const source = appletSource(identity)
121
- const bridge: AppletBridge = {
129
+ const urlContext = {
130
+ apiBase: `/api/workspaces/${encodeURIComponent(workspaceId)}`,
131
+ workspacePath: workspacePath(workspaceId, base)
132
+ }
133
+ const bridge: HostAppletBridge = {
134
+ get collab() {
135
+ return alive ? appletCollabApi : undefined
136
+ },
122
137
  addChatAttachment(input) {
123
138
  if (!alive) return
124
139
  try {
@@ -130,20 +145,20 @@ function createRuntime(workspaceId: string) {
130
145
  drop(identity, `addChatAttachment() was dropped: ${message}`)
131
146
  }
132
147
  },
133
- navigate(href) {
148
+ navigate(url) {
134
149
  if (!alive) return
135
150
  try {
136
- if (typeof href !== 'string') throw new Error('Navigation needs a URL')
137
- resolveWorkspaceHref(workspaceId, href, base)
138
- emitter.emit('navigate', href)
151
+ if (typeof url !== 'string') throw new Error('Navigation needs a URL')
152
+ resolveUrl(url, urlContext)
153
+ emitter.emit('navigate', url)
139
154
  } catch (error) {
140
155
  drop(identity, `navigate() was dropped: ${errorMessage(error)}`)
141
156
  }
142
157
  },
143
- resolveHref(href) {
158
+ resolveUrl(url) {
144
159
  if (!alive) return ''
145
- if (typeof href !== 'string') throw new Error('A URL is required')
146
- return resolveWorkspaceHref(workspaceId, href, base)
160
+ if (typeof url !== 'string') throw new Error('A URL is required')
161
+ return resolveUrl(url, urlContext)
147
162
  },
148
163
  sendChatMessage(input, legacyContext) {
149
164
  if (!alive) return
@@ -268,7 +283,7 @@ export function useAppletEvent<K extends keyof AppletEvents>(
268
283
  // The shape of the host wiring every bundle entry re-exports (see the entry
269
284
  // plugin in server/applets/build-applet.ts).
270
285
  type BridgeModule = {
271
- __attachBridge?: (bridge: AppletBridge) => void
286
+ __attachBridge?: (bridge: Partial<SharedAppletBridge>) => void
272
287
  }
273
288
 
274
289
  // Live connections keyed by applet cache key (`${segment}/${workspaceId}/${name}`)
@@ -4,6 +4,7 @@ import { useAppletThumbnailRecords, useSaveAppletThumbnails } from '@/client/fea
4
4
  import { useWorkspaceId } from '@/client/features/workspace/WorkspaceContext'
5
5
  import { useLatestRef } from '@/client/lib/use-latest-ref'
6
6
  import type { AppletKind, AppletThumbnail, AppletThumbnailUpdate } from '@/lib/types'
7
+ import { appletId } from './applet-cache'
7
8
 
8
9
  export const THUMBNAIL_MAX_EDGE = 1_000
9
10
  export const THUMBNAIL_PIXEL_RATIO = 3
@@ -269,7 +270,7 @@ export function useAppletThumbnails({ kind, enabled, targets }: UseAppletThumbna
269
270
  targetsRef.current.map(target => ({
270
271
  ...target,
271
272
  element: document.querySelector<HTMLElement>(
272
- `[data-applet-thumbnail="${CSS.escape(`${kind}:${target.id}`)}"]`
273
+ `[data-applet-thumbnail="${CSS.escape(appletId(kind === 'view' ? 'views' : 'widgets', target.id))}"]`
273
274
  )
274
275
  })),
275
276
  () =>
@@ -12,10 +12,11 @@ import {
12
12
  import { prepareChatAttachments, type ChatSendOptions, type PreparedAttachments } from './chat-send'
13
13
  import { useLayoutEffect } from 'react'
14
14
  import { useQueryClient, type QueryClient } from '@tanstack/react-query'
15
- import { appUiKeys } from '@/client/api/app-ui-keys'
16
15
  import { toast } from '@/client/components/ui/toast'
16
+ import { selectedSessionKey } from '@/client/features/chat/sessions/useSelectedSession'
17
+ import { useCollabEnabled } from '@/client/features/collab'
17
18
  import { useLatestRef } from '@/client/lib/use-latest-ref'
18
- import type { SelectedSessionState } from '@/lib/types'
19
+ import type { SelectedSessionScope, SelectedSessionState } from '@/lib/types'
19
20
  import { useWorkspaceId } from '@/client/features/workspace/WorkspaceContext'
20
21
  import type { AgentAvailability } from '@/client/lib/agent-availability'
21
22
 
@@ -51,12 +52,13 @@ export function appletSendBlockedReason(availability: AgentAvailability): string
51
52
  export function createAppletMessageHandler(
52
53
  workspaceId: string,
53
54
  queryClient: QueryClient,
54
- getOptions: () => UseAppletChatMessageOptions
55
+ getOptions: () => UseAppletChatMessageOptions,
56
+ scope: SelectedSessionScope = 'shared'
55
57
  ) {
56
58
  const pending = new Set<() => void>()
57
59
  let disposed = false
58
60
  const selectedSession = () =>
59
- queryClient.getQueryData<SelectedSessionState>(appUiKeys.selectedSession(workspaceId))
61
+ queryClient.getQueryData<SelectedSessionState>(selectedSessionKey(workspaceId, scope))
60
62
  ?.sessionId ?? null
61
63
 
62
64
  async function handle(event: AppletChatMessage): Promise<void> {
@@ -148,9 +150,15 @@ export function createAppletMessageHandler(
148
150
  export function useAppletChatMessage(options: UseAppletChatMessageOptions): void {
149
151
  const workspaceId = useWorkspaceId()
150
152
  const queryClient = useQueryClient()
153
+ const collabEnabled = useCollabEnabled()
151
154
  const latest = useLatestRef(options)
152
155
  useLayoutEffect(() => {
153
- const handler = createAppletMessageHandler(workspaceId, queryClient, () => latest.current)
156
+ const handler = createAppletMessageHandler(
157
+ workspaceId,
158
+ queryClient,
159
+ () => latest.current,
160
+ collabEnabled ? 'browser-tab' : 'shared'
161
+ )
154
162
  const unsubscribe = appletRuntime(workspaceId).on('sendChatMessage', event => {
155
163
  void handler.handle(event)
156
164
  })
@@ -158,7 +166,7 @@ export function useAppletChatMessage(options: UseAppletChatMessageOptions): void
158
166
  unsubscribe()
159
167
  handler.dispose()
160
168
  }
161
- }, [workspaceId, queryClient, latest])
169
+ }, [workspaceId, queryClient, latest, collabEnabled])
162
170
  }
163
171
 
164
172
  export function useAppletChatAttachment(sessionId: string | null, revealChat: () => void): void {
@@ -6,7 +6,7 @@ import rehypeHighlight from 'rehype-highlight'
6
6
  import remarkGfm from 'remark-gfm'
7
7
 
8
8
  import { useWorkspaceId } from '@/client/features/workspace/WorkspaceContext'
9
- import { resolveWorkspaceHref } from '@/lib/navigation'
9
+ import { resolveUrl, workspacePath } from '@/lib/navigation'
10
10
  import { cn } from '@/client/lib/cn'
11
11
 
12
12
  const remarkPlugins = [remarkGfm]
@@ -63,7 +63,10 @@ export function MarkdownContent({ size = 'sm', content }: MarkdownContentProps)
63
63
  urlTransform={(url, key, node) => {
64
64
  if (node.tagName === 'a' && key === 'href' && url.startsWith('moi:')) {
65
65
  try {
66
- return resolveWorkspaceHref(workspaceId, url, base)
66
+ return resolveUrl(url, {
67
+ apiBase: `/api/workspaces/${encodeURIComponent(workspaceId)}`,
68
+ workspacePath: workspacePath(workspaceId, base)
69
+ })
67
70
  } catch {
68
71
  return ''
69
72
  }
@@ -0,0 +1,18 @@
1
+ const keyFor = (workspaceId: string) => `moi:collab:${workspaceId}:session`
2
+
3
+ export function readSelectedSession(workspaceId: string): string | null {
4
+ try {
5
+ return sessionStorage.getItem(keyFor(workspaceId))
6
+ } catch {
7
+ return null
8
+ }
9
+ }
10
+
11
+ export function writeSelectedSession(workspaceId: string, sessionId: string | null): void {
12
+ try {
13
+ if (sessionId === null) sessionStorage.removeItem(keyFor(workspaceId))
14
+ else sessionStorage.setItem(keyFor(workspaceId), sessionId)
15
+ } catch {
16
+ /* A private browser can still keep the active query in memory. */
17
+ }
18
+ }
@@ -1,3 +1,8 @@
1
+ import { useCollabEnabled } from '@/client/features/collab'
2
+ import {
3
+ readSelectedSession,
4
+ writeSelectedSession
5
+ } from '@/client/features/chat/sessions/browser-tab-state'
1
6
  import { useCallback, useMemo } from 'react'
2
7
 
3
8
  import { useIsMutating, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
@@ -8,7 +13,7 @@ import { jsonRequest, requestJson } from '@/client/api/http'
8
13
  import { toast } from '@/client/components/ui/toast'
9
14
  import { useWorkspaceId } from '@/client/features/workspace/WorkspaceContext'
10
15
  import { useWorkspaceEvent } from '@/client/runtime/useWorkspaceEvents'
11
- import type { SelectedSessionState } from '@/lib/types'
16
+ import type { SelectedSessionScope, SelectedSessionState } from '@/lib/types'
12
17
 
13
18
  type SaveSelectedSessionInput = {
14
19
  sessionId: string | null
@@ -24,16 +29,22 @@ type SelectedSessionResult = readonly [
24
29
 
25
30
  export type SelectedSessionSaveResult = 'applied' | 'conflict' | 'ignored'
26
31
 
27
- function selectedSessionMutationKey(workspaceId: string) {
28
- return [...appUiKeys.selectedSession(workspaceId), 'save'] as const
32
+ export function selectedSessionKey(workspaceId: string, scope: SelectedSessionScope = 'shared') {
33
+ const key = appUiKeys.selectedSession(workspaceId)
34
+ return scope === 'browser-tab' ? ([...key, 'browser-tab'] as const) : key
35
+ }
36
+
37
+ function selectedSessionMutationKey(workspaceId: string, scope: SelectedSessionScope) {
38
+ return [...selectedSessionKey(workspaceId, scope), 'save'] as const
29
39
  }
30
40
 
31
41
  export function optimisticallySetSelectedSession(
32
42
  queryClient: QueryClient,
33
43
  workspaceId: string,
34
- sessionId: string | null
44
+ sessionId: string | null,
45
+ scope: SelectedSessionScope = 'shared'
35
46
  ): SaveSelectedSessionInput | null {
36
- const queryKey = appUiKeys.selectedSession(workspaceId)
47
+ const queryKey = selectedSessionKey(workspaceId, scope)
37
48
  const current = queryClient.getQueryData<SelectedSessionState>(queryKey)
38
49
  const previousSessionId = current?.sessionId ?? null
39
50
  if (current && previousSessionId === sessionId) return null
@@ -46,9 +57,10 @@ export function settleSelectedSessionSave(
46
57
  queryClient: QueryClient,
47
58
  workspaceId: string,
48
59
  saved: SelectedSessionState,
49
- input: SaveSelectedSessionInput
60
+ input: SaveSelectedSessionInput,
61
+ scope: SelectedSessionScope = 'shared'
50
62
  ): SelectedSessionSaveResult {
51
- const queryKey = appUiKeys.selectedSession(workspaceId)
63
+ const queryKey = selectedSessionKey(workspaceId, scope)
52
64
  const current = queryClient.getQueryData<SelectedSessionState>(queryKey)
53
65
 
54
66
  if (saved.sessionId !== input.sessionId && current?.sessionId !== saved.sessionId) {
@@ -80,24 +92,36 @@ export function renameSelectedSessionInCache(
80
92
  from: string,
81
93
  to: string
82
94
  ): void {
83
- queryClient.setQueryData<SelectedSessionState>(appUiKeys.selectedSession(workspaceId), current =>
84
- current?.sessionId === from ? { sessionId: to } : current
85
- )
95
+ for (const scope of ['shared', 'browser-tab'] as const) {
96
+ queryClient.setQueryData<SelectedSessionState>(
97
+ selectedSessionKey(workspaceId, scope),
98
+ current => (current?.sessionId === from ? { sessionId: to } : current)
99
+ )
100
+ }
101
+ if (readSelectedSession(workspaceId) === from) writeSelectedSession(workspaceId, to)
86
102
  }
87
103
 
88
104
  export function useSelectedSession(): SelectedSessionResult {
89
105
  const workspaceId = useWorkspaceId()
106
+ const collabEnabled = useCollabEnabled()
107
+ const scope: SelectedSessionScope = collabEnabled ? 'browser-tab' : 'shared'
90
108
  const queryClient = useQueryClient()
91
- const queryKey = useMemo(() => appUiKeys.selectedSession(workspaceId), [workspaceId])
92
- const mutationKey = useMemo(() => selectedSessionMutationKey(workspaceId), [workspaceId])
109
+ const queryKey = useMemo(() => selectedSessionKey(workspaceId, scope), [workspaceId, scope])
110
+ const mutationKey = useMemo(
111
+ () => selectedSessionMutationKey(workspaceId, scope),
112
+ [workspaceId, scope]
113
+ )
93
114
  const pendingSaves = useIsMutating({ mutationKey, exact: true })
94
115
 
95
- // WorkspaceLoader remains an observer for the active workspace. Nested hook
116
+ // WorkspaceContent remains an observer for the active workspace. Nested hook
96
117
  // users reuse its result without refetching; once the route unmounts, dropping
97
118
  // the cache makes the next visit load the server-owned selection again.
98
119
  const query = useQuery<SelectedSessionState>({
99
120
  queryKey,
100
- queryFn: () => requestJson(`/api/workspaces/${workspaceId}/selected-session`),
121
+ queryFn: () =>
122
+ scope === 'browser-tab'
123
+ ? Promise.resolve({ sessionId: readSelectedSession(workspaceId) })
124
+ : requestJson(`/api/workspaces/${workspaceId}/selected-session`),
101
125
  staleTime: Infinity,
102
126
  gcTime: 0,
103
127
  refetchOnMount: false,
@@ -111,14 +135,19 @@ export function useSelectedSession(): SelectedSessionResult {
111
135
  >({
112
136
  mutationKey,
113
137
  scope: { id: `selected-session:${workspaceId}` },
114
- mutationFn: input =>
115
- requestJson(
138
+ mutationFn: input => {
139
+ if (scope === 'browser-tab') {
140
+ writeSelectedSession(workspaceId, input.sessionId)
141
+ return Promise.resolve({ sessionId: input.sessionId })
142
+ }
143
+ return requestJson<SelectedSessionState>(
116
144
  `/api/workspaces/${workspaceId}/selected-session`,
117
145
  jsonRequest('PUT', input),
118
146
  'Couldn’t save selected chat'
119
- ),
147
+ )
148
+ },
120
149
  onSuccess: (saved, input) => {
121
- const result = settleSelectedSessionSave(queryClient, workspaceId, saved, input)
150
+ const result = settleSelectedSessionSave(queryClient, workspaceId, saved, input, scope)
122
151
  if (result !== 'conflict') return
123
152
 
124
153
  toast.add({ title: 'Couldn’t save selected chat', type: 'error' })
@@ -135,14 +164,19 @@ export function useSelectedSession(): SelectedSessionResult {
135
164
 
136
165
  const setSelectedSessionId = useCallback<SetSelectedSession>(
137
166
  sessionId => {
138
- const input = optimisticallySetSelectedSession(queryClient, workspaceId, sessionId)
167
+ const input = optimisticallySetSelectedSession(queryClient, workspaceId, sessionId, scope)
139
168
  if (input) saveSelectedSession(input)
140
169
  },
141
- [queryClient, saveSelectedSession, workspaceId]
170
+ [queryClient, saveSelectedSession, workspaceId, scope]
142
171
  )
143
172
 
144
173
  useWorkspaceEvent(event => {
145
- if (event.type !== 'selected-session:updated' || event.workspaceId !== workspaceId) return
174
+ if (
175
+ scope === 'browser-tab' ||
176
+ event.type !== 'selected-session:updated' ||
177
+ event.workspaceId !== workspaceId
178
+ )
179
+ return
146
180
  applySelectedSessionEvent(queryClient, workspaceId, event.sessionId, pendingSaves > 0)
147
181
  })
148
182
 
@@ -10,6 +10,7 @@ import {
10
10
  } from '@/client/features/chat/sessions/api'
11
11
  import { useWorkspaceAgent } from '@/client/features/workspace/api'
12
12
  import { useSelectedSession } from '@/client/features/chat/sessions/useSelectedSession'
13
+ import { useCollabEnabled } from '@/client/features/collab'
13
14
  import {
14
15
  type WorkspaceTabAddress,
15
16
  useMoiUserMessageContext
@@ -53,6 +54,7 @@ export function useChat(address: WorkspaceTabAddress) {
53
54
  const qc = useQueryClient()
54
55
  const { layout } = useWorkspaceLayoutCtx()
55
56
  const [selectedSession, selectSession] = useSelectedSession()
57
+ const collabEnabled = useCollabEnabled()
56
58
  const modelsData = useWorkspaceAgent(workspaceId).data
57
59
  const sessions = useWorkspaceSessions(workspaceId).data
58
60
  const selectedSessionMissing =
@@ -173,6 +175,7 @@ export function useChat(address: WorkspaceTabAddress) {
173
175
  content: text,
174
176
  sessionId: sid,
175
177
  isNew,
178
+ selectedSessionScope: collabEnabled ? 'browser-tab' : 'shared',
176
179
  optimisticId,
177
180
  model,
178
181
  effort,
@@ -205,6 +208,7 @@ export function useChat(address: WorkspaceTabAddress) {
205
208
  sessionConfig?.effort,
206
209
  sessionConfig?.fastMode,
207
210
  selectSession,
211
+ collabEnabled,
208
212
  modelsData
209
213
  ]
210
214
  )
@@ -0,0 +1,34 @@
1
+ import type * as CollabApi from 'moi/collab'
2
+ import { UserAvatarGroup } from './components/user-avatar-group'
3
+ import { User } from './components/user'
4
+ import { UserAvatar } from './components/user-avatar'
5
+ import { Cursors } from './components/cursors'
6
+ import { PresenceFrame } from './components/presence-frame'
7
+ import { PresenceGroup } from './components/presence-group'
8
+ import { PresenceAvatars } from './components/presence-avatars'
9
+ import {
10
+ useMe,
11
+ usePeers,
12
+ usePresence,
13
+ usePublishPresence,
14
+ useUser,
15
+ useWorkspaceUsers
16
+ } from './hooks'
17
+
18
+ export type AppletCollabApi = typeof CollabApi
19
+
20
+ export const appletCollabApi = {
21
+ Cursors,
22
+ User,
23
+ UserAvatar,
24
+ UserAvatarGroup,
25
+ PresenceFrame,
26
+ PresenceAvatars,
27
+ PresenceGroup,
28
+ useMe,
29
+ usePeers,
30
+ useUser,
31
+ useWorkspaceUsers,
32
+ usePresence,
33
+ usePublishPresence
34
+ } satisfies AppletCollabApi