moi-computer 0.0.3 → 0.1.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 (214) hide show
  1. package/bunfig.toml +4 -0
  2. package/client/api/workspaces.ts +277 -6
  3. package/client/assets/mcp/agentation.png +0 -0
  4. package/client/assets/mcp/airtable.png +0 -0
  5. package/client/assets/mcp/apollo.png +0 -0
  6. package/client/assets/mcp/asana.png +0 -0
  7. package/client/assets/mcp/box.png +0 -0
  8. package/client/assets/mcp/chrome.svg +33 -0
  9. package/client/assets/mcp/clickup.png +0 -0
  10. package/client/assets/mcp/cloudflare.png +0 -0
  11. package/client/assets/mcp/context7.png +0 -0
  12. package/client/assets/mcp/datadog.png +0 -0
  13. package/client/assets/mcp/dropbox.png +0 -0
  14. package/client/assets/mcp/elevenlabs.png +0 -0
  15. package/client/assets/mcp/exa.png +0 -0
  16. package/client/assets/mcp/firecrawl.png +0 -0
  17. package/client/assets/mcp/gmail.png +0 -0
  18. package/client/assets/mcp/googlecalendar.png +0 -0
  19. package/client/assets/mcp/googledrive.png +0 -0
  20. package/client/assets/mcp/grafana.png +0 -0
  21. package/client/assets/mcp/huggingface.png +0 -0
  22. package/client/assets/mcp/intercom.png +0 -0
  23. package/client/assets/mcp/monday.png +0 -0
  24. package/client/assets/mcp/mongodb.png +0 -0
  25. package/client/assets/mcp/paper.png +0 -0
  26. package/client/assets/mcp/paypal.png +0 -0
  27. package/client/assets/mcp/perplexity.png +0 -0
  28. package/client/assets/mcp/postgresql.png +0 -0
  29. package/client/assets/mcp/posthog.png +0 -0
  30. package/client/assets/mcp/puppeteer.png +0 -0
  31. package/client/assets/mcp/railway.png +0 -0
  32. package/client/assets/mcp/redis.png +0 -0
  33. package/client/assets/mcp/salesforce.png +0 -0
  34. package/client/assets/mcp/shopify.png +0 -0
  35. package/client/assets/mcp/snowflake.png +0 -0
  36. package/client/assets/mcp/telegram.png +0 -0
  37. package/client/assets/mcp/twilio.png +0 -0
  38. package/client/assets/mcp/zapier.png +0 -0
  39. package/client/components/App.tsx +7 -1
  40. package/client/components/ChatInput.tsx +194 -13
  41. package/client/components/ChatPanel.tsx +116 -47
  42. package/client/components/ChatPopup.tsx +1 -1
  43. package/client/components/IconMcp.tsx +21 -0
  44. package/client/components/McpMenu.tsx +125 -0
  45. package/client/components/ModelPicker.tsx +147 -0
  46. package/client/components/Scratchpad.tsx +775 -0
  47. package/client/components/ShimmerText.tsx +20 -0
  48. package/client/components/ThreadSelector.tsx +2 -2
  49. package/client/components/TurnView.tsx +111 -531
  50. package/client/components/WidgetShell.tsx +1 -1
  51. package/client/components/WorkspacesPage.tsx +12 -4
  52. package/client/components/layout/SidebarLayout.tsx +18 -9
  53. package/client/components/playground/ToolCallsPage.tsx +81 -0
  54. package/client/components/routes/workspace/[id].tsx +534 -141
  55. package/client/components/routes/workspace/create.tsx +155 -0
  56. package/client/components/settings/IconPicker.tsx +590 -0
  57. package/client/components/settings/SettingsPages.tsx +307 -0
  58. package/client/components/settings/WorkspaceSettings.tsx +92 -0
  59. package/client/components/tool-group/CodeBlock.tsx +41 -0
  60. package/client/components/tool-group/Collapse.tsx +28 -0
  61. package/client/components/tool-group/ReadImagePreview.tsx +46 -0
  62. package/client/components/tool-group/SubagentCard.tsx +135 -0
  63. package/client/components/tool-group/TimelineRow.tsx +147 -0
  64. package/client/components/tool-group/ToolCallGroup.tsx +231 -0
  65. package/client/components/tool-group/ToolOutput.tsx +139 -0
  66. package/client/components/tool-group/detect.ts +93 -0
  67. package/client/components/tool-group/fixtures.ts +315 -0
  68. package/client/components/tool-group/format.ts +211 -0
  69. package/client/components/tool-group/index.ts +9 -0
  70. package/client/components/ui/dialog.tsx +58 -0
  71. package/client/components/ui/hover-card.tsx +44 -0
  72. package/client/components/ui/switch.tsx +23 -0
  73. package/client/components/ui/tooltip.tsx +54 -0
  74. package/client/externalize-react.ts +6 -0
  75. package/client/hooks/useApplet.ts +117 -0
  76. package/client/hooks/useChat.ts +162 -62
  77. package/client/hooks/useMeiEvents.ts +9 -2
  78. package/client/hooks/useStickToBottom.ts +86 -0
  79. package/client/hooks/useWorkspaceTheme.ts +8 -2
  80. package/client/index.css +48 -2
  81. package/client/index.html +9 -5
  82. package/client/index.tsx +29 -2
  83. package/client/lib/WorkspaceContext.tsx +5 -8
  84. package/client/lib/WorkspaceLayoutContext.tsx +30 -10
  85. package/client/lib/applet-cache.ts +54 -0
  86. package/client/lib/connection.ts +237 -0
  87. package/client/lib/flags.ts +10 -0
  88. package/client/lib/mcp-icons.ts +142 -10
  89. package/client/lib/preview-turn.ts +37 -0
  90. package/client/lib/render-icon.ts +173 -0
  91. package/client/lib/scratch-executor.ts +20 -0
  92. package/client/lib/uploads.ts +18 -0
  93. package/client/main.tsx +5 -0
  94. package/client/store/live.ts +282 -0
  95. package/client/structured-clone-shim.ts +14 -0
  96. package/client/theme.css +2 -2
  97. package/client/vendor/emojibase/en/data.json +1 -0
  98. package/client/vendor/emojibase/en/messages.json +1 -0
  99. package/client/vendor/react/development/_impl/react-dom-client.js +15871 -0
  100. package/client/vendor/react/development/_impl/react-dom.js +223 -0
  101. package/client/vendor/react/development/_impl/react-jsx-dev-runtime.js +256 -0
  102. package/client/vendor/react/development/_impl/react-jsx-runtime.js +260 -0
  103. package/client/vendor/react/development/_impl/react.js +863 -0
  104. package/client/vendor/react/development/react-dom-client.js +6 -0
  105. package/client/vendor/react/development/react-dom.js +17 -0
  106. package/client/vendor/react/development/react-jsx-dev-runtime.js +5 -0
  107. package/client/vendor/react/development/react-jsx-runtime.js +6 -0
  108. package/client/vendor/react/development/react.js +47 -0
  109. package/client/vendor/react/production/_impl/react-dom-client.js +10361 -0
  110. package/client/vendor/react/production/_impl/react-dom.js +184 -0
  111. package/client/vendor/react/production/_impl/react-jsx-dev-runtime.js +37 -0
  112. package/client/vendor/react/production/_impl/react-jsx-runtime.js +60 -0
  113. package/client/vendor/react/production/_impl/react.js +428 -0
  114. package/client/vendor/react/production/react-dom-client.js +6 -0
  115. package/client/vendor/react/production/react-dom.js +17 -0
  116. package/client/vendor/react/production/react-jsx-dev-runtime.js +5 -0
  117. package/client/vendor/react/production/react-jsx-runtime.js +6 -0
  118. package/client/vendor/react/production/react.js +47 -0
  119. package/dist/agentation-4s0nn45p.png +0 -0
  120. package/dist/airtable-hsa66v6q.png +0 -0
  121. package/dist/apollo-2ed5dy2d.png +0 -0
  122. package/dist/asana-tvgtwbx2.png +0 -0
  123. package/dist/box-w3n36t5g.png +0 -0
  124. package/dist/chrome-tspm94rw.svg +33 -0
  125. package/dist/chunk-kc6e9nd4.css +1 -0
  126. package/dist/chunk-yf3p7qg7.js +673 -0
  127. package/dist/clickup-qqrqqvqb.png +0 -0
  128. package/dist/cloudflare-j9p931v6.png +0 -0
  129. package/dist/context7-8ht0xjfy.png +0 -0
  130. package/dist/datadog-70ne3yzt.png +0 -0
  131. package/dist/dropbox-4m5s9mgr.png +0 -0
  132. package/dist/elevenlabs-2nzzej1t.png +0 -0
  133. package/dist/exa-qqj3vr0x.png +0 -0
  134. package/dist/firecrawl-w2t8nehx.png +0 -0
  135. package/dist/gmail-sg6a5v3x.png +0 -0
  136. package/dist/googlecalendar-nqhh2v7r.png +0 -0
  137. package/dist/googledrive-6s8xyab7.png +0 -0
  138. package/dist/grafana-1yfsnwr6.png +0 -0
  139. package/dist/huggingface-kxzaxj83.png +0 -0
  140. package/dist/index.html +10 -6
  141. package/dist/intercom-td763jt8.png +0 -0
  142. package/dist/monday-jdbs4wwf.png +0 -0
  143. package/dist/mongodb-emzxvhd5.png +0 -0
  144. package/dist/paper-zbt34fab.png +0 -0
  145. package/dist/paypal-kwwf7xsc.png +0 -0
  146. package/dist/perplexity-4y63rxvj.png +0 -0
  147. package/dist/postgresql-qsspbsr1.png +0 -0
  148. package/dist/posthog-sphppc4w.png +0 -0
  149. package/dist/puppeteer-2xjt1a9b.png +0 -0
  150. package/dist/railway-834de8d2.png +0 -0
  151. package/dist/redis-spm6w2m1.png +0 -0
  152. package/dist/salesforce-1mk56v4z.png +0 -0
  153. package/dist/shopify-90dadaav.png +0 -0
  154. package/dist/snowflake-hfpykpgy.png +0 -0
  155. package/dist/telegram-v6tjyrs7.png +0 -0
  156. package/dist/twilio-dpyjdwpj.png +0 -0
  157. package/dist/zapier-p67qfch0.png +0 -0
  158. package/lib/attachment-note.ts +48 -0
  159. package/lib/claude-adapter.ts +219 -29
  160. package/lib/format.ts +32 -0
  161. package/lib/types.ts +314 -6
  162. package/package.json +10 -5
  163. package/server/CLAUDE.md +3 -0
  164. package/server/agent.ts +25 -118
  165. package/server/api.ts +593 -0
  166. package/server/applets.ts +396 -0
  167. package/server/build-applet.ts +580 -0
  168. package/server/cc-session.ts +611 -0
  169. package/server/cli-colors.ts +17 -0
  170. package/server/cli-ui.ts +52 -0
  171. package/server/cli.ts +964 -72
  172. package/server/control.ts +166 -19
  173. package/server/debug.ts +10 -0
  174. package/server/events.ts +24 -0
  175. package/server/functions-worker.ts +18 -2
  176. package/server/functions.ts +59 -12
  177. package/server/icon.ts +13 -0
  178. package/server/layout.ts +25 -3
  179. package/server/mcp.ts +125 -0
  180. package/server/moi-scaffold.ts +85 -0
  181. package/server/openclaw-session.ts +41 -10
  182. package/server/openclaw.ts +22 -0
  183. package/server/preview.ts +70 -0
  184. package/server/registry.ts +32 -2
  185. package/server/scratchpad-executor.ts +380 -0
  186. package/server/scratchpad-relay.ts +45 -0
  187. package/server/scratchpad.ts +171 -0
  188. package/server/skill-version.ts +146 -0
  189. package/server/skills-template.ts +6 -1
  190. package/server/state.ts +22 -36
  191. package/server/static.ts +23 -0
  192. package/server/status.ts +94 -0
  193. package/server/thread-config.ts +125 -0
  194. package/server/uploads.ts +0 -0
  195. package/server/vendor.ts +63 -0
  196. package/server/views.ts +0 -0
  197. package/server/web.ts +108 -253
  198. package/server/widgets.ts +52 -142
  199. package/server/workspace-config.ts +37 -0
  200. package/server/workspace-env.ts +407 -0
  201. package/server/workspace-init.ts +66 -0
  202. package/workspace/.claude/skills/moi-workspace/DESIGN.md +109 -0
  203. package/workspace/.claude/skills/moi-workspace/SCRATCHPAD.md +57 -0
  204. package/workspace/.claude/skills/moi-workspace/SKILL.md +252 -0
  205. package/workspace/.claude/skills/moi-workspace/VIEW-DESIGN.md +22 -0
  206. package/client/hooks/useWidget.ts +0 -72
  207. package/client/hooks/useWidgetList.ts +0 -30
  208. package/client/lib/ws.ts +0 -129
  209. package/client/store/chat.tsx +0 -162
  210. package/dist/chunk-4615fa69.js +0 -67
  211. package/dist/chunk-582xmy05.css +0 -1
  212. package/server/build-widget.ts +0 -343
  213. package/workspace/.claude/skills/widgets/DESIGN.md +0 -630
  214. package/workspace/.claude/skills/widgets/SKILL.md +0 -176
@@ -0,0 +1,23 @@
1
+ import { Switch as SwitchPrimitive } from '@base-ui/react/switch'
2
+
3
+ import { cn } from '@/client/lib/cn'
4
+
5
+ function Switch({ className, ...props }: SwitchPrimitive.Root.Props) {
6
+ return (
7
+ <SwitchPrimitive.Root
8
+ data-slot="switch"
9
+ className={cn(
10
+ 'peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border border-transparent shadow-xs transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 data-checked:bg-primary data-unchecked:bg-input',
11
+ className
12
+ )}
13
+ {...props}
14
+ >
15
+ <SwitchPrimitive.Thumb
16
+ data-slot="switch-thumb"
17
+ className="pointer-events-none block size-4 rounded-full bg-background shadow-sm ring-0 transition-transform data-checked:translate-x-4 data-unchecked:translate-x-0.5"
18
+ />
19
+ </SwitchPrimitive.Root>
20
+ )
21
+ }
22
+
23
+ export { Switch }
@@ -0,0 +1,54 @@
1
+ import { Tooltip as TooltipPrimitive } from '@base-ui/react/tooltip'
2
+
3
+ import { cn } from '@/client/lib/cn'
4
+
5
+ // Self-contained: each Tooltip wraps its own provider so `delay` can be set
6
+ // per-instance (Base UI exposes delay/closeDelay on the provider, not the root).
7
+ function Tooltip({
8
+ delay,
9
+ closeDelay,
10
+ ...props
11
+ }: TooltipPrimitive.Root.Props & { delay?: number; closeDelay?: number }) {
12
+ return (
13
+ <TooltipPrimitive.Provider delay={delay} closeDelay={closeDelay}>
14
+ <TooltipPrimitive.Root data-slot="tooltip" {...props} />
15
+ </TooltipPrimitive.Provider>
16
+ )
17
+ }
18
+
19
+ function TooltipTrigger({ ...props }: TooltipPrimitive.Trigger.Props) {
20
+ return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
21
+ }
22
+
23
+ function TooltipContent({
24
+ className,
25
+ side = 'top',
26
+ sideOffset = 6,
27
+ align = 'center',
28
+ alignOffset = 0,
29
+ ...props
30
+ }: TooltipPrimitive.Popup.Props &
31
+ Pick<TooltipPrimitive.Positioner.Props, 'align' | 'alignOffset' | 'side' | 'sideOffset'>) {
32
+ return (
33
+ <TooltipPrimitive.Portal>
34
+ <TooltipPrimitive.Positioner
35
+ align={align}
36
+ alignOffset={alignOffset}
37
+ side={side}
38
+ sideOffset={sideOffset}
39
+ className="isolate z-50"
40
+ >
41
+ <TooltipPrimitive.Popup
42
+ data-slot="tooltip-content"
43
+ className={cn(
44
+ 'z-50 origin-(--transform-origin) rounded-sm bg-white px-2 py-1 text-xs font-medium text-primary shadow-md outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-1 data-[side=left]:slide-in-from-right-1 data-[side=right]:slide-in-from-left-1 data-[side=top]:slide-in-from-bottom-1 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
45
+ className
46
+ )}
47
+ {...props}
48
+ />
49
+ </TooltipPrimitive.Positioner>
50
+ </TooltipPrimitive.Portal>
51
+ )
52
+ }
53
+
54
+ export { Tooltip, TooltipContent, TooltipTrigger }
@@ -1,5 +1,11 @@
1
1
  import type { BunPlugin } from 'bun'
2
2
 
3
+ // React is not bundled into the app. Each of these specifiers is replaced with a
4
+ // read from `globalThis.__esm`, which the preload in index.html fills by
5
+ // importing them through the importmap (→ the locally-vendored ESM served at
6
+ // /vendor/react, see scripts/build-vendor.ts). This keeps ONE React instance
7
+ // shared between the host app and every applet/widget (which resolve the same
8
+ // importmap) — bundling React in would give each its own copy and break hooks.
3
9
  const esmModules = [
4
10
  'react',
5
11
  'react/jsx-runtime',
@@ -0,0 +1,117 @@
1
+ import type { ComponentType } from 'react'
2
+ import { useCallback, useEffect, useState } from 'react'
3
+
4
+ import {
5
+ type AppletSegment,
6
+ appletKey,
7
+ appletUrl,
8
+ getCachedApplet,
9
+ invalidateApplet,
10
+ setCachedApplet
11
+ } from '@/client/lib/applet-cache'
12
+ import { useWorkspaceId } from '@/client/lib/WorkspaceContext'
13
+
14
+ import { type MeiEvent, useMeiEvent } from './useMeiEvents'
15
+
16
+ type AppletState =
17
+ | { status: 'loading'; version: number }
18
+ | { status: 'ready'; Component: ComponentType; version: number }
19
+ | { status: 'error'; error: string; version: number }
20
+
21
+ // An applet kind (widget / view) differs only in its URL path segment and which
22
+ // MEI events tell it to reload. Everything else — dynamic import, caching,
23
+ // cache-busting — is shared. An applet is an agent-authored UI unit loaded as an
24
+ // ESM module and mounted into the workspace.
25
+ type AppletKind = {
26
+ segment: AppletSegment
27
+ // True when this MEI event means the named applet should cache-bust + reload.
28
+ shouldReload: (event: MeiEvent, name: string) => boolean
29
+ }
30
+
31
+ const WIDGET_KIND: AppletKind = {
32
+ segment: 'widgets',
33
+ shouldReload: (e, name) =>
34
+ (e.type === 'widget:updated' && e.name === name) || e.type === 'widgets:refresh'
35
+ }
36
+
37
+ const VIEW_KIND: AppletKind = {
38
+ segment: 'views',
39
+ shouldReload: (e, name) => e.type === 'view:updated' && e.name === name
40
+ }
41
+
42
+ function loadApplet(
43
+ segment: AppletSegment,
44
+ workspaceId: string,
45
+ name: string
46
+ ): Promise<ComponentType> {
47
+ const key = appletKey(segment, workspaceId, name)
48
+ const existing = getCachedApplet(key) as Promise<ComponentType> | undefined
49
+ if (existing) return existing
50
+
51
+ // Import the bundle dir's `index.js` at its current `?v`; the version is bumped
52
+ // (and this entry dropped) by `invalidateApplet` on every rebuild — including
53
+ // while this applet is unmounted — so a backgrounded tab never serves stale.
54
+ const promise = import(/* @vite-ignore */ appletUrl(segment, workspaceId, name)).then(mod => {
55
+ if (!mod.default) throw new Error(`"${name}" has no default export`)
56
+ return mod.default as ComponentType
57
+ })
58
+
59
+ setCachedApplet(key, promise)
60
+ return promise
61
+ }
62
+
63
+ function useApplet(kind: AppletKind, name: string): AppletState {
64
+ const workspaceId = useWorkspaceId()
65
+ const [state, setState] = useState<AppletState>({ status: 'loading', version: 0 })
66
+
67
+ const load = useCallback(() => {
68
+ setState(prev => ({ status: 'loading', version: prev.version }))
69
+ loadApplet(kind.segment, workspaceId, name)
70
+ .then(Component =>
71
+ setState(prev => ({ status: 'ready', Component, version: prev.version + 1 }))
72
+ )
73
+ .catch(err =>
74
+ setState(prev => ({ status: 'error', error: String(err), version: prev.version + 1 }))
75
+ )
76
+ }, [kind.segment, workspaceId, name])
77
+
78
+ useEffect(() => {
79
+ load()
80
+ }, [load])
81
+
82
+ // Reload the MOUNTED applet the moment the server says its bundle changed (or,
83
+ // widgets only, `moi refresh`). Invalidate first so we don't re-read a stale
84
+ // cache entry — `useAppletCacheInvalidation` may already have done so for the
85
+ // unmounted case, but doing it here keeps this self-sufficient and
86
+ // order-independent. The bumped version remounts the component and re-runs its
87
+ // `rpc()` calls.
88
+ useMeiEvent(event => {
89
+ if (kind.shouldReload(event, name)) {
90
+ invalidateApplet(kind.segment, workspaceId, name)
91
+ load()
92
+ }
93
+ })
94
+
95
+ return state
96
+ }
97
+
98
+ export function useWidget(name: string): AppletState {
99
+ return useApplet(WIDGET_KIND, name)
100
+ }
101
+
102
+ export function useView(name: string): AppletState {
103
+ return useApplet(VIEW_KIND, name)
104
+ }
105
+
106
+ // Mount once per workspace (in the workspace route). Invalidates the shared
107
+ // applet module cache on every `*:updated` event, regardless of what's currently
108
+ // mounted — so an applet edited while its tab is backgrounded is fetched fresh on
109
+ // the next mount instead of served stale. The per-applet listener above only
110
+ // fires while that applet is on screen; this covers the (common) rest.
111
+ export function useAppletCacheInvalidation(): void {
112
+ const workspaceId = useWorkspaceId()
113
+ useMeiEvent(event => {
114
+ if (event.type === 'view:updated') invalidateApplet('views', workspaceId, event.name)
115
+ else if (event.type === 'widget:updated') invalidateApplet('widgets', workspaceId, event.name)
116
+ })
117
+ }
@@ -1,88 +1,188 @@
1
- import { useCallback, useEffect } from 'react'
2
- import { useState } from 'react'
1
+ import { useCallback, useMemo } from 'react'
3
2
 
3
+ import { useQueryClient } from '@tanstack/react-query'
4
+
5
+ import {
6
+ useSessionView,
7
+ useThreadConfig,
8
+ useWorkspaceModels,
9
+ workspaceKeys
10
+ } from '@/client/api/workspaces'
4
11
  import { useWorkspaceId } from '@/client/lib/WorkspaceContext'
5
- import { connectWs, disconnectWs, sendWs } from '@/client/lib/ws'
6
- import { useChatStore, useChatStoreApi } from '@/client/store/chat'
7
- import { emptyViewState } from '@/lib/format'
8
- import type { ViewState } from '@/lib/types'
12
+ import { useWorkspaceLayoutCtx } from '@/client/lib/WorkspaceLayoutContext'
13
+ import { sendMessage } from '@/client/lib/connection'
14
+ import { STREAM_RESPONSES } from '@/client/lib/flags'
15
+ import { buildPreviewTurn } from '@/client/lib/preview-turn'
16
+ import { draftKey, liveStore, selectPreviews, useLive } from '@/client/store/live'
17
+ import { applyEvent, emptyViewState } from '@/lib/format'
18
+ import type { Part, ViewState } from '@/lib/types'
9
19
 
10
20
  const EMPTY: ViewState = emptyViewState()
11
21
 
22
+ // Thin projection over app-level state: the active thread + spinner/error come
23
+ // from the live store; the transcript comes from the React Query cache (kept
24
+ // current by the connection manager's WS deltas). No socket lifecycle here.
12
25
  export function useChat() {
13
26
  const workspaceId = useWorkspaceId()
14
- const store = useChatStoreApi()
15
- const [input, setInput] = useState('')
27
+ const qc = useQueryClient()
28
+ const { layout } = useWorkspaceLayoutCtx()
29
+ const modelsData = useWorkspaceModels(workspaceId).data
30
+ const models = modelsData?.models
31
+ const supportsStreaming = modelsData?.supportsStreaming ?? false
32
+
33
+ const activeSessionId = useLive(s => s.activeByWorkspace[workspaceId] ?? null)
34
+ const processing = useLive(s =>
35
+ activeSessionId ? (s.processing[`${workspaceId}:${activeSessionId}`] ?? false) : false
36
+ )
37
+ const error = useLive(s =>
38
+ activeSessionId ? (s.errors[`${workspaceId}:${activeSessionId}`] ?? null) : null
39
+ )
16
40
 
17
- const activeSessionId = useChatStore(s => s.activeSessionId)
18
- const setActiveSession = useChatStore(s => s.setActiveSession)
41
+ const view = useSessionView(workspaceId, activeSessionId).data ?? EMPTY
19
42
 
20
- const view = useChatStore(s => s.views[activeSessionId ?? ''] ?? EMPTY)
21
- const processing = useChatStore(s => s.processing[activeSessionId ?? ''] ?? false)
22
- const error = useChatStore(s => s.errors[activeSessionId ?? ''] ?? null)
43
+ // The live streaming preview as a synthetic assistant turn, so the ChatPanel
44
+ // can run it through the SAME groupTurns pipeline as finalized turns — a
45
+ // thinking-only preview then folds into the current tool group instead of
46
+ // rendering as a detached block. Recomputed per delta (the previews slice is
47
+ // stable across other updates); null when there's nothing visible yet.
48
+ const previews = useLive(s => s.previews)
49
+ const previewTurn = useMemo(
50
+ () => buildPreviewTurn(selectPreviews(previews, workspaceId, activeSessionId).root),
51
+ [previews, workspaceId, activeSessionId]
52
+ )
23
53
 
24
- // Persistent WS for live events — reconnects if workspace changes. Hands the
25
- // workspace's chat store to the (non-React) socket layer so it writes there.
26
- useEffect(() => {
27
- connectWs(workspaceId, store)
28
- return () => disconnectWs()
29
- }, [workspaceId, store])
54
+ // The active thread's persisted model/effort. For a brand-new chat (no thread
55
+ // yet) this is empty and `send` falls back to the workspace defaults below.
56
+ const threadCfg = useThreadConfig(workspaceId, activeSessionId).data
30
57
 
31
- // When active session changes and we don't have its events cached, fetch them
32
- useEffect(() => {
33
- if (!activeSessionId) return
34
- if (store.getState().events[activeSessionId] !== undefined) return
35
- store.getState().loadEvents(workspaceId, activeSessionId)
36
- }, [workspaceId, activeSessionId, store])
37
-
38
- const send = useCallback(() => {
39
- const text = input.trim()
40
- if (!text || processing) return
41
-
42
- let sid = activeSessionId
43
- let isNew = false
44
- if (!sid) {
45
- sid = crypto.randomUUID()
46
- isNew = true
47
- store.getState().setEvents(sid, [])
48
- setActiveSession(sid)
49
- }
50
-
51
- // Optimistic user turn — rendered immediately, upserted in place when the
52
- // SDK echoes it back via expectUserEcho on the server.
53
- const optimisticId = `optimistic:${crypto.randomUUID()}`
54
- store.getState().append(sid, {
55
- kind: 'turn',
56
- turn: {
57
- id: optimisticId,
58
- role: 'user',
59
- origin: { kind: 'user-input' },
60
- parts: [{ type: 'text', text }],
61
- timestamp: new Date().toISOString()
58
+ // The composer owns the draft (in the live store) and hands the text in, so a
59
+ // keystroke re-renders only the composer — not this hook's host (WorkspaceView)
60
+ // and its whole subtree. See `ChatInput`.
61
+ const send = useCallback(
62
+ (draft: string) => {
63
+ const text = draft.trim()
64
+ // Attachments for the active thread, keyed exactly like the draft. Only
65
+ // fully-uploaded ones are sent; the composer disables send while any are
66
+ // still uploading, so in practice they're all ready here.
67
+ const pending = liveStore.getState().attachments[draftKey(workspaceId, activeSessionId)] ?? []
68
+ const ready = pending.filter(a => a.status === 'ready' && a.upload)
69
+ // No `processing` guard: sending while a turn is in flight QUEUES the
70
+ // message into the same live server session (streaming-input mode).
71
+ if (!text && ready.length === 0) return
72
+
73
+ let sid = activeSessionId
74
+ let isNew = false
75
+ if (!sid) {
76
+ sid = crypto.randomUUID()
77
+ isNew = true
78
+ liveStore.getState().setActive(workspaceId, sid)
79
+ }
80
+
81
+ // Optimistic user turn — primed into the RQ transcript cache so it renders
82
+ // immediately. The server re-ids the SDK's user echo to optimisticId so it
83
+ // upserts in place rather than duplicating. Image attachments render from
84
+ // their local object URL until the server's broadcast (with a data URL)
85
+ // upserts in place.
86
+ const optimisticId = `optimistic:${crypto.randomUUID()}`
87
+ const parts: Part[] = []
88
+ for (const a of ready) {
89
+ if (a.upload?.kind === 'image' && a.previewUrl) {
90
+ parts.push({ type: 'file', mediaType: a.mediaType, url: a.previewUrl, filename: a.name })
91
+ } else {
92
+ parts.push({ type: 'file', mediaType: a.mediaType, url: '', filename: a.name })
93
+ }
62
94
  }
63
- })
95
+ if (text) parts.push({ type: 'text', text })
96
+ qc.setQueryData<ViewState>(workspaceKeys.events(workspaceId, sid), prev =>
97
+ applyEvent(prev ?? emptyViewState(), {
98
+ kind: 'turn',
99
+ turn: {
100
+ id: optimisticId,
101
+ role: 'user',
102
+ origin: { kind: 'user-input' },
103
+ parts,
104
+ timestamp: new Date().toISOString()
105
+ }
106
+ })
107
+ )
108
+ liveStore.getState().setProcessing(workspaceId, sid, true)
109
+ liveStore.getState().setError(workspaceId, sid, null)
64
110
 
65
- sendWs({ type: 'chat', content: text, sessionId: sid, isNew, optimisticId })
66
- store.getState().setError(sid, null)
67
- setInput('')
68
- }, [input, processing, activeSessionId, setActiveSession, store])
111
+ // The thread's persisted choice (workspace defaults for a new chat). Drop a
112
+ // model the loaded list no longer offers (stale alias) so the SDK doesn't
113
+ // reject model_not_found. Drop an effort the resolved model doesn't support
114
+ // (e.g. model changed under it); when the model is unknown/default we can't
115
+ // check, so pass it through — the SDK silently downgrades unsupported effort.
116
+ const pickedModel = threadCfg?.model ?? layout.selectedModel
117
+ const modelOk = !pickedModel || !models || models.some(m => m.value === pickedModel)
118
+ const model = modelOk ? pickedModel : undefined
119
+ const modelInfo = models?.find(m => m.value === model)
120
+ const pickedEffort = threadCfg?.effort ?? layout.selectedEffort
121
+ const effort =
122
+ pickedEffort &&
123
+ (!modelInfo || (modelInfo.supportedEffortLevels ?? []).includes(pickedEffort))
124
+ ? pickedEffort
125
+ : undefined
126
+ // Live token streaming is a compile-time dev flag (client/lib/flags.ts),
127
+ // gated to providers that support it. Send `true` or omit (never `false`),
128
+ // so a provider that ignores it behaves identically.
129
+ const stream = STREAM_RESPONSES && supportsStreaming ? true : undefined
130
+ sendMessage({
131
+ type: 'chat',
132
+ workspaceId,
133
+ content: text,
134
+ sessionId: sid,
135
+ isNew,
136
+ optimisticId,
137
+ model,
138
+ effort,
139
+ stream,
140
+ ...(ready.length > 0 ? { attachments: ready.map(a => a.upload!.id) } : {})
141
+ })
142
+ // Drop the thread's attachments now that they've been sent (revokes the
143
+ // preview object URLs). Keyed by the pre-mint id, matching where they were
144
+ // stored by the composer.
145
+ liveStore.getState().clearAttachments(workspaceId, activeSessionId)
146
+ },
147
+ [
148
+ activeSessionId,
149
+ workspaceId,
150
+ qc,
151
+ layout.selectedModel,
152
+ layout.selectedEffort,
153
+ threadCfg?.model,
154
+ threadCfg?.effort,
155
+ models,
156
+ supportsStreaming
157
+ ]
158
+ )
69
159
 
70
160
  const dismissError = useCallback(() => {
71
161
  if (!activeSessionId) return
72
- store.getState().setError(activeSessionId, null)
73
- }, [activeSessionId, store])
162
+ liveStore.getState().setError(workspaceId, activeSessionId, null)
163
+ }, [activeSessionId, workspaceId])
74
164
 
75
165
  const stop = useCallback(() => {
76
166
  if (!processing || !activeSessionId) return
77
- sendWs({ type: 'stop', sessionId: activeSessionId })
78
- }, [processing, activeSessionId])
167
+ sendMessage({ type: 'stop', workspaceId, sessionId: activeSessionId })
168
+ }, [processing, activeSessionId, workspaceId])
79
169
 
80
170
  const switchThread = useCallback(
81
171
  (sessionId: string | null) => {
82
- setActiveSession(sessionId)
172
+ liveStore.getState().setActive(workspaceId, sessionId)
83
173
  },
84
- [setActiveSession]
174
+ [workspaceId]
85
175
  )
86
176
 
87
- return { view, processing, error, input, setInput, send, stop, switchThread, dismissError }
177
+ return {
178
+ view,
179
+ previewTurn,
180
+ sessionId: activeSessionId,
181
+ processing,
182
+ error,
183
+ send,
184
+ stop,
185
+ switchThread,
186
+ dismissError
187
+ }
88
188
  }
@@ -1,11 +1,18 @@
1
1
  import { useEffect, useRef } from 'react'
2
2
 
3
- import type { WidgetInfo } from '@/lib/types'
3
+ import type { ViewInfo, WidgetInfo } from '@/lib/types'
4
4
 
5
- type MeiEvent =
5
+ export type MeiEvent =
6
6
  | { type: 'widget:updated'; name: string }
7
7
  | { type: 'widget-layout:updated'; widgets: WidgetInfo[] }
8
+ | { type: 'widgets:refresh' }
9
+ | { type: 'view:updated'; name: string }
10
+ | { type: 'view-layout:updated'; views: ViewInfo[] }
8
11
  | { type: 'theme:updated' }
12
+ | { type: 'workspace:updated' }
13
+ // The Scratchpad canvas for `workspaceId` was saved — open tabs reload from
14
+ // disk. `origin` is the tab that wrote it, so that tab can skip its own echo.
15
+ | { type: 'scratchpad:updated'; workspaceId: string; origin?: string }
9
16
 
10
17
  type MeiEventHandler = (event: MeiEvent) => void
11
18
 
@@ -0,0 +1,86 @@
1
+ import { type RefObject, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
2
+
3
+ // Best-practice chat scroll behavior — "stick to bottom, but respect the user":
4
+ // • Pinned to the bottom by default: new content (new turns, streaming tokens,
5
+ // images loading) keeps the latest line in view.
6
+ // • The moment the user scrolls up, un-pin — never yank them back down while
7
+ // they read history.
8
+ // • Re-pin automatically when they scroll back to (near) the bottom.
9
+ // • `scrollToBottom()` for the "jump to latest" button and for send.
10
+ // • On mount and whenever `resetKey` changes (thread switch), jump to bottom.
11
+ //
12
+ // Content growth is followed via a ResizeObserver on the scroll content, so we
13
+ // don't depend on React deps to know when to scroll — it just works for any
14
+ // height change, including per-token streaming.
15
+
16
+ // Within this many px of the bottom still counts as "at the bottom" — covers
17
+ // sub-pixel rounding and lets a small overscroll keep the pin.
18
+ const STICK_THRESHOLD_PX = 48
19
+
20
+ type StickToBottom = {
21
+ // True when pinned to (near) the bottom — drives the jump-to-latest button.
22
+ atBottom: boolean
23
+ // Scroll to the bottom and re-pin. `smooth` for user-initiated jumps.
24
+ scrollToBottom: (behavior?: ScrollBehavior) => void
25
+ }
26
+
27
+ export function useStickToBottom(
28
+ scrollRef: RefObject<HTMLElement | null>,
29
+ resetKey?: unknown
30
+ ): StickToBottom {
31
+ // Ref (not state) so the scroll/resize handlers read the latest value without
32
+ // re-subscribing; `atBottom` state mirrors it for rendering the button.
33
+ const pinnedRef = useRef(true)
34
+ const [atBottom, setAtBottom] = useState(true)
35
+
36
+ const setPinned = useCallback((pinned: boolean) => {
37
+ pinnedRef.current = pinned
38
+ setAtBottom(prev => (prev === pinned ? prev : pinned))
39
+ }, [])
40
+
41
+ const scrollToBottom = useCallback(
42
+ (behavior: ScrollBehavior = 'auto') => {
43
+ const el = scrollRef.current
44
+ if (!el) return
45
+ setPinned(true)
46
+ el.scrollTo({ top: el.scrollHeight, behavior })
47
+ },
48
+ [scrollRef, setPinned]
49
+ )
50
+
51
+ // Track whether the user is at the bottom. A programmatic scroll-to-bottom
52
+ // also fires this with distance ≈ 0, so pinned stays true — no fight.
53
+ useEffect(() => {
54
+ const el = scrollRef.current
55
+ if (!el) return
56
+ const onScroll = () => {
57
+ const distance = el.scrollHeight - el.scrollTop - el.clientHeight
58
+ setPinned(distance <= STICK_THRESHOLD_PX)
59
+ }
60
+ el.addEventListener('scroll', onScroll, { passive: true })
61
+ return () => el.removeEventListener('scroll', onScroll)
62
+ }, [scrollRef, setPinned])
63
+
64
+ // Follow content growth while pinned. Observing the content element catches
65
+ // every height change (new turns, streaming text, images) without React deps.
66
+ // Setting scrollTop doesn't change the observed size, so there's no RO loop.
67
+ useEffect(() => {
68
+ const el = scrollRef.current
69
+ if (!el) return
70
+ const content = el.firstElementChild ?? el
71
+ const ro = new ResizeObserver(() => {
72
+ if (pinnedRef.current) el.scrollTop = el.scrollHeight
73
+ })
74
+ ro.observe(content)
75
+ return () => ro.disconnect()
76
+ }, [scrollRef])
77
+
78
+ // Jump to bottom on mount and on thread switch (before paint, so no flash).
79
+ // If the new thread's content is still loading, the ResizeObserver above lands
80
+ // us at the bottom once it arrives (pin is set here).
81
+ useLayoutEffect(() => {
82
+ scrollToBottom('auto')
83
+ }, [resetKey, scrollToBottom])
84
+
85
+ return { atBottom, scrollToBottom }
86
+ }
@@ -22,6 +22,11 @@ export function useWorkspaceTheme(
22
22
  target: RefObject<HTMLElement | null>
23
23
  ) {
24
24
  const font = theme?.font ?? 'default'
25
+ // Read the scoped color overrides up front so the color effect below depends
26
+ // on these exact values rather than the whole `theme` object (it accesses
27
+ // them via a dynamic key, which the deps linter can't see through).
28
+ const background = theme?.background
29
+ const foreground = theme?.foreground
25
30
 
26
31
  useEffect(() => {
27
32
  const el = target.current
@@ -58,8 +63,9 @@ export function useWorkspaceTheme(
58
63
  useEffect(() => {
59
64
  const el = target.current
60
65
  if (!el) return
66
+ const overrides = { background, foreground }
61
67
  for (const key of COLOR_OVERRIDES) {
62
- const value = theme?.[key]
68
+ const value = overrides[key]
63
69
  if (value) {
64
70
  el.style.setProperty(`--${key}`, value)
65
71
  } else {
@@ -69,7 +75,7 @@ export function useWorkspaceTheme(
69
75
  return () => {
70
76
  for (const key of COLOR_OVERRIDES) el.style.removeProperty(`--${key}`)
71
77
  }
72
- }, [theme?.background, theme?.foreground, target])
78
+ }, [background, foreground, target])
73
79
 
74
80
  // Drop the shared font <link> when the workspace unmounts.
75
81
  useEffect(() => () => document.getElementById(FONT_LINK_ID)?.remove(), [])