moi-computer 0.13.1-next.1 → 0.13.1-next.3

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 (205) hide show
  1. package/client/api/app-config.ts +12 -1
  2. package/client/api/http.ts +11 -1
  3. package/client/app/app-router.tsx +3 -2
  4. package/client/app/routes/home-route.tsx +1 -1
  5. package/client/app/routes/workspace-registration.tsx +68 -0
  6. package/client/app/routes/workspace-route.tsx +33 -6
  7. package/client/app/shell/sidebar-layout.tsx +10 -5
  8. package/client/components/shared/workspace-icon.tsx +8 -17
  9. package/client/features/account/account-test-utils.tsx +15 -9
  10. package/client/features/account/api.ts +6 -6
  11. package/client/features/account/profile-actions.ts +5 -7
  12. package/client/features/app-settings/settings-page.tsx +2 -1
  13. package/client/features/applets/api.ts +6 -6
  14. package/client/features/applets/applet-cache.ts +6 -5
  15. package/client/features/applets/applet-log.ts +2 -1
  16. package/client/features/applets/applet-runtime.ts +2 -1
  17. package/client/features/applets/use-applet.ts +73 -18
  18. package/client/features/applets/widget-shell.tsx +4 -2
  19. package/client/features/chat/applet-chat-intents.ts +5 -13
  20. package/client/features/chat/chat-popup.tsx +8 -4
  21. package/client/features/chat/chat-send.ts +2 -2
  22. package/client/features/chat/composer/model-order.ts +4 -4
  23. package/client/features/chat/composer/model-picker.tsx +12 -10
  24. package/client/features/chat/composer/use-workspace-composer-state.tsx +1 -1
  25. package/client/features/chat/sessions/api.ts +11 -28
  26. package/client/features/chat/sessions/use-selected-session.ts +14 -109
  27. package/client/features/chat/use-chat.ts +8 -12
  28. package/client/features/collab/members/api.ts +4 -10
  29. package/client/features/collab/members/hooks.ts +32 -38
  30. package/client/features/collab/members/store.ts +96 -71
  31. package/client/features/collab/members/types.ts +5 -3
  32. package/client/features/collab/presence/client.ts +2 -3
  33. package/client/features/collab/presence/hooks.tsx +1 -1
  34. package/client/features/collab/proxy-user.ts +1 -3
  35. package/client/features/collab/sharing/workspace-members.tsx +0 -8
  36. package/client/features/dev/chat-states-page.tsx +3 -1
  37. package/client/features/dev/harness-debug-page.tsx +7 -7
  38. package/client/features/dev/workspace-setup-mocks.ts +1 -1
  39. package/client/features/dev/workspace-setup-preview.tsx +6 -4
  40. package/client/features/harness/api.ts +13 -10
  41. package/client/features/harness/harness-login-panel.tsx +9 -5
  42. package/client/features/harness/harness-presentation.ts +4 -4
  43. package/client/features/harness/harness-selector.tsx +13 -13
  44. package/client/features/harness/use-harness-login.ts +5 -5
  45. package/client/features/home/api.ts +38 -2
  46. package/client/features/home/home-page.tsx +43 -13
  47. package/client/features/home/shared-workspaces.tsx +70 -0
  48. package/client/features/home/workspace-invitations.tsx +101 -0
  49. package/client/features/identity/host-api.ts +3 -2
  50. package/client/features/identity/store.ts +1 -7
  51. package/client/features/onboarding/agent-setup-step.tsx +8 -8
  52. package/client/features/onboarding/onboarding-page.tsx +3 -2
  53. package/client/features/onboarding/workspace-setup-step.tsx +1 -1
  54. package/client/features/overview/api.ts +3 -5
  55. package/client/features/overview/default/registry.tsx +1 -1
  56. package/client/features/overview/default/views-widget.tsx +2 -2
  57. package/client/features/overview/hidden-panel.tsx +7 -5
  58. package/client/features/overview/overview.tsx +18 -16
  59. package/client/features/overview/workspace-name.tsx +2 -2
  60. package/client/features/scratchpad/scratchpad.tsx +9 -7
  61. package/client/features/scratchpad/use-scratchpad-snapshot.tsx +13 -5
  62. package/client/features/views/api.ts +66 -23
  63. package/client/features/views/use-view-actions.ts +10 -41
  64. package/client/features/views/view-manager.tsx +1 -1
  65. package/client/features/views/view-submission.ts +2 -21
  66. package/client/features/workspace/add/api.ts +5 -4
  67. package/client/features/workspace/add/create-workspace-dialog.tsx +12 -9
  68. package/client/features/workspace/add/import-workspace-dialog.tsx +7 -7
  69. package/client/features/workspace/add/use-workspace-import.ts +10 -10
  70. package/client/features/workspace/add/workspace-agent-options.ts +21 -20
  71. package/client/features/workspace/add/workspace-agent-selector.tsx +11 -11
  72. package/client/features/workspace/api.ts +60 -13
  73. package/client/features/workspace/harness-transition.ts +7 -13
  74. package/client/features/workspace/remote.ts +25 -0
  75. package/client/features/workspace/settings/api.ts +7 -12
  76. package/client/features/workspace/settings/connectors-settings.tsx +3 -3
  77. package/client/features/workspace/settings/general-settings.tsx +8 -8
  78. package/client/features/workspace/setup/workspace-login-state.tsx +4 -4
  79. package/client/features/workspace/setup/workspace-recovery-states.tsx +43 -14
  80. package/client/features/workspace/setup/workspace-setup.tsx +6 -6
  81. package/client/features/workspace/tab-resolution.ts +1 -8
  82. package/client/features/workspace/use-workspace-navigation.ts +11 -7
  83. package/client/features/workspace/workspace-content.tsx +24 -31
  84. package/client/features/workspace/workspace-frame.tsx +13 -26
  85. package/client/features/workspace/workspace-layout-context.tsx +45 -12
  86. package/client/features/workspace/workspace-menu.tsx +2 -2
  87. package/client/features/workspace/workspace-pane.tsx +22 -0
  88. package/client/features/workspace/workspace-pending-screen.tsx +1 -1
  89. package/client/features/workspace/workspace-preferences.ts +91 -0
  90. package/client/features/workspace/workspace-presentation.tsx +12 -16
  91. package/client/features/workspace/workspace-screen.tsx +2 -2
  92. package/client/features/workspace/workspace-state.ts +42 -16
  93. package/client/features/workspace/workspace-tabs.tsx +1 -1
  94. package/client/features/workspace/workspace-test-utils.ts +23 -0
  95. package/client/runtime/use-workspace-events.ts +14 -0
  96. package/client/runtime/workspace-events.ts +9 -9
  97. package/client/store/ui.ts +24 -9
  98. package/client/store/workspace-session.ts +30 -0
  99. package/dist/chunk-0h4zypgf.js +1 -0
  100. package/dist/chunk-1tksq43z.js +72 -0
  101. package/dist/chunk-6gxf0xr8.js +5 -0
  102. package/dist/chunk-a865c7x4.js +1 -0
  103. package/dist/chunk-f44cs6mw.js +2 -0
  104. package/dist/chunk-h3qag4a6.js +2 -0
  105. package/dist/chunk-kffcah9w.css +1 -0
  106. package/dist/chunk-q2tpy0h7.js +2 -0
  107. package/dist/chunk-r95acex1.js +546 -0
  108. package/dist/chunk-w5h9grdr.js +1 -0
  109. package/dist/{chunk-th91xfnp.js → chunk-xj1pjhng.js} +1 -1
  110. package/dist/index.html +1 -1
  111. package/lib/harness-instructions.ts +4 -4
  112. package/lib/harness-types.ts +13 -0
  113. package/lib/moi-context.ts +19 -5
  114. package/lib/types.ts +38 -54
  115. package/lib/workspace-config.ts +48 -0
  116. package/lib/workspace-layout.ts +5 -24
  117. package/package.json +5 -2
  118. package/server/AGENTS.md +1 -1
  119. package/server/README.md +36 -31
  120. package/server/api/harnesses.ts +5 -5
  121. package/server/api/index.ts +268 -162
  122. package/server/applets/index.ts +15 -9
  123. package/server/applets/views.ts +2 -17
  124. package/server/applets/widgets.ts +3 -2
  125. package/server/cli/commands/config.ts +8 -20
  126. package/server/cli/commands/hermes.ts +2 -2
  127. package/server/cli/commands/init.ts +102 -54
  128. package/server/cli/commands/openclaw.ts +2 -2
  129. package/server/cli/commands/refresh.ts +10 -1
  130. package/server/cli/commands/remote.ts +330 -0
  131. package/server/cli/commands/skill.ts +4 -4
  132. package/server/cli/commands/tabs.ts +5 -12
  133. package/server/cli/control.ts +35 -4
  134. package/server/cli/index.ts +10 -6
  135. package/server/cli/remote-command.ts +77 -0
  136. package/server/cli/remote-control.ts +73 -0
  137. package/server/cli/remote-operations.ts +247 -0
  138. package/server/collab/config.ts +3 -3
  139. package/server/collab/skill/index.ts +3 -3
  140. package/server/control.ts +47 -12
  141. package/server/harness/acp/session.ts +4 -4
  142. package/server/harness/auth.ts +26 -31
  143. package/server/harness/claude-code/index.ts +1 -1
  144. package/server/harness/codex/discovery.ts +1 -1
  145. package/server/harness/codex/session.ts +1 -1
  146. package/server/harness/detect.ts +14 -19
  147. package/server/harness/executable.ts +10 -10
  148. package/server/harness/hermes/NOTES.md +2 -2
  149. package/server/harness/hermes/index.ts +1 -1
  150. package/server/harness/install.ts +11 -11
  151. package/server/harness/openclaw/index.ts +1 -1
  152. package/server/harness/registry.ts +7 -6
  153. package/server/harness/types.ts +4 -4
  154. package/server/onboarding/jobs.ts +2 -2
  155. package/server/operations/commands.ts +46 -0
  156. package/server/operations/files.ts +148 -0
  157. package/server/operations/server.ts +206 -0
  158. package/server/remote/agent.ts +103 -0
  159. package/server/remote/broker-client.ts +76 -0
  160. package/server/remote/broker.ts +81 -0
  161. package/server/remote/client.ts +725 -0
  162. package/server/remote/errors.ts +2 -0
  163. package/server/remote/routes.ts +121 -0
  164. package/server/remote/workspace.ts +34 -0
  165. package/server/scratchpad/document.ts +33 -12
  166. package/server/scratchpad/executor.ts +16 -7
  167. package/server/sessions/config.ts +8 -5
  168. package/server/sessions/pending-views.ts +17 -0
  169. package/server/sessions/send-message.ts +102 -0
  170. package/server/sessions/view-sessions.ts +9 -101
  171. package/server/skills/locations.ts +4 -4
  172. package/server/skills/update.ts +11 -11
  173. package/server/skills/version.ts +7 -7
  174. package/server/skills/workspace.ts +13 -11
  175. package/server/web.ts +13 -9
  176. package/server/workspace-state/file.ts +4 -0
  177. package/server/workspace-state/index.ts +0 -4
  178. package/server/workspaces/api.ts +24 -0
  179. package/server/workspaces/change-harness.ts +15 -26
  180. package/server/workspaces/import.ts +4 -4
  181. package/server/workspaces/init.ts +15 -13
  182. package/server/workspaces/layout.ts +60 -66
  183. package/server/workspaces/registry.ts +43 -18
  184. package/server/workspaces/shared.ts +74 -0
  185. package/server/workspaces/tabs.ts +5 -12
  186. package/skill/SKILL.md +80 -19
  187. package/skill/references/SCRATCHPAD.md +4 -0
  188. package/skill/references/UI-COMPONENTS.md +1 -1
  189. package/client/api/app-ui-keys.ts +0 -6
  190. package/client/features/chat/sessions/browser-tab-state.ts +0 -43
  191. package/client/features/collab/members/keys.ts +0 -6
  192. package/client/features/workspace/browser-tab-state.ts +0 -51
  193. package/client/features/workspace/layout-save.ts +0 -13
  194. package/dist/chunk-3smkkcfw.js +0 -546
  195. package/dist/chunk-47h9c2qy.js +0 -2
  196. package/dist/chunk-8qed2gqp.js +0 -75
  197. package/dist/chunk-8zy3vesm.js +0 -1
  198. package/dist/chunk-a47zy276.js +0 -2
  199. package/dist/chunk-g4c1nte9.css +0 -1
  200. package/dist/chunk-kcactdr4.js +0 -2
  201. package/dist/chunk-m8bhx6tw.js +0 -1
  202. package/dist/chunk-pf19zcrn.js +0 -2
  203. package/dist/chunk-ygzxah0e.js +0 -1
  204. package/lib/workspace-types.ts +0 -13
  205. package/server/workspace-state/legacy-migration.ts +0 -79
@@ -0,0 +1,2 @@
1
+ /** No usable Cloud login: the caller has to sign in before this can work. */
2
+ export class CloudSignInRequired extends Error {}
@@ -0,0 +1,121 @@
1
+ import { parse } from 'regexparam'
2
+ import {
3
+ parseRemoteWorkspaceAddress,
4
+ parseRemoteWorkspaceTarget,
5
+ workspaceAddress,
6
+ type RemoteWorkspaceTarget
7
+ } from '@/lib/workspace-config'
8
+
9
+ // Every Cloud request the CLI may make: its methods, the pattern that allows
10
+ // it, and the function callers use to write its path. The CLI checks a request
11
+ // against this table before sending, and the running server checks it again
12
+ // before lending its login to a caller (broker.ts).
13
+ //
14
+ // `api/…` is sent relative to the Cloud URL; `/api/workspaces/…` goes to the
15
+ // owner's workspace API at its origin. Sign-in itself (login, token refresh,
16
+ // logout, agent join) uses fixed URLs in client.ts and never comes through here.
17
+
18
+ type Access = 'any login' | 'own login'
19
+ type Workspace = RemoteWorkspaceTarget
20
+
21
+ const refused = () => new Error('This Cloud request is not allowed')
22
+
23
+ function route<Args extends unknown[]>(
24
+ methods: string,
25
+ pattern: string,
26
+ path: (...args: Args) => string,
27
+ /** 'own login' requests are never sent with a login lent by the server. */
28
+ access: Access = 'any login'
29
+ ) {
30
+ const [pathname = '', query = ''] = pattern.split('?')
31
+ return { methods: methods.split(' '), ...parse(pathname), pathname, query, path, access }
32
+ }
33
+
34
+ const address = (workspace: Workspace) => {
35
+ const { workspace_id, user_id } = parseRemoteWorkspaceTarget(workspace)
36
+ return workspaceAddress(workspace_id, user_id)
37
+ }
38
+ const cloud = (workspace: Workspace) => `api/workspaces/${address(workspace)}`
39
+ const owner = (workspace: Workspace) => `/api/workspaces/${address(workspace)}`
40
+ // A file path relative to the workspace root, one encoded segment per name.
41
+ function encodePath(file: string) {
42
+ const names = file.split('/')
43
+ if (names.some(name => !name || name === '.' || name === '..' || name.includes('\\')))
44
+ throw new Error('Use a file path relative to the remote workspace')
45
+ return names.map(encodeURIComponent).join('/')
46
+ }
47
+
48
+ const CLOUD = 'api/workspaces/:workspace'
49
+ const OWNER = '/api/workspaces/:workspace'
50
+
51
+ export const cloudRoutes = {
52
+ // Account
53
+ me: route('GET', 'api/me', () => 'api/me'),
54
+ sharedWorkspaces: route('GET', 'api/workspaces/shared', () => 'api/workspaces/shared'),
55
+ invitations: route('GET', 'api/workspaces/invitations', () => 'api/workspaces/invitations'),
56
+ // Changes to the account itself stay with whoever holds the login.
57
+ renameAgent: route('PATCH', 'api/me', () => 'api/me', 'own login'),
58
+ acceptInvitation: route(
59
+ 'POST',
60
+ 'api/invitations/:id/accept',
61
+ (id: string) => `api/invitations/${encodePath(id)}/accept`,
62
+ 'own login'
63
+ ),
64
+ leave: route('POST', `${CLOUD}/leave`, (w: Workspace) => `${cloud(w)}/leave`, 'own login'),
65
+ // Operations on the owner's machine
66
+ exec: route('POST', `${CLOUD}/ops/exec`, (w: Workspace) => `${cloud(w)}/ops/exec`),
67
+ commands: route('POST', `${CLOUD}/ops/commands`, (w: Workspace) => `${cloud(w)}/ops/commands`),
68
+ files: route(
69
+ 'GET PUT PATCH',
70
+ `${CLOUD}/ops/files/*`,
71
+ (w: Workspace, file: string) => `${cloud(w)}/ops/files/${encodePath(file)}`
72
+ ),
73
+ // Owner's workspace API
74
+ views: route(
75
+ 'GET',
76
+ `${OWNER}/views?includePending=true`,
77
+ (w: Workspace) => `${owner(w)}/views?includePending=true`
78
+ ),
79
+ compiledViews: route('GET', `${OWNER}/views`, (w: Workspace) => `${owner(w)}/views`),
80
+ config: route('GET PUT', `${OWNER}/config`, (w: Workspace) => `${owner(w)}/config`),
81
+ icon: route('PUT DELETE', `${OWNER}/icon`, (w: Workspace) => `${owner(w)}/icon`),
82
+ scratchpad: route('GET', `${OWNER}/scratchpad`, (w: Workspace) => `${owner(w)}/scratchpad`),
83
+ scratchpadOps: route(
84
+ 'POST',
85
+ `${OWNER}/scratchpad/ops`,
86
+ (w: Workspace) => `${owner(w)}/scratchpad/ops`
87
+ ),
88
+ scratchpadAsset: route(
89
+ 'GET',
90
+ `${OWNER}/scratchpad/assets/:name`,
91
+ (w: Workspace, name: string) => `${owner(w)}/scratchpad/assets/${encodePath(name)}`
92
+ )
93
+ }
94
+
95
+ // Spellings that make a path resolve somewhere other than where it reads:
96
+ // dot segments, empty segments, backslashes, and their encoded forms. None
97
+ // appears in a path built above.
98
+ const UNSAFE = /(^|\/)\.\.?(\/|\?|$)|\/\/|\\|%2e|%2f|%5c/i
99
+
100
+ export type AllowedCloudRequest = { workspace?: Workspace; access: Access }
101
+
102
+ /** Throws unless the request is listed; names the workspace it addresses, if any. */
103
+ export function allowedCloudRequest(method: string, path: string): AllowedCloudRequest {
104
+ if (UNSAFE.test(path)) throw refused()
105
+ const [pathname = '', query = ''] = path.split('?')
106
+ for (const route of Object.values(cloudRoutes)) {
107
+ if (!route.methods.includes(method.toUpperCase()) || route.query !== query) continue
108
+ // regexparam ignores a leading slash, and here it says where the request goes.
109
+ if (route.pathname.startsWith('/') !== pathname.startsWith('/')) continue
110
+ const found = route.pattern.exec(pathname.replace(/^\/?/, '/'))
111
+ if (!found) continue
112
+ const workspace = found[route.keys.indexOf('workspace') + 1]
113
+ if (!route.keys.includes('workspace')) return { access: route.access }
114
+ try {
115
+ return { access: route.access, workspace: parseRemoteWorkspaceAddress(workspace ?? '') }
116
+ } catch {
117
+ throw refused()
118
+ }
119
+ }
120
+ throw refused()
121
+ }
@@ -0,0 +1,34 @@
1
+ import { resolve } from 'node:path'
2
+ import { fetchSharedWorkspaces } from './client'
3
+ import { parseRemoteWorkspaceTarget, type RemoteWorkspaceTarget } from '@/lib/workspace-config'
4
+ import { loadWorkspaceFileConfig } from '../workspaces/layout'
5
+ import { registerRemoteWorkspaceReference } from '../workspaces/shared'
6
+ import { listWorkspaces } from '../workspaces/registry'
7
+ import { resolveWorkspaceRoot } from '../skills/version'
8
+
9
+ export async function currentRemoteWorkspace(path = process.cwd()) {
10
+ const root = await resolveWorkspaceRoot(resolve(path))
11
+ const config = await loadWorkspaceFileConfig(root)
12
+ return config.remote ? { path: root, ...config.remote } : undefined
13
+ }
14
+ export async function initializeRemoteWorkspace(path: string, target: RemoteWorkspaceTarget) {
15
+ target = parseRemoteWorkspaceTarget(target)
16
+ const shares = await fetchSharedWorkspaces()
17
+ if (!shares.some(w => w.id === target.workspace_id && w.owner.id === target.user_id))
18
+ throw new Error('This workspace is not shared with this account')
19
+ // Initialization creates a workspace at the requested folder. An ancestor's
20
+ // registration must not redirect this write into a different directory.
21
+ const root = resolve(path)
22
+ const existing = (await listWorkspaces()).find(
23
+ workspace =>
24
+ workspace.remote?.user_id === target.user_id &&
25
+ workspace.remote.workspace_id === target.workspace_id &&
26
+ resolve(workspace.path) !== root
27
+ )
28
+ if (existing)
29
+ throw new Error(
30
+ `This workspace is already initialized at ${existing.path} — remove that registration in Moi first`
31
+ )
32
+ const entry = await registerRemoteWorkspaceReference(root, target)
33
+ return { path: root, id: entry.id, ...target }
34
+ }
@@ -1,3 +1,6 @@
1
+ import type { WorkspaceApiTarget } from '../workspaces/api'
2
+ import { requestWorkspace } from '../workspaces/api'
3
+ import { cloudRoutes } from '../remote/routes'
1
4
  import { readdir } from 'node:fs/promises'
2
5
  import { join } from 'path'
3
6
 
@@ -185,10 +188,10 @@ function extractText(props: unknown): string | undefined {
185
188
  // them for one image. Ids match with or without the `shape:` prefix (read
186
189
  // surfaces them stripped).
187
190
  export async function readScratchpadImage(
188
- workspacePath: string,
191
+ workspace: string | WorkspaceApiTarget,
189
192
  id: string
190
193
  ): Promise<{ src: string } | { error: string }> {
191
- const { document } = await loadScratchpadDoc(workspacePath)
194
+ const { document } = await readSnapshot(workspace)
192
195
  const store = document?.store
193
196
  if (!store || typeof store !== 'object') return { error: `No shape named "${id}"` }
194
197
 
@@ -212,12 +215,12 @@ export async function readScratchpadImage(
212
215
  if (a.typeName === 'asset' && a.id === assetId && typeof a.props?.src === 'string') {
213
216
  const fileName = assetSrcFileName(a.props.src)
214
217
  if (!fileName) return { src: a.props.src }
215
- const resolved = scratchpadAssetFile(workspacePath, fileName)
216
- if (!resolved || !(await resolved.file.exists())) {
218
+ const resolved = await readAsset(workspace, fileName)
219
+ if (!resolved) {
217
220
  return { error: `Image "${id}" file is missing from .moi/.scratchpad` }
218
221
  }
219
- const bytes = Buffer.from(await resolved.file.arrayBuffer())
220
- return { src: `data:${resolved.mimeType};base64,${bytes.toString('base64')}` }
222
+ const bytes = Buffer.from(await resolved.arrayBuffer())
223
+ return { src: `data:${resolved.type};base64,${bytes.toString('base64')}` }
221
224
  }
222
225
  }
223
226
  return { error: `Image "${id}" has no stored data` }
@@ -225,8 +228,10 @@ export async function readScratchpadImage(
225
228
 
226
229
  // no browser needed. Ids are reported without tldraw's `shape:` prefix so they
227
230
  // round-trip with `createShapeId(name)` on the draw side.
228
- export async function readScratchpadShapes(workspacePath: string): Promise<ScratchShape[]> {
229
- const { document } = await loadScratchpadDoc(workspacePath)
231
+ export async function readScratchpadShapes(
232
+ workspace: string | WorkspaceApiTarget
233
+ ): Promise<ScratchShape[]> {
234
+ const { document } = await readSnapshot(workspace)
230
235
  const store = document?.store
231
236
  if (!store || typeof store !== 'object') return []
232
237
 
@@ -244,10 +249,7 @@ export async function readScratchpadShapes(workspacePath: string): Promise<Scrat
244
249
  if (typeof a.props?.src === 'string') {
245
250
  assetSrc.set(a.id, a.props.src)
246
251
  const fileName = assetSrcFileName(a.props.src)
247
- if (fileName) {
248
- const resolved = scratchpadAssetFile(workspacePath, fileName)
249
- if (!resolved || !(await resolved.file.exists())) assetGone.add(a.id)
250
- }
252
+ if (fileName && !(await readAsset(workspace, fileName))) assetGone.add(a.id)
251
253
  }
252
254
  }
253
255
 
@@ -289,3 +291,22 @@ export async function readScratchpadShapes(workspacePath: string): Promise<Scrat
289
291
  }
290
292
  return shapes
291
293
  }
294
+
295
+ async function readSnapshot(workspace: string | WorkspaceApiTarget): Promise<ScratchpadSnapshot> {
296
+ return typeof workspace === 'string'
297
+ ? loadScratchpadDoc(workspace)
298
+ : (await requestWorkspace(cloudRoutes.scratchpad.path(workspace.remote))).json()
299
+ }
300
+
301
+ async function readAsset(
302
+ workspace: string | WorkspaceApiTarget,
303
+ fileName: string
304
+ ): Promise<Blob | undefined> {
305
+ if (typeof workspace !== 'string')
306
+ return (
307
+ await requestWorkspace(cloudRoutes.scratchpadAsset.path(workspace.remote, fileName))
308
+ ).blob()
309
+ const asset = scratchpadAssetFile(workspace, fileName)
310
+ if (!asset || !(await asset.file.exists())) return undefined
311
+ return asset.file.slice(0, asset.file.size, asset.mimeType)
312
+ }
@@ -231,11 +231,12 @@ const MAX_IMAGE_BYTES = 50 * 1024 * 1024
231
231
 
232
232
  async function processCanvasImage(
233
233
  path: string,
234
- quality: ScratchImageQuality
234
+ quality: ScratchImageQuality,
235
+ imageBytes?: Uint8Array
235
236
  ): Promise<{ data: Buffer; w: number; h: number; mimeType: string; name: string }> {
236
237
  const file = Bun.file(path)
237
- if (!(await file.exists())) throw new Error(`Image file not found: ${path}`)
238
- const bytes = new Uint8Array(await file.arrayBuffer())
238
+ if (!imageBytes && !(await file.exists())) throw new Error(`Image file not found: ${path}`)
239
+ const bytes = imageBytes ?? new Uint8Array(await file.arrayBuffer())
239
240
  if (bytes.length === 0) throw new Error(`Image file is empty: ${path}`)
240
241
  if (bytes.length > MAX_IMAGE_BYTES) {
241
242
  throw new Error(`Image is too large (${Math.round(bytes.length / 1e6)}MB, max 50MB): ${path}`)
@@ -256,7 +257,8 @@ async function processCanvasImage(
256
257
  async function applyAddImage(
257
258
  store: HeadlessStore,
258
259
  workspacePath: string,
259
- op: Extract<ScratchOp, { kind: 'add-image' }>
260
+ op: Extract<ScratchOp, { kind: 'add-image' }>,
261
+ imageBytes?: Uint8Array
260
262
  ): Promise<ScratchOpResult> {
261
263
  const pageId = firstPageId(store)
262
264
  // Re-adding under an existing id replaces that shape; note its current asset so
@@ -265,7 +267,11 @@ async function applyAddImage(
265
267
  | { props?: { assetId?: unknown } }
266
268
  | undefined
267
269
  const prevAssetId = typeof prev?.props?.assetId === 'string' ? prev.props.assetId : undefined
268
- const { data, w, h, mimeType, name } = await processCanvasImage(op.path, op.quality ?? 'lo')
270
+ const { data, w, h, mimeType, name } = await processCanvasImage(
271
+ op.path,
272
+ op.quality ?? 'lo',
273
+ imageBytes
274
+ )
269
275
  const { src } = await storeScratchpadAsset(workspacePath, data, mimeType)
270
276
  const assetId = AssetRecordType.createId()
271
277
  store.put([
@@ -474,14 +480,17 @@ function withLock<T>(key: string, fn: () => Promise<T>): Promise<T> {
474
480
  export function executeScratchOp(
475
481
  workspacePath: string,
476
482
  workspaceId: string,
477
- op: ScratchOp
483
+ op: ScratchOp,
484
+ imageBytes?: Uint8Array
478
485
  ): Promise<ScratchOpResult> {
479
486
  return withLock(workspacePath, async () => {
480
487
  const { document, writer } = await loadScratchpadDoc(workspacePath)
481
488
  const store = buildStore(document, writer)
482
489
  // add-image decodes/resizes the file first, so it's the one async op.
483
490
  const result =
484
- op.kind === 'add-image' ? await applyAddImage(store, workspacePath, op) : applyOp(store, op)
491
+ op.kind === 'add-image'
492
+ ? await applyAddImage(store, workspacePath, op, imageBytes)
493
+ : applyOp(store, op)
485
494
  const next = store.getStoreSnapshot() as unknown as ScratchpadDoc
486
495
  await saveScratchpadDoc(next, workspacePath)
487
496
  publishEvent({ type: 'scratchpad:updated', workspaceId })
@@ -21,22 +21,25 @@ export async function hasSessionConfig(ws: WorkspaceRef, sessionId: string): Pro
21
21
  return Object.keys(await getSessionConfig(ws, sessionId)).length > 0
22
22
  }
23
23
 
24
+ // Without a session id, update the personal defaults used by new chats.
24
25
  export async function saveSessionConfig(
25
26
  ws: WorkspaceRef,
26
- sessionId: string,
27
+ sessionId: string | undefined,
27
28
  patch: SessionConfigPatch
28
29
  ): Promise<SessionConfig> {
29
30
  return updateWorkspaceState(ws, state => {
30
- const session = (state.sessions[sessionId] ??= {})
31
- const config: SessionConfig = { ...session.config }
31
+ const session = sessionId ? (state.sessions[sessionId] ??= {}) : undefined
32
+ const config: SessionConfig = { ...(session ? session.config : state.chatDefaults) }
32
33
  for (const key of ['model', 'effort', 'speedMode'] as const) {
33
34
  if (patch[key] === null) delete config[key]
34
35
  }
35
36
  if (typeof patch.model === 'string') config.model = patch.model
36
37
  if (typeof patch.effort === 'string') config.effort = patch.effort
37
38
  if (isSpeedMode(patch.speedMode)) config.speedMode = patch.speedMode
38
- if (Object.keys(config).length) session.config = config
39
- else delete session.config
39
+ if (session) {
40
+ if (Object.keys(config).length) session.config = config
41
+ else delete session.config
42
+ } else state.chatDefaults = config
40
43
  return config
41
44
  })
42
45
  }
@@ -2,6 +2,8 @@ import { isIdentityIconId } from '@/lib/identity-icons'
2
2
  import { newViewId } from '@/lib/ids'
3
3
  import type { PendingView, WorkspaceEntry, WorkspaceState } from '@/lib/types'
4
4
  import { readWorkspaceState, updateWorkspaceState, type WorkspaceRef } from '../workspace-state'
5
+ import { requestWorkspace } from '../workspaces/api'
6
+ import { cloudRoutes } from '../remote/routes'
5
7
  import { archiveViewSessions } from './archive'
6
8
 
7
9
  export class PendingViewError extends Error {
@@ -108,6 +110,21 @@ export async function completeViewBuild(ws: WorkspaceRef, id: string) {
108
110
  })
109
111
  }
110
112
 
113
+ // A remote view compiles on its owner, which cannot reach this Moi's state. The
114
+ // visitor's CLI calls this after a build to clear the views the owner now lists.
115
+ export async function completeRemoteViewBuilds(ws: WorkspaceEntry, request = requestWorkspace) {
116
+ if (!ws.remote) return
117
+ if (!Object.keys((await readWorkspaceState(ws)).pendingViews).length) return
118
+ const response = await request(cloudRoutes.compiledViews.path(ws.remote), { method: 'GET' })
119
+ if (!response.ok) throw new Error(`Could not list the owner's views (${response.status})`)
120
+ const { views } = (await response.json()) as { views: { id: string }[] }
121
+ const compiled = new Set(views.map(view => view.id))
122
+ await updateWorkspaceState(ws, state => {
123
+ for (const id of Object.keys(state.pendingViews))
124
+ if (compiled.has(id)) delete state.pendingViews[id]
125
+ })
126
+ }
127
+
111
128
  // Follow a temporary id's rename in every build that runs in it.
112
129
  export function renameBuildSession(state: WorkspaceState, from: string, to: string): void {
113
130
  for (const view of Object.values(state.pendingViews)) {
@@ -0,0 +1,102 @@
1
+ import { HarnessTransitionError, reserveWorkspaceOperation } from '../workspaces/harness-transition'
2
+ import { IDENTITY_ICON_IDS } from '@/lib/identity-icons'
3
+ import { viewBuildDirectives } from '@/lib/view-build-directives'
4
+ import { viewIdFromTab } from '@/lib/workspace-tabs'
5
+ import type { WorkspaceEntry } from '@/lib/types'
6
+ import { getCollabReferencePath } from '../collab/config'
7
+ import { harnessFor } from '../harness/registry'
8
+ import type { SendMessageInput } from '../harness/types'
9
+ import { getPinnedSession, saveSelectedSession, resolveRenamedSession } from './selected'
10
+ import { getSessionEntry, updateSessionEntry } from './store'
11
+ import {
12
+ getPendingView,
13
+ listPendingViews,
14
+ patchPendingView,
15
+ PendingViewError
16
+ } from './pending-views'
17
+
18
+ // Both ordinary chat and initial build requests use this boundary.
19
+ export async function sendWorkspaceMessage(
20
+ ws: WorkspaceEntry,
21
+ input: SendMessageInput & { viewBuildId?: string }
22
+ ) {
23
+ const release = reserveWorkspaceOperation(ws.id)
24
+ try {
25
+ const { getWorkspace } = await import('../workspaces/registry')
26
+ const current = await getWorkspace(ws.id)
27
+ if (current && (current.harness ?? 'claude-code') !== (ws.harness ?? 'claude-code'))
28
+ throw new HarnessTransitionError('Agent changed. Start a new chat')
29
+ const { prepareWorkspaceHarness } = await import('../workspaces/change-harness')
30
+ await prepareWorkspaceHarness(ws)
31
+ const { viewBuildId, ...message } = input
32
+ const sessionId = resolveRenamedSession(ws.id, input.sessionId)
33
+ const record = await getSessionEntry(ws, sessionId)
34
+ const tabId = input.context?.activeTab?.id ?? record.tabId ?? 'overview'
35
+ const targetViewId = viewBuildId ?? (input.isNew ? viewIdFromTab(tabId) : undefined)
36
+ const ownedViews = targetViewId
37
+ ? []
38
+ : (await listPendingViews(ws)).filter(view => view.buildSessionId === sessionId)
39
+ const pending = targetViewId
40
+ ? await getPendingView(ws, targetViewId)
41
+ : (ownedViews.find(view => view.id === viewIdFromTab(tabId)) ?? ownedViews[0])
42
+ const isBuildRequest = pending && (viewBuildId === pending.id || input.isNew)
43
+ if (
44
+ isBuildRequest &&
45
+ pending.buildSessionId &&
46
+ pending.buildSessionId !== sessionId &&
47
+ (pending.status === 'starting' ||
48
+ harnessFor(ws)
49
+ .activeSessions()
50
+ .some(
51
+ session => session.workspaceId === ws.id && session.sessionId === pending.buildSessionId
52
+ ))
53
+ )
54
+ throw new PendingViewError('This view is already being built in another chat', 409)
55
+ if (input.isNew && record.tabId !== tabId) {
56
+ record.tabId = tabId === 'overview' ? undefined : tabId
57
+ await updateSessionEntry(ws, sessionId, { tabId: record.tabId })
58
+ await saveSelectedSession(ws, sessionId, tabId, null)
59
+ }
60
+ if (isBuildRequest)
61
+ await patchPendingView(ws, pending.id, {
62
+ buildSessionId: sessionId
63
+ })
64
+ const collabReference = await getCollabReferencePath(ws.path, ws.harness)
65
+ const pinnedSessionId = await getPinnedSession(ws)
66
+ await harnessFor(ws).sendMessage({
67
+ ...message,
68
+ sessionId,
69
+ context: {
70
+ ...input.context,
71
+ // Resolve here for both browser messages and programmatic view builds;
72
+ // the agent must not infer file location from its local working directory.
73
+ workspaceMode: ws.remote ? 'remote' : 'local',
74
+ session: {
75
+ id: sessionId,
76
+ tabId: record.tabId,
77
+ pinned: pinnedSessionId === sessionId
78
+ },
79
+ ...(collabReference ? { collabReference } : {}),
80
+ directives: [
81
+ ...(input.context?.directives ?? []),
82
+ ...(isBuildRequest ? viewBuildDirectives(pending.id, IDENTITY_ICON_IDS) : []),
83
+ ...(isBuildRequest && record.fork
84
+ ? [
85
+ 'Inherited conversation is background. Work on the current request; do not resume unrelated earlier tasks.'
86
+ ]
87
+ : []),
88
+ ...(pending && input.isNew && pending.requirements !== input.content
89
+ ? [`Original view requirements:\n${pending.requirements}`]
90
+ : []),
91
+ ...(pending && input.attachments?.length
92
+ ? ['Use the attachments as reference material for the intended view.']
93
+ : [])
94
+ ]
95
+ }
96
+ })
97
+ if (pending && pending.status !== 'starting')
98
+ await patchPendingView(ws, pending.id, { status: 'submitted', error: undefined })
99
+ } finally {
100
+ release()
101
+ }
102
+ }
@@ -1,27 +1,19 @@
1
- import { HarnessTransitionError, reserveWorkspaceOperation } from '../workspaces/harness-transition'
1
+ import { sendWorkspaceMessage } from './send-message'
2
2
  import { IDENTITY_ICON_IDS } from '@/lib/identity-icons'
3
3
  import { viewBuildDirectives } from '@/lib/view-build-directives'
4
- import { viewIdFromTab, viewTabId } from '@/lib/workspace-tabs'
5
- import type { PendingView, SelectedSessionScope, WorkspaceEntry, WorkspaceTabId } from '@/lib/types'
6
- import { getCollabReferencePath } from '../collab/config'
4
+ import { viewTabId } from '@/lib/workspace-tabs'
5
+ import type { PendingView, WorkspaceEntry, WorkspaceTabId } from '@/lib/types'
7
6
  import { harnessFor } from '../harness/registry'
8
7
  import type { SendMessageInput } from '../harness/types'
9
8
  import { ForkUnsupportedError, inheritedHistoryBoundary } from '../harness/fork'
10
9
  import { updateWorkspaceState } from '../workspace-state'
11
- import {
12
- getPinnedSession,
13
- saveSelectedSession,
14
- resolveRenamedSession,
15
- selectSessionForTab
16
- } from './selected'
17
- import { getSessionEntry, setSessionTab, updateSessionEntry } from './store'
10
+ import { saveSelectedSession, resolveRenamedSession, selectSessionForTab } from './selected'
11
+ import { setSessionTab, updateSessionEntry } from './store'
18
12
  import { getSessionConfig, saveSessionConfig } from './config'
19
13
  import {
20
14
  createPendingView,
21
- getPendingView,
22
15
  listPendingViews,
23
16
  patchPendingView,
24
- PendingViewError,
25
17
  startViewBuild
26
18
  } from './pending-views'
27
19
 
@@ -37,100 +29,17 @@ export class ViewStartupError extends Error {
37
29
  type BuildSendOptions = Pick<
38
30
  SendMessageInput,
39
31
  'attachments' | 'optimisticId' | 'model' | 'effort' | 'speedMode' | 'stream'
40
- > & { selectedSessionScope?: SelectedSessionScope }
32
+ >
41
33
  export type SubmitViewInput = BuildSendOptions & { requirements: string; sessionId?: string }
42
34
 
43
- // Both ordinary chat and initial build requests use this boundary.
44
- export async function sendWorkspaceMessage(
45
- ws: WorkspaceEntry,
46
- input: SendMessageInput & { selectedSessionScope?: SelectedSessionScope; viewBuildId?: string }
47
- ) {
48
- const release = reserveWorkspaceOperation(ws.id)
49
- try {
50
- const { getWorkspace } = await import('../workspaces/registry')
51
- const current = await getWorkspace(ws.id)
52
- if (current && (current.type ?? 'claude-code') !== (ws.type ?? 'claude-code'))
53
- throw new HarnessTransitionError('Agent changed. Start a new chat')
54
- const { prepareWorkspaceHarness } = await import('../workspaces/change-harness')
55
- await prepareWorkspaceHarness(ws)
56
- const { selectedSessionScope, viewBuildId, ...message } = input
57
- const sessionId = resolveRenamedSession(ws.id, input.sessionId)
58
- const record = await getSessionEntry(ws, sessionId)
59
- const tabId = input.context?.activeTab?.id ?? record.tabId ?? 'overview'
60
- const targetViewId = viewBuildId ?? (input.isNew ? viewIdFromTab(tabId) : undefined)
61
- const ownedViews = targetViewId
62
- ? []
63
- : (await listPendingViews(ws)).filter(view => view.buildSessionId === sessionId)
64
- const pending = targetViewId
65
- ? await getPendingView(ws, targetViewId)
66
- : (ownedViews.find(view => view.id === viewIdFromTab(tabId)) ?? ownedViews[0])
67
- const isBuildRequest = pending && (viewBuildId === pending.id || input.isNew)
68
- if (
69
- isBuildRequest &&
70
- pending.buildSessionId &&
71
- pending.buildSessionId !== sessionId &&
72
- (pending.status === 'starting' ||
73
- harnessFor(ws)
74
- .activeSessions()
75
- .some(
76
- session => session.workspaceId === ws.id && session.sessionId === pending.buildSessionId
77
- ))
78
- )
79
- throw new PendingViewError('This view is already being built in another chat', 409)
80
- if (input.isNew && record.tabId !== tabId) {
81
- record.tabId = tabId === 'overview' ? undefined : tabId
82
- await attachSession(ws, tabId, sessionId, null, selectedSessionScope)
83
- }
84
- if (isBuildRequest)
85
- await patchPendingView(ws, pending.id, {
86
- buildSessionId: sessionId
87
- })
88
- const collabReference = await getCollabReferencePath(ws.path, ws.type)
89
- const pinnedSessionId = await getPinnedSession(ws)
90
- await harnessFor(ws).sendMessage({
91
- ...message,
92
- sessionId,
93
- context: {
94
- ...input.context,
95
- session: {
96
- id: sessionId,
97
- tabId: record.tabId,
98
- pinned: pinnedSessionId === sessionId
99
- },
100
- ...(collabReference ? { collabReference } : {}),
101
- directives: [
102
- ...(input.context?.directives ?? []),
103
- ...(isBuildRequest ? viewBuildDirectives(pending.id, IDENTITY_ICON_IDS) : []),
104
- ...(isBuildRequest && record.fork
105
- ? [
106
- 'Inherited conversation is background. Work on the current request; do not resume unrelated earlier tasks.'
107
- ]
108
- : []),
109
- ...(pending && input.isNew && pending.requirements !== input.content
110
- ? [`Original view requirements:\n${pending.requirements}`]
111
- : []),
112
- ...(pending && input.attachments?.length
113
- ? ['Use the attachments as reference material for the intended view.']
114
- : [])
115
- ]
116
- }
117
- })
118
- if (pending && pending.status !== 'starting')
119
- await patchPendingView(ws, pending.id, { status: 'submitted', error: undefined })
120
- } finally {
121
- release()
122
- }
123
- }
124
-
125
35
  async function attachSession(
126
36
  ws: WorkspaceEntry,
127
37
  tabId: WorkspaceTabId,
128
38
  sessionId: string,
129
- ifMatch?: string | null,
130
- selectedSessionScope: SelectedSessionScope = 'shared'
39
+ ifMatch?: string | null
131
40
  ) {
132
41
  await updateSessionEntry(ws, sessionId, { tabId: tabId === 'overview' ? undefined : tabId })
133
- if (selectedSessionScope === 'shared') await saveSelectedSession(ws, sessionId, tabId, ifMatch)
42
+ await saveSelectedSession(ws, sessionId, tabId, ifMatch)
134
43
  }
135
44
  async function sendBuild(
136
45
  ws: WorkspaceEntry,
@@ -176,7 +85,6 @@ async function failStartup(
176
85
 
177
86
  export async function submitView(ws: WorkspaceEntry, viewId: string, input: SubmitViewInput) {
178
87
  const tabId = viewTabId(viewId)
179
- const shared = (input.selectedSessionScope ?? 'shared') === 'shared'
180
88
  // The build, the chat's tab and the tab's selection start in one write. A
181
89
  // pinned chat takes the build and keeps its own tab.
182
90
  const { view, sessionId, pinned } = await updateWorkspaceState(ws, state => {
@@ -191,7 +99,7 @@ export async function submitView(ws: WorkspaceEntry, viewId: string, input: Subm
191
99
  )
192
100
  if (!pinned) {
193
101
  setSessionTab(state, sessionId, tabId)
194
- if (shared) selectSessionForTab(state, ws.id, sessionId, tabId)
102
+ selectSessionForTab(state, ws.id, sessionId, tabId)
195
103
  }
196
104
  return { view, sessionId, pinned }
197
105
  })
@@ -1,7 +1,7 @@
1
1
  import { lstat, realpath } from 'node:fs/promises'
2
2
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
3
3
 
4
- import type { WorkspaceType } from '@/lib/types'
4
+ import type { HarnessType } from '@/lib/types'
5
5
 
6
6
  import { skillsDirFor } from '../workspaces/init'
7
7
  import { bundledSkillNames } from './template'
@@ -47,10 +47,10 @@ async function inspectDirectory(path: string): Promise<SkillDirectory> {
47
47
  // their primary destination and include existing Claude/Codex installations.
48
48
  export async function resolveSkillLocations(
49
49
  workspaceRoot: string,
50
- type?: WorkspaceType
50
+ harness?: HarnessType
51
51
  ): Promise<SkillLocation[]> {
52
52
  const root = resolve(workspaceRoot)
53
- const primary = resolve(skillsDirFor(root, type))
53
+ const primary = resolve(skillsDirFor(root, harness))
54
54
  const directories = [
55
55
  ...new Set([primary, join(root, '.claude', 'skills'), join(root, '.agents', 'skills')])
56
56
  ]
@@ -61,7 +61,7 @@ export async function resolveSkillLocations(
61
61
  try {
62
62
  const inspected = await inspectDirectory(path)
63
63
  if (
64
- usesSharedWorkspaceSkill(type) ||
64
+ usesSharedWorkspaceSkill(harness) ||
65
65
  directory === primary ||
66
66
  inspected.exists ||
67
67
  inspected.brokenLink