@mobius-os/mobius 0.3.61 → 0.3.64

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/README.md CHANGED
@@ -95,8 +95,9 @@ to green.
95
95
  `<Static>` rows with dynamic UI.
96
96
  - The `typing` event drives the working indicator. Press Esc (or Ctrl+C) to
97
97
  interrupt a running turn.
98
- - Slash commands: `/clear` (new session), `/resume` (history), `/help`,
99
- `/quit`. Ctrl+C stops a running turn, or quits when idle.
98
+ - Slash commands: `/clear` (new session), `/resume` (history), `/upgrade`
99
+ (install the newest AIMUX from PyPI and reconnect), `/help`, `/quit`.
100
+ Ctrl+C stops a running turn, or quits when idle.
100
101
 
101
102
  ## Reusing the web frontend
102
103
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mobius-os/mobius",
3
- "version": "0.3.61",
3
+ "version": "0.3.64",
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,10 +13,10 @@ set -euo pipefail
13
13
 
14
14
  TAG=20241002
15
15
  PYVER=3.12.7
16
- BUNDLE_VER=11
17
- AIMUX_VERSION=0.3.61
16
+ BUNDLE_VER=13
17
+ AIMUX_VERSION=0.3.64
18
18
  PYPI_INDEX=https://pypi.org/simple
19
- WORK="${WORK:-/home/tianyi/python-bundles}"
19
+ WORK="${WORK:-$HOME/python-bundles}"
20
20
  DIST="${DIST:-$WORK/dist}"
21
21
  AIMUX_WHEEL="${AIMUX_WHEEL:-}"
22
22
  mkdir -p "$WORK" "$DIST"
package/src/App.tsx CHANGED
@@ -19,7 +19,7 @@ import { ChatScreen } from './components/Chat.js'
19
19
  import type { ConfigResult } from './components/ConfigFlow.js'
20
20
  import { ResumePicker } from './components/ResumePicker.js'
21
21
  import { Screen } from './components/Screen.js'
22
- import { startAimuxConnection, stopAimuxConnection, type AimuxStatus } from './aimux.js'
22
+ import { startAimuxConnection, stopAimuxConnection, upgradeAimuxRuntime, type AimuxStatus } from './aimux.js'
23
23
  import { AimuxStatusLine } from './components/AimuxStatus.js'
24
24
  import { bufferUnclaimedInput, useStableInput } from './components/primitives.js'
25
25
 
@@ -200,6 +200,7 @@ export function App() {
200
200
  onResume={onResume}
201
201
  onQuit={onQuit}
202
202
  onLogout={() => { void onLogout() }}
203
+ onUpgradeAimux={() => { void upgradeAimuxRuntime() }}
203
204
  onReconfigure={onReconfigure}
204
205
  onConfigCancel={onConfigCancel}
205
206
  aimuxStatus={aimuxStatus}
package/src/aimux.ts CHANGED
@@ -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.61'
35
+ const AIMUX_TARGET_VERSION = '0.3.64'
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')
@@ -92,7 +92,8 @@ async function pythonForAimux(onProgress?: (p: InstallProgress) => void): Promis
92
92
  // 解压到 ~/.mobius/python-bundle/ 后用 `<python> -m aimux` 运行,彻底绕开宿主机
93
93
  // 系统 python(如被精简掉 ensurepip 的容器镜像)。aimux 全部依赖为纯 Python,
94
94
  // 故三平台可共用同一套打包产物,分别按 arch 发布到 CDN。
95
- const BUNDLE_VER = '11'
95
+ /** Plan B 内置运行时包版本;每次发版跟 aimux pin 一起 +1,测试也从这里取。 */
96
+ export const BUNDLE_VER = '13'
96
97
  const BUNDLE_AIMUX_VERSION = AIMUX_TARGET_VERSION
97
98
  /** Version expected from the installed or bundled AIMUX runtime. */
98
99
  export const AIMUX_VERSION = BUNDLE_AIMUX_VERSION
@@ -288,22 +289,44 @@ function spawnDetachedDaemon(launcher: AimuxLauncher, args: string[]): ChildProc
288
289
  /** test-only 导出: 暴露内部 downloadBundle 以便单测 mock fetch 验证流式下载+进度。 */
289
290
  export const downloadBundleForTest = downloadBundle
290
291
 
291
- function venvReady(): boolean {
292
- if (!existsSync(aimuxExe()) || !existsSync(venvPython())) return false
292
+ /** `a >= b`(点分数字)。非数字段一律判 false,宁可重装也不要用一个看不懂的版本。 */
293
+ export function versionAtLeast(a: string, b: string): boolean {
294
+ const pa = a.split('.'), pb = b.split('.')
295
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
296
+ const x = Number(pa[i] ?? 0), y = Number(pb[i] ?? 0)
297
+ if (!Number.isFinite(x) || !Number.isFinite(y)) return false
298
+ if (x !== y) return x > y
299
+ }
300
+ return true
301
+ }
302
+
303
+ /** venv 里现成的 aimux 版本(跑不起来时 null)。 */
304
+ function installedAimuxVersion(): string | null {
305
+ if (!existsSync(aimuxExe()) || !existsSync(venvPython())) return null
293
306
  try {
294
- return spawnSync(
295
- venvPython(),
296
- ['-c', `import aimux; assert aimux.__version__ == '${AIMUX_TARGET_VERSION}'`],
297
- { stdio: 'ignore', windowsHide: true },
298
- ).status === 0
307
+ const r = spawnSync(venvPython(), ['-c', 'import aimux; print(aimux.__version__)'], { encoding: 'utf8', windowsHide: true })
308
+ if (r.status !== 0) return null
309
+ const v = (r.stdout ?? '').trim().split(/\s+/).pop()
310
+ return v || null
299
311
  } catch {
300
- return false
312
+ return null
301
313
  }
302
314
  }
303
315
 
316
+ /**
317
+ * pin 是**最低可用版本**,不是精确版本:比它新的直接沿用。
318
+ * 否则用户 `/upgrade` 到 PyPI 最新版后,下一次连接(乃至下次启动)会被拽回 pin,
319
+ * 升级看着"没生效"。
320
+ */
321
+ function venvReady(): boolean {
322
+ const installed = installedAimuxVersion()
323
+ return installed !== null && versionAtLeast(installed, AIMUX_TARGET_VERSION)
324
+ }
325
+
304
326
  export async function ensureAimux(onProgress?: (p: InstallProgress) => void): Promise<{ ok: boolean; error?: string; launcher?: AimuxLauncher }> {
305
327
  // Fast-path:venv 里已有 aimux 可执行 → 直接用。
306
- if (venvReady()) { logInstall(`ensureAimux fast-path: venv aimux ${AIMUX_TARGET_VERSION} present\n`); onProgress?.({ phase: 'ready' }); return { ok: true, launcher: { kind: 'exe', path: aimuxExe() } } }
328
+ const existing = venvReady() ? installedAimuxVersion() : null
329
+ if (existing) { logInstall(`ensureAimux fast-path: venv aimux ${existing} present (pin ${AIMUX_TARGET_VERSION})\n`); onProgress?.({ phase: 'ready' }); return { ok: true, launcher: { kind: 'exe', path: aimuxExe() } } }
307
330
  logInstall(`\n########## ensureAimux install begin ${new Date().toISOString()} platform=${process.platform} arch=${process.arch} home=${mobiusHome()} ##########\n`)
308
331
  const py = await pythonForAimux(onProgress)
309
332
  logInstall(` pythonForAimux → ${py ?? '(null: no system python)'}\n`)
@@ -666,17 +689,21 @@ export class AimuxSupervisor {
666
689
 
667
690
  let supervisor: AimuxSupervisor | null = null
668
691
  let installing: Promise<void> | null = null
669
- // Resolved Windows console-hiding flag for the installed aimux (undefined =
670
- // not probed yet this process). Cached so reconnects reuse it without re-running
671
- // `aimux reverse connect --help`. See reverseConnectArgs for why this is probed.
672
- let cachedSilentFlag: string | null | undefined = undefined
692
+ /** 上一次 startAimuxConnection 的参数,供 `/upgrade` 重装后原地重连。 */
693
+ let lastStartOpts: StartOptions | null = null
673
694
 
674
- export async function startAimuxConnection(opts: {
695
+ interface StartOptions {
675
696
  server: string
676
697
  token: string
677
698
  onStatus?: (s: AimuxStatus) => void
678
699
  refreshToken?: () => Promise<string | null>
679
- }): Promise<void> {
700
+ }
701
+ // Resolved Windows console-hiding flag for the installed aimux (undefined =
702
+ // not probed yet this process). Cached so reconnects reuse it without re-running
703
+ // `aimux reverse connect --help`. See reverseConnectArgs for why this is probed.
704
+ let cachedSilentFlag: string | null | undefined = undefined
705
+
706
+ export async function startAimuxConnection(opts: StartOptions): Promise<void> {
680
707
  const onStatus = opts.onStatus ?? (() => {})
681
708
  // Tests and explicitly opted-out users should not spawn a network worker.
682
709
  if (process.env.MOBIUS_TUI_DISABLE_AIMUX === '1') {
@@ -686,6 +713,7 @@ export async function startAimuxConnection(opts: {
686
713
  onStatus({ state: 'disabled', phase: 'idle', detail: 'AIMUX 测试连接已跳过' }); return
687
714
  }
688
715
  if (supervisor || installing) return
716
+ lastStartOpts = opts
689
717
  installing = (async () => {
690
718
  onStatus({ state: 'starting', phase: 'python', detail: '检查 Python 与 AIMUX 运行环境…' })
691
719
  const ready = await ensureAimux(p => onStatus({
@@ -718,3 +746,79 @@ export async function stopAimuxConnection(): Promise<void> {
718
746
  const current = supervisor; supervisor = null
719
747
  await current?.stop()
720
748
  }
749
+
750
+ /** SIGTERM 掉本工作区 runtime JSON 里记录的守护进程,并删掉该文件。
751
+ * 不这么做的话,新 supervisor 会按 pid 复用到刚升级前的旧 daemon。 */
752
+ async function stopDaemonFromRuntime(): Promise<void> {
753
+ const hash = aimuxWorkspaceHash()
754
+ const pid = (await readRuntime(hash))?.pid ?? null
755
+ if (pid !== null && pidAlive(pid)) {
756
+ try { process.kill(pid, 'SIGTERM') } catch { /* 已经退了 */ }
757
+ for (let i = 0; i < 30 && pidAlive(pid); i++) await new Promise(r => setTimeout(r, 100))
758
+ if (pidAlive(pid)) { try { process.kill(pid, 'SIGKILL') } catch { /* ignore */ } }
759
+ }
760
+ try { await fs.unlink(runtimePath(hash)) } catch { /* 本来就没有 */ }
761
+ }
762
+
763
+ /** `/upgrade` 装的永远是 PyPI 上的最新版,故意不走 AIMUX_TARGET_VERSION 这条 pin。 */
764
+ const AIMUX_PYPI_INDEX = 'https://pypi.org/simple'
765
+
766
+ /** 从 PyPI 官方索引安装最新 aimux(不带版本约束),返回实际装上的版本。 */
767
+ async function installLatestAimux(onProgress?: (p: InstallProgress) => void): Promise<{ ok: boolean; version?: string; error?: string }> {
768
+ const py = await pythonForAimux(onProgress)
769
+ if (!py) return { ok: false, error: '未找到 Python 3.10+(或 uv),无法升级 AIMUX' }
770
+ if (!existsSync(venvPython())) {
771
+ onProgress?.({ phase: 'venv', detail: `创建 Python 虚拟环境(${py})…` })
772
+ let r = await run(py, ['-m', 'venv', venvDir()])
773
+ if (r.code !== 0 && py === 'py') r = await run(py, ['-3', '-m', 'venv', venvDir()])
774
+ if (r.code !== 0) return { ok: false, error: `venv 创建失败: ${r.stderr || r.stdout}` }
775
+ }
776
+ onProgress?.({ phase: 'install', detail: '正在从 PyPI 安装最新 aimux…' })
777
+ // --no-cache-dir:刚发布的版本可能还躺在 pip 的索引/包缓存里(TTL 内),
778
+ // 用户点 /upgrade 就是要立刻拿到新版本,宁可多下一次也不吃缓存。
779
+ const r = await run(venvPython(), [
780
+ '-m', 'pip', 'install', '--no-input', '--disable-pip-version-check',
781
+ '--upgrade', '--no-cache-dir', '--index-url', AIMUX_PYPI_INDEX, 'aimux',
782
+ ], line => {
783
+ if (/downloading|collecting|installing|using cached|%\s*\d|━|─/i.test(line)) onProgress?.({ phase: 'install', detail: line.slice(0, 120) })
784
+ })
785
+ if (r.code !== 0) return { ok: false, error: `pip install 失败: ${r.stderr || r.stdout}` }
786
+ const v = await run(venvPython(), ['-c', 'import aimux; print(aimux.__version__)'])
787
+ const version = v.code === 0 ? v.stdout.trim().split(/\s+/).pop() : undefined
788
+ logInstall(`/upgrade installed aimux ${version ?? '(version unknown)'} from ${AIMUX_PYPI_INDEX}\n`)
789
+ return { ok: true, version }
790
+ }
791
+
792
+ /**
793
+ * `/upgrade`:把本地 AIMUX 升到 PyPI 上的最新版并原地重连。
794
+ *
795
+ * 顺序很关键——先停 TUI 的续租与旧守护进程,再装,最后用上次的连接参数重连:
796
+ * 否则 supervisor 会按旧 pid 把升级前的 daemon 复用回来,升级看起来"没生效"。
797
+ */
798
+ export async function upgradeAimuxRuntime(): Promise<{ ok: boolean; version?: string; error?: string }> {
799
+ const opts = lastStartOpts
800
+ const onStatus = opts?.onStatus ?? (() => {})
801
+ if (process.env.MOBIUS_TUI_DISABLE_AIMUX === '1') {
802
+ const error = 'AIMUX 自动连接已关闭 (MOBIUS_TUI_DISABLE_AIMUX=1)'
803
+ onStatus({ state: 'disabled', phase: 'idle', detail: 'AIMUX 自动连接已关闭' })
804
+ return { ok: false, error }
805
+ }
806
+ if (!opts) return { ok: false, error: '尚未登录或 AIMUX 未启动,无法升级' }
807
+ logInstall(`\n########## /upgrade requested ${new Date().toISOString()} ##########\n`)
808
+ onStatus({ state: 'starting', phase: 'install', detail: '正在停止 AIMUX 守护进程…' })
809
+ await stopAimuxConnection()
810
+ await stopDaemonFromRuntime()
811
+ const installed = await installLatestAimux(p => onStatus({
812
+ state: 'starting',
813
+ phase: p.phase === 'ready' ? 'connecting' : p.phase,
814
+ detail: p.detail || (p.phase === 'ready' ? 'AIMUX 已就绪,准备连接…' : p.phase),
815
+ }))
816
+ if (!installed.ok) {
817
+ logInstall(`########## /upgrade FAILED: ${installed.error} ##########\n`)
818
+ onStatus({ state: 'failed', phase: 'idle', detail: `${installed.error} · 日志: ${aimuxLogPath()}` })
819
+ return { ok: false, error: installed.error }
820
+ }
821
+ onStatus({ state: 'starting', phase: 'connecting', detail: `AIMUX ${installed.version ?? '最新版'} 已安装,正在重新连接…` })
822
+ await startAimuxConnection(opts)
823
+ return { ok: true, version: installed.version }
824
+ }
@@ -40,6 +40,8 @@ interface ChatProps {
40
40
  onResume: () => void
41
41
  onQuit: () => void
42
42
  onLogout: () => void
43
+ /** 可选,与 aimuxStatus 一样只在接了 AIMUX 的宿主里给;缺省时 /upgrade 不动作。 */
44
+ onUpgradeAimux?: () => void
43
45
  onReconfigure: (result: ConfigResult) => void
44
46
  onConfigCancel: (sessionId: string | null) => void
45
47
  aimuxStatus?: AimuxStatus
@@ -64,10 +66,11 @@ const SLASH_COMMANDS = [
64
66
  { cmd: '/logout', desc: '断开当前连接并返回登录界面' },
65
67
  { cmd: '/help', desc: '显示帮助' },
66
68
  { cmd: '/version', desc: '显示 TUI、AIMUX 和运行环境版本' },
69
+ { cmd: '/upgrade', desc: '从 PyPI 安装最新 AIMUX 并重连' },
67
70
  { cmd: '/quit', desc: '退出 TUI' },
68
71
  ]
69
72
 
70
- export function ChatScreen({ client, ready, webUserId, resumeSessionId, onClear, onResume, onQuit, onLogout, onReconfigure, onConfigCancel, aimuxStatus }: ChatProps) {
73
+ export function ChatScreen({ client, ready, webUserId, resumeSessionId, onClear, onResume, onQuit, onLogout, onUpgradeAimux, onReconfigure, onConfigCancel, aimuxStatus }: ChatProps) {
71
74
  const chat = useChat({ client, ready, resumeSessionId })
72
75
  const [showHelp, setShowHelp] = useState(false)
73
76
  // null means "follow the tail". A concrete anchor identifies the exact row
@@ -130,11 +133,18 @@ export function ChatScreen({ client, ready, webUserId, resumeSessionId, onClear,
130
133
  }
131
134
  case '/model': setConfigOpen(true); return true
132
135
  case '/config': setReconfigOpen(true); return true
136
+ case '/upgrade': {
137
+ // 安装与重连进度都走 aimuxStatus(状态行),失败也会落进 aimuxStatus.detail,
138
+ // 所以这里只管触发,不额外弹错。
139
+ setVersionInfo(null)
140
+ onUpgradeAimux?.()
141
+ return true
142
+ }
133
143
  case '/logout': onLogout(); return true
134
144
  case '/quit': case '/exit': onQuit(); return true
135
145
  default: return false
136
146
  }
137
- }, [aimuxStatus, chat, client.server, modelLabel, ready.prefs.model, onClear, onResume, onQuit, onLogout])
147
+ }, [aimuxStatus, chat, client.server, modelLabel, ready.prefs.model, onClear, onResume, onQuit, onLogout, onUpgradeAimux])
138
148
 
139
149
  const onSubmit = useCallback((text: string) => {
140
150
  const t = text.trim()
@@ -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, bundleArch, bundleUrl, spawnLauncher, ensureFromBundle, downloadBundleForTest, reverseConnectArgs, pickSilentFlag, 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 } 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
@@ -174,11 +174,11 @@ async function testBundleArchAndUrl() {
174
174
  const arch = bundleArch()
175
175
  ok(arch === 'linux-x64' || arch === 'win-x64' || arch === 'mac-x64', `bundleArch returns a supported arch on this host (${arch})`)
176
176
  const before = bundleUrl('linux-x64')
177
- ok(before.includes('mobius-python-linux-x64-v11') && before.endsWith('.zip'), 'bundleUrl follows the fixed filename pattern')
177
+ ok(before.includes(`mobius-python-linux-x64-v${BUNDLE_VER}`) && before.endsWith('.zip'), 'bundleUrl follows the fixed filename pattern')
178
178
  const saved = process.env.MOBIUS_TUI_PYTHON_BUNDLE_URL
179
179
  process.env.MOBIUS_TUI_PYTHON_BUNDLE_URL = 'https://example.test/cdn/'
180
180
  try {
181
- ok(bundleUrl('win-x64') === 'https://example.test/cdn/mobius-python-win-x64-v11.zip', 'MOBIUS_TUI_PYTHON_BUNDLE_URL overrides the CDN base and trims trailing slash')
181
+ ok(bundleUrl('win-x64') === `https://example.test/cdn/mobius-python-win-x64-v${BUNDLE_VER}.zip`, 'MOBIUS_TUI_PYTHON_BUNDLE_URL overrides the CDN base and trims trailing slash')
182
182
  } finally { if (saved === undefined) delete process.env.MOBIUS_TUI_PYTHON_BUNDLE_URL; else process.env.MOBIUS_TUI_PYTHON_BUNDLE_URL = saved }
183
183
  }
184
184
 
@@ -226,6 +226,18 @@ function testPickSilentFlag() {
226
226
  ok(pickSilentFlag(' --silent-v2 Hide console.', 'linux') === null, 'off-Windows → always null')
227
227
  }
228
228
 
229
+ function testVersionAtLeast() {
230
+ console.log('\n[AIMUX 6c] aimux pin is a floor, not an exact match')
231
+ // /upgrade 装的是 PyPI 最新版,通常比 pin 新;不能被 pin 校验判成"没装好"又拽回去。
232
+ ok(versionAtLeast('0.3.62', '0.3.61'), 'newer aimux satisfies the pinned floor')
233
+ ok(versionAtLeast('0.3.61', '0.3.61'), 'exactly the pinned version satisfies the floor')
234
+ ok(versionAtLeast('0.4.0', '0.3.61'), 'a newer minor satisfies the floor')
235
+ ok(!versionAtLeast('0.3.60', '0.3.61'), 'an older aimux is still reinstalled')
236
+ ok(!versionAtLeast('0.1.40', '0.3.61'), 'the old 0.1.x line is still reinstalled')
237
+ ok(versionAtLeast('0.3.61.1', '0.3.61'), 'a longer version string compares by segment')
238
+ ok(!versionAtLeast('garbage', '0.3.61'), 'an unparseable version is treated as not-ready')
239
+ }
240
+
229
241
  function testAimuxIdentifierScopesWorkspace() {
230
242
  console.log('\n[AIMUX 6a] reverse client identifier workspace isolation')
231
243
  const first = tuiAimuxIdentifier('same-host', '/work/project-a')
@@ -298,6 +310,7 @@ async function main() {
298
310
  await testSpawnLauncher()
299
311
  testReverseConnectArgs()
300
312
  testPickSilentFlag()
313
+ testVersionAtLeast()
301
314
  testAimuxIdentifierScopesWorkspace()
302
315
  testBundleHealthCheck()
303
316
  await testEnsureFromBundleReady()
@@ -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) })
package/tests/ui.test.tsx CHANGED
@@ -1256,6 +1256,40 @@ async function testVersionSlash() {
1256
1256
  } finally { restoreFetch() }
1257
1257
  }
1258
1258
 
1259
+ // ════════════════════════════════════════════════════════════════════════════
1260
+ // TEST 18 — /upgrade hands off to the host (install latest aimux + reconnect)
1261
+ // ════════════════════════════════════════════════════════════════════════════
1262
+ async function testUpgradeSlash() {
1263
+ console.log('\n[UI 18] /upgrade slash command')
1264
+ const client = new MobiusClient('http://mock.local', 'mock-jwt-token')
1265
+ const ready: ReadyState = {
1266
+ project: { id: 'p1', name: '测试项目' },
1267
+ issue: { id: 'i1', project_id: 'p1', title: '测试任务' },
1268
+ prefs: { model: 'codex', language: 'zh', excluded_skill_ids: [], excluded_memory_ids: [] },
1269
+ }
1270
+ installMock((url) => {
1271
+ if (url.includes('/events')) {
1272
+ return new Response(new RS({ start(c: any) { sseController = c; c.enqueue(enc.encode('event: subscribed\ndata: {"event":"subscribed","session":{}}\n\n')) } }), { status: 200, headers: { 'content-type': 'text/event-stream' } })
1273
+ }
1274
+ return jsonResponse({ error: 'no mock' }, 404)
1275
+ })
1276
+ try {
1277
+ let upgrades = 0
1278
+ const { stdin, lastFrame, unmount } = render(
1279
+ <ChatScreen client={client} ready={ready} webUserId="u" onClear={() => {}} onResume={() => {}} onQuit={() => {}} onLogout={() => {}} onUpgradeAimux={() => { upgrades += 1 }} onReconfigure={() => {}} onConfigCancel={() => {}} />,
1280
+ )
1281
+ await delay(60)
1282
+ // 打全了命令名弹窗就收起,所以先在只打了前缀时看菜单里有没有它。
1283
+ stdin.write('/upg'); await delay(40)
1284
+ const menu = lastFrame() ?? ''
1285
+ ok(menu.includes('/upgrade'), '/upgrade is offered in the slash-command menu')
1286
+ stdin.write('rade'); await delay(40)
1287
+ stdin.write('\r'); await delay(80)
1288
+ unmount()
1289
+ ok(upgrades === 1, '/upgrade calls the host upgrade hook exactly once')
1290
+ } finally { restoreFetch() }
1291
+ }
1292
+
1259
1293
  async function main() {
1260
1294
  await testLogin()
1261
1295
  await testChat()
@@ -1283,6 +1317,7 @@ async function main() {
1283
1317
  await testSendRetries502()
1284
1318
  await testCompactSlash()
1285
1319
  await testVersionSlash()
1320
+ await testUpgradeSlash()
1286
1321
  // cleanup temp home
1287
1322
  try { fs.rmSync(TMP_HOME, { recursive: true, force: true }) } catch { /* ignore */ }
1288
1323
  console.log(`\n==== UI RESULT: ${pass} passed, ${fail} failed ====\n`)