moi-computer 0.3.1-next.0 → 0.4.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 (99) hide show
  1. package/README.md +49 -12
  2. package/client/api/workspace-keys.ts +2 -2
  3. package/client/app/AppRouter.tsx +0 -2
  4. package/client/app/shell/SidebarLayout.tsx +3 -16
  5. package/client/assets/openai.svg +1 -3
  6. package/client/components/shared/Composer.tsx +53 -2
  7. package/client/components/ui/button.tsx +1 -1
  8. package/client/components/ui/tooltip.tsx +12 -15
  9. package/client/features/chat/ChatComposer.tsx +25 -15
  10. package/client/features/chat/ChatPanel.tsx +5 -2
  11. package/client/features/chat/MarkdownContent.tsx +20 -2
  12. package/client/features/chat/ModelPicker.tsx +5 -3
  13. package/client/features/chat/TurnView.tsx +2 -2
  14. package/client/features/chat/chat-frames.ts +13 -6
  15. package/client/features/chat/chat-send.ts +1 -1
  16. package/client/features/chat/chat-store.ts +22 -17
  17. package/client/features/chat/tool-group/ToolOutput.tsx +4 -12
  18. package/client/features/chat/tool-group/format.ts +22 -7
  19. package/client/features/chat/useChat.ts +11 -2
  20. package/client/features/connectors/McpServerCards.tsx +95 -0
  21. package/client/features/connectors/api.ts +0 -11
  22. package/client/features/dev/HarnessDebugPage.tsx +210 -74
  23. package/client/features/home/HomePage.tsx +33 -28
  24. package/client/features/home/api.ts +24 -12
  25. package/client/features/home/workspace-presentation.tsx +17 -15
  26. package/client/features/home/workspace-setup/CreateWorkspaceDialog.tsx +243 -0
  27. package/client/features/home/workspace-setup/ImportWorkspaceDialog.tsx +95 -0
  28. package/client/features/home/workspace-setup/WorkspaceAgentStep.tsx +230 -0
  29. package/client/features/home/workspace-setup/WorkspaceDialogContent.tsx +35 -0
  30. package/client/features/home/workspace-setup/useWorkspaceImport.ts +61 -0
  31. package/client/features/settings/ConnectorsSettings.tsx +89 -0
  32. package/client/features/settings/SettingsLayout.tsx +2 -2
  33. package/client/features/settings/WorkspaceSettings.tsx +8 -4
  34. package/client/features/views/ViewBuilderTab.tsx +19 -15
  35. package/client/features/views/useViewBuilderActions.ts +1 -1
  36. package/client/features/workspace/WorkspaceLayoutContext.tsx +3 -4
  37. package/client/features/workspace/WorkspaceScreen.tsx +11 -3
  38. package/client/features/workspace/api.ts +19 -1
  39. package/client/features/workspace/moi-context.ts +85 -0
  40. package/client/main.tsx +16 -5
  41. package/dist/chunk-19g80zc9.css +1 -0
  42. package/dist/{chunk-jen6xcm1.js → chunk-2vaafjp4.js} +1 -1
  43. package/dist/{chunk-vkvb3hjm.js → chunk-35fq49qa.js} +1 -1
  44. package/dist/chunk-69nhbjhy.js +50 -0
  45. package/dist/{chunk-axszxe4c.js → chunk-72atbmh3.js} +1 -1
  46. package/dist/{chunk-zpxrb1ce.js → chunk-7mkv2gr0.js} +2 -2
  47. package/dist/{chunk-cs8vbert.js → chunk-fh2mf6v9.js} +3 -3
  48. package/dist/chunk-gt7n06ef.js +1 -0
  49. package/dist/chunk-jwmc32rp.js +63 -0
  50. package/dist/chunk-kh24bstm.js +10 -0
  51. package/dist/chunk-sfa4mbmx.js +15 -0
  52. package/dist/index.html +1 -1
  53. package/dist/openai-ep9ht2pq.svg +1 -0
  54. package/lib/ids.ts +15 -0
  55. package/lib/moi-context.ts +170 -0
  56. package/lib/types.ts +29 -11
  57. package/lib/view-builder-directives.ts +16 -0
  58. package/lib/workspace-types.ts +12 -0
  59. package/package.json +2 -1
  60. package/server/api.ts +92 -30
  61. package/server/harness/README.md +25 -9
  62. package/server/harness/claude-code/NOTES.md +20 -6
  63. package/server/harness/claude-code/adapter.ts +2 -2
  64. package/server/harness/claude-code/git-worktree.ts +32 -0
  65. package/server/harness/claude-code/index.ts +33 -12
  66. package/server/harness/claude-code/mcp.ts +16 -65
  67. package/server/harness/claude-code/models.ts +3 -0
  68. package/server/harness/claude-code/session.ts +196 -61
  69. package/server/harness/codex/NOTES.md +41 -11
  70. package/server/harness/codex/adapter.ts +121 -16
  71. package/server/harness/codex/client.ts +67 -18
  72. package/server/harness/codex/discovery.ts +114 -0
  73. package/server/harness/codex/index.ts +10 -5
  74. package/server/harness/codex/probe.ts +4 -2
  75. package/server/harness/codex/session.ts +89 -13
  76. package/server/harness/executable.ts +82 -0
  77. package/server/harness/openclaw/adapter.ts +8 -1
  78. package/server/harness/openclaw/index.ts +8 -14
  79. package/server/harness/openclaw/session.ts +50 -10
  80. package/server/harness/openclaw/strip.ts +2 -2
  81. package/server/harness/shell-path.ts +79 -0
  82. package/server/harness/types.ts +22 -5
  83. package/server/registry.ts +57 -12
  84. package/server/view-builders.ts +3 -2
  85. package/server/web.ts +24 -8
  86. package/server/workspace-import.ts +45 -0
  87. package/workspace/.claude/skills/moi-workspace/SKILL.md +3 -3
  88. package/client/features/connectors/ConnectorsPage.tsx +0 -92
  89. package/client/features/connectors/McpMenu.tsx +0 -145
  90. package/client/features/home/CreateWorkspaceDialog.tsx +0 -130
  91. package/client/features/home/CreateWorkspaceDialogSteps.tsx +0 -234
  92. package/dist/chunk-4vf1t6v1.js +0 -10
  93. package/dist/chunk-6c8cwpzc.js +0 -1
  94. package/dist/chunk-b3ynfk4g.js +0 -62
  95. package/dist/chunk-b4b276wx.js +0 -15
  96. package/dist/chunk-kxmvv1ax.js +0 -48
  97. package/dist/chunk-npwq6jmr.css +0 -1
  98. package/dist/openai-h13pza4b.svg +0 -3
  99. package/lib/view-builder-meta.ts +0 -35
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
 
@@ -15,7 +15,7 @@ import type {
15
15
  } from '@/lib/format'
16
16
 
17
17
  import { ATTACHMENT_ONLY_PLACEHOLDER, splitAttachmentNote } from '@/lib/attachment-note'
18
- import { stripViewBuilderMeta } from '@/lib/view-builder-meta'
18
+ import { stripMoiContext } from '@/lib/moi-context'
19
19
 
20
20
  // Loose SDK message shape — we don't pull in the full SDK type tree; the
21
21
  // adapter tolerates missing fields. Reference: ./NOTES.md.
@@ -521,7 +521,7 @@ export class ClaudeAdapter {
521
521
  // file chips here — a reloaded bubble matches the live one
522
522
  // instead of leaking temp paths into it.
523
523
  const split = splitAttachmentNote(text)
524
- text = stripViewBuilderMeta(split.text)
524
+ text = stripMoiContext(split.text)
525
525
  for (const f of split.files) {
526
526
  parts.push({
527
527
  type: 'file',
@@ -0,0 +1,32 @@
1
+ // Detecting linked git worktrees so workspace discovery can skip them.
2
+ //
3
+ // Claude Code accumulates session history in every directory an agent ever ran
4
+ // in, including the throwaway checkouts created for worktree-isolated runs.
5
+ // Those derived directories shouldn't surface as importable workspaces in the
6
+ // discovery list, so we filter them out. moi doesn't support running inside a
7
+ // worktree yet — see docs/git-worktrees.md.
8
+ import { readFile } from 'node:fs/promises'
9
+ import { join } from 'node:path'
10
+
11
+ // A linked git worktree stores its `.git` as a *file* (not a directory) whose
12
+ // single line points into the primary repo: `gitdir: /repo/.git/worktrees/<id>`.
13
+ // Return true only for that shape. Submodules also use a `.git` file, but they
14
+ // point into `.git/modules/…`, so keying on the `worktrees` segment leaves
15
+ // submodule checkouts alone.
16
+ export function pointsIntoWorktrees(gitFileContents: string): boolean {
17
+ const match = /^gitdir:\s*(.+?)\s*$/m.exec(gitFileContents)
18
+ if (!match) return false
19
+ return /(?:^|[/\\])\.git[/\\]worktrees[/\\]/.test(match[1])
20
+ }
21
+
22
+ // Whether `dir` is a linked git worktree checkout. A normal repo keeps `.git`
23
+ // as a directory (so `readFile` fails with EISDIR → false); a non-repo has no
24
+ // `.git` at all (ENOENT → false). Any read error is treated as "not a
25
+ // worktree" so discovery fails open rather than hiding real workspaces.
26
+ export async function isLinkedGitWorktree(dir: string): Promise<boolean> {
27
+ try {
28
+ return pointsIntoWorktrees(await readFile(join(dir, '.git'), 'utf8'))
29
+ } catch {
30
+ return false
31
+ }
32
+ }
@@ -2,15 +2,17 @@
2
2
  // ../types.ts for the contract and ../README.md for the architecture.
3
3
  import { join } from 'node:path'
4
4
 
5
- import type { DiscoveredWorkspace, McpServer } from '@/lib/types'
5
+ import type { McpServer } from '@/lib/types'
6
6
 
7
- import type { Harness } from '../types'
7
+ import type { DiscoveredWorkspaceCandidate, Harness } from '../types'
8
+ import { findHarnessExecutable, pathHarnessAvailability } from '../executable'
9
+ import { isLinkedGitWorktree } from './git-worktree'
8
10
  import { getMcpStatus } from './mcp'
9
11
  import { getClaudeModels } from './models'
10
12
  import {
11
13
  SESSION_LIMITS,
12
14
  getCCDebugSnapshot,
13
- getCCRunningSessions,
15
+ getCCActiveSessions,
14
16
  interruptCCSession,
15
17
  killAllCCSessions,
16
18
  restartWorkspaceSessions,
@@ -38,7 +40,9 @@ function fmtAgo(ts: number, now: number): string {
38
40
  }
39
41
 
40
42
  // Discover directories with CC session history that aren't registered yet.
41
- async function discoverWorkspaces(registeredPaths: Set<string>): Promise<DiscoveredWorkspace[]> {
43
+ async function discoverWorkspaces(
44
+ registeredPaths: Set<string>
45
+ ): Promise<DiscoveredWorkspaceCandidate[]> {
42
46
  try {
43
47
  const { listSessions } = await import('@anthropic-ai/claude-agent-sdk')
44
48
  const sessions = await listSessions({})
@@ -51,7 +55,13 @@ async function discoverWorkspaces(registeredPaths: Set<string>): Promise<Discove
51
55
  if (info.isDirectory()) paths.add(s.cwd)
52
56
  } catch {}
53
57
  }
54
- return [...paths].map(path => ({ path, type: 'claude-code' as const }))
58
+ // Drop linked git worktrees — throwaway checkouts (e.g. worktree-isolated
59
+ // runs) that shouldn't surface as importable workspaces.
60
+ const candidates = [...paths]
61
+ const worktree = await Promise.all(candidates.map(isLinkedGitWorktree))
62
+ return candidates
63
+ .filter((_, i) => !worktree[i])
64
+ .map(path => ({ path, type: 'claude-code' as const }))
55
65
  } catch {
56
66
  return []
57
67
  }
@@ -69,7 +79,7 @@ export const claudeCodeHarness: Harness = {
69
79
 
70
80
  sendMessage: input => sendCCMessage(input),
71
81
  interrupt: (workspaceId, sessionId) => interruptCCSession(workspaceId, sessionId),
72
- runningSessions: () => getCCRunningSessions(),
82
+ activeSessions: () => getCCActiveSessions(),
73
83
 
74
84
  listSessions: ws => getSessions(ws.path),
75
85
  workspacePreview: (ws, includeFirstUserMessage) =>
@@ -78,8 +88,9 @@ export const claudeCodeHarness: Harness = {
78
88
  listModels: ws => getClaudeModels(ws.path),
79
89
  // The SDK's McpServerStatus is a superset of the UI's McpServer (extra
80
90
  // fields are ignored by the client) — pass it through unchanged.
81
- mcpStatus: async ws => (await getMcpStatus(ws.path, 'project')) as unknown as McpServer[],
91
+ mcpStatus: async ws => (await getMcpStatus(ws.path)) as unknown as McpServer[],
82
92
  discoverWorkspaces,
93
+ availability: async () => pathHarnessAvailability('claude-code'),
83
94
 
84
95
  onEnvChanged: workspacePath => restartWorkspaceSessions(workspacePath),
85
96
  shutdown: () => killAllCCSessions(),
@@ -87,8 +98,9 @@ export const claudeCodeHarness: Harness = {
87
98
 
88
99
  statusLines: now => {
89
100
  const cc = getCCDebugSnapshot()
90
- const busy = cc.sessions.filter(s => s.busy).length
101
+ const busy = cc.sessions.filter(s => s.activity !== 'idle').length
91
102
  const lines = [
103
+ `claude executable ${findHarnessExecutable('claude-code') ?? '(not found)'}`,
92
104
  `live CC sessions ${cc.sessions.length}/${SESSION_LIMITS.maxLive} ` +
93
105
  `(${busy} busy, ${cc.sessions.length - busy} idle, ${cc.aliases} alias${cc.aliases === 1 ? '' : 'es'}, ` +
94
106
  `idle TTL ${fmtDuration(SESSION_LIMITS.idleTtlMs)})`
@@ -99,10 +111,19 @@ export const claudeCodeHarness: Harness = {
99
111
  }
100
112
  // Busiest / most-recently-active first.
101
113
  const sorted = [...cc.sessions].sort(
102
- (a, b) => Number(b.busy) - Number(a.busy) || b.lastActivityAt - a.lastActivityAt
114
+ (a, b) =>
115
+ Number(b.activity !== 'idle') - Number(a.activity !== 'idle') ||
116
+ b.lastActivityAt - a.lastActivityAt
103
117
  )
104
118
  for (const s of sorted) {
105
- const mark = s.busy ? '▶ busy' : s.closed ? '✗ closed' : '○ idle'
119
+ const mark =
120
+ s.activity === 'running'
121
+ ? '▶ busy'
122
+ : s.activity === 'requires-action'
123
+ ? '⏸ input'
124
+ : s.closed
125
+ ? '✗ closed'
126
+ : '○ idle'
106
127
  const bits = [
107
128
  mark.padEnd(8),
108
129
  `ws=${s.workspaceId}`,
@@ -110,13 +131,13 @@ export const claudeCodeHarness: Harness = {
110
131
  `model=${s.model ?? 'default'}`,
111
132
  `effort=${s.effort ?? 'default'}`,
112
133
  `stream=${s.stream ? 'on' : 'off'}`,
113
- `pending=${s.pendingTurns}`,
114
134
  `age=${fmtDuration(now - s.createdAt)}`,
115
135
  `lastActivity=${fmtAgo(s.lastActivityAt, now)}`
116
136
  ]
137
+ if (s.bgTasks > 0) bits.push(`bgTasks=${s.bgTasks}`)
117
138
  if (s.desiredEffort !== s.effort) bits.push(`desiredEffort=${s.desiredEffort ?? 'default'}`)
118
139
  if (s.desiredStream !== s.stream) bits.push(`desiredStream=${s.desiredStream ? 'on' : 'off'}`)
119
- if (!s.busy && !s.hasIdleTimer) bits.push('(no idle timer)')
140
+ if (s.activity === 'idle' && !s.hasIdleTimer) bits.push('(no idle timer)')
120
141
  let line = ' ' + bits.join(' ')
121
142
  if (s.lastUserText) line += `\n last: ${JSON.stringify(s.lastUserText)}`
122
143
  lines.push(line)
@@ -1,14 +1,8 @@
1
1
  import { query } from '@anthropic-ai/claude-agent-sdk'
2
- import type {
3
- McpServerConfig,
4
- McpServerStatus,
5
- SDKUserMessage
6
- } from '@anthropic-ai/claude-agent-sdk'
7
- import { join } from 'path'
2
+ import type { McpServerStatus, SDKUserMessage } from '@anthropic-ai/claude-agent-sdk'
8
3
 
9
4
  import { debugEnabled } from '../../debug'
10
-
11
- export type McpScope = 'user' | 'project'
5
+ import { requireHarnessExecutable } from '../executable'
12
6
 
13
7
  // MCP server status probing. Intentionally decoupled from agent chat runs
14
8
  // (cc-session.ts): connecting to MCP servers and reading their status is a
@@ -38,9 +32,9 @@ function isSettled(status: McpServerStatus[]): boolean {
38
32
  // attention (failed / needs-auth / still-pending) called out by name. The full
39
33
  // per-server dump (every `connected` line too) is opt-in via `moi start --debug`.
40
34
  // `connected`/`disabled` are the boring majority, so they're folded into counts.
41
- function logMcpStatus(scope: McpScope, status: McpServerStatus[]): void {
35
+ function logMcpStatus(status: McpServerStatus[]): void {
42
36
  if (debugEnabled) {
43
- console.log(`[mcp:${scope}]`, status.map(s => `${s.name}:${s.status}`).join(', '))
37
+ console.log('[mcp]', status.map(s => `${s.name}:${s.status}`).join(', '))
44
38
  return
45
39
  }
46
40
  const connected = status.filter(s => s.status === 'connected').length
@@ -49,41 +43,10 @@ function logMcpStatus(scope: McpScope, status: McpServerStatus[]): void {
49
43
  const parts = [`${connected} connected`]
50
44
  if (disabled) parts.push(`${disabled} disabled`)
51
45
  for (const s of attention) parts.push(`${s.status}: ${s.name}`)
52
- console.log(`[mcp:${scope}]`, parts.join(' · '))
53
- }
54
-
55
- function isRecord(value: unknown): value is Record<string, unknown> {
56
- return typeof value === 'object' && value !== null && !Array.isArray(value)
46
+ console.log('[mcp]', parts.join(' · '))
57
47
  }
58
48
 
59
- async function projectMcpServers(workspacePath: string): Promise<Record<string, McpServerConfig>> {
60
- const file = Bun.file(join(workspacePath, '.mcp.json'))
61
- if (!(await file.exists())) return {}
62
-
63
- const parsed = await file.json().catch(() => null)
64
- if (!isRecord(parsed) || !isRecord(parsed.mcpServers)) return {}
65
-
66
- const servers: Record<string, McpServerConfig> = {}
67
- for (const [name, config] of Object.entries(parsed.mcpServers)) {
68
- // The SDK owns the detailed MCP config union; here we only need to confirm
69
- // the project JSON declares an object keyed by server name before passing it
70
- // through unchanged.
71
- if (isRecord(config)) servers[name] = config as unknown as McpServerConfig
72
- }
73
- return servers
74
- }
75
-
76
- async function probeMcpStatus(workspacePath: string, scope: McpScope): Promise<McpServerStatus[]> {
77
- // Known gap, revisit: the project probe covers only `.mcp.json` (strict), and
78
- // the user probe runs from the server's cwd — so servers added via `claude
79
- // mcp add` (user scope) or `.claude/settings(.local).json` never appear in
80
- // the workspace connectors menu, even though chat sessions still load them
81
- // (cc-session runs with settingSources ['user','project']). Surfacing those
82
- // scopes here needs a per-workspace user+project probe without double-listing
83
- // servers across the menu and the /connectors page.
84
- const mcpServers = scope === 'project' ? await projectMcpServers(workspacePath) : undefined
85
- if (scope === 'project' && Object.keys(mcpServers ?? {}).length === 0) return []
86
-
49
+ async function probeMcpStatus(workspacePath: string): Promise<McpServerStatus[]> {
87
50
  // A prompt that never yields keeps the session alive without a model turn.
88
51
  let release!: () => void
89
52
  const done = new Promise<void>(r => (release = r))
@@ -98,9 +61,9 @@ async function probeMcpStatus(workspacePath: string, scope: McpScope): Promise<M
98
61
  prompt: keepAlive(),
99
62
  options: {
100
63
  cwd: workspacePath,
64
+ pathToClaudeCodeExecutable: requireHarnessExecutable('claude-code'),
101
65
  persistSession: false,
102
- settingSources: [scope],
103
- ...(mcpServers && { mcpServers, strictMcpConfig: true }),
66
+ settingSources: ['user', 'project'],
104
67
  env: { ...process.env, CLAUDECODE: undefined }
105
68
  }
106
69
  })
@@ -113,7 +76,7 @@ async function probeMcpStatus(workspacePath: string, scope: McpScope): Promise<M
113
76
  if (isSettled(status)) break
114
77
  await new Promise(r => setTimeout(r, POLL_INTERVAL_MS))
115
78
  }
116
- logMcpStatus(scope, status)
79
+ logMcpStatus(status)
117
80
  return status
118
81
  } finally {
119
82
  release()
@@ -150,33 +113,21 @@ const cache = new Map<string, CacheEntry>()
150
113
  // cheap insurance against parallel probes of the same workspace.
151
114
  const inflight = new Map<string, Promise<McpServerStatus[]>>()
152
115
 
153
- function cacheKey(scope: McpScope, workspacePath: string): string {
154
- return `${scope}:${workspacePath}`
155
- }
156
-
157
- export async function getMcpStatus(
158
- workspacePath: string,
159
- scope: McpScope = 'project'
160
- ): Promise<McpServerStatus[]> {
161
- const key = cacheKey(scope, workspacePath)
162
- const cached = cache.get(key)
116
+ export async function getMcpStatus(workspacePath: string): Promise<McpServerStatus[]> {
117
+ const cached = cache.get(workspacePath)
163
118
  if (cached && cached.expiresAt > Date.now()) return cached.status
164
119
 
165
- const existing = inflight.get(key)
120
+ const existing = inflight.get(workspacePath)
166
121
  if (existing) return existing
167
122
 
168
- const probe = probeMcpStatus(workspacePath, scope)
123
+ const probe = probeMcpStatus(workspacePath)
169
124
  .then(status => {
170
125
  const ttl = ttlFor(status)
171
- if (ttl > 0) cache.set(key, { status, expiresAt: Date.now() + ttl })
126
+ if (ttl > 0) cache.set(workspacePath, { status, expiresAt: Date.now() + ttl })
172
127
  return status
173
128
  })
174
- .finally(() => inflight.delete(key))
129
+ .finally(() => inflight.delete(workspacePath))
175
130
 
176
- inflight.set(key, probe)
131
+ inflight.set(workspacePath, probe)
177
132
  return probe
178
133
  }
179
-
180
- export async function getUserMcpStatus(): Promise<McpServerStatus[]> {
181
- return getMcpStatus(process.cwd(), 'user')
182
- }