moi-computer 0.3.0 → 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.
Files changed (57) hide show
  1. package/client/app/routes/WorkspaceRoute.tsx +3 -1
  2. package/client/components/shared/Composer.tsx +61 -0
  3. package/client/components/ui/dropdown-menu.tsx +3 -3
  4. package/client/features/applets/WidgetErrorBoundary.tsx +19 -3
  5. package/client/features/applets/WidgetShell.tsx +8 -1
  6. package/client/features/applets/applet-log.ts +100 -0
  7. package/client/features/applets/useApplet.ts +21 -7
  8. package/client/features/chat/ChatComposer.tsx +9 -16
  9. package/client/features/chat/ModelPicker.tsx +26 -40
  10. package/client/features/chat/chat-frames.ts +1 -0
  11. package/client/features/chat/model-order.ts +47 -0
  12. package/client/features/chat/useChat.ts +4 -0
  13. package/client/features/home/HomePage.tsx +13 -15
  14. package/client/features/home/WorkspacePreview.tsx +179 -38
  15. package/client/features/settings/GeneralSettings.tsx +12 -0
  16. package/client/features/views/ViewBuilderTab.tsx +10 -15
  17. package/client/features/widgets/WidgetFrame.tsx +3 -0
  18. package/client/features/widgets/WidgetGrid.tsx +1 -0
  19. package/client/features/widgets/Widgets.tsx +12 -3
  20. package/client/features/widgets/api.ts +47 -0
  21. package/client/features/widgets/useWidgetThumbnails.ts +107 -0
  22. package/client/features/widgets/widget-snapshot.ts +71 -0
  23. package/client/features/workspace/WorkspaceScreen.tsx +8 -1
  24. package/client/features/workspace/api.ts +6 -2
  25. package/client/index.css +0 -5
  26. package/client/main.tsx +6 -0
  27. package/dist/{chunk-fjksw6xf.js → chunk-axszxe4c.js} +1 -1
  28. package/dist/chunk-b3ynfk4g.js +62 -0
  29. package/dist/chunk-jen6xcm1.js +14 -0
  30. package/dist/chunk-npwq6jmr.css +1 -0
  31. package/dist/index.html +1 -1
  32. package/lib/types.ts +66 -2
  33. package/package.json +3 -2
  34. package/server/api.ts +87 -3
  35. package/server/applet-log.ts +149 -0
  36. package/server/cli.ts +161 -7
  37. package/server/control.ts +81 -1
  38. package/server/functions.ts +44 -14
  39. package/server/harness/README.md +1 -0
  40. package/server/harness/claude-code/index.ts +3 -1
  41. package/server/harness/claude-code/sessions.ts +51 -0
  42. package/server/harness/codex/adapter.ts +32 -0
  43. package/server/harness/codex/client.ts +36 -1
  44. package/server/harness/codex/index.ts +3 -0
  45. package/server/harness/openclaw/discovery.ts +139 -6
  46. package/server/harness/openclaw/gateway.ts +40 -18
  47. package/server/harness/openclaw/index.ts +4 -1
  48. package/server/harness/types.ts +15 -0
  49. package/server/layout.ts +81 -51
  50. package/server/scratchpad-assets.ts +41 -6
  51. package/server/scratchpad.ts +30 -0
  52. package/server/views.ts +5 -0
  53. package/server/web.ts +6 -0
  54. package/server/widgets.ts +23 -2
  55. package/workspace/.claude/skills/moi-workspace/SKILL.md +24 -0
  56. package/dist/chunk-4z52b2av.css +0 -1
  57. package/dist/chunk-y82s1jxm.js +0 -61
package/server/control.ts CHANGED
@@ -1,10 +1,13 @@
1
+ import { stringify as devalueStringify } from 'devalue'
1
2
  import { resolve } from 'path'
2
3
 
3
4
  import type { WorkspaceEntry } from '@/lib/types'
4
5
 
6
+ import { clearAppletLog, getAppletLog, getAppletLogCount } from './applet-log'
5
7
  import { serializeWorkspaceBundle } from './bundle-queue'
6
8
  import { CONTROL_PORT } from './constants'
7
9
  import { applyEnvChanged } from './env-apply'
10
+ import { callFunctionEphemeral, parseFunctionPath } from './functions'
8
11
  import { processIcon } from './icon'
9
12
  import { loadLayout, saveLayout } from './layout'
10
13
  import { publishEvent } from './events'
@@ -119,7 +122,84 @@ export const control = Bun.serve({
119
122
  }
120
123
  }
121
124
  })
122
- ws.send(JSON.stringify({ ok: true, workspacePath, results }))
125
+ // Entries still standing after the rebuild's clear-on-success sweep —
126
+ // the CLI nudges the agent toward `moi debug logs` when non-zero.
127
+ ws.send(
128
+ JSON.stringify({
129
+ ok: true,
130
+ workspacePath,
131
+ results,
132
+ logCount: getAppletLogCount(workspacePath)
133
+ })
134
+ )
135
+ return
136
+ }
137
+
138
+ // The applet error journal — `moi debug logs` (docs/self-correction.md).
139
+ if (data.type === 'debug:logs') {
140
+ const match = await resolveWorkspace(ws, data.path)
141
+ if (!match) return
142
+ if (data.clear === true) {
143
+ ws.send(JSON.stringify({ ok: true, cleared: clearAppletLog(match.path) }))
144
+ return
145
+ }
146
+ ws.send(JSON.stringify({ ok: true, entries: getAppletLog(match.path) }))
147
+ return
148
+ }
149
+
150
+ // Direct server-function invocation — `moi call-server-fn <module>/<fn>`.
151
+ // Runs in an EPHEMERAL worker: a fresh process spawned for this one call
152
+ // and killed after, so a debug invocation is fully isolated from the
153
+ // warm pool the widgets use (same env/timeout/wire format otherwise).
154
+ // Args arrive as plain JSON (easier to hand-write than devalue's wire
155
+ // format) and are re-encoded for the worker; the result goes back
156
+ // devalue-encoded for the CLI to render.
157
+ if (data.type === 'call-server-fn') {
158
+ const match = await resolveWorkspace(ws, data.path)
159
+ if (!match) return
160
+ const parsed = parseFunctionPath(String(data.fn ?? ''))
161
+ if (!parsed) {
162
+ ws.send(
163
+ JSON.stringify({
164
+ error: `Invalid function path "${data.fn}". Use <module>/<fn>, e.g. widgets/hello/getGreeting.`
165
+ })
166
+ )
167
+ return
168
+ }
169
+ let args: unknown
170
+ try {
171
+ args = JSON.parse(String(data.args ?? '[]'))
172
+ } catch (err) {
173
+ ws.send(
174
+ JSON.stringify({
175
+ error: `Arguments must be valid JSON: ${err instanceof Error ? err.message : String(err)}`
176
+ })
177
+ )
178
+ return
179
+ }
180
+ if (!Array.isArray(args)) {
181
+ ws.send(
182
+ JSON.stringify({ error: 'Arguments must be a JSON array, e.g. \'["ann", 10]\'' })
183
+ )
184
+ return
185
+ }
186
+ const t0 = performance.now()
187
+ try {
188
+ const result = await callFunctionEphemeral(
189
+ parsed.module,
190
+ parsed.name,
191
+ devalueStringify(args),
192
+ match.path
193
+ )
194
+ ws.send(JSON.stringify({ ok: true, result, ms: Math.round(performance.now() - t0) }))
195
+ } catch (err) {
196
+ ws.send(
197
+ JSON.stringify({
198
+ error: err instanceof Error ? err.message : String(err),
199
+ ms: Math.round(performance.now() - t0)
200
+ })
201
+ )
202
+ }
123
203
  return
124
204
  }
125
205
 
@@ -186,20 +186,10 @@ export function parseFunctionPath(tail: string): { module: string; name: string
186
186
  return { module, name }
187
187
  }
188
188
 
189
- export async function callFunction(
190
- module: string,
191
- name: string,
192
- args: string,
193
- workspacePath: string
194
- ): Promise<string> {
195
- // Resolve the workspace env before (maybe) spawning, so a fresh worker picks
196
- // up current .env + custom overrides. Env is fixed at spawn — an already-warm
197
- // worker keeps its snapshot until restartWorker() reaps it. Widgets only see
198
- // secrets scoped to the 'widgets' sink.
199
- const workspaceEnv = await resolveWorkspaceEnv(workspacePath)
200
- const slot = getOrSpawn(workspacePath, workspaceEnv)
201
- await slot.readyPromise
202
-
189
+ // Issue one call against a live slot: register a pending entry, send the IPC
190
+ // frame, settle from the worker's reply (or the timeout). Shared by the warm
191
+ // pool path (callFunction) and the ephemeral path (callFunctionEphemeral).
192
+ function callInSlot(slot: Slot, module: string, name: string, args: string): Promise<string> {
203
193
  slot.calls++
204
194
  slot.lastCallAt = Date.now()
205
195
 
@@ -223,6 +213,46 @@ export async function callFunction(
223
213
  })
224
214
  }
225
215
 
216
+ export async function callFunction(
217
+ module: string,
218
+ name: string,
219
+ args: string,
220
+ workspacePath: string
221
+ ): Promise<string> {
222
+ // Resolve the workspace env before (maybe) spawning, so a fresh worker picks
223
+ // up current .env + custom overrides. Env is fixed at spawn — an already-warm
224
+ // worker keeps its snapshot until restartWorker() reaps it. Widgets only see
225
+ // secrets scoped to the 'widgets' sink.
226
+ const workspaceEnv = await resolveWorkspaceEnv(workspacePath)
227
+ const slot = getOrSpawn(workspacePath, workspaceEnv)
228
+ await slot.readyPromise
229
+ return callInSlot(slot, module, name, args)
230
+ }
231
+
232
+ // One-shot, isolated invocation — `moi call-server-fn`'s path. Spawns a fresh
233
+ // worker just for this call and kills it afterwards, so a debug invocation
234
+ // never touches the warm pool the widgets use: no shared module-level state in
235
+ // either direction, and a call that wedges the process takes the throwaway
236
+ // worker with it, not the pool. Same env resolution, module loading, timeout,
237
+ // and devalue wire format as the pool path — only the process lifetime differs.
238
+ // The slot is never registered in the LRU cache; its onExit cache-cleanup guard
239
+ // no-ops for an uncached slot.
240
+ export async function callFunctionEphemeral(
241
+ module: string,
242
+ name: string,
243
+ args: string,
244
+ workspacePath: string
245
+ ): Promise<string> {
246
+ const workspaceEnv = await resolveWorkspaceEnv(workspacePath)
247
+ const slot = spawnSlot(workspacePath, workspaceEnv)
248
+ try {
249
+ await slot.readyPromise
250
+ return await callInSlot(slot, module, name, args)
251
+ } finally {
252
+ killSlot(slot, 'Ephemeral call finished')
253
+ }
254
+ }
255
+
226
256
  // Kill every live worker. Called from the server's shutdown handler so a
227
257
  // dev-supervisor restart (or Ctrl-C) never orphans worker child processes.
228
258
  // killSlot is idempotent, so a dispose() racing in via clear() is harmless.
@@ -208,6 +208,7 @@ Legend: ✅ supported · ⚠️ partial/workaround · ❌ missing.
208
208
  | Images in input | ✅ base64 blocks | ⚠️ materialize to path | ✅ data URL or path |
209
209
  | Interactive approvals | ⚠️ (we bypass) | ✅ | ✅ server→client requests (we bypass) |
210
210
  | Session list/history API | ✅ `listSessions()` + jsonl | ✅ `sessions.get` | ✅ `thread/list`/`read` |
211
+ | Home card preview | ✅ session file scan | ✅ cached first message | ⚠️ live app-server only |
211
212
  | MCP status | ✅ `mcpServerStatus()` | n/a | ✅ `mcpServerStatus/list` |
212
213
  | Usage reporting | ⚠️ cost/duration on `result` (adapter drops tokens) | ✅ tokens + cost per turn | ✅ live + rate limits |
213
214
  | Structured output | ❌ | ❌ | ✅ per turn |
@@ -16,7 +16,7 @@ import {
16
16
  restartWorkspaceSessions,
17
17
  sendCCMessage
18
18
  } from './session'
19
- import { getSessionEvents, getSessions } from './sessions'
19
+ import { getSessionEvents, getSessions, getSessionWorkspacePreview } from './sessions'
20
20
 
21
21
  function fmtDuration(ms: number): string {
22
22
  const s = Math.floor(ms / 1000)
@@ -72,6 +72,8 @@ export const claudeCodeHarness: Harness = {
72
72
  runningSessions: () => getCCRunningSessions(),
73
73
 
74
74
  listSessions: ws => getSessions(ws.path),
75
+ workspacePreview: (ws, includeFirstUserMessage) =>
76
+ getSessionWorkspacePreview(ws.path, includeFirstUserMessage),
75
77
  sessionEvents: (ws, sessionId) => getSessionEvents(sessionId, ws.path),
76
78
  listModels: ws => getClaudeModels(ws.path),
77
79
  // The SDK's McpServerStatus is a superset of the UI's McpServer (extra
@@ -6,6 +6,18 @@ import type { SessionInfo, StreamEvent } from '@/lib/types'
6
6
 
7
7
  import { ClaudeAdapter } from './adapter'
8
8
 
9
+ export type SessionFirstPromptCandidate = {
10
+ sessionId: string
11
+ firstPrompt?: string
12
+ createdAt?: number
13
+ lastModified: number
14
+ }
15
+
16
+ export type SessionWorkspacePreview = {
17
+ firstUserMessage?: string
18
+ updatedAt?: number
19
+ }
20
+
9
21
  export async function getSessions(workspacePath: string): Promise<SessionInfo[]> {
10
22
  const sessions = await listSessions({ dir: workspacePath })
11
23
  return sessions.map(s => ({
@@ -16,6 +28,45 @@ export async function getSessions(workspacePath: string): Promise<SessionInfo[]>
16
28
  }))
17
29
  }
18
30
 
31
+ export function selectOldestSessionFirstUserMessage(
32
+ sessions: SessionFirstPromptCandidate[]
33
+ ): string | undefined {
34
+ const oldest = sessions
35
+ .slice()
36
+ .sort(
37
+ (a, b) =>
38
+ (a.createdAt ?? a.lastModified) - (b.createdAt ?? b.lastModified) ||
39
+ a.sessionId.localeCompare(b.sessionId)
40
+ )[0]
41
+ return oldest?.firstPrompt
42
+ }
43
+
44
+ export function selectLatestSessionUpdatedAt(
45
+ sessions: Pick<SessionFirstPromptCandidate, 'lastModified'>[]
46
+ ): number | undefined {
47
+ return sessions.reduce<number | undefined>(
48
+ (latest, session) =>
49
+ latest === undefined || session.lastModified > latest ? session.lastModified : latest,
50
+ undefined
51
+ )
52
+ }
53
+
54
+ export async function getSessionWorkspacePreview(
55
+ workspacePath: string,
56
+ includeFirstUserMessage: boolean
57
+ ): Promise<SessionWorkspacePreview> {
58
+ const sessions = await listSessions({ dir: workspacePath })
59
+ const updatedAt = selectLatestSessionUpdatedAt(sessions)
60
+ const firstUserMessage = includeFirstUserMessage
61
+ ? selectOldestSessionFirstUserMessage(sessions)
62
+ : undefined
63
+
64
+ return {
65
+ ...(firstUserMessage ? { firstUserMessage } : {}),
66
+ ...(updatedAt !== undefined ? { updatedAt } : {})
67
+ }
68
+ }
69
+
19
70
  /**
20
71
  * Replay a session's persisted raw messages through a fresh adapter and
21
72
  * return the resulting StreamEvents. Events are carefully NOT deduplicated —
@@ -11,6 +11,8 @@
11
11
  import type { Part, StreamEvent, SystemNotice, ToolCall, ToolState, Turn } from '@/lib/format'
12
12
  import type { Model, SessionInfo } from '@/lib/types'
13
13
 
14
+ import type { WorkspaceActivityPreview } from '../types'
15
+
14
16
  // ---- protocol shapes (subset we consume) ------------------------------------
15
17
 
16
18
  export type CodexUserInput =
@@ -113,6 +115,36 @@ export function codexThreadToSessionInfo(t: CodexThread): SessionInfo {
113
115
  }
114
116
  }
115
117
 
118
+ // Home-page card preview from thread/list alone: `preview` already carries the
119
+ // thread's first-message snippet, so no thread/read is needed. The oldest
120
+ // thread by creation supplies the message; the newest activity supplies the
121
+ // timestamp.
122
+ export function selectCodexWorkspacePreview(
123
+ threads: CodexThread[],
124
+ includeFirstUserMessage: boolean
125
+ ): WorkspaceActivityPreview {
126
+ const latest = threads.reduce<number | undefined>((acc, t) => {
127
+ const ts = t.updatedAt ?? t.createdAt
128
+ return ts !== undefined && (acc === undefined || ts > acc) ? ts : acc
129
+ }, undefined)
130
+ const updatedAt = latest !== undefined ? latest * 1000 : undefined
131
+
132
+ let firstUserMessage: string | undefined
133
+ if (includeFirstUserMessage) {
134
+ const oldest = [...threads].sort(
135
+ (a, b) =>
136
+ (a.createdAt ?? a.updatedAt ?? 0) - (b.createdAt ?? b.updatedAt ?? 0) ||
137
+ a.id.localeCompare(b.id)
138
+ )[0]
139
+ firstUserMessage = oldest?.preview?.trim() || undefined
140
+ }
141
+
142
+ return {
143
+ ...(firstUserMessage ? { firstUserMessage } : {}),
144
+ ...(updatedAt !== undefined ? { updatedAt } : {})
145
+ }
146
+ }
147
+
116
148
  export function codexModelToModel(m: CodexModel): Model {
117
149
  const efforts = (m.supportedReasoningEfforts ?? []).map(e => e.reasoningEffort)
118
150
  return {
@@ -17,8 +17,10 @@ import {
17
17
  type CodexThread,
18
18
  codexModelToModel,
19
19
  codexThreadToEvents,
20
- codexThreadToSessionInfo
20
+ codexThreadToSessionInfo,
21
+ selectCodexWorkspacePreview
21
22
  } from './adapter'
23
+ import type { WorkspaceActivityPreview } from '../types'
22
24
  import { debug } from '../../debug'
23
25
  import { tapWire } from '../debug'
24
26
  import { resolveWorkspaceEnv } from '../../workspace-env'
@@ -250,6 +252,20 @@ export async function getCodexClient(workspacePath: string): Promise<CodexClient
250
252
  }
251
253
  }
252
254
 
255
+ // Preview reads must not spawn an app-server — home-page cards render for
256
+ // every workspace, and starting a codex process per card is disproportionate.
257
+ // Returns the workspace's client only if one is already running.
258
+ async function peekCodexClient(workspacePath: string): Promise<CodexClient | null> {
259
+ const existing = clients.get(workspacePath)
260
+ if (!existing) return null
261
+ try {
262
+ const rec = await existing
263
+ return rec.client.isAlive() ? rec.client : null
264
+ } catch {
265
+ return null
266
+ }
267
+ }
268
+
253
269
  // Kill a workspace's app-server so the next message respawns it with fresh
254
270
  // env (env is process-level and frozen at spawn). Mirrors the semantics of
255
271
  // cc-session's restartWorkspaceSessions; in-flight turns are lost.
@@ -285,6 +301,25 @@ export async function getCodexSessions(workspacePath: string): Promise<SessionIn
285
301
  }
286
302
  }
287
303
 
304
+ // Home-page card preview. Peek-only: with no live app-server the card simply
305
+ // omits the activity fields until the workspace is opened once.
306
+ export async function getCodexWorkspacePreview(
307
+ workspacePath: string,
308
+ includeFirstUserMessage: boolean
309
+ ): Promise<WorkspaceActivityPreview> {
310
+ const client = await peekCodexClient(workspacePath)
311
+ if (!client) return {}
312
+ try {
313
+ const res = await client.rpc<{ data?: CodexThread[] }>('thread/list', {
314
+ cwd: workspacePath,
315
+ limit: 50
316
+ })
317
+ return selectCodexWorkspacePreview(res.data ?? [], includeFirstUserMessage)
318
+ } catch {
319
+ return {}
320
+ }
321
+ }
322
+
288
323
  // Account-wide model catalog (identical for every workspace); cached like the
289
324
  // Claude list in agent.ts, cleared on failure so a later call can retry.
290
325
  let codexModelsPromise: Promise<Model[]> | null = null
@@ -7,6 +7,7 @@ import {
7
7
  getCodexProcessInfo,
8
8
  getCodexSessions,
9
9
  getCodexThreadEvents,
10
+ getCodexWorkspacePreview,
10
11
  killAllCodexClients,
11
12
  killCodexWorkspace
12
13
  } from './client'
@@ -33,6 +34,8 @@ export const codexHarness: Harness = {
33
34
  runningSessions: () => getCodexRunningSessions(),
34
35
 
35
36
  listSessions: ws => getCodexSessions(ws.path),
37
+ workspacePreview: (ws, includeFirstUserMessage) =>
38
+ getCodexWorkspacePreview(ws.path, includeFirstUserMessage),
36
39
  // Prefer the live view when one exists; otherwise resume the thread so WS
37
40
  // frames upsert into the same view, and fall back to a static thread/read
38
41
  // if the resume fails.
@@ -4,6 +4,10 @@ import { join, resolve } from 'node:path'
4
4
 
5
5
  import type { Model } from '@/lib/types'
6
6
 
7
+ import { getGateway } from './gateway'
8
+ import type { GatewayHandle } from './gateway'
9
+ import { stripUserMessageMetadata } from './strip'
10
+
7
11
  export type OpenClawAgent = {
8
12
  path: string
9
13
  agentId: string
@@ -45,6 +49,17 @@ export type OpenClawSessionDetail = {
45
49
  messages: OpenClawMessage[]
46
50
  }
47
51
 
52
+ export type OpenClawSessionPreviewCandidate = {
53
+ key: string
54
+ updatedAt: number
55
+ detail: OpenClawSessionDetail | null
56
+ }
57
+
58
+ export type OpenClawWorkspacePreview = {
59
+ firstUserMessage?: string
60
+ updatedAt?: number
61
+ }
62
+
48
63
  const TIMEOUT_MS = 2000
49
64
 
50
65
  type AgentsList = {
@@ -101,17 +116,20 @@ async function withGatewayClient<T>(fn: (rpc: Rpc) => Promise<T>): Promise<T | n
101
116
  return null
102
117
  }
103
118
 
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 connect = new Promise<void>((res, rej) => {
123
+ settleConnect = { res, rej }
124
+ })
104
125
  const client = new GatewayClient({
105
126
  url: `ws://127.0.0.1:${port}`,
106
127
  token,
107
128
  role: 'operator',
108
129
  scopes: ['operator.admin', 'operator.read', 'operator.write'],
109
- requestTimeoutMs: TIMEOUT_MS
110
- })
111
-
112
- const connect = new Promise<void>((res, rej) => {
113
- client.opts.onHelloOk = () => res()
114
- client.opts.onConnectError = rej
130
+ requestTimeoutMs: TIMEOUT_MS,
131
+ onHelloOk: () => settleConnect.res(),
132
+ onConnectError: err => settleConnect.rej(err)
115
133
  })
116
134
 
117
135
  try {
@@ -207,6 +225,121 @@ export async function getOpenClawSessionMessages(
207
225
  return out ?? null
208
226
  }
209
227
 
228
+ function firstUserMessageText(detail: OpenClawSessionDetail | null): string | undefined {
229
+ const message = detail?.messages.find(candidate => candidate.role === 'user')
230
+ if (!message) return undefined
231
+
232
+ const raw =
233
+ typeof message.content === 'string'
234
+ ? message.content
235
+ : message.content
236
+ .filter(
237
+ (block): block is Extract<OpenClawContentBlock, { type: 'text' }> =>
238
+ block.type === 'text'
239
+ )
240
+ .map(block => block.text)
241
+ .join('\n')
242
+ const text = stripUserMessageMetadata(raw).trim()
243
+ return text || undefined
244
+ }
245
+
246
+ export function selectOldestOpenClawFirstUserMessage(
247
+ candidates: OpenClawSessionPreviewCandidate[]
248
+ ): string | undefined {
249
+ const oldest = candidates.slice().sort((a, b) => {
250
+ const aCreatedAt =
251
+ a.detail?.messages.find(message => typeof message.timestamp === 'number')?.timestamp ??
252
+ a.updatedAt
253
+ const bCreatedAt =
254
+ b.detail?.messages.find(message => typeof message.timestamp === 'number')?.timestamp ??
255
+ b.updatedAt
256
+ return aCreatedAt - bCreatedAt || a.key.localeCompare(b.key)
257
+ })[0]
258
+ return oldest ? firstUserMessageText(oldest.detail) : undefined
259
+ }
260
+
261
+ export function selectLatestOpenClawUpdatedAt(
262
+ sessions: Pick<OpenClawSessionRow, 'updatedAt'>[]
263
+ ): number | undefined {
264
+ return sessions.reduce<number | undefined>(
265
+ (latest, session) =>
266
+ latest === undefined || session.updatedAt > latest ? session.updatedAt : latest,
267
+ undefined
268
+ )
269
+ }
270
+
271
+ // Session-set identity for the first-user-message cache: transcripts are
272
+ // append-only, so once the oldest session's first message exists it can only
273
+ // change when a session is added or removed. Order-insensitive.
274
+ export function openClawSessionSetSignature(sessions: Pick<OpenClawSessionRow, 'key'>[]): string {
275
+ return sessions
276
+ .map(session => session.key)
277
+ .sort()
278
+ .join('\n')
279
+ }
280
+
281
+ const firstUserMessageCache = new Map<string, { signature: string; message: string }>()
282
+
283
+ export async function getOpenClawWorkspacePreview(
284
+ workspacePath: string,
285
+ agentId: string | undefined,
286
+ includeFirstUserMessage: boolean
287
+ ): Promise<OpenClawWorkspacePreview> {
288
+ // Preview reads ride the shared persistent gateway connection instead of a
289
+ // one-shot client per home-page card; per-call timeouts keep the card fast
290
+ // when the gateway is up but slow.
291
+ let gateway: GatewayHandle
292
+ try {
293
+ gateway = await getGateway()
294
+ } catch {
295
+ return {}
296
+ }
297
+ const rpc: Rpc = (method, params = {}) =>
298
+ withTimeout(gateway.rpc(method, params), TIMEOUT_MS, method)
299
+
300
+ try {
301
+ const id = agentId ?? (await resolveAgentIdForPath(rpc, workspacePath))
302
+ if (!id) return {}
303
+
304
+ const res = await rpc<{ sessions: OpenClawSessionRow[] }>('sessions.list', {
305
+ agentId: id
306
+ })
307
+ const updatedAt = selectLatestOpenClawUpdatedAt(res.sessions)
308
+ if (!includeFirstUserMessage) {
309
+ return updatedAt !== undefined ? { updatedAt } : {}
310
+ }
311
+
312
+ const signature = openClawSessionSetSignature(res.sessions)
313
+ const cached = firstUserMessageCache.get(workspacePath)
314
+ let firstUserMessage = cached?.signature === signature ? cached.message : undefined
315
+
316
+ if (firstUserMessage === undefined) {
317
+ const candidates = await Promise.all(
318
+ res.sessions.map(async session => ({
319
+ key: session.key,
320
+ updatedAt: session.updatedAt,
321
+ detail: await rpc<OpenClawSessionDetail>('sessions.get', { key: session.key }).catch(
322
+ () => null
323
+ )
324
+ }))
325
+ )
326
+ firstUserMessage = selectOldestOpenClawFirstUserMessage(candidates)
327
+ // Only cache found messages: a session without a user message yet can
328
+ // gain one later without the session set changing.
329
+ if (firstUserMessage) {
330
+ firstUserMessageCache.set(workspacePath, { signature, message: firstUserMessage })
331
+ }
332
+ }
333
+
334
+ return {
335
+ ...(firstUserMessage ? { firstUserMessage } : {}),
336
+ ...(updatedAt !== undefined ? { updatedAt } : {})
337
+ }
338
+ } catch {
339
+ return {}
340
+ }
341
+ }
342
+
210
343
  // One entry from the gateway's `models.list` catalog. The catalog is
211
344
  // gateway-wide (no per-agent param) — the allowed model set filtered by config.
212
345
  type OpenClawModelChoice = {
@@ -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
- client.opts.onHelloOk = () => {
154
- clearTimeout(t)
155
- connected = true
156
- res()
157
- }
158
- client.opts.onConnectError = err => {
159
- clearTimeout(t)
160
- rej(err)
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
- client.opts.onHelloOk = () => {
240
- clearTimeout(t)
241
- res()
242
- }
243
- client.opts.onConnectError = e => {
244
- clearTimeout(t)
245
- rej(e)
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