@mobius-os/mobius 0.3.79 → 0.3.85

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/README.md CHANGED
@@ -84,6 +84,14 @@ child and reconnect with 1/2/4/8/15-second capped exponential backoff. A
84
84
  successful bridge heartbeat resets the backoff and changes the status indicator
85
85
  to green.
86
86
 
87
+ Every 30 minutes the TUI also reads `/aimux_bridge/api/health` and compares the
88
+ broker's aimux version with the one in use. A newer server version installs that
89
+ exact version locally and restarts the reverse connection, so a Mobius upgrade
90
+ reaches TUIs that were left open; an older version is never forced on the client
91
+ (the next TUI start aligns in either direction). Failures keep the existing
92
+ version connected and are retried at most three times per version. Set
93
+ `MOBIUS_TUI_AIMUX_FOLLOW_MS` to change the interval, or to `0` to disable it.
94
+
87
95
  ## Flow
88
96
 
89
97
  1. **Login** — server / username / password → `POST /api/auth/login` → save
@@ -147,6 +155,19 @@ npm test # all three
147
155
 
148
156
  ## Build an installable package
149
157
 
158
+ ### Upgrade from inside the TUI
159
+
160
+ Enter `/upgrade_tui` in the chat composer to install the latest
161
+ `@mobius-os/mobius` from the official npm registry. The command upgrades the
162
+ current global installation using its existing prefix, shows progress and
163
+ errors, and verifies the installed version. After success, enter `/quit` and
164
+ run `mobius` again; use `/resume` to return to your conversation. If already
165
+ on the latest version, no installation runs. Repeated requests while upgrading
166
+ are ignored. Source checkouts and temporary npx installations receive an
167
+ installation hint instead of being overwritten.
168
+
169
+ `/upgrade` remains the separate command for upgrading AIMUX from PyPI.
170
+
150
171
  The TUI release version has one source of truth: `mobius/tui/package.json`.
151
172
  The welcome screen, npm package metadata, artifact filename, and download
152
173
  manifest all read that value. `package-lock.json` mirrors it as generated npm
package/install.ps1 CHANGED
@@ -10,7 +10,9 @@
10
10
  文件夹空白处注册两个 Explorer 右键入口:“在Mobius终端中打开”与
11
11
  “在Mobius终端中打开(管理员权限)”。
12
12
  .EXAMPLE
13
- irm https://serve.nutshellai.cn/publish/auto/mobiustui/install-v18.ps1 | iex
13
+ irm https://serve.nutshellai.cn/publish/auto/mobiustui/install-v21.ps1 | iex
14
+ .EXAMPLE
15
+ 双击 installers/tui-install-v21.cmd (脚本内容由本文件生成, 见 scripts/build-install-cmd.py)
14
16
  #>
15
17
  $ErrorActionPreference = 'Stop'
16
18
  $ProgressPreference = 'SilentlyContinue'
@@ -321,13 +323,18 @@ Write-Host "右键文件夹或文件夹空白处,可选择: 在Mobius终端中
321
323
  try {
322
324
  Invoke-MobiusInstall
323
325
  } catch {
324
- $errorLog = Join-Path $env:TEMP "mobius-install-v18-error.log"
326
+ $errorLog = Join-Path $env:TEMP "mobius-install-error.log"
325
327
  $errorText = $_ | Format-List * -Force | Out-String
326
328
  $errorText | Set-Content -Path $errorLog -Encoding UTF8
327
329
  Write-Host ""
328
330
  Err "Mobius 安装失败: $($_.Exception.Message)"
329
331
  Write-Host "完整错误日志: $errorLog" -ForegroundColor Yellow
330
332
  Write-Host $errorText -ForegroundColor DarkYellow
333
+ # 双击安装器 (tui-install-vNN.cmd) 自己会 pause, 这里只回报非零退出码;
334
+ # 只有 `irm | iex` 这种交互式调用才需要 Read-Host 把窗口留住.
335
+ # The double-click launcher pauses on its own, so it only needs a non-zero
336
+ # exit code here; the interactive `irm | iex` call still needs Read-Host.
337
+ if ($env:MOBIUS_INSTALL_LAUNCHER) { exit 1 }
331
338
  try { Read-Host "按 Enter 返回 PowerShell(窗口不会自动关闭)" | Out-Null } catch { }
332
339
  return
333
340
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mobius-os/mobius",
3
- "version": "0.3.79",
3
+ "version": "0.3.85",
4
4
  "type": "module",
5
5
  "description": "Mobius terminal client. Reuses Mobius frontend TypeScript types and jsonl entry shapes.",
6
6
  "bin": {
@@ -14,6 +14,7 @@
14
14
  "test:integration": "tsx tests/integration.test.ts",
15
15
  "test:size": "tsx tests/terminal-size.test.ts",
16
16
  "test:ui": "tsx tests/ui.test.tsx",
17
+ "test:upgrade-tui": "tsx tests/upgrade-tui.test.ts",
17
18
  "test:flow": "tsx tests/flow.test.tsx",
18
19
  "test:resume": "tsx tests/resume.test.tsx",
19
20
  "test:aimux": "tsx tests/aimux.test.tsx",
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env python3
2
+ """Build the double-clickable Windows installer (.cmd) from install.ps1.
3
+
4
+ A .ps1 cannot be double-clicked: Explorer opens it in Notepad and the default
5
+ execution policy blocks it. A .cmd can, so this script appends the exact
6
+ install.ps1 payload to a small batch stub.
7
+
8
+ Two constraints shape the layout:
9
+
10
+ * The stub is ASCII-only. cmd.exe decodes batch files with the console code
11
+ page; UTF-8 Chinese inside the stub would print as mojibake. All Chinese
12
+ output comes from the PowerShell payload, which is a real UTF-8 file.
13
+ * cmd.exe executes batch line by line and every outcome in the stub ends with
14
+ "exit /b" before the marker line, so the appended PowerShell text is never
15
+ parsed as batch. The stub uses PowerShell to slice the payload out of its own
16
+ file (PowerShell knows the file is UTF-8) and runs it with -File, which also
17
+ keeps `#requires` handling and exit codes intact.
18
+
19
+ Usage:
20
+ python3 mobius/tui/scripts/build-install-cmd.py
21
+ python3 mobius/tui/scripts/build-install-cmd.py --version v21
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import argparse
26
+ import hashlib
27
+ import pathlib
28
+ import sys
29
+
30
+ STUB_PS1 = pathlib.Path(__file__).resolve().parents[1] / "install.ps1"
31
+ REPO_ROOT = pathlib.Path(__file__).resolve().parents[3]
32
+ OUT_DIR = REPO_ROOT / "mobius" / "installers"
33
+ MARKER = "#__MOBIUS_INSTALLER_PAYLOAD__"
34
+
35
+ STUB = r"""@echo off
36
+ rem ===================================================================
37
+ rem Mobius TUI installer for Windows - double-click to run.
38
+ rem
39
+ rem GENERATED FILE, do not edit by hand. Rebuild with:
40
+ rem python3 mobius/tui/scripts/build-install-cmd.py
41
+ rem Payload source of truth: mobius/tui/install.ps1
42
+ rem
43
+ rem The stub is ASCII-only on purpose: cmd.exe decodes batch files with the
44
+ rem console code page, which would mangle UTF-8 Chinese. Everything the user
45
+ rem reads comes from the PowerShell payload appended below the marker.
46
+ rem Payload extraction stays on plain cmdlets on purpose: this machine runs
47
+ rem PowerShell in ConstrainedLanguage (AppLocker/WDAC), where New-Object and
48
+ rem other non-core .NET type creation fail. See the CLM notes in install.ps1.
49
+ rem cmd.exe executes this file line by line and every path here ends with
50
+ rem "exit /b" before the marker, so the payload is never parsed as batch.
51
+ rem The stub mentions the marker text itself, so the payload is located with
52
+ rem LastIndexOf (the marker line is always the final occurrence).
53
+ rem ===================================================================
54
+ setlocal
55
+ set "MOBIUS_INSTALL_LAUNCHER=1"
56
+ set "MOBIUS_SELF=%~f0"
57
+ set "MOBIUS_PAYLOAD=%TEMP%\mobius-install-%RANDOM%%RANDOM%.ps1"
58
+
59
+ echo.
60
+ echo Preparing the Mobius TUI installer...
61
+ echo.
62
+
63
+ powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference='Stop'; try { $text = Get-Content -LiteralPath $env:MOBIUS_SELF -Raw -Encoding UTF8; $marker = '#__MOBIUS_INSTALLER_PAYLOAD__'; $at = $text.LastIndexOf($marker); if ($at -lt 0) { throw 'installer payload marker missing' }; $body = $text.Substring($at + $marker.Length).TrimStart(); Set-Content -LiteralPath $env:MOBIUS_PAYLOAD -Value $body -Encoding UTF8 } catch { Write-Host ('[X] ' + $_.Exception.Message) -ForegroundColor Red; exit 1 }"
64
+ if errorlevel 1 (
65
+ echo.
66
+ echo [X] Could not unpack the installer. Please download the file again.
67
+ echo.
68
+ pause
69
+ exit /b 1
70
+ )
71
+
72
+ powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -File "%MOBIUS_PAYLOAD%"
73
+ set "MOBIUS_RC=%ERRORLEVEL%"
74
+ del /f /q "%MOBIUS_PAYLOAD%" >nul 2>&1
75
+
76
+ echo.
77
+ if not "%MOBIUS_RC%"=="0" echo [X] Installation failed. Exit code: %MOBIUS_RC%
78
+ echo.
79
+ pause
80
+ exit /b %MOBIUS_RC%
81
+
82
+ """
83
+
84
+
85
+ def main() -> int:
86
+ parser = argparse.ArgumentParser(description="Build the double-clickable Windows installer.")
87
+ parser.add_argument("--version", default="v21", help="installer version used in the file name")
88
+ args = parser.parse_args()
89
+
90
+ payload = STUB_PS1.read_text(encoding="utf-8")
91
+ if MARKER in payload:
92
+ print(f"error: {STUB_PS1} already contains the marker {MARKER}", file=sys.stderr)
93
+ return 1
94
+ # A BOM would break cmd.exe's first line and confuse Get-Content -Encoding UTF8.
95
+ if payload.startswith("\ufeff"):
96
+ payload = payload[1:]
97
+ if not payload.startswith("#requires"):
98
+ print(f"error: {STUB_PS1} must start with a #requires line", file=sys.stderr)
99
+ return 1
100
+
101
+ non_ascii = [(i, line) for i, line in enumerate(STUB.splitlines(), 1) if not line.isascii()]
102
+ if non_ascii:
103
+ print(f"error: batch stub must stay ASCII-only, offending line {non_ascii[0][0]}: {non_ascii[0][1]!r}",
104
+ file=sys.stderr)
105
+ return 1
106
+
107
+ # cmd.exe needs CRLF; the payload goes through unchanged apart from line endings.
108
+ content = (STUB + MARKER + "\r\n" + payload).replace("\r\n", "\n").replace("\n", "\r\n")
109
+
110
+ OUT_DIR.mkdir(parents=True, exist_ok=True)
111
+ out = OUT_DIR / f"tui-install-{args.version}.cmd"
112
+ with out.open("w", encoding="utf-8", newline="") as handle:
113
+ handle.write(content)
114
+
115
+ digest = hashlib.sha256(content.encode("utf-8")).hexdigest()
116
+ print(f"wrote {out.relative_to(REPO_ROOT)} ({len(content.encode('utf-8'))} bytes, sha256 {digest})")
117
+ return 0
118
+
119
+
120
+ if __name__ == "__main__":
121
+ raise SystemExit(main())
package/src/App.tsx CHANGED
@@ -23,6 +23,8 @@ import { startAimuxConnection, stopAimuxConnection, upgradeAimuxRuntime, type Ai
23
23
  import { AimuxStatusLine } from './components/AimuxStatus.js'
24
24
  import { bufferUnclaimedInput, useStableInput } from './components/primitives.js'
25
25
 
26
+ import { upgradeTui, type TuiUpgradeStatus } from './upgrade-tui.js'
27
+
26
28
  type Route = 'boot' | 'login' | 'prep' | 'chat' | 'resume'
27
29
 
28
30
  export function App() {
@@ -31,6 +33,7 @@ export function App() {
31
33
  // the next Chat/Select mount, making the first arrows or typed characters
32
34
  // appear ignored until a later key causes another render.
33
35
  useStableInput(bufferUnclaimedInput, { interactive: false })
36
+ const [tuiUpgradeStatus, setTuiUpgradeStatus] = useState<TuiUpgradeStatus | undefined>()
34
37
  const [route, setRoute] = useState<Route>('boot')
35
38
  const [bootMsg, setBootMsg] = useState('初始化…')
36
39
  const [client, setClient] = useState<MobiusClient | null>(null)
@@ -229,6 +232,8 @@ export function App() {
229
232
  onQuit={onQuit}
230
233
  onLogout={() => { void onLogout() }}
231
234
  onUpgradeAimux={() => { void upgradeAimuxRuntime() }}
235
+ onUpgradeTui={() => { void upgradeTui(setTuiUpgradeStatus) }}
236
+ tuiUpgradeStatus={tuiUpgradeStatus}
232
237
  onReconfigure={onReconfigure}
233
238
  onConfigCancel={onConfigCancel}
234
239
  aimuxStatus={aimuxStatus}
package/src/aimux.ts CHANGED
@@ -13,7 +13,7 @@ import { Readable } from 'node:stream'
13
13
  import extract from 'extract-zip'
14
14
  import { mobiusHome } from './config.js'
15
15
  import { windowsElevated } from './lib/windows-admin.js'
16
- import { alignTarget, aimuxWorkspaceHash, pidAlive, reverseConnectArgs, pickSilentFlag, pickEnableGuiFlag, pickGuiNoElevateFlag, pickGuiArgs, currentUsername, AIMUX_TARGET_VERSION, type GuiMode } from './lib/aimux-protocol.js'
16
+ import { alignTarget, aimuxWorkspaceHash, daemonAlive, pidAlive, reverseConnectArgs, pickSilentFlag, pickEnableGuiFlag, pickGuiNoElevateFlag, pickGuiArgs, currentUsername, AIMUX_TARGET_VERSION, type GuiMode } from './lib/aimux-protocol.js'
17
17
  export { alignTarget, aimuxWorkspaceHash, pidAlive, reverseConnectArgs, pickSilentFlag, pickEnableGuiFlag, pickGuiNoElevateFlag, pickGuiArgs, type GuiMode } from './lib/aimux-protocol.js'
18
18
 
19
19
  export type AimuxState = 'starting' | 'connected' | 'failed' | 'stopped' | 'disabled'
@@ -609,7 +609,7 @@ async function ensureRuntimeDir(): Promise<void> {
609
609
  await fs.mkdir(aimuxRuntimeDir(), { recursive: true, mode: 0o700 })
610
610
  }
611
611
 
612
- interface RuntimeRecord { pid?: number; last_feed_watchdog?: number; need_external_restart?: boolean; realtime_healthy_display?: boolean; identifier?: string; launched_at?: number }
612
+ interface RuntimeRecord { pid?: number; last_feed_watchdog?: number; need_external_restart?: boolean; realtime_healthy_display?: boolean; identifier?: string; launched_at?: number; daemon_heartbeat_at?: number }
613
613
  async function readRuntime(hash: string): Promise<RuntimeRecord | null> {
614
614
  try {
615
615
  return JSON.parse(await fs.readFile(runtimePath(hash), 'utf8')) as RuntimeRecord
@@ -744,8 +744,7 @@ export class AimuxSupervisor {
744
744
  private async ensureDaemon(): Promise<void> {
745
745
  if (this.stopping) return
746
746
  const current = await readRuntime(this.hash)
747
- const pid = current?.pid ?? null
748
- if (current && pid !== null && pidAlive(pid)) {
747
+ if (current && daemonAlive(current)) {
749
748
  await touchWatchdog(this.hash)
750
749
  this.opts.onStatus({ state: 'starting', phase: 'heartbeat', detail: 'AIMUX runtime 已存在,复用中…', identifier: this.opts.identifier })
751
750
  return
@@ -757,8 +756,7 @@ export class AimuxSupervisor {
757
756
  private async spawnDaemon(): Promise<void> {
758
757
  if (this.stopping) return
759
758
  const current = await readRuntime(this.hash)
760
- const pid = current?.pid ?? null
761
- if (pid !== null && pidAlive(pid)) { await touchWatchdog(this.hash); return }
759
+ if (current && daemonAlive(current)) { await touchWatchdog(this.hash); return }
762
760
  const { server, token, identifier, onStatus } = this.opts
763
761
  onStatus({ state: 'starting', phase: 'connecting', detail: '正在启动 AIMUX 守护进程…', identifier, attempt: this.reconnectAttempt })
764
762
  const gui = resolvedGuiArgs()
@@ -807,7 +805,9 @@ export class AimuxSupervisor {
807
805
  await this.updateRuntimeHealth(false)
808
806
  const runtime = await readRuntime(this.hash)
809
807
  const pid = runtime?.pid ?? null
810
- const alive = pid !== null && pidAlive(pid)
808
+ // A reused PID (or a defunct process) still answers pidAlive; the daemon's
809
+ // own heartbeat is what distinguishes "still running" from "number taken".
810
+ const alive = daemonAlive(runtime)
811
811
  // Runtime state on disk means the daemon got past its own start — which on
812
812
  // Windows may have meant an elevation prompt — so the attempt produced
813
813
  // something and the retry budget is not the thing to withhold.
@@ -883,6 +883,9 @@ export class AimuxSupervisor {
883
883
  if (this.stopping) return
884
884
  if (!token) throw new Error('登录接口未返回新 JWT')
885
885
  this.opts.token = token
886
+ // 跟随检查用的是 lastStartOpts 里的 token;JWT 刷新后必须一起更新,
887
+ // 否则 TUI 连过一周之后定时探测会一直 401。
888
+ if (lastStartOpts && lastStartOpts.server === this.opts.server) lastStartOpts.token = token
886
889
  this.reconnectAttempt = 0
887
890
  appendAimuxLog(installLogQueue, `AIMUX JWT refreshed at ${new Date().toISOString()}; restarting bridge client\n`)
888
891
  this.opts.onStatus({ state: 'starting', phase: 'connecting', detail: 'JWT 已刷新,正在重新连接 AIMUX bridge…', identifier: this.opts.identifier })
@@ -916,6 +919,48 @@ let lastStartOpts: StartOptions | null = null
916
919
  let skipAutoAlignOnce = false
917
920
  /** 实际装着的 aimux 版本,供状态行显示(自动对齐后可能和 pin 不同)。 */
918
921
  let runtimeAimuxVersion: string | null = null
922
+ /** 跟随服务端版本的定时器(TUI 开着的时候才跑)。 */
923
+ let followTimer: ReturnType<typeof setInterval> | null = null
924
+ let followInFlight = false
925
+ /** 同一个服务端版本连续升级失败的次数;到上限就停止重试,等版本再变或 TUI 重启。 */
926
+ let followFailedVersion: string | null = null
927
+ let followFailureCount = 0
928
+ const FOLLOW_MAX_FAILURES = 3
929
+
930
+ /**
931
+ * 跟随检查间隔。默认 30 分钟;设 0 关闭(离线/受控环境)。
932
+ * 单独抽出来是为了测试和排障时不必等半小时。
933
+ */
934
+ export function followCheckIntervalMs(): number {
935
+ const raw = process.env.MOBIUS_TUI_AIMUX_FOLLOW_MS
936
+ if (raw !== undefined && raw !== '') {
937
+ const n = Number(raw)
938
+ if (Number.isFinite(n) && n >= 0) return n
939
+ }
940
+ return 30 * 60 * 1000
941
+ }
942
+
943
+ /**
944
+ * 按数字段比较两个 aimux 版本,返回 -1/0/1;任一侧不是纯数字点分版本时返回 null。
945
+ * 不能用字符串比较:'0.3.9' > '0.3.10' 是错的,而这里恰好只关心谁更新。
946
+ */
947
+ export function compareAimuxVersions(a: string | null | undefined, b: string | null | undefined): number | null {
948
+ const parse = (value: string | null | undefined): number[] | null => {
949
+ const text = typeof value === 'string' ? value.trim().replace(/^v/i, '') : ''
950
+ if (!/^\d+(\.\d+)*$/.test(text)) return null
951
+ return text.split('.').map(part => Number(part))
952
+ }
953
+ const left = parse(a)
954
+ const right = parse(b)
955
+ if (!left || !right) return null
956
+ const length = Math.max(left.length, right.length)
957
+ for (let i = 0; i < length; i += 1) {
958
+ const x = left[i] ?? 0
959
+ const y = right[i] ?? 0
960
+ if (x !== y) return x > y ? 1 : -1
961
+ }
962
+ return 0
963
+ }
919
964
 
920
965
  interface StartOptions {
921
966
  server: string
@@ -1024,15 +1069,86 @@ export async function startAimuxConnection(opts: StartOptions): Promise<void> {
1024
1069
  spawnProcess: token => spawnDetachedDaemon(launcher, reverseConnectArgs(opts.server, identifier, token, process.platform, silentFlag, runtimePath(aimuxWorkspaceHash()), gui.enableGui, gui.guiNoElevate)),
1025
1070
  })
1026
1071
  await supervisor.start()
1072
+ scheduleFollowCheck(opts)
1027
1073
  })().finally(() => { installing = null })
1028
1074
  await installing
1029
1075
  }
1030
1076
 
1031
1077
  export async function stopAimuxConnection(): Promise<void> {
1078
+ clearFollowCheck()
1032
1079
  const current = supervisor; supervisor = null
1033
1080
  await current?.stop()
1034
1081
  }
1035
1082
 
1083
+ /** 重新开始计时;每次连接成功都重置,避免旧定时器指向已废弃的 opts。 */
1084
+ function scheduleFollowCheck(opts: StartOptions): void {
1085
+ clearFollowCheck()
1086
+ const intervalMs = followCheckIntervalMs()
1087
+ if (!(intervalMs > 0)) {
1088
+ logInstall('aimux follow: disabled by MOBIUS_TUI_AIMUX_FOLLOW_MS=0\n')
1089
+ return
1090
+ }
1091
+ followTimer = setInterval(() => { void followServerVersion(opts) }, intervalMs)
1092
+ followTimer.unref?.()
1093
+ logInstall(`aimux follow: checking the server version every ${Math.round(intervalMs / 1000)}s\n`)
1094
+ }
1095
+
1096
+ function clearFollowCheck(): void {
1097
+ if (followTimer) { clearInterval(followTimer); followTimer = null }
1098
+ }
1099
+
1100
+ /**
1101
+ * “Mobius 升级 aimux,连着的 TUI 跟着升级”的落点。
1102
+ *
1103
+ * 每 30 分钟读一次服务端 broker 版本;只有服务端**更新**时才动手(回滚不把用户
1104
+ * 往回拽 —— 那是下次启动对齐的事)。升级不复用连接期的对齐逻辑,而是先停掉
1105
+ * supervisor 和旧守护进程,再走一遍 startAimuxConnection:它会重新读版本、装到
1106
+ * 目标版本、版本变化时丢弃旧 daemon 并重新探测命令行开关,失败也会带着旧版本
1107
+ * 连回去,不会把设备留在离线状态。
1108
+ */
1109
+ async function followServerVersion(opts: StartOptions): Promise<void> {
1110
+ if (followInFlight || installing || !supervisor) return
1111
+ if (process.env.MOBIUS_TUI_DISABLE_AIMUX === '1') return
1112
+ const current = runtimeAimuxVersion
1113
+ const serverVersion = await fetchServerAimuxVersion(opts.server, opts.token)
1114
+ if (!serverVersion) return
1115
+ if (followFailedVersion && followFailedVersion !== serverVersion) {
1116
+ followFailedVersion = null
1117
+ followFailureCount = 0
1118
+ }
1119
+ if (followFailedVersion === serverVersion && followFailureCount >= FOLLOW_MAX_FAILURES) {
1120
+ logInstall(`aimux follow: ${serverVersion} already failed ${followFailureCount} times; waiting for a different version\n`)
1121
+ return
1122
+ }
1123
+ const cmp = compareAimuxVersions(serverVersion, current)
1124
+ if (cmp === null || cmp <= 0) return
1125
+ followInFlight = true
1126
+ logInstall(`\n########## aimux follow: server ${serverVersion} > local ${current ?? '(unknown)'} at ${new Date().toISOString()} ##########\n`)
1127
+ opts.onStatus?.({ state: 'starting', phase: 'install', detail: `服务端 AIMUX 已升级到 ${serverVersion},正在跟随升级…` })
1128
+ try {
1129
+ await stopAimuxConnection()
1130
+ await stopDaemonFromRuntime()
1131
+ await startAimuxConnection(opts)
1132
+ if (runtimeAimuxVersion === serverVersion) {
1133
+ logInstall(`aimux follow: now running ${runtimeAimuxVersion}\n`)
1134
+ followFailedVersion = null
1135
+ followFailureCount = 0
1136
+ } else {
1137
+ followFailedVersion = serverVersion
1138
+ followFailureCount += 1
1139
+ logInstall(`aimux follow: still on ${runtimeAimuxVersion ?? '(unknown)'} after the attempt (${followFailureCount}/${FOLLOW_MAX_FAILURES})\n`)
1140
+ }
1141
+ } catch (e: any) {
1142
+ followFailedVersion = serverVersion
1143
+ followFailureCount += 1
1144
+ logInstall(`aimux follow failed: ${e?.stack || e?.message || String(e)}\n`)
1145
+ // 别把设备留在离线状态:升级链路异常时用旧版本把连接拉回来。
1146
+ if (!supervisor) { try { await startAimuxConnection(opts) } catch { /* 下一轮定时器再试 */ } }
1147
+ } finally {
1148
+ followInFlight = false
1149
+ }
1150
+ }
1151
+
1036
1152
  /**
1037
1153
  * Re-do the reverse connection after the GUI authorization choice changed.
1038
1154
  * The old daemon must die first (its runtime JSON is keyed by workspace hash,
@@ -1052,8 +1168,12 @@ export async function restartAimuxConnectionForGuiChange(): Promise<void> {
1052
1168
  * 不这么做的话,新 supervisor 会按 pid 复用到刚升级前的旧 daemon。 */
1053
1169
  async function stopDaemonFromRuntime(): Promise<void> {
1054
1170
  const hash = aimuxWorkspaceHash()
1055
- const pid = (await readRuntime(hash))?.pid ?? null
1056
- if (pid !== null && pidAlive(pid)) {
1171
+ const runtime = await readRuntime(hash)
1172
+ const pid = runtime?.pid ?? null
1173
+ // Only signal the PID when the daemon's own heartbeat (or, for an old daemon,
1174
+ // the PID check) says this is still our process; a recycled PID must not be
1175
+ // killed just because the runtime file still names it.
1176
+ if (pid !== null && daemonAlive(runtime)) {
1057
1177
  // EPERM means the daemon is elevated and not ours to signal; waiting for it
1058
1178
  // to die would just stall the caller, so leave it to its own watchdog.
1059
1179
  let ours = true
@@ -21,6 +21,18 @@ export function aimuxStatusText(status: AimuxStatus, compact = false): string {
21
21
  return hostText(`AIMUX${phase} · ${compact ? compactDetail(detail) : detail}`)
22
22
  }
23
23
 
24
+ /*
25
+ * The version shown in the welcome card. Prefer the version the running daemon
26
+ * actually reports; the bundled pin is only an install fallback, so printing it
27
+ * here would claim a version nobody is running. Until the supervisor reports
28
+ * one, say so rather than guessing.
29
+ */
30
+ export function aimuxVersionLabel(status?: AimuxStatus): string {
31
+ if (status?.version) return `v${status.version}`
32
+ if (!status || status.state === 'disabled') return '未启用'
33
+ return '检测中…'
34
+ }
35
+
24
36
  export function AimuxStatusLine({ status, compact = false }: { status: AimuxStatus; compact?: boolean }) {
25
37
  const style = STYLE[status.state]
26
38
  return (
@@ -26,12 +26,14 @@ import { IS_CONHOST, hostText } from '../lib/host-text.js'
26
26
  import type { AnyEntry } from '../types.js'
27
27
  import { ConfigFlow, ReconfigFlow, type ConfigResult } from './ConfigFlow.js'
28
28
  import { AIMUX_VERSION, type AimuxStatus } from '../aimux.js'
29
- import { AimuxStatusLine, aimuxStatusText } from './AimuxStatus.js'
29
+ import { AimuxStatusLine, aimuxStatusText, aimuxVersionLabel } from './AimuxStatus.js'
30
30
  import { isEscapeKeypress, isMouseInput, useMouseEvents, useStableInput } from './primitives.js'
31
31
  import { useDeleteKeyCapture, applyDeleteIntent, clampCursor, previousCursorBoundary, nextCursorBoundary, previousWordBoundary, nextWordBoundary } from '../lib/delete-keys.js'
32
32
  import { useCursorKeyCapture } from '../lib/cursor-keys.js'
33
33
  import { usePaintFlushOnInput } from '../lib/paint-flush.js'
34
34
 
35
+ import type { TuiUpgradeStatus } from '../upgrade-tui.js'
36
+
35
37
  interface ChatProps {
36
38
  client: MobiusClient
37
39
  ready: ReadyState
@@ -43,6 +45,8 @@ interface ChatProps {
43
45
  onLogout: () => void
44
46
  /** 可选,与 aimuxStatus 一样只在接了 AIMUX 的宿主里给;缺省时 /upgrade 不动作。 */
45
47
  onUpgradeAimux?: () => void
48
+ onUpgradeTui?: () => void
49
+ tuiUpgradeStatus?: TuiUpgradeStatus
46
50
  onReconfigure: (result: ConfigResult) => void
47
51
  onConfigCancel: (sessionId: string | null) => void
48
52
  aimuxStatus?: AimuxStatus
@@ -79,10 +83,11 @@ const SLASH_COMMANDS = [
79
83
  { cmd: '/help', desc: '显示帮助' },
80
84
  { cmd: '/version', desc: '显示 TUI、AIMUX 和运行环境版本' },
81
85
  { cmd: '/upgrade', desc: '从 PyPI 安装最新 AIMUX 并重连' },
86
+ { cmd: '/upgrade_tui', desc: '升级 TUI 到 npm 最新版,重启后生效' },
82
87
  { cmd: '/quit', desc: '退出 TUI' },
83
88
  ]
84
89
 
85
- export function ChatScreen({ client, ready, webUserId, resumeSessionId, onClear, onResume, onQuit, onLogout, onUpgradeAimux, onReconfigure, onConfigCancel, aimuxStatus }: ChatProps) {
90
+ export function ChatScreen({ client, ready, webUserId, resumeSessionId, onClear, onResume, onQuit, onLogout, onUpgradeAimux, onUpgradeTui, tuiUpgradeStatus, onReconfigure, onConfigCancel, aimuxStatus }: ChatProps) {
86
91
  const chat = useChat({ client, ready, resumeSessionId })
87
92
  const aimuxQuestionSubmissionBlocked = isAimuxQuestionSubmissionBlocked(aimuxStatus)
88
93
  const [showHelp, setShowHelp] = useState(false)
@@ -146,6 +151,13 @@ export function ChatScreen({ client, ready, webUserId, resumeSessionId, onClear,
146
151
  }
147
152
  case '/model': setConfigOpen(true); return true
148
153
  case '/config': setReconfigOpen(true); return true
154
+ case '/upgrade_tui': {
155
+ setVersionInfo(null)
156
+ setShowHelp(false)
157
+ if (onUpgradeTui) onUpgradeTui()
158
+ else setSlashError('当前宿主不支持 TUI 自升级')
159
+ return true
160
+ }
149
161
  case '/upgrade': {
150
162
  // 安装与重连进度都走 aimuxStatus(状态行),失败也会落进 aimuxStatus.detail,
151
163
  // 所以这里只管触发,不额外弹错。
@@ -157,7 +169,7 @@ export function ChatScreen({ client, ready, webUserId, resumeSessionId, onClear,
157
169
  case '/quit': case '/exit': onQuit(); return true
158
170
  default: return false
159
171
  }
160
- }, [aimuxStatus, chat, client.server, modelLabel, ready.prefs.model, onClear, onResume, onQuit, onLogout, onUpgradeAimux])
172
+ }, [aimuxStatus, chat, client.server, modelLabel, ready.prefs.model, onClear, onResume, onQuit, onLogout, onUpgradeAimux, onUpgradeTui])
161
173
 
162
174
  const onSubmit = useCallback((text: string): boolean => {
163
175
  const t = text.trim()
@@ -249,7 +261,7 @@ export function ChatScreen({ client, ready, webUserId, resumeSessionId, onClear,
249
261
  (entry) => rowsForEntry(entry),
250
262
  ), [transcriptEntries, rowsForEntry])
251
263
  const viewportRows = terminal.isTty ? Math.max(9, terminal.rows - 1) : terminal.rows
252
- const activityRows = (chat.typing ? 2 : 0) + (chat.error ? 1 : 0) + (slashError ? 1 : 0) + (versionInfo ? versionInfo.length + 2 : 0)
264
+ const activityRows = (chat.typing ? 2 : 0) + (chat.error ? 1 : 0) + (tuiUpgradeStatus ? 1 : 0) + (slashError ? 1 : 0) + (versionInfo ? versionInfo.length + 2 : 0)
253
265
  const helpRows = showHelp ? SLASH_COMMANDS.length + 3 : 0
254
266
  // Conversation chrome is exactly two rows: compact header + navigation.
255
267
  const transcriptRows = Math.max(1, viewportRows - composerRows - STATUS_ROWS - activityRows - helpRows - 2)
@@ -421,7 +433,7 @@ export function ChatScreen({ client, ready, webUserId, resumeSessionId, onClear,
421
433
  >
422
434
  <Box flexDirection="column" flexGrow={1} flexShrink={1} overflowY="hidden">
423
435
  {showWelcome
424
- ? <WelcomeCard ready={ready} columns={terminal.columns} resumed={Boolean(resumeSessionId)} modelDisplay={modelDisplay} />
436
+ ? <WelcomeCard ready={ready} columns={terminal.columns} resumed={Boolean(resumeSessionId)} modelDisplay={modelDisplay} aimuxStatus={aimuxStatus} />
425
437
  : <CompactHeader ready={ready} sessionId={chat.sessionId} columns={terminal.columns} />}
426
438
 
427
439
  {chat.switchedAway ? (
@@ -462,6 +474,7 @@ export function ChatScreen({ client, ready, webUserId, resumeSessionId, onClear,
462
474
  {chat.typing ? <WorkingIndicator firstQuery={firstQueryInFlight} /> : null}
463
475
  {chat.error ? <Text color="red">⚠ {chat.error}</Text> : null}
464
476
  {slashError ? <Text color="red">⚠ {slashError}</Text> : null}
477
+ {tuiUpgradeStatus ? <Text wrap="truncate-end" color={tuiUpgradeStatus.state === 'error' ? 'red' : tuiUpgradeStatus.state === 'success' ? 'green' : 'cyan'}>{tuiUpgradeStatus.detail}</Text> : null}
465
478
  {versionInfo ? <VersionBlock lines={versionInfo} /> : null}
466
479
 
467
480
  <Composer
@@ -508,7 +521,7 @@ function useTerminalSize(): TerminalSize {
508
521
  return size
509
522
  }
510
523
 
511
- function WelcomeCard({ ready, columns, resumed, modelDisplay }: { ready: ReadyState; columns: number; resumed: boolean; modelDisplay: string }) {
524
+ export function WelcomeCard({ ready, columns, resumed, modelDisplay, aimuxStatus }: { ready: ReadyState; columns: number; resumed: boolean; modelDisplay: string; aimuxStatus?: AimuxStatus }) {
512
525
  const cwd = compactPath(process.cwd())
513
526
  const width = Math.max(18, Math.min(68, columns - 4))
514
527
  const labelWidth = 11
@@ -525,6 +538,7 @@ function WelcomeCard({ ready, columns, resumed, modelDisplay }: { ready: ReadySt
525
538
  <MetaRow label="project:" value={ready.project.name} labelWidth={labelWidth} />
526
539
  <MetaRow label="task:" value={ready.issue.title} labelWidth={labelWidth} />
527
540
  <MetaRow label="directory:" value={cwd} labelWidth={labelWidth} />
541
+ <MetaRow label="aimux:" value={aimuxVersionLabel(aimuxStatus)} labelWidth={labelWidth} />
528
542
  </Box>
529
543
  <Box marginTop={1} paddingLeft={1}>
530
544
  <Text><Text bold>Tip:</Text> {resumed ? '已恢复历史会话;上下文会继续保留。' : '偏好按任务保存;下次进入会自动恢复模型、语言、Skill 与 Memory。'}</Text>
@@ -6,9 +6,13 @@
6
6
  export const EASY_DEFAULT_PROJECT_NAME = '快捷任务'
7
7
  export const EASY_DEFAULT_ISSUE_TITLE = '日常会话'
8
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 = '💡'
9
+ /**
10
+ * Picker labels: the easy default reads as "skip the choice".
11
+ * Icons carry a trailing space: emoji glyphs fill their two cells edge-to-edge,
12
+ * so an unspaced `📁name` reads as glued together in most terminal fonts.
13
+ */
14
+ export const EASY_PROJECT_LABEL = '🕊️ 不使用任何项目'
15
+ export const EASY_ISSUE_LABEL = '🕊️ 不使用任何任务'
16
+ export const CREATE_ITEM_ICON = '🚀 '
17
+ export const PROJECT_ITEM_ICON = '📁 '
18
+ export const ISSUE_ITEM_ICON = '💡 '
@@ -40,6 +40,31 @@ export function pidAlive(
40
40
  try { probe(pid, 0); return true } catch (e: any) { return e?.code === 'EPERM' }
41
41
  }
42
42
 
43
+ /** A daemon that has not written its heartbeat for this long is gone. */
44
+ export const DAEMON_HEARTBEAT_STALE_MS = 30_000
45
+
46
+ /*
47
+ * Whether the recorded daemon is still the process this owner started.
48
+ *
49
+ * A live PID is not proof: the OS recycles PIDs (so an unrelated process can
50
+ * inherit the number), and a defunct/zombie process still answers kill(pid, 0).
51
+ * The daemon writes `daemon_heartbeat_at` every 5s and nobody else writes it,
52
+ * so a fresh value is the only trustworthy "alive" signal. Older daemons do
53
+ * not write the field; for them fall back to the PID check.
54
+ */
55
+ export function daemonAlive(
56
+ runtime: { pid?: number; daemon_heartbeat_at?: number } | null | undefined,
57
+ now = Date.now(),
58
+ probe: (pid: number) => boolean = pidAlive,
59
+ ): boolean {
60
+ const beat = runtime?.daemon_heartbeat_at
61
+ if (typeof beat === 'number' && beat > 0) {
62
+ return now - beat <= DAEMON_HEARTBEAT_STALE_MS
63
+ }
64
+ const pid = runtime?.pid
65
+ return typeof pid === 'number' && Number.isFinite(pid) && pid > 0 && probe(pid)
66
+ }
67
+
43
68
  /*
44
69
  * Build the reverse connection arguments shared by both clients.
45
70
  */
@@ -0,0 +1,86 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { readFile, realpath, access } from 'node:fs/promises'
3
+ import path from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+ import { TUI_PACKAGE_NAME, TUI_VERSION } from './version.js'
6
+
7
+ const REGISTRY = 'https://registry.npmjs.org/'
8
+ const PACKAGE_ROOT = fileURLToPath(new URL('../', import.meta.url))
9
+ export type UpgradeRunner = (args: string[], timeout: number) => Promise<string>
10
+ export interface TuiUpgradeStatus { state: 'running' | 'success' | 'error'; detail: string }
11
+
12
+ // Use the prefix containing THIS installation, never npm's possibly unrelated
13
+ // configured default. Source checkouts, npx caches and pnpm stores are not global installs.
14
+ export function installationPrefix(root: string, platform = process.platform): string {
15
+ const p = platform === 'win32' ? path.win32 : path.posix
16
+ const normalized = p.normalize(root)
17
+ const suffix = p.join(...(platform === 'win32' ? [] : ['lib']), 'node_modules', '@mobius-os', 'mobius')
18
+ if (!normalized.endsWith(p.sep + suffix) || /[\\/](_npx|\.pnpm)[\\/]/.test(normalized)) {
19
+ throw new Error('当前 TUI 不是 npm 全局安装版,请先用 npm install -g @mobius-os/mobius@latest 安装,再运行 mobius。源码目录不会被覆盖。')
20
+ }
21
+ return normalized.slice(0, -suffix.length).replace(/[\\/]$/, '') || p.parse(normalized).root
22
+ }
23
+
24
+ async function npmCommand(): Promise<{ command: string; prefix: string[] }> {
25
+ if (process.platform !== 'win32') return { command: 'npm', prefix: [] }
26
+ // Avoid shell:true / cmd quoting. npm.cmd cannot be execFile'd directly.
27
+ const dirs = [path.dirname(process.execPath), ...(process.env.PATH || '').split(path.delimiter)]
28
+ for (const dir of dirs) {
29
+ const cli = path.join(dir.replace(/^"|"$/g, ''), 'node_modules', 'npm', 'bin', 'npm-cli.js')
30
+ try { await access(cli); return { command: process.execPath, prefix: [cli] } } catch { /* next */ }
31
+ }
32
+ throw new Error('找不到 npm,请安装包含 npm 的 Node.js 后重试。')
33
+ }
34
+
35
+ const runNpm: UpgradeRunner = async (args, timeout) => {
36
+ const { command, prefix } = await npmCommand()
37
+ return new Promise((resolve, reject) => {
38
+ execFile(command, [...prefix, ...args], {
39
+ cwd: path.dirname(process.execPath), timeout, maxBuffer: 2 * 1024 * 1024,
40
+ windowsHide: true, env: { ...process.env, NO_COLOR: '1' },
41
+ }, (error, stdout, stderr) => {
42
+ if (error) {
43
+ const detail = String(stderr || error.message).replace(/\x1b\[[0-9;]*[A-Za-z]/g, '').trim().slice(-1600)
44
+ reject(new Error(detail))
45
+ } else resolve(stdout.trim())
46
+ })
47
+ })
48
+ }
49
+
50
+ export async function performTuiUpgrade(
51
+ report: (status: TuiUpgradeStatus) => void,
52
+ options: { root?: string; platform?: NodeJS.Platform; run?: UpgradeRunner; currentVersion?: string } = {},
53
+ ): Promise<void> {
54
+ const root = await realpath(options.root ?? PACKAGE_ROOT)
55
+ const prefix = installationPrefix(root, options.platform)
56
+ const run = options.run ?? runNpm
57
+ report({ state: 'running', detail: '正在查询 npm 上的最新 TUI 版本…' })
58
+ const latest = JSON.parse(await run(['view', `${TUI_PACKAGE_NAME}@latest`, 'version', '--json', '--registry', REGISTRY], 60_000))
59
+ if (typeof latest !== 'string' || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(latest)) {
60
+ throw new Error('npm 返回的 TUI 版本无效,请稍后重试。')
61
+ }
62
+ const current = options.currentVersion ?? TUI_VERSION
63
+ const currentParts = current.split('.').map(Number)
64
+ const latestParts = latest.split('.').map(Number)
65
+ const firstDifference = currentParts.findIndex((part, i) => part !== latestParts[i])
66
+ const newerLocal = /^\d+\.\d+\.\d+$/.test(current) && /^\d+\.\d+\.\d+$/.test(latest)
67
+ && firstDifference >= 0 && currentParts[firstDifference] > latestParts[firstDifference]
68
+ if (latest === current || newerLocal) {
69
+ report({ state: 'success', detail: newerLocal ? `当前 TUI v${current} 高于 npm 最新版 v${latest},无需升级。` : `TUI v${current} 已是最新版本。` })
70
+ return
71
+ }
72
+ report({ state: 'running', detail: `正在升级 TUI:v${current} → v${latest},请勿退出…` })
73
+ await run(['install', '--global', '--prefix', prefix, `${TUI_PACKAGE_NAME}@${latest}`, '--registry', REGISTRY, '--no-audit', '--no-fund', '--prefer-online'], 600_000)
74
+ const installed = JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8'))
75
+ if (installed.version !== latest) throw new Error(`安装后版本校验失败:期望 ${latest},实际 ${installed.version}。`)
76
+ report({ state: 'success', detail: `TUI v${latest} 已安装。输入 /quit 后重新运行 mobius 生效,可用 /resume 恢复会话。` })
77
+ }
78
+
79
+ let upgrading = false
80
+ export async function upgradeTui(report: (status: TuiUpgradeStatus) => void): Promise<void> {
81
+ if (upgrading) return
82
+ upgrading = true
83
+ try { await performTuiUpgrade(report) }
84
+ catch (error) { report({ state: 'error', detail: `TUI 升级失败:${error instanceof Error ? error.message : String(error)}` }) }
85
+ finally { upgrading = false }
86
+ }
@@ -7,7 +7,10 @@ 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, 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'
10
+ import { AimuxSupervisor, probeAimuxBridgeConnection, BUNDLE_VER, bundleArch, bundleUrl, spawnLauncher, ensureFromBundle, ensureAimux, downloadBundleForTest, reverseConnectArgs, pickSilentFlag, alignTarget, compareAimuxVersions, followCheckIntervalMs, 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
+ import { aimuxVersionLabel } from '../src/components/AimuxStatus.js'
12
+ import { daemonAlive, DAEMON_HEARTBEAT_STALE_MS } from '../src/lib/aimux-protocol.js'
13
+ import { WelcomeCard } from '../src/components/Chat.js'
11
14
  import { parseElevatedGroups } from '../src/lib/windows-admin.js'
12
15
 
13
16
  const delay = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms))
@@ -470,6 +473,70 @@ function testAlignTarget() {
470
473
  ok(alignTarget('0.3.71', '0.3.71') === '0.3.71', 'an exact match targets that same version (no swap happens)')
471
474
  }
472
475
 
476
+ function testDaemonAlive() {
477
+ console.log('\n[AIMUX 6j] daemon liveness: the heartbeat beats a live PID')
478
+ const now = 1_000_000
479
+ const dead = () => false
480
+ const alive = () => true
481
+
482
+ ok(daemonAlive({ pid: 123, daemon_heartbeat_at: now - 1000 }, now, dead) === true,
483
+ 'a fresh heartbeat proves liveness even when kill(0) fails (defunct process)')
484
+ ok(daemonAlive({ pid: 123, daemon_heartbeat_at: now - DAEMON_HEARTBEAT_STALE_MS - 1 }, now, alive) === false,
485
+ 'a stale heartbeat plus a live PID means the number was recycled')
486
+ ok(daemonAlive({ pid: 123, daemon_heartbeat_at: now - DAEMON_HEARTBEAT_STALE_MS }, now, dead) === true,
487
+ 'exactly at the threshold still counts as alive')
488
+ ok(daemonAlive({ pid: 123 }, now, alive) === true,
489
+ 'an older daemon without the field still uses the PID check')
490
+ ok(daemonAlive({ pid: 123 }, now, dead) === false,
491
+ 'missing field and a dead PID is dead')
492
+ ok(daemonAlive(null, now, alive) === false, 'no runtime record is not alive')
493
+ ok(daemonAlive({ daemon_heartbeat_at: now - 5000 }, now, dead) === true,
494
+ 'a fresh heartbeat alone is enough')
495
+ }
496
+
497
+ function testWelcomeCardAimuxVersion() {
498
+ console.log('\n[AIMUX 6i] the welcome card reports the running aimux version')
499
+ ok(aimuxVersionLabel({ state: 'connected', version: '0.3.83' }) === 'v0.3.83', 'the running version is shown')
500
+ ok(aimuxVersionLabel({ state: 'starting' }) === '检测中…', 'before the supervisor reports, the card says it is checking')
501
+ ok(aimuxVersionLabel({ state: 'disabled' }) === '未启用', 'a disabled AIMUX is not presented as a version')
502
+ ok(aimuxVersionLabel(undefined) === '未启用', 'a host without AIMUX status does not invent a version')
503
+
504
+ const ready: any = {
505
+ project: { name: 'JEV 调研' },
506
+ issue: { title: '日常会话' },
507
+ prefs: { model: 'deepseek-flash', language: 'zh' },
508
+ }
509
+ const { lastFrame, unmount } = render(
510
+ <WelcomeCard ready={ready} columns={80} resumed={false} modelDisplay="deepseek-flash"
511
+ aimuxStatus={{ state: 'connected', version: '0.3.83' }} />,
512
+ )
513
+ const frame = lastFrame() ?? ''
514
+ ok(/aimux:\s+v0\.3\.83/.test(frame), 'the card renders an aimux row next to the other metadata')
515
+ unmount()
516
+ }
517
+
518
+ function testFollowServerVersion() {
519
+ console.log('\n[AIMUX 6h] follow the server version while the TUI stays open')
520
+ // 数字段比较:字符串比较会把 0.3.9 判成比 0.3.10 新。
521
+ ok(compareAimuxVersions('0.3.81', '0.3.77') === 1, 'a newer server version compares as newer')
522
+ ok(compareAimuxVersions('0.3.9', '0.3.10') === -1, 'numeric comparison handles multi-digit segments')
523
+ ok(compareAimuxVersions('0.3.81', '0.3.81') === 0, 'equal versions do not trigger an upgrade')
524
+ ok(compareAimuxVersions('0.3.77', '0.3.81') === -1, 'an older server version is never followed (no auto-downgrade)')
525
+ ok(compareAimuxVersions('v0.4.0', '0.3.81') === 1, 'a leading v is tolerated')
526
+ ok(compareAimuxVersions('0.3.81-beta', '0.3.81') === null, 'a non-numeric version is not acted on')
527
+ ok(compareAimuxVersions(null, '0.3.81') === null, 'an unknown server version is not acted on')
528
+ // 默认 30 分钟一轮;可被环境变量覆盖或关闭。
529
+ const previous = process.env.MOBIUS_TUI_AIMUX_FOLLOW_MS
530
+ delete process.env.MOBIUS_TUI_AIMUX_FOLLOW_MS
531
+ ok(followCheckIntervalMs() === 30 * 60 * 1000, 'the default follow interval is 30 minutes')
532
+ process.env.MOBIUS_TUI_AIMUX_FOLLOW_MS = '0'
533
+ ok(followCheckIntervalMs() === 0, 'setting 0 disables the follow check')
534
+ process.env.MOBIUS_TUI_AIMUX_FOLLOW_MS = '1234'
535
+ ok(followCheckIntervalMs() === 1234, 'an explicit interval is honoured')
536
+ if (previous === undefined) delete process.env.MOBIUS_TUI_AIMUX_FOLLOW_MS
537
+ else process.env.MOBIUS_TUI_AIMUX_FOLLOW_MS = previous
538
+ }
539
+
473
540
  function testAimuxIdentifierScopesWorkspace() {
474
541
  console.log('\n[AIMUX 6a] reverse client identifier workspace isolation')
475
542
  const first = tuiAimuxIdentifier('same-host', '/work/project-a')
@@ -630,6 +697,9 @@ async function main() {
630
697
  testElevationDetection()
631
698
  testGuiModeAvailability()
632
699
  testAlignTarget()
700
+ testFollowServerVersion()
701
+ testWelcomeCardAimuxVersion()
702
+ testDaemonAlive()
633
703
  await testFetchServerAimuxVersion()
634
704
  await testEnsureAimuxVersionSwap()
635
705
  testAimuxIdentifierScopesWorkspace()
package/tests/ui.test.tsx CHANGED
@@ -472,7 +472,7 @@ async function testPrepRender() {
472
472
  ok(!frame.includes('已有项目A - 第一行') && !frame.includes('已有项目B - 单行描述'), 'unfocused project rows omit their descriptions')
473
473
  stdin.write('\x1b[B'); await delay(15) // move focus from search to the list
474
474
  stdin.write('\x1b[B'); await delay(15) // highlight the pinned easy-default row
475
- ok((lastFrame() ?? '').includes('🕊️不使用任何项目 - 一键创建并进入'), 'easy-default project is pinned above the list')
475
+ ok((lastFrame() ?? '').includes('🕊️ 不使用任何项目 - 一键创建并进入'), 'easy-default project is pinned above the list')
476
476
  stdin.write('\x1b[B'); await delay(15) // step over the blank separator to the first project
477
477
  const selectedFrame = lastFrame() ?? ''
478
478
  ok(selectedFrame.includes('已有项目A - 第一行 ⏎ 第二行'), 'selected multi-line description stays on the main row')
@@ -1544,8 +1544,9 @@ async function testUpgradeSlash() {
1544
1544
  })
1545
1545
  try {
1546
1546
  let upgrades = 0
1547
+ let tuiUpgrades = 0
1547
1548
  const { stdin, lastFrame, unmount } = render(
1548
- <ChatScreen client={client} ready={ready} webUserId="u" onClear={() => {}} onResume={() => {}} onQuit={() => {}} onLogout={() => {}} onUpgradeAimux={() => { upgrades += 1 }} onReconfigure={() => {}} onConfigCancel={() => {}} />,
1549
+ <ChatScreen client={client} ready={ready} webUserId="u" onClear={() => {}} onResume={() => {}} onQuit={() => {}} onLogout={() => {}} onUpgradeAimux={() => { upgrades += 1 }} onUpgradeTui={() => { tuiUpgrades += 1 }} onReconfigure={() => {}} onConfigCancel={() => {}} />,
1549
1550
  )
1550
1551
  await delay(60)
1551
1552
  // 打全了命令名弹窗就收起,所以先在只打了前缀时看菜单里有没有它。
@@ -1554,8 +1555,11 @@ async function testUpgradeSlash() {
1554
1555
  ok(menu.includes('/upgrade'), '/upgrade is offered in the slash-command menu')
1555
1556
  stdin.write('rade'); await delay(40)
1556
1557
  stdin.write('\r'); await delay(80)
1557
- unmount()
1558
1558
  ok(upgrades === 1, '/upgrade calls the host upgrade hook exactly once')
1559
+ stdin.write('/upgrade_tui'); await delay(40); stdin.write('\r'); await delay(80)
1560
+ ok(tuiUpgrades === 1, '/upgrade_tui calls the TUI upgrade hook exactly once')
1561
+ ok(upgrades === 1, '/upgrade_tui does not upgrade AIMUX')
1562
+ unmount()
1559
1563
  } finally { restoreFetch() }
1560
1564
  }
1561
1565
 
@@ -0,0 +1,45 @@
1
+ import assert from 'node:assert/strict'
2
+ import { mkdtemp, mkdir, writeFile, rm } from 'node:fs/promises'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import { installationPrefix, performTuiUpgrade, type TuiUpgradeStatus } from '../src/upgrade-tui.js'
6
+
7
+ assert.equal(installationPrefix('/home/me/.local/lib/node_modules/@mobius-os/mobius', 'linux'), '/home/me/.local')
8
+ assert.equal(installationPrefix('C:\\Users\\Me\\AppData\\Roaming\\npm\\node_modules\\@mobius-os\\mobius', 'win32'), 'C:\\Users\\Me\\AppData\\Roaming\\npm')
9
+ assert.throws(() => installationPrefix('/work/mobius/tui', 'linux'), /不是 npm 全局安装/)
10
+ assert.throws(() => installationPrefix('/home/me/.npm/_npx/123/node_modules/@mobius-os/mobius', 'linux'))
11
+
12
+ const tmp = await mkdtemp(path.join(os.tmpdir(), 'tui upgrade test-'))
13
+ const root = path.join(tmp, 'lib/node_modules/@mobius-os/mobius')
14
+ await mkdir(root, { recursive: true })
15
+ try {
16
+ const statuses: TuiUpgradeStatus[] = []
17
+ const calls: string[][] = []
18
+ await performTuiUpgrade(s => statuses.push(s), {
19
+ root, platform: 'linux', currentVersion: '0.3.82',
20
+ run: async args => {
21
+ calls.push(args)
22
+ if (args[0] === 'view') return '"0.3.83"'
23
+ await writeFile(path.join(root, 'package.json'), JSON.stringify({ version: '0.3.83' }))
24
+ return ''
25
+ },
26
+ })
27
+ assert.equal(calls.length, 2)
28
+ assert.equal(calls[1][calls[1].indexOf('--prefix') + 1], tmp)
29
+ assert.ok(calls[1].includes('@mobius-os/mobius@0.3.83'))
30
+ assert.equal(statuses.at(-1)?.state, 'success')
31
+ assert.match(statuses.at(-1)!.detail, /重新运行 mobius/)
32
+ let count = 0
33
+ await performTuiUpgrade(() => {}, { root, platform: 'linux', currentVersion: '0.3.83', run: async () => { count++; return '"0.3.83"' } })
34
+ assert.equal(count, 1, 'already latest must not install')
35
+ count = 0
36
+ await performTuiUpgrade(() => {}, { root, platform: 'linux', currentVersion: '0.4.0', run: async () => { count++; return '"0.3.83"' } })
37
+ assert.equal(count, 1, 'newer local release must not be downgraded')
38
+ await assert.rejects(performTuiUpgrade(() => {}, { root, platform: 'linux', run: async () => '"invalid;command"' }), /版本无效/)
39
+ await assert.rejects(performTuiUpgrade(() => {}, { root, platform: 'linux', currentVersion: '0.3.82', run: async args => {
40
+ if (args[0] === 'view') return '"0.3.84"'
41
+ throw new Error('EACCES permission denied')
42
+ } }), /EACCES/)
43
+ await assert.rejects(performTuiUpgrade(() => {}, { root, platform: 'linux', currentVersion: '0.3.82', run: async args => args[0] === 'view' ? '"0.3.84"' : '' }), /版本校验失败/)
44
+ console.log('TUI upgrade tests passed: install prefixes, source/npx rejection, version lookup, upgrade, no-op, invalid response, install failure, verification failure')
45
+ } finally { await rm(tmp, { recursive: true, force: true }) }