moi-computer 0.3.0 → 0.3.1-next.1

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 (121) hide show
  1. package/client/api/workspace-keys.ts +2 -2
  2. package/client/app/AppRouter.tsx +0 -2
  3. package/client/app/routes/WorkspaceRoute.tsx +3 -1
  4. package/client/app/shell/SidebarLayout.tsx +3 -16
  5. package/client/assets/openai.svg +1 -3
  6. package/client/components/shared/Composer.tsx +112 -0
  7. package/client/components/ui/button.tsx +1 -1
  8. package/client/components/ui/dropdown-menu.tsx +3 -3
  9. package/client/components/ui/tooltip.tsx +12 -15
  10. package/client/features/applets/WidgetErrorBoundary.tsx +19 -3
  11. package/client/features/applets/WidgetShell.tsx +8 -1
  12. package/client/features/applets/applet-log.ts +100 -0
  13. package/client/features/applets/useApplet.ts +21 -7
  14. package/client/features/chat/ChatComposer.tsx +33 -30
  15. package/client/features/chat/ChatPanel.tsx +5 -2
  16. package/client/features/chat/MarkdownContent.tsx +20 -2
  17. package/client/features/chat/ModelPicker.tsx +29 -41
  18. package/client/features/chat/TurnView.tsx +2 -2
  19. package/client/features/chat/chat-frames.ts +14 -6
  20. package/client/features/chat/chat-send.ts +1 -1
  21. package/client/features/chat/chat-store.ts +22 -17
  22. package/client/features/chat/model-order.ts +47 -0
  23. package/client/features/chat/tool-group/ToolOutput.tsx +4 -12
  24. package/client/features/chat/tool-group/format.ts +0 -6
  25. package/client/features/chat/useChat.ts +15 -2
  26. package/client/features/connectors/McpServerCards.tsx +95 -0
  27. package/client/features/connectors/api.ts +0 -11
  28. package/client/features/home/HomePage.tsx +45 -42
  29. package/client/features/home/WorkspacePreview.tsx +179 -38
  30. package/client/features/home/api.ts +24 -12
  31. package/client/features/home/workspace-presentation.tsx +17 -15
  32. package/client/features/home/workspace-setup/CreateWorkspaceDialog.tsx +243 -0
  33. package/client/features/home/workspace-setup/ImportWorkspaceDialog.tsx +95 -0
  34. package/client/features/home/workspace-setup/WorkspaceAgentStep.tsx +230 -0
  35. package/client/features/home/workspace-setup/WorkspaceDialogContent.tsx +35 -0
  36. package/client/features/home/workspace-setup/useWorkspaceImport.ts +61 -0
  37. package/client/features/settings/ConnectorsSettings.tsx +89 -0
  38. package/client/features/settings/GeneralSettings.tsx +12 -0
  39. package/client/features/settings/SettingsLayout.tsx +2 -2
  40. package/client/features/settings/WorkspaceSettings.tsx +8 -4
  41. package/client/features/views/ViewBuilderTab.tsx +28 -29
  42. package/client/features/views/useViewBuilderActions.ts +1 -1
  43. package/client/features/widgets/WidgetFrame.tsx +3 -0
  44. package/client/features/widgets/WidgetGrid.tsx +1 -0
  45. package/client/features/widgets/Widgets.tsx +12 -3
  46. package/client/features/widgets/api.ts +47 -0
  47. package/client/features/widgets/useWidgetThumbnails.ts +107 -0
  48. package/client/features/widgets/widget-snapshot.ts +71 -0
  49. package/client/features/workspace/WorkspaceLayoutContext.tsx +3 -4
  50. package/client/features/workspace/WorkspaceScreen.tsx +19 -4
  51. package/client/features/workspace/api.ts +25 -3
  52. package/client/features/workspace/moi-context.ts +85 -0
  53. package/client/index.css +0 -5
  54. package/client/main.tsx +13 -4
  55. package/dist/{chunk-cs8vbert.js → chunk-1dfbr7n2.js} +2 -2
  56. package/dist/chunk-339jds4x.js +15 -0
  57. package/dist/chunk-3xsvsnhr.css +1 -0
  58. package/dist/{chunk-zpxrb1ce.js → chunk-anqmsbjt.js} +2 -2
  59. package/dist/chunk-hbvfb6sk.js +63 -0
  60. package/dist/chunk-jen6xcm1.js +14 -0
  61. package/dist/{chunk-kxmvv1ax.js → chunk-qwm5f6qk.js} +1 -1
  62. package/dist/{chunk-fjksw6xf.js → chunk-sxbfh73c.js} +1 -1
  63. package/dist/chunk-yp4srgqt.js +10 -0
  64. package/dist/index.html +1 -1
  65. package/dist/openai-ep9ht2pq.svg +1 -0
  66. package/lib/ids.ts +15 -0
  67. package/lib/moi-context.ts +170 -0
  68. package/lib/types.ts +95 -13
  69. package/lib/view-builder-directives.ts +16 -0
  70. package/lib/workspace-types.ts +12 -0
  71. package/package.json +4 -2
  72. package/server/api.ts +180 -34
  73. package/server/applet-log.ts +149 -0
  74. package/server/cli.ts +161 -7
  75. package/server/control.ts +81 -1
  76. package/server/functions.ts +44 -14
  77. package/server/harness/README.md +26 -9
  78. package/server/harness/claude-code/NOTES.md +20 -6
  79. package/server/harness/claude-code/adapter.ts +2 -2
  80. package/server/harness/claude-code/git-worktree.ts +32 -0
  81. package/server/harness/claude-code/index.ts +35 -13
  82. package/server/harness/claude-code/mcp.ts +16 -65
  83. package/server/harness/claude-code/models.ts +3 -0
  84. package/server/harness/claude-code/session.ts +196 -61
  85. package/server/harness/claude-code/sessions.ts +51 -0
  86. package/server/harness/codex/NOTES.md +41 -11
  87. package/server/harness/codex/adapter.ts +52 -6
  88. package/server/harness/codex/client.ts +69 -18
  89. package/server/harness/codex/discovery.ts +114 -0
  90. package/server/harness/codex/index.ts +12 -5
  91. package/server/harness/codex/probe.ts +4 -2
  92. package/server/harness/codex/session.ts +57 -5
  93. package/server/harness/executable.ts +82 -0
  94. package/server/harness/openclaw/adapter.ts +8 -1
  95. package/server/harness/openclaw/discovery.ts +139 -6
  96. package/server/harness/openclaw/gateway.ts +40 -18
  97. package/server/harness/openclaw/index.ts +12 -15
  98. package/server/harness/openclaw/session.ts +50 -10
  99. package/server/harness/openclaw/strip.ts +2 -2
  100. package/server/harness/shell-path.ts +79 -0
  101. package/server/harness/types.ts +37 -5
  102. package/server/layout.ts +81 -51
  103. package/server/registry.ts +57 -12
  104. package/server/scratchpad-assets.ts +41 -6
  105. package/server/scratchpad.ts +30 -0
  106. package/server/view-builders.ts +3 -2
  107. package/server/views.ts +5 -0
  108. package/server/web.ts +30 -8
  109. package/server/widgets.ts +23 -2
  110. package/server/workspace-import.ts +45 -0
  111. package/workspace/.claude/skills/moi-workspace/SKILL.md +27 -3
  112. package/client/features/connectors/ConnectorsPage.tsx +0 -92
  113. package/client/features/connectors/McpMenu.tsx +0 -145
  114. package/client/features/home/CreateWorkspaceDialog.tsx +0 -130
  115. package/client/features/home/CreateWorkspaceDialogSteps.tsx +0 -234
  116. package/dist/chunk-4vf1t6v1.js +0 -10
  117. package/dist/chunk-4z52b2av.css +0 -1
  118. package/dist/chunk-b4b276wx.js +0 -15
  119. package/dist/chunk-y82s1jxm.js +0 -61
  120. package/dist/openai-h13pza4b.svg +0 -3
  121. package/lib/view-builder-meta.ts +0 -35
package/server/layout.ts CHANGED
@@ -1,7 +1,6 @@
1
- import { readdir } from 'node:fs/promises'
2
1
  import { join } from 'path'
3
2
 
4
- import type { WidgetConfig, WorkspaceLayout, WorkspacePreview, WorkspaceTabId } from '@/lib/types'
3
+ import type { WorkspaceLayout, WorkspacePreview, WorkspaceTabId } from '@/lib/types'
5
4
  import { createDefaultWorkspaceLayout, createDefaultWorkspaceTabs } from '@/lib/workspace-layout'
6
5
 
7
6
  function isTabId(value: unknown): value is WorkspaceTabId {
@@ -33,10 +32,6 @@ function normalizeLayout(parsed: Record<string, unknown>): WorkspaceLayout {
33
32
  return layout as unknown as WorkspaceLayout
34
33
  }
35
34
 
36
- const DEFAULT_WIDGET_CONFIG: WidgetConfig = { rowSpan: 1, colSpan: 2 }
37
- const PREVIEW_COLS = 4
38
- const EMPTY_PREVIEW: WorkspacePreview = { cols: PREVIEW_COLS, items: [] }
39
-
40
35
  export function getLayoutPath(workspacePath: string): string {
41
36
  return join(workspacePath, '.moi', '.workspace.json')
42
37
  }
@@ -63,68 +58,103 @@ export async function saveLayout(layout: WorkspaceLayout, workspacePath: string)
63
58
  // possibly-stale `icon`.
64
59
  // A blind overwrite therefore erases a `moi config`-set name (and could revert an
65
60
  // icon). So drop whatever identity the body carries and re-apply the server-owned
66
- // `name`/`icon` from `existing` — conditionally, so an absent field never
67
- // serializes as `name: undefined`.
61
+ // fields from `existing` — conditionally, so an absent field never serializes
62
+ // as `name: undefined`. Widget thumbnails are likewise not the layout PUT's to
63
+ // write: they have their own endpoint (saveWidgetThumbnails), and the layout
64
+ // GET doesn't even ship the map — a round-trip would erase it.
68
65
  export function mergeLayoutForSave(
69
66
  existing: WorkspaceLayout,
70
67
  body: WorkspaceLayout
71
68
  ): WorkspaceLayout {
72
- const { name: _name, icon: _icon, ...editor } = body
69
+ const { name: _name, icon: _icon, widgetThumbnails: _thumbnails, ...editor } = body
73
70
  return {
74
71
  ...editor,
75
72
  ...(existing.name !== undefined && { name: existing.name }),
76
- ...(existing.icon !== undefined && { icon: existing.icon })
73
+ ...(existing.icon !== undefined && { icon: existing.icon }),
74
+ ...(existing.widgetThumbnails !== undefined && {
75
+ widgetThumbnails: existing.widgetThumbnails
76
+ })
77
77
  }
78
78
  }
79
79
 
80
- async function scanWidgetIds(workspacePath: string): Promise<Set<string>> {
81
- try {
82
- const entries = await readdir(join(workspacePath, '.moi', 'widgets'))
83
- return new Set(
84
- entries
85
- .filter(f => /\.(tsx|ts)$/.test(f) && !f.endsWith('.server.ts'))
86
- .map(f => f.replace(/\.tsx?$/, ''))
87
- )
88
- } catch {
89
- return new Set()
90
- }
80
+ // Merge a captured thumbnail set into the stored layout. Lives beside
81
+ // mergeLayoutForSave but on its own write path (PUT .../thumbnails): grid and
82
+ // theme saves never carry the base64 map, and a thumbnail save can't touch
83
+ // the grid. Entries merge over the existing map — removed widgets keep their
84
+ // last image.
85
+ export async function saveWidgetThumbnails(
86
+ workspacePath: string,
87
+ key: string,
88
+ images: Record<string, string>
89
+ ): Promise<void> {
90
+ const existing = await loadLayout(workspacePath)
91
+ await saveLayout(
92
+ {
93
+ ...existing,
94
+ widgetThumbnails: {
95
+ key,
96
+ // Server clock, so age-based invalidation doesn't trust client time.
97
+ at: new Date().toISOString(),
98
+ images: { ...existing.widgetThumbnails?.images, ...images }
99
+ }
100
+ },
101
+ workspacePath
102
+ )
91
103
  }
92
104
 
93
- export async function getWorkspacePreview(workspacePath: string): Promise<WorkspacePreview> {
105
+ // Thumbnails for the home screen's workspace card: a few captured widget
106
+ // images from the stored layout (see saveWidgetThumbnails). The card renders
107
+ // them as a loose stack, so the cap just keeps the payload small — anything
108
+ // past it would hide under the pile anyway.
109
+ const PREVIEW_LIMIT = 3
110
+ const PREVIEW_MESSAGE_LIMIT = 240
111
+
112
+ function normalizePreviewMessage(message: string | undefined): string | undefined {
113
+ const normalized = message?.replace(/\s+/g, ' ').trim()
114
+ if (!normalized) return undefined
115
+ if (normalized.length <= PREVIEW_MESSAGE_LIMIT) return normalized
116
+ return `${normalized.slice(0, PREVIEW_MESSAGE_LIMIT - 1).trimEnd()}…`
117
+ }
118
+
119
+ export async function getWorkspacePreview(
120
+ workspacePath: string,
121
+ getProviderPreview?: (includeFirstUserMessage: boolean) => Promise<{
122
+ firstUserMessage?: string
123
+ updatedAt?: number
124
+ }>
125
+ ): Promise<WorkspacePreview> {
94
126
  try {
95
127
  const layout = await loadLayout(workspacePath)
96
- if (!Array.isArray(layout.widgetGrid) || layout.widgetGrid.length === 0) return EMPTY_PREVIEW
97
-
98
- const validIds = await scanWidgetIds(workspacePath)
99
- if (validIds.size === 0) return EMPTY_PREVIEW
128
+ const images = layout.widgetThumbnails?.images ?? {}
129
+ const thumbnails = [...layout.widgetGrid]
130
+ .sort((a, b) => a.y - b.y || a.x - b.x)
131
+ .map(item => images[item.i])
132
+ .filter((image): image is string => typeof image === 'string')
133
+ .slice(0, PREVIEW_LIMIT)
134
+ // The message bubble is the card's fallback for "nothing to show": gate on
135
+ // captured thumbnails, not grid emptiness — a workspace with widgets that
136
+ // were never captured (never opened in a browser) still renders an empty
137
+ // folder otherwise.
138
+ const includeFirstUserMessage = thumbnails.length === 0
139
+ const providerPreview = await getProviderPreview?.(includeFirstUserMessage).catch(
140
+ () => undefined
141
+ )
142
+ const updatedAt = providerPreview?.updatedAt
100
143
 
101
- let manifest: Record<string, WidgetConfig> = {}
102
- try {
103
- const manifestPath = join(workspacePath, '.moi', '.build', 'widgets', 'manifest.json')
104
- const parsed = JSON.parse(await Bun.file(manifestPath).text())
105
- if (parsed && typeof parsed.config === 'object' && parsed.config !== null) {
106
- manifest = parsed.config as Record<string, WidgetConfig>
144
+ if (includeFirstUserMessage) {
145
+ const firstUserMessage = normalizePreviewMessage(providerPreview?.firstUserMessage)
146
+ return {
147
+ thumbnails,
148
+ ...(firstUserMessage ? { firstUserMessage } : {}),
149
+ ...(updatedAt !== undefined ? { updatedAt } : {})
107
150
  }
108
- } catch {}
109
-
110
- const items = layout.widgetGrid
111
- .map(({ i, x, y }) => {
112
- if (!validIds.has(i)) return null
113
- const cfg = manifest[i] ?? DEFAULT_WIDGET_CONFIG
114
- if (
115
- typeof x !== 'number' ||
116
- typeof y !== 'number' ||
117
- typeof cfg.colSpan !== 'number' ||
118
- typeof cfg.rowSpan !== 'number'
119
- ) {
120
- return null
121
- }
122
- return { x, y, w: cfg.colSpan, h: cfg.rowSpan }
123
- })
124
- .filter((v): v is { x: number; y: number; w: number; h: number } => v !== null)
151
+ }
125
152
 
126
- return { cols: PREVIEW_COLS, items }
153
+ return {
154
+ thumbnails,
155
+ ...(updatedAt !== undefined ? { updatedAt } : {})
156
+ }
127
157
  } catch {
128
- return EMPTY_PREVIEW
158
+ return { thumbnails: [] }
129
159
  }
130
160
  }
@@ -2,10 +2,13 @@ import { mkdir } from 'node:fs/promises'
2
2
  import { homedir } from 'node:os'
3
3
  import { join, resolve, sep } from 'path'
4
4
 
5
+ import { newWorkspaceId } from '@/lib/ids'
5
6
  import type { DiscoveredWorkspace, WorkspaceEntry, WorkspaceType } from '@/lib/types'
7
+ import { orderWorkspaceTypes } from '@/lib/workspace-types'
6
8
 
7
9
  import { DATA_DIR } from './data-dir'
8
10
  import { allHarnesses } from './harness/registry'
11
+ import type { DiscoveredWorkspaceCandidate } from './harness/types'
9
12
 
10
13
  // Replace the home-dir prefix with `~` for display. Keeps the original
11
14
  // absolute path in place; callers should put the result in `displayPath`.
@@ -61,7 +64,7 @@ export async function registerWorkspace(
61
64
  const existing = entries.find(e => e.path === normalPath)
62
65
  if (existing) return existing
63
66
  const entry: WorkspaceEntry = {
64
- id: crypto.randomUUID(),
67
+ id: newWorkspaceId(),
65
68
  path: normalPath,
66
69
  addedAt: new Date().toISOString(),
67
70
  ...(opts.type ? { type: opts.type } : {}),
@@ -138,20 +141,62 @@ export function liftToWorkspaceRoot(p: string): string {
138
141
  return segments.slice(0, i).join(sep) || sep
139
142
  }
140
143
 
141
- // Ask every harness for workspaces it knows about that aren't registered yet.
142
- // Precedence: entries from a specific backend (OpenClaw agents, Codex threads)
143
- // win over Claude Code's generic session-history scan when they claim the
144
- // same path — CC sessions exist in most directories an agent ever ran in.
145
- export async function discoverWorkspaces(): Promise<DiscoveredWorkspace[]> {
146
- const registeredPaths = new Set((await readRegistry()).map(e => e.path))
144
+ async function collectDiscoveredWorkspaces(
145
+ registeredPaths: Set<string>
146
+ ): Promise<DiscoveredWorkspaceCandidate[]> {
147
147
  const perHarness = await Promise.all(
148
148
  allHarnesses().map(
149
149
  h => h.discoverWorkspaces?.(registeredPaths).catch(() => []) ?? Promise.resolve([])
150
150
  )
151
151
  )
152
- const found = perHarness.flat()
153
- const specific = found.filter(w => w.type !== 'claude-code')
154
- const specificPaths = new Set(specific.map(w => w.path))
155
- const generic = found.filter(w => w.type === 'claude-code' && !specificPaths.has(w.path))
156
- return [...specific, ...generic].map(withDisplayPath)
152
+ return perHarness.flat()
153
+ }
154
+
155
+ export function groupDiscoveredWorkspaces(
156
+ candidates: DiscoveredWorkspaceCandidate[],
157
+ registeredPaths: Set<string> = new Set()
158
+ ): DiscoveredWorkspace[] {
159
+ const normalizedRegisteredPaths = new Set([...registeredPaths].map(path => resolve(path)))
160
+ const byPath = new Map<string, Set<WorkspaceType>>()
161
+
162
+ for (const candidate of candidates) {
163
+ const path = resolve(candidate.path)
164
+ if (normalizedRegisteredPaths.has(path)) continue
165
+ const types = byPath.get(path) ?? new Set<WorkspaceType>()
166
+ types.add(candidate.type)
167
+ byPath.set(path, types)
168
+ }
169
+
170
+ return [...byPath].map(([path, types]) => ({
171
+ path,
172
+ types: orderWorkspaceTypes(types)
173
+ }))
174
+ }
175
+
176
+ export function discoveredWorkspaceForPath(
177
+ path: string,
178
+ candidates: DiscoveredWorkspaceCandidate[]
179
+ ): DiscoveredWorkspace {
180
+ const normalizedPath = resolve(path)
181
+ return (
182
+ groupDiscoveredWorkspaces(candidates).find(workspace => workspace.path === normalizedPath) ?? {
183
+ path: normalizedPath,
184
+ types: []
185
+ }
186
+ )
187
+ }
188
+
189
+ // Ask every harness for workspaces it knows about that aren't registered yet,
190
+ // then combine providers that claim the same normalized folder.
191
+ export async function discoverWorkspaces(): Promise<DiscoveredWorkspace[]> {
192
+ const registeredPaths = new Set((await readRegistry()).map(e => e.path))
193
+ const found = await collectDiscoveredWorkspaces(registeredPaths)
194
+ return groupDiscoveredWorkspaces(found, registeredPaths).map(withDisplayPath)
195
+ }
196
+
197
+ // Inspect one folder through the same provider discovery used by the home
198
+ // suggestions. An empty types list means no provider recognized the folder.
199
+ export async function discoverWorkspace(path: string): Promise<DiscoveredWorkspace> {
200
+ const found = await collectDiscoveredWorkspaces(new Set())
201
+ return withDisplayPath(discoveredWorkspaceForPath(path, found))
157
202
  }
@@ -145,7 +145,7 @@ export async function extractInlineAssets(
145
145
  // tab's pending autosave — letting the sweep permanently delete a file the
146
146
  // surviving snapshot still pointed at.) The window covers the upload→autosave
147
147
  // gap and a stale tab that re-PUTs an old, still-referencing document alike.
148
- const SWEEP_GRACE_MS = 5 * 60_000
148
+ export const SWEEP_GRACE_MS = 5 * 60_000
149
149
 
150
150
  // When each still-unreferenced asset file was first seen unreferenced, keyed by
151
151
  // absolute path. In-memory and per-process: a restart just restarts the clock
@@ -176,9 +176,13 @@ async function bakReferencedAssets(bakFile: string): Promise<Set<string>> {
176
176
  }
177
177
  }
178
178
 
179
- // Delete asset files that neither the (just-saved) document nor the snapshot's
180
- // `.bak` backup references. Runs after every save; best-effort — a sweep
181
- // failure must never surface into the save.
179
+ // Delete asset files that no shape in the document uses and the snapshot's
180
+ // `.bak` backup doesn't reference. Best-effort — a sweep failure must never
181
+ // surface into a save. Runs after every save AND from the periodic sweeper
182
+ // (see startScratchpadSweeper in scratchpad.ts): a single sweep only STARTS an
183
+ // orphan's grace clock, so something must sweep again after the window elapses
184
+ // — on a quiet canvas (delete an image, walk away) the periodic pass is what
185
+ // actually reclaims the file.
182
186
  export async function sweepOrphanAssets(
183
187
  workspacePath: string,
184
188
  document: ScratchpadDoc,
@@ -190,18 +194,41 @@ export async function sweepOrphanAssets(
190
194
  const files = await readdir(dir).catch(() => [] as string[])
191
195
  if (files.length === 0) return
192
196
 
197
+ // A file is referenced only when an asset record points at it AND some
198
+ // shape still uses that asset. The shape check matters: tldraw's editor
199
+ // deletes only the shape when the user removes an image in the browser —
200
+ // the asset record stays in the document forever — so counting bare asset
201
+ // records as references kept every browser-deleted image's file pinned for
202
+ // good. An asset orphaned this way gets the normal grace window, so an
203
+ // undo shortly after the delete (which restores the shape and re-saves)
204
+ // resets its clock before anything is reclaimed.
205
+ const usedAssetIds = new Set<string>()
206
+ for (const record of Object.values(document?.store ?? {})) {
207
+ if (!record || typeof record !== 'object') continue
208
+ const r = record as { typeName?: string; props?: { assetId?: unknown } }
209
+ if (r.typeName === 'shape' && typeof r.props?.assetId === 'string') {
210
+ usedAssetIds.add(r.props.assetId)
211
+ }
212
+ }
193
213
  const referenced = new Set<string>()
194
214
  for (const record of Object.values(document?.store ?? {})) {
195
215
  if (!record || typeof record !== 'object') continue
196
- const r = record as { typeName?: string; props?: { src?: unknown } }
216
+ const r = record as { typeName?: string; id?: string; props?: { src?: unknown } }
197
217
  if (r.typeName !== 'asset' || typeof r.props?.src !== 'string') continue
218
+ if (typeof r.id !== 'string' || !usedAssetIds.has(r.id)) continue
198
219
  const name = assetSrcFileName(r.props.src)
199
220
  if (name) referenced.add(name)
200
221
  }
201
222
  if (bakFile) for (const name of await bakReferencedAssets(bakFile)) referenced.add(name)
202
223
 
203
224
  for (const name of files) {
204
- if (!ASSET_FILE_RE.test(name)) continue
225
+ if (!ASSET_FILE_RE.test(name)) {
226
+ // A `.tmp-*` sibling stranded by a crash between write and rename in
227
+ // storeScratchpadAsset. A live one exists for milliseconds, so anything
228
+ // older than the grace window (by mtime) is abandoned — reclaim it.
229
+ if (name.startsWith('.tmp-')) await reclaimStaleTmp(join(dir, name), now)
230
+ continue
231
+ }
205
232
  const path = join(dir, name)
206
233
  if (referenced.has(name)) {
207
234
  firstUnreferencedAt.delete(path) // referenced (again) — reset its clock
@@ -221,3 +248,11 @@ export async function sweepOrphanAssets(
221
248
  }
222
249
  } catch {}
223
250
  }
251
+
252
+ // Unlink an abandoned `.tmp-*` file once it's older than the grace window.
253
+ async function reclaimStaleTmp(path: string, now: number): Promise<void> {
254
+ try {
255
+ const { mtimeMs } = await stat(path)
256
+ if (now - mtimeMs > SWEEP_GRACE_MS) await unlink(path)
257
+ } catch {}
258
+ }
@@ -1,3 +1,4 @@
1
+ import { readdir } from 'node:fs/promises'
1
2
  import { join } from 'path'
2
3
 
3
4
  import tldrawPkg from 'tldraw/package.json'
@@ -6,8 +7,10 @@ import type { ScratchpadWriter } from '@/lib/types'
6
7
 
7
8
  import moiPkg from '../package.json'
8
9
  import {
10
+ SWEEP_GRACE_MS,
9
11
  assetSrcFileName,
10
12
  extractInlineAssets,
13
+ getScratchpadAssetsDir,
11
14
  scratchpadAssetFile,
12
15
  sweepOrphanAssets
13
16
  } from './scratchpad-assets'
@@ -99,6 +102,33 @@ export async function saveScratchpadDoc(
99
102
  await sweepOrphanAssets(workspacePath, document, `${path}.bak`)
100
103
  }
101
104
 
105
+ // The save-time sweep only STARTS an orphan's grace clock — deletion needs a
106
+ // later sweep after the window elapses, and on a quiet canvas (delete an
107
+ // image, walk away) no later save comes. Rather than scheduling per-workspace
108
+ // follow-ups, one dumb periodic pass re-sweeps every registered workspace:
109
+ // it also catches uploads whose tab died before the autosave and leftovers
110
+ // from before a restart (the grace clock is in-memory). Workspaces without
111
+ // asset files cost one readdir per tick.
112
+ export async function sweepAllWorkspaces(): Promise<void> {
113
+ // Lazy: the registry pulls in the harness adapters, which this module's
114
+ // other consumers (CLI reads, tests) shouldn't load just to parse a snapshot.
115
+ const { listWorkspaces } = await import('./registry')
116
+ for (const ws of await listWorkspaces()) {
117
+ try {
118
+ const dir = getScratchpadAssetsDir(ws.path)
119
+ if ((await readdir(dir).catch(() => [])).length === 0) continue
120
+ const { document } = await loadScratchpadDoc(ws.path)
121
+ await sweepOrphanAssets(ws.path, document ?? {}, `${getScratchpadPath(ws.path)}.bak`)
122
+ } catch {}
123
+ }
124
+ }
125
+
126
+ export function startScratchpadSweeper(): void {
127
+ const timer = setInterval(sweepAllWorkspaces, SWEEP_GRACE_MS + 60_000)
128
+ // A background sweeper must never hold the process open.
129
+ timer.unref?.()
130
+ }
131
+
102
132
  // When a save is about to overwrite a snapshot with a *different* schema (i.e.
103
133
  // the first write after a tldraw upgrade), keep the old file as `.bak` — the
104
134
  // manual escape hatch after a downgrade, since the new file won't open in the
@@ -1,6 +1,7 @@
1
1
  import { mkdir, rename } from 'node:fs/promises'
2
2
  import { join } from 'node:path'
3
3
 
4
+ import { newBuilderId } from '@/lib/ids'
4
5
  import type { AppletKind, ViewBuilder, ViewInfo } from '@/lib/types'
5
6
 
6
7
  import { DATA_DIR } from './data-dir'
@@ -107,7 +108,7 @@ export async function createViewBuilder(
107
108
  const builder = await mutateBuilders(workspacePath, builders => {
108
109
  const now = Date.now()
109
110
  const created: ViewBuilder = {
110
- id: crypto.randomUUID(),
111
+ id: newBuilderId(),
111
112
  kind: 'view',
112
113
  status: 'draft',
113
114
  input: { requirements: '' },
@@ -215,7 +216,7 @@ export async function setBuilder(
215
216
  const now = Date.now()
216
217
  const status = input.status ?? 'building'
217
218
  const created: ViewBuilder = {
218
- id: crypto.randomUUID(),
219
+ id: newBuilderId(),
219
220
  kind,
220
221
  status,
221
222
  input: { requirements: '' },
package/server/views.ts CHANGED
@@ -2,6 +2,7 @@ import { existsSync } from 'node:fs'
2
2
 
3
3
  import type { ViewConfig, ViewInfo } from '@/lib/types'
4
4
 
5
+ import { syncAppletLogAfterBuild } from './applet-log'
5
6
  import { buildApplets, getAppletPaths, listBuilt, scanSources, serveApplet } from './applets'
6
7
  import { reloadModules } from './functions'
7
8
  import { markViewBuilderReady } from './view-builders'
@@ -160,6 +161,10 @@ export async function handleBundleViews(
160
161
  const after = await readManifest(workspacePath)
161
162
  const afterBuilt = new Set(await listBuiltViews(workspacePath))
162
163
 
164
+ // Keep the applet error journal honest: record build failures, clear entries
165
+ // superseded by a successful rebuild (see docs/self-correction.md).
166
+ syncAppletLogAfterBuild(workspacePath, 'view', results)
167
+
163
168
  const identityChanged = results.some(
164
169
  r =>
165
170
  r.status === 'built' &&
package/server/web.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type { ClientMessage } from '@/lib/types'
1
+ import type { ClientMessage, StatusSnapshotMessage } from '@/lib/types'
2
+ import { isMoiContext } from '@/lib/moi-context'
2
3
 
3
4
  import index from '../client/index.html'
4
5
  import { api } from './api'
@@ -6,10 +7,11 @@ import { PORT } from './constants'
6
7
  import { control } from './control'
7
8
  import { EVENTS_TOPIC, setEventServer } from './events'
8
9
  import { killAllWorkers } from './functions'
10
+ import { startScratchpadSweeper } from './scratchpad'
9
11
  import { resolveScratchOp } from './scratchpad-relay'
10
12
  import { allHarnesses, harnessFor } from './harness/registry'
11
13
  import { getWorkspace } from './registry'
12
- import { addClient, removeClient, sendToClient } from './state'
14
+ import { addClient, broadcastAll, getClientCount, removeClient, sendToClient } from './state'
13
15
  import { distShell, prebuilt } from './static'
14
16
  import { renderStatus } from './status'
15
17
  import { serveVendorEmojibase, serveVendorReact } from './vendor'
@@ -28,6 +30,7 @@ function isClientMessage(value: unknown): value is ClientMessage {
28
30
  model?: unknown
29
31
  effort?: unknown
30
32
  stream?: unknown
33
+ context?: unknown
31
34
  attachments?: unknown
32
35
  opId?: unknown
33
36
  }
@@ -41,6 +44,7 @@ function isClientMessage(value: unknown): value is ClientMessage {
41
44
  (v.model === undefined || typeof v.model === 'string') &&
42
45
  (v.effort === undefined || typeof v.effort === 'string') &&
43
46
  (v.stream === undefined || typeof v.stream === 'boolean') &&
47
+ (v.context === undefined || isMoiContext(v.context)) &&
44
48
  (v.attachments === undefined ||
45
49
  (Array.isArray(v.attachments) && v.attachments.every(a => typeof a === 'string')))
46
50
  )
@@ -54,6 +58,13 @@ function isClientMessage(value: unknown): value is ClientMessage {
54
58
  // stays here, in the routes table, so Bun's dev bundler keys off it.
55
59
  const shell = prebuilt ? distShell : index
56
60
 
61
+ // Authoritative activity snapshot across all harnesses. Sent on chat-socket
62
+ // connect and re-broadcast periodically (below) so a spinner whose terminal
63
+ // status frame was lost self-heals without a reconnect.
64
+ function statusSnapshot(): StatusSnapshotMessage {
65
+ return { type: 'status_snapshot', sessions: allHarnesses().flatMap(h => h.activeSessions()) }
66
+ }
67
+
57
68
  type Upgradable = { upgrade(req: Request, opts: { data: WsData }): boolean }
58
69
 
59
70
  function upgrade(server: Upgradable, req: Request, data: WsData) {
@@ -88,7 +99,6 @@ export const app = Bun.serve<WsData>({
88
99
 
89
100
  // Client-side routes — serve the SPA shell.
90
101
  '/': shell,
91
- '/connectors': shell,
92
102
  '/dev': shell,
93
103
  '/dev/*': shell,
94
104
  '/workspace/*': shell,
@@ -110,11 +120,10 @@ export const app = Bun.serve<WsData>({
110
120
  open(ws) {
111
121
  if (ws.data.channel === 'chat') {
112
122
  addClient(ws)
113
- // Authoritative snapshot of every running session across all harnesses
114
- // so the client can light/clear spinners correctly even for runs whose
115
- // status transitions it missed while disconnected.
116
- const running = allHarnesses().flatMap(h => h.runningSessions())
117
- sendToClient(ws, { type: 'status_snapshot', running })
123
+ // Authoritative snapshot of every non-idle session across all
124
+ // harnesses so the client can light/clear spinners correctly even for
125
+ // runs whose status transitions it missed while disconnected.
126
+ sendToClient(ws, statusSnapshot())
118
127
  } else {
119
128
  ws.subscribe(EVENTS_TOPIC)
120
129
  }
@@ -143,6 +152,7 @@ export const app = Bun.serve<WsData>({
143
152
  model: data.model,
144
153
  effort: data.effort,
145
154
  stream: data.stream,
155
+ context: data.context,
146
156
  agentId: workspace.agentId
147
157
  })
148
158
  .catch(() => {})
@@ -172,6 +182,18 @@ export const app = Bun.serve<WsData>({
172
182
  // importing web.ts (which binds ports on load).
173
183
  setEventServer(app)
174
184
 
185
+ // The snapshot heartbeat: the client's reconcile fully replaces its activity
186
+ // map from each snapshot, so any stale spinner clears within one interval.
187
+ const SNAPSHOT_INTERVAL_MS = 30_000
188
+ setInterval(() => {
189
+ if (getClientCount() > 0) broadcastAll(statusSnapshot())
190
+ }, SNAPSHOT_INTERVAL_MS)
191
+
192
+ // Periodically reclaim scratchpad asset files nothing references anymore —
193
+ // deleting an image in the browser (or an upload whose tab died) otherwise
194
+ // leaves its file behind forever. See sweepOrphanAssets.
195
+ startScratchpadSweeper()
196
+
175
197
  // Graceful shutdown. In dev the supervisor sends SIGTERM on server-file
176
198
  // changes; in any context Ctrl-C sends SIGINT. Close both servers and kill the
177
199
  // per-workspace function workers so no child processes are orphaned.
package/server/widgets.ts CHANGED
@@ -1,7 +1,9 @@
1
- import { existsSync } from 'node:fs'
1
+ import { existsSync, statSync } from 'node:fs'
2
+ import { join } from 'path'
2
3
 
3
4
  import type { WidgetConfig, WidgetInfo } from '@/lib/types'
4
5
 
6
+ import { syncAppletLogAfterBuild } from './applet-log'
5
7
  import { buildApplets, getAppletPaths, listBuilt, serveApplet } from './applets'
6
8
  import { reloadModules } from './functions'
7
9
 
@@ -77,19 +79,34 @@ export function listBuiltWidgets(workspacePath: string): Promise<string[]> {
77
79
  return listBuilt(buildDir)
78
80
  }
79
81
 
82
+ // Content tag of a widget's built bundle: size+mtime of its entry, the same
83
+ // recipe as the serve ETag. Changes on every rebundle, so clients can use it
84
+ // to invalidate cached artifacts (widget thumbnails).
85
+ function widgetTag(buildDir: string, id: string): string | undefined {
86
+ try {
87
+ const stat = statSync(join(buildDir, id, 'index.js'))
88
+ return `${stat.size}-${Math.trunc(stat.mtimeMs)}`
89
+ } catch {
90
+ return undefined
91
+ }
92
+ }
93
+
80
94
  async function getWidgetList(workspacePath: string): Promise<WidgetInfo[]> {
81
95
  const [names, manifest] = await Promise.all([
82
96
  listBuiltWidgets(workspacePath),
83
97
  readManifest(workspacePath)
84
98
  ])
99
+ const { buildDir } = getAppletPaths(workspacePath, 'widget')
85
100
  return names.map(id => {
86
101
  const raw = manifest[id] ?? {}
87
102
  const rowSpan = VALID_SPANS.includes(raw.rowSpan) ? raw.rowSpan : DEFAULT_CONFIG.rowSpan
88
103
  const colSpan = VALID_SPANS.includes(raw.colSpan) ? raw.colSpan : DEFAULT_CONFIG.colSpan
89
104
  const requiredEnv = Array.isArray(raw.requiredEnv) ? raw.requiredEnv : undefined
105
+ const tag = widgetTag(buildDir, id)
90
106
  return {
91
107
  id,
92
- config: { rowSpan, colSpan, ...(requiredEnv ? { requiredEnv } : {}) } as WidgetConfig
108
+ config: { rowSpan, colSpan, ...(requiredEnv ? { requiredEnv } : {}) } as WidgetConfig,
109
+ ...(tag ? { tag } : {})
93
110
  }
94
111
  })
95
112
  }
@@ -122,6 +139,10 @@ export async function handleBundle(
122
139
  const results = await buildAllWidgets(workspacePath, force)
123
140
  const after = new Set(await listBuiltWidgets(workspacePath))
124
141
 
142
+ // Keep the applet error journal honest: record build failures, clear entries
143
+ // superseded by a successful rebuild (see docs/self-correction.md).
144
+ syncAppletLogAfterBuild(workspacePath, 'widget', results)
145
+
125
146
  const configChanged = results.some(r => {
126
147
  if (r.status !== 'built' || !r.config) return false
127
148
  const old = manifestBefore[r.name]
@@ -0,0 +1,45 @@
1
+ import { resolve } from 'node:path'
2
+
3
+ import type { WorkspaceType } from '@/lib/types'
4
+
5
+ import { discoverOpenClawAgents } from './harness/openclaw/discovery'
6
+ import type { OpenClawAgent } from './harness/openclaw/discovery'
7
+
8
+ export type WorkspaceImportMetadata = {
9
+ name?: string
10
+ agentId?: string
11
+ isDefault?: boolean
12
+ lastRunAt?: string
13
+ }
14
+
15
+ type DiscoverOpenClawAgents = () => Promise<OpenClawAgent[]>
16
+
17
+ function compareOpenClawAgents(a: OpenClawAgent, b: OpenClawAgent): number {
18
+ if (a.isDefault !== b.isDefault) return a.isDefault ? -1 : 1
19
+ const byLastRun = (b.lastRunAt ?? '').localeCompare(a.lastRunAt ?? '')
20
+ return byLastRun || a.agentId.localeCompare(b.agentId)
21
+ }
22
+
23
+ export async function resolveWorkspaceImportMetadata(
24
+ path: string,
25
+ type: WorkspaceType,
26
+ discoverAgents: DiscoverOpenClawAgents = discoverOpenClawAgents
27
+ ): Promise<WorkspaceImportMetadata> {
28
+ if (type !== 'openclaw') return {}
29
+
30
+ const normalizedPath = resolve(path)
31
+ const agent = (await discoverAgents())
32
+ .filter(candidate => resolve(candidate.path) === normalizedPath)
33
+ .sort(compareOpenClawAgents)[0]
34
+
35
+ if (!agent) {
36
+ throw new Error('OpenClaw is not initialized for this folder')
37
+ }
38
+
39
+ return {
40
+ ...(agent.name ? { name: agent.name } : {}),
41
+ agentId: agent.agentId,
42
+ ...(agent.isDefault ? { isDefault: true } : {}),
43
+ ...(agent.lastRunAt ? { lastRunAt: agent.lastRunAt } : {})
44
+ }
45
+ }