@mobius-os/mobius 0.3.69 → 0.3.72

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mobius-os/mobius",
3
- "version": "0.3.69",
3
+ "version": "0.3.72",
4
4
  "type": "module",
5
5
  "description": "Mobius terminal client. Reuses Mobius frontend TypeScript types and jsonl entry shapes.",
6
6
  "bin": {
@@ -13,8 +13,8 @@ set -euo pipefail
13
13
 
14
14
  TAG=20241002
15
15
  PYVER=3.12.7
16
- BUNDLE_VER=17
17
- AIMUX_VERSION=0.3.69
16
+ BUNDLE_VER=18
17
+ AIMUX_VERSION=0.3.72
18
18
  PYPI_INDEX=https://pypi.org/simple
19
19
  WORK="${WORK:-$HOME/python-bundles}"
20
20
  DIST="${DIST:-$WORK/dist}"
package/src/aimux.ts CHANGED
@@ -33,8 +33,11 @@ export type AimuxLauncher =
33
33
  | { kind: 'exe'; path: string }
34
34
  | { kind: 'module'; python: string }
35
35
 
36
- const AIMUX_TARGET_VERSION = '0.3.69'
37
- const AIMUX_PACKAGE = `aimux==${AIMUX_TARGET_VERSION}`
36
+ /**
37
+ * 兜底 pin:只在读不到服务端版本时用(老 broker / 网络不通),**不是**"最低可用版本"。
38
+ * 正常情况下连接时会读服务端 broker 的 aimux 版本,本地跟它对齐(升级、降级都一样)。
39
+ */
40
+ const AIMUX_TARGET_VERSION = '0.3.72'
38
41
  const WIN = process.platform === 'win32'
39
42
  const venvDir = () => path.join(mobiusHome(), 'aimux-venv')
40
43
  const venvPython = () => WIN ? path.join(venvDir(), 'Scripts', 'python.exe') : path.join(venvDir(), 'bin', 'python')
@@ -94,7 +97,7 @@ async function pythonForAimux(onProgress?: (p: InstallProgress) => void): Promis
94
97
  // 系统 python(如被精简掉 ensurepip 的容器镜像)。aimux 全部依赖为纯 Python,
95
98
  // 故三平台可共用同一套打包产物,分别按 arch 发布到 CDN。
96
99
  /** Plan B 内置运行时包版本;每次发版跟 aimux pin 一起 +1,测试也从这里取。 */
97
- export const BUNDLE_VER = '17'
100
+ export const BUNDLE_VER = '18'
98
101
  const BUNDLE_AIMUX_VERSION = AIMUX_TARGET_VERSION
99
102
  /** Version expected from the installed or bundled AIMUX runtime. */
100
103
  export const AIMUX_VERSION = BUNDLE_AIMUX_VERSION
@@ -135,17 +138,25 @@ export function bundleArch(): string | null {
135
138
  export const bundleBaseUrl = () => (process.env.MOBIUS_TUI_PYTHON_BUNDLE_URL || 'https://serve.nutshellai.cn/publish/auto/mobius-tui').replace(/\/$/, '')
136
139
  export const bundleUrl = (arch: string) => `${bundleBaseUrl()}/mobius-python-${arch}-v${BUNDLE_VER}.zip`
137
140
 
138
- export function bundleHealthCheckCode(platform: NodeJS.Platform = process.platform): string {
141
+ /**
142
+ * 内置运行时校验脚本。`expected` 非 null 时额外断言 aimux 版本——版本对不上就重下整包
143
+ * (老行为,pin 与包版本一致时用)。传 null 表示"只要求能 import":服务端要求另一个
144
+ * 版本时靠 pip 就地换,而不是重下几百 MB 的包。
145
+ */
146
+ export function bundleHealthCheckCode(
147
+ platform: NodeJS.Platform = process.platform,
148
+ expected: string | null = BUNDLE_AIMUX_VERSION,
149
+ ): string {
139
150
  const imports = platform === 'win32'
140
151
  ? 'import aimux, aimux.bridge_client, win32_setctime'
141
152
  : 'import aimux, aimux.bridge_client'
142
- return `${imports}; assert aimux.__version__ == '${BUNDLE_AIMUX_VERSION}'`
153
+ return expected ? `${imports}; assert aimux.__version__ == '${expected}'` : imports
143
154
  }
144
155
 
145
- function bundleReady(): boolean {
156
+ function bundleReady(expected: string | null = BUNDLE_AIMUX_VERSION): boolean {
146
157
  return existsSync(bundlePython()) && spawnSync(
147
158
  bundlePython(),
148
- ['-c', bundleHealthCheckCode()],
159
+ ['-c', bundleHealthCheckCode(process.platform, expected)],
149
160
  { stdio: 'ignore', windowsHide: true },
150
161
  ).status === 0
151
162
  }
@@ -226,14 +237,14 @@ async function extractBundle(zipPath: string, onProgress?: (p: InstallProgress)
226
237
 
227
238
  /** 解压后校验内置 python 能 import aimux。用 spawn(非阻塞 spawnSync)避免冻结 Ink 渲染;
228
239
  * 60s 上限强杀(首次 import 在慢盘上可能慢,但不会无限);stderr(traceback) 落日志,让"解压完仍卡"可诊断。 */
229
- async function verifyBundle(onProgress?: (p: InstallProgress) => void): Promise<{ ok: boolean; error?: string }> {
240
+ async function verifyBundle(onProgress?: (p: InstallProgress) => void, expected: string | null = BUNDLE_AIMUX_VERSION): Promise<{ ok: boolean; error?: string }> {
230
241
  onProgress?.({ phase: 'install', detail: '校验内置运行时(首次 import aimux,可能耗时)…' })
231
242
  const py = bundlePython()
232
- logInstall(` verify start: ${py} -c "import aimux…" (expect v${BUNDLE_AIMUX_VERSION})\n`)
243
+ logInstall(` verify start: ${py} -c "import aimux…" (expect ${expected ? `v${expected}` : 'any version'})\n`)
233
244
  const startedAt = Date.now()
234
245
  return new Promise(resolve => {
235
246
  let child: ChildProcess
236
- try { child = spawn(py, ['-c', bundleHealthCheckCode()], { windowsHide: true }) }
247
+ try { child = spawn(py, ['-c', bundleHealthCheckCode(process.platform, expected)], { windowsHide: true }) }
237
248
  catch (e: any) { resolve({ ok: false, error: `校验失败: ${e?.message ?? e}` }); return }
238
249
  let stderr = ''
239
250
  const timer = setTimeout(() => { try { child.kill('SIGKILL') } catch {}; resolve({ ok: false, error: `校验超时(60s 未完成 import aimux,疑似慢盘)· 日志: ${aimuxLogPath()}` }) }, 60_000)
@@ -249,8 +260,8 @@ async function verifyBundle(onProgress?: (p: InstallProgress) => void): Promise<
249
260
  })
250
261
  }
251
262
 
252
- export async function ensureFromBundle(onProgress?: (p: InstallProgress) => void): Promise<{ ok: boolean; error?: string; launcher?: AimuxLauncher }> {
253
- if (bundleReady()) { logInstall(`bundle fast-path: python-bundle already ready\n`); return { ok: true, launcher: { kind: 'module', python: bundlePython() } } }
263
+ export async function ensureFromBundle(onProgress?: (p: InstallProgress) => void, expected: string | null = BUNDLE_AIMUX_VERSION): Promise<{ ok: boolean; error?: string; launcher?: AimuxLauncher }> {
264
+ if (bundleReady(expected)) { logInstall(`bundle fast-path: python-bundle already ready\n`); return { ok: true, launcher: { kind: 'module', python: bundlePython() } } }
254
265
  const arch = bundleArch()
255
266
  if (!arch) return { ok: false, error: `当前平台无内置运行时 (platform=${process.platform} arch=${process.arch})` }
256
267
  logInstall(`bundle install begin: arch=${arch} platform=${process.platform} home=${mobiusHome()}\n`)
@@ -261,7 +272,7 @@ export async function ensureFromBundle(onProgress?: (p: InstallProgress) => void
261
272
  const ex = await extractBundle(dl.zipPath, onProgress)
262
273
  try { await fs.unlink(dl.zipPath) } catch {}
263
274
  if (!ex.ok) return { ok: false, error: ex.error }
264
- const v = await verifyBundle(onProgress)
275
+ const v = await verifyBundle(onProgress, expected)
265
276
  if (!v.ok) return { ok: false, error: v.error ?? '内置运行时解压后仍无法 import aimux' }
266
277
  logInstall(`bundle install OK\n`)
267
278
  return { ok: true, launcher: { kind: 'module', python: bundlePython() } }
@@ -290,45 +301,114 @@ function spawnDetachedDaemon(launcher: AimuxLauncher, args: string[]): ChildProc
290
301
  /** test-only 导出: 暴露内部 downloadBundle 以便单测 mock fetch 验证流式下载+进度。 */
291
302
  export const downloadBundleForTest = downloadBundle
292
303
 
293
- /** `a >= b`(点分数字)。非数字段一律判 false,宁可重装也不要用一个看不懂的版本。 */
294
- export function versionAtLeast(a: string, b: string): boolean {
295
- const pa = a.split('.'), pb = b.split('.')
296
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
297
- const x = Number(pa[i] ?? 0), y = Number(pb[i] ?? 0)
298
- if (!Number.isFinite(x) || !Number.isFinite(y)) return false
299
- if (x !== y) return x > y
304
+ /** 某个 python 环境里的 aimux 版本(跑不起来时 null)。 */
305
+ function pythonAimuxVersion(python: string): string | null {
306
+ try {
307
+ const r = spawnSync(python, ['-c', 'import aimux; print(aimux.__version__)'], { encoding: 'utf8', windowsHide: true })
308
+ if (r.status !== 0) return null
309
+ const v = (r.stdout ?? '').trim().split(/\s+/).pop()
310
+ return v || null
311
+ } catch {
312
+ return null
300
313
  }
301
- return true
302
314
  }
303
315
 
304
316
  /** venv 里现成的 aimux 版本(跑不起来时 null)。 */
305
317
  function installedAimuxVersion(): string | null {
306
318
  if (!existsSync(aimuxExe()) || !existsSync(venvPython())) return null
319
+ return pythonAimuxVersion(venvPython())
320
+ }
321
+
322
+ /**
323
+ * 连接前要装的版本:**服务端 broker 跑的那个版本**。
324
+ *
325
+ * 服务端版本读不到(老 broker 没有 /api/health 的 version 字段、或网络不通)时退回 pin——
326
+ * 宁可不动,也不要凭猜测给用户换一个版本。
327
+ */
328
+ export function alignTarget(serverVersion: string | null | undefined, pin = AIMUX_TARGET_VERSION): string {
329
+ const v = typeof serverVersion === 'string' ? serverVersion.trim() : ''
330
+ return v || pin
331
+ }
332
+
333
+ /**
334
+ * 读服务端 broker 的 aimux 版本(`GET <server>/aimux_bridge/api/health`)。
335
+ * 经 mobius 代理转发:这里带的 token 是登录 JWT,代理会换成 broker token。
336
+ * 任何失败都返回 null —— 读不到就按"未知"处理,绝不猜。
337
+ */
338
+ export async function fetchServerAimuxVersion(server: string, token: string, timeoutMs = 8_000): Promise<string | null> {
339
+ const url = `${server.replace(/\/$/, '')}/aimux_bridge/api/health`
340
+ const controller = new AbortController()
341
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
307
342
  try {
308
- const r = spawnSync(venvPython(), ['-c', 'import aimux; print(aimux.__version__)'], { encoding: 'utf8', windowsHide: true })
309
- if (r.status !== 0) return null
310
- const v = (r.stdout ?? '').trim().split(/\s+/).pop()
343
+ const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` }, signal: controller.signal })
344
+ if (!res.ok) { logInstall(`server aimux version probe: HTTP ${res.status} (${url})\n`); return null }
345
+ const body: any = await res.json().catch(() => null)
346
+ const v = typeof body?.version === 'string' ? body.version.trim() : ''
347
+ if (!v) logInstall(`server aimux version probe: no version field (${url})\n`)
311
348
  return v || null
312
- } catch {
349
+ } catch (e: any) {
350
+ logInstall(`server aimux version probe failed (${url}): ${e?.name === 'AbortError' ? 'timeout' : e?.message ?? e}\n`)
313
351
  return null
314
- }
352
+ } finally { clearTimeout(timer) }
315
353
  }
316
354
 
317
355
  /**
318
- * pin 是**最低可用版本**,不是精确版本:比它新的直接沿用。
319
- * 否则用户 `/upgrade` 到 PyPI 最新版后,下一次连接(乃至下次启动)会被拽回 pin,
320
- * 升级看着"没生效"。
356
+ * 把某个 python 环境里的 aimux 换成指定版本。pip 装 `aimux==X` 自己会卸掉当前版本,
357
+ * 所以**升级和降级是同一条命令**,不需要先卸载、更不需要重建 venv。
321
358
  */
322
- function venvReady(): boolean {
323
- const installed = installedAimuxVersion()
324
- return installed !== null && versionAtLeast(installed, AIMUX_TARGET_VERSION)
359
+ async function swapAimuxVersion(python: string, target: string, current: string, onProgress?: (p: InstallProgress) => void): Promise<{ ok: boolean; error?: string }> {
360
+ logInstall(`aimux version swap ${current} → ${target} via ${python}\n`)
361
+ onProgress?.({ phase: 'install', detail: `切换 AIMUX ${current} → ${target}…` })
362
+ const r = await run(python, [
363
+ '-m', 'pip', 'install', '--no-input', '--disable-pip-version-check', `aimux==${target}`,
364
+ ], line => {
365
+ if (/downloading|collecting|installing|uninstalling|using cached|%\s*\d|━|─/i.test(line)) onProgress?.({ phase: 'install', detail: line.slice(0, 120) })
366
+ })
367
+ if (r.code !== 0) return { ok: false, error: `pip install 失败: ${(r.stderr || r.stdout).slice(-300)}` }
368
+ const after = pythonAimuxVersion(python)
369
+ if (after !== target) return { ok: false, error: `装完仍是 ${after ?? '(无法读取版本)'}` }
370
+ logInstall(`aimux version swap OK → ${after}\n`)
371
+ return { ok: true }
325
372
  }
326
373
 
327
- export async function ensureAimux(onProgress?: (p: InstallProgress) => void): Promise<{ ok: boolean; error?: string; launcher?: AimuxLauncher }> {
328
- // Fast-path:venv 里已有 aimux 可执行 → 直接用。
329
- const existing = venvReady() ? installedAimuxVersion() : null
330
- if (existing) { logInstall(`ensureAimux fast-path: venv aimux ${existing} present (pin ${AIMUX_TARGET_VERSION})\n`); onProgress?.({ phase: 'ready' }); return { ok: true, launcher: { kind: 'exe', path: aimuxExe() } } }
374
+ /** ensureAimux 的结果;`versionWarning` = 想对齐但没成,已按现有版本继续。 */
375
+ export interface AimuxReady {
376
+ ok: boolean
377
+ error?: string
378
+ launcher?: AimuxLauncher
379
+ /** 实际会用上的版本。 */
380
+ version?: string
381
+ versionWarning?: string
382
+ }
383
+
384
+ /**
385
+ * 保证本地有一个能跑的 aimux,且版本恰好是 `target`。
386
+ *
387
+ * `target` 默认是 pin;连接时上层传的是**服务端 broker 的版本**(见 alignTarget),
388
+ * 所以本地比服务端新也会被换下去——版本不匹配本身就会让 bridge 出各种怪问题。
389
+ * 换版本失败不阻断连接:记一条 `versionWarning`,按现有版本继续。
390
+ */
391
+ export async function ensureAimux(onProgress?: (p: InstallProgress) => void, target = AIMUX_TARGET_VERSION): Promise<AimuxReady> {
392
+ // Fast-path:版本正好对上 → 直接用。
393
+ const existing = installedAimuxVersion()
394
+ if (existing === target) {
395
+ logInstall(`ensureAimux fast-path: venv aimux ${existing} == target ${target}\n`)
396
+ onProgress?.({ phase: 'ready' })
397
+ return { ok: true, launcher: { kind: 'exe', path: aimuxExe() }, version: existing }
398
+ }
399
+ // 手上已经有 venv,只是版本不对 → 原地换版本(升级/降级同一条路)。
400
+ if (existing !== null) {
401
+ const swap = await swapAimuxVersion(venvPython(), target, existing, onProgress)
402
+ if (swap.ok) { onProgress?.({ phase: 'ready' }); return { ok: true, launcher: { kind: 'exe', path: aimuxExe() }, version: target } }
403
+ logInstall(`########## ensureAimux version swap failed: ${swap.error};按现有 ${existing} 继续 ##########\n`)
404
+ onProgress?.({ phase: 'ready' })
405
+ return {
406
+ ok: true, launcher: { kind: 'exe', path: aimuxExe() }, version: existing,
407
+ versionWarning: `AIMUX 版本未对齐:本地 ${existing}/目标 ${target}(${swap.error})`,
408
+ }
409
+ }
331
410
  logInstall(`\n########## ensureAimux install begin ${new Date().toISOString()} platform=${process.platform} arch=${process.arch} home=${mobiusHome()} ##########\n`)
411
+ const pkg = `aimux==${target}`
332
412
  const py = await pythonForAimux(onProgress)
333
413
  logInstall(` pythonForAimux → ${py ?? '(null: no system python)'}\n`)
334
414
  let venvError = '未找到 Python。请先安装 Python 3.10+(或安装 uv 后重试)。'
@@ -337,11 +417,11 @@ export async function ensureAimux(onProgress?: (p: InstallProgress) => void): Pr
337
417
  let r = await run(py, ['-m', 'venv', venvDir()])
338
418
  if (r.code !== 0 && py === 'py') r = await run(py, ['-3', '-m', 'venv', venvDir()])
339
419
  if (r.code === 0) {
340
- onProgress?.({ phase: 'install', detail: `下载并安装 ${AIMUX_PACKAGE}…` })
341
- r = await run(venvPython(), ['-m', 'pip', 'install', '--no-input', '--disable-pip-version-check', AIMUX_PACKAGE], line => {
342
- if (/downloading|collecting|installing|using cached|%\s*\d|━|─/i.test(line)) onProgress?.({ phase: 'install', detail: line.slice(0, 120) })
420
+ onProgress?.({ phase: 'install', detail: `下载并安装 ${pkg}…` })
421
+ r = await run(venvPython(), ['-m', 'pip', 'install', '--no-input', '--disable-pip-version-check', pkg], line => {
422
+ if (/downloading|collecting|installing|uninstalling|using cached|%\s*\d|━|─/i.test(line)) onProgress?.({ phase: 'install', detail: line.slice(0, 120) })
343
423
  })
344
- if (r.code === 0 && existsSync(aimuxExe())) { onProgress?.({ phase: 'ready' }); return { ok: true, launcher: { kind: 'exe', path: aimuxExe() } } }
424
+ if (r.code === 0 && existsSync(aimuxExe())) { onProgress?.({ phase: 'ready' }); return { ok: true, launcher: { kind: 'exe', path: aimuxExe() }, version: pythonAimuxVersion(venvPython()) ?? target } }
345
425
  venvError = r.code === 0 ? `aimux 可执行未生成: ${aimuxExe()}` : `pip install 失败: ${r.stderr || r.stdout}`
346
426
  } else {
347
427
  venvError = `venv 创建失败: ${r.stderr || r.stdout}`
@@ -350,8 +430,24 @@ export async function ensureAimux(onProgress?: (p: InstallProgress) => void): Pr
350
430
  // ── Plan B 兜底:本地 python/venv 不可用 → 下载内置 python+aimux 运行时 ──
351
431
  logInstall(` venv path failed (${venvError || ''}) → falling back to bundle\n`)
352
432
  onProgress?.({ phase: 'install', detail: '本地 Python 不可用,改用内置运行时…' })
353
- const bundle = await ensureFromBundle(onProgress)
354
- if (bundle.ok && bundle.launcher) { onProgress?.({ phase: 'ready' }); return { ok: true, launcher: bundle.launcher } }
433
+ // 目标就是 pin 时仍按老规矩校验包内版本(版本不对就重下整包);目标是服务端版本时
434
+ // 只要求包能 import,随后用 pip 就地换成目标版本——否则每次都得重下整包还会校验失败。
435
+ const expected = target === AIMUX_TARGET_VERSION ? BUNDLE_AIMUX_VERSION : null
436
+ const bundle = await ensureFromBundle(onProgress, expected)
437
+ if (bundle.ok && bundle.launcher) {
438
+ const py2 = bundle.launcher.kind === 'module' ? bundle.launcher.python : null
439
+ const bundled = py2 ? pythonAimuxVersion(py2) : null
440
+ if (py2 && bundled !== null && bundled !== target) {
441
+ const swap = await swapAimuxVersion(py2, target, bundled, onProgress)
442
+ if (!swap.ok) {
443
+ logInstall(`########## bundle version swap failed: ${swap.error};按现有 ${bundled} 继续 ##########\n`)
444
+ onProgress?.({ phase: 'ready' })
445
+ return { ok: true, launcher: bundle.launcher, version: bundled, versionWarning: `内置运行时 AIMUX 未对齐:本地 ${bundled}/目标 ${target}(${swap.error})` }
446
+ }
447
+ }
448
+ onProgress?.({ phase: 'ready' })
449
+ return { ok: true, launcher: bundle.launcher, version: py2 ? pythonAimuxVersion(py2) ?? undefined : undefined }
450
+ }
355
451
  logInstall(`########## ensureAimux FAILED: ${venvError};内置运行时也失败: ${bundle.error} ##########\n`)
356
452
  return { ok: false, error: `${venvError};内置运行时也失败: ${bundle.error}` }
357
453
  }
@@ -923,6 +1019,14 @@ let supervisor: AimuxSupervisor | null = null
923
1019
  let installing: Promise<void> | null = null
924
1020
  /** 上一次 startAimuxConnection 的参数,供 `/upgrade` 重装后原地重连。 */
925
1021
  let lastStartOpts: StartOptions | null = null
1022
+ /**
1023
+ * `/upgrade` 显式装了 PyPI 最新版之后,跳过**下一次**连接时的版本对齐。
1024
+ * 否则刚升级完的那次重连会立刻把它拽回服务端版本,用户看到的是"升级没生效"。
1025
+ * 只跳过一次:下次启动 TUI 仍然对齐。
1026
+ */
1027
+ let skipAutoAlignOnce = false
1028
+ /** 实际装着的 aimux 版本,供状态行显示(自动对齐后可能和 pin 不同)。 */
1029
+ let runtimeAimuxVersion: string | null = null
926
1030
 
927
1031
  interface StartOptions {
928
1032
  server: string
@@ -1002,12 +1106,30 @@ export async function startAimuxConnection(opts: StartOptions): Promise<void> {
1002
1106
  lastStartOpts = opts
1003
1107
  installing = (async () => {
1004
1108
  onStatus({ state: 'starting', phase: 'python', detail: '检查 Python 与 AIMUX 运行环境…' })
1109
+ // 连接前先读服务端 broker 的 aimux 版本:不一致就把本地换成同一个版本(升、降都算)。
1110
+ // 读不到服务端版本时退回 pin —— 见 alignTarget。
1111
+ const skipAlign = skipAutoAlignOnce
1112
+ skipAutoAlignOnce = false
1113
+ const installedBefore = installedAimuxVersion()
1114
+ const serverVersion = skipAlign ? null : await fetchServerAimuxVersion(opts.server, opts.token)
1115
+ const target = skipAlign ? (installedBefore ?? AIMUX_TARGET_VERSION) : alignTarget(serverVersion)
1116
+ logInstall(`aimux target=${target} server=${serverVersion ?? '(unknown)'} pin=${AIMUX_TARGET_VERSION} installed=${installedBefore ?? '(none)'}${skipAlign ? ' (auto-align skipped once after /upgrade)' : ''}\n`)
1005
1117
  const ready = await ensureAimux(p => onStatus({
1006
1118
  state: 'starting',
1007
1119
  phase: p.phase === 'ready' ? 'connecting' : p.phase,
1008
1120
  detail: p.detail || (p.phase === 'ready' ? 'AIMUX 已就绪,准备连接…' : p.phase),
1009
- }))
1121
+ }), target)
1010
1122
  if (!ready.ok || !ready.launcher) { logInstall(`startAimuxConnection giving up: ${ready.error}\n`); onStatus({ state: 'failed', phase: 'idle', detail: `${ready.error} · 日志: ${aimuxLogPath()}` }); return }
1123
+ if (ready.versionWarning) { logInstall(`########## ${ready.versionWarning} ##########\n`); onStatus({ state: 'starting', phase: 'connecting', detail: ready.versionWarning }) }
1124
+ // 状态行显示的版本跟实际装的一致(自动对齐后可能和 pin 不同)。
1125
+ runtimeAimuxVersion = ready.version ?? null
1126
+ const emit = (s: AimuxStatus): void => onStatus({ ...s, version: s.version ?? runtimeAimuxVersion ?? undefined })
1127
+ // 版本被换过 → 上次探测到的命令行开关不再可信,且旧的守护进程还跑着老版本。
1128
+ if (installedBefore !== null && ready.version !== undefined && ready.version !== installedBefore) {
1129
+ logInstall(`aimux ${installedBefore} → ${ready.version}: re-probing flags and dropping the old daemon\n`)
1130
+ cachedSilentFlag = undefined; cachedEnableGui = undefined; cachedGuiNoElevate = undefined
1131
+ await stopDaemonFromRuntime()
1132
+ }
1011
1133
  const identifier = tuiAimuxIdentifier()
1012
1134
  const launcher = ready.launcher
1013
1135
  // Windows only: ask the installed aimux which console-hiding flag it accepts
@@ -1030,7 +1152,7 @@ export async function startAimuxConnection(opts: StartOptions): Promise<void> {
1030
1152
  const gui = resolvedGuiArgs()
1031
1153
  logInstall(`GUI mode ${tuiGuiMode()} → ${gui.enableGui ? (gui.guiNoElevate ? '--enable-gui --gui-no-elevate (no UAC)' : '--enable-gui (UAC on Windows)') : 'no GUI flags'}\n`)
1032
1154
  supervisor = new AimuxSupervisor({
1033
- server: opts.server, token: opts.token, identifier, onStatus, refreshToken: opts.refreshToken,
1155
+ server: opts.server, token: opts.token, identifier, onStatus: emit, refreshToken: opts.refreshToken,
1034
1156
  spawnProcess: token => spawnDetachedDaemon(launcher, reverseConnectArgs(opts.server, identifier, token, process.platform, silentFlag, runtimePath(aimuxWorkspaceHash()), gui.enableGui, gui.guiNoElevate)),
1035
1157
  })
1036
1158
  await supervisor.start()
@@ -1135,6 +1257,8 @@ export async function upgradeAimuxRuntime(): Promise<{ ok: boolean; version?: st
1135
1257
  return { ok: false, error: installed.error }
1136
1258
  }
1137
1259
  onStatus({ state: 'starting', phase: 'connecting', detail: `AIMUX ${installed.version ?? '最新版'} 已安装,正在重新连接…` })
1260
+ // 这次重连不把刚升上去的版本又对齐回服务端版本(见 skipAutoAlignOnce)。
1261
+ skipAutoAlignOnce = true
1138
1262
  await startAimuxConnection(opts)
1139
1263
  return { ok: true, version: installed.version }
1140
1264
  }
@@ -7,7 +7,7 @@ import os from 'node:os'
7
7
  import path from 'node:path'
8
8
  import { render } from 'ink-testing-library'
9
9
  import { AimuxStatusLine } from '../src/components/AimuxStatus.js'
10
- import { AimuxSupervisor, probeAimuxBridgeConnection, BUNDLE_VER, bundleArch, bundleUrl, spawnLauncher, ensureFromBundle, downloadBundleForTest, reverseConnectArgs, pickSilentFlag, versionAtLeast, aimuxLogPath, bundleHealthCheckCode, tuiAimuxIdentifier, AIMUX_VERSION, tuiGuiAuthorized, setTuiGuiAuthorized, pickEnableGuiFlag, pickGuiNoElevateFlag, tuiGuiMode, tuiGuiNoElevate, setTuiGuiMode, readGuiModeForTest, pidAlive, aimuxWorkspaceHash, guiModeAvailability, guiModeOptions, pickGuiArgs, hasGuiSupport, effectiveGuiMode } from '../src/aimux.js'
10
+ import { AimuxSupervisor, probeAimuxBridgeConnection, BUNDLE_VER, bundleArch, bundleUrl, spawnLauncher, ensureFromBundle, ensureAimux, downloadBundleForTest, reverseConnectArgs, pickSilentFlag, alignTarget, fetchServerAimuxVersion, aimuxLogPath, bundleHealthCheckCode, tuiAimuxIdentifier, AIMUX_VERSION, tuiGuiAuthorized, setTuiGuiAuthorized, pickEnableGuiFlag, pickGuiNoElevateFlag, tuiGuiMode, tuiGuiNoElevate, setTuiGuiMode, readGuiModeForTest, pidAlive, aimuxWorkspaceHash, guiModeAvailability, guiModeOptions, pickGuiArgs, hasGuiSupport, effectiveGuiMode } from '../src/aimux.js'
11
11
  import { parseElevatedGroups } from '../src/lib/windows-admin.js'
12
12
 
13
13
  const delay = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms))
@@ -459,16 +459,15 @@ function testGuiModeAvailability() {
459
459
  ok(effectiveGuiMode('elevate', false, 'darwin') === 'elevate', 'macOS is unaffected')
460
460
  }
461
461
 
462
- function testVersionAtLeast() {
463
- console.log('\n[AIMUX 6e] aimux pin is a floor, not an exact match')
464
- // /upgrade 装的是 PyPI 最新版,通常比 pin 新;不能被 pin 校验判成"没装好"又拽回去。
465
- ok(versionAtLeast('0.3.62', '0.3.61'), 'newer aimux satisfies the pinned floor')
466
- ok(versionAtLeast('0.3.61', '0.3.61'), 'exactly the pinned version satisfies the floor')
467
- ok(versionAtLeast('0.4.0', '0.3.61'), 'a newer minor satisfies the floor')
468
- ok(!versionAtLeast('0.3.60', '0.3.61'), 'an older aimux is still reinstalled')
469
- ok(!versionAtLeast('0.1.40', '0.3.61'), 'the old 0.1.x line is still reinstalled')
470
- ok(versionAtLeast('0.3.61.1', '0.3.61'), 'a longer version string compares by segment')
471
- ok(!versionAtLeast('garbage', '0.3.61'), 'an unparseable version is treated as not-ready')
462
+ function testAlignTarget() {
463
+ console.log('\n[AIMUX 6e] connect-time version target: the server wins, in both directions')
464
+ // 连接时读服务端 broker 的 aimux 版本,本地跟它对齐 —— 比 pin 新就升,比 pin 老就降。
465
+ ok(alignTarget('0.3.72', '0.3.61') === '0.3.72', 'a server newer than the pin is the target (upgrade)')
466
+ ok(alignTarget('0.3.60', '0.3.61') === '0.3.60', 'a server older than the pin is the target too (downgrade)')
467
+ ok(alignTarget(null) === AIMUX_VERSION, 'an unknown server version falls back to the pin')
468
+ ok(alignTarget(undefined) === AIMUX_VERSION, 'a missing server version falls back to the pin')
469
+ ok(alignTarget(' ') === AIMUX_VERSION, 'a blank server version falls back to the pin')
470
+ ok(alignTarget('0.3.71', '0.3.71') === '0.3.71', 'an exact match targets that same version (no swap happens)')
472
471
  }
473
472
 
474
473
  function testAimuxIdentifierScopesWorkspace() {
@@ -486,10 +485,90 @@ function testBundleHealthCheck() {
486
485
  const win = bundleHealthCheckCode('win32')
487
486
  const linux = bundleHealthCheckCode('linux')
488
487
  ok(win.includes('aimux.bridge_client') && win.includes('win32_setctime'), 'Windows bundle probe imports the real bridge path and its platform dependency')
489
- ok(win.includes(`aimux.__version__ == '${AIMUX_VERSION}'`), 'bundle probe rejects stale AIMUX versions')
488
+ ok(win.includes(`aimux.__version__ == '${AIMUX_VERSION}'`), 'bundle probe pins the expected AIMUX version by default')
489
+ ok(!bundleHealthCheckCode('linux', null).includes('__version__'), 'a null expectation only asks the bundle to import aimux (the swap happens through pip)')
490
490
  ok(!linux.includes('win32_setctime'), 'non-Windows bundle probe does not require the Windows-only package')
491
491
  }
492
492
 
493
+ async function testFetchServerAimuxVersion() {
494
+ console.log('\n[AIMUX 6f] the broker reports the aimux version it runs')
495
+ const realFetch = globalThis.fetch
496
+ const seen: Array<{ url: string; auth: string }> = []
497
+ const respond = (body: unknown, status = 200) => (async (url: any, init: any) => {
498
+ seen.push({ url: String(url), auth: String(init?.headers?.Authorization ?? '') })
499
+ return new Response(typeof body === 'string' ? body : JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })
500
+ }) as typeof fetch
501
+ try {
502
+ globalThis.fetch = respond({ ok: true, version: '0.3.61' })
503
+ ok(await fetchServerAimuxVersion('https://mobius.test/', 'jwt-token') === '0.3.61', 'the version comes from /aimux_bridge/api/health')
504
+ ok(seen[0].url === 'https://mobius.test/aimux_bridge/api/health', 'a trailing slash on the server URL is not doubled')
505
+ ok(seen[0].auth === 'Bearer jwt-token', 'the probe sends the caller token')
506
+ globalThis.fetch = respond({ ok: true })
507
+ ok(await fetchServerAimuxVersion('https://mobius.test', 'jwt-token') === null, 'an older broker without a version field reads as unknown')
508
+ globalThis.fetch = respond('gateway said no', 502)
509
+ ok(await fetchServerAimuxVersion('https://mobius.test', 'jwt-token') === null, 'a gateway error reads as unknown instead of throwing')
510
+ globalThis.fetch = (async () => { throw new Error('offline') }) as typeof fetch
511
+ ok(await fetchServerAimuxVersion('https://mobius.test', 'jwt-token') === null, 'a network failure reads as unknown instead of throwing')
512
+ } finally { globalThis.fetch = realFetch }
513
+ }
514
+
515
+ /** 假 venv:`python -c import aimux` 读版本文件,`python -m pip install aimux==X` 改它。 */
516
+ async function fakeVenv(home: string, version: string | null, failInstall = false) {
517
+ const bin = path.join(home, 'aimux-venv', 'bin')
518
+ await fs.mkdir(bin, { recursive: true })
519
+ const state = path.join(home, 'aimux-version')
520
+ await fs.writeFile(state, version ?? '', 'utf8')
521
+ const script = [
522
+ '#!/bin/sh',
523
+ 'state="' + state + '"',
524
+ 'case "$*" in',
525
+ ' *"import aimux"*) [ -s "$state" ] && cat "$state" || exit 1 ;;',
526
+ ' *"pip install"*)',
527
+ failInstall ? ' echo "ERROR: no matching distribution" >&2; exit 1 ;;' :
528
+ ' for a in "$@"; do case "$a" in aimux==*) printf "%s" "${a#aimux==}" > "$state" ;; esac; done; echo "Successfully installed aimux" ;;',
529
+ ' *) exit 0 ;;',
530
+ 'esac',
531
+ ].join('\n') + '\n'
532
+ await fs.writeFile(path.join(bin, 'python'), script, { mode: 0o755 })
533
+ await fs.writeFile(path.join(bin, 'aimux'), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
534
+ return { version: () => fs.readFile(state, 'utf8').then(v => v.trim()) }
535
+ }
536
+
537
+ async function testEnsureAimuxVersionSwap() {
538
+ console.log('\n[AIMUX 6g] connecting swaps the local aimux to the server version')
539
+ for (const [installed, target, what] of [['0.3.60', '0.3.71', 'upgrade'], ['0.3.72', '0.3.71', 'downgrade']] as const) {
540
+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'mobius-tui-swap-'))
541
+ const savedHome = process.env.MOBIUS_TUI_HOME
542
+ process.env.MOBIUS_TUI_HOME = home
543
+ try {
544
+ const fake = await fakeVenv(home, installed)
545
+ const r = await ensureAimux(undefined, target)
546
+ ok(r.ok && r.version === target, `${what}: ensureAimux(${target}) over ${installed} reports the new version`)
547
+ ok(await fake.version() === target, `${what}: pip install aimux==${target} actually ran`)
548
+ ok(!r.versionWarning, `${what}: no warning when the swap succeeds`)
549
+ } finally { if (savedHome === undefined) delete process.env.MOBIUS_TUI_HOME; else process.env.MOBIUS_TUI_HOME = savedHome; await fs.rm(home, { recursive: true, force: true }) }
550
+ }
551
+
552
+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'mobius-tui-swap-'))
553
+ const savedHome = process.env.MOBIUS_TUI_HOME
554
+ process.env.MOBIUS_TUI_HOME = home
555
+ try {
556
+ // 版本已经对上 → 不跑 pip。
557
+ const same = await fakeVenv(home, '0.3.71')
558
+ const r = await ensureAimux(undefined, '0.3.71')
559
+ ok(r.ok && r.version === '0.3.71', 'an exact match is reused as-is')
560
+ ok(!r.versionWarning, 'an exact match needs no warning')
561
+ await fs.rm(path.join(home, 'aimux-venv'), { recursive: true, force: true })
562
+ // 换不动(PyPI 上没这个版本 / 断网)→ 按现有版本继续,只记一条 warning。
563
+ const failing = await fakeVenv(home, '0.3.70', true)
564
+ const bad = await ensureAimux(undefined, '0.3.99')
565
+ ok(bad.ok && bad.version === '0.3.70', 'a failed swap keeps the installed version and still connects')
566
+ ok(!!bad.versionWarning && bad.versionWarning.includes('0.3.99'), 'a failed swap reports what could not be aligned')
567
+ ok(await failing.version() === '0.3.70', 'a failed swap leaves the installed version untouched')
568
+ void same
569
+ } finally { if (savedHome === undefined) delete process.env.MOBIUS_TUI_HOME; else process.env.MOBIUS_TUI_HOME = savedHome; await fs.rm(home, { recursive: true, force: true }) }
570
+ }
571
+
493
572
  async function testEnsureFromBundleReady() {
494
573
  console.log('\n[AIMUX 7] Plan B ensureFromBundle fast-path (bundle already extracted)')
495
574
  const home = await fs.mkdtemp(path.join(os.tmpdir(), 'mobius-tui-bundle-'))
@@ -550,7 +629,9 @@ async function main() {
550
629
  await testGuiModes()
551
630
  testElevationDetection()
552
631
  testGuiModeAvailability()
553
- testVersionAtLeast()
632
+ testAlignTarget()
633
+ await testFetchServerAimuxVersion()
634
+ await testEnsureAimuxVersionSwap()
554
635
  testAimuxIdentifierScopesWorkspace()
555
636
  testBundleHealthCheck()
556
637
  await testEnsureFromBundleReady()