@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.
@@ -15,20 +15,22 @@ import React, { useEffect, useState } from 'react'
15
15
  import { Box, Text } from 'ink'
16
16
  import { Select, TextInput, type SelectItem } from './primitives.js'
17
17
  import { MobiusClient } from '../api.js'
18
- import { restartAimuxConnectionForGuiChange, setTuiGuiAuthorized, tuiGuiAuthorized } from '../aimux.js'
18
+ import { effectiveGuiMode, guiModeOptions, hasGuiSupport, restartAimuxConnectionForGuiChange, setTuiGuiMode, tuiGuiMode, type GuiMode } from '../aimux.js'
19
+ import { windowsElevated } from '../lib/windows-admin.js'
19
20
  import {
20
21
  bindCwdToProject, cwd, getCwdPreference, loadDir2Project, loadProjectsCache,
21
22
  saveProjectsCache, setCwdIssue, updateIssuePreference, type IssuePreference,
22
23
  } from '../config.js'
23
24
  import type { Issue, Memory, Project, SessionModelOption, Skill } from '../types.js'
24
25
 
25
- type PrefStep = 'issue' | 'model' | 'language' | 'gui' | 'skills' | 'memories'
26
- // GUI authorization is only meaningful where a computer-use helper exists
27
- // (Windows/macOS in this release); other platforms never see the step.
28
- const GUI_STEP_PLATFORMS: NodeJS.Platform[] = ['win32', 'darwin']
29
- const STEP_ORDER: PrefStep[] = GUI_STEP_PLATFORMS.includes(process.platform)
30
- ? ['model', 'language', 'gui', 'skills', 'memories']
31
- : ['model', 'language', 'skills', 'memories']
26
+ export type PrefStep = 'issue' | 'model' | 'language' | 'gui' | 'skills' | 'memories'
27
+ /** A function rather than a constant so tests can reach the platform-gated
28
+ * GUI step on any host (they pass `platform` to PrepScreen). */
29
+ export function stepOrderFor(platform: NodeJS.Platform): PrefStep[] {
30
+ return hasGuiSupport(platform)
31
+ ? ['model', 'language', 'gui', 'skills', 'memories']
32
+ : ['model', 'language', 'skills', 'memories']
33
+ }
32
34
 
33
35
  export interface ReadyState {
34
36
  project: Project
@@ -36,11 +38,18 @@ export interface ReadyState {
36
38
  prefs: IssuePreference
37
39
  }
38
40
 
39
- export function PrepScreen({ client, onReady, onQuit }: {
41
+ export function PrepScreen({ client, onReady, onQuit, platform = process.platform, elevated = windowsElevated() }: {
40
42
  client: MobiusClient
41
43
  onReady: (st: ReadyState) => void
42
44
  onQuit?: () => void
45
+ /** Overridable so tests can exercise the platform-gated GUI step anywhere. */
46
+ platform?: NodeJS.Platform
47
+ /** Overridable so tests can exercise the elevated branch anywhere. */
48
+ elevated?: boolean
43
49
  }) {
50
+ const stepOrder = stepOrderFor(platform)
51
+ // Mark the mode in force, which availability can have moved off the stored one.
52
+ const effective = effectiveGuiMode(tuiGuiMode(), elevated, platform)
44
53
  const [phase, setPhase] = useState<'loading' | 'project' | 'pref' | 'done'>('loading')
45
54
  const [projects, setProjects] = useState<Project[]>([])
46
55
  const [project, setProject] = useState<Project | null>(null)
@@ -54,10 +63,6 @@ export function PrepScreen({ client, onReady, onQuit }: {
54
63
  const [memories, setMemories] = useState<Memory[]>([])
55
64
  const [defaultModel, setDefaultModel] = useState<string | null>(null)
56
65
  const [statusMsg, setStatusMsg] = useState<string>('')
57
- // GUI 授权的确认子屏: 选"是"后先停下来高亮提醒(Windows 会弹 UAC), 用户再确认才真正生效
58
- // GUI authorization confirm sub-screen: pause with a highlighted notice (a
59
- // UAC prompt follows on Windows) before the choice takes effect.
60
- const [guiConfirm, setGuiConfirm] = useState(false)
61
66
  const thisCwd = cwd()
62
67
 
63
68
  // ── bootstrap ────────────────────────────────────────────────────────────
@@ -115,7 +120,7 @@ export function PrepScreen({ client, onReady, onQuit }: {
115
120
 
116
121
  function computeStep(p: IssuePreference): PrefStep | null {
117
122
  const done = new Set(p.done ?? [])
118
- for (const s of STEP_ORDER) if (!done.has(s)) return s
123
+ for (const s of stepOrder) if (!done.has(s)) return s
119
124
  return null
120
125
  }
121
126
 
@@ -179,6 +184,19 @@ export function PrepScreen({ client, onReady, onQuit }: {
179
184
  onReady({ project, issue: iss, prefs: p })
180
185
  }
181
186
 
187
+ /** Commit the wizard's GUI choice, then swap the daemon when it changed.
188
+ * Both the identifier (tui-⇄gui-) and the reverse-connect flags differ per
189
+ * mode, and the old daemon cannot be retargeted in place. */
190
+ function applyGuiMode(mode: GuiMode) {
191
+ if (tuiGuiMode() !== mode) {
192
+ setTuiGuiMode(mode)
193
+ // In elevate mode the replacement daemon is what raises the Windows UAC
194
+ // prompt; in no-elevate mode it is what removes it.
195
+ void restartAimuxConnectionForGuiChange()
196
+ }
197
+ completeStep('gui', {})
198
+ }
199
+
182
200
  // ── lazy-load lists for the active step ──────────────────────────────────
183
201
  useEffect(() => {
184
202
  if (phase !== 'pref' || !step) return
@@ -223,53 +241,17 @@ export function PrepScreen({ client, onReady, onQuit }: {
223
241
  items={[{ label: '中文', value: 'zh' }, { label: 'English', value: 'en' }]}
224
242
  onSelect={v => completeStep('language', { language: v as 'zh' | 'en' })} />
225
243
  : null}
226
- {step === 'gui' && !guiConfirm
244
+ {step === 'gui'
227
245
  ? <Select
228
246
  title="是否授权操作图形界面 (GUI/computer use)"
229
- items={[
230
- { label: `否(默认)`, value: 'no', desc: '仅命令行/文件方式操作本机' },
231
- { label: `是`, value: 'yes', desc: '以 gui- 前缀注册 bridge client 并启用界面操作工具' },
232
- ]}
233
- onSelect={v => {
234
- if (v === 'yes') {
235
- // 先停在确认屏: 让用户对即将出现的系统授权弹窗有预期, 不做突袭
236
- // Pause on the confirm screen first so the OS prompt never
237
- // ambushes the user.
238
- setGuiConfirm(true)
239
- return
240
- }
241
- if (tuiGuiAuthorized()) {
242
- setTuiGuiAuthorized(false)
243
- void restartAimuxConnectionForGuiChange()
244
- }
245
- completeStep('gui', {})
246
- }} />
247
- : null}
248
- {step === 'gui' && guiConfirm
249
- ? <Box flexDirection="column" borderStyle="round" borderColor="yellow" paddingX={1}>
250
- <Text bold color="yellow">⚠ 即将授权操作图形界面</Text>
251
- <Text color="yellow">确认后{process.platform === 'win32' ? '系统会弹出 UAC 管理员授权窗口' : '将启用界面操作工具'},请留意屏幕上的弹窗并点击确认。</Text>
252
- <Text color="yellow">授权后本机以 gui- 前缀注册,智能体可以操作本机图形界面(含{process.platform === 'win32' ? '管理员' : ''}窗口)。</Text>
253
- <Box marginTop={1}>
254
- <Select
255
- title="继续吗?"
256
- items={[
257
- { label: '继续并授权', value: 'go', desc: process.platform === 'win32' ? '回车后请到 UAC 弹窗点击"是"' : '启用界面操作' },
258
- { label: '取消', value: 'cancel', desc: '返回上一题,不做任何改动' },
259
- ]}
260
- onSelect={v => {
261
- if (v !== 'go') { setGuiConfirm(false); return }
262
- setTuiGuiAuthorized(true)
263
- // 标识符在 tui-⇄gui- 间切换, 旧守护进程必须换掉才能带上 --enable-gui
264
- // (Windows 下新客户端启动时会请求管理员权限 → UAC 弹窗)
265
- // The identifier flips tui-⇄gui-, so the daemon restarts with
266
- // --enable-gui (which triggers the UAC request on Windows).
267
- void restartAimuxConnectionForGuiChange()
268
- setGuiConfirm(false)
269
- completeStep('gui', {})
270
- }} />
271
- </Box>
272
- </Box>
247
+ // Rows come from the shared builder so the wizard and /config cannot
248
+ // drift: a mode this machine cannot provide stays visible, disabled,
249
+ // with the reason in its label.
250
+ items={guiModeOptions(elevated, platform).map(row => ({
251
+ ...row,
252
+ label: `${row.label}${effective === row.value ? ' · 当前' : ''}`,
253
+ }))}
254
+ onSelect={v => applyGuiMode(v === 'elevate' ? 'elevate' : v === 'no-elevate' ? 'no-elevate' : 'off')} />
273
255
  : null}
274
256
  {step === 'skills'
275
257
  ? <MultiPicker title={`选择启用的 Skill(默认全部启用,空格取消)`} items={toItems(skills)}
@@ -429,6 +429,8 @@ export interface SelectItem {
429
429
  label: string
430
430
  value: string
431
431
  desc?: string
432
+ /** Shown but not choosable — for options this machine cannot provide. */
433
+ disabled?: boolean
432
434
  }
433
435
 
434
436
  /** Keep a picker explanation on the item's main row; Select truncates that row. */
@@ -453,26 +455,47 @@ export interface SelectProps {
453
455
 
454
456
  export function Select(props: SelectProps) {
455
457
  const mode = props.mode ?? 'single'
456
- const [active, setActive] = useState(() => Math.max(0, props.initialActive ?? 0))
457
458
  const items = props.items
459
+ // A disabled row is visible but never reachable: the highlight steps over it
460
+ // and Enter on it does nothing.
461
+ const move = (from: number, dir: 1 | -1): number => {
462
+ const n = items.length
463
+ if (n === 0) return from
464
+ let i = from
465
+ for (let step = 0; step < n; step += 1) {
466
+ i = (i + dir + n) % n
467
+ if (!items[i]?.disabled) return i
468
+ }
469
+ return from
470
+ }
471
+ const [active, setActive] = useState(() => {
472
+ const start = Math.max(0, props.initialActive ?? 0)
473
+ return items[start]?.disabled ? move(start, 1) : start
474
+ })
458
475
  const selectedSet = new Set<string>(mode === 'multi' ? (props.selected as string[]) ?? [] : [])
459
476
  const { stdout } = useStdout()
460
477
 
461
- useEffect(() => { setActive(a => Math.min(a, Math.max(0, items.length - 1))) }, [items.length])
478
+ useEffect(() => {
479
+ setActive(a => {
480
+ const clamped = Math.min(a, Math.max(0, items.length - 1))
481
+ return items[clamped]?.disabled ? move(clamped, 1) : clamped
482
+ })
483
+ }, [items.length])
462
484
 
463
485
  useStableInput((input, key) => {
464
486
  if (!items.length) return
465
487
  if (isMouseInput(input)) return
466
- if (key.upArrow) { setActive(a => (a - 1 + items.length) % items.length); return }
467
- if (key.downArrow) { setActive(a => (a + 1) % items.length); return }
488
+ if (key.upArrow) { setActive(a => move(a, -1)); return }
489
+ if (key.downArrow) { setActive(a => move(a, 1)); return }
490
+ const current = items[active]
468
491
  if (mode === 'single') {
469
492
  if (key.return) {
470
- props.onSelect?.(items[active].value)
493
+ if (current && !current.disabled) props.onSelect?.(current.value)
471
494
  return
472
495
  }
473
496
  } else {
474
497
  if (key.return) { props.onConfirm?.(Array.from(selectedSet)); return }
475
- if (input === ' ') { props.onToggle?.(items[active].value); return }
498
+ if (input === ' ') { if (current && !current.disabled) props.onToggle?.(current.value); return }
476
499
  }
477
500
  if (isEscapeKeypress(input, key)) { props.onBack?.(); return }
478
501
  }, { isActive: props.focused !== false })
@@ -504,7 +527,8 @@ export function Select(props: SelectProps) {
504
527
  {hiddenAbove > 0 ? <Text color="gray"> ↑ 还有 {hiddenAbove} 项</Text> : null}
505
528
  {items.slice(start, end).map((it, i) => {
506
529
  const realIdx = start + i
507
- const isActive = realIdx === active
530
+ const disabled = it.disabled === true
531
+ const isActive = realIdx === active && !disabled
508
532
  const checked = mode === 'multi' ? selectedSet.has(it.value) : false
509
533
  const marker = mode === 'multi' ? (checked ? '☑' : '☐') : isActive ? '❯' : ' '
510
534
  // Keep picker rows compact: descriptions belong on the highlighted
@@ -514,7 +538,7 @@ export function Select(props: SelectProps) {
514
538
  return (
515
539
  <Box key={it.value}>
516
540
  <Text
517
- color={isActive ? 'black' : undefined}
541
+ color={disabled ? 'gray' : isActive ? 'black' : undefined}
518
542
  backgroundColor={isActive ? 'cyan' : undefined}
519
543
  bold={isActive}
520
544
  wrap="truncate-end"
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Is this process running with an administrator token?
3
+ *
4
+ * Only a *report* — nothing here changes what aimux does. What decides whether
5
+ * `--enable-gui` raises a UAC prompt is aimux's own `IsUserAnAdmin()` check on
6
+ * the daemon, and Windows children inherit the parent's token, so a daemon
7
+ * started from an elevated terminal is already elevated and never asks. The
8
+ * wizard uses this to stop warning about a prompt that will not appear.
9
+ *
10
+ * The token's integrity level is read from `whoami /groups` rather than by
11
+ * running an admin-only command and checking its exit code: `whoami` works
12
+ * unelevated too, and the SID it prints is not localized.
13
+ */
14
+ import { spawnSync } from 'node:child_process'
15
+
16
+ /** High (elevated by UAC) and System (elevated by service) integrity levels. */
17
+ const ELEVATED_SIDS = ['S-1-16-12288', 'S-1-16-16384']
18
+
19
+ /** Interpret `whoami /groups` output: a High or System mandatory label means elevated. */
20
+ export function parseElevatedGroups(output: string): boolean {
21
+ return ELEVATED_SIDS.some(sid => output.includes(sid))
22
+ }
23
+
24
+ function readWhoamiGroups(): string | null {
25
+ try {
26
+ const r = spawnSync('whoami', ['/groups'], { encoding: 'utf8', windowsHide: true })
27
+ return r.status === 0 ? `${r.stdout ?? ''}` : null
28
+ } catch { return null }
29
+ }
30
+
31
+ let elevatedCache: boolean | undefined = undefined
32
+
33
+ /** Cached; one probe per process. False off Windows, and on any probe failure. */
34
+ export function windowsElevated(): boolean {
35
+ if (elevatedCache === undefined) {
36
+ elevatedCache = process.platform === 'win32' ? parseElevatedGroups(readWhoamiGroups() ?? '') : false
37
+ }
38
+ return elevatedCache
39
+ }
@@ -2,12 +2,13 @@
2
2
  import React from 'react'
3
3
  import { EventEmitter } from 'node:events'
4
4
  import { spawn } from 'node:child_process'
5
- import { promises as fs, existsSync } from 'node:fs'
5
+ import { promises as fs, existsSync, readFileSync, writeFileSync } from 'node:fs'
6
6
  import os from 'node:os'
7
7
  import path from 'node:path'
8
8
  import { render } from 'ink-testing-library'
9
9
  import { AimuxStatusLine } from '../src/components/AimuxStatus.js'
10
- import { AimuxSupervisor, probeAimuxBridgeConnection, BUNDLE_VER, bundleArch, bundleUrl, spawnLauncher, ensureFromBundle, downloadBundleForTest, reverseConnectArgs, pickSilentFlag, versionAtLeast, aimuxLogPath, bundleHealthCheckCode, tuiAimuxIdentifier, AIMUX_VERSION, tuiGuiAuthorized, setTuiGuiAuthorized, pickEnableGuiFlag } from '../src/aimux.js'
10
+ import { AimuxSupervisor, probeAimuxBridgeConnection, BUNDLE_VER, bundleArch, bundleUrl, spawnLauncher, ensureFromBundle, downloadBundleForTest, reverseConnectArgs, pickSilentFlag, versionAtLeast, aimuxLogPath, bundleHealthCheckCode, tuiAimuxIdentifier, AIMUX_VERSION, tuiGuiAuthorized, setTuiGuiAuthorized, pickEnableGuiFlag, pickGuiNoElevateFlag, tuiGuiMode, tuiGuiNoElevate, setTuiGuiMode, readGuiModeForTest, pidAlive, aimuxWorkspaceHash, guiModeAvailability, guiModeOptions, pickGuiArgs, hasGuiSupport, effectiveGuiMode } from '../src/aimux.js'
11
+ import { parseElevatedGroups } from '../src/lib/windows-admin.js'
11
12
 
12
13
  const delay = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms))
13
14
  let pass = 0, fail = 0
@@ -145,23 +146,95 @@ function pidAliveForTest(pid: number): boolean {
145
146
  try { process.kill(pid, 0); return true } catch { return false }
146
147
  }
147
148
 
148
- async function testUnresponsiveLiveDaemonRestarts() {
149
- console.log('\n[AIMUX 3d] stale live PID recovery')
150
- const home = await fs.mkdtemp(path.join(os.tmpdir(), 'mobius-tui-aimux-stale-'))
149
+ function testPidAliveErrorSemantics() {
150
+ console.log('\n[AIMUX 3e] liveness probe reads the kill() error code')
151
+ const throwing = (code: string) => () => { const e: any = new Error(code); e.code = code; throw e }
152
+ ok(pidAlive(process.pid) === true, 'no error means the pid is alive')
153
+ // The elevated-daemon case: --enable-gui makes aimux administrator while the
154
+ // TUI stays unelevated, so the probe is refused rather than answered.
155
+ ok(pidAlive(1234, throwing('EPERM')) === true, 'EPERM means "exists but not ours to signal" → alive')
156
+ ok(pidAlive(1234, throwing('ESRCH')) === false, 'ESRCH means the process is gone')
157
+ ok(pidAlive(1234, throwing('EINVAL')) === false, 'an unexpected error is not optimistically alive')
158
+ }
159
+
160
+ async function testLiveDaemonIsNotRespawned() {
161
+ console.log('\n[AIMUX 3d] a live daemon is left to reconnect itself')
162
+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'mobius-tui-aimux-live-'))
163
+ const savedHome = process.env.MOBIUS_TUI_HOME
164
+ process.env.MOBIUS_TUI_HOME = home
165
+ const runtimeDir = path.join(home, 'aimux-runtime')
166
+ await fs.mkdir(runtimeDir, { recursive: true })
167
+ await fs.writeFile(path.join(runtimeDir, `${aimuxWorkspaceHash()}.json`), JSON.stringify({ pid: process.pid }))
168
+ let spawns = 0
169
+ const supervisor = new AimuxSupervisor({
170
+ server: 'https://mobius.test', token: 'jwt-test', identifier: 'tui-live',
171
+ heartbeatIntervalMs: 5,
172
+ probeConnection: async () => ({ connected: false, authError: false }),
173
+ spawnProcess: () => { spawns += 1; const c = fakeChild(() => {}); c.pid = process.pid; return c },
174
+ onStatus: () => {},
175
+ })
176
+ try {
177
+ await supervisor.start()
178
+ await delay(120) // ~24 probe intervals, well past the old 3-failure threshold
179
+ ok(spawns === 0, 'failing probes never kill or replace a daemon that is still running')
180
+ await supervisor.stop()
181
+ } finally {
182
+ if (savedHome === undefined) delete process.env.MOBIUS_TUI_HOME; else process.env.MOBIUS_TUI_HOME = savedHome
183
+ await fs.rm(home, { recursive: true, force: true })
184
+ }
185
+ }
186
+
187
+ async function testSlowStartDoesNotStackSpawns() {
188
+ console.log('\n[AIMUX 3f] a start with no runtime state yet does not stack spawns')
189
+ // --enable-gui waits for a human at the elevation prompt, and the daemon cannot
190
+ // write runtime state until it is approved. Respawning on "no pid on disk"
191
+ // therefore stacked one window (and one prompt) per probe interval.
192
+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'mobius-tui-aimux-slow-'))
151
193
  const savedHome = process.env.MOBIUS_TUI_HOME
152
194
  process.env.MOBIUS_TUI_HOME = home
153
195
  let spawns = 0
154
196
  const supervisor = new AimuxSupervisor({
155
- server: 'https://mobius.test', token: 'jwt-test', identifier: 'tui-stale',
197
+ server: 'https://mobius.test', token: 'jwt-test', identifier: 'gui-slow',
156
198
  heartbeatIntervalMs: 5,
199
+ spawnGraceMs: 30_000, // the real value is 90s; only the ordering matters here
157
200
  probeConnection: async () => ({ connected: false, authError: false }),
158
201
  spawnProcess: () => { spawns += 1; const c = fakeChild(() => {}); c.pid = process.pid; return c },
159
202
  onStatus: () => {},
160
203
  })
161
204
  try {
162
205
  await supervisor.start()
163
- for (let i = 0; i < 100 && spawns < 2; i += 1) await delay(5)
164
- ok(spawns >= 2, 'three failed bridge probes restart an apparently live daemon')
206
+ await delay(150) // ~30 probe intervals
207
+ ok(spawns === 1, 'the grace window absorbs the failed probes instead of starting more')
208
+ await supervisor.stop()
209
+ } finally {
210
+ if (savedHome === undefined) delete process.env.MOBIUS_TUI_HOME; else process.env.MOBIUS_TUI_HOME = savedHome
211
+ await fs.rm(home, { recursive: true, force: true })
212
+ }
213
+ }
214
+
215
+ async function testSpawnBudgetGivesUp() {
216
+ console.log('\n[AIMUX 3g] the retry budget ends in an actionable failure')
217
+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'mobius-tui-aimux-budget-'))
218
+ const savedHome = process.env.MOBIUS_TUI_HOME
219
+ process.env.MOBIUS_TUI_HOME = home
220
+ let spawns = 0
221
+ let lastDetail = ''
222
+ const supervisor = new AimuxSupervisor({
223
+ server: 'https://mobius.test', token: 'jwt-test', identifier: 'gui-noprompt',
224
+ heartbeatIntervalMs: 5,
225
+ spawnGraceMs: 0, // exercise the budget without waiting 90s per attempt
226
+ maxUnproductiveSpawns: 3,
227
+ probeConnection: async () => ({ connected: false, authError: false }),
228
+ spawnProcess: () => { spawns += 1; const c = fakeChild(() => {}); c.pid = process.pid; return c },
229
+ onStatus: s => { if (s.detail) lastDetail = s.detail },
230
+ })
231
+ try {
232
+ await supervisor.start()
233
+ for (let i = 0; i < 300 && spawns < 3; i += 1) await delay(5)
234
+ ok(spawns === 3, 'spawns up to the budget')
235
+ await delay(150)
236
+ ok(spawns === 3, 'and then stops — no endless stream of windows')
237
+ ok(lastDetail.includes('GUI 授权'), 'the failure names the thing the user can change')
165
238
  await supervisor.stop()
166
239
  } finally {
167
240
  if (savedHome === undefined) delete process.env.MOBIUS_TUI_HOME; else process.env.MOBIUS_TUI_HOME = savedHome
@@ -226,8 +299,14 @@ function testPickSilentFlag() {
226
299
  ok(pickSilentFlag(' --silent-v2 Hide console.', 'linux') === null, 'off-Windows → always null')
227
300
  }
228
301
 
229
- function testGuiAuthorization() {
302
+ async function testGuiAuthorization() {
230
303
  console.log('\n[AIMUX 6c] GUI authorization: identifier prefix + --enable-gui args')
304
+ // Hermetic home: setTuiGuiMode writes a file, and running the suite must not
305
+ // change this machine's real computer-use setting.
306
+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'mobius-tui-gui-'))
307
+ const savedHome = process.env.MOBIUS_TUI_HOME
308
+ process.env.MOBIUS_TUI_HOME = home
309
+ try {
231
310
  // Default (flag off): classic tui- prefix, no --enable-gui.
232
311
  ok(tuiAimuxIdentifier('host-a', '/w', 'alice', false).startsWith('tui-host-a-'), 'flag off keeps the tui- prefix')
233
312
  // Authorized: gui- prefix on the same host/hash — the capability shows in the remote name.
@@ -241,10 +320,20 @@ function testGuiAuthorization() {
241
320
  const gui = reverseConnectArgs('https://mobius.test/', 'gui-x', 't', 'linux', null, null, true)
242
321
  ok(!plain.includes('--enable-gui'), 'flag off sends no --enable-gui')
243
322
  ok(gui.includes('--enable-gui'), 'authorized connection passes --enable-gui')
323
+ ok(!gui.includes('--gui-no-elevate'), 'plain authorization still asks for elevation')
324
+ // no-elevate: same --enable-gui, plus the flag that skips aimux's UAC request.
325
+ const quiet = reverseConnectArgs('https://mobius.test/', 'gui-x', 't', 'win32', null, null, true, true)
326
+ ok(quiet.includes('--enable-gui') && quiet.includes('--gui-no-elevate'), 'no-elevate keeps GUI on and adds --gui-no-elevate')
327
+ // --gui-no-elevate alone is meaningless: it only skips *another* flag's
328
+ // elevation request, so it must never be sent without --enable-gui.
329
+ const orphan = reverseConnectArgs('https://mobius.test/', 'tui-x', 't', 'win32', null, null, false, true)
330
+ ok(!orphan.includes('--gui-no-elevate'), 'no-elevate is not sent when GUI is off')
244
331
  // Probe gates on what aimux advertises (0.3.64+), mirroring pickSilentFlag.
245
332
  ok(pickEnableGuiFlag(' --enable-gui Start the GUI helper.') === true, 'probe sees --enable-gui when advertised')
246
333
  ok(pickEnableGuiFlag(' --silent-v2 Hide console.') === false, 'probe stays false without --enable-gui')
247
- // setTuiGuiAuthorized flips the module cache and the default identifier prefix with it.
334
+ ok(pickGuiNoElevateFlag(' --enable-gui Start. --gui-no-elevate Stay unelevated.') === true, 'probe sees --gui-no-elevate when advertised')
335
+ ok(pickGuiNoElevateFlag(' --enable-gui Start the GUI helper.') === false, 'probe stays false without --gui-no-elevate')
336
+ // setTuiGuiMode flips the module cache and the default identifier prefix with it.
248
337
  const before = tuiAimuxIdentifier('host-b', '/w2', 'bob')
249
338
  setTuiGuiAuthorized(true)
250
339
  const after = tuiAimuxIdentifier('host-b', '/w2', 'bob')
@@ -252,10 +341,126 @@ function testGuiAuthorization() {
252
341
  ok(tuiGuiAuthorized() === true, 'flag reads back true after write')
253
342
  setTuiGuiAuthorized(false)
254
343
  ok(tuiAimuxIdentifier('host-b', '/w2', 'bob').startsWith('tui-'), 'clearing the flag restores the tui- prefix')
344
+ } finally {
345
+ setTuiGuiMode('off') // back to the temp file, so the real home is never written
346
+ if (savedHome === undefined) delete process.env.MOBIUS_TUI_HOME
347
+ else process.env.MOBIUS_TUI_HOME = savedHome
348
+ await fs.rm(home, { recursive: true, force: true }).catch(() => {})
349
+ }
350
+ }
351
+
352
+ async function testGuiModes() {
353
+ console.log('\n[AIMUX 6d] GUI modes: off / no-elevate / elevate persist and read back')
354
+ // Hermetic: never touch the developer's real ~/.mobius/tui-gui-authorized.json
355
+ // — running the suite must not change this machine's computer-use setting.
356
+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'mobius-tui-gui-'))
357
+ const savedHome = process.env.MOBIUS_TUI_HOME
358
+ const file = path.join(home, 'tui-gui-authorized.json')
359
+ process.env.MOBIUS_TUI_HOME = home
360
+ try {
361
+ setTuiGuiMode('off')
362
+ ok(tuiGuiMode() === 'off' && tuiGuiAuthorized() === false && tuiGuiNoElevate() === false, 'off: nothing authorized')
363
+ setTuiGuiMode('no-elevate')
364
+ ok(tuiGuiMode() === 'no-elevate', 'no-elevate round-trips')
365
+ ok(tuiGuiAuthorized() === true, 'no-elevate still counts as authorized (gui- identifier prefix)')
366
+ ok(tuiGuiNoElevate() === true, 'no-elevate is the only mode that skips the UAC request')
367
+ ok(tuiAimuxIdentifier('host-c', '/w3', 'carol').startsWith('gui-'), 'no-elevate registers under the gui- prefix')
368
+ setTuiGuiMode('elevate')
369
+ ok(tuiGuiAuthorized() === true && tuiGuiNoElevate() === false, 'elevate authorizes without skipping elevation')
370
+ // The on-disk shape must stay readable by <=0.3.66, which only knows `gui`.
371
+ const written = JSON.parse(readFileSync(file, 'utf8'))
372
+ ok(written.mode === 'elevate' && written.gui === true, 'elevate writes both mode and the legacy gui flag')
373
+ setTuiGuiMode('off')
374
+ ok(JSON.parse(readFileSync(file, 'utf8')).gui === false, 'off writes gui:false too, so a downgrade reads it back as off')
375
+ // A file written before modes existed must not lose the authorization.
376
+ writeFileSync(file, JSON.stringify({ gui: true }))
377
+ ok(readGuiModeForTest() === 'elevate', 'a legacy {gui:true} file reads back as elevate')
378
+ writeFileSync(file, JSON.stringify({ gui: false }))
379
+ ok(readGuiModeForTest() === 'off', 'a legacy {gui:false} file reads back as off')
380
+ writeFileSync(file, 'not json at all')
381
+ ok(readGuiModeForTest() === 'off', 'an unreadable file falls back to off rather than throwing')
382
+ } finally {
383
+ // Re-point the cache at the temp file before it disappears, so the real
384
+ // home is never written on the way out.
385
+ setTuiGuiMode('off')
386
+ if (savedHome === undefined) delete process.env.MOBIUS_TUI_HOME
387
+ else process.env.MOBIUS_TUI_HOME = savedHome
388
+ await fs.rm(home, { recursive: true, force: true }).catch(() => {})
389
+ }
390
+ }
391
+
392
+ function testElevationDetection() {
393
+ console.log('\n[AIMUX 6f] administrator-token detection (whoami /groups)')
394
+ // Elevated: the mandatory label is High (UAC) or System (service).
395
+ const high = `Group Name Type SID Attributes
396
+ =================================
397
+ BUILTIN\\Administrators Alias S-1-5-32-544 Enabled group
398
+ Mandatory Label\\High Mandatory Level Label S-1-16-12288`
399
+ ok(parseElevatedGroups(high) === true, 'a High mandatory label reads as elevated')
400
+ ok(parseElevatedGroups('Mandatory Label\\System Mandatory Level Label S-1-16-16384') === true, 'a System mandatory label reads as elevated')
401
+ // Not elevated: Medium, and the Administrators group alone must not count —
402
+ // a normal Windows account is *in* that group with a filtered token, which is
403
+ // exactly the case that must not be mistaken for an elevated shell.
404
+ const medium = `Group Name Type SID Attributes
405
+ BUILTIN\\Administrators Alias S-1-5-32-544 Mandatory group, Enabled by default, Enabled group
406
+ Mandatory Label\\Medium Mandatory Level Label S-1-16-8192`
407
+ ok(parseElevatedGroups(medium) === false, 'a filtered administrator token (Medium) is not elevated')
408
+ ok(parseElevatedGroups('BUILTIN\\Administrators Alias S-1-5-32-544') === false, 'the Administrators group alone is not elevation')
409
+ // Localized output keeps the SID, so the match must not depend on the label text.
410
+ ok(parseElevatedGroups('强制标签\\高强制级别 Label S-1-16-12288') === true, 'a localized label is still detected by SID')
411
+ ok(parseElevatedGroups('') === false, 'empty output falls back to not-elevated')
412
+ }
413
+
414
+ function testGuiModeAvailability() {
415
+ console.log('\n[AIMUX 6g] GUI modes available here, and the flags they imply')
416
+ // Availability follows from the exclusive rule: a child inherits the parent's
417
+ // token, so exactly one authorized mode is offerable on Windows.
418
+ const admin = guiModeAvailability(true, 'win32')
419
+ const plain = guiModeAvailability(false, 'win32')
420
+ ok(admin.off.available && admin.elevate.available, 'an elevated TUI can offer command-line and high privilege')
421
+ ok(!admin['no-elevate'].available, 'an elevated TUI cannot offer low privilege — it cannot drop the inherited token')
422
+ ok(admin['no-elevate'].reason?.includes('非管理员模式') === true, 'and says to reopen non-elevated')
423
+ ok(plain.off.available && plain['no-elevate'].available, 'an unelevated TUI can offer command-line and low privilege')
424
+ ok(!plain.elevate.available, 'an unelevated TUI can never offer high privilege')
425
+ ok(plain.elevate.reason?.includes('管理员模式') === true, 'and says to reopen as administrator')
426
+ ok(guiModeAvailability(false, 'darwin').elevate.available, 'off Windows there is no elevation to gate on')
427
+ ok(hasGuiSupport('win32') && hasGuiSupport('darwin') && !hasGuiSupport('linux'), 'the GUI choice exists only where a helper does')
428
+
429
+ // The picker rows keep the unavailable mode visible, with the reason in the label.
430
+ const rows = guiModeOptions(false, 'win32')
431
+ ok(rows.length === 3, 'three rows are offered on Windows')
432
+ ok(rows[0].label === '使用纯命令行操作(推荐)', 'row 1 keeps the agreed wording')
433
+ ok(rows[1].label === '授权使用图形界面(低权限)', 'an available mode carries no suffix')
434
+ ok(rows[2].label === '授权使用图形界面(高权限 - 不可用,请用管理员模式打开 Mobius TUI)', 'row 3 says exactly why it is out of reach')
435
+ ok(rows[2].disabled === true, 'and is marked unselectable')
436
+ ok(guiModeOptions(true, 'win32')[1].label === '授权使用图形界面(低权限 - 不可用,请用非管理员模式打开 Mobius TUI)', 'the mirrored case reads the same way')
437
+ ok(guiModeOptions(true, 'darwin').length === 2, 'macOS is offered no middle row')
438
+
439
+ // The rule that actually reaches the daemon: an unelevated TUI may only ever
440
+ // send the pair that asks Windows for nothing.
441
+ const canBoth = { enable: true, noElevate: true }
442
+ ok(pickGuiArgs('off', false, canBoth, 'win32').enableGui === false, 'command-line mode sends no GUI flags')
443
+ ok(pickGuiArgs('elevate', true, canBoth, 'win32').guiNoElevate === false, 'elevated + high privilege sends the bare flag')
444
+ ok(pickGuiArgs('no-elevate', false, canBoth, 'win32').guiNoElevate === true, 'unelevated + low privilege sends --gui-no-elevate')
445
+ const stored = pickGuiArgs('elevate', false, canBoth, 'win32')
446
+ ok(stored.enableGui === true && stored.guiNoElevate === true, 'a stored high-privilege choice is downgraded when this TUI is not elevated')
447
+ const noSupport = pickGuiArgs('elevate', false, { enable: true, noElevate: false }, 'win32')
448
+ ok(noSupport.enableGui === false, 'without --gui-no-elevate the unelevated TUI sends nothing rather than risk a blocking prompt')
449
+ ok(pickGuiArgs('elevate', true, { enable: true, noElevate: false }, 'win32').enableGui === true, 'the elevated TUI is unaffected by that gap')
450
+ ok(pickGuiArgs('elevate', false, { enable: false, noElevate: true }, 'win32').enableGui === false, 'an aimux without --enable-gui gets no GUI flags at all')
451
+ ok(pickGuiArgs('elevate', false, canBoth, 'darwin').guiNoElevate === false, 'macOS has no elevation request, so it stays on the bare flag')
452
+
453
+ // The picker's "current" marker must point at the mode in force, which
454
+ // availability can have moved off the stored one.
455
+ ok(effectiveGuiMode('elevate', true, 'win32') === 'elevate', 'an elevated TUI uses the stored high privilege')
456
+ ok(effectiveGuiMode('elevate', false, 'win32') === 'no-elevate', 'the same choice from an ordinary TUI reports as low privilege')
457
+ ok(effectiveGuiMode('no-elevate', true, 'win32') === 'elevate', 'and the mirror case reports high privilege')
458
+ ok(effectiveGuiMode('off', false, 'win32') === 'off', 'command-line mode is never moved')
459
+ ok(effectiveGuiMode('elevate', false, 'darwin') === 'elevate', 'macOS is unaffected')
255
460
  }
256
461
 
257
462
  function testVersionAtLeast() {
258
- console.log('\n[AIMUX 6c] aimux pin is a floor, not an exact match')
463
+ console.log('\n[AIMUX 6e] aimux pin is a floor, not an exact match')
259
464
  // /upgrade 装的是 PyPI 最新版,通常比 pin 新;不能被 pin 校验判成"没装好"又拽回去。
260
465
  ok(versionAtLeast('0.3.62', '0.3.61'), 'newer aimux satisfies the pinned floor')
261
466
  ok(versionAtLeast('0.3.61', '0.3.61'), 'exactly the pinned version satisfies the floor')
@@ -333,12 +538,18 @@ async function main() {
333
538
  await testAdoptOrSpawn()
334
539
  await testJwtRefreshViaProbe()
335
540
  await testLastTuiStopsDaemon()
336
- await testUnresponsiveLiveDaemonRestarts()
541
+ testPidAliveErrorSemantics()
542
+ await testLiveDaemonIsNotRespawned()
543
+ await testSlowStartDoesNotStackSpawns()
544
+ await testSpawnBudgetGivesUp()
337
545
  await testBundleArchAndUrl()
338
546
  await testSpawnLauncher()
339
547
  testReverseConnectArgs()
340
548
  testPickSilentFlag()
341
- testGuiAuthorization()
549
+ await testGuiAuthorization()
550
+ await testGuiModes()
551
+ testElevationDetection()
552
+ testGuiModeAvailability()
342
553
  testVersionAtLeast()
343
554
  testAimuxIdentifierScopesWorkspace()
344
555
  testBundleHealthCheck()