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
package/client/index.css CHANGED
@@ -39,8 +39,9 @@
39
39
  equivalents. (The app sidebar's own widths live in SidebarLayout.tsx.) */
40
40
  --page-pad: 2rem; /* padding around the working area */
41
41
  --column-w: 40rem; /* grid content width; also the widget area's min before the chat yields */
42
- --chat-min: 400px; /* docked chat min width — narrower than this and it floats */
43
- --chat-max: 520px; /* docked chat max width on wide screens */
42
+ --chat-min: 380px; /* docked chat min width — narrower than this and it floats */
43
+ --chat-max: 460px; /* docked chat max width on wide screens */
44
+ --chat-max-container: 640px; /* contained ChatPanel: max width of the centered history + composer column */
44
45
  }
45
46
 
46
47
  @media (max-width: 1024px) {
@@ -134,6 +135,18 @@
134
135
  }
135
136
  }
136
137
 
138
+ /* Text shimmer — a brighter band sweeps left→right across muted text to signal
139
+ activity. Pair with `bg-clip-text text-transparent` and a 200%-wide gradient
140
+ whose highlight sits in the middle (see <ShimmerText>). */
141
+ @keyframes text-shimmer {
142
+ 0% {
143
+ background-position: -100% center;
144
+ }
145
+ 100% {
146
+ background-position: 100% center;
147
+ }
148
+ }
149
+
137
150
  @utility prose-inherit {
138
151
  --tw-prose-body: inherit;
139
152
  --tw-prose-headings: inherit;
@@ -170,6 +183,39 @@
170
183
  mask-repeat: no-repeat;
171
184
  }
172
185
 
186
+ /* Hide the scrollbar entirely (e.g. the MCP hover card, which signals overflow
187
+ with top/bottom mask fades instead — see useScrollFade + mask-fade-*). */
188
+ @utility scrollbar-none {
189
+ scrollbar-width: none;
190
+ &::-webkit-scrollbar {
191
+ display: none;
192
+ }
193
+ }
194
+
195
+ /* Slim, unobtrusive scrollbar — keeps a clear scroll affordance while taming
196
+ the chunky macOS "always show" scrollbar (a transparent border insets the
197
+ thumb into a thin floating pill). */
198
+ @utility scrollbar-thin {
199
+ scrollbar-width: thin;
200
+ scrollbar-color: rgb(0 0 0 / 0.2) transparent;
201
+ &::-webkit-scrollbar {
202
+ width: 10px;
203
+ height: 10px;
204
+ }
205
+ &::-webkit-scrollbar-track {
206
+ background: transparent;
207
+ }
208
+ &::-webkit-scrollbar-thumb {
209
+ background-color: rgb(0 0 0 / 0.2);
210
+ border-radius: 9999px;
211
+ border: 3px solid transparent;
212
+ background-clip: padding-box;
213
+ }
214
+ &::-webkit-scrollbar-thumb:hover {
215
+ background-color: rgb(0 0 0 / 0.32);
216
+ }
217
+ }
218
+
173
219
  /* Tool details toggle */
174
220
  details > summary {
175
221
  list-style: none;
package/client/index.html CHANGED
@@ -5,14 +5,18 @@
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>moi.computer</title>
7
7
  <link rel="icon" type="image/png" href="./assets/favicon.png" />
8
+ <!-- React is vendored locally (client/vendor/react, generated by
9
+ scripts/build-vendor.ts) and served by the /vendor/react route, so Moi
10
+ runs fully offline — no CDN fetch. The server picks the development or
11
+ production build per environment behind these stable URLs. -->
8
12
  <script type="importmap">
9
13
  {
10
14
  "imports": {
11
- "react": "https://esm.sh/react@19?dev",
12
- "react/jsx-runtime": "https://esm.sh/react@19/jsx-runtime?dev",
13
- "react/jsx-dev-runtime": "https://esm.sh/react@19/jsx-dev-runtime?dev",
14
- "react-dom": "https://esm.sh/react-dom@19?dev",
15
- "react-dom/client": "https://esm.sh/react-dom@19/client?dev"
15
+ "react": "/vendor/react/react.js",
16
+ "react/jsx-runtime": "/vendor/react/react-jsx-runtime.js",
17
+ "react/jsx-dev-runtime": "/vendor/react/react-jsx-dev-runtime.js",
18
+ "react-dom": "/vendor/react/react-dom.js",
19
+ "react-dom/client": "/vendor/react/react-dom-client.js"
16
20
  }
17
21
  }
18
22
  </script>
package/client/index.tsx CHANGED
@@ -1,13 +1,40 @@
1
+ // Must run before any tldraw module loads — see the file for why.
2
+ import './structured-clone-shim'
3
+
1
4
  import './index.css'
2
5
 
3
- // React is externalized to esm.sh (see client/externalize-react.ts + the importmap
4
- // in index.html), so Bun's bundled Fast Refresh runtime isn't bound to the React
6
+ // React is externalized to the locally-vendored ESM (see client/externalize-react.ts
7
+ // + the importmap in index.html → /vendor/react), so Bun's bundled Fast Refresh
8
+ // runtime isn't bound to the React
5
9
  // instance that actually renders the app: it registers component families but
6
10
  // performReactRefresh() no-ops, leaving stale modules mounted after an edit.
7
11
  // Downgrade HMR to plain live-reload — every hot update triggers a full page
8
12
  // reload, which re-fetches a clean bundle. Dead-code-eliminated in production.
9
13
  if (import.meta.hot) {
10
14
  import.meta.hot.on('bun:beforeUpdate', () => location.reload())
15
+
16
+ // Bun's HMR client (≤1.3.14) never re-arms `onclose` on the socket it
17
+ // creates while reconnecting, so the second disconnect in a tab's life
18
+ // (e.g. laptop sleep, then a dev-supervisor restart) silently kills
19
+ // live-reload and the tab serves a stale bundle forever. Watchdog: poll
20
+ // the shell and hard-reload when the served script generation no longer
21
+ // matches the one this page is running.
22
+ const devScript = document.querySelector<HTMLScriptElement>('[data-bun-dev-server-script]')
23
+ if (devScript) {
24
+ const scriptPath = new URL(devScript.src).pathname
25
+ const checkStale = async () => {
26
+ try {
27
+ const html = await (await fetch('/', { cache: 'no-store' })).text()
28
+ if (!html.includes(scriptPath)) location.reload()
29
+ } catch {
30
+ // server mid-restart — the next tick will catch it
31
+ }
32
+ }
33
+ setInterval(checkStale, 5_000)
34
+ document.addEventListener('visibilitychange', () => {
35
+ if (document.visibilityState === 'visible') checkStale()
36
+ })
37
+ }
11
38
  }
12
39
 
13
40
  export async function init(el: HTMLElement) {
@@ -1,4 +1,4 @@
1
- import { type ReactNode, createContext, useContext, useEffect } from 'react'
1
+ import { type ReactNode, createContext, useContext } from 'react'
2
2
 
3
3
  const WorkspaceContext = createContext<string>('default')
4
4
 
@@ -11,14 +11,11 @@ type WorkspaceProps = {
11
11
  children: ReactNode
12
12
  }
13
13
 
14
- // Provides the active workspace id to the tree (read by chat + widget hooks).
14
+ // Provides the active workspace id to the tree (read by chat + applet hooks).
15
15
  // Data loading lives in React Query now (see WorkspaceLayoutProvider and the
16
- // useWorkspace* query hooks) — this only carries the id.
16
+ // useWorkspace* query hooks) — this only carries the id. Applet bundles no
17
+ // longer read a window global for their workspace: the serve route bakes the
18
+ // API base into each bundle's RPC/fileUrl calls.
17
19
  export function Workspace({ id, children }: WorkspaceProps) {
18
- useEffect(() => {
19
- // Expose to widget RPC bundles
20
- ;(window as unknown as Record<string, unknown>).__MEI_WS__ = id
21
- }, [id])
22
-
23
20
  return <WorkspaceContext value={id}>{children}</WorkspaceContext>
24
21
  }
@@ -1,4 +1,4 @@
1
- import { type ReactNode, createContext, useCallback, useContext, useRef } from 'react'
1
+ import { type ReactNode, createContext, useCallback, useContext, useMemo, useRef } from 'react'
2
2
 
3
3
  import { useQueryClient } from '@tanstack/react-query'
4
4
 
@@ -8,7 +8,7 @@ import {
8
8
  useWorkspaceLayout,
9
9
  workspaceKeys
10
10
  } from '@/client/api/workspaces'
11
- import type { WorkspaceLayout } from '@/lib/types'
11
+ import type { WorkspaceLayout, WorkspaceType } from '@/lib/types'
12
12
 
13
13
  const DEFAULT_LAYOUT: WorkspaceLayout = {
14
14
  version: 1,
@@ -25,7 +25,17 @@ type WorkspaceLayoutContextValue = {
25
25
  setLayout: (update: Partial<WorkspaceLayout>) => void
26
26
  // Workspace metadata that rides along on the layout endpoint.
27
27
  name: string | null
28
+ // Custom workspace icon (base64 data URL), or null to use the provider icon.
29
+ icon: string | null
28
30
  cwd: string | null
31
+ // The agent backend (claude-code / openclaw / hermes …). Exposed here so
32
+ // components like McpMenu read it from the shared layout query instead of
33
+ // spawning their own observer (a second observer that remounts would trigger
34
+ // `refetchOnMount` and clobber an in-flight optimistic layout update).
35
+ provider: WorkspaceType | null
36
+ // The workspace's registry id (the route param), so descendants can key
37
+ // their own queries (e.g. the model picker) without prop-drilling.
38
+ workspaceId: string
29
39
  isLoading: boolean
30
40
  }
31
41
 
@@ -40,7 +50,7 @@ export function useWorkspaceLayoutCtx(): WorkspaceLayoutContextValue {
40
50
  // Strip the server-only metadata so what we PUT back (and expose as `layout`)
41
51
  // is just the persisted `WorkspaceLayout`.
42
52
  function stripMeta(data: WorkspaceLayoutResponse): WorkspaceLayout {
43
- const { cwd: _cwd, name: _name, agentId: _agentId, ...layout } = data
53
+ const { cwd: _cwd, name: _name, provider: _provider, agentId: _agentId, ...layout } = data
44
54
  return layout
45
55
  }
46
56
 
@@ -80,13 +90,23 @@ export function WorkspaceLayoutProvider({ id, children }: WorkspaceLayoutProvide
80
90
  [id, qc]
81
91
  )
82
92
 
83
- const value: WorkspaceLayoutContextValue = {
84
- layout: query.data ? stripMeta(query.data) : DEFAULT_LAYOUT,
85
- setLayout,
86
- name: query.data?.name ?? null,
87
- cwd: query.data?.cwd ?? null,
88
- isLoading: query.isLoading
89
- }
93
+ // Memoized so the context value keeps a stable identity across unrelated
94
+ // renders — otherwise every consumer (WorkspaceView, Widgets, ModelPicker,
95
+ // TurnView, …) would re-render whenever this provider re-renders. `setLayout`
96
+ // is already stable; the rest derive from `query.data`.
97
+ const value = useMemo<WorkspaceLayoutContextValue>(
98
+ () => ({
99
+ layout: query.data ? stripMeta(query.data) : DEFAULT_LAYOUT,
100
+ setLayout,
101
+ name: query.data?.name ?? null,
102
+ icon: query.data?.icon ?? null,
103
+ cwd: query.data?.cwd ?? null,
104
+ provider: query.data?.provider ?? null,
105
+ workspaceId: id,
106
+ isLoading: query.isLoading
107
+ }),
108
+ [query.data, query.isLoading, setLayout, id]
109
+ )
90
110
 
91
111
  return <WorkspaceLayoutContext value={value}>{children}</WorkspaceLayoutContext>
92
112
  }
@@ -0,0 +1,54 @@
1
+ // Shared load cache for agent-authored applets (widgets / views).
2
+ //
3
+ // An applet is loaded as an ESM module via dynamic `import()`. The browser
4
+ // memoizes a module by its exact URL forever, so to pick up a rebuilt bundle the
5
+ // URL must change — we vary a `?v=<n>` per applet. The catch: a workspace shows
6
+ // one view (or the widget grid) at a time, so most applets are UNMOUNTED at any
7
+ // moment. If invalidation lived only in the mounted component, an applet rebuilt
8
+ // while its tab is in the background would never bump its version and would be
9
+ // served stale from cache on the next mount.
10
+ //
11
+ // So the cache + version registry live here, module-level and mount-independent:
12
+ // a workspace-wide listener invalidates on every `*:updated` event (see
13
+ // `useAppletCacheInvalidation`), and the per-applet hook invalidates the mounted
14
+ // one too. Either path bumps the version + drops the cached module, so the next
15
+ // load() fetches the rebuilt bundle.
16
+ export type AppletSegment = 'widgets' | 'views'
17
+
18
+ // `${segment}/${workspaceId}/${name}` — namespaced so a widget and a view (or
19
+ // two workspaces) sharing a name never collide.
20
+ export function appletKey(segment: AppletSegment, workspaceId: string, name: string): string {
21
+ return `${segment}/${workspaceId}/${name}`
22
+ }
23
+
24
+ const versions = new Map<string, number>()
25
+ const moduleCache = new Map<string, Promise<unknown>>()
26
+
27
+ export function appletVersion(segment: AppletSegment, workspaceId: string, name: string): number {
28
+ return versions.get(appletKey(segment, workspaceId, name)) ?? 0
29
+ }
30
+
31
+ // The cache-busting import URL for an applet's entry at its current version.
32
+ // Assets + chunks resolve module-relative from the entry (via import.meta.url),
33
+ // so they don't inherit `?v` and aren't re-fetched needlessly.
34
+ export function appletUrl(segment: AppletSegment, workspaceId: string, name: string): string {
35
+ return `/api/workspaces/${workspaceId}/${segment}/${name}/index.js?v=${appletVersion(segment, workspaceId, name)}`
36
+ }
37
+
38
+ export function getCachedApplet(key: string): Promise<unknown> | undefined {
39
+ return moduleCache.get(key)
40
+ }
41
+
42
+ export function setCachedApplet(key: string, mod: Promise<unknown>): void {
43
+ moduleCache.set(key, mod)
44
+ }
45
+
46
+ // Drop the cached module and bump the load version for one applet, so the next
47
+ // load() — including a fresh mount of a previously-backgrounded tab — fetches the
48
+ // rebuilt bundle instead of the memoized old one. Safe (and intended) to call
49
+ // when nothing for this applet is mounted.
50
+ export function invalidateApplet(segment: AppletSegment, workspaceId: string, name: string): void {
51
+ const key = appletKey(segment, workspaceId, name)
52
+ moduleCache.delete(key)
53
+ versions.set(key, (versions.get(key) ?? 0) + 1)
54
+ }
@@ -0,0 +1,237 @@
1
+ import type { QueryClient } from '@tanstack/react-query'
2
+
3
+ import { workspaceKeys } from '@/client/api/workspaces'
4
+ import { getScratchExecutor } from '@/client/lib/scratch-executor'
5
+ import { liveStore } from '@/client/store/live'
6
+ import { applyEvent } from '@/lib/format'
7
+ import type {
8
+ ClientMessage,
9
+ PreviewFrame,
10
+ ScratchOp,
11
+ StreamEvent,
12
+ ThreadConfig,
13
+ ViewState
14
+ } from '@/lib/types'
15
+
16
+ // App-wide chat connection: ONE WebSocket for the whole client, opened once at
17
+ // startup and never torn down on navigation. Every server frame is tagged with
18
+ // `workspaceId`, so a single socket serves every workspace and the client routes
19
+ // each frame to the right `(workspaceId, sessionId)` slice — live transcript
20
+ // deltas into the React Query cache, status/error/rename into the live store.
21
+ //
22
+ // Socket identity is tracked by a monotonic `generation`: each socket captures
23
+ // the generation at creation and every callback bails if it's no longer current,
24
+ // so a delayed close/open from a superseded socket can't corrupt live state.
25
+
26
+ let qc: QueryClient | null = null
27
+ let socket: WebSocket | null = null
28
+ let generation = 0
29
+ let reconnectTimer: ReturnType<typeof setTimeout> | null = null
30
+ const queue: ClientMessage[] = []
31
+ let onWorkspaceSwitch: ((workspaceId: string) => void) | null = null
32
+ let sweepTimer: ReturnType<typeof setInterval> | null = null
33
+
34
+ // TTL backstop for live previews. Every clear path (turn arrival, run end,
35
+ // reconnect) is exact and should fire first; this only reaps a preview whose
36
+ // clear was somehow missed, so it can be generous.
37
+ const PREVIEW_TTL_MS = 15_000
38
+
39
+ export function initConnection(queryClient: QueryClient) {
40
+ qc = queryClient
41
+ if (!sweepTimer) {
42
+ sweepTimer = setInterval(
43
+ () => liveStore.getState().sweepPreviews(PREVIEW_TTL_MS, Date.now()),
44
+ 5_000
45
+ )
46
+ }
47
+ if (socket) return // already connected (mount/StrictMode re-invoke safety)
48
+ connect()
49
+ }
50
+
51
+ function connect() {
52
+ const myGen = ++generation
53
+ if (reconnectTimer) {
54
+ clearTimeout(reconnectTimer)
55
+ reconnectTimer = null
56
+ }
57
+
58
+ const s = new WebSocket(`ws://${location.host}/ws`)
59
+ socket = s
60
+
61
+ s.onopen = () => {
62
+ if (generation !== myGen) {
63
+ s.close()
64
+ return
65
+ }
66
+ for (const m of queue) s.send(JSON.stringify(m))
67
+ queue.length = 0
68
+ // Heal any deltas missed while disconnected: refetch every live transcript.
69
+ // No-op on the first connect (nothing cached yet).
70
+ qc?.invalidateQueries({ queryKey: ['workspaces', 'events'] })
71
+ // Any in-flight preview from before the drop is superseded by that refetch
72
+ // (which returns the authoritative disk state) — drop them all so a frozen
73
+ // half-streamed preview can't linger over the healed transcript.
74
+ liveStore.getState().clearAllPreviews()
75
+ }
76
+
77
+ s.onmessage = e => {
78
+ if (generation !== myGen) return
79
+ let data: unknown
80
+ try {
81
+ data = JSON.parse(e.data)
82
+ } catch {
83
+ return
84
+ }
85
+ handleFrame(data as Record<string, unknown>)
86
+ }
87
+
88
+ s.onclose = () => {
89
+ if (generation !== myGen) return
90
+ socket = null
91
+ reconnectTimer = setTimeout(connect, 1000)
92
+ }
93
+
94
+ s.onerror = () => s.close()
95
+ }
96
+
97
+ export function handleFrame(data: Record<string, unknown>) {
98
+ const store = liveStore.getState()
99
+
100
+ // Control frames first.
101
+ if (data.type === 'status_snapshot') {
102
+ store.reconcileProcessing(
103
+ (data.running as { workspaceId: string; sessionId: string }[] | undefined) ?? []
104
+ )
105
+ return
106
+ }
107
+ if (data.type === 'status') {
108
+ const workspaceId = data.workspaceId as string
109
+ const sessionId = data.sessionId as string
110
+ const processing = data.processing as boolean
111
+ store.setProcessing(workspaceId, sessionId, processing)
112
+ // Run fully ended → any leftover preview for this session is stale (its
113
+ // finalized turns already arrived). Belt for a per-message clear that was
114
+ // missed (e.g. a turn that carried no apiMessageId).
115
+ if (!processing) store.clearPreviewsForSession(workspaceId, sessionId)
116
+ return
117
+ }
118
+ if (data.type === 'preview') {
119
+ const frame = data as unknown as PreviewFrame
120
+ // Only hold previews for a thread whose transcript is loaded (mirrors
121
+ // patchView): keeps the store bounded and never renders a preview over a
122
+ // history-less background session that would then never refetch.
123
+ const key = workspaceKeys.events(frame.workspaceId, frame.sessionId)
124
+ if (qc?.getQueryData(key) === undefined) return
125
+ store.setPreview({
126
+ workspaceId: frame.workspaceId,
127
+ sessionId: frame.sessionId,
128
+ messageId: frame.messageId,
129
+ parentToolUseId: frame.parentToolUseId,
130
+ blocks: frame.blocks
131
+ })
132
+ return
133
+ }
134
+ if (data.type === 'session_renamed') {
135
+ const workspaceId = data.workspaceId as string
136
+ const from = data.from as string
137
+ const to = data.to as string
138
+ store.renameSession(workspaceId, from, to)
139
+ // Move the cached transcript from the client's temp id to the real one.
140
+ const prev = qc?.getQueryData<ViewState>(workspaceKeys.events(workspaceId, from))
141
+ if (prev !== undefined) {
142
+ qc?.setQueryData(workspaceKeys.events(workspaceId, to), prev)
143
+ qc?.removeQueries({ queryKey: workspaceKeys.events(workspaceId, from) })
144
+ }
145
+ // Likewise move any per-thread config the picker wrote under the temp id, so
146
+ // a model/effort change made before the rename lands isn't stranded. The
147
+ // server migrates the stored config in renameSession to match.
148
+ const cfg = qc?.getQueryData<ThreadConfig>(workspaceKeys.threadConfig(workspaceId, from))
149
+ if (cfg !== undefined) {
150
+ qc?.setQueryData(workspaceKeys.threadConfig(workspaceId, to), cfg)
151
+ qc?.removeQueries({ queryKey: workspaceKeys.threadConfig(workspaceId, from) })
152
+ }
153
+ // The real id now exists on disk — refresh the thread list so it appears.
154
+ qc?.invalidateQueries({ queryKey: workspaceKeys.sessions(workspaceId) })
155
+ return
156
+ }
157
+ if (data.type === 'workspace:switch') {
158
+ onWorkspaceSwitch?.(data.workspaceId as string)
159
+ return
160
+ }
161
+
162
+ // A relayed Scratchpad op from `moi scratch`. Only run it if THIS tab has a
163
+ // live editor for that workspace; otherwise ignore (another tab — or none —
164
+ // handles it, and the server times out if no tab answers). Ids are
165
+ // deterministic, so if several tabs run it they converge; first reply wins.
166
+ if (data.type === 'scratchpad:op') {
167
+ const run = getScratchExecutor(data.workspaceId as string)
168
+ if (!run) return
169
+ const opId = data.opId as string
170
+ run(data.op as ScratchOp).then(
171
+ result => sendMessage({ type: 'scratchpad:op-result', opId, result }),
172
+ err =>
173
+ sendMessage({
174
+ type: 'scratchpad:op-result',
175
+ opId,
176
+ error: err instanceof Error ? err.message : String(err)
177
+ })
178
+ )
179
+ return
180
+ }
181
+
182
+ // StreamEvent frames — tagged with workspaceId + sessionId.
183
+ const workspaceId = data.workspaceId as string | undefined
184
+ const sessionId = data.sessionId as string | undefined
185
+ if (!workspaceId || !sessionId) return
186
+ const kind = data.kind
187
+
188
+ if (kind === 'snapshot' || kind === 'turn' || kind === 'notice' || kind === 'result') {
189
+ patchView(workspaceId, sessionId, data as unknown as StreamEvent)
190
+ // The real turn superseding a live preview is the clean handoff: drop the
191
+ // preview for that exact message id the instant its finalized turn lands, so
192
+ // there's no double-render and no flicker (both updates commit together).
193
+ if (kind === 'turn') {
194
+ const mid = (data as unknown as { turn?: { meta?: { apiMessageId?: string } } }).turn?.meta
195
+ ?.apiMessageId
196
+ if (mid) store.clearPreview(mid)
197
+ }
198
+ // A `result` ends the turn — sweep any preview that never got an exact clear.
199
+ if (kind === 'result') store.clearPreviewsForSession(workspaceId, sessionId)
200
+ }
201
+ if (kind === 'error' && typeof data.content === 'string') {
202
+ store.setError(workspaceId, sessionId, data.content)
203
+ store.clearPreviewsForSession(workspaceId, sessionId)
204
+ }
205
+ if (kind === 'stopped') {
206
+ store.setProcessing(workspaceId, sessionId, false)
207
+ store.clearPreviewsForSession(workspaceId, sessionId)
208
+ }
209
+ }
210
+
211
+ // Fold a delta into a thread's cached transcript — but only if that transcript
212
+ // is already loaded/primed. A never-viewed background session has no cache
213
+ // entry; we deliberately skip it so a stray mid-run delta can't seed a partial,
214
+ // history-less view that would then never refetch. It loads in full from disk
215
+ // when the user actually opens it.
216
+ function patchView(workspaceId: string, sessionId: string, ev: StreamEvent) {
217
+ const queryKey = workspaceKeys.events(workspaceId, sessionId)
218
+ const existing = qc?.getQueryData<ViewState>(queryKey)
219
+ if (existing === undefined) return
220
+ qc?.setQueryData<ViewState>(queryKey, applyEvent(existing, ev))
221
+ }
222
+
223
+ export function sendMessage(msg: ClientMessage) {
224
+ if (socket && socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(msg))
225
+ else queue.push(msg)
226
+ }
227
+
228
+ export function setWorkspaceSwitchHandler(fn: ((workspaceId: string) => void) | null) {
229
+ onWorkspaceSwitch = fn
230
+ }
231
+
232
+ // Test seam: inject the QueryClient the frame handler reads, without opening a
233
+ // socket (the browser-only `connect()` path). Production always goes through
234
+ // `initConnection`.
235
+ export function __setQueryClientForTests(client: QueryClient | null) {
236
+ qc = client
237
+ }
@@ -0,0 +1,10 @@
1
+ // Personal / dev feature flags — flip these in code, not in the UI.
2
+ //
3
+ // These are compile-time constants (inlined into the client bundle), not
4
+ // per-thread or per-workspace settings. Change one and rebuild the client.
5
+
6
+ // Live token-by-token streaming of assistant responses. When true, the client
7
+ // asks the server to stream partial messages (only honored by providers that
8
+ // report `supportsStreaming` — Claude Code; ignored elsewhere). When false,
9
+ // responses arrive as whole blocks, exactly as before streaming existed.
10
+ export const STREAM_RESPONSES = true