@mobius-os/mobius 0.3.50 → 0.3.52

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.50",
3
+ "version": "0.3.52",
4
4
  "type": "module",
5
5
  "description": "Mobius terminal client. Reuses Mobius frontend TypeScript types and jsonl entry shapes.",
6
6
  "bin": {
@@ -21,6 +21,7 @@
21
21
  "extract-zip": "^2.0.1",
22
22
  "ink": "5.2.0",
23
23
  "marked": "12.0.2",
24
+ "proper-lockfile": "^4.1.2",
24
25
  "react": "18.3.1",
25
26
  "tsx": "4.19.2",
26
27
  "wrap-ansi": "^9.0.0"
package/src/App.tsx CHANGED
@@ -9,7 +9,7 @@
9
9
  * GET /api/auth/me; on a stale token, re-login with the stored username/password
10
10
  * (matching the desktop electron flow). Otherwise show the login form.
11
11
  */
12
- import React, { useEffect, useState } from 'react'
12
+ import React, { useEffect, useRef, useState } from 'react'
13
13
  import { Box, Text } from 'ink'
14
14
  import { MobiusClient, getMe, login, ApiError } from './api.js'
15
15
  import { clearLogin, loadLogin, saveLogin, type LoginRecord } from './config.js'
@@ -39,18 +39,33 @@ export function App() {
39
39
  const [ready, setReady] = useState<ReadyState | null>(null)
40
40
  const [chatKey, setChatKey] = useState(0)
41
41
  const [resumeSessionId, setResumeSessionId] = useState<string | null>(null)
42
+ // Mutating MobiusClient.token is enough for future requests, while this
43
+ // revision also re-renders Chat so its token-dependent SSE effect reconnects.
44
+ const [, setAuthRevision] = useState(0)
45
+ const aimuxAuthGeneration = useRef(0)
42
46
  const [aimuxStatus, setAimuxStatus] = useState<AimuxStatus>({
43
47
  state: process.env.MOBIUS_TUI_DISABLE_AIMUX === '1' ? 'disabled' : 'stopped',
44
48
  phase: 'idle',
45
49
  detail: process.env.MOBIUS_TUI_DISABLE_AIMUX === '1' ? 'AIMUX 自动连接已关闭' : '登录后自动连接',
46
50
  })
47
51
 
48
- function bootAimux(rec: LoginRecord): void {
52
+ function bootAimux(rec: LoginRecord, activeClient: MobiusClient): void {
49
53
  // AIMUX installation/connection is deliberately backgrounded: the TUI can
50
54
  // continue into project preparation while a first-time pip install runs.
55
+ const generation = ++aimuxAuthGeneration.current
51
56
  void startAimuxConnection({
52
57
  server: rec.server,
53
58
  token: rec.token,
59
+ refreshToken: async () => {
60
+ const refreshed = await login(rec.server, rec.username, rec.password)
61
+ if (generation !== aimuxAuthGeneration.current) return null
62
+ const updated: LoginRecord = { ...rec, token: refreshed.token, user: refreshed.user }
63
+ await saveLogin(updated)
64
+ activeClient.setToken(refreshed.token)
65
+ setUserId(refreshed.user.id)
66
+ setAuthRevision(value => value + 1)
67
+ return refreshed.token
68
+ },
54
69
  onStatus: (status: AimuxStatus) => {
55
70
  setAimuxStatus(status)
56
71
  if (status.detail) setBootMsg(status.detail)
@@ -58,7 +73,7 @@ export function App() {
58
73
  }).catch((e: any) => setBootMsg(`AIMUX 启动失败: ${e?.message ?? String(e)}`))
59
74
  }
60
75
 
61
- useEffect(() => () => { void stopAimuxConnection() }, [])
76
+ useEffect(() => () => { aimuxAuthGeneration.current += 1; void stopAimuxConnection() }, [])
62
77
 
63
78
  // ── bootstrap ──────────────────────────────────────────────────────────────
64
79
  useEffect(() => { (async () => {
@@ -71,32 +86,32 @@ export function App() {
71
86
  const me = await getMe(rec.server, rec.token)
72
87
  setUserId(me.id)
73
88
  setClient(c); setRoute('prep')
74
- bootAimux(rec)
89
+ bootAimux(rec, c)
75
90
  } catch {
76
91
  // token expired — try to re-login with stored creds
77
- if (rec.password) {
78
- try {
79
- setBootMsg('登录态已过期,重新登录…')
80
- const r = await login(rec.server, rec.username, rec.password)
81
- const updated: LoginRecord = { ...rec, token: r.token, user: r.user }
82
- await saveLogin(updated)
83
- setUserId(r.user.id)
84
- setClient(new MobiusClient(rec.server, r.token))
85
- setRoute('prep')
86
- bootAimux(updated)
87
- return
88
- } catch { /* fall through to login */ }
89
- }
92
+ try {
93
+ setBootMsg('登录态已过期,重新登录…')
94
+ const r = await login(rec.server, rec.username, rec.password)
95
+ const updated: LoginRecord = { ...rec, token: r.token, user: r.user }
96
+ await saveLogin(updated)
97
+ const refreshedClient = new MobiusClient(rec.server, r.token)
98
+ setUserId(r.user.id)
99
+ setClient(refreshedClient)
100
+ setRoute('prep')
101
+ bootAimux(updated, refreshedClient)
102
+ return
103
+ } catch { /* fall through to login */ }
90
104
  setRoute('login')
91
105
  }
92
106
  })() }, [])
93
107
 
94
108
  // ── handlers ───────────────────────────────────────────────────────────────
95
109
  function onLoginSuccess(rec: LoginRecord) {
110
+ const loggedInClient = new MobiusClient(rec.server, rec.token)
96
111
  setUserId(rec.user.id)
97
- setClient(new MobiusClient(rec.server, rec.token))
112
+ setClient(loggedInClient)
98
113
  setRoute('prep')
99
- bootAimux(rec)
114
+ bootAimux(rec, loggedInClient)
100
115
  }
101
116
 
102
117
  function onPrepReady(st: ReadyState) {
@@ -151,6 +166,7 @@ export function App() {
151
166
  }
152
167
 
153
168
  async function onLogout() {
169
+ aimuxAuthGeneration.current += 1
154
170
  if (process.env.MOBIUS_TUI_DEBUG) console.error('[route] logout')
155
171
  try {
156
172
  await clearLogin()
package/src/aimux.ts CHANGED
@@ -5,13 +5,14 @@
5
5
  * aimux on first use, then keep `aimux reverse connect` attached to the
6
6
  * currently authenticated Mobius server. Nothing is started before login.
7
7
  */
8
- import { spawn, spawnSync, type ChildProcess } from 'node:child_process'
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 } from 'node:fs'
10
+ import { promises as fs, existsSync, createWriteStream, mkdirSync, openSync, closeSync } from 'node:fs'
11
11
  import os from 'node:os'
12
12
  import path from 'node:path'
13
13
  import { Readable } from 'node:stream'
14
14
  import extract from 'extract-zip'
15
+ import lockfile from 'proper-lockfile'
15
16
  import { mobiusHome } from './config.js'
16
17
 
17
18
  export type AimuxState = 'starting' | 'connected' | 'failed' | 'stopped' | 'disabled'
@@ -272,6 +273,19 @@ export function spawnLauncher(launcher: AimuxLauncher, args: string[]): ChildPro
272
273
  : spawn(launcher.python, ['-m', 'aimux', ...args], { windowsHide: true })
273
274
  }
274
275
 
276
+ /** 以守护进程形态 spawn aimux:detached(父变 init)+ stdio 重定向到 aimux.log, 不随 TUI 退出而亡。 */
277
+ function spawnDetachedDaemon(launcher: AimuxLauncher, args: string[]): ChildProcess {
278
+ let logFd = -1
279
+ try { mkdirSync(mobiusHome(), { recursive: true }); logFd = openSync(aimuxLogPath(), 'a') } catch { logFd = -1 }
280
+ const stdio: StdioOptions = logFd >= 0 ? ['ignore', logFd, logFd] : 'ignore'
281
+ const child = launcher.kind === 'exe'
282
+ ? spawn(launcher.path, args, { detached: true, stdio, windowsHide: true })
283
+ : spawn(launcher.python, ['-m', 'aimux', ...args], { detached: true, stdio, windowsHide: true })
284
+ if (logFd >= 0) { try { closeSync(logFd) } catch { /* ignore */ } }
285
+ child.unref?.()
286
+ return child
287
+ }
288
+
275
289
  /** test-only 导出: 暴露内部 downloadBundle 以便单测 mock fetch 验证流式下载+进度。 */
276
290
  export const downloadBundleForTest = downloadBundle
277
291
 
@@ -319,15 +333,65 @@ export async function ensureAimux(onProgress?: (p: InstallProgress) => void): Pr
319
333
  return { ok: false, error: `${venvError};内置运行时也失败: ${bundle.error}` }
320
334
  }
321
335
 
322
- export function tuiAimuxIdentifier(hostname = os.hostname(), cwd = process.cwd()): string {
336
+ /** Effective OS user (not `$USER`, which sudo/containers can pollute). */
337
+ function currentUsername(): string {
338
+ try { return os.userInfo().username } catch { return process.env.USER || process.env.USERNAME || 'user' }
339
+ }
340
+
341
+ /** Per (username, workspace) hash — reused by the identifier and the lease/lock filenames. */
342
+ export function aimuxWorkspaceHash(username = currentUsername(), cwd = process.cwd()): string {
343
+ return createHash('sha256').update(`${username}:${path.resolve(cwd)}`).digest('hex').slice(0, 10)
344
+ }
345
+
346
+ export function tuiAimuxIdentifier(hostname = os.hostname(), cwd = process.cwd(), username = currentUsername()): string {
323
347
  const host = hostname.toLowerCase().replace(/[^a-z0-9_.-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 32)
324
- // One machine may run several Mobius TUIs for different projects. A
325
- // hostname-only identifier makes every reverse client register with the
326
- // same name and --replace continuously evicts its siblings ("client
327
- // replaced"). The normalized cwd hash is stable across restarts/resume but
328
- // unique for the common multi-project case.
329
- const workspace = createHash('sha256').update(path.resolve(cwd)).digest('hex').slice(0, 10)
330
- return `tui-${host || 'pc'}-${workspace}`
348
+ // One machine may run several Mobius TUIs for different projects (and for
349
+ // different users). A hostname-only identifier makes every reverse client
350
+ // register with the same name and --replace continuously evicts its siblings.
351
+ // The (username, cwd) hash is stable across restarts/resume but unique per
352
+ // user and per workspace, so separate projects/users never collide.
353
+ return `tui-${host || 'pc'}-${aimuxWorkspaceHash(username, cwd)}`
354
+ }
355
+
356
+ // ── shared-daemon coordination files (one reverse connect per user+workspace) ──
357
+ // The reverse connect is a detached daemon shared by every TUI in the same
358
+ // user+workspace. Two files coordinate it, both under ~/.mobius/aimux-runtime/:
359
+ // <hash>.lease — mtime = "some TUI renewed me recently" (liveness heartbeat);
360
+ // content = the daemon's pid (for dead-process detection).
361
+ // <hash>.lock — short-lived spawn lock (proper-lockfile), so exactly one TUI
362
+ // spawns at a time and a crashed spawner never wedges the lock.
363
+ const LEASE_TIMEOUT_MS = 10 * 60 * 1000 // daemon is orphaned after 10 min without a renew
364
+ const LEASE_RENEW_MS = 5_000 // adopters renew the lease every 5s
365
+
366
+ const aimuxRuntimeDir = () => path.join(mobiusHome(), 'aimux-runtime')
367
+ const leasePath = (hash: string) => path.join(aimuxRuntimeDir(), `${hash}.lease`)
368
+ const lockPath = (hash: string) => path.join(aimuxRuntimeDir(), `${hash}.lock`)
369
+
370
+ async function ensureRuntimeDir(): Promise<void> {
371
+ await fs.mkdir(aimuxRuntimeDir(), { recursive: true, mode: 0o700 })
372
+ }
373
+
374
+ async function writeLease(hash: string, pid: number): Promise<void> {
375
+ await ensureRuntimeDir()
376
+ await fs.writeFile(leasePath(hash), String(pid), { mode: 0o600 })
377
+ }
378
+
379
+ async function readLeasePid(hash: string): Promise<number | null> {
380
+ try {
381
+ const pid = Number.parseInt(await fs.readFile(leasePath(hash), 'utf8'), 10)
382
+ return Number.isInteger(pid) && pid > 0 ? pid : null
383
+ } catch { return null }
384
+ }
385
+
386
+ /** Bump the lease mtime so the daemon sees "someone still wants me". */
387
+ async function touchLease(hash: string): Promise<void> {
388
+ await ensureRuntimeDir()
389
+ const now = new Date()
390
+ try { await fs.utimes(leasePath(hash), now, now) } catch { /* no lease yet (not spawned) */ }
391
+ }
392
+
393
+ function pidAlive(pid: number): boolean {
394
+ try { process.kill(pid, 0); return true } catch { return false }
331
395
  }
332
396
 
333
397
  /**
@@ -389,12 +453,16 @@ export function pickSilentFlag(helpText: string, platform: NodeJS.Platform = pro
389
453
  return null
390
454
  }
391
455
 
392
- export async function probeAimuxBridgeConnection(
456
+ /** Result of a bridge heartbeat: is the stream up, and did the JWT just get rejected? */
457
+ export interface AimuxBridgeProbe { connected: boolean; authError: boolean }
458
+
459
+ /** Heartbeat probe that distinguishes "stream down" from "JWT expired" (401/403). */
460
+ export async function probeAimuxBridge(
393
461
  server: string,
394
462
  token: string,
395
463
  identifier: string,
396
464
  timeoutMs = 4_000,
397
- ): Promise<boolean> {
465
+ ): Promise<AimuxBridgeProbe> {
398
466
  const controller = new AbortController()
399
467
  const timeout = setTimeout(() => controller.abort(), timeoutMs)
400
468
  try {
@@ -402,166 +470,171 @@ export async function probeAimuxBridgeConnection(
402
470
  `${server.replace(/\/$/, '')}/aimux_bridge/api/remotes/${encodeURIComponent(identifier)}/connection`,
403
471
  { headers: { Authorization: `Bearer ${token}` }, signal: controller.signal },
404
472
  )
405
- if (!response.ok) return false
473
+ if (response.status === 401 || response.status === 403) return { connected: false, authError: true }
474
+ if (!response.ok) return { connected: false, authError: false }
406
475
  const data: any = await response.json().catch(() => ({}))
407
- return data?.identifier === identifier && data?.event_stream_connected === true
476
+ return { connected: data?.identifier === identifier && data?.event_stream_connected === true, authError: false }
408
477
  } catch {
409
- return false
478
+ return { connected: false, authError: false }
410
479
  } finally {
411
480
  clearTimeout(timeout)
412
481
  }
413
482
  }
414
483
 
484
+ export async function probeAimuxBridgeConnection(
485
+ server: string,
486
+ token: string,
487
+ identifier: string,
488
+ timeoutMs = 4_000,
489
+ ): Promise<boolean> {
490
+ return (await probeAimuxBridge(server, token, identifier, timeoutMs)).connected
491
+ }
492
+
415
493
  interface SupervisorOptions {
416
494
  server: string
417
495
  token: string
418
496
  identifier: string
419
497
  onStatus: (s: AimuxStatus) => void
498
+ /** Re-authenticate after AIMUX reports an expired/invalid bridge JWT. */
499
+ refreshToken?: () => Promise<string | null>
420
500
  heartbeatIntervalMs?: number
421
- heartbeatFailureThreshold?: number
422
501
  retryBaseMs?: number
423
- probeConnection?: () => Promise<boolean>
424
- spawnProcess?: () => ChildProcess
502
+ probeConnection?: () => Promise<boolean | AimuxBridgeProbe>
503
+ spawnProcess?: (token: string) => ChildProcess
425
504
  }
426
505
 
506
+ /**
507
+ * Coordinates the shared `aimux reverse connect` daemon for one user+workspace.
508
+ *
509
+ * The daemon is spawned detached (survives this TUI) and shared by every TUI in
510
+ * the same user+workspace. Two files under ~/.mobius/aimux-runtime/ coordinate
511
+ * it: a lease (mtime = "a TUI renewed me recently", content = daemon pid) and a
512
+ * short-lived spawn lock (proper-lockfile). A TUI only spawns when no live daemon
513
+ * is found; otherwise it adopts and keeps renewing the lease. The daemon is never
514
+ * killed on TUI exit — it is torn down when the lease expires (handled by aimux).
515
+ */
427
516
  export class AimuxSupervisor {
428
- private child: ChildProcess | null = null
429
517
  private stopping = false
430
- private retry: ReturnType<typeof setTimeout> | null = null
431
- private heartbeatTimer: ReturnType<typeof setTimeout> | null = null
432
- private heartbeatEpoch = 0
433
- private heartbeatFailures = 0
518
+ private refreshingToken = false
434
519
  private reconnectAttempt = 0
435
- private bridgeConnected = false
520
+ private leaseTimer: ReturnType<typeof setTimeout> | null = null
521
+ private probeTimer: ReturnType<typeof setTimeout> | null = null
436
522
  private opts: SupervisorOptions
437
- constructor(opts: SupervisorOptions) { this.opts = opts }
438
- start() { this.stopping = false; this.spawnChild() }
439
- private spawnChild() {
440
- const { server, token, identifier, onStatus } = this.opts
441
- onStatus({ state: 'starting', phase: 'connecting', detail: '正在连接 Mobius AIMUX bridge…', identifier, attempt: this.reconnectAttempt })
442
- const child = this.opts.spawnProcess?.() ?? spawn(
443
- aimuxExe(),
444
- reverseConnectArgs(server, identifier, token),
445
- { windowsHide: true },
446
- )
447
- this.child = child
448
- this.startHeartbeat()
449
- let tail = '' // 缓存 aimux 最近输出, 进程异常退出时带进状态行, 便于诊断(code=1 不再是黑盒)
450
- const logWrite = { queue: Promise.resolve() }
451
- appendAimuxLog(logWrite, `\n===== AIMUX start ${new Date().toISOString()} =====\n`)
452
- appendAimuxLog(logWrite, `server=${server} identifier=${identifier} platform=${process.platform} arch=${process.arch}\n`)
453
- const classify = (buf: Buffer) => {
454
- const text = buf.toString('utf8')
455
- tail = (tail + text).slice(-4000)
456
- appendAimuxLog(logWrite, text)
457
- if (!this.bridgeConnected && /connected|registered|event stream|heartbeat|sse/i.test(text)) {
458
- onStatus({ state: 'starting', phase: 'heartbeat', detail: 'AIMUX 已启动,等待 bridge 心跳确认…', identifier })
459
- } else if (/connection (refused|reset|closed|error)|failed to connect|unauthorized|forbidden|token.*invalid/i.test(text)) {
460
- onStatus({ state: 'failed', phase: 'heartbeat', detail: text.trim().slice(-200), identifier })
461
- }
523
+ private hash: string
524
+ constructor(opts: SupervisorOptions) { this.opts = opts; this.hash = aimuxWorkspaceHash() }
525
+
526
+ async start(): Promise<void> {
527
+ this.stopping = false
528
+ await this.ensureDaemon()
529
+ this.startLeaseRenewal()
530
+ this.scheduleProbe()
531
+ }
532
+
533
+ /** Adopt an existing daemon if one is alive; otherwise spawn (under the lock). */
534
+ private async ensureDaemon(): Promise<void> {
535
+ const pid = await readLeasePid(this.hash)
536
+ if (pid !== null && pidAlive(pid)) {
537
+ this.opts.onStatus({ state: 'starting', phase: 'heartbeat', detail: 'AIMUX 守护进程已在运行,采用中…', identifier: this.opts.identifier })
538
+ return
462
539
  }
463
- child.stdout?.on('data', classify); child.stderr?.on('data', classify)
464
- child.on('error', e => {
465
- appendAimuxLog(logWrite, `\n[spawn error] ${e.stack || e.message}\n`)
466
- onStatus({ state: 'failed', phase: 'retrying', detail: `AIMUX 启动失败: ${e.message} · 日志: ${aimuxLogPath()}`, identifier })
467
- })
468
- child.on('exit', code => {
469
- if (this.child !== child) return
470
- this.child = null
471
- this.stopHeartbeat()
472
- if (this.stopping) { onStatus({ state: 'stopped', phase: 'idle', detail: 'AIMUX 已停止', identifier }); return }
473
- appendAimuxLog(logWrite, `\n===== AIMUX exit code=${code} ${new Date().toISOString()} =====\n`)
474
- const reason = code !== 0 && tail.trim()
475
- ? `AIMUX 进程退出(code=${code}): ${tail.trim().split(/[\r\n]+/).filter(Boolean).slice(-3).join(' ⏎ ').slice(-220)} · 日志: ${aimuxLogPath()}`
476
- : `AIMUX 进程退出(code=${code}) · 日志: ${aimuxLogPath()}`
477
- this.scheduleReconnect(reason)
478
- })
540
+ await this.spawnDaemon()
479
541
  }
480
542
 
481
- private startHeartbeat() {
482
- this.stopHeartbeat()
483
- this.heartbeatFailures = 0
484
- this.bridgeConnected = false
485
- const epoch = ++this.heartbeatEpoch
486
- void this.checkHeartbeat(epoch)
543
+ /** Spawn the detached daemon exactly once, serialized by the path lock. */
544
+ private async spawnDaemon(): Promise<void> {
545
+ await ensureRuntimeDir()
546
+ const release = await lockfile.lock(lockPath(this.hash), {
547
+ stale: 30_000,
548
+ retries: { retries: 30, factor: 1.2, minTimeout: 100, maxTimeout: 1000 },
549
+ }).catch(() => null)
550
+ try {
551
+ // Re-check under the lock — another TUI may have spawned while we waited.
552
+ const pid = await readLeasePid(this.hash)
553
+ if (pid !== null && pidAlive(pid)) return
554
+ const { server, token, identifier, onStatus } = this.opts
555
+ onStatus({ state: 'starting', phase: 'connecting', detail: '正在启动 AIMUX 守护进程…', identifier, attempt: this.reconnectAttempt })
556
+ const child = this.opts.spawnProcess?.(token) ?? spawnDetachedDaemon({ kind: 'exe', path: aimuxExe() }, reverseConnectArgs(server, identifier, token))
557
+ child.on('error', (e: Error) => { appendAimuxLog(installLogQueue, `\n[aimux spawn error] ${e.stack || e.message}\n`) })
558
+ await writeLease(this.hash, child.pid ?? 0)
559
+ child.unref?.()
560
+ this.reconnectAttempt = 0
561
+ } finally {
562
+ if (release) await release()
563
+ }
487
564
  }
488
565
 
489
- private stopHeartbeat() {
490
- this.heartbeatEpoch += 1
491
- if (this.heartbeatTimer) clearTimeout(this.heartbeatTimer)
492
- this.heartbeatTimer = null
566
+ /** Renew the lease every 5s while this TUI is alive. */
567
+ private startLeaseRenewal(): void {
568
+ const tick = () => {
569
+ if (this.stopping) return
570
+ void touchLease(this.hash).catch(() => {})
571
+ this.leaseTimer = setTimeout(tick, LEASE_RENEW_MS)
572
+ }
573
+ void touchLease(this.hash).catch(() => {})
574
+ this.leaseTimer = setTimeout(tick, LEASE_RENEW_MS)
493
575
  }
494
576
 
495
- private async checkHeartbeat(epoch: number): Promise<void> {
496
- const connected = await (this.opts.probeConnection?.() ?? probeAimuxBridgeConnection(this.opts.server, this.opts.token, this.opts.identifier))
497
- if (this.stopping || epoch !== this.heartbeatEpoch || !this.child) return
577
+ private scheduleProbe(): void {
578
+ if (this.stopping) return
579
+ this.probeTimer = setTimeout(() => void this.checkDaemon(), this.opts.heartbeatIntervalMs ?? 5_000)
580
+ }
498
581
 
499
- const threshold = this.opts.heartbeatFailureThreshold ?? 3
500
- if (connected) {
501
- this.heartbeatFailures = 0
582
+ /** Probe the bridge; refresh on auth error, respawn only when the daemon died. */
583
+ private async checkDaemon(): Promise<void> {
584
+ if (this.stopping) return
585
+ const raw = await (this.opts.probeConnection?.() ?? probeAimuxBridge(this.opts.server, this.opts.token, this.opts.identifier))
586
+ const probe: AimuxBridgeProbe = typeof raw === 'boolean' ? { connected: raw, authError: false } : raw
587
+ if (this.stopping) return
588
+ if (probe.authError) {
589
+ await this.refreshCredentials('JWT 已过期')
590
+ } else if (probe.connected) {
502
591
  this.reconnectAttempt = 0
503
- this.bridgeConnected = true
504
- this.opts.onStatus({
505
- state: 'connected', phase: 'connected',
506
- detail: `心跳正常 · ${this.opts.identifier}`,
507
- identifier: this.opts.identifier,
508
- })
592
+ this.opts.onStatus({ state: 'connected', phase: 'connected', detail: `心跳正常 · ${this.opts.identifier}`, identifier: this.opts.identifier })
509
593
  } else {
510
- this.heartbeatFailures += 1
511
- if (this.heartbeatFailures >= threshold) {
512
- this.bridgeConnected = false
513
- await this.restartAfterDisconnect(`bridge 心跳连续 ${this.heartbeatFailures} 次未响应`)
514
- return
594
+ const pid = await readLeasePid(this.hash)
595
+ if (pid === null || !pidAlive(pid)) {
596
+ this.reconnectAttempt += 1
597
+ this.opts.onStatus({ state: 'failed', phase: 'retrying', detail: `AIMUX 守护进程已退出,重连中(第 ${this.reconnectAttempt} 次)…`, identifier: this.opts.identifier, attempt: this.reconnectAttempt })
598
+ await this.spawnDaemon()
599
+ } else {
600
+ // Daemon alive but stream down → transient; its own reconnect handles it.
601
+ this.opts.onStatus({ state: 'starting', phase: 'heartbeat', detail: '等待 bridge 心跳确认…', identifier: this.opts.identifier })
515
602
  }
516
- this.opts.onStatus({
517
- state: 'starting', phase: 'heartbeat',
518
- detail: `等待 bridge 心跳确认(${this.heartbeatFailures}/${threshold})…`,
519
- identifier: this.opts.identifier,
520
- })
521
603
  }
522
- const interval = this.opts.heartbeatIntervalMs ?? 5_000
523
- this.heartbeatTimer = setTimeout(() => void this.checkHeartbeat(epoch), interval)
604
+ this.scheduleProbe()
524
605
  }
525
606
 
526
- private async restartAfterDisconnect(reason: string) {
527
- this.stopHeartbeat()
528
- await this.killChild()
529
- if (!this.stopping) this.scheduleReconnect(reason)
530
- }
531
-
532
- private scheduleReconnect(reason: string) {
533
- if (this.stopping || this.retry) return
534
- this.reconnectAttempt += 1
535
- const base = this.opts.retryBaseMs ?? 1_000
536
- const delay = Math.min(15_000, base * (2 ** Math.min(this.reconnectAttempt - 1, 4)))
537
- const seconds = Math.max(1, Math.ceil(delay / 1_000))
538
- this.opts.onStatus({
539
- state: 'failed', phase: 'retrying',
540
- detail: `${reason},${seconds} 秒后进行第 ${this.reconnectAttempt} 次重连…`,
541
- identifier: this.opts.identifier,
542
- attempt: this.reconnectAttempt,
543
- })
544
- this.retry = setTimeout(() => {
545
- this.retry = null
546
- if (!this.stopping) this.spawnChild()
547
- }, delay)
548
- }
549
-
550
- private async killChild() {
551
- const child = this.child
552
- this.child = null
553
- if (!child?.pid) return
554
- if (WIN) await run('taskkill', ['/PID', String(child.pid), '/T', '/F'])
555
- else try { child.kill('SIGTERM') } catch { /* ignore */ }
607
+ private async refreshCredentials(reason: string): Promise<void> {
608
+ if (this.stopping || this.refreshingToken) return
609
+ const refreshToken = this.opts.refreshToken
610
+ if (!refreshToken) return
611
+ this.refreshingToken = true
612
+ this.opts.onStatus({ state: 'starting', phase: 'retrying', detail: 'AIMUX 登录凭据已过期,正在刷新 JWT…', identifier: this.opts.identifier })
613
+ try {
614
+ const token = await refreshToken()
615
+ if (this.stopping) return
616
+ if (!token) throw new Error('登录接口未返回新 JWT')
617
+ this.opts.token = token
618
+ this.reconnectAttempt = 0
619
+ appendAimuxLog(installLogQueue, `AIMUX JWT refreshed at ${new Date().toISOString()}; restarting bridge client\n`)
620
+ this.opts.onStatus({ state: 'starting', phase: 'connecting', detail: 'JWT 已刷新,正在重新连接 AIMUX bridge…', identifier: this.opts.identifier })
621
+ await this.spawnDaemon()
622
+ } catch {
623
+ // refresh failed → the probe loop will retry on the next tick
624
+ } finally {
625
+ this.refreshingToken = false
626
+ }
556
627
  }
557
628
 
558
- async stop() {
629
+ async stop(): Promise<void> {
559
630
  this.stopping = true
560
- if (this.retry) clearTimeout(this.retry)
561
- this.retry = null
562
- this.stopHeartbeat()
563
- await this.killChild()
564
- this.opts.onStatus({ state: 'stopped', phase: 'idle', detail: 'AIMUX 已停止', identifier: this.opts.identifier })
631
+ if (this.leaseTimer) clearTimeout(this.leaseTimer)
632
+ this.leaseTimer = null
633
+ if (this.probeTimer) clearTimeout(this.probeTimer)
634
+ this.probeTimer = null
635
+ // The daemon is shared: do NOT kill it. It self-terminates when the lease
636
+ // expires (no TUI renewing it for 10 minutes).
637
+ this.opts.onStatus({ state: 'stopped', phase: 'idle', detail: 'AIMUX 已停止(守护进程继续运行)', identifier: this.opts.identifier })
565
638
  }
566
639
  }
567
640
 
@@ -572,7 +645,12 @@ let installing: Promise<void> | null = null
572
645
  // `aimux reverse connect --help`. See reverseConnectArgs for why this is probed.
573
646
  let cachedSilentFlag: string | null | undefined = undefined
574
647
 
575
- export async function startAimuxConnection(opts: { server: string; token: string; onStatus?: (s: AimuxStatus) => void }): Promise<void> {
648
+ export async function startAimuxConnection(opts: {
649
+ server: string
650
+ token: string
651
+ onStatus?: (s: AimuxStatus) => void
652
+ refreshToken?: () => Promise<string | null>
653
+ }): Promise<void> {
576
654
  const onStatus = opts.onStatus ?? (() => {})
577
655
  // Tests and explicitly opted-out users should not spawn a network worker.
578
656
  if (process.env.MOBIUS_TUI_DISABLE_AIMUX === '1') {
@@ -602,10 +680,10 @@ export async function startAimuxConnection(opts: { server: string; token: string
602
680
  }
603
681
  const silentFlag = cachedSilentFlag
604
682
  supervisor = new AimuxSupervisor({
605
- server: opts.server, token: opts.token, identifier, onStatus,
606
- spawnProcess: () => spawnLauncher(launcher, reverseConnectArgs(opts.server, identifier, opts.token, process.platform, silentFlag)),
683
+ server: opts.server, token: opts.token, identifier, onStatus, refreshToken: opts.refreshToken,
684
+ spawnProcess: token => spawnDetachedDaemon(launcher, reverseConnectArgs(opts.server, identifier, token, process.platform, silentFlag)),
607
685
  })
608
- supervisor.start()
686
+ await supervisor.start()
609
687
  })().finally(() => { installing = null })
610
688
  await installing
611
689
  }
@@ -157,7 +157,7 @@ export function ChatScreen({ client, ready, webUserId, resumeSessionId, onClear,
157
157
  // the indicator falls back to the normal Working label for every turn.
158
158
  const firstQueryInFlight = !resumeSessionId && !chat.entries.some(isAssistantOutput)
159
159
 
160
- // 用户输入去重 (对齐 web viewer/rounds.ts buildRounds): codex 同一提问的 3 形态
160
+ // 用户输入去重 (对齐 web viewer/display-dedup.ts): codex 同一提问的 3 形态
161
161
  // (type:user / response_item.message[user] / event_msg.user_message) 合并成 1 条,
162
162
  // 避免在累积视图里把同一条提问显示多次.
163
163
  const dedupedEntries = useMemo(() => dedupeUserEntries(chat.entries), [chat.entries])
@@ -679,7 +679,7 @@ export function toolLabel(name: string): string {
679
679
  return TOOL_LABEL[n] ?? n
680
680
  }
681
681
 
682
- // ── 用户输入去重 (对齐 web viewer/rounds.ts buildRounds) ──────────────────────
682
+ // ── 用户输入去重 (对齐 web viewer/display-dedup.ts) ──────────────────────────
683
683
  // codex 一次用户输入在 jsonl 里以 3 种形态出现 (type:user / response_item.message[role=user]
684
684
  // / event_msg.user_message), 文本相同. 若与上一条用户输入文本相同, 且之间还没出现任何
685
685
  // agent 输出, 则视为同一次输入的重复入口 → 丢弃, 避免 TUI 把同一条提问显示多次.
@@ -735,12 +735,51 @@ export function isAssistantOutput(e: AnyEntry): boolean {
735
735
  return false
736
736
  }
737
737
 
738
+ // 开轮 kind 白名单 (与后端 mobius-kinds.ts 同源; TUI 是独立包, 只能各存一份)
739
+ // Round-opening kinds, same rule as the backend's mobius-kinds.ts (the TUI is a separate package)
740
+ const ROUND_OPENING_KINDS = new Set(['user', 'user-sp-command', 'mobius-multiagent', 'mobius-com', 'mobius-extension'])
741
+ // 来源枚举之前的旧 kind, 让改动前入库的老会话仍能认出自己的开轮卡
742
+ // The kinds used before the enum; they keep openers recognisable in sessions stored back then
743
+ const LEGACY_ROUND_OPENING_KINDS = new Set(['user_input', 'compact'])
744
+
745
+ /*
746
+ * True when this card is the user prompt that opened its round. The kind decides: a session prompt
747
+ * (or a slash command in it) and one 小莫 asks itself open a round, every other kind does not.
748
+ */
749
+ export function isRoundOpenerEntry(e: AnyEntry): boolean {
750
+ // 只认 Mobius 自己写的 user 卡,agent 侧的原生副本没有 mobius 块
751
+ // Only Mobius-authored user cards count, the agent's own copies carry no mobius block
752
+ if (e?.type !== 'user') return false
753
+ const kind = e?.mobius?.kind
754
+ if (typeof kind !== 'string') return false
755
+ return ROUND_OPENING_KINDS.has(kind) || LEGACY_ROUND_OPENING_KINDS.has(kind)
756
+ }
757
+
758
+ /*
759
+ * Drops duplicate user-input entries while keeping the round-opener card. One user input reaches
760
+ * the jsonl in several shapes (type:user / response_item.message[user] / event_msg.user_message)
761
+ * with the same text; the opener is the authoritative one, so every other shape steps aside.
762
+ * The older rule is kept as a fallback for backends that emit no opener card at all.
763
+ */
738
764
  export function dedupeUserEntries(entries: AnyEntry[]): AnyEntry[] {
765
+ // 先收集开轮卡文本,用来判断某条输入是否已由开轮卡承载
766
+ // Collect the opener texts first, they mark inputs already carried by an opener card
767
+ const openerTexts = new Set<string>()
768
+ for (const e of entries) {
769
+ if (!isRoundOpenerEntry(e)) continue
770
+ const text = userTextOf(e)
771
+ if (text) openerTexts.add(text)
772
+ }
739
773
  let lastUserText = ''
740
774
  let seenAssistantAfter = false
741
775
  return entries.filter((e) => {
742
776
  const text = userTextOf(e)
743
777
  if (text) {
778
+ // ✨ 核心:同文的非开轮形态一律让位,开轮卡是这条输入的权威载体
779
+ // ✨ Core: any non-opener form with the same text gives way to the opener card
780
+ if (openerTexts.has(text) && !isRoundOpenerEntry(e)) return false
781
+ // 相邻同文且其间没有 agent 输出,视为同一次输入的重复落盘
782
+ // Same text with no agent output in between is one input landing twice
744
783
  if (text === lastUserText && !seenAssistantAfter) return false
745
784
  lastUserText = text
746
785
  seenAssistantAfter = false