@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.
@@ -15,14 +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 { effectiveGuiMode, guiModeOptions, hasGuiSupport, restartAimuxConnectionForGuiChange, setTuiGuiMode, tuiGuiMode, type GuiMode } from '../aimux.js'
19
+ import { windowsElevated } from '../lib/windows-admin.js'
18
20
  import {
19
21
  bindCwdToProject, cwd, getCwdPreference, loadDir2Project, loadProjectsCache,
20
22
  saveProjectsCache, setCwdIssue, updateIssuePreference, type IssuePreference,
21
23
  } from '../config.js'
22
24
  import type { Issue, Memory, Project, SessionModelOption, Skill } from '../types.js'
23
25
 
24
- type PrefStep = 'issue' | 'model' | 'language' | 'skills' | 'memories'
25
- const STEP_ORDER: PrefStep[] = ['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
+ }
26
34
 
27
35
  export interface ReadyState {
28
36
  project: Project
@@ -30,11 +38,18 @@ export interface ReadyState {
30
38
  prefs: IssuePreference
31
39
  }
32
40
 
33
- export function PrepScreen({ client, onReady, onQuit }: {
41
+ export function PrepScreen({ client, onReady, onQuit, platform = process.platform, elevated = windowsElevated() }: {
34
42
  client: MobiusClient
35
43
  onReady: (st: ReadyState) => void
36
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
37
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)
38
53
  const [phase, setPhase] = useState<'loading' | 'project' | 'pref' | 'done'>('loading')
39
54
  const [projects, setProjects] = useState<Project[]>([])
40
55
  const [project, setProject] = useState<Project | null>(null)
@@ -105,7 +120,7 @@ export function PrepScreen({ client, onReady, onQuit }: {
105
120
 
106
121
  function computeStep(p: IssuePreference): PrefStep | null {
107
122
  const done = new Set(p.done ?? [])
108
- for (const s of STEP_ORDER) if (!done.has(s)) return s
123
+ for (const s of stepOrder) if (!done.has(s)) return s
109
124
  return null
110
125
  }
111
126
 
@@ -169,6 +184,19 @@ export function PrepScreen({ client, onReady, onQuit }: {
169
184
  onReady({ project, issue: iss, prefs: p })
170
185
  }
171
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
+
172
200
  // ── lazy-load lists for the active step ──────────────────────────────────
173
201
  useEffect(() => {
174
202
  if (phase !== 'pref' || !step) return
@@ -213,6 +241,18 @@ export function PrepScreen({ client, onReady, onQuit }: {
213
241
  items={[{ label: '中文', value: 'zh' }, { label: 'English', value: 'en' }]}
214
242
  onSelect={v => completeStep('language', { language: v as 'zh' | 'en' })} />
215
243
  : null}
244
+ {step === 'gui'
245
+ ? <Select
246
+ title="是否授权操作图形界面 (GUI/computer use)"
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')} />
255
+ : null}
216
256
  {step === 'skills'
217
257
  ? <MultiPicker title={`选择启用的 Skill(默认全部启用,空格取消)`} items={toItems(skills)}
218
258
  excluded={prefs.excluded_skill_ids}
@@ -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"
@@ -17,7 +17,7 @@ import { useCallback, useEffect, useRef, useState } from 'react'
17
17
  import { MobiusClient, ApiError } from '../api.js'
18
18
  import { SseConnection } from '../sse.js'
19
19
  import { updateIssuePreference } from '../config.js'
20
- import { tuiAimuxIdentifier, probeAimuxBridgeConnection } from '../aimux.js'
20
+ import { tuiGuiAuthorized, tuiAimuxIdentifier, probeAimuxBridgeConnection } from '../aimux.js'
21
21
  import { viewsForEntry } from '../lib/entry-view.js'
22
22
  import type { AnyEntry, HistoryPendingOpener } from '../types.js'
23
23
  import type { ReadyState } from '../components/PrepScreen.js'
@@ -493,6 +493,7 @@ export function useChat({ client, ready, resumeSessionId }: ChatApi): ChatContro
493
493
  local_path: process.cwd(),
494
494
  is_tui: true,
495
495
  add_remote_aimux_mcp: true,
496
+ ...(tuiGuiAuthorized() ? { gui_authorized: true } : {}),
496
497
  },
497
498
  })
498
499
  const sid = s.session_id
@@ -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 } 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,14 +146,28 @@ 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-'))
151
163
  const savedHome = process.env.MOBIUS_TUI_HOME
152
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 }))
153
168
  let spawns = 0
154
169
  const supervisor = new AimuxSupervisor({
155
- server: 'https://mobius.test', token: 'jwt-test', identifier: 'tui-stale',
170
+ server: 'https://mobius.test', token: 'jwt-test', identifier: 'tui-live',
156
171
  heartbeatIntervalMs: 5,
157
172
  probeConnection: async () => ({ connected: false, authError: false }),
158
173
  spawnProcess: () => { spawns += 1; const c = fakeChild(() => {}); c.pid = process.pid; return c },
@@ -160,8 +175,66 @@ async function testUnresponsiveLiveDaemonRestarts() {
160
175
  })
161
176
  try {
162
177
  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')
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-'))
193
+ const savedHome = process.env.MOBIUS_TUI_HOME
194
+ process.env.MOBIUS_TUI_HOME = home
195
+ let spawns = 0
196
+ const supervisor = new AimuxSupervisor({
197
+ server: 'https://mobius.test', token: 'jwt-test', identifier: 'gui-slow',
198
+ heartbeatIntervalMs: 5,
199
+ spawnGraceMs: 30_000, // the real value is 90s; only the ordering matters here
200
+ probeConnection: async () => ({ connected: false, authError: false }),
201
+ spawnProcess: () => { spawns += 1; const c = fakeChild(() => {}); c.pid = process.pid; return c },
202
+ onStatus: () => {},
203
+ })
204
+ try {
205
+ await supervisor.start()
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,168 @@ function testPickSilentFlag() {
226
299
  ok(pickSilentFlag(' --silent-v2 Hide console.', 'linux') === null, 'off-Windows → always null')
227
300
  }
228
301
 
302
+ async function testGuiAuthorization() {
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 {
310
+ // Default (flag off): classic tui- prefix, no --enable-gui.
311
+ ok(tuiAimuxIdentifier('host-a', '/w', 'alice', false).startsWith('tui-host-a-'), 'flag off keeps the tui- prefix')
312
+ // Authorized: gui- prefix on the same host/hash — the capability shows in the remote name.
313
+ const tuiId = tuiAimuxIdentifier('host-a', '/w', 'alice', false)
314
+ const guiId = tuiAimuxIdentifier('host-a', '/w', 'alice', true)
315
+ ok(guiId.startsWith('gui-host-a-'), 'authorized client registers as gui-<host>-<hash>')
316
+ ok(guiId.endsWith(tuiId.split('-').slice(-1)[0]), 'gui- identifier keeps the same workspace hash')
317
+ ok(tuiAimuxIdentifier('host-a', '/w', 'alice', false) !== guiId, 'prefix flip changes the identifier')
318
+ // reverse connect args only carry --enable-gui when asked.
319
+ const plain = reverseConnectArgs('https://mobius.test/', 'tui-x', 't', 'linux', null, null, false)
320
+ const gui = reverseConnectArgs('https://mobius.test/', 'gui-x', 't', 'linux', null, null, true)
321
+ ok(!plain.includes('--enable-gui'), 'flag off sends no --enable-gui')
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')
331
+ // Probe gates on what aimux advertises (0.3.64+), mirroring pickSilentFlag.
332
+ ok(pickEnableGuiFlag(' --enable-gui Start the GUI helper.') === true, 'probe sees --enable-gui when advertised')
333
+ ok(pickEnableGuiFlag(' --silent-v2 Hide console.') === false, 'probe stays false without --enable-gui')
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.
337
+ const before = tuiAimuxIdentifier('host-b', '/w2', 'bob')
338
+ setTuiGuiAuthorized(true)
339
+ const after = tuiAimuxIdentifier('host-b', '/w2', 'bob')
340
+ ok(before.startsWith('tui-') && after.startsWith('gui-'), 'writing the flag flips the default identifier prefix')
341
+ ok(tuiGuiAuthorized() === true, 'flag reads back true after write')
342
+ setTuiGuiAuthorized(false)
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')
460
+ }
461
+
229
462
  function testVersionAtLeast() {
230
- 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')
231
464
  // /upgrade 装的是 PyPI 最新版,通常比 pin 新;不能被 pin 校验判成"没装好"又拽回去。
232
465
  ok(versionAtLeast('0.3.62', '0.3.61'), 'newer aimux satisfies the pinned floor')
233
466
  ok(versionAtLeast('0.3.61', '0.3.61'), 'exactly the pinned version satisfies the floor')
@@ -305,11 +538,18 @@ async function main() {
305
538
  await testAdoptOrSpawn()
306
539
  await testJwtRefreshViaProbe()
307
540
  await testLastTuiStopsDaemon()
308
- await testUnresponsiveLiveDaemonRestarts()
541
+ testPidAliveErrorSemantics()
542
+ await testLiveDaemonIsNotRespawned()
543
+ await testSlowStartDoesNotStackSpawns()
544
+ await testSpawnBudgetGivesUp()
309
545
  await testBundleArchAndUrl()
310
546
  await testSpawnLauncher()
311
547
  testReverseConnectArgs()
312
548
  testPickSilentFlag()
549
+ await testGuiAuthorization()
550
+ await testGuiModes()
551
+ testElevationDetection()
552
+ testGuiModeAvailability()
313
553
  testVersionAtLeast()
314
554
  testAimuxIdentifierScopesWorkspace()
315
555
  testBundleHealthCheck()