@trans-ai/trans-code 0.4.0 → 0.6.0

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.
@@ -0,0 +1,138 @@
1
+ # transcode 自动更新 Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** REPL 启动时后台静默检查并安装 npm 更新(默认启用,24h 节流),`~/.transcode.json` 可关闭或钉住版本,`transcode upgrade [version]` 支持指定版本。
6
+
7
+ **Architecture:** 决策逻辑全部放两个纯函数(`normalizeAutoUpdate` 在 config.ts、`planAutoUpdate` 在 upgrade.ts),后台执行器 `startAutoUpdate` 是薄壳(读配置 → 纯函数决策 → npm 子进程),notice 经模块级 Promise 传入 REPL 展示横幅。现有 `runUpgrade` 拆出可复用的 `isDevInstall(entry, root)` 守卫。
8
+
9
+ **Tech Stack:** TypeScript + Bun(测试 `bun test`)、ink/React(REPL)、node:child_process(npm 子进程)。
10
+
11
+ **Spec:** `docs/superpowers/specs/2026-11-21-auto-update-design.md`
12
+
13
+ ## Global Constraints
14
+
15
+ - 用户可见文案用中文,横幅格式固定:`⟳ 已自动更新 ${from} → ${to},重启 transcode 生效`
16
+ - 注册表固定官方源 `https://registry.npmjs.org`(复用 upgrade.ts 的 `OFFICIAL` 常量,防镜像假升级)
17
+ - 不新增依赖;`tsc --noEmit` 必须保持零错误;现有 194 个测试保持全绿
18
+ - 环境变量:`TRANSCODE_SKIP_UPDATE=1` 强制关闭自动更新;`TRANSCODE_UPDATE_INTERVAL_HOURS` 覆盖节流时长(默认 24)
19
+ - `lastCheck` 仅在真正查询过 registry 后写回(失败不写,下次启动重试)
20
+ - 测试一律用 `TRANSCODE_CONFIG_PATH` 指向 mkdtemp 临时目录,绝不触碰真实 `~/.transcode.json`
21
+
22
+ ## Review Focus
23
+
24
+ 1. registry 不可达/超时 → 静默跳过且不写 `lastCheck` — Task 2 测 `unknown-latest`;Task 3 测 `disabled` 快速返回 null(网络路径靠 catch 兜底,Task 6 手动断网验证)
25
+ 2. `autoUpdate` 为非法值(数字、字符串 `"yes"`、数组)→ 按默认启用处理,不抛错 — Task 1
26
+ 3. 节流边界:距上次检查恰好 ≥ interval 才放行 — Task 2
27
+ 4. 钉住版本 == 当前版本 → 不安装(含 `latest` == 当前)— Task 2
28
+ 5. 仓库开发安装(bun link / checkout,entry 不在 npm root 下)→ 后台路径静默退出 — Task 3 对 `isDevInstall(entry, root)` 用 tmp 目录测两侧
29
+
30
+ ---
31
+
32
+ ### Task 1: `normalizeAutoUpdate` 配置规范化
33
+
34
+ **Files:**
35
+ - Modify: `src/config.ts`
36
+ - Test: `src/config.test.ts`(新建)
37
+
38
+ **Interfaces:**
39
+ - Produces:
40
+ ```ts
41
+ export interface AutoUpdateConfig {
42
+ enabled?: boolean;
43
+ target?: string; // 'latest'(缺省)或具体版本号
44
+ lastCheck?: number; // epoch ms
45
+ }
46
+ // TranscodeConfig 增加: autoUpdate?: boolean | AutoUpdateConfig
47
+ export interface NormalizedAutoUpdate { enabled: boolean; target: string; lastCheck: number }
48
+ export function normalizeAutoUpdate(raw: unknown): NormalizedAutoUpdate
49
+ ```
50
+ 规则:`false` → `{enabled:false, target:'latest', lastCheck:0}`;`undefined` → 默认启用;对象取字段(`enabled` 缺省 true,`target` 缺省 `'latest'`,`lastCheck` 缺省 0);其余任何类型(数字/字符串/数组/null)→ 默认启用形。
51
+
52
+ - [ ] **Step 1: 写失败测试** — `src/config.test.ts`,`bun:test` 风格(参考 `src/screens/submit.test.ts`),describe `normalizeAutoUpdate`:false→关闭;undefined→enabled true;空对象→`{true,'latest',0}`;`{enabled:false,target:'0.3.0'}`→保留 target;`{enabled:true,target:'0.3.0',lastCheck:123}`→原样;非法值(`"yes"`、`5`、`null`、`[]`)→默认启用形
53
+ - [ ] **Step 2: 跑测确认失败** — `bun test src/config.test.ts` → Cannot find module 或 fail
54
+ - [ ] **Step 3: 实现** — config.ts 加类型 + `normalizeAutoUpdate`(纯函数,不碰 fs)
55
+ - [ ] **Step 4: 跑测通过** — `bun test src/config.test.ts` 全绿
56
+ - [ ] **Step 5: Commit** — `feat: normalizeAutoUpdate config parsing`
57
+
58
+ ### Task 2: `planAutoUpdate` 决策纯函数
59
+
60
+ **Files:**
61
+ - Modify: `src/upgrade.ts`
62
+ - Test: `src/upgrade.test.ts`(新建)
63
+
64
+ **Interfaces:**
65
+ - Consumes: Task 1 的 `NormalizedAutoUpdate`(仅形状)
66
+ - Produces:
67
+ ```ts
68
+ export type AutoUpdatePlan =
69
+ | { action: 'skip'; reason: 'env-skip' | 'disabled' | 'throttled' | 'up-to-date' | 'unknown-latest' }
70
+ | { action: 'install'; spec: string; from: string; to: string };
71
+ export function planAutoUpdate(input: {
72
+ current: string; latest: string | null; target: string;
73
+ enabled: boolean; lastCheck: number; now: number;
74
+ intervalHours?: number; envSkip?: boolean;
75
+ }): AutoUpdatePlan
76
+ ```
77
+ 顺序:envSkip→`env-skip`;!enabled→`disabled`;`now - lastCheck < (intervalHours ?? 24) * 3600_000`→`throttled`;target==='latest':latest null→`unknown-latest`,===current→`up-to-date`,否则 install `@trans-ai/trans-code@latest`;具体 target:===current→`up-to-date`,否则 install `@trans-ai/trans-code@${target}`(允许降级)。`spec` 含包名全名。
78
+
79
+ - [ ] **Step 1: 写失败测试** — describe `planAutoUpdate`:env-skip 优先于一切;disabled;throttled(差 1ms 也拦);边界 `now-lastCheck === interval` 放行;latest 模式 unknown-latest / up-to-date / install;pin 模式相同版本跳过、不同版本(含降级 0.4.0→0.3.0)install 且 spec 正确
80
+ - [ ] **Step 2: 跑测确认失败**
81
+ - [ ] **Step 3: 实现** — upgrade.ts 顶部导出纯函数
82
+ - [ ] **Step 4: 跑测通过**
83
+ - [ ] **Step 5: Commit** — `feat: planAutoUpdate decision function`
84
+
85
+ ### Task 3: `isDevInstall` 守卫 + `startAutoUpdate` 后台执行
86
+
87
+ **Files:**
88
+ - Modify: `src/upgrade.ts`(从 `runUpgrade` 中抽出守卫)
89
+ - Test: `src/upgrade.test.ts`(追加)
90
+
91
+ **Interfaces:**
92
+ - Consumes: Task 1 `normalizeAutoUpdate`、Task 2 `planAutoUpdate`
93
+ - Produces:
94
+ ```ts
95
+ export function isDevInstall(entryPath: string, npmRoot: string): boolean // 双参纯化,realpath 归一后前缀比较
96
+ export function autoUpdateNotice(): Promise<string | null> // 未启动时 resolve null
97
+ export function startAutoUpdate(): void // 仅 REPL 路径调用;fire-and-forget
98
+ ```
99
+ `startAutoUpdate` 内部:临时 `TRANSCODE_CONFIG_PATH` 读配置 → normalize → envSkip → dev-install(`isDevInstall(realpathSync(fileURLToPath(import.meta.url)), await npmRoot())`)→ `target !== 'latest'` 时 `latest = target`,否则 `latestVersion()` → `planAutoUpdate` → skip 则 notice=null;install 则 `npm i -g ${spec} --registry=OFFICIAL`,成功后 notice=`⟳ 已自动更新 ${current} → ${installed ?? to},重启 transcode 生效` 并写回 lastCheck=now(skip 的 throttled/disabled 不写);任何异常 catch → notice=null。`autoUpdateNotice()` 返回模块级已 settle/settling 的 promise(`startAutoUpdate` 未调用时为 `Promise.resolve(null)`)。
100
+ - [ ] **Step 1: 写失败测试** — `isDevInstall`:mkdtemp 建 `root/pkg/entry.js`(同侧 false)与 root 外文件(true);`autoUpdateNotice`:未调用时 resolve null;`startAutoUpdate`(`TRANSCODE_CONFIG_PATH` 指临时配置写 `"autoUpdate": false`)→ notice 快速 resolve null 且不产生 npm 子进程(用 disabled 短路保证)
101
+ - [ ] **Step 2: 跑测确认失败**
102
+ - [ ] **Step 3: 实现** — 抽 `isDevInstall` 并让 `runUpgrade` 复用;实现 `startAutoUpdate`/`autoUpdateNotice`
103
+ - [ ] **Step 4: 跑测通过 + 全套回归** — `bun test`(194+新增)全绿
104
+ - [ ] **Step 5: Commit** — `feat: background auto-update with silent install`
105
+
106
+ ### Task 4: `runUpgrade(target?)` 与 cli 子命令
107
+
108
+ **Files:**
109
+ - Modify: `src/upgrade.ts:61`(`runUpgrade` 签名加 `target?: string`)、`src/cli.ts:50-54`、`src/cli.ts` USAGE
110
+
111
+ **Interfaces:**
112
+ - Consumes: Task 3 `isDevInstall`
113
+ - Produces: `runUpgrade(target?: string): Promise<void>` — 有 target 时跳过 latest 比对直接装 `PKG@target`(仍走 dev-install 守卫与官方源),输出 `Upgrading ${VERSION} → ${target}…`
114
+ - [ ] **Step 1: 实现** — cli.ts:`const target = rest[0]; await runUpgrade(target)`;USAGE 第 8 行改为 `transcode upgrade [version] Upgrade to the latest or a specific version`
115
+ - [ ] **Step 2: 验证** — `bun run typecheck` 零错误;`bun test` 全绿
116
+ - [ ] **Step 3: 手动冒烟** — `bun bin/transcode.ts --help` 输出含 `upgrade [version]`
117
+ - [ ] **Step 4: Commit** — `feat: upgrade to a specific version`
118
+
119
+ ### Task 5: REPL 接入与更新横幅
120
+
121
+ **Files:**
122
+ - Modify: `src/cli.ts`(REPL 分支先 `startAutoUpdate()`)、`src/main.tsx:53`、`src/screens/REPL.tsx:51`(props)+ 新增 useEffect
123
+
124
+ **Interfaces:**
125
+ - Consumes: Task 3 `autoUpdateNotice`
126
+ - Produces: `REPLProps` 增加 `updateNotice?: Promise<string | null>`;App 传 `autoUpdateNotice()`
127
+ - [ ] **Step 1: 实现** — cli.ts REPL 分支(`await import('./main.js')` 前)调 `startAutoUpdate()`(acp/upgrade 分支不调);main.tsx 传入;REPL 挂载时 `void updateNotice?.then(msg => { if (msg) { addHistory({input:'', output: msg}); dragFlush(); } })`,deps `[updateNotice]`
128
+ - [ ] **Step 2: 验证** — `bun run typecheck`;`bun test` 全绿
129
+ - [ ] **Step 3: Commit** — `feat: wire auto-update banner into the REPL`
130
+
131
+ ### Task 6: E2E 验证与全局重装
132
+
133
+ **Files:** 无新改动(验证任务)
134
+
135
+ - [ ] **Step 1: 节流验证** — 临时配置 `lastCheck` = 当前时间 → `timeout 15 bun bin/transcode.ts` 启动退出,确认无 npm 安装输出、`lastCheck` 未变
136
+ - [ ] **Step 2: 钉版本验证** — 临时配置 `{"target":"0.3.0","lastCheck":0}`,`TRANSCODE_CONFIG_PATH=… timeout 60 bun bin/transcode.ts`,确认横幅与全局降至 0.3.0(`transcode --version`);随后 `npm i -g .` 恢复开发版本
137
+ - [ ] **Step 3: 断网/强制关验证** — `TRANSCODE_SKIP_UPDATE=1` 启动无更新动作;配置 enabled:false 同样静默
138
+ - [ ] **Step 4: 全局重装收尾** — `npm i -g .`;`bun test` + `bun run typecheck` 最后确认
@@ -0,0 +1,61 @@
1
+ # transcode 自动更新 — 设计
2
+
3
+ 日期:2026-11-21 · 状态:待确认
4
+
5
+ ## 意图
6
+
7
+ 用户启动 transcode 时自动保持 npm 全局安装为最新(或配置指定的版本),无需手动 `transcode upgrade`。默认启用,可在 `~/.transcode.json` 关闭或钉住版本。
8
+
9
+ ## 现有基础
10
+
11
+ `src/upgrade.ts` 已有手动 `transcode upgrade`:查 npm 官方源(防镜像假升级)、版本比对、`npm i -g` 安装、仓库开发安装识别。本设计将其拆出可复用的检查/安装原语。
12
+
13
+ ## 行为设计(已确认:静默安装)
14
+
15
+ **触发**:仅 REPL 启动路径(`cli.ts` 进 REPL 前);`acp` / `--version` / `help` / `upgrade` 子命令不触发。
16
+
17
+ **流程**:后台异步执行,绝不阻塞 REPL 启动——
18
+ 1. 读取配置,未启用 → 退出(静默)
19
+ 2. 节流:距上次检查 <24h → 退出(`TRANSCODE_UPDATE_INTERVAL_HOURS` 可调,`TRANSCODE_SKIP_UPDATE=1` 强制关闭)
20
+ 3. 仓库开发安装(realpath 不在 npm root 下)→ 静默退出
21
+ 4. 查目标版本:`target` 缺省 = `latest`;指定版本(如 `0.3.0`)= 钉住该版本(含降级)
22
+ 5. 目标 ≠ 当前版本 → 静默 `npm i -g @trans-ai/trans-code@<target>`(官方源)
23
+ 6. 完成/失败均不中断会话;成功后 REPL 内横幅一条:`⟳ 已自动更新 0.4.0 → 0.4.1,重启 transcode 生效`;失败静默(`TRANSCODE_DEBUG_UPGRADE=1` 可见原因)
24
+ 7. 写回 `lastCheck` 时间戳
25
+
26
+ 当前会话继续运行旧代码(新版本下次启动生效),避免运行中换文件。
27
+
28
+ ## 配置(`~/.transcode.json`)
29
+
30
+ ```json
31
+ {
32
+ "autoUpdate": {
33
+ "enabled": true, // 缺省 true;"autoUpdate": false 为关闭简写
34
+ "target": "latest", // 或 "0.3.0" 钉住指定版本(含降级)
35
+ "lastCheck": 0 // 内部节流缓存,epoch ms
36
+ }
37
+ }
38
+ ```
39
+
40
+ ## 手动命令
41
+
42
+ `transcode upgrade [version]` — 带版本号参数时安装指定版本(一次性,不写 target),其余行为不变。
43
+
44
+ ## 模块划分
45
+
46
+ - `config.ts`:`TranscodeConfig.autoUpdate?: boolean | { enabled?; target?; lastCheck? }` + `normalizeAutoUpdate()` 纯函数(false/对象/缺省 → 规范形)
47
+ - `upgrade.ts`:`planAutoUpdate()` 纯函数(输入 current/latest/config/now → 输出 skip 原因或 install spec);`startAutoUpdate()` 后台执行并返回 notice Promise;`runUpgrade(target?)` 接受版本参数
48
+ - `cli.ts`:REPL 分支先 `startAutoUpdate()`,notice 以 Promise 传入 REPL,完成时 `addHistory` 横幅
49
+ - `main.tsx` / `REPL.tsx`:接受可选 notice prop,resolve 后展示
50
+
51
+ ## 非目标
52
+
53
+ - 不做定时器/会话中周期检查(仅启动时)
54
+ - 不做更新日志/变更说明展示
55
+ - 不覆盖 `TRANSCODE_SKIP_UPDATE=1`
56
+
57
+ ## 测试(TDD)
58
+
59
+ - `normalizeAutoUpdate`:false / 对象 / 缺省 / 非法值 → 规范形(enabled 默认 true)
60
+ - `planAutoUpdate`:未启用、节流中、已是目标版本、钉版本降级、升级、查不到版本 → 各自 action
61
+ - 现有 186+ 测试保持全绿
@@ -0,0 +1,31 @@
1
+ # 先输 key 再选模型 — 设计
2
+
3
+ 日期:2026-11-21 · 状态:已确认(会话内)
4
+
5
+ ## 意图
6
+
7
+ 内置厂商的 /models 流程改为"key 优先":首次使用先输 key,再展示**线上实时**模型列表,避免首次用户只看到可能过期的 curated 兜底。对齐 custom 网关流程已有的顺序(baseurl → key → live 列表)。
8
+
9
+ ## 行为
10
+
11
+ ```
12
+ /models → 选厂商(非 custom)
13
+ ├─ 已存 key → 直接进模型列表(实时拉取,现行为不变)
14
+ └─ 无 key → 先提示 apikey> → 用该 key 拉实时列表 → 选模型
15
+ ```
16
+
17
+ - 首次输入的 key 只存内存草稿,`applyModelSwitch` 验证通过才落盘(Esc 中途退出不留未验证 key)
18
+ - 选完模型:若 key 是本流程刚输的 → 直接验证(不重复问);老用户 → 保留现有"回车沿用"确认步(key 轮换入口不丢)
19
+ - 实时拉取失败/超时 → curated 兜底 + 提示行"(本地列表 · 保存 key 后显示线上实时列表)"
20
+
21
+ ## 同批打磨项
22
+
23
+ - A 新者优先排序:`listEndpointModels` 按版本号降序(数值段逐位比较,同版本基础名在前)
24
+ - B 切换提示:verify 探测到的实际模型与所选不符时,切换行追加"(实际生效 X)";`verifyModel` 返回值新增 `served` 字段
25
+ - C 兜底提示:`model_pick` 显示 curated 时标注本地列表来源
26
+
27
+ ## 测试
28
+
29
+ - A:model-list.test.ts 断言代表性集合的新者排序
30
+ - B:provider.test.ts 断言 `served` 返回与提示组合
31
+ - 流程重排为 REPL 状态机改动,靠 typecheck + 全套回归 + 手动验证
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trans-ai/trans-code",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "AI-powered multi-model coding CLI",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
package/src/cli.ts CHANGED
@@ -5,7 +5,7 @@ const USAGE = `transcode v${VERSION}
5
5
  Usage:
6
6
  transcode Start the interactive REPL
7
7
  transcode acp Start the ACP stdio server (for transonce, multica and other ACP clients)
8
- transcode upgrade Upgrade the npm global install to the latest version
8
+ transcode upgrade [version] Upgrade the npm global install to the latest or a specific version
9
9
  transcode --version Print the version
10
10
  transcode --help Show this help
11
11
 
@@ -48,8 +48,9 @@ export async function runCli(argv: string[]): Promise<void> {
48
48
  }
49
49
 
50
50
  if (command === 'upgrade' || command === 'update') {
51
+ const target = rest.find(arg => !arg.startsWith('-'));
51
52
  const { runUpgrade } = await import('./upgrade.js');
52
- await runUpgrade();
53
+ await runUpgrade(target);
53
54
  return;
54
55
  }
55
56
 
@@ -59,6 +60,9 @@ export async function runCli(argv: string[]): Promise<void> {
59
60
  return;
60
61
  }
61
62
 
62
- // Default: interactive Ink REPL.
63
+ // Default: interactive Ink REPL. The auto-update runs in the background;
64
+ // its notice reaches the REPL through autoUpdateNotice() once settled.
65
+ const { startAutoUpdate } = await import('./upgrade.js');
66
+ startAutoUpdate();
63
67
  await import('./main.js');
64
68
  }
@@ -0,0 +1,49 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { normalizeAutoUpdate } from './config.js';
3
+
4
+ describe('normalizeAutoUpdate', () => {
5
+ test('false disables auto-update, keeping default target and lastCheck', () => {
6
+ expect(normalizeAutoUpdate(false)).toEqual({
7
+ enabled: false,
8
+ target: 'latest',
9
+ lastCheck: 0,
10
+ });
11
+ });
12
+
13
+ test('undefined (no config) defaults to enabled', () => {
14
+ expect(normalizeAutoUpdate(undefined)).toEqual({
15
+ enabled: true,
16
+ target: 'latest',
17
+ lastCheck: 0,
18
+ });
19
+ });
20
+
21
+ test('an empty object keeps defaults (enabled, latest, 0)', () => {
22
+ expect(normalizeAutoUpdate({})).toEqual({
23
+ enabled: true,
24
+ target: 'latest',
25
+ lastCheck: 0,
26
+ });
27
+ });
28
+
29
+ test('an object preserves its fields', () => {
30
+ expect(normalizeAutoUpdate({ enabled: false, target: '0.3.0' })).toEqual({
31
+ enabled: false,
32
+ target: '0.3.0',
33
+ lastCheck: 0,
34
+ });
35
+ expect(
36
+ normalizeAutoUpdate({ enabled: true, target: '0.3.0', lastCheck: 123 }),
37
+ ).toEqual({ enabled: true, target: '0.3.0', lastCheck: 123 });
38
+ });
39
+
40
+ test('invalid values fall back to the enabled default instead of throwing', () => {
41
+ for (const raw of ['yes', 5, null, [true]]) {
42
+ expect(normalizeAutoUpdate(raw)).toEqual({
43
+ enabled: true,
44
+ target: 'latest',
45
+ lastCheck: 0,
46
+ });
47
+ }
48
+ });
49
+ });
package/src/config.ts CHANGED
@@ -21,6 +21,48 @@ export interface TranscodeConfig {
21
21
  profiles?: Record<string, ProfileConfig>;
22
22
  /** Role → profile routing (default / analysis / design / vision / …). */
23
23
  routing?: Record<string, string>;
24
+ /** Auto-update on startup: `false` disables, an object configures it. */
25
+ autoUpdate?: boolean | AutoUpdateConfig;
26
+ }
27
+
28
+ /** Raw (on-disk) shape of the autoUpdate config block. */
29
+ export interface AutoUpdateConfig {
30
+ enabled?: boolean;
31
+ /** Registry version to stay at; defaults to 'latest'. */
32
+ target?: string;
33
+ /** Epoch ms of the last registry check; internal throttle cache. */
34
+ lastCheck?: number;
35
+ }
36
+
37
+ /** Normalized form used by the updater. */
38
+ export interface NormalizedAutoUpdate {
39
+ enabled: boolean;
40
+ target: string;
41
+ lastCheck: number;
42
+ }
43
+
44
+ const DEFAULT_AUTO_UPDATE: NormalizedAutoUpdate = {
45
+ enabled: true,
46
+ target: 'latest',
47
+ lastCheck: 0,
48
+ };
49
+
50
+ /**
51
+ * Normalizes the raw autoUpdate config value. Anything unrecognizable
52
+ * (wrong type, null, arrays) falls back to the enabled default rather
53
+ * than throwing — a bad config must never break startup.
54
+ */
55
+ export function normalizeAutoUpdate(raw: unknown): NormalizedAutoUpdate {
56
+ if (raw === false) return { ...DEFAULT_AUTO_UPDATE, enabled: false };
57
+ if (raw === null || raw === undefined || typeof raw !== 'object' || Array.isArray(raw)) {
58
+ return { ...DEFAULT_AUTO_UPDATE };
59
+ }
60
+ const obj = raw as AutoUpdateConfig;
61
+ return {
62
+ enabled: typeof obj.enabled === 'boolean' ? obj.enabled : true,
63
+ target: typeof obj.target === 'string' && obj.target ? obj.target : 'latest',
64
+ lastCheck: typeof obj.lastCheck === 'number' ? obj.lastCheck : 0,
65
+ };
24
66
  }
25
67
 
26
68
  // Overridable so tests never touch the user's real ~/.transcode.json.
package/src/main.tsx CHANGED
@@ -5,6 +5,7 @@ import { type CommandContext } from './commands.js';
5
5
  import REPL from './screens/REPL.js';
6
6
  import { bannerLines } from './screens/banner.js';
7
7
  import { createKeyedStdin } from './tui/keyed-stdin.js';
8
+ import { autoUpdateNotice } from './upgrade.js';
8
9
  import { VERSION } from './version.js';
9
10
  const DEFAULT_MODEL: string = preferredModelId() ?? 'opus';
10
11
 
@@ -50,7 +51,7 @@ function App() {
50
51
  <Box flexDirection="column">
51
52
  {/* A saved model choice (from the models flow) wins over the env label */}
52
53
  <Banner modelId={modelId} cwd={cwd} envLabel={preferredModelId() ? undefined : envModelLabel()} />
53
- <REPL ctx={ctx} />
54
+ <REPL ctx={ctx} updateNotice={autoUpdateNotice()} />
54
55
  </Box>
55
56
  );
56
57
  }
@@ -31,7 +31,7 @@ function stubModelsEndpoint(ids: string[]): string {
31
31
  }
32
32
 
33
33
  describe('listEndpointModels', () => {
34
- test('fetches the live model list from the endpoint', async () => {
34
+ test('fetches the live model list from the endpoint, newest generation first', async () => {
35
35
  const baseUrl = stubModelsEndpoint(['glm-5.1', 'glm-4.6', 'glm-5.3-flash']);
36
36
  const { saveConfig } = await import('../config.js');
37
37
  saveConfig({
@@ -40,13 +40,41 @@ describe('listEndpointModels', () => {
40
40
  });
41
41
 
42
42
  const models = await listEndpointModels('myhub');
43
- expect(models).toEqual(['glm-4.6', 'glm-5.1', 'glm-5.3-flash']); // sorted
43
+ expect(models).toEqual(['glm-5.3-flash', 'glm-5.1', 'glm-4.6']); // newest first
44
+ });
45
+
46
+ test('orders newest generation first: base name before variants, variants before older lines', async () => {
47
+ const baseUrl = stubModelsEndpoint([
48
+ 'glm-4.5-air',
49
+ 'glm-5.3-flashx-legal',
50
+ 'glm-4.6',
51
+ 'glm-5.3',
52
+ 'glm-5.3-flashx',
53
+ 'glm-5.3-flash',
54
+ 'glm-5-turbo',
55
+ ]);
56
+ const { saveConfig } = await import('../config.js');
57
+ saveConfig({
58
+ apiKeys: { custom: 'k' },
59
+ profiles: { gen: { baseUrl, model: 'glm-4.6', keyId: 'custom' } },
60
+ });
61
+
62
+ const models = await listEndpointModels('gen');
63
+ expect(models).toEqual([
64
+ 'glm-5.3',
65
+ 'glm-5.3-flash',
66
+ 'glm-5.3-flashx',
67
+ 'glm-5.3-flashx-legal',
68
+ 'glm-5-turbo',
69
+ 'glm-4.6',
70
+ 'glm-4.5-air',
71
+ ]);
44
72
  });
45
73
 
46
74
  test('override form queries an unsaved custom gateway with its key', async () => {
47
75
  const baseUrl = stubModelsEndpoint(['m1', 'm2']);
48
76
  const models = await listEndpointModels('', { baseUrl, apiKey: 'k' });
49
- expect(models).toEqual(['m1', 'm2']);
77
+ expect(models).toEqual(['m2', 'm1']); // newest-first heuristic: m2 > m1
50
78
  });
51
79
 
52
80
  test('returns an empty list on failure so callers can fall back', async () => {
@@ -13,6 +13,7 @@ import {
13
13
  vendorModelSpec,
14
14
  vendorModels,
15
15
  verifyModel,
16
+ switchNote,
16
17
  } from './provider.js';
17
18
 
18
19
  let configDir: string;
@@ -45,7 +46,7 @@ describe('GLM Coding Plan preset', () => {
45
46
  registerApiKey('glmc', 'test-key');
46
47
  const provider = createModel('glmc');
47
48
  expect(provider.config.baseUrl).toContain('/api/coding/');
48
- expect(provider.config.model).toBe('glm-4.6');
49
+ expect(provider.config.model).toBe('glm-5.3');
49
50
  });
50
51
 
51
52
  test('appears in the model list for /models', () => {
@@ -64,8 +65,30 @@ describe('vendor model lists', () => {
64
65
 
65
66
  test('glm lists the current model line', () => {
66
67
  const glm = vendorModels('glm');
68
+ // The glm-5.x generation is what the endpoints actually serve now;
69
+ // glm-4.6/4.5 live on as server-side aliases. glm-4-flash is retired.
70
+ expect(glm).toContain('glm-5.3');
71
+ expect(glm).toContain('glm-5.3-flash');
67
72
  expect(glm).toContain('glm-4.6');
68
- expect(glm).toContain('glm-4.5');
73
+ expect(glm).not.toContain('glm-4-flash');
74
+ });
75
+
76
+ test('glmc lists the current model line of the coding endpoint', () => {
77
+ const glmc = vendorModels('glmc');
78
+ expect(glmc).toContain('glm-5.3');
79
+ expect(glmc).toContain('glm-5.3-flash');
80
+ expect(glmc).toContain('glm-4.6');
81
+ });
82
+
83
+ test('registry defaults resolve to models the endpoints actually serve', () => {
84
+ expect(resolveModel('glm').model).toBe('glm-5.3');
85
+ expect(resolveModel('glmc').model).toBe('glm-5.3');
86
+ });
87
+
88
+ test('deepseek lists the current model line', () => {
89
+ const deepseek = vendorModels('deepseek');
90
+ expect(deepseek).toContain('deepseek-v4-pro');
91
+ expect(deepseek).toContain('deepseek-flash');
69
92
  });
70
93
 
71
94
  test('spec mapping routes registry ids to provider prefixes', () => {
@@ -115,3 +138,16 @@ describe('verifyModel', () => {
115
138
  expect(result.message).toMatch(/key/i);
116
139
  });
117
140
  });
141
+
142
+ describe('switchNote', () => {
143
+ test('plain switch line when the endpoint serves the picked name', () => {
144
+ expect(switchNote('glmc/glm-5.3', 'glm-5.3', 'glm-5.3')).toBe('已切换到 glmc/glm-5.3');
145
+ expect(switchNote('glmc/glm-5.3', 'glm-5.3', undefined)).toBe('已切换到 glmc/glm-5.3');
146
+ });
147
+
148
+ test('appends the effectively served model when it differs from the pick', () => {
149
+ expect(switchNote('glmc/glm-4.6', 'glm-4.6', 'glm-5.3-flash')).toBe(
150
+ '已切换到 glmc/glm-4.6(实际生效 glm-5.3-flash)',
151
+ );
152
+ });
153
+ });
@@ -44,9 +44,9 @@ const MODEL_REGISTRY: Record<ModelId, ModelConfig> = {
44
44
  envKey: 'DEEPSEEK_API_KEY',
45
45
  },
46
46
  glm: {
47
- name: 'GLM-4',
47
+ name: 'GLM',
48
48
  provider: 'openai',
49
- model: 'glm-4',
49
+ model: 'glm-5.3',
50
50
  baseUrl: 'https://open.bigmodel.cn/api/paas/v4',
51
51
  envKey: 'GLM_API_KEY',
52
52
  },
@@ -56,7 +56,7 @@ const MODEL_REGISTRY: Record<ModelId, ModelConfig> = {
56
56
  // The GLM Coding Plan subscription only bills against the dedicated
57
57
  // coding endpoint; the standard /api/paas/v4 endpoint answers 429
58
58
  // "余额不足或无可用资源包" because the plan is not applied there.
59
- model: 'glm-4.6',
59
+ model: 'glm-5.3',
60
60
  baseUrl: 'https://open.bigmodel.cn/api/coding/paas/v4',
61
61
  envKey: 'GLM_API_KEY',
62
62
  },
@@ -87,9 +87,9 @@ const MODEL_REGISTRY: Record<ModelId, ModelConfig> = {
87
87
  const VENDOR_MODELS: Partial<Record<ModelId, string[]>> = {
88
88
  opus: ['claude-opus-4-20250514', 'claude-sonnet-4-20250514'],
89
89
  gpt: ['gpt-4o', 'gpt-4o-mini'],
90
- deepseek: ['deepseek-chat', 'deepseek-reasoner'],
91
- glm: ['glm-4.6', 'glm-4.5', 'glm-4.5-air', 'glm-4-flash'],
92
- glmc: ['glm-4.6', 'glm-4.5'],
90
+ deepseek: ['deepseek-v4-pro', 'deepseek-flash'],
91
+ glm: ['glm-5.3', 'glm-5.3-flash', 'glm-5.2', 'glm-5.1', 'glm-4.6', 'glm-4.5', 'glm-4.5-air'],
92
+ glmc: ['glm-5.3', 'glm-5.3-flash', 'glm-5.2', 'glm-4.6', 'glm-4.5'],
93
93
  minimax: ['MiniMax-Text-01'],
94
94
  kimi: ['moonshot-v1-128k', 'moonshot-v1-8k'],
95
95
  };
@@ -462,7 +462,7 @@ function buildChatModel(
462
462
  export async function verifyModel(
463
463
  spec: string,
464
464
  apiKeyOverride?: string,
465
- ): Promise<{ ok: boolean; message: string }> {
465
+ ): Promise<{ ok: boolean; message: string; served?: string }> {
466
466
  const resolved = resolveModel(spec);
467
467
  const apiKey = apiKeyOverride?.trim() || lookupApiKey(resolved.id);
468
468
  if (!apiKey) {
@@ -481,6 +481,7 @@ export async function verifyModel(
481
481
  const served = response?.response_metadata?.model_name;
482
482
  return {
483
483
  ok: true,
484
+ served,
484
485
  message: `连通正常${served ? `(实际模型 ${served})` : ''}`,
485
486
  };
486
487
  } catch (error) {
@@ -489,6 +490,18 @@ export async function verifyModel(
489
490
  }
490
491
  }
491
492
 
493
+ /**
494
+ * Switch-line copy for applyModelSwitch: appends the effectively served
495
+ * model when the gateway maps the picked name onto a different one
496
+ * (e.g. glm-4.6 → glm-5.3-flash).
497
+ */
498
+ export function switchNote(displayName: string, pickedModel: string, served?: string): string {
499
+ if (served && served !== pickedModel) {
500
+ return `已切换到 ${displayName}(实际生效 ${served})`;
501
+ }
502
+ return `已切换到 ${displayName}`;
503
+ }
504
+
492
505
  /** @deprecated Use createModel instead. Kept for the existing REPL. */
493
506
  export function createProviderWithKey(id: string, apiKey: string): TransProvider {
494
507
  const config = MODEL_REGISTRY[id as ModelId];
@@ -581,6 +594,25 @@ export function getRouting(): Record<string, string> {
581
594
  return { ...(loadConfig().routing ?? {}) };
582
595
  }
583
596
 
597
+ /**
598
+ * Newest-generation-first ordering for a live model list: numeric runs
599
+ * compare pairwise, descending ('glm-5.3' > 'glm-4.6' > 'glm-4.5-air');
600
+ * on a version tie the shorter base name leads ('glm-5.3' before
601
+ * 'glm-5.3-flashx'), then alphabetical.
602
+ */
603
+ function newestFirst(a: string, b: string): number {
604
+ const digits = (s: string): number[] => (s.match(/\d+/g) ?? []).map(Number);
605
+ const na = digits(a);
606
+ const nb = digits(b);
607
+ for (let i = 0; i < Math.max(na.length, nb.length); i++) {
608
+ const da = na[i] ?? -1;
609
+ const db = nb[i] ?? -1;
610
+ if (da !== db) return db - da;
611
+ }
612
+ if (a.length !== b.length) return a.length - b.length;
613
+ return a.localeCompare(b);
614
+ }
615
+
584
616
  /**
585
617
  * Live model list from an endpoint's OpenAI-compatible GET /models, so the
586
618
  * /models picker shows what the gateway actually serves (Zhipu's coding
@@ -590,7 +622,7 @@ export function getRouting(): Record<string, string> {
590
622
  */
591
623
  export async function listEndpointModels(
592
624
  specOrId: string,
593
- override?: { baseUrl: string; apiKey?: string },
625
+ override?: { baseUrl?: string; apiKey?: string },
594
626
  ): Promise<string[]> {
595
627
  try {
596
628
  const baseUrl = (override?.baseUrl ?? baseUrlFor(resolveModel(specOrId)))?.replace(/\/$/, '');
@@ -609,7 +641,7 @@ export async function listEndpointModels(
609
641
  const ids = (body.data ?? [])
610
642
  .map((entry) => entry?.id)
611
643
  .filter((id): id is string => typeof id === 'string' && id.length > 0);
612
- return [...new Set(ids)].sort();
644
+ return [...new Set(ids)].sort(newestFirst);
613
645
  } catch {
614
646
  return [];
615
647
  }
@@ -91,7 +91,7 @@ describe('role routing', () => {
91
91
  test('resolveRole maps a role through to the profile model', () => {
92
92
  setRouting('analysis', 'glmc');
93
93
  const resolved = resolveRole('analysis');
94
- expect(resolved?.model).toBe('glm-4.6');
94
+ expect(resolved?.model).toBe('glm-5.3');
95
95
  expect(resolved?.baseUrl).toContain('/api/coding/');
96
96
  });
97
97