@mobius-os/mobius 0.3.66 → 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.66",
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=14
17
- AIMUX_VERSION=0.3.66
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
@@ -13,6 +13,7 @@ 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.66'
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 = '14'
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
@@ -366,30 +367,137 @@ export function aimuxWorkspaceHash(username = currentUsername(), cwd = process.c
366
367
  }
367
368
 
368
369
  // ── GUI (computer use) authorization ─────────────────────────────────────
369
- // Machine-level choice made in the first-run wizard: when true the reverse
370
- // client registers as gui-<host>-<hash> and connects with --enable-gui, so
371
- // the remote exposes the remote_gui_* (computer use) toolset.
372
- const GUI_AUTH_FILE = 'tui-gui-authorized.json'
373
- let guiAuthorizedCache: boolean | undefined = undefined
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'
374
400
 
375
- export function tuiGuiAuthorized(): boolean {
376
- if (guiAuthorizedCache === undefined) {
377
- try {
378
- const raw = readFileSync(path.join(mobiusHome(), GUI_AUTH_FILE), 'utf8')
379
- guiAuthorizedCache = (JSON.parse(raw) as { gui?: boolean })?.gui === true
380
- } catch { guiAuthorizedCache = false }
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
+ })
381
446
  }
382
- return guiAuthorizedCache
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
383
478
  }
384
479
 
385
- export function setTuiGuiAuthorized(value: boolean): void {
386
- guiAuthorizedCache = value
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
387
485
  try {
388
486
  mkdirSync(mobiusHome(), { recursive: true })
389
- writeFileSync(path.join(mobiusHome(), GUI_AUTH_FILE), JSON.stringify({ gui: value }), { mode: 0o600 })
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 })
390
490
  } catch { /* unwritable home: the in-memory cache still holds this session */ }
391
491
  }
392
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
+
393
501
  export function tuiAimuxIdentifier(hostname = os.hostname(), cwd = process.cwd(), username = currentUsername(), guiEnabled = tuiGuiAuthorized()): string {
394
502
  const host = hostname.toLowerCase().replace(/[^a-z0-9_.-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 32)
395
503
  // One machine may run several Mobius TUIs for different projects (and for
@@ -404,7 +512,25 @@ export function tuiAimuxIdentifier(hostname = os.hostname(), cwd = process.cwd()
404
512
 
405
513
  // ── shared daemon runtime JSON (one reverse connect per user+workspace) ──
406
514
  const LEASE_RENEW_MS = 5_000
407
- 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
408
534
 
409
535
  const aimuxRuntimeDir = () => path.join(mobiusHome(), 'aimux-runtime')
410
536
  const runtimePath = (hash: string) => path.join(aimuxRuntimeDir(), `${hash}.json`)
@@ -440,8 +566,20 @@ async function touchWatchdog(hash: string): Promise<void> {
440
566
  } catch { /* directory not writable; nothing useful to do here */ }
441
567
  }
442
568
 
443
- function pidAlive(pid: number): boolean {
444
- 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' }
445
583
  }
446
584
 
447
585
 
@@ -465,6 +603,7 @@ export function reverseConnectArgs(
465
603
  silentFlag: string | null = null,
466
604
  runtimeFile: string | null = null,
467
605
  enableGui = false,
606
+ guiNoElevate = false,
468
607
  ): string[] {
469
608
  return [
470
609
  'reverse', 'connect', `${server.replace(/\/$/, '')}/aimux_bridge`,
@@ -474,6 +613,9 @@ export function reverseConnectArgs(
474
613
  ...(runtimeFile ? ['--runtime', runtimeFile, '--watchdog', runtimeFile] : []),
475
614
  ...(platform === 'win32' && silentFlag ? [silentFlag] : []),
476
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'] : []),
477
619
  ]
478
620
  }
479
621
 
@@ -517,6 +659,15 @@ export function pickEnableGuiFlag(helpText: string): boolean {
517
659
  return /--enable-gui\b/.test(helpText)
518
660
  }
519
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
+
520
671
  /** Result of a bridge heartbeat: is the stream up, and did the JWT just get rejected? */
521
672
  export interface AimuxBridgeProbe { connected: boolean; authError: boolean }
522
673
 
@@ -562,6 +713,10 @@ interface SupervisorOptions {
562
713
  /** Re-authenticate after AIMUX reports an expired/invalid bridge JWT. */
563
714
  refreshToken?: () => Promise<string | null>
564
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
565
720
  retryBaseMs?: number
566
721
  probeConnection?: () => Promise<boolean | AimuxBridgeProbe>
567
722
  spawnProcess?: (token: string) => ChildProcess
@@ -583,6 +738,12 @@ export class AimuxSupervisor {
583
738
  private watchdogTimer: ReturnType<typeof setTimeout> | null = null
584
739
  private probeTimer: ReturnType<typeof setTimeout> | null = null
585
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
586
747
  private opts: SupervisorOptions
587
748
  private hash: string
588
749
  constructor(opts: SupervisorOptions) { this.opts = opts; this.hash = aimuxWorkspaceHash() }
@@ -615,9 +776,13 @@ export class AimuxSupervisor {
615
776
  if (pid !== null && pidAlive(pid)) { await touchWatchdog(this.hash); return }
616
777
  const { server, token, identifier, onStatus } = this.opts
617
778
  onStatus({ state: 'starting', phase: 'connecting', detail: '正在启动 AIMUX 守护进程…', identifier, attempt: this.reconnectAttempt })
618
- const child = this.opts.spawnProcess?.(token) ?? spawnDetachedDaemon({ kind: 'exe', path: aimuxExe() }, reverseConnectArgs(server, identifier, token, process.platform, null, runtimePath(this.hash), tuiGuiAuthorized()))
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))
619
781
  child.on('error', (e: Error) => { appendAimuxLog(installLogQueue, `\n[aimux spawn error] ${e.stack || e.message}\n`) })
620
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`)
621
786
  this.reconnectAttempt = 0
622
787
  }
623
788
 
@@ -637,7 +802,7 @@ export class AimuxSupervisor {
637
802
  this.probeTimer = setTimeout(() => void this.checkDaemon(), this.opts.heartbeatIntervalMs ?? 5_000)
638
803
  }
639
804
 
640
- /** 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. */
641
806
  private async checkDaemon(): Promise<void> {
642
807
  if (this.stopping) return
643
808
  const raw = await (this.opts.probeConnection?.() ?? probeAimuxBridge(this.opts.server, this.opts.token, this.opts.identifier))
@@ -648,6 +813,8 @@ export class AimuxSupervisor {
648
813
  await this.refreshCredentials('JWT 已过期')
649
814
  } else if (probe.connected) {
650
815
  this.reconnectAttempt = 0
816
+ this.gaveUp = false
817
+ this.unproductiveSpawns = 0
651
818
  this.opts.onStatus({ state: 'connected', phase: 'connected', detail: `心跳正常 · ${this.opts.identifier}`, identifier: this.opts.identifier })
652
819
  this.bridgeFailures = 0
653
820
  } else {
@@ -655,15 +822,42 @@ export class AimuxSupervisor {
655
822
  await this.updateRuntimeHealth(false)
656
823
  const runtime = await readRuntime(this.hash)
657
824
  const pid = runtime?.pid ?? null
658
- 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.
659
857
  this.reconnectAttempt += 1
660
- this.opts.onStatus({ state: 'failed', phase: 'retrying', detail: `AIMUX bridge 无响应,重启连接中(第 ${this.reconnectAttempt} 次)…`, identifier: this.opts.identifier, attempt: this.reconnectAttempt })
661
- 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 })
662
859
  this.bridgeFailures = 0
663
860
  await this.spawnDaemon()
664
- } else {
665
- // Daemon alive but stream down → transient; its own reconnect handles it.
666
- this.opts.onStatus({ state: 'starting', phase: 'heartbeat', detail: '等待 bridge 心跳确认…', identifier: this.opts.identifier })
667
861
  }
668
862
  }
669
863
  this.scheduleProbe()
@@ -743,6 +937,57 @@ let cachedSilentFlag: string | null | undefined = undefined
743
937
  // Same caching for --enable-gui support (aimux 0.3.64+): sending it to an older
744
938
  // build crashes the supervisor with "No such option".
745
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
+ }
746
991
 
747
992
  export async function startAimuxConnection(opts: StartOptions): Promise<void> {
748
993
  const onStatus = opts.onStatus ?? (() => {})
@@ -777,14 +1022,16 @@ export async function startAimuxConnection(opts: StartOptions): Promise<void> {
777
1022
  }
778
1023
  if (needGuiFlag && cachedEnableGui === undefined) {
779
1024
  cachedEnableGui = pickEnableGuiFlag(help)
780
- logInstall(`reverse-connect --enable-gui probe → ${cachedEnableGui ? 'supported' : 'NOT supported (skipping; upgrade aimux to 0.3.64+)'}\n`)
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`)
781
1027
  }
782
1028
  }
783
1029
  const silentFlag = cachedSilentFlag
784
- const enableGui = needGuiFlag && cachedEnableGui === true
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`)
785
1032
  supervisor = new AimuxSupervisor({
786
1033
  server: opts.server, token: opts.token, identifier, onStatus, refreshToken: opts.refreshToken,
787
- spawnProcess: token => spawnDetachedDaemon(launcher, reverseConnectArgs(opts.server, identifier, token, process.platform, silentFlag, runtimePath(aimuxWorkspaceHash()), enableGui)),
1034
+ spawnProcess: token => spawnDetachedDaemon(launcher, reverseConnectArgs(opts.server, identifier, token, process.platform, silentFlag, runtimePath(aimuxWorkspaceHash()), gui.enableGui, gui.guiNoElevate)),
788
1035
  })
789
1036
  await supervisor.start()
790
1037
  })().finally(() => { installing = null })
@@ -797,11 +1044,12 @@ export async function stopAimuxConnection(): Promise<void> {
797
1044
  }
798
1045
 
799
1046
  /**
800
- * Re-do the reverse connection after the GUI authorization choice changed:
801
- * the identifier flips tui-⇄gui-, so the old daemon must die first (its
802
- * runtime JSON is keyed by workspace hash, not identifier) and a fresh one
803
- * spawns with/without --enable-gui. No-op when no connection is up yet —
804
- * the next startAimuxConnection picks the new flag up anyway.
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.
805
1053
  */
806
1054
  export async function restartAimuxConnectionForGuiChange(): Promise<void> {
807
1055
  const opts = lastStartOpts
@@ -816,9 +1064,14 @@ async function stopDaemonFromRuntime(): Promise<void> {
816
1064
  const hash = aimuxWorkspaceHash()
817
1065
  const pid = (await readRuntime(hash))?.pid ?? null
818
1066
  if (pid !== null && pidAlive(pid)) {
819
- try { process.kill(pid, 'SIGTERM') } catch { /* 已经退了 */ }
820
- for (let i = 0; i < 30 && pidAlive(pid); i++) await new Promise(r => setTimeout(r, 100))
821
- 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
+ }
822
1075
  }
823
1076
  try { await fs.unlink(runtimePath(hash)) } catch { /* 本来就没有 */ }
824
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, tuiGuiAuthorized} 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 {
@@ -133,12 +137,16 @@ export function ConfigFlow({ client, issue, onDone }: {
133
137
 
134
138
  // ── /config: full reconfigure (project → issue → model) ─────────────────────
135
139
 
136
- type ReconfigStep = 'projects' | 'issues' | 'models' | 'creating'
140
+ type ReconfigStep = 'projects' | 'issues' | 'models' | 'gui' | 'creating'
137
141
 
138
- export function ReconfigFlow({ client, onDone, onCancel }: {
142
+ export function ReconfigFlow({ client, onDone, onCancel, platform = process.platform, elevated = windowsElevated() }: {
139
143
  client: MobiusClient
140
144
  onDone: (r: ConfigResult) => void
141
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
142
150
  }) {
143
151
  const [step, setStep] = useState<ReconfigStep>('projects')
144
152
  const [projects, setProjects] = useState<Project[] | null>(null)
@@ -148,6 +156,7 @@ export function ReconfigFlow({ client, onDone, onCancel }: {
148
156
  const [models, setModels] = useState<SessionModelOption[] | null>(null)
149
157
  const [defaultKey, setDefaultKey] = useState<string | null>(null)
150
158
  const [status, setStatus] = useState('')
159
+ const [pendingModel, setPendingModel] = useState<string | null>(null)
151
160
  const [createName, setCreateName] = useState('')
152
161
  const [createMode, setCreateMode] = useState<'project' | 'issue' | null>(null)
153
162
  const doneRef = useRef(false)
@@ -157,6 +166,10 @@ export function ReconfigFlow({ client, onDone, onCancel }: {
157
166
  // The focused TextInput owns Esc while a create form is open. Returning
158
167
  // here prevents the same raw key from also navigating the underlying step.
159
168
  if (createMode !== null) return
169
+ if (step === 'gui') {
170
+ setStep('models')
171
+ return
172
+ }
160
173
  if (step === 'models') {
161
174
  setIssue(null)
162
175
  setStep('issues')
@@ -263,8 +276,25 @@ export function ReconfigFlow({ client, onDone, onCancel }: {
263
276
  } catch (e: any) { if (!doneRef.current) setStatus(`创建任务失败: ${e?.message ?? e}`) }
264
277
  }
265
278
 
266
- // ── model → session ───────────────────────────────────────────────────────
279
+ // ── model → gui → session ─────────────────────────────────────────────────
267
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) {
268
298
  if (!project || !issue) return
269
299
  setStep('creating')
270
300
  try {
@@ -400,6 +430,23 @@ export function ReconfigFlow({ client, onDone, onCancel }: {
400
430
  <Text color="gray">↑↓ 选择 · 回车确认 · Esc 取消</Text>
401
431
  </Box>
402
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}
403
450
  </Box>
404
451
  )
405
452
  }