moi-computer 0.3.0-next.3 → 0.3.1-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client/app/routes/WorkspaceRoute.tsx +3 -1
- package/client/components/shared/Composer.tsx +61 -0
- package/client/components/ui/dropdown-menu.tsx +3 -3
- package/client/features/applets/WidgetErrorBoundary.tsx +19 -3
- package/client/features/applets/WidgetShell.tsx +8 -1
- package/client/features/applets/applet-log.ts +100 -0
- package/client/features/applets/useApplet.ts +21 -7
- package/client/features/chat/ChatComposer.tsx +9 -16
- package/client/features/chat/ModelPicker.tsx +26 -40
- package/client/features/chat/chat-frames.ts +1 -0
- package/client/features/chat/model-order.ts +47 -0
- package/client/features/chat/useChat.ts +4 -0
- package/client/features/home/HomePage.tsx +13 -15
- package/client/features/home/WorkspacePreview.tsx +179 -31
- package/client/features/settings/GeneralSettings.tsx +12 -0
- package/client/features/views/ViewBuilderTab.tsx +10 -15
- package/client/features/widgets/WidgetFrame.tsx +3 -0
- package/client/features/widgets/WidgetGrid.tsx +1 -0
- package/client/features/widgets/Widgets.tsx +12 -3
- package/client/features/widgets/api.ts +47 -0
- package/client/features/widgets/useWidgetThumbnails.ts +107 -0
- package/client/features/widgets/widget-snapshot.ts +71 -0
- package/client/features/workspace/WorkspaceScreen.tsx +8 -1
- package/client/features/workspace/api.ts +6 -2
- package/client/index.css +0 -5
- package/client/main.tsx +6 -0
- package/dist/{chunk-rq0ar7vp.js → chunk-axszxe4c.js} +1 -1
- package/dist/chunk-b3ynfk4g.js +62 -0
- package/dist/chunk-jen6xcm1.js +14 -0
- package/dist/chunk-npwq6jmr.css +1 -0
- package/dist/index.html +1 -1
- package/lib/types.ts +66 -2
- package/package.json +3 -2
- package/server/api.ts +87 -3
- package/server/applet-log.ts +149 -0
- package/server/cli.ts +161 -7
- package/server/control.ts +81 -1
- package/server/functions.ts +44 -14
- package/server/harness/README.md +1 -0
- package/server/harness/claude-code/index.ts +3 -1
- package/server/harness/claude-code/sessions.ts +51 -0
- package/server/harness/codex/NOTES.md +88 -1
- package/server/harness/codex/adapter.ts +32 -0
- package/server/harness/codex/client.ts +36 -1
- package/server/harness/codex/index.ts +3 -0
- package/server/harness/openclaw/discovery.ts +139 -6
- package/server/harness/openclaw/gateway.ts +40 -18
- package/server/harness/openclaw/index.ts +4 -1
- package/server/harness/types.ts +15 -0
- package/server/layout.ts +81 -51
- package/server/scratchpad-assets.ts +41 -6
- package/server/scratchpad.ts +30 -0
- package/server/views.ts +5 -0
- package/server/web.ts +6 -0
- package/server/widgets.ts +23 -2
- package/workspace/.claude/skills/moi-workspace/SKILL.md +25 -1
- package/dist/chunk-6c24yndg.js +0 -61
- package/dist/chunk-cwqmay73.css +0 -1
|
@@ -116,12 +116,25 @@ async function startClient(): Promise<{ handle: GatewayHandle; client: GatewayIn
|
|
|
116
116
|
const { GatewayClient } = await import('openclaw/plugin-sdk/gateway-runtime')
|
|
117
117
|
|
|
118
118
|
let connected = false
|
|
119
|
+
// The SDK's `opts` is private since 2026.7.x — connect callbacks must be
|
|
120
|
+
// handed to the constructor, so wire them to a deferred promise up front.
|
|
121
|
+
let settleConnect!: { res: () => void; rej: (err: Error) => void }
|
|
122
|
+
const connectPromise = new Promise<void>((res, rej) => {
|
|
123
|
+
settleConnect = { res, rej }
|
|
124
|
+
})
|
|
119
125
|
const client = new GatewayClient({
|
|
120
126
|
url: `ws://127.0.0.1:${cfg.port}`,
|
|
121
127
|
token: cfg.token,
|
|
122
128
|
role: 'operator',
|
|
123
129
|
scopes: ['operator.admin', 'operator.read', 'operator.write'],
|
|
124
130
|
requestTimeoutMs: REQUEST_TIMEOUT_MS,
|
|
131
|
+
onHelloOk: () => {
|
|
132
|
+
connected = true
|
|
133
|
+
settleConnect.res()
|
|
134
|
+
},
|
|
135
|
+
onConnectError: err => {
|
|
136
|
+
settleConnect.rej(err)
|
|
137
|
+
},
|
|
125
138
|
onEvent: evt => {
|
|
126
139
|
const event = (evt as unknown as { event?: unknown }).event
|
|
127
140
|
const payload = (evt as unknown as { payload?: unknown }).payload
|
|
@@ -150,15 +163,16 @@ async function startClient(): Promise<{ handle: GatewayHandle; client: GatewayIn
|
|
|
150
163
|
() => rej(new Error(`openclaw connect timeout after ${CONNECT_TIMEOUT_MS}ms`)),
|
|
151
164
|
CONNECT_TIMEOUT_MS
|
|
152
165
|
)
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
166
|
+
connectPromise.then(
|
|
167
|
+
() => {
|
|
168
|
+
clearTimeout(t)
|
|
169
|
+
res()
|
|
170
|
+
},
|
|
171
|
+
err => {
|
|
172
|
+
clearTimeout(t)
|
|
173
|
+
rej(err)
|
|
174
|
+
}
|
|
175
|
+
)
|
|
162
176
|
client.start()
|
|
163
177
|
})
|
|
164
178
|
|
|
@@ -226,24 +240,32 @@ export async function withOneShotGateway<T>(fn: (rpc: Rpc) => Promise<T>): Promi
|
|
|
226
240
|
const cfg = await readGatewayConfig()
|
|
227
241
|
if (!cfg) return null
|
|
228
242
|
const { GatewayClient } = await import('openclaw/plugin-sdk/gateway-runtime')
|
|
243
|
+
let settleConnect!: { res: () => void; rej: (err: Error) => void }
|
|
244
|
+
const connectPromise = new Promise<void>((res, rej) => {
|
|
245
|
+
settleConnect = { res, rej }
|
|
246
|
+
})
|
|
229
247
|
const client = new GatewayClient({
|
|
230
248
|
url: `ws://127.0.0.1:${cfg.port}`,
|
|
231
249
|
token: cfg.token,
|
|
232
250
|
role: 'operator',
|
|
233
251
|
scopes: ['operator.admin', 'operator.read', 'operator.write'],
|
|
234
|
-
requestTimeoutMs: 2000
|
|
252
|
+
requestTimeoutMs: 2000,
|
|
253
|
+
onHelloOk: () => settleConnect.res(),
|
|
254
|
+
onConnectError: err => settleConnect.rej(err)
|
|
235
255
|
})
|
|
236
256
|
try {
|
|
237
257
|
await new Promise<void>((res, rej) => {
|
|
238
258
|
const t = setTimeout(() => rej(new Error('openclaw connect timeout')), 2000)
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
259
|
+
connectPromise.then(
|
|
260
|
+
() => {
|
|
261
|
+
clearTimeout(t)
|
|
262
|
+
res()
|
|
263
|
+
},
|
|
264
|
+
err => {
|
|
265
|
+
clearTimeout(t)
|
|
266
|
+
rej(err)
|
|
267
|
+
}
|
|
268
|
+
)
|
|
247
269
|
client.start()
|
|
248
270
|
})
|
|
249
271
|
return await fn((m, p = {}) => client.request(m, p) as Promise<never>)
|
|
@@ -8,7 +8,8 @@ import {
|
|
|
8
8
|
discoverOpenClawAgents,
|
|
9
9
|
getOpenClawModels,
|
|
10
10
|
getOpenClawSessionMessages,
|
|
11
|
-
getOpenClawSessions
|
|
11
|
+
getOpenClawSessions,
|
|
12
|
+
getOpenClawWorkspacePreview
|
|
12
13
|
} from './discovery'
|
|
13
14
|
import {
|
|
14
15
|
abortOpenClawRun,
|
|
@@ -41,6 +42,8 @@ export const openclawHarness: Harness = {
|
|
|
41
42
|
const rows = await getOpenClawSessions(ws.path, ws.agentId)
|
|
42
43
|
return rows.map(r => toSessionInfo(r, ws.path))
|
|
43
44
|
},
|
|
45
|
+
workspacePreview: (ws, includeFirstUserMessage) =>
|
|
46
|
+
getOpenClawWorkspacePreview(ws.path, ws.agentId, includeFirstUserMessage),
|
|
44
47
|
// Prefer the live view if we already hold one — keeps REST + WS in
|
|
45
48
|
// agreement for any reload that lands while a run is active. The first cold
|
|
46
49
|
// call also primes the live subscription so subsequent WS frames upsert
|
package/server/harness/types.ts
CHANGED
|
@@ -48,6 +48,13 @@ export type HarnessCapabilities = {
|
|
|
48
48
|
nativeUserEcho: boolean
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
+
// Home-page workspace card data beyond thumbnails: latest session activity
|
|
52
|
+
// and (for widget-less workspaces) the oldest session's first user message.
|
|
53
|
+
export type WorkspaceActivityPreview = {
|
|
54
|
+
firstUserMessage?: string
|
|
55
|
+
updatedAt?: number
|
|
56
|
+
}
|
|
57
|
+
|
|
51
58
|
export type Harness = {
|
|
52
59
|
id: WorkspaceType
|
|
53
60
|
capabilities: HarnessCapabilities
|
|
@@ -61,6 +68,14 @@ export type Harness = {
|
|
|
61
68
|
|
|
62
69
|
// -- discovery / metadata ---------------------------------------------------
|
|
63
70
|
listSessions(ws: WorkspaceEntry): Promise<SessionInfo[]>
|
|
71
|
+
// Home-page card preview. Called for every card on the home screen, so
|
|
72
|
+
// implementations must stay cheap: no process spawns, no per-session
|
|
73
|
+
// transcript reads unless cached. Failures resolve to {} — the card
|
|
74
|
+
// renders without the activity fields.
|
|
75
|
+
workspacePreview(
|
|
76
|
+
ws: WorkspaceEntry,
|
|
77
|
+
includeFirstUserMessage: boolean
|
|
78
|
+
): Promise<WorkspaceActivityPreview>
|
|
64
79
|
sessionEvents(ws: WorkspaceEntry, sessionId: string): Promise<StreamEvent[]>
|
|
65
80
|
listModels(ws: WorkspaceEntry): Promise<Model[]>
|
|
66
81
|
// MCP server status for the connectors UI; absent = backend has no MCP story.
|
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 {
|
|
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
|
-
//
|
|
67
|
-
//
|
|
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
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
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
|
-
|
|
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
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
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
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
144
|
+
if (includeFirstUserMessage) {
|
|
145
|
+
const firstUserMessage = normalizePreviewMessage(providerPreview?.firstUserMessage)
|
|
146
|
+
return {
|
|
147
|
+
thumbnails,
|
|
148
|
+
...(firstUserMessage ? { firstUserMessage } : {}),
|
|
149
|
+
...(updatedAt !== undefined ? { updatedAt } : {})
|
|
107
150
|
}
|
|
108
|
-
}
|
|
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 {
|
|
153
|
+
return {
|
|
154
|
+
thumbnails,
|
|
155
|
+
...(updatedAt !== undefined ? { updatedAt } : {})
|
|
156
|
+
}
|
|
127
157
|
} catch {
|
|
128
|
-
return
|
|
158
|
+
return { thumbnails: [] }
|
|
129
159
|
}
|
|
130
160
|
}
|
|
@@ -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
|
|
180
|
-
// `.bak` backup
|
|
181
|
-
//
|
|
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))
|
|
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
|
+
}
|
package/server/scratchpad.ts
CHANGED
|
@@ -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
|
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
|
@@ -6,6 +6,7 @@ import { PORT } from './constants'
|
|
|
6
6
|
import { control } from './control'
|
|
7
7
|
import { EVENTS_TOPIC, setEventServer } from './events'
|
|
8
8
|
import { killAllWorkers } from './functions'
|
|
9
|
+
import { startScratchpadSweeper } from './scratchpad'
|
|
9
10
|
import { resolveScratchOp } from './scratchpad-relay'
|
|
10
11
|
import { allHarnesses, harnessFor } from './harness/registry'
|
|
11
12
|
import { getWorkspace } from './registry'
|
|
@@ -172,6 +173,11 @@ export const app = Bun.serve<WsData>({
|
|
|
172
173
|
// importing web.ts (which binds ports on load).
|
|
173
174
|
setEventServer(app)
|
|
174
175
|
|
|
176
|
+
// Periodically reclaim scratchpad asset files nothing references anymore —
|
|
177
|
+
// deleting an image in the browser (or an upload whose tab died) otherwise
|
|
178
|
+
// leaves its file behind forever. See sweepOrphanAssets.
|
|
179
|
+
startScratchpadSweeper()
|
|
180
|
+
|
|
175
181
|
// Graceful shutdown. In dev the supervisor sends SIGTERM on server-file
|
|
176
182
|
// changes; in any context Ctrl-C sends SIGINT. Close both servers and kill the
|
|
177
183
|
// 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]
|
|
@@ -112,6 +112,8 @@ never from inside `.moi/` itself. You don't pass paths; moi resolves the workspa
|
|
|
112
112
|
- `moi bundle --force` — rebuild all applets (use after changing `config`)
|
|
113
113
|
- `moi refresh` — re-fetch widget/view data without rebuilding (use after you mutated data the
|
|
114
114
|
widgets read — DB rows, files, external API records — so the displayed values catch up)
|
|
115
|
+
- `moi call-server-fn <module>/<fn> '[args]'` — invoke a `.server.ts` function directly (smoke test)
|
|
116
|
+
- `moi debug logs` — applet runtime errors on record (experimental)
|
|
115
117
|
- `moi theme --font=<key>` — change font theme (omit `--font` to list options)
|
|
116
118
|
- `moi theme --color=<key>` — change color preset (omit `--color` to list options)
|
|
117
119
|
- `moi config` — set the workspace name & icon (`moi config --help` for usage)
|
|
@@ -259,6 +261,28 @@ Typical loop: check/`bun install` deps → write `.moi/widgets/<name>.tsx` → `
|
|
|
259
261
|
on the dashboard → change it and re-`bundle`, or `moi refresh` after mutating data, or any other `moi`
|
|
260
262
|
command as needed. Views work the same way (`.moi/views/<name>.tsx`, appears as a nav tab).
|
|
261
263
|
|
|
264
|
+
# Debugging applets
|
|
265
|
+
|
|
266
|
+
`moi bundle` only proves an applet compiles — it can still fail to load in the browser, crash on
|
|
267
|
+
render, or throw in its server functions. Two feedback channels exist for what happens after the
|
|
268
|
+
build; reach for them when they'd help (smoke-testing something new, or investigating a problem):
|
|
269
|
+
|
|
270
|
+
- `moi call-server-fn widgets/hello/getGreeting` /
|
|
271
|
+
`moi call-server-fn views/crm/searchUsers '["ann", 10]'` — run one `.server.ts` function
|
|
272
|
+
directly (args are one JSON array). Each invocation runs in a fresh, isolated one-shot process
|
|
273
|
+
with the same env, module loading, and timeout as the browser's calls, so a pass means the real
|
|
274
|
+
path works — handy for trying a function without touching the UI. Server functions only; for
|
|
275
|
+
arbitrary scripts use `moi env exec`.
|
|
276
|
+
- `moi debug logs` — the applet errors the workspace has seen since each applet's last good
|
|
277
|
+
build: browser-side load failures and render crashes, plus server-function (rpc) errors. The
|
|
278
|
+
user's tab reports these automatically, so when the user says something is broken, what
|
|
279
|
+
happened is usually already on record — a good first place to look. Entries clear when their
|
|
280
|
+
applet next builds successfully. (`moi debug` is an experimental command group — expect its
|
|
281
|
+
output and flags to evolve; use `--json` when you need to parse it.)
|
|
282
|
+
|
|
283
|
+
`moi bundle`'s footer also mentions when runtime errors are on record, so standing breakage
|
|
284
|
+
surfaces on its own.
|
|
285
|
+
|
|
262
286
|
# Views
|
|
263
287
|
|
|
264
288
|
Full-screen apps, one per nav tab — the user switches tabs; there is no routing inside a view.
|
|
@@ -304,4 +328,4 @@ This skill is installed with moi (via the CLI or the UI) and can fall behind whe
|
|
|
304
328
|
- **Then** — if you updated, mention it.
|
|
305
329
|
|
|
306
330
|
<!-- moi skill version marker — read by `moi skill` to detect drift; do not edit by hand -->
|
|
307
|
-
<moi-skill version="0.
|
|
331
|
+
<moi-skill version="0.6.0" />
|