moi-computer 0.0.2 → 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 (246) hide show
  1. package/bin/moi.mjs +3 -1
  2. package/bunfig.toml +4 -0
  3. package/client/api/workspaces.ts +277 -6
  4. package/client/assets/mcp/agentation.png +0 -0
  5. package/client/assets/mcp/airtable.png +0 -0
  6. package/client/assets/mcp/apollo.png +0 -0
  7. package/client/assets/mcp/asana.png +0 -0
  8. package/client/assets/mcp/box.png +0 -0
  9. package/client/assets/mcp/chrome.svg +33 -0
  10. package/client/assets/mcp/clickup.png +0 -0
  11. package/client/assets/mcp/cloudflare.png +0 -0
  12. package/client/assets/mcp/context7.png +0 -0
  13. package/client/assets/mcp/datadog.png +0 -0
  14. package/client/assets/mcp/dropbox.png +0 -0
  15. package/client/assets/mcp/elevenlabs.png +0 -0
  16. package/client/assets/mcp/exa.png +0 -0
  17. package/client/assets/mcp/firecrawl.png +0 -0
  18. package/client/assets/mcp/gmail.png +0 -0
  19. package/client/assets/mcp/googlecalendar.png +0 -0
  20. package/client/assets/mcp/googledrive.png +0 -0
  21. package/client/assets/mcp/grafana.png +0 -0
  22. package/client/assets/mcp/huggingface.png +0 -0
  23. package/client/assets/mcp/intercom.png +0 -0
  24. package/client/assets/mcp/monday.png +0 -0
  25. package/client/assets/mcp/mongodb.png +0 -0
  26. package/client/assets/mcp/paper.png +0 -0
  27. package/client/assets/mcp/paypal.png +0 -0
  28. package/client/assets/mcp/perplexity.png +0 -0
  29. package/client/assets/mcp/postgresql.png +0 -0
  30. package/client/assets/mcp/posthog.png +0 -0
  31. package/client/assets/mcp/puppeteer.png +0 -0
  32. package/client/assets/mcp/railway.png +0 -0
  33. package/client/assets/mcp/redis.png +0 -0
  34. package/client/assets/mcp/salesforce.png +0 -0
  35. package/client/assets/mcp/shopify.png +0 -0
  36. package/client/assets/mcp/snowflake.png +0 -0
  37. package/client/assets/mcp/telegram.png +0 -0
  38. package/client/assets/mcp/twilio.png +0 -0
  39. package/client/assets/mcp/zapier.png +0 -0
  40. package/client/components/App.tsx +7 -1
  41. package/client/components/BottomPanel.tsx +2 -2
  42. package/client/components/ChatInput.tsx +195 -14
  43. package/client/components/ChatPanel.tsx +118 -49
  44. package/client/components/ChatPopup.tsx +2 -2
  45. package/client/components/CustomizePanel.tsx +8 -8
  46. package/client/components/HiddenPanel.tsx +1 -1
  47. package/client/components/HomePage.tsx +1 -1
  48. package/client/components/IconMcp.tsx +21 -0
  49. package/client/components/MarkdownContent.tsx +2 -2
  50. package/client/components/McpMenu.tsx +125 -0
  51. package/client/components/ModelPicker.tsx +147 -0
  52. package/client/components/Scratchpad.tsx +775 -0
  53. package/client/components/ShimmerText.tsx +20 -0
  54. package/client/components/ThreadSelector.tsx +2 -2
  55. package/client/components/TurnView.tsx +114 -534
  56. package/client/components/WidgetErrorBoundary.tsx +2 -2
  57. package/client/components/WidgetFrame.tsx +1 -1
  58. package/client/components/WidgetShell.tsx +2 -2
  59. package/client/components/Widgets.tsx +2 -2
  60. package/client/components/WorkspacePreview.tsx +3 -3
  61. package/client/components/WorkspacesPage.tsx +28 -20
  62. package/client/components/layout/SidebarLayout.tsx +24 -15
  63. package/client/components/playground/PixelPainter.tsx +2 -2
  64. package/client/components/playground/PlaygroundPage.tsx +1 -1
  65. package/client/components/playground/ToolCallsPage.tsx +81 -0
  66. package/client/components/routes/workspace/[id].tsx +534 -141
  67. package/client/components/routes/workspace/create.tsx +155 -0
  68. package/client/components/settings/IconPicker.tsx +590 -0
  69. package/client/components/settings/SettingsPages.tsx +307 -0
  70. package/client/components/settings/WorkspaceSettings.tsx +92 -0
  71. package/client/components/tool-group/CodeBlock.tsx +41 -0
  72. package/client/components/tool-group/Collapse.tsx +28 -0
  73. package/client/components/tool-group/ReadImagePreview.tsx +46 -0
  74. package/client/components/tool-group/SubagentCard.tsx +135 -0
  75. package/client/components/tool-group/TimelineRow.tsx +147 -0
  76. package/client/components/tool-group/ToolCallGroup.tsx +231 -0
  77. package/client/components/tool-group/ToolOutput.tsx +139 -0
  78. package/client/components/tool-group/detect.ts +93 -0
  79. package/client/components/tool-group/fixtures.ts +315 -0
  80. package/client/components/tool-group/format.ts +211 -0
  81. package/client/components/tool-group/index.ts +9 -0
  82. package/client/components/ui/button.tsx +4 -4
  83. package/client/components/ui/dialog.tsx +58 -0
  84. package/client/components/ui/dropdown-menu.tsx +9 -9
  85. package/client/components/ui/hover-card.tsx +44 -0
  86. package/client/components/ui/popover.tsx +1 -1
  87. package/client/components/ui/switch.tsx +23 -0
  88. package/client/components/ui/tooltip.tsx +54 -0
  89. package/client/externalize-react.ts +11 -5
  90. package/client/hooks/useApplet.ts +117 -0
  91. package/client/hooks/useChat.ts +162 -62
  92. package/client/hooks/useMeiEvents.ts +9 -2
  93. package/client/hooks/useStickToBottom.ts +86 -0
  94. package/client/hooks/useWorkspaceTheme.ts +8 -2
  95. package/client/index.css +49 -3
  96. package/client/index.html +22 -18
  97. package/client/index.tsx +29 -2
  98. package/client/lib/WorkspaceContext.tsx +5 -8
  99. package/client/lib/WorkspaceLayoutContext.tsx +30 -10
  100. package/client/lib/applet-cache.ts +54 -0
  101. package/client/lib/connection.ts +237 -0
  102. package/client/lib/flags.ts +10 -0
  103. package/client/lib/mcp-icons.ts +142 -10
  104. package/client/lib/preview-turn.ts +37 -0
  105. package/client/lib/render-icon.ts +173 -0
  106. package/client/lib/scratch-executor.ts +20 -0
  107. package/client/lib/uploads.ts +18 -0
  108. package/client/main.tsx +5 -0
  109. package/client/store/live.ts +282 -0
  110. package/client/structured-clone-shim.ts +14 -0
  111. package/client/theme.css +2 -2
  112. package/client/vendor/emojibase/en/data.json +1 -0
  113. package/client/vendor/emojibase/en/messages.json +1 -0
  114. package/client/vendor/react/development/_impl/react-dom-client.js +15871 -0
  115. package/client/vendor/react/development/_impl/react-dom.js +223 -0
  116. package/client/vendor/react/development/_impl/react-jsx-dev-runtime.js +256 -0
  117. package/client/vendor/react/development/_impl/react-jsx-runtime.js +260 -0
  118. package/client/vendor/react/development/_impl/react.js +863 -0
  119. package/client/vendor/react/development/react-dom-client.js +6 -0
  120. package/client/vendor/react/development/react-dom.js +17 -0
  121. package/client/vendor/react/development/react-jsx-dev-runtime.js +5 -0
  122. package/client/vendor/react/development/react-jsx-runtime.js +6 -0
  123. package/client/vendor/react/development/react.js +47 -0
  124. package/client/vendor/react/production/_impl/react-dom-client.js +10361 -0
  125. package/client/vendor/react/production/_impl/react-dom.js +184 -0
  126. package/client/vendor/react/production/_impl/react-jsx-dev-runtime.js +37 -0
  127. package/client/vendor/react/production/_impl/react-jsx-runtime.js +60 -0
  128. package/client/vendor/react/production/_impl/react.js +428 -0
  129. package/client/vendor/react/production/react-dom-client.js +6 -0
  130. package/client/vendor/react/production/react-dom.js +17 -0
  131. package/client/vendor/react/production/react-jsx-dev-runtime.js +5 -0
  132. package/client/vendor/react/production/react-jsx-runtime.js +6 -0
  133. package/client/vendor/react/production/react.js +47 -0
  134. package/dist/agentation-4s0nn45p.png +0 -0
  135. package/dist/airtable-hsa66v6q.png +0 -0
  136. package/dist/apollo-2ed5dy2d.png +0 -0
  137. package/dist/asana-tvgtwbx2.png +0 -0
  138. package/dist/atlassian-b3tq39hs.png +0 -0
  139. package/dist/box-w3n36t5g.png +0 -0
  140. package/dist/chrome-tspm94rw.svg +33 -0
  141. package/dist/chunk-kc6e9nd4.css +1 -0
  142. package/dist/chunk-yf3p7qg7.js +673 -0
  143. package/dist/claude-z2xnay0d.svg +3 -0
  144. package/dist/clickup-qqrqqvqb.png +0 -0
  145. package/dist/cloudflare-j9p931v6.png +0 -0
  146. package/dist/context7-8ht0xjfy.png +0 -0
  147. package/dist/datadog-70ne3yzt.png +0 -0
  148. package/dist/discord-vejhptwx.png +0 -0
  149. package/dist/dropbox-4m5s9mgr.png +0 -0
  150. package/dist/elevenlabs-2nzzej1t.png +0 -0
  151. package/dist/exa-qqj3vr0x.png +0 -0
  152. package/dist/favicon-nbmyjfjh.png +0 -0
  153. package/dist/figma-y9898rry.png +0 -0
  154. package/dist/firecrawl-w2t8nehx.png +0 -0
  155. package/dist/github-av5r5y3e.png +0 -0
  156. package/dist/gitlab-4pv5vm6b.png +0 -0
  157. package/dist/gmail-sg6a5v3x.png +0 -0
  158. package/dist/googlecalendar-nqhh2v7r.png +0 -0
  159. package/dist/googledrive-6s8xyab7.png +0 -0
  160. package/dist/grafana-1yfsnwr6.png +0 -0
  161. package/dist/granola-7j3b0nk2.png +0 -0
  162. package/dist/hermes-nous-pznd63x9.png +0 -0
  163. package/dist/hubspot-hghcmc2t.png +0 -0
  164. package/dist/huggingface-kxzaxj83.png +0 -0
  165. package/dist/index.html +47 -0
  166. package/dist/intercom-td763jt8.png +0 -0
  167. package/dist/linear-v9s3az2d.png +0 -0
  168. package/dist/monday-jdbs4wwf.png +0 -0
  169. package/dist/mongodb-emzxvhd5.png +0 -0
  170. package/dist/neon-zj4qar44.png +0 -0
  171. package/dist/notion-w034c0b8.png +0 -0
  172. package/dist/openclaw-a2pyfhpn.svg +22 -0
  173. package/dist/paper-zbt34fab.png +0 -0
  174. package/dist/paypal-kwwf7xsc.png +0 -0
  175. package/dist/perplexity-4y63rxvj.png +0 -0
  176. package/dist/postgresql-qsspbsr1.png +0 -0
  177. package/dist/posthog-sphppc4w.png +0 -0
  178. package/dist/puppeteer-2xjt1a9b.png +0 -0
  179. package/dist/railway-834de8d2.png +0 -0
  180. package/dist/redis-spm6w2m1.png +0 -0
  181. package/dist/salesforce-1mk56v4z.png +0 -0
  182. package/dist/sentry-hdwpmvek.png +0 -0
  183. package/dist/shopify-90dadaav.png +0 -0
  184. package/dist/slack-1c1wj62s.png +0 -0
  185. package/dist/snowflake-hfpykpgy.png +0 -0
  186. package/dist/stripe-zrfaqbj3.png +0 -0
  187. package/dist/supabase-4vg33zf2.png +0 -0
  188. package/dist/telegram-v6tjyrs7.png +0 -0
  189. package/dist/twilio-dpyjdwpj.png +0 -0
  190. package/dist/vercel-7d0ssw28.png +0 -0
  191. package/dist/zapier-p67qfch0.png +0 -0
  192. package/lib/attachment-note.ts +48 -0
  193. package/lib/claude-adapter.ts +219 -29
  194. package/lib/format.ts +32 -0
  195. package/lib/types.ts +314 -6
  196. package/package.json +21 -31
  197. package/server/CLAUDE.md +3 -0
  198. package/server/agent.ts +25 -118
  199. package/server/api.ts +593 -0
  200. package/server/applets.ts +396 -0
  201. package/server/build-applet.ts +580 -0
  202. package/server/cc-session.ts +611 -0
  203. package/server/cli-colors.ts +17 -0
  204. package/server/cli-ui.ts +52 -0
  205. package/server/cli.ts +970 -72
  206. package/server/control.ts +166 -19
  207. package/server/debug.ts +10 -0
  208. package/server/events.ts +24 -0
  209. package/server/functions-worker.ts +18 -2
  210. package/server/functions.ts +59 -12
  211. package/server/icon.ts +13 -0
  212. package/server/layout.ts +25 -3
  213. package/server/mcp.ts +125 -0
  214. package/server/moi-scaffold.ts +85 -0
  215. package/server/openclaw-session.ts +41 -10
  216. package/server/openclaw.ts +22 -0
  217. package/server/preview.ts +70 -0
  218. package/server/registry.ts +32 -2
  219. package/server/scratchpad-executor.ts +380 -0
  220. package/server/scratchpad-relay.ts +45 -0
  221. package/server/scratchpad.ts +171 -0
  222. package/server/skill-version.ts +146 -0
  223. package/server/skills-template.ts +6 -1
  224. package/server/state.ts +22 -36
  225. package/server/static.ts +23 -0
  226. package/server/status.ts +94 -0
  227. package/server/thread-config.ts +125 -0
  228. package/server/uploads.ts +0 -0
  229. package/server/vendor.ts +63 -0
  230. package/server/views.ts +0 -0
  231. package/server/web.ts +113 -223
  232. package/server/widgets.ts +52 -142
  233. package/server/workspace-config.ts +37 -0
  234. package/server/workspace-env.ts +407 -0
  235. package/server/workspace-init.ts +66 -0
  236. package/workspace/.claude/skills/moi-workspace/DESIGN.md +109 -0
  237. package/workspace/.claude/skills/moi-workspace/SCRATCHPAD.md +57 -0
  238. package/workspace/.claude/skills/moi-workspace/SKILL.md +252 -0
  239. package/workspace/.claude/skills/moi-workspace/VIEW-DESIGN.md +22 -0
  240. package/client/hooks/useWidget.ts +0 -72
  241. package/client/hooks/useWidgetList.ts +0 -30
  242. package/client/lib/ws.ts +0 -129
  243. package/client/store/chat.tsx +0 -162
  244. package/server/build-widget.ts +0 -343
  245. package/workspace/.claude/skills/widgets/DESIGN.md +0 -630
  246. package/workspace/.claude/skills/widgets/SKILL.md +0 -176
@@ -0,0 +1,146 @@
1
+ // Skill versioning for Case 1: a workspace's installed skill copy drifting
2
+ // behind the version this CLI ships. The CLI is "stupid" — it only reads the
3
+ // version marker stamped in each skill's `SKILL.md`, compares the workspace
4
+ // copy against the bundled copy, and reports drift. Updating is never
5
+ // automatic: the agent (which reads command output) sees the notice and runs
6
+ // `moi skill update`. See `moi skill` in `cli.ts`.
7
+ import { readdir } from 'node:fs/promises'
8
+ import { join } from 'node:path'
9
+
10
+ import type { WorkspaceType } from '@/lib/types'
11
+
12
+ import { findWorkspaceForPath, liftToWorkspaceRoot, listWorkspaces } from './registry'
13
+ import { BUNDLED_SKILLS_DIR } from './skills-template'
14
+ import { skillsDirFor } from './workspace-init'
15
+
16
+ export type SkillStatus = {
17
+ name: string
18
+ // Version stamped in the workspace's copy. `null` means absent — either the
19
+ // skill isn't installed or it predates skill versioning (treated as behind).
20
+ installed: string | null
21
+ // Version shipped with this CLI. `null` only if a bundled skill lacks a stamp.
22
+ bundled: string | null
23
+ }
24
+
25
+ // The version is stamped as a self-contained marker in SKILL.md, e.g.
26
+ // `<moi-skill version="0.1.0" />`, rather than in YAML frontmatter. SKILL.md
27
+ // frontmatter is NOT reliably strict YAML — the free-text `description` routinely
28
+ // contains `: ` and other tokens that make real parsers reject the block — so a
29
+ // controlled, unambiguous marker we own is both simpler and more robust than
30
+ // scraping the frontmatter. Returns `null` when the file or marker is missing.
31
+ const VERSION_MARKER = /<moi-skill\b[^>]*\bversion="([^"]+)"/
32
+
33
+ export async function readSkillVersion(skillMdPath: string): Promise<string | null> {
34
+ const file = Bun.file(skillMdPath)
35
+ if (!(await file.exists())) return null
36
+ const m = (await file.text()).match(VERSION_MARKER)
37
+ return m ? m[1] : null
38
+ }
39
+
40
+ // Bun.semver (built-in: `order` + `satisfies`) isn't in this repo's bun-types
41
+ // yet, so reach it through a narrow typed view rather than `any`.
42
+ const semver = (
43
+ Bun as unknown as {
44
+ semver: {
45
+ order(a: string, b: string): -1 | 0 | 1
46
+ satisfies(v: string, range: string): boolean
47
+ }
48
+ }
49
+ ).semver
50
+
51
+ function isValidVersion(v: string): boolean {
52
+ try {
53
+ semver.order(v, v)
54
+ return true
55
+ } catch {
56
+ return false
57
+ }
58
+ }
59
+
60
+ // Compare an installed version against the bundled one with Bun's semver.
61
+ // `behind` = bundled is strictly newer; `minorBehind` = that gap is at least a
62
+ // minor bump (patch gaps stay silent). `~installed` spans installed's whole
63
+ // major.minor, so a bundled version outside it is a minor-or-major bump. A
64
+ // missing/invalid installed counts as behind (legacy or broken stamp → prompt);
65
+ // a missing/invalid bundled never does (don't nag on our own broken ship).
66
+ function compare(
67
+ installed: string | null,
68
+ bundled: string | null
69
+ ): { behind: boolean; minorBehind: boolean } {
70
+ if (!bundled || !isValidVersion(bundled)) return { behind: false, minorBehind: false }
71
+ if (!installed || !isValidVersion(installed)) return { behind: true, minorBehind: true }
72
+ const behind = semver.order(installed, bundled) < 0
73
+ return { behind, minorBehind: behind && !semver.satisfies(bundled, `~${installed}`) }
74
+ }
75
+
76
+ // Bundled is a MINOR-or-major release ahead — surfaced to the agent. Patch bumps
77
+ // stay silent and ride along on the next minor update.
78
+ export const isMinorBehind = (installed: string | null, bundled: string | null): boolean =>
79
+ compare(installed, bundled).minorBehind
80
+
81
+ // Any difference at all, patch included — decides whether `moi skill update`
82
+ // would change anything, for status display.
83
+ export const isBehind = (installed: string | null, bundled: string | null): boolean =>
84
+ compare(installed, bundled).behind
85
+
86
+ // Skills shipped with this CLI — directory names under the bundled skills dir.
87
+ export async function bundledSkillNames(): Promise<string[]> {
88
+ try {
89
+ const entries = await readdir(BUNDLED_SKILLS_DIR, { withFileTypes: true })
90
+ return entries.filter(e => e.isDirectory()).map(e => e.name)
91
+ } catch {
92
+ return []
93
+ }
94
+ }
95
+
96
+ // Per-skill installed-vs-bundled versions for a workspace root. `type` picks
97
+ // the installed-skills location (OpenClaw keeps them in `skills/`, not
98
+ // `.claude/skills/`) — pass the registry entry's type when known.
99
+ export async function skillStatuses(
100
+ workspaceRoot: string,
101
+ type?: WorkspaceType
102
+ ): Promise<SkillStatus[]> {
103
+ const names = await bundledSkillNames()
104
+ const skillsDir = skillsDirFor(workspaceRoot, type)
105
+ return Promise.all(
106
+ names.map(async name => ({
107
+ name,
108
+ bundled: await readSkillVersion(join(BUNDLED_SKILLS_DIR, name, 'SKILL.md')),
109
+ installed: await readSkillVersion(join(skillsDir, name, 'SKILL.md'))
110
+ }))
111
+ )
112
+ }
113
+
114
+ export type ResolvedWorkspace = { root: string; type?: WorkspaceType }
115
+
116
+ // Resolve a path to its workspace root: the registered workspace that owns it
117
+ // (carrying its backend type), else lifted out of any `.moi/`, else the path
118
+ // itself. Mirrors how `moi bundle` resolves a target so `moi skill` works from
119
+ // the same places.
120
+ export async function resolveWorkspace(cwd: string): Promise<ResolvedWorkspace> {
121
+ const ws = findWorkspaceForPath(await listWorkspaces(), cwd)
122
+ if (ws) return { root: ws.path, type: ws.type }
123
+ return { root: liftToWorkspaceRoot(cwd) }
124
+ }
125
+
126
+ export async function resolveWorkspaceRoot(cwd: string): Promise<string> {
127
+ return (await resolveWorkspace(cwd)).root
128
+ }
129
+
130
+ // One-line, agent-facing notice when any installed skill is a minor+ behind the
131
+ // bundled version — else `null`. Other commands append it to their output so
132
+ // the agent reading that output knows to run `moi skill update`. Never throws:
133
+ // version checks must not break the command they ride on.
134
+ export async function staleSkillNotice(cwd: string): Promise<string | null> {
135
+ try {
136
+ const { root, type } = await resolveWorkspace(cwd)
137
+ const stale = (await skillStatuses(root, type)).filter(s =>
138
+ isMinorBehind(s.installed, s.bundled)
139
+ )
140
+ if (stale.length === 0) return null
141
+ const parts = stale.map(s => `${s.name} (${s.installed ?? 'none'} → ${s.bundled})`)
142
+ return `⚠ moi skill outdated: ${parts.join(', ')} — run \`moi skill update\` to refresh.`
143
+ } catch {
144
+ return null
145
+ }
146
+ }
@@ -9,12 +9,17 @@ import { join } from 'node:path'
9
9
  // symlinked CLI binaries still find the source tree.
10
10
  export const TEMPLATE_DIR = join(import.meta.dir, '..', 'workspace')
11
11
 
12
+ // The folder holding the skill packages this CLI ships. Each subdirectory is
13
+ // one skill (e.g. `moi-workspace/`) with its own `SKILL.md`. Source of truth
14
+ // for what `moi skill update` copies and what versions it compares against.
15
+ export const BUNDLED_SKILLS_DIR = join(TEMPLATE_DIR, '.claude', 'skills')
16
+
12
17
  // Copy each shipped skill folder into `targetSkillsDir`. Overwrites existing
13
18
  // files (e.g. on a re-install after a moi upgrade) but leaves unrelated
14
19
  // directories alone. Creates the target if missing.
15
20
  export async function installBundledSkills(targetSkillsDir: string): Promise<void> {
16
21
  await mkdir(targetSkillsDir, { recursive: true })
17
- await cp(join(TEMPLATE_DIR, '.claude', 'skills'), targetSkillsDir, {
22
+ await cp(BUNDLED_SKILLS_DIR, targetSkillsDir, {
18
23
  recursive: true,
19
24
  force: true
20
25
  })
package/server/state.ts CHANGED
@@ -1,53 +1,36 @@
1
1
  import { getSessionMessages, listSessions } from '@anthropic-ai/claude-agent-sdk'
2
2
 
3
3
  import { ClaudeAdapter } from '@/lib/claude-adapter'
4
- import type { ServerMessage, SessionInfo, StreamEvent } from '@/lib/types'
4
+ import type { BroadcastFrame, ServerMessage, SessionInfo, StreamEvent } from '@/lib/types'
5
5
 
6
- // Per-workspace connected chat clients
7
- const clientsByWorkspace = new Map<string, Set<Bun.ServerWebSocket<unknown>>>()
6
+ // The chat socket is app-wide (one per client tab, not per workspace), so a
7
+ // single set of all connected chat clients is enough. Each broadcast frame
8
+ // carries its `workspaceId`, and the client routes it.
9
+ const chatClients = new Set<Bun.ServerWebSocket<unknown>>()
8
10
 
9
- export function addClient(workspaceId: string, ws: Bun.ServerWebSocket<unknown>) {
10
- if (!clientsByWorkspace.has(workspaceId)) clientsByWorkspace.set(workspaceId, new Set())
11
- clientsByWorkspace.get(workspaceId)!.add(ws)
11
+ export function addClient(ws: Bun.ServerWebSocket<unknown>) {
12
+ chatClients.add(ws)
12
13
  }
13
14
 
14
- export function removeClient(workspaceId: string, ws: Bun.ServerWebSocket<unknown>) {
15
- clientsByWorkspace.get(workspaceId)?.delete(ws)
15
+ export function removeClient(ws: Bun.ServerWebSocket<unknown>) {
16
+ chatClients.delete(ws)
16
17
  }
17
18
 
18
- // Per-session agent state — the ONLY mutable state
19
- type Agent = { processing: boolean; abortController: AbortController | null }
20
- const agents = new Map<string, Agent>()
21
-
22
- export function getAgent(id: string): Agent {
23
- if (!agents.has(id)) agents.set(id, { processing: false, abortController: null })
24
- return agents.get(id)!
25
- }
26
-
27
- export function renameAgent(from: string, to: string) {
28
- const a = agents.get(from)
29
- if (!a) return
30
- agents.set(to, a)
31
- agents.delete(from)
19
+ // Connected chat clients (browser tabs), surfaced by /status.
20
+ export function getClientCount(): number {
21
+ return chatClients.size
32
22
  }
33
23
 
34
- export function getProcessingSessions(workspaceId: string): string[] {
35
- void workspaceId
36
- const result: string[] = []
37
- for (const [id, a] of agents) if (a.processing) result.push(id)
38
- return result
39
- }
40
-
41
- export function broadcast(workspaceId: string, msg: ServerMessage) {
42
- const json = JSON.stringify(msg)
43
- for (const ws of clientsByWorkspace.get(workspaceId) ?? []) ws.send(json)
24
+ // Stamp `workspaceId` onto the frame and fan it out to every connected chat
25
+ // client. (Phase 1: broadcast-all; Phase 2 will scope by topic subscription.)
26
+ export function broadcast(workspaceId: string, frame: BroadcastFrame) {
27
+ const json = JSON.stringify({ ...frame, workspaceId })
28
+ for (const ws of chatClients) ws.send(json)
44
29
  }
45
30
 
46
31
  export function broadcastAll(msg: ServerMessage) {
47
32
  const json = JSON.stringify(msg)
48
- for (const clients of clientsByWorkspace.values()) {
49
- for (const ws of clients) ws.send(json)
50
- }
33
+ for (const ws of chatClients) ws.send(json)
51
34
  }
52
35
 
53
36
  export function sendToClient(ws: Bun.ServerWebSocket<unknown>, msg: ServerMessage) {
@@ -78,7 +61,10 @@ export async function getSessionEvents(
78
61
  try {
79
62
  const raw = await getSessionMessages(sessionId, { dir: workspacePath })
80
63
  for (const msg of raw) {
81
- for (const ev of adapter.ingest(msg)) events.push(ev)
64
+ // Disk replay carries no `stream_event` messages, so the adapter never
65
+ // produces previews here — filter defensively to keep this the pure,
66
+ // persisted StreamEvent path that reconnect-healing trusts.
67
+ for (const ev of adapter.ingest(msg)) if (ev.kind !== 'preview') events.push(ev)
82
68
  }
83
69
  } catch {
84
70
  // session file missing or unreadable — return whatever we have (often [])
@@ -0,0 +1,23 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
4
+ // Production (published/global install) ships a prebuilt client in `dist/`
5
+ // (see scripts/build-client.ts). When present we serve it as static files,
6
+ // because Bun's runtime bundler won't run plugins on source under the global
7
+ // install tree. In dev there is no `dist/`, so web.ts falls back to the
8
+ // imported HTML route + Bun.serve's live bundler (HMR). `import.meta.dir` is
9
+ // server/, so `dist/` sits one level up. The Hono API serves files from here
10
+ // via `serveStatic` (see api.ts).
11
+ export const DIST_DIR = join(import.meta.dir, '..', 'dist')
12
+ const DIST_INDEX = join(DIST_DIR, 'index.html')
13
+
14
+ // Whether to serve the prebuilt client from `dist/`: true in production, but
15
+ // never in dev mode (MOI_DEV is set by the dev supervisor), so `bun run dev`
16
+ // always uses the live bundler + HMR even if a stale `dist/` is lying around.
17
+ export const prebuilt = !process.env.MOI_DEV && existsSync(DIST_INDEX)
18
+
19
+ // The prebuilt SPA shell, served for client-side routes in production. In dev,
20
+ // web.ts uses the live-bundled HTML import instead (for HMR).
21
+ export function distShell(): Response {
22
+ return new Response(Bun.file(DIST_INDEX))
23
+ }
@@ -0,0 +1,94 @@
1
+ // Plain-text introspection of the running server, served at GET /status.
2
+ // A quick "peek into the process": connected tabs, the in-memory live-session
3
+ // registry (CC + OpenClaw), and each session's busy/idle state + last message —
4
+ // handy when a chat appears stuck (loader spinning) and you want to know whether
5
+ // the server still holds a live session for that thread and what it's doing.
6
+ import { type CCDebugSession, SESSION_LIMITS, getCCDebugSnapshot } from './cc-session'
7
+ import { CONTROL_PORT, PORT } from './constants'
8
+ import { debugEnabled } from './debug'
9
+ import { getOpenClawRunningSessions } from './openclaw-session'
10
+ import { getClientCount } from './state'
11
+
12
+ const STARTED_AT = Date.now()
13
+
14
+ function fmtDuration(ms: number): string {
15
+ const s = Math.floor(ms / 1000)
16
+ const h = Math.floor(s / 3600)
17
+ const m = Math.floor((s % 3600) / 60)
18
+ const sec = s % 60
19
+ if (h > 0) return `${h}h ${m}m ${sec}s`
20
+ if (m > 0) return `${m}m ${sec}s`
21
+ return `${sec}s`
22
+ }
23
+
24
+ function fmtAgo(ts: number, now: number): string {
25
+ const s = Math.round((now - ts) / 1000)
26
+ if (s < 1) return 'now'
27
+ if (s < 60) return `${s}s ago`
28
+ const m = Math.floor(s / 60)
29
+ if (m < 60) return `${m}m ${s % 60}s ago`
30
+ return `${Math.floor(m / 60)}h ${m % 60}m ago`
31
+ }
32
+
33
+ function sessionLine(s: CCDebugSession, now: number): string {
34
+ const mark = s.busy ? '▶ busy' : s.closed ? '✗ closed' : '○ idle'
35
+ const bits = [
36
+ mark.padEnd(8),
37
+ `ws=${s.workspaceId}`,
38
+ `session=${s.sessionId}`,
39
+ `model=${s.model ?? 'default'}`,
40
+ `effort=${s.effort ?? 'default'}`,
41
+ `stream=${s.stream ? 'on' : 'off'}`,
42
+ `pending=${s.pendingTurns}`,
43
+ `age=${fmtDuration(now - s.createdAt)}`,
44
+ `lastActivity=${fmtAgo(s.lastActivityAt, now)}`
45
+ ]
46
+ if (s.desiredEffort !== s.effort) bits.push(`desiredEffort=${s.desiredEffort ?? 'default'}`)
47
+ if (s.desiredStream !== s.stream) bits.push(`desiredStream=${s.desiredStream ? 'on' : 'off'}`)
48
+ if (!s.busy && !s.hasIdleTimer) bits.push('(no idle timer)')
49
+ let line = ' ' + bits.join(' ')
50
+ if (s.lastUserText) line += `\n last: ${JSON.stringify(s.lastUserText)}`
51
+ return line
52
+ }
53
+
54
+ export function renderStatus(): string {
55
+ const now = Date.now()
56
+ const cc = getCCDebugSnapshot()
57
+ const openclawRunning = getOpenClawRunningSessions()
58
+
59
+ const lines: string[] = []
60
+ lines.push('moi server status')
61
+ lines.push('=================')
62
+ lines.push('')
63
+ lines.push(`uptime ${fmtDuration(now - STARTED_AT)}`)
64
+ lines.push(`http port ${PORT}`)
65
+ lines.push(`control port ${CONTROL_PORT}`)
66
+ lines.push(`debug logging ${debugEnabled ? 'on (--debug)' : 'off'}`)
67
+ lines.push(`connected tabs ${getClientCount()}`)
68
+ lines.push('')
69
+
70
+ const busy = cc.sessions.filter(s => s.busy).length
71
+ lines.push(
72
+ `live CC sessions ${cc.sessions.length}/${SESSION_LIMITS.maxLive} ` +
73
+ `(${busy} busy, ${cc.sessions.length - busy} idle, ${cc.aliases} alias${cc.aliases === 1 ? '' : 'es'}, ` +
74
+ `idle TTL ${fmtDuration(SESSION_LIMITS.idleTtlMs)})`
75
+ )
76
+ if (cc.sessions.length === 0) {
77
+ lines.push(' (none held in memory — next message will resume from disk)')
78
+ } else {
79
+ // Busiest / most-recently-active first.
80
+ const sorted = [...cc.sessions].sort(
81
+ (a, b) => Number(b.busy) - Number(a.busy) || b.lastActivityAt - a.lastActivityAt
82
+ )
83
+ for (const s of sorted) lines.push(sessionLine(s, now))
84
+ }
85
+ lines.push('')
86
+
87
+ lines.push(`live OpenClaw runs ${openclawRunning.length}`)
88
+ for (const r of openclawRunning) {
89
+ lines.push(` ▶ busy ws=${r.workspaceId} session=${r.sessionId}`)
90
+ }
91
+ lines.push('')
92
+
93
+ return lines.join('\n') + '\n'
94
+ }
@@ -0,0 +1,125 @@
1
+ import { mkdir, rename } from 'node:fs/promises'
2
+ import { join } from 'path'
3
+
4
+ import envPaths from 'env-paths'
5
+
6
+ import type { ThreadConfig } from '@/lib/types'
7
+
8
+ // Per-thread model/effort overrides for chat threads. Stored OUTSIDE the user's
9
+ // workspace (no repo churn) in ONE global JSON file in moi's data dir, alongside
10
+ // the workspace registry. Keyed by workspace path then sessionId:
11
+ // { "<workspacePath>": { "<sessionId>": { model?, effort? } } }
12
+ // Path (not registry id) is the key so config survives re-registration and lines
13
+ // up with the SDK's path-based session storage.
14
+
15
+ // A patch may clear a field with `null` (vs `undefined`, which leaves it alone).
16
+ export type ThreadConfigPatch = {
17
+ model?: string | null
18
+ effort?: string | null
19
+ }
20
+
21
+ type Store = Record<string, Record<string, ThreadConfig>>
22
+
23
+ const DATA_DIR = envPaths('moi', { suffix: false }).data
24
+ let _path = join(DATA_DIR, 'thread-config.json')
25
+
26
+ // Test seam: point the store at a scratch file (mirrors registry.setRegistryPath).
27
+ export function setThreadConfigPath(path: string): void {
28
+ _path = path
29
+ }
30
+
31
+ function clean(cfg: ThreadConfig | undefined): ThreadConfig {
32
+ const out: ThreadConfig = {}
33
+ if (typeof cfg?.model === 'string') out.model = cfg.model
34
+ if (typeof cfg?.effort === 'string') out.effort = cfg.effort
35
+ return out
36
+ }
37
+
38
+ function isEmpty(cfg: ThreadConfig): boolean {
39
+ return cfg.model === undefined && cfg.effort === undefined
40
+ }
41
+
42
+ async function readStore(): Promise<Store> {
43
+ try {
44
+ const parsed = JSON.parse(await Bun.file(_path).text())
45
+ return parsed && typeof parsed === 'object' ? (parsed as Store) : {}
46
+ } catch {
47
+ return {}
48
+ }
49
+ }
50
+
51
+ async function writeStore(store: Store): Promise<void> {
52
+ await mkdir(join(_path, '..'), { recursive: true })
53
+ const tmp = `${_path}.${process.pid}.tmp`
54
+ await Bun.write(tmp, JSON.stringify(store, null, 2))
55
+ await rename(tmp, _path)
56
+ }
57
+
58
+ // Serialize read-modify-write so concurrent save/rename calls can't clobber the
59
+ // single shared file (last writer would otherwise drop the other's update).
60
+ let writeChain: Promise<unknown> = Promise.resolve()
61
+ function locked<T>(fn: () => Promise<T>): Promise<T> {
62
+ const run = writeChain.then(fn, fn)
63
+ writeChain = run.catch(() => {})
64
+ return run
65
+ }
66
+
67
+ export async function getThreadConfig(
68
+ workspacePath: string,
69
+ sessionId: string
70
+ ): Promise<ThreadConfig> {
71
+ const store = await readStore()
72
+ return clean(store[workspacePath]?.[sessionId])
73
+ }
74
+
75
+ export async function hasThreadConfig(workspacePath: string, sessionId: string): Promise<boolean> {
76
+ return !isEmpty(await getThreadConfig(workspacePath, sessionId))
77
+ }
78
+
79
+ // Merge a patch over the stored config and write it back. `null` clears a field,
80
+ // `undefined` leaves it untouched, a string sets it. An emptied entry is dropped
81
+ // to keep the file tidy. Returns the merged config.
82
+ export async function saveThreadConfig(
83
+ workspacePath: string,
84
+ sessionId: string,
85
+ patch: ThreadConfigPatch
86
+ ): Promise<ThreadConfig> {
87
+ return locked(async () => {
88
+ const store = await readStore()
89
+ const threads = store[workspacePath] ?? {}
90
+ const next = clean(threads[sessionId])
91
+ for (const key of ['model', 'effort'] as const) {
92
+ const value = patch[key]
93
+ if (value === undefined) continue
94
+ if (value === null) delete next[key]
95
+ else next[key] = value
96
+ }
97
+ if (isEmpty(next)) delete threads[sessionId]
98
+ else threads[sessionId] = next
99
+ if (Object.keys(threads).length === 0) delete store[workspacePath]
100
+ else store[workspacePath] = threads
101
+ await writeStore(store)
102
+ return next
103
+ })
104
+ }
105
+
106
+ // Move a thread's config from one id to another (temp id → SDK real id on
107
+ // rename). Merges onto whatever the destination already holds (destination wins,
108
+ // so a concurrent write under the real id isn't lost) and removes the source.
109
+ export async function renameThreadConfig(
110
+ workspacePath: string,
111
+ from: string,
112
+ to: string
113
+ ): Promise<void> {
114
+ if (from === to) return
115
+ await locked(async () => {
116
+ const store = await readStore()
117
+ const threads = store[workspacePath]
118
+ const src = clean(threads?.[from])
119
+ if (isEmpty(src)) return
120
+ threads![to] = { ...src, ...clean(threads![to]) }
121
+ delete threads![from]
122
+ store[workspacePath] = threads!
123
+ await writeStore(store)
124
+ })
125
+ }
Binary file
@@ -0,0 +1,63 @@
1
+ // Serves the locally-vendored React ESM (client/vendor/react, generated by
2
+ // scripts/build-vendor.ts) behind the stable `/vendor/react/*` URLs the
3
+ // importmap in client/index.html points at. This is what makes Moi run offline
4
+ // — no esm.sh fetch.
5
+ //
6
+ // The importmap URLs carry no dev/prod distinction; we pick the build here so
7
+ // developers get React's warnings (invalid hook calls, key warnings) while
8
+ // production gets the smaller build. `client/` ships in the published package
9
+ // (see package.json `files`), so this resolves in a global install too.
10
+ import { join } from 'node:path'
11
+
12
+ import { prebuilt } from './static'
13
+
14
+ const VENDOR_DIR = join(import.meta.dir, '..', 'client', 'vendor', 'react')
15
+ const EMOJIBASE_DIR = join(import.meta.dir, '..', 'client', 'vendor', 'emojibase')
16
+ const MODE = prebuilt ? 'production' : 'development'
17
+
18
+ // A single flat file (`react.js`) or one nested under `_impl/` — both `.js`,
19
+ // no traversal. Matches exactly the layout build-vendor.ts emits.
20
+ const ALLOWED = /^(_impl\/)?[a-zA-Z0-9_-]+\.js$/
21
+
22
+ export async function serveVendorReact(req: Request): Promise<Response> {
23
+ const rel = new URL(req.url).pathname.replace(/^\/vendor\/react\//, '')
24
+ if (!ALLOWED.test(rel) || rel.includes('..')) {
25
+ return new Response('Not found', { status: 404 })
26
+ }
27
+ const file = Bun.file(join(VENDOR_DIR, MODE, rel))
28
+ if (!(await file.exists())) {
29
+ return new Response('Not found', { status: 404 })
30
+ }
31
+ return new Response(file, {
32
+ headers: {
33
+ 'Content-Type': 'text/javascript; charset=utf-8',
34
+ // Stable URL across versions, so don't cache immutably — revalidate so a
35
+ // `vendor:react` regen after a React bump is picked up.
36
+ 'Cache-Control': prebuilt ? 'public, max-age=3600' : 'no-store'
37
+ }
38
+ })
39
+ }
40
+
41
+ // `<locale>/<file>.json` only — mirrors the emojibase-data package layout the
42
+ // emoji picker expects (`${emojibaseUrl}/${locale}/data.json`).
43
+ const EMOJIBASE_ALLOWED = /^[a-z-]+\/[a-z]+\.json$/
44
+
45
+ // Serves the vendored emojibase-data JSON (client/vendor/emojibase) behind
46
+ // `/vendor/emojibase/*`, so the settings emoji picker works offline — no
47
+ // jsdelivr fetch at runtime.
48
+ export async function serveVendorEmojibase(req: Request): Promise<Response> {
49
+ const rel = new URL(req.url).pathname.replace(/^\/vendor\/emojibase\//, '')
50
+ if (!EMOJIBASE_ALLOWED.test(rel) || rel.includes('..')) {
51
+ return new Response('Not found', { status: 404 })
52
+ }
53
+ const file = Bun.file(join(EMOJIBASE_DIR, rel))
54
+ if (!(await file.exists())) {
55
+ return new Response('Not found', { status: 404 })
56
+ }
57
+ return new Response(file, {
58
+ headers: {
59
+ 'Content-Type': 'application/json; charset=utf-8',
60
+ 'Cache-Control': 'public, max-age=3600'
61
+ }
62
+ })
63
+ }
Binary file