moi-computer 0.8.1-next.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.
package/lib/format.ts CHANGED
@@ -115,9 +115,11 @@ export type Turn = {
115
115
  parentTaskId?: string
116
116
  parts: Part[]
117
117
  timestamp?: string
118
- // Stable monotonic ordering hint when the source provides one (OpenClaw's
119
- // `__openclaw.seq`). Used as a tiebreaker when timestamps collide; the UI
120
- // 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.
121
123
  seq?: number
122
124
  meta?: TurnMeta
123
125
  }
@@ -251,9 +253,21 @@ export function applyEvent(state: ViewState, ev: StreamEvent): ViewState {
251
253
  return { ...state, snapshot: ev.snapshot }
252
254
  case 'turn': {
253
255
  const idx = state.turns.findIndex(t => t.id === ev.turn.id)
254
- const turns =
255
- idx >= 0 ? state.turns.map((t, i) => (i === idx ? ev.turn : t)) : [...state.turns, ev.turn]
256
- 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)] }
257
271
  }
258
272
  case 'notice': {
259
273
  if (state.notices.some(n => n.id === ev.notice.id)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "moi-computer",
3
- "version": "0.8.1-next.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",
@@ -99,7 +99,6 @@
99
99
  "tailwindcss": "^4.3.3",
100
100
  "tldraw": "5.2.3",
101
101
  "tw-animate-css": "^1.4.0",
102
- "typescript": "^5.9.3",
103
102
  "wouter": "^3.9.0",
104
103
  "zustand": "^5.0.12"
105
104
  },
@@ -107,12 +106,14 @@
107
106
  "openclaw": "2026.7.1"
108
107
  },
109
108
  "devDependencies": {
109
+ "@babel/types": "^7.29.8",
110
110
  "@types/bun": "latest",
111
111
  "@types/culori": "^4.0.1",
112
112
  "@types/react": "^19",
113
113
  "@types/react-dom": "^19",
114
114
  "@types/react-grid-layout": "^2.1.0",
115
115
  "oxfmt": "^0.54.0",
116
- "oxlint": "^1.69.0"
116
+ "oxlint": "^1.69.0",
117
+ "typescript": "^5.9.3"
117
118
  }
118
119
  }
@@ -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(', ')}`)
package/server/cli-env.ts CHANGED
@@ -9,7 +9,7 @@ import type { WorkspaceEntry, WorkspaceEnvView } from '@/lib/types'
9
9
 
10
10
  import pc from './cli-pc'
11
11
  import { columns } from './cli-ui'
12
- import { CONTROL_PORT } from './constants'
12
+ import { CONTROL_URL } from './constants'
13
13
  import { findWorkspaceForPath, listWorkspaces } from './registry'
14
14
  import { discoverDotenvKeys, resolveWorkspaceEnv } from './workspace-env'
15
15
 
@@ -170,7 +170,7 @@ export function notifyEnvChanged(path: string): Promise<boolean> {
170
170
  return new Promise(resolve => {
171
171
  let ws: WebSocket
172
172
  try {
173
- ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
173
+ ws = new WebSocket(CONTROL_URL)
174
174
  } catch {
175
175
  resolve(false)
176
176
  return
package/server/cli.ts CHANGED
@@ -40,7 +40,8 @@ import {
40
40
  resolveCwdWorkspace
41
41
  } from './cli-env'
42
42
  import { columns } from './cli-ui'
43
- import { CONTROL_PORT, PORT } from './constants'
43
+ import { CONTROL_HOST, CONTROL_PORT, CONTROL_URL, PORT } from './constants'
44
+ import { type ControlProbe, controlFailureMessage, probeControlServer } from './control-client'
44
45
  import { type OpenClawAgent, discoverOpenClawAgents } from './harness/openclaw/discovery'
45
46
  import { liftToWorkspaceRoot, registerWorkspace } from './registry'
46
47
  import { serverCwd } from './server-cwd'
@@ -83,22 +84,15 @@ import { provisionWorkspace } from './workspace-init'
83
84
  // ---- helpers ----------------------------------------------------------------
84
85
 
85
86
  async function isServerRunning(): Promise<boolean> {
86
- return new Promise(resolve => {
87
- const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
88
- const timer = setTimeout(() => {
89
- ws.close()
90
- resolve(false)
91
- }, 600)
92
- ws.onopen = () => {
93
- clearTimeout(timer)
94
- ws.close()
95
- resolve(true)
96
- }
97
- ws.onerror = () => {
98
- clearTimeout(timer)
99
- resolve(false)
100
- }
101
- })
87
+ return (await probeControlServer()).status === 'running'
88
+ }
89
+
90
+ // Print why the control socket could not be opened, then exit. Classifies the
91
+ // failure first, so "no server is listening" and "the server is up but the
92
+ // address is unreachable" no longer read as the same problem.
93
+ async function exitControlUnreachable(): Promise<never> {
94
+ console.error(controlFailureMessage(await probeControlServer()))
95
+ process.exit(1)
102
96
  }
103
97
 
104
98
  async function waitForServer(timeoutMs = 10_000): Promise<boolean> {
@@ -112,7 +106,7 @@ async function waitForServer(timeoutMs = 10_000): Promise<boolean> {
112
106
 
113
107
  async function registerViaControl(absPath: string): Promise<string> {
114
108
  return new Promise((res, rej) => {
115
- const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
109
+ const ws = new WebSocket(CONTROL_URL)
116
110
  ws.onopen = () => ws.send(JSON.stringify({ type: 'workspace:register', path: absPath }))
117
111
  ws.onmessage = event => {
118
112
  const data = JSON.parse(String(event.data))
@@ -121,7 +115,7 @@ async function registerViaControl(absPath: string): Promise<string> {
121
115
  res(data.id)
122
116
  }
123
117
  }
124
- ws.onerror = () => rej(new Error('Could not connect to control server'))
118
+ ws.onerror = () => void probeControlServer().then(p => rej(new Error(controlFailureMessage(p))))
125
119
  })
126
120
  }
127
121
 
@@ -486,7 +480,7 @@ const bundle = defineCommand({
486
480
  // Computed locally up front so it can ride along in the success output; the
487
481
  // agent reads this and knows to run `moi skill update`.
488
482
  const notice = await staleSkillNotice(path)
489
- const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
483
+ const ws = new WebSocket(CONTROL_URL)
490
484
 
491
485
  ws.onopen = () =>
492
486
  ws.send(
@@ -567,10 +561,7 @@ const bundle = defineCommand({
567
561
  process.exit(failed.length > 0 ? 1 : 0)
568
562
  }
569
563
 
570
- ws.onerror = () => {
571
- console.error('Could not connect to control server. Is the main process running?')
572
- process.exit(1)
573
- }
564
+ ws.onerror = () => void exitControlUnreachable()
574
565
  }
575
566
  })
576
567
 
@@ -594,7 +585,7 @@ const builderSet = defineCommand({
594
585
  },
595
586
  run({ args }) {
596
587
  const path = resolve(args.dir)
597
- const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
588
+ const ws = new WebSocket(CONTROL_URL)
598
589
  ws.onopen = () =>
599
590
  ws.send(
600
591
  JSON.stringify({
@@ -625,10 +616,7 @@ const builderSet = defineCommand({
625
616
  ws.close()
626
617
  process.exit(0)
627
618
  }
628
- ws.onerror = () => {
629
- console.error('Could not connect to control server. Is the main process running?')
630
- process.exit(1)
631
- }
619
+ ws.onerror = () => void exitControlUnreachable()
632
620
  }
633
621
  })
634
622
 
@@ -659,7 +647,7 @@ const refresh = defineCommand({
659
647
  process.exit(1)
660
648
  }
661
649
  const notice = await staleSkillNotice(process.cwd())
662
- const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
650
+ const ws = new WebSocket(CONTROL_URL)
663
651
 
664
652
  ws.onopen = () => ws.send(JSON.stringify({ type: 'applets:refresh', only: args.only }))
665
653
 
@@ -678,10 +666,7 @@ const refresh = defineCommand({
678
666
  process.exit(0)
679
667
  }
680
668
 
681
- ws.onerror = () => {
682
- console.error('Could not connect to control server. Is the main process running?')
683
- process.exit(1)
684
- }
669
+ ws.onerror = () => void exitControlUnreachable()
685
670
  }
686
671
  })
687
672
 
@@ -720,7 +705,7 @@ const theme = defineCommand({
720
705
  async run({ args }) {
721
706
  const path = resolve(args.dir)
722
707
  const notice = await staleSkillNotice(path)
723
- const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
708
+ const ws = new WebSocket(CONTROL_URL)
724
709
 
725
710
  ws.onopen = () =>
726
711
  ws.send(
@@ -834,10 +819,7 @@ const theme = defineCommand({
834
819
  process.exit(0)
835
820
  }
836
821
 
837
- ws.onerror = () => {
838
- console.error('Could not connect to control server. Is the main process running?')
839
- process.exit(1)
840
- }
822
+ ws.onerror = () => void exitControlUnreachable()
841
823
  }
842
824
  })
843
825
 
@@ -858,15 +840,24 @@ function versionMismatchNotice(serverVersion: string): string | null {
858
840
  const status = defineCommand({
859
841
  meta: { name: 'status', description: 'Show server status and registered workspaces' },
860
842
  async run() {
861
- const running = await isServerRunning()
843
+ const probe: ControlProbe = await probeControlServer()
862
844
  const notice = await staleSkillNotice(process.cwd())
863
845
 
864
- if (!running) {
846
+ if (probe.status === 'not-running') {
865
847
  console.log('\n' + pc.dim('○') + ' Server is ' + pc.bold('not running'))
866
848
  console.log(pc.dim(` cli version ${VERSION}`) + '\n')
867
849
  process.exit(0)
868
850
  }
869
851
 
852
+ // The dial failed for a reason other than an empty port, so the server may
853
+ // be up and healthy. Name the real obstacle instead of blaming the process.
854
+ if (probe.status === 'unreachable') {
855
+ console.log('\n' + pc.yellow('◆') + ' Server is ' + pc.bold('unreachable'))
856
+ console.log(pc.dim(` control port ${CONTROL_HOST}:${CONTROL_PORT} — ${probe.reason}`))
857
+ console.log(pc.dim(` cli version ${VERSION}`) + '\n')
858
+ process.exit(1)
859
+ }
860
+
870
861
  const info = await queryServerInfo()
871
862
  console.log(
872
863
  '\n' +
@@ -890,7 +881,7 @@ const status = defineCommand({
890
881
  if (mismatch) console.log('\n' + mismatch)
891
882
 
892
883
  await new Promise<void>((resolve, reject) => {
893
- const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
884
+ const ws = new WebSocket(CONTROL_URL)
894
885
 
895
886
  ws.onopen = () => ws.send(JSON.stringify({ type: 'workspace:list' }))
896
887
 
@@ -904,7 +895,8 @@ const status = defineCommand({
904
895
  resolve()
905
896
  }
906
897
 
907
- ws.onerror = () => reject(new Error('Could not connect to control server'))
898
+ ws.onerror = () =>
899
+ void probeControlServer().then(p => reject(new Error(controlFailureMessage(p))))
908
900
  })
909
901
 
910
902
  if (notice) console.log(pc.yellow(notice) + '\n')
@@ -1207,7 +1199,7 @@ async function sendConfig(payload: {
1207
1199
  clearIcon?: boolean
1208
1200
  }) {
1209
1201
  const notice = await staleSkillNotice(payload.path)
1210
- const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
1202
+ const ws = new WebSocket(CONTROL_URL)
1211
1203
  ws.onopen = () => ws.send(JSON.stringify({ type: 'config', ...payload }))
1212
1204
  ws.onmessage = event => {
1213
1205
  const res = JSON.parse(String(event.data))
@@ -1240,10 +1232,7 @@ async function sendConfig(payload: {
1240
1232
  ws.close()
1241
1233
  process.exit(0)
1242
1234
  }
1243
- ws.onerror = () => {
1244
- console.error('Could not connect to control server. Is the main process running?')
1245
- process.exit(1)
1246
- }
1235
+ ws.onerror = () => void exitControlUnreachable()
1247
1236
  }
1248
1237
 
1249
1238
  // A terse cheat sheet — one line per command — so an agent can grasp the
@@ -1482,7 +1471,7 @@ function sendControl(
1482
1471
  payload: Record<string, unknown>,
1483
1472
  onResult: (res: Record<string, unknown>) => void | Promise<void>
1484
1473
  ) {
1485
- const ws = new WebSocket(`ws://localhost:${CONTROL_PORT}`)
1474
+ const ws = new WebSocket(CONTROL_URL)
1486
1475
  ws.onopen = () => ws.send(JSON.stringify(payload))
1487
1476
  ws.onmessage = async event => {
1488
1477
  const res = JSON.parse(String(event.data))
@@ -1499,10 +1488,7 @@ function sendControl(
1499
1488
  ws.close()
1500
1489
  process.exit(0)
1501
1490
  }
1502
- ws.onerror = () => {
1503
- console.error('Could not connect to control server. Is the main process running?')
1504
- process.exit(1)
1505
- }
1491
+ ws.onerror = () => void exitControlUnreachable()
1506
1492
  }
1507
1493
 
1508
1494
  function sendScratch(
@@ -1,3 +1,11 @@
1
1
  export const PORT = Number(process.env.PORT) || 13337
2
2
  // M=13, E=5, I=9 -> 13059
3
3
  export const CONTROL_PORT = 13059
4
+ // The address the control server binds AND the one every client dials — never
5
+ // the name `localhost`. Resolution of that name is not guaranteed: container
6
+ // images ship an /etc/hosts without a `localhost` entry (Bun's resolver, unlike
7
+ // glibc, does not special-case it), and where it does resolve it may prefer
8
+ // ::1 while the control server listens on IPv4 only. Bind and dial read this
9
+ // same constant so the two can never drift apart.
10
+ export const CONTROL_HOST = '127.0.0.1'
11
+ export const CONTROL_URL = `ws://${CONTROL_HOST}:${CONTROL_PORT}`
@@ -0,0 +1,124 @@
1
+ import { connect } from 'node:net'
2
+
3
+ import { CONTROL_HOST, CONTROL_PORT, CONTROL_URL } from './constants'
4
+
5
+ // Why the CLI probes the control port instead of just asking "did the socket
6
+ // open?": a failed dial has more than one cause, and they need different
7
+ // answers. Nothing listening means the server is not running (`moi start`).
8
+ // Anything else — the name or address not resolving, the host unreachable, a
9
+ // stranger squatting on the port — means the server may well be running and
10
+ // fine, and the fix is not to restart it. Bun's WebSocket collapses all of
11
+ // these into a single "Failed to connect" error, so the classification is
12
+ // recovered with a second probe at the TCP layer, where the real errno
13
+ // survives (`node:net` reports it; `Bun.connect` reports ECONNREFUSED for
14
+ // everything, so it cannot be used here).
15
+
16
+ export type ControlProbe =
17
+ // A control socket opened — the server is up.
18
+ | { status: 'running' }
19
+ // Connection refused: the port is free, so no server is listening.
20
+ | { status: 'not-running' }
21
+ // Anything else. `reason` names the actual failure for the user.
22
+ | { status: 'unreachable'; reason: string }
23
+
24
+ export type ControlProbeOptions = {
25
+ host?: string
26
+ port?: number
27
+ timeoutMs?: number
28
+ }
29
+
30
+ function closeQuietly(ws: WebSocket): void {
31
+ try {
32
+ ws.close()
33
+ } catch {}
34
+ }
35
+
36
+ // Re-dial the same address at the TCP layer to recover the errno the WebSocket
37
+ // error swallowed. Reaching this means the WebSocket already failed, so a
38
+ // successful TCP connect is itself a finding: something holds the control port
39
+ // but does not speak our protocol.
40
+ function classifyDialFailure(host: string, port: number, timeoutMs: number): Promise<ControlProbe> {
41
+ return new Promise(resolve => {
42
+ let settled = false
43
+ const settle = (probe: ControlProbe) => {
44
+ if (settled) return
45
+ settled = true
46
+ resolve(probe)
47
+ }
48
+ const socket = connect({ host, port })
49
+ socket.setTimeout(timeoutMs)
50
+ socket.on('connect', () => {
51
+ socket.destroy()
52
+ settle({
53
+ status: 'unreachable',
54
+ reason:
55
+ 'the port accepted a connection but refused the control WebSocket — another process may hold it'
56
+ })
57
+ })
58
+ socket.on('timeout', () => {
59
+ socket.destroy()
60
+ settle({ status: 'unreachable', reason: `no answer within ${timeoutMs}ms` })
61
+ })
62
+ socket.on('error', (err: NodeJS.ErrnoException) => {
63
+ socket.destroy()
64
+ if (err.code === 'ECONNREFUSED') {
65
+ settle({ status: 'not-running' })
66
+ return
67
+ }
68
+ if (err.code === 'ENOTFOUND' || err.code === 'EAI_AGAIN') {
69
+ settle({ status: 'unreachable', reason: `could not resolve "${host}" (${err.code})` })
70
+ return
71
+ }
72
+ settle({
73
+ status: 'unreachable',
74
+ reason: err.code ?? err.message
75
+ })
76
+ })
77
+ })
78
+ }
79
+
80
+ // Open a control socket and report what happened. The happy path is one
81
+ // WebSocket connect; the extra TCP probe only runs when that fails.
82
+ export function probeControlServer(options: ControlProbeOptions = {}): Promise<ControlProbe> {
83
+ const { host = CONTROL_HOST, port = CONTROL_PORT, timeoutMs = 1500 } = options
84
+ const url = host === CONTROL_HOST && port === CONTROL_PORT ? CONTROL_URL : `ws://${host}:${port}`
85
+ return new Promise(resolve => {
86
+ let settled = false
87
+ const settle = (probe: ControlProbe) => {
88
+ if (settled) return
89
+ settled = true
90
+ resolve(probe)
91
+ }
92
+ let ws: WebSocket
93
+ try {
94
+ ws = new WebSocket(url)
95
+ } catch (err) {
96
+ settle({ status: 'unreachable', reason: err instanceof Error ? err.message : String(err) })
97
+ return
98
+ }
99
+ const timer = setTimeout(() => {
100
+ closeQuietly(ws)
101
+ // A hung dial is not evidence of an absent server — say so rather than
102
+ // reporting it as "not running" the way a bare timeout used to.
103
+ void classifyDialFailure(host, port, timeoutMs).then(settle)
104
+ }, timeoutMs)
105
+ ws.onopen = () => {
106
+ clearTimeout(timer)
107
+ closeQuietly(ws)
108
+ settle({ status: 'running' })
109
+ }
110
+ ws.onerror = () => {
111
+ clearTimeout(timer)
112
+ void classifyDialFailure(host, port, timeoutMs).then(settle)
113
+ }
114
+ })
115
+ }
116
+
117
+ // The one-line explanation the CLI prints when a command could not reach the
118
+ // control server. `running` never reaches here.
119
+ export function controlFailureMessage(probe: ControlProbe): string {
120
+ if (probe.status === 'unreachable') {
121
+ return `Could not reach the control server at ${CONTROL_HOST}:${CONTROL_PORT} — ${probe.reason}. The server may still be running.`
122
+ }
123
+ return 'Could not connect to control server. Is the main process running?'
124
+ }
package/server/control.ts CHANGED
@@ -7,7 +7,7 @@ import { isParamsRecord } from '@/lib/workspace-tabs'
7
7
 
8
8
  import { clearAppletLog, getAppletLog, getAppletLogCount } from './applet-log'
9
9
  import { serializeWorkspaceBundle } from './bundle-queue'
10
- import { CONTROL_PORT, PORT } from './constants'
10
+ import { CONTROL_HOST, CONTROL_PORT, PORT } from './constants'
11
11
  import { applyEnvChanged } from './env-apply'
12
12
  import { callFunctionEphemeral, parseFunctionPath } from './functions'
13
13
  import { processIcon } from './icon'
@@ -63,7 +63,7 @@ async function resolveWorkspace(
63
63
 
64
64
  export const control = Bun.serve({
65
65
  port: CONTROL_PORT,
66
- hostname: '127.0.0.1',
66
+ hostname: CONTROL_HOST,
67
67
  fetch(req, server) {
68
68
  return server.upgrade(req)
69
69
  ? new Response(null, { status: 101 })
@@ -121,12 +121,16 @@ SDK has no live setter for them.
121
121
  **OpenClaw — shipped.** Chat over the local gateway's WebSocket JSON-RPC
122
122
  (wire protocol 4 — the 2026.7.x and 2026.6.x lines; protocol-3 gateways are
123
123
  detected and surfaced, see `openclaw/compat.ts`): sessions seeded cold from
124
- `sessions.get` then updated from live `session.message` frames, token-delta
125
- previews from `chat` frames, live tool state + output from `session.tool`
126
- frames, model/effort applied per send via `sessions.patch`, abort via
127
- `sessions.abort`, per-turn usage (tokens + cost) into `TurnMeta`, user-echo
128
- rendezvous by `<runId>:user` idempotency key (text fallback), uploads
129
- materialized to file paths. Known gaps: no rich vision blocks (string-only
124
+ `sessions.get` then updated from live `session.message` frames (placed by the
125
+ transcript `seq` they carry, so a late row still renders in order), token-delta
126
+ previews from `chat` frames, live tool state + output from the tool stream
127
+ (`session.tool` and `agent`/tool are one payload split by audience — see
128
+ `openclaw/NOTES.md` §6 — and share one handler), run failures surfaced from the
129
+ frames that carry them, model/effort applied per send via `sessions.patch`,
130
+ abort via `sessions.abort`, per-turn usage (tokens + cost) into `TurnMeta`,
131
+ user-echo rendezvous by `<runId>:user` idempotency key (text fallback), uploads
132
+ materialized to file paths. The frame orders a live gateway produces are
133
+ replayed against the real session code by `openclaw/wire-replay.test.ts`. Known gaps: no rich vision blocks (string-only
130
134
  `sessions.send`), and the gateway is the sole source of truth (no local
131
135
  persistence; cold restarts re-seed).
132
136