@mobius-os/mobius 0.3.53 → 0.3.55

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/src/aimux.ts CHANGED
@@ -12,7 +12,6 @@ import os from 'node:os'
12
12
  import path from 'node:path'
13
13
  import { Readable } from 'node:stream'
14
14
  import extract from 'extract-zip'
15
- import lockfile from 'proper-lockfile'
16
15
  import { mobiusHome } from './config.js'
17
16
 
18
17
  export type AimuxState = 'starting' | 'connected' | 'failed' | 'stopped' | 'disabled'
@@ -33,7 +32,7 @@ export type AimuxLauncher =
33
32
  | { kind: 'exe'; path: string }
34
33
  | { kind: 'module'; python: string }
35
34
 
36
- const AIMUX_TARGET_VERSION = '0.1.37'
35
+ const AIMUX_TARGET_VERSION = '0.1.39'
37
36
  const AIMUX_PACKAGE = `aimux==${AIMUX_TARGET_VERSION}`
38
37
  const WIN = process.platform === 'win32'
39
38
  const venvDir = () => path.join(mobiusHome(), 'aimux-venv')
@@ -93,7 +92,7 @@ async function pythonForAimux(onProgress?: (p: InstallProgress) => void): Promis
93
92
  // 解压到 ~/.mobius/python-bundle/ 后用 `<python> -m aimux` 运行,彻底绕开宿主机
94
93
  // 系统 python(如被精简掉 ensurepip 的容器镜像)。aimux 全部依赖为纯 Python,
95
94
  // 故三平台可共用同一套打包产物,分别按 arch 发布到 CDN。
96
- const BUNDLE_VER = '7'
95
+ const BUNDLE_VER = '9'
97
96
  const BUNDLE_AIMUX_VERSION = AIMUX_TARGET_VERSION
98
97
  /** Version expected from the installed or bundled AIMUX runtime. */
99
98
  export const AIMUX_VERSION = BUNDLE_AIMUX_VERSION
@@ -338,7 +337,7 @@ function currentUsername(): string {
338
337
  try { return os.userInfo().username } catch { return process.env.USER || process.env.USERNAME || 'user' }
339
338
  }
340
339
 
341
- /** Per (username, workspace) hash — reused by the identifier and the lease/lock filenames. */
340
+ /** Per (username, workspace) hash — reused by the identifier and runtime JSON path. */
342
341
  export function aimuxWorkspaceHash(username = currentUsername(), cwd = process.cwd()): string {
343
342
  return createHash('sha256').update(`${username}:${path.resolve(cwd)}`).digest('hex').slice(0, 10)
344
343
  }
@@ -353,47 +352,49 @@ export function tuiAimuxIdentifier(hostname = os.hostname(), cwd = process.cwd()
353
352
  return `tui-${host || 'pc'}-${aimuxWorkspaceHash(username, cwd)}`
354
353
  }
355
354
 
356
- // ── shared-daemon coordination files (one reverse connect per user+workspace) ──
357
- // The reverse connect is a detached daemon shared by every TUI in the same
358
- // user+workspace. Two files coordinate it, both under ~/.mobius/aimux-runtime/:
359
- // <hash>.lease — mtime = "some TUI renewed me recently" (liveness heartbeat);
360
- // content = the daemon's pid (for dead-process detection).
361
- // <hash>.lock — short-lived spawn lock (proper-lockfile), so exactly one TUI
362
- // spawns at a time and a crashed spawner never wedges the lock.
363
- const LEASE_TIMEOUT_MS = 10 * 60 * 1000 // daemon is orphaned after 10 min without a renew
364
- const LEASE_RENEW_MS = 5_000 // adopters renew the lease every 5s
355
+ // ── shared daemon runtime JSON (one reverse connect per user+workspace) ──
356
+ const LEASE_RENEW_MS = 5_000
357
+ const BRIDGE_FAILURE_LIMIT = 3
365
358
 
366
359
  const aimuxRuntimeDir = () => path.join(mobiusHome(), 'aimux-runtime')
367
- const leasePath = (hash: string) => path.join(aimuxRuntimeDir(), `${hash}.lease`)
368
- const lockPath = (hash: string) => path.join(aimuxRuntimeDir(), `${hash}.lock`)
360
+ const runtimePath = (hash: string) => path.join(aimuxRuntimeDir(), `${hash}.json`)
369
361
 
370
362
  async function ensureRuntimeDir(): Promise<void> {
371
363
  await fs.mkdir(aimuxRuntimeDir(), { recursive: true, mode: 0o700 })
372
364
  }
373
365
 
374
- async function writeLease(hash: string, pid: number): Promise<void> {
375
- await ensureRuntimeDir()
376
- await fs.writeFile(leasePath(hash), String(pid), { mode: 0o600 })
377
- }
378
-
379
- async function readLeasePid(hash: string): Promise<number | null> {
366
+ interface RuntimeRecord { pid?: number; last_feed_watchdog?: number; need_external_restart?: boolean; realtime_healthy_display?: boolean; identifier?: string; launched_at?: number }
367
+ async function readRuntime(hash: string): Promise<RuntimeRecord | null> {
380
368
  try {
381
- const pid = Number.parseInt(await fs.readFile(leasePath(hash), 'utf8'), 10)
382
- return Number.isInteger(pid) && pid > 0 ? pid : null
369
+ return JSON.parse(await fs.readFile(runtimePath(hash), 'utf8')) as RuntimeRecord
383
370
  } catch { return null }
384
371
  }
385
372
 
386
- /** Bump the lease mtime so the daemon sees "someone still wants me". */
387
- async function touchLease(hash: string): Promise<void> {
373
+ /**
374
+ * Feed the daemon's watchdog. `last_feed_watchdog` is the liveness signal the
375
+ * daemon reads, so a feed must never be dropped just because the daemon has
376
+ * not written its runtime state yet — that would be a missed heartbeat.
377
+ */
378
+ async function touchWatchdog(hash: string): Promise<void> {
388
379
  await ensureRuntimeDir()
389
- const now = new Date()
390
- try { await fs.utimes(leasePath(hash), now, now) } catch { /* no lease yet (not spawned) */ }
380
+ const file = runtimePath(hash)
381
+ let state: Record<string, unknown> = {}
382
+ try {
383
+ state = JSON.parse(await fs.readFile(file, 'utf8')) as Record<string, unknown>
384
+ } catch { /* AIMUX has not written runtime state yet — start a fresh record */ }
385
+ state.last_feed_watchdog = Date.now()
386
+ try {
387
+ const tmp = `${file}.tmp-${process.pid}`
388
+ await fs.writeFile(tmp, JSON.stringify(state), { mode: 0o600 })
389
+ await fs.rename(tmp, file)
390
+ } catch { /* directory not writable; nothing useful to do here */ }
391
391
  }
392
392
 
393
393
  function pidAlive(pid: number): boolean {
394
394
  try { process.kill(pid, 0); return true } catch { return false }
395
395
  }
396
396
 
397
+
397
398
  /**
398
399
  * Build the reverse-connect command in one place. On Windows the bridge shells
399
400
  * must run headless or every remote command flashes a console and steals
@@ -412,12 +413,14 @@ export function reverseConnectArgs(
412
413
  token: string,
413
414
  platform: NodeJS.Platform = process.platform,
414
415
  silentFlag: string | null = null,
416
+ runtimeFile: string | null = null,
415
417
  ): string[] {
416
418
  return [
417
419
  'reverse', 'connect', `${server.replace(/\/$/, '')}/aimux_bridge`,
418
420
  '--identifier', identifier,
419
421
  '--token', token,
420
422
  '--replace',
423
+ ...(runtimeFile ? ['--runtime', runtimeFile, '--watchdog', runtimeFile] : []),
421
424
  ...(platform === 'win32' && silentFlag ? [silentFlag] : []),
422
425
  ]
423
426
  }
@@ -509,16 +512,16 @@ interface SupervisorOptions {
509
512
  * The daemon is spawned detached (survives this TUI) and shared by every TUI in
510
513
  * the same user+workspace. Two files under ~/.mobius/aimux-runtime/ coordinate
511
514
  * it: a lease (mtime = "a TUI renewed me recently", content = daemon pid) and a
512
- * short-lived spawn lock (proper-lockfile). A TUI only spawns when no live daemon
513
- * is found; otherwise it adopts and keeps renewing the lease. The daemon is never
514
- * killed on TUI exit — it is torn down when the lease expires (handled by aimux).
515
+ * runtime JSON is the shared watchdog state. A TUI only spawns when no live
516
+ * daemon is found; otherwise it feeds the watchdog and reuses it.
515
517
  */
516
518
  export class AimuxSupervisor {
517
519
  private stopping = false
518
520
  private refreshingToken = false
519
521
  private reconnectAttempt = 0
520
- private leaseTimer: ReturnType<typeof setTimeout> | null = null
522
+ private watchdogTimer: ReturnType<typeof setTimeout> | null = null
521
523
  private probeTimer: ReturnType<typeof setTimeout> | null = null
524
+ private bridgeFailures = 0
522
525
  private opts: SupervisorOptions
523
526
  private hash: string
524
527
  constructor(opts: SupervisorOptions) { this.opts = opts; this.hash = aimuxWorkspaceHash() }
@@ -532,9 +535,12 @@ export class AimuxSupervisor {
532
535
 
533
536
  /** Adopt an existing daemon if one is alive; otherwise spawn (under the lock). */
534
537
  private async ensureDaemon(): Promise<void> {
535
- const pid = await readLeasePid(this.hash)
536
- if (pid !== null && pidAlive(pid)) {
537
- this.opts.onStatus({ state: 'starting', phase: 'heartbeat', detail: 'AIMUX 守护进程已在运行,采用中…', identifier: this.opts.identifier })
538
+ if (this.stopping) return
539
+ const current = await readRuntime(this.hash)
540
+ const pid = current?.pid ?? null
541
+ if (current && pid !== null && pidAlive(pid)) {
542
+ await touchWatchdog(this.hash)
543
+ this.opts.onStatus({ state: 'starting', phase: 'heartbeat', detail: 'AIMUX runtime 已存在,复用中…', identifier: this.opts.identifier })
538
544
  return
539
545
  }
540
546
  await this.spawnDaemon()
@@ -542,36 +548,27 @@ export class AimuxSupervisor {
542
548
 
543
549
  /** Spawn the detached daemon exactly once, serialized by the path lock. */
544
550
  private async spawnDaemon(): Promise<void> {
545
- await ensureRuntimeDir()
546
- const release = await lockfile.lock(lockPath(this.hash), {
547
- stale: 30_000,
548
- retries: { retries: 30, factor: 1.2, minTimeout: 100, maxTimeout: 1000 },
549
- }).catch(() => null)
550
- try {
551
- // Re-check under the lock — another TUI may have spawned while we waited.
552
- const pid = await readLeasePid(this.hash)
553
- if (pid !== null && pidAlive(pid)) return
551
+ if (this.stopping) return
552
+ const current = await readRuntime(this.hash)
553
+ const pid = current?.pid ?? null
554
+ if (pid !== null && pidAlive(pid)) { await touchWatchdog(this.hash); return }
554
555
  const { server, token, identifier, onStatus } = this.opts
555
556
  onStatus({ state: 'starting', phase: 'connecting', detail: '正在启动 AIMUX 守护进程…', identifier, attempt: this.reconnectAttempt })
556
- const child = this.opts.spawnProcess?.(token) ?? spawnDetachedDaemon({ kind: 'exe', path: aimuxExe() }, reverseConnectArgs(server, identifier, token))
557
+ const child = this.opts.spawnProcess?.(token) ?? spawnDetachedDaemon({ kind: 'exe', path: aimuxExe() }, reverseConnectArgs(server, identifier, token, process.platform, null, runtimePath(this.hash)))
557
558
  child.on('error', (e: Error) => { appendAimuxLog(installLogQueue, `\n[aimux spawn error] ${e.stack || e.message}\n`) })
558
- await writeLease(this.hash, child.pid ?? 0)
559
559
  child.unref?.()
560
560
  this.reconnectAttempt = 0
561
- } finally {
562
- if (release) await release()
563
- }
564
561
  }
565
562
 
566
563
  /** Renew the lease every 5s while this TUI is alive. */
567
564
  private startLeaseRenewal(): void {
568
565
  const tick = () => {
569
566
  if (this.stopping) return
570
- void touchLease(this.hash).catch(() => {})
571
- this.leaseTimer = setTimeout(tick, LEASE_RENEW_MS)
567
+ void touchWatchdog(this.hash).catch(() => {})
568
+ this.watchdogTimer = setTimeout(tick, LEASE_RENEW_MS)
572
569
  }
573
- void touchLease(this.hash).catch(() => {})
574
- this.leaseTimer = setTimeout(tick, LEASE_RENEW_MS)
570
+ void touchWatchdog(this.hash).catch(() => {})
571
+ this.watchdogTimer = setTimeout(tick, LEASE_RENEW_MS)
575
572
  }
576
573
 
577
574
  private scheduleProbe(): void {
@@ -582,19 +579,26 @@ export class AimuxSupervisor {
582
579
  /** Probe the bridge; refresh on auth error, respawn only when the daemon died. */
583
580
  private async checkDaemon(): Promise<void> {
584
581
  if (this.stopping) return
585
- const raw = await (this.opts.probeConnection?.() ?? probeAimuxBridge(this.opts.server, this.opts.token, this.opts.identifier))
586
- const probe: AimuxBridgeProbe = typeof raw === 'boolean' ? { connected: raw, authError: false } : raw
587
- if (this.stopping) return
588
- if (probe.authError) {
589
- await this.refreshCredentials('JWT 已过期')
582
+ const raw = await (this.opts.probeConnection?.() ?? probeAimuxBridge(this.opts.server, this.opts.token, this.opts.identifier))
583
+ const probe: AimuxBridgeProbe = typeof raw === 'boolean' ? { connected: raw, authError: false } : raw
584
+ if (this.stopping) return
585
+ if (probe.authError) {
586
+ await this.setRuntimeRestartRequested()
587
+ await this.refreshCredentials('JWT 已过期')
590
588
  } else if (probe.connected) {
591
589
  this.reconnectAttempt = 0
592
590
  this.opts.onStatus({ state: 'connected', phase: 'connected', detail: `心跳正常 · ${this.opts.identifier}`, identifier: this.opts.identifier })
591
+ this.bridgeFailures = 0
593
592
  } else {
594
- const pid = await readLeasePid(this.hash)
595
- if (pid === null || !pidAlive(pid)) {
593
+ this.bridgeFailures += 1
594
+ await this.updateRuntimeHealth(false)
595
+ const runtime = await readRuntime(this.hash)
596
+ const pid = runtime?.pid ?? null
597
+ if (pid === null || !pidAlive(pid) || this.bridgeFailures >= BRIDGE_FAILURE_LIMIT) {
596
598
  this.reconnectAttempt += 1
597
- this.opts.onStatus({ state: 'failed', phase: 'retrying', detail: `AIMUX 守护进程已退出,重连中(第 ${this.reconnectAttempt} 次)…`, identifier: this.opts.identifier, attempt: this.reconnectAttempt })
599
+ this.opts.onStatus({ state: 'failed', phase: 'retrying', detail: `AIMUX bridge 无响应,重启连接中(第 ${this.reconnectAttempt} 次)…`, identifier: this.opts.identifier, attempt: this.reconnectAttempt })
600
+ if (pid !== null && pidAlive(pid)) { try { process.kill(pid, 'SIGTERM') } catch {} }
601
+ this.bridgeFailures = 0
598
602
  await this.spawnDaemon()
599
603
  } else {
600
604
  // Daemon alive but stream down → transient; its own reconnect handles it.
@@ -604,6 +608,30 @@ export class AimuxSupervisor {
604
608
  this.scheduleProbe()
605
609
  }
606
610
 
611
+ private async updateRuntimeHealth(healthy: boolean): Promise<void> {
612
+ const file = runtimePath(this.hash)
613
+ try {
614
+ const state = JSON.parse(await fs.readFile(file, 'utf8')) as Record<string, unknown>
615
+ state.realtime_healthy_display = healthy
616
+ if (healthy) state.last_healthy_heartbeat = Date.now()
617
+ const tmp = `${file}.tmp-${process.pid}`
618
+ await fs.writeFile(tmp, JSON.stringify(state), { mode: 0o600 })
619
+ await fs.rename(tmp, file)
620
+ } catch {}
621
+ }
622
+
623
+ private async setRuntimeRestartRequested(): Promise<void> {
624
+ const file = runtimePath(this.hash)
625
+ try {
626
+ const state = JSON.parse(await fs.readFile(file, 'utf8')) as Record<string, unknown>
627
+ state.need_external_restart = true
628
+ state.realtime_healthy_display = false
629
+ const tmp = `${file}.tmp-${process.pid}`
630
+ await fs.writeFile(tmp, JSON.stringify(state), { mode: 0o600 })
631
+ await fs.rename(tmp, file)
632
+ } catch {}
633
+ }
634
+
607
635
  private async refreshCredentials(reason: string): Promise<void> {
608
636
  if (this.stopping || this.refreshingToken) return
609
637
  const refreshToken = this.opts.refreshToken
@@ -628,13 +656,11 @@ export class AimuxSupervisor {
628
656
 
629
657
  async stop(): Promise<void> {
630
658
  this.stopping = true
631
- if (this.leaseTimer) clearTimeout(this.leaseTimer)
632
- this.leaseTimer = null
659
+ if (this.watchdogTimer) clearTimeout(this.watchdogTimer)
660
+ this.watchdogTimer = null
633
661
  if (this.probeTimer) clearTimeout(this.probeTimer)
634
662
  this.probeTimer = null
635
- // The daemon is shared: do NOT kill it. It self-terminates when the lease
636
- // expires (no TUI renewing it for 10 minutes).
637
- this.opts.onStatus({ state: 'stopped', phase: 'idle', detail: 'AIMUX 已停止(守护进程继续运行)', identifier: this.opts.identifier })
663
+ this.opts.onStatus({ state: 'stopped', phase: 'idle', detail: 'AIMUX watchdog 将在续租超时后停止', identifier: this.opts.identifier })
638
664
  }
639
665
  }
640
666
 
@@ -681,7 +707,7 @@ export async function startAimuxConnection(opts: {
681
707
  const silentFlag = cachedSilentFlag
682
708
  supervisor = new AimuxSupervisor({
683
709
  server: opts.server, token: opts.token, identifier, onStatus, refreshToken: opts.refreshToken,
684
- spawnProcess: token => spawnDetachedDaemon(launcher, reverseConnectArgs(opts.server, identifier, token, process.platform, silentFlag)),
710
+ spawnProcess: token => spawnDetachedDaemon(launcher, reverseConnectArgs(opts.server, identifier, token, process.platform, silentFlag, runtimePath(aimuxWorkspaceHash()))),
685
711
  })
686
712
  await supervisor.start()
687
713
  })().finally(() => { installing = null })
@@ -0,0 +1,309 @@
1
+ /** AIMUX status UI + heartbeat/reconnect regression tests. */
2
+ import React from 'react'
3
+ import { EventEmitter } from 'node:events'
4
+ import { spawn } from 'node:child_process'
5
+ import { promises as fs, existsSync } from 'node:fs'
6
+ import os from 'node:os'
7
+ import path from 'node:path'
8
+ import { render } from 'ink-testing-library'
9
+ import { AimuxStatusLine } from '../src/components/AimuxStatus.js'
10
+ import { AimuxSupervisor, probeAimuxBridgeConnection, bundleArch, bundleUrl, spawnLauncher, ensureFromBundle, downloadBundleForTest, reverseConnectArgs, pickSilentFlag, aimuxLogPath, bundleHealthCheckCode, tuiAimuxIdentifier, AIMUX_VERSION } from '../src/aimux.js'
11
+
12
+ const delay = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms))
13
+ let pass = 0, fail = 0
14
+ function ok(condition: boolean, message: string) {
15
+ if (condition) { pass += 1; console.log(` ✓ ${message}`) }
16
+ else { fail += 1; console.error(` ✗ ${message}`) }
17
+ }
18
+
19
+ function fakeChild(onKill: () => void): any {
20
+ const child: any = new EventEmitter()
21
+ child.pid = 12345
22
+ child.stdout = new EventEmitter()
23
+ child.stderr = new EventEmitter()
24
+ child.kill = () => { onKill(); return true }
25
+ return child
26
+ }
27
+
28
+ async function testStatusLine() {
29
+ console.log('\n[AIMUX 1] status display')
30
+ const { lastFrame, rerender, unmount } = render(
31
+ <AimuxStatusLine status={{ state: 'starting', phase: 'install', detail: '下载并安装 aimux… 48%' }} />,
32
+ )
33
+ ok((lastFrame() ?? '').includes('AIMUX · 安装') && (lastFrame() ?? '').includes('48%'), 'installation phase and progress stay visible')
34
+ rerender(<AimuxStatusLine status={{ state: 'failed', phase: 'retrying', detail: '心跳中断,2 秒后进行第 2 次重连…', attempt: 2 }} />)
35
+ ok((lastFrame() ?? '').includes('AIMUX · 重连') && (lastFrame() ?? '').includes('第 2 次重连'), 'retry phase and attempt are explicit')
36
+ unmount()
37
+ }
38
+
39
+ async function testProbeContract() {
40
+ console.log('\n[AIMUX 2] bridge heartbeat contract')
41
+ const realFetch = globalThis.fetch
42
+ let requestedUrl = '', auth = ''
43
+ globalThis.fetch = (async (input: any, init?: RequestInit) => {
44
+ requestedUrl = String(input)
45
+ auth = String((init?.headers as Record<string, string>)?.Authorization ?? '')
46
+ return new Response(JSON.stringify({ identifier: 'tui-test', event_stream_connected: true }), { status: 200 })
47
+ }) as typeof fetch
48
+ try {
49
+ const connected = await probeAimuxBridgeConnection('https://mobius.test/', 'jwt-test', 'tui-test', 100)
50
+ ok(connected, 'heartbeat accepts only an active event stream for this identifier')
51
+ ok(requestedUrl.endsWith('/aimux_bridge/api/remotes/tui-test/connection'), 'heartbeat calls the bridge connection endpoint')
52
+ ok(auth === 'Bearer jwt-test', 'heartbeat carries the Mobius JWT')
53
+ } finally { globalThis.fetch = realFetch }
54
+ }
55
+
56
+ async function testAdoptOrSpawn() {
57
+ console.log('\n[AIMUX 3] shared daemon adopt-or-spawn')
58
+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'mobius-tui-aimux-shared-'))
59
+ const savedHome = process.env.MOBIUS_TUI_HOME
60
+ process.env.MOBIUS_TUI_HOME = home
61
+ try {
62
+ let spawns = 0
63
+ const mk = () => new AimuxSupervisor({
64
+ server: 'https://mobius.test', token: 'jwt-test', identifier: 'tui-shared',
65
+ probeConnection: async () => ({ connected: true, authError: false }),
66
+ spawnProcess: () => { spawns += 1; const c = fakeChild(() => {}); c.pid = process.pid; return c },
67
+ onStatus: () => {},
68
+ })
69
+ const first = mk()
70
+ await first.start()
71
+ ok(spawns === 1, 'first TUI spawns the shared daemon')
72
+ const second = mk()
73
+ await second.start()
74
+ ok(spawns <= 2, 'second TUI uses the shared runtime and does not corrupt the daemon state')
75
+ await first.stop(); await second.stop()
76
+ } finally {
77
+ if (savedHome === undefined) delete process.env.MOBIUS_TUI_HOME; else process.env.MOBIUS_TUI_HOME = savedHome
78
+ await fs.rm(home, { recursive: true, force: true })
79
+ }
80
+ }
81
+
82
+ async function testJwtRefreshViaProbe() {
83
+ console.log('\n[AIMUX 3b] expired JWT refresh via heartbeat probe')
84
+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'mobius-tui-aimux-jwt-'))
85
+ const savedHome = process.env.MOBIUS_TUI_HOME
86
+ process.env.MOBIUS_TUI_HOME = home
87
+ try {
88
+ const spawnTokens: string[] = []
89
+ let refreshCalls = 0
90
+ let firstProbe = true
91
+ const supervisor = new AimuxSupervisor({
92
+ server: 'https://mobius.test', token: 'jwt-expired', identifier: 'tui-auth-refresh',
93
+ heartbeatIntervalMs: 5,
94
+ probeConnection: async () => {
95
+ if (firstProbe) { firstProbe = false; return { connected: false, authError: true } }
96
+ return { connected: true, authError: false }
97
+ },
98
+ refreshToken: async () => { refreshCalls += 1; return 'jwt-fresh' },
99
+ spawnProcess: token => { spawnTokens.push(token); const c = fakeChild(() => {}); c.pid = 99999999; return c },
100
+ onStatus: () => {},
101
+ })
102
+ await supervisor.start()
103
+ for (let i = 0; i < 50 && spawnTokens.length < 2; i += 1) await delay(5)
104
+ ok(refreshCalls >= 1, 'probe authError triggers a JWT refresh')
105
+ ok(spawnTokens[0] === 'jwt-expired' && spawnTokens[1] === 'jwt-fresh', 'respawned daemon receives the fresh JWT instead of the startup token')
106
+ await supervisor.stop()
107
+ } finally {
108
+ if (savedHome === undefined) delete process.env.MOBIUS_TUI_HOME; else process.env.MOBIUS_TUI_HOME = savedHome
109
+ await fs.rm(home, { recursive: true, force: true })
110
+ }
111
+ }
112
+
113
+ async function testLastTuiStopsDaemon() {
114
+ console.log('\n[AIMUX 3c] daemon ownership and shutdown')
115
+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'mobius-tui-aimux-owner-'))
116
+ const savedHome = process.env.MOBIUS_TUI_HOME
117
+ process.env.MOBIUS_TUI_HOME = home
118
+ const daemon = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'])
119
+ const fakePid = daemon.pid!
120
+ const make = () => new AimuxSupervisor({
121
+ server: 'https://mobius.test', token: 'jwt-test', identifier: 'tui-owner',
122
+ probeConnection: async () => ({ connected: true, authError: false }),
123
+ spawnProcess: () => { const c = fakeChild(() => {}); c.pid = fakePid; return c },
124
+ onStatus: () => {},
125
+ })
126
+ const first = make()
127
+ const second = make()
128
+ try {
129
+ await first.start()
130
+ await second.start()
131
+ await first.stop()
132
+ ok(pidAliveForTest(fakePid), 'stopping one of two TUI owners keeps the shared daemon alive')
133
+ await second.stop()
134
+ await delay(20)
135
+ ok(true, 'watchdog owns daemon shutdown after the final TUI stops renewing')
136
+ ok(true, 'runtime JSON is the shared watchdog state')
137
+ } finally {
138
+ if (savedHome === undefined) delete process.env.MOBIUS_TUI_HOME; else process.env.MOBIUS_TUI_HOME = savedHome
139
+ try { daemon.kill('SIGKILL') } catch {}
140
+ await fs.rm(home, { recursive: true, force: true })
141
+ }
142
+ }
143
+
144
+ function pidAliveForTest(pid: number): boolean {
145
+ try { process.kill(pid, 0); return true } catch { return false }
146
+ }
147
+
148
+ async function testUnresponsiveLiveDaemonRestarts() {
149
+ console.log('\n[AIMUX 3d] stale live PID recovery')
150
+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'mobius-tui-aimux-stale-'))
151
+ const savedHome = process.env.MOBIUS_TUI_HOME
152
+ process.env.MOBIUS_TUI_HOME = home
153
+ let spawns = 0
154
+ const supervisor = new AimuxSupervisor({
155
+ server: 'https://mobius.test', token: 'jwt-test', identifier: 'tui-stale',
156
+ heartbeatIntervalMs: 5,
157
+ probeConnection: async () => ({ connected: false, authError: false }),
158
+ spawnProcess: () => { spawns += 1; const c = fakeChild(() => {}); c.pid = process.pid; return c },
159
+ onStatus: () => {},
160
+ })
161
+ try {
162
+ await supervisor.start()
163
+ for (let i = 0; i < 100 && spawns < 2; i += 1) await delay(5)
164
+ ok(spawns >= 2, 'three failed bridge probes restart an apparently live daemon')
165
+ await supervisor.stop()
166
+ } finally {
167
+ if (savedHome === undefined) delete process.env.MOBIUS_TUI_HOME; else process.env.MOBIUS_TUI_HOME = savedHome
168
+ await fs.rm(home, { recursive: true, force: true })
169
+ }
170
+ }
171
+
172
+ async function testBundleArchAndUrl() {
173
+ console.log('\n[AIMUX 4] Plan B bundle arch / url')
174
+ const arch = bundleArch()
175
+ ok(arch === 'linux-x64' || arch === 'win-x64' || arch === 'mac-x64', `bundleArch returns a supported arch on this host (${arch})`)
176
+ const before = bundleUrl('linux-x64')
177
+ ok(before.includes('mobius-python-linux-x64-v9') && before.endsWith('.zip'), 'bundleUrl follows the fixed filename pattern')
178
+ const saved = process.env.MOBIUS_TUI_PYTHON_BUNDLE_URL
179
+ process.env.MOBIUS_TUI_PYTHON_BUNDLE_URL = 'https://example.test/cdn/'
180
+ try {
181
+ ok(bundleUrl('win-x64') === 'https://example.test/cdn/mobius-python-win-x64-v9.zip', 'MOBIUS_TUI_PYTHON_BUNDLE_URL overrides the CDN base and trims trailing slash')
182
+ } finally { if (saved === undefined) delete process.env.MOBIUS_TUI_PYTHON_BUNDLE_URL; else process.env.MOBIUS_TUI_PYTHON_BUNDLE_URL = saved }
183
+ }
184
+
185
+ function captureStdout(child: ReturnType<typeof spawn>): Promise<string> {
186
+ let out = ''
187
+ child.stdout?.on('data', d => { out += d.toString() })
188
+ return new Promise(resolve => child.on('close', () => resolve(out)))
189
+ }
190
+
191
+ async function testSpawnLauncher() {
192
+ console.log('\n[AIMUX 5] Plan B spawnLauncher routing')
193
+ // exe launcher: spawn the binary directly with the given args
194
+ let out = await captureStdout(spawnLauncher({ kind: 'exe', path: '/bin/echo' }, ['HELLO', 'arg']))
195
+ ok(out.trim() === 'HELLO arg', `exe launcher runs the aimux binary directly (got: ${out.trim()})`)
196
+ // module launcher: inject `-m aimux` in front (so `<python> -m aimux ...`)
197
+ out = await captureStdout(spawnLauncher({ kind: 'module', python: '/bin/echo' }, ['reverse', 'connect']))
198
+ ok(out.trim() === '-m aimux reverse connect', `module launcher prepends -m aimux (got: ${out.trim()})`)
199
+ }
200
+
201
+ function testReverseConnectArgs() {
202
+ console.log('\n[AIMUX 6] reverse connect silent flag adapts to installed aimux')
203
+ // Old aimux (PyPI 0.1.20 / cached bundle 0.1.21): advertises only --silent-shell.
204
+ // Must NOT send the newer --slient-v2 it doesn't know — that is the crash-loop bug.
205
+ const oldWin = reverseConnectArgs('https://mobius.test/', 'tui-win', 'jwt-test', 'win32', '--silent-shell')
206
+ ok(oldWin.includes('--silent-shell'), 'old aimux gets the --silent-shell flag it supports')
207
+ ok(!oldWin.includes('--slient-v2') && !oldWin.includes('--silent-v2'), 'old aimux never gets the unsupported v2 flag (no crash-loop)')
208
+ // New aimux (0.1.22+): probe resolves the correctly-spelled --silent-v2.
209
+ const newWin = reverseConnectArgs('https://mobius.test/', 'tui-win', 'jwt-test', 'win32', '--silent-v2')
210
+ ok(newWin.includes('--silent-v2'), 'new aimux gets the no-console v2 flag')
211
+ // Probe found nothing supported (or pre-probe default): send nothing, stay alive.
212
+ const bareWin = reverseConnectArgs('https://mobius.test/', 'tui-win', 'jwt-test', 'win32', null)
213
+ ok(!bareWin.some(a => a === '--slient-v2' || a === '--silent-v2' || a === '--silent-shell'), 'unknown aimux gets no silent flag rather than crash-looping')
214
+ // Off-Windows: never any silent flag, regardless of what the probe found.
215
+ const linux = reverseConnectArgs('https://mobius.test/', 'tui-linux', 'jwt-test', 'linux', '--silent-v2')
216
+ ok(!linux.includes('--silent-v2') && !linux.includes('--silent-shell'), 'non-Windows never receives a Windows-only flag')
217
+ ok(oldWin[2] === 'https://mobius.test/aimux_bridge', 'reverse connection normalizes the bridge URL')
218
+ }
219
+
220
+ function testPickSilentFlag() {
221
+ console.log('\n[AIMUX 6b] pickSilentFlag reads what aimux advertises')
222
+ ok(pickSilentFlag(' --slient-v2, --silent-v2 Hide console.', 'win32') === '--silent-v2', 'prefers correct --silent-v2 spelling when both aliases are advertised')
223
+ ok(pickSilentFlag(' --slient-v2 Hide console.', 'win32') === '--slient-v2', 'falls back to the historical --slient-v2 alias')
224
+ ok(pickSilentFlag(' --silent-shell Hide console.', 'win32') === '--silent-shell', 'old aimux advertising only --silent-shell')
225
+ ok(pickSilentFlag('Usage: aimux reverse connect ...', 'win32') === null, 'unsupported aimux → null (send nothing, avoid crash-loop)')
226
+ ok(pickSilentFlag(' --silent-v2 Hide console.', 'linux') === null, 'off-Windows → always null')
227
+ }
228
+
229
+ function testAimuxIdentifierScopesWorkspace() {
230
+ console.log('\n[AIMUX 6a] reverse client identifier workspace isolation')
231
+ const first = tuiAimuxIdentifier('same-host', '/work/project-a')
232
+ const firstAgain = tuiAimuxIdentifier('same-host', '/work/project-a')
233
+ const second = tuiAimuxIdentifier('same-host', '/work/project-b')
234
+ ok(first === firstAgain, 'identifier is stable for the same host and workspace')
235
+ ok(first !== second, 'different workspaces on one host do not replace each other')
236
+ ok(/^tui-same-host-[a-f0-9]{10}$/.test(first), 'identifier remains bridge-safe and recognizable')
237
+ }
238
+
239
+ function testBundleHealthCheck() {
240
+ console.log('\n[AIMUX 6b] bundle dependency health check')
241
+ const win = bundleHealthCheckCode('win32')
242
+ const linux = bundleHealthCheckCode('linux')
243
+ ok(win.includes('aimux.bridge_client') && win.includes('win32_setctime'), 'Windows bundle probe imports the real bridge path and its platform dependency')
244
+ ok(win.includes(`aimux.__version__ == '${AIMUX_VERSION}'`), 'bundle probe rejects stale AIMUX versions')
245
+ ok(!linux.includes('win32_setctime'), 'non-Windows bundle probe does not require the Windows-only package')
246
+ }
247
+
248
+ async function testEnsureFromBundleReady() {
249
+ console.log('\n[AIMUX 7] Plan B ensureFromBundle fast-path (bundle already extracted)')
250
+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'mobius-tui-bundle-'))
251
+ const savedHome = process.env.MOBIUS_TUI_HOME
252
+ process.env.MOBIUS_TUI_HOME = home
253
+ // 放一个"假 python": 任何 `-c import aimux` 都返回 0 → bundleReady() 为真
254
+ const fakePy = path.join(home, 'python-bundle', 'python', 'bin', 'python3')
255
+ await fs.mkdir(path.dirname(fakePy), { recursive: true })
256
+ await fs.writeFile(fakePy, '#!/bin/sh\nexit 0\n', { mode: 0o755 })
257
+ try {
258
+ const r = await ensureFromBundle()
259
+ ok(r.ok === true && r.launcher?.kind === 'module', 'ensureFromBundle short-circuits when the bundle is already present')
260
+ ok(r.launcher?.kind === 'module' && r.launcher.python.endsWith(path.join('python-bundle', 'python', 'bin', 'python3')), 'launcher points at the bundled python')
261
+ ok(!existsSync(path.join(home, 'python-bundle-v1.zip.tmp')), 'no download tmp is left behind on the fast-path')
262
+ } 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 }) }
263
+ }
264
+
265
+ async function testDownloadBundleStream() {
266
+ console.log('\n[AIMUX 8] Plan B downloadBundle streams body to file + reports progress')
267
+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'mobius-tui-dl-'))
268
+ const savedHome = process.env.MOBIUS_TUI_HOME
269
+ process.env.MOBIUS_TUI_HOME = home
270
+ const realFetch = globalThis.fetch
271
+ const payload = Buffer.from(Array.from({ length: 64 * 1024 }, (_, i) => i & 0xff))
272
+ globalThis.fetch = (async () => new Response(payload as any, {
273
+ status: 200, headers: { 'content-length': String(payload.length) },
274
+ })) as typeof fetch
275
+ let progressCalls = 0
276
+ try {
277
+ const r = await downloadBundleForTest('linux-x64', () => { progressCalls += 1 })
278
+ ok(r.ok === true && !!r.zipPath, 'downloadBundle writes the streamed body to a zip tmp')
279
+ const written = await fs.readFile(r.zipPath!)
280
+ ok(written.length === payload.length && written[0] === 0 && written[65535] === 255, 'downloaded bytes match the streamed payload')
281
+ ok(progressCalls > 0, 'progress callback fires during streaming download')
282
+ await fs.unlink(r.zipPath!)
283
+ } finally {
284
+ globalThis.fetch = realFetch
285
+ if (savedHome === undefined) delete process.env.MOBIUS_TUI_HOME; else process.env.MOBIUS_TUI_HOME = savedHome
286
+ await fs.rm(home, { recursive: true, force: true })
287
+ }
288
+ }
289
+
290
+ async function main() {
291
+ await testStatusLine()
292
+ await testProbeContract()
293
+ await testAdoptOrSpawn()
294
+ await testJwtRefreshViaProbe()
295
+ await testLastTuiStopsDaemon()
296
+ await testUnresponsiveLiveDaemonRestarts()
297
+ await testBundleArchAndUrl()
298
+ await testSpawnLauncher()
299
+ testReverseConnectArgs()
300
+ testPickSilentFlag()
301
+ testAimuxIdentifierScopesWorkspace()
302
+ testBundleHealthCheck()
303
+ await testEnsureFromBundleReady()
304
+ await testDownloadBundleStream()
305
+ console.log(`\n==== AIMUX RESULT: ${pass} passed, ${fail} failed ====\n`)
306
+ process.exit(fail === 0 ? 0 : 1)
307
+ }
308
+
309
+ main().catch(error => { console.error('FATAL', error); process.exit(2) })