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
package/server/cli.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env bun
2
2
  import './cli-colors' // must precede citty: sets NO_COLOR before its color flag is computed
3
3
  import { defineCommand, runMain, showUsage } from 'citty'
4
+ import { parse as devalueParse } from 'devalue'
4
5
  import { existsSync, readFileSync } from 'node:fs'
5
6
  import { tmpdir } from 'node:os'
6
7
  import { join, resolve } from 'path'
@@ -9,13 +10,15 @@ import pc from './cli-pc'
9
10
  import { COLOR_THEMES, FONT_THEMES } from '@/lib/themes'
10
11
  import type { ColorTheme, FontTheme } from '@/lib/themes'
11
12
  import type {
13
+ AppletLogEntry,
12
14
  ScratchArrowEnd,
13
15
  ScratchColor,
14
16
  ScratchFill,
15
17
  ScratchImageQuality,
16
18
  ScratchOp,
17
19
  ScratchSize,
18
- ScratchStyle
20
+ ScratchStyle,
21
+ WorkspaceEntry
19
22
  } from '@/lib/types'
20
23
 
21
24
  import {
@@ -481,6 +484,16 @@ const bundle = defineCommand({
481
484
  console.log(' ' + f.error + '\n')
482
485
  }
483
486
 
487
+ // Runtime errors still standing after the rebuild's clear-on-success
488
+ // sweep — point the agent at the journal while it's paying attention.
489
+ const logCount = typeof res.logCount === 'number' ? res.logCount : 0
490
+ if (logCount > 0) {
491
+ console.log(
492
+ pc.yellow(`ℹ ${logCount} applet runtime error(s) on record — run \`moi debug logs\`.`) +
493
+ '\n'
494
+ )
495
+ }
496
+
484
497
  if (notice) console.log(pc.yellow(notice) + '\n')
485
498
  ws.close()
486
499
  process.exit(failed.length > 0 ? 1 : 0)
@@ -741,7 +754,7 @@ const status = defineCommand({
741
754
 
742
755
  ws.onmessage = event => {
743
756
  const res = JSON.parse(String(event.data))
744
- const workspaces: { id: string; path: string; addedAt: string }[] = res.workspaces ?? []
757
+ const workspaces: WorkspaceEntry[] = res.workspaces ?? []
745
758
  const n = workspaces.length
746
759
  console.log(pc.dim(` ${n} workspace${n === 1 ? '' : 's'} registered\n`))
747
760
 
@@ -1319,15 +1332,16 @@ function styleArgs(args: {
1319
1332
 
1320
1333
  type ScratchCliOp = ScratchOp | { kind: 'read' } | { kind: 'read-image'; name: string }
1321
1334
 
1322
- // Round-trip one op through the control port and hand the reply to `onResult`.
1323
- // Mirrors the `bundle`/`theme` commands: one socket per invocation, print, exit.
1324
- function sendScratch(
1335
+ // Round-trip one request through the control port and hand the reply to
1336
+ // `onResult`. Mirrors the `bundle`/`theme` commands: one socket per invocation,
1337
+ // print, exit. Shared by `scratch`, `call-server-fn`, and `debug logs`.
1338
+ function sendControl(
1325
1339
  path: string,
1326
- op: ScratchCliOp,
1340
+ payload: Record<string, unknown>,
1327
1341
  onResult: (res: Record<string, unknown>) => void | Promise<void>
1328
1342
  ) {
1329
1343
  const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
1330
- ws.onopen = () => ws.send(JSON.stringify({ type: 'scratch', path, op }))
1344
+ ws.onopen = () => ws.send(JSON.stringify(payload))
1331
1345
  ws.onmessage = async event => {
1332
1346
  const res = JSON.parse(String(event.data))
1333
1347
  if (res.error) {
@@ -1349,6 +1363,14 @@ function sendScratch(
1349
1363
  }
1350
1364
  }
1351
1365
 
1366
+ function sendScratch(
1367
+ path: string,
1368
+ op: ScratchCliOp,
1369
+ onResult: (res: Record<string, unknown>) => void | Promise<void>
1370
+ ) {
1371
+ sendControl(path, { type: 'scratch', path, op }, onResult)
1372
+ }
1373
+
1352
1374
  // Print the name a draw op landed on, so the agent can address it later.
1353
1375
  function printAdded(res: Record<string, unknown>) {
1354
1376
  const result = res.result as { name?: string } | undefined
@@ -1677,6 +1699,136 @@ const scratch = defineCommand({
1677
1699
  }
1678
1700
  })
1679
1701
 
1702
+ // ---- self-correction commands (docs/self-correction.md) ---------------------
1703
+
1704
+ const callServerFn = defineCommand({
1705
+ meta: {
1706
+ name: 'call-server-fn',
1707
+ description: 'Invoke an applet .server.ts function in an isolated one-shot worker (smoke test)'
1708
+ },
1709
+ args: {
1710
+ fn: {
1711
+ type: 'positional',
1712
+ required: true,
1713
+ description: 'Function path: <module>/<fn>, e.g. widgets/hello/getGreeting'
1714
+ },
1715
+ args: {
1716
+ type: 'positional',
1717
+ required: false,
1718
+ description: 'Arguments as one JSON array, e.g. \'["ann", 10]\' (default [])'
1719
+ },
1720
+ dir: dirArg
1721
+ },
1722
+ run({ args }) {
1723
+ const path = resolve(args.dir)
1724
+ sendControl(
1725
+ path,
1726
+ { type: 'call-server-fn', path, fn: args.fn, args: args.args ?? '[]' },
1727
+ res => {
1728
+ // The worker replies devalue-encoded (same wire format the browser RPC
1729
+ // parses), so Map/Set/Date render readably through Bun.inspect.
1730
+ const value = devalueParse(String(res.result))
1731
+ console.log(Bun.inspect(value, { depth: 8, colors: process.stdout.isTTY }))
1732
+ // Duration on stderr: stdout stays clean data, and a slow call is a
1733
+ // warning sign worth surfacing (browser RPC times out at 30s).
1734
+ console.error(pc.dim(`↩ ${res.ms}ms`))
1735
+ }
1736
+ )
1737
+ }
1738
+ })
1739
+
1740
+ // Compact relative age for a journal row: "just now", "4m ago", "2h ago", …
1741
+ function agoLabel(ts: number): string {
1742
+ const s = Math.max(0, Math.round((Date.now() - ts) / 1000))
1743
+ if (s < 60) return 'just now'
1744
+ if (s < 3600) return `${Math.round(s / 60)}m ago`
1745
+ if (s < 86400) return `${Math.round(s / 3600)}h ago`
1746
+ return `${Math.round(s / 86400)}d ago`
1747
+ }
1748
+
1749
+ // Where a journal entry points: the server function for rpc rows, else the applet.
1750
+ function logSubject(e: {
1751
+ source: string
1752
+ kind?: string
1753
+ name?: string
1754
+ module?: string
1755
+ fn?: string
1756
+ }): string {
1757
+ if (e.module) return `${e.module}/${e.fn ?? '?'}`
1758
+ if (e.name) return `${e.kind ?? 'applet'} ${e.name}`
1759
+ return 'unattributed'
1760
+ }
1761
+
1762
+ const MAX_LOG_MESSAGE_LINES = 12
1763
+
1764
+ const debugLogs = defineCommand({
1765
+ meta: {
1766
+ name: 'logs',
1767
+ description: 'Applet runtime errors on record (load / render / rpc / build failures)'
1768
+ },
1769
+ args: {
1770
+ dir: dirArg,
1771
+ json: {
1772
+ type: 'boolean',
1773
+ default: false,
1774
+ description: 'Machine-readable output, includes stacks and epoch timestamps'
1775
+ },
1776
+ clear: { type: 'boolean', default: false, description: 'Wipe the journal' }
1777
+ },
1778
+ run({ args }) {
1779
+ const path = resolve(args.dir)
1780
+ if (args.clear) {
1781
+ sendControl(path, { type: 'debug:logs', path, clear: true }, res => {
1782
+ console.log('\n' + pc.green('✓') + ` cleared ${res.cleared ?? 0} entries\n`)
1783
+ })
1784
+ return
1785
+ }
1786
+ sendControl(path, { type: 'debug:logs', path }, res => {
1787
+ const entries = (Array.isArray(res.entries) ? res.entries : []) as AppletLogEntry[]
1788
+ if (args.json) {
1789
+ console.log(JSON.stringify(entries, null, 2))
1790
+ return
1791
+ }
1792
+ if (entries.length === 0) {
1793
+ console.log(
1794
+ '\n' + pc.bold('moi debug logs') + pc.dim(' — no applet errors on record') + '\n'
1795
+ )
1796
+ return
1797
+ }
1798
+ console.log(
1799
+ '\n' + pc.bold('moi debug logs') + pc.dim(` — ${entries.length} error(s) on record`) + '\n'
1800
+ )
1801
+ for (const e of entries) {
1802
+ const count = e.count > 1 ? pc.dim(` ×${e.count}`) : ''
1803
+ console.log(
1804
+ ` ${pc.dim(agoLabel(e.ts).padEnd(10))} ${e.source.padEnd(7)} ${pc.bold(logSubject(e))}${count}`
1805
+ )
1806
+ const lines = e.message.split('\n')
1807
+ for (const line of lines.slice(0, MAX_LOG_MESSAGE_LINES)) {
1808
+ console.log(' ' + line)
1809
+ }
1810
+ if (lines.length > MAX_LOG_MESSAGE_LINES) {
1811
+ console.log(pc.dim(` … ${lines.length - MAX_LOG_MESSAGE_LINES} more lines (--json)`))
1812
+ }
1813
+ console.log()
1814
+ }
1815
+ console.log(
1816
+ pc.dim(' Entries clear when their applet next builds successfully, or via --clear.') + '\n'
1817
+ )
1818
+ })
1819
+ }
1820
+ })
1821
+
1822
+ // Experimental workspace-debugging toolbox. One subcommand for now (`logs`);
1823
+ // more introspection (worker state, RPC traces, …) may hang off it later.
1824
+ const debug = defineCommand({
1825
+ meta: {
1826
+ name: 'debug',
1827
+ description: 'Debug the workspace (experimental) — `moi debug logs` for applet errors'
1828
+ },
1829
+ subCommands: { logs: debugLogs }
1830
+ })
1831
+
1680
1832
  // Re-copy bundled skills into a workspace, then report what changed. Pure
1681
1833
  // filesystem op — no running server needed. Resolves the workspace root the
1682
1834
  // same way `moi bundle` does, so it works from `.moi/` or any subdirectory.
@@ -1808,6 +1960,8 @@ const main = defineCommand({
1808
1960
  bundle,
1809
1961
  builder,
1810
1962
  refresh,
1963
+ 'call-server-fn': callServerFn,
1964
+ debug,
1811
1965
  theme,
1812
1966
  config,
1813
1967
  env,
package/server/control.ts CHANGED
@@ -1,10 +1,13 @@
1
+ import { stringify as devalueStringify } from 'devalue'
1
2
  import { resolve } from 'path'
2
3
 
3
4
  import type { WorkspaceEntry } from '@/lib/types'
4
5
 
6
+ import { clearAppletLog, getAppletLog, getAppletLogCount } from './applet-log'
5
7
  import { serializeWorkspaceBundle } from './bundle-queue'
6
8
  import { CONTROL_PORT } from './constants'
7
9
  import { applyEnvChanged } from './env-apply'
10
+ import { callFunctionEphemeral, parseFunctionPath } from './functions'
8
11
  import { processIcon } from './icon'
9
12
  import { loadLayout, saveLayout } from './layout'
10
13
  import { publishEvent } from './events'
@@ -119,7 +122,84 @@ export const control = Bun.serve({
119
122
  }
120
123
  }
121
124
  })
122
- ws.send(JSON.stringify({ ok: true, workspacePath, results }))
125
+ // Entries still standing after the rebuild's clear-on-success sweep —
126
+ // the CLI nudges the agent toward `moi debug logs` when non-zero.
127
+ ws.send(
128
+ JSON.stringify({
129
+ ok: true,
130
+ workspacePath,
131
+ results,
132
+ logCount: getAppletLogCount(workspacePath)
133
+ })
134
+ )
135
+ return
136
+ }
137
+
138
+ // The applet error journal — `moi debug logs` (docs/self-correction.md).
139
+ if (data.type === 'debug:logs') {
140
+ const match = await resolveWorkspace(ws, data.path)
141
+ if (!match) return
142
+ if (data.clear === true) {
143
+ ws.send(JSON.stringify({ ok: true, cleared: clearAppletLog(match.path) }))
144
+ return
145
+ }
146
+ ws.send(JSON.stringify({ ok: true, entries: getAppletLog(match.path) }))
147
+ return
148
+ }
149
+
150
+ // Direct server-function invocation — `moi call-server-fn <module>/<fn>`.
151
+ // Runs in an EPHEMERAL worker: a fresh process spawned for this one call
152
+ // and killed after, so a debug invocation is fully isolated from the
153
+ // warm pool the widgets use (same env/timeout/wire format otherwise).
154
+ // Args arrive as plain JSON (easier to hand-write than devalue's wire
155
+ // format) and are re-encoded for the worker; the result goes back
156
+ // devalue-encoded for the CLI to render.
157
+ if (data.type === 'call-server-fn') {
158
+ const match = await resolveWorkspace(ws, data.path)
159
+ if (!match) return
160
+ const parsed = parseFunctionPath(String(data.fn ?? ''))
161
+ if (!parsed) {
162
+ ws.send(
163
+ JSON.stringify({
164
+ error: `Invalid function path "${data.fn}". Use <module>/<fn>, e.g. widgets/hello/getGreeting.`
165
+ })
166
+ )
167
+ return
168
+ }
169
+ let args: unknown
170
+ try {
171
+ args = JSON.parse(String(data.args ?? '[]'))
172
+ } catch (err) {
173
+ ws.send(
174
+ JSON.stringify({
175
+ error: `Arguments must be valid JSON: ${err instanceof Error ? err.message : String(err)}`
176
+ })
177
+ )
178
+ return
179
+ }
180
+ if (!Array.isArray(args)) {
181
+ ws.send(
182
+ JSON.stringify({ error: 'Arguments must be a JSON array, e.g. \'["ann", 10]\'' })
183
+ )
184
+ return
185
+ }
186
+ const t0 = performance.now()
187
+ try {
188
+ const result = await callFunctionEphemeral(
189
+ parsed.module,
190
+ parsed.name,
191
+ devalueStringify(args),
192
+ match.path
193
+ )
194
+ ws.send(JSON.stringify({ ok: true, result, ms: Math.round(performance.now() - t0) }))
195
+ } catch (err) {
196
+ ws.send(
197
+ JSON.stringify({
198
+ error: err instanceof Error ? err.message : String(err),
199
+ ms: Math.round(performance.now() - t0)
200
+ })
201
+ )
202
+ }
123
203
  return
124
204
  }
125
205
 
@@ -186,20 +186,10 @@ export function parseFunctionPath(tail: string): { module: string; name: string
186
186
  return { module, name }
187
187
  }
188
188
 
189
- export async function callFunction(
190
- module: string,
191
- name: string,
192
- args: string,
193
- workspacePath: string
194
- ): Promise<string> {
195
- // Resolve the workspace env before (maybe) spawning, so a fresh worker picks
196
- // up current .env + custom overrides. Env is fixed at spawn — an already-warm
197
- // worker keeps its snapshot until restartWorker() reaps it. Widgets only see
198
- // secrets scoped to the 'widgets' sink.
199
- const workspaceEnv = await resolveWorkspaceEnv(workspacePath)
200
- const slot = getOrSpawn(workspacePath, workspaceEnv)
201
- await slot.readyPromise
202
-
189
+ // Issue one call against a live slot: register a pending entry, send the IPC
190
+ // frame, settle from the worker's reply (or the timeout). Shared by the warm
191
+ // pool path (callFunction) and the ephemeral path (callFunctionEphemeral).
192
+ function callInSlot(slot: Slot, module: string, name: string, args: string): Promise<string> {
203
193
  slot.calls++
204
194
  slot.lastCallAt = Date.now()
205
195
 
@@ -223,6 +213,46 @@ export async function callFunction(
223
213
  })
224
214
  }
225
215
 
216
+ export async function callFunction(
217
+ module: string,
218
+ name: string,
219
+ args: string,
220
+ workspacePath: string
221
+ ): Promise<string> {
222
+ // Resolve the workspace env before (maybe) spawning, so a fresh worker picks
223
+ // up current .env + custom overrides. Env is fixed at spawn — an already-warm
224
+ // worker keeps its snapshot until restartWorker() reaps it. Widgets only see
225
+ // secrets scoped to the 'widgets' sink.
226
+ const workspaceEnv = await resolveWorkspaceEnv(workspacePath)
227
+ const slot = getOrSpawn(workspacePath, workspaceEnv)
228
+ await slot.readyPromise
229
+ return callInSlot(slot, module, name, args)
230
+ }
231
+
232
+ // One-shot, isolated invocation — `moi call-server-fn`'s path. Spawns a fresh
233
+ // worker just for this call and kills it afterwards, so a debug invocation
234
+ // never touches the warm pool the widgets use: no shared module-level state in
235
+ // either direction, and a call that wedges the process takes the throwaway
236
+ // worker with it, not the pool. Same env resolution, module loading, timeout,
237
+ // and devalue wire format as the pool path — only the process lifetime differs.
238
+ // The slot is never registered in the LRU cache; its onExit cache-cleanup guard
239
+ // no-ops for an uncached slot.
240
+ export async function callFunctionEphemeral(
241
+ module: string,
242
+ name: string,
243
+ args: string,
244
+ workspacePath: string
245
+ ): Promise<string> {
246
+ const workspaceEnv = await resolveWorkspaceEnv(workspacePath)
247
+ const slot = spawnSlot(workspacePath, workspaceEnv)
248
+ try {
249
+ await slot.readyPromise
250
+ return await callInSlot(slot, module, name, args)
251
+ } finally {
252
+ killSlot(slot, 'Ephemeral call finished')
253
+ }
254
+ }
255
+
226
256
  // Kill every live worker. Called from the server's shutdown handler so a
227
257
  // dev-supervisor restart (or Ctrl-C) never orphans worker child processes.
228
258
  // killSlot is idempotent, so a dispose() racing in via clear() is harmless.
@@ -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
 
@@ -208,6 +224,7 @@ Legend: ✅ supported · ⚠️ partial/workaround · ❌ missing.
208
224
  | Images in input | ✅ base64 blocks | ⚠️ materialize to path | ✅ data URL or path |
209
225
  | Interactive approvals | ⚠️ (we bypass) | ✅ | ✅ server→client requests (we bypass) |
210
226
  | Session list/history API | ✅ `listSessions()` + jsonl | ✅ `sessions.get` | ✅ `thread/list`/`read` |
227
+ | Home card preview | ✅ session file scan | ✅ cached first message | ⚠️ live app-server only |
211
228
  | MCP status | ✅ `mcpServerStatus()` | n/a | ✅ `mcpServerStatus/list` |
212
229
  | Usage reporting | ⚠️ cost/duration on `result` (adapter drops tokens) | ✅ tokens + cost per turn | ✅ live + rate limits |
213
230
  | Structured output | ❌ | ❌ | ✅ per turn |
@@ -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
+ }