one-model-router 0.0.14 → 0.0.15
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/bin/omr.js +6 -3
- package/package.json +1 -1
- package/src/admin.js +69 -24
- package/src/boot.js +4 -2
- package/src/install-forms.js +238 -0
- package/src/update.js +133 -63
- package/web/app.js +22 -4
package/bin/omr.js
CHANGED
|
@@ -308,7 +308,8 @@ async function postinstall() {
|
|
|
308
308
|
|
|
309
309
|
/**
|
|
310
310
|
* omr update:自更新(与桌面版同一套 feed/产物逻辑)。
|
|
311
|
-
* - 默认 auto
|
|
311
|
+
* - 默认 auto:按本机已安装形态逐个升级——只装 npm 包就只升 npm 包,
|
|
312
|
+
* 只装桌面端就只换原生安装包,两者都装则两者都升;
|
|
312
313
|
* - --npm:强制走 npm i -g one-model-router@latest;
|
|
313
314
|
* - --check:只检查是否有新版本,不下载安装。
|
|
314
315
|
* 升级完成后自动重启服务使其生效,并打印登录地址。
|
|
@@ -322,7 +323,9 @@ async function update() {
|
|
|
322
323
|
else {
|
|
323
324
|
log(`可升级:v${info.current} → v${info.latest}(更新源:${info.source})`)
|
|
324
325
|
if (info.notes) log(`更新说明:${info.notes}`)
|
|
325
|
-
log(
|
|
326
|
+
log(`已安装形态:${info.forms?.text || '未探测到'}`)
|
|
327
|
+
const scope = [info.targets?.desktop && '桌面端', info.targets?.npm && 'npm 包'].filter(Boolean).join(' + ')
|
|
328
|
+
log(`执行 omr update 升级${scope ? `(${scope})` : ''}${info.asset ? '' : '(本平台无原生包)'}`)
|
|
326
329
|
}
|
|
327
330
|
return
|
|
328
331
|
}
|
|
@@ -380,7 +383,7 @@ function help() {
|
|
|
380
383
|
log(' restart 停止后重新后台启动')
|
|
381
384
|
log(' status 查看运行状态与健康探针')
|
|
382
385
|
log(' portal 打印并用系统浏览器打开管理面板(登录地址)')
|
|
383
|
-
log(' update
|
|
386
|
+
log(' update 检查并升级到最新版(按本机已安装形态:npm 包 / 桌面端,装了什么升什么)')
|
|
384
387
|
log(' update --check 只检查是否有新版本')
|
|
385
388
|
log(' update --npm 强制走 npm 全局升级(npm i -g one-model-router@latest)')
|
|
386
389
|
log(' version 显示版本')
|
package/package.json
CHANGED
package/src/admin.js
CHANGED
|
@@ -25,6 +25,7 @@ import { syncState, updateSyncSettings, generatePairCode, latestPair, startRelay
|
|
|
25
25
|
import { json, openAiError, slugify, shortId, generateApiKey } from './util.js'
|
|
26
26
|
import { BUILTIN_PROVIDERS, BUILTIN_IDS } from './providers/builtin.js'
|
|
27
27
|
import { checkForUpdate, runUpdate, applyUpdate, getUpdateState, onUpdateEvent } from './update.js'
|
|
28
|
+
import { detectForms } from './install-forms.js'
|
|
28
29
|
|
|
29
30
|
const WEB_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', 'web')
|
|
30
31
|
const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.json': 'application/json' }
|
|
@@ -39,7 +40,49 @@ function appVersionText() {
|
|
|
39
40
|
return appVersion
|
|
40
41
|
}
|
|
41
42
|
|
|
42
|
-
|
|
43
|
+
/**
|
|
44
|
+
* 更新引擎适配层:把「宿主自己的更新器」与「内置 npm 引擎」统一成同一套 HTTP 语义,
|
|
45
|
+
* 这样浏览器打开的管理面板,无论服务是 Electron 主进程还是 `omr start` 起的 Node 进程,
|
|
46
|
+
* 拿到的都是同一份状态与同一组动作(getState / check / run / install)。
|
|
47
|
+
*
|
|
48
|
+
* @param {{ getState:()=>any, check:()=>Promise<any>, run:()=>Promise<any>, install:()=>Promise<any> }} host
|
|
49
|
+
* 宿主注入的更新器(桌面端传 electron/updater.js 的公开态);不传则用内置引擎。
|
|
50
|
+
*/
|
|
51
|
+
function createUpdateEngine(host, log) {
|
|
52
|
+
if (host) {
|
|
53
|
+
// 宿主已经把状态、进度、错误都放进自己的状态机,这里只做异常归一
|
|
54
|
+
const wrap = async fn => {
|
|
55
|
+
try { const r = await fn(); return r && typeof r === 'object' ? r : { ok: r !== false } }
|
|
56
|
+
catch (error) { return { ok: false, error: String(error?.message ?? error) } }
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
getState: () => host.getState(),
|
|
60
|
+
check: () => wrap(() => host.check()),
|
|
61
|
+
run: () => wrap(() => host.run()),
|
|
62
|
+
install: () => wrap(() => host.install()),
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
getState: () => getUpdateState(),
|
|
67
|
+
check: async () => {
|
|
68
|
+
try { await checkForUpdate(); return { ok: true } }
|
|
69
|
+
catch (error) { return { ok: false, error: error?.message ?? String(error) } }
|
|
70
|
+
},
|
|
71
|
+
// 面板点「升级」= 一次完成全部已安装形态的升级(原生包 + npm 包)
|
|
72
|
+
run: async () => {
|
|
73
|
+
try {
|
|
74
|
+
const result = await runUpdate({ mode: 'auto', log: () => {} })
|
|
75
|
+
return { ok: !result.error && result.updated !== false, error: result.error ?? null, via: result.via ?? null }
|
|
76
|
+
} catch (error) { return { ok: false, error: error?.message ?? String(error) } }
|
|
77
|
+
},
|
|
78
|
+
install: async () => {
|
|
79
|
+
const ok = await applyUpdate({ log: () => {} })
|
|
80
|
+
return { ok, error: getUpdateState().error }
|
|
81
|
+
},
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function createAdminServer({ log = () => {}, updater = null } = {}) {
|
|
43
86
|
const server = http.createServer((req, res) => {
|
|
44
87
|
void handle(req, res).catch(error => {
|
|
45
88
|
log(`admin request failed: ${error?.message ?? error}`)
|
|
@@ -47,9 +90,11 @@ export function createAdminServer({ log = () => {} } = {}) {
|
|
|
47
90
|
else res.end()
|
|
48
91
|
})
|
|
49
92
|
})
|
|
93
|
+
const updateEngine = createUpdateEngine(updater, log)
|
|
50
94
|
|
|
51
|
-
//
|
|
52
|
-
|
|
95
|
+
// 内置引擎(Node 宿主):更新状态变化经 SSE 'update' 事件推给管理面板。
|
|
96
|
+
// 桌面端不订阅这里——主进程自己会把原生更新器的状态 emitRuntimeEvent('update', …)。
|
|
97
|
+
if (!updater && !process.versions.electron) {
|
|
53
98
|
onUpdateEvent(next => emitRuntimeEvent('update', next))
|
|
54
99
|
}
|
|
55
100
|
|
|
@@ -58,24 +103,16 @@ export function createAdminServer({ log = () => {} } = {}) {
|
|
|
58
103
|
const path = url.pathname.replace(/\/+$/, '') || '/'
|
|
59
104
|
|
|
60
105
|
if (path === '/admin/api/version' && req.method === 'GET') return json(res, 200, { version: appVersionText() })
|
|
61
|
-
//
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
}
|
|
68
|
-
if (path === '/admin/api/update/run' && req.method === 'POST') {
|
|
69
|
-
try {
|
|
70
|
-
const result = await runUpdate({ mode: 'auto', log: () => {} })
|
|
71
|
-
return json(res, 200, { ok: !result.error, error: result.error ?? null, via: result.via ?? null })
|
|
72
|
-
} catch (error) { return json(res, 200, { ok: false, error: error?.message ?? String(error) }) }
|
|
73
|
-
}
|
|
74
|
-
if (path === '/admin/api/update/install' && req.method === 'POST') {
|
|
75
|
-
const ok = await applyUpdate({ log: () => {} })
|
|
76
|
-
return json(res, 200, { ok, error: getUpdateState().error })
|
|
77
|
-
}
|
|
106
|
+
// 自更新接口:桌面宿主(Electron 注入原生更新器)与 npm 宿主(内置引擎)走同一组路由,
|
|
107
|
+
// 浏览器里打开的面板因此与桌面窗口内的面板能力完全一致。
|
|
108
|
+
if (path === '/admin/api/update' && req.method === 'GET') return json(res, 200, updateEngine.getState() ?? { status: 'idle' })
|
|
109
|
+
if (path === '/admin/api/update/forms' && req.method === 'GET') {
|
|
110
|
+
try { return json(res, 200, await detectForms({ refresh: url.searchParams.get('refresh') === '1' })) }
|
|
111
|
+
catch (error) { return json(res, 200, { desktop: { installed: false }, npm: { installed: false }, installed: [], error: error?.message ?? String(error) }) }
|
|
78
112
|
}
|
|
113
|
+
if (path === '/admin/api/update/check' && req.method === 'POST') return json(res, 200, await updateEngine.check())
|
|
114
|
+
if (path === '/admin/api/update/run' && req.method === 'POST') return json(res, 200, await updateEngine.run())
|
|
115
|
+
if (path === '/admin/api/update/install' && req.method === 'POST') return json(res, 200, await updateEngine.install())
|
|
79
116
|
if (path === '/admin/api/state' && req.method === 'GET') return apiState(res)
|
|
80
117
|
if (path === '/admin/api/settings' && req.method === 'PUT') return apiUpdateSettings(req, res)
|
|
81
118
|
if (path === '/admin/api/opencode/probe' && req.method === 'POST') return apiProbeOpencode(res)
|
|
@@ -131,6 +168,12 @@ export function createAdminServer({ log = () => {} } = {}) {
|
|
|
131
168
|
if (path === '/admin/api/requests' && req.method === 'GET') return json(res, 200, { stats: runtime.stats, recent: runtime.recentRequests, health: health.snapshot(), probe: probe.probeSnapshot(), probeMeta: probe.probeMeta() })
|
|
132
169
|
if (path === '/admin/api/events' && req.method === 'GET') return apiEvents(req, res)
|
|
133
170
|
|
|
171
|
+
// 未注册的 API 路径必须回 JSON 404:漏了这条会被下面的 SPA 回退吞成 index.html(200),
|
|
172
|
+
// 前端 fetch().json() 直接解析失败,表现为「功能静默不可用」而不是「接口不存在」。
|
|
173
|
+
if (path.startsWith('/admin/api/')) {
|
|
174
|
+
openAiError(res, 404, 'not_found_error', `no admin route: ${req.method} ${path}`)
|
|
175
|
+
return
|
|
176
|
+
}
|
|
134
177
|
// 静态 UI:/admin、/、以及静态资源
|
|
135
178
|
if (req.method === 'GET') return serveStatic(path, res)
|
|
136
179
|
openAiError(res, 404, 'not_found_error', `no admin route: ${req.method} ${path}`)
|
|
@@ -1076,14 +1119,16 @@ export function createAdminServer({ log = () => {} } = {}) {
|
|
|
1076
1119
|
return server
|
|
1077
1120
|
}
|
|
1078
1121
|
|
|
1079
|
-
export async function startAdmin({ log = () => {}, port = 18681, host = '127.0.0.1' } = {}) {
|
|
1080
|
-
const server = createAdminServer({ log })
|
|
1122
|
+
export async function startAdmin({ log = () => {}, port = 18681, host = '127.0.0.1', updater = null } = {}) {
|
|
1123
|
+
const server = createAdminServer({ log, updater })
|
|
1081
1124
|
return new Promise((resolve, reject) => {
|
|
1082
1125
|
server.once('error', reject)
|
|
1083
1126
|
server.listen(port, host, () => {
|
|
1084
1127
|
server.off('error', reject)
|
|
1085
|
-
|
|
1086
|
-
|
|
1128
|
+
// 端口传 0 时由系统分配:回填真实端口,否则调用方拿到的仍是 0
|
|
1129
|
+
const actual = server.address()?.port || port
|
|
1130
|
+
log(`admin UI listening on http://${host}:${actual}/admin`)
|
|
1131
|
+
resolve({ server, port: actual, host })
|
|
1087
1132
|
})
|
|
1088
1133
|
})
|
|
1089
1134
|
}
|
package/src/boot.js
CHANGED
|
@@ -45,8 +45,9 @@ function closeServer(server, graceMs = 2000) {
|
|
|
45
45
|
|
|
46
46
|
/**
|
|
47
47
|
* 启动全部服务。
|
|
48
|
-
* @param {{ log?: (...args:any[]) => void, adminPort?: number, gatewayPort?: number, adminHost?: string, gatewayHost?: string, onProbeRound?: () => void }} [options]
|
|
48
|
+
* @param {{ log?: (...args:any[]) => void, adminPort?: number, gatewayPort?: number, adminHost?: string, gatewayHost?: string, onProbeRound?: () => void, updater?: object|null }} [options]
|
|
49
49
|
* onProbeRound:每轮自动模型探测结束后的回调(桌面端用于顺带检查新版本)。
|
|
50
|
+
* updater:宿主自带的更新器桥(桌面端注入原生更新器);不传时管理面用内置 npm 引擎。
|
|
50
51
|
* @returns {Promise<{ admin: { server: import('node:http').Server, port: number, host: string }, gateway: { server: import('node:http').Server, port: number, host: string }, stop: () => Promise<void> }>}
|
|
51
52
|
*/
|
|
52
53
|
export async function startAll({
|
|
@@ -56,6 +57,7 @@ export async function startAll({
|
|
|
56
57
|
adminHost = process.env.OMR_ADMIN_HOST ?? '127.0.0.1',
|
|
57
58
|
gatewayHost = process.env.OMR_GATEWAY_HOST,
|
|
58
59
|
onProbeRound = null,
|
|
60
|
+
updater = null,
|
|
59
61
|
} = {}) {
|
|
60
62
|
runtime.startedAt = Date.now()
|
|
61
63
|
invalidateCatalog()
|
|
@@ -75,7 +77,7 @@ export async function startAll({
|
|
|
75
77
|
// 结果写进同一份缓存/同一 in-flight Promise,首屏要么直接命中快照,要么只等剩余重建时间。
|
|
76
78
|
buildCatalog().catch(() => { /* 预热失败不影响启动,首屏会重试 */ })
|
|
77
79
|
|
|
78
|
-
const admin = await startAdmin({ log, port: adminPort, host: adminHost })
|
|
80
|
+
const admin = await startAdmin({ log, port: adminPort, host: adminHost, updater })
|
|
79
81
|
let gateway
|
|
80
82
|
try {
|
|
81
83
|
gateway = await startGateway({ log, port: gatewayPort, host: gatewayHost })
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 本机「安装形态」探测:桌面端(安装包 / .app / AppImage)与 npm 全局包。
|
|
3
|
+
*
|
|
4
|
+
* 升级策略的前提:装了哪种形态就升级哪种形态——只装 npm 包就只升 npm 包,
|
|
5
|
+
* 只装桌面端就只升桌面端,两者都装则两者都升。探测只依赖 Node 内置模块
|
|
6
|
+
* (不 import electron),因此 npm 服务端、Electron 主进程、CLI 三处共用。
|
|
7
|
+
*
|
|
8
|
+
* 判定口径:
|
|
9
|
+
* - runningAs:当前进程自己是以哪种形态在跑(desktop / npm / source),
|
|
10
|
+
* 源码开发态(有 .git 或 electron/ 目录)既不算桌面安装也不算 npm 安装。
|
|
11
|
+
* - 当前形态必然「已安装」,不再额外探测(避免 npm prefix 漂移、asar 路径判断失误)。
|
|
12
|
+
* - 另一形态按各自的落盘位置探测;npm 全局根目录用 `npm root -g` 取,取不到退回常见前缀。
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { spawn, execFileSync } from 'node:child_process'
|
|
16
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
17
|
+
import { dirname, join, resolve } from 'node:path'
|
|
18
|
+
import { homedir, tmpdir } from 'node:os'
|
|
19
|
+
import { fileURLToPath } from 'node:url'
|
|
20
|
+
|
|
21
|
+
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
|
|
22
|
+
const APP_NAME = 'OneModelRouter'
|
|
23
|
+
|
|
24
|
+
function readSelfPkg() {
|
|
25
|
+
try { return JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')) } catch { return {} }
|
|
26
|
+
}
|
|
27
|
+
const SELF_PKG = readSelfPkg()
|
|
28
|
+
|
|
29
|
+
/** npm 包名(`npm i -g <PKG_NAME>@latest`)。 */
|
|
30
|
+
export const PKG_NAME = String(SELF_PKG.name || 'one-model-router')
|
|
31
|
+
|
|
32
|
+
/** 探测结果缓存 TTL:升级动作会改写磁盘状态,需要时可 refresh 强制重探。 */
|
|
33
|
+
const DETECT_TTL_MS = 10 * 60_000
|
|
34
|
+
/** `npm root -g` 的超时:npm 冷启动慢,超过这个时间当作拿不到全局根目录。 */
|
|
35
|
+
const NPM_ROOT_TIMEOUT_MS = 8000
|
|
36
|
+
let detectCache = null
|
|
37
|
+
|
|
38
|
+
const isElectron = () => Boolean(process.versions?.electron)
|
|
39
|
+
/** Electron 开发态直跑(打包态 process.defaultApp 恒为 undefined)。 */
|
|
40
|
+
const isElectronDev = () => isElectron() && process.defaultApp === true
|
|
41
|
+
const isSourceCheckout = () => existsSync(join(ROOT, '.git')) || existsSync(join(ROOT, 'electron', 'main.js'))
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* 当前进程的运行形态。
|
|
45
|
+
* @returns {'desktop'|'npm'|'source'}
|
|
46
|
+
*/
|
|
47
|
+
export function runningAs() {
|
|
48
|
+
if (isElectron() && !isElectronDev()) return 'desktop'
|
|
49
|
+
if (isElectronDev() || isSourceCheckout()) return 'source'
|
|
50
|
+
return 'npm'
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 桌面端在本机的可能落盘路径(按优先级),命中即为已安装。 */
|
|
54
|
+
function desktopCandidates() {
|
|
55
|
+
const home = homedir()
|
|
56
|
+
if (process.platform === 'win32') {
|
|
57
|
+
const local = process.env.LOCALAPPDATA || join(home, 'AppData', 'Local')
|
|
58
|
+
const pf = process.env.ProgramFiles || 'C:\\Program Files'
|
|
59
|
+
const pf86 = process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)'
|
|
60
|
+
return [
|
|
61
|
+
join(local, 'Programs', APP_NAME, `${APP_NAME}.exe`),
|
|
62
|
+
join(pf, APP_NAME, `${APP_NAME}.exe`),
|
|
63
|
+
join(pf86, APP_NAME, `${APP_NAME}.exe`),
|
|
64
|
+
]
|
|
65
|
+
}
|
|
66
|
+
if (process.platform === 'darwin') {
|
|
67
|
+
return [
|
|
68
|
+
`/Applications/${APP_NAME}.app`,
|
|
69
|
+
join(home, 'Applications', `${APP_NAME}.app`),
|
|
70
|
+
]
|
|
71
|
+
}
|
|
72
|
+
// deb 落在 /opt/<productName>/,AppImage 由安装脚本放到 ~/.local/bin,两者都探
|
|
73
|
+
return [
|
|
74
|
+
join('/opt', APP_NAME, APP_NAME),
|
|
75
|
+
join('/opt', APP_NAME, PKG_NAME),
|
|
76
|
+
join(home, '.local', 'bin', APP_NAME),
|
|
77
|
+
join('/usr', 'bin', APP_NAME.toLowerCase()),
|
|
78
|
+
]
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Electron 打包态下正在运行的应用本体路径(可覆盖标准目录探测不到的自定义安装位置)。 */
|
|
82
|
+
function runningDesktopPath() {
|
|
83
|
+
if (!isElectron() || isElectronDev()) return ''
|
|
84
|
+
const exe = process.execPath || ''
|
|
85
|
+
if (!exe) return ''
|
|
86
|
+
// 便携版与安装版都算:exe 存在即视为已装桌面端
|
|
87
|
+
return existsSync(exe) ? exe : ''
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 读取 Windows exe 的版本号(FileVersion)。
|
|
92
|
+
* 非 Windows 或读不到返回空串——上层按「版本未知 → 需要升级」处理。
|
|
93
|
+
* 用 PowerShell 读版本信息是 Windows 上唯一免依赖的可靠方式(只在本机装了桌面端时才调用)。
|
|
94
|
+
*/
|
|
95
|
+
function exeVersion(file) {
|
|
96
|
+
if (process.platform !== 'win32') return ''
|
|
97
|
+
try {
|
|
98
|
+
const script = `(Get-Item -LiteralPath '${file.replace(/'/g, "''")}').VersionInfo.FileVersion`
|
|
99
|
+
const out = execFileSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], {
|
|
100
|
+
encoding: 'utf8',
|
|
101
|
+
timeout: 8000,
|
|
102
|
+
windowsHide: true,
|
|
103
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
104
|
+
})
|
|
105
|
+
// FileVersion 形如 "0.0.13.0":取前三段作为语义化版本
|
|
106
|
+
const parts = String(out || '').trim().split(/\s+/)[0].split('.').filter(p => /^\d+$/.test(p))
|
|
107
|
+
if (!parts.length) return ''
|
|
108
|
+
return parts.slice(0, 3).join('.')
|
|
109
|
+
} catch { return '' }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** `npm root -g`:拿不到(无 npm / 超时 / 报错)返回空串。 */
|
|
113
|
+
function npmGlobalRoot() {
|
|
114
|
+
return new Promise(resolveP => {
|
|
115
|
+
let child
|
|
116
|
+
try {
|
|
117
|
+
child = spawn('npm', ['root', '-g'], { stdio: ['ignore', 'pipe', 'ignore'], shell: process.platform === 'win32', windowsHide: true })
|
|
118
|
+
} catch { resolveP(''); return }
|
|
119
|
+
let out = ''
|
|
120
|
+
const timer = setTimeout(() => { try { child.kill('SIGKILL') } catch { /* 已结束 */ }; resolveP('') }, NPM_ROOT_TIMEOUT_MS)
|
|
121
|
+
child.stdout.on('data', chunk => { out = (out + chunk.toString()).slice(-4000) })
|
|
122
|
+
child.on('error', () => { clearTimeout(timer); resolveP('') })
|
|
123
|
+
child.on('close', code => {
|
|
124
|
+
clearTimeout(timer)
|
|
125
|
+
const root = code === 0 ? out.split(/\r?\n/).map(s => s.trim()).filter(Boolean).pop() || '' : ''
|
|
126
|
+
resolveP(root)
|
|
127
|
+
})
|
|
128
|
+
})
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** npm 全局根目录的候选(`npm root -g` 不可用时的兜底探测)。 */
|
|
132
|
+
function npmRootCandidates() {
|
|
133
|
+
const home = homedir()
|
|
134
|
+
const list = []
|
|
135
|
+
if (process.platform === 'win32') {
|
|
136
|
+
if (process.env.APPDATA) list.push(join(process.env.APPDATA, 'npm', 'node_modules'))
|
|
137
|
+
list.push(join(home, 'AppData', 'Roaming', 'npm', 'node_modules'))
|
|
138
|
+
list.push('C:\\Program Files\\nodejs\\node_modules')
|
|
139
|
+
} else {
|
|
140
|
+
list.push(join(home, '.npm-global', 'lib', 'node_modules'))
|
|
141
|
+
list.push('/usr/local/lib/node_modules')
|
|
142
|
+
list.push('/usr/lib/node_modules')
|
|
143
|
+
if (process.env.PREFIX) list.push(join(process.env.PREFIX, 'lib', 'node_modules'))
|
|
144
|
+
}
|
|
145
|
+
return list
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** 读取某个包目录里的版本号(读不到返回空串)。 */
|
|
149
|
+
function pkgVersionAt(dir) {
|
|
150
|
+
try { return String(JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'))?.version || '') } catch { return '' }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* 探测 npm 全局包形态。
|
|
155
|
+
* @param {boolean} forceSelf 当前进程正以该 npm 包在跑时,即便探测不到全局目录也按已安装处理
|
|
156
|
+
*/
|
|
157
|
+
async function detectNpmForm(forceSelf) {
|
|
158
|
+
const roots = []
|
|
159
|
+
const push = r => { if (r && !roots.includes(r)) roots.push(r) }
|
|
160
|
+
push(await npmGlobalRoot())
|
|
161
|
+
npmRootCandidates().forEach(push)
|
|
162
|
+
for (const root of roots) {
|
|
163
|
+
const dir = join(root, PKG_NAME)
|
|
164
|
+
const version = pkgVersionAt(dir)
|
|
165
|
+
if (!version) continue
|
|
166
|
+
return { installed: true, version, prefix: root, self: forceSelf || dir === ROOT || dirname(dir) === ROOT }
|
|
167
|
+
}
|
|
168
|
+
// 以 npm 包形态在跑(如 `omr start`)却没探到全局目录:prefix 漂移等边缘情况,仍按已安装处理
|
|
169
|
+
if (forceSelf) return { installed: true, version: String(SELF_PKG.version || ''), prefix: dirname(ROOT), self: true }
|
|
170
|
+
return { installed: false, version: '', prefix: '', self: false }
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* 探测本机已安装的形态。
|
|
175
|
+
* @param {{ refresh?: boolean }} [options] refresh=true 忽略缓存重探(升级动作之后调用)
|
|
176
|
+
* @returns {Promise<{ desktop:object, npm:object, runningAs:string, installed:string[] }>}
|
|
177
|
+
*/
|
|
178
|
+
export async function detectForms({ refresh = false } = {}) {
|
|
179
|
+
if (!refresh && detectCache && Date.now() - detectCache.at < DETECT_TTL_MS) return detectCache.value
|
|
180
|
+
|
|
181
|
+
const mode = runningAs()
|
|
182
|
+
const hit = desktopCandidates().find(p => existsSync(p))
|
|
183
|
+
// 桌面形态:正在跑的就是桌面端 → 必已安装(自定义安装目录也能覆盖);否则按落盘位置探测
|
|
184
|
+
const desktop = mode === 'desktop'
|
|
185
|
+
? { installed: true, path: runningDesktopPath() || hit || '', version: String(SELF_PKG.version || '') }
|
|
186
|
+
: { installed: !!hit, path: hit || '', version: hit ? exeVersion(hit) : '' }
|
|
187
|
+
// npm 形态:以 npm 包在跑时按已安装处理,其余情况探测全局目录
|
|
188
|
+
const npm = mode === 'npm'
|
|
189
|
+
? { installed: true, version: String(SELF_PKG.version || ''), prefix: dirname(ROOT), self: true }
|
|
190
|
+
: await detectNpmForm(false)
|
|
191
|
+
|
|
192
|
+
const installed = [desktop.installed && 'desktop', npm.installed && 'npm'].filter(Boolean)
|
|
193
|
+
const value = { desktop, npm, runningAs: mode, installed }
|
|
194
|
+
detectCache = { at: Date.now(), value }
|
|
195
|
+
return value
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** 形态一句话描述(管理面板文案):如「桌面端 + npm 包」。 */
|
|
199
|
+
export function describeForms(forms) {
|
|
200
|
+
const parts = []
|
|
201
|
+
if (forms?.desktop?.installed) parts.push('桌面端')
|
|
202
|
+
if (forms?.npm?.installed) parts.push('npm 包')
|
|
203
|
+
return parts.join(' + ')
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* 升级 npm 全局包到最新版。
|
|
208
|
+
* @param {{ log?: (...args:any[])=>void, inherit?: boolean }} [options] inherit=true 直接把 npm 输出接到当前终端(CLI 用)
|
|
209
|
+
*/
|
|
210
|
+
export function upgradeNpmForm({ log = () => {}, inherit = false } = {}) {
|
|
211
|
+
const cmd = `npm i -g ${PKG_NAME}@latest`
|
|
212
|
+
log(`执行 npm 升级:${cmd}`)
|
|
213
|
+
return new Promise((resolveP, reject) => {
|
|
214
|
+
let child
|
|
215
|
+
try {
|
|
216
|
+
child = spawn('npm', ['i', '-g', `${PKG_NAME}@latest`], {
|
|
217
|
+
stdio: inherit ? 'inherit' : ['ignore', 'pipe', 'pipe'],
|
|
218
|
+
shell: true,
|
|
219
|
+
windowsHide: true,
|
|
220
|
+
})
|
|
221
|
+
} catch (error) { reject(error); return }
|
|
222
|
+
let tail = ''
|
|
223
|
+
const drain = stream => { stream?.on('data', chunk => { tail = (tail + chunk.toString()).slice(-4000) }) }
|
|
224
|
+
if (!inherit) { drain(child.stdout); drain(child.stderr) }
|
|
225
|
+
const timer = setTimeout(() => {
|
|
226
|
+
try { child.kill('SIGKILL') } catch { /* 已结束 */ }
|
|
227
|
+
reject(new Error('npm 升级超时'))
|
|
228
|
+
}, 10 * 60_000)
|
|
229
|
+
child.on('error', error => { clearTimeout(timer); reject(error) })
|
|
230
|
+
child.on('close', code => {
|
|
231
|
+
clearTimeout(timer)
|
|
232
|
+
if (code === 0) { resolveP(); return }
|
|
233
|
+
const detail = tail.trim().split(/\r?\n/).filter(Boolean).slice(-3).join(' / ')
|
|
234
|
+
reject(new Error(`npm 退出码 ${code}${detail ? ':' + detail : ''}`))
|
|
235
|
+
})
|
|
236
|
+
})
|
|
237
|
+
}
|
|
238
|
+
|
package/src/update.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* 网页版(npm 包)自更新引擎。
|
|
3
3
|
*
|
|
4
|
-
* 只依赖 Node 内置模块(不含 Electron),供 bin/omr.js(CLI
|
|
4
|
+
* 只依赖 Node 内置模块(不含 Electron),供 bin/omr.js(CLI)、src/admin.js(Web 面板)
|
|
5
|
+
* 与 electron/updater.js(桌面端顺带升级 npm 形态)共用。
|
|
5
6
|
*
|
|
6
7
|
* 设计对齐桌面端(electron/self-update.js):
|
|
7
8
|
* 1. feed(latest.json)源顺序:TRAE 站点 → GitHub raw(githubusercontent) → Gitee raw → GitHub Release → 加速镜像;
|
|
@@ -11,7 +12,9 @@
|
|
|
11
12
|
* darwin → macos-<arch>-zip.file(无 zip 退回 dmg):解压/挂载后整包换入 /Applications。
|
|
12
13
|
* linux → linux-appimage-<arch>.file:AppImage 运行态原子覆盖自身;否则装到 ~/.local/bin。
|
|
13
14
|
* 3. 下载流式校验 sha512(缺失退 sha256),不符即删并报错。
|
|
14
|
-
* 4.
|
|
15
|
+
* 4. 升级范围由「本机装了哪些形态」决定(见 install-forms.js):
|
|
16
|
+
* 只装 npm 包 → 只 `npm i -g`;只装桌面端 → 只换原生包;两者都装 → 两者都升。
|
|
17
|
+
* 一种形态都没探测到(源码直跑等)时退回旧策略:原生包优先、npm 兜底。
|
|
15
18
|
*/
|
|
16
19
|
|
|
17
20
|
import { accessSync, chmodSync, constants, cpSync, createWriteStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync } from 'node:fs'
|
|
@@ -23,6 +26,7 @@ import { fileURLToPath } from 'node:url'
|
|
|
23
26
|
import { Readable } from 'node:stream'
|
|
24
27
|
import { pipeline } from 'node:stream/promises'
|
|
25
28
|
import { ensureBunDetached } from './bun-bootstrap.js'
|
|
29
|
+
import { detectForms, describeForms, upgradeNpmForm } from './install-forms.js'
|
|
26
30
|
|
|
27
31
|
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
|
|
28
32
|
|
|
@@ -30,7 +34,6 @@ function readPkg() {
|
|
|
30
34
|
try { return JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')) } catch { return {} }
|
|
31
35
|
}
|
|
32
36
|
const PKG = readPkg()
|
|
33
|
-
const PKG_NAME = String(PKG.name || 'one-model-router')
|
|
34
37
|
|
|
35
38
|
/** 官网(TRAE 站点)根地址:一行安装脚本与 feed 的首选源。 */
|
|
36
39
|
export const SITE = 'https://one-model-router.traesite.cn'
|
|
@@ -144,19 +147,27 @@ function pickAsset(feed, base) {
|
|
|
144
147
|
|
|
145
148
|
// ── 状态机(供 CLI 打印 / Web 面板 SSE 推送)──────────────────────────────
|
|
146
149
|
|
|
150
|
+
/** 形态占位(desktop / npm 两个布尔位 + 说明字段),每次新建避免状态之间互相污染。 */
|
|
151
|
+
const emptyForms = () => ({ desktop: false, npm: false, text: '', runningAs: '' })
|
|
152
|
+
|
|
147
153
|
let state = {
|
|
148
154
|
status: 'idle', // idle / checking / available / downloading / downloaded / installing / done / not-available / error
|
|
149
155
|
current: getCurrentVersion(),
|
|
150
156
|
latest: null,
|
|
157
|
+
version: null, // = latest,管理面板统一读这个字段(与桌面端状态对齐)
|
|
151
158
|
notes: null,
|
|
152
159
|
progress: null,
|
|
153
160
|
error: null,
|
|
154
161
|
source: null,
|
|
155
162
|
via: null,
|
|
156
163
|
downloadPage: null,
|
|
164
|
+
forms: emptyForms(), // 本机已安装形态
|
|
165
|
+
targets: emptyForms(), // 本次升级要覆盖的形态(装了才升)
|
|
157
166
|
}
|
|
158
167
|
/** 最近一次检查命中的待安装信息(不对外暴露,供 download/install 阶段使用)。 */
|
|
159
168
|
let pending = null
|
|
169
|
+
/** 本轮是否没探测到任何已安装形态(源码直跑等):true 时沿用「原生优先、npm 兜底」。 */
|
|
170
|
+
let legacyMode = false
|
|
160
171
|
|
|
161
172
|
const listeners = new Set()
|
|
162
173
|
export function onUpdateEvent(fn) {
|
|
@@ -173,6 +184,34 @@ export function getUpdateState() {
|
|
|
173
184
|
return { ...state }
|
|
174
185
|
}
|
|
175
186
|
|
|
187
|
+
/**
|
|
188
|
+
* 探测本机形态并折算出本次要升级的形态;探测失败不影响检查结论,退回旧策略。
|
|
189
|
+
* 逐形态判断是否落后于 feed:
|
|
190
|
+
* - npm 包:能读到全局版本就比版本;
|
|
191
|
+
* - 桌面端:非桌面宿主下拿不到已安装版本,一律按「需要」处理
|
|
192
|
+
* (安装器自带「已装版本不低于本包则拒绝」的把关,重复执行无副作用)。
|
|
193
|
+
*/
|
|
194
|
+
async function resolveTargets({ latest, asset }) {
|
|
195
|
+
let detected = { desktop: { installed: false, version: '' }, npm: { installed: false, version: '' }, runningAs: '' }
|
|
196
|
+
try { detected = await detectForms() } catch { /* 探测异常当作什么都没装,走兜底 */ }
|
|
197
|
+
const forms = {
|
|
198
|
+
desktop: !!detected.desktop?.installed,
|
|
199
|
+
npm: !!detected.npm?.installed,
|
|
200
|
+
text: describeForms(detected),
|
|
201
|
+
runningAs: detected.runningAs || '',
|
|
202
|
+
}
|
|
203
|
+
// 一种形态都没探测到(源码直跑 / 全局目录探测失败):保持旧行为——原生优先,npm 兜底
|
|
204
|
+
legacyMode = !forms.desktop && !forms.npm
|
|
205
|
+
if (legacyMode) {
|
|
206
|
+
return { forms, targets: { desktop: !!asset, npm: true } }
|
|
207
|
+
}
|
|
208
|
+
const npmVersion = String(detected.npm?.version || '')
|
|
209
|
+
const npmNeeds = forms.npm && (npmVersion ? compareVersions(latest, npmVersion) > 0 : true)
|
|
210
|
+
const desktopVersion = String(detected.desktop?.version || '')
|
|
211
|
+
const desktopNeeds = forms.desktop && !!asset && (desktopVersion ? compareVersions(latest, desktopVersion) > 0 : true)
|
|
212
|
+
return { forms, targets: { desktop: desktopNeeds, npm: npmNeeds } }
|
|
213
|
+
}
|
|
214
|
+
|
|
176
215
|
/**
|
|
177
216
|
* 检查更新(不下载)。成功返回详情;失败抛出。
|
|
178
217
|
*/
|
|
@@ -187,24 +226,27 @@ export async function checkForUpdate({ timeoutMs } = {}) {
|
|
|
187
226
|
}
|
|
188
227
|
const latest = String(feed.version)
|
|
189
228
|
const current = getCurrentVersion()
|
|
190
|
-
const hasUpdate = compareVersions(latest, current) > 0
|
|
191
229
|
let asset = null
|
|
192
230
|
let assetError = ''
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
231
|
+
try { asset = pickAsset(feed, base) } catch (e) { assetError = e.message }
|
|
232
|
+
const { forms, targets } = await resolveTargets({ latest, asset })
|
|
233
|
+
// 有没有更新 = 本机任一已装形态需要升级;一种都没装时退回「运行版本是否落后」
|
|
234
|
+
const hasUpdate = legacyMode ? compareVersions(latest, current) > 0 : (targets.desktop || targets.npm)
|
|
196
235
|
pending = asset ? { feed, base, asset } : null
|
|
197
236
|
setState({
|
|
198
237
|
status: hasUpdate ? 'available' : 'not-available',
|
|
199
238
|
current,
|
|
200
239
|
latest,
|
|
240
|
+
version: hasUpdate ? latest : current,
|
|
201
241
|
notes: feed.notes || '',
|
|
202
242
|
source: label,
|
|
203
243
|
downloadPage: feed.url || SITE,
|
|
244
|
+
forms,
|
|
245
|
+
targets,
|
|
204
246
|
error: null,
|
|
205
247
|
progress: null,
|
|
206
248
|
})
|
|
207
|
-
return { hasUpdate, current, latest, notes: feed.notes || '', source: label, downloadPage: feed.url || SITE, asset, assetError }
|
|
249
|
+
return { hasUpdate, current, latest, notes: feed.notes || '', source: label, downloadPage: feed.url || SITE, asset, assetError, forms, targets }
|
|
208
250
|
}
|
|
209
251
|
|
|
210
252
|
function stagedPath(kind) {
|
|
@@ -388,73 +430,101 @@ async function installArtifact(asset, file) {
|
|
|
388
430
|
throw new Error(`当前系统不支持内置自更新(${process.platform}),请从官网重新安装`)
|
|
389
431
|
}
|
|
390
432
|
|
|
391
|
-
/**
|
|
433
|
+
/** npm 全局包升级(一种安装形态,不只是兜底)。 */
|
|
392
434
|
export function npmUpgrade(log = () => {}) {
|
|
393
|
-
|
|
394
|
-
return new Promise((resolveP, reject) => {
|
|
395
|
-
const child = spawn('npm', ['i', '-g', `${PKG_NAME}@latest`], { stdio: 'inherit', shell: true })
|
|
396
|
-
child.on('error', reject)
|
|
397
|
-
child.on('close', code => (code === 0 ? resolveP() : reject(new Error(`npm 退出码 ${code}`))))
|
|
398
|
-
})
|
|
435
|
+
return upgradeNpmForm({ log, inherit: true })
|
|
399
436
|
}
|
|
400
437
|
|
|
401
|
-
/**
|
|
438
|
+
/**
|
|
439
|
+
* 按「已安装形态」执行升级,返回每一形态的成败。
|
|
440
|
+
* 顺序:npm 先跑完再动原生安装包——Windows 安装器会接管并可能结束旧实例,
|
|
441
|
+
* 把 npm 放在后面有被中途截断的风险;桌面端在装完(或跳过)后立即换包。
|
|
442
|
+
* legacyMode(一个形态都没探测到,如源码直跑)沿用旧策略:原生优先、npm 兜底。
|
|
443
|
+
* @returns {Promise<{ done:string[], errors:string[] }>}
|
|
444
|
+
*/
|
|
445
|
+
async function upgradeInstalledForms({ log }) {
|
|
446
|
+
const targets = { ...state.targets }
|
|
447
|
+
if (!pending?.stagedPath) targets.desktop = false
|
|
448
|
+
const done = []
|
|
449
|
+
const errors = []
|
|
450
|
+
const npmStep = async () => {
|
|
451
|
+
setState({ status: 'installing', via: done.join('+') || 'npm', error: null })
|
|
452
|
+
try { await npmUpgrade(log); done.push('npm') } catch (error) { errors.push(`npm 包升级失败:${error.message}`) }
|
|
453
|
+
}
|
|
454
|
+
const desktopStep = async () => {
|
|
455
|
+
setState({ status: 'installing', via: done.join('+') || 'native', error: null })
|
|
456
|
+
try { await installArtifact(pending.asset, pending.stagedPath); done.push('native') } catch (error) { errors.push(`桌面端安装失败:${error.message}`) }
|
|
457
|
+
}
|
|
458
|
+
if (legacyMode) {
|
|
459
|
+
if (targets.desktop) await desktopStep()
|
|
460
|
+
if (!done.length && targets.npm) await npmStep()
|
|
461
|
+
return { done, errors }
|
|
462
|
+
}
|
|
463
|
+
if (targets.npm) await npmStep()
|
|
464
|
+
if (targets.desktop) await desktopStep()
|
|
465
|
+
return { done, errors }
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/** 升级途径(state.via)→ 人话:native=桌面端原生安装包,npm=npm 全局包。 */
|
|
469
|
+
function viaLabel(via) {
|
|
470
|
+
const parts = String(via || '').split('+').filter(Boolean)
|
|
471
|
+
const named = parts.map(p => (p === 'npm' ? 'npm 包' : p === 'native' ? '桌面端安装包' : p))
|
|
472
|
+
return named.length ? named.join(' + ') : '未知途径'
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/** 安装已下载的更新,并把其余已安装形态一并升级(装了才升)。 */
|
|
402
476
|
export async function applyUpdate({ log = () => {} } = {}) {
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
setState({ status: '
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
await npmUpgrade(log)
|
|
416
|
-
setState({ status: 'done', via: 'npm' })
|
|
417
|
-
ensureBunDetached({ log })
|
|
418
|
-
return true
|
|
419
|
-
} catch (npmError) {
|
|
420
|
-
setState({ status: 'error', error: `原生升级失败:${error.message};npm 兜底也失败:${npmError.message}` })
|
|
421
|
-
return false
|
|
422
|
-
}
|
|
477
|
+
const targets = state.targets || {}
|
|
478
|
+
const hasDesktop = Boolean(pending?.stagedPath) && targets.desktop
|
|
479
|
+
if (!hasDesktop && !targets.npm) {
|
|
480
|
+
const why = targets.desktop ? '桌面端更新包未下载成功' : '本机没有可升级的已安装形态'
|
|
481
|
+
setState({ status: 'error', error: why })
|
|
482
|
+
log(`${why},本次升级中止`)
|
|
483
|
+
return false
|
|
484
|
+
}
|
|
485
|
+
const { done, errors } = await upgradeInstalledForms({ log })
|
|
486
|
+
if (!done.length) {
|
|
487
|
+
setState({ status: 'error', error: errors.join(';') })
|
|
488
|
+
return false
|
|
423
489
|
}
|
|
490
|
+
setState({ status: 'done', via: done.join('+'), error: errors.length ? errors.join(';') : null })
|
|
491
|
+
// 升级完成后顺带补齐 OpenCode 免费车道依赖的 Bun(已装则跳过;分离进程,不阻塞重启)
|
|
492
|
+
ensureBunDetached({ log })
|
|
493
|
+
for (const label of done) log(label === 'npm' ? 'npm 包已升级到最新版' : '桌面端安装包已提交安装')
|
|
494
|
+
return true
|
|
424
495
|
}
|
|
425
496
|
|
|
426
497
|
/**
|
|
427
|
-
* 一键更新:检查 →
|
|
498
|
+
* 一键更新:检查 → 按已安装形态逐个升级(桌面端换原生包、npm 包走 npm i -g)。
|
|
428
499
|
* @param {{ mode?: 'auto'|'npm', log?: (...a:any[])=>void }} [options]
|
|
429
500
|
*/
|
|
430
501
|
export async function runUpdate({ mode = 'auto', log = () => {} } = {}) {
|
|
431
|
-
if (mode
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
log(`发现新版本 v${info.latest},下载 ${info.asset.name} …`)
|
|
437
|
-
const downloaded = await downloadUpdate()
|
|
438
|
-
if (downloaded) {
|
|
439
|
-
log('下载完成并通过校验,开始安装…')
|
|
440
|
-
const installed = await applyUpdate({ log })
|
|
441
|
-
if (installed) {
|
|
442
|
-
const via = getUpdateState().via
|
|
443
|
-
log(`升级完成(${via === 'npm' ? 'npm 兜底' : '原生安装包'}),正在自动重启服务…`)
|
|
444
|
-
return { updated: true, via, ...info }
|
|
445
|
-
}
|
|
446
|
-
log(`升级失败:${getUpdateState().error}`)
|
|
447
|
-
return { updated: false, via: null, error: getUpdateState().error, ...info }
|
|
448
|
-
}
|
|
449
|
-
log(`下载失败:${getUpdateState().error},改用 npm 兜底升级`)
|
|
450
|
-
} else {
|
|
451
|
-
log(`本平台无原生安装包(${info.assetError || '无'}),改用 npm 兜底升级`)
|
|
452
|
-
}
|
|
502
|
+
if (mode === 'npm') {
|
|
503
|
+
await npmUpgrade(log)
|
|
504
|
+
ensureBunDetached({ log })
|
|
505
|
+
log('npm 升级完成,正在自动重启服务…')
|
|
506
|
+
return { updated: true, via: 'npm' }
|
|
453
507
|
}
|
|
454
|
-
await
|
|
455
|
-
|
|
456
|
-
log(
|
|
457
|
-
return { updated:
|
|
508
|
+
const info = await checkForUpdate()
|
|
509
|
+
const scope = info.forms?.text ? `(已安装形态:${info.forms.text})` : '(未探测到已安装形态,按原生包优先 / npm 兜底执行)'
|
|
510
|
+
log(`更新源:${info.source};当前 v${info.current},最新 v${info.latest}${scope}`)
|
|
511
|
+
if (!info.hasUpdate) { log('已是最新版本'); return { updated: false, via: null, ...info } }
|
|
512
|
+
if (info.targets?.desktop && info.asset) {
|
|
513
|
+
log(`发现新版本 v${info.latest},下载 ${info.asset.name} 升级桌面端…`)
|
|
514
|
+
if (!(await downloadUpdate())) log(`桌面端更新包下载失败:${getUpdateState().error}`)
|
|
515
|
+
} else if (info.targets?.desktop) {
|
|
516
|
+
log(`桌面端这次跳过:${info.assetError || '更新源里没有本平台可用的安装包'}`)
|
|
517
|
+
}
|
|
518
|
+
const installed = await applyUpdate({ log })
|
|
519
|
+
if (!installed) {
|
|
520
|
+
const error = getUpdateState().error
|
|
521
|
+
log(`升级失败:${error}`)
|
|
522
|
+
return { updated: false, via: null, error, ...info }
|
|
523
|
+
}
|
|
524
|
+
const { via, error } = getUpdateState()
|
|
525
|
+
if (error) log(`部分形态未升级成功:${error}`)
|
|
526
|
+
log(`升级完成(${viaLabel(via)}),正在自动重启服务…`)
|
|
527
|
+
return { updated: true, via, ...info }
|
|
458
528
|
}
|
|
459
529
|
|
|
460
530
|
/** 关闭时清理下载残留(进程退出调用)。 */
|
package/web/app.js
CHANGED
|
@@ -4202,16 +4202,19 @@ setInterval(() => {
|
|
|
4202
4202
|
// 网页版(npm 安装):走 /admin/api/update/* HTTP 接口,行为与桌面版一致。
|
|
4203
4203
|
// 纯浏览器/桌面端均由同一个 updater 抽象驱动,UI 零差异。
|
|
4204
4204
|
const webUpdater = window.omrUpdater ? null : (function createWebUpdater() {
|
|
4205
|
+
// 只接受 JSON 响应:早期 Electron 宿主的 /admin/api/update 会回落到首页 HTML(200),
|
|
4206
|
+
// 若不校验会被 JSON.parse 抛错吞掉,表现为「永远查不到更新」的静默故障。
|
|
4207
|
+
const asJson = r => (r && r.ok && (r.headers.get('content-type') || '').includes('application/json') ? r.json() : null)
|
|
4205
4208
|
const post = path => fetch(path, { method: 'POST' })
|
|
4206
|
-
.then(r => r.
|
|
4209
|
+
.then(r => asJson(r).then(d => d || {}).catch(() => ({})))
|
|
4207
4210
|
.then(d => (d && d.ok === false ? { ok: false, error: d.error ?? '未知错误' } : { ok: true }))
|
|
4208
4211
|
.catch(e => ({ ok: false, error: String(e?.message ?? e) }))
|
|
4209
4212
|
return {
|
|
4210
|
-
getState: () => fetch('/admin/api/update').then(
|
|
4213
|
+
getState: () => fetch('/admin/api/update').then(asJson).catch(() => null),
|
|
4211
4214
|
check: () => post('/admin/api/update/check'),
|
|
4212
|
-
// 网页版点「升级」= 服务端一次完成 下载 +
|
|
4215
|
+
// 网页版点「升级」= 服务端一次完成 下载 + 安装(桌面端换原生包、npm 包走 npm i -g)
|
|
4213
4216
|
download: () => post('/admin/api/update/run').then(r => {
|
|
4214
|
-
if (r.ok) toast('
|
|
4217
|
+
if (r.ok) toast('升级任务已完成;若提示需重启,请执行 omr restart 使其生效')
|
|
4215
4218
|
return r
|
|
4216
4219
|
}),
|
|
4217
4220
|
install: () => post('/admin/api/update/install'),
|
|
@@ -4240,6 +4243,17 @@ if (updater) {
|
|
|
4240
4243
|
|
|
4241
4244
|
const version = s => (s?.version ? `v${s.version}` : '')
|
|
4242
4245
|
const pct = p => Math.min(100, Math.max(0, typeof p === 'number' ? p : Number(p?.percent ?? 0)))
|
|
4246
|
+
// 已安装形态 / 本次要升级的形态:只显示装了才升的那部分
|
|
4247
|
+
const formsText = s => {
|
|
4248
|
+
const t = s?.forms?.text || ''
|
|
4249
|
+
return t ? `已安装形态:${t}` : ''
|
|
4250
|
+
}
|
|
4251
|
+
const targetText = s => {
|
|
4252
|
+
const parts = []
|
|
4253
|
+
if (s?.targets?.desktop) parts.push('桌面端')
|
|
4254
|
+
if (s?.targets?.npm) parts.push('npm 包')
|
|
4255
|
+
return parts.length ? `将升级:${parts.join(' + ')}` : ''
|
|
4256
|
+
}
|
|
4243
4257
|
|
|
4244
4258
|
function btnTitle(s) {
|
|
4245
4259
|
if (!s) return '检查更新'
|
|
@@ -4270,10 +4284,13 @@ if (updater) {
|
|
|
4270
4284
|
function renderPanel(s) {
|
|
4271
4285
|
if (!s) { $panel.innerHTML = '<div class="omr-update-line">加载中…</div>'; return }
|
|
4272
4286
|
const v = version(s)
|
|
4287
|
+
const scope = [formsText(s), targetText(s)].filter(Boolean).join(' · ')
|
|
4288
|
+
const scopeLine = scope ? `<div class="omr-update-line">${esc(scope)}</div>` : ''
|
|
4273
4289
|
switch (s.status) {
|
|
4274
4290
|
case 'available': {
|
|
4275
4291
|
$panel.innerHTML = `
|
|
4276
4292
|
<div class="omr-update-title">检测到新版本 ${esc(v)}</div>
|
|
4293
|
+
${scopeLine}
|
|
4277
4294
|
<button class="btn primary small" data-up="download">立即升级</button>`
|
|
4278
4295
|
break
|
|
4279
4296
|
}
|
|
@@ -4298,6 +4315,7 @@ if (updater) {
|
|
|
4298
4315
|
case 'done':
|
|
4299
4316
|
$panel.innerHTML = `
|
|
4300
4317
|
<div class="omr-update-title">${esc(v)} 升级完成</div>
|
|
4318
|
+
${s.via ? `<div class="omr-update-line">升级方式:${esc(String(s.via).split('+').map(x => (x === 'npm' ? 'npm 包' : x === 'native' ? '桌面端安装包' : x)).join(' + '))}</div>` : ''}
|
|
4301
4319
|
<div class="omr-update-line">请执行 omr restart 重启服务使其生效</div>`
|
|
4302
4320
|
break
|
|
4303
4321
|
case 'error':
|