diff --git a/CHANGELOG.md b/CHANGELOG.md index 09437f6..5687282 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -61,6 +61,9 @@ All notable changes to LLeMbas CLI. The format follows database was created readable by everyone on the machine. Both directories are now made — and, when they already exist, set — readable by you alone, and so are the session and library databases and the prompt history. +- **`get.sh` refuses a signed release list that does not name its version**, as the updater + does: an older release's signed files could be served under a newer tag and its binary run + before the mismatch was noticed. Both now follow one rule, tested against the same cases. - A folder whose name begins with two dots (`..cache`) inside an allowed folder is inside it. - **The force-push floor reads the push.** It refused any forced push with "main" somewhere in it (`feature/main-menu`) and missed deleting the branch (`git push origin :main`, @@ -90,6 +93,17 @@ All notable changes to LLeMbas CLI. The format follows and `/decide` said "/trust creates it", and it did not — and says `/reload` loads the project's config (it said to restart). - A command that could not be started says why instead of "stopped (SIGTERM)". +- **The updater never moves to a new major version by itself.** The newest release of the + version's own major is installed; a later major (which may need a newer LLeMbas server) is + named — in `lembas update` and once an hour at most in the TUI — and installed only when you + name it: `lembas update v3.0.0`. +- **A version you chose stays.** After `lembas update vX.Y.Z` or `lembas update --rollback` the + next start installed the newest release again. Automatic updates now pause until you run + `lembas update` yourself, and both commands say so. +- **A slow connection no longer fails every update.** A download had 30 seconds in all — too + little for the release binary below about 11 Mbit/s; the limit is now 30 seconds of silence. +- `lembas update` says an ordinary failure (no network, nothing kept to roll back to) in one + line instead of printing a program stack. ### Terminal — LLeMbas TTY is now LLeMbas TERM diff --git a/get.sh b/get.sh index ce1ab43..3ddaa25 100755 --- a/get.sh +++ b/get.sh @@ -11,19 +11,19 @@ # stops and says so — it does not quietly build whatever the main branch holds instead. # # Environment: -# LEMBAS_FORGE where releases come from (default https://github.com); a Gitea or Forgejo -# (https://git.example.org) is told apart by its API +# LEMBAS_FORGE the server releases come from (default https://github.com); a Gitea or +# Forgejo server (https://git.example.org) is told apart by its API # LEMBAS_SLUG owner/name of the repository (default LLeMbas/LLeMbas-CLI) # LEMBAS_CHANNEL stable (default) or beta: also vX.Y.Z-beta.N, whichever is newest # LEMBAS_REF a release tag (v1.2.3) to install instead of the newest; or a branch (main), # which is built from source # LEMBAS_PUBKEY the ssh-ed25519 key SHA256SUMS.sig must be signed with (a build of your own) # LEMBAS_VERIFY signature (default) or checksum: no signature asked for (an unsigned source) -# LEMBAS_TOKEN for a private repository on the forge +# LEMBAS_TOKEN for a private repository # LEMBAS_FROM source: clone and build instead (needs git; fetches Bun if it is missing) -# LEMBAS_REPO what to clone for a source build (default: the forge's .git) +# LEMBAS_REPO what to clone for a source build (default: /.git) # LEMBAS_SRC where a source build keeps the source (default ~/.local/share/lembas/src) -# LEMBAS_API the releases API, when it is not where the forge's name says +# LEMBAS_API the releases API, when it is not where LEMBAS_FORGE says # # A release needs curl, sha256sum, gzip and ssh-keygen (openssh-client). Nothing runs as root. # Linux only: x86-64 and arm64. @@ -123,10 +123,19 @@ check_signature() { # The signed list says which version it is for: an old release's files under a new tag are refused. local version version="$(sed -n -E 's/^# lembas (.*)$/\1/p' "$dir/SHA256SUMS" | head -n1)" - if [ -n "$version" ] && [ "v$version" != "$tag" ]; then - echo "get.sh: release $tag carries the files of $version — nothing installed" >&2 - return 1 - fi + version_line_ok "$VERIFY" "$version" "$tag" +} + +# The list's version line against the tag — the updater's rule (src/update/index.ts +# versionLineRefusal; both are tested against tests/fixtures/release-version.json). A signed list +# must name the version tagged; with LEMBAS_VERIFY=checksum a list without the line is taken, one +# naming another version never is. +version_line_ok() { + local verify="$1" listed="$2" tag="$3" + [ "v$listed" = "$tag" ] && return 0 + [ -z "$listed" ] && [ "$verify" = checksum ] && return 0 + echo "get.sh: release $tag carries the files of ${listed:-an unnamed version} — nothing installed" >&2 + return 1 } # Fetch a release's SHA256SUMS (+ signature) and the named files into $TMP, and check them all. diff --git a/src/cli.ts b/src/cli.ts index 1a9a7ee..b6868cd 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -80,7 +80,9 @@ Usage: lembas voice say "…" [-o f] speak (or write a WAV); voice transcribe lembas trust [--readonly] trust the current project (its .agent/ config is then honoured) lembas update [--check] [--channel stable|beta] [vX.Y.Z] [--rollback] - install the newest release (or that one; --rollback: the one before) + install the newest release of this major version (or the one named, + any major; --rollback: the one before). A version named or rolled + back to stays until lembas update is run again lembas kb [create|add|docs|search|rm|reindex] knowledge bases the agent can search (lembas kb help) lembas uninstall [--purge] [--yes] @@ -753,7 +755,7 @@ async function main() { } if (cmd === "update") { - const { autoUpdate, check, install, installTag, lock, rollback, installedBinary } = await import("./update/index.ts") + const { check, hold, heldVersion, install, installTag, lock, rollback, installedBinary } = await import("./update/index.ts") const { values, positionals } = parseArgs({ args: argv.slice(1), allowPositionals: true, @@ -764,24 +766,52 @@ async function main() { const unlock = lock() if (!unlock) fail("another LLeMbas CLI is updating right now; try again in a minute") process.on("exit", () => unlock()) - if (values.rollback) { - const v = rollback() - console.log(`rolled back to ${v} (run it again to undo)`) + // An update that fails for an ordinary reason (no network, nothing kept to roll back to) is said + // in one line, never as a program's stack. + const PAUSED = "Automatic updates are paused until you run lembas update." + try { + if (values.rollback) { + const v = rollback() + hold(v) + console.log(`rolled back to ${v} (--rollback again goes back). ${PAUSED}`) + return + } + const config = { ...loadConfig().config.update, ...(values.channel ? { channel: values.channel as "stable" | "beta" } : {}) } + const later = (major?: string) => (major ? `\n${major} is out: a new major version is installed only when you name it — lembas update v${major}` : "") + const say = (r: Awaited>) => { + if (r.kind === "installed") console.log(`updated ${r.previous} → ${r.version} (${installedBinary()}); restart lembas, or /reload in a running one`) + else if (r.kind === "current") console.log(`${r.version} is the newest ${config.channel ?? "stable"} release of its major version${later(r.major)}`) + else if (r.kind === "available") console.log(`${r.version} is out — lembas update installs it${later(r.major)}`) + else if (r.kind === "skipped") console.log(r.reason) + else fail(r.reason) + } + if (positionals[0]) { + const r = await installTag(positionals[0], { config }) + if (r.kind === "installed") { + hold(r.version) + say(r) + console.log(`${PAUSED} (It stays on ${r.version}.)`) + return + } + return say(r) + } + const found = await check({ config }) + if (values.check) { + const held = heldVersion() + if (held) console.log(`held at ${held}, which you chose. ${PAUSED}`) + if ("kind" in found) return say(found) + return say({ kind: "available", version: found.release.tag.replace(/^v/, ""), ...(found.major ? { major: found.major } : {}) }) + } + // Run by hand: whatever was held is let go of, and automatic updates go on. + hold(undefined) + if ("kind" in found) return say(found) + const r = await install(found.release, found.version, { config }) + say(r) + if (found.major) console.log(later(found.major).trim()) return + } catch (e) { + fail((e as Error).message) } - const config = { ...loadConfig().config.update, ...(values.channel ? { channel: values.channel as "stable" | "beta" } : {}) } - const say = (r: Awaited>) => { - if (r.kind === "installed") console.log(`updated ${r.previous} → ${r.version} (${installedBinary()}); restart lembas, or /reload in a running one`) - else if (r.kind === "current") console.log(`${r.version} is the newest ${config.channel ?? "stable"} release`) - else if (r.kind === "available") console.log(`${r.version} is out — lembas update installs it`) - else if (r.kind === "skipped") console.log(r.reason) - else fail(r.reason) - } - if (positionals[0]) return say(await installTag(positionals[0], { config })) - const found = await check({ config }) - if ("kind" in found) return say(found) - if (values.check) return say({ kind: "available", version: found.release.tag.replace(/^v/, "") }) - return say(await install(found.release, found.version, { config })) } if (cmd === "kb") { diff --git a/src/tui/index.tsx b/src/tui/index.tsx index d2e1bbf..6969a0f 100644 --- a/src/tui/index.tsx +++ b/src/tui/index.tsx @@ -94,6 +94,8 @@ export function Boot(p: { options: TuiOptions; onQuit: () => void; onReload?: (a } else if (r.kind === "available") view.info(`LLeMbas CLI ${r.version} is out — \`lembas update\` installs it`) else if (r.kind === "failed" && r.security) view.info(`update refused: ${r.reason}`, "warn") else if (r.kind === "failed" && r.repeated) view.info(`${r.reason} — lembas update says more`, "warn") + // A new major version is never installed unasked (it may need a newer server): said, once an hour at most. + if ((r.kind === "current" || r.kind === "available") && r.major) view.info(`LLeMbas CLI ${r.major}, a new major version, is out — \`lembas update v${r.major}\` installs it`) }) } diff --git a/src/update/index.ts b/src/update/index.ts index 7c31fa2..6fa3c08 100644 --- a/src/update/index.ts +++ b/src/update/index.ts @@ -7,10 +7,13 @@ // 3. the running binary is kept as .prev and the new one renamed over it. // The running process keeps the old file open and carries on; /reload starts the new one. Nothing // is ever installed that is older than what runs, unless asked for by name (lembas update vX). +// Nothing of another major version is installed unless asked for by name either: a new major may +// need a new server, and the person decides when. A version chosen by name (or a rollback) holds +// until lembas update is run again: the next start does not undo it. import { createHash } from "node:crypto" import { accessSync, closeSync, constants, copyFileSync, existsSync, linkSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs" import { basename, dirname, join } from "node:path" -import { paths } from "../config/paths.ts" +import { ownDir, paths } from "../config/paths.ts" import type { Update } from "../config/schema.ts" import { VERSION } from "../version.ts" import { assetUrl, DEFAULT_SOURCE, fetcher, listReleases, resolveSource, type Fetcher, type Release, type Source } from "./source.ts" @@ -25,8 +28,9 @@ const CHECK_EVERY_MS = 60 * 60 * 1000 const LOCK_STALE_MS = 10 * 60 * 1000 export type Outcome = - | { kind: "current"; version: string } - | { kind: "available"; version: string } + /** `major`: the newest release of a later major version, which is never installed unasked. */ + | { kind: "current"; version: string; major?: string } + | { kind: "available"; version: string; major?: string } | { kind: "installed"; version: string; previous: string } | { kind: "skipped"; reason: string } /** `security`: the release did not prove itself (signature, checksum) — said loudly. */ @@ -67,8 +71,9 @@ export function installedBinary(): string | undefined { const sourceOf = (c?: Update): Source => resolveSource(c?.source ?? DEFAULT_SOURCE) const keysOf = (c?: Update) => (c?.public_key === undefined ? RELEASE_KEYS : [c.public_key].flat()) -/** The newest release of the configured channel, if it is newer than `current`. */ -export async function check(o: UpdateOptions = {}): Promise<{ release: Release; version: Version } | Outcome> { +/** The newest release of the configured channel within the running major version, if it is newer + * than `current`. A later major is named (`major`) and never chosen here. */ +export async function check(o: UpdateOptions = {}): Promise<{ release: Release; version: Version; major?: string } | Outcome> { const current = parseVersion(o.current ?? VERSION) if (!current) return { kind: "skipped", reason: `this is a build from source (${o.current ?? VERSION}); update it with get.sh or by rebuilding` } let releases: Release[] @@ -78,9 +83,25 @@ export async function check(o: UpdateOptions = {}): Promise<{ release: Release; } catch (e) { return { kind: "failed", reason: (e as Error).message } } - const newest = newestFor(releases, o.config?.channel ?? "stable") - if (!newest || compareVersions(newest.version, current) <= 0) return { kind: "current", version: versionText(current) } - return { release: newest, version: newest.version } + const channel = o.config?.channel ?? "stable" + const same = releases.filter((r) => parseVersion(r.tag)?.major === current.major) + const later = newestFor(releases.filter((r) => (parseVersion(r.tag)?.major ?? 0) > current.major), channel) + const major = later ? { major: versionText(later.version) } : {} + const newest = newestFor(same, channel) + if (!newest || compareVersions(newest.version, current) <= 0) return { kind: "current", version: versionText(current), ...major } + return { release: newest, version: newest.version, ...major } +} + +/** The signed list's version line against the tag (one rule with get.sh's `version_line_ok`; + * tests/fixtures/release-version.json holds the cases both are tested against). Where the list is + * signed it must name the version, and the one tagged: an older release's signed files served + * under a newer tag are refused before anything is run. With `verify: checksum` a list without + * the line is taken; one that names another version never is. Undefined: accepted. */ +export function versionLineRefusal(listed: string | undefined, tag: string, verify: "signature" | "checksum" = "signature"): string | undefined { + const want = tag.replace(/^v/, "") + if (listed === want) return undefined + if (listed === undefined && verify === "checksum") return undefined + return `release ${tag} carries the files of ${listed ?? "an unnamed version"} — not installed` } /** The signed list: file → SHA-256, and the version it names (`# lembas X.Y.Z`). */ @@ -137,8 +158,8 @@ export async function install(release: Release, version: Version, o: UpdateOptio const list = parseSums(new TextDecoder().decode(sums)) // The signed list names its version: an old release's files under a newer tag are refused here, // before anything is run. (Required where the list is signed.) - if (list.version !== versionText(version) && (list.version !== undefined || o.config?.verify !== "checksum")) - throw new Refused(`release ${release.tag} carries the files of ${list.version ?? "an unnamed version"} — not installed`) + const wrong = versionLineRefusal(list.version, `v${versionText(version)}`, o.config?.verify === "checksum" ? "checksum" : "signature") + if (wrong) throw new Refused(wrong.replace(`release v${versionText(version)}`, `release ${release.tag}`)) const name = asset const want = list.sums.get(`${name}.gz`) if (!want) throw new Refused(`release ${release.tag}: SHA256SUMS lists no ${asset}.gz`) @@ -192,6 +213,9 @@ export function lock(dir = paths.state): (() => void) | undefined { interface State { checked?: number + /** A version the person chose by name or by a rollback: no automatic install until they run + * `lembas update` again. */ + held?: string /** Failed looks in a row, and the last reason: said once there are three. */ failures?: number reason?: string @@ -212,6 +236,9 @@ export async function autoUpdate(o: UpdateOptions & { force?: boolean } = {}): P // A build from source is updated with git, not from releases: nothing to look for. if (!(o.target ?? installedBinary())) return { kind: "skipped", reason: "a build from source" } const dir = o.stateDir ?? paths.state + // A version the person chose stays until they run lembas update again (it is never held here). + const held = readState(dir).held + if (held) return { kind: "skipped", reason: `held at ${held}, which you chose; lembas update looks for updates again` } if (!o.force && Date.now() - (readState(dir).checked ?? 0) < CHECK_EVERY_MS) return { kind: "skipped", reason: "checked within the hour" } const unlock = lock(dir) if (!unlock) return { kind: "skipped", reason: "another session is updating" } @@ -222,7 +249,7 @@ export async function autoUpdate(o: UpdateOptions & { force?: boolean } = {}): P let r: Outcome try { const found = await check(o) - r = "kind" in found ? found : mode === "notify" ? { kind: "available", version: versionText(found.version) } : await install(found.release, found.version, o) + r = "kind" in found ? found : mode === "notify" ? { kind: "available", version: versionText(found.version), ...(found.major ? { major: found.major } : {}) } : await install(found.release, found.version, o) } catch (e) { r = { kind: "failed", reason: (e as Error).message } } @@ -239,7 +266,21 @@ export async function autoUpdate(o: UpdateOptions & { force?: boolean } = {}): P } } -/** `lembas update vX.Y.Z`: that release, older or newer, on purpose. */ +/** Hold the version the person chose (`lembas update vX`, `--rollback`), or let go of the hold + * (`lembas update`). */ +export function hold(version: string | undefined, dir = paths.state) { + const s = readState(dir) + if (version) s.held = version + else delete s.held + try { + ownDir(dir) + writeFileSync(join(dir, "update.json"), JSON.stringify(s)) + } catch {} +} + +export const heldVersion = (dir = paths.state): string | undefined => readState(dir).held + +/** `lembas update vX.Y.Z`: that release, older or newer, another major too, on purpose. */ export async function installTag(tag: string, o: UpdateOptions = {}): Promise { const version = parseVersion(tag) if (!version) return { kind: "failed", reason: `${tag} is not a release tag (vX.Y.Z or vX.Y.Z-beta.N)` } @@ -251,7 +292,12 @@ export async function installTag(tag: string, o: UpdateOptions = {}): Promise parseVersion(r.tag) && compareVersions(parseVersion(r.tag)!, version) === 0) + let release: Release | undefined + try { + release = (await listReleases(source, f)).find((r) => parseVersion(r.tag) && compareVersions(parseVersion(r.tag)!, version) === 0) + } catch (e) { + return { kind: "failed", reason: (e as Error).message } + } if (!release) return { kind: "failed", reason: `no release ${tag} at the update source` } return install(release, version, { ...o, fetcher: f }) } diff --git a/src/update/source.ts b/src/update/source.ts index 42ac256..db58d0e 100644 --- a/src/update/source.ts +++ b/src/update/source.ts @@ -13,7 +13,7 @@ export const DEFAULT_SOURCE: Source = { type: "github", repo: "LLeMbas/LLeMbas-C export interface Release { tag: string - /** Asset name → where to download it (a forge's release). */ + /** Asset name → where to download it (a GitHub or Gitea release). */ assets?: Record /** A static source's directory for this tag: every asset is `/`. */ dir?: string @@ -43,28 +43,63 @@ export function resolveSource(source: Source): Source { return substituteDeep(source, "update.source") } -export function fetcher(source: Source, timeoutMs = 30_000): Fetcher { +/** `silenceMs`: how long the source may send nothing — waiting for an answer, or between two + * pieces of one. Not a limit on the whole: a release binary is tens of megabytes, and a total + * limit failed every update on a slow line. */ +export function fetcher(source: Source, silenceMs = 30_000): Fetcher { const headers: Record = { "user-agent": `lembas-cli/${VERSION}` } const token = source.token ? source.token : source.key_cmd ? runKeyCmd(source.key_cmd, "update.source.key_cmd") : undefined if (token) headers.authorization = source.type === "gitea" ? `token ${token}` : `Bearer ${token}` if (source.type === "github") headers.accept = "application/vnd.github+json" const tls = tlsFor(source) // The token goes only where the source is: an API that names another host for its downloads (a - // forge with a wrong ROOT_URL, plain http) does not get it. + // server with a wrong ROOT_URL, plain http) does not get it. const own = new Set([source.url ? new URL(source.url).origin : undefined, source.type === "github" ? new URL(source.url ?? "https://api.github.com").origin : undefined, source.type === "github" ? "https://github.com" : undefined].filter(Boolean) as string[]) - const get = async (url: string, accept?: string) => { + const get = async (url: string, accept?: string): Promise => { const h: Record = { ...headers, ...(accept ? { accept } : {}) } if (!own.has(new URL(url).origin)) delete h.authorization - const r = await fetch(url, { headers: h, tls, signal: AbortSignal.timeout(timeoutMs) } as RequestInit) - if (!r.ok) throw new HttpError(r.status, url) - return r + const ctl = new AbortController() + let timer: ReturnType | undefined + const quiet = () => { + clearTimeout(timer) + timer = setTimeout(() => ctl.abort(), silenceMs) + } + const silent = () => new Error(`${url}: nothing received for ${Math.round(silenceMs / 1000)} s`) + quiet() + try { + let r: Response + try { + r = await fetch(url, { headers: h, tls, signal: ctl.signal } as RequestInit) + } catch (e) { + throw ctl.signal.aborted ? silent() : e + } + if (!r.ok) throw new HttpError(r.status, url) + if (!r.body) return new Uint8Array() + const parts: Uint8Array[] = [] + const reader = r.body.getReader() + for (;;) { + quiet() + let next: Awaited> + try { + next = await reader.read() + } catch (e) { + throw ctl.signal.aborted ? silent() : e + } + if (next.done) break + parts.push(next.value) + } + return Buffer.concat(parts) + } finally { + clearTimeout(timer) + } } + const text = (b: Uint8Array) => new TextDecoder().decode(b) return { - json: async (url) => (await get(url)).json(), - bytes: async (url) => new Uint8Array(await (await get(url, source.type === "github" && token ? "application/octet-stream" : "*/*")).arrayBuffer()), + json: async (url) => JSON.parse(text(await get(url))), + bytes: (url) => get(url, source.type === "github" && token ? "application/octet-stream" : "*/*"), async text(url) { try { - return await (await get(url, "text/plain")).text() + return text(await get(url, "text/plain")) } catch (e) { if (e instanceof HttpError && e.status === 404) return undefined throw e @@ -95,7 +130,7 @@ export async function listReleases(source: Source, f: Fetcher): Promise { + // get.sh's own function, taken out of it and run: the rule as get.sh has it, nothing restated. + const fn = Bun.spawnSync(["sed", "-n", "/^version_line_ok() {/,/^}/p", getSh]).stdout.toString() + expect(fn).toContain("version_line_ok") + const vectors = JSON.parse(readFileSync(resolve(import.meta.dir, "fixtures/release-version.json"), "utf8")) as { cases: { verify: string; tag: string; listed: string | null; ok: boolean }[] } + for (const c of vectors.cases) { + const r = Bun.spawnSync(["bash", "-c", `${fn}\nversion_line_ok "$1" "$2" "$3"`, "x", c.verify, c.listed ?? "", c.tag], { stderr: "pipe" }) + expect({ c, ok: r.exitCode === 0 }).toEqual({ c, ok: c.ok }) + } +}) diff --git a/tests/update.test.ts b/tests/update.test.ts index e78eca3..88e7e9d 100644 --- a/tests/update.test.ts +++ b/tests/update.test.ts @@ -7,7 +7,9 @@ import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync import { tmpdir } from "node:os" import { join } from "node:path" import type { Update } from "../src/config/schema.ts" -import { autoUpdate, check, install, installTag, rollback } from "../src/update/index.ts" +import { autoUpdate, check, heldVersion, hold, install, installTag, rollback, versionLineRefusal } from "../src/update/index.ts" +import { fetcher } from "../src/update/source.ts" +import VECTORS from "./fixtures/release-version.json" import { verifySshSig } from "../src/update/sshsig.ts" import { compareVersions, newestFor, parseVersion } from "../src/update/version.ts" @@ -179,7 +181,7 @@ test("looked for at most once an hour; off is off; a build from source never loo }) test("an old release's signed files under a newer tag are refused before anything runs", async () => { - const s = source(["v2.0.0"], { relabel: "1.0.0" }) + const s = source(["v1.1.0"], { relabel: "1.0.0" }) const target = installed("1.0.0") const r = await autoUpdate({ current: "1.0.0", config: cfg(s.gitea), target, asset: ASSET, stateDir: mkdtempSync(join(tmpdir(), "ph-upd-state-")) }) expect(r).toMatchObject({ kind: "failed", security: true }) @@ -204,3 +206,68 @@ test("a signature with anything around or after it is not one", () => { expect(() => verifySshSig(msg, `junk\n${sig}`, "lembas-release", [PUBKEY])).toThrow("not one armored") expect(() => verifySshSig(msg, `${sig}${sig}`, "lembas-release", [PUBKEY])).toThrow() }) + +test("the version line: one rule with get.sh (tests/fixtures/release-version.json)", () => { + for (const c of VECTORS.cases) expect({ c, ok: versionLineRefusal(c.listed ?? undefined, c.tag, c.verify as "signature" | "checksum") === undefined }).toEqual({ c, ok: c.ok }) +}) + +test("a new major version is never installed unasked; it is named, and installed by name", async () => { + const s = source(["v1.0.0", "v1.1.0", "v2.0.0", "v2.1.0"]) + const found = await check({ current: "1.0.0", config: cfg(s.gitea) }) + expect("release" in found && found.release.tag).toBe("v1.1.0") + expect("release" in found && found.major).toBe("2.1.0") + expect(await check({ current: "1.1.0", config: cfg(s.gitea) })).toEqual({ kind: "current", version: "1.1.0", major: "2.1.0" }) + const target = installed("1.1.0") + const stateDir = mkdtempSync(join(tmpdir(), "ph-upd-state-")) + expect(await autoUpdate({ current: "1.1.0", config: cfg(s.gitea), target, asset: ASSET, stateDir })).toEqual({ kind: "current", version: "1.1.0", major: "2.1.0" }) + expect(ran(target)).toBe("1.1.0") + expect(await installTag("v2.0.0", { current: "1.1.0", config: cfg(s.gitea), target, asset: ASSET })).toMatchObject({ kind: "installed", version: "2.0.0" }) +}) + +test("a version chosen by name or a rollback is held: the next start does not undo it", async () => { + const s = source(["v1.0.0", "v1.1.0"]) + const target = installed("1.0.0") + const stateDir = mkdtempSync(join(tmpdir(), "ph-upd-state-")) + hold("1.0.0", stateDir) + expect(heldVersion(stateDir)).toBe("1.0.0") + const r = await autoUpdate({ current: "1.0.0", config: cfg(s.gitea), target, asset: ASSET, stateDir, force: true }) + expect(r.kind).toBe("skipped") + expect(r.kind === "skipped" && r.reason).toContain("held at 1.0.0") + expect(ran(target)).toBe("1.0.0") + // lembas update by hand lets go of it. + hold(undefined, stateDir) + expect(await autoUpdate({ current: "1.0.0", config: cfg(s.gitea), target, asset: ASSET, stateDir, force: true })).toMatchObject({ kind: "installed", version: "1.1.0" }) +}) + +test("installing by name with no source to ask is an ordinary failure, not a throw", async () => { + const r = await installTag("v1.0.0", { current: "1.1.0", config: cfg({ type: "gitea", url: "http://127.0.0.1:9", repo: "o/p" }), target: installed("1.1.0"), asset: ASSET }) + expect(r.kind).toBe("failed") +}) + +test("a download is limited by silence, not by its length", async () => { + // 6 pieces 150 ms apart (900 ms in all) under a 400 ms silence limit: it arrives. + const slow = Bun.serve({ + port: 0, + fetch(req) { + const stall = new URL(req.url).pathname === "/stall" + return new Response( + new ReadableStream({ + async pull(c) { + for (let i = 0; i < 6; i++) { + await Bun.sleep(stall && i === 2 ? 1500 : 150) + c.enqueue(new Uint8Array([i])) + } + c.close() + }, + }), + ) + }, + }) + try { + const f = fetcher({ type: "static", url: `http://127.0.0.1:${slow.port}` }, 400) + expect([...(await f.bytes(`http://127.0.0.1:${slow.port}/slow`))]).toEqual([0, 1, 2, 3, 4, 5]) + await expect(f.bytes(`http://127.0.0.1:${slow.port}/stall`)).rejects.toThrow("nothing received for") + } finally { + slow.stop(true) + } +})