moi-computer 0.3.0 → 0.3.1-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/client/api/workspace-keys.ts +2 -2
  2. package/client/app/AppRouter.tsx +0 -2
  3. package/client/app/routes/WorkspaceRoute.tsx +3 -1
  4. package/client/app/shell/SidebarLayout.tsx +3 -16
  5. package/client/assets/openai.svg +1 -3
  6. package/client/components/shared/Composer.tsx +112 -0
  7. package/client/components/ui/button.tsx +1 -1
  8. package/client/components/ui/dropdown-menu.tsx +3 -3
  9. package/client/components/ui/tooltip.tsx +12 -15
  10. package/client/features/applets/WidgetErrorBoundary.tsx +19 -3
  11. package/client/features/applets/WidgetShell.tsx +8 -1
  12. package/client/features/applets/applet-log.ts +100 -0
  13. package/client/features/applets/useApplet.ts +21 -7
  14. package/client/features/chat/ChatComposer.tsx +33 -30
  15. package/client/features/chat/ChatPanel.tsx +5 -2
  16. package/client/features/chat/MarkdownContent.tsx +20 -2
  17. package/client/features/chat/ModelPicker.tsx +29 -41
  18. package/client/features/chat/TurnView.tsx +2 -2
  19. package/client/features/chat/chat-frames.ts +14 -6
  20. package/client/features/chat/chat-send.ts +1 -1
  21. package/client/features/chat/chat-store.ts +22 -17
  22. package/client/features/chat/model-order.ts +47 -0
  23. package/client/features/chat/tool-group/ToolOutput.tsx +4 -12
  24. package/client/features/chat/tool-group/format.ts +0 -6
  25. package/client/features/chat/useChat.ts +15 -2
  26. package/client/features/connectors/McpServerCards.tsx +95 -0
  27. package/client/features/connectors/api.ts +0 -11
  28. package/client/features/home/HomePage.tsx +45 -42
  29. package/client/features/home/WorkspacePreview.tsx +179 -38
  30. package/client/features/home/api.ts +24 -12
  31. package/client/features/home/workspace-presentation.tsx +17 -15
  32. package/client/features/home/workspace-setup/CreateWorkspaceDialog.tsx +243 -0
  33. package/client/features/home/workspace-setup/ImportWorkspaceDialog.tsx +95 -0
  34. package/client/features/home/workspace-setup/WorkspaceAgentStep.tsx +230 -0
  35. package/client/features/home/workspace-setup/WorkspaceDialogContent.tsx +35 -0
  36. package/client/features/home/workspace-setup/useWorkspaceImport.ts +61 -0
  37. package/client/features/settings/ConnectorsSettings.tsx +89 -0
  38. package/client/features/settings/GeneralSettings.tsx +12 -0
  39. package/client/features/settings/SettingsLayout.tsx +2 -2
  40. package/client/features/settings/WorkspaceSettings.tsx +8 -4
  41. package/client/features/views/ViewBuilderTab.tsx +28 -29
  42. package/client/features/views/useViewBuilderActions.ts +1 -1
  43. package/client/features/widgets/WidgetFrame.tsx +3 -0
  44. package/client/features/widgets/WidgetGrid.tsx +1 -0
  45. package/client/features/widgets/Widgets.tsx +12 -3
  46. package/client/features/widgets/api.ts +47 -0
  47. package/client/features/widgets/useWidgetThumbnails.ts +107 -0
  48. package/client/features/widgets/widget-snapshot.ts +71 -0
  49. package/client/features/workspace/WorkspaceLayoutContext.tsx +3 -4
  50. package/client/features/workspace/WorkspaceScreen.tsx +19 -4
  51. package/client/features/workspace/api.ts +25 -3
  52. package/client/features/workspace/moi-context.ts +85 -0
  53. package/client/index.css +0 -5
  54. package/client/main.tsx +13 -4
  55. package/dist/{chunk-cs8vbert.js → chunk-1dfbr7n2.js} +2 -2
  56. package/dist/chunk-339jds4x.js +15 -0
  57. package/dist/chunk-3xsvsnhr.css +1 -0
  58. package/dist/{chunk-zpxrb1ce.js → chunk-anqmsbjt.js} +2 -2
  59. package/dist/chunk-hbvfb6sk.js +63 -0
  60. package/dist/chunk-jen6xcm1.js +14 -0
  61. package/dist/{chunk-kxmvv1ax.js → chunk-qwm5f6qk.js} +1 -1
  62. package/dist/{chunk-fjksw6xf.js → chunk-sxbfh73c.js} +1 -1
  63. package/dist/chunk-yp4srgqt.js +10 -0
  64. package/dist/index.html +1 -1
  65. package/dist/openai-ep9ht2pq.svg +1 -0
  66. package/lib/ids.ts +15 -0
  67. package/lib/moi-context.ts +170 -0
  68. package/lib/types.ts +95 -13
  69. package/lib/view-builder-directives.ts +16 -0
  70. package/lib/workspace-types.ts +12 -0
  71. package/package.json +4 -2
  72. package/server/api.ts +180 -34
  73. package/server/applet-log.ts +149 -0
  74. package/server/cli.ts +161 -7
  75. package/server/control.ts +81 -1
  76. package/server/functions.ts +44 -14
  77. package/server/harness/README.md +26 -9
  78. package/server/harness/claude-code/NOTES.md +20 -6
  79. package/server/harness/claude-code/adapter.ts +2 -2
  80. package/server/harness/claude-code/git-worktree.ts +32 -0
  81. package/server/harness/claude-code/index.ts +35 -13
  82. package/server/harness/claude-code/mcp.ts +16 -65
  83. package/server/harness/claude-code/models.ts +3 -0
  84. package/server/harness/claude-code/session.ts +196 -61
  85. package/server/harness/claude-code/sessions.ts +51 -0
  86. package/server/harness/codex/NOTES.md +41 -11
  87. package/server/harness/codex/adapter.ts +52 -6
  88. package/server/harness/codex/client.ts +69 -18
  89. package/server/harness/codex/discovery.ts +114 -0
  90. package/server/harness/codex/index.ts +12 -5
  91. package/server/harness/codex/probe.ts +4 -2
  92. package/server/harness/codex/session.ts +57 -5
  93. package/server/harness/executable.ts +82 -0
  94. package/server/harness/openclaw/adapter.ts +8 -1
  95. package/server/harness/openclaw/discovery.ts +139 -6
  96. package/server/harness/openclaw/gateway.ts +40 -18
  97. package/server/harness/openclaw/index.ts +12 -15
  98. package/server/harness/openclaw/session.ts +50 -10
  99. package/server/harness/openclaw/strip.ts +2 -2
  100. package/server/harness/shell-path.ts +79 -0
  101. package/server/harness/types.ts +37 -5
  102. package/server/layout.ts +81 -51
  103. package/server/registry.ts +57 -12
  104. package/server/scratchpad-assets.ts +41 -6
  105. package/server/scratchpad.ts +30 -0
  106. package/server/view-builders.ts +3 -2
  107. package/server/views.ts +5 -0
  108. package/server/web.ts +30 -8
  109. package/server/widgets.ts +23 -2
  110. package/server/workspace-import.ts +45 -0
  111. package/workspace/.claude/skills/moi-workspace/SKILL.md +27 -3
  112. package/client/features/connectors/ConnectorsPage.tsx +0 -92
  113. package/client/features/connectors/McpMenu.tsx +0 -145
  114. package/client/features/home/CreateWorkspaceDialog.tsx +0 -130
  115. package/client/features/home/CreateWorkspaceDialogSteps.tsx +0 -234
  116. package/dist/chunk-4vf1t6v1.js +0 -10
  117. package/dist/chunk-4z52b2av.css +0 -1
  118. package/dist/chunk-b4b276wx.js +0 -15
  119. package/dist/chunk-y82s1jxm.js +0 -61
  120. package/dist/openai-h13pza4b.svg +0 -3
  121. package/lib/view-builder-meta.ts +0 -35
@@ -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>)
@@ -1,20 +1,19 @@
1
1
  // OpenClaw as a Harness. Thin wiring over this folder's modules — see
2
2
  // ../types.ts for the contract and ../README.md for the architecture.
3
- import type { DiscoveredWorkspace } from '@/lib/types'
4
-
5
- import type { Harness } from '../types'
3
+ import type { DiscoveredWorkspaceCandidate, Harness } from '../types'
6
4
  import { toSessionInfo, toStreamEvents } from './adapter'
7
5
  import {
8
6
  discoverOpenClawAgents,
9
7
  getOpenClawModels,
10
8
  getOpenClawSessionMessages,
11
- getOpenClawSessions
9
+ getOpenClawSessions,
10
+ getOpenClawWorkspacePreview
12
11
  } from './discovery'
13
12
  import {
14
13
  abortOpenClawRun,
15
14
  ensureOpenClawSessionLive,
16
15
  getLiveOpenClawEvents,
17
- getOpenClawRunningSessions,
16
+ getOpenClawActiveSessions,
18
17
  sendOpenClawMessage
19
18
  } from './session'
20
19
 
@@ -35,12 +34,14 @@ export const openclawHarness: Harness = {
35
34
  return sendOpenClawMessage({ ...input, agentId: input.agentId })
36
35
  },
37
36
  interrupt: (workspaceId, sessionId) => abortOpenClawRun({ workspaceId, sessionId }),
38
- runningSessions: () => getOpenClawRunningSessions(),
37
+ activeSessions: () => getOpenClawActiveSessions(),
39
38
 
40
39
  listSessions: async ws => {
41
40
  const rows = await getOpenClawSessions(ws.path, ws.agentId)
42
41
  return rows.map(r => toSessionInfo(r, ws.path))
43
42
  },
43
+ workspacePreview: (ws, includeFirstUserMessage) =>
44
+ getOpenClawWorkspacePreview(ws.path, ws.agentId, includeFirstUserMessage),
44
45
  // Prefer the live view if we already hold one — keeps REST + WS in
45
46
  // agreement for any reload that lands while a run is active. The first cold
46
47
  // call also primes the live subscription so subsequent WS frames upsert
@@ -70,13 +71,9 @@ export const openclawHarness: Harness = {
70
71
  return agents
71
72
  .filter(a => !registeredPaths.has(a.path))
72
73
  .map(
73
- (a): DiscoveredWorkspace => ({
74
+ (a): DiscoveredWorkspaceCandidate => ({
74
75
  path: a.path,
75
- type: 'openclaw',
76
- ...(a.name ? { name: a.name } : {}),
77
- ...(a.agentId ? { agentId: a.agentId } : {}),
78
- ...(a.isDefault ? { isDefault: a.isDefault } : {}),
79
- ...(a.lastRunAt ? { lastRunAt: a.lastRunAt } : {})
76
+ type: 'openclaw'
80
77
  })
81
78
  )
82
79
  },
@@ -84,10 +81,10 @@ export const openclawHarness: Harness = {
84
81
  skillsDir: workspaceRoot => `${workspaceRoot}/skills`,
85
82
 
86
83
  statusLines: () => {
87
- const running = getOpenClawRunningSessions()
84
+ const active = getOpenClawActiveSessions()
88
85
  return [
89
- `live OpenClaw runs ${running.length}`,
90
- ...running.map(r => ` ▶ busy ws=${r.workspaceId} session=${r.sessionId}`)
86
+ `live OpenClaw runs ${active.length}`,
87
+ ...active.map(r => ` ▶ busy ws=${r.workspaceId} session=${r.sessionId}`)
91
88
  ]
92
89
  }
93
90
  }
@@ -12,9 +12,9 @@
12
12
  // - Disk persistence — the gateway is the source of truth; we re-seed from
13
13
  // `sessions.get` on cold start.
14
14
  import { appendAttachmentNote } from '@/lib/attachment-note'
15
- import { stripViewBuilderMeta } from '@/lib/view-builder-meta'
15
+ import { type MoiContext, appendMoiContext, renderMoiContext } from '@/lib/moi-context'
16
16
  import { applyEvent, emptyViewState } from '@/lib/format'
17
- import type { StreamEvent, ViewState } from '@/lib/types'
17
+ import type { SessionActivity, StreamEvent, ViewState } from '@/lib/types'
18
18
 
19
19
  import {
20
20
  type OpenClawMessage,
@@ -82,20 +82,46 @@ onGatewayReconnected(async () => {
82
82
  console.error('[openclaw-session] reconcile-on-reconnect failed', err)
83
83
  }
84
84
  }
85
+ // Lifecycle frames emitted during the disconnect window are gone for good —
86
+ // a run that ended while we were away would leave its session busy forever.
87
+ // Re-derive every busy flag from the gateway's own `sessions.list` status.
88
+ try {
89
+ const busy = [...sessions.values()].filter(rec =>
90
+ isOpenClawProcessing(rec.workspaceId, rec.sessionId)
91
+ )
92
+ if (busy.length === 0) return
93
+ const gw = await getGateway()
94
+ const res = await gw.rpc<{ sessions: { key: string; status?: string }[] }>('sessions.list', {
95
+ includeGlobal: true
96
+ })
97
+ const running = new Set(
98
+ (res?.sessions ?? []).filter(row => row.status === 'running').map(row => row.key)
99
+ )
100
+ for (const rec of busy) {
101
+ if (!running.has(rec.sessionKey)) setProcessing(rec, false, null)
102
+ }
103
+ } catch (err) {
104
+ console.error('[openclaw-session] busy-flag reconcile failed', err)
105
+ }
85
106
  })
86
107
 
87
108
  function recKey(workspaceId: string, sessionId: string): string {
88
109
  return `${workspaceId}:${sessionId}`
89
110
  }
90
111
 
91
- // All running OpenClaw sessions across every workspace, for the connect-time
92
- // status snapshot. Key is `${workspaceId}:${sessionId}` (both are colon-free).
93
- export function getOpenClawRunningSessions(): { workspaceId: string; sessionId: string }[] {
94
- const out: { workspaceId: string; sessionId: string }[] = []
112
+ // All non-idle OpenClaw sessions across every workspace, for the status
113
+ // snapshot. Key is `${workspaceId}:${sessionId}` (both are colon-free). The
114
+ // protocol has no "waiting for user input" concept, so activity is binary.
115
+ export function getOpenClawActiveSessions(): {
116
+ workspaceId: string
117
+ sessionId: string
118
+ activity: SessionActivity
119
+ }[] {
120
+ const out: { workspaceId: string; sessionId: string; activity: SessionActivity }[] = []
95
121
  for (const [k, v] of openclawAgents) {
96
122
  if (!v.processing) continue
97
123
  const i = k.indexOf(':')
98
- out.push({ workspaceId: k.slice(0, i), sessionId: k.slice(i + 1) })
124
+ out.push({ workspaceId: k.slice(0, i), sessionId: k.slice(i + 1), activity: 'running' })
99
125
  }
100
126
  return out
101
127
  }
@@ -113,7 +139,11 @@ function setProcessing(rec: SessionRecord, processing: boolean, runId: string |
113
139
  activeRunId: runId
114
140
  })
115
141
  if (existing?.processing === processing) return
116
- broadcast(rec.workspaceId, { type: 'status', sessionId: rec.sessionId, processing })
142
+ broadcast(rec.workspaceId, {
143
+ type: 'status',
144
+ sessionId: rec.sessionId,
145
+ activity: processing ? 'running' : 'idle'
146
+ })
117
147
  if (processing) {
118
148
  void markViewBuilderBuildingBySession(rec.workspaceId, rec.workspacePath, rec.sessionId)
119
149
  } else {
@@ -385,6 +415,10 @@ export async function sendOpenClawMessage(input: {
385
415
  // (see dev/file-uploads.md).
386
416
  attachments?: string[]
387
417
  optimisticId?: string
418
+ // Structured moi context (lib/moi-context.ts), rendered and appended at
419
+ // the gateway send only — `content` stays clean so the optimistic-id echo
420
+ // rendezvous keeps matching on the user's text.
421
+ context?: MoiContext
388
422
  }): Promise<void> {
389
423
  // Fold any attachments into the message text as file-path references.
390
424
  let content = input.content
@@ -411,6 +445,7 @@ async function sendOpenClawMessageImpl(input: {
411
445
  isNew: boolean
412
446
  content: string
413
447
  optimisticId?: string
448
+ context?: MoiContext
414
449
  }): Promise<void> {
415
450
  // New threads: ask the gateway to create one, then rename the client's
416
451
  // tentative UUID to the real session id. Mirrors the Claude Code flow
@@ -463,7 +498,7 @@ async function sendOpenClawMessageImpl(input: {
463
498
  if (input.optimisticId) {
464
499
  rec.pendingUserEchoes.push({
465
500
  optimisticId: input.optimisticId,
466
- text: stripViewBuilderMeta(input.content)
501
+ text: input.content
467
502
  })
468
503
  if (rec.pendingUserEchoes.length > MAX_PENDING_USER_ECHOES) {
469
504
  rec.pendingUserEchoes.shift()
@@ -477,7 +512,9 @@ async function sendOpenClawMessageImpl(input: {
477
512
  const gw = await getGateway()
478
513
  const resp = await gw.rpc<{ runId?: string; status?: string }>('sessions.send', {
479
514
  key: rec.sessionKey,
480
- message: input.content
515
+ message: input.context
516
+ ? appendMoiContext(input.content, renderMoiContext(input.context))
517
+ : input.content
481
518
  })
482
519
  if (resp?.runId) setProcessing(rec, true, resp.runId)
483
520
  } catch (err) {
@@ -522,6 +559,9 @@ export async function abortOpenClawRun(input: {
522
559
  sessionId: rec.sessionId,
523
560
  content: err instanceof Error ? err.message : 'abort failed'
524
561
  })
562
+ // Stop is the user's escape hatch from a stuck spinner — clear the busy
563
+ // flag even when the abort RPC fails (the run may already be gone).
564
+ setProcessing(rec, false, null)
525
565
  }
526
566
  }
527
567
 
@@ -1,4 +1,4 @@
1
- import { stripViewBuilderMeta } from '@/lib/view-builder-meta'
1
+ import { stripMoiContext } from '@/lib/moi-context'
2
2
 
3
3
  // Strip OpenClaw-injected inbound metadata from user-role message text.
4
4
  //
@@ -132,5 +132,5 @@ export function stripBootstrapPreamble(text: string): string {
132
132
  }
133
133
 
134
134
  export function stripUserMessageMetadata(text: string): string {
135
- return stripViewBuilderMeta(stripInboundMetadata(stripBootstrapPreamble(text)))
135
+ return stripMoiContext(stripInboundMetadata(stripBootstrapPreamble(text)))
136
136
  }
@@ -0,0 +1,79 @@
1
+ import { userInfo } from 'node:os'
2
+ import { delimiter } from 'node:path'
3
+
4
+ // The moi server does not always start from a terminal (GUI launcher, service
5
+ // manager), and a non-shell parent's PATH misses exactly the dirs agent CLIs
6
+ // install to: ~/.local/bin, ~/.bun/bin, homebrew, version-manager shims. Probe
7
+ // the user's login shell for its PATH once and merge it into every executable
8
+ // lookup — the same recovery VS Code and Superset use, minus the PTY.
9
+
10
+ const MARKER = '__moi_env__'
11
+ const TIMEOUT_MS = 3000
12
+
13
+ function configuredShell(): string | null {
14
+ if (process.platform === 'win32') return null
15
+ try {
16
+ const shell = userInfo().shell
17
+ if (shell) return shell
18
+ } catch {
19
+ // userInfo() throws when the account has no passwd entry (containers).
20
+ }
21
+ return process.env.SHELL || null
22
+ }
23
+
24
+ // `/usr/bin/env` instead of `echo $PATH`: fish joins list variables with
25
+ // spaces, and rc files are free to print noise — the markers isolate env's
26
+ // output so only the real PATH line is parsed.
27
+ async function detectLoginShellPath(): Promise<string | null> {
28
+ const shell = configuredShell()
29
+ if (!shell) return null
30
+ const proc = Bun.spawn(
31
+ [shell, '-l', '-c', `printf '%s' '${MARKER}'; /usr/bin/env; printf '%s' '${MARKER}'`],
32
+ { stdin: 'ignore', stdout: 'pipe', stderr: 'ignore' }
33
+ )
34
+ const timeout = setTimeout(() => proc.kill(), TIMEOUT_MS)
35
+ try {
36
+ const [out] = await Promise.all([new Response(proc.stdout).text(), proc.exited])
37
+ const start = out.indexOf(MARKER)
38
+ const end = out.lastIndexOf(MARKER)
39
+ if (start === -1 || end <= start) return null
40
+ const env = out.slice(start + MARKER.length, end)
41
+ for (const line of env.split('\n')) {
42
+ if (line.startsWith('PATH=')) return line.slice('PATH='.length) || null
43
+ }
44
+ return null
45
+ } catch {
46
+ return null
47
+ } finally {
48
+ clearTimeout(timeout)
49
+ }
50
+ }
51
+
52
+ let cached: string | null = null
53
+ let pending: Promise<string | null> | null = null
54
+
55
+ // Start (or join) the login-shell PATH probe. Failure is not an error —
56
+ // lookups just fall back to the server's own PATH.
57
+ export function loginShellPath(): Promise<string | null> {
58
+ pending ??= detectLoginShellPath()
59
+ .catch(() => null)
60
+ .then(path => (cached = path))
61
+ return pending
62
+ }
63
+
64
+ // Last resolved value, for sync callers on the spawn path. Null until the
65
+ // probe settles; executable.ts kicks it off at module load, so real spawns
66
+ // (always later than server start) see the resolved value.
67
+ export function cachedLoginShellPath(): string | null {
68
+ return cached
69
+ }
70
+
71
+ export function mergeSearchPaths(...paths: Array<string | null | undefined>): string {
72
+ const seen = new Set<string>()
73
+ for (const path of paths) {
74
+ for (const dir of (path ?? '').split(delimiter)) {
75
+ if (dir) seen.add(dir)
76
+ }
77
+ }
78
+ return [...seen].join(delimiter)
79
+ }
@@ -2,10 +2,12 @@
2
2
  // by moi. See README.md in this folder for the full checklist and the
3
3
  // message-type layers; each harness's index.ts exports one Harness object
4
4
  // wrapping its session/adapter/transport modules.
5
+ import type { MoiContext } from '@/lib/moi-context'
5
6
  import type {
6
- DiscoveredWorkspace,
7
+ HarnessAvailability,
7
8
  McpServer,
8
9
  Model,
10
+ SessionActivity,
9
11
  SessionInfo,
10
12
  StreamEvent,
11
13
  WorkspaceEntry,
@@ -28,6 +30,12 @@ export type SendMessageInput = {
28
30
  model?: string
29
31
  effort?: string
30
32
  stream?: boolean
33
+ // Structured moi context (lib/moi-context.ts). Each harness renders and
34
+ // injects it its own way: Claude Code as a leading system-reminder text
35
+ // block, Codex >= 0.135 via the native additionalContext channel (appended
36
+ // to the text below that), OpenClaw appended after the text at the gateway
37
+ // send.
38
+ context?: MoiContext
31
39
  // OpenClaw: the gateway agent that owns the workspace.
32
40
  agentId?: string
33
41
  }
@@ -48,6 +56,18 @@ export type HarnessCapabilities = {
48
56
  nativeUserEcho: boolean
49
57
  }
50
58
 
59
+ // Home-page workspace card data beyond thumbnails: latest session activity
60
+ // and (for widget-less workspaces) the oldest session's first user message.
61
+ export type WorkspaceActivityPreview = {
62
+ firstUserMessage?: string
63
+ updatedAt?: number
64
+ }
65
+
66
+ export type DiscoveredWorkspaceCandidate = {
67
+ path: string
68
+ type: WorkspaceType
69
+ }
70
+
51
71
  export type Harness = {
52
72
  id: WorkspaceType
53
73
  capabilities: HarnessCapabilities
@@ -55,18 +75,30 @@ export type Harness = {
55
75
  // -- chat lifecycle ---------------------------------------------------------
56
76
  sendMessage(input: SendMessageInput): Promise<void>
57
77
  interrupt(workspaceId: string, sessionId: string): Promise<void>
58
- // Sessions currently processing a turn, across all workspaces (drives the
59
- // connect-time status snapshot and view-builder reconciliation).
60
- runningSessions(): { workspaceId: string; sessionId: string }[]
78
+ // Every session whose activity is not `idle`, across all workspaces (drives
79
+ // the status snapshot and view-builder reconciliation). Activity is mirrored
80
+ // from the backend's native lifecycle signal, never derived by counting.
81
+ activeSessions(): { workspaceId: string; sessionId: string; activity: SessionActivity }[]
61
82
 
62
83
  // -- discovery / metadata ---------------------------------------------------
63
84
  listSessions(ws: WorkspaceEntry): Promise<SessionInfo[]>
85
+ // Home-page card preview. Called for every card on the home screen, so
86
+ // implementations must stay cheap: no process spawns, no per-session
87
+ // transcript reads unless cached. Failures resolve to {} — the card
88
+ // renders without the activity fields.
89
+ workspacePreview(
90
+ ws: WorkspaceEntry,
91
+ includeFirstUserMessage: boolean
92
+ ): Promise<WorkspaceActivityPreview>
64
93
  sessionEvents(ws: WorkspaceEntry, sessionId: string): Promise<StreamEvent[]>
65
94
  listModels(ws: WorkspaceEntry): Promise<Model[]>
66
95
  // MCP server status for the connectors UI; absent = backend has no MCP story.
67
96
  mcpStatus?(ws: WorkspaceEntry): Promise<McpServer[]>
68
97
  // Workspaces this backend knows about that aren't registered yet.
69
- discoverWorkspaces?(registeredPaths: Set<string>): Promise<DiscoveredWorkspace[]>
98
+ discoverWorkspaces?(registeredPaths: Set<string>): Promise<DiscoveredWorkspaceCandidate[]>
99
+ // Is the backend's runtime present on this machine? Absent = always
100
+ // available. Cheap enough to call per request (a PATH lookup, not a probe).
101
+ availability?(): Promise<HarnessAvailability>
70
102
 
71
103
  // -- host integration hooks -------------------------------------------------
72
104
  // Env is frozen at spawn everywhere; this reaps idle sessions/processes so