@mobius-os/mobius 0.3.75 → 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 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
@@ -236,29 +236,35 @@ Set-Content -Path $openHereCmd -Value $openHereLines -Encoding ASCII
236
236
  # Use Windows Terminal explicitly: the hidden parent's console is not handed to
237
237
  # the default terminal, and conhost renders wide/ambiguous chars in 2 cells.
238
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.
239
245
  $openHereAdminLines = @(
240
246
  'param([string]$Target)',
241
- '# 每次启动覆盖写诊断日志, 闪退时可以直接看原因.',
242
- '# Overwrite a diagnostic log on every launch so a flash-and-close can be explained later.',
247
+ '# Diagnostic log, overwritten on every launch so a flash-and-close can be explained later.',
243
248
  '$log = Join-Path $env:USERPROFILE ".mobius\logs\admin-launch.log"',
244
249
  'try {',
245
250
  ' New-Item -ItemType Directory -Force -Path (Split-Path $log) | Out-Null',
246
- '# 右键文件夹时 Explorer 会传路径, 兜底用当前目录.',
247
251
  '# Explorer passes the folder path; fall back to the current directory.',
248
252
  ' if (-not $Target) { $Target = (Get-Location).Path }',
249
253
  ' $launcher = Join-Path $PSScriptRoot "mobius-open-here.cmd"',
254
+ ' $shell = New-Object -ComObject Shell.Application',
250
255
  ' $wt = Join-Path $env:LOCALAPPDATA "Microsoft\WindowsApps\wt.exe"',
251
256
  ' if (Test-Path $wt) {',
252
- '# wt 用 -d 指定起始目录, 再让 cmd 执行同一个启动器.',
253
- '# wt takes the starting directory with -d and runs the same launcher via cmd.',
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.',
254
262
  ' $wtArgs = ''-d "{0}" cmd.exe /d /s /c ""{1}" "{2}""'' -f $Target, $launcher, $Target',
255
- ' Start-Process -FilePath $wt -ArgumentList $wtArgs',
256
- ' "$(Get-Date -Format o) launched wt target=$Target launcher=$launcher" | Set-Content -Path $log',
263
+ ' $shell.ShellExecute($wt, $wtArgs, $PSScriptRoot, "runas", 1)',
264
+ ' "$(Get-Date -Format o) launched wt elevated target=$Target launcher=$launcher" | Set-Content -Path $log',
257
265
  ' } else {',
258
266
  ' $commandLine = ''/d /s /c ""{0}" "{1}""'' -f $launcher, $Target',
259
- '# 第五个参数 1 是 SW_SHOWNORMAL, 强制提权后的窗口可见.',
260
- '# The fifth argument is SW_SHOWNORMAL, forcing the elevated window to be visible.',
261
- ' $shell = New-Object -ComObject Shell.Application',
267
+ '# The 5th argument 1 = SW_SHOWNORMAL, forcing the elevated window to be visible.',
262
268
  ' $shell.ShellExecute($env:ComSpec, $commandLine, $PSScriptRoot, "runas", 1)',
263
269
  ' "$(Get-Date -Format o) launched conhost target=$Target launcher=$launcher" | Set-Content -Path $log',
264
270
  ' }',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mobius-os/mobius",
3
- "version": "0.3.75",
3
+ "version": "0.3.76",
4
4
  "type": "module",
5
5
  "description": "Mobius terminal client. Reuses Mobius frontend TypeScript types and jsonl entry shapes.",
6
6
  "bin": {
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(
@@ -57,6 +57,17 @@ interface TerminalSize {
57
57
  import { TUI_VERSION } from '../version.js'
58
58
  const DEFAULT_COMPOSER_ROWS = 5
59
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
+ }
60
71
 
61
72
  const SLASH_COMMANDS = [
62
73
  { cmd: '/clear', desc: '清空当前对话,开启新会话' },
@@ -73,6 +84,7 @@ const SLASH_COMMANDS = [
73
84
 
74
85
  export function ChatScreen({ client, ready, webUserId, resumeSessionId, onClear, onResume, onQuit, onLogout, onUpgradeAimux, onReconfigure, onConfigCancel, aimuxStatus }: ChatProps) {
75
86
  const chat = useChat({ client, ready, resumeSessionId })
87
+ const aimuxQuestionSubmissionBlocked = isAimuxQuestionSubmissionBlocked(aimuxStatus)
76
88
  const [showHelp, setShowHelp] = useState(false)
77
89
  // null means "follow the tail". A concrete anchor identifies the exact row
78
90
  // at the top of the viewport while the user browses history.
@@ -147,19 +159,31 @@ export function ChatScreen({ client, ready, webUserId, resumeSessionId, onClear,
147
159
  }
148
160
  }, [aimuxStatus, chat, client.server, modelLabel, ready.prefs.model, onClear, onResume, onQuit, onLogout, onUpgradeAimux])
149
161
 
150
- const onSubmit = useCallback((text: string) => {
162
+ const onSubmit = useCallback((text: string): boolean => {
151
163
  const t = text.trim()
152
- if (!t) return
164
+ if (!t) return false
153
165
  setSlashError(null)
154
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
+ }
155
174
  if (!runSlash(t)) setShowHelp(true)
156
- return
175
+ return true
176
+ }
177
+ if (aimuxQuestionSubmissionBlocked) {
178
+ setSlashError(AIMUX_HEARTBEAT_BLOCKED_MESSAGE)
179
+ return false
157
180
  }
158
181
  setShowHelp(false)
159
182
  setVersionInfo(null)
160
183
  setRowAnchor(null)
161
184
  void chat.send(t)
162
- }, [chat, runSlash])
185
+ return true
186
+ }, [aimuxQuestionSubmissionBlocked, chat, runSlash])
163
187
 
164
188
  // First query of a fresh session triggers the full backend bootstrap (lazy
165
189
  // session creation, worker spawn, context load) before any output streams.
@@ -450,6 +474,7 @@ export function ChatScreen({ client, ready, webUserId, resumeSessionId, onClear,
450
474
  inputActiveRef={chatInputActiveRef}
451
475
  onPauseToDequeue={chat.pauseToDequeue}
452
476
  hasPending={chat.pending.length > 0}
477
+ submissionBlocked={aimuxQuestionSubmissionBlocked}
453
478
  />
454
479
  <StatusArea
455
480
  ready={ready}
@@ -644,7 +669,8 @@ function VersionBlock({ lines }: { lines: string[] }) {
644
669
  }
645
670
 
646
671
  interface ComposerProps {
647
- onSubmit: (text: string) => void
672
+ /** Return false when the caller rejects the submission so the draft stays intact. */
673
+ onSubmit: (text: string) => unknown
648
674
  onStop: () => void
649
675
  onQuit: () => void
650
676
  typing: boolean
@@ -654,9 +680,11 @@ interface ComposerProps {
654
680
  // 排队插队: 有挂起指令时空输入回车触发; hasPending 控制提示文案与触发开关.
655
681
  onPauseToDequeue?: () => void
656
682
  hasPending?: boolean
683
+ /** Visual hint only; onSubmit remains the authoritative gate (slash commands stay usable). */
684
+ submissionBlocked?: boolean
657
685
  }
658
686
 
659
- 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) {
660
688
  const [value, setValue] = useState('')
661
689
  const [cursor, setCursor] = useState(0)
662
690
  const [popupIdx, setPopupIdx] = useState(0)
@@ -873,10 +901,14 @@ export function Composer({ onSubmit, onStop, onQuit, typing, commands, onHeightC
873
901
  }
874
902
  const submitted = valueRef.current
875
903
  if (submitted.trim()) {
876
- historyRef.current.push(submitted)
877
- onSubmit(submitted)
878
- edit('', 0)
879
- setHistIdx(null)
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
+ }
880
912
  } else if (hasPending) {
881
913
  // 空输入回车 = 插队: 打断当前 turn 并出队下一条排队指令.
882
914
  void onPauseToDequeue?.()
@@ -1014,7 +1046,9 @@ export function Composer({ onSubmit, onStop, onQuit, typing, commands, onHeightC
1014
1046
  ? <Text color="yellowBright" bold>请再次按下Ctrl+C退出</Text>
1015
1047
  : <Text dimColor>
1016
1048
  {hasPending ? <Text color="yellowBright">{hostText('空回车插队 · ')}</Text> : null}
1017
- {hostText((stdout.columns ?? 80) >= 72 ? 'Enter 发送 · Shift+Enter / Alt+Enter / Ctrl+J 换行' : 'Enter 发送 · Alt+Enter / Ctrl+J 换行')}
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 换行')}
1018
1052
  </Text>}
1019
1053
  <Text dimColor>{wrapped.length > maxRows ? `${visualCursor + 1}/${wrapped.length} 行` : `${wrapped.length} 行`}</Text>
1020
1054
  </Box>
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
+ }
@@ -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()