moi-computer 0.3.1-next.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 (92) hide show
  1. package/client/api/workspace-keys.ts +2 -2
  2. package/client/app/AppRouter.tsx +0 -2
  3. package/client/app/shell/SidebarLayout.tsx +3 -16
  4. package/client/assets/openai.svg +1 -3
  5. package/client/components/shared/Composer.tsx +53 -2
  6. package/client/components/ui/button.tsx +1 -1
  7. package/client/components/ui/tooltip.tsx +12 -15
  8. package/client/features/chat/ChatComposer.tsx +25 -15
  9. package/client/features/chat/ChatPanel.tsx +5 -2
  10. package/client/features/chat/MarkdownContent.tsx +20 -2
  11. package/client/features/chat/ModelPicker.tsx +5 -3
  12. package/client/features/chat/TurnView.tsx +2 -2
  13. package/client/features/chat/chat-frames.ts +13 -6
  14. package/client/features/chat/chat-send.ts +1 -1
  15. package/client/features/chat/chat-store.ts +22 -17
  16. package/client/features/chat/tool-group/ToolOutput.tsx +4 -12
  17. package/client/features/chat/tool-group/format.ts +0 -6
  18. package/client/features/chat/useChat.ts +11 -2
  19. package/client/features/connectors/McpServerCards.tsx +95 -0
  20. package/client/features/connectors/api.ts +0 -11
  21. package/client/features/home/HomePage.tsx +33 -28
  22. package/client/features/home/api.ts +24 -12
  23. package/client/features/home/workspace-presentation.tsx +17 -15
  24. package/client/features/home/workspace-setup/CreateWorkspaceDialog.tsx +243 -0
  25. package/client/features/home/workspace-setup/ImportWorkspaceDialog.tsx +95 -0
  26. package/client/features/home/workspace-setup/WorkspaceAgentStep.tsx +230 -0
  27. package/client/features/home/workspace-setup/WorkspaceDialogContent.tsx +35 -0
  28. package/client/features/home/workspace-setup/useWorkspaceImport.ts +61 -0
  29. package/client/features/settings/ConnectorsSettings.tsx +89 -0
  30. package/client/features/settings/SettingsLayout.tsx +2 -2
  31. package/client/features/settings/WorkspaceSettings.tsx +8 -4
  32. package/client/features/views/ViewBuilderTab.tsx +19 -15
  33. package/client/features/views/useViewBuilderActions.ts +1 -1
  34. package/client/features/workspace/WorkspaceLayoutContext.tsx +3 -4
  35. package/client/features/workspace/WorkspaceScreen.tsx +11 -3
  36. package/client/features/workspace/api.ts +19 -1
  37. package/client/features/workspace/moi-context.ts +85 -0
  38. package/client/main.tsx +7 -4
  39. package/dist/{chunk-cs8vbert.js → chunk-1dfbr7n2.js} +2 -2
  40. package/dist/chunk-339jds4x.js +15 -0
  41. package/dist/chunk-3xsvsnhr.css +1 -0
  42. package/dist/{chunk-zpxrb1ce.js → chunk-anqmsbjt.js} +2 -2
  43. package/dist/chunk-hbvfb6sk.js +63 -0
  44. package/dist/{chunk-kxmvv1ax.js → chunk-qwm5f6qk.js} +1 -1
  45. package/dist/{chunk-axszxe4c.js → chunk-sxbfh73c.js} +1 -1
  46. package/dist/chunk-yp4srgqt.js +10 -0
  47. package/dist/index.html +1 -1
  48. package/dist/openai-ep9ht2pq.svg +1 -0
  49. package/lib/ids.ts +15 -0
  50. package/lib/moi-context.ts +170 -0
  51. package/lib/types.ts +29 -11
  52. package/lib/view-builder-directives.ts +16 -0
  53. package/lib/workspace-types.ts +12 -0
  54. package/package.json +2 -1
  55. package/server/api.ts +92 -30
  56. package/server/harness/README.md +25 -9
  57. package/server/harness/claude-code/NOTES.md +20 -6
  58. package/server/harness/claude-code/adapter.ts +2 -2
  59. package/server/harness/claude-code/git-worktree.ts +32 -0
  60. package/server/harness/claude-code/index.ts +32 -12
  61. package/server/harness/claude-code/mcp.ts +16 -65
  62. package/server/harness/claude-code/models.ts +3 -0
  63. package/server/harness/claude-code/session.ts +196 -61
  64. package/server/harness/codex/NOTES.md +41 -11
  65. package/server/harness/codex/adapter.ts +21 -7
  66. package/server/harness/codex/client.ts +33 -17
  67. package/server/harness/codex/discovery.ts +114 -0
  68. package/server/harness/codex/index.ts +9 -5
  69. package/server/harness/codex/probe.ts +4 -2
  70. package/server/harness/codex/session.ts +57 -5
  71. package/server/harness/executable.ts +82 -0
  72. package/server/harness/openclaw/adapter.ts +8 -1
  73. package/server/harness/openclaw/index.ts +8 -14
  74. package/server/harness/openclaw/session.ts +50 -10
  75. package/server/harness/openclaw/strip.ts +2 -2
  76. package/server/harness/shell-path.ts +79 -0
  77. package/server/harness/types.ts +22 -5
  78. package/server/registry.ts +57 -12
  79. package/server/view-builders.ts +3 -2
  80. package/server/web.ts +24 -8
  81. package/server/workspace-import.ts +45 -0
  82. package/workspace/.claude/skills/moi-workspace/SKILL.md +3 -3
  83. package/client/features/connectors/ConnectorsPage.tsx +0 -92
  84. package/client/features/connectors/McpMenu.tsx +0 -145
  85. package/client/features/home/CreateWorkspaceDialog.tsx +0 -130
  86. package/client/features/home/CreateWorkspaceDialogSteps.tsx +0 -234
  87. package/dist/chunk-4vf1t6v1.js +0 -10
  88. package/dist/chunk-b3ynfk4g.js +0 -62
  89. package/dist/chunk-b4b276wx.js +0 -15
  90. package/dist/chunk-npwq6jmr.css +0 -1
  91. package/dist/openai-h13pza4b.svg +0 -3
  92. package/lib/view-builder-meta.ts +0 -35
@@ -0,0 +1,170 @@
1
+ // The moi context envelope: ambient workspace state that rides along with
2
+ // every user message so the agent knows it is running inside a moi workspace
3
+ // and what the user is looking at. Everything about the envelope lives here —
4
+ // the structured `MoiContext` form, the rendered `<moi-context>` text, the
5
+ // per-harness injection transforms, and the strip used to keep the envelope
6
+ // out of chat bubbles.
7
+ //
8
+ // Flow: a structured `MoiContext` is assembled at send time — by the client
9
+ // for chat sends (client/features/workspace/moi-context.ts, sent as the chat
10
+ // frame's `context`), by the server for view-builder requests — and travels
11
+ // structured all the way to the harness, which renders it with the transform
12
+ // matching its conventions:
13
+ // - Claude Code — `moiContextSystemReminder` as its own leading text block
14
+ // (mirrors how Claude Code itself injects ambient context; a string
15
+ // prefix would defeat the SDK's first-prompt extraction, which skips
16
+ // tag-leading text)
17
+ // - Codex — native `turn/start.additionalContext` (`renderMoiContextBody`,
18
+ // the entry key becomes the tag) on servers >= 0.135; `appendMoiContext`
19
+ // fallback below that
20
+ // - OpenClaw — `appendMoiContext` after the user's text
21
+ // Display paths strip with `stripMoiContext` so the envelope never surfaces
22
+ // in a bubble, live or replayed from a transcript.
23
+ import type { WorkspaceTabId } from './types'
24
+
25
+ const MOI_CONTEXT_OPEN = '<moi-context>'
26
+ const MOI_CONTEXT_CLOSE = '</moi-context>'
27
+ // Start of the first line inside the tag. Doubles as the strip guard: a user
28
+ // literally typing `<moi-context>` in their message won't have their text
29
+ // eaten. Keep this phrase byte-stable when rewording the envelope.
30
+ const MOI_CONTEXT_MARKER = 'You are running in a `moi` workspace'
31
+
32
+ const SYSTEM_REMINDER_OPEN = '<system-reminder>'
33
+ const SYSTEM_REMINDER_CLOSE = '</system-reminder>'
34
+
35
+ // The structured form built at send time — by the client for chat sends, by
36
+ // the server for programmatic sends (the view builder). Extend this (and
37
+ // `renderMoiContext`) when new ambient fields land.
38
+ export type MoiContext = {
39
+ // The workspace tab the user is on when they hit send — for a view-builder
40
+ // request that's the builder's own tab (`view-builder:<id>`).
41
+ activeTab: WorkspaceTabId
42
+ // UI label of the active tab when it differs from the id — a view's
43
+ // configured title (e.g. "Grading review" for `view:color-studio`), or a
44
+ // view builder's claimed title while the build runs. The tab bar falls
45
+ // back to the id when unset; so does the envelope.
46
+ tabTitle?: string
47
+ // One-shot imperative lines for this message only (e.g. the view-builder
48
+ // bootstrap instructions from lib/view-builder-directives.ts).
49
+ directives?: string[]
50
+ }
51
+
52
+ // One sentence per tab, using the labels the user sees in the tab bar (except
53
+ // view-builder tabs, which print the builder id — that's what `moi builder
54
+ // set` needs). A view tab also names its backing file: the user speaks in
55
+ // titles ("fix the Grading review page") while the agent edits
56
+ // `.moi/views/<id>.tsx` — this line connects the two.
57
+ function describeTab(tab: WorkspaceTabId, title?: string): string {
58
+ if (tab === 'agent') return 'The user is on the "Agent" tab (full page chat).'
59
+ if (tab === 'widgets') return 'The user is on the "Widgets" tab.'
60
+ if (tab === 'scratchpad') return 'The user is on the "Scratchpad" tab.'
61
+ if (tab.startsWith('view-builder:')) {
62
+ const id = tab.slice('view-builder:'.length)
63
+ return title
64
+ ? `The user is building a new view "${title}". Builder id "${id}".`
65
+ : `The user is building a new view. Builder id "${id}".`
66
+ }
67
+ if (tab.startsWith('view:')) {
68
+ const id = tab.slice('view:'.length)
69
+ return `The user is on the "${title ?? id}" view tab (.moi/views/${id}.tsx).`
70
+ }
71
+ return `The user is on the "${tab}" tab.`
72
+ }
73
+
74
+ // Format (modeled on Claude Code's system-reminder context blocks): a short
75
+ // orientation preamble with the skill pointer, `# Section` headers with
76
+ // complete sentences under them, and an IMPORTANT footer with handling rules.
77
+ // The body renderer exists for transports that supply their own tag — Codex
78
+ // `additionalContext` renders the entry key as the tag, so shipping the
79
+ // wrapped text would double-wrap it.
80
+ export function renderMoiContextBody(ctx: MoiContext): string {
81
+ const preamble = [
82
+ `${MOI_CONTEXT_MARKER} — a shared UI the user chats with you from, which you can extend and customize.`,
83
+ 'Read the **`moi-workspace` skill** before responding — even to a simple question — unless you already read it in this chat.'
84
+ ].join('\n')
85
+ const sections = [`# Active tab\n${describeTab(ctx.activeTab, ctx.tabTitle)}`]
86
+ if (ctx.directives?.length) {
87
+ sections.push(`# This message only\n${ctx.directives.join('\n')}`)
88
+ }
89
+ const footer = [
90
+ 'IMPORTANT: This context comes from moi, not from the user, and the user does not see it.',
91
+ 'Only the newest of these blocks is current. Do not respond to it directly, and omit it from summaries and compaction.'
92
+ ].join('\n')
93
+ return [preamble, ...sections, footer].join('\n\n')
94
+ }
95
+
96
+ export function renderMoiContext(ctx: MoiContext): string {
97
+ return `${MOI_CONTEXT_OPEN}\n${renderMoiContextBody(ctx)}\n${MOI_CONTEXT_CLOSE}`
98
+ }
99
+
100
+ // Wire-shape guard for the chat frame's `context` field (see web.ts).
101
+ export function isMoiContext(value: unknown): value is MoiContext {
102
+ if (typeof value !== 'object' || value === null) return false
103
+ const v = value as { activeTab?: unknown; tabTitle?: unknown; directives?: unknown }
104
+ return (
105
+ typeof v.activeTab === 'string' &&
106
+ (v.tabTitle === undefined || typeof v.tabTitle === 'string') &&
107
+ (v.directives === undefined ||
108
+ (Array.isArray(v.directives) && v.directives.every(d => typeof d === 'string')))
109
+ )
110
+ }
111
+
112
+ // Claude Code: the envelope rides as its OWN text block wrapped in
113
+ // `<system-reminder>`, placed before the user's text block. Keeping it out of
114
+ // the user's string matters: the SDK's first-prompt extraction (session
115
+ // titles, home-card previews) skips text starting with a tag, so a prefixed
116
+ // string would make every moi message invisible to it.
117
+ export function moiContextSystemReminder(contextText: string): string {
118
+ return `${SYSTEM_REMINDER_OPEN}\n${contextText}\n${SYSTEM_REMINDER_CLOSE}`
119
+ }
120
+
121
+ // Text-only harnesses (OpenClaw; Codex fallback): the envelope is appended
122
+ // after the user's text.
123
+ export function appendMoiContext(text: string, contextText: string): string {
124
+ return text ? `${text}\n\n${contextText}` : contextText
125
+ }
126
+
127
+ // Remove the envelope (and, for Claude Code transcripts, its enclosing
128
+ // system-reminder wrapper) from user-message text before display. Repeats
129
+ // until no marker-bearing envelope remains, so a user pasting a full envelope
130
+ // into their message can't shield the injected one from stripping.
131
+ export function stripMoiContext(text: string): string {
132
+ let out = text
133
+ for (;;) {
134
+ const next = stripOneMoiContext(out)
135
+ if (next === out) return out
136
+ out = next
137
+ }
138
+ }
139
+
140
+ function stripOneMoiContext(text: string): string {
141
+ const start = text.indexOf(MOI_CONTEXT_OPEN)
142
+ if (start === -1) return text
143
+ const end = text.indexOf(MOI_CONTEXT_CLOSE, start)
144
+ if (end === -1) return text
145
+ if (!text.slice(start, end).includes(MOI_CONTEXT_MARKER)) return text
146
+ let before = text.slice(0, start)
147
+ let after = text.slice(end + MOI_CONTEXT_CLOSE.length)
148
+ if (
149
+ before.trimEnd().endsWith(SYSTEM_REMINDER_OPEN) &&
150
+ after.trimStart().startsWith(SYSTEM_REMINDER_CLOSE)
151
+ ) {
152
+ before = before.trimEnd().slice(0, -SYSTEM_REMINDER_OPEN.length)
153
+ after = after.trimStart().slice(SYSTEM_REMINDER_CLOSE.length)
154
+ }
155
+ return `${before.trim()}\n\n${after.trim()}`.trim()
156
+ }
157
+
158
+ // For truncated snippets (session-list / home-card previews): like
159
+ // `stripMoiContext`, but also cuts an envelope (or its system-reminder
160
+ // wrapper) left unterminated by mid-envelope truncation. Skips the marker
161
+ // guard — cutting a preview short on a user-typed literal tag is harmless,
162
+ // unlike eating chat-bubble text.
163
+ export function stripMoiContextLoose(text: string): string {
164
+ let stripped = stripMoiContext(text)
165
+ const open = stripped.indexOf(MOI_CONTEXT_OPEN)
166
+ if (open !== -1) stripped = stripped.slice(0, open)
167
+ const reminder = stripped.indexOf(SYSTEM_REMINDER_OPEN)
168
+ if (reminder !== -1) stripped = stripped.slice(0, reminder)
169
+ return stripped.trimEnd()
170
+ }
package/lib/types.ts CHANGED
@@ -230,6 +230,11 @@ export type ClientMessage =
230
230
  // `supportsStreaming` (Claude Code); ignored otherwise. Like effort, a
231
231
  // change forces the live session to rebuild.
232
232
  stream?: boolean
233
+ // Structured moi context (lib/moi-context.ts): ambient workspace state
234
+ // snapshotted at send time, assembled by
235
+ // client/features/workspace/moi-context.ts. The server renders it per
236
+ // harness; display paths strip the rendered envelope from bubbles.
237
+ context?: import('./moi-context').MoiContext
233
238
  }
234
239
  | { type: 'stop'; workspaceId: string; sessionId: string }
235
240
  // Reply to a relayed Scratchpad op (see ScratchpadOpMessage). Carries the
@@ -330,13 +335,14 @@ export type BroadcastFrame =
330
335
  | Omit<ErrorFrame, 'workspaceId'>
331
336
  | Omit<StoppedFrame, 'workspaceId'>
332
337
 
333
- // Sent to a client right after it connects: the authoritative set of currently
334
- // running sessions across all workspaces. The client treats it as ground truth —
335
- // any session NOT listed is marked not-processing — which clears a spinner whose
336
- // terminal `status:false` was emitted while the client was disconnected.
338
+ // Sent to a client right after it connects (and re-broadcast periodically): the
339
+ // authoritative set of non-idle sessions across all workspaces. The client
340
+ // treats it as ground truth — any session NOT listed is marked idle — which
341
+ // clears a spinner whose terminal `status` frame was lost (disconnect window,
342
+ // dropped frame, harness gap).
337
343
  export type StatusSnapshotMessage = {
338
344
  type: 'status_snapshot'
339
- running: { workspaceId: string; sessionId: string }[]
345
+ sessions: { workspaceId: string; sessionId: string; activity: SessionActivity }[]
340
346
  }
341
347
 
342
348
  export type WorkspaceSwitchMessage = {
@@ -346,6 +352,12 @@ export type WorkspaceSwitchMessage = {
346
352
 
347
353
  export type WorkspaceType = 'claude-code' | 'openclaw' | 'codex'
348
354
 
355
+ // Whether an agent backend's runtime is installed on this machine. `reason` is
356
+ // user-facing copy explaining what to do next. Surfaced by
357
+ // GET /api/workspaces/create (per-type map, drives setup dialogs) and
358
+ // GET /api/workspaces/:id/availability (disables Send in existing workspaces).
359
+ export type HarnessAvailability = { available: true } | { available: false; reason: string }
360
+
349
361
  // One MCP server's connection status, as surfaced by GET /api/workspaces/:id/mcp
350
362
  // (a subset of the agent SDK's McpServerStatus — only what the UI renders).
351
363
  export type McpServerState = 'connected' | 'failed' | 'needs-auth' | 'pending' | 'disabled'
@@ -379,12 +391,9 @@ export type WorkspaceEntry = {
379
391
 
380
392
  export type DiscoveredWorkspace = {
381
393
  path: string
382
- type: WorkspaceType
383
- name?: string
384
394
  displayPath?: string
385
- agentId?: string
386
- isDefault?: boolean
387
- lastRunAt?: string
395
+ // Deduplicated in canonical provider order by the discovery API.
396
+ types: WorkspaceType[]
388
397
  }
389
398
 
390
399
  export type SessionRenamedMessage = {
@@ -407,11 +416,20 @@ export type StoppedFrame = {
407
416
  sessionId: string
408
417
  }
409
418
 
419
+ // Unified per-session activity state, mirrored from each harness's native
420
+ // lifecycle signal (CC `session_state_changed`, Codex `turn/*`, OpenClaw run
421
+ // lifecycle) rather than derived by counting messages:
422
+ // running — the agent is working; the client shows the loader/Stop
423
+ // requires-action — the agent is blocked on user input (permission prompt,
424
+ // MCP elicitation). Not rendered yet: no loader, no Stop.
425
+ // idle — everything else, including interrupted/failed turns
426
+ export type SessionActivity = 'idle' | 'running' | 'requires-action'
427
+
410
428
  export type StatusMessage = {
411
429
  type: 'status'
412
430
  workspaceId: string
413
431
  sessionId: string
414
- processing: boolean
432
+ activity: SessionActivity
415
433
  }
416
434
 
417
435
  // Workspace layout persistence
@@ -0,0 +1,16 @@
1
+ // View-builder bootstrap instructions, delivered as one-shot directives inside
2
+ // the `<moi-context>` envelope (lib/moi-context.ts) via SendMessageInput's
3
+ // `context` channel — see the view-builder POST route in server/api.ts.
4
+ export function viewBuilderDirectives(builderId: string, availableIcons: string[]): string[] {
5
+ return [
6
+ 'View builder request — this chat is linked to a pending view tab.',
7
+ `Builder id: ${builderId}`,
8
+ `Available view icons: ${availableIcons.join(', ')}`,
9
+ 'Your first action must be to infer a stable view id, sentence-case title, and relevant icon from the requirements, then run:',
10
+ `moi builder set <view-id> --builder ${builderId} --kind view --title "<title>" --icon <icon-id>`,
11
+ 'Do this before reading files, planning, or writing code. Choose the icon id from the available view icons above.',
12
+ 'Capitalize only the first word of the title.',
13
+ 'Use the same icon id in the view config.',
14
+ 'After building the view, run `moi bundle --only views`.'
15
+ ]
16
+ }
@@ -0,0 +1,12 @@
1
+ import type { WorkspaceType } from './types'
2
+
3
+ export const WORKSPACE_TYPE_ORDER = [
4
+ 'claude-code',
5
+ 'codex',
6
+ 'openclaw'
7
+ ] as const satisfies readonly WorkspaceType[]
8
+
9
+ export function orderWorkspaceTypes(types: Iterable<WorkspaceType>): WorkspaceType[] {
10
+ const unique = new Set(types)
11
+ return WORKSPACE_TYPE_ORDER.filter(type => unique.has(type))
12
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "moi-computer",
3
- "version": "0.3.1-next.0",
3
+ "version": "0.3.1-next.1",
4
4
  "description": "Local AI workspace powered by the Claude Agent SDK, Bun, React, and Tailwind. Requires Bun.",
5
5
  "license": "Elastic-2.0",
6
6
  "type": "module",
@@ -77,6 +77,7 @@
77
77
  "lru-cache": "^11.3.5",
78
78
  "modern-screenshot": "^4.7.0",
79
79
  "motion": "^12.35.1",
80
+ "nanoid": "^6.0.0",
80
81
  "pathe": "^2.0.3",
81
82
  "picocolors": "^1.1.1",
82
83
  "postcss": "^8.5.19",
package/server/api.ts CHANGED
@@ -4,8 +4,16 @@ import { createMiddleware } from 'hono/factory'
4
4
  import { existsSync } from 'node:fs'
5
5
  import { basename, join, resolve } from 'node:path'
6
6
 
7
- import type { UploadInfo, ViewBuilderInput, WorkspaceEntry, WorkspaceModels } from '@/lib/types'
8
- import { appendViewBuilderMeta } from '@/lib/view-builder-meta'
7
+ import type {
8
+ HarnessAvailability,
9
+ UploadInfo,
10
+ ViewBuilderInput,
11
+ WorkspaceEntry,
12
+ WorkspaceModels,
13
+ WorkspaceType
14
+ } from '@/lib/types'
15
+ import type { MoiContext } from '@/lib/moi-context'
16
+ import { viewBuilderDirectives } from '@/lib/view-builder-directives'
9
17
 
10
18
  import { appletForModule, recordAppletError } from './applet-log'
11
19
  import { apiBaseFor, parseAppletTail, serveWorkspaceFile } from './applets'
@@ -20,10 +28,10 @@ import {
20
28
  saveLayout,
21
29
  saveWidgetThumbnails
22
30
  } from './layout'
23
- import { getUserMcpStatus } from './harness/claude-code/mcp'
24
31
  import { getClientFrameLog, getWireLog } from './harness/debug'
25
32
  import { allHarnesses, harnessFor, isHarnessType } from './harness/registry'
26
33
  import {
34
+ discoverWorkspace,
27
35
  discoverWorkspaces,
28
36
  getWorkspace,
29
37
  listWorkspaces,
@@ -57,6 +65,8 @@ import {
57
65
  provisionWorkspace,
58
66
  validateWorkspaceFolderName
59
67
  } from './workspace-init'
68
+ import { resolveWorkspaceImportMetadata } from './workspace-import'
69
+ import type { WorkspaceImportMetadata } from './workspace-import'
60
70
  import { getWorkspaceEnvView, isValidEnvKey, updateWorkspaceEnv } from './workspace-env'
61
71
  import type { EnvUpdate } from './workspace-env'
62
72
 
@@ -166,7 +176,7 @@ one.get('/view-builders', async c => {
166
176
  const ws = c.get('ws')
167
177
  const activeSessionIds = new Set(
168
178
  allHarnesses()
169
- .flatMap(h => h.runningSessions())
179
+ .flatMap(h => h.activeSessions())
170
180
  .filter(session => session.workspaceId === ws.id)
171
181
  .map(session => session.sessionId)
172
182
  )
@@ -226,6 +236,8 @@ one.post('/view-builders/:builderId/submit', async c => {
226
236
  }
227
237
  const availableIcons = parseAvailableViewIcons(body.availableIcons)
228
238
  if (!availableIcons) return c.text('Available view icons are required', 400)
239
+ const availability = await workspaceTypeAvailability(ws.type ?? 'claude-code')
240
+ if (!availability.available) return c.text(availability.reason, 400)
229
241
  try {
230
242
  const builder = await beginViewBuilder(
231
243
  ws.id,
@@ -233,14 +245,21 @@ one.post('/view-builders/:builderId/submit', async c => {
233
245
  c.req.param('builderId'),
234
246
  body.input.requirements
235
247
  )
236
- const content = appendViewBuilderMeta(builder.input.requirements, builder.id, availableIcons)
248
+ // The bootstrap instructions ride the moi-context envelope, injected by
249
+ // the harness like any other ambient context; the user text stays bare.
250
+ // The user submits from the builder's own tab, so that's the active tab.
251
+ const context: MoiContext = {
252
+ activeTab: `view-builder:${builder.id}`,
253
+ directives: viewBuilderDirectives(builder.id, availableIcons)
254
+ }
237
255
  try {
238
256
  await harnessFor(ws).sendMessage({
239
257
  workspaceId: ws.id,
240
258
  workspacePath: ws.path,
241
259
  sessionId: builder.sessionId,
242
260
  isNew: true,
243
- content,
261
+ content: builder.input.requirements,
262
+ context,
244
263
  optimisticId: body.optimisticId,
245
264
  model: typeof body.model === 'string' ? body.model : undefined,
246
265
  effort: typeof body.effort === 'string' ? body.effort : undefined,
@@ -518,15 +537,30 @@ one.put('/env', async c => {
518
537
  return c.json(await getWorkspaceEnvView(ws.path, requiredEnvFor(ws.path)))
519
538
  })
520
539
 
540
+ // Is the workspace's agent backend usable right now? (e.g. a codex workspace
541
+ // on a machine without the codex CLI). The chat surfaces the `reason` as a
542
+ // banner instead of letting the first send fail cold.
543
+ one.get('/availability', async c => {
544
+ const availability = await workspaceTypeAvailability(c.get('ws').type ?? 'claude-code')
545
+ return c.json(availability satisfies HarnessAvailability)
546
+ })
547
+
521
548
  // Models the workspace's agent backend can run, normalized across providers.
522
549
  // OpenClaw queries the gateway catalog; everything else (Claude Code) reads the
523
550
  // account-wide Agent SDK model list.
524
551
  one.get('/models', async c => {
525
552
  const ws = c.get('ws')
526
553
  const harness = harnessFor(ws)
554
+ // A backend that can't answer (codex CLI missing, gateway down) degrades to
555
+ // an empty catalog — the picker hides and chat surfaces the real problem via
556
+ // the availability banner, instead of this endpoint 500ing on page load.
557
+ const models = await harness.listModels(ws).catch(err => {
558
+ console.error(`[api] listModels failed for ${harness.id}`, err)
559
+ return []
560
+ })
527
561
  return c.json({
528
562
  provider: harness.id,
529
- models: await harness.listModels(ws),
563
+ models,
530
564
  supportsStreaming: harness.capabilities.supportsStreaming
531
565
  } satisfies WorkspaceModels)
532
566
  })
@@ -735,9 +769,19 @@ workspaces.put('/order', async c => {
735
769
  workspaces.post('/', async c => {
736
770
  const body = await c.req.json()
737
771
  if (!body?.path) return c.text('Missing path', 400)
738
- const rawType = body?.type
739
- const type = isHarnessType(rawType) ? rawType : undefined
772
+ const requestedType: unknown = body?.type ?? 'claude-code'
773
+ if (!isHarnessType(requestedType)) return c.text('Unknown workspace type', 400)
774
+ const type: WorkspaceType = requestedType
775
+ const availability = await workspaceTypeAvailability(type)
776
+ if (!availability.available) return c.text(availability.reason, 400)
740
777
  const path = resolve(String(body.path))
778
+ let metadata: WorkspaceImportMetadata
779
+ try {
780
+ metadata = await resolveWorkspaceImportMetadata(path, type)
781
+ } catch (err) {
782
+ const message = err instanceof Error ? err.message : String(err)
783
+ return c.text(message, 400)
784
+ }
741
785
  // Importing IS initializing: lay down the bundled skills (in the backend's
742
786
  // skills dir) and the `.moi/` scaffold, exactly like `moi init` — a workspace
743
787
  // added from the UI must be indistinguishable from one added via the CLI.
@@ -749,48 +793,70 @@ workspaces.post('/', async c => {
749
793
  }
750
794
  const entry = await registerWorkspace(path, {
751
795
  type,
752
- name: typeof body?.name === 'string' ? body.name : undefined,
753
- agentId: typeof body?.agentId === 'string' ? body.agentId : undefined,
754
- isDefault: typeof body?.isDefault === 'boolean' ? body.isDefault : undefined,
755
- lastRunAt: typeof body?.lastRunAt === 'string' ? body.lastRunAt : undefined
796
+ ...metadata
756
797
  })
757
798
  return c.json(entry, 201)
758
799
  })
759
800
 
760
801
  workspaces.get('/discover', async c => c.json(await discoverWorkspaces()))
761
802
 
803
+ // Backends the create dialog can provision from scratch. OpenClaw workspaces
804
+ // belong to their agents and arrive via discovery.
805
+ const CREATABLE_TYPES = new Set<WorkspaceType>(['claude-code', 'codex'])
806
+
807
+ async function workspaceTypeAvailability(type: WorkspaceType): Promise<HarnessAvailability> {
808
+ return (await harnessFor(type).availability?.()) ?? { available: true }
809
+ }
810
+
811
+ // Per-backend runtime availability, keyed by workspace type. Harnesses without
812
+ // the hook are always available.
813
+ async function harnessAvailability(): Promise<Record<string, HarnessAvailability>> {
814
+ const out: Record<string, HarnessAvailability> = {}
815
+ for (const h of allHarnesses()) {
816
+ out[h.id] = await workspaceTypeAvailability(h.id)
817
+ }
818
+ return out
819
+ }
820
+
762
821
  // Where `/workspace/create` places new folders — the client shows the resolved
763
822
  // location while the user types a name. `canChooseFolder` tells the UI whether
764
- // the native folder picker is available (macOS only for now).
765
- workspaces.get('/create', c =>
823
+ // the native folder picker is available (macOS only for now). `availability`
824
+ // lets the dialog disable backends whose runtime is missing.
825
+ workspaces.get('/create', async c =>
766
826
  c.json({
767
827
  root: CREATED_WORKSPACES_ROOT,
768
828
  displayRoot: tildify(CREATED_WORKSPACES_ROOT),
769
- canChooseFolder: process.platform === 'darwin'
829
+ canChooseFolder: process.platform === 'darwin',
830
+ availability: await harnessAvailability()
770
831
  })
771
832
  )
772
833
 
773
834
  // Create a brand-new workspace: a fresh folder under CREATED_WORKSPACES_ROOT,
774
- // provisioned (skills + `.moi/` scaffold) and registered. Claude Code only for
775
- // now — OpenClaw workspaces belong to their agents and arrive via discovery.
835
+ // provisioned (skills + `.moi/` scaffold) and registered.
776
836
  workspaces.post('/create', async c => {
777
837
  const body = await c.req.json()
778
- const type = body?.type ?? 'claude-code'
779
- if (type !== 'claude-code') {
780
- return c.text('Only Claude Code workspaces can be created for now', 400)
838
+ const requestedType: unknown = body?.type ?? 'claude-code'
839
+ if (!isHarnessType(requestedType)) {
840
+ return c.text('Unknown workspace type', 400)
781
841
  }
842
+ const type: WorkspaceType = requestedType
843
+ if (!CREATABLE_TYPES.has(type)) {
844
+ return c.text('Workspaces of this type arrive through discovery, not creation', 400)
845
+ }
846
+ const availability = await workspaceTypeAvailability(type)
847
+ if (!availability.available) return c.text(availability.reason, 400)
782
848
  const name = typeof body?.name === 'string' ? body.name.trim() : ''
783
849
  const invalid = validateWorkspaceFolderName(name)
784
850
  if (invalid) return c.text(invalid, 400)
785
851
  const path = join(CREATED_WORKSPACES_ROOT, name)
786
852
  if (existsSync(path)) return c.text('A folder with that name already exists', 409)
787
853
  try {
788
- await provisionWorkspace(path, 'claude-code')
854
+ await provisionWorkspace(path, type)
789
855
  } catch (err) {
790
856
  const message = err instanceof Error ? err.message : String(err)
791
857
  return c.text(`Could not create workspace: ${message}`, 500)
792
858
  }
793
- const entry = await registerWorkspace(path, { type: 'claude-code' })
859
+ const entry = await registerWorkspace(path, { type })
794
860
  // Nudge every connected client (the sidebar list) to refetch.
795
861
  publishEvent({ type: 'workspaces-list:updated' })
796
862
  return c.json(entry, 201)
@@ -824,8 +890,8 @@ export function isSameOriginRequest(req: Request): boolean {
824
890
  // Open the OS-native folder picker so the user can choose an existing folder to
825
891
  // import (the create dialog's "Use existing folder"). The server runs on the
826
892
  // user's machine, so it can drive the real system dialog — the browser can't.
827
- // Returns the chosen POSIX path, or `{ canceled: true }` if the dialog is
828
- // dismissed. macOS only for now (via `osascript`).
893
+ // Returns the same grouped provider discovery shape as `/discover`, or
894
+ // `{ canceled: true }` if the dialog is dismissed. macOS only for now.
829
895
  workspaces.post('/choose-folder', async c => {
830
896
  if (!isSameOriginRequest(c.req.raw)) return c.text('Forbidden', 403)
831
897
  if (process.platform !== 'darwin') {
@@ -855,7 +921,7 @@ workspaces.post('/choose-folder', async c => {
855
921
  if (exitCode !== 0) return c.json({ canceled: true })
856
922
  const path = (await new Response(proc.stdout).text()).trim()
857
923
  if (!path) return c.json({ canceled: true })
858
- return c.json({ path })
924
+ return c.json(await discoverWorkspace(path))
859
925
  } catch (err) {
860
926
  const message = err instanceof Error ? err.message : String(err)
861
927
  return c.text(`Could not open the folder picker: ${message}`, 500)
@@ -872,10 +938,6 @@ workspaces.route('/:id', one)
872
938
  // ---- top-level API ----------------------------------------------------------
873
939
  export const api = new Hono()
874
940
 
875
- api.get('/api/mcp', async c => {
876
- return c.json(await getUserMcpStatus())
877
- })
878
-
879
941
  api.route('/api/workspaces', workspaces)
880
942
 
881
943
  // Everything else: in production, serve the prebuilt client from `dist/` via
@@ -39,8 +39,13 @@ Socket-protocol notes the layers rely on (all defined in `lib/types.ts`):
39
39
  echoes it natively (`clientUserMessageId` → `clientId`), Claude Code never
40
40
  echoes (the server synthesizes the turn), OpenClaw echoes lagged (matched
41
41
  by text).
42
- - **`status` / `status_snapshot`** — busy/idle per session; the snapshot on
43
- connect is authoritative (clears spinners for missed transitions).
42
+ - **`status` / `status_snapshot`** — per-session `activity`
43
+ (`idle | running | requires-action`), mirrored from the backend's native
44
+ lifecycle signal — never derived by counting sends vs results. The snapshot
45
+ (sent on connect and re-broadcast periodically) is authoritative: the client
46
+ rebuilds its whole activity map from it, so a lost terminal frame self-heals.
47
+ `requires-action` (agent blocked on user input) is tracked but not rendered
48
+ yet — the client shows no loader for it.
44
49
  - **`preview`** — live token frames, cumulative text, never persisted;
45
50
  cleared when the turn with matching `meta.apiMessageId` lands.
46
51
 
@@ -89,9 +94,12 @@ eviction/restart, interrupt, per-thread model + effort picker (backed by
89
94
  `supportedModels()`), opt-in live token streaming, image/file attachments,
90
95
  subagent lanes, MCP status probe, and session list/history replay from the
91
96
  SDK's `.jsonl` files, with per-turn token usage folded into the final
92
- assistant turn. Known gaps: runs with `bypassPermissions` only (no
93
- interactive approval flow), and effort/streaming changes require a
94
- teardown-and-resume because the SDK has no live setter for them.
97
+ assistant turn. The Agent SDK remains the transport, while every query is
98
+ forced through the `claude` executable resolved via `executable.ts` (server
99
+ PATH merged with the login-shell PATH).
100
+ Known gaps: runs with `bypassPermissions` only (no interactive approval
101
+ flow), and effort/streaming changes require a teardown-and-resume because the
102
+ SDK has no live setter for them.
95
103
 
96
104
  **OpenClaw — shipped, experimental.** Chat over the local gateway's WebSocket
97
105
  JSON-RPC: sessions seeded cold from `sessions.get` then updated from live
@@ -113,8 +121,12 @@ rendezvous, session list via `thread/list` (cwd-filtered) and history replay
113
121
  via `thread/read`, subagent (collab) child threads nested as live
114
122
  SubagentRecord transcripts on the parent card, semantic exec labels from
115
123
  `commandActions`, MCP status via `mcpServerStatus/list`, and hook / failed
116
- MCP-startup notices. Runs `danger-full-access` + `approvalPolicy: never` to
117
- match moi's bypass-permissions trust model. Known gaps: no interactive
124
+ MCP-startup notices. Workspace discovery scans `~/.codex/sessions` rollout
125
+ heads for cwds (`codex/discovery.ts` — no binary needed), and `availability()`
126
+ reports a missing `codex` executable (PATH + login-shell PATH lookup, with a
127
+ Codex Desktop app-bundle fallback — `executable.ts`) to setup flows and the
128
+ workspace composer. Runs `danger-full-access` + `approvalPolicy: never`
129
+ to match moi's bypass-permissions trust model. Known gaps: no interactive
118
130
  approval flow (server→client approval requests are auto-accepted
119
131
  defensively), and images ride inline as data URLs only (no `localImage` path
120
132
  mode).
@@ -137,8 +149,12 @@ doubles as the evaluation rubric for new harnesses.
137
149
  - **Interrupt / cancel** — stop the current turn without killing the session,
138
150
  and drop queued messages.
139
151
  - **Teardown** — graceful close on idle TTL, LRU eviction, server shutdown.
140
- - **Turn accounting** — know when a turn ends (CC: `result` message; Codex:
141
- `turn/completed`) to drive busy/idle state and the processing spinner.
152
+ - **Activity mirror** — map the backend's native lifecycle signal onto
153
+ `SessionActivity` (CC: `result` as the turn-over fallback plus
154
+ `session_state_changed` when the CLI emits it; Codex: `turn/started` /
155
+ `turn/completed`; OpenClaw: `agent` lifecycle phases). Flip to `running`
156
+ optimistically on send; a session with live background tasks (CC
157
+ `task_started`/`task_notification`) must not be idle-evicted.
142
158
 
143
159
  ### Per-request configuration
144
160
 
@@ -27,6 +27,19 @@ Evidence drawn from:
27
27
 
28
28
  ---
29
29
 
30
+ ## Runtime executable
31
+
32
+ The Agent SDK remains the transport layer, but every `query()` explicitly uses
33
+ the `claude` executable through `pathToClaudeCodeExecutable`. Lookup goes
34
+ through `../executable.ts`: the server's PATH merged with the user's
35
+ login-shell PATH (`../shell-path.ts`, probed once at startup), so a moi server
36
+ launched outside a terminal still finds CLIs from `~/.local/bin`, homebrew,
37
+ and version-manager shims. There is no SDK bundled-executable fallback. If the
38
+ command is missing, setup and existing workspaces report:
39
+ `Run curl -fsSL https://claude.ai/install.sh | sh in your terminal to install Claude`.
40
+
41
+ ---
42
+
30
43
  ## 1. Three layers
31
44
 
32
45
  ```
@@ -247,16 +260,17 @@ Message
247
260
 
248
261
  ## 9. What's missing today vs. what the SDK emits
249
262
 
250
- Known blind spots the abstraction should close:
263
+ Known blind spots the abstraction should close (historical audit — items marked
264
+ CLOSED have since been handled; see adapter.ts / session.ts):
251
265
 
252
266
  - **Thinking blocks** — SDK emits them; `transformMessage` drops them. Would require a new repo-level block type.
253
267
  - **Server tool use** (`web_search`, `web_fetch`, `code_execution`, etc.) — completely invisible. An assistant using `WebSearch` currently looks like a silent gap between user turn and final answer.
254
268
  - **MCP tool calls proper** (`mcp_tool_use` / `mcp_tool_result` blocks) — dropped. Regular `Task`/`Bash` MCP tools happen to survive because they wear the plain `tool_use` shape.
255
- - **Streaming** — `stream_event` dropped, so assistant text lands in one block per turn, not token-by-token.
256
- - **Session lifecycle signals** — `system/init`, `system/session_state_changed`, `system/status` dropped. UI can't display model name, current tools, permission mode, "thinking…", "awaiting permission".
257
- - **Sub-agent nesting** — subagent turns survive structurally but lose `parent_tool_use_id`, so they render flat. All `task_*` events dropped.
258
- - **Hooks / tasks / rate limits / api_retry** — all invisible.
259
- - **MessageBlock switch exhaustiveness** — any future repo-level type crashes render.
269
+ - **Streaming** — CLOSED: `stream_event` drives live token previews (`preview` frames) when the client opts into streaming.
270
+ - **Session lifecycle signals** — partially CLOSED: `system/init` feeds the session snapshot; `system/session_state_changed` mirrors into `SessionActivity` (note: current CLIs don't emit it in streaming-input mode — `result` is the everyday turn-over fallback); `requires-action` reaches the wire but has no UI yet. `system/status` (`requesting`/`compacting`) still dropped.
271
+ - **Sub-agent nesting** — CLOSED: `task_started`/`task_progress`/`task_notification` build nested subagent records; `task_started`/`task_updated`/`task_notification` also track live background tasks for the idle-eviction keep-alive (session.ts `bgTasks`).
272
+ - **Hooks / rate limits / api_retry** — CLOSED: surfaced as notices.
273
+ - **MessageBlock switch exhaustiveness** — the UI layer this referred to (`MessageBlock.tsx`) no longer exists; turns render via `TurnView`/`ToolCallGroup`.
260
274
 
261
275
  ---
262
276