@mobius-os/mobius 0.3.74 → 0.3.76
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 +16 -0
- package/install.ps1 +44 -5
- package/package.json +1 -1
- package/src/App.tsx +29 -1
- package/src/aimux.ts +2 -134
- package/src/components/AimuxStatus.tsx +5 -2
- package/src/components/Chat.tsx +79 -24
- package/src/config.ts +17 -0
- package/src/lib/aimux-protocol.ts +108 -0
- package/src/lib/host-text.ts +35 -0
- package/tests/flow.test.tsx +20 -0
- package/tests/ui.test.tsx +80 -1
- package/uninstall.ps1 +4 -8
package/README.md
CHANGED
|
@@ -43,6 +43,22 @@ Enter your Mobius server URL and username (most servers are passwordless).
|
|
|
43
43
|
On success the token is saved and the next launch auto-logs in
|
|
44
44
|
(validated via `/api/auth/me`; re-login on expiry).
|
|
45
45
|
|
|
46
|
+
For unattended starts the credentials can come from the environment instead:
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
MOBIUS_TUI_SERVER=https://your-mobius-server.example.com \
|
|
50
|
+
MOBIUS_TUI_USERNAME=alice \
|
|
51
|
+
MOBIUS_TUI_PASSWORD=... # optional; leave unset on passwordless servers
|
|
52
|
+
mobius
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
When both `MOBIUS_TUI_SERVER` and `MOBIUS_TUI_USERNAME` are set, the TUI logs in
|
|
56
|
+
immediately, saves the token to `~/.mobius/login.json`, and skips the login
|
|
57
|
+
form. A partial environment is ignored, and a failed environment login falls
|
|
58
|
+
back to the stored login or the form (the reason is shown in the boot message).
|
|
59
|
+
Environment credentials win over `login.json`, so a stale token cannot beat an
|
|
60
|
+
explicitly stated account.
|
|
61
|
+
|
|
46
62
|
After a successful login the TUI also starts its local AIMUX reverse connection
|
|
47
63
|
in the background. The first run creates `~/.mobius/aimux-venv` and installs
|
|
48
64
|
the `aimux` Python package, then runs:
|
package/install.ps1
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
文件夹空白处注册两个 Explorer 右键入口:“在Mobius终端中打开”与
|
|
11
11
|
“在Mobius终端中打开(管理员权限)”。
|
|
12
12
|
.EXAMPLE
|
|
13
|
-
irm https://serve.nutshellai.cn/publish/auto/mobiustui/install-
|
|
13
|
+
irm https://serve.nutshellai.cn/publish/auto/mobiustui/install-v18.ps1 | iex
|
|
14
14
|
#>
|
|
15
15
|
$ErrorActionPreference = 'Stop'
|
|
16
16
|
$ProgressPreference = 'SilentlyContinue'
|
|
@@ -212,6 +212,9 @@ if ($userPath -notlike "*$binDir*") {
|
|
|
212
212
|
# Directory\Background\shell\Mobius = 右键文件夹空白处,目标参数 %V
|
|
213
213
|
# ...\MobiusAdmin = 同样的两处,UAC 提权后启动(管理员权限)
|
|
214
214
|
# 使用 .cmd 辅助启动器,避免右键动作依赖 PowerShell ExecutionPolicy。
|
|
215
|
+
$logsDir = Join-Path $MHOME "logs"
|
|
216
|
+
New-Item -ItemType Directory -Force -Path $logsDir | Out-Null
|
|
217
|
+
|
|
215
218
|
$openHereCmd = Join-Path $binDir "mobius-open-here.cmd"
|
|
216
219
|
$openHereLines = @(
|
|
217
220
|
'@echo off',
|
|
@@ -219,19 +222,55 @@ $openHereLines = @(
|
|
|
219
222
|
'set "MOBIUS_TARGET=%~1"',
|
|
220
223
|
'if not defined MOBIUS_TARGET set "MOBIUS_TARGET=%CD%"',
|
|
221
224
|
'cd /d "%MOBIUS_TARGET%"',
|
|
225
|
+
'> "%USERPROFILE%\.mobius\logs\launcher.log" echo %DATE% %TIME% start target=%MOBIUS_TARGET%',
|
|
222
226
|
'call "%~dp0mobius.cmd"',
|
|
227
|
+
'>> "%USERPROFILE%\.mobius\logs\launcher.log" echo %DATE% %TIME% exit=%ERRORLEVEL%',
|
|
223
228
|
'endlocal'
|
|
224
229
|
)
|
|
225
230
|
Set-Content -Path $openHereCmd -Value $openHereLines -Encoding ASCII
|
|
226
231
|
|
|
227
232
|
# 管理员入口: Explorer 直接跑这个脚本, 由它用 UAC 提权拉起同一个启动器.
|
|
228
233
|
# -Encoding UTF8 在 Windows PowerShell 5.1 会写入 BOM, -File 才能正确读中文/引号.
|
|
234
|
+
# 优先显式拉起 Windows Terminal: 隐藏父窗口创建的控制台不会被默认终端接管,
|
|
235
|
+
# 落到 conhost 后中文/歧义宽度字符按 2 列渲染, TUI 右对齐的行会折行.
|
|
236
|
+
# Use Windows Terminal explicitly: the hidden parent's console is not handed to
|
|
237
|
+
# the default terminal, and conhost renders wide/ambiguous chars in 2 cells.
|
|
229
238
|
$openHereAdminPs1 = Join-Path $binDir "mobius-open-here-admin.ps1"
|
|
239
|
+
# 生成的管理员脚本刻意只用 ASCII 注释: Windows PowerShell 5.1 会把无 BOM 的 .ps1
|
|
240
|
+
# 当 ANSI 读, 中文字符串可能吃掉后面的 { }, 而这份脚本会被 apply-patch 之类不写 BOM
|
|
241
|
+
# 的工具直接改; 用纯 ASCII 就没有这个隐患.
|
|
242
|
+
# The generated script stays ASCII-only: Windows PowerShell 5.1 reads a BOM-less
|
|
243
|
+
# .ps1 as ANSI, so non-ASCII text can swallow following braces; tools that rewrite
|
|
244
|
+
# files without a BOM (apply-patch) would otherwise break it.
|
|
230
245
|
$openHereAdminLines = @(
|
|
231
246
|
'param([string]$Target)',
|
|
232
|
-
'#
|
|
233
|
-
'
|
|
234
|
-
'
|
|
247
|
+
'# Diagnostic log, overwritten on every launch so a flash-and-close can be explained later.',
|
|
248
|
+
'$log = Join-Path $env:USERPROFILE ".mobius\logs\admin-launch.log"',
|
|
249
|
+
'try {',
|
|
250
|
+
' New-Item -ItemType Directory -Force -Path (Split-Path $log) | Out-Null',
|
|
251
|
+
'# Explorer passes the folder path; fall back to the current directory.',
|
|
252
|
+
' if (-not $Target) { $Target = (Get-Location).Path }',
|
|
253
|
+
' $launcher = Join-Path $PSScriptRoot "mobius-open-here.cmd"',
|
|
254
|
+
' $shell = New-Object -ComObject Shell.Application',
|
|
255
|
+
' $wt = Join-Path $env:LOCALAPPDATA "Microsoft\WindowsApps\wt.exe"',
|
|
256
|
+
' if (Test-Path $wt) {',
|
|
257
|
+
'# wt takes the start directory with -d and runs the same launcher via cmd.',
|
|
258
|
+
'# Elevation is mandatory: without runas this menu opens a normal-privilege',
|
|
259
|
+
'# terminal, so the TUI can never offer its high-privilege GUI mode.',
|
|
260
|
+
'# ShellExecute rather than Start-Process: the hidden parent would otherwise',
|
|
261
|
+
'# hand down a hidden startup state; the 5th argument 1 = SW_SHOWNORMAL.',
|
|
262
|
+
' $wtArgs = ''-d "{0}" cmd.exe /d /s /c ""{1}" "{2}""'' -f $Target, $launcher, $Target',
|
|
263
|
+
' $shell.ShellExecute($wt, $wtArgs, $PSScriptRoot, "runas", 1)',
|
|
264
|
+
' "$(Get-Date -Format o) launched wt elevated target=$Target launcher=$launcher" | Set-Content -Path $log',
|
|
265
|
+
' } else {',
|
|
266
|
+
' $commandLine = ''/d /s /c ""{0}" "{1}""'' -f $launcher, $Target',
|
|
267
|
+
'# The 5th argument 1 = SW_SHOWNORMAL, forcing the elevated window to be visible.',
|
|
268
|
+
' $shell.ShellExecute($env:ComSpec, $commandLine, $PSScriptRoot, "runas", 1)',
|
|
269
|
+
' "$(Get-Date -Format o) launched conhost target=$Target launcher=$launcher" | Set-Content -Path $log',
|
|
270
|
+
' }',
|
|
271
|
+
'} catch {',
|
|
272
|
+
' "$(Get-Date -Format o) failed: $($_.Exception.Message)" | Set-Content -Path $log',
|
|
273
|
+
'}'
|
|
235
274
|
)
|
|
236
275
|
Set-Content -Path $openHereAdminPs1 -Value $openHereAdminLines -Encoding UTF8
|
|
237
276
|
|
|
@@ -282,7 +321,7 @@ Write-Host "右键文件夹或文件夹空白处,可选择: 在Mobius终端中
|
|
|
282
321
|
try {
|
|
283
322
|
Invoke-MobiusInstall
|
|
284
323
|
} catch {
|
|
285
|
-
$errorLog = Join-Path $env:TEMP "mobius-install-
|
|
324
|
+
$errorLog = Join-Path $env:TEMP "mobius-install-v18-error.log"
|
|
286
325
|
$errorText = $_ | Format-List * -Force | Out-String
|
|
287
326
|
$errorText | Set-Content -Path $errorLog -Encoding UTF8
|
|
288
327
|
Write-Host ""
|
package/package.json
CHANGED
package/src/App.tsx
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
import React, { useEffect, useRef, useState } from 'react'
|
|
13
13
|
import { Box, Text } from 'ink'
|
|
14
14
|
import { MobiusClient, getMe, login, ApiError } from './api.js'
|
|
15
|
-
import { clearLogin, loadLogin, saveLogin, type LoginRecord } from './config.js'
|
|
15
|
+
import { clearLogin, loadLogin, loginFromEnv, saveLogin, type LoginRecord } from './config.js'
|
|
16
16
|
import { LoginScreen } from './components/Login.js'
|
|
17
17
|
import { PrepScreen, type ReadyState } from './components/PrepScreen.js'
|
|
18
18
|
import { ChatScreen } from './components/Chat.js'
|
|
@@ -77,6 +77,34 @@ export function App() {
|
|
|
77
77
|
|
|
78
78
|
// ── bootstrap ──────────────────────────────────────────────────────────────
|
|
79
79
|
useEffect(() => { (async () => {
|
|
80
|
+
// Environment credentials win over the stored login: an unattended start
|
|
81
|
+
// (container entrypoint, CI, a launcher that already knows the account)
|
|
82
|
+
// must not be silently beaten by a stale login.json.
|
|
83
|
+
const envLogin = loginFromEnv()
|
|
84
|
+
if (envLogin) {
|
|
85
|
+
setBootMsg('使用环境变量登录…')
|
|
86
|
+
try {
|
|
87
|
+
const r = await login(envLogin.server, envLogin.username, envLogin.password)
|
|
88
|
+
const rec: LoginRecord = {
|
|
89
|
+
server: envLogin.server,
|
|
90
|
+
username: envLogin.username,
|
|
91
|
+
password: envLogin.password,
|
|
92
|
+
token: r.token,
|
|
93
|
+
user: r.user,
|
|
94
|
+
}
|
|
95
|
+
await saveLogin(rec)
|
|
96
|
+
const envClient = new MobiusClient(rec.server, rec.token)
|
|
97
|
+
setUserId(r.user.id)
|
|
98
|
+
setClient(envClient)
|
|
99
|
+
setRoute('prep')
|
|
100
|
+
bootAimux(rec, envClient)
|
|
101
|
+
return
|
|
102
|
+
} catch (e: any) {
|
|
103
|
+
// Fall back to the stored login or the form; the user still gets to
|
|
104
|
+
// see why the environment credentials did not work.
|
|
105
|
+
setBootMsg(`环境变量登录失败: ${e?.message ?? String(e)}`)
|
|
106
|
+
}
|
|
107
|
+
}
|
|
80
108
|
const rec = await loadLogin()
|
|
81
109
|
if (!rec) { setRoute('login'); return }
|
|
82
110
|
setPrefill({ server: rec.server, username: rec.username })
|
package/src/aimux.ts
CHANGED
|
@@ -6,7 +6,6 @@
|
|
|
6
6
|
* currently authenticated Mobius server. Nothing is started before login.
|
|
7
7
|
*/
|
|
8
8
|
import { spawn, spawnSync, type ChildProcess, type StdioOptions } from 'node:child_process'
|
|
9
|
-
import { createHash } from 'node:crypto'
|
|
10
9
|
import { promises as fs, existsSync, createWriteStream, mkdirSync, openSync, closeSync, readFileSync, writeFileSync } from 'node:fs'
|
|
11
10
|
import os from 'node:os'
|
|
12
11
|
import path from 'node:path'
|
|
@@ -14,6 +13,8 @@ import { Readable } from 'node:stream'
|
|
|
14
13
|
import extract from 'extract-zip'
|
|
15
14
|
import { mobiusHome } from './config.js'
|
|
16
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'
|
|
17
|
+
export { alignTarget, aimuxWorkspaceHash, pidAlive, reverseConnectArgs, pickSilentFlag, pickEnableGuiFlag, pickGuiNoElevateFlag, pickGuiArgs, type GuiMode } from './lib/aimux-protocol.js'
|
|
17
18
|
|
|
18
19
|
export type AimuxState = 'starting' | 'connected' | 'failed' | 'stopped' | 'disabled'
|
|
19
20
|
export type AimuxPhase = 'idle' | 'python' | 'venv' | 'install' | 'connecting' | 'heartbeat' | 'retrying' | 'connected'
|
|
@@ -33,11 +34,6 @@ export type AimuxLauncher =
|
|
|
33
34
|
| { kind: 'exe'; path: string }
|
|
34
35
|
| { kind: 'module'; python: string }
|
|
35
36
|
|
|
36
|
-
/**
|
|
37
|
-
* 兜底 pin:只在读不到服务端版本时用(老 broker / 网络不通),**不是**"最低可用版本"。
|
|
38
|
-
* 正常情况下连接时会读服务端 broker 的 aimux 版本,本地跟它对齐(升级、降级都一样)。
|
|
39
|
-
*/
|
|
40
|
-
const AIMUX_TARGET_VERSION = '0.3.72'
|
|
41
37
|
const WIN = process.platform === 'win32'
|
|
42
38
|
const venvDir = () => path.join(mobiusHome(), 'aimux-venv')
|
|
43
39
|
const venvPython = () => WIN ? path.join(venvDir(), 'Scripts', 'python.exe') : path.join(venvDir(), 'bin', 'python')
|
|
@@ -319,17 +315,6 @@ function installedAimuxVersion(): string | null {
|
|
|
319
315
|
return pythonAimuxVersion(venvPython())
|
|
320
316
|
}
|
|
321
317
|
|
|
322
|
-
/**
|
|
323
|
-
* 连接前要装的版本:**服务端 broker 跑的那个版本**。
|
|
324
|
-
*
|
|
325
|
-
* 服务端版本读不到(老 broker 没有 /api/health 的 version 字段、或网络不通)时退回 pin——
|
|
326
|
-
* 宁可不动,也不要凭猜测给用户换一个版本。
|
|
327
|
-
*/
|
|
328
|
-
export function alignTarget(serverVersion: string | null | undefined, pin = AIMUX_TARGET_VERSION): string {
|
|
329
|
-
const v = typeof serverVersion === 'string' ? serverVersion.trim() : ''
|
|
330
|
-
return v || pin
|
|
331
|
-
}
|
|
332
|
-
|
|
333
318
|
/**
|
|
334
319
|
* 读服务端 broker 的 aimux 版本(`GET <server>/aimux_bridge/api/health`)。
|
|
335
320
|
* 经 mobius 代理转发:这里带的 token 是登录 JWT,代理会换成 broker token。
|
|
@@ -452,16 +437,6 @@ export async function ensureAimux(onProgress?: (p: InstallProgress) => void, tar
|
|
|
452
437
|
return { ok: false, error: `${venvError};内置运行时也失败: ${bundle.error}` }
|
|
453
438
|
}
|
|
454
439
|
|
|
455
|
-
/** Effective OS user (not `$USER`, which sudo/containers can pollute). */
|
|
456
|
-
function currentUsername(): string {
|
|
457
|
-
try { return os.userInfo().username } catch { return process.env.USER || process.env.USERNAME || 'user' }
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
/** Per (username, workspace) hash — reused by the identifier and runtime JSON path. */
|
|
461
|
-
export function aimuxWorkspaceHash(username = currentUsername(), cwd = process.cwd()): string {
|
|
462
|
-
return createHash('sha256').update(`${username}:${path.resolve(cwd)}`).digest('hex').slice(0, 10)
|
|
463
|
-
}
|
|
464
|
-
|
|
465
440
|
// ── GUI (computer use) authorization ─────────────────────────────────────
|
|
466
441
|
// Machine-level choice made in the first-run wizard.
|
|
467
442
|
//
|
|
@@ -486,7 +461,6 @@ export function aimuxWorkspaceHash(username = currentUsername(), cwd = process.c
|
|
|
486
461
|
// elevated windows
|
|
487
462
|
// elevate GUI helper that can also drive administrator windows
|
|
488
463
|
// Either authorized mode registers as gui-<host>-<hash>.
|
|
489
|
-
export type GuiMode = 'off' | 'no-elevate' | 'elevate'
|
|
490
464
|
|
|
491
465
|
/** Whether a mode can be offered here, and if not, what the user must change. */
|
|
492
466
|
export interface GuiModeAvailability { available: boolean; reason?: string }
|
|
@@ -662,59 +636,6 @@ async function touchWatchdog(hash: string): Promise<void> {
|
|
|
662
636
|
} catch { /* directory not writable; nothing useful to do here */ }
|
|
663
637
|
}
|
|
664
638
|
|
|
665
|
-
/**
|
|
666
|
-
* Is `pid` still running? `process.kill(pid, 0)` is the only portable probe, and
|
|
667
|
-
* its *error* carries the answer: ESRCH means gone, EPERM means the process is
|
|
668
|
-
* there and simply not ours to signal. EPERM is the normal case now that
|
|
669
|
-
* --enable-gui makes the daemon an elevated process while the TUI stays
|
|
670
|
-
* unelevated (and it is the classic cross-user case on POSIX). Reading EPERM as
|
|
671
|
-
* dead is what made the supervisor kill and respawn healthy daemons on every
|
|
672
|
-
* bridge hiccup.
|
|
673
|
-
*/
|
|
674
|
-
export function pidAlive(
|
|
675
|
-
pid: number,
|
|
676
|
-
probe: (pid: number, signal: number) => void = (p, s) => process.kill(p, s),
|
|
677
|
-
): boolean {
|
|
678
|
-
try { probe(pid, 0); return true } catch (e: any) { return e?.code === 'EPERM' }
|
|
679
|
-
}
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
/**
|
|
683
|
-
* Build the reverse-connect command in one place. On Windows the bridge shells
|
|
684
|
-
* must run headless or every remote command flashes a console and steals
|
|
685
|
-
* keyboard focus from the TUI — but *which* flag asks for that depends on the
|
|
686
|
-
* installed aimux: `--silent-shell` landed in 0.1.18, the no-console
|
|
687
|
-
* `--slient-v2`/`--silent-v2` only in 0.1.22+. PyPI and cached bundles in the
|
|
688
|
-
* wild are often older, and hard-coding any one spelling makes Click reject the
|
|
689
|
-
* whole command ("No such option: --slient-v2") and the supervisor crash-loop.
|
|
690
|
-
* So the caller probes `reverse connect --help` once (see probeReverseConnectHelp
|
|
691
|
-
* + pickSilentFlag) and passes the flag aimux actually advertises; when nothing
|
|
692
|
-
* is supported we send nothing rather than crash.
|
|
693
|
-
*/
|
|
694
|
-
export function reverseConnectArgs(
|
|
695
|
-
server: string,
|
|
696
|
-
identifier: string,
|
|
697
|
-
token: string,
|
|
698
|
-
platform: NodeJS.Platform = process.platform,
|
|
699
|
-
silentFlag: string | null = null,
|
|
700
|
-
runtimeFile: string | null = null,
|
|
701
|
-
enableGui = false,
|
|
702
|
-
guiNoElevate = false,
|
|
703
|
-
): string[] {
|
|
704
|
-
return [
|
|
705
|
-
'reverse', 'connect', `${server.replace(/\/$/, '')}/aimux_bridge`,
|
|
706
|
-
'--identifier', identifier,
|
|
707
|
-
'--token', token,
|
|
708
|
-
'--replace',
|
|
709
|
-
...(runtimeFile ? ['--runtime', runtimeFile, '--watchdog', runtimeFile] : []),
|
|
710
|
-
...(platform === 'win32' && silentFlag ? [silentFlag] : []),
|
|
711
|
-
...(enableGui ? ['--enable-gui'] : []),
|
|
712
|
-
// Only meaningful next to --enable-gui: it skips that flag's elevation
|
|
713
|
-
// request, and without --enable-gui there is no request to skip.
|
|
714
|
-
...(enableGui && guiNoElevate ? ['--gui-no-elevate'] : []),
|
|
715
|
-
]
|
|
716
|
-
}
|
|
717
|
-
|
|
718
639
|
/**
|
|
719
640
|
* Capture `aimux reverse connect --help` so we can see which console-hiding
|
|
720
641
|
* flags this particular build advertises. Returns '' on any failure (the
|
|
@@ -732,38 +653,6 @@ export async function probeReverseConnectHelp(launcher: AimuxLauncher): Promise<
|
|
|
732
653
|
}
|
|
733
654
|
}
|
|
734
655
|
|
|
735
|
-
/**
|
|
736
|
-
* Pick the strongest console-hiding flag aimux advertised for Windows. Prefers
|
|
737
|
-
* the correctly-spelled --silent-v2 (future-proof if the historical --slient-v2
|
|
738
|
-
* typo alias is ever dropped), then the --slient-v2 alias, then --silent-shell.
|
|
739
|
-
* Returns null off-Windows or when the installed aimux supports none.
|
|
740
|
-
*/
|
|
741
|
-
export function pickSilentFlag(helpText: string, platform: NodeJS.Platform = process.platform): string | null {
|
|
742
|
-
if (platform !== 'win32') return null
|
|
743
|
-
if (/--silent-v2\b/.test(helpText)) return '--silent-v2'
|
|
744
|
-
if (/--slient-v2\b/.test(helpText)) return '--slient-v2'
|
|
745
|
-
if (/--silent-shell\b/.test(helpText)) return '--silent-shell'
|
|
746
|
-
return null
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
/**
|
|
750
|
-
* Does this aimux build advertise --enable-gui (0.3.64+)? Older installs
|
|
751
|
-
* reject unknown options outright, so the flag is only sent when the help
|
|
752
|
-
* text confirms it — same defensive pattern as pickSilentFlag.
|
|
753
|
-
*/
|
|
754
|
-
export function pickEnableGuiFlag(helpText: string): boolean {
|
|
755
|
-
return /--enable-gui\b/.test(helpText)
|
|
756
|
-
}
|
|
757
|
-
|
|
758
|
-
/**
|
|
759
|
-
* Does this aimux build advertise --gui-no-elevate? It landed in the same
|
|
760
|
-
* 0.3.64 release as --enable-gui, but probe it separately: sending it to a
|
|
761
|
-
* build that lacks it is the same "No such option" crash-loop.
|
|
762
|
-
*/
|
|
763
|
-
export function pickGuiNoElevateFlag(helpText: string): boolean {
|
|
764
|
-
return /--gui-no-elevate\b/.test(helpText)
|
|
765
|
-
}
|
|
766
|
-
|
|
767
656
|
/** Result of a bridge heartbeat: is the stream up, and did the JWT just get rejected? */
|
|
768
657
|
export interface AimuxBridgeProbe { connected: boolean; authError: boolean }
|
|
769
658
|
|
|
@@ -1063,27 +952,6 @@ export function effectiveGuiMode(
|
|
|
1063
952
|
return elevated ? 'elevate' : 'no-elevate'
|
|
1064
953
|
}
|
|
1065
954
|
|
|
1066
|
-
/**
|
|
1067
|
-
* The GUI flags to send, given the stored mode, this TUI's own privilege and
|
|
1068
|
-
* what the installed aimux advertises.
|
|
1069
|
-
*
|
|
1070
|
-
* Pure so the rule can be tested directly. The rule is that an unelevated TUI may
|
|
1071
|
-
* only ever send the pair that requests nothing; when the installed build cannot
|
|
1072
|
-
* express that, it sends no GUI flags at all rather than risk a daemon start that
|
|
1073
|
-
* blocks on a consent prompt the supervisor can neither see nor clean up.
|
|
1074
|
-
*/
|
|
1075
|
-
export function pickGuiArgs(
|
|
1076
|
-
mode: GuiMode,
|
|
1077
|
-
elevated: boolean,
|
|
1078
|
-
supports: { enable: boolean; noElevate: boolean },
|
|
1079
|
-
platform: NodeJS.Platform = process.platform,
|
|
1080
|
-
): { enableGui: boolean; guiNoElevate: boolean } {
|
|
1081
|
-
if (mode === 'off' || !supports.enable) return { enableGui: false, guiNoElevate: false }
|
|
1082
|
-
if (platform !== 'win32') return { enableGui: true, guiNoElevate: mode === 'no-elevate' && supports.noElevate }
|
|
1083
|
-
if (elevated) return { enableGui: true, guiNoElevate: false }
|
|
1084
|
-
return supports.noElevate ? { enableGui: true, guiNoElevate: true } : { enableGui: false, guiNoElevate: false }
|
|
1085
|
-
}
|
|
1086
|
-
|
|
1087
955
|
/** pickGuiArgs bound to the stored mode, this process's token and the probe caches. */
|
|
1088
956
|
function resolvedGuiArgs(): { enableGui: boolean; guiNoElevate: boolean } {
|
|
1089
957
|
return pickGuiArgs(
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import React from 'react'
|
|
2
2
|
import { Box, Text } from 'ink'
|
|
3
3
|
import type { AimuxStatus } from '../aimux.js'
|
|
4
|
+
import { hostText } from '../lib/host-text.js'
|
|
4
5
|
|
|
5
6
|
const STYLE: Record<AimuxStatus['state'], { icon: string; color: 'green' | 'yellow' | 'red' | 'gray' }> = {
|
|
6
7
|
connected: { icon: '●', color: 'green' },
|
|
@@ -15,14 +16,16 @@ const STYLE: Record<AimuxStatus['state'], { icon: string; color: 'green' | 'yell
|
|
|
15
16
|
export function aimuxStatusText(status: AimuxStatus, compact = false): string {
|
|
16
17
|
const phase = status.phase && !['idle', 'connected'].includes(status.phase) ? ` · ${phaseLabel(status.phase)}` : ''
|
|
17
18
|
const detail = status.detail || stateLabel(status.state)
|
|
18
|
-
|
|
19
|
+
// conhost 把 · 等歧义字符画成两列, Ink 只算一列 → 右侧内容溢出.
|
|
20
|
+
// conhost draws ambiguous glyphs two cells wide while Ink counts one.
|
|
21
|
+
return hostText(`AIMUX${phase} · ${compact ? compactDetail(detail) : detail}`)
|
|
19
22
|
}
|
|
20
23
|
|
|
21
24
|
export function AimuxStatusLine({ status, compact = false }: { status: AimuxStatus; compact?: boolean }) {
|
|
22
25
|
const style = STYLE[status.state]
|
|
23
26
|
return (
|
|
24
27
|
<Box>
|
|
25
|
-
<Text color={style.color}>{style.icon}</Text>
|
|
28
|
+
<Text color={style.color}>{hostText(style.icon)}</Text>
|
|
26
29
|
<Text dimColor={status.state === 'disabled' || status.state === 'stopped'}>
|
|
27
30
|
{' ' + aimuxStatusText(status, compact)}
|
|
28
31
|
</Text>
|
package/src/components/Chat.tsx
CHANGED
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
type RowAnchor,
|
|
23
23
|
} from '../lib/transcript-viewport.js'
|
|
24
24
|
import type { ReadyState } from './PrepScreen.js'
|
|
25
|
+
import { IS_CONHOST, hostText } from '../lib/host-text.js'
|
|
25
26
|
import type { AnyEntry } from '../types.js'
|
|
26
27
|
import { ConfigFlow, ReconfigFlow, type ConfigResult } from './ConfigFlow.js'
|
|
27
28
|
import { AIMUX_VERSION, type AimuxStatus } from '../aimux.js'
|
|
@@ -56,6 +57,17 @@ interface TerminalSize {
|
|
|
56
57
|
import { TUI_VERSION } from '../version.js'
|
|
57
58
|
const DEFAULT_COMPOSER_ROWS = 5
|
|
58
59
|
const STATUS_ROWS = 3
|
|
60
|
+
const AIMUX_HEARTBEAT_BLOCKED_MESSAGE = 'AIMUX 正在等待 bridge 心跳确认,暂时无法提交问题;连接恢复后请再次按 Enter。'
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The heartbeat phase means the local daemon exists, but the server has not
|
|
64
|
+
* confirmed its reverse connection yet. Creating a session in that window can
|
|
65
|
+
* start an agent with an unavailable AIMUX remote, so keep the prompt local
|
|
66
|
+
* until the supervisor reports `connected`.
|
|
67
|
+
*/
|
|
68
|
+
export function isAimuxQuestionSubmissionBlocked(status?: AimuxStatus): boolean {
|
|
69
|
+
return status?.state === 'starting' && status.phase === 'heartbeat'
|
|
70
|
+
}
|
|
59
71
|
|
|
60
72
|
const SLASH_COMMANDS = [
|
|
61
73
|
{ cmd: '/clear', desc: '清空当前对话,开启新会话' },
|
|
@@ -72,6 +84,7 @@ const SLASH_COMMANDS = [
|
|
|
72
84
|
|
|
73
85
|
export function ChatScreen({ client, ready, webUserId, resumeSessionId, onClear, onResume, onQuit, onLogout, onUpgradeAimux, onReconfigure, onConfigCancel, aimuxStatus }: ChatProps) {
|
|
74
86
|
const chat = useChat({ client, ready, resumeSessionId })
|
|
87
|
+
const aimuxQuestionSubmissionBlocked = isAimuxQuestionSubmissionBlocked(aimuxStatus)
|
|
75
88
|
const [showHelp, setShowHelp] = useState(false)
|
|
76
89
|
// null means "follow the tail". A concrete anchor identifies the exact row
|
|
77
90
|
// at the top of the viewport while the user browses history.
|
|
@@ -146,19 +159,31 @@ export function ChatScreen({ client, ready, webUserId, resumeSessionId, onClear,
|
|
|
146
159
|
}
|
|
147
160
|
}, [aimuxStatus, chat, client.server, modelLabel, ready.prefs.model, onClear, onResume, onQuit, onLogout, onUpgradeAimux])
|
|
148
161
|
|
|
149
|
-
const onSubmit = useCallback((text: string) => {
|
|
162
|
+
const onSubmit = useCallback((text: string): boolean => {
|
|
150
163
|
const t = text.trim()
|
|
151
|
-
if (!t) return
|
|
164
|
+
if (!t) return false
|
|
152
165
|
setSlashError(null)
|
|
153
166
|
if (t.startsWith('/')) {
|
|
167
|
+
// /compact is the only slash command that dispatches content to the
|
|
168
|
+
// agent. Keep local navigation/help commands available while heartbeat
|
|
169
|
+
// confirmation is pending, but apply the same gate to this remote one.
|
|
170
|
+
if (t === '/compact' && aimuxQuestionSubmissionBlocked) {
|
|
171
|
+
setSlashError(AIMUX_HEARTBEAT_BLOCKED_MESSAGE)
|
|
172
|
+
return false
|
|
173
|
+
}
|
|
154
174
|
if (!runSlash(t)) setShowHelp(true)
|
|
155
|
-
return
|
|
175
|
+
return true
|
|
176
|
+
}
|
|
177
|
+
if (aimuxQuestionSubmissionBlocked) {
|
|
178
|
+
setSlashError(AIMUX_HEARTBEAT_BLOCKED_MESSAGE)
|
|
179
|
+
return false
|
|
156
180
|
}
|
|
157
181
|
setShowHelp(false)
|
|
158
182
|
setVersionInfo(null)
|
|
159
183
|
setRowAnchor(null)
|
|
160
184
|
void chat.send(t)
|
|
161
|
-
|
|
185
|
+
return true
|
|
186
|
+
}, [aimuxQuestionSubmissionBlocked, chat, runSlash])
|
|
162
187
|
|
|
163
188
|
// First query of a fresh session triggers the full backend bootstrap (lazy
|
|
164
189
|
// session creation, worker spawn, context load) before any output streams.
|
|
@@ -449,6 +474,7 @@ export function ChatScreen({ client, ready, webUserId, resumeSessionId, onClear,
|
|
|
449
474
|
inputActiveRef={chatInputActiveRef}
|
|
450
475
|
onPauseToDequeue={chat.pauseToDequeue}
|
|
451
476
|
hasPending={chat.pending.length > 0}
|
|
477
|
+
submissionBlocked={aimuxQuestionSubmissionBlocked}
|
|
452
478
|
/>
|
|
453
479
|
<StatusArea
|
|
454
480
|
ready={ready}
|
|
@@ -518,7 +544,7 @@ function MetaRow({ label, value, hint, labelWidth }: { label: string; value: str
|
|
|
518
544
|
}
|
|
519
545
|
|
|
520
546
|
function CompactHeader({ ready, sessionId, columns }: { ready: ReadyState; sessionId: string | null; columns: number }) {
|
|
521
|
-
const context = `${ready.project.name} › ${ready.issue.title}${sessionId ? ` · ${sessionId.slice(0, 8)}` : ''}`
|
|
547
|
+
const context = hostText(`${ready.project.name} › ${ready.issue.title}${sessionId ? ` · ${sessionId.slice(0, 8)}` : ''}`)
|
|
522
548
|
return (
|
|
523
549
|
<Box justifyContent="space-between">
|
|
524
550
|
<Text bold><Text dimColor>{'>_ '}</Text>Mobius</Text>
|
|
@@ -643,7 +669,8 @@ function VersionBlock({ lines }: { lines: string[] }) {
|
|
|
643
669
|
}
|
|
644
670
|
|
|
645
671
|
interface ComposerProps {
|
|
646
|
-
|
|
672
|
+
/** Return false when the caller rejects the submission so the draft stays intact. */
|
|
673
|
+
onSubmit: (text: string) => unknown
|
|
647
674
|
onStop: () => void
|
|
648
675
|
onQuit: () => void
|
|
649
676
|
typing: boolean
|
|
@@ -653,9 +680,11 @@ interface ComposerProps {
|
|
|
653
680
|
// 排队插队: 有挂起指令时空输入回车触发; hasPending 控制提示文案与触发开关.
|
|
654
681
|
onPauseToDequeue?: () => void
|
|
655
682
|
hasPending?: boolean
|
|
683
|
+
/** Visual hint only; onSubmit remains the authoritative gate (slash commands stay usable). */
|
|
684
|
+
submissionBlocked?: boolean
|
|
656
685
|
}
|
|
657
686
|
|
|
658
|
-
export function Composer({ onSubmit, onStop, onQuit, typing, commands, onHeightChange, inputActiveRef, onPauseToDequeue, hasPending }: ComposerProps) {
|
|
687
|
+
export function Composer({ onSubmit, onStop, onQuit, typing, commands, onHeightChange, inputActiveRef, onPauseToDequeue, hasPending, submissionBlocked }: ComposerProps) {
|
|
659
688
|
const [value, setValue] = useState('')
|
|
660
689
|
const [cursor, setCursor] = useState(0)
|
|
661
690
|
const [popupIdx, setPopupIdx] = useState(0)
|
|
@@ -872,10 +901,14 @@ export function Composer({ onSubmit, onStop, onQuit, typing, commands, onHeightC
|
|
|
872
901
|
}
|
|
873
902
|
const submitted = valueRef.current
|
|
874
903
|
if (submitted.trim()) {
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
904
|
+
// A rejected submission (for example while the AIMUX bridge heartbeat
|
|
905
|
+
// is still pending) remains editable and can be retried with Enter as
|
|
906
|
+
// soon as the blocking condition clears.
|
|
907
|
+
if (onSubmit(submitted) !== false) {
|
|
908
|
+
historyRef.current.push(submitted)
|
|
909
|
+
edit('', 0)
|
|
910
|
+
setHistIdx(null)
|
|
911
|
+
}
|
|
879
912
|
} else if (hasPending) {
|
|
880
913
|
// 空输入回车 = 插队: 打断当前 turn 并出队下一条排队指令.
|
|
881
914
|
void onPauseToDequeue?.()
|
|
@@ -1012,8 +1045,10 @@ export function Composer({ onSubmit, onStop, onQuit, typing, commands, onHeightC
|
|
|
1012
1045
|
{confirmQuit
|
|
1013
1046
|
? <Text color="yellowBright" bold>请再次按下Ctrl+C退出</Text>
|
|
1014
1047
|
: <Text dimColor>
|
|
1015
|
-
{hasPending ? <Text color="yellowBright"
|
|
1016
|
-
{
|
|
1048
|
+
{hasPending ? <Text color="yellowBright">{hostText('空回车插队 · ')}</Text> : null}
|
|
1049
|
+
{submissionBlocked
|
|
1050
|
+
? <Text color="yellowBright">等待 AIMUX 心跳 · 暂不可发送(/ 命令可用)</Text>
|
|
1051
|
+
: hostText((stdout.columns ?? 80) >= 72 ? 'Enter 发送 · Shift+Enter / Alt+Enter / Ctrl+J 换行' : 'Enter 发送 · Alt+Enter / Ctrl+J 换行')}
|
|
1017
1052
|
</Text>}
|
|
1018
1053
|
<Text dimColor>{wrapped.length > maxRows ? `${visualCursor + 1}/${wrapped.length} 行` : `${wrapped.length} 行`}</Text>
|
|
1019
1054
|
</Box>
|
|
@@ -1114,14 +1149,17 @@ function StatusArea({ ready, sessionId, columns, webUrl, aimuxStatus, modelDispl
|
|
|
1114
1149
|
const model = modelDisplay
|
|
1115
1150
|
const language = ready.prefs.language === 'en' ? 'English' : '中文'
|
|
1116
1151
|
const cwd = compactPath(process.cwd())
|
|
1117
|
-
const leftRaw = columns >= 100
|
|
1152
|
+
const leftRaw = hostText(columns >= 100
|
|
1118
1153
|
? `${model} · ${language} · ${cwd}`
|
|
1119
|
-
: `${model} · ${ready.project.name}`
|
|
1120
|
-
const rightRaw = columns >= 72
|
|
1154
|
+
: `${model} · ${ready.project.name}`)
|
|
1155
|
+
const rightRaw = hostText(columns >= 72
|
|
1121
1156
|
? `${ready.project.name} › ${ready.issue.title}${sessionId ? ` · ${sessionId.slice(0, 8)}` : ''}`
|
|
1122
|
-
: ''
|
|
1157
|
+
: '')
|
|
1123
1158
|
const left = truncateDisplay(leftRaw, rightRaw ? Math.floor(columns * 0.45) : columns - 2)
|
|
1124
|
-
|
|
1159
|
+
// 宽度按显示列算, 不能用 .length: 中文/表情占两列, 按字符数会多给出预算.
|
|
1160
|
+
// Measure display columns, not UTF-16 units, or wide chars push the row over.
|
|
1161
|
+
const leftShown = copyNotice ?? left
|
|
1162
|
+
const right = rightRaw ? truncateDisplay(rightRaw, columns - displayWidth(leftShown) - 5) : ''
|
|
1125
1163
|
return (
|
|
1126
1164
|
<Box flexDirection="column" marginTop={1}>
|
|
1127
1165
|
<Box justifyContent="space-between">
|
|
@@ -1146,12 +1184,15 @@ function ConnectivityRow({ aimuxStatus, webUrl, columns }: { aimuxStatus?: Aimux
|
|
|
1146
1184
|
// No AIMUX status → web URL keeps the whole row (unchanged from before).
|
|
1147
1185
|
// Otherwise leave room for the AIMUX block + 'web · ' prefix + a safety gap
|
|
1148
1186
|
// (the gap also absorbs ambiguous-width chars like box-drawing in the detail).
|
|
1187
|
+
// conhost 下 '·' 按两列渲染, 改用 ASCII 前缀.
|
|
1188
|
+
// Under conhost '·' renders two cells wide, so use the ASCII prefix.
|
|
1189
|
+
const prefix = hostText(WEB_PREFIX)
|
|
1149
1190
|
const urlBudget = aimuxWidth
|
|
1150
|
-
? Math.max(8, columns - 2 - aimuxWidth -
|
|
1191
|
+
? Math.max(8, columns - 2 - aimuxWidth - prefix.length - 6)
|
|
1151
1192
|
: undefined
|
|
1152
1193
|
const web = (
|
|
1153
1194
|
<Text>
|
|
1154
|
-
<Text dimColor>{
|
|
1195
|
+
<Text dimColor>{prefix}</Text>
|
|
1155
1196
|
<Text color="cyan" underline>{clickableUrl(webUrl, urlBudget)}</Text>
|
|
1156
1197
|
</Text>
|
|
1157
1198
|
)
|
|
@@ -1173,10 +1214,24 @@ function compactPath(path: string): string {
|
|
|
1173
1214
|
return path.startsWith(`${home}/`) ? `~/${path.slice(home.length + 1)}` : path
|
|
1174
1215
|
}
|
|
1175
1216
|
|
|
1176
|
-
function truncateDisplay(value: string,
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1217
|
+
function truncateDisplay(value: string, maxWidth: number): string {
|
|
1218
|
+
// conhost 下用 ASCII 省略号, 避免 … 按两列渲染又溢出一列.
|
|
1219
|
+
// Use an ASCII ellipsis under conhost: … renders two cells there while Ink counts one.
|
|
1220
|
+
const ellipsis = IS_CONHOST ? '...' : '…'
|
|
1221
|
+
const limit = Math.max(1, Math.floor(maxWidth))
|
|
1222
|
+
if (displayWidth(value) <= limit) return value
|
|
1223
|
+
if (limit <= displayWidth(ellipsis)) return ellipsis
|
|
1224
|
+
// 按显示列切, 不把一个双列字符劈成两半.
|
|
1225
|
+
// Cut on display columns so a double-width char is never split in half.
|
|
1226
|
+
let out = ''
|
|
1227
|
+
let width = 0
|
|
1228
|
+
for (const ch of Array.from(value)) {
|
|
1229
|
+
const w = displayWidth(ch)
|
|
1230
|
+
if (width + w > limit - displayWidth(ellipsis)) break
|
|
1231
|
+
out += ch
|
|
1232
|
+
width += w
|
|
1233
|
+
}
|
|
1234
|
+
return `${out}${ellipsis}`
|
|
1180
1235
|
}
|
|
1181
1236
|
|
|
1182
1237
|
function buildWebUrl(server: string, webUserId: string, ready: ReadyState, sessionId: string | null): string {
|
package/src/config.ts
CHANGED
|
@@ -71,6 +71,23 @@ async function writeJson(file: string, data: unknown): Promise<void> {
|
|
|
71
71
|
}
|
|
72
72
|
|
|
73
73
|
// ── login.json ───────────────────────────────────────────────────────────────
|
|
74
|
+
/**
|
|
75
|
+
* Credentials handed in by the environment, for unattended starts: a container
|
|
76
|
+
* entrypoint, CI, or a launcher that already knows the account.
|
|
77
|
+
*
|
|
78
|
+
* Server and username must come together; the password is optional because
|
|
79
|
+
* Mobius servers default to passwordless. A partial environment returns null
|
|
80
|
+
* instead of guessing, so a half-filled shell cannot silently replace a
|
|
81
|
+
* working login.json.
|
|
82
|
+
*/
|
|
83
|
+
export function loginFromEnv(env: NodeJS.ProcessEnv = process.env): { server: string; username: string; password?: string } | null {
|
|
84
|
+
const server = (env.MOBIUS_TUI_SERVER ?? '').trim()
|
|
85
|
+
const username = (env.MOBIUS_TUI_USERNAME ?? '').trim()
|
|
86
|
+
if (!server || !username) return null
|
|
87
|
+
const password = env.MOBIUS_TUI_PASSWORD
|
|
88
|
+
return { server: server.replace(/\/+$/, ''), username, password: password ? password : undefined }
|
|
89
|
+
}
|
|
90
|
+
|
|
74
91
|
export async function loadLogin(): Promise<LoginRecord | null> {
|
|
75
92
|
const rec = await readJson<LoginRecord | null>(LOGIN_FILE(), null)
|
|
76
93
|
if (!rec || !rec.token || !rec.server) return null
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Shared AIMUX command and privilege policy for the terminal and desktop clients.
|
|
3
|
+
*/
|
|
4
|
+
import { createHash } from 'node:crypto'
|
|
5
|
+
import os from 'node:os'
|
|
6
|
+
import path from 'node:path'
|
|
7
|
+
|
|
8
|
+
export const AIMUX_TARGET_VERSION = '0.3.72'
|
|
9
|
+
export type GuiMode = 'off' | 'no-elevate' | 'elevate'
|
|
10
|
+
|
|
11
|
+
/*
|
|
12
|
+
* Match the broker version, falling back to the bundled pin when unavailable.
|
|
13
|
+
*/
|
|
14
|
+
export function alignTarget(serverVersion: string | null | undefined, pin = AIMUX_TARGET_VERSION): string {
|
|
15
|
+
const v = typeof serverVersion === 'string' ? serverVersion.trim() : ''
|
|
16
|
+
return v || pin
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/*
|
|
20
|
+
* Use the effective OS user rather than inherited shell identity.
|
|
21
|
+
*/
|
|
22
|
+
export function currentUsername(): string {
|
|
23
|
+
try { return os.userInfo().username } catch { return process.env.USER || process.env.USERNAME || 'user' }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/*
|
|
27
|
+
* Hash the full user and workspace identity to avoid prefix collisions.
|
|
28
|
+
*/
|
|
29
|
+
export function aimuxWorkspaceHash(username = currentUsername(), cwd = process.cwd()): string {
|
|
30
|
+
return createHash('sha256').update(`${username}:${path.resolve(cwd)}`).digest('hex').slice(0, 10)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/*
|
|
34
|
+
* Treat EPERM as alive: insufficient permission does not mean a missing process.
|
|
35
|
+
*/
|
|
36
|
+
export function pidAlive(
|
|
37
|
+
pid: number,
|
|
38
|
+
probe: (pid: number, signal: number) => void = (p, s) => process.kill(p, s),
|
|
39
|
+
): boolean {
|
|
40
|
+
try { probe(pid, 0); return true } catch (e: any) { return e?.code === 'EPERM' }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/*
|
|
44
|
+
* Build the reverse connection arguments shared by both clients.
|
|
45
|
+
*/
|
|
46
|
+
export function reverseConnectArgs(
|
|
47
|
+
server: string,
|
|
48
|
+
identifier: string,
|
|
49
|
+
token: string,
|
|
50
|
+
platform: NodeJS.Platform = process.platform,
|
|
51
|
+
silentFlag: string | null = null,
|
|
52
|
+
runtimeFile: string | null = null,
|
|
53
|
+
enableGui = false,
|
|
54
|
+
guiNoElevate = false,
|
|
55
|
+
): string[] {
|
|
56
|
+
return [
|
|
57
|
+
'reverse', 'connect', `${server.replace(/\/$/, '')}/aimux_bridge`,
|
|
58
|
+
'--identifier', identifier,
|
|
59
|
+
'--token', token,
|
|
60
|
+
'--replace',
|
|
61
|
+
...(runtimeFile ? ['--runtime', runtimeFile, '--watchdog', runtimeFile] : []),
|
|
62
|
+
...(platform === 'win32' && silentFlag ? [silentFlag] : []),
|
|
63
|
+
...(enableGui ? ['--enable-gui'] : []),
|
|
64
|
+
// 只有启用 GUI 时才需要禁止提权。
|
|
65
|
+
// Suppress elevation only when GUI access is enabled.
|
|
66
|
+
...(enableGui && guiNoElevate ? ['--gui-no-elevate'] : []),
|
|
67
|
+
]
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/*
|
|
71
|
+
* Choose only a Windows console flag advertised by the installed runtime.
|
|
72
|
+
*/
|
|
73
|
+
export function pickSilentFlag(helpText: string, platform: NodeJS.Platform = process.platform): string | null {
|
|
74
|
+
if (platform !== 'win32') return null
|
|
75
|
+
if (/--silent-v2\b/.test(helpText)) return '--silent-v2'
|
|
76
|
+
if (/--slient-v2\b/.test(helpText)) return '--slient-v2'
|
|
77
|
+
if (/--silent-shell\b/.test(helpText)) return '--silent-shell'
|
|
78
|
+
return null
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/*
|
|
82
|
+
* Detect explicit GUI support before sending the corresponding flag.
|
|
83
|
+
*/
|
|
84
|
+
export function pickEnableGuiFlag(helpText: string): boolean {
|
|
85
|
+
return /--enable-gui\b/.test(helpText)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/*
|
|
89
|
+
* Detect support for GUI access without requesting elevation.
|
|
90
|
+
*/
|
|
91
|
+
export function pickGuiNoElevateFlag(helpText: string): boolean {
|
|
92
|
+
return /--gui-no-elevate\b/.test(helpText)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/*
|
|
96
|
+
* Never request rights absent from the parent process; disable unsupported GUI access.
|
|
97
|
+
*/
|
|
98
|
+
export function pickGuiArgs(
|
|
99
|
+
mode: GuiMode,
|
|
100
|
+
elevated: boolean,
|
|
101
|
+
supports: { enable: boolean; noElevate: boolean },
|
|
102
|
+
platform: NodeJS.Platform = process.platform,
|
|
103
|
+
): { enableGui: boolean; guiNoElevate: boolean } {
|
|
104
|
+
if (mode === 'off' || !supports.enable) return { enableGui: false, guiNoElevate: false }
|
|
105
|
+
if (platform !== 'win32') return { enableGui: true, guiNoElevate: mode === 'no-elevate' && supports.noElevate }
|
|
106
|
+
if (elevated) return { enableGui: true, guiNoElevate: false }
|
|
107
|
+
return supports.noElevate ? { enableGui: true, guiNoElevate: true } : { enableGui: false, guiNoElevate: false }
|
|
108
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Terminal-host quirks for classic Windows consoles.
|
|
3
|
+
*
|
|
4
|
+
* conhost (the native cmd window) renders East Asian ambiguous characters
|
|
5
|
+
* (·, ›, …, ●, ○) as two cells when the console font is a CJK font, while Ink's
|
|
6
|
+
* layout (string-width) counts them as one. Right-aligned rows therefore spill
|
|
7
|
+
* their last cells onto the next line, and resizing the window does not help
|
|
8
|
+
* because the mismatch depends on the glyphs, not the width. Windows Terminal
|
|
9
|
+
* renders the same characters as one cell, so only classic conhost needs the
|
|
10
|
+
* ASCII fallbacks below.
|
|
11
|
+
*/
|
|
12
|
+
export const IS_CONHOST = process.platform === 'win32'
|
|
13
|
+
&& !process.env.WT_SESSION
|
|
14
|
+
&& process.env.TERM_PROGRAM !== 'vscode'
|
|
15
|
+
|
|
16
|
+
const ASCII_FALLBACK: Record<string, string> = {
|
|
17
|
+
'·': '-', // middle dot used in status separators
|
|
18
|
+
'›': '>', // breadcrumb separator
|
|
19
|
+
'…': '...', // ellipsis
|
|
20
|
+
'●': '*', // filled status dot
|
|
21
|
+
'○': 'o', // hollow status dot
|
|
22
|
+
'◐': '~', // partial status dot
|
|
23
|
+
'◇': '<>', // reasoning marker
|
|
24
|
+
'✎': '*', // edit marker
|
|
25
|
+
'⚠': '!', // warning marker
|
|
26
|
+
'•': '*', // bullet
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Replace wide-rendered ambiguous glyphs when running inside classic conhost. */
|
|
30
|
+
export function hostText(value: string): string {
|
|
31
|
+
if (!IS_CONHOST) return value
|
|
32
|
+
let out = ''
|
|
33
|
+
for (const ch of Array.from(value)) out += ASCII_FALLBACK[ch] ?? ch
|
|
34
|
+
return out
|
|
35
|
+
}
|
package/tests/flow.test.tsx
CHANGED
|
@@ -119,6 +119,26 @@ async function main() {
|
|
|
119
119
|
globalThis.fetch = ((u: any, init?: any) => mockFetch(String(u), init)) as unknown as typeof fetch
|
|
120
120
|
process.env.MOBIUS_TUI_DEBUG = '1'
|
|
121
121
|
|
|
122
|
+
// ── environment login: no login.json at all; credentials come from the env ──
|
|
123
|
+
process.env.MOBIUS_TUI_SERVER = 'http://mock.local'
|
|
124
|
+
process.env.MOBIUS_TUI_USERNAME = 'tester'
|
|
125
|
+
// The env-login run only checks the credential path; skip the AIMUX reverse
|
|
126
|
+
// connection so the test does not touch a real Python environment.
|
|
127
|
+
process.env.MOBIUS_TUI_DISABLE_AIMUX = '1'
|
|
128
|
+
const envRun = render(React.createElement(App))
|
|
129
|
+
try {
|
|
130
|
+
ok(await waitFor(envRun.lastFrame, '选择当前路径的绑定项目'),
|
|
131
|
+
'env credentials log in without a stored login.json')
|
|
132
|
+
const envLogin = JSON.parse(fs.readFileSync(path.join(TMP_HOME, 'login.json'), 'utf8'))
|
|
133
|
+
ok(envLogin.username === 'tester' && envLogin.token === 'mock-jwt-token',
|
|
134
|
+
'env login persists a usable login.json')
|
|
135
|
+
} finally {
|
|
136
|
+
envRun.unmount()
|
|
137
|
+
delete process.env.MOBIUS_TUI_SERVER
|
|
138
|
+
delete process.env.MOBIUS_TUI_USERNAME
|
|
139
|
+
delete process.env.MOBIUS_TUI_DISABLE_AIMUX
|
|
140
|
+
}
|
|
141
|
+
|
|
122
142
|
console.log('\n[FLOW] full App drive (mocked backend)\n')
|
|
123
143
|
const { stdin, lastFrame, unmount } = render(React.createElement(App))
|
|
124
144
|
|
package/tests/ui.test.tsx
CHANGED
|
@@ -15,7 +15,7 @@ process.env.MOBIUS_TUI_HOME = TMP_HOME
|
|
|
15
15
|
|
|
16
16
|
import React from 'react'
|
|
17
17
|
import { render } from 'ink-testing-library'
|
|
18
|
-
import { ChatScreen, Composer, shimmerText } from '../src/components/Chat.js'
|
|
18
|
+
import { ChatScreen, Composer, isAimuxQuestionSubmissionBlocked, shimmerText } from '../src/components/Chat.js'
|
|
19
19
|
import { WindowsInputDecoder } from '../src/lib/windows-input.js'
|
|
20
20
|
import { LoginScreen } from '../src/components/Login.js'
|
|
21
21
|
import { PrepScreen } from '../src/components/PrepScreen.js'
|
|
@@ -126,6 +126,17 @@ async function testLogin() {
|
|
|
126
126
|
unmount()
|
|
127
127
|
console.log(` ${captured ? '✓' : '·'} form keystroke submit ${captured ? 'succeeded' : 'skipped (harness timing)'} — logic covered by (a)`)
|
|
128
128
|
} finally { restoreFetch() }
|
|
129
|
+
|
|
130
|
+
// (c) environment credentials for unattended starts.
|
|
131
|
+
const { loginFromEnv } = await import('../src/config.js')
|
|
132
|
+
ok(loginFromEnv({ MOBIUS_TUI_SERVER: ' https://m.example.com/ ', MOBIUS_TUI_USERNAME: 'alice' } as any)?.server === 'https://m.example.com',
|
|
133
|
+
'loginFromEnv trims the server and strips trailing slashes')
|
|
134
|
+
ok(loginFromEnv({ MOBIUS_TUI_SERVER: 'https://m.example.com', MOBIUS_TUI_USERNAME: 'alice' } as any)?.password === undefined,
|
|
135
|
+
'loginFromEnv leaves the password optional (passwordless servers)')
|
|
136
|
+
ok(loginFromEnv({ MOBIUS_TUI_SERVER: 'https://m.example.com', MOBIUS_TUI_USERNAME: 'alice', MOBIUS_TUI_PASSWORD: 's3cret' } as any)?.password === 's3cret',
|
|
137
|
+
'loginFromEnv forwards the password')
|
|
138
|
+
ok(loginFromEnv({ MOBIUS_TUI_SERVER: 'https://m.example.com' } as any) === null,
|
|
139
|
+
'loginFromEnv stays off unless server and username both exist')
|
|
129
140
|
}
|
|
130
141
|
|
|
131
142
|
// ════════════════════════════════════════════════════════════════════════════
|
|
@@ -214,6 +225,73 @@ async function testChat() {
|
|
|
214
225
|
} finally { restoreFetch() }
|
|
215
226
|
}
|
|
216
227
|
|
|
228
|
+
// ════════════════════════════════════════════════════════════════════════════
|
|
229
|
+
// TEST 2a — a pending AIMUX bridge heartbeat blocks prompts without consuming
|
|
230
|
+
// the draft; once connected, the same draft can be retried with Enter.
|
|
231
|
+
// ════════════════════════════════════════════════════════════════════════════
|
|
232
|
+
async function testHeartbeatBlocksQuestionSubmission() {
|
|
233
|
+
console.log('\n[UI 2a] pending AIMUX heartbeat blocks question submission')
|
|
234
|
+
const client = new MobiusClient('http://mock.local', 'mock-jwt-token')
|
|
235
|
+
const ready: ReadyState = {
|
|
236
|
+
project: { id: 'p1', name: '测试项目' },
|
|
237
|
+
issue: { id: 'i1', project_id: 'p1', title: '测试任务' },
|
|
238
|
+
prefs: { model: 'codex', language: 'zh', excluded_skill_ids: [], excluded_memory_ids: [] },
|
|
239
|
+
}
|
|
240
|
+
let sessionCreates = 0
|
|
241
|
+
let messagePosts = 0
|
|
242
|
+
installMock((url, init) => {
|
|
243
|
+
if (url.includes('/events')) {
|
|
244
|
+
return new Response(new RS({
|
|
245
|
+
start(c: any) { c.enqueue(enc.encode('event: subscribed\ndata: {"event":"subscribed","session":{}}\n\n')) },
|
|
246
|
+
}), { status: 200, headers: { 'content-type': 'text/event-stream' } })
|
|
247
|
+
}
|
|
248
|
+
if (url.includes('/api/issues/i1/sessions') && init?.method === 'POST') {
|
|
249
|
+
sessionCreates += 1
|
|
250
|
+
return jsonResponse({ session_id: 's-heartbeat' })
|
|
251
|
+
}
|
|
252
|
+
if (url.endsWith('/messages') && init?.method === 'POST') {
|
|
253
|
+
messagePosts += 1
|
|
254
|
+
return jsonResponse({ ok: true, session_id: 's-heartbeat', turn_number: 1 })
|
|
255
|
+
}
|
|
256
|
+
if (url.endsWith('/api/sessions/s-heartbeat/groups')) return jsonResponse({ groups: [], pending: [] })
|
|
257
|
+
if (url.endsWith('/api/sessions/s-heartbeat/status')) {
|
|
258
|
+
return jsonResponse({ session_id: 's-heartbeat', alive: true, working: false })
|
|
259
|
+
}
|
|
260
|
+
return jsonResponse({ error: 'no mock' }, 404)
|
|
261
|
+
})
|
|
262
|
+
try {
|
|
263
|
+
const baseProps = {
|
|
264
|
+
client, ready, webUserId: 'u',
|
|
265
|
+
onClear: () => {}, onResume: () => {}, onQuit: () => {}, onLogout: () => {},
|
|
266
|
+
onReconfigure: () => {}, onConfigCancel: () => {},
|
|
267
|
+
}
|
|
268
|
+
const waitingStatus = { state: 'starting', phase: 'heartbeat', detail: '等待 bridge 心跳确认…' } as const
|
|
269
|
+
ok(isAimuxQuestionSubmissionBlocked(waitingStatus), 'semantic heartbeat state is recognized as submission-blocking')
|
|
270
|
+
ok(!isAimuxQuestionSubmissionBlocked({ state: 'connected', phase: 'connected' }), 'connected AIMUX state allows submissions')
|
|
271
|
+
|
|
272
|
+
const view = render(<ChatScreen {...baseProps} aimuxStatus={waitingStatus} />)
|
|
273
|
+
await delay(40)
|
|
274
|
+
view.stdin.write('等待连接后发送的问题')
|
|
275
|
+
await delay(80) // outlast paste-burst detection so Enter is a real submit
|
|
276
|
+
view.stdin.write('\r')
|
|
277
|
+
await delay(100)
|
|
278
|
+
const blockedFrame = view.lastFrame() ?? ''
|
|
279
|
+
ok(sessionCreates === 0 && messagePosts === 0, 'heartbeat wait does not create a session or POST a message')
|
|
280
|
+
ok(blockedFrame.includes('暂时无法提交问题'), 'blocked Enter explains why the question was not sent')
|
|
281
|
+
ok(blockedFrame.includes('等待连接后发送的问题'), 'blocked Enter preserves the draft in the composer')
|
|
282
|
+
ok(blockedFrame.includes('等待 AIMUX 心跳 · 暂不可发送'), 'composer advertises the temporary submission lock')
|
|
283
|
+
|
|
284
|
+
view.rerender(<ChatScreen {...baseProps} aimuxStatus={{ state: 'connected', phase: 'connected', detail: '心跳正常 · tui-test' }} />)
|
|
285
|
+
await delay(40)
|
|
286
|
+
view.stdin.write('\r')
|
|
287
|
+
for (let i = 0; i < 30 && messagePosts === 0; i++) await delay(50)
|
|
288
|
+
const connectedFrame = view.lastFrame() ?? ''
|
|
289
|
+
view.unmount()
|
|
290
|
+
ok(sessionCreates === 1 && messagePosts === 1, 'the preserved draft submits once after heartbeat recovery')
|
|
291
|
+
ok(!connectedFrame.includes('暂时无法提交问题'), 'the blocking warning clears after a successful retry')
|
|
292
|
+
} finally { restoreFetch() }
|
|
293
|
+
}
|
|
294
|
+
|
|
217
295
|
// ════════════════════════════════════════════════════════════════════════════
|
|
218
296
|
// TEST 2b — first-turn bootstrap keeps its indicator while the worker is not
|
|
219
297
|
// yet observable through the authoritative status endpoint.
|
|
@@ -1484,6 +1562,7 @@ async function testUpgradeSlash() {
|
|
|
1484
1562
|
async function main() {
|
|
1485
1563
|
await testLogin()
|
|
1486
1564
|
await testChat()
|
|
1565
|
+
await testHeartbeatBlocksQuestionSubmission()
|
|
1487
1566
|
await testFirstTurnBootstrapIndicator()
|
|
1488
1567
|
await testResumedWorkingStatus()
|
|
1489
1568
|
testMarkdownCodeRendering()
|
package/uninstall.ps1
CHANGED
|
@@ -119,14 +119,10 @@ function Invoke-MobiusUninstall {
|
|
|
119
119
|
Step '删除临时安装器和旧错误日志...'
|
|
120
120
|
Get-ChildItem $env:TEMP -Filter 'mobius-install-v*.ps1' -ErrorAction SilentlyContinue |
|
|
121
121
|
Remove-Item -Force -ErrorAction SilentlyContinue
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
Remove-Item (Join-Path $env:TEMP 'mobius-install-v14-error.log') -Force -ErrorAction SilentlyContinue
|
|
127
|
-
Remove-Item (Join-Path $env:TEMP 'mobius-install-v15-error.log') -Force -ErrorAction SilentlyContinue
|
|
128
|
-
Remove-Item (Join-Path $env:TEMP 'mobius-install-v16-error.log') -Force -ErrorAction SilentlyContinue
|
|
129
|
-
Remove-Item (Join-Path $env:TEMP 'mobius-uninstall-v11-error.log') -Force -ErrorAction SilentlyContinue
|
|
122
|
+
Get-ChildItem $env:TEMP -Filter 'mobius-install-v*-error.log' -ErrorAction SilentlyContinue |
|
|
123
|
+
Remove-Item -Force -ErrorAction SilentlyContinue
|
|
124
|
+
Get-ChildItem $env:TEMP -Filter 'mobius-uninstall-v*-error.log' -ErrorAction SilentlyContinue |
|
|
125
|
+
Remove-Item -Force -ErrorAction SilentlyContinue
|
|
130
126
|
Ok '临时安装文件已清理。'
|
|
131
127
|
|
|
132
128
|
Write-Host ''
|