moi-computer 0.12.1-next.3 → 0.12.1-next.4

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 (224) hide show
  1. package/bunfig.toml +1 -5
  2. package/client/api/app-config.ts +1 -2
  3. package/client/api/app-ui-keys.ts +3 -1
  4. package/client/api/http.ts +4 -1
  5. package/client/api/workspace-keys.ts +3 -3
  6. package/client/app/app-provider.tsx +22 -2
  7. package/client/app/app-router.tsx +4 -0
  8. package/client/app/routes/home-route.tsx +14 -0
  9. package/client/app/routes/onboarding-route.tsx +11 -0
  10. package/client/app/routes/settings-route.tsx +1 -1
  11. package/client/app/routes/workspace-route.tsx +21 -19
  12. package/client/components/shared/screen-shell.tsx +23 -0
  13. package/client/components/shared/ultrafast-icon.tsx +61 -0
  14. package/client/components/shared/workspace-icon.tsx +2 -2
  15. package/client/features/account/account-test-utils.tsx +4 -3
  16. package/client/features/app-settings/api.ts +33 -0
  17. package/client/features/app-settings/general-settings.tsx +39 -0
  18. package/client/features/{settings → app-settings}/settings-page.tsx +5 -1
  19. package/client/features/chat/applet-chat-intents.ts +4 -20
  20. package/client/features/chat/chat-send.ts +17 -13
  21. package/client/features/chat/composer/model-order.ts +8 -4
  22. package/client/features/chat/composer/model-picker.tsx +88 -34
  23. package/client/features/chat/composer/use-workspace-composer-state.tsx +11 -3
  24. package/client/features/chat/composer/use-workspace-skill-updates.ts +1 -1
  25. package/client/features/chat/connection/chat-frames.ts +3 -15
  26. package/client/features/chat/messages/chat-empty-state.tsx +1 -4
  27. package/client/features/chat/messages/fork-history.ts +5 -5
  28. package/client/features/chat/messages/turn-view.tsx +3 -12
  29. package/client/features/chat/messages/user-message-bubble.tsx +63 -0
  30. package/client/features/chat/sessions/api.ts +121 -80
  31. package/client/features/chat/sessions/browser-tab-state.ts +14 -12
  32. package/client/features/chat/sessions/chat-selector.tsx +5 -6
  33. package/client/features/chat/sessions/use-selected-session.ts +172 -257
  34. package/client/features/chat/use-chat.ts +14 -19
  35. package/client/features/collab/workspace-users-menu.tsx +1 -1
  36. package/client/features/demo/demo-dialog.tsx +11 -3
  37. package/client/features/dev/dev-index-page.tsx +5 -0
  38. package/client/features/dev/dev-routes.tsx +2 -0
  39. package/client/features/dev/harness-debug-page.tsx +3 -3
  40. package/client/features/dev/onboarding-preview-page.tsx +76 -0
  41. package/client/features/dev/workspace-setup-mocks.ts +16 -14
  42. package/client/features/dev/workspace-setup-preview.tsx +11 -17
  43. package/client/features/harness/api.ts +45 -15
  44. package/client/features/harness/device-login-steps.tsx +9 -3
  45. package/client/features/harness/harness-login-panel.tsx +228 -0
  46. package/client/features/harness/harness-presentation.ts +15 -0
  47. package/client/features/harness/harness-selector.tsx +119 -0
  48. package/client/features/harness/use-harness-login.ts +77 -0
  49. package/client/features/home/home-page.tsx +7 -7
  50. package/client/features/onboarding/agent-setup-step.tsx +57 -0
  51. package/client/features/onboarding/api.ts +42 -0
  52. package/client/features/onboarding/onboarding-idea-disk.tsx +129 -0
  53. package/client/features/onboarding/onboarding-page.tsx +32 -0
  54. package/client/features/onboarding/onboarding-screen.tsx +20 -0
  55. package/client/features/onboarding/onboarding-status.tsx +24 -0
  56. package/client/features/onboarding/workspace-setup-step.tsx +239 -0
  57. package/client/features/overview/default/registry.tsx +2 -2
  58. package/client/features/overview/default/views-widget.tsx +6 -5
  59. package/client/features/overview/overview.tsx +9 -11
  60. package/client/features/overview/widget-canvas.tsx +1 -1
  61. package/client/features/overview/workspace-name.tsx +2 -2
  62. package/client/features/views/api.ts +69 -16
  63. package/client/features/views/pending-view-screen.tsx +30 -9
  64. package/client/features/views/use-view-actions.ts +19 -20
  65. package/client/features/views/view-presentation.ts +2 -2
  66. package/client/features/views/view-submission.ts +28 -41
  67. package/client/features/workspace/add/api.ts +3 -23
  68. package/client/features/workspace/add/create-workspace-dialog.tsx +6 -5
  69. package/client/features/workspace/add/import-workspace-dialog.tsx +3 -3
  70. package/client/features/workspace/add/workspace-agent-options.ts +11 -12
  71. package/client/features/workspace/add/workspace-agent-selector.tsx +3 -132
  72. package/client/features/workspace/api.ts +32 -36
  73. package/client/features/workspace/harness-transition.ts +88 -0
  74. package/client/features/{settings → workspace/settings}/api.ts +1 -34
  75. package/client/features/{settings → workspace/settings}/general-settings.tsx +76 -2
  76. package/client/features/{settings → workspace/settings}/use-env-vars.ts +1 -1
  77. package/client/features/{settings → workspace/settings}/workspace-icon-picker.tsx +3 -3
  78. package/client/features/workspace/setup/workspace-login-state.tsx +37 -156
  79. package/client/features/workspace/setup/workspace-recovery-states.tsx +0 -12
  80. package/client/features/workspace/setup/workspace-setup.tsx +34 -14
  81. package/client/features/workspace/setup/workspace-welcome-state.tsx +2 -2
  82. package/client/features/workspace/use-workspace-navigation.ts +25 -9
  83. package/client/features/workspace/workspace-content.tsx +11 -8
  84. package/client/features/workspace/workspace-frame.tsx +2 -1
  85. package/client/features/workspace/workspace-layout-context.tsx +5 -2
  86. package/client/features/workspace/workspace-menu.tsx +12 -8
  87. package/client/features/workspace/workspace-pending-screen.tsx +10 -10
  88. package/client/features/workspace/workspace-presentation.tsx +5 -13
  89. package/client/features/workspace/workspace-state.ts +169 -0
  90. package/client/features/workspace/workspace-tabs.tsx +22 -2
  91. package/client/index.css +2 -0
  92. package/client/index.tsx +3 -3
  93. package/client/lib/flags.ts +1 -1
  94. package/client/lib/{app-icon-registry.ts → identity-icon-registry.ts} +10 -14
  95. package/client/runtime/workspace-events.ts +21 -4
  96. package/client/runtime/workspace-theme.ts +9 -0
  97. package/client/tailwind-config.ts +43 -0
  98. package/dist/chunk-0mjzg20x.js +2 -0
  99. package/dist/chunk-2y59vrxg.js +5 -0
  100. package/dist/chunk-58dyt9bk.js +2 -0
  101. package/dist/chunk-5aj040e5.css +1 -0
  102. package/dist/{chunk-tqd3pkg8.css → chunk-60q353jq.css} +1 -1
  103. package/dist/chunk-71fn6rmj.js +546 -0
  104. package/dist/chunk-7yg1m8hx.js +2 -0
  105. package/dist/chunk-825hys3h.js +1 -0
  106. package/dist/chunk-9bb8m9rx.js +2 -0
  107. package/dist/{chunk-11cab5dq.css → chunk-cq2r11fg.css} +1 -1
  108. package/dist/chunk-g0tcwqxc.js +1 -0
  109. package/dist/chunk-n0nab26d.js +1 -0
  110. package/dist/chunk-nf2wkvf9.js +14 -0
  111. package/dist/chunk-v88n1bay.js +74 -0
  112. package/dist/index.html +1 -1
  113. package/lib/harness-instructions.ts +1 -1
  114. package/lib/{app-icons.ts → identity-icons.ts} +6 -7
  115. package/lib/onboarding.ts +41 -0
  116. package/lib/speed-mode.ts +5 -0
  117. package/lib/types.ts +71 -62
  118. package/lib/view-build-directives.ts +1 -2
  119. package/lib/workspace-icon.ts +2 -2
  120. package/lib/workspace-layout.ts +1 -1
  121. package/lib/workspace-name.ts +15 -12
  122. package/package.json +9 -8
  123. package/server/README.md +27 -25
  124. package/server/api/harnesses.ts +31 -8
  125. package/server/api/index.ts +163 -126
  126. package/server/api/onboarding.ts +46 -0
  127. package/server/app-config.ts +16 -24
  128. package/server/app-settings.ts +6 -2
  129. package/server/applets/config.ts +5 -5
  130. package/server/applets/views.ts +19 -17
  131. package/server/cli/commands/init.ts +3 -3
  132. package/server/cli/commands/skill.ts +16 -17
  133. package/server/cli/commands/start.ts +8 -34
  134. package/server/cli/server.ts +18 -6
  135. package/server/collab/config.ts +1 -2
  136. package/server/collab/manager.ts +4 -1
  137. package/server/collab/skill/index.ts +1 -1
  138. package/server/control.ts +3 -3
  139. package/server/data-dir.ts +1 -1
  140. package/server/harness/README.md +24 -8
  141. package/server/harness/acp/session.ts +8 -4
  142. package/server/harness/auth.ts +14 -17
  143. package/server/harness/claude-code/NOTES.md +4 -3
  144. package/server/harness/claude-code/index.ts +2 -0
  145. package/server/harness/claude-code/models.ts +2 -20
  146. package/server/harness/claude-code/run-action.ts +123 -0
  147. package/server/harness/claude-code/session-title.ts +5 -7
  148. package/server/harness/claude-code/session.ts +24 -16
  149. package/server/harness/codex/NOTES.md +14 -9
  150. package/server/harness/codex/adapter.ts +14 -17
  151. package/server/harness/codex/index.ts +2 -0
  152. package/server/harness/codex/run-action.ts +93 -0
  153. package/server/harness/codex/session-title.ts +6 -8
  154. package/server/harness/codex/session.ts +11 -11
  155. package/server/harness/command.ts +45 -0
  156. package/server/harness/executable.ts +5 -0
  157. package/server/harness/fork.ts +6 -4
  158. package/server/harness/install.ts +49 -0
  159. package/server/harness/openclaw/session.ts +1 -2
  160. package/server/harness/run-action.ts +85 -0
  161. package/server/harness/session-title.ts +0 -46
  162. package/server/harness/types.ts +26 -2
  163. package/server/onboarding/brief.ts +29 -0
  164. package/server/onboarding/ideas.ts +48 -0
  165. package/server/onboarding/jobs.ts +291 -0
  166. package/server/onboarding/prompt.md +49 -0
  167. package/server/sessions/archive.ts +5 -14
  168. package/server/sessions/config.ts +17 -16
  169. package/server/sessions/lifecycle.ts +15 -13
  170. package/server/sessions/pending-views.ts +79 -108
  171. package/server/sessions/selected.ts +75 -161
  172. package/server/sessions/store.ts +40 -113
  173. package/server/sessions/view-sessions.ts +128 -111
  174. package/server/skills/locations.ts +82 -0
  175. package/server/skills/lock.ts +29 -0
  176. package/server/skills/template.ts +36 -25
  177. package/server/skills/update.ts +52 -5
  178. package/server/skills/version.ts +17 -22
  179. package/server/skills/workspace.ts +121 -0
  180. package/server/web.ts +22 -8
  181. package/server/workspace-state/file.ts +177 -0
  182. package/server/workspace-state/index.ts +162 -0
  183. package/server/workspace-state/legacy-migration.ts +79 -0
  184. package/server/workspace-state/lock.ts +42 -0
  185. package/server/workspace-state/types.ts +16 -0
  186. package/server/workspaces/change-harness.ts +88 -0
  187. package/server/workspaces/harness-transition.ts +29 -0
  188. package/server/workspaces/init.ts +29 -6
  189. package/server/workspaces/layout.ts +3 -0
  190. package/server/workspaces/registry.ts +27 -1
  191. package/{workspace/.claude/skills/moi-workspace → skill}/SKILL.md +7 -5
  192. package/{workspace/.claude/skills/moi-workspace → skill}/references/COLLAB.md +4 -8
  193. package/skill/references/DESIGN.md +148 -0
  194. package/{workspace/.claude/skills/moi-workspace → skill}/references/SCRATCHPAD.md +2 -2
  195. package/{workspace/.claude/skills/moi-workspace → skill}/references/UI-COMPONENTS.md +3 -0
  196. package/ui-components/badge.tsx +1 -1
  197. package/client/accept-hmr-dependencies.ts +0 -22
  198. package/client/features/workspace/setup/workspace-setup-panel.tsx +0 -18
  199. package/dist/chunk-20ynagd4.js +0 -2
  200. package/dist/chunk-42tde9a6.js +0 -1
  201. package/dist/chunk-9w543s0r.js +0 -2
  202. package/dist/chunk-a5372n61.js +0 -546
  203. package/dist/chunk-aja9y1vn.js +0 -68
  204. package/dist/chunk-fvcvrh3d.css +0 -1
  205. package/dist/chunk-gtfjw3nx.js +0 -1
  206. package/dist/chunk-j39y2aky.js +0 -14
  207. package/dist/chunk-pcnahct1.js +0 -5
  208. package/dist/chunk-pja30km3.js +0 -1
  209. package/dist/chunk-rm894bc2.js +0 -2
  210. package/dist/chunk-tevvtfbk.js +0 -10
  211. package/dist/chunk-tgt9zd0r.js +0 -2
  212. package/dist/chunk-tv5k5z00.js +0 -1
  213. package/dist/chunk-zq2ae5dx.js +0 -2
  214. package/lib/experimental.ts +0 -14
  215. package/workspace/.claude/skills/moi-workspace/references/DESIGN.md +0 -157
  216. /package/client/features/{settings → app-settings}/profile-settings.tsx +0 -0
  217. /package/client/features/{settings → app-settings}/settings-section.tsx +0 -0
  218. /package/client/features/{settings → app-settings}/users-settings.tsx +0 -0
  219. /package/client/features/{settings → workspace/settings}/connectors-settings.tsx +0 -0
  220. /package/client/features/{settings → workspace/settings}/environment-settings.tsx +0 -0
  221. /package/client/features/{settings → workspace/settings}/icon-picker-options.ts +0 -0
  222. /package/client/features/{settings → workspace/settings}/settings-layout.tsx +0 -0
  223. /package/client/features/{settings → workspace/settings}/workspace-settings-dialog.tsx +0 -0
  224. /package/{workspace/.claude/skills/moi-workspace → skill}/references/INTENTS.md +0 -0
@@ -1,14 +1,14 @@
1
1
  // Skill versioning for a workspace's installed skill copy drifting behind the
2
2
  // version this moi installation ships. The marker in each skill's `SKILL.md`
3
3
  // drives both the CLI status and the frontend's automatic update check.
4
- import { readdir } from 'node:fs/promises'
5
4
  import { join } from 'node:path'
6
5
 
7
6
  import type { WorkspaceSkillStatus, WorkspaceType } from '@/lib/types'
8
7
 
9
8
  import { findWorkspaceForPath, liftToWorkspaceRoot, listWorkspaces } from '../workspaces/registry'
10
- import { BUNDLED_SKILLS_DIR } from './template'
11
- import { skillsDirFor } from '../workspaces/init'
9
+ import { bundledSkillDirectory } from './template'
10
+ import { displaySkillPath, resolveSkillLocations } from './locations'
11
+ import type { SkillLocation } from './locations'
12
12
 
13
13
  // The version is stamped as a self-contained marker in SKILL.md, e.g.
14
14
  // `<moi-skill version="0.1.0" />`, rather than in YAML frontmatter. SKILL.md
@@ -71,30 +71,23 @@ export const isMinorBehind = (installed: string | null, bundled: string | null):
71
71
  export const isBehind = (installed: string | null, bundled: string | null): boolean =>
72
72
  compare(installed, bundled).behind
73
73
 
74
- // Skills shipped with this CLI — directory names under the bundled skills dir.
75
- export async function bundledSkillNames(): Promise<string[]> {
76
- try {
77
- const entries = await readdir(BUNDLED_SKILLS_DIR, { withFileTypes: true })
78
- return entries.filter(e => e.isDirectory()).map(e => e.name)
79
- } catch {
80
- return []
81
- }
82
- }
83
-
84
- // Per-skill installed-vs-bundled versions for a workspace root. `type` picks
85
- // the installed-skills location (OpenClaw keeps them in `skills/`, not
86
- // `.claude/skills/`) — pass the registry entry's type when known.
74
+ // Report every installed copy, plus the required primary harness destination.
87
75
  export async function skillStatuses(
88
76
  workspaceRoot: string,
89
77
  type?: WorkspaceType
90
78
  ): Promise<WorkspaceSkillStatus[]> {
91
- const names = await bundledSkillNames()
92
- const skillsDir = skillsDirFor(workspaceRoot, type)
79
+ return skillStatusesForLocations(await resolveSkillLocations(workspaceRoot, type))
80
+ }
81
+
82
+ export async function skillStatusesForLocations(
83
+ locations: SkillLocation[]
84
+ ): Promise<WorkspaceSkillStatus[]> {
93
85
  return Promise.all(
94
- names.map(async name => ({
86
+ locations.map(async ({ name, path, brokenLink }) => ({
95
87
  name,
96
- bundled: await readSkillVersion(join(BUNDLED_SKILLS_DIR, name, 'SKILL.md')),
97
- installed: await readSkillVersion(join(skillsDir, name, 'SKILL.md'))
88
+ path,
89
+ bundled: await readSkillVersion(join(bundledSkillDirectory(name), 'SKILL.md')),
90
+ installed: brokenLink ? null : await readSkillVersion(join(path, 'SKILL.md'))
98
91
  }))
99
92
  )
100
93
  }
@@ -126,7 +119,9 @@ export async function staleSkillNotice(cwd: string): Promise<string | null> {
126
119
  isMinorBehind(s.installed, s.bundled)
127
120
  )
128
121
  if (stale.length === 0) return null
129
- const parts = stale.map(s => `${s.name} (${s.installed ?? 'none'} → ${s.bundled})`)
122
+ const parts = stale.map(
123
+ s => `${displaySkillPath(root, s.path)} (${s.installed ?? 'none'} → ${s.bundled})`
124
+ )
130
125
  return `⚠ Moi skill outdated: ${parts.join(', ')} — run \`moi skill update\` to refresh.`
131
126
  } catch {
132
127
  return null
@@ -0,0 +1,121 @@
1
+ import { lstat, mkdir, mkdtemp, readlink, realpath, rename, rm, symlink } from 'node:fs/promises'
2
+ import { dirname, join, relative, resolve } from 'node:path'
3
+
4
+ import type { WorkspaceType } from '@/lib/types'
5
+
6
+ import { installBundledSkill, installBundledSkills, matchesBundledSkill } from './template'
7
+ import { skillsDirFor } from '../workspaces/init'
8
+ import { withSkillLock } from './lock'
9
+
10
+ const SKILL_NAME = 'moi-workspace'
11
+
12
+ export function usesSharedWorkspaceSkill(type?: WorkspaceType): boolean {
13
+ return type === undefined || type === 'claude-code' || type === 'codex'
14
+ }
15
+
16
+ async function entryAt(path: string) {
17
+ return lstat(path).catch((error: unknown) => {
18
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined
19
+ throw error
20
+ })
21
+ }
22
+
23
+ // Replacing a whole-folder link would also change unrelated skills.
24
+ async function checkSkillsDirectory(path: string): Promise<void> {
25
+ if ((await entryAt(path))?.isSymbolicLink()) {
26
+ throw new Error(
27
+ `Cannot install workspace skill: ${path} is a symlink; use a real skills directory`
28
+ )
29
+ }
30
+ }
31
+
32
+ export async function installWorkspaceSkills(
33
+ root: string,
34
+ type?: WorkspaceType
35
+ ): Promise<string[]> {
36
+ return withSkillLock(workspaceSkillLockPath(root, type), () =>
37
+ installWorkspaceSkillFiles(root, type)
38
+ )
39
+ }
40
+
41
+ export function workspaceSkillLockPath(root: string, type?: WorkspaceType): string {
42
+ return usesSharedWorkspaceSkill(type) ? join(root, '.agents', 'skills') : skillsDirFor(root, type)
43
+ }
44
+
45
+ // Callers must hold the workspace skill lock across any surrounding status reads.
46
+ export async function installWorkspaceSkillFiles(
47
+ root: string,
48
+ type?: WorkspaceType
49
+ ): Promise<string[]> {
50
+ if (usesSharedWorkspaceSkill(type)) return resetWorkspaceSkill(root)
51
+ const directory = skillsDirFor(root, type)
52
+ return (await installBundledSkills(directory)).map(name => join(directory, name))
53
+ }
54
+
55
+ // Both init and updates reset the owned skill. Local additions (including the
56
+ // experimental collab guide) are intentionally discarded; sibling skills stay.
57
+ async function resetWorkspaceSkill(workspaceRoot: string): Promise<string[]> {
58
+ const root = resolve(workspaceRoot)
59
+ const canonical = join(root, '.agents', 'skills', SKILL_NAME)
60
+ const claude = join(root, '.claude', 'skills', SKILL_NAME)
61
+ try {
62
+ await checkSkillsDirectory(dirname(canonical))
63
+ await checkSkillsDirectory(dirname(claude))
64
+ await mkdir(dirname(canonical), { recursive: true })
65
+ await mkdir(dirname(claude), { recursive: true })
66
+ const sharedDirectory =
67
+ (await realpath(dirname(canonical))) === (await realpath(dirname(claude)))
68
+ if (!sharedDirectory && (await entryAt(join(root, '.claude')))?.isSymbolicLink()) {
69
+ throw new Error(
70
+ 'The .claude directory is a symlink; point it to .agents or use a real .claude directory'
71
+ )
72
+ }
73
+ const linkTarget = relative(dirname(claude), canonical)
74
+ const claudeEntry = await entryAt(claude)
75
+ const linked =
76
+ sharedDirectory || (claudeEntry?.isSymbolicLink() && (await readlink(claude)) === linkTarget)
77
+ const matches = await matchesBundledSkill(SKILL_NAME, canonical)
78
+ if (matches && linked) return []
79
+
80
+ // Prepare the new files and link before removing either old skill. A copy
81
+ // or symlink-permission failure leaves the installed copies available.
82
+ const staging = await mkdtemp(join(dirname(canonical), '.moi-workspace-'))
83
+ try {
84
+ const skill = join(staging, SKILL_NAME)
85
+ const link = join(staging, 'claude-link')
86
+ if (!matches) await installBundledSkill(SKILL_NAME, skill)
87
+ if (!linked) {
88
+ try {
89
+ await symlink(linkTarget, link, 'dir')
90
+ } catch (cause) {
91
+ const code = (cause as NodeJS.ErrnoException).code
92
+ if (process.platform === 'win32' && (code === 'EPERM' || code === 'EACCES')) {
93
+ throw new Error(
94
+ 'Windows could not create the workspace skill symlink; enable Developer Mode or run Moi as administrator, then retry',
95
+ { cause }
96
+ )
97
+ }
98
+ throw cause
99
+ }
100
+ }
101
+ if (!matches) {
102
+ await rm(canonical, { recursive: true, force: true })
103
+ await rename(skill, canonical)
104
+ }
105
+ if (!linked) {
106
+ await rm(claude, { recursive: true, force: true })
107
+ await rename(link, claude)
108
+ }
109
+ } finally {
110
+ await rm(staging, { recursive: true, force: true })
111
+ }
112
+ return matches ? [claude] : [canonical, claude]
113
+ } catch (cause) {
114
+ throw new Error(
115
+ `Cannot reset workspace skill at ${canonical} and ${claude}: ${String(cause)}`,
116
+ {
117
+ cause
118
+ }
119
+ )
120
+ }
121
+ }
package/server/web.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { isSpeedMode } from '@/lib/speed-mode'
1
2
  import type { UserProfile } from '@/lib/collab/types'
2
3
  import { isMessageAttachments } from '@/lib/message-attachments'
3
4
  import type { ClientMessage, StatusSnapshotMessage } from '@/lib/types'
@@ -10,7 +11,6 @@ import devSandbox from '../client/dev/index.html'
10
11
  import { api } from './api'
11
12
  import { getAppConfig } from './app-config'
12
13
  import { harnessStore } from './harness/auth'
13
- import { AttachmentUploadError } from './sessions/attachment-message'
14
14
  import { PORT } from './constants'
15
15
  import { control } from './control'
16
16
  import { proxyUserState } from './collab/cloudflare-access'
@@ -25,7 +25,8 @@ import { resolveScratchOp } from './scratchpad/relay'
25
25
  import { allHarnesses, harnessFor } from './harness/registry'
26
26
  import { getWorkspace, listWorkspaces } from './workspaces/registry'
27
27
  import { failInterruptedViewStarts, sendWorkspaceMessage } from './sessions/view-sessions'
28
- import { PendingViewError } from './sessions/pending-views'
28
+ import { prepareWorkspaceStates } from './workspace-state'
29
+ import { migrateLegacyWorkspaceState } from './workspace-state/legacy-migration'
29
30
  import {
30
31
  addClient,
31
32
  broadcast,
@@ -59,7 +60,7 @@ function isClientMessage(value: unknown): value is ClientMessage {
59
60
  optimisticId?: unknown
60
61
  model?: unknown
61
62
  effort?: unknown
62
- fastMode?: unknown
63
+ speedMode?: unknown
63
64
  stream?: unknown
64
65
  context?: unknown
65
66
  attachments?: unknown
@@ -77,7 +78,7 @@ function isClientMessage(value: unknown): value is ClientMessage {
77
78
  (v.optimisticId === undefined || typeof v.optimisticId === 'string') &&
78
79
  (v.model === undefined || typeof v.model === 'string') &&
79
80
  (v.effort === undefined || typeof v.effort === 'string') &&
80
- (v.fastMode === undefined || typeof v.fastMode === 'boolean') &&
81
+ (v.speedMode === undefined || isSpeedMode(v.speedMode)) &&
81
82
  (v.stream === undefined || typeof v.stream === 'boolean') &&
82
83
  (v.context === undefined || isMoiContext(v.context)) &&
83
84
  (v.attachments === undefined || isMessageAttachments(v.attachments))
@@ -110,7 +111,10 @@ function upgrade(server: Upgradable, req: Request, data: WsData) {
110
111
  // Bun owns the fullstack surface: the HTML shell + dev bundler/HMR, and the two
111
112
  // WebSocket channels (which need Bun's native `server.upgrade` + pub/sub). Every
112
113
  // HTTP API route is delegated to the Hono app (`./api`) via `fetch`.
113
- await Promise.all((await listWorkspaces()).map(failInterruptedViewStarts))
114
+ const registeredWorkspaces = await listWorkspaces()
115
+ await migrateLegacyWorkspaceState(registeredWorkspaces)
116
+ await prepareWorkspaceStates(registeredWorkspaces)
117
+ await Promise.all(registeredWorkspaces.map(failInterruptedViewStarts))
114
118
 
115
119
  // Managed machines serve the web side on a Unix socket file that only the
116
120
  // machine's gateway can open, so nothing else running there reaches the API
@@ -158,6 +162,7 @@ export const app = Bun.serve<WsData>({
158
162
  : devSandbox,
159
163
  '/workspace/*': shell,
160
164
  '/settings': shell,
165
+ '/onboarding': shell,
161
166
 
162
167
  // Chat websocket — app-wide (one per client, not per workspace). Each chat
163
168
  // frame carries its own workspaceId.
@@ -192,7 +197,16 @@ export const app = Bun.serve<WsData>({
192
197
  },
193
198
  // Anything not matched above (the whole HTTP API + prod static assets + 404)
194
199
  // is handled by Hono.
195
- fetch: req => api.fetch(req),
200
+ fetch: (req, server) => {
201
+ // Downloads can exceed the normal HTTP idle timeout; the installer has its own deadline.
202
+ if (
203
+ req.method === 'POST' &&
204
+ /^\/api\/harnesses\/(claude-code|codex)\/auth\/install$/.test(new URL(req.url).pathname)
205
+ ) {
206
+ server.timeout(req, 0)
207
+ }
208
+ return api.fetch(req)
209
+ },
196
210
  websocket: {
197
211
  open(ws) {
198
212
  if (ws.data.channel === 'collab') {
@@ -239,12 +253,12 @@ export const app = Bun.serve<WsData>({
239
253
  optimisticId: data.optimisticId,
240
254
  model: data.model,
241
255
  effort: data.effort,
242
- fastMode: data.fastMode,
256
+ speedMode: data.speedMode,
243
257
  stream: data.stream,
244
258
  context: data.context,
245
259
  agentId: workspace.agentId
246
260
  }).catch(error => {
247
- if (error instanceof AttachmentUploadError || error instanceof PendingViewError) {
261
+ if (error instanceof Error) {
248
262
  broadcast(workspace.id, {
249
263
  kind: 'error',
250
264
  sessionId: data.sessionId,
@@ -0,0 +1,177 @@
1
+ import { isSpeedMode } from '@/lib/speed-mode'
2
+ import { mkdir, rename, rm } from 'node:fs/promises'
3
+ import { dirname } from 'node:path'
4
+
5
+ import type { PendingView, SessionFork, WorkspaceSessionState } from '@/lib/types'
6
+ import { isWorkspaceTabId } from '@/lib/workspace-tabs'
7
+ import { LockTimeoutError, type Lease } from './lock'
8
+ import { WORKSPACE_STATE_VERSION, type StoredWorkspaceState } from './types'
9
+
10
+ type PendingViewState = Omit<PendingView, 'id'>
11
+
12
+ export type LoadedState = {
13
+ state: StoredWorkspaceState
14
+ // False for a file written by a newer Moi: read what we understand, never
15
+ // overwrite what we don't.
16
+ writable: boolean
17
+ }
18
+
19
+ export class WorkspaceStateVersionError extends Error {
20
+ constructor(path: string) {
21
+ super(`${path} was written by a newer version of Moi. Update Moi to change this workspace.`)
22
+ }
23
+ }
24
+
25
+ const PENDING_VIEW_STATUSES = new Set<string>(['draft', 'starting', 'submitted', 'failed'])
26
+
27
+ export function emptyWorkspaceState(workspacePath: string): StoredWorkspaceState {
28
+ return {
29
+ version: WORKSPACE_STATE_VERSION,
30
+ workspacePath,
31
+ revision: 0,
32
+ selected: {},
33
+ sessions: {},
34
+ pendingViews: {}
35
+ }
36
+ }
37
+
38
+ function isRecord(value: unknown): value is Record<string, unknown> {
39
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
40
+ }
41
+
42
+ function optionalString(value: unknown): string | undefined {
43
+ return typeof value === 'string' ? value : undefined
44
+ }
45
+
46
+ function normalizeFork(value: unknown): SessionFork | undefined {
47
+ if (!isRecord(value) || typeof value.fromSessionId !== 'string') return undefined
48
+ const noticeIds = Array.isArray(value.noticeIds)
49
+ ? value.noticeIds.filter((id): id is string => typeof id === 'string')
50
+ : undefined
51
+ return {
52
+ fromSessionId: value.fromSessionId,
53
+ ...(typeof value.throughMessageId === 'string'
54
+ ? { throughMessageId: value.throughMessageId }
55
+ : {}),
56
+ ...(noticeIds?.length ? { noticeIds } : {})
57
+ }
58
+ }
59
+
60
+ function normalizeSession(value: unknown): WorkspaceSessionState {
61
+ if (!isRecord(value)) return {}
62
+ const session: WorkspaceSessionState = {}
63
+ if (isWorkspaceTabId(value.tabId)) session.tabId = value.tabId
64
+ if (isRecord(value.config)) {
65
+ const { model, effort, speedMode } = value.config
66
+ const config = {
67
+ ...(typeof model === 'string' ? { model } : {}),
68
+ ...(typeof effort === 'string' ? { effort } : {}),
69
+ ...(isSpeedMode(speedMode) ? { speedMode } : {})
70
+ }
71
+ if (Object.keys(config).length) session.config = config
72
+ }
73
+ const fork = normalizeFork(value.fork)
74
+ if (fork) session.fork = fork
75
+ return session
76
+ }
77
+
78
+ function normalizePendingView(value: unknown): PendingViewState | undefined {
79
+ if (!isRecord(value) || !PENDING_VIEW_STATUSES.has(String(value.status))) return undefined
80
+ const view: PendingViewState = {
81
+ status: value.status as PendingViewState['status'],
82
+ requirements: optionalString(value.requirements) ?? ''
83
+ }
84
+ for (const key of ['title', 'icon', 'buildSessionId', 'error'] as const) {
85
+ const field = optionalString(value[key])
86
+ if (field !== undefined) view[key] = field
87
+ }
88
+ return view
89
+ }
90
+
91
+ // Keep every entry we can make sense of and drop the rest, so one bad field
92
+ // never costs the whole workspace its state.
93
+ export function normalizeWorkspaceState(
94
+ value: Record<string, unknown>,
95
+ workspacePath: string
96
+ ): StoredWorkspaceState {
97
+ const state = emptyWorkspaceState(optionalString(value.workspacePath) ?? workspacePath)
98
+ if (typeof value.revision === 'number' && Number.isSafeInteger(value.revision))
99
+ state.revision = value.revision
100
+ const pinned = optionalString(value.pinnedSessionId)
101
+ if (pinned) state.pinnedSessionId = pinned
102
+ if (isRecord(value.selected)) {
103
+ for (const [tabId, sessionId] of Object.entries(value.selected)) {
104
+ if (isWorkspaceTabId(tabId) && typeof sessionId === 'string')
105
+ state.selected[tabId] = sessionId
106
+ }
107
+ }
108
+ if (isRecord(value.sessions)) {
109
+ for (const [sessionId, session] of Object.entries(value.sessions))
110
+ state.sessions[sessionId] = normalizeSession(session)
111
+ }
112
+ if (isRecord(value.pendingViews)) {
113
+ for (const [viewId, view] of Object.entries(value.pendingViews)) {
114
+ const normalized = normalizePendingView(view)
115
+ if (normalized) state.pendingViews[viewId] = normalized
116
+ }
117
+ }
118
+ return compactWorkspaceState(state)
119
+ }
120
+
121
+ // Empty session entries and settings carry no information; leaving them out
122
+ // keeps the file readable.
123
+ export function compactWorkspaceState<T extends StoredWorkspaceState>(state: T): T {
124
+ for (const [sessionId, session] of Object.entries(state.sessions)) {
125
+ for (const key of Object.keys(session) as (keyof WorkspaceSessionState)[])
126
+ if (session[key] === undefined) delete session[key]
127
+ if (session.config && Object.keys(session.config).length === 0) delete session.config
128
+ if (Object.keys(session).length === 0) delete state.sessions[sessionId]
129
+ }
130
+ if (!state.pinnedSessionId) delete state.pinnedSessionId
131
+ return state
132
+ }
133
+
134
+ async function setAside(path: string, reason: string): Promise<undefined> {
135
+ const aside = `${path}.corrupt-${Date.now()}`
136
+ await rename(path, aside).catch(() => {})
137
+ console.error(`[workspace-state] ${reason}; moved ${path} to ${aside} and started empty`)
138
+ return undefined
139
+ }
140
+
141
+ // Reads one state file. A missing file reads as undefined. A damaged file is
142
+ // moved aside instead of being overwritten by the next write.
143
+ export async function readStateFile(
144
+ path: string,
145
+ workspacePath: string
146
+ ): Promise<LoadedState | undefined> {
147
+ const file = Bun.file(path)
148
+ if (!(await file.exists())) return undefined
149
+ let parsed: unknown
150
+ try {
151
+ parsed = JSON.parse(await file.text())
152
+ } catch {
153
+ return setAside(path, 'Unreadable JSON')
154
+ }
155
+ if (!isRecord(parsed) || typeof parsed.version !== 'number')
156
+ return setAside(path, 'Not a workspace state file')
157
+ const writable = parsed.version <= WORKSPACE_STATE_VERSION
158
+ if (!writable) console.warn(`[workspace-state] ${new WorkspaceStateVersionError(path).message}`)
159
+ return { state: normalizeWorkspaceState(parsed, workspacePath), writable }
160
+ }
161
+
162
+ let tempSequence = 0
163
+
164
+ // Write to a sibling temp file, then rename over the target: readers see the
165
+ // old file or the new one, never a partial write. A holder whose lock expired
166
+ // gives up before the rename, so a late write cannot replace a newer one.
167
+ export async function writeStateFile(path: string, state: StoredWorkspaceState, lease: Lease) {
168
+ await mkdir(dirname(path), { recursive: true })
169
+ const temp = `${path}.${process.pid}.${++tempSequence}.tmp`
170
+ try {
171
+ await Bun.write(temp, `${JSON.stringify(state, null, 2)}\n`)
172
+ if (!lease.isCurrent()) throw new LockTimeoutError(path)
173
+ await rename(temp, path)
174
+ } finally {
175
+ await rm(temp, { force: true })
176
+ }
177
+ }
@@ -0,0 +1,162 @@
1
+ // Moi's per-workspace state, one `state.json` per workspace id under
2
+ // `DATA_DIR/workspaces/`. Reads come from a write-through cache: the server is
3
+ // the only process that writes these files (the CLI goes through the control
4
+ // port), so the cache never goes stale. Writes for one workspace run one at a
5
+ // time, each as a synchronous change applied to a copy and saved atomically.
6
+ // Every saved change is published to browsers as `state:changed`.
7
+ import { existsSync } from 'node:fs'
8
+ import { readdir, rm } from 'node:fs/promises'
9
+ import { join } from 'node:path'
10
+
11
+ import type { WorkspaceState } from '@/lib/types'
12
+ import { DATA_DIR } from '../data-dir'
13
+ import { publishEvent } from '../events'
14
+ import {
15
+ compactWorkspaceState,
16
+ emptyWorkspaceState,
17
+ readStateFile,
18
+ writeStateFile,
19
+ WorkspaceStateVersionError,
20
+ type LoadedState
21
+ } from './file'
22
+ import { createKeyedLock } from './lock'
23
+ import type { StoredWorkspaceState, WorkspaceRef } from './types'
24
+
25
+ export { LockTimeoutError } from './lock'
26
+ export { WorkspaceStateVersionError } from './file'
27
+ export type { StoredWorkspaceState, WorkspaceRef } from './types'
28
+
29
+ const STATE_FILE = 'state.json'
30
+ // Long enough for a slow disk, short enough that one stuck write does not
31
+ // freeze the workspace's chats.
32
+ const LOCK_TIMEOUT_MS = 10_000
33
+
34
+ export const DEFAULT_WORKSPACE_STATE_ROOT = join(DATA_DIR, 'workspaces')
35
+
36
+ let root = DEFAULT_WORKSPACE_STATE_ROOT
37
+ const cache = new Map<string, Promise<LoadedState>>()
38
+ const withLock = createKeyedLock(LOCK_TIMEOUT_MS)
39
+
40
+ // Test seam: keep state in a scratch folder.
41
+ export function setWorkspaceStateRoot(dir: string): void {
42
+ root = dir
43
+ cache.clear()
44
+ }
45
+
46
+ function statePath(workspaceId: string): string {
47
+ return join(root, workspaceId, STATE_FILE)
48
+ }
49
+
50
+ function load(ws: WorkspaceRef): Promise<LoadedState> {
51
+ let loaded = cache.get(ws.id)
52
+ if (!loaded) {
53
+ const loading = readStateFile(statePath(ws.id), ws.path).then(
54
+ found => found ?? { state: emptyWorkspaceState(ws.path), writable: true }
55
+ )
56
+ loading.catch(() => {
57
+ if (cache.get(ws.id) === loading) cache.delete(ws.id)
58
+ })
59
+ cache.set(ws.id, loading)
60
+ loaded = loading
61
+ }
62
+ return loaded
63
+ }
64
+
65
+ // A copy of the current state. Changing it changes nothing on disk.
66
+ export async function readWorkspaceState(ws: WorkspaceRef): Promise<StoredWorkspaceState> {
67
+ return structuredClone((await load(ws)).state)
68
+ }
69
+
70
+ // The state as clients see it, without the file's bookkeeping.
71
+ export function toWorkspaceState(stored: StoredWorkspaceState): WorkspaceState {
72
+ const { version: _version, workspacePath: _workspacePath, ...state } = stored
73
+ return state
74
+ }
75
+
76
+ export async function getWorkspaceState(ws: WorkspaceRef): Promise<WorkspaceState> {
77
+ return toWorkspaceState(await readWorkspaceState(ws))
78
+ }
79
+
80
+ // Applies `change` to a copy of the state and saves the result in one atomic
81
+ // write. Keep `change` synchronous and free of I/O: it runs while every other
82
+ // write to this workspace waits. Throwing from it leaves the state untouched;
83
+ // a change that leaves the state as it was skips the write.
84
+ export async function updateWorkspaceState<T>(
85
+ ws: WorkspaceRef,
86
+ change: (draft: StoredWorkspaceState) => T
87
+ ): Promise<T> {
88
+ return withLock(ws.id, async lease => {
89
+ const loaded = await load(ws)
90
+ const draft = structuredClone(loaded.state)
91
+ const result = change(draft)
92
+ if (result instanceof Promise)
93
+ throw new TypeError('Workspace state changes must be synchronous')
94
+ draft.workspacePath = ws.path
95
+ draft.revision = loaded.state.revision
96
+ compactWorkspaceState(draft)
97
+ if (JSON.stringify(draft) === JSON.stringify(loaded.state)) return result
98
+ if (!loaded.writable) throw new WorkspaceStateVersionError(statePath(ws.id))
99
+ draft.revision++
100
+ await writeStateFile(statePath(ws.id), draft, lease)
101
+ loaded.state = draft
102
+ publishEvent({ type: 'state:changed', workspaceId: ws.id, state: toWorkspaceState(draft) })
103
+ return result
104
+ })
105
+ }
106
+
107
+ export function hasWorkspaceState(workspaceId: string): boolean {
108
+ return existsSync(statePath(workspaceId))
109
+ }
110
+
111
+ async function listStateIds(): Promise<string[]> {
112
+ try {
113
+ const entries = await readdir(root, { withFileTypes: true })
114
+ return entries.filter(entry => entry.isDirectory()).map(entry => entry.name)
115
+ } catch {
116
+ return []
117
+ }
118
+ }
119
+
120
+ // Read-only on purpose: the CLI calls this while registering a workspace, and
121
+ // only the server may change state files.
122
+ async function peekWorkspacePath(workspaceId: string): Promise<string | undefined> {
123
+ try {
124
+ const parsed: unknown = JSON.parse(await Bun.file(statePath(workspaceId)).text())
125
+ if (typeof parsed !== 'object' || parsed === null) return undefined
126
+ const { workspacePath } = parsed as { workspacePath?: unknown }
127
+ return typeof workspacePath === 'string' ? workspacePath : undefined
128
+ } catch {
129
+ return undefined
130
+ }
131
+ }
132
+
133
+ // The id a removed workspace had, so re-adding the same folder brings back its
134
+ // chats, pin and settings.
135
+ export async function findStateIdForPath(workspacePath: string): Promise<string | undefined> {
136
+ for (const id of await listStateIds()) {
137
+ if ((await peekWorkspacePath(id)) === workspacePath) return id
138
+ }
139
+ return undefined
140
+ }
141
+
142
+ // Startup housekeeping: drop temp files a killed process left behind, and the
143
+ // state of removed workspaces whose folders no longer exist. A removed
144
+ // workspace whose folder still exists keeps its state for re-adding.
145
+ export async function prepareWorkspaceStates(registered: readonly WorkspaceRef[]): Promise<void> {
146
+ const registeredIds = new Set(registered.map(ws => ws.id))
147
+ for (const id of await listStateIds()) {
148
+ const dir = join(root, id)
149
+ if (!registeredIds.has(id)) {
150
+ const workspacePath = await peekWorkspacePath(id)
151
+ if (workspacePath && !existsSync(workspacePath)) {
152
+ await rm(dir, { recursive: true, force: true })
153
+ continue
154
+ }
155
+ }
156
+ const files = await readdir(dir).catch(() => [])
157
+ for (const file of files) {
158
+ if (file.startsWith(`${STATE_FILE}.`) && file.endsWith('.tmp'))
159
+ await rm(join(dir, file), { force: true })
160
+ }
161
+ }
162
+ }