@mobius-os/mobius 0.3.64 → 0.3.67

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mobius-os/mobius",
3
- "version": "0.3.64",
3
+ "version": "0.3.67",
4
4
  "type": "module",
5
5
  "description": "Mobius terminal client. Reuses Mobius frontend TypeScript types and jsonl entry shapes.",
6
6
  "bin": {
@@ -13,8 +13,8 @@ set -euo pipefail
13
13
 
14
14
  TAG=20241002
15
15
  PYVER=3.12.7
16
- BUNDLE_VER=13
17
- AIMUX_VERSION=0.3.64
16
+ BUNDLE_VER=15
17
+ AIMUX_VERSION=0.3.67
18
18
  PYPI_INDEX=https://pypi.org/simple
19
19
  WORK="${WORK:-$HOME/python-bundles}"
20
20
  DIST="${DIST:-$WORK/dist}"
package/src/aimux.ts CHANGED
@@ -7,12 +7,13 @@
7
7
  */
8
8
  import { spawn, spawnSync, type ChildProcess, type StdioOptions } from 'node:child_process'
9
9
  import { createHash } from 'node:crypto'
10
- import { promises as fs, existsSync, createWriteStream, mkdirSync, openSync, closeSync } from 'node:fs'
10
+ import { promises as fs, existsSync, createWriteStream, mkdirSync, openSync, closeSync, readFileSync, writeFileSync } from 'node:fs'
11
11
  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
15
  import { mobiusHome } from './config.js'
16
+ import { windowsElevated } from './lib/windows-admin.js'
16
17
 
17
18
  export type AimuxState = 'starting' | 'connected' | 'failed' | 'stopped' | 'disabled'
18
19
  export type AimuxPhase = 'idle' | 'python' | 'venv' | 'install' | 'connecting' | 'heartbeat' | 'retrying' | 'connected'
@@ -32,7 +33,7 @@ export type AimuxLauncher =
32
33
  | { kind: 'exe'; path: string }
33
34
  | { kind: 'module'; python: string }
34
35
 
35
- const AIMUX_TARGET_VERSION = '0.3.64'
36
+ const AIMUX_TARGET_VERSION = '0.3.67'
36
37
  const AIMUX_PACKAGE = `aimux==${AIMUX_TARGET_VERSION}`
37
38
  const WIN = process.platform === 'win32'
38
39
  const venvDir = () => path.join(mobiusHome(), 'aimux-venv')
@@ -93,7 +94,7 @@ async function pythonForAimux(onProgress?: (p: InstallProgress) => void): Promis
93
94
  // 系统 python(如被精简掉 ensurepip 的容器镜像)。aimux 全部依赖为纯 Python,
94
95
  // 故三平台可共用同一套打包产物,分别按 arch 发布到 CDN。
95
96
  /** Plan B 内置运行时包版本;每次发版跟 aimux pin 一起 +1,测试也从这里取。 */
96
- export const BUNDLE_VER = '13'
97
+ export const BUNDLE_VER = '15'
97
98
  const BUNDLE_AIMUX_VERSION = AIMUX_TARGET_VERSION
98
99
  /** Version expected from the installed or bundled AIMUX runtime. */
99
100
  export const AIMUX_VERSION = BUNDLE_AIMUX_VERSION
@@ -365,19 +366,171 @@ export function aimuxWorkspaceHash(username = currentUsername(), cwd = process.c
365
366
  return createHash('sha256').update(`${username}:${path.resolve(cwd)}`).digest('hex').slice(0, 10)
366
367
  }
367
368
 
368
- export function tuiAimuxIdentifier(hostname = os.hostname(), cwd = process.cwd(), username = currentUsername()): string {
369
+ // ── GUI (computer use) authorization ─────────────────────────────────────
370
+ // Machine-level choice made in the first-run wizard.
371
+ //
372
+ // The daemon's privilege is decided by this TUI's own privilege, once, and is
373
+ // never negotiated at start time. A TUI must never ask Windows for rights it
374
+ // does not already have: aimux satisfies such a request with
375
+ // ShellExecuteW("runas"), which is synchronous and raises its consent prompt on
376
+ // the secure desktop — a prompt nobody answers blocks the daemon *before* it
377
+ // writes any state or starts its watchdog, leaving an immortal process the
378
+ // supervisor can neither see nor kill. So:
379
+ //
380
+ // unelevated TUI --enable-gui --gui-no-elevate (nothing is ever requested)
381
+ // elevated TUI --enable-gui (aimux sees it is already
382
+ // administrator and stays put)
383
+ //
384
+ // That is also why the modes are exclusive: a child inherits the parent's token,
385
+ // so an elevated TUI cannot produce a low-privilege daemon, and an unelevated
386
+ // one cannot produce an elevated daemon without prompting.
387
+ //
388
+ // off no GUI helper at all; registers as tui-<host>-<hash>
389
+ // no-elevate GUI helper, unelevated: Windows UIPI then blocks input into
390
+ // elevated windows
391
+ // elevate GUI helper that can also drive administrator windows
392
+ // Either authorized mode registers as gui-<host>-<hash>.
393
+ export type GuiMode = 'off' | 'no-elevate' | 'elevate'
394
+
395
+ /** Whether a mode can be offered here, and if not, what the user must change. */
396
+ export interface GuiModeAvailability { available: boolean; reason?: string }
397
+
398
+ const ADMIN_REASON = '请用管理员模式打开 Mobius TUI'
399
+ const NON_ADMIN_REASON = '请用非管理员模式打开 Mobius TUI'
400
+
401
+ /**
402
+ * Which GUI modes this machine can provide. Availability follows from the
403
+ * exclusive rule above: exactly one of the two authorized modes is offerable,
404
+ * and which one is decided by the TUI's own token.
405
+ */
406
+ export function guiModeAvailability(
407
+ elevated: boolean,
408
+ platform: NodeJS.Platform = process.platform,
409
+ ): Record<GuiMode, GuiModeAvailability> {
410
+ return {
411
+ off: { available: true },
412
+ 'no-elevate': platform === 'win32' && elevated
413
+ ? { available: false, reason: NON_ADMIN_REASON }
414
+ : { available: true },
415
+ // Off Windows there is no elevation to speak of, so the mode is always fine.
416
+ elevate: platform !== 'win32' || elevated ? { available: true } : { available: false, reason: ADMIN_REASON },
417
+ }
418
+ }
419
+
420
+ /**
421
+ * The GUI authorization picker's rows. An unavailable mode stays visible with
422
+ * the reason in its label — the user needs to know *why* the level they want is
423
+ * out of reach, and what to do about it.
424
+ */
425
+ export function guiModeOptions(
426
+ elevated: boolean,
427
+ platform: NodeJS.Platform = process.platform,
428
+ ): Array<{ label: string; value: GuiMode; desc?: string; disabled?: boolean }> {
429
+ const availability = guiModeAvailability(elevated, platform)
430
+ const label = (name: string, mode: GuiMode): string => {
431
+ const a = availability[mode]
432
+ return a.available ? `授权使用图形界面(${name})` : `授权使用图形界面(${name} - 不可用,${a.reason})`
433
+ }
434
+ const rows: Array<{ label: string; value: GuiMode; desc?: string; disabled?: boolean }> = [
435
+ { label: '使用纯命令行操作(推荐)', value: 'off', desc: '仅命令行/文件方式操作本机' },
436
+ ]
437
+ // Off Windows there is no elevation request to skip, so the middle choice
438
+ // would be identical to the last one; only offer it where it means something.
439
+ if (platform === 'win32') {
440
+ rows.push({
441
+ label: label('低权限', 'no-elevate'),
442
+ value: 'no-elevate',
443
+ desc: availability['no-elevate'].available ? '不弹 UAC;能操作普通窗口,管理员窗口不行' : undefined,
444
+ disabled: !availability['no-elevate'].available,
445
+ })
446
+ }
447
+ rows.push({
448
+ label: label('高权限', 'elevate'),
449
+ value: 'elevate',
450
+ desc: availability.elevate.available
451
+ ? (platform === 'win32' ? '可操作管理员窗口(TUI 已是管理员,不会弹 UAC)' : '启用界面操作工具')
452
+ : undefined,
453
+ disabled: !availability.elevate.available,
454
+ })
455
+ return rows
456
+ }
457
+
458
+ /** Platforms where a computer-use helper exists at all, so the GUI choice applies. */
459
+ export function hasGuiSupport(platform: NodeJS.Platform = process.platform): boolean {
460
+ return platform === 'win32' || platform === 'darwin'
461
+ }
462
+
463
+ const GUI_AUTH_FILE = 'tui-gui-authorized.json'
464
+ let guiModeCache: GuiMode | undefined = undefined
465
+
466
+ /** Read the stored mode, also accepting the `{gui: boolean}` file written by <=0.3.66. */
467
+ function readGuiMode(): GuiMode {
468
+ try {
469
+ const raw = JSON.parse(readFileSync(path.join(mobiusHome(), GUI_AUTH_FILE), 'utf8')) as { mode?: unknown; gui?: unknown }
470
+ if (raw?.mode === 'off' || raw?.mode === 'no-elevate' || raw?.mode === 'elevate') return raw.mode
471
+ return raw?.gui === true ? 'elevate' : 'off'
472
+ } catch { return 'off' }
473
+ }
474
+
475
+ export function tuiGuiMode(): GuiMode {
476
+ if (guiModeCache === undefined) guiModeCache = readGuiMode()
477
+ return guiModeCache
478
+ }
479
+
480
+ /** test-only: read the stored mode straight from disk, bypassing the module cache. */
481
+ export const readGuiModeForTest = readGuiMode
482
+
483
+ export function setTuiGuiMode(mode: GuiMode): void {
484
+ guiModeCache = mode
485
+ try {
486
+ mkdirSync(mobiusHome(), { recursive: true })
487
+ // `gui` is written alongside `mode` so that a downgrade to <=0.3.66 still
488
+ // reads the right boolean instead of silently dropping the authorization.
489
+ writeFileSync(path.join(mobiusHome(), GUI_AUTH_FILE), JSON.stringify({ mode, gui: mode !== 'off' }), { mode: 0o600 })
490
+ } catch { /* unwritable home: the in-memory cache still holds this session */ }
491
+ }
492
+
493
+ /** Authorized in either mode — this is what flips the gui- identifier prefix. */
494
+ export function tuiGuiAuthorized(): boolean { return tuiGuiMode() !== 'off' }
495
+
496
+ /** Only this mode makes aimux request elevation, i.e. show a UAC prompt. */
497
+ export function tuiGuiNoElevate(): boolean { return tuiGuiMode() === 'no-elevate' }
498
+
499
+ export function setTuiGuiAuthorized(value: boolean): void { setTuiGuiMode(value ? 'elevate' : 'off') }
500
+
501
+ export function tuiAimuxIdentifier(hostname = os.hostname(), cwd = process.cwd(), username = currentUsername(), guiEnabled = tuiGuiAuthorized()): string {
369
502
  const host = hostname.toLowerCase().replace(/[^a-z0-9_.-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 32)
370
503
  // One machine may run several Mobius TUIs for different projects (and for
371
504
  // different users). A hostname-only identifier makes every reverse client
372
505
  // register with the same name and --replace continuously evicts its siblings.
373
506
  // The (username, cwd) hash is stable across restarts/resume but unique per
374
507
  // user and per workspace, so separate projects/users never collide.
375
- return `tui-${host || 'pc'}-${aimuxWorkspaceHash(username, cwd)}`
508
+ // GUI-authorized machines register under a gui- prefix so the capability is
509
+ // visible in the remote name itself (web device picker, remote ls).
510
+ return `${guiEnabled ? 'gui' : 'tui'}-${host || 'pc'}-${aimuxWorkspaceHash(username, cwd)}`
376
511
  }
377
512
 
378
513
  // ── shared daemon runtime JSON (one reverse connect per user+workspace) ──
379
514
  const LEASE_RENEW_MS = 5_000
380
- const BRIDGE_FAILURE_LIMIT = 3
515
+ /**
516
+ * How long a freshly spawned daemon has to put runtime state on disk before the
517
+ * supervisor may conclude it never started.
518
+ *
519
+ * Generous on purpose. With --enable-gui on Windows the daemon cannot write
520
+ * anything until a human approves the elevation prompt — `runtime_update()` runs
521
+ * inside bridge_client.connect, which is *after* the elevation gate — so "no pid
522
+ * recorded yet" is the normal shape of a start in progress, not evidence of
523
+ * failure. Respawning on that evidence stacks another process (and another
524
+ * prompt) on top of the one already waiting.
525
+ */
526
+ const SPAWN_GRACE_MS = 90_000
527
+ /**
528
+ * Give up after this many consecutive spawns that never produced runtime state.
529
+ * Each attempt may raise a system authorization prompt, so an unbounded retry
530
+ * turns into a stream of windows; a clear failure the user can act on is worth
531
+ * far more than one more attempt.
532
+ */
533
+ const MAX_UNPRODUCTIVE_SPAWNS = 3
381
534
 
382
535
  const aimuxRuntimeDir = () => path.join(mobiusHome(), 'aimux-runtime')
383
536
  const runtimePath = (hash: string) => path.join(aimuxRuntimeDir(), `${hash}.json`)
@@ -413,8 +566,20 @@ async function touchWatchdog(hash: string): Promise<void> {
413
566
  } catch { /* directory not writable; nothing useful to do here */ }
414
567
  }
415
568
 
416
- function pidAlive(pid: number): boolean {
417
- try { process.kill(pid, 0); return true } catch { return false }
569
+ /**
570
+ * Is `pid` still running? `process.kill(pid, 0)` is the only portable probe, and
571
+ * its *error* carries the answer: ESRCH means gone, EPERM means the process is
572
+ * there and simply not ours to signal. EPERM is the normal case now that
573
+ * --enable-gui makes the daemon an elevated process while the TUI stays
574
+ * unelevated (and it is the classic cross-user case on POSIX). Reading EPERM as
575
+ * dead is what made the supervisor kill and respawn healthy daemons on every
576
+ * bridge hiccup.
577
+ */
578
+ export function pidAlive(
579
+ pid: number,
580
+ probe: (pid: number, signal: number) => void = (p, s) => process.kill(p, s),
581
+ ): boolean {
582
+ try { probe(pid, 0); return true } catch (e: any) { return e?.code === 'EPERM' }
418
583
  }
419
584
 
420
585
 
@@ -437,6 +602,8 @@ export function reverseConnectArgs(
437
602
  platform: NodeJS.Platform = process.platform,
438
603
  silentFlag: string | null = null,
439
604
  runtimeFile: string | null = null,
605
+ enableGui = false,
606
+ guiNoElevate = false,
440
607
  ): string[] {
441
608
  return [
442
609
  'reverse', 'connect', `${server.replace(/\/$/, '')}/aimux_bridge`,
@@ -445,6 +612,10 @@ export function reverseConnectArgs(
445
612
  '--replace',
446
613
  ...(runtimeFile ? ['--runtime', runtimeFile, '--watchdog', runtimeFile] : []),
447
614
  ...(platform === 'win32' && silentFlag ? [silentFlag] : []),
615
+ ...(enableGui ? ['--enable-gui'] : []),
616
+ // Only meaningful next to --enable-gui: it skips that flag's elevation
617
+ // request, and without --enable-gui there is no request to skip.
618
+ ...(enableGui && guiNoElevate ? ['--gui-no-elevate'] : []),
448
619
  ]
449
620
  }
450
621
 
@@ -479,6 +650,24 @@ export function pickSilentFlag(helpText: string, platform: NodeJS.Platform = pro
479
650
  return null
480
651
  }
481
652
 
653
+ /**
654
+ * Does this aimux build advertise --enable-gui (0.3.64+)? Older installs
655
+ * reject unknown options outright, so the flag is only sent when the help
656
+ * text confirms it — same defensive pattern as pickSilentFlag.
657
+ */
658
+ export function pickEnableGuiFlag(helpText: string): boolean {
659
+ return /--enable-gui\b/.test(helpText)
660
+ }
661
+
662
+ /**
663
+ * Does this aimux build advertise --gui-no-elevate? It landed in the same
664
+ * 0.3.64 release as --enable-gui, but probe it separately: sending it to a
665
+ * build that lacks it is the same "No such option" crash-loop.
666
+ */
667
+ export function pickGuiNoElevateFlag(helpText: string): boolean {
668
+ return /--gui-no-elevate\b/.test(helpText)
669
+ }
670
+
482
671
  /** Result of a bridge heartbeat: is the stream up, and did the JWT just get rejected? */
483
672
  export interface AimuxBridgeProbe { connected: boolean; authError: boolean }
484
673
 
@@ -524,6 +713,10 @@ interface SupervisorOptions {
524
713
  /** Re-authenticate after AIMUX reports an expired/invalid bridge JWT. */
525
714
  refreshToken?: () => Promise<string | null>
526
715
  heartbeatIntervalMs?: number
716
+ /** Grace before a spawn that produced no runtime state counts as failed (tests shrink this). */
717
+ spawnGraceMs?: number
718
+ /** Spawns allowed before giving up (tests shrink this). */
719
+ maxUnproductiveSpawns?: number
527
720
  retryBaseMs?: number
528
721
  probeConnection?: () => Promise<boolean | AimuxBridgeProbe>
529
722
  spawnProcess?: (token: string) => ChildProcess
@@ -545,6 +738,12 @@ export class AimuxSupervisor {
545
738
  private watchdogTimer: ReturnType<typeof setTimeout> | null = null
546
739
  private probeTimer: ReturnType<typeof setTimeout> | null = null
547
740
  private bridgeFailures = 0
741
+ /** When this supervisor last started a daemon (0 = it has not started any). */
742
+ private spawnedAt = 0
743
+ /** Spawns in a row that never reached runtime state — see MAX_UNPRODUCTIVE_SPAWNS. */
744
+ private unproductiveSpawns = 0
745
+ /** Set once the retry budget is spent: keep probing (so a late approval still recovers) but stop spawning. */
746
+ private gaveUp = false
548
747
  private opts: SupervisorOptions
549
748
  private hash: string
550
749
  constructor(opts: SupervisorOptions) { this.opts = opts; this.hash = aimuxWorkspaceHash() }
@@ -577,9 +776,13 @@ export class AimuxSupervisor {
577
776
  if (pid !== null && pidAlive(pid)) { await touchWatchdog(this.hash); return }
578
777
  const { server, token, identifier, onStatus } = this.opts
579
778
  onStatus({ state: 'starting', phase: 'connecting', detail: '正在启动 AIMUX 守护进程…', identifier, attempt: this.reconnectAttempt })
580
- const child = this.opts.spawnProcess?.(token) ?? spawnDetachedDaemon({ kind: 'exe', path: aimuxExe() }, reverseConnectArgs(server, identifier, token, process.platform, null, runtimePath(this.hash)))
779
+ const gui = resolvedGuiArgs()
780
+ const child = this.opts.spawnProcess?.(token) ?? spawnDetachedDaemon({ kind: 'exe', path: aimuxExe() }, reverseConnectArgs(server, identifier, token, process.platform, null, runtimePath(this.hash), gui.enableGui, gui.guiNoElevate))
581
781
  child.on('error', (e: Error) => { appendAimuxLog(installLogQueue, `\n[aimux spawn error] ${e.stack || e.message}\n`) })
582
782
  child.unref?.()
783
+ this.spawnedAt = Date.now()
784
+ this.unproductiveSpawns += 1
785
+ appendAimuxLog(installLogQueue, `\n[aimux spawn] at=${new Date(this.spawnedAt).toISOString()} workspace=${this.hash} cwd=${process.cwd()} pid=${process.pid} gui=${gui.enableGui ? (gui.guiNoElevate ? 'no-elevate' : 'elevate') : 'off'} attempt=${this.unproductiveSpawns}\n`)
583
786
  this.reconnectAttempt = 0
584
787
  }
585
788
 
@@ -599,7 +802,7 @@ export class AimuxSupervisor {
599
802
  this.probeTimer = setTimeout(() => void this.checkDaemon(), this.opts.heartbeatIntervalMs ?? 5_000)
600
803
  }
601
804
 
602
- /** Probe the bridge; refresh on auth error, respawn only when the daemon died. */
805
+ /** Probe the bridge; refresh on auth error, respawn only when the daemon is gone. */
603
806
  private async checkDaemon(): Promise<void> {
604
807
  if (this.stopping) return
605
808
  const raw = await (this.opts.probeConnection?.() ?? probeAimuxBridge(this.opts.server, this.opts.token, this.opts.identifier))
@@ -610,6 +813,8 @@ export class AimuxSupervisor {
610
813
  await this.refreshCredentials('JWT 已过期')
611
814
  } else if (probe.connected) {
612
815
  this.reconnectAttempt = 0
816
+ this.gaveUp = false
817
+ this.unproductiveSpawns = 0
613
818
  this.opts.onStatus({ state: 'connected', phase: 'connected', detail: `心跳正常 · ${this.opts.identifier}`, identifier: this.opts.identifier })
614
819
  this.bridgeFailures = 0
615
820
  } else {
@@ -617,15 +822,42 @@ export class AimuxSupervisor {
617
822
  await this.updateRuntimeHealth(false)
618
823
  const runtime = await readRuntime(this.hash)
619
824
  const pid = runtime?.pid ?? null
620
- if (pid === null || !pidAlive(pid) || this.bridgeFailures >= BRIDGE_FAILURE_LIMIT) {
825
+ const alive = pid !== null && pidAlive(pid)
826
+ // Runtime state on disk means the daemon got past its own start — which on
827
+ // Windows may have meant an elevation prompt — so the attempt produced
828
+ // something and the retry budget is not the thing to withhold.
829
+ if (pid !== null) this.unproductiveSpawns = 0
830
+ if (alive) {
831
+ // The daemon owns reconnection — it retries with backoff and re-registers
832
+ // on its own. Killing a live daemon cannot fix a bridge problem, and on
833
+ // Windows the replacement costs a UAC prompt; worse, the two then take
834
+ // turns evicting each other through --replace, which drops the stream
835
+ // again. So a live daemon is left alone no matter how long it takes.
836
+ this.opts.onStatus({ state: 'starting', phase: 'heartbeat', detail: '等待 bridge 心跳确认…', identifier: this.opts.identifier })
837
+ } else if (pid === null && this.unproductiveSpawns >= (this.opts.maxUnproductiveSpawns ?? MAX_UNPRODUCTIVE_SPAWNS)) {
838
+ // Stop rather than keep stacking attempts the user cannot act on. The
839
+ // actionable cause is almost always a system authorization prompt that
840
+ // was never shown (a remote or locked session) or never answered, and
841
+ // the daemon cannot reach its watchdog until the prompt is dealt with.
842
+ this.opts.onStatus({
843
+ state: 'failed', phase: 'idle',
844
+ detail: `AIMUX 连续 ${this.unproductiveSpawns} 次启动失败。若系统授权弹窗看不到或点不了(远程/锁屏会话),请在向导里把 GUI 授权改为「低权限」或「纯命令行」。日志: ${aimuxLogPath()}`,
845
+ identifier: this.opts.identifier,
846
+ })
847
+ this.gaveUp = true
848
+ } else if (pid === null && Date.now() - this.spawnedAt < (this.opts.spawnGraceMs ?? SPAWN_GRACE_MS)) {
849
+ // Nothing on disk yet. With --enable-gui on Windows the daemon cannot
850
+ // write runtime state until a human approves the elevation prompt, so
851
+ // this is the normal shape of a start in progress — respawning here
852
+ // stacks another prompt every probe interval. Wait it out.
853
+ this.opts.onStatus({ state: 'starting', phase: 'connecting', detail: '等待 AIMUX 守护进程就绪(若弹出系统授权请点击确认)…', identifier: this.opts.identifier })
854
+ } else if (!this.gaveUp) {
855
+ // No runtime state and our own spawn is long past, or the recorded pid is
856
+ // genuinely gone (ESRCH) — nothing to reconnect, so start one.
621
857
  this.reconnectAttempt += 1
622
- this.opts.onStatus({ state: 'failed', phase: 'retrying', detail: `AIMUX bridge 无响应,重启连接中(第 ${this.reconnectAttempt} 次)…`, identifier: this.opts.identifier, attempt: this.reconnectAttempt })
623
- if (pid !== null && pidAlive(pid)) { try { process.kill(pid, 'SIGTERM') } catch {} }
858
+ this.opts.onStatus({ state: 'failed', phase: 'retrying', detail: `AIMUX 守护进程未响应,重启连接中(第 ${this.reconnectAttempt} 次)…`, identifier: this.opts.identifier, attempt: this.reconnectAttempt })
624
859
  this.bridgeFailures = 0
625
860
  await this.spawnDaemon()
626
- } else {
627
- // Daemon alive but stream down → transient; its own reconnect handles it.
628
- this.opts.onStatus({ state: 'starting', phase: 'heartbeat', detail: '等待 bridge 心跳确认…', identifier: this.opts.identifier })
629
861
  }
630
862
  }
631
863
  this.scheduleProbe()
@@ -702,6 +934,60 @@ interface StartOptions {
702
934
  // not probed yet this process). Cached so reconnects reuse it without re-running
703
935
  // `aimux reverse connect --help`. See reverseConnectArgs for why this is probed.
704
936
  let cachedSilentFlag: string | null | undefined = undefined
937
+ // Same caching for --enable-gui support (aimux 0.3.64+): sending it to an older
938
+ // build crashes the supervisor with "No such option".
939
+ let cachedEnableGui: boolean | undefined = undefined
940
+ // --gui-no-elevate shipped in that same release, so it is probed from the same
941
+ // help text and only consulted while --enable-gui is being sent.
942
+ let cachedGuiNoElevate: boolean | undefined = undefined
943
+
944
+ /**
945
+ * The mode actually in force, as opposed to the stored preference. Availability
946
+ * can invalidate a stored choice — a machine-level 'elevate' picked from an
947
+ * administrator session, reopened from an ordinary one — and the daemon gets
948
+ * this, not what was stored. Mirrors pickGuiArgs so the picker's "current"
949
+ * marker cannot point at a mode this machine will not use.
950
+ */
951
+ export function effectiveGuiMode(
952
+ mode: GuiMode = tuiGuiMode(),
953
+ elevated = windowsElevated(),
954
+ platform: NodeJS.Platform = process.platform,
955
+ ): GuiMode {
956
+ if (mode === 'off') return 'off'
957
+ if (guiModeAvailability(elevated, platform)[mode].available) return mode
958
+ if (platform !== 'win32') return mode
959
+ return elevated ? 'elevate' : 'no-elevate'
960
+ }
961
+
962
+ /**
963
+ * The GUI flags to send, given the stored mode, this TUI's own privilege and
964
+ * what the installed aimux advertises.
965
+ *
966
+ * Pure so the rule can be tested directly. The rule is that an unelevated TUI may
967
+ * only ever send the pair that requests nothing; when the installed build cannot
968
+ * express that, it sends no GUI flags at all rather than risk a daemon start that
969
+ * blocks on a consent prompt the supervisor can neither see nor clean up.
970
+ */
971
+ export function pickGuiArgs(
972
+ mode: GuiMode,
973
+ elevated: boolean,
974
+ supports: { enable: boolean; noElevate: boolean },
975
+ platform: NodeJS.Platform = process.platform,
976
+ ): { enableGui: boolean; guiNoElevate: boolean } {
977
+ if (mode === 'off' || !supports.enable) return { enableGui: false, guiNoElevate: false }
978
+ if (platform !== 'win32') return { enableGui: true, guiNoElevate: mode === 'no-elevate' && supports.noElevate }
979
+ if (elevated) return { enableGui: true, guiNoElevate: false }
980
+ return supports.noElevate ? { enableGui: true, guiNoElevate: true } : { enableGui: false, guiNoElevate: false }
981
+ }
982
+
983
+ /** pickGuiArgs bound to the stored mode, this process's token and the probe caches. */
984
+ function resolvedGuiArgs(): { enableGui: boolean; guiNoElevate: boolean } {
985
+ return pickGuiArgs(
986
+ tuiGuiMode(),
987
+ windowsElevated(),
988
+ { enable: cachedEnableGui === true, noElevate: cachedGuiNoElevate === true },
989
+ )
990
+ }
705
991
 
706
992
  export async function startAimuxConnection(opts: StartOptions): Promise<void> {
707
993
  const onStatus = opts.onStatus ?? (() => {})
@@ -727,15 +1013,25 @@ export async function startAimuxConnection(opts: StartOptions): Promise<void> {
727
1013
  // Windows only: ask the installed aimux which console-hiding flag it accepts
728
1014
  // before spawning, so a version mismatch (older PyPI/bundle aimux without
729
1015
  // --slient-v2) can't crash-loop the supervisor with "No such option".
730
- if (WIN && cachedSilentFlag === undefined) {
1016
+ const needGuiFlag = tuiGuiAuthorized()
1017
+ if (cachedSilentFlag === undefined || (needGuiFlag && cachedEnableGui === undefined)) {
731
1018
  const help = await probeReverseConnectHelp(launcher)
732
- cachedSilentFlag = pickSilentFlag(help)
733
- logInstall(`reverse-connect silent flag probe → ${cachedSilentFlag ?? '(none supported; sending no flag)'}\n`)
1019
+ if (WIN && cachedSilentFlag === undefined) {
1020
+ cachedSilentFlag = pickSilentFlag(help)
1021
+ logInstall(`reverse-connect silent flag probe → ${cachedSilentFlag ?? '(none supported; sending no flag)'}\n`)
1022
+ }
1023
+ if (needGuiFlag && cachedEnableGui === undefined) {
1024
+ cachedEnableGui = pickEnableGuiFlag(help)
1025
+ cachedGuiNoElevate = pickGuiNoElevateFlag(help)
1026
+ logInstall(`reverse-connect --enable-gui probe → ${cachedEnableGui ? 'supported' : 'NOT supported (skipping; upgrade aimux to 0.3.64+)'} · --gui-no-elevate ${cachedGuiNoElevate ? 'supported' : 'NOT supported'}\n`)
1027
+ }
734
1028
  }
735
1029
  const silentFlag = cachedSilentFlag
1030
+ const gui = resolvedGuiArgs()
1031
+ logInstall(`GUI mode ${tuiGuiMode()} → ${gui.enableGui ? (gui.guiNoElevate ? '--enable-gui --gui-no-elevate (no UAC)' : '--enable-gui (UAC on Windows)') : 'no GUI flags'}\n`)
736
1032
  supervisor = new AimuxSupervisor({
737
1033
  server: opts.server, token: opts.token, identifier, onStatus, refreshToken: opts.refreshToken,
738
- spawnProcess: token => spawnDetachedDaemon(launcher, reverseConnectArgs(opts.server, identifier, token, process.platform, silentFlag, runtimePath(aimuxWorkspaceHash()))),
1034
+ spawnProcess: token => spawnDetachedDaemon(launcher, reverseConnectArgs(opts.server, identifier, token, process.platform, silentFlag, runtimePath(aimuxWorkspaceHash()), gui.enableGui, gui.guiNoElevate)),
739
1035
  })
740
1036
  await supervisor.start()
741
1037
  })().finally(() => { installing = null })
@@ -747,15 +1043,35 @@ export async function stopAimuxConnection(): Promise<void> {
747
1043
  await current?.stop()
748
1044
  }
749
1045
 
1046
+ /**
1047
+ * Re-do the reverse connection after the GUI authorization choice changed.
1048
+ * The old daemon must die first (its runtime JSON is keyed by workspace hash,
1049
+ * not by the identifier or flags) and a fresh one spawns with the new set:
1050
+ * the identifier flips tui-⇄gui- on off⇄authorized, and the flags differ
1051
+ * between no-elevate and elevate. No-op when no connection is up yet — the
1052
+ * next startAimuxConnection picks the new mode up anyway.
1053
+ */
1054
+ export async function restartAimuxConnectionForGuiChange(): Promise<void> {
1055
+ const opts = lastStartOpts
1056
+ await stopAimuxConnection()
1057
+ await stopDaemonFromRuntime()
1058
+ if (opts) await startAimuxConnection(opts)
1059
+ }
1060
+
750
1061
  /** SIGTERM 掉本工作区 runtime JSON 里记录的守护进程,并删掉该文件。
751
1062
  * 不这么做的话,新 supervisor 会按 pid 复用到刚升级前的旧 daemon。 */
752
1063
  async function stopDaemonFromRuntime(): Promise<void> {
753
1064
  const hash = aimuxWorkspaceHash()
754
1065
  const pid = (await readRuntime(hash))?.pid ?? null
755
1066
  if (pid !== null && pidAlive(pid)) {
756
- try { process.kill(pid, 'SIGTERM') } catch { /* 已经退了 */ }
757
- for (let i = 0; i < 30 && pidAlive(pid); i++) await new Promise(r => setTimeout(r, 100))
758
- if (pidAlive(pid)) { try { process.kill(pid, 'SIGKILL') } catch { /* ignore */ } }
1067
+ // EPERM means the daemon is elevated and not ours to signal; waiting for it
1068
+ // to die would just stall the caller, so leave it to its own watchdog.
1069
+ let ours = true
1070
+ try { process.kill(pid, 'SIGTERM') } catch (e: any) { ours = e?.code !== 'EPERM' }
1071
+ if (ours) {
1072
+ for (let i = 0; i < 30 && pidAlive(pid); i++) await new Promise(r => setTimeout(r, 100))
1073
+ if (pidAlive(pid)) { try { process.kill(pid, 'SIGKILL') } catch { /* ignore */ } }
1074
+ }
759
1075
  }
760
1076
  try { await fs.unlink(runtimePath(hash)) } catch { /* 本来就没有 */ }
761
1077
  }
@@ -62,7 +62,7 @@ const SLASH_COMMANDS = [
62
62
  { cmd: '/compact', desc: '压缩当前会话上下文' },
63
63
  { cmd: '/resume', desc: '恢复一个历史会话' },
64
64
  { cmd: '/model', desc: '更换模型并开启新会话(保留当前任务)' },
65
- { cmd: '/config', desc: '重新选择项目、任务和模型' },
65
+ { cmd: '/config', desc: '重新选择项目、任务、模型和 AIMUX 图形界面授权' },
66
66
  { cmd: '/logout', desc: '断开当前连接并返回登录界面' },
67
67
  { cmd: '/help', desc: '显示帮助' },
68
68
  { cmd: '/version', desc: '显示 TUI、AIMUX 和运行环境版本' },
@@ -27,7 +27,11 @@ import {
27
27
  bindCwdToProject, cwd, getCwdPreference, loadDir2Project, loadProjectsCache,
28
28
  saveProjectsCache, setCwdIssue, updateIssuePreference, type IssuePreference,
29
29
  } from '../config.js'
30
- import { tuiAimuxIdentifier } from '../aimux.js'
30
+ import {
31
+ effectiveGuiMode, guiModeOptions, hasGuiSupport, restartAimuxConnectionForGuiChange,
32
+ setTuiGuiMode, tuiAimuxIdentifier, tuiGuiAuthorized, tuiGuiMode, type GuiMode,
33
+ } from '../aimux.js'
34
+ import { windowsElevated } from '../lib/windows-admin.js'
31
35
  import type { Issue, Project, SessionModelOption } from '../types.js'
32
36
 
33
37
  export interface ConfigResult {
@@ -82,6 +86,7 @@ export function ConfigFlow({ client, issue, onDone }: {
82
86
  local_path: process.cwd(),
83
87
  is_tui: true,
84
88
  add_remote_aimux_mcp: true,
89
+ ...(tuiGuiAuthorized() ? { gui_authorized: true } : {}),
85
90
  },
86
91
  })
87
92
  if (doneRef.current) return
@@ -132,12 +137,16 @@ export function ConfigFlow({ client, issue, onDone }: {
132
137
 
133
138
  // ── /config: full reconfigure (project → issue → model) ─────────────────────
134
139
 
135
- type ReconfigStep = 'projects' | 'issues' | 'models' | 'creating'
140
+ type ReconfigStep = 'projects' | 'issues' | 'models' | 'gui' | 'creating'
136
141
 
137
- export function ReconfigFlow({ client, onDone, onCancel }: {
142
+ export function ReconfigFlow({ client, onDone, onCancel, platform = process.platform, elevated = windowsElevated() }: {
138
143
  client: MobiusClient
139
144
  onDone: (r: ConfigResult) => void
140
145
  onCancel: () => void
146
+ /** Overridable so tests can exercise the platform-gated GUI step anywhere. */
147
+ platform?: NodeJS.Platform
148
+ /** Overridable so tests can exercise the elevated branch anywhere. */
149
+ elevated?: boolean
141
150
  }) {
142
151
  const [step, setStep] = useState<ReconfigStep>('projects')
143
152
  const [projects, setProjects] = useState<Project[] | null>(null)
@@ -147,6 +156,7 @@ export function ReconfigFlow({ client, onDone, onCancel }: {
147
156
  const [models, setModels] = useState<SessionModelOption[] | null>(null)
148
157
  const [defaultKey, setDefaultKey] = useState<string | null>(null)
149
158
  const [status, setStatus] = useState('')
159
+ const [pendingModel, setPendingModel] = useState<string | null>(null)
150
160
  const [createName, setCreateName] = useState('')
151
161
  const [createMode, setCreateMode] = useState<'project' | 'issue' | null>(null)
152
162
  const doneRef = useRef(false)
@@ -156,6 +166,10 @@ export function ReconfigFlow({ client, onDone, onCancel }: {
156
166
  // The focused TextInput owns Esc while a create form is open. Returning
157
167
  // here prevents the same raw key from also navigating the underlying step.
158
168
  if (createMode !== null) return
169
+ if (step === 'gui') {
170
+ setStep('models')
171
+ return
172
+ }
159
173
  if (step === 'models') {
160
174
  setIssue(null)
161
175
  setStep('issues')
@@ -262,8 +276,25 @@ export function ReconfigFlow({ client, onDone, onCancel }: {
262
276
  } catch (e: any) { if (!doneRef.current) setStatus(`创建任务失败: ${e?.message ?? e}`) }
263
277
  }
264
278
 
265
- // ── model → session ───────────────────────────────────────────────────────
279
+ // ── model → gui → session ─────────────────────────────────────────────────
266
280
  async function pickModel(model: string) {
281
+ if (!project || !issue) return
282
+ // The GUI choice is machine-level and lives here so it can be revisited
283
+ // without re-running the first-run wizard.
284
+ if (hasGuiSupport(platform)) { setPendingModel(model); setStep('gui'); return }
285
+ await createSession(model)
286
+ }
287
+
288
+ /** Commit the GUI choice, then create the session the model step deferred. */
289
+ async function applyGuiMode(mode: GuiMode, model: string) {
290
+ if (tuiGuiMode() !== mode) {
291
+ setTuiGuiMode(mode)
292
+ void restartAimuxConnectionForGuiChange()
293
+ }
294
+ await createSession(model)
295
+ }
296
+
297
+ async function createSession(model: string) {
267
298
  if (!project || !issue) return
268
299
  setStep('creating')
269
300
  try {
@@ -281,6 +312,7 @@ export function ReconfigFlow({ client, onDone, onCancel }: {
281
312
  local_path: process.cwd(),
282
313
  is_tui: true,
283
314
  add_remote_aimux_mcp: true,
315
+ ...(tuiGuiAuthorized() ? { gui_authorized: true } : {}),
284
316
  },
285
317
  })
286
318
  if (doneRef.current) return
@@ -398,6 +430,23 @@ export function ReconfigFlow({ client, onDone, onCancel }: {
398
430
  <Text color="gray">↑↓ 选择 · 回车确认 · Esc 取消</Text>
399
431
  </Box>
400
432
  ) : null}
433
+
434
+ {step === 'gui' ? (
435
+ <Box flexDirection="column">
436
+ <Text bold color="cyan">AIMUX 图形界面授权</Text>
437
+ <Text color="gray">项目: {project?.name} · 任务: {issue?.title}</Text>
438
+ <Box marginTop={1}>
439
+ <Select
440
+ items={guiModeOptions(elevated, platform).map(row => ({
441
+ ...row,
442
+ label: `${row.label}${effectiveGuiMode(tuiGuiMode(), elevated, platform) === row.value ? ' · 当前' : ''}`,
443
+ }))}
444
+ onSelect={v => void applyGuiMode(v === 'elevate' ? 'elevate' : v === 'no-elevate' ? 'no-elevate' : 'off', pendingModel!)}
445
+ />
446
+ </Box>
447
+ <Text color="gray">↑↓ 选择 · 回车确认 · Esc 返回</Text>
448
+ </Box>
449
+ ) : null}
401
450
  </Box>
402
451
  )
403
452
  }