moi-computer 0.8.0 → 0.9.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 (110) hide show
  1. package/client/api/workspace-keys.ts +1 -2
  2. package/client/app/AppRouter.tsx +10 -3
  3. package/client/app/routes/HomeRoute.tsx +1 -1
  4. package/client/app/shell/SidebarLayout.tsx +2 -14
  5. package/client/components/shared/Composer.tsx +20 -7
  6. package/client/components/shared/PanelHeader.tsx +8 -1
  7. package/client/components/ui/button.tsx +3 -3
  8. package/client/components/ui/dialog.tsx +1 -1
  9. package/client/components/ui/dropdown-menu.tsx +2 -2
  10. package/client/components/ui/hover-card.tsx +1 -1
  11. package/client/components/ui/popover.tsx +1 -1
  12. package/client/components/ui/resizable.tsx +40 -0
  13. package/client/features/chat/ChatEmptyState.tsx +9 -11
  14. package/client/features/chat/ChatPanel.tsx +76 -48
  15. package/client/features/chat/ChatPopup.tsx +16 -2
  16. package/client/features/chat/ChatPromptBubbles.tsx +6 -8
  17. package/client/features/chat/ChatSelector.tsx +24 -7
  18. package/client/features/chat/MarkdownContent.tsx +1 -1
  19. package/client/features/chat/ModelPicker.tsx +5 -4
  20. package/client/features/chat/TurnView.tsx +108 -13
  21. package/client/features/chat/api.ts +1 -18
  22. package/client/features/chat/chat-send.ts +2 -2
  23. package/client/features/chat/{ChatComposer.tsx → composer/ChatComposer.tsx} +6 -5
  24. package/client/features/chat/composer/banners/ChatErrorBanner.tsx +28 -0
  25. package/client/features/chat/composer/banners/ComposerBanner.tsx +30 -0
  26. package/client/features/chat/composer/banners/WorkspaceAgentAvailabilityBanner.tsx +91 -0
  27. package/client/features/{workspace → chat/composer/banners}/WorkspaceSkillUpdateBanner.tsx +9 -7
  28. package/client/features/chat/composer/useWorkspaceComposerState.tsx +74 -0
  29. package/client/features/{workspace → chat/composer}/useWorkspaceSkillUpdates.ts +1 -1
  30. package/client/features/chat/group-turns.ts +46 -28
  31. package/client/features/chat/interleave-notices.ts +84 -0
  32. package/client/features/chat/model-order.ts +9 -3
  33. package/client/features/chat/tool-group/TimelineRow.tsx +23 -11
  34. package/client/features/chat/tool-group/ToolCallGroup.tsx +38 -3
  35. package/client/features/chat/tool-group/format.ts +51 -10
  36. package/client/features/chat/useAppletChatMessage.ts +11 -16
  37. package/client/features/chat/useChat.ts +3 -7
  38. package/client/features/dev/ChatStatesPage.tsx +466 -0
  39. package/client/features/dev/DevIndexPage.tsx +52 -0
  40. package/client/features/dev/DevRoutes.tsx +6 -3
  41. package/client/features/dev/HarnessDebugPage.tsx +3 -3
  42. package/client/features/dev/chat-states-fixtures.ts +744 -0
  43. package/client/features/scratchpad/Scratchpad.tsx +4 -0
  44. package/client/features/scratchpad/scratch-session.ts +71 -0
  45. package/client/features/views/ViewBuilderTab.tsx +5 -4
  46. package/client/features/views/useViewBuilderActions.ts +2 -2
  47. package/client/features/workspace/WorkspaceLayoutContext.tsx +4 -2
  48. package/client/features/workspace/WorkspaceScreen.tsx +128 -146
  49. package/client/features/workspace/WorkspaceSplitLayout.tsx +111 -0
  50. package/client/features/workspace/api.ts +33 -8
  51. package/client/features/workspace/useFitsSplitLayout.ts +31 -5
  52. package/client/index.css +1 -1
  53. package/client/lib/flags.ts +4 -3
  54. package/client/runtime/useWorkspaceEvents.ts +18 -1
  55. package/client/store/ui.ts +5 -1
  56. package/dist/{chunk-0pcdwjkp.js → chunk-2vaafjp4.js} +1 -1
  57. package/dist/{chunk-9y2zbzqz.js → chunk-35fq49qa.js} +1 -1
  58. package/dist/{chunk-h9h8f176.js → chunk-3b3rkjet.js} +1 -1
  59. package/dist/chunk-gt7n06ef.js +1 -0
  60. package/dist/{chunk-r5ce5cdg.js → chunk-kkj86722.js} +75 -75
  61. package/dist/chunk-ty1sqbmn.js +80 -0
  62. package/dist/chunk-xeyxk7ep.js +10 -0
  63. package/dist/chunk-yz6wd5vc.css +1 -0
  64. package/dist/index.html +1 -1
  65. package/lib/format.ts +37 -7
  66. package/lib/themes.ts +2 -2
  67. package/lib/types.ts +38 -8
  68. package/lib/workspace-layout.ts +2 -2
  69. package/package.json +6 -4
  70. package/server/agent.ts +199 -0
  71. package/server/api.ts +36 -17
  72. package/server/bundler/build-applet.ts +35 -44
  73. package/server/cli-env.ts +2 -2
  74. package/server/cli.ts +39 -53
  75. package/server/constants.ts +8 -0
  76. package/server/control-client.ts +124 -0
  77. package/server/control.ts +2 -2
  78. package/server/env-apply.ts +4 -0
  79. package/server/harness/README.md +32 -12
  80. package/server/harness/claude-code/auth.ts +54 -0
  81. package/server/harness/claude-code/index.ts +6 -1
  82. package/server/harness/codex/adapter.ts +9 -1
  83. package/server/harness/codex/auth.ts +50 -0
  84. package/server/harness/codex/index.ts +6 -1
  85. package/server/harness/codex/session.ts +33 -14
  86. package/server/harness/openclaw/NOTES.md +619 -186
  87. package/server/harness/openclaw/adapter.ts +121 -54
  88. package/server/harness/openclaw/compat.ts +95 -0
  89. package/server/harness/openclaw/cron-view.ts +78 -0
  90. package/server/harness/openclaw/discovery.ts +145 -52
  91. package/server/harness/openclaw/gateway.ts +224 -36
  92. package/server/harness/openclaw/index.ts +56 -21
  93. package/server/harness/openclaw/session.ts +1002 -67
  94. package/server/harness/openclaw/strip.ts +71 -23
  95. package/server/harness/openclaw/thinking.ts +150 -0
  96. package/server/harness/types.ts +10 -5
  97. package/server/layout.ts +5 -2
  98. package/server/service.ts +2 -2
  99. package/workspace/.claude/skills/moi-workspace/SKILL.md +6 -6
  100. package/workspace/.claude/skills/moi-workspace/{DESIGN.md → references/DESIGN.md} +19 -9
  101. package/client/features/dev/PixelPainter.tsx +0 -94
  102. package/client/features/dev/PlaygroundPage.tsx +0 -69
  103. package/dist/chunk-0k7brsms.js +0 -9
  104. package/dist/chunk-dfs36zgc.js +0 -1
  105. package/dist/chunk-dtwxpxbg.js +0 -51
  106. package/dist/chunk-ga7t9qsk.js +0 -2
  107. package/dist/chunk-tey2nq7c.js +0 -31
  108. package/dist/chunk-z73xpsa0.js +0 -50
  109. package/dist/chunk-zzgredta.css +0 -1
  110. /package/workspace/.claude/skills/moi-workspace/{SCRATCHPAD.md → references/SCRATCHPAD.md} +0 -0
package/lib/format.ts CHANGED
@@ -51,7 +51,17 @@ export type Citation = { url?: string; title?: string; quote?: string }
51
51
 
52
52
  export type Part =
53
53
  | { type: 'text'; text: string; citations?: Citation[] }
54
- | { type: 'reasoning'; text: string; redacted?: boolean; signature?: string }
54
+ // `redacted` marks reasoning the backend acknowledges but won't hand over:
55
+ // Anthropic's `redacted_thinking`, and the codex app-server's `Reasoning`
56
+ // item, which reports that the model thought (and for how long) but carries
57
+ // no text. Such a part has empty `text` and renders as a duration, not a body.
58
+ | {
59
+ type: 'reasoning'
60
+ text: string
61
+ redacted?: boolean
62
+ signature?: string
63
+ durationMs?: number
64
+ }
55
65
  | { type: 'tool-call'; call: ToolCall }
56
66
  | { type: 'file'; mediaType: string; url: string; filename?: string }
57
67
  | { type: 'source-url'; url: string; title?: string; sourceId: string }
@@ -87,6 +97,9 @@ export type TurnMeta = {
87
97
  model?: string
88
98
  provider?: string
89
99
  stopReason?: string
100
+ // Agent-run duration. Derived from transcript timestamps when available;
101
+ // Codex supplies its native duration because its transcript items lack them.
102
+ durationMs?: number
90
103
  usage?: { inputTokens?: number; outputTokens?: number; totalTokens?: number; costUsd?: number }
91
104
  // The API message id (`msg_...`) that produced this assistant turn, when the
92
105
  // backend reports one. NOT the Turn `id`. Used to reconcile a live streaming
@@ -102,9 +115,11 @@ export type Turn = {
102
115
  parentTaskId?: string
103
116
  parts: Part[]
104
117
  timestamp?: string
105
- // Stable monotonic ordering hint when the source provides one (OpenClaw's
106
- // `__openclaw.seq`). Used as a tiebreaker when timestamps collide; the UI
107
- // is free to ignore it.
118
+ // The backend's own transcript position, when it reports one (OpenClaw's
119
+ // `__openclaw.seq`). `applyEvent` places a new seq-bearing turn by this
120
+ // value rather than by arrival, so a row that reaches us late still renders
121
+ // in transcript order. Backends that don't report a position omit it and
122
+ // keep plain append semantics.
108
123
  seq?: number
109
124
  meta?: TurnMeta
110
125
  }
@@ -143,6 +158,9 @@ export type SystemNotice =
143
158
  error?: string
144
159
  }
145
160
  | { id: string; kind: 'compact'; at: string; metadata?: unknown }
161
+ // Mid-session model switch observed on the backend (e.g. OpenClaw
162
+ // `sessions.patch { model }` — from moi's picker or any other client).
163
+ | { id: string; kind: 'model-change'; at: string; model: string; prev?: string }
146
164
  | {
147
165
  id: string
148
166
  kind: 'hook'
@@ -235,9 +253,21 @@ export function applyEvent(state: ViewState, ev: StreamEvent): ViewState {
235
253
  return { ...state, snapshot: ev.snapshot }
236
254
  case 'turn': {
237
255
  const idx = state.turns.findIndex(t => t.id === ev.turn.id)
238
- const turns =
239
- idx >= 0 ? state.turns.map((t, i) => (i === idx ? ev.turn : t)) : [...state.turns, ev.turn]
240
- return { ...state, turns }
256
+ // Known turn: replace in place. Its position was decided when it first
257
+ // landed and must not move under the reader mid-run.
258
+ if (idx >= 0) {
259
+ return { ...state, turns: state.turns.map((t, i) => (i === idx ? ev.turn : t)) }
260
+ }
261
+ // New turn: arrival order is the default, but a backend that reports a
262
+ // transcript position (`seq`) gets placed by it, so a row that arrives
263
+ // late — reconciled after a dropped frame, or replayed after a
264
+ // reconnect — lands where the transcript says it belongs instead of at
265
+ // the end. Only seq-bearing turns are reordered against each other;
266
+ // turns without one keep pure append semantics.
267
+ if (ev.turn.seq === undefined) return { ...state, turns: [...state.turns, ev.turn] }
268
+ const at = state.turns.findIndex(t => t.seq !== undefined && t.seq > ev.turn.seq!)
269
+ if (at < 0) return { ...state, turns: [...state.turns, ev.turn] }
270
+ return { ...state, turns: [...state.turns.slice(0, at), ev.turn, ...state.turns.slice(at)] }
241
271
  }
242
272
  case 'notice': {
243
273
  if (state.notices.some(n => n.id === ev.notice.id)) {
package/lib/themes.ts CHANGED
@@ -106,7 +106,7 @@ const THEME_COLOR_DERIVATIONS = {
106
106
  primaryForeground: primary => foregroundForPrimary(primary),
107
107
  background: () => 'color-mix(var(--primary) 3%, oklch(1 0 0) 97%)',
108
108
  foreground: () => 'color-mix(var(--primary) 20%, oklch(0 0 0) 80%)',
109
- muted: () => 'color-mix(var(--background) 95%, var(--foreground) 5%)',
109
+ muted: () => 'color-mix(var(--background) 96%, var(--foreground) 4%)',
110
110
  mutedForeground: () => 'color-mix(var(--background) 50%, var(--foreground) 50%)',
111
111
  accent: () => 'color-mix(var(--primary) 4%, var(--foreground) 4%)',
112
112
  accentForeground: () => 'var(--foreground)',
@@ -117,7 +117,7 @@ const THEME_COLOR_DERIVATIONS = {
117
117
  foreground: primary => foregroundForPrimary(primary),
118
118
  primary: () => 'color-mix(var(--background) 3%, oklch(1 0 0) 97%)',
119
119
  primaryForeground: () => 'color-mix(var(--background) 20%, oklch(0 0 0) 80%)',
120
- muted: () => 'color-mix(var(--background) 95%, var(--foreground) 5%)',
120
+ muted: () => 'color-mix(var(--background) 97%, var(--foreground) 3%)',
121
121
  mutedForeground: () => 'color-mix(var(--background) 50%, var(--foreground) 50%)',
122
122
  accent: () => 'color-mix(var(--primary) 4%, var(--foreground) 4%)',
123
123
  accentForeground: () => 'var(--foreground)',
package/lib/types.ts CHANGED
@@ -256,6 +256,12 @@ export type SessionInfo = {
256
256
  summary: string
257
257
  lastModified: number
258
258
  cwd?: string
259
+ // Where the conversation originates when the backend routes external
260
+ // channels into it (OpenClaw: telegram/irc/discord/…; absent = app chat).
261
+ origin?: { provider: string; label?: string }
262
+ // Session flavor beyond a plain chat: scheduled cron runs and spawned
263
+ // subagent sessions get a badge in the chat selector.
264
+ flavor?: 'chat' | 'cron' | 'subagent'
259
265
  }
260
266
 
261
267
  // Per-session agent settings, persisted server-side in one global file in moi's
@@ -392,11 +398,22 @@ export type WorkspaceSkillsUpdateFailure = WorkspaceSkillsStatus & {
392
398
  error: string
393
399
  }
394
400
 
395
- // Whether an agent backend's runtime is installed on this machine. `reason` is
396
- // user-facing copy explaining what to do next. Surfaced by
397
- // GET /api/workspaces/create (per-type map, drives setup dialogs) and
398
- // GET /api/workspaces/:id/availability (disables Send in existing workspaces).
399
- export type HarnessAvailability = { available: true } | { available: false; reason: string }
401
+ // Setup checks only runtime availability. Workspace checks may also attach a
402
+ // login command, which makes the composer show its Sign in action.
403
+ export type HarnessAvailability =
404
+ | { available: true }
405
+ | { available: false; reason: string; loginCommand?: string }
406
+
407
+ // Codex returns a URL for the browser. Claude opens it from its own CLI.
408
+ export type HarnessLogin = { url?: string }
409
+
410
+ // The server-owned login ceremony, one per workspace. `pending` means a watch
411
+ // loop is re-probing the provider until the login lands or the deadline
412
+ // passes; transitions arrive as `agent:updated` events, so every tab shows
413
+ // the same ceremony without polling.
414
+ export type AgentLoginState =
415
+ | { state: 'pending'; url?: string }
416
+ | { state: 'failed'; reason: string }
400
417
 
401
418
  // One MCP server's connection status, as surfaced by GET /api/workspaces/:id/mcp
402
419
  // (a subset of the agent SDK's McpServerStatus — only what the UI renders).
@@ -613,6 +630,10 @@ export type Model = {
613
630
  // the SDK under-types (e.g. 'xhigh'), so it stays string[].
614
631
  supportsEffort?: boolean
615
632
  supportedEffortLevels?: string[]
633
+ // Provider-resolved effort default when the user hasn't picked one (OpenClaw
634
+ // `thinkingDefault`, which differs per model — `low`/`medium`/`off`). Must be
635
+ // one of `supportedEffortLevels`.
636
+ defaultEffort?: string
616
637
  supportsAdaptiveThinking?: boolean
617
638
  supportsFastMode?: boolean
618
639
  // Provider-resolved default when moi has no stored Fast-mode preference.
@@ -620,10 +641,19 @@ export type Model = {
620
641
  supportsAutoMode?: boolean
621
642
  }
622
643
 
623
- // GET /api/workspaces/:id/models payload.
624
- export type WorkspaceModels = {
625
- // The agent backend that produced this list — matches the workspace provider.
644
+ // GET /api/workspaces/:id/agent payload — everything the client needs to know
645
+ // about the workspace's agent backend in one request at workspace open.
646
+ // `models` and capabilities are stable per process; `availability` and `login`
647
+ // are the volatile part, kept fresh after load by `agent:updated` events
648
+ // instead of refetches.
649
+ export type WorkspaceAgent = {
650
+ // The agent backend that produced this snapshot — matches the workspace
651
+ // provider.
626
652
  provider: WorkspaceType
653
+ // Runtime presence and provider auth state, from the server-side cache.
654
+ availability: HarnessAvailability
655
+ // Present while a login ceremony is in flight or after one failed.
656
+ login?: AgentLoginState
627
657
  models: Model[]
628
658
  // Whether this provider supports live token-by-token streaming (the picker
629
659
  // shows the "Live typing" toggle only when true). Provider-wide, not per-model
@@ -1,14 +1,14 @@
1
1
  import type { WorkspaceLayout, WorkspaceTabsState } from './types'
2
2
 
3
3
  export function createDefaultWorkspaceTabs(): WorkspaceTabsState {
4
- return { open: ['agent', 'widgets'], active: 'agent' }
4
+ return { open: ['agent', 'widgets', 'scratchpad'], active: 'agent' }
5
5
  }
6
6
 
7
7
  export function createDefaultWorkspaceLayout(): WorkspaceLayout {
8
8
  return {
9
9
  version: 1,
10
10
  widgetGrid: [],
11
- layoutMode: 'fullscreen',
11
+ layoutMode: 'split',
12
12
  tabs: createDefaultWorkspaceTabs()
13
13
  }
14
14
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "moi-computer",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Local AI workspace powered by the Claude Agent SDK, Bun, React, and Tailwind. Requires Bun.",
5
5
  "license": "Elastic-2.0",
6
6
  "type": "module",
@@ -58,12 +58,12 @@
58
58
  "dependencies": {
59
59
  "@anthropic-ai/claude-agent-sdk": "^0.3.197",
60
60
  "@anthropic-ai/sdk": "^0.109.1",
61
+ "@babel/parser": "^7.29.8",
61
62
  "@base-ui/react": "^1.2.0",
62
63
  "@dnd-kit/core": "^6.3.1",
63
64
  "@tabler/icons-react": "^3.44.0",
64
65
  "@tailwindcss/typography": "^0.5.19",
65
66
  "@tanstack/react-query": "^5.100.1",
66
- "@typescript-eslint/typescript-estree": "^8.57.2",
67
67
  "agentation": "^2.3.3",
68
68
  "bun-plugin-tailwind": "^0.1.2",
69
69
  "citty": "^0.2.1",
@@ -89,6 +89,7 @@
89
89
  "react-grid-layout": "^2.2.3",
90
90
  "react-markdown": "^10.1.0",
91
91
  "react-resizable": "^3.1.3",
92
+ "react-resizable-panels": "^4.12.2",
92
93
  "rehype-highlight": "^7.0.2",
93
94
  "remark-gfm": "^4.0.1",
94
95
  "shadcn": "^4.13.0",
@@ -98,7 +99,6 @@
98
99
  "tailwindcss": "^4.3.3",
99
100
  "tldraw": "5.2.3",
100
101
  "tw-animate-css": "^1.4.0",
101
- "typescript": "^5.9.3",
102
102
  "wouter": "^3.9.0",
103
103
  "zustand": "^5.0.12"
104
104
  },
@@ -106,12 +106,14 @@
106
106
  "openclaw": "2026.7.1"
107
107
  },
108
108
  "devDependencies": {
109
+ "@babel/types": "^7.29.8",
109
110
  "@types/bun": "latest",
110
111
  "@types/culori": "^4.0.1",
111
112
  "@types/react": "^19",
112
113
  "@types/react-dom": "^19",
113
114
  "@types/react-grid-layout": "^2.1.0",
114
115
  "oxfmt": "^0.54.0",
115
- "oxlint": "^1.69.0"
116
+ "oxlint": "^1.69.0",
117
+ "typescript": "^5.9.3"
116
118
  }
117
119
  }
@@ -0,0 +1,199 @@
1
+ // Server-owned agent state: the availability cache and the login ceremony.
2
+ //
3
+ // The client never polls for auth. `GET /api/workspaces/:id/agent` serves the
4
+ // snapshot from this store (one probe per workspace inside the TTL, however
5
+ // many tabs are open); `POST .../auth/login` starts — or joins — the single
6
+ // ceremony per workspace. While a ceremony is pending, a watch loop re-probes
7
+ // the provider until the login lands or the deadline passes, and every
8
+ // transition is pushed to all tabs as an `agent:updated` event on the
9
+ // workspace events socket.
10
+ import type {
11
+ AgentLoginState,
12
+ HarnessAvailability,
13
+ HarnessLogin,
14
+ WorkspaceEntry
15
+ } from '@/lib/types'
16
+
17
+ import { publishEvent } from './events'
18
+ import { harnessFor } from './harness/registry'
19
+
20
+ export type AgentUpdatedEvent = {
21
+ type: 'agent:updated'
22
+ workspaceId: string
23
+ availability: HarnessAvailability
24
+ login?: AgentLoginState
25
+ }
26
+
27
+ // Only the fields the probe/login provider calls actually read — lets callers
28
+ // that don't have a full registry entry on hand (e.g. a harness session
29
+ // reacting to a mid-conversation send failure) still trigger a refresh.
30
+ export type AgentWorkspace = Pick<WorkspaceEntry, 'id' | 'path' | 'type'>
31
+
32
+ export type AgentStoreOptions = {
33
+ probe: (ws: AgentWorkspace) => Promise<HarnessAvailability>
34
+ startLogin: (ws: AgentWorkspace) => Promise<HarnessLogin>
35
+ publish: (event: AgentUpdatedEvent) => void
36
+ availabilityTtlMs?: number
37
+ loginPollMs?: number
38
+ loginDeadlineMs?: number
39
+ }
40
+
41
+ type LoginCeremony = {
42
+ state: AgentLoginState
43
+ // The in-flight provider call; joiners await it instead of starting a
44
+ // second flow. Cleared once settled.
45
+ starting?: Promise<HarnessLogin>
46
+ stop: () => void
47
+ }
48
+
49
+ type AgentEntry = {
50
+ cached?: { value: HarnessAvailability; checkedAt: number }
51
+ // In-flight probe, shared by concurrent callers.
52
+ probe?: Promise<HarnessAvailability>
53
+ login?: LoginCeremony
54
+ }
55
+
56
+ export function createAgentStore(options: AgentStoreOptions) {
57
+ const ttlMs = options.availabilityTtlMs ?? 30_000
58
+ const pollMs = options.loginPollMs ?? 2_000
59
+ const deadlineMs = options.loginDeadlineMs ?? 3 * 60_000
60
+ const entries = new Map<string, AgentEntry>()
61
+
62
+ function entryFor(workspaceId: string): AgentEntry {
63
+ let entry = entries.get(workspaceId)
64
+ if (!entry) {
65
+ entry = {}
66
+ entries.set(workspaceId, entry)
67
+ }
68
+ return entry
69
+ }
70
+
71
+ function publish(workspaceId: string, availability: HarnessAvailability) {
72
+ const login = entries.get(workspaceId)?.login?.state
73
+ options.publish({
74
+ type: 'agent:updated',
75
+ workspaceId,
76
+ availability,
77
+ ...(login ? { login } : {})
78
+ })
79
+ }
80
+
81
+ async function probeFresh(ws: AgentWorkspace): Promise<HarnessAvailability> {
82
+ const entry = entryFor(ws.id)
83
+ if (!entry.probe) {
84
+ entry.probe = options.probe(ws).finally(() => {
85
+ entry.probe = undefined
86
+ })
87
+ }
88
+ const value = await entry.probe
89
+ entry.cached = { value, checkedAt: Date.now() }
90
+ return value
91
+ }
92
+
93
+ async function getAvailability(ws: AgentWorkspace): Promise<HarnessAvailability> {
94
+ const entry = entryFor(ws.id)
95
+ if (entry.cached && Date.now() - entry.cached.checkedAt < ttlMs) {
96
+ return entry.cached.value
97
+ }
98
+ return probeFresh(ws)
99
+ }
100
+
101
+ // Bypass the TTL and push the result even if it's unchanged. For callers
102
+ // that suspect the cached snapshot is stale for a reason other than an env
103
+ // change (e.g. a send just failed, which can mean the provider was signed
104
+ // out from outside moi — a `codex logout` in a terminal, say).
105
+ async function refresh(ws: AgentWorkspace): Promise<HarnessAvailability> {
106
+ const value = await probeFresh(ws)
107
+ publish(ws.id, value)
108
+ return value
109
+ }
110
+
111
+ function getLogin(workspaceId: string): AgentLoginState | undefined {
112
+ return entries.get(workspaceId)?.login?.state
113
+ }
114
+
115
+ // Re-probe until the login lands or the deadline passes. One loop per
116
+ // ceremony; a replaced or completed ceremony stops its loop.
117
+ function watch(ws: AgentWorkspace, login: LoginCeremony) {
118
+ const deadline = Date.now() + deadlineMs
119
+ let stopped = false
120
+ let timer: ReturnType<typeof setTimeout>
121
+ login.stop = () => {
122
+ stopped = true
123
+ clearTimeout(timer)
124
+ }
125
+ const tick = async () => {
126
+ let value: HarnessAvailability
127
+ try {
128
+ value = await probeFresh(ws)
129
+ } catch {
130
+ value = { available: false, reason: 'Could not verify the login' }
131
+ }
132
+ if (stopped) return
133
+ const entry = entryFor(ws.id)
134
+ if (value.available) {
135
+ entry.login = undefined
136
+ publish(ws.id, value)
137
+ return
138
+ }
139
+ if (Date.now() >= deadline) {
140
+ // Keep the failed state so the composer can show it; the next
141
+ // startLogin replaces it.
142
+ login.state = { state: 'failed', reason: 'Sign-in did not complete. Try again' }
143
+ publish(ws.id, value)
144
+ return
145
+ }
146
+ timer = setTimeout(tick, pollMs)
147
+ timer.unref?.()
148
+ }
149
+ // Unref'd so a pending ceremony never keeps the process alive on its own.
150
+ timer = setTimeout(tick, pollMs)
151
+ timer.unref?.()
152
+ }
153
+
154
+ async function startLogin(ws: AgentWorkspace): Promise<HarnessLogin> {
155
+ const entry = entryFor(ws.id)
156
+ // Join the in-flight ceremony instead of starting a second provider flow
157
+ // (two tabs, a remount, a double-click — all land here).
158
+ const current = entry.login
159
+ if (current?.starting) return current.starting
160
+ if (current?.state.state === 'pending') return { url: current.state.url }
161
+
162
+ current?.stop()
163
+ const starting = options.startLogin(ws)
164
+ const login: LoginCeremony = { state: { state: 'pending' }, starting, stop: () => {} }
165
+ entry.login = login
166
+ try {
167
+ const result = await starting
168
+ login.starting = undefined
169
+ login.state = { state: 'pending', ...(result.url ? { url: result.url } : {}) }
170
+ publish(ws.id, entry.cached?.value ?? { available: false, reason: 'Waiting for sign-in' })
171
+ watch(ws, login)
172
+ return result
173
+ } catch (err) {
174
+ entry.login = undefined
175
+ throw err
176
+ }
177
+ }
178
+
179
+ // Drop the cached snapshot so the next read re-probes (e.g. after an env
180
+ // change swaps credentials).
181
+ function invalidate(workspaceId: string) {
182
+ const entry = entries.get(workspaceId)
183
+ if (entry) entry.cached = undefined
184
+ }
185
+
186
+ return { getAvailability, refresh, getLogin, startLogin, invalidate }
187
+ }
188
+
189
+ export type AgentStore = ReturnType<typeof createAgentStore>
190
+
191
+ export const agentStore = createAgentStore({
192
+ probe: async ws => (await harnessFor(ws).availability?.(ws)) ?? { available: true },
193
+ startLogin: ws => {
194
+ const start = harnessFor(ws).startLogin
195
+ if (!start) throw new Error('This agent requires terminal sign-in')
196
+ return start(ws)
197
+ },
198
+ publish: publishEvent
199
+ })
package/server/api.ts CHANGED
@@ -11,13 +11,14 @@ import type {
11
11
  SessionInfo,
12
12
  UploadInfo,
13
13
  ViewBuilderInput,
14
+ WorkspaceAgent,
14
15
  WorkspaceEntry,
15
- WorkspaceModels,
16
16
  WorkspaceType
17
17
  } from '@/lib/types'
18
18
  import type { MoiContext } from '@/lib/moi-context'
19
19
  import { viewBuilderDirectives } from '@/lib/view-builder-directives'
20
20
 
21
+ import { agentStore } from './agent'
21
22
  import { getAppSettings, pickAppSettingsPatch, saveAppSettings } from './app-settings'
22
23
  import { appletForModule, recordAppletError } from './applet-log'
23
24
  import { apiBaseFor, parseAppletTail, serveWorkspaceFile } from './applets'
@@ -516,7 +517,11 @@ one.post('/sessions/:sessionId/archive', async c => {
516
517
  return c.body(null, 204)
517
518
  } catch (error) {
518
519
  console.error(`[api] archive chat failed for ${harness.id}`, error)
519
- return c.text('Couldn’t archive chat', 500)
520
+ // Harnesses translate backend refusals into actionable one-liners (e.g.
521
+ // OpenClaw: main chat not archivable, gateway too old) — surface them.
522
+ const message =
523
+ error instanceof Error && error.message ? error.message : 'Couldn’t archive chat'
524
+ return c.text(message, 500)
520
525
  }
521
526
  })
522
527
 
@@ -638,12 +643,18 @@ one.put('/env', async c => {
638
643
  return c.json(await getWorkspaceEnvView(ws.path, requiredEnvFor(ws.path)))
639
644
  })
640
645
 
641
- // Is the workspace's agent backend usable right now? (e.g. a codex workspace
642
- // on a machine without the codex CLI). The chat surfaces the `reason` as a
643
- // banner instead of letting the first send fail cold.
644
- one.get('/availability', async c => {
645
- const availability = await workspaceTypeAvailability(c.get('ws').type ?? 'claude-code')
646
- return c.json(availability satisfies HarnessAvailability)
646
+ // Start a provider login ceremony. Codex returns a browser OAuth URL for the
647
+ // host to open; Claude launches its browser flow through the CLI itself.
648
+ // Idempotent per workspace: a second call joins the pending ceremony instead
649
+ // of starting another provider flow. Completion is pushed as `agent:updated`.
650
+ one.post('/auth/login', async c => {
651
+ const ws = c.get('ws')
652
+ if (!harnessFor(ws).startLogin) return c.text('This agent requires terminal sign-in', 409)
653
+ try {
654
+ return c.json(await agentStore.startLogin(ws))
655
+ } catch (err) {
656
+ return c.text(err instanceof Error ? err.message : 'Could not start sign-in', 500)
657
+ }
647
658
  })
648
659
 
649
660
  one.get('/skills', async c => {
@@ -657,25 +668,33 @@ one.post('/skills/update', async c => {
657
668
  return c.json(result.status)
658
669
  })
659
670
 
660
- // Models the workspace's agent backend can run, normalized across providers.
661
- // OpenClaw queries the gateway catalog; everything else (Claude Code) reads the
662
- // account-wide Agent SDK model list.
663
- one.get('/models', async c => {
671
+ // The workspace's agent backend in one snapshot: provider, availability
672
+ // (runtime presence + auth, from the server-side cache), any in-flight login
673
+ // ceremony, the model catalog, and capabilities. One request at workspace
674
+ // open; the volatile parts stay fresh afterwards via `agent:updated` events,
675
+ // not refetches.
676
+ one.get('/agent', async c => {
664
677
  const ws = c.get('ws')
665
678
  const harness = harnessFor(ws)
666
679
  // A backend that can't answer (codex CLI missing, gateway down) degrades to
667
680
  // an empty catalog — the picker hides and chat surfaces the real problem via
668
681
  // the availability banner, instead of this endpoint 500ing on page load.
669
- const models = await harness.listModels(ws).catch(err => {
670
- console.error(`[api] listModels failed for ${harness.id}`, err)
671
- return []
672
- })
682
+ const [availability, models] = await Promise.all([
683
+ agentStore.getAvailability(ws),
684
+ harness.listModels(ws).catch(err => {
685
+ console.error(`[api] listModels failed for ${harness.id}`, err)
686
+ return []
687
+ })
688
+ ])
689
+ const login = agentStore.getLogin(ws.id)
673
690
  return c.json({
674
691
  provider: harness.id,
692
+ availability,
693
+ ...(login ? { login } : {}),
675
694
  models,
676
695
  supportsStreaming: harness.capabilities.supportsStreaming,
677
696
  supportsArchiving: Boolean(harness.archiveSession)
678
- } satisfies WorkspaceModels)
697
+ } satisfies WorkspaceAgent)
679
698
  })
680
699
 
681
700
  // Workspace identity (name). GET returns the current {name, icon}; PUT a JSON
@@ -1,8 +1,5 @@
1
- import type {
2
- ExportNamedDeclaration,
3
- VariableDeclarator
4
- } from '@typescript-eslint/types/dist/generated/ast-spec'
5
- import { parse } from '@typescript-eslint/typescript-estree'
1
+ import { parse } from '@babel/parser'
2
+ import type { ObjectProperty, StringLiteral } from '@babel/types'
6
3
  import type { BunPlugin } from 'bun'
7
4
  import tailwind from 'bun-plugin-tailwind'
8
5
  import { realpathSync } from 'node:fs'
@@ -74,43 +71,37 @@ const VALID_SPANS = [1, 2, 3, 4] as const
74
71
  // The properties of an exported `const config = { … }` object literal, or null
75
72
  // when the file declares no such export. Shared by the widget and view config
76
73
  // extractors — they each interpret the properties under their own schema.
74
+ // Parsed with @babel/parser: it handles TS + JSX with no peer dependencies, so
75
+ // it always resolves from moi's own tree. A parser that peer-depends on
76
+ // `typescript` breaks under bun's shared global tree, where another globally
77
+ // installed package controls which `typescript` sits at the hoisted root.
77
78
  function findConfigProperties(source: string) {
78
- const ast = parse(source, { jsx: true, errorOnUnknownASTType: false })
79
-
80
- const exportDecl = ast.body.find(
81
- node =>
82
- node.type === 'ExportNamedDeclaration' &&
83
- node.declaration?.type === 'VariableDeclaration' &&
84
- node.declaration.declarations.some(d => d.id.type === 'Identifier' && d.id.name === 'config')
85
- ) as ExportNamedDeclaration | undefined
86
- if (!exportDecl) return null
87
-
88
- const varDecl = exportDecl.declaration
89
- if (varDecl?.type !== 'VariableDeclaration') return null
90
-
91
- const decl = varDecl.declarations.find(
92
- (d): d is VariableDeclarator & { id: { type: 'Identifier'; name: string } } =>
93
- d.id.type === 'Identifier' && d.id.name === 'config'
94
- )
95
- const rawInit = decl?.init
96
- // Unwrap `as const` — AST wraps the object in TSAsExpression
97
- const init = rawInit?.type === 'TSAsExpression' ? rawInit.expression : rawInit
98
- if (init?.type !== 'ObjectExpression') return null
99
-
100
- return init.properties
79
+ const ast = parse(source, { sourceType: 'module', plugins: ['typescript', 'jsx'] })
80
+
81
+ for (const node of ast.program.body) {
82
+ if (node.type !== 'ExportNamedDeclaration') continue
83
+ if (node.declaration?.type !== 'VariableDeclaration') continue
84
+ const decl = node.declaration.declarations.find(
85
+ d => d.id.type === 'Identifier' && d.id.name === 'config'
86
+ )
87
+ if (!decl) continue
88
+
89
+ const rawInit = decl.init
90
+ // Unwrap `as const` — AST wraps the object in TSAsExpression
91
+ const init = rawInit?.type === 'TSAsExpression' ? rawInit.expression : rawInit
92
+ if (init?.type !== 'ObjectExpression') return null
93
+ return init.properties
94
+ }
95
+
96
+ return null
101
97
  }
102
98
 
103
99
  // `requiredEnv`: an array of string literals naming env vars the bundle needs.
104
100
  // Advisory only — surfaced in the env UI, never enforced at build/load.
105
- function readRequiredEnv(propValue: unknown): string[] | undefined {
106
- const value = propValue as { type?: string; elements?: unknown[] }
107
- if (value?.type !== 'ArrayExpression') return undefined
108
- const names = (value.elements ?? [])
109
- .filter(
110
- (el): el is { type: 'Literal'; value: string } =>
111
- (el as { type?: string })?.type === 'Literal' &&
112
- typeof (el as { value?: unknown }).value === 'string'
113
- )
101
+ function readRequiredEnv(propValue: ObjectProperty['value']): string[] | undefined {
102
+ if (propValue.type !== 'ArrayExpression') return undefined
103
+ const names = propValue.elements
104
+ .filter((el): el is StringLiteral => el?.type === 'StringLiteral')
114
105
  .map(el => el.value)
115
106
  return names.length ? names : undefined
116
107
  }
@@ -125,8 +116,8 @@ export async function extractWidgetConfig(srcPath: string): Promise<WidgetConfig
125
116
  const result: Partial<WidgetConfig> = {}
126
117
 
127
118
  for (const prop of properties) {
128
- if (prop.type !== 'Property' || prop.key?.type !== 'Identifier') continue
129
- const key = prop.key.name as string
119
+ if (prop.type !== 'ObjectProperty' || prop.key.type !== 'Identifier') continue
120
+ const key = prop.key.name
130
121
 
131
122
  if (key === 'requiredEnv') {
132
123
  const names = readRequiredEnv(prop.value)
@@ -135,7 +126,7 @@ export async function extractWidgetConfig(srcPath: string): Promise<WidgetConfig
135
126
  }
136
127
 
137
128
  if (key !== 'rowSpan' && key !== 'colSpan') continue
138
- if (prop.value?.type !== 'Literal' || typeof prop.value.value !== 'number') continue
129
+ if (prop.value.type !== 'NumericLiteral') continue
139
130
 
140
131
  const val = prop.value.value
141
132
  if (!(VALID_SPANS as readonly number[]).includes(val)) {
@@ -159,17 +150,17 @@ export async function extractViewConfig(srcPath: string): Promise<ViewConfig | n
159
150
  const result: ViewConfig = {}
160
151
 
161
152
  for (const prop of properties) {
162
- if (prop.type !== 'Property' || prop.key?.type !== 'Identifier') continue
163
- const key = prop.key.name as string
153
+ if (prop.type !== 'ObjectProperty' || prop.key.type !== 'Identifier') continue
154
+ const key = prop.key.name
164
155
 
165
156
  if (key === 'title') {
166
- if (prop.value?.type === 'Literal' && typeof prop.value.value === 'string') {
157
+ if (prop.value.type === 'StringLiteral') {
167
158
  result.title = prop.value.value
168
159
  }
169
160
  continue
170
161
  }
171
162
  if (key === 'icon') {
172
- if (prop.value?.type === 'Literal' && typeof prop.value.value === 'string') {
163
+ if (prop.value.type === 'StringLiteral') {
173
164
  const icon = prop.value.value
174
165
  if (!isAppIconId(icon)) {
175
166
  throw new Error(`Unknown view icon id "${icon}". Use one of: ${APP_ICON_IDS.join(', ')}`)