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.
Files changed (58) 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 -31
  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-rq0ar7vp.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/NOTES.md +88 -1
  43. package/server/harness/codex/adapter.ts +32 -0
  44. package/server/harness/codex/client.ts +36 -1
  45. package/server/harness/codex/index.ts +3 -0
  46. package/server/harness/openclaw/discovery.ts +139 -6
  47. package/server/harness/openclaw/gateway.ts +40 -18
  48. package/server/harness/openclaw/index.ts +4 -1
  49. package/server/harness/types.ts +15 -0
  50. package/server/layout.ts +81 -51
  51. package/server/scratchpad-assets.ts +41 -6
  52. package/server/scratchpad.ts +30 -0
  53. package/server/views.ts +5 -0
  54. package/server/web.ts +6 -0
  55. package/server/widgets.ts +23 -2
  56. package/workspace/.claude/skills/moi-workspace/SKILL.md +25 -1
  57. package/dist/chunk-6c24yndg.js +0 -61
  58. package/dist/chunk-cwqmay73.css +0 -1
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 —
@@ -221,7 +221,94 @@ state, steer/interrupt, previews, usage). Empirical findings beyond §2:
221
221
  - `thread/start` responses label threads `source: "vscode"` — app-server
222
222
  clients are indistinguishable from the VS Code extension in `thread/list`.
223
223
 
224
- ## 6. Type maintenance (`generate-ts`)
224
+ ## 6. MCP servers & connectors (probed at CLI 0.144.5)
225
+
226
+ One-off probe: `bun server/harness/codex/probe.ts rpc . mcpServerStatus/list '{}'`.
227
+
228
+ ### `mcpServerStatus/list` payload
229
+
230
+ `{ data: McpServerStatus[] }`, one entry per server Codex loaded:
231
+
232
+ - `name` — the registry key (config.toml table name, or injected name).
233
+ - `serverInfo` — the server's MCP `initialize` result (`name`, `title`,
234
+ `version`, `description`, `icons`, `websiteUrl`), `null` if it never
235
+ answered. A server can list with `serverInfo: null` and an empty `tools`
236
+ map and still be "configured" — that's what a dead/misbehaving remote
237
+ looks like (no error field).
238
+ - `tools` — a **map keyed by tool name**, each value a full MCP tool def:
239
+ `name`, `title`, `description`, `inputSchema`, `outputSchema`,
240
+ `annotations` (`readOnlyHint`/`destructiveHint`/`openWorldHint`), `_meta`.
241
+ This payload is BIG (~0.5 MB with ChatGPT connectors installed) — don't
242
+ fold it into anything broadcast.
243
+ - `resources`, `resourceTemplates` — arrays.
244
+ - `authStatus` — `bearerToken` (authed HTTP/OAuth), `notLoggedIn` (OAuth
245
+ awaiting `mcpServer/oauth/login`; the one `getCodexMcpStatus` maps to
246
+ `needs-auth`), `unsupported` (stdio server, no auth concept).
247
+
248
+ ### `codex_apps` — the ChatGPT connector aggregator
249
+
250
+ Injected automatically when signed in with a ChatGPT account; **absent from
251
+ config.toml**. `serverInfo.name` is `plugin-runtime`. It flattens every
252
+ connector installed on the user's ChatGPT account (GitHub, Figma, Granola, …)
253
+ into ONE server whose tool names are dotted `<connector>.<tool>`
254
+ (`figma.generate_deck`). The true brand lives in each tool's `_meta`:
255
+ `connector_id`, `connector_name` ("Figma"), `connector_description`,
256
+ `link_id` (the user's authorization to that connector), plus Apps SDK widget
257
+ hints (`openai/outputTemplate: "ui://widget/….html"`). This is why the
258
+ client's `parseCodexMcp` brands dotted `codex_apps` calls by the prefix
259
+ before the dot, not the server name. The adapter does not currently carry
260
+ `_meta.connector_name` through to the `ToolCall` — icon/brand matching is
261
+ name-based.
262
+
263
+ ### Where MCP servers can be defined (config layers)
264
+
265
+ From the 0.144.5 binary's config-layer enum, lowest to highest:
266
+
267
+ 1. **User** — `$CODEX_HOME/config.toml` (`[mcp_servers.<name>]`). Shared by
268
+ three writers: hand edits, `codex mcp add/remove`, and other apps (the
269
+ ChatGPT desktop app writes `node_repl` / `computer-use` entries here).
270
+ 2. **Profile v2** — `$CODEX_HOME/<name>.config.toml`, layered via `-p <name>`
271
+ (legacy `[profiles.<name>]` tables in config.toml also exist).
272
+ 3. **Project** — `.codex/config.toml` in a trusted repo ("sandbox, MCP,
273
+ hooks, model, or reasoning defaults").
274
+ 4. **Session flags** — `-c 'mcp_servers.foo.command="…"'` per invocation.
275
+ 5. **Plugins** — an enabled plugin can provide MCP servers ("not configured
276
+ in config.toml or an enabled plugin").
277
+ 6. **Account-injected** — `codex_apps` (above); server-side, no local file.
278
+ 7. **Admin layers** — system config.toml, MDM managed preferences, legacy
279
+ `managed_config.toml`, and an enterprise-managed cloud layer;
280
+ `requirements.toml` restricts (never defines) what the others may set.
281
+
282
+ The app-server can also edit the user layer programmatically
283
+ (`config/value/write`, `config/batchWrite`) — unused by moi.
284
+
285
+ ### The full MCP RPC surface (from the 0.144.5 binary's method enums)
286
+
287
+ Requests:
288
+
289
+ - `mcpServerStatus/list` — the registry dump above.
290
+ - `mcpServer/tool/call` — **direct one-off tool invocation, no model turn**:
291
+ `{ threadId, server, tool, arguments }` → a raw MCP `CallToolResult`
292
+ (`{ content: [...], isError }`). Requires a live `threadId` (MCP servers
293
+ are started per thread), but `thread/start` + call works without ever
294
+ running a turn — verified against `mastra_docs`. Argument validation
295
+ errors come back as `isError: true` content, not JSON-RPC errors.
296
+ - `mcpServer/resource/read` — read an MCP resource by uri.
297
+ - `mcpServer/oauth/login` — start OAuth for a `notLoggedIn` server;
298
+ completion arrives as the `mcpServer/oauthLogin/completed` notification.
299
+ - `config/mcpServer/reload` — re-read server definitions without a restart.
300
+ - `config/read`, `config/value/write`, `config/batchWrite`,
301
+ `configRequirements/read` — inspect/edit the config layers that define
302
+ servers.
303
+
304
+ Notifications: `mcpServer/startupStatus/updated` (per-thread startup
305
+ progress/failures — we currently ignore it), `mcpServer/oauthLogin/completed`,
306
+ `item/mcpToolCall/progress` (progress of an in-turn MCP call).
307
+
308
+ Server→client request: `mcpServer/elicitation/request` — an MCP server
309
+ asking the user for input mid-call, forwarded for the client to answer.
310
+
311
+ ## 7. Type maintenance (`generate-ts`)
225
312
 
226
313
  The wire types in `adapter.ts`/`client.ts` are a hand-written defensive
227
314
  subset of the protocol, produced against the bindings from:
@@ -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 = {