moi-computer 0.3.1-next.1 → 0.4.1-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/README.md +85 -12
  2. package/bin/moi.mjs +11 -0
  3. package/client/api/workspace-keys.ts +1 -0
  4. package/client/app/AppRouter.tsx +5 -1
  5. package/client/app/routes/WorkspaceRoute.tsx +9 -5
  6. package/client/app/shell/SidebarLayout.tsx +9 -7
  7. package/client/components/shared/BottomPanel.tsx +24 -5
  8. package/client/components/shared/Composer.tsx +1 -1
  9. package/client/components/shared/PanelHeader.tsx +1 -1
  10. package/client/components/ui/button.tsx +5 -5
  11. package/client/components/ui/dropdown-menu.tsx +6 -6
  12. package/client/components/ui/hover-card.tsx +1 -1
  13. package/client/components/ui/input.tsx +1 -1
  14. package/client/components/ui/popover.tsx +1 -1
  15. package/client/components/ui/skeleton.tsx +1 -1
  16. package/client/components/ui/textarea.tsx +1 -1
  17. package/client/components/ui/tooltip.tsx +1 -1
  18. package/client/features/applets/applet-cache.ts +20 -1
  19. package/client/features/applets/applet-log.ts +10 -30
  20. package/client/features/applets/applet-runtime.ts +272 -0
  21. package/client/features/applets/useApplet.ts +36 -10
  22. package/client/features/chat/ChatComposer.tsx +1 -1
  23. package/client/features/chat/ChatEmptyState.tsx +186 -0
  24. package/client/features/chat/ChatPanel.tsx +95 -54
  25. package/client/features/chat/ChatPopup.tsx +3 -13
  26. package/client/features/chat/ChatPromptBubbles.tsx +74 -0
  27. package/client/features/chat/MarkdownContent.tsx +15 -3
  28. package/client/features/chat/ModelPicker.tsx +1 -1
  29. package/client/features/chat/TurnView.tsx +6 -17
  30. package/client/features/chat/chat-send.ts +26 -1
  31. package/client/features/chat/tool-group/CodeBlock.tsx +1 -1
  32. package/client/features/chat/tool-group/ReadImagePreview.tsx +1 -1
  33. package/client/features/chat/tool-group/SubagentCard.tsx +1 -1
  34. package/client/features/chat/tool-group/TimelineRow.tsx +4 -4
  35. package/client/features/chat/tool-group/ToolCallGroup.tsx +12 -5
  36. package/client/features/chat/tool-group/ToolOutput.tsx +2 -2
  37. package/client/features/chat/tool-group/format.ts +25 -4
  38. package/client/features/chat/useAppletChatMessage.ts +69 -0
  39. package/client/features/chat/useChat.ts +49 -14
  40. package/client/features/chat/useStickToBottom.ts +11 -1
  41. package/client/features/connectors/McpServerCards.tsx +3 -3
  42. package/client/features/dev/HarnessDebugPage.tsx +213 -77
  43. package/client/features/dev/PixelPainter.tsx +1 -1
  44. package/client/features/dev/PlaygroundPage.tsx +1 -1
  45. package/client/features/dev/ToolCallsPage.tsx +2 -2
  46. package/client/features/home/HomePage.tsx +17 -14
  47. package/client/features/home/WorkspacePreview.tsx +12 -13
  48. package/client/features/home/api.ts +8 -5
  49. package/client/features/home/workspace-presentation.tsx +1 -1
  50. package/client/features/home/workspace-setup/CreateWorkspaceDialog.tsx +1 -1
  51. package/client/features/home/workspace-setup/WorkspaceAgentStep.tsx +21 -8
  52. package/client/features/scratchpad/Scratchpad.tsx +41 -2
  53. package/client/features/scratchpad/ScratchpadControls.tsx +13 -13
  54. package/client/features/scratchpad/useScratchpadSnapshot.tsx +1 -1
  55. package/client/features/settings/EnvironmentSettings.tsx +1 -1
  56. package/client/features/settings/IconPicker.tsx +11 -11
  57. package/client/features/settings/SettingsLayout.tsx +1 -1
  58. package/client/features/settings/WorkspaceSettings.tsx +2 -2
  59. package/client/features/settings/api.ts +33 -1
  60. package/client/features/widgets/HiddenPanel.tsx +4 -3
  61. package/client/features/widgets/Widgets.tsx +1 -0
  62. package/client/features/workspace/CustomizePanel.tsx +96 -82
  63. package/client/features/workspace/WorkspaceScreen.tsx +129 -107
  64. package/client/features/workspace/WorkspaceSkillUpdateBanner.tsx +91 -0
  65. package/client/features/workspace/WorkspaceTabs.tsx +1 -1
  66. package/client/features/workspace/api.ts +52 -0
  67. package/client/features/workspace/moi-context.ts +63 -17
  68. package/client/features/workspace/tab-resolution.ts +75 -0
  69. package/client/features/workspace/useWorkspaceNavigation.ts +128 -0
  70. package/client/features/workspace/useWorkspaceSkillUpdates.ts +160 -0
  71. package/client/index.css +10 -15
  72. package/client/lib/app-icon-registry.ts +77 -70
  73. package/client/lib/rate-limit.ts +77 -0
  74. package/client/main.tsx +10 -2
  75. package/client/runtime/useWorkspaceEvents.ts +15 -2
  76. package/client/runtime/workspace-theme.ts +115 -0
  77. package/client/store/ui.ts +42 -17
  78. package/client/theme.css +20 -15
  79. package/dist/{chunk-1dfbr7n2.js → chunk-3m1xe1j3.js} +94 -94
  80. package/dist/chunk-5vaevt8z.js +2 -0
  81. package/dist/chunk-7bzpmtxp.js +50 -0
  82. package/dist/chunk-h0hk61pm.js +9 -0
  83. package/dist/{chunk-vkvb3hjm.js → chunk-h3evrtyp.js} +1 -1
  84. package/dist/chunk-k5sjx9s5.js +1 -0
  85. package/dist/{chunk-jen6xcm1.js → chunk-m9qja0nx.js} +1 -1
  86. package/dist/chunk-s7za1qsv.css +1 -0
  87. package/dist/{chunk-sxbfh73c.js → chunk-tcfa3vt3.js} +1 -1
  88. package/dist/chunk-v797g6ap.js +51 -0
  89. package/dist/chunk-xyrw8318.js +27 -0
  90. package/dist/index.html +1 -1
  91. package/lib/app-icons.ts +73 -0
  92. package/lib/moi-context.ts +104 -3
  93. package/lib/themes.ts +83 -45
  94. package/lib/types.ts +44 -9
  95. package/lib/workspace-tabs.ts +48 -0
  96. package/package.json +4 -1
  97. package/server/api.ts +57 -5
  98. package/server/app-settings.ts +65 -0
  99. package/server/applets.ts +132 -22
  100. package/server/bundler/build-applet.ts +74 -16
  101. package/server/cli.ts +144 -17
  102. package/server/control.ts +53 -7
  103. package/server/data-dir.ts +1 -1
  104. package/server/events.ts +1 -1
  105. package/server/functions-worker.ts +15 -1
  106. package/server/functions.ts +51 -6
  107. package/server/harness/claude-code/index.ts +2 -1
  108. package/server/harness/codex/adapter.ts +100 -9
  109. package/server/harness/codex/client.ts +34 -1
  110. package/server/harness/codex/index.ts +2 -1
  111. package/server/harness/codex/session.ts +32 -8
  112. package/server/layout.ts +9 -14
  113. package/server/moi-scaffold.ts +37 -3
  114. package/server/registry.ts +1 -1
  115. package/server/skill-update.ts +47 -0
  116. package/server/skill-version.ts +2 -11
  117. package/server/tabs.ts +59 -0
  118. package/server/theme.ts +8 -14
  119. package/server/view-builders.ts +6 -2
  120. package/workspace/.claude/skills/moi-workspace/DESIGN.md +265 -107
  121. package/workspace/.claude/skills/moi-workspace/SKILL.md +85 -11
  122. package/client/features/workspace/useWorkspaceTheme.ts +0 -82
  123. package/dist/chunk-339jds4x.js +0 -15
  124. package/dist/chunk-3xsvsnhr.css +0 -1
  125. package/dist/chunk-6c8cwpzc.js +0 -1
  126. package/dist/chunk-anqmsbjt.js +0 -2
  127. package/dist/chunk-hbvfb6sk.js +0 -63
  128. package/dist/chunk-qwm5f6qk.js +0 -48
  129. package/dist/chunk-yp4srgqt.js +0 -10
  130. package/workspace/.claude/skills/moi-workspace/VIEW-DESIGN.md +0 -22
package/server/cli.ts CHANGED
@@ -7,8 +7,9 @@ import { tmpdir } from 'node:os'
7
7
  import { join, resolve } from 'path'
8
8
  import pc from './cli-pc'
9
9
 
10
- import { COLOR_THEMES, FONT_THEMES } from '@/lib/themes'
10
+ import { COLOR_THEMES, FONT_THEMES, deriveThemeColors } from '@/lib/themes'
11
11
  import type { ColorTheme, FontTheme } from '@/lib/themes'
12
+ import { isParamsRecord } from '@/lib/workspace-tabs'
12
13
  import type {
13
14
  AppletLogEntry,
14
15
  ScratchArrowEnd,
@@ -18,7 +19,8 @@ import type {
18
19
  ScratchOp,
19
20
  ScratchSize,
20
21
  ScratchStyle,
21
- WorkspaceEntry
22
+ WorkspaceEntry,
23
+ WorkspaceSkillStatus
22
24
  } from '@/lib/types'
23
25
 
24
26
  import {
@@ -34,21 +36,20 @@ import { type OpenClawAgent, discoverOpenClawAgents } from './harness/openclaw/d
34
36
  import { liftToWorkspaceRoot, registerWorkspace } from './registry'
35
37
  import { serverCwd } from './server-cwd'
36
38
  import {
37
- type SkillStatus,
38
39
  isBehind,
39
40
  isMinorBehind,
40
41
  resolveWorkspace,
41
42
  skillStatuses,
42
43
  staleSkillNotice
43
44
  } from './skill-version'
44
- import { installBundledSkills } from './skills-template'
45
+ import { updateWorkspaceSkills } from './skill-update'
45
46
  import {
46
47
  getWorkspaceEnvView,
47
48
  isValidEnvKey,
48
49
  secretBackend,
49
50
  updateWorkspaceEnv
50
51
  } from './workspace-env'
51
- import { provisionWorkspace, skillsDirFor } from './workspace-init'
52
+ import { provisionWorkspace } from './workspace-init'
52
53
 
53
54
  // ---- helpers ----------------------------------------------------------------
54
55
 
@@ -573,13 +574,27 @@ const refresh = defineCommand({
573
574
  meta: {
574
575
  name: 'refresh',
575
576
  description:
576
- 'Refresh widget data without rebuilding. Use after the agent mutates underlying data.'
577
+ 'Refresh widget and view data without rebuilding. Use after the agent mutates underlying data.'
577
578
  },
578
- async run() {
579
+ args: {
580
+ only: {
581
+ type: 'string',
582
+ description: 'Narrow the refresh to "widgets" or "views" (default: both)'
583
+ }
584
+ },
585
+ async run({ args }) {
586
+ // Validate up front: a typo'd filter silently refreshing everything would
587
+ // read as "my filter worked".
588
+ if (args.only && args.only !== 'widgets' && args.only !== 'views') {
589
+ console.error(
590
+ '\n' + pc.red('✗') + ` Unknown --only value "${args.only}" — use "widgets" or "views".\n`
591
+ )
592
+ process.exit(1)
593
+ }
579
594
  const notice = await staleSkillNotice(process.cwd())
580
595
  const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
581
596
 
582
- ws.onopen = () => ws.send(JSON.stringify({ type: 'widget:refresh' }))
597
+ ws.onopen = () => ws.send(JSON.stringify({ type: 'applets:refresh', only: args.only }))
583
598
 
584
599
  ws.onmessage = event => {
585
600
  const data = JSON.parse(String(event.data))
@@ -588,7 +603,9 @@ const refresh = defineCommand({
588
603
  ws.close()
589
604
  process.exit(1)
590
605
  }
591
- console.log('\n' + pc.green('✓') + ' Refresh signal sent\n')
606
+ console.log(
607
+ '\n' + pc.green('✓') + ' Refresh signal sent' + (args.only ? ` (${args.only})` : '') + '\n'
608
+ )
592
609
  if (notice) console.log(pc.yellow(notice) + '\n')
593
610
  ws.close()
594
611
  process.exit(0)
@@ -615,6 +632,12 @@ function swatch(bg?: string, fg?: string): string {
615
632
  return `\x1b[48;2;${br};${bgg};${bb}m\x1b[38;2;${fr};${fgg};${fb}m Aa \x1b[0m`
616
633
  }
617
634
 
635
+ function themeSwatch(primary?: string): string {
636
+ if (!primary) return swatch()
637
+ const colors = deriveThemeColors(primary)
638
+ return swatch(colors.primary, colors.primaryForeground)
639
+ }
640
+
618
641
  const theme = defineCommand({
619
642
  meta: { name: 'theme', description: 'Show or set the workspace font and color themes' },
620
643
  args: {
@@ -663,7 +686,7 @@ const theme = defineCommand({
663
686
  }
664
687
  if (res.color) {
665
688
  const preset = COLOR_THEMES[res.color as ColorTheme]
666
- const chip = swatch(preset.background, preset.foreground)
689
+ const chip = themeSwatch(preset.primary)
667
690
  console.log(pc.green('✓') + ' Color set to ' + pc.bold(preset.label) + ' ' + chip)
668
691
  }
669
692
  console.log()
@@ -704,14 +727,13 @@ const theme = defineCommand({
704
727
  selected ? pc.green('→') : ' ',
705
728
  selected ? pc.bold(key) : key,
706
729
  c.label,
707
- swatch(c.background, c.foreground),
708
- pc.dim(c.feel)
730
+ themeSwatch(c.primary)
709
731
  ]
710
732
  })
711
733
  console.log(pc.dim(' Colors'))
712
734
  console.log(
713
735
  columns(
714
- ['', 'key', 'label', 'swatch', 'feel'].map(h => pc.dim(h)),
736
+ ['', 'key', 'label', 'swatch'].map(h => pc.dim(h)),
715
737
  colorRows
716
738
  ) + '\n'
717
739
  )
@@ -1829,6 +1851,97 @@ const debug = defineCommand({
1829
1851
  subCommands: { logs: debugLogs }
1830
1852
  })
1831
1853
 
1854
+ // ---- workspace tabs ----------------------------------------------------------
1855
+
1856
+ // The shared listing behind `moi tabs` and bare `moi tab`: every tab (static +
1857
+ // views), one per row, the saved default (`layout.tabs.active`) marked. The
1858
+ // output shape is documented in docs/rfc-intents-v2.md §3 — keep them in sync.
1859
+ function runTabsList(dir: string) {
1860
+ const path = resolve(dir)
1861
+ sendControl(path, { type: 'tabs', path }, res => {
1862
+ type Row = { id: string; title: string; isDefault: boolean }
1863
+ const rows: Row[] = Array.isArray(res.tabs) ? (res.tabs as Row[]) : []
1864
+ console.log(
1865
+ '\n' + pc.bold('moi tabs') + pc.dim(' — workspace tabs, the default one marked') + '\n'
1866
+ )
1867
+ console.log(
1868
+ columns(
1869
+ ['', 'tab', 'title'].map(h => pc.dim(h)),
1870
+ rows.map(row => [
1871
+ row.isDefault ? pc.green('●') : ' ',
1872
+ row.isDefault ? pc.bold(row.id) : row.id,
1873
+ row.title
1874
+ ])
1875
+ )
1876
+ )
1877
+ console.log(
1878
+ '\n' + pc.dim(' Focus one: moi tab focus <tab-id> [--params \'{"k":"v"}\']') + '\n'
1879
+ )
1880
+ })
1881
+ }
1882
+
1883
+ const tabFocus = defineCommand({
1884
+ meta: { name: 'focus', description: 'Focus a workspace tab in every open client' },
1885
+ args: {
1886
+ tab: {
1887
+ type: 'positional',
1888
+ required: true,
1889
+ description: 'Tab id from `moi tabs`, e.g. view:orders'
1890
+ },
1891
+ params: {
1892
+ type: 'string',
1893
+ description: 'One JSON object delivered to the view as its params, e.g. \'{"order":"o-1"}\''
1894
+ },
1895
+ dir: dirArg
1896
+ },
1897
+ run({ args }) {
1898
+ const path = resolve(args.dir)
1899
+ let params: Record<string, unknown> | undefined
1900
+ if (args.params !== undefined) {
1901
+ try {
1902
+ const parsed: unknown = JSON.parse(args.params)
1903
+ if (!isParamsRecord(parsed)) throw new Error('not a JSON object')
1904
+ params = parsed
1905
+ } catch {
1906
+ console.error(
1907
+ '\n' + pc.red('✗') + ' --params must be one JSON object, e.g. \'{"order":"o-1"}\'\n'
1908
+ )
1909
+ process.exit(1)
1910
+ }
1911
+ }
1912
+ sendControl(
1913
+ path,
1914
+ { type: 'tab:focus', path, tab: args.tab, ...(params ? { params } : {}) },
1915
+ res => {
1916
+ console.log('\n' + pc.green('✓') + ' Focused ' + pc.bold(String(res.tab)) + '\n')
1917
+ }
1918
+ )
1919
+ }
1920
+ })
1921
+
1922
+ const tabSubCommands = { focus: tabFocus }
1923
+
1924
+ const tab = defineCommand({
1925
+ meta: { name: 'tab', description: 'List workspace tabs, or focus one: `moi tab focus <tab-id>`' },
1926
+ subCommands: tabSubCommands,
1927
+ args: { dir: dirArg },
1928
+ run({ args, rawArgs }) {
1929
+ // citty invokes the parent run even after dispatching a subcommand — only
1930
+ // list when none ran (same pattern as `moi env` / `moi skill`).
1931
+ const sub = rawArgs.find(a => !a.startsWith('-'))
1932
+ if (sub && Object.hasOwn(tabSubCommands, sub)) return
1933
+ runTabsList(args.dir)
1934
+ }
1935
+ })
1936
+
1937
+ const tabs = defineCommand({
1938
+ meta: { name: 'tabs', description: 'List workspace tabs (alias for `moi tab`)' },
1939
+ args: { dir: dirArg },
1940
+ run({ args }) {
1941
+ runTabsList(args.dir)
1942
+ }
1943
+ })
1944
+
1832
1945
  // Re-copy bundled skills into a workspace, then report what changed. Pure
1833
1946
  // filesystem op — no running server needed. Resolves the workspace root the
1834
1947
  // same way `moi bundle` does, so it works from `.moi/` or any subdirectory.
@@ -1836,11 +1949,23 @@ async function runSkillUpdate(cwd: string): Promise<void> {
1836
1949
  // Type-aware: an OpenClaw workspace keeps its skills in `skills/`, so the
1837
1950
  // update must target the same dir the agent actually loads from.
1838
1951
  const { root, type } = await resolveWorkspace(cwd)
1839
- const before = await skillStatuses(root, type)
1840
- await installBundledSkills(skillsDirFor(root, type))
1841
- const after = await skillStatuses(root, type)
1952
+ const { before, status, appletTypesWritten } = await updateWorkspaceSkills(
1953
+ root,
1954
+ type ?? 'claude-code'
1955
+ )
1956
+ const after = status.skills
1842
1957
 
1843
1958
  console.log('\n' + pc.green('✓') + ' Skills updated in ' + pc.bold(root) + '\n')
1959
+ printSkillUpdateTable(before, after)
1960
+ if (appletTypesWritten) {
1961
+ console.log(pc.dim(' Ambient applet types regenerated: ') + pc.bold('.moi/applet-env.d.ts\n'))
1962
+ }
1963
+ }
1964
+
1965
+ function printSkillUpdateTable(
1966
+ before: WorkspaceSkillStatus[],
1967
+ after: WorkspaceSkillStatus[]
1968
+ ): void {
1844
1969
  console.log(
1845
1970
  columns(
1846
1971
  ['skill', 'from', 'to'].map(h => pc.dim(h)),
@@ -1866,7 +1991,7 @@ async function runSkillUpdate(cwd: string): Promise<void> {
1866
1991
 
1867
1992
  // Colored status label for one skill row: minor+ behind is actionable, a patch
1868
1993
  // gap is informational, otherwise current.
1869
- function skillState(s: SkillStatus): string {
1994
+ function skillState(s: WorkspaceSkillStatus): string {
1870
1995
  if (isMinorBehind(s.installed, s.bundled)) return pc.yellow('update available')
1871
1996
  if (isBehind(s.installed, s.bundled)) return pc.dim('patch behind')
1872
1997
  return pc.green('up to date')
@@ -1969,6 +2094,8 @@ const main = defineCommand({
1969
2094
  openclaw,
1970
2095
  scratch,
1971
2096
  skill,
2097
+ tab,
2098
+ tabs,
1972
2099
  version
1973
2100
  }
1974
2101
  })
package/server/control.ts CHANGED
@@ -2,6 +2,7 @@ import { stringify as devalueStringify } from 'devalue'
2
2
  import { resolve } from 'path'
3
3
 
4
4
  import type { WorkspaceEntry } from '@/lib/types'
5
+ import { isParamsRecord } from '@/lib/workspace-tabs'
5
6
 
6
7
  import { clearAppletLog, getAppletLog, getAppletLogCount } from './applet-log'
7
8
  import { serializeWorkspaceBundle } from './bundle-queue'
@@ -16,6 +17,7 @@ import { executeScratchOp } from './scratchpad-executor'
16
17
  import { readScratchpadImage, readScratchpadShapes } from './scratchpad'
17
18
  import { relayScratchOp } from './scratchpad-relay'
18
19
  import { broadcastAll } from './state'
20
+ import { assembleTabRows, resolveFocusTab } from './tabs'
19
21
  import { applyThemeUpdate, matchColorTheme } from './theme'
20
22
  import { handleBundle } from './widgets'
21
23
  import { getViewList, handleBundleViews, hasViewId } from './views'
@@ -263,12 +265,56 @@ export const control = Bun.serve({
263
265
  return
264
266
  }
265
267
 
266
- if (data.type === 'widget:refresh') {
267
- // Tell every connected widget to re-import its module (cache-bust)
268
- // and re-run its data fetches. No rebuild, no page reload — the
269
- // existing `useWidget` hook handles `widgets:refresh` identically
270
- // to `widget:updated` (load with bust=true).
271
- publishEvent({ type: 'widgets:refresh' })
268
+ // The workspace tab listing — `moi tabs` (and bare `moi tab`).
269
+ if (data.type === 'tabs') {
270
+ const match = await resolveWorkspace(ws, data.path)
271
+ if (!match) return
272
+ const [layout, views] = await Promise.all([
273
+ loadLayout(match.path),
274
+ getViewList(match.path)
275
+ ])
276
+ ws.send(JSON.stringify({ ok: true, tabs: assembleTabRows(views, layout.tabs.active) }))
277
+ return
278
+ }
279
+
280
+ // `moi tab focus <tab-id>` — validate the target, then publish a
281
+ // workspace-scoped `tab:focus` event. Every connected client of that
282
+ // workspace navigates (replace) with the params in navigation state.
283
+ if (data.type === 'tab:focus') {
284
+ const match = await resolveWorkspace(ws, data.path)
285
+ if (!match) return
286
+ const resolved = await resolveFocusTab(data.tab, {
287
+ hasView: viewId => hasViewId(match.path, viewId),
288
+ viewList: () => getViewList(match.path)
289
+ })
290
+ if (!resolved.ok) {
291
+ ws.send(JSON.stringify({ error: resolved.error }))
292
+ return
293
+ }
294
+ // The CLI already validated --params as one JSON object; re-check the
295
+ // shape here so a hand-rolled control client can't publish garbage.
296
+ if (data.params !== undefined && !isParamsRecord(data.params)) {
297
+ ws.send(JSON.stringify({ error: 'Params must be one JSON object' }))
298
+ return
299
+ }
300
+ publishEvent({
301
+ type: 'tab:focus',
302
+ workspaceId: match.id,
303
+ tab: resolved.tab,
304
+ ...(data.params !== undefined ? { params: data.params } : {})
305
+ })
306
+ ws.send(JSON.stringify({ ok: true, tab: resolved.tab }))
307
+ return
308
+ }
309
+
310
+ // Tell every connected applet to re-import its module (cache-bust) and
311
+ // re-run its data fetches. No rebuild, no page reload — `useApplet`
312
+ // handles `applets:refresh` like `*:updated` (invalidate + reload).
313
+ // `only` narrows to one kind; default is both widgets and views.
314
+ // `widget:refresh` is the pre-filter message name older CLIs send.
315
+ if (data.type === 'applets:refresh' || data.type === 'widget:refresh') {
316
+ const only = data.only === 'widgets' || data.only === 'views' ? data.only : undefined
317
+ publishEvent({ type: 'applets:refresh', only })
272
318
  ws.send(JSON.stringify({ ok: true }))
273
319
  return
274
320
  }
@@ -295,7 +341,7 @@ export const control = Bun.serve({
295
341
  ws.send(
296
342
  JSON.stringify({
297
343
  currentFont: layout.theme?.font ?? 'default',
298
- currentColor: matchColorTheme(layout.theme?.background, layout.theme?.foreground)
344
+ currentColor: matchColorTheme(layout.theme?.primary)
299
345
  })
300
346
  )
301
347
  return
@@ -1,5 +1,5 @@
1
1
  // Single source of truth for the OS data dir holding moi's global state
2
- // (workspaces.json, thread-config.json, workspace-env.json, …).
2
+ // (workspaces.json, settings.json, thread-config.json, workspace-env.json, …).
3
3
  //
4
4
  // MOI_DATA_DIR overrides it wholesale. This is the isolation seam for CLI
5
5
  // e2e tests: env-paths only honors XDG_DATA_HOME on Linux, so on macOS a
package/server/events.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  // Live-event channel: server → browser push over the `/api/workspaces/ws`
2
2
  // socket. Bundles, the control server, and the REST API publish build/refresh/
3
- // identity events (`widgets:refresh`, `theme:updated`, `workspace:updated`, …)
3
+ // identity events (`applets:refresh`, `theme:updated`, `workspace:updated`, …)
4
4
  // here; every subscribed browser receives them. This is not a transport of its
5
5
  // own — it rides the Bun WebSocket pub/sub already open for that route.
6
6
  //
@@ -67,7 +67,8 @@ async function evictModule(name: string) {
67
67
 
68
68
  type CallMessage = { id: string; type: 'call'; module: string; name: string; args: string }
69
69
  type ReloadMessage = { type: 'reload'; modules: string[] }
70
- type IncomingMessage = CallMessage | ReloadMessage
70
+ type ShutdownMessage = { type: 'shutdown' }
71
+ type IncomingMessage = CallMessage | ReloadMessage | ShutdownMessage
71
72
 
72
73
  process.on('message', async (raw: IncomingMessage) => {
73
74
  if (raw.type === 'reload') {
@@ -77,6 +78,19 @@ process.on('message', async (raw: IncomingMessage) => {
77
78
  return
78
79
  }
79
80
 
81
+ // Graceful exit. The parent kills this process to pick up edited server code
82
+ // — evicting from moduleCache isn't enough, because a module's own imports
83
+ // are pinned in Bun's ESM registry with no way to invalidate them (the
84
+ // `?t=` buster below only busts the .server.ts itself, one level deep). Run
85
+ // every cached module's `dispose()` first so a hard kill doesn't strand a db
86
+ // handle or timer; the parent hard-kills us if we take too long.
87
+ if (raw.type === 'shutdown') {
88
+ for (const name of [...moduleCache.keys()]) {
89
+ await evictModule(name)
90
+ }
91
+ process.exit(0)
92
+ }
93
+
80
94
  if (raw.type === 'call') {
81
95
  const { id, module: moduleName, name, args } = raw
82
96
 
@@ -68,6 +68,41 @@ function killSlot(slot: Slot, reason: string) {
68
68
  } catch {}
69
69
  }
70
70
 
71
+ // How long a worker gets to run its modules' `dispose()` and exit on its own
72
+ // before we kill it outright.
73
+ const SHUTDOWN_GRACE_MS = 2_000
74
+
75
+ // Same end state as killSlot — a dead worker — but the worker is asked to exit
76
+ // so it can run each cached module's `dispose()` first. Used when server code
77
+ // changed: a hard kill would strand whatever those modules hold open (db
78
+ // handles, timers, watchers).
79
+ //
80
+ // The slot is marked killed immediately, so a call arriving mid-shutdown spawns
81
+ // a fresh worker rather than queueing behind a dying one. In-flight calls are
82
+ // rejected rather than left to hit the 30s timeout.
83
+ function gracefulKillSlot(slot: Slot, reason: string) {
84
+ if (slot.killed) return
85
+ slot.killed = true
86
+ rejectAndClearPending(slot, reason)
87
+
88
+ const timer = setTimeout(() => {
89
+ try {
90
+ slot.worker.kill()
91
+ } catch {}
92
+ }, SHUTDOWN_GRACE_MS)
93
+ timer.unref?.()
94
+ void slot.worker.exited.then(() => clearTimeout(timer)).catch(() => clearTimeout(timer))
95
+
96
+ try {
97
+ slot.worker.send({ type: 'shutdown' })
98
+ } catch {
99
+ clearTimeout(timer)
100
+ try {
101
+ slot.worker.kill()
102
+ } catch {}
103
+ }
104
+ }
105
+
71
106
  const slots = new LRUCache<string, Slot>({
72
107
  max: MAX_WORKERS,
73
108
  ttl: WORKER_IDLE_TTL_MS,
@@ -331,16 +366,26 @@ export function getWorkersDebugSnapshot(): WorkerDebugInfo[] {
331
366
  return out
332
367
  }
333
368
 
369
+ // Make edited server code take effect: recycle the workspace's worker so the
370
+ // next call loads it fresh.
371
+ //
372
+ // This RECYCLES THE WHOLE WORKER rather than evicting the named modules,
373
+ // because eviction cannot actually reload edited code. `loadModule` busts its
374
+ // import with `?t=<mtime>`, which only makes a new URL for the `.server.ts`
375
+ // itself — everything that file imports stays pinned in Bun's ESM registry
376
+ // with no API to invalidate it. So a module whose *dependency* changed re-
377
+ // executes against the old dependency, and one whose own mtime is unchanged
378
+ // doesn't re-execute at all. A fresh process is the only reliable reset.
379
+ //
380
+ // `modules` is the reason, not the scope: every module in the worker is
381
+ // dropped. Kept in the signature for the kill reason surfaced to callers.
334
382
  export function reloadModules(modules: string[], workspacePath: string) {
335
383
  if (modules.length === 0) return
336
384
  // peek: don't refresh TTL just because files changed. If the worker was
337
385
  // already idle-evicted, the next callFunction will re-spawn fresh anyway.
338
386
  const slot = slots.peek(workspacePath)
339
387
  if (!slot || slot.killed) return
340
- try {
341
- slot.worker.send({ type: 'reload', modules })
342
- // The worker evicts these from its module cache; it re-reports 'loaded'
343
- // on the next call, so drop them from the introspection set too.
344
- for (const m of modules) slot.modules.delete(m)
345
- } catch {}
388
+ // No need to prune `slot.modules`: the whole slot is going away, and
389
+ // getStatus already skips killed slots.
390
+ gracefulKillSlot(slot, `Server code changed (${modules.join(', ')})`)
346
391
  }
@@ -5,7 +5,7 @@ import { join } from 'node:path'
5
5
  import type { McpServer } from '@/lib/types'
6
6
 
7
7
  import type { DiscoveredWorkspaceCandidate, Harness } from '../types'
8
- import { pathHarnessAvailability } from '../executable'
8
+ import { findHarnessExecutable, pathHarnessAvailability } from '../executable'
9
9
  import { isLinkedGitWorktree } from './git-worktree'
10
10
  import { getMcpStatus } from './mcp'
11
11
  import { getClaudeModels } from './models'
@@ -100,6 +100,7 @@ export const claudeCodeHarness: Harness = {
100
100
  const cc = getCCDebugSnapshot()
101
101
  const busy = cc.sessions.filter(s => s.activity !== 'idle').length
102
102
  const lines = [
103
+ `claude executable ${findHarnessExecutable('claude-code') ?? '(not found)'}`,
103
104
  `live CC sessions ${cc.sessions.length}/${SESSION_LIMITS.maxLive} ` +
104
105
  `(${busy} busy, ${cc.sessions.length - busy} idle, ${cc.aliases} alias${cc.aliases === 1 ? '' : 'es'}, ` +
105
106
  `idle TTL ${fmtDuration(SESSION_LIMITS.idleTtlMs)})`
@@ -8,7 +8,15 @@
8
8
  //
9
9
  // Type shapes are hand-written against `codex app-server generate-ts`
10
10
  // (CLI 0.144.5) and read defensively — see ./NOTES.md.
11
- import type { Part, StreamEvent, SystemNotice, ToolCall, ToolState, Turn } from '@/lib/format'
11
+ import type {
12
+ Part,
13
+ StreamEvent,
14
+ SubagentRecord,
15
+ SystemNotice,
16
+ ToolCall,
17
+ ToolState,
18
+ Turn
19
+ } from '@/lib/format'
12
20
  import { stripMoiContext, stripMoiContextLoose } from '@/lib/moi-context'
13
21
  import type { Model, SessionInfo } from '@/lib/types'
14
22
 
@@ -76,6 +84,7 @@ export type CodexTurn = {
76
84
  items: CodexThreadItem[]
77
85
  status: string
78
86
  error?: { message?: string; codexErrorInfo?: unknown } | null
87
+ durationMs?: number | null
79
88
  }
80
89
 
81
90
  export type CodexThread = {
@@ -85,6 +94,7 @@ export type CodexThread = {
85
94
  createdAt?: number
86
95
  updatedAt?: number
87
96
  name?: string | null
97
+ status?: { type?: string }
88
98
  turns?: CodexTurn[]
89
99
  }
90
100
 
@@ -309,12 +319,15 @@ function itemToToolCall(item: CodexThreadItem): ToolCall | null {
309
319
  input: { plan: item.text }
310
320
  }
311
321
  }
312
- // Codex multi-agent: the parent's collab tool invocations (spawn / send /
313
- // wait / close). The child agent runs as its OWN thread whose items
314
- // stream on the same connection under `agentThreadId` — nesting that
315
- // transcript into a SubagentRecord is future work; for now the card makes
316
- // the spawn/wait visible instead of silently dropping it.
322
+ // Codex multi-agent: the parent's collab tool invocations (`spawn_agent`,
323
+ // `send_input`, `resume_agent`, `wait`, `close_agent`). The child agent
324
+ // runs as its OWN thread whose items stream on the same connection under
325
+ // `agentThreadId`; its transcript nests into the `subAgentActivity` card
326
+ // (see session.ts), so this card only narrates the parent's side.
317
327
  case 'collabAgentToolCall': {
328
+ // `wait` is the parent idling on its children — protocol noise next to
329
+ // the activity card that already shows the child running. Drop it.
330
+ if (item.tool === 'wait') return null
318
331
  return {
319
332
  toolCallId: item.id,
320
333
  name: 'subagent',
@@ -412,7 +425,9 @@ export function codexItemToTurn(item: CodexThreadItem, threadId: string): Turn |
412
425
  }
413
426
  }
414
427
  if (item.type === 'reasoning') {
415
- const text = (item.summary ?? []).filter(Boolean).join('\n\n')
428
+ // Single newline between summary sections — must match the live preview
429
+ // separator (session.ts summaryPartAdded) or the text reflows on land.
430
+ const text = (item.summary ?? []).filter(Boolean).join('\n')
416
431
  if (!text) return null
417
432
  return {
418
433
  id: turnId,
@@ -441,14 +456,90 @@ export function codexItemToNotice(item: CodexThreadItem, threadId: string): Syst
441
456
  }
442
457
  }
443
458
 
459
+ // A child agent thread rebuilt from replay: the parent card carrying the
460
+ // nested transcript plus the record itself (same shape session.ts keeps live).
461
+ export type SubagentReplay = { toolCallId: string; record: SubagentRecord }
462
+
463
+ // The parent's `subAgentActivity` items, one per child thread (the last item
464
+ // wins so `kind` reflects the child's final state).
465
+ export function collectSubagentActivities(thread: CodexThread): CodexThreadItem[] {
466
+ const byChild = new Map<string, CodexThreadItem>()
467
+ for (const turn of thread.turns ?? []) {
468
+ for (const item of turn.items ?? []) {
469
+ if (item.type === 'subAgentActivity' && item.agentThreadId)
470
+ byChild.set(item.agentThreadId, item)
471
+ }
472
+ }
473
+ return [...byChild.values()]
474
+ }
475
+
476
+ // Rebuild a SubagentRecord from the child thread's own replay payload.
477
+ // Children are forks of the parent, so their replay inherits the parent's
478
+ // turns verbatim (same turn ids) — exclude those. Also drop `subAgentActivity`
479
+ // echoes (the child's send-back to the parent) which would render as cryptic
480
+ // nested agent cards.
481
+ export function childThreadToSubagentRecord(
482
+ child: CodexThread,
483
+ activity: CodexThreadItem,
484
+ parentTurnIds: Set<string>
485
+ ): SubagentRecord {
486
+ const transcript: Turn[] = []
487
+ let durationMs = 0
488
+ let toolUses = 0
489
+ for (const turn of child.turns ?? []) {
490
+ if (parentTurnIds.has(turn.id)) continue
491
+ if (typeof turn.durationMs === 'number') durationMs += turn.durationMs
492
+ for (const item of turn.items ?? []) {
493
+ if (item.type === 'subAgentActivity') continue
494
+ const t = codexItemToTurn(item, child.id)
495
+ if (!t) continue
496
+ if (t.parts.some(p => p.type === 'tool-call')) toolUses++
497
+ transcript.push(t)
498
+ }
499
+ }
500
+ const status =
501
+ activity.kind === 'failed'
502
+ ? ('failed' as const)
503
+ : child.status?.type === 'active'
504
+ ? ('running' as const)
505
+ : ('completed' as const)
506
+ return {
507
+ taskId: child.id,
508
+ description: activity.agentPath?.split('/').pop() || 'sub-agent',
509
+ progress: [],
510
+ status,
511
+ // Zero counts stay out: codex's child replay drops commandExecution
512
+ // items, and a "Took 0 steps" subline reads as broken.
513
+ ...(durationMs || toolUses
514
+ ? {
515
+ usage: {
516
+ ...(durationMs ? { durationMs } : {}),
517
+ ...(toolUses ? { toolUses } : {})
518
+ }
519
+ }
520
+ : {}),
521
+ transcript
522
+ }
523
+ }
524
+
444
525
  // Static replay path: map a `thread/read`/`thread/resume` payload (turns
445
- // included) onto StreamEvents for the REST events endpoint.
446
- export function codexThreadToEvents(thread: CodexThread): StreamEvent[] {
526
+ // included) onto StreamEvents for the REST events endpoint. `subagents`
527
+ // (child thread id → replay record) re-attaches nested transcripts to their
528
+ // `subAgentActivity` cards.
529
+ export function codexThreadToEvents(
530
+ thread: CodexThread,
531
+ subagents?: Map<string, SubagentReplay>
532
+ ): StreamEvent[] {
447
533
  const events: StreamEvent[] = []
448
534
  for (const turn of thread.turns ?? []) {
449
535
  for (const item of turn.items ?? []) {
450
536
  const t = codexItemToTurn(item, thread.id)
451
537
  if (t) {
538
+ if (item.type === 'subAgentActivity' && item.agentThreadId) {
539
+ const sub = subagents?.get(item.agentThreadId)
540
+ const part = t.parts.find(p => p.type === 'tool-call')
541
+ if (sub && part?.type === 'tool-call') part.call.subagent = sub.record
542
+ }
452
543
  events.push({ kind: 'turn', turn: t })
453
544
  continue
454
545
  }