@mobius-os/mobius 0.3.69 → 0.3.73

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/install.ps1 CHANGED
@@ -6,10 +6,11 @@
6
6
  下载 portable Node win-x64 zip 解压到 ~/.mobius/node-portable/ → 用 node.exe 直跑 npm-cli.js
7
7
  装 @mobius-os/mobius 到 ~/.mobius/npm-global/ → 自建 mobius.cmd 启动器(绝对路径指向便携 node)
8
8
  → 加 ~/.mobius/bin 到用户 PATH (无需 admin)。
9
- npm 安装和 mobius 启动均直接使用 node.exe/tsx;安装完成后同时注册两个
10
- Explorer 右键入口:“在 Mobius 中打开”(文件夹本身 + 文件夹空白处)。
9
+ npm 安装和 mobius 启动均直接使用 node.exe/tsx;安装完成后在文件夹本身和
10
+ 文件夹空白处注册两个 Explorer 右键入口:“在Mobius终端中打开”与
11
+ “在Mobius终端中打开(管理员权限)”。
11
12
  .EXAMPLE
12
- irm https://serve.nutshellai.cn/publish/auto/mobiustui/install-v15.ps1 | iex
13
+ irm https://serve.nutshellai.cn/publish/auto/mobiustui/install-v16.ps1 | iex
13
14
  #>
14
15
  $ErrorActionPreference = 'Stop'
15
16
  $ProgressPreference = 'SilentlyContinue'
@@ -206,9 +207,10 @@ if ($userPath -notlike "*$binDir*") {
206
207
  }
207
208
 
208
209
  # --- 5. Explorer 右键菜单 (当前用户,无需 admin) ----------------------------
209
- # 两个入口必须同时注册:
210
+ # 两套入口,各注册两个位置:
210
211
  # Directory\shell\Mobius = 右键文件夹本身,目标参数 %1
211
212
  # Directory\Background\shell\Mobius = 右键文件夹空白处,目标参数 %V
213
+ # ...\MobiusAdmin = 同样的两处,UAC 提权后启动(管理员权限)
212
214
  # 使用 .cmd 辅助启动器,避免右键动作依赖 PowerShell ExecutionPolicy。
213
215
  $openHereCmd = Join-Path $binDir "mobius-open-here.cmd"
214
216
  $openHereLines = @(
@@ -222,38 +224,65 @@ $openHereLines = @(
222
224
  )
223
225
  Set-Content -Path $openHereCmd -Value $openHereLines -Encoding ASCII
224
226
 
227
+ # 管理员入口: Explorer 直接跑这个脚本, 由它用 UAC 提权拉起同一个启动器.
228
+ # -Encoding UTF8 在 Windows PowerShell 5.1 会写入 BOM, -File 才能正确读中文/引号.
229
+ $openHereAdminPs1 = Join-Path $binDir "mobius-open-here-admin.ps1"
230
+ $openHereAdminLines = @(
231
+ 'param([string]$Target)',
232
+ '# 右键文件夹时 Explorer 会传路径, 兜底用当前目录.',
233
+ 'if (-not $Target) { $Target = (Get-Location).Path }',
234
+ 'Start-Process -FilePath (Join-Path $PSScriptRoot ''mobius-open-here.cmd'') -ArgumentList (''"{0}"'' -f $Target) -Verb RunAs'
235
+ )
236
+ Set-Content -Path $openHereAdminPs1 -Value $openHereAdminLines -Encoding UTF8
237
+
225
238
  $classes = "HKCU:\Software\Classes"
226
239
  $folderMenu = Join-Path $classes "Directory\shell\Mobius"
227
240
  $folderCommand = Join-Path $folderMenu "command"
228
241
  $backgroundMenu = Join-Path $classes "Directory\Background\shell\Mobius"
229
242
  $backgroundCommand = Join-Path $backgroundMenu "command"
243
+ $folderAdminMenu = Join-Path $classes "Directory\shell\MobiusAdmin"
244
+ $folderAdminCommand = Join-Path $folderAdminMenu "command"
245
+ $backgroundAdminMenu = Join-Path $classes "Directory\Background\shell\MobiusAdmin"
246
+ $backgroundAdminCommand = Join-Path $backgroundAdminMenu "command"
230
247
 
231
- foreach ($key in @($folderCommand, $backgroundCommand)) {
248
+ foreach ($key in @($folderCommand, $backgroundCommand, $folderAdminCommand, $backgroundAdminCommand)) {
232
249
  New-Item -Path $key -Force | Out-Null
233
250
  }
234
251
 
235
252
  foreach ($menu in @($folderMenu, $backgroundMenu)) {
236
- Set-ItemProperty -Path $menu -Name "MUIVerb" -Value "在 Mobius 中打开"
253
+ Set-ItemProperty -Path $menu -Name "MUIVerb" -Value "在Mobius终端中打开"
237
254
  Set-ItemProperty -Path $menu -Name "Icon" -Value "$env:SystemRoot\System32\cmd.exe,0"
238
255
  }
256
+ foreach ($menu in @($folderAdminMenu, $backgroundAdminMenu)) {
257
+ Set-ItemProperty -Path $menu -Name "MUIVerb" -Value "在Mobius终端中打开(管理员权限)"
258
+ Set-ItemProperty -Path $menu -Name "Icon" -Value "$env:SystemRoot\System32\cmd.exe,0"
259
+ # 空字符串的 HasLUAShield 让 Explorer 在菜单项旁边显示 UAC 盾牌.
260
+ Set-ItemProperty -Path $menu -Name "HasLUAShield" -Value ""
261
+ }
239
262
 
240
263
  # Explorer command quoting: cmd /c ""helper.cmd" "%1"".
241
264
  $folderCommandValue = '"{0}" /d /s /c ""{1}" "%1""' -f $env:ComSpec, $openHereCmd
242
265
  $backgroundCommandValue = '"{0}" /d /s /c ""{1}" "%V""' -f $env:ComSpec, $openHereCmd
243
266
  Set-Item -Path $folderCommand -Value $folderCommandValue
244
267
  Set-Item -Path $backgroundCommand -Value $backgroundCommandValue
245
- Ok "右键菜单已添加: 在 Mobius 中打开 (文件夹 + 空白处)"
268
+
269
+ # 管理员入口: 隐藏中间窗口跑 .ps1, 提权后的终端窗口由 Start-Process 拉起.
270
+ $folderAdminCommandValue = 'powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "{0}" "%1"' -f $openHereAdminPs1
271
+ $backgroundAdminCommandValue = 'powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "{0}" "%V"' -f $openHereAdminPs1
272
+ Set-Item -Path $folderAdminCommand -Value $folderAdminCommandValue
273
+ Set-Item -Path $backgroundAdminCommand -Value $backgroundAdminCommandValue
274
+ Ok "右键菜单已添加: 在Mobius终端中打开 + 在Mobius终端中打开(管理员权限)(文件夹 + 空白处)"
246
275
 
247
276
  Write-Host ""
248
277
  Write-Host "=== 完成! 重开 PowerShell 后运行: mobius ===" -ForegroundColor Green
249
278
  Write-Host "(或直接运行: $mobiusCmd)" -ForegroundColor Gray
250
- Write-Host "右键文件夹或文件夹空白处,可选择: 在 Mobius 中打开" -ForegroundColor Gray
279
+ Write-Host "右键文件夹或文件夹空白处,可选择: 在Mobius终端中打开 / 在Mobius终端中打开(管理员权限)" -ForegroundColor Gray
251
280
  }
252
281
 
253
282
  try {
254
283
  Invoke-MobiusInstall
255
284
  } catch {
256
- $errorLog = Join-Path $env:TEMP "mobius-install-v15-error.log"
285
+ $errorLog = Join-Path $env:TEMP "mobius-install-v16-error.log"
257
286
  $errorText = $_ | Format-List * -Force | Out-String
258
287
  $errorText | Set-Content -Path $errorLog -Encoding UTF8
259
288
  Write-Host ""
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.73",
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
  }
@@ -32,6 +32,10 @@ import {
32
32
  setTuiGuiMode, tuiAimuxIdentifier, tuiGuiAuthorized, tuiGuiMode, type GuiMode,
33
33
  } from '../aimux.js'
34
34
  import { windowsElevated } from '../lib/windows-admin.js'
35
+ import {
36
+ CREATE_ITEM_ICON, EASY_DEFAULT_ISSUE_TITLE, EASY_DEFAULT_PROJECT_NAME,
37
+ EASY_ISSUE_LABEL, EASY_PROJECT_LABEL, ISSUE_ITEM_ICON, PROJECT_ITEM_ICON,
38
+ } from '../easy-mode-defaults.js'
35
39
  import type { Issue, Project, SessionModelOption } from '../types.js'
36
40
 
37
41
  export interface ConfigResult {
@@ -161,6 +165,10 @@ export function ReconfigFlow({ client, onDone, onCancel, platform = process.plat
161
165
  const [createMode, setCreateMode] = useState<'project' | 'issue' | null>(null)
162
166
  const doneRef = useRef(false)
163
167
  const thisCwd = cwd()
168
+ // 快捷任务/日常会话置顶, 不存在时选中即创建
169
+ // Pin the easy defaults on top; picking a missing one creates it on demand.
170
+ const pinnedProject = (projects ?? []).find(p => p.name === EASY_DEFAULT_PROJECT_NAME) ?? null
171
+ const pinnedIssue = (issues ?? []).find(i => i.title === EASY_DEFAULT_ISSUE_TITLE) ?? null
164
172
 
165
173
  function goBack() {
166
174
  // The focused TextInput owns Esc while a create form is open. Returning
@@ -375,11 +383,19 @@ export function ReconfigFlow({ client, onDone, onCancel, platform = process.plat
375
383
  ? <Text color="cyan">加载项目列表…</Text>
376
384
  : <Select
377
385
  items={[
378
- { label: '➕ 创建新项目', value: '__create__' },
379
- ...projects.map(p => ({ label: p.name, desc: p.description, value: p.id })),
386
+ { label: `${CREATE_ITEM_ICON}创建新项目`, value: '__create__' },
387
+ // 快捷任务固定第二行, 列表其余项目排在空行之后
388
+ // The easy default sits on row 2; the remaining projects follow one blank row.
389
+ { label: EASY_PROJECT_LABEL, desc: pinnedProject?.description || '一键创建并进入', value: pinnedProject?.id ?? '__easy_project__' },
390
+ { label: '', value: '__sep__', disabled: true },
391
+ ...projects.filter(p => p.id !== pinnedProject?.id).map(p => ({ label: `${PROJECT_ITEM_ICON}${p.name}`, desc: p.description, value: p.id })),
380
392
  ]}
381
- initialActive={projects.length > 0 ? 1 : 0}
382
- onSelect={v => v === '__create__' ? setCreateMode('project') : pickProject(projects!.find(p => p.id === v)!)}
393
+ initialActive={pinnedProject ? 1 : projects.length ? 2 : 1}
394
+ onSelect={v => {
395
+ if (v === '__create__') return setCreateMode('project')
396
+ if (v === '__easy_project__') return void createProject(EASY_DEFAULT_PROJECT_NAME)
397
+ return void pickProject(projects.find(p => p.id === v)!)
398
+ }}
383
399
  />}
384
400
  </Box>
385
401
  <Text color="gray">↑↓ 选择 · 回车确认 · Esc 取消</Text>
@@ -393,17 +409,21 @@ export function ReconfigFlow({ client, onDone, onCancel, platform = process.plat
393
409
  <Box marginTop={1}>
394
410
  {issues === null
395
411
  ? <Text color="cyan">加载任务列表…</Text>
396
- : issues.length === 0
397
- ? <Select
398
- items={[{ label: '➕ 创建新任务(尚无任务)', value: '__create__' }]}
399
- onSelect={() => setCreateMode('issue')} />
400
- : <Select
401
- items={[
402
- { label: '➕ 创建新任务', value: '__create__' },
403
- ...issues.map(i => ({ label: i.title, desc: i.description, value: i.id })),
404
- ]}
405
- initialActive={1}
406
- onSelect={v => v === '__create__' ? setCreateMode('issue') : pickIssue(issues!.find(i => i.id === v)!)} />}
412
+ : <Select
413
+ items={[
414
+ { label: issues.length ? `${CREATE_ITEM_ICON}创建新任务` : `${CREATE_ITEM_ICON}创建新任务(尚无任务)`, value: '__create__' },
415
+ // 日常会话固定第二行, 列表其余任务排在空行之后
416
+ // The easy default sits on row 2; the remaining tasks follow one blank row.
417
+ { label: EASY_ISSUE_LABEL, desc: pinnedIssue?.description || '一键创建并进入', value: pinnedIssue?.id ?? '__easy_issue__' },
418
+ { label: '', value: '__sep__', disabled: true },
419
+ ...issues.filter(i => i.id !== pinnedIssue?.id).map(i => ({ label: `${ISSUE_ITEM_ICON}${i.title}`, desc: i.description, value: i.id })),
420
+ ]}
421
+ initialActive={pinnedIssue ? 1 : issues.length ? 2 : 1}
422
+ onSelect={v => {
423
+ if (v === '__create__') return setCreateMode('issue')
424
+ if (v === '__easy_issue__') return void createIssue(EASY_DEFAULT_ISSUE_TITLE)
425
+ return void pickIssue(issues.find(i => i.id === v)!)
426
+ }} />}
407
427
  </Box>
408
428
  <Text color="gray">↑↓ 选择 · 回车确认 · Esc 取消</Text>
409
429
  </Box>
@@ -17,6 +17,10 @@ import { Select, TextInput, type SelectItem } from './primitives.js'
17
17
  import { MobiusClient } from '../api.js'
18
18
  import { effectiveGuiMode, guiModeOptions, hasGuiSupport, restartAimuxConnectionForGuiChange, setTuiGuiMode, tuiGuiMode, type GuiMode } from '../aimux.js'
19
19
  import { windowsElevated } from '../lib/windows-admin.js'
20
+ import {
21
+ CREATE_ITEM_ICON, EASY_DEFAULT_ISSUE_TITLE, EASY_DEFAULT_PROJECT_NAME,
22
+ EASY_ISSUE_LABEL, EASY_PROJECT_LABEL, ISSUE_ITEM_ICON, PROJECT_ITEM_ICON,
23
+ } from '../easy-mode-defaults.js'
20
24
  import {
21
25
  bindCwdToProject, cwd, getCwdPreference, loadDir2Project, loadProjectsCache,
22
26
  saveProjectsCache, setCwdIssue, updateIssuePreference, type IssuePreference,
@@ -369,11 +373,14 @@ function ProjectPicker({ cwd, projects, statusMsg, onPick, onCreate, onQuit }: {
369
373
  )
370
374
  }
371
375
 
372
- const items: SelectItem[] = projects.map(p => ({
373
- label: p.name,
374
- desc: p.description,
375
- value: p.id,
376
- }))
376
+ // 快捷任务置顶, 不存在时选中即创建
377
+ // Pin the easy default on top; picking it while missing creates it on demand.
378
+ const pinned = projects.find(p => p.name === EASY_DEFAULT_PROJECT_NAME) ?? null
379
+ const items: SelectItem[] = [
380
+ { label: EASY_PROJECT_LABEL, desc: pinned?.description || '一键创建并进入', value: pinned?.id ?? '__easy_project__' },
381
+ { label: '', value: '__sep__', disabled: true },
382
+ ...projects.filter(p => p.id !== pinned?.id).map(p => ({ label: `${PROJECT_ITEM_ICON}${p.name}`, desc: p.description, value: p.id })),
383
+ ]
377
384
  return (
378
385
  <Box flexDirection="column" paddingX={2} paddingY={1}>
379
386
  <Text color="gray">{cwd}</Text>
@@ -381,8 +388,8 @@ function ProjectPicker({ cwd, projects, statusMsg, onPick, onCreate, onQuit }: {
381
388
  title="选择当前路径的绑定项目"
382
389
  placeholder="输入项目名或描述"
383
390
  items={items}
384
- createItem={{ label: '➕ 创建新项目', value: '__create__', desc: '绑定到当前路径' }}
385
- onSelect={v => onPick(projects.find(p => p.id === v)!)}
391
+ createItem={{ label: `${CREATE_ITEM_ICON}创建新项目`, value: '__create__', desc: '绑定到当前路径' }}
392
+ onSelect={v => v === '__easy_project__' ? onCreate(EASY_DEFAULT_PROJECT_NAME, '') : onPick(projects.find(p => p.id === v)!)}
386
393
  onCreate={() => setMode('create')}
387
394
  onQuit={onQuit}
388
395
  />
@@ -414,11 +421,14 @@ function IssuePicker({ issues, onPick, onCreate }: {
414
421
  </Box>
415
422
  )
416
423
  }
417
- const items: SelectItem[] = issues.map(i => ({
418
- label: i.title,
419
- desc: i.description,
420
- value: i.id,
421
- }))
424
+ // 日常会话置顶, 不存在时选中即创建
425
+ // Pin the easy default on top; picking it while missing creates it on demand.
426
+ const pinned = issues.find(i => i.title === EASY_DEFAULT_ISSUE_TITLE) ?? null
427
+ const items: SelectItem[] = [
428
+ { label: EASY_ISSUE_LABEL, desc: pinned?.description || '一键创建并进入', value: pinned?.id ?? '__easy_issue__' },
429
+ { label: '', value: '__sep__', disabled: true },
430
+ ...issues.filter(i => i.id !== pinned?.id).map(i => ({ label: `${ISSUE_ITEM_ICON}${i.title}`, desc: i.description, value: i.id })),
431
+ ]
422
432
  return (
423
433
  <Box flexDirection="column">
424
434
  <Text color="gray">偏好设置将保存在所选任务内部</Text>
@@ -427,8 +437,8 @@ function IssuePicker({ issues, onPick, onCreate }: {
427
437
  title="选择任务(Issue)"
428
438
  placeholder="输入任务标题或描述"
429
439
  items={items}
430
- createItem={{ label: issues.length ? '➕ 创建新任务' : '➕ 创建新任务(尚无任务)', value: '__create__' }}
431
- onSelect={v => onPick(issues.find(i => i.id === v)!)}
440
+ createItem={{ label: issues.length ? `${CREATE_ITEM_ICON}创建新任务` : `${CREATE_ITEM_ICON}创建新任务(尚无任务)`, value: '__create__' }}
441
+ onSelect={v => v === '__easy_issue__' ? onCreate(EASY_DEFAULT_ISSUE_TITLE) : onPick(issues.find(i => i.id === v)!)}
432
442
  onCreate={() => setMode('create-name')}
433
443
  />
434
444
  </Box>
@@ -538,8 +538,10 @@ export function Select(props: SelectProps) {
538
538
  return (
539
539
  <Box key={it.value}>
540
540
  <Text
541
- color={disabled ? 'gray' : isActive ? 'black' : undefined}
542
- backgroundColor={isActive ? 'cyan' : undefined}
541
+ // 高亮行用白字深蓝底, 避免旧配色看不清
542
+ // White on blue keeps the highlighted row readable on Windows consoles.
543
+ color={disabled ? 'gray' : isActive ? 'white' : undefined}
544
+ backgroundColor={isActive ? 'blue' : undefined}
543
545
  bold={isActive}
544
546
  wrap="truncate-end"
545
547
  >
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Easy-mode default names, mirrored from the web UI's
3
+ * mobius/frontend/src/services/easy-mode-defaults.ts — keep both in sync.
4
+ * The TUI ships as a standalone npm package and cannot import frontend code.
5
+ */
6
+ export const EASY_DEFAULT_PROJECT_NAME = '快捷任务'
7
+ export const EASY_DEFAULT_ISSUE_TITLE = '日常会话'
8
+
9
+ /** Picker labels: the easy default reads as "skip the choice". */
10
+ export const EASY_PROJECT_LABEL = '🕊️不使用任何项目'
11
+ export const EASY_ISSUE_LABEL = '🕊️不使用任何任务'
12
+ export const CREATE_ITEM_ICON = '🚀'
13
+ export const PROJECT_ITEM_ICON = '📁'
14
+ export const ISSUE_ITEM_ICON = '💡'
@@ -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()
package/tests/ui.test.tsx CHANGED
@@ -393,13 +393,16 @@ async function testPrepRender() {
393
393
  // compact and show their names alone.
394
394
  ok(!frame.includes('已有项目A - 第一行') && !frame.includes('已有项目B - 单行描述'), 'unfocused project rows omit their descriptions')
395
395
  stdin.write('\x1b[B'); await delay(15) // move focus from search to the list
396
- stdin.write('\x1b[B'); await delay(15) // highlight the first project
396
+ stdin.write('\x1b[B'); await delay(15) // highlight the pinned easy-default row
397
+ ok((lastFrame() ?? '').includes('🕊️不使用任何项目 - 一键创建并进入'), 'easy-default project is pinned above the list')
398
+ stdin.write('\x1b[B'); await delay(15) // step over the blank separator to the first project
397
399
  const selectedFrame = lastFrame() ?? ''
398
400
  ok(selectedFrame.includes('已有项目A - 第一行 ⏎ 第二行'), 'selected multi-line description stays on the main row')
399
401
  ok(!selectedFrame.includes('已有项目B - 单行描述'), 'unselected project description is omitted')
400
402
  ok(!frame.includes('\n 第一行') && !frame.includes('\n 单行描述'), 'project explanations do not render as an additional row')
401
403
  ok(!frame.includes('加载项目列表…'), 'completed project load does not leave a stale loading message')
402
404
 
405
+ stdin.write('\x1b[A'); await delay(15) // back to the easy-default row
403
406
  stdin.write('\x1b[A'); await delay(15) // return to the create row
404
407
  stdin.write('\r')
405
408
  await delay(30)
package/uninstall.ps1 CHANGED
@@ -4,11 +4,13 @@
4
4
  Completely uninstall the current-user Mobius TUI installation on Windows.
5
5
  .DESCRIPTION
6
6
  Removes the portable Node runtime, npm package, launchers, AIMUX/Python bundle,
7
- saved login and preferences under ~/.mobius, user PATH entries, and both
8
- Explorer "Open in Mobius" context-menu registrations. No administrator rights
9
- are required. Unrelated system Node.js/Python/AIMUX installations are untouched.
7
+ saved login and preferences under ~/.mobius, user PATH entries, and the two
8
+ Explorer context-menu entries ("在Mobius终端中打开" and its administrator
9
+ variant) registered for both a folder and the folder background. No
10
+ administrator rights are required. Unrelated system Node.js/Python/AIMUX
11
+ installations are untouched.
10
12
  .EXAMPLE
11
- irm https://serve.nutshellai.cn/publish/auto/mobiustui/uninstall-v11.ps1 | iex
13
+ irm https://serve.nutshellai.cn/publish/auto/mobiustui/uninstall-v12.ps1 | iex
12
14
  #>
13
15
  $ErrorActionPreference = 'Stop'
14
16
  $ProgressPreference = 'SilentlyContinue'
@@ -33,7 +35,7 @@ function Invoke-MobiusUninstall {
33
35
  Write-Host ''
34
36
  Warn "将永久删除: $mobiusHome"
35
37
  Warn '包括登录信息、项目缓存、目录绑定、Issue 偏好、便携 Node、TUI 和 AIMUX/Python bundle。'
36
- Warn '还会删除用户 PATH 中的 Mobius 项和两个“在 Mobius 中打开”右键菜单。'
38
+ Warn '还会删除用户 PATH 中的 Mobius 项和“在Mobius终端中打开”(含管理员权限)右键菜单。'
37
39
  Write-Host ''
38
40
 
39
41
  if ($env:MOBIUS_UNINSTALL_FORCE -ne '1') {
@@ -66,12 +68,14 @@ function Invoke-MobiusUninstall {
66
68
  Step '删除 Explorer 右键菜单...'
67
69
  $contextMenuKeys = @(
68
70
  'HKCU:\Software\Classes\Directory\shell\Mobius',
69
- 'HKCU:\Software\Classes\Directory\Background\shell\Mobius'
71
+ 'HKCU:\Software\Classes\Directory\Background\shell\Mobius',
72
+ 'HKCU:\Software\Classes\Directory\shell\MobiusAdmin',
73
+ 'HKCU:\Software\Classes\Directory\Background\shell\MobiusAdmin'
70
74
  )
71
75
  foreach ($key in $contextMenuKeys) {
72
76
  if (Test-Path $key) { Remove-Item $key -Recurse -Force }
73
77
  }
74
- Ok '文件夹本身和文件夹空白处的右键菜单已删除。'
78
+ Ok '文件夹本身和文件夹空白处的右键菜单已删除(含管理员权限入口)。'
75
79
 
76
80
  Step '从当前用户 PATH 删除 Mobius 目录...'
77
81
  $removeEntries = @($mobiusBin, $npmGlobal, $npmGlobalBin) |
@@ -121,6 +125,7 @@ function Invoke-MobiusUninstall {
121
125
  Remove-Item (Join-Path $env:TEMP 'mobius-install-v13-error.log') -Force -ErrorAction SilentlyContinue
122
126
  Remove-Item (Join-Path $env:TEMP 'mobius-install-v14-error.log') -Force -ErrorAction SilentlyContinue
123
127
  Remove-Item (Join-Path $env:TEMP 'mobius-install-v15-error.log') -Force -ErrorAction SilentlyContinue
128
+ Remove-Item (Join-Path $env:TEMP 'mobius-install-v16-error.log') -Force -ErrorAction SilentlyContinue
124
129
  Remove-Item (Join-Path $env:TEMP 'mobius-uninstall-v11-error.log') -Force -ErrorAction SilentlyContinue
125
130
  Ok '临时安装文件已清理。'
126
131