pi-webapp 0.1.51 → 0.1.52-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -8
- package/README.zh-CN.md +10 -8
- package/bin/pi-webapp.mjs +47 -2
- package/bin/upgrade-transaction.d.mts +17 -0
- package/bin/upgrade-transaction.mjs +122 -0
- package/dist/extension.js +32 -32
- package/dist/hosted-recovery.js +5 -4
- package/dist/hosted-worker.js +2 -2
- package/docs/desktop.md +1 -1
- package/docs/hosted-paired-updater.md +7 -0
- package/docs/hosted-update-recovery.md +42 -12
- package/package.json +2 -2
- package/web/dist/.vite/manifest.json +4 -4
- package/web/dist/assets/{app-rE2dO2Sf.js → app-tKAlvGnx.js} +94 -94
- package/web/dist/assets/app.css +1 -1
- package/web/dist/assets/app.js +4 -4
- package/web/dist/assets/{plugin-Daa3_Q-m.js → plugin-3Ib-WXMi.js} +2 -2
- package/web/dist/assets/{plugin-D3ueGV13.js → plugin-DJaiYPEQ.js} +2 -2
- package/web/dist/assets/{plugin-Cw0h9Dlw.js → plugin-DObSoug1.js} +2 -2
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ Conversations, project files, terminals, and Git—side by side. Use the same wo
|
|
|
6
6
|
|
|
7
7
|
[简体中文](README.zh-CN.md) · [Get started](#get-started) · [Download desktop](#desktop-downloads) · [Architecture](#architecture-highlights) · [User guide](docs/en/introduction.md) · [npm](https://www.npmjs.com/package/pi-webapp)
|
|
8
8
|
|
|
9
|
-
**Desktop test build
|
|
9
|
+
**Desktop test build 16:** [macOS Apple Silicon DMG](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-b16/pi-0.1.39-desktop.16-mac-arm64.dmg) · [Intel, Windows & Linux downloads](#desktop-downloads) · [SHA-256 checksums](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-b16/SHA256SUMS). These are unsigned/unnotarized test packages. See [safe installation](docs/desktop-testing.md).
|
|
10
10
|
|
|
11
11
|
[](assets/readme/workbench.png)
|
|
12
12
|
|
|
@@ -105,25 +105,27 @@ Enter **`/web`** inside Pi. The browser stays synchronized with that terminal se
|
|
|
105
105
|
|
|
106
106
|
## Desktop downloads
|
|
107
107
|
|
|
108
|
-
**Latest desktop test release: [pi 0.1.39 · build
|
|
108
|
+
**Latest desktop test release: [pi 0.1.39 · build 16](https://github.com/chengzhiyi/pi-webapp/releases/tag/desktop-v0.1.39-b16).** Download the installer for your operating system and CPU:
|
|
109
109
|
|
|
110
110
|
| Platform | Download |
|
|
111
111
|
| --- | --- |
|
|
112
|
-
| **macOS · Apple Silicon (arm64)** | [Download DMG](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-
|
|
113
|
-
| **macOS · Intel (x64)** | [Download DMG](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-
|
|
114
|
-
| **Windows · x64** | [Download EXE installer](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-
|
|
115
|
-
| **Linux · x64** | [Download AppImage](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-
|
|
112
|
+
| **macOS · Apple Silicon (arm64)** | [Download DMG](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-b16/pi-0.1.39-desktop.16-mac-arm64.dmg) |
|
|
113
|
+
| **macOS · Intel (x64)** | [Download DMG](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-b16/pi-0.1.39-desktop.16-mac-x64.dmg) |
|
|
114
|
+
| **Windows · x64** | [Download EXE installer](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-b16/pi-0.1.39-desktop.16-win-x64.exe) |
|
|
115
|
+
| **Linux · x64** | [Download AppImage](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-b16/pi-0.1.39-desktop.16-linux-x86_64.AppImage) |
|
|
116
116
|
|
|
117
|
-
[All releases](https://github.com/chengzhiyi/pi-webapp/releases) · [SHA256SUMS](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-
|
|
117
|
+
[All releases](https://github.com/chengzhiyi/pi-webapp/releases) · [SHA256SUMS](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-b16/SHA256SUMS) · [Build/runtime metadata](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-b16/desktop-release.json)
|
|
118
118
|
|
|
119
119
|
**Build 12 fixes desktop quit responsiveness.** Quit confirmations focus the main window, closing a loading window no longer opens a blocking error alert, and a failed backend stop offers a desktop-only exit. Existing background services remain available.
|
|
120
120
|
|
|
121
121
|
**Build 14 adds safe transfer from an old shared launcher.** Build 12 already supports preview updates, but attaching it to a build 10 backend preserves the old launcher's capabilities. With build 14 installed, first update the business package on Stable, then use **pi → 安全切换到当前桌面启动器…**. Handoff waits for idle chats, closed terminals and real drawing save confirmation, preserves the local address and recovery copies, and never force-stops the old owner. Then select Preview and update; the selected channel/release persist across restarts. Preview chooses the newer of npm’s `latest` and `alpha`; an older alpha is not offered as an upgrade. Current-window, launcher and business-package versions are shown separately. Existing npm 0.1.26/0.1.27 services remain available for attachment without taking over their tasks.
|
|
122
122
|
|
|
123
|
+
**Build 16 refreshes the bundled interface.** The native desktop menus and dialogs follow the selected language; text, links and editors get native right-click menus; workspaces and chats open their actions on right-click; copy controls fall back when clipboard permission is denied; stale model errors clear after a successful retry; and activity durations are human-readable.
|
|
124
|
+
|
|
123
125
|
The **pi** desktop app bundles Node and Pi—no separate runtime installation needed. It can reuse a compatible Web service, open the same service in your browser, and let you choose whether background tasks continue after closing the app. Bring your own model credentials, Git/SSH setup, and project toolchains.
|
|
124
126
|
|
|
125
127
|
- **Install:** macOS: drag **pi.app** from the DMG into Applications. Windows: run the EXE installer. Linux: make the AppImage executable and run it; see the release notes for the FUSE alternative.
|
|
126
|
-
- **Verify:** compare the installer with `SHA256SUMS` from the same release. Confirm **build
|
|
128
|
+
- **Verify:** compare the installer with `SHA256SUMS` from the same release. Confirm **build 16** in **pi → 关于 pi (About pi)**. Quit the old desktop before replacing it; do not delete `~/.pi`.
|
|
127
129
|
- **Test-release limits:** these are opt-in prereleases, not publisher-signed stable distributions. macOS uses ad-hoc signatures without Apple notarization and may be blocked by Gatekeeper; follow the [macOS test installation guide](docs/desktop-testing.md) and stop if verification fails. Windows/Linux packages are unsigned. Never disable system security globally. Desktop shell updates require manual installation; business-package updates use the app's Settings. Windows ARM and Linux ARM are not included.
|
|
128
130
|
|
|
129
131
|
## Architecture highlights
|
package/README.zh-CN.md
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
[English](README.md) · [快速开始](#快速开始) · [下载桌面端](#桌面端下载) · [项目架构](#技术架构亮点) · [使用指南](docs/zh/getting-started.md) · [npm](https://www.npmjs.com/package/pi-webapp)
|
|
8
8
|
|
|
9
|
-
**桌面测试版 build
|
|
9
|
+
**桌面测试版 build 16:** [macOS Apple 芯片 DMG](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-b16/pi-0.1.39-desktop.16-mac-arm64.dmg) · [Intel、Windows 与 Linux 下载](#桌面端下载) · [SHA-256 校验文件](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-b16/SHA256SUMS)。测试包未签名或未公证,详见[安全安装说明](docs/desktop-testing.md)。
|
|
10
10
|
|
|
11
11
|
[](assets/readme/workbench.png)
|
|
12
12
|
|
|
@@ -105,25 +105,27 @@ pi
|
|
|
105
105
|
|
|
106
106
|
## 桌面端下载
|
|
107
107
|
|
|
108
|
-
**最新桌面测试版:[pi 0.1.39 · build
|
|
108
|
+
**最新桌面测试版:[pi 0.1.39 · build 16](https://github.com/chengzhiyi/pi-webapp/releases/tag/desktop-v0.1.39-b16)。** 请按系统与芯片选择安装包:
|
|
109
109
|
|
|
110
110
|
| 平台 | 下载 |
|
|
111
111
|
| --- | --- |
|
|
112
|
-
| **macOS · Apple 芯片(arm64)** | [下载 DMG](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-
|
|
113
|
-
| **macOS · Intel(x64)** | [下载 DMG](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-
|
|
114
|
-
| **Windows · x64** | [下载 EXE 安装包](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-
|
|
115
|
-
| **Linux · x64** | [下载 AppImage](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-
|
|
112
|
+
| **macOS · Apple 芯片(arm64)** | [下载 DMG](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-b16/pi-0.1.39-desktop.16-mac-arm64.dmg) |
|
|
113
|
+
| **macOS · Intel(x64)** | [下载 DMG](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-b16/pi-0.1.39-desktop.16-mac-x64.dmg) |
|
|
114
|
+
| **Windows · x64** | [下载 EXE 安装包](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-b16/pi-0.1.39-desktop.16-win-x64.exe) |
|
|
115
|
+
| **Linux · x64** | [下载 AppImage](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-b16/pi-0.1.39-desktop.16-linux-x86_64.AppImage) |
|
|
116
116
|
|
|
117
|
-
[全部版本](https://github.com/chengzhiyi/pi-webapp/releases) · [SHA256SUMS 校验文件](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-
|
|
117
|
+
[全部版本](https://github.com/chengzhiyi/pi-webapp/releases) · [SHA256SUMS 校验文件](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-b16/SHA256SUMS) · [构建与运行时信息](https://github.com/chengzhiyi/pi-webapp/releases/download/desktop-v0.1.39-b16/desktop-release.json)
|
|
118
118
|
|
|
119
119
|
**build 12 修复桌面退出无响应。** 退出确认会显示在主窗口前方;加载中关闭不再弹出阻塞警告;后台停止失败时可以选择“仅退出桌面”。已有后台服务和任务可继续运行。
|
|
120
120
|
|
|
121
121
|
**build 14 新增旧共享后台的安全启动器交接。** build 12 本身支持体验版,但附加到 build 10 启动的后台后,旧启动器能力仍会保留。安装 build 14 后,先在稳定版通道升级业务包,再使用「pi → 安全切换到当前桌面启动器…」。交接会等待聊天空闲、终端关闭和真实图稿保存确认,保留原本地地址与恢复副本,不会强制停止旧进程;之后再切换体验版并在线升级。通道和所选版本在重启后保持;体验版选择 npm `latest` 与 `alpha` 中较新的版本,不会把旧 alpha 当作升级。界面分别显示当前窗口、后台启动器和业务包版本。已有 npm 0.1.26/0.1.27 后台仍可安全连接,不接管其任务。
|
|
122
122
|
|
|
123
|
+
**build 16 更新内置界面。** 桌面原生菜单和对话框跟随所选语言;文本、链接与编辑区提供原生右键菜单;右键工作区和聊天可直接打开操作菜单;剪贴板权限被拒绝时复制按钮会自动降级;重试成功后清除过期的模型错误;活动耗时以易读格式显示。
|
|
124
|
+
|
|
123
125
|
桌面应用名为 **pi**,自带 Node 和 Pi,无需另装运行时。支持复用兼容的 Web 服务、在浏览器中打开同一服务,以及退出时选择是否保留后台任务。模型凭据、Git/SSH 配置和项目工具链仍需自行准备。
|
|
124
126
|
|
|
125
127
|
- **安装:** macOS 从 DMG 将 **pi.app** 拖入“应用程序”;Windows 运行 EXE;Linux 为 AppImage 添加执行权限后运行,不支持 FUSE 时可参考该版本发布说明中的替代方式。
|
|
126
|
-
- **核对:** 对照同一 Release 的 `SHA256SUMS` 校验安装包,在「pi → 关于 pi」确认 **build
|
|
128
|
+
- **核对:** 对照同一 Release 的 `SHA256SUMS` 校验安装包,在「pi → 关于 pi」确认 **build 16**。替换前先退出旧桌面,不要删除 `~/.pi`。
|
|
127
129
|
- **测试版边界:** 当前为自愿参与的预发布测试包,不是具有发布者签名的稳定发行版。macOS 使用 ad-hoc 临时签名、未经过 Apple 公证,可能被 Gatekeeper 拦截;请按 [macOS 测试安装说明](docs/desktop-testing.md)核验,失败就停止。Windows/Linux 安装包未签名。不要全局关闭系统安全保护。桌面外壳更新仍需手动安装,业务包更新在应用设置中进行;暂不包含 Windows ARM 和 Linux ARM。
|
|
128
130
|
|
|
129
131
|
## 技术架构亮点
|
package/bin/pi-webapp.mjs
CHANGED
|
@@ -15,6 +15,7 @@ import { compareVersions, parseVersion } from "../desktop/release-version.mjs";
|
|
|
15
15
|
import { desktopProtocolVersion, desktopUpdatePath, readDesktopRelease, rollbackDesktopRelease } from "../desktop/managed-release.mjs";
|
|
16
16
|
|
|
17
17
|
import { launcherHandoffProtocol, readHandoff, writeHandoff } from "../desktop/launcher-handoff.mjs";
|
|
18
|
+
import { readCandidate, recordUpgradeTransaction, retireCandidate, rollbackSelection, selectCandidate } from "./upgrade-transaction.mjs";
|
|
18
19
|
|
|
19
20
|
const minimum = [0, 87, 1];
|
|
20
21
|
const packageVersion = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
@@ -244,10 +245,22 @@ async function serve(pi, args) {
|
|
|
244
245
|
}
|
|
245
246
|
try {
|
|
246
247
|
const request = JSON.parse(await readFile(restartPath, "utf8"));
|
|
248
|
+
if (request.nonce !== nonce || (runtimeKind === "desktop" && !desktopPackages)) return;
|
|
249
|
+
if (typeof request.candidate === "string") {
|
|
250
|
+
// The host only names its validated candidate. Selection, admission and rollback are ours.
|
|
251
|
+
const candidate = await readCandidate(agentDir);
|
|
252
|
+
if (stopping || epoch !== stopEpoch) return;
|
|
253
|
+
if (candidate?.id === request.candidate && existsSync(candidate.launcher)) {
|
|
254
|
+
restartRequest = { ...request, launcher: candidate.launcher, candidate };
|
|
255
|
+
shutdown("restart_request");
|
|
256
|
+
}
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
// Legacy form: the pointer was already selected by the host that wrote this marker.
|
|
247
260
|
const prepared = JSON.parse(await readFile(updatePath, "utf8"));
|
|
248
261
|
const selected = desktopPackages ? await readDesktopRelease(agentDir, packageVersion, desktopFallbackVersion) : prepared;
|
|
249
262
|
if (stopping || epoch !== stopEpoch) return;
|
|
250
|
-
if (
|
|
263
|
+
if (request.launcher === selected?.launcher && existsSync(request.launcher)) {
|
|
251
264
|
restartRequest = request;
|
|
252
265
|
shutdown("restart_request");
|
|
253
266
|
}
|
|
@@ -404,7 +417,8 @@ async function serve(pi, args) {
|
|
|
404
417
|
next.once("exit", (code) => resolveExit(code ?? 1));
|
|
405
418
|
});
|
|
406
419
|
};
|
|
407
|
-
if (await
|
|
420
|
+
if (restartRequest.candidate) await upgradeInto(restartRequest.candidate, runLauncher);
|
|
421
|
+
else if (await runLauncher(restartRequest.launcher) !== 0) {
|
|
408
422
|
await clearManagedLauncher(restartRequest.launcher);
|
|
409
423
|
console.error("pi-webapp: 新版启动失败,正在恢复旧版服务");
|
|
410
424
|
if (await runLauncher(launcher) !== 0) console.error(`pi-webapp: 旧版恢复失败。日志:${logPath}`);
|
|
@@ -413,6 +427,37 @@ async function serve(pi, args) {
|
|
|
413
427
|
}
|
|
414
428
|
}
|
|
415
429
|
|
|
430
|
+
/** The launcher-owned upgrade transaction: select the candidate's pointer, admit the new host only
|
|
431
|
+
* when its launcher reports ready (plugins are not part of admission), otherwise restore the exact
|
|
432
|
+
* previous pointer and restart this release. Every outcome, with its real cause, goes to history. */
|
|
433
|
+
async function upgradeInto(candidate, runLauncher) {
|
|
434
|
+
const base = { id: candidate.id, version: candidate.version, from: packageVersion };
|
|
435
|
+
// Retire the candidate before recording an outcome, so anyone who sees the outcome sees it consumed.
|
|
436
|
+
const recover = async (message) => {
|
|
437
|
+
await retireCandidate(agentDir, candidate.id, "rolled-back").catch(() => {});
|
|
438
|
+
await recordUpgradeTransaction(agentDir, { ...base, phase: "rolled-back", message }).catch(() => {});
|
|
439
|
+
console.error(`pi-webapp: ${message}`);
|
|
440
|
+
if (await runLauncher(launcher) !== 0) console.error(`pi-webapp: 旧版恢复失败。日志:${logPath}`);
|
|
441
|
+
};
|
|
442
|
+
let selection;
|
|
443
|
+
try {
|
|
444
|
+
selection = await selectCandidate({ agentDir, desktop: desktopPackages, currentVersion: packageVersion, candidate });
|
|
445
|
+
await recordUpgradeTransaction(agentDir, { ...base, phase: "selected" });
|
|
446
|
+
} catch (error) {
|
|
447
|
+
if (selection) await rollbackSelection(selection).catch(() => {});
|
|
448
|
+
await recover(`Version ${candidate.version} was not selected: ${error instanceof Error ? error.message : String(error)}; current version kept`);
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
const code = await runLauncher(candidate.launcher);
|
|
452
|
+
if (code === 0) {
|
|
453
|
+
await retireCandidate(agentDir, candidate.id, "committed").catch(() => {});
|
|
454
|
+
await recordUpgradeTransaction(agentDir, { ...base, phase: "committed", message: "New version reported ready" }).catch(() => {});
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
const restored = await rollbackSelection(selection).catch(() => false);
|
|
458
|
+
await recover(`Version ${candidate.version} failed to start (launcher exit code ${code}); ${restored ? "previous version restored" : "version selection was changed by another client and left as is"}. Log: ${logPath}`);
|
|
459
|
+
}
|
|
460
|
+
|
|
416
461
|
async function clearManagedLauncher(path) {
|
|
417
462
|
if (desktopPackages) { await rollbackDesktopRelease(agentDir, path); return; }
|
|
418
463
|
try {
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export const upgradeSchema: 1;
|
|
2
|
+
export const candidateTtlMs: number;
|
|
3
|
+
export interface UpgradeCandidate { schema: 1; id: string; version: string; launcher: string; packageRoot: string; channel: "stable" | "alpha"; downgrade: boolean; createdAt: string }
|
|
4
|
+
export interface UpgradeTransactionRecord { schema: 1; id: string; phase: "selected" | "committed" | "rolled-back"; version: string; from: string; message?: string; updatedAt: string }
|
|
5
|
+
export interface UpgradeSelection { path: string; before: Buffer | null; after: Buffer | null }
|
|
6
|
+
export const upgradeRoot: (agentDir: string) => string;
|
|
7
|
+
export const candidatePath: (agentDir: string) => string;
|
|
8
|
+
export const upgradeTransactionPath: (agentDir: string) => string;
|
|
9
|
+
export function validCandidate(value: unknown): value is UpgradeCandidate;
|
|
10
|
+
export function readCandidate(agentDir: string, now?: number): Promise<UpgradeCandidate | null>;
|
|
11
|
+
export function writeCandidate(agentDir: string, candidate: Omit<UpgradeCandidate, "schema" | "createdAt"> & { createdAt?: string }): Promise<UpgradeCandidate>;
|
|
12
|
+
export function retireCandidate(agentDir: string, id: string | undefined, outcome: string): Promise<void>;
|
|
13
|
+
export function validUpgradeTransaction(value: unknown): value is UpgradeTransactionRecord;
|
|
14
|
+
export function readUpgradeTransaction(agentDir: string): Promise<UpgradeTransactionRecord | null>;
|
|
15
|
+
export function recordUpgradeTransaction(agentDir: string, transaction: Omit<UpgradeTransactionRecord, "schema" | "updatedAt">): Promise<UpgradeTransactionRecord>;
|
|
16
|
+
export function selectCandidate(options: { agentDir: string; desktop: boolean; currentVersion: string; candidate: UpgradeCandidate }): Promise<UpgradeSelection>;
|
|
17
|
+
export function rollbackSelection(selection: UpgradeSelection): Promise<boolean>;
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// Launcher-owned host upgrade transaction.
|
|
2
|
+
//
|
|
3
|
+
// Layering: desktop shell -> launcher -> host -> plugins. The host (business package) only
|
|
4
|
+
// downloads, validates and writes a candidate. The launcher, a more stable layer, selects the
|
|
5
|
+
// pointer, admits the new host by health (the new launcher reports ready) and rolls back. Plugins
|
|
6
|
+
// take no part. Every record here carries a schema version and fails open: unreadable, unknown or
|
|
7
|
+
// expired state is moved aside (never deleted) and treated as absent.
|
|
8
|
+
import { randomUUID } from "node:crypto";
|
|
9
|
+
import { mkdir, readFile, rename, rm, unlink, writeFile } from "node:fs/promises";
|
|
10
|
+
import { isAbsolute, join } from "node:path";
|
|
11
|
+
import { desktopProtocolVersion, desktopUpdatePath, readDesktopRelease, validateDesktopRelease, writeDesktopRelease } from "../desktop/managed-release.mjs";
|
|
12
|
+
import { parseVersion } from "../desktop/release-version.mjs";
|
|
13
|
+
|
|
14
|
+
export const upgradeSchema = 1;
|
|
15
|
+
/** A candidate nobody restarted into within a day is stale: download it again. */
|
|
16
|
+
export const candidateTtlMs = 24 * 60 * 60_000;
|
|
17
|
+
export const upgradeRoot = agentDir => join(agentDir, "pi-web", "upgrade");
|
|
18
|
+
export const candidatePath = agentDir => join(upgradeRoot(agentDir), "candidate.json");
|
|
19
|
+
export const upgradeTransactionPath = agentDir => join(upgradeRoot(agentDir), "transaction.json");
|
|
20
|
+
const historyRoot = agentDir => join(upgradeRoot(agentDir), "history");
|
|
21
|
+
const uuid = /^[a-f0-9-]{36}$/i;
|
|
22
|
+
|
|
23
|
+
async function atomicBytes(path, value) {
|
|
24
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
25
|
+
try { await writeFile(temporary, value, { mode: 0o600 }); await rename(temporary, path); }
|
|
26
|
+
finally { await rm(temporary, { force: true }); }
|
|
27
|
+
}
|
|
28
|
+
const atomicJson = (path, value) => atomicBytes(path, JSON.stringify(value));
|
|
29
|
+
/** Bytes are kept for diagnosis; a bad record never becomes a permanent fence. */
|
|
30
|
+
async function quarantine(path, reason) {
|
|
31
|
+
await rename(path, `${path}.${reason}-${Date.now()}`).catch(error => { if (error?.code !== "ENOENT") throw error; });
|
|
32
|
+
}
|
|
33
|
+
async function readRecord(path, valid, expired = () => false) {
|
|
34
|
+
let value;
|
|
35
|
+
try { value = JSON.parse(await readFile(path, "utf8")); }
|
|
36
|
+
catch (error) {
|
|
37
|
+
if (error?.code === "ENOENT") return null;
|
|
38
|
+
await quarantine(path, "invalid"); return null;
|
|
39
|
+
}
|
|
40
|
+
if (!valid(value)) { await quarantine(path, "invalid"); return null; }
|
|
41
|
+
if (expired(value)) { await quarantine(path, "expired"); return null; }
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function validCandidate(value) {
|
|
46
|
+
if (!value || typeof value !== "object" || value.schema !== upgradeSchema || !uuid.test(value.id ?? "")) return false;
|
|
47
|
+
try { parseVersion(value.version); } catch { return false; }
|
|
48
|
+
return typeof value.launcher === "string" && isAbsolute(value.launcher) && typeof value.packageRoot === "string" && isAbsolute(value.packageRoot)
|
|
49
|
+
&& ["stable", "alpha"].includes(value.channel) && typeof value.downgrade === "boolean" && !Number.isNaN(Date.parse(value.createdAt ?? ""));
|
|
50
|
+
}
|
|
51
|
+
export async function readCandidate(agentDir, now = Date.now()) {
|
|
52
|
+
return readRecord(candidatePath(agentDir), validCandidate, value => now - Date.parse(value.createdAt) > candidateTtlMs);
|
|
53
|
+
}
|
|
54
|
+
/** Host side: the only upgrade write the business package makes. No lock, no pointer. */
|
|
55
|
+
export async function writeCandidate(agentDir, candidate) {
|
|
56
|
+
const value = { schema: upgradeSchema, createdAt: new Date().toISOString(), ...candidate };
|
|
57
|
+
if (!validCandidate(value)) throw new Error("Invalid upgrade candidate");
|
|
58
|
+
await mkdir(upgradeRoot(agentDir), { recursive: true, mode: 0o700 });
|
|
59
|
+
await atomicJson(candidatePath(agentDir), value);
|
|
60
|
+
return value;
|
|
61
|
+
}
|
|
62
|
+
/** Moves the candidate aside into history (kept, never deleted) once it is consumed or cancelled. */
|
|
63
|
+
export async function retireCandidate(agentDir, id, outcome) {
|
|
64
|
+
const current = await readCandidate(agentDir);
|
|
65
|
+
if (!current || id && current.id !== id) return;
|
|
66
|
+
await mkdir(historyRoot(agentDir), { recursive: true, mode: 0o700 });
|
|
67
|
+
await rename(candidatePath(agentDir), join(historyRoot(agentDir), `${current.id}-candidate-${outcome}.json`)).catch(error => { if (error?.code !== "ENOENT") throw error; });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const phases = ["selected", "committed", "rolled-back"];
|
|
71
|
+
export function validUpgradeTransaction(value) {
|
|
72
|
+
return !!value && typeof value === "object" && value.schema === upgradeSchema && uuid.test(value.id ?? "") && phases.includes(value.phase)
|
|
73
|
+
&& typeof value.version === "string" && typeof value.from === "string" && !Number.isNaN(Date.parse(value.updatedAt ?? ""));
|
|
74
|
+
}
|
|
75
|
+
export async function readUpgradeTransaction(agentDir) {
|
|
76
|
+
return readRecord(upgradeTransactionPath(agentDir), validUpgradeTransaction);
|
|
77
|
+
}
|
|
78
|
+
export async function recordUpgradeTransaction(agentDir, transaction) {
|
|
79
|
+
const value = { schema: upgradeSchema, ...transaction, updatedAt: new Date().toISOString() };
|
|
80
|
+
if (!validUpgradeTransaction(value)) throw new Error("Invalid upgrade transaction");
|
|
81
|
+
await mkdir(historyRoot(agentDir), { recursive: true, mode: 0o700 });
|
|
82
|
+
await atomicJson(upgradeTransactionPath(agentDir), value);
|
|
83
|
+
if (value.phase !== "selected") await atomicJson(join(historyRoot(agentDir), `${value.id}-${value.phase}.json`), value);
|
|
84
|
+
return value;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function bytes(path) {
|
|
88
|
+
try { return await readFile(path); }
|
|
89
|
+
catch (error) { if (error?.code === "ENOENT") return null; throw error; }
|
|
90
|
+
}
|
|
91
|
+
/** Writes the pointer for a candidate with the running release as its rollback entry, and returns
|
|
92
|
+
* the exact bytes before and after so rollback can compare-and-swap. */
|
|
93
|
+
export async function selectCandidate({ agentDir, desktop, currentVersion, candidate }) {
|
|
94
|
+
const path = desktop ? desktopUpdatePath(agentDir) : join(agentDir, "pi-web", "update.json");
|
|
95
|
+
const before = await bytes(path);
|
|
96
|
+
if (desktop) {
|
|
97
|
+
const selected = await validateDesktopRelease(agentDir, { version: candidate.version, launcher: candidate.launcher, desktopProtocolVersion });
|
|
98
|
+
const saved = await readDesktopRelease(agentDir, currentVersion);
|
|
99
|
+
const previous = saved?.version === currentVersion ? saved : null;
|
|
100
|
+
const fallbackVersion = process.env.PI_WEBAPP_DESKTOP_VERSION ?? saved?.fallbackVersion ?? currentVersion;
|
|
101
|
+
await writeDesktopRelease(agentDir, { ...selected, ...((candidate.downgrade || saved?.fallbackVersion) ? { fallbackVersion } : {}), ...(previous ? { previous } : {}) });
|
|
102
|
+
} else {
|
|
103
|
+
let saved;
|
|
104
|
+
try { saved = JSON.parse(before?.toString("utf8") ?? "null"); } catch { saved = null; }
|
|
105
|
+
const previous = saved?.version === currentVersion ? { ...saved } : undefined;
|
|
106
|
+
// Keep only one rollback entry, never a recursively growing chain.
|
|
107
|
+
if (previous) delete previous.previous;
|
|
108
|
+
await mkdir(join(agentDir, "pi-web"), { recursive: true });
|
|
109
|
+
await atomicJson(path, { version: candidate.version, launcher: candidate.launcher, baseVersion: saved?.baseVersion ?? currentVersion,
|
|
110
|
+
...((candidate.downgrade || saved?.allowDowngrade === true) ? { allowDowngrade: true } : {}), ...(previous ? { previous } : {}) });
|
|
111
|
+
}
|
|
112
|
+
return { path, before, after: await bytes(path) };
|
|
113
|
+
}
|
|
114
|
+
/** Restores the exact previous pointer only while the pointer is still the one we wrote. A pointer
|
|
115
|
+
* that another client changed meanwhile is never overwritten. */
|
|
116
|
+
export async function rollbackSelection(selection) {
|
|
117
|
+
const current = await bytes(selection.path);
|
|
118
|
+
if (!current || !selection.after || !current.equals(selection.after)) return false;
|
|
119
|
+
if (selection.before) await atomicBytes(selection.path, selection.before);
|
|
120
|
+
else await unlink(selection.path).catch(error => { if (error?.code !== "ENOENT") throw error; });
|
|
121
|
+
return true;
|
|
122
|
+
}
|