@trans-ai/trans-code 0.4.0 → 0.5.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.
- package/docs/superpowers/plans/2026-11-21-auto-update.md +138 -0
- package/docs/superpowers/specs/2026-11-21-auto-update-design.md +61 -0
- package/package.json +1 -1
- package/src/cli.ts +7 -3
- package/src/config.test.ts +49 -0
- package/src/config.ts +42 -0
- package/src/main.tsx +2 -1
- package/src/provider/provider.test.ts +6 -0
- package/src/provider/provider.ts +1 -1
- package/src/screens/REPL.tsx +80 -15
- package/src/screens/slash-completion.test.ts +62 -0
- package/src/screens/slash-completion.ts +41 -0
- package/src/screens/submit.test.ts +23 -0
- package/src/screens/submit.ts +17 -0
- package/src/upgrade.test.ts +242 -0
- package/src/upgrade.ts +206 -9
- package/src/version.ts +1 -1
|
@@ -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+ 测试保持全绿
|
package/package.json
CHANGED
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
|
|
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
|
}
|
|
@@ -68,6 +68,12 @@ describe('vendor model lists', () => {
|
|
|
68
68
|
expect(glm).toContain('glm-4.5');
|
|
69
69
|
});
|
|
70
70
|
|
|
71
|
+
test('deepseek lists the current model line', () => {
|
|
72
|
+
const deepseek = vendorModels('deepseek');
|
|
73
|
+
expect(deepseek).toContain('deepseek-v4-pro');
|
|
74
|
+
expect(deepseek).toContain('deepseek-flash');
|
|
75
|
+
});
|
|
76
|
+
|
|
71
77
|
test('spec mapping routes registry ids to provider prefixes', () => {
|
|
72
78
|
expect(vendorModelSpec('deepseek', 'deepseek-reasoner')).toBe('deepseek:deepseek-reasoner');
|
|
73
79
|
expect(vendorModelSpec('opus', 'claude-sonnet-4')).toBe('anthropic:claude-sonnet-4');
|
package/src/provider/provider.ts
CHANGED
|
@@ -87,7 +87,7 @@ 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-
|
|
90
|
+
deepseek: ['deepseek-v4-pro', 'deepseek-flash'],
|
|
91
91
|
glm: ['glm-4.6', 'glm-4.5', 'glm-4.5-air', 'glm-4-flash'],
|
|
92
92
|
glmc: ['glm-4.6', 'glm-4.5'],
|
|
93
93
|
minimax: ['MiniMax-Text-01'],
|
package/src/screens/REPL.tsx
CHANGED
|
@@ -28,6 +28,12 @@ import {
|
|
|
28
28
|
} from '../sessions/store.js';
|
|
29
29
|
import { walkFiles } from '../agent/tools/fs-utils.js';
|
|
30
30
|
import { applyCompletion, filterFiles, mentionQuery } from './file-completion.js';
|
|
31
|
+
import {
|
|
32
|
+
applySlashCompletion,
|
|
33
|
+
filterSlashCommands,
|
|
34
|
+
slashQuery,
|
|
35
|
+
} from './slash-completion.js';
|
|
36
|
+
import { resolveSubmitInput } from './submit.js';
|
|
31
37
|
import { renderDiff } from './diff-render.js';
|
|
32
38
|
import { createTurnStats, recordCall, shouldCollapse, summaryLine } from './turn-summary.js';
|
|
33
39
|
import { buildSystemPrompt, INIT_PROMPT, loadProjectContext } from '../agent/system-prompt.js';
|
|
@@ -50,9 +56,11 @@ type PromptPhase =
|
|
|
50
56
|
|
|
51
57
|
interface REPLProps {
|
|
52
58
|
ctx: CommandContext;
|
|
59
|
+
/** Background auto-update outcome; a non-null message shows as a banner. */
|
|
60
|
+
updateNotice?: Promise<string | null>;
|
|
53
61
|
}
|
|
54
62
|
|
|
55
|
-
export default function REPL({ ctx }: REPLProps) {
|
|
63
|
+
export default function REPL({ ctx, updateNotice }: REPLProps) {
|
|
56
64
|
const { exit } = useApp();
|
|
57
65
|
const [input, setInput] = useState('');
|
|
58
66
|
// Multiple keystrokes can be handled in one React batch before a
|
|
@@ -155,6 +163,38 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
155
163
|
() => (mentionActive && fileList ? filterFiles(fileList, mention ?? '', 8) : []),
|
|
156
164
|
[mentionActive, fileList, mention],
|
|
157
165
|
);
|
|
166
|
+
|
|
167
|
+
// Slash-command popup (mirrors the @-mention popup): candidates for the
|
|
168
|
+
// current input, a cursor, and a dismissed flag reset when the query changes.
|
|
169
|
+
const [slashCursor, setSlashCursor] = useState(0);
|
|
170
|
+
const [slashDismissed, setSlashDismissed] = useState(false);
|
|
171
|
+
const slashPrefix = phase === 'idle' && !busy ? slashQuery(input) : null;
|
|
172
|
+
const slashCandidates = useMemo(
|
|
173
|
+
() =>
|
|
174
|
+
slashPrefix !== null && !slashDismissed
|
|
175
|
+
? filterSlashCommands(input, getCommands())
|
|
176
|
+
: [],
|
|
177
|
+
[slashPrefix, slashDismissed, input],
|
|
178
|
+
);
|
|
179
|
+
useEffect(() => {
|
|
180
|
+
setSlashCursor(0);
|
|
181
|
+
if (slashPrefix === null) setSlashDismissed(false);
|
|
182
|
+
}, [slashPrefix]);
|
|
183
|
+
|
|
184
|
+
// Background auto-update outcome: surface as a history banner once settled.
|
|
185
|
+
useEffect(() => {
|
|
186
|
+
if (!updateNotice) return;
|
|
187
|
+
let cancelled = false;
|
|
188
|
+
void updateNotice.then(message => {
|
|
189
|
+
if (!cancelled && message) {
|
|
190
|
+
addHistory({ input: '', output: message });
|
|
191
|
+
dragFlush();
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
return () => {
|
|
195
|
+
cancelled = true;
|
|
196
|
+
};
|
|
197
|
+
}, [updateNotice, addHistory, dragFlush]);
|
|
158
198
|
const pendingPermissionRef = useRef<{
|
|
159
199
|
request: PermissionRequest;
|
|
160
200
|
resolve: (allow: boolean) => void;
|
|
@@ -458,8 +498,10 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
458
498
|
);
|
|
459
499
|
|
|
460
500
|
const handleSubmit = useCallback(async (raw: string) => {
|
|
461
|
-
|
|
462
|
-
|
|
501
|
+
// Bare Enter is a no-op except at the apikey prompt, where it means
|
|
502
|
+
// "reuse the saved key" (the prompt's 回车沿用 hint).
|
|
503
|
+
const trimmed = resolveSubmitInput(phase, raw);
|
|
504
|
+
if (trimmed === null) return;
|
|
463
505
|
|
|
464
506
|
if (phase === 'model_apikey' || phase === 'model_check') {
|
|
465
507
|
await handleApiKey(trimmed);
|
|
@@ -643,6 +685,11 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
643
685
|
setMentionDismissed(true);
|
|
644
686
|
return;
|
|
645
687
|
}
|
|
688
|
+
// Slash-command popup: same — Esc dismisses instead of exiting.
|
|
689
|
+
if (key.escape && slashCandidates.length > 0) {
|
|
690
|
+
setSlashDismissed(true);
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
646
693
|
if (key.escape) {
|
|
647
694
|
// While generating, Esc cancels instead of exiting.
|
|
648
695
|
if (busyRef.current && abortRef.current) {
|
|
@@ -775,6 +822,23 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
775
822
|
}
|
|
776
823
|
}
|
|
777
824
|
|
|
825
|
+
// Slash-command popup: ↑↓ navigate, Tab/Enter complete (takes precedence
|
|
826
|
+
// over history navigation and submission).
|
|
827
|
+
if (phase === 'idle' && slashCandidates.length > 0) {
|
|
828
|
+
if (key.upArrow) {
|
|
829
|
+
setSlashCursor(prev => (prev - 1 + slashCandidates.length) % slashCandidates.length);
|
|
830
|
+
return;
|
|
831
|
+
}
|
|
832
|
+
if (key.downArrow) {
|
|
833
|
+
setSlashCursor(prev => (prev + 1) % slashCandidates.length);
|
|
834
|
+
return;
|
|
835
|
+
}
|
|
836
|
+
if (key.tab || key.return) {
|
|
837
|
+
commitInput(applySlashCompletion(inputRef.current, slashCandidates[slashCursor]!.name));
|
|
838
|
+
return;
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
|
|
778
842
|
if (key.return) {
|
|
779
843
|
if (busyRef.current) return; // still generating; Esc cancels
|
|
780
844
|
handleSubmit(inputRef.current);
|
|
@@ -942,18 +1006,19 @@ export default function REPL({ ctx }: REPLProps) {
|
|
|
942
1006
|
</Box>
|
|
943
1007
|
)}
|
|
944
1008
|
|
|
945
|
-
{phase === 'idle' &&
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
1009
|
+
{phase === 'idle' && slashCandidates.length > 0 && (
|
|
1010
|
+
<Box flexDirection="column" marginLeft={2}>
|
|
1011
|
+
{slashCandidates.map((cmd, i) => (
|
|
1012
|
+
<Box key={cmd.name}>
|
|
1013
|
+
<Text color={i === slashCursor ? 'cyan' : 'gray'}>
|
|
1014
|
+
{i === slashCursor ? '❯ ' : ' '}
|
|
1015
|
+
/{cmd.name.padEnd(10)} {cmd.description}
|
|
1016
|
+
</Text>
|
|
1017
|
+
</Box>
|
|
1018
|
+
))}
|
|
1019
|
+
<Text color="gray" dimColor>↑↓ navigate · tab/enter complete · esc close</Text>
|
|
1020
|
+
</Box>
|
|
1021
|
+
)}
|
|
957
1022
|
|
|
958
1023
|
{phase === 'idle' && !busy && mentionActive && (
|
|
959
1024
|
<Box flexDirection="column" marginLeft={2}>
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import {
|
|
3
|
+
applySlashCompletion,
|
|
4
|
+
filterSlashCommands,
|
|
5
|
+
slashQuery,
|
|
6
|
+
} from './slash-completion.js';
|
|
7
|
+
|
|
8
|
+
const CMDS = [
|
|
9
|
+
{ name: 'help', description: 'Show help' },
|
|
10
|
+
{ name: 'models', description: 'List and switch model' },
|
|
11
|
+
{ name: 'new', description: 'Start a new conversation' },
|
|
12
|
+
];
|
|
13
|
+
|
|
14
|
+
describe('slashQuery', () => {
|
|
15
|
+
test('extracts the command prefix after the slash', () => {
|
|
16
|
+
expect(slashQuery('/')).toBe('');
|
|
17
|
+
expect(slashQuery('/mo')).toBe('mo');
|
|
18
|
+
expect(slashQuery('/models')).toBe('models');
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
test('returns null for non-slash input', () => {
|
|
22
|
+
expect(slashQuery('')).toBeNull();
|
|
23
|
+
expect(slashQuery('hello')).toBeNull();
|
|
24
|
+
expect(slashQuery('a /b')).toBeNull();
|
|
25
|
+
});
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
describe('filterSlashCommands', () => {
|
|
29
|
+
test('bare slash lists every command', () => {
|
|
30
|
+
expect(filterSlashCommands('/', CMDS)).toEqual(CMDS);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test('prefix-matches case-insensitively', () => {
|
|
34
|
+
expect(filterSlashCommands('/MO', CMDS)).toEqual([CMDS[1]]);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test('no matches (or non-slash input) yields an empty list', () => {
|
|
38
|
+
expect(filterSlashCommands('/xyz', CMDS)).toEqual([]);
|
|
39
|
+
expect(filterSlashCommands('/plan task', CMDS)).toEqual([]);
|
|
40
|
+
expect(filterSlashCommands('hello', CMDS)).toEqual([]);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
test('a lone exact match suppresses the popup (Enter should submit)', () => {
|
|
44
|
+
// Typing the full command name hides the popup so Enter runs the
|
|
45
|
+
// command instead of completing it.
|
|
46
|
+
expect(filterSlashCommands('/models', CMDS)).toEqual([]);
|
|
47
|
+
// …while a shared or partial prefix keeps it visible.
|
|
48
|
+
expect(filterSlashCommands('/mo', CMDS)).toEqual([CMDS[1]]);
|
|
49
|
+
expect(filterSlashCommands('/n', CMDS)).toEqual([CMDS[2]]);
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
describe('applySlashCompletion', () => {
|
|
54
|
+
test('replaces the slash token with the selected command plus a space', () => {
|
|
55
|
+
expect(applySlashCompletion('/mo', 'models')).toBe('/models ');
|
|
56
|
+
expect(applySlashCompletion('/', 'plan')).toBe('/plan ');
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test('leaves non-slash input untouched', () => {
|
|
60
|
+
expect(applySlashCompletion('hello', 'models')).toBe('hello');
|
|
61
|
+
});
|
|
62
|
+
});
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure helpers for the REPL slash-command popup. Rendering/keys live in
|
|
3
|
+
* REPL.tsx (mirroring the @-mention popup); these are the testable parts.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export interface SlashCommand {
|
|
7
|
+
name: string;
|
|
8
|
+
description: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Returns the command prefix after a leading '/', or null if input has none. */
|
|
12
|
+
export function slashQuery(input: string): string | null {
|
|
13
|
+
if (!input.startsWith('/')) return null;
|
|
14
|
+
return input.slice(1);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Commands visible in the popup for the current input: prefix matches,
|
|
19
|
+
* case-insensitive. A lone exact match suppresses the popup so Enter
|
|
20
|
+
* submits the typed command instead of completing it. Non-slash input,
|
|
21
|
+
* or input with arguments (no matching prefix), yields an empty list.
|
|
22
|
+
*/
|
|
23
|
+
export function filterSlashCommands(
|
|
24
|
+
input: string,
|
|
25
|
+
commands: SlashCommand[],
|
|
26
|
+
): SlashCommand[] {
|
|
27
|
+
const query = slashQuery(input);
|
|
28
|
+
if (query === null) return [];
|
|
29
|
+
const prefix = query.toLowerCase();
|
|
30
|
+
const matches = commands.filter((cmd) => cmd.name.startsWith(prefix));
|
|
31
|
+
if (matches.length === 1 && prefix !== '' && matches[0]!.name === prefix) {
|
|
32
|
+
return [];
|
|
33
|
+
}
|
|
34
|
+
return matches;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Replaces the slash token with the selected command (plus a space for args). */
|
|
38
|
+
export function applySlashCompletion(input: string, name: string): string {
|
|
39
|
+
if (slashQuery(input) === null) return input;
|
|
40
|
+
return `/${name} `;
|
|
41
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { resolveSubmitInput } from './submit.js';
|
|
3
|
+
|
|
4
|
+
describe('resolveSubmitInput', () => {
|
|
5
|
+
test('empty Enter at the apikey prompt submits (reuses the saved key)', () => {
|
|
6
|
+
// The prompt advertises "apikey (回车沿用 sk-…xxxx)> " — a bare Enter
|
|
7
|
+
// must reach handleApiKey, which falls back to the saved key.
|
|
8
|
+
expect(resolveSubmitInput('model_apikey', '')).toBe('');
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
test('empty Enter in every other phase is a no-op', () => {
|
|
12
|
+
expect(resolveSubmitInput('idle', '')).toBeNull();
|
|
13
|
+
expect(resolveSubmitInput('model_name', '')).toBeNull();
|
|
14
|
+
expect(resolveSubmitInput('custom_baseurl', '')).toBeNull();
|
|
15
|
+
expect(resolveSubmitInput('model_select', '')).toBeNull();
|
|
16
|
+
expect(resolveSubmitInput('model_pick', '')).toBeNull();
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
test('non-empty input is trimmed and passed through', () => {
|
|
20
|
+
expect(resolveSubmitInput('model_apikey', ' sk-abc ')).toBe('sk-abc');
|
|
21
|
+
expect(resolveSubmitInput('idle', 'hello')).toBe('hello');
|
|
22
|
+
});
|
|
23
|
+
});
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prompt phases where submitting an empty line is meaningful. At the apikey
|
|
3
|
+
* prompt the hint reads "apikey (回车沿用 sk-…xxxx)> " — a bare Enter means
|
|
4
|
+
* "reuse the saved key", and handleApiKey falls back to it for empty input.
|
|
5
|
+
*/
|
|
6
|
+
const EMPTY_SUBMIT_PHASES = new Set(['model_apikey']);
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Decide whether a submitted line should be dispatched. Returns the trimmed
|
|
10
|
+
* value, or null when the line is empty and the phase gives it no meaning —
|
|
11
|
+
* so a bare Enter is a no-op everywhere except the apikey prompt.
|
|
12
|
+
*/
|
|
13
|
+
export function resolveSubmitInput(phase: string, raw: string): string | null {
|
|
14
|
+
const trimmed = raw.trim();
|
|
15
|
+
if (!trimmed && !EMPTY_SUBMIT_PHASES.has(phase)) return null;
|
|
16
|
+
return trimmed;
|
|
17
|
+
}
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import { afterEach, describe, expect, test } from 'bun:test';
|
|
2
|
+
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import {
|
|
6
|
+
autoUpdateNotice,
|
|
7
|
+
isDevInstall,
|
|
8
|
+
planAutoUpdate,
|
|
9
|
+
startAutoUpdate,
|
|
10
|
+
} from './upgrade.js';
|
|
11
|
+
|
|
12
|
+
let configDir: string | undefined;
|
|
13
|
+
|
|
14
|
+
function useTempConfig(raw: unknown): void {
|
|
15
|
+
configDir = mkdtempSync(path.join(tmpdir(), 'transcode-autoupdate-test-'));
|
|
16
|
+
process.env.TRANSCODE_CONFIG_PATH = path.join(configDir, 'config.json');
|
|
17
|
+
writeFileSync(process.env.TRANSCODE_CONFIG_PATH, JSON.stringify({ autoUpdate: raw }));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
afterEach(() => {
|
|
21
|
+
delete process.env.TRANSCODE_CONFIG_PATH;
|
|
22
|
+
if (configDir) {
|
|
23
|
+
rmSync(configDir, { recursive: true, force: true });
|
|
24
|
+
configDir = undefined;
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
describe('isDevInstall', () => {
|
|
29
|
+
test('an entry under the npm root is a global install', () => {
|
|
30
|
+
const root = mkdtempSync(path.join(tmpdir(), 'transcode-root-test-'));
|
|
31
|
+
try {
|
|
32
|
+
mkdirSync(path.join(root, '@trans-ai'));
|
|
33
|
+
const entry = path.join(root, '@trans-ai', 'trans-code.ts');
|
|
34
|
+
writeFileSync(entry, '');
|
|
35
|
+
expect(isDevInstall(entry, root)).toBe(false);
|
|
36
|
+
} finally {
|
|
37
|
+
rmSync(root, { recursive: true, force: true });
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test('an entry outside the npm root (repo checkout / bun link) is a dev install', () => {
|
|
42
|
+
const root = mkdtempSync(path.join(tmpdir(), 'transcode-root-test-'));
|
|
43
|
+
const outside = mkdtempSync(path.join(tmpdir(), 'transcode-dev-test-'));
|
|
44
|
+
try {
|
|
45
|
+
const entry = path.join(outside, 'trans-code.ts');
|
|
46
|
+
writeFileSync(entry, '');
|
|
47
|
+
expect(isDevInstall(entry, root)).toBe(true);
|
|
48
|
+
} finally {
|
|
49
|
+
rmSync(root, { recursive: true, force: true });
|
|
50
|
+
rmSync(outside, { recursive: true, force: true });
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
describe('autoUpdateNotice / startAutoUpdate', () => {
|
|
56
|
+
test('autoUpdateNotice resolves null before startAutoUpdate runs', async () => {
|
|
57
|
+
expect(await autoUpdateNotice()).toBeNull();
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test('a disabled config settles the notice to null without touching npm', async () => {
|
|
61
|
+
useTempConfig(false);
|
|
62
|
+
startAutoUpdate();
|
|
63
|
+
expect(await autoUpdateNotice()).toBeNull();
|
|
64
|
+
// lastCheck must not be written for a disabled updater.
|
|
65
|
+
const saved = JSON.parse(
|
|
66
|
+
await Bun.file(process.env.TRANSCODE_CONFIG_PATH!).text(),
|
|
67
|
+
);
|
|
68
|
+
expect(saved.autoUpdate).toBe(false);
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
const HOUR = 3_600_000;
|
|
73
|
+
const NOW = 1_700_000_000_000;
|
|
74
|
+
|
|
75
|
+
function defaults(overrides: Partial<Parameters<typeof planAutoUpdate>[0]> = {}) {
|
|
76
|
+
return {
|
|
77
|
+
current: '0.4.0',
|
|
78
|
+
latest: '0.5.0',
|
|
79
|
+
target: 'latest',
|
|
80
|
+
enabled: true,
|
|
81
|
+
lastCheck: 0,
|
|
82
|
+
now: NOW,
|
|
83
|
+
...overrides,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
describe('planAutoUpdate', () => {
|
|
88
|
+
test('envSkip wins over everything, including disabled', () => {
|
|
89
|
+
const plan = planAutoUpdate(defaults({ envSkip: true, enabled: false, lastCheck: NOW }));
|
|
90
|
+
expect(plan).toEqual({ action: 'skip', reason: 'env-skip' });
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
test('disabled skips regardless of throttle state', () => {
|
|
94
|
+
expect(planAutoUpdate(defaults({ enabled: false }))).toEqual({
|
|
95
|
+
action: 'skip',
|
|
96
|
+
reason: 'disabled',
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
test('throttled while the interval has not fully elapsed (even by 1ms)', () => {
|
|
101
|
+
expect(
|
|
102
|
+
planAutoUpdate(defaults({ lastCheck: NOW - 24 * HOUR + 1 })),
|
|
103
|
+
).toEqual({ action: 'skip', reason: 'throttled' });
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
test('the boundary elapses exactly at now - lastCheck === interval', () => {
|
|
107
|
+
const plan = planAutoUpdate(defaults({ lastCheck: NOW - 24 * HOUR }));
|
|
108
|
+
expect(plan).toEqual({ action: 'install', spec: '@trans-ai/trans-code@latest', from: '0.4.0', to: '0.5.0' });
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
test('intervalHours overrides the default 24h window', () => {
|
|
112
|
+
expect(
|
|
113
|
+
planAutoUpdate(defaults({ lastCheck: NOW - 2 * HOUR, intervalHours: 1 })),
|
|
114
|
+
).toEqual({ action: 'install', spec: '@trans-ai/trans-code@latest', from: '0.4.0', to: '0.5.0' });
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
test('latest mode: unreachable registry skips silently (unknown-latest)', () => {
|
|
118
|
+
expect(planAutoUpdate(defaults({ latest: null }))).toEqual({
|
|
119
|
+
action: 'skip',
|
|
120
|
+
reason: 'unknown-latest',
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
test('latest mode: already current skips (up-to-date)', () => {
|
|
125
|
+
expect(planAutoUpdate(defaults({ latest: '0.4.0' }))).toEqual({
|
|
126
|
+
action: 'skip',
|
|
127
|
+
reason: 'up-to-date',
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
test('latest mode: newer version installs the full package spec', () => {
|
|
132
|
+
expect(planAutoUpdate(defaults({ latest: '0.5.0' }))).toEqual({
|
|
133
|
+
action: 'install',
|
|
134
|
+
spec: '@trans-ai/trans-code@latest',
|
|
135
|
+
from: '0.4.0',
|
|
136
|
+
to: '0.5.0',
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
test('pinned mode: same version skips even when the registry moved on', () => {
|
|
141
|
+
expect(planAutoUpdate(defaults({ target: '0.4.0', latest: '0.9.0' }))).toEqual({
|
|
142
|
+
action: 'skip',
|
|
143
|
+
reason: 'up-to-date',
|
|
144
|
+
});
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
test('pinned mode: a different version installs the pin, downgrades included', () => {
|
|
148
|
+
expect(planAutoUpdate(defaults({ target: '0.3.0', latest: '0.9.0' }))).toEqual({
|
|
149
|
+
action: 'install',
|
|
150
|
+
spec: '@trans-ai/trans-code@0.3.0',
|
|
151
|
+
from: '0.4.0',
|
|
152
|
+
to: '0.3.0',
|
|
153
|
+
});
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
describe('background update silence (spawned-runner E2E)', () => {
|
|
158
|
+
/**
|
|
159
|
+
* Spawns a runner that calls startAutoUpdate() against a fake npm whose
|
|
160
|
+
* non-`root` calls fail on stderr after a 5s sleep (degraded network).
|
|
161
|
+
* `holdMs` keeps the runner alive that long, simulating a REPL session.
|
|
162
|
+
* Returns the child's exit status and captured stderr.
|
|
163
|
+
*/
|
|
164
|
+
async function runAgainstSlowFailingNpm(holdMs: number) {
|
|
165
|
+
const dir = mkdtempSync(path.join(tmpdir(), 'transcode-silence-test-'));
|
|
166
|
+
try {
|
|
167
|
+
const bin = path.join(dir, 'bin');
|
|
168
|
+
mkdirSync(bin);
|
|
169
|
+
writeFileSync(
|
|
170
|
+
path.join(bin, 'npm'),
|
|
171
|
+
[
|
|
172
|
+
'#!/bin/sh',
|
|
173
|
+
// A root that contains every path lets the dev-install guard pass.
|
|
174
|
+
'if [ "$1" = "root" ]; then echo "/"; exit 0; fi',
|
|
175
|
+
'sleep 5',
|
|
176
|
+
'echo "npm error fake-network-boom" >&2',
|
|
177
|
+
'exit 1',
|
|
178
|
+
].join('\n'),
|
|
179
|
+
);
|
|
180
|
+
const { chmodSync } = await import('node:fs');
|
|
181
|
+
chmodSync(path.join(bin, 'npm'), 0o755);
|
|
182
|
+
|
|
183
|
+
const configPath = path.join(dir, 'config.json');
|
|
184
|
+
writeFileSync(configPath, JSON.stringify({ autoUpdate: { lastCheck: 0 } }));
|
|
185
|
+
|
|
186
|
+
const runner = path.join(dir, 'runner.ts');
|
|
187
|
+
writeFileSync(
|
|
188
|
+
runner,
|
|
189
|
+
`import { startAutoUpdate } from ${JSON.stringify(path.join(import.meta.dir, 'upgrade.ts'))};\n` +
|
|
190
|
+
'startAutoUpdate();\n' +
|
|
191
|
+
`setTimeout(() => {}, ${holdMs});\n`,
|
|
192
|
+
);
|
|
193
|
+
|
|
194
|
+
const { spawnSync } = await import('node:child_process');
|
|
195
|
+
// Strip bun-test-injected vars: a child `bun <file>` with BUN_TEST_*
|
|
196
|
+
// set misbehaves. Keep the ambient PATH/HOME only.
|
|
197
|
+
const cleanEnv: Record<string, string> = {};
|
|
198
|
+
for (const [key, value] of Object.entries(process.env)) {
|
|
199
|
+
if (value !== undefined && !key.startsWith('BUN_')) cleanEnv[key] = value;
|
|
200
|
+
}
|
|
201
|
+
const result = spawnSync(process.execPath, [runner], {
|
|
202
|
+
timeout: 9000,
|
|
203
|
+
encoding: 'utf8',
|
|
204
|
+
env: {
|
|
205
|
+
...cleanEnv,
|
|
206
|
+
PATH: `${bin}:${process.env.PATH}`,
|
|
207
|
+
TRANSCODE_CONFIG_PATH: configPath,
|
|
208
|
+
},
|
|
209
|
+
});
|
|
210
|
+
return {
|
|
211
|
+
status: result.status,
|
|
212
|
+
signal: result.signal,
|
|
213
|
+
stderr: result.stderr ?? '',
|
|
214
|
+
};
|
|
215
|
+
} finally {
|
|
216
|
+
rmSync(dir, { recursive: true, force: true });
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
test(
|
|
221
|
+
'quitting right after startup must not hang on a slow npm',
|
|
222
|
+
async () => {
|
|
223
|
+
const { status, signal, stderr } = await runAgainstSlowFailingNpm(0);
|
|
224
|
+
expect(
|
|
225
|
+
`status=${status} signal=${signal}\n${stderr.slice(0, 300)}`,
|
|
226
|
+
).toBe('status=0 signal=null\n');
|
|
227
|
+
},
|
|
228
|
+
15_000,
|
|
229
|
+
);
|
|
230
|
+
|
|
231
|
+
test(
|
|
232
|
+
'npm failure text must never reach the terminal (silent failure)',
|
|
233
|
+
async () => {
|
|
234
|
+
// Stay alive past the fake npm's 5s sleep so the failure would land
|
|
235
|
+
// if stderr were inherited.
|
|
236
|
+
const { status, stderr } = await runAgainstSlowFailingNpm(6500);
|
|
237
|
+
expect(status).toBe(0);
|
|
238
|
+
expect(stderr).not.toContain('fake-network-boom');
|
|
239
|
+
},
|
|
240
|
+
15_000,
|
|
241
|
+
);
|
|
242
|
+
});
|
package/src/upgrade.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { spawn } from 'node:child_process';
|
|
|
2
2
|
import { realpathSync } from 'node:fs';
|
|
3
3
|
import { readFileSync } from 'node:fs';
|
|
4
4
|
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { loadConfig, normalizeAutoUpdate, saveConfig } from './config.js';
|
|
5
6
|
import { VERSION } from './version.js';
|
|
6
7
|
|
|
7
8
|
const PKG = '@trans-ai/trans-code';
|
|
@@ -11,6 +12,185 @@ const PKG = '@trans-ai/trans-code';
|
|
|
11
12
|
// to the stale version.
|
|
12
13
|
const OFFICIAL = 'https://registry.npmjs.org';
|
|
13
14
|
|
|
15
|
+
const DEFAULT_INTERVAL_HOURS = 24;
|
|
16
|
+
|
|
17
|
+
export type AutoUpdatePlan =
|
|
18
|
+
| { action: 'skip'; reason: 'env-skip' | 'disabled' | 'throttled' | 'up-to-date' | 'unknown-latest' }
|
|
19
|
+
| { action: 'install'; spec: string; from: string; to: string };
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Pure decision for the background auto-update: whether to skip (and why)
|
|
23
|
+
* or which package spec to install. Order matters — envSkip and the
|
|
24
|
+
* enabled flag short-circuit before the throttle check so a disabled
|
|
25
|
+
* updater never hits the registry.
|
|
26
|
+
*/
|
|
27
|
+
export function planAutoUpdate(input: {
|
|
28
|
+
current: string;
|
|
29
|
+
/** Latest version from the registry; null when it could not be reached. */
|
|
30
|
+
latest: string | null;
|
|
31
|
+
/** 'latest' or a pinned version string. */
|
|
32
|
+
target: string;
|
|
33
|
+
enabled: boolean;
|
|
34
|
+
lastCheck: number;
|
|
35
|
+
now: number;
|
|
36
|
+
intervalHours?: number;
|
|
37
|
+
envSkip?: boolean;
|
|
38
|
+
}): AutoUpdatePlan {
|
|
39
|
+
if (input.envSkip) return { action: 'skip', reason: 'env-skip' };
|
|
40
|
+
if (!input.enabled) return { action: 'skip', reason: 'disabled' };
|
|
41
|
+
const interval =
|
|
42
|
+
(input.intervalHours ?? DEFAULT_INTERVAL_HOURS) * 3_600_000;
|
|
43
|
+
if (input.now - input.lastCheck < interval) {
|
|
44
|
+
return { action: 'skip', reason: 'throttled' };
|
|
45
|
+
}
|
|
46
|
+
if (input.target === 'latest') {
|
|
47
|
+
if (input.latest === null) return { action: 'skip', reason: 'unknown-latest' };
|
|
48
|
+
if (input.latest === input.current) return { action: 'skip', reason: 'up-to-date' };
|
|
49
|
+
return { action: 'install', spec: `${PKG}@latest`, from: input.current, to: input.latest };
|
|
50
|
+
}
|
|
51
|
+
// Pinned target: stay at it exactly, downgrades included.
|
|
52
|
+
if (input.target === input.current) return { action: 'skip', reason: 'up-to-date' };
|
|
53
|
+
return { action: 'install', spec: `${PKG}@${input.target}`, from: input.current, to: input.target };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* True when the running entry file lives outside the npm global root
|
|
58
|
+
* (repo checkout, bun link) — nothing to auto-upgrade there. Both sides
|
|
59
|
+
* are realpath-normalized so macOS aliases (/tmp vs /private/tmp) and
|
|
60
|
+
* symlinked roots compare correctly.
|
|
61
|
+
*/
|
|
62
|
+
export function isDevInstall(entryPath: string, npmRoot: string): boolean {
|
|
63
|
+
if (!npmRoot) return true;
|
|
64
|
+
try {
|
|
65
|
+
const entryReal = realpathSync(entryPath);
|
|
66
|
+
const rootReal = realpathSync(npmRoot);
|
|
67
|
+
return !entryReal.startsWith(rootReal);
|
|
68
|
+
} catch {
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Like sh(), but fully silent AND detached: background updates must never
|
|
75
|
+
* write into the TUI, and must never keep the event loop (and thereby a
|
|
76
|
+
* quitting REPL) alive until npm finishes. A kill timer bounds a hung npm.
|
|
77
|
+
*/
|
|
78
|
+
function shQuiet(cmd: string, args: string[]): Promise<{ code: number; stdout: string }> {
|
|
79
|
+
return new Promise(resolve => {
|
|
80
|
+
const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
81
|
+
let settled = false;
|
|
82
|
+
const settle = (code: number, stdout: string) => {
|
|
83
|
+
if (settled) return;
|
|
84
|
+
settled = true;
|
|
85
|
+
clearTimeout(timer);
|
|
86
|
+
resolve({ code, stdout });
|
|
87
|
+
};
|
|
88
|
+
const timer = setTimeout(() => child.kill('SIGKILL'), 120_000);
|
|
89
|
+
timer.unref?.();
|
|
90
|
+
// Detach: a REPL that quits mid-check exits promptly; an orphaned npm
|
|
91
|
+
// that still completes is benign (the next startup self-corrects).
|
|
92
|
+
child.unref?.();
|
|
93
|
+
(child.stdout as { unref?: () => void } | null)?.unref?.();
|
|
94
|
+
(child.stderr as { unref?: () => void } | null)?.unref?.();
|
|
95
|
+
let stdout = '';
|
|
96
|
+
child.stdout.on('data', (d: Buffer) => {
|
|
97
|
+
stdout += d.toString();
|
|
98
|
+
});
|
|
99
|
+
child.on('error', () => settle(1, stdout));
|
|
100
|
+
child.on('close', code => settle(code ?? 1, stdout));
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
let noticePromise: Promise<string | null> = Promise.resolve(null);
|
|
105
|
+
|
|
106
|
+
/** The auto-update outcome, once settled; null when nothing happened. */
|
|
107
|
+
export function autoUpdateNotice(): Promise<string | null> {
|
|
108
|
+
return noticePromise;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Kick off the background auto-update (REPL startup only). Never throws
|
|
113
|
+
* and never blocks: every failure path settles the notice to null, and
|
|
114
|
+
* npm output stays invisible unless TRANSCODE_DEBUG_UPGRADE=1.
|
|
115
|
+
*
|
|
116
|
+
* lastCheck is written only when the check reached a definitive state
|
|
117
|
+
* (up-to-date, or install succeeded) — on failure the next startup retries.
|
|
118
|
+
*/
|
|
119
|
+
export function startAutoUpdate(): void {
|
|
120
|
+
noticePromise = (async (): Promise<string | null> => {
|
|
121
|
+
const debug = process.env.TRANSCODE_DEBUG_UPGRADE === '1';
|
|
122
|
+
try {
|
|
123
|
+
const auto = normalizeAutoUpdate(loadConfig().autoUpdate);
|
|
124
|
+
const envSkip = process.env.TRANSCODE_SKIP_UPDATE === '1';
|
|
125
|
+
const intervalHours = Number(process.env.TRANSCODE_UPDATE_INTERVAL_HOURS) || undefined;
|
|
126
|
+
|
|
127
|
+
// Cheap gates first — no subprocess before we know we might install.
|
|
128
|
+
const early = planAutoUpdate({
|
|
129
|
+
current: VERSION,
|
|
130
|
+
latest: 'x', // placeholder: gates below never read it
|
|
131
|
+
target: auto.target,
|
|
132
|
+
enabled: auto.enabled,
|
|
133
|
+
lastCheck: auto.lastCheck,
|
|
134
|
+
now: Date.now(),
|
|
135
|
+
intervalHours,
|
|
136
|
+
envSkip,
|
|
137
|
+
});
|
|
138
|
+
if (early.action === 'skip' && early.reason !== 'unknown-latest') {
|
|
139
|
+
if (early.reason === 'up-to-date' && auto.target !== 'latest') return null; // pin satisfied
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const root = (await shQuiet('npm', ['root', '-g'])).stdout.trim();
|
|
144
|
+
const entry = realpathSync(fileURLToPath(import.meta.url));
|
|
145
|
+
if (isDevInstall(entry, root)) {
|
|
146
|
+
if (debug) process.stderr.write('[transcode] auto-update: dev install, skipped\n');
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const latest = auto.target === 'latest' ? await latestVersion(true) : auto.target;
|
|
151
|
+
const plan = planAutoUpdate({
|
|
152
|
+
current: VERSION,
|
|
153
|
+
latest,
|
|
154
|
+
target: auto.target,
|
|
155
|
+
enabled: auto.enabled,
|
|
156
|
+
lastCheck: auto.lastCheck,
|
|
157
|
+
now: Date.now(),
|
|
158
|
+
intervalHours,
|
|
159
|
+
envSkip,
|
|
160
|
+
});
|
|
161
|
+
if (plan.action === 'skip') {
|
|
162
|
+
// Up-to-date is a definitive outcome — record it so the next
|
|
163
|
+
// startup is throttled. Unknown-latest stays unwritten to retry.
|
|
164
|
+
if (plan.reason === 'up-to-date') writeLastCheck();
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const install = await shQuiet('npm', ['i', '-g', plan.spec, `--registry=${OFFICIAL}`]);
|
|
169
|
+
if (install.code !== 0) {
|
|
170
|
+
if (debug) process.stderr.write('[transcode] auto-update install failed\n');
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
const installed = installedVersionUnder(root);
|
|
174
|
+
writeLastCheck();
|
|
175
|
+
return `⟳ 已自动更新 ${VERSION} → ${installed ?? plan.to},重启 transcode 生效`;
|
|
176
|
+
} catch (error) {
|
|
177
|
+
if (debug) process.stderr.write(`[transcode] auto-update error: ${String(error)}\n`);
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
})();
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function writeLastCheck(): void {
|
|
184
|
+
try {
|
|
185
|
+
const cfg = loadConfig();
|
|
186
|
+
const auto = normalizeAutoUpdate(cfg.autoUpdate);
|
|
187
|
+
cfg.autoUpdate = { ...auto, lastCheck: Date.now() };
|
|
188
|
+
saveConfig(cfg);
|
|
189
|
+
} catch {
|
|
190
|
+
// The throttle cache is best-effort.
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
14
194
|
function sh(cmd: string, args: string[]): Promise<{ code: number; stdout: string }> {
|
|
15
195
|
return new Promise(resolve => {
|
|
16
196
|
const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'inherit'] });
|
|
@@ -42,8 +222,11 @@ async function npmRoot(): Promise<string> {
|
|
|
42
222
|
return r.stdout.trim();
|
|
43
223
|
}
|
|
44
224
|
|
|
45
|
-
async function latestVersion(): Promise<string | null> {
|
|
46
|
-
const
|
|
225
|
+
async function latestVersion(quiet = false): Promise<string | null> {
|
|
226
|
+
const run = quiet
|
|
227
|
+
? shQuiet('npm', ['view', `${PKG}@latest`, 'version', `--registry=${OFFICIAL}`])
|
|
228
|
+
: sh('npm', ['view', `${PKG}@latest`, 'version', `--registry=${OFFICIAL}`]);
|
|
229
|
+
const r = await run;
|
|
47
230
|
if (r.code !== 0) return null;
|
|
48
231
|
const v = r.stdout.trim();
|
|
49
232
|
return v || null;
|
|
@@ -58,19 +241,20 @@ function installedVersionUnder(root: string): string | null {
|
|
|
58
241
|
}
|
|
59
242
|
}
|
|
60
243
|
|
|
61
|
-
export async function runUpgrade(): Promise<void> {
|
|
62
|
-
|
|
244
|
+
export async function runUpgrade(target?: string): Promise<void> {
|
|
245
|
+
if (target) {
|
|
246
|
+
process.stdout.write(`transcode v${VERSION} — upgrading to ${target}…\n`);
|
|
247
|
+
} else {
|
|
248
|
+
process.stdout.write(`transcode v${VERSION} — checking for upgrades…\n`);
|
|
249
|
+
}
|
|
63
250
|
|
|
64
251
|
const entry = realpathSync(fileURLToPath(import.meta.url));
|
|
65
252
|
const root = await npmRoot();
|
|
66
|
-
// Normalize both sides through realpath — macOS aliases like /tmp vs
|
|
67
|
-
// /private/tmp would otherwise break prefix comparison.
|
|
68
|
-
const rootReal = root ? realpathSync(root) : '';
|
|
69
253
|
if (process.env.TRANSCODE_DEBUG_UPGRADE === '1') {
|
|
70
|
-
process.stdout.write(`[debug] entry=${entry}\n[debug] root=${
|
|
254
|
+
process.stdout.write(`[debug] entry=${entry}\n[debug] root=${root}\n`);
|
|
71
255
|
}
|
|
72
256
|
|
|
73
|
-
if (
|
|
257
|
+
if (isDevInstall(entry, root)) {
|
|
74
258
|
process.stdout.write(
|
|
75
259
|
[
|
|
76
260
|
'This looks like a development install (bun link / repo checkout),',
|
|
@@ -84,6 +268,19 @@ export async function runUpgrade(): Promise<void> {
|
|
|
84
268
|
return;
|
|
85
269
|
}
|
|
86
270
|
|
|
271
|
+
if (target) {
|
|
272
|
+
process.stdout.write(`Upgrading ${VERSION} → ${target}…\n`);
|
|
273
|
+
const code = await shInherit('npm', ['i', '-g', `${PKG}@${target}`, `--registry=${OFFICIAL}`]);
|
|
274
|
+
if (code !== 0) {
|
|
275
|
+
process.stderr.write('[transcode] upgrade failed — see npm output above.\n');
|
|
276
|
+
process.exitCode = 1;
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
const installed = installedVersionUnder(root);
|
|
280
|
+
process.stdout.write(`Upgraded to v${installed ?? target}. Restart transcode if it is running.\n`);
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
|
|
87
284
|
const latest = await latestVersion();
|
|
88
285
|
if (!latest) {
|
|
89
286
|
process.stderr.write(
|
package/src/version.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// Auto-generated from package.json by scripts/sync-version.ts (npm version hook)
|
|
2
|
-
export const VERSION = '0.
|
|
2
|
+
export const VERSION = '0.5.0';
|