@mobius-os/mobius 0.3.62 → 0.3.66

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.62",
3
+ "version": "0.3.66",
4
4
  "type": "module",
5
5
  "description": "Mobius terminal client. Reuses Mobius frontend TypeScript types and jsonl entry shapes.",
6
6
  "bin": {
@@ -12,6 +12,7 @@
12
12
  "start": "tsx src/main.tsx",
13
13
  "typecheck": "tsc --noEmit",
14
14
  "test:integration": "tsx tests/integration.test.ts",
15
+ "test:size": "tsx tests/terminal-size.test.ts",
15
16
  "test:ui": "tsx tests/ui.test.tsx",
16
17
  "test:flow": "tsx tests/flow.test.tsx",
17
18
  "test:resume": "tsx tests/resume.test.tsx",
@@ -21,7 +22,7 @@
21
22
  "test:scroll": "tsx tests/scroll.test.tsx",
22
23
  "test:viewport": "tsx tests/viewport.test.ts",
23
24
  "test:selection": "FORCE_COLOR=1 tsx tests/selection.test.tsx",
24
- "test": "npm run typecheck && npm run test:ui && npm run test:integration"
25
+ "test": "npm run typecheck && npm run test:size && npm run test:ui && npm run test:integration"
25
26
  },
26
27
  "dependencies": {
27
28
  "chalk": "^5.3.0",
@@ -13,8 +13,8 @@ set -euo pipefail
13
13
 
14
14
  TAG=20241002
15
15
  PYVER=3.12.7
16
- BUNDLE_VER=12
17
- AIMUX_VERSION=0.3.62
16
+ BUNDLE_VER=14
17
+ AIMUX_VERSION=0.3.66
18
18
  PYPI_INDEX=https://pypi.org/simple
19
19
  WORK="${WORK:-$HOME/python-bundles}"
20
20
  DIST="${DIST:-$WORK/dist}"
package/src/aimux.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  */
8
8
  import { spawn, spawnSync, type ChildProcess, type StdioOptions } from 'node:child_process'
9
9
  import { createHash } from 'node:crypto'
10
- import { promises as fs, existsSync, createWriteStream, mkdirSync, openSync, closeSync } from 'node:fs'
10
+ import { promises as fs, existsSync, createWriteStream, mkdirSync, openSync, closeSync, readFileSync, writeFileSync } from 'node:fs'
11
11
  import os from 'node:os'
12
12
  import path from 'node:path'
13
13
  import { Readable } from 'node:stream'
@@ -32,7 +32,7 @@ export type AimuxLauncher =
32
32
  | { kind: 'exe'; path: string }
33
33
  | { kind: 'module'; python: string }
34
34
 
35
- const AIMUX_TARGET_VERSION = '0.3.62'
35
+ const AIMUX_TARGET_VERSION = '0.3.66'
36
36
  const AIMUX_PACKAGE = `aimux==${AIMUX_TARGET_VERSION}`
37
37
  const WIN = process.platform === 'win32'
38
38
  const venvDir = () => path.join(mobiusHome(), 'aimux-venv')
@@ -93,7 +93,7 @@ async function pythonForAimux(onProgress?: (p: InstallProgress) => void): Promis
93
93
  // 系统 python(如被精简掉 ensurepip 的容器镜像)。aimux 全部依赖为纯 Python,
94
94
  // 故三平台可共用同一套打包产物,分别按 arch 发布到 CDN。
95
95
  /** Plan B 内置运行时包版本;每次发版跟 aimux pin 一起 +1,测试也从这里取。 */
96
- export const BUNDLE_VER = '12'
96
+ export const BUNDLE_VER = '14'
97
97
  const BUNDLE_AIMUX_VERSION = AIMUX_TARGET_VERSION
98
98
  /** Version expected from the installed or bundled AIMUX runtime. */
99
99
  export const AIMUX_VERSION = BUNDLE_AIMUX_VERSION
@@ -365,14 +365,41 @@ export function aimuxWorkspaceHash(username = currentUsername(), cwd = process.c
365
365
  return createHash('sha256').update(`${username}:${path.resolve(cwd)}`).digest('hex').slice(0, 10)
366
366
  }
367
367
 
368
- export function tuiAimuxIdentifier(hostname = os.hostname(), cwd = process.cwd(), username = currentUsername()): string {
368
+ // ── 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
374
+
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 }
381
+ }
382
+ return guiAuthorizedCache
383
+ }
384
+
385
+ export function setTuiGuiAuthorized(value: boolean): void {
386
+ guiAuthorizedCache = value
387
+ try {
388
+ mkdirSync(mobiusHome(), { recursive: true })
389
+ writeFileSync(path.join(mobiusHome(), GUI_AUTH_FILE), JSON.stringify({ gui: value }), { mode: 0o600 })
390
+ } catch { /* unwritable home: the in-memory cache still holds this session */ }
391
+ }
392
+
393
+ export function tuiAimuxIdentifier(hostname = os.hostname(), cwd = process.cwd(), username = currentUsername(), guiEnabled = tuiGuiAuthorized()): string {
369
394
  const host = hostname.toLowerCase().replace(/[^a-z0-9_.-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 32)
370
395
  // One machine may run several Mobius TUIs for different projects (and for
371
396
  // different users). A hostname-only identifier makes every reverse client
372
397
  // register with the same name and --replace continuously evicts its siblings.
373
398
  // The (username, cwd) hash is stable across restarts/resume but unique per
374
399
  // user and per workspace, so separate projects/users never collide.
375
- return `tui-${host || 'pc'}-${aimuxWorkspaceHash(username, cwd)}`
400
+ // GUI-authorized machines register under a gui- prefix so the capability is
401
+ // visible in the remote name itself (web device picker, remote ls).
402
+ return `${guiEnabled ? 'gui' : 'tui'}-${host || 'pc'}-${aimuxWorkspaceHash(username, cwd)}`
376
403
  }
377
404
 
378
405
  // ── shared daemon runtime JSON (one reverse connect per user+workspace) ──
@@ -437,6 +464,7 @@ export function reverseConnectArgs(
437
464
  platform: NodeJS.Platform = process.platform,
438
465
  silentFlag: string | null = null,
439
466
  runtimeFile: string | null = null,
467
+ enableGui = false,
440
468
  ): string[] {
441
469
  return [
442
470
  'reverse', 'connect', `${server.replace(/\/$/, '')}/aimux_bridge`,
@@ -445,6 +473,7 @@ export function reverseConnectArgs(
445
473
  '--replace',
446
474
  ...(runtimeFile ? ['--runtime', runtimeFile, '--watchdog', runtimeFile] : []),
447
475
  ...(platform === 'win32' && silentFlag ? [silentFlag] : []),
476
+ ...(enableGui ? ['--enable-gui'] : []),
448
477
  ]
449
478
  }
450
479
 
@@ -479,6 +508,15 @@ export function pickSilentFlag(helpText: string, platform: NodeJS.Platform = pro
479
508
  return null
480
509
  }
481
510
 
511
+ /**
512
+ * Does this aimux build advertise --enable-gui (0.3.64+)? Older installs
513
+ * reject unknown options outright, so the flag is only sent when the help
514
+ * text confirms it — same defensive pattern as pickSilentFlag.
515
+ */
516
+ export function pickEnableGuiFlag(helpText: string): boolean {
517
+ return /--enable-gui\b/.test(helpText)
518
+ }
519
+
482
520
  /** Result of a bridge heartbeat: is the stream up, and did the JWT just get rejected? */
483
521
  export interface AimuxBridgeProbe { connected: boolean; authError: boolean }
484
522
 
@@ -577,7 +615,7 @@ export class AimuxSupervisor {
577
615
  if (pid !== null && pidAlive(pid)) { await touchWatchdog(this.hash); return }
578
616
  const { server, token, identifier, onStatus } = this.opts
579
617
  onStatus({ state: 'starting', phase: 'connecting', detail: '正在启动 AIMUX 守护进程…', identifier, attempt: this.reconnectAttempt })
580
- const child = this.opts.spawnProcess?.(token) ?? spawnDetachedDaemon({ kind: 'exe', path: aimuxExe() }, reverseConnectArgs(server, identifier, token, process.platform, null, runtimePath(this.hash)))
618
+ const child = this.opts.spawnProcess?.(token) ?? spawnDetachedDaemon({ kind: 'exe', path: aimuxExe() }, reverseConnectArgs(server, identifier, token, process.platform, null, runtimePath(this.hash), tuiGuiAuthorized()))
581
619
  child.on('error', (e: Error) => { appendAimuxLog(installLogQueue, `\n[aimux spawn error] ${e.stack || e.message}\n`) })
582
620
  child.unref?.()
583
621
  this.reconnectAttempt = 0
@@ -702,6 +740,9 @@ interface StartOptions {
702
740
  // not probed yet this process). Cached so reconnects reuse it without re-running
703
741
  // `aimux reverse connect --help`. See reverseConnectArgs for why this is probed.
704
742
  let cachedSilentFlag: string | null | undefined = undefined
743
+ // Same caching for --enable-gui support (aimux 0.3.64+): sending it to an older
744
+ // build crashes the supervisor with "No such option".
745
+ let cachedEnableGui: boolean | undefined = undefined
705
746
 
706
747
  export async function startAimuxConnection(opts: StartOptions): Promise<void> {
707
748
  const onStatus = opts.onStatus ?? (() => {})
@@ -727,15 +768,23 @@ export async function startAimuxConnection(opts: StartOptions): Promise<void> {
727
768
  // Windows only: ask the installed aimux which console-hiding flag it accepts
728
769
  // before spawning, so a version mismatch (older PyPI/bundle aimux without
729
770
  // --slient-v2) can't crash-loop the supervisor with "No such option".
730
- if (WIN && cachedSilentFlag === undefined) {
771
+ const needGuiFlag = tuiGuiAuthorized()
772
+ if (cachedSilentFlag === undefined || (needGuiFlag && cachedEnableGui === undefined)) {
731
773
  const help = await probeReverseConnectHelp(launcher)
732
- cachedSilentFlag = pickSilentFlag(help)
733
- logInstall(`reverse-connect silent flag probe → ${cachedSilentFlag ?? '(none supported; sending no flag)'}\n`)
774
+ if (WIN && cachedSilentFlag === undefined) {
775
+ cachedSilentFlag = pickSilentFlag(help)
776
+ logInstall(`reverse-connect silent flag probe → ${cachedSilentFlag ?? '(none supported; sending no flag)'}\n`)
777
+ }
778
+ if (needGuiFlag && cachedEnableGui === undefined) {
779
+ cachedEnableGui = pickEnableGuiFlag(help)
780
+ logInstall(`reverse-connect --enable-gui probe → ${cachedEnableGui ? 'supported' : 'NOT supported (skipping; upgrade aimux to 0.3.64+)'}\n`)
781
+ }
734
782
  }
735
783
  const silentFlag = cachedSilentFlag
784
+ const enableGui = needGuiFlag && cachedEnableGui === true
736
785
  supervisor = new AimuxSupervisor({
737
786
  server: opts.server, token: opts.token, identifier, onStatus, refreshToken: opts.refreshToken,
738
- spawnProcess: token => spawnDetachedDaemon(launcher, reverseConnectArgs(opts.server, identifier, token, process.platform, silentFlag, runtimePath(aimuxWorkspaceHash()))),
787
+ spawnProcess: token => spawnDetachedDaemon(launcher, reverseConnectArgs(opts.server, identifier, token, process.platform, silentFlag, runtimePath(aimuxWorkspaceHash()), enableGui)),
739
788
  })
740
789
  await supervisor.start()
741
790
  })().finally(() => { installing = null })
@@ -747,6 +796,20 @@ export async function stopAimuxConnection(): Promise<void> {
747
796
  await current?.stop()
748
797
  }
749
798
 
799
+ /**
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.
805
+ */
806
+ export async function restartAimuxConnectionForGuiChange(): Promise<void> {
807
+ const opts = lastStartOpts
808
+ await stopAimuxConnection()
809
+ await stopDaemonFromRuntime()
810
+ if (opts) await startAimuxConnection(opts)
811
+ }
812
+
750
813
  /** SIGTERM 掉本工作区 runtime JSON 里记录的守护进程,并删掉该文件。
751
814
  * 不这么做的话,新 supervisor 会按 pid 复用到刚升级前的旧 daemon。 */
752
815
  async function stopDaemonFromRuntime(): Promise<void> {
@@ -27,7 +27,7 @@ import {
27
27
  bindCwdToProject, cwd, getCwdPreference, loadDir2Project, loadProjectsCache,
28
28
  saveProjectsCache, setCwdIssue, updateIssuePreference, type IssuePreference,
29
29
  } from '../config.js'
30
- import { tuiAimuxIdentifier } from '../aimux.js'
30
+ import { tuiAimuxIdentifier, tuiGuiAuthorized} from '../aimux.js'
31
31
  import type { Issue, Project, SessionModelOption } from '../types.js'
32
32
 
33
33
  export interface ConfigResult {
@@ -82,6 +82,7 @@ export function ConfigFlow({ client, issue, onDone }: {
82
82
  local_path: process.cwd(),
83
83
  is_tui: true,
84
84
  add_remote_aimux_mcp: true,
85
+ ...(tuiGuiAuthorized() ? { gui_authorized: true } : {}),
85
86
  },
86
87
  })
87
88
  if (doneRef.current) return
@@ -281,6 +282,7 @@ export function ReconfigFlow({ client, onDone, onCancel }: {
281
282
  local_path: process.cwd(),
282
283
  is_tui: true,
283
284
  add_remote_aimux_mcp: true,
285
+ ...(tuiGuiAuthorized() ? { gui_authorized: true } : {}),
284
286
  },
285
287
  })
286
288
  if (doneRef.current) return
@@ -15,14 +15,20 @@ 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
19
  import {
19
20
  bindCwdToProject, cwd, getCwdPreference, loadDir2Project, loadProjectsCache,
20
21
  saveProjectsCache, setCwdIssue, updateIssuePreference, type IssuePreference,
21
22
  } from '../config.js'
22
23
  import type { Issue, Memory, Project, SessionModelOption, Skill } from '../types.js'
23
24
 
24
- type PrefStep = 'issue' | 'model' | 'language' | 'skills' | 'memories'
25
- const STEP_ORDER: PrefStep[] = ['model', 'language', 'skills', 'memories']
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
32
 
27
33
  export interface ReadyState {
28
34
  project: Project
@@ -48,6 +54,10 @@ export function PrepScreen({ client, onReady, onQuit }: {
48
54
  const [memories, setMemories] = useState<Memory[]>([])
49
55
  const [defaultModel, setDefaultModel] = useState<string | null>(null)
50
56
  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)
51
61
  const thisCwd = cwd()
52
62
 
53
63
  // ── bootstrap ────────────────────────────────────────────────────────────
@@ -213,6 +223,54 @@ export function PrepScreen({ client, onReady, onQuit }: {
213
223
  items={[{ label: '中文', value: 'zh' }, { label: 'English', value: 'en' }]}
214
224
  onSelect={v => completeStep('language', { language: v as 'zh' | 'en' })} />
215
225
  : null}
226
+ {step === 'gui' && !guiConfirm
227
+ ? <Select
228
+ 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>
273
+ : null}
216
274
  {step === 'skills'
217
275
  ? <MultiPicker title={`选择启用的 Skill(默认全部启用,空格取消)`} items={toItems(skills)}
218
276
  excluded={prefs.excluded_skill_ids}
@@ -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,183 @@
1
+ /**
2
+ * Terminal size probe — the Windows width workaround.
3
+ *
4
+ * Two things make `stdout.columns` disagree with the visible window:
5
+ *
6
+ * 1. A missed resize. Windows has no SIGWINCH, so the size only arrives as a
7
+ * console event. The terminal can push that event while Node is still
8
+ * booting (`tsx` takes a beat), i.e. before Ink has attached its listener,
9
+ * and the frame is then laid out with whatever width the process started
10
+ * with — until the user resizes the window by hand and a fresh event lands.
11
+ * 2. A console that reports the wrong size at all. Classic cmd.exe has a screen
12
+ * buffer (120 columns by default) that can be wider than its window, and
13
+ * under ConPTY (Windows Terminal, VS Code, the Win11 default host) the child
14
+ * talks to a pseudo console whose size is only refreshed on a real resize.
15
+ *
16
+ * Either way Ink lays the frame out a few columns too wide (`ink.js`:
17
+ * `stdout.columns || 80`) and the terminal hard-wraps the overflow — text
18
+ * "falls" onto the next row and borders stop lining up.
19
+ *
20
+ * So the probe does both cheap things: re-reads Node's own value (cures 1) and
21
+ * asks the terminal itself with `CSI 18 t` ("report text area size in
22
+ * characters", cures 2). A terminal that never answers is left as it was.
23
+ */
24
+ import { Transform, type TransformCallback } from 'node:stream'
25
+
26
+ /** Ask the terminal to report its text-area size (CSI 18 t). */
27
+ const SIZE_QUERY = '\x1b[18t'
28
+ /** The answer: CSI 8 ; <n> ; <n> t. Which number is height and which is width varies — see interpretSizeReport. */
29
+ const SIZE_REPORT = /\x1b\[8;(\d+);(\d+)t/g
30
+ /**
31
+ * A chunk tail that might still grow into a size report (`\x1b`, `\x1b[`, `\x1b[8;24;80…`).
32
+ * Reports can straddle two reads, so the tail is held for one beat rather than
33
+ * forwarded — otherwise Ink would receive report bytes as junk keystrokes.
34
+ */
35
+ const PARTIAL_REPORT = /^\x1b(\[(\d*;)*\d*)?$/
36
+ const PARTIAL_HOLD_MS = 15
37
+ /** Ignore nonsense sizes rather than handing the layout an unusable width. */
38
+ const MIN_COLUMNS = 20, MAX_COLUMNS = 1000, MIN_ROWS = 5, MAX_ROWS = 500
39
+ const DEFAULT_POLL_MS = 1_000
40
+
41
+ export interface TerminalSize { columns: number; rows: number }
42
+
43
+ /**
44
+ * Pull every complete size report out of `text`, leaving `rest` for the app.
45
+ * The two numbers are returned in the order the terminal sent them; deciding
46
+ * which is which is `interpretSizeReport`'s job.
47
+ */
48
+ export function extractSizeReports(text: string): { reports: Array<[number, number]>; rest: string } {
49
+ const reports: Array<[number, number]> = []
50
+ let rest = ''
51
+ let lastIndex = 0
52
+ SIZE_REPORT.lastIndex = 0
53
+ let match = SIZE_REPORT.exec(text)
54
+ while (match) {
55
+ rest += text.slice(lastIndex, match.index)
56
+ reports.push([Number(match[1]), Number(match[2])])
57
+ lastIndex = match.index + match[0].length
58
+ match = SIZE_REPORT.exec(text)
59
+ }
60
+ rest += text.slice(lastIndex)
61
+ return { reports, rest }
62
+ }
63
+
64
+ /**
65
+ * xterm's ctlseqs says the report is `CSI 8 ; height ; width t`, and Windows
66
+ * Terminal follows that — but not every terminal does: tmux answers width first
67
+ * (measured). Both readings are plausible integers, so take the one closer to
68
+ * what we already believe: this probe only ever corrects a *stale* size, and
69
+ * swapping the axes moves both of them by far more than a stale value does.
70
+ * Ties go to the documented order.
71
+ */
72
+ export function interpretSizeReport(first: number, second: number, current: TerminalSize): TerminalSize {
73
+ const documented: TerminalSize = { rows: first, columns: second }
74
+ const swapped: TerminalSize = { rows: second, columns: first }
75
+ const drift = (size: TerminalSize) => Math.abs(size.columns - current.columns) + Math.abs(size.rows - current.rows)
76
+ return drift(documented) <= drift(swapped) ? documented : swapped
77
+ }
78
+
79
+ function usable({ columns, rows }: TerminalSize): boolean {
80
+ return columns >= MIN_COLUMNS && columns <= MAX_COLUMNS && rows >= MIN_ROWS && rows <= MAX_ROWS
81
+ }
82
+
83
+ /**
84
+ * Wrap `input` in a stream that swallows terminal size reports, applies them (and
85
+ * Node's own size once it moves) to `output`, and nudges Ink's resize handler so
86
+ * the frame is re-laid out. Returns `input` untouched when probing cannot work
87
+ * (no TTY, or explicitly disabled), so callers can use it unconditionally.
88
+ */
89
+ export function createTerminalSizeProbe(
90
+ input: NodeJS.ReadStream,
91
+ output: NodeJS.WriteStream,
92
+ options: { pollMs?: number } = {},
93
+ ): NodeJS.ReadStream {
94
+ if (process.env.MOBIUS_TUI_DISABLE_SIZE_PROBE === '1') return input
95
+ if (!input.isTTY || !output.isTTY || typeof input.setRawMode !== 'function') return input
96
+
97
+ const pollMs = options.pollMs ?? DEFAULT_POLL_MS
98
+ let held = ''
99
+ let holdTimer: ReturnType<typeof setTimeout> | null = null
100
+ let applied: TerminalSize | null = null
101
+ // Our own `emit('resize')` must not be mistaken for a real one and re-ask.
102
+ let applying = false
103
+
104
+ const requestSize = (): void => {
105
+ try { output.write(SIZE_QUERY) } catch { /* terminal went away */ }
106
+ }
107
+
108
+ const nudge = (): void => {
109
+ applying = true
110
+ try { output.emit('resize') } finally { applying = false }
111
+ }
112
+
113
+ const applySize = (size: TerminalSize): void => {
114
+ if (!usable(size)) return
115
+ if (applied && applied.columns === size.columns && applied.rows === size.rows) return
116
+ applied = { columns: size.columns, rows: size.rows }
117
+ // Node keeps columns/rows as writable own properties on a tty stream and
118
+ // updates them the same way, so a plain assignment is enough here.
119
+ output.columns = size.columns
120
+ output.rows = size.rows
121
+ nudge()
122
+ }
123
+
124
+ const onResize = (): void => { if (!applying) requestSize() }
125
+
126
+ // (1) Node's value can move without an event reaching us — after the terminal
127
+ // pushed its size while Ink was still booting, say. A cheap 1s re-read turns
128
+ // "resize the window by hand to fix it" into "it just settles".
129
+ const pollTimer = setInterval(() => {
130
+ if (applying) return
131
+ const columns = output.columns, rows = output.rows
132
+ if (applied && applied.columns === columns && applied.rows === rows) return
133
+ applied = { columns, rows }
134
+ if (usable(applied)) nudge()
135
+ }, pollMs)
136
+ if (typeof pollTimer.unref === 'function') pollTimer.unref()
137
+
138
+ const probe = new Transform({
139
+ transform(chunk: Buffer | string, _encoding: string, callback: TransformCallback) {
140
+ if (holdTimer) { clearTimeout(holdTimer); holdTimer = null }
141
+ const { reports, rest } = extractSizeReports(held + String(chunk))
142
+ held = ''
143
+ for (const [first, second] of reports) {
144
+ applySize(interpretSizeReport(first, second, { columns: output.columns, rows: output.rows }))
145
+ }
146
+ // Hold a tail that could still become a report; forward everything else.
147
+ if (rest.length > 0 && rest.length <= 16 && PARTIAL_REPORT.test(rest)) {
148
+ held = rest
149
+ holdTimer = setTimeout(() => {
150
+ holdTimer = null
151
+ const flushed = held
152
+ held = ''
153
+ if (flushed) probe.push(flushed)
154
+ }, PARTIAL_HOLD_MS)
155
+ callback(null, '')
156
+ return
157
+ }
158
+ callback(null, rest)
159
+ },
160
+ flush(callback: TransformCallback) {
161
+ if (holdTimer) clearTimeout(holdTimer)
162
+ holdTimer = null
163
+ const flushed = held
164
+ held = ''
165
+ callback(null, flushed)
166
+ },
167
+ }) as Transform & Partial<NodeJS.ReadStream>
168
+
169
+ // Mimic the tty surface Ink and the win32 input decoder expect downstream.
170
+ Object.defineProperty(probe, 'isTTY', { value: true })
171
+ Object.defineProperty(probe, 'isRaw', { get: () => input.isRaw })
172
+ probe.setRawMode = (enabled: boolean) => { input.setRawMode?.(enabled); return probe as NodeJS.ReadStream }
173
+ probe.ref = () => { input.ref(); return probe as NodeJS.ReadStream }
174
+ probe.unref = () => { input.unref(); return probe as NodeJS.ReadStream }
175
+
176
+ output.on('resize', onResize)
177
+ // The answer only arrives once the tty is raw — in cooked mode it would sit in
178
+ // the line buffer until the user pressed Enter.
179
+ try { input.setRawMode(true) } catch { /* not a real tty after all */ }
180
+ requestSize()
181
+ input.pipe(probe)
182
+ return probe as NodeJS.ReadStream
183
+ }
package/src/main.tsx CHANGED
@@ -10,8 +10,16 @@ import React from 'react'
10
10
  import { render } from 'ink'
11
11
  import { App } from './App.js'
12
12
  import { createInkInputStream } from './lib/windows-input.js'
13
+ import { createTerminalSizeProbe } from './lib/terminal-size.js'
14
+
15
+ // Ask the terminal for its real text-area size before Ink lays anything out:
16
+ // on Windows (ConPTY, and cmd whose screen buffer is wider than its window) the
17
+ // size Node reports can be a stale, too-wide value until the window is resized
18
+ // by hand. See lib/terminal-size.ts.
19
+ const stdout = process.stdout
20
+ const stdin = createInkInputStream(createTerminalSizeProbe(process.stdin, stdout), stdout)
13
21
 
14
22
  render(React.createElement(App), {
15
23
  exitOnCtrlC: true,
16
- stdin: createInkInputStream(process.stdin, process.stdout),
24
+ stdin,
17
25
  })
@@ -7,7 +7,7 @@ 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 } from '../src/aimux.js'
11
11
 
12
12
  const delay = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms))
13
13
  let pass = 0, fail = 0
@@ -226,6 +226,34 @@ function testPickSilentFlag() {
226
226
  ok(pickSilentFlag(' --silent-v2 Hide console.', 'linux') === null, 'off-Windows → always null')
227
227
  }
228
228
 
229
+ function testGuiAuthorization() {
230
+ console.log('\n[AIMUX 6c] GUI authorization: identifier prefix + --enable-gui args')
231
+ // Default (flag off): classic tui- prefix, no --enable-gui.
232
+ ok(tuiAimuxIdentifier('host-a', '/w', 'alice', false).startsWith('tui-host-a-'), 'flag off keeps the tui- prefix')
233
+ // Authorized: gui- prefix on the same host/hash — the capability shows in the remote name.
234
+ const tuiId = tuiAimuxIdentifier('host-a', '/w', 'alice', false)
235
+ const guiId = tuiAimuxIdentifier('host-a', '/w', 'alice', true)
236
+ ok(guiId.startsWith('gui-host-a-'), 'authorized client registers as gui-<host>-<hash>')
237
+ ok(guiId.endsWith(tuiId.split('-').slice(-1)[0]), 'gui- identifier keeps the same workspace hash')
238
+ ok(tuiAimuxIdentifier('host-a', '/w', 'alice', false) !== guiId, 'prefix flip changes the identifier')
239
+ // reverse connect args only carry --enable-gui when asked.
240
+ const plain = reverseConnectArgs('https://mobius.test/', 'tui-x', 't', 'linux', null, null, false)
241
+ const gui = reverseConnectArgs('https://mobius.test/', 'gui-x', 't', 'linux', null, null, true)
242
+ ok(!plain.includes('--enable-gui'), 'flag off sends no --enable-gui')
243
+ ok(gui.includes('--enable-gui'), 'authorized connection passes --enable-gui')
244
+ // Probe gates on what aimux advertises (0.3.64+), mirroring pickSilentFlag.
245
+ ok(pickEnableGuiFlag(' --enable-gui Start the GUI helper.') === true, 'probe sees --enable-gui when advertised')
246
+ 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.
248
+ const before = tuiAimuxIdentifier('host-b', '/w2', 'bob')
249
+ setTuiGuiAuthorized(true)
250
+ const after = tuiAimuxIdentifier('host-b', '/w2', 'bob')
251
+ ok(before.startsWith('tui-') && after.startsWith('gui-'), 'writing the flag flips the default identifier prefix')
252
+ ok(tuiGuiAuthorized() === true, 'flag reads back true after write')
253
+ setTuiGuiAuthorized(false)
254
+ ok(tuiAimuxIdentifier('host-b', '/w2', 'bob').startsWith('tui-'), 'clearing the flag restores the tui- prefix')
255
+ }
256
+
229
257
  function testVersionAtLeast() {
230
258
  console.log('\n[AIMUX 6c] aimux pin is a floor, not an exact match')
231
259
  // /upgrade 装的是 PyPI 最新版,通常比 pin 新;不能被 pin 校验判成"没装好"又拽回去。
@@ -310,6 +338,7 @@ async function main() {
310
338
  await testSpawnLauncher()
311
339
  testReverseConnectArgs()
312
340
  testPickSilentFlag()
341
+ testGuiAuthorization()
313
342
  testVersionAtLeast()
314
343
  testAimuxIdentifierScopesWorkspace()
315
344
  testBundleHealthCheck()
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Terminal size probe tests.
3
+ *
4
+ * The probe exists because Windows can leave the process with a stale terminal
5
+ * width — a resize delivered while Ink was still booting, or a console whose
6
+ * reported size disagrees with the window (cmd's screen buffer, ConPTY). See
7
+ * src/lib/terminal-size.ts. These tests drive it with fake tty streams so the
8
+ * parts that must hold on every platform are covered.
9
+ */
10
+ import { EventEmitter } from 'node:events'
11
+ import { PassThrough } from 'node:stream'
12
+ import { createTerminalSizeProbe, extractSizeReports, interpretSizeReport } from '../src/lib/terminal-size.js'
13
+
14
+ let pass = 0, fail = 0
15
+ function ok(condition: boolean, message: string) {
16
+ if (condition) { pass += 1; console.log(` ✓ ${message}`) }
17
+ else { fail += 1; console.error(` ✗ ${message}`) }
18
+ }
19
+
20
+ const delay = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms))
21
+ /** CSI 8 ; n ; n t — the answer to CSI 18 t, given in the terminal's own order. */
22
+ const report = (first: number, second: number) => `\x1b[8;${first};${second}t`
23
+
24
+ function fakeStdin(): NodeJS.ReadStream & { rawCalls: boolean[] } {
25
+ const stdin = new PassThrough() as any
26
+ stdin.isTTY = true
27
+ stdin.isRaw = false
28
+ stdin.rawCalls = []
29
+ stdin.setRawMode = (value: boolean) => { stdin.isRaw = value; stdin.rawCalls.push(value); return stdin }
30
+ return stdin as NodeJS.ReadStream & { rawCalls: boolean[] }
31
+ }
32
+
33
+ function fakeStdout(columns: number, rows: number): NodeJS.WriteStream & { written: string[] } {
34
+ const stdout = new EventEmitter() as any
35
+ stdout.isTTY = true
36
+ stdout.columns = columns // Node keeps these as plain writable data properties
37
+ stdout.rows = rows
38
+ stdout.written = []
39
+ stdout.write = (chunk: string) => { stdout.written.push(String(chunk)); return true }
40
+ return stdout
41
+ }
42
+
43
+ /** Collect what the app would see downstream of the probe. */
44
+ function collector(stream: NodeJS.ReadableStream): { text: () => string } {
45
+ let seen = ''
46
+ stream.on('data', (chunk: Buffer | string) => { seen += String(chunk) })
47
+ return { text: () => seen }
48
+ }
49
+
50
+ function testExtractSizeReports() {
51
+ console.log('\n[SIZE 1] report extraction')
52
+ const one = extractSizeReports(report(30, 113))
53
+ ok(one.reports.length === 1 && one.reports[0][0] === 30 && one.reports[0][1] === 113,
54
+ 'a plain report yields both numbers in the order sent')
55
+ const mixed = extractSizeReports(`ab${report(24, 80)}cd`)
56
+ ok(mixed.rest === 'abcd' && mixed.reports.length === 1, 'report bytes are removed and the rest is kept')
57
+ const two = extractSizeReports(`${report(24, 80)}${report(30, 100)}`)
58
+ ok(two.reports.length === 2 && two.reports[1][1] === 100, 'back-to-back reports both parse')
59
+ ok(extractSizeReports('no report here').reports.length === 0, 'ordinary input yields no reports')
60
+ }
61
+
62
+ function testInterpretSizeReport() {
63
+ console.log('\n[SIZE 2] which number is the width')
64
+ // xterm/Windows Terminal: CSI 8 ; height ; width t — a stale 120-wide console
65
+ // answering for a 113-wide window must correct the width, not swap the axes.
66
+ const documented = interpretSizeReport(30, 113, { columns: 120, rows: 30 })
67
+ ok(documented.columns === 113 && documented.rows === 30, 'the documented height;width order is preferred when it is the closer read')
68
+ // tmux answers width first (measured): 100x30 pane replying "100;30" must not
69
+ // be read as 100 rows tall.
70
+ const swapped = interpretSizeReport(100, 30, { columns: 100, rows: 30 })
71
+ ok(swapped.columns === 100 && swapped.rows === 30, 'a width-first terminal is not turned into 100 rows')
72
+ const tie = interpretSizeReport(24, 80, { columns: 0, rows: 0 })
73
+ ok(tie.columns === 80 && tie.rows === 24, 'an unreadable current size falls back to the documented order')
74
+ }
75
+
76
+ async function testAppliesReportedSize() {
77
+ console.log('\n[SIZE 3] the terminal answer wins over a stale stdout size')
78
+ const stdin = fakeStdin()
79
+ const stdout = fakeStdout(120, 30) // stale, too-wide console size
80
+ const probe = createTerminalSizeProbe(stdin, stdout, { pollMs: 10_000 })
81
+ const seen = collector(probe)
82
+ try {
83
+ ok(stdout.written.join('') === '\x1b[18t', 'the probe asks the terminal with CSI 18 t')
84
+ ok(stdin.rawCalls[0] === true, 'the tty is put in raw mode so the answer is not line-buffered')
85
+ let resized = 0
86
+ stdout.on('resize', () => { resized += 1 })
87
+ stdin.write(report(30, 113))
88
+ await delay(20)
89
+ ok(stdout.columns === 113 && stdout.rows === 30, 'the reported size is mirrored onto stdout')
90
+ ok(resized === 1, 'a resize event is emitted so Ink re-lays out')
91
+ ok(seen.text() === '', 'the report never reaches the app as input')
92
+ } finally { probe.destroy(); stdin.destroy() }
93
+ }
94
+
95
+ async function testSplitReportAcrossChunks() {
96
+ console.log('\n[SIZE 4] a report split across reads')
97
+ const stdin = fakeStdin()
98
+ const stdout = fakeStdout(120, 30)
99
+ const probe = createTerminalSizeProbe(stdin, stdout, { pollMs: 10_000 })
100
+ const seen = collector(probe)
101
+ try {
102
+ stdin.write('\x1b[8;3')
103
+ await delay(5)
104
+ ok(seen.text() === '' && stdout.columns === 120, 'an unfinished report is held, not forwarded or applied')
105
+ stdin.write('0;113t')
106
+ await delay(25)
107
+ ok(stdout.columns === 113 && stdout.rows === 30, 'the finished report applies once the tail arrives')
108
+ ok(seen.text() === '', 'no half-report leaks to the app')
109
+ } finally { probe.destroy(); stdin.destroy() }
110
+ }
111
+
112
+ async function testNormalInputPassesThrough() {
113
+ console.log('\n[SIZE 5] ordinary input is untouched')
114
+ const stdin = fakeStdin()
115
+ const stdout = fakeStdout(120, 30)
116
+ const probe = createTerminalSizeProbe(stdin, stdout, { pollMs: 10_000 })
117
+ const seen = collector(probe)
118
+ try {
119
+ stdin.write('hello \x1b[A\x1b[1;5C\r')
120
+ await delay(30)
121
+ ok(seen.text() === 'hello \x1b[A\x1b[1;5C\r', 'typed text, arrows and Enter pass through unchanged')
122
+ ok(stdout.columns === 120, 'unrelated input does not change the size')
123
+ } finally { probe.destroy(); stdin.destroy() }
124
+ }
125
+
126
+ async function testResizeAsksAgain() {
127
+ console.log('\n[SIZE 6] a real resize re-asks the terminal')
128
+ const stdin = fakeStdin()
129
+ const stdout = fakeStdout(120, 30)
130
+ const probe = createTerminalSizeProbe(stdin, stdout, { pollMs: 10_000 })
131
+ const seen = collector(probe)
132
+ try {
133
+ stdin.write(report(30, 113)); await delay(20)
134
+ ok(stdout.columns === 113, 'first answer applied')
135
+ stdout.written.length = 0
136
+ stdout.emit('resize') // a real window resize
137
+ ok(stdout.written.join('') === '\x1b[18t', 'the probe asks again instead of trusting the stale value')
138
+ stdin.write(report(40, 90)); await delay(20)
139
+ ok(stdout.columns === 90 && stdout.rows === 40, 'the new answer replaces the old one')
140
+ ok(stdout.written.length === 1, 'the probe does not re-ask in a loop off its own resize event')
141
+ } finally { probe.destroy(); stdin.destroy() }
142
+ }
143
+
144
+ async function testPollsNodeSize() {
145
+ console.log('\n[SIZE 7] a size that moved without an event still gets repainted')
146
+ const stdin = fakeStdin()
147
+ const stdout = fakeStdout(120, 30)
148
+ const probe = createTerminalSizeProbe(stdin, stdout, { pollMs: 20 })
149
+ try {
150
+ let resized = 0
151
+ stdout.on('resize', () => { resized += 1 })
152
+ stdout.columns = 90 // the terminal pushed a resize while Ink was booting
153
+ stdout.rows = 24
154
+ await delay(80)
155
+ ok(resized >= 1, 'the periodic re-read nudges Ink once the value moved')
156
+ const settled = resized
157
+ await delay(60)
158
+ ok(resized === settled, 'a size that stopped moving is not nudged again')
159
+ } finally { probe.destroy(); stdin.destroy() }
160
+ }
161
+
162
+ async function testNonsenseIsIgnored() {
163
+ console.log('\n[SIZE 8] unusable answers and non-tty hosts')
164
+ const stdin = fakeStdin()
165
+ const stdout = fakeStdout(120, 30)
166
+ const probe = createTerminalSizeProbe(stdin, stdout, { pollMs: 10_000 })
167
+ try {
168
+ stdin.write(report(0, 0)); await delay(20)
169
+ ok(stdout.columns === 120 && stdout.rows === 30, 'an absurd size is ignored rather than breaking the layout')
170
+ stdin.write(report(900, 5000)); await delay(20)
171
+ ok(stdout.columns === 120, 'an out-of-range width is ignored too')
172
+ } finally { probe.destroy(); stdin.destroy() }
173
+
174
+ const pipe = fakeStdin(); pipe.isTTY = false
175
+ const out = fakeStdout(80, 24)
176
+ ok(createTerminalSizeProbe(pipe, out) === pipe, 'a non-tty stdin is returned untouched')
177
+
178
+ const tty = fakeStdin()
179
+ const pipedOut = fakeStdout(80, 24); pipedOut.isTTY = false
180
+ ok(createTerminalSizeProbe(tty, pipedOut) === tty, 'a non-tty stdout is returned untouched')
181
+ }
182
+
183
+ async function main() {
184
+ testExtractSizeReports()
185
+ testInterpretSizeReport()
186
+ await testAppliesReportedSize()
187
+ await testSplitReportAcrossChunks()
188
+ await testNormalInputPassesThrough()
189
+ await testResizeAsksAgain()
190
+ await testPollsNodeSize()
191
+ await testNonsenseIsIgnored()
192
+ console.log(`\n==== SIZE RESULT: ${pass} passed, ${fail} failed ====\n`)
193
+ process.exit(fail === 0 ? 0 : 1)
194
+ }
195
+
196
+ main().catch(error => { console.error('FATAL', error); process.exit(2) })