@mobius-os/mobius 0.3.52 → 0.3.54
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 +265 -0
- package/package.json +25 -7
- package/scripts/build-python-bundles.sh +139 -0
- package/src/aimux.ts +85 -66
- package/tests/aimux.test.tsx +309 -0
- package/tests/flow.test.tsx +261 -0
- package/tests/integration.test.ts +125 -0
- package/tests/perf-typing.tsx +128 -0
- package/tests/preview.tsx +104 -0
- package/tests/reconnect.test.tsx +183 -0
- package/tests/resume.test.tsx +73 -0
- package/tests/screen.test.tsx +118 -0
- package/tests/scroll.test.tsx +259 -0
- package/tests/selection.test.tsx +226 -0
- package/tests/ui.test.tsx +1292 -0
- package/tests/viewport.test.ts +83 -0
- package/tsconfig.json +19 -0
- package/uninstall.ps1 +144 -0
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.
|
|
35
|
+
const AIMUX_TARGET_VERSION = '0.1.38'
|
|
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 = '
|
|
95
|
+
const BUNDLE_VER = '8'
|
|
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
|
|
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,42 @@ export function tuiAimuxIdentifier(hostname = os.hostname(), cwd = process.cwd()
|
|
|
353
352
|
return `tui-${host || 'pc'}-${aimuxWorkspaceHash(username, cwd)}`
|
|
354
353
|
}
|
|
355
354
|
|
|
356
|
-
// ── shared
|
|
357
|
-
|
|
358
|
-
|
|
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
|
|
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
|
-
|
|
375
|
-
|
|
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
|
-
|
|
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
|
-
|
|
387
|
-
async function touchLease(hash: string): Promise<void> {
|
|
373
|
+
async function touchWatchdog(hash: string): Promise<void> {
|
|
388
374
|
await ensureRuntimeDir()
|
|
389
|
-
const
|
|
390
|
-
try {
|
|
375
|
+
const file = runtimePath(hash)
|
|
376
|
+
try {
|
|
377
|
+
const raw = await fs.readFile(file, 'utf8')
|
|
378
|
+
const state = JSON.parse(raw) as Record<string, unknown>
|
|
379
|
+
state.last_feed_watchdog = Date.now()
|
|
380
|
+
const tmp = `${file}.tmp-${process.pid}`
|
|
381
|
+
await fs.writeFile(tmp, JSON.stringify(state), { mode: 0o600 })
|
|
382
|
+
await fs.rename(tmp, file)
|
|
383
|
+
} catch { /* AIMUX has not written runtime state yet */ }
|
|
391
384
|
}
|
|
392
385
|
|
|
393
386
|
function pidAlive(pid: number): boolean {
|
|
394
387
|
try { process.kill(pid, 0); return true } catch { return false }
|
|
395
388
|
}
|
|
396
389
|
|
|
390
|
+
|
|
397
391
|
/**
|
|
398
392
|
* Build the reverse-connect command in one place. On Windows the bridge shells
|
|
399
393
|
* must run headless or every remote command flashes a console and steals
|
|
@@ -412,12 +406,14 @@ export function reverseConnectArgs(
|
|
|
412
406
|
token: string,
|
|
413
407
|
platform: NodeJS.Platform = process.platform,
|
|
414
408
|
silentFlag: string | null = null,
|
|
409
|
+
runtimeFile: string | null = null,
|
|
415
410
|
): string[] {
|
|
416
411
|
return [
|
|
417
412
|
'reverse', 'connect', `${server.replace(/\/$/, '')}/aimux_bridge`,
|
|
418
413
|
'--identifier', identifier,
|
|
419
414
|
'--token', token,
|
|
420
415
|
'--replace',
|
|
416
|
+
...(runtimeFile ? ['--runtime', runtimeFile, '--watchdog', runtimeFile] : []),
|
|
421
417
|
...(platform === 'win32' && silentFlag ? [silentFlag] : []),
|
|
422
418
|
]
|
|
423
419
|
}
|
|
@@ -509,16 +505,16 @@ interface SupervisorOptions {
|
|
|
509
505
|
* The daemon is spawned detached (survives this TUI) and shared by every TUI in
|
|
510
506
|
* the same user+workspace. Two files under ~/.mobius/aimux-runtime/ coordinate
|
|
511
507
|
* it: a lease (mtime = "a TUI renewed me recently", content = daemon pid) and a
|
|
512
|
-
*
|
|
513
|
-
* is found; otherwise it
|
|
514
|
-
* killed on TUI exit — it is torn down when the lease expires (handled by aimux).
|
|
508
|
+
* runtime JSON is the shared watchdog state. A TUI only spawns when no live
|
|
509
|
+
* daemon is found; otherwise it feeds the watchdog and reuses it.
|
|
515
510
|
*/
|
|
516
511
|
export class AimuxSupervisor {
|
|
517
512
|
private stopping = false
|
|
518
513
|
private refreshingToken = false
|
|
519
514
|
private reconnectAttempt = 0
|
|
520
|
-
private
|
|
515
|
+
private watchdogTimer: ReturnType<typeof setTimeout> | null = null
|
|
521
516
|
private probeTimer: ReturnType<typeof setTimeout> | null = null
|
|
517
|
+
private bridgeFailures = 0
|
|
522
518
|
private opts: SupervisorOptions
|
|
523
519
|
private hash: string
|
|
524
520
|
constructor(opts: SupervisorOptions) { this.opts = opts; this.hash = aimuxWorkspaceHash() }
|
|
@@ -532,9 +528,12 @@ export class AimuxSupervisor {
|
|
|
532
528
|
|
|
533
529
|
/** Adopt an existing daemon if one is alive; otherwise spawn (under the lock). */
|
|
534
530
|
private async ensureDaemon(): Promise<void> {
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
531
|
+
if (this.stopping) return
|
|
532
|
+
const current = await readRuntime(this.hash)
|
|
533
|
+
const pid = current?.pid ?? null
|
|
534
|
+
if (current && pid !== null && pidAlive(pid)) {
|
|
535
|
+
await touchWatchdog(this.hash)
|
|
536
|
+
this.opts.onStatus({ state: 'starting', phase: 'heartbeat', detail: 'AIMUX runtime 已存在,复用中…', identifier: this.opts.identifier })
|
|
538
537
|
return
|
|
539
538
|
}
|
|
540
539
|
await this.spawnDaemon()
|
|
@@ -542,36 +541,27 @@ export class AimuxSupervisor {
|
|
|
542
541
|
|
|
543
542
|
/** Spawn the detached daemon exactly once, serialized by the path lock. */
|
|
544
543
|
private async spawnDaemon(): Promise<void> {
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
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
|
|
544
|
+
if (this.stopping) return
|
|
545
|
+
const current = await readRuntime(this.hash)
|
|
546
|
+
const pid = current?.pid ?? null
|
|
547
|
+
if (pid !== null && pidAlive(pid)) { await touchWatchdog(this.hash); return }
|
|
554
548
|
const { server, token, identifier, onStatus } = this.opts
|
|
555
549
|
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))
|
|
550
|
+
const child = this.opts.spawnProcess?.(token) ?? spawnDetachedDaemon({ kind: 'exe', path: aimuxExe() }, reverseConnectArgs(server, identifier, token, process.platform, null, runtimePath(this.hash)))
|
|
557
551
|
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
552
|
child.unref?.()
|
|
560
553
|
this.reconnectAttempt = 0
|
|
561
|
-
} finally {
|
|
562
|
-
if (release) await release()
|
|
563
|
-
}
|
|
564
554
|
}
|
|
565
555
|
|
|
566
556
|
/** Renew the lease every 5s while this TUI is alive. */
|
|
567
557
|
private startLeaseRenewal(): void {
|
|
568
558
|
const tick = () => {
|
|
569
559
|
if (this.stopping) return
|
|
570
|
-
void
|
|
571
|
-
this.
|
|
560
|
+
void touchWatchdog(this.hash).catch(() => {})
|
|
561
|
+
this.watchdogTimer = setTimeout(tick, LEASE_RENEW_MS)
|
|
572
562
|
}
|
|
573
|
-
void
|
|
574
|
-
this.
|
|
563
|
+
void touchWatchdog(this.hash).catch(() => {})
|
|
564
|
+
this.watchdogTimer = setTimeout(tick, LEASE_RENEW_MS)
|
|
575
565
|
}
|
|
576
566
|
|
|
577
567
|
private scheduleProbe(): void {
|
|
@@ -582,19 +572,26 @@ export class AimuxSupervisor {
|
|
|
582
572
|
/** Probe the bridge; refresh on auth error, respawn only when the daemon died. */
|
|
583
573
|
private async checkDaemon(): Promise<void> {
|
|
584
574
|
if (this.stopping) return
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
await this.
|
|
575
|
+
const raw = await (this.opts.probeConnection?.() ?? probeAimuxBridge(this.opts.server, this.opts.token, this.opts.identifier))
|
|
576
|
+
const probe: AimuxBridgeProbe = typeof raw === 'boolean' ? { connected: raw, authError: false } : raw
|
|
577
|
+
if (this.stopping) return
|
|
578
|
+
if (probe.authError) {
|
|
579
|
+
await this.setRuntimeRestartRequested()
|
|
580
|
+
await this.refreshCredentials('JWT 已过期')
|
|
590
581
|
} else if (probe.connected) {
|
|
591
582
|
this.reconnectAttempt = 0
|
|
592
583
|
this.opts.onStatus({ state: 'connected', phase: 'connected', detail: `心跳正常 · ${this.opts.identifier}`, identifier: this.opts.identifier })
|
|
584
|
+
this.bridgeFailures = 0
|
|
593
585
|
} else {
|
|
594
|
-
|
|
595
|
-
|
|
586
|
+
this.bridgeFailures += 1
|
|
587
|
+
await this.updateRuntimeHealth(false)
|
|
588
|
+
const runtime = await readRuntime(this.hash)
|
|
589
|
+
const pid = runtime?.pid ?? null
|
|
590
|
+
if (pid === null || !pidAlive(pid) || this.bridgeFailures >= BRIDGE_FAILURE_LIMIT) {
|
|
596
591
|
this.reconnectAttempt += 1
|
|
597
|
-
this.opts.onStatus({ state: 'failed', phase: 'retrying', detail: `AIMUX
|
|
592
|
+
this.opts.onStatus({ state: 'failed', phase: 'retrying', detail: `AIMUX bridge 无响应,重启连接中(第 ${this.reconnectAttempt} 次)…`, identifier: this.opts.identifier, attempt: this.reconnectAttempt })
|
|
593
|
+
if (pid !== null && pidAlive(pid)) { try { process.kill(pid, 'SIGTERM') } catch {} }
|
|
594
|
+
this.bridgeFailures = 0
|
|
598
595
|
await this.spawnDaemon()
|
|
599
596
|
} else {
|
|
600
597
|
// Daemon alive but stream down → transient; its own reconnect handles it.
|
|
@@ -604,6 +601,30 @@ export class AimuxSupervisor {
|
|
|
604
601
|
this.scheduleProbe()
|
|
605
602
|
}
|
|
606
603
|
|
|
604
|
+
private async updateRuntimeHealth(healthy: boolean): Promise<void> {
|
|
605
|
+
const file = runtimePath(this.hash)
|
|
606
|
+
try {
|
|
607
|
+
const state = JSON.parse(await fs.readFile(file, 'utf8')) as Record<string, unknown>
|
|
608
|
+
state.realtime_healthy_display = healthy
|
|
609
|
+
if (healthy) state.last_healthy_heartbeat = Date.now()
|
|
610
|
+
const tmp = `${file}.tmp-${process.pid}`
|
|
611
|
+
await fs.writeFile(tmp, JSON.stringify(state), { mode: 0o600 })
|
|
612
|
+
await fs.rename(tmp, file)
|
|
613
|
+
} catch {}
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
private async setRuntimeRestartRequested(): Promise<void> {
|
|
617
|
+
const file = runtimePath(this.hash)
|
|
618
|
+
try {
|
|
619
|
+
const state = JSON.parse(await fs.readFile(file, 'utf8')) as Record<string, unknown>
|
|
620
|
+
state.need_external_restart = true
|
|
621
|
+
state.realtime_healthy_display = false
|
|
622
|
+
const tmp = `${file}.tmp-${process.pid}`
|
|
623
|
+
await fs.writeFile(tmp, JSON.stringify(state), { mode: 0o600 })
|
|
624
|
+
await fs.rename(tmp, file)
|
|
625
|
+
} catch {}
|
|
626
|
+
}
|
|
627
|
+
|
|
607
628
|
private async refreshCredentials(reason: string): Promise<void> {
|
|
608
629
|
if (this.stopping || this.refreshingToken) return
|
|
609
630
|
const refreshToken = this.opts.refreshToken
|
|
@@ -628,13 +649,11 @@ export class AimuxSupervisor {
|
|
|
628
649
|
|
|
629
650
|
async stop(): Promise<void> {
|
|
630
651
|
this.stopping = true
|
|
631
|
-
if (this.
|
|
632
|
-
this.
|
|
652
|
+
if (this.watchdogTimer) clearTimeout(this.watchdogTimer)
|
|
653
|
+
this.watchdogTimer = null
|
|
633
654
|
if (this.probeTimer) clearTimeout(this.probeTimer)
|
|
634
655
|
this.probeTimer = null
|
|
635
|
-
|
|
636
|
-
// expires (no TUI renewing it for 10 minutes).
|
|
637
|
-
this.opts.onStatus({ state: 'stopped', phase: 'idle', detail: 'AIMUX 已停止(守护进程继续运行)', identifier: this.opts.identifier })
|
|
656
|
+
this.opts.onStatus({ state: 'stopped', phase: 'idle', detail: 'AIMUX watchdog 将在续租超时后停止', identifier: this.opts.identifier })
|
|
638
657
|
}
|
|
639
658
|
}
|
|
640
659
|
|
|
@@ -681,7 +700,7 @@ export async function startAimuxConnection(opts: {
|
|
|
681
700
|
const silentFlag = cachedSilentFlag
|
|
682
701
|
supervisor = new AimuxSupervisor({
|
|
683
702
|
server: opts.server, token: opts.token, identifier, onStatus, refreshToken: opts.refreshToken,
|
|
684
|
-
spawnProcess: token => spawnDetachedDaemon(launcher, reverseConnectArgs(opts.server, identifier, token, process.platform, silentFlag)),
|
|
703
|
+
spawnProcess: token => spawnDetachedDaemon(launcher, reverseConnectArgs(opts.server, identifier, token, process.platform, silentFlag, runtimePath(aimuxWorkspaceHash()))),
|
|
685
704
|
})
|
|
686
705
|
await supervisor.start()
|
|
687
706
|
})().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-v8') && 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-v8.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) })
|