feat: add npm nightly release channel (#2126)
This commit is contained in:
@@ -1,11 +1,13 @@
|
||||
---
|
||||
name: release
|
||||
description: Kandev release & versioning conventions — single SemVer across npm, Homebrew, GitHub release. Use when cutting a release, debugging release artifacts, or answering questions about version channels.
|
||||
description: Kandev release and version-channel conventions — unified Stable SemVer plus deterministic npm-only Nightlies. Use when cutting a release, changing channels, debugging artifacts, or answering version-channel questions.
|
||||
---
|
||||
|
||||
# Release & Versioning
|
||||
|
||||
Kandev uses a **single SemVer** `X.Y.Z` shared across all distribution channels.
|
||||
Kandev Stable releases use a **single SemVer** `X.Y.Z` shared across all distribution channels.
|
||||
npm also has an explicit prerelease-only `nightly` channel; it is not part of the unified Stable
|
||||
artifact set.
|
||||
|
||||
## Version targets
|
||||
|
||||
@@ -18,18 +20,46 @@ Kandev uses a **single SemVer** `X.Y.Z` shared across all distribution channels.
|
||||
|
||||
**npm and Homebrew are sibling channels**, not chained. Both consume the same GitHub release artifacts; neither depends on the other.
|
||||
|
||||
For npm Nightly, Stable `X.Y.Z` plus a full `main` SHA produces
|
||||
`X.Y.(Z+1)-nightly.sha<first-12-lowercase-hex>`. `kandev` and all five runtime packages publish at
|
||||
that exact version under npm's `nightly` dist-tag. Nightly never moves `latest` and creates no Git
|
||||
tag, GitHub Release, Homebrew formula, Desktop feed/build, or container tag.
|
||||
|
||||
## Release flow
|
||||
|
||||
Entirely in CI via `.github/workflows/release.yml`, triggered by a maintainer from the GitHub Actions UI:
|
||||
Stable runs entirely in CI via `.github/workflows/release.yml`, triggered by a maintainer from the GitHub Actions UI:
|
||||
|
||||
1. Maintainer clicks "Run workflow" → picks `bump` (patch/minor/major) → optional `dry_run` or `desktop_validation_only`.
|
||||
1. Maintainer clicks "Run workflow" → keeps `channel=stable` → picks `bump` (patch/minor/major) → optional `dry_run` or `desktop_validation_only`.
|
||||
2. `prepare` job bumps version + regenerates CHANGELOG, opens release PR, squash-merges, tags `vX.Y.Z`.
|
||||
3. `build-web` + `build-cli` + `build-bundles` (5 platforms) build the release artifacts.
|
||||
4. `publish-release` creates the GitHub release with platform tarballs + sha256 + auto-generated notes.
|
||||
5. `publish-npm` publishes 5 `@kdlbs/runtime-*` packages + main `kandev` package to npmjs.
|
||||
6. `update-homebrew-tap` pushes updated `Formula/kandev.rb` to `kdlbs/homebrew-kandev` via SSH deploy key.
|
||||
|
||||
There is no local release script — the entire flow runs in GHA.
|
||||
Stable has no local release driver; the entire Stable flow runs in GHA. The Nightly metadata and
|
||||
publication revalidation state machine lives in `scripts/release/nightly-release.sh`, which GHA
|
||||
invokes for scheduled and manual Nightly runs.
|
||||
|
||||
The same workflow schedules npm Nightly with cron `0 12 * * *`. It skips before building when
|
||||
`main` has no commit after the latest Stable tag, the exact commit is already published, or a same
|
||||
or newer `main` Nightly supersedes the scheduled commit. Eligible runs build only the shared web
|
||||
bundle and five native runtime archives, then publish runtimes first and `kandev` last with OIDC
|
||||
provenance. Stable and Nightly workflow runs share one non-cancelling release-wide concurrency
|
||||
slot. Before publishing, Nightly rechecks the stable Git/npm baseline and the previously observed
|
||||
`nightly` tag; a pending Stable tag or moved value safely suppresses stale publication.
|
||||
|
||||
Maintainers may run that same Nightly path from the Actions UI with the `main` ref and
|
||||
`channel=nightly`. `dry_run=true` retains the real metadata and registry preflight but skips shared
|
||||
builds and all npm writes. The shared form's required `bump` value is ignored for Nightly;
|
||||
`desktop_validation_only` and `backfill_tag` are Stable-only and rejected when combined with it.
|
||||
|
||||
Validate Nightly automation changes with:
|
||||
|
||||
```bash
|
||||
node --test scripts/release/nightly-version.test.mjs scripts/release/nightly-release.test.mjs
|
||||
python3 .github/scripts/release-workflow-contract_test.py
|
||||
bash -n scripts/release/nightly-release.sh scripts/release/publish-npm.sh
|
||||
```
|
||||
|
||||
## Release-tag signing configuration
|
||||
|
||||
|
||||
@@ -12,12 +12,14 @@ REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
WORKFLOW_PATH = REPO_ROOT / ".github" / "workflows" / "release.yml"
|
||||
DIAGNOSTICS_PATH = REPO_ROOT / ".github" / "scripts" / "collect-macos-desktop-diagnostics.sh"
|
||||
PUBLISH_NPM_PATH = REPO_ROOT / "scripts" / "release" / "publish-npm.sh"
|
||||
NPM_PACKAGES_PATH = REPO_ROOT / "scripts" / "release" / "npm-packages.sh"
|
||||
PUBLIC_KEY_PATH = REPO_ROOT / ".github" / "release-signing-key.asc"
|
||||
RELEASE_PROCESS_PATH = REPO_ROOT / "docs" / "public" / "release-process.md"
|
||||
LINT_WORKFLOW_PATH = REPO_ROOT / ".github" / "workflows" / "lint-action-pinning.yml"
|
||||
WORKFLOW = WORKFLOW_PATH.read_text()
|
||||
DIAGNOSTICS = DIAGNOSTICS_PATH.read_text()
|
||||
PUBLISH_NPM = PUBLISH_NPM_PATH.read_text()
|
||||
NPM_PACKAGES = NPM_PACKAGES_PATH.read_text()
|
||||
RELEASE_PROCESS = RELEASE_PROCESS_PATH.read_text()
|
||||
LINT_WORKFLOW = LINT_WORKFLOW_PATH.read_text()
|
||||
NORMAL_RELEASE_IF = (
|
||||
@@ -46,7 +48,195 @@ def job_block(name: str) -> str:
|
||||
return WORKFLOW[start:end]
|
||||
|
||||
|
||||
def job_condition(name: str) -> str:
|
||||
match = re.search(r"(?m)^ if: [^\n]*(?:\n {6,}[^\n]*)*", job_block(name))
|
||||
if match is None:
|
||||
raise AssertionError(f"job condition not found: {name}")
|
||||
return " ".join(match.group().split())
|
||||
|
||||
|
||||
class ReleaseWorkflowContractTest(unittest.TestCase):
|
||||
def test_nightly_runs_on_schedule_or_manual_channel_and_delegates_metadata_resolution(
|
||||
self,
|
||||
) -> None:
|
||||
self.assertIn('schedule:\n - cron: "0 12 * * *"', WORKFLOW)
|
||||
self.assertRegex(
|
||||
WORKFLOW,
|
||||
r"(?ms) channel:\n"
|
||||
r" description: \"Release channel\"\n"
|
||||
r" required: true\n"
|
||||
r" type: choice\n"
|
||||
r" default: stable\n"
|
||||
r" options:\n"
|
||||
r" - stable\n"
|
||||
r" - nightly",
|
||||
)
|
||||
|
||||
nightly = job_block("nightly-prepare")
|
||||
self.assertIn("github.event_name == 'schedule'", nightly)
|
||||
self.assertIn(
|
||||
"github.event_name == 'workflow_dispatch' && inputs.channel == 'nightly'",
|
||||
nightly,
|
||||
)
|
||||
self.assertIn("ref: ${{ github.sha }}", nightly)
|
||||
validation = step_block("Validate manual Nightly request")
|
||||
self.assertIn("refs/heads/main", validation)
|
||||
self.assertIn("DESKTOP_VALIDATION_ONLY", validation)
|
||||
self.assertIn("BACKFILL_TAG", validation)
|
||||
metadata = step_block("Resolve nightly metadata")
|
||||
self.assertIn("id: metadata", metadata)
|
||||
self.assertIn("bash scripts/release/nightly-release.sh prepare", metadata)
|
||||
self.assertIn('--scheduled-sha "${{ github.sha }}"', metadata)
|
||||
self.assertIn('--output "$GITHUB_OUTPUT"', metadata)
|
||||
self.assertNotIn("npm-view-version.sh", metadata)
|
||||
self.assertIn(
|
||||
"nightly_tags_at_start: ${{ steps.metadata.outputs.nightly_tags_at_start }}",
|
||||
nightly,
|
||||
)
|
||||
|
||||
def test_manual_nightly_dry_run_stops_after_preflight(self) -> None:
|
||||
summary = step_block("Nightly dry-run summary")
|
||||
self.assertIn("github.event_name == 'workflow_dispatch' && inputs.dry_run", summary)
|
||||
self.assertIn("steps.metadata.outputs.should_publish", summary)
|
||||
self.assertIn("steps.metadata.outputs.version", summary)
|
||||
|
||||
for name in ("build-web", "build-bundles", "publish-npm-nightly"):
|
||||
condition = job_condition(name)
|
||||
self.assertIn("inputs.channel == 'nightly'", condition)
|
||||
self.assertIn("!inputs.dry_run", condition)
|
||||
|
||||
for name in ("build-web", "build-bundles"):
|
||||
block = job_block(name)
|
||||
self.assertIn(
|
||||
"needs.nightly-prepare.result == 'success' && "
|
||||
"needs.nightly-prepare.outputs.ref || needs.prepare.outputs.ref",
|
||||
block,
|
||||
)
|
||||
self.assertIn(
|
||||
"needs.nightly-prepare.result == 'success' && "
|
||||
"needs.nightly-prepare.outputs.tag || needs.prepare.outputs.tag",
|
||||
block,
|
||||
)
|
||||
|
||||
def test_nightly_package_inventory_remains_shared(self) -> None:
|
||||
for package in (
|
||||
"kandev",
|
||||
"@kdlbs/runtime-linux-x64",
|
||||
"@kdlbs/runtime-linux-arm64",
|
||||
"@kdlbs/runtime-darwin-x64",
|
||||
"@kdlbs/runtime-darwin-arm64",
|
||||
"@kdlbs/runtime-win32-x64",
|
||||
):
|
||||
self.assertIn(package, NPM_PACKAGES)
|
||||
|
||||
self.assertIn('NIGHTLY_PACKAGES=("kandev" "${RUNTIME_PACKAGES[@]}")', NPM_PACKAGES)
|
||||
|
||||
def test_only_shared_runtime_builds_run_for_a_scheduled_nightly(self) -> None:
|
||||
for name in ("build-web", "build-bundles"):
|
||||
block = job_block(name)
|
||||
self.assertIn("needs: [prepare, nightly-prepare", block)
|
||||
self.assertIn("github.event_name == 'workflow_dispatch'", block)
|
||||
self.assertIn("github.event_name == 'schedule'", block)
|
||||
self.assertIn("inputs.channel == 'nightly'", block)
|
||||
self.assertIn("needs.nightly-prepare.outputs.should_publish == 'true'", block)
|
||||
|
||||
for name in (
|
||||
"prepare",
|
||||
"build-desktop",
|
||||
"docker-amd64",
|
||||
"docker-arm64",
|
||||
"docker-manifest",
|
||||
"docker-universal-amd64",
|
||||
"docker-universal-arm64",
|
||||
"docker-universal-manifest",
|
||||
"publish-release",
|
||||
"publish-npm",
|
||||
"update-homebrew-tap",
|
||||
):
|
||||
block = job_block(name)
|
||||
self.assertIn("github.event_name == 'workflow_dispatch'", block)
|
||||
self.assertIn("inputs.channel == 'stable'", block)
|
||||
self.assertNotIn("github.event_name == 'schedule'", block)
|
||||
|
||||
def test_nightly_publish_uses_exact_sha_local_assets_and_release_serialization(self) -> None:
|
||||
stable = job_block("publish-npm")
|
||||
nightly = job_block("publish-npm-nightly")
|
||||
|
||||
workflow_preamble = WORKFLOW.split("\njobs:", 1)[0]
|
||||
self.assertIn("group: release-npm-publication", workflow_preamble)
|
||||
self.assertIn("cancel-in-progress: false", workflow_preamble)
|
||||
self.assertIn("queue: max", workflow_preamble)
|
||||
|
||||
for block in (stable, nightly):
|
||||
self.assertNotIn("\n concurrency:", block)
|
||||
self.assertIn("id-token: write", block)
|
||||
|
||||
self.assertIn("needs: [nightly-prepare, build-bundles]", nightly)
|
||||
self.assertIn("needs.build-bundles.result == 'success'", nightly)
|
||||
self.assertIn("needs.build-web.result == 'success'", job_block("build-bundles"))
|
||||
self.assertIn("ref: ${{ needs.nightly-prepare.outputs.ref }}", nightly)
|
||||
self.assertIn("fetch-depth: 0", nightly)
|
||||
self.assertIn("pattern: bundle-*", nightly)
|
||||
self.assertIn("merge-multiple: true", nightly)
|
||||
self.assertIn('--version "${{ needs.nightly-prepare.outputs.version }}"', nightly)
|
||||
self.assertIn('--assets-dir dist/nightly-assets', nightly)
|
||||
publish = step_block("Publish npm nightly packages")
|
||||
self.assertIn("bash scripts/release/nightly-release.sh publish", publish)
|
||||
self.assertIn('--stable-at-start "$NIGHTLY_BASELINE"', publish)
|
||||
self.assertIn('--nightly-at-start "$NIGHTLY_AT_START"', publish)
|
||||
self.assertIn('--tags-at-start "$NIGHTLY_TAGS_AT_START"', publish)
|
||||
self.assertIn(
|
||||
"NIGHTLY_TAGS_AT_START: ${{ needs.nightly-prepare.outputs.nightly_tags_at_start }}",
|
||||
nightly,
|
||||
)
|
||||
self.assertNotIn("npm-view-version.sh", publish)
|
||||
self.assertNotIn("publish-npm.sh", publish)
|
||||
|
||||
self.assertIn('--version "${{ needs.prepare.outputs.version }}"', stable)
|
||||
self.assertIn('--dist-tag latest', stable)
|
||||
self.assertIn('--release-tag "${{ needs.prepare.outputs.tag }}"', stable)
|
||||
|
||||
self.assertIn('elif [[ "$DIST_TAG" == "latest" && -z "$RELEASE_TAG" ]]', PUBLISH_NPM)
|
||||
self.assertIn(
|
||||
'elif [[ "$DIST_TAG" == "nightly" && -z "$SOURCE_ASSETS_DIR" ]]',
|
||||
PUBLISH_NPM,
|
||||
)
|
||||
self.assertIn('bash "$ROOT_DIR/scripts/release/npm-view-version.sh"', PUBLISH_NPM)
|
||||
self.assertIn('CLI_PACKAGE_BACKUP="$WORK_DIR/cli-package.json"', PUBLISH_NPM)
|
||||
self.assertIn('cp "$CLI_PACKAGE_BACKUP" "$CLI_PACKAGE_JSON"', PUBLISH_NPM)
|
||||
|
||||
def test_publish_npm_rejects_version_dist_tag_mismatches(self) -> None:
|
||||
cases = (
|
||||
(
|
||||
"1.2.3-nightly.shaabcdef123456",
|
||||
"latest",
|
||||
"--version must be stable X.Y.Z for --dist-tag latest",
|
||||
),
|
||||
(
|
||||
"1.2.3",
|
||||
"nightly",
|
||||
"--version must be X.Y.Z-nightly.sha<12-hex> for --dist-tag nightly",
|
||||
),
|
||||
)
|
||||
for version, dist_tag, expected in cases:
|
||||
with self.subTest(dist_tag=dist_tag):
|
||||
result = subprocess.run(
|
||||
[
|
||||
"bash",
|
||||
str(PUBLISH_NPM_PATH),
|
||||
"--version",
|
||||
version,
|
||||
"--dist-tag",
|
||||
dist_tag,
|
||||
],
|
||||
cwd=REPO_ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn(expected, result.stderr)
|
||||
|
||||
def test_normal_release_uses_release_environment_and_requires_main(self) -> None:
|
||||
prepare = job_block("prepare")
|
||||
self.assertIn(
|
||||
@@ -211,6 +401,33 @@ class ReleaseWorkflowContractTest(unittest.TestCase):
|
||||
self.assertIsNotNone(trigger_block)
|
||||
self.assertIn('".github/release-signing-key.asc"', trigger_block.group(0))
|
||||
self.assertIn('"docs/public/release-process.md"', trigger_block.group(0))
|
||||
self.assertIn('"scripts/release/package-npm-runtime.sh"', trigger_block.group(0))
|
||||
self.assertIn('"scripts/release/publish-npm.sh"', trigger_block.group(0))
|
||||
self.assertIn('"scripts/release/publish-npm.test.mjs"', trigger_block.group(0))
|
||||
self.assertIn('"scripts/release/npm-packages.sh"', trigger_block.group(0))
|
||||
self.assertIn('"scripts/release/npm-view-version.sh"', trigger_block.group(0))
|
||||
self.assertIn('"scripts/release/npm-view-version.test.mjs"', trigger_block.group(0))
|
||||
self.assertIn('"scripts/release/nightly-version.mjs"', trigger_block.group(0))
|
||||
self.assertIn('"scripts/release/nightly-version.test.mjs"', trigger_block.group(0))
|
||||
self.assertIn('"scripts/release/nightly-release.sh"', trigger_block.group(0))
|
||||
self.assertIn('"scripts/release/nightly-release.test.mjs"', trigger_block.group(0))
|
||||
|
||||
setup_node = (
|
||||
"uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6"
|
||||
)
|
||||
self.assertIn(setup_node, LINT_WORKFLOW)
|
||||
self.assertIn('node-version: "24"', LINT_WORKFLOW)
|
||||
self.assertLess(
|
||||
LINT_WORKFLOW.index(setup_node),
|
||||
LINT_WORKFLOW.index("- name: Test npm release helpers"),
|
||||
)
|
||||
self.assertIn(
|
||||
"node --test scripts/release/nightly-version.test.mjs "
|
||||
"scripts/release/nightly-release.test.mjs "
|
||||
"scripts/release/npm-view-version.test.mjs "
|
||||
"scripts/release/publish-npm.test.mjs",
|
||||
LINT_WORKFLOW,
|
||||
)
|
||||
|
||||
def test_tag_push_recovery_recreates_tag_at_logged_merge_commit(self) -> None:
|
||||
tag = step_block("Create and push signed release tag")
|
||||
@@ -235,7 +452,7 @@ class ReleaseWorkflowContractTest(unittest.TestCase):
|
||||
"@kdlbs/runtime-darwin-arm64",
|
||||
"@kdlbs/runtime-win32-x64",
|
||||
):
|
||||
self.assertIn(f'"{package}"', PUBLISH_NPM)
|
||||
self.assertIn(f'"{package}"', NPM_PACKAGES)
|
||||
|
||||
def test_backfill_tag_input_uses_existing_tag_without_recreating_it(self) -> None:
|
||||
self.assertIn("backfill_tag:", WORKFLOW)
|
||||
@@ -284,7 +501,10 @@ class ReleaseWorkflowContractTest(unittest.TestCase):
|
||||
"update-homebrew-tap",
|
||||
):
|
||||
block = job_block(name)
|
||||
self.assertIn("if: ${{ !inputs.dry_run", block)
|
||||
self.assertRegex(
|
||||
job_condition(name),
|
||||
r"github\.event_name == 'workflow_dispatch'.*!inputs\.dry_run",
|
||||
)
|
||||
self.assertNotIn("inputs.backfill_tag == ''", block)
|
||||
|
||||
def test_updater_signing_validation_uses_workflow_control_revision(self) -> None:
|
||||
|
||||
@@ -12,6 +12,16 @@ on:
|
||||
- ".github/scripts/release-workflow-contract_test.py"
|
||||
- ".github/release-signing-key.asc"
|
||||
- "docs/public/release-process.md"
|
||||
- "scripts/release/npm-packages.sh"
|
||||
- "scripts/release/nightly-version.mjs"
|
||||
- "scripts/release/nightly-version.test.mjs"
|
||||
- "scripts/release/nightly-release.sh"
|
||||
- "scripts/release/nightly-release.test.mjs"
|
||||
- "scripts/release/npm-view-version.sh"
|
||||
- "scripts/release/npm-view-version.test.mjs"
|
||||
- "scripts/release/package-npm-runtime.sh"
|
||||
- "scripts/release/publish-npm.sh"
|
||||
- "scripts/release/publish-npm.test.mjs"
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths:
|
||||
@@ -23,6 +33,16 @@ on:
|
||||
- ".github/scripts/release-workflow-contract_test.py"
|
||||
- ".github/release-signing-key.asc"
|
||||
- "docs/public/release-process.md"
|
||||
- "scripts/release/npm-packages.sh"
|
||||
- "scripts/release/nightly-version.mjs"
|
||||
- "scripts/release/nightly-version.test.mjs"
|
||||
- "scripts/release/nightly-release.sh"
|
||||
- "scripts/release/nightly-release.test.mjs"
|
||||
- "scripts/release/npm-view-version.sh"
|
||||
- "scripts/release/npm-view-version.test.mjs"
|
||||
- "scripts/release/package-npm-runtime.sh"
|
||||
- "scripts/release/publish-npm.sh"
|
||||
- "scripts/release/publish-npm.test.mjs"
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
@@ -52,5 +72,13 @@ jobs:
|
||||
- name: Test release workflow contract
|
||||
run: python3 .github/scripts/release-workflow-contract_test.py
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
|
||||
with:
|
||||
node-version: "24"
|
||||
|
||||
- name: Test npm release helpers
|
||||
run: node --test scripts/release/nightly-version.test.mjs scripts/release/nightly-release.test.mjs scripts/release/npm-view-version.test.mjs scripts/release/publish-npm.test.mjs
|
||||
|
||||
- name: Verify action refs
|
||||
run: python3 .github/scripts/lint-action-pinning.py
|
||||
|
||||
+179
-26
@@ -1,7 +1,7 @@
|
||||
name: release
|
||||
|
||||
# Maintainer-only release workflow.
|
||||
# Trigger: GitHub Actions UI → "Run workflow" (workflow_dispatch).
|
||||
# Stable releases are maintainer-dispatched. npm nightlies run from main at
|
||||
# 12:00 UTC when main has changed since the latest stable npm release.
|
||||
#
|
||||
# Flow (one click → everything below):
|
||||
# 1. prepare — bump version, regen CHANGELOG, open + merge release PR, push tag vX.Y.Z
|
||||
@@ -39,10 +39,20 @@ name: release
|
||||
# TAURI_SIGNING_PRIVATE_KEY / TAURI_SIGNING_PRIVATE_KEY_PASSWORD — updater artifact signing
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 12 * * *"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
channel:
|
||||
description: "Release channel"
|
||||
required: true
|
||||
type: choice
|
||||
default: stable
|
||||
options:
|
||||
- stable
|
||||
- nightly
|
||||
bump:
|
||||
description: "Version bump"
|
||||
description: "Stable only: version bump"
|
||||
required: true
|
||||
type: choice
|
||||
default: minor
|
||||
@@ -51,19 +61,26 @@ on:
|
||||
- minor
|
||||
- major
|
||||
dry_run:
|
||||
description: "Dry run (no PR, tag, npm publish, or tap update)"
|
||||
description: "Validate selected channel without publishing"
|
||||
type: boolean
|
||||
default: false
|
||||
desktop_validation_only:
|
||||
description: "Build desktop artifacts only (no PR, tag, publish, npm, or tap update)"
|
||||
description: "Stable only: build desktop artifacts without publishing"
|
||||
type: boolean
|
||||
default: false
|
||||
backfill_tag:
|
||||
description: "Existing release tag to rebuild/publish (for recovery; leave empty for normal release)"
|
||||
description: "Stable only: existing release tag to rebuild/publish"
|
||||
required: false
|
||||
default: ""
|
||||
type: string
|
||||
|
||||
# A Stable tag is pushed before its npm job is ready. Serializing whole runs
|
||||
# prevents a Nightly from using the previous npm baseline during that window.
|
||||
concurrency:
|
||||
group: release-npm-publication
|
||||
cancel-in-progress: false
|
||||
queue: max
|
||||
|
||||
# Default to read-only at the workflow level. Each job opts into the writes
|
||||
# it actually needs.
|
||||
permissions:
|
||||
@@ -72,6 +89,7 @@ permissions:
|
||||
jobs:
|
||||
prepare:
|
||||
name: Prepare release (bump version, PR, tag)
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.channel == 'stable' }}
|
||||
runs-on: ubuntu-latest
|
||||
environment: ${{ (!inputs.dry_run && !inputs.desktop_validation_only && inputs.backfill_tag == '') && 'release' || 'release-validation' }}
|
||||
permissions:
|
||||
@@ -574,15 +592,91 @@ jobs:
|
||||
echo "DRY RUN: apps/cli/package.json bumped to $NEXT (in-runner only)."
|
||||
echo "DRY RUN: CHANGELOG.md regenerated (in-runner only)."
|
||||
|
||||
nightly-prepare:
|
||||
name: Prepare npm nightly metadata
|
||||
if: >-
|
||||
${{
|
||||
github.event_name == 'schedule' ||
|
||||
(github.event_name == 'workflow_dispatch' && inputs.channel == 'nightly')
|
||||
}}
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
should_publish: ${{ steps.metadata.outputs.should_publish }}
|
||||
version: ${{ steps.metadata.outputs.version }}
|
||||
tag: ${{ steps.metadata.outputs.tag }}
|
||||
ref: ${{ steps.metadata.outputs.ref }}
|
||||
stable_version: ${{ steps.metadata.outputs.stable_version }}
|
||||
nightly_version_at_start: ${{ steps.metadata.outputs.nightly_version_at_start }}
|
||||
nightly_tags_at_start: ${{ steps.metadata.outputs.nightly_tags_at_start }}
|
||||
steps:
|
||||
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
|
||||
with:
|
||||
node-version: "24"
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
|
||||
- name: Validate manual Nightly request
|
||||
if: ${{ github.event_name == 'workflow_dispatch' }}
|
||||
env:
|
||||
CURRENT_REF: ${{ github.ref }}
|
||||
DESKTOP_VALIDATION_ONLY: ${{ inputs.desktop_validation_only }}
|
||||
BACKFILL_TAG: ${{ inputs.backfill_tag }}
|
||||
BUMP: ${{ inputs.bump }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ "$CURRENT_REF" != "refs/heads/main" ]; then
|
||||
echo "Manual Nightlies must be dispatched from refs/heads/main (got $CURRENT_REF)." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ "$DESKTOP_VALIDATION_ONLY" = "true" ]; then
|
||||
echo "desktop_validation_only cannot be combined with channel=nightly." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ -n "$BACKFILL_TAG" ]; then
|
||||
echo "backfill_tag cannot be combined with channel=nightly." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "::notice::The Stable-only bump input ($BUMP) is ignored for Nightly."
|
||||
|
||||
- name: Resolve nightly metadata
|
||||
id: metadata
|
||||
run: |
|
||||
bash scripts/release/nightly-release.sh prepare \
|
||||
--scheduled-sha "${{ github.sha }}" \
|
||||
--output "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Nightly dry-run summary
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }}
|
||||
env:
|
||||
SHOULD_PUBLISH: ${{ steps.metadata.outputs.should_publish }}
|
||||
VERSION: ${{ steps.metadata.outputs.version }}
|
||||
REF: ${{ steps.metadata.outputs.ref }}
|
||||
run: |
|
||||
if [ "$SHOULD_PUBLISH" = "true" ]; then
|
||||
echo "DRY RUN: Would publish $VERSION from $REF under npm's nightly dist-tag."
|
||||
else
|
||||
echo "DRY RUN: Nightly preflight found no eligible publication."
|
||||
fi
|
||||
echo "DRY RUN: No bundles were built and npm was not changed."
|
||||
|
||||
build-web:
|
||||
name: Build web SPA
|
||||
needs: prepare
|
||||
if: ${{ !inputs.dry_run }}
|
||||
needs: [prepare, nightly-prepare]
|
||||
if: >-
|
||||
${{ !cancelled() && (
|
||||
(github.event_name == 'workflow_dispatch' && inputs.channel == 'stable' && needs.prepare.result == 'success' && !inputs.dry_run) ||
|
||||
((github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.channel == 'nightly' && !inputs.dry_run)) && needs.nightly-prepare.result == 'success' && needs.nightly-prepare.outputs.should_publish == 'true')
|
||||
) }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
|
||||
with:
|
||||
ref: ${{ needs.prepare.outputs.ref }}
|
||||
ref: ${{ needs.nightly-prepare.result == 'success' && needs.nightly-prepare.outputs.ref || needs.prepare.outputs.ref }}
|
||||
persist-credentials: false
|
||||
- uses: pnpm/action-setup@a8198c4bff370c8506180b035930dea56dbd5288 # v5
|
||||
with:
|
||||
@@ -596,7 +690,7 @@ jobs:
|
||||
run: pnpm -C apps install --frozen-lockfile
|
||||
- name: Build web (Vite)
|
||||
env:
|
||||
KANDEV_VERSION: ${{ needs.prepare.outputs.tag }}
|
||||
KANDEV_VERSION: ${{ needs.nightly-prepare.result == 'success' && needs.nightly-prepare.outputs.tag || needs.prepare.outputs.tag }}
|
||||
VITE_KANDEV_API_PORT: ""
|
||||
VITE_KANDEV_DEBUG: ""
|
||||
run: pnpm -C apps --filter @kandev/web build
|
||||
@@ -608,8 +702,12 @@ jobs:
|
||||
|
||||
build-bundles:
|
||||
name: Build platform bundle (${{ matrix.platform }})
|
||||
needs: [prepare, build-web]
|
||||
if: ${{ !inputs.dry_run }}
|
||||
needs: [prepare, nightly-prepare, build-web]
|
||||
if: >-
|
||||
${{ !cancelled() && needs.build-web.result == 'success' && (
|
||||
(github.event_name == 'workflow_dispatch' && inputs.channel == 'stable' && needs.prepare.result == 'success' && !inputs.dry_run) ||
|
||||
((github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.channel == 'nightly' && !inputs.dry_run)) && needs.nightly-prepare.result == 'success' && needs.nightly-prepare.outputs.should_publish == 'true')
|
||||
) }}
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
@@ -642,7 +740,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
|
||||
with:
|
||||
ref: ${{ needs.prepare.outputs.ref }}
|
||||
ref: ${{ needs.nightly-prepare.result == 'success' && needs.nightly-prepare.outputs.ref || needs.prepare.outputs.ref }}
|
||||
persist-credentials: false
|
||||
- uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6
|
||||
with:
|
||||
@@ -671,7 +769,7 @@ jobs:
|
||||
- name: Build backend binaries
|
||||
env:
|
||||
CC: ${{ matrix.cc || '' }}
|
||||
KANDEV_VERSION: ${{ needs.prepare.outputs.tag }}
|
||||
KANDEV_VERSION: ${{ needs.nightly-prepare.result == 'success' && needs.nightly-prepare.outputs.tag || needs.prepare.outputs.tag }}
|
||||
run: |
|
||||
test -f apps/backend/internal/webapp/embedded/generated/index.html
|
||||
cd apps/backend
|
||||
@@ -725,7 +823,7 @@ jobs:
|
||||
build-desktop:
|
||||
name: Build desktop app (${{ matrix.platform }})
|
||||
needs: [prepare, build-bundles]
|
||||
if: ${{ !inputs.dry_run }}
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.channel == 'stable' && !inputs.dry_run }}
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
@@ -1271,7 +1369,7 @@ jobs:
|
||||
docker-amd64:
|
||||
name: Build & push container image (amd64)
|
||||
needs: [prepare, build-bundles]
|
||||
if: ${{ !inputs.dry_run && !inputs.desktop_validation_only }}
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.channel == 'stable' && !inputs.dry_run && !inputs.desktop_validation_only }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -1342,7 +1440,7 @@ jobs:
|
||||
docker-arm64:
|
||||
name: Build & push container image (arm64)
|
||||
needs: [prepare, build-bundles]
|
||||
if: ${{ !inputs.dry_run && !inputs.desktop_validation_only }}
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.channel == 'stable' && !inputs.dry_run && !inputs.desktop_validation_only }}
|
||||
runs-on: ubuntu-24.04-arm
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -1401,7 +1499,7 @@ jobs:
|
||||
docker-manifest:
|
||||
name: Assemble multi-arch base manifest
|
||||
needs: [prepare, docker-amd64, docker-arm64]
|
||||
if: ${{ !inputs.dry_run && !inputs.desktop_validation_only }}
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.channel == 'stable' && !inputs.dry_run && !inputs.desktop_validation_only }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -1455,7 +1553,7 @@ jobs:
|
||||
docker-universal-amd64:
|
||||
name: Build & push universal image (amd64)
|
||||
needs: [prepare, docker-manifest]
|
||||
if: ${{ !inputs.dry_run && !inputs.desktop_validation_only }}
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.channel == 'stable' && !inputs.dry_run && !inputs.desktop_validation_only }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -1507,7 +1605,7 @@ jobs:
|
||||
docker-universal-arm64:
|
||||
name: Build & push universal image (arm64)
|
||||
needs: [prepare, docker-manifest]
|
||||
if: ${{ !inputs.dry_run && !inputs.desktop_validation_only }}
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.channel == 'stable' && !inputs.dry_run && !inputs.desktop_validation_only }}
|
||||
runs-on: ubuntu-24.04-arm
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -1558,7 +1656,7 @@ jobs:
|
||||
# docker-universal-manifest is included in publish-release's `needs` so
|
||||
# its size gate (and any per-arch build failure) blocks the release.
|
||||
needs: [prepare, docker-universal-amd64, docker-universal-arm64]
|
||||
if: ${{ !inputs.dry_run && !inputs.desktop_validation_only }}
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.channel == 'stable' && !inputs.dry_run && !inputs.desktop_validation_only }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -1615,7 +1713,7 @@ jobs:
|
||||
publish-release:
|
||||
name: Publish GitHub release
|
||||
needs: [prepare, build-bundles, build-desktop, docker-universal-manifest]
|
||||
if: ${{ !inputs.dry_run && !inputs.desktop_validation_only }}
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.channel == 'stable' && !inputs.dry_run && !inputs.desktop_validation_only }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write # softprops/action-gh-release creates the release
|
||||
@@ -1765,7 +1863,7 @@ jobs:
|
||||
publish-npm:
|
||||
name: Publish npm packages
|
||||
needs: [prepare, publish-release]
|
||||
if: ${{ !inputs.dry_run && !inputs.desktop_validation_only }}
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.channel == 'stable' && !inputs.dry_run && !inputs.desktop_validation_only }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
id-token: write # Required for OIDC trusted publishing
|
||||
@@ -1794,13 +1892,68 @@ jobs:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
bash scripts/release/publish-npm.sh \
|
||||
"${{ needs.prepare.outputs.version }}" \
|
||||
"${{ needs.prepare.outputs.tag }}"
|
||||
--version "${{ needs.prepare.outputs.version }}" \
|
||||
--dist-tag latest \
|
||||
--release-tag "${{ needs.prepare.outputs.tag }}"
|
||||
|
||||
publish-npm-nightly:
|
||||
name: Publish npm nightly packages
|
||||
needs: [nightly-prepare, build-bundles]
|
||||
if: >-
|
||||
${{ !cancelled() &&
|
||||
(github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.channel == 'nightly' && !inputs.dry_run)) &&
|
||||
needs.nightly-prepare.result == 'success' &&
|
||||
needs.nightly-prepare.outputs.should_publish == 'true' &&
|
||||
needs.build-bundles.result == 'success'
|
||||
}}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
id-token: write # Required for OIDC trusted publishing
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
|
||||
with:
|
||||
ref: ${{ needs.nightly-prepare.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- uses: pnpm/action-setup@a8198c4bff370c8506180b035930dea56dbd5288 # v5
|
||||
with:
|
||||
version: "9.15.9"
|
||||
|
||||
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
|
||||
with:
|
||||
node-version: "24"
|
||||
registry-url: "https://registry.npmjs.org"
|
||||
cache: pnpm
|
||||
cache-dependency-path: apps/pnpm-lock.yaml
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm -C apps install --frozen-lockfile
|
||||
|
||||
- uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0 # v5
|
||||
with:
|
||||
pattern: bundle-*
|
||||
path: dist/nightly-assets
|
||||
merge-multiple: true
|
||||
|
||||
- name: Publish npm nightly packages
|
||||
env:
|
||||
NIGHTLY_BASELINE: ${{ needs.nightly-prepare.outputs.stable_version }}
|
||||
NIGHTLY_AT_START: ${{ needs.nightly-prepare.outputs.nightly_version_at_start }}
|
||||
NIGHTLY_TAGS_AT_START: ${{ needs.nightly-prepare.outputs.nightly_tags_at_start }}
|
||||
run: |
|
||||
bash scripts/release/nightly-release.sh publish \
|
||||
--stable-at-start "$NIGHTLY_BASELINE" \
|
||||
--nightly-at-start "$NIGHTLY_AT_START" \
|
||||
--tags-at-start "$NIGHTLY_TAGS_AT_START" \
|
||||
--version "${{ needs.nightly-prepare.outputs.version }}" \
|
||||
--assets-dir dist/nightly-assets
|
||||
|
||||
update-homebrew-tap:
|
||||
name: Update Homebrew tap
|
||||
needs: [prepare, publish-release]
|
||||
if: ${{ !inputs.dry_run && !inputs.desktop_validation_only }}
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.channel == 'stable' && !inputs.dry_run && !inputs.desktop_validation_only }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
|
||||
|
||||
@@ -36,7 +36,7 @@ repos:
|
||||
|
||||
- id: go-lint
|
||||
name: Go lint (PR changed code)
|
||||
entry: bash -c 'unset GIT_DIR GIT_WORK_TREE; base=$(git merge-base HEAD origin/main 2>/dev/null || git rev-parse HEAD); cd apps/backend && golangci-lint run ./... --new-from-rev="$base" --timeout=5m'
|
||||
entry: bash -c 'unset GIT_DIR GIT_WORK_TREE; merge_head=$(git rev-parse --verify MERGE_HEAD 2>/dev/null || true); base_tip=$(git rev-parse --verify origin/main 2>/dev/null || true); if [[ -n "$merge_head" && "$merge_head" == "$base_tip" ]]; then base="$merge_head"; else base=$(git merge-base HEAD origin/main 2>/dev/null || git rev-parse HEAD); fi; cd apps/backend && golangci-lint run ./... --new-from-rev="$base" --timeout=5m'
|
||||
language: system
|
||||
files: ^apps/backend/.*\.go$
|
||||
pass_filenames: false
|
||||
|
||||
@@ -53,7 +53,7 @@ The commitlint hook caps the header at **100 characters** (`type(scope): descrip
|
||||
|
||||
### Release & Versioning
|
||||
|
||||
Kandev uses a **single SemVer** `X.Y.Z` across npm, Homebrew, and GitHub release; release flow runs entirely in CI via `.github/workflows/release.yml`. Full details in the `/release` skill — load it when cutting a release or debugging release artifacts.
|
||||
Stable Kandev releases use one **SemVer** `X.Y.Z` across npm, Homebrew, GitHub Releases, Desktop, and containers. Scheduled npm-only Nightlies use `X.Y.(Z+1)-nightly.sha<12-hex>` without moving any Stable channel. Both flows run in `.github/workflows/release.yml`. Full details are in the `/release` skill — load it when cutting a release, changing version channels, or debugging release artifacts.
|
||||
|
||||
### Code Quality
|
||||
|
||||
|
||||
@@ -501,6 +501,8 @@ test-scripts:
|
||||
@python3 scripts/lint-architecture.test.py
|
||||
@bash scripts/release-desktop.test.sh
|
||||
@node --test apps/desktop/e2e/desktop-launch-smoke.test.mjs
|
||||
@python3 .github/scripts/release-workflow-contract_test.py
|
||||
@node --test scripts/release/nightly-version.test.mjs scripts/release/nightly-release.test.mjs scripts/release/npm-view-version.test.mjs scripts/release/publish-npm.test.mjs
|
||||
@node --test scripts/validate-public-docs.test.mjs
|
||||
|
||||
.PHONY: test-e2e
|
||||
|
||||
@@ -148,6 +148,23 @@ kandev
|
||||
- `npx kandev@latest` (always uses the latest published version)
|
||||
- `npm install -g kandev@latest`
|
||||
|
||||
To try the current prerelease from `main`, use npm's `nightly` tag:
|
||||
|
||||
```bash
|
||||
npx -y kandev@nightly
|
||||
# or
|
||||
npm install -g kandev@nightly
|
||||
```
|
||||
|
||||
`npx` runs a transient Nightly without changing a global package. The global install replaces your
|
||||
installed Kandev until you reinstall `kandev@latest`.
|
||||
|
||||
Nightlies are best-effort builds scheduled for 12:00 UTC when `main` has changed since the latest
|
||||
stable release. They do not move `latest`, and no Homebrew or Desktop nightly channel is published.
|
||||
A verified Kandev-managed npm/npx user service can switch between Stable and Nightly in
|
||||
**Settings > System > Updates**. Other install types expose only Stable in that page; npm/npx users
|
||||
can still invoke `@nightly` directly with the commands above.
|
||||
|
||||
The worktrees and sqlite db live in `~/.kandev` by default. Works on macOS, Linux, and Windows (WSL or native).
|
||||
|
||||
### From Source
|
||||
|
||||
@@ -11,17 +11,45 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
metaKeyLatestVersion = "latest_version"
|
||||
metaKeyLatestVersionURL = "latest_version_url"
|
||||
metaKeyLatestVersionCheckedAt = "latest_version_checked_at"
|
||||
metaKeyLatestVersion = "latest_version"
|
||||
metaKeyLatestVersionURL = "latest_version_url"
|
||||
metaKeyLatestVersionCheckedAt = "latest_version_checked_at"
|
||||
metaKeyLatestNightlyVersion = "latest_version_nightly"
|
||||
metaKeyLatestNightlyVersionURL = "latest_version_nightly_url"
|
||||
metaKeyLatestNightlyVersionCheckedAt = "latest_version_nightly_checked_at"
|
||||
)
|
||||
|
||||
type latestVersionKeys struct {
|
||||
version string
|
||||
url string
|
||||
checkedAt string
|
||||
}
|
||||
|
||||
var stableLatestVersionKeys = latestVersionKeys{
|
||||
version: metaKeyLatestVersion,
|
||||
url: metaKeyLatestVersionURL,
|
||||
checkedAt: metaKeyLatestVersionCheckedAt,
|
||||
}
|
||||
|
||||
var nightlyLatestVersionKeys = latestVersionKeys{
|
||||
version: metaKeyLatestNightlyVersion,
|
||||
url: metaKeyLatestNightlyVersionURL,
|
||||
checkedAt: metaKeyLatestNightlyVersionCheckedAt,
|
||||
}
|
||||
|
||||
const metaTableDDL = `
|
||||
CREATE TABLE IF NOT EXISTS kandev_meta (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL DEFAULT ''
|
||||
)`
|
||||
|
||||
const metaKeyUpsert = `INSERT INTO kandev_meta (key, value) VALUES (?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value`
|
||||
|
||||
type metaKeyExecutor interface {
|
||||
Exec(query string, args ...interface{}) (sql.Result, error)
|
||||
}
|
||||
|
||||
// ensureMetaTable creates the kandev_meta table if it does not exist.
|
||||
func ensureMetaTable(db *sqlx.DB) error {
|
||||
if _, err := db.Exec(metaTableDDL); err != nil {
|
||||
@@ -45,15 +73,7 @@ func readKey(db *sqlx.DB, key string) (string, error) {
|
||||
|
||||
// writeKey upserts key=value into kandev_meta.
|
||||
func writeKey(db *sqlx.DB, key, value string) error {
|
||||
_, err := db.Exec(
|
||||
db.Rebind(`INSERT INTO kandev_meta (key, value) VALUES (?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value`),
|
||||
key, value,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("write meta key %q: %w", key, err)
|
||||
}
|
||||
return nil
|
||||
return writeMetaKey(db, db.Rebind(metaKeyUpsert), key, value)
|
||||
}
|
||||
|
||||
// WriteVersion records currentVersion as the binary version that last
|
||||
@@ -68,18 +88,34 @@ func WriteVersion(db *sqlx.DB, version string) error {
|
||||
|
||||
// WriteLatestVersion persists the highest semver tag from the GitHub Releases
|
||||
// poll, its release URL, and the timestamp of the successful poll. The three
|
||||
// values are written under separate keys (latest_version,
|
||||
// latest_version_url, latest_version_checked_at) on the existing key/value
|
||||
// kandev_meta table.
|
||||
// values use separate keys (latest_version, latest_version_url,
|
||||
// latest_version_checked_at) on the existing key/value kandev_meta table, but
|
||||
// the tuple is committed atomically.
|
||||
func WriteLatestVersion(db *sqlx.DB, version, url string, checkedAt time.Time) error {
|
||||
if err := writeKey(db, metaKeyLatestVersion, version); err != nil {
|
||||
return writeLatestVersion(db, stableLatestVersionKeys, version, url, checkedAt)
|
||||
}
|
||||
|
||||
func writeLatestVersion(db *sqlx.DB, keys latestVersionKeys, version, url string, checkedAt time.Time) error {
|
||||
tx, err := db.Beginx()
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin latest version write: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
query := db.Rebind(metaKeyUpsert)
|
||||
if err := writeMetaKey(tx, query, keys.version, version); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeKey(db, metaKeyLatestVersionURL, url); err != nil {
|
||||
if err := writeMetaKey(tx, query, keys.url, url); err != nil {
|
||||
return err
|
||||
}
|
||||
ts := strconv.FormatInt(checkedAt.UTC().Unix(), 10)
|
||||
return writeKey(db, metaKeyLatestVersionCheckedAt, ts)
|
||||
if err := writeMetaKey(tx, query, keys.checkedAt, ts); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("commit latest version write: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReadLatestVersion returns the last-known latest release tag, its URL, and
|
||||
@@ -87,29 +123,52 @@ func WriteLatestVersion(db *sqlx.DB, version, url string, checkedAt time.Time) e
|
||||
// the keys are absent (e.g. on a fresh install before the first poll
|
||||
// completes) and tolerates a subset of the three keys being missing.
|
||||
func ReadLatestVersion(db *sqlx.DB) (string, string, time.Time, error) {
|
||||
version, err := readKey(db, metaKeyLatestVersion)
|
||||
if err != nil {
|
||||
return "", "", time.Time{}, err
|
||||
}
|
||||
url, err := readKey(db, metaKeyLatestVersionURL)
|
||||
if err != nil {
|
||||
return "", "", time.Time{}, err
|
||||
}
|
||||
tsRaw, err := readKey(db, metaKeyLatestVersionCheckedAt)
|
||||
if err != nil {
|
||||
return "", "", time.Time{}, err
|
||||
return readLatestVersion(db, stableLatestVersionKeys)
|
||||
}
|
||||
|
||||
func readLatestVersion(db *sqlx.DB, keys latestVersionKeys) (string, string, time.Time, error) {
|
||||
query := db.Rebind(`SELECT
|
||||
COALESCE(MAX(CASE WHEN key = ? THEN value END), ''),
|
||||
COALESCE(MAX(CASE WHEN key = ? THEN value END), ''),
|
||||
COALESCE(MAX(CASE WHEN key = ? THEN value END), '')
|
||||
FROM kandev_meta`)
|
||||
var version, url, tsRaw string
|
||||
if err := db.QueryRow(query, keys.version, keys.url, keys.checkedAt).Scan(
|
||||
&version,
|
||||
&url,
|
||||
&tsRaw,
|
||||
); err != nil {
|
||||
return "", "", time.Time{}, fmt.Errorf("read latest version tuple: %w", err)
|
||||
}
|
||||
var checkedAt time.Time
|
||||
if tsRaw != "" {
|
||||
secs, perr := strconv.ParseInt(tsRaw, 10, 64)
|
||||
if perr != nil {
|
||||
return "", "", time.Time{}, fmt.Errorf("parse latest_version_checked_at %q: %w", tsRaw, perr)
|
||||
return "", "", time.Time{}, fmt.Errorf("parse %s %q: %w", keys.checkedAt, tsRaw, perr)
|
||||
}
|
||||
checkedAt = time.Unix(secs, 0).UTC()
|
||||
}
|
||||
return version, url, checkedAt, nil
|
||||
}
|
||||
|
||||
func writeMetaKey(executor metaKeyExecutor, query, key, value string) error {
|
||||
if _, err := executor.Exec(query, key, value); err != nil {
|
||||
return fmt.Errorf("write meta key %q: %w", key, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// WriteLatestNightlyVersion persists the npm nightly target independently
|
||||
// from the stable GitHub release cache.
|
||||
func WriteLatestNightlyVersion(db *sqlx.DB, version, url string, checkedAt time.Time) error {
|
||||
return writeLatestVersion(db, nightlyLatestVersionKeys, version, url, checkedAt)
|
||||
}
|
||||
|
||||
// ReadLatestNightlyVersion returns the isolated npm nightly target cache.
|
||||
func ReadLatestNightlyVersion(db *sqlx.DB) (string, string, time.Time, error) {
|
||||
return readLatestVersion(db, nightlyLatestVersionKeys)
|
||||
}
|
||||
|
||||
// hasUserTables returns true when the DB contains at least one table that is
|
||||
// not part of the SQLite internal schema and not kandev_meta itself. This
|
||||
// distinguishes a genuinely fresh DB from a pre-meta DB being upgraded.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package persistence
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -14,6 +15,7 @@ func memSQLiteDB(t *testing.T) *sqlx.DB {
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
db.SetMaxOpenConns(1)
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
return db
|
||||
}
|
||||
@@ -170,6 +172,74 @@ func TestReadLatestVersion_PartialPersistedState(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteLatestNightlyVersionRollsBackPartialTuple(t *testing.T) {
|
||||
db := memSQLiteDB(t)
|
||||
if err := ensureMetaTable(db); err != nil {
|
||||
t.Fatalf("ensureMetaTable: %v", err)
|
||||
}
|
||||
if _, err := db.Exec(fmt.Sprintf(`
|
||||
CREATE TRIGGER fail_nightly_url
|
||||
BEFORE INSERT ON kandev_meta
|
||||
WHEN NEW.key = '%s'
|
||||
BEGIN
|
||||
SELECT RAISE(ABORT, 'forced nightly URL failure');
|
||||
END`, metaKeyLatestNightlyVersionURL)); err != nil {
|
||||
t.Fatalf("create trigger: %v", err)
|
||||
}
|
||||
|
||||
err := WriteLatestNightlyVersion(
|
||||
db,
|
||||
"1.2.4-nightly.shaabc123def456",
|
||||
"https://example/nightly",
|
||||
time.Unix(1_700_000_000, 0).UTC(),
|
||||
)
|
||||
if err == nil {
|
||||
t.Fatal("WriteLatestNightlyVersion error = nil, want forced failure")
|
||||
}
|
||||
version, readErr := readKey(db, metaKeyLatestNightlyVersion)
|
||||
if readErr != nil {
|
||||
t.Fatalf("read nightly version: %v", readErr)
|
||||
}
|
||||
if version != "" {
|
||||
t.Fatalf("partial nightly version persisted: %q", version)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStableAndNightlyLatestVersionsAreIsolated(t *testing.T) {
|
||||
db := memSQLiteDB(t)
|
||||
if err := ensureMetaTable(db); err != nil {
|
||||
t.Fatalf("ensureMetaTable: %v", err)
|
||||
}
|
||||
stableAt := time.Unix(1_700_000_000, 0).UTC()
|
||||
nightlyAt := stableAt.Add(time.Hour)
|
||||
if err := WriteLatestVersion(db, "v1.2.3", "https://example/stable", stableAt); err != nil {
|
||||
t.Fatalf("WriteLatestVersion: %v", err)
|
||||
}
|
||||
if err := WriteLatestNightlyVersion(
|
||||
db,
|
||||
"1.2.4-nightly.shaabc123def456",
|
||||
"https://example/nightly",
|
||||
nightlyAt,
|
||||
); err != nil {
|
||||
t.Fatalf("WriteLatestNightlyVersion: %v", err)
|
||||
}
|
||||
|
||||
stable, stableURL, stableChecked, err := ReadLatestVersion(db)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadLatestVersion: %v", err)
|
||||
}
|
||||
nightly, nightlyURL, nightlyChecked, err := ReadLatestNightlyVersion(db)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadLatestNightlyVersion: %v", err)
|
||||
}
|
||||
if stable != "v1.2.3" || stableURL != "https://example/stable" || !stableChecked.Equal(stableAt) {
|
||||
t.Fatalf("stable cache changed: version=%q url=%q checked=%v", stable, stableURL, stableChecked)
|
||||
}
|
||||
if nightly != "1.2.4-nightly.shaabc123def456" || nightlyURL != "https://example/nightly" || !nightlyChecked.Equal(nightlyAt) {
|
||||
t.Fatalf("nightly cache mismatch: version=%q url=%q checked=%v", nightly, nightlyURL, nightlyChecked)
|
||||
}
|
||||
}
|
||||
|
||||
// TestShouldBackup verifies the backup decision logic.
|
||||
func TestShouldBackup(t *testing.T) {
|
||||
tests := []struct {
|
||||
|
||||
@@ -25,4 +25,31 @@ func TestPostgresLatestVersionMetaRoundTrip(t *testing.T) {
|
||||
if version != "v1.2.3" || url != "https://example.test/release" || !gotCheckedAt.Equal(checkedAt) {
|
||||
t.Fatalf("meta round-trip = (%q, %q, %s)", version, url, gotCheckedAt)
|
||||
}
|
||||
|
||||
nightlyCheckedAt := checkedAt.Add(time.Hour)
|
||||
if err := WriteLatestNightlyVersion(
|
||||
db,
|
||||
"v1.2.4-nightly.shaabc123def456",
|
||||
"https://example.test/nightly",
|
||||
nightlyCheckedAt,
|
||||
); err != nil {
|
||||
t.Fatalf("write latest nightly version: %v", err)
|
||||
}
|
||||
nightlyVersion, nightlyURL, gotNightlyCheckedAt, err := ReadLatestNightlyVersion(db)
|
||||
if err != nil {
|
||||
t.Fatalf("read latest nightly version: %v", err)
|
||||
}
|
||||
if nightlyVersion != "v1.2.4-nightly.shaabc123def456" ||
|
||||
nightlyURL != "https://example.test/nightly" ||
|
||||
!gotNightlyCheckedAt.Equal(nightlyCheckedAt) {
|
||||
t.Fatalf("nightly meta round-trip = (%q, %q, %s)", nightlyVersion, nightlyURL, gotNightlyCheckedAt)
|
||||
}
|
||||
|
||||
version, url, gotCheckedAt, err = ReadLatestVersion(db)
|
||||
if err != nil {
|
||||
t.Fatalf("read stable version after nightly write: %v", err)
|
||||
}
|
||||
if version != "v1.2.3" || url != "https://example.test/release" || !gotCheckedAt.Equal(checkedAt) {
|
||||
t.Fatalf("stable meta changed after nightly write = (%q, %q, %s)", version, url, gotCheckedAt)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,9 @@ package system
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
@@ -35,6 +37,8 @@ import (
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
const e2eNPMRegistryURLEnv = "KANDEV_E2E_NPM_REGISTRY_URL"
|
||||
|
||||
// BuildInfo holds the ldflag-injected build metadata that cmd/kandev
|
||||
// passes to Provide.
|
||||
type BuildInfo struct {
|
||||
@@ -101,6 +105,12 @@ func Provide(cfg *config.Config, log *logger.Logger, pool *db.Pool, eventBus bus
|
||||
if settingsStore != nil {
|
||||
metricsStore := metrics.NewStore(settingsStore)
|
||||
metricsSvc = metrics.NewService(metricsStore, metrics.NewCollector())
|
||||
updatesOpts = append(updatesOpts, updates.WithSettingsStore(settingsStore))
|
||||
}
|
||||
|
||||
updatesSvc := updates.NewService(pool, build.Version, nil, log, updatesOpts...)
|
||||
if registryURL := e2eNPMRegistryURL(); registryURL != "" {
|
||||
updatesSvc.SetNightlyURL(registryURL)
|
||||
}
|
||||
|
||||
return &Service{
|
||||
@@ -115,11 +125,18 @@ func Provide(cfg *config.Config, log *logger.Logger, pool *db.Pool, eventBus bus
|
||||
}),
|
||||
FrontendErrors: frontenderrors.New(log, nil),
|
||||
Metrics: metricsSvc,
|
||||
Updates: updates.NewService(pool, build.Version, nil, log, updatesOpts...),
|
||||
Updates: updatesSvc,
|
||||
Restart: restart.NewManagerFromEnv(),
|
||||
}
|
||||
}
|
||||
|
||||
func e2eNPMRegistryURL() string {
|
||||
if os.Getenv("KANDEV_E2E_MOCK") != "true" {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(os.Getenv(e2eNPMRegistryURLEnv))
|
||||
}
|
||||
|
||||
// RegisterRoutes mounts every system endpoint under /api/v1/system.
|
||||
// The health endpoint is mounted by internal/health.RegisterRoutes,
|
||||
// not here, to keep the existing package's surface unchanged.
|
||||
@@ -159,6 +176,7 @@ func (s *Service) RegisterRoutes(router *gin.Engine, log *logger.Logger) {
|
||||
|
||||
g.GET("/updates", updates.HandleGet(s.Updates))
|
||||
admin.POST("/updates/check", updates.HandleCheck(s.Updates))
|
||||
admin.PATCH("/updates/channel", updates.HandleSetChannel(s.Updates))
|
||||
admin.POST("/updates/apply", updates.HandleApply(s.Updates))
|
||||
g.GET("/restart-capability", restart.HandleCapability(s.Restart))
|
||||
admin.POST("/restart", restart.HandleRequest(s.Restart))
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package system
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestE2ENPMRegistryURLIsStrictlyTestGated(t *testing.T) {
|
||||
t.Setenv(e2eNPMRegistryURLEnv, " http://127.0.0.1:1234/kandev ")
|
||||
|
||||
t.Setenv("KANDEV_E2E_MOCK", "false")
|
||||
if got := e2eNPMRegistryURL(); got != "" {
|
||||
t.Fatalf("e2eNPMRegistryURL() without test gate = %q, want empty", got)
|
||||
}
|
||||
|
||||
t.Setenv("KANDEV_E2E_MOCK", "true")
|
||||
if got := e2eNPMRegistryURL(); got != "http://127.0.0.1:1234/kandev" {
|
||||
t.Fatalf("e2eNPMRegistryURL() = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -13,8 +13,6 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/persistence"
|
||||
)
|
||||
|
||||
type applyRunner func(context.Context, applyRequest) (map[string]interface{}, error)
|
||||
@@ -43,24 +41,38 @@ type updateIntent struct {
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
func (s *Service) applyPreflight() (UpdatesResponse, *serviceInstallMetadata, error) {
|
||||
version, releaseURL, checkedAt, err := persistence.ReadLatestVersion(s.pool.Reader())
|
||||
func (s *Service) applyPreflight(
|
||||
ctx context.Context,
|
||||
expectedTarget string,
|
||||
) (UpdatesResponse, *serviceInstallMetadata, error) {
|
||||
s.updateMu.Lock()
|
||||
defer s.updateMu.Unlock()
|
||||
|
||||
// Read install state once so channel capability, ApplySupported, and the
|
||||
// intent file all reflect the same service metadata snapshot.
|
||||
install, metadata := s.detectInstallState()
|
||||
applySupported, reason := install.applySupport()
|
||||
if !applySupported {
|
||||
return UpdatesResponse{}, nil, fmt.Errorf("%w: %s", ErrApplyUnsupported, reason)
|
||||
}
|
||||
channel, err := s.effectiveChannel(ctx, install)
|
||||
if err != nil {
|
||||
return UpdatesResponse{}, nil, err
|
||||
}
|
||||
// Read install state once so the ApplySupported gate below and the intent
|
||||
// file written by the caller both reflect the same snapshot.
|
||||
install, metadata := s.detectInstallState()
|
||||
resp := s.buildResponseFrom(install, version, releaseURL, checkedAt)
|
||||
version, releaseURL, checkedAt, err := s.readLatestVersion(channel)
|
||||
if err != nil {
|
||||
return UpdatesResponse{}, nil, err
|
||||
}
|
||||
// Bind Apply to the exact immutable version presented to the user. Update
|
||||
// discovery may move the cache between rendering and confirmation; reject
|
||||
// that stale request instead of silently installing a different artifact.
|
||||
if expectedTarget == "" || version != expectedTarget {
|
||||
return UpdatesResponse{}, nil, ErrUpdateTargetChanged
|
||||
}
|
||||
resp := s.buildResponseFromChannel(channel, install, version, releaseURL, checkedAt)
|
||||
if !resp.UpdateAvailable {
|
||||
return UpdatesResponse{}, nil, ErrNoUpdateAvailable
|
||||
}
|
||||
if !resp.ApplySupported {
|
||||
return UpdatesResponse{}, nil, fmt.Errorf("%w: %s", ErrApplyUnsupported, resp.ApplyUnsupportedReason)
|
||||
}
|
||||
if metadata == nil {
|
||||
return UpdatesResponse{}, nil, ErrApplyUnsupported
|
||||
}
|
||||
return resp, metadata, nil
|
||||
}
|
||||
|
||||
@@ -284,6 +296,9 @@ func selfUpdateEnvironment() []string {
|
||||
return env
|
||||
}
|
||||
|
||||
// Install-wide mutations use exact browser same-origin checks, stricter than
|
||||
// general UI CORS allowances. Requests without Origin remain available to
|
||||
// trusted non-browser clients such as the local CLI.
|
||||
func sameOriginOrNoOrigin(r *http.Request) bool {
|
||||
origin := r.Header.Get("Origin")
|
||||
if origin == "" {
|
||||
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -53,7 +55,7 @@ func TestService_ApplyQueuesSelfUpdateJobAndWritesIntent(t *testing.T) {
|
||||
}),
|
||||
)
|
||||
|
||||
jobID, err := svc.Apply(context.Background(), "UPDATE")
|
||||
jobID, err := svc.Apply(context.Background(), "UPDATE", "v1.0.1")
|
||||
if err != nil {
|
||||
t.Fatalf("Apply: %v", err)
|
||||
}
|
||||
@@ -77,6 +79,125 @@ func TestService_ApplyQueuesSelfUpdateJobAndWritesIntent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestService_ApplyUsesCachedExactNightlyTarget(t *testing.T) {
|
||||
homeDir := configureManagedNPMInstall(t)
|
||||
pool := newTestPool(t)
|
||||
const packageVersion = "1.2.4-nightly.shaabc123def456"
|
||||
const targetTag = "v" + packageVersion
|
||||
if err := persistence.WriteLatestNightlyVersion(
|
||||
pool.Writer(),
|
||||
targetTag,
|
||||
"https://example/cached-nightly",
|
||||
time.Now().UTC(),
|
||||
); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := &memorySettingsStore{value: []byte(ChannelNightly), present: true}
|
||||
tracker := jobs.NewTracker(nil, logger.Default())
|
||||
var gotReq applyRequest
|
||||
svc := NewService(
|
||||
pool,
|
||||
"v1.2.3",
|
||||
nil,
|
||||
logger.Default(),
|
||||
WithHomeDir(homeDir),
|
||||
WithSettingsStore(store),
|
||||
WithJobs(tracker),
|
||||
WithApplyRunner(func(_ context.Context, req applyRequest) (map[string]interface{}, error) {
|
||||
gotReq = req
|
||||
return map[string]interface{}{"status": "started"}, nil
|
||||
}),
|
||||
)
|
||||
var resolutions atomic.Int32
|
||||
svc.SetNightlyFetcher(func(context.Context) (string, string, error) {
|
||||
resolutions.Add(1)
|
||||
return "v1.2.5-nightly.shafedcba654321", "https://example/new-nightly", nil
|
||||
})
|
||||
|
||||
jobID, err := svc.Apply(context.Background(), "UPDATE", targetTag)
|
||||
if err != nil {
|
||||
t.Fatalf("Apply: %v", err)
|
||||
}
|
||||
waitForJobState(t, tracker, jobID, jobs.StateSucceeded)
|
||||
if gotReq.Intent.TargetTag != targetTag || gotReq.Intent.TargetVersion != packageVersion {
|
||||
t.Fatalf(
|
||||
"intent target tag=%q version=%q want tag=%q version=%q",
|
||||
gotReq.Intent.TargetTag,
|
||||
gotReq.Intent.TargetVersion,
|
||||
targetTag,
|
||||
packageVersion,
|
||||
)
|
||||
}
|
||||
if got := resolutions.Load(); got != 0 {
|
||||
t.Fatalf("nightly resolutions=%d want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestService_ApplyRejectsChangedCachedTarget(t *testing.T) {
|
||||
homeDir := configureManagedNPMInstall(t)
|
||||
pool := newTestPool(t)
|
||||
const cachedTarget = "v1.2.5-nightly.shafedcba654321"
|
||||
if err := persistence.WriteLatestNightlyVersion(
|
||||
pool.Writer(),
|
||||
cachedTarget,
|
||||
"https://example/new-nightly",
|
||||
time.Now().UTC(),
|
||||
); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
svc := NewService(
|
||||
pool,
|
||||
"v1.2.3",
|
||||
nil,
|
||||
logger.Default(),
|
||||
WithHomeDir(homeDir),
|
||||
WithSettingsStore(&memorySettingsStore{value: []byte(ChannelNightly), present: true}),
|
||||
WithJobs(jobs.NewTracker(nil, logger.Default())),
|
||||
)
|
||||
|
||||
_, err := svc.Apply(context.Background(), "UPDATE", "v1.2.4-nightly.shaabc123def456")
|
||||
if !errors.Is(err, ErrUpdateTargetChanged) {
|
||||
t.Fatalf("Apply error=%v want ErrUpdateTargetChanged", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestService_ApplyRejectsConcurrentNightlyWhileFirstApplyIsRunning(t *testing.T) {
|
||||
homeDir := configureManagedNPMInstall(t)
|
||||
pool := newTestPool(t)
|
||||
release := make(chan struct{})
|
||||
closeRelease := sync.OnceFunc(func() { close(release) })
|
||||
t.Cleanup(closeRelease)
|
||||
svc := NewService(
|
||||
pool,
|
||||
"v1.2.3",
|
||||
nil,
|
||||
logger.Default(),
|
||||
WithHomeDir(homeDir),
|
||||
WithSettingsStore(&memorySettingsStore{value: []byte(ChannelNightly), present: true}),
|
||||
WithJobs(jobs.NewTracker(nil, logger.Default())),
|
||||
WithApplyRunner(func(_ context.Context, _ applyRequest) (map[string]interface{}, error) {
|
||||
<-release
|
||||
return map[string]interface{}{"status": "started"}, nil
|
||||
}),
|
||||
)
|
||||
const target = "v1.2.4-nightly.shaabc123def456"
|
||||
if err := persistence.WriteLatestNightlyVersion(
|
||||
pool.Writer(),
|
||||
target,
|
||||
"https://example/nightly",
|
||||
time.Now().UTC(),
|
||||
); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := svc.Apply(context.Background(), "UPDATE", target); err != nil {
|
||||
t.Fatalf("first Apply: %v", err)
|
||||
}
|
||||
if _, err := svc.Apply(context.Background(), "UPDATE", target); !errors.Is(err, ErrApplyInProgress) {
|
||||
t.Fatalf("second Apply error=%v want ErrApplyInProgress", err)
|
||||
}
|
||||
closeRelease()
|
||||
}
|
||||
|
||||
func TestWriteApplyIntentPreservesNativeNoBootStart(t *testing.T) {
|
||||
homeDir := t.TempDir()
|
||||
metadataPath := filepath.Join(homeDir, "service", "install.json")
|
||||
@@ -128,7 +249,7 @@ func TestService_ApplyRejectsUnsupportedInstall(t *testing.T) {
|
||||
}
|
||||
svc := NewService(pool, "v1.0.0", nil, logger.Default(), WithJobs(jobs.NewTracker(nil, logger.Default())))
|
||||
|
||||
_, err := svc.Apply(context.Background(), "UPDATE")
|
||||
_, err := svc.Apply(context.Background(), "UPDATE", "v1.0.1")
|
||||
if !errors.Is(err, ErrApplyUnsupported) {
|
||||
t.Fatalf("err=%v want ErrApplyUnsupported", err)
|
||||
}
|
||||
@@ -159,6 +280,8 @@ func TestService_ApplyRejectsConcurrentSelfUpdate(t *testing.T) {
|
||||
// Block the first helper so its job stays running while the second apply is
|
||||
// attempted, making the in-flight guard deterministic.
|
||||
release := make(chan struct{})
|
||||
closeRelease := sync.OnceFunc(func() { close(release) })
|
||||
t.Cleanup(closeRelease)
|
||||
svc := NewService(pool, "v1.0.0", nil, logger.Default(),
|
||||
WithHomeDir(homeDir),
|
||||
WithJobs(jobs.NewTracker(nil, logger.Default())),
|
||||
@@ -168,13 +291,13 @@ func TestService_ApplyRejectsConcurrentSelfUpdate(t *testing.T) {
|
||||
}),
|
||||
)
|
||||
|
||||
if _, err := svc.Apply(context.Background(), "UPDATE"); err != nil {
|
||||
if _, err := svc.Apply(context.Background(), "UPDATE", "v1.0.1"); err != nil {
|
||||
t.Fatalf("first Apply: %v", err)
|
||||
}
|
||||
if _, err := svc.Apply(context.Background(), "UPDATE"); !errors.Is(err, ErrApplyInProgress) {
|
||||
if _, err := svc.Apply(context.Background(), "UPDATE", "v1.0.1"); !errors.Is(err, ErrApplyInProgress) {
|
||||
t.Fatalf("second Apply err=%v want ErrApplyInProgress", err)
|
||||
}
|
||||
close(release)
|
||||
closeRelease()
|
||||
}
|
||||
|
||||
func TestService_ApplyGuardExpiresAfterTTL(t *testing.T) {
|
||||
@@ -211,23 +334,23 @@ func TestService_ApplyGuardExpiresAfterTTL(t *testing.T) {
|
||||
clock := time.Now()
|
||||
svc.now = func() time.Time { return clock }
|
||||
|
||||
if _, err := svc.Apply(context.Background(), "UPDATE"); err != nil {
|
||||
if _, err := svc.Apply(context.Background(), "UPDATE", "v1.0.1"); err != nil {
|
||||
t.Fatalf("first Apply: %v", err)
|
||||
}
|
||||
// Within the TTL a second apply is still refused.
|
||||
if _, err := svc.Apply(context.Background(), "UPDATE"); !errors.Is(err, ErrApplyInProgress) {
|
||||
if _, err := svc.Apply(context.Background(), "UPDATE", "v1.0.1"); !errors.Is(err, ErrApplyInProgress) {
|
||||
t.Fatalf("within TTL err=%v want ErrApplyInProgress", err)
|
||||
}
|
||||
// Past the TTL the guard expires (helper assumed dead) and a retry succeeds.
|
||||
clock = clock.Add(applyGuardTTL + time.Second)
|
||||
if _, err := svc.Apply(context.Background(), "UPDATE"); err != nil {
|
||||
if _, err := svc.Apply(context.Background(), "UPDATE", "v1.0.1"); err != nil {
|
||||
t.Fatalf("after TTL Apply: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestService_ApplyRejectsWrongConfirm(t *testing.T) {
|
||||
svc := NewService(newTestPool(t), "v1.0.0", nil, logger.Default())
|
||||
_, err := svc.Apply(context.Background(), "NOPE")
|
||||
_, err := svc.Apply(context.Background(), "NOPE", "v1.0.1")
|
||||
if !errors.Is(err, ErrApplyConfirm) {
|
||||
t.Fatalf("err=%v want ErrApplyConfirm", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
package updates
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
type Channel string
|
||||
|
||||
const (
|
||||
ChannelStable Channel = "stable"
|
||||
ChannelNightly Channel = "nightly"
|
||||
)
|
||||
|
||||
const updatesChannelSettingKey = "updates_channel"
|
||||
|
||||
const channelSettingsUnavailableReason = "Update channel settings are unavailable."
|
||||
|
||||
var ErrInvalidChannel = errors.New("invalid updates channel")
|
||||
var ErrChannelUnsupported = errors.New("updates channel unsupported")
|
||||
var ErrUpdateResolve = errors.New("update target resolution failed")
|
||||
var ErrUpdateTargetChanged = errors.New("update target changed; refresh updates before applying")
|
||||
|
||||
var nightlyVersionPattern = regexp.MustCompile(
|
||||
`^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)-nightly\.sha[0-9a-f]{12}$`,
|
||||
)
|
||||
|
||||
type settingsStore interface {
|
||||
Get(ctx context.Context, key string) ([]byte, bool, error)
|
||||
Save(ctx context.Context, key string, value []byte) error
|
||||
}
|
||||
|
||||
// WithSettingsStore wires the install-wide settings store used for channel selection.
|
||||
func WithSettingsStore(store settingsStore) Option {
|
||||
return func(s *Service) {
|
||||
s.settings = store
|
||||
}
|
||||
}
|
||||
|
||||
func parseChannel(value string) (Channel, bool) {
|
||||
channel := Channel(value)
|
||||
switch channel {
|
||||
case ChannelStable, ChannelNightly:
|
||||
return channel, true
|
||||
default:
|
||||
return ChannelStable, false
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) selectedChannel(ctx context.Context) (Channel, error) {
|
||||
if s.settings == nil {
|
||||
return ChannelStable, nil
|
||||
}
|
||||
raw, ok, err := s.settings.Get(ctx, updatesChannelSettingKey)
|
||||
if err != nil {
|
||||
return ChannelStable, fmt.Errorf("read updates channel: %w", err)
|
||||
}
|
||||
if !ok {
|
||||
return ChannelStable, nil
|
||||
}
|
||||
channel, valid := parseChannel(string(raw))
|
||||
if !valid {
|
||||
return ChannelStable, nil
|
||||
}
|
||||
return channel, nil
|
||||
}
|
||||
|
||||
func (s *Service) persistChannel(ctx context.Context, channel Channel) error {
|
||||
if _, valid := parseChannel(string(channel)); !valid {
|
||||
return fmt.Errorf("%w: %q", ErrInvalidChannel, channel)
|
||||
}
|
||||
if s.settings == nil {
|
||||
return errors.New("updates settings store is unavailable")
|
||||
}
|
||||
if err := s.settings.Save(ctx, updatesChannelSettingKey, []byte(channel)); err != nil {
|
||||
return fmt.Errorf("save updates channel: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) effectiveChannel(
|
||||
ctx context.Context,
|
||||
install InstallStateResponse,
|
||||
) (Channel, error) {
|
||||
editable, _ := s.channelSupport(install)
|
||||
if !editable {
|
||||
return ChannelStable, nil
|
||||
}
|
||||
return s.selectedChannel(ctx)
|
||||
}
|
||||
|
||||
func (s *Service) channelSupport(install InstallStateResponse) (bool, string) {
|
||||
editable, reason := install.nightlySupport()
|
||||
if !editable {
|
||||
return false, reason
|
||||
}
|
||||
if s.settings == nil {
|
||||
return false, channelSettingsUnavailableReason
|
||||
}
|
||||
return true, ""
|
||||
}
|
||||
|
||||
func isNightlyVersion(version string) bool {
|
||||
return nightlyVersionPattern.MatchString(version)
|
||||
}
|
||||
|
||||
// SelectChannel validates and persists a new update channel, returning its
|
||||
// resolved update state.
|
||||
func (s *Service) SelectChannel(ctx context.Context, value string) (UpdatesResponse, error) {
|
||||
channel, valid := parseChannel(value)
|
||||
if !valid {
|
||||
return UpdatesResponse{}, fmt.Errorf("%w: %q", ErrInvalidChannel, value)
|
||||
}
|
||||
install, _ := s.detectInstallState()
|
||||
editable, reason := s.channelSupport(install)
|
||||
if !editable {
|
||||
return UpdatesResponse{}, fmt.Errorf("%w: %s", ErrChannelUnsupported, reason)
|
||||
}
|
||||
if ok, _ := s.limiter.Allow(); !ok {
|
||||
return UpdatesResponse{}, ErrRateLimited
|
||||
}
|
||||
|
||||
s.updateMu.Lock()
|
||||
defer s.updateMu.Unlock()
|
||||
|
||||
version, targetURL, err := s.resolveLatest(ctx, channel)
|
||||
if err != nil {
|
||||
return UpdatesResponse{}, fmt.Errorf("%w: %v", ErrUpdateResolve, err)
|
||||
}
|
||||
checkedAt := s.now().UTC()
|
||||
if err := s.writeLatestVersion(channel, version, targetURL, checkedAt); err != nil {
|
||||
return UpdatesResponse{}, err
|
||||
}
|
||||
if err := s.persistChannel(ctx, channel); err != nil {
|
||||
return UpdatesResponse{}, err
|
||||
}
|
||||
return s.buildResponseFromChannel(channel, install, version, targetURL, checkedAt), nil
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
package updates
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"github.com/kandev/kandev/internal/persistence"
|
||||
)
|
||||
|
||||
func configureManagedNPMInstall(t *testing.T) string {
|
||||
t.Helper()
|
||||
homeDir := t.TempDir()
|
||||
metadataPath, _ := writeServiceInstallForTest(t, homeDir, serviceInstallMetadata{
|
||||
Manager: serviceManagerSystemd,
|
||||
Mode: installModeUser,
|
||||
Kind: installKindNPM,
|
||||
HomeDir: homeDir,
|
||||
LogDir: filepath.Join(homeDir, "logs"),
|
||||
ServicePath: filepath.Join(homeDir, "kandev.service"),
|
||||
NodePath: "/usr/bin/node",
|
||||
CLIEntry: "/usr/lib/node_modules/kandev/bin/cli.js",
|
||||
})
|
||||
t.Setenv(envRunningAsService, "true")
|
||||
t.Setenv(envServiceMode, installModeUser)
|
||||
t.Setenv(envServiceManager, serviceManagerSystemd)
|
||||
t.Setenv(envInstallKind, installKindNPM)
|
||||
t.Setenv(envServiceMetadata, metadataPath)
|
||||
return homeDir
|
||||
}
|
||||
|
||||
type memorySettingsStore struct {
|
||||
mu sync.Mutex
|
||||
value []byte
|
||||
present bool
|
||||
getErr error
|
||||
saveErr error
|
||||
}
|
||||
|
||||
type cancelAwareSettingsStore struct {
|
||||
calls atomic.Int32
|
||||
}
|
||||
|
||||
type failingSettingsStore struct {
|
||||
getCalls atomic.Int32
|
||||
}
|
||||
|
||||
func (s *failingSettingsStore) Get(context.Context, string) ([]byte, bool, error) {
|
||||
s.getCalls.Add(1)
|
||||
return nil, false, errors.New("settings unavailable")
|
||||
}
|
||||
|
||||
func (*failingSettingsStore) Save(context.Context, string, []byte) error {
|
||||
return errors.New("settings unavailable")
|
||||
}
|
||||
|
||||
func (s *cancelAwareSettingsStore) Get(ctx context.Context, _ string) ([]byte, bool, error) {
|
||||
if s.calls.Add(1) == 1 {
|
||||
return []byte(ChannelNightly), true, nil
|
||||
}
|
||||
return nil, false, ctx.Err()
|
||||
}
|
||||
|
||||
func (*cancelAwareSettingsStore) Save(context.Context, string, []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *memorySettingsStore) Get(context.Context, string) ([]byte, bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return append([]byte(nil), s.value...), s.present, s.getErr
|
||||
}
|
||||
|
||||
func (s *memorySettingsStore) Save(_ context.Context, _ string, value []byte) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.saveErr != nil {
|
||||
return s.saveErr
|
||||
}
|
||||
s.value = append([]byte(nil), value...)
|
||||
s.present = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestSelectedChannelDefaultsInvalidAndMissingValuesToStable(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
store *memorySettingsStore
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "missing", store: &memorySettingsStore{}},
|
||||
{name: "invalid", store: &memorySettingsStore{value: []byte("preview"), present: true}},
|
||||
{name: "read failure", store: &memorySettingsStore{getErr: errors.New("db down")}, wantErr: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
svc := NewService(newTestPool(t), "v1.0.0", nil, logger.Default(), WithSettingsStore(tc.store))
|
||||
got, err := svc.selectedChannel(context.Background())
|
||||
if tc.wantErr {
|
||||
if err == nil {
|
||||
t.Fatal("selectedChannel error = nil, want error")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("selectedChannel: %v", err)
|
||||
}
|
||||
if got != ChannelStable {
|
||||
t.Fatalf("channel=%q want %q", got, ChannelStable)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPersistedNightlyChannelSurvivesServiceRestart(t *testing.T) {
|
||||
store := &memorySettingsStore{}
|
||||
first := NewService(newTestPool(t), "v1.0.0", nil, logger.Default(), WithSettingsStore(store))
|
||||
if err := first.persistChannel(context.Background(), ChannelNightly); err != nil {
|
||||
t.Fatalf("persistChannel: %v", err)
|
||||
}
|
||||
second := NewService(first.pool, "v1.0.0", nil, logger.Default(), WithSettingsStore(store))
|
||||
got, err := second.selectedChannel(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("selectedChannel: %v", err)
|
||||
}
|
||||
if got != ChannelNightly {
|
||||
t.Fatalf("channel=%q want nightly", got)
|
||||
}
|
||||
|
||||
if err := second.persistChannel(context.Background(), Channel("preview")); err == nil {
|
||||
t.Fatal("persistChannel accepted invalid channel")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetReadsOnlyTheSelectedChannelCache(t *testing.T) {
|
||||
homeDir := configureManagedNPMInstall(t)
|
||||
pool := newTestPool(t)
|
||||
stableAt := time.Unix(1_700_000_000, 0).UTC()
|
||||
nightlyAt := stableAt.Add(time.Hour)
|
||||
if err := persistence.WriteLatestVersion(pool.Writer(), "v1.2.3", "https://example/stable", stableAt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := persistence.WriteLatestNightlyVersion(
|
||||
pool.Writer(),
|
||||
"1.2.4-nightly.shaabc123def456",
|
||||
"https://example/nightly",
|
||||
nightlyAt,
|
||||
); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := &memorySettingsStore{value: []byte(ChannelNightly), present: true}
|
||||
svc := NewService(pool, "v1.2.3", nil, logger.Default(), WithHomeDir(homeDir), WithSettingsStore(store))
|
||||
resp, err := svc.Get(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Get: %v", err)
|
||||
}
|
||||
if resp.Latest != "1.2.4-nightly.shaabc123def456" || resp.LatestURL != "https://example/nightly" || !resp.LatestCheckedAt.Equal(nightlyAt) {
|
||||
t.Fatalf("Get returned wrong cache: %+v", resp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNightlyAvailabilityTreatsUnequalSHAsAsNewTargets(t *testing.T) {
|
||||
svc := NewService(nil, "v1.2.4-nightly.shaffffffffffff", nil, logger.Default())
|
||||
if !svc.updateAvailableFor(ChannelNightly, "1.2.4-nightly.sha000000000000") {
|
||||
t.Fatal("unequal authoritative nightly SHA should be available regardless of lexical order")
|
||||
}
|
||||
if svc.updateAvailableFor(ChannelNightly, "1.2.4-nightly.shaffffffffffff") {
|
||||
t.Fatal("identical nightly version should not be available")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNightlyAvailabilityRejectsLowerNumericVersion(t *testing.T) {
|
||||
svc := NewService(nil, "v1.2.5-nightly.shaaaaaaaaaaaaa", nil, logger.Default())
|
||||
if svc.updateAvailableFor(ChannelNightly, "v1.2.4-nightly.shabbbbbbbbbbbb") {
|
||||
t.Fatal("lower numeric nightly version must not be offered as an update")
|
||||
}
|
||||
if !svc.updateAvailableFor(ChannelNightly, "v1.2.6-nightly.shabbbbbbbbbbbb") {
|
||||
t.Fatal("higher numeric nightly version should be offered as an update")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNightlyChannelDoesNotOfferPrereleaseOfInstalledStable(t *testing.T) {
|
||||
svc := NewService(nil, "v1.2.4", nil, logger.Default())
|
||||
if svc.updateAvailableFor(ChannelNightly, "v1.2.4-nightly.shaaaaaaaaaaaaa") {
|
||||
t.Fatal("a prerelease of the installed stable version must not be offered as an update")
|
||||
}
|
||||
if !svc.updateAvailableFor(ChannelNightly, "v1.2.5-nightly.shaaaaaaaaaaaaa") {
|
||||
t.Fatal("the next patch nightly should be offered to a stable install")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckUsesNightlyResolverAndWritesOnlyNightlyCache(t *testing.T) {
|
||||
homeDir := configureManagedNPMInstall(t)
|
||||
pool := newTestPool(t)
|
||||
store := &memorySettingsStore{value: []byte(ChannelNightly), present: true}
|
||||
svc := NewService(pool, "v1.2.3", nil, logger.Default(), WithHomeDir(homeDir), WithSettingsStore(store))
|
||||
stableCalled := false
|
||||
svc.SetFetcher(func(context.Context) (string, string, error) {
|
||||
stableCalled = true
|
||||
return "", "", errors.New("stable resolver should not run")
|
||||
})
|
||||
svc.SetNightlyFetcher(func(context.Context) (string, string, error) {
|
||||
return "1.2.4-nightly.shaabc123def456", "https://example/nightly", nil
|
||||
})
|
||||
|
||||
resp, err := svc.Check(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Check: %v", err)
|
||||
}
|
||||
if stableCalled {
|
||||
t.Fatal("stable resolver ran for nightly channel")
|
||||
}
|
||||
if resp.Latest != "1.2.4-nightly.shaabc123def456" {
|
||||
t.Fatalf("latest=%q", resp.Latest)
|
||||
}
|
||||
stable, _, _, err := persistence.ReadLatestVersion(pool.Reader())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nightly, _, _, err := persistence.ReadLatestNightlyVersion(pool.Reader())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stable != "" || nightly != "1.2.4-nightly.shaabc123def456" {
|
||||
t.Fatalf("cache isolation failed: stable=%q nightly=%q", stable, nightly)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsupportedInstallForcesPersistedNightlyPreferenceToStable(t *testing.T) {
|
||||
pool := newTestPool(t)
|
||||
if err := persistence.WriteLatestVersion(pool.Writer(), "v1.2.3", "https://example/stable", time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := persistence.WriteLatestNightlyVersion(
|
||||
pool.Writer(),
|
||||
"1.2.4-nightly.shaabc123def456",
|
||||
"https://example/nightly",
|
||||
time.Now(),
|
||||
); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := &memorySettingsStore{value: []byte(ChannelNightly), present: true}
|
||||
svc := NewService(pool, "v1.2.3", nil, logger.Default(), WithSettingsStore(store))
|
||||
resp, err := svc.Get(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.Channel != ChannelStable || resp.Latest != "v1.2.3" || resp.ChannelEditable {
|
||||
t.Fatalf("unsupported effective response=%+v", resp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsupportedInstallDoesNotReadChannelSettings(t *testing.T) {
|
||||
store := &failingSettingsStore{}
|
||||
svc := NewService(newTestPool(t), "v1.2.3", nil, logger.Default(), WithSettingsStore(store))
|
||||
|
||||
resp, err := svc.Get(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Get: %v", err)
|
||||
}
|
||||
if resp.Channel != ChannelStable || resp.ChannelEditable {
|
||||
t.Fatalf("unsupported effective response=%+v", resp)
|
||||
}
|
||||
if got := store.getCalls.Load(); got != 0 {
|
||||
t.Fatalf("settings reads=%d want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManagedNPMInstallWithoutSettingsStoreIsNotChannelEditable(t *testing.T) {
|
||||
homeDir := configureManagedNPMInstall(t)
|
||||
svc := NewService(newTestPool(t), "v1.2.3", nil, logger.Default(), WithHomeDir(homeDir))
|
||||
|
||||
resp, err := svc.Get(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Get: %v", err)
|
||||
}
|
||||
if resp.ChannelEditable || resp.ChannelUnsupportedReason == "" {
|
||||
t.Fatalf("channel capability editable=%v reason=%q", resp.ChannelEditable, resp.ChannelUnsupportedReason)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectChannelWithoutSettingsStoreRejectsBeforeResolution(t *testing.T) {
|
||||
homeDir := configureManagedNPMInstall(t)
|
||||
svc := NewService(newTestPool(t), "v1.2.3", nil, logger.Default(), WithHomeDir(homeDir))
|
||||
var resolutions atomic.Int32
|
||||
svc.SetNightlyFetcher(func(context.Context) (string, string, error) {
|
||||
resolutions.Add(1)
|
||||
return "v1.2.4-nightly.shaabc123def456", "https://example/nightly", nil
|
||||
})
|
||||
|
||||
_, err := svc.SelectChannel(context.Background(), string(ChannelNightly))
|
||||
if !errors.Is(err, ErrChannelUnsupported) {
|
||||
t.Fatalf("SelectChannel error=%v want ErrChannelUnsupported", err)
|
||||
}
|
||||
if got := resolutions.Load(); got != 0 {
|
||||
t.Fatalf("upstream resolutions=%d want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailedCheckReturnsCapturedChannelCacheAfterContextCancellation(t *testing.T) {
|
||||
homeDir := configureManagedNPMInstall(t)
|
||||
pool := newTestPool(t)
|
||||
checkedAt := time.Unix(1_700_000_000, 0).UTC()
|
||||
if err := persistence.WriteLatestNightlyVersion(
|
||||
pool.Writer(),
|
||||
"v1.2.4-nightly.shaabc123def456",
|
||||
"https://example/nightly",
|
||||
checkedAt,
|
||||
); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := &cancelAwareSettingsStore{}
|
||||
svc := NewService(pool, "v1.2.3", nil, logger.Default(), WithHomeDir(homeDir), WithSettingsStore(store))
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
svc.SetNightlyFetcher(func(context.Context) (string, string, error) {
|
||||
cancel()
|
||||
return "", "", errors.New("registry unavailable")
|
||||
})
|
||||
|
||||
resp, err := svc.fetchAndPersist(ctx)
|
||||
if err == nil || !strings.Contains(err.Error(), "registry unavailable") {
|
||||
t.Fatalf("error=%v", err)
|
||||
}
|
||||
if resp.Latest != "v1.2.4-nightly.shaabc123def456" || !resp.LatestCheckedAt.Equal(checkedAt) {
|
||||
t.Fatalf("fallback response lost cached state: %+v", resp)
|
||||
}
|
||||
if got := store.calls.Load(); got != 1 {
|
||||
t.Fatalf("settings reads=%d want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectChannelSharesManualUpstreamRateLimit(t *testing.T) {
|
||||
homeDir := configureManagedNPMInstall(t)
|
||||
svc := NewService(
|
||||
newTestPool(t),
|
||||
"v1.2.3",
|
||||
nil,
|
||||
logger.Default(),
|
||||
WithHomeDir(homeDir),
|
||||
WithSettingsStore(&memorySettingsStore{}),
|
||||
)
|
||||
var resolutions atomic.Int32
|
||||
svc.SetNightlyFetcher(func(context.Context) (string, string, error) {
|
||||
resolutions.Add(1)
|
||||
return "v1.2.4-nightly.shaabc123def456", "https://example/nightly", nil
|
||||
})
|
||||
|
||||
if _, err := svc.SelectChannel(context.Background(), string(ChannelNightly)); err != nil {
|
||||
t.Fatalf("first SelectChannel: %v", err)
|
||||
}
|
||||
if _, err := svc.SelectChannel(context.Background(), string(ChannelNightly)); !errors.Is(err, ErrRateLimited) {
|
||||
t.Fatalf("second SelectChannel error=%v want ErrRateLimited", err)
|
||||
}
|
||||
if got := resolutions.Load(); got != 1 {
|
||||
t.Fatalf("upstream resolutions=%d want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchAndPersistSerializesCacheRefreshes(t *testing.T) {
|
||||
homeDir := configureManagedNPMInstall(t)
|
||||
pool := newTestPool(t)
|
||||
store := &memorySettingsStore{value: []byte(ChannelNightly), present: true}
|
||||
svc := NewService(pool, "v1.2.3", nil, logger.Default(), WithHomeDir(homeDir), WithSettingsStore(store))
|
||||
firstEntered := make(chan struct{})
|
||||
releaseFirst := make(chan struct{})
|
||||
closeReleaseFirst := sync.OnceFunc(func() { close(releaseFirst) })
|
||||
t.Cleanup(closeReleaseFirst)
|
||||
secondEntered := make(chan struct{})
|
||||
releaseSecond := make(chan struct{})
|
||||
closeReleaseSecond := sync.OnceFunc(func() { close(releaseSecond) })
|
||||
t.Cleanup(closeReleaseSecond)
|
||||
var calls atomic.Int32
|
||||
svc.SetNightlyFetcher(func(context.Context) (string, string, error) {
|
||||
if calls.Add(1) == 1 {
|
||||
close(firstEntered)
|
||||
<-releaseFirst
|
||||
return "v1.2.4-nightly.shaaaaaaaaaaaaa", "https://example/first", nil
|
||||
}
|
||||
close(secondEntered)
|
||||
<-releaseSecond
|
||||
return "v1.2.5-nightly.shabbbbbbbbbbbb", "https://example/second", nil
|
||||
})
|
||||
|
||||
firstDone := make(chan error, 1)
|
||||
secondDone := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := svc.fetchAndPersist(context.Background())
|
||||
firstDone <- err
|
||||
}()
|
||||
select {
|
||||
case <-firstEntered:
|
||||
case err := <-firstDone:
|
||||
t.Fatalf("first refresh returned before resolver: %v", err)
|
||||
}
|
||||
if svc.updateMu.TryLock() {
|
||||
svc.updateMu.Unlock()
|
||||
t.Fatal("refresh lock was not held while first resolver was active")
|
||||
}
|
||||
go func() {
|
||||
_, err := svc.fetchAndPersist(context.Background())
|
||||
secondDone <- err
|
||||
}()
|
||||
|
||||
closeReleaseFirst()
|
||||
if err := <-firstDone; err != nil {
|
||||
t.Fatalf("first refresh: %v", err)
|
||||
}
|
||||
select {
|
||||
case <-secondEntered:
|
||||
case err := <-secondDone:
|
||||
t.Fatalf("second refresh returned before resolver: %v", err)
|
||||
}
|
||||
version, targetURL, _, err := persistence.ReadLatestNightlyVersion(pool.Reader())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if version != "v1.2.4-nightly.shaaaaaaaaaaaaa" || targetURL != "https://example/first" {
|
||||
t.Fatalf("cache before second release version=%q url=%q", version, targetURL)
|
||||
}
|
||||
|
||||
closeReleaseSecond()
|
||||
if err := <-secondDone; err != nil {
|
||||
t.Fatalf("second refresh: %v", err)
|
||||
}
|
||||
version, targetURL, _, err = persistence.ReadLatestNightlyVersion(pool.Reader())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if version != "v1.2.5-nightly.shabbbbbbbbbbbb" || targetURL != "https://example/second" {
|
||||
t.Fatalf("final cache version=%q url=%q", version, targetURL)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package updates
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"go.uber.org/goleak"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
goleak.VerifyTestMain(m)
|
||||
}
|
||||
@@ -2,20 +2,27 @@ package updates
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// HandleGet returns the cached kandev_meta view of latest version. It never
|
||||
// hits GitHub. Errors from the meta read are surfaced as 500.
|
||||
const errorResponseKey = "error"
|
||||
|
||||
// HandleGet returns the cached kandev_meta view of the selected channel. It
|
||||
// never contacts an upstream. Read failures are logged and returned as a
|
||||
// generic 500 so storage details do not cross the API boundary.
|
||||
func HandleGet(svc *Service) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
resp, err := svc.Get()
|
||||
resp, err := svc.Get(c.Request.Context())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
svc.log.Error("updates: get failed", zap.Error(err))
|
||||
c.JSON(http.StatusInternalServerError, gin.H{errorResponseKey: "failed to load updates"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
@@ -23,58 +30,116 @@ func HandleGet(svc *Service) gin.HandlerFunc {
|
||||
}
|
||||
|
||||
type applyRequestBody struct {
|
||||
Confirm string `json:"confirm"`
|
||||
Confirm string `json:"confirm"`
|
||||
TargetVersion string `json:"target_version"`
|
||||
}
|
||||
|
||||
// HandleCheck triggers a synchronous GitHub poll. When the per-process
|
||||
// limiter denies the request a 429 is returned with retry_after_seconds.
|
||||
// Other errors are surfaced as 502 since the upstream is GitHub.
|
||||
type channelRequestBody struct {
|
||||
Channel string `json:"channel"`
|
||||
}
|
||||
|
||||
// HandleSetChannel changes the install-wide update source.
|
||||
func HandleSetChannel(svc *Service) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if !sameOriginOrNoOrigin(c.Request) {
|
||||
c.JSON(http.StatusForbidden, gin.H{errorResponseKey: "cross-origin update channel change is not allowed"})
|
||||
return
|
||||
}
|
||||
var req channelRequestBody
|
||||
if err := decodeSingleJSON(c.Request.Body, &req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{errorResponseKey: "invalid channel request"})
|
||||
return
|
||||
}
|
||||
resp, err := svc.SelectChannel(c.Request.Context(), req.Channel)
|
||||
switch {
|
||||
case errors.Is(err, ErrInvalidChannel):
|
||||
c.JSON(http.StatusBadRequest, gin.H{errorResponseKey: err.Error()})
|
||||
case errors.Is(err, ErrChannelUnsupported):
|
||||
c.JSON(http.StatusConflict, gin.H{errorResponseKey: err.Error()})
|
||||
case errors.Is(err, ErrRateLimited):
|
||||
writeRateLimited(c, svc)
|
||||
case errors.Is(err, ErrUpdateResolve):
|
||||
c.JSON(http.StatusBadGateway, gin.H{errorResponseKey: err.Error()})
|
||||
case err != nil:
|
||||
svc.log.Error("updates: set channel failed", zap.Error(err))
|
||||
c.JSON(http.StatusInternalServerError, gin.H{errorResponseKey: "failed to set update channel"})
|
||||
default:
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// HandleCheck triggers a synchronous poll of the selected source. When the
|
||||
// per-process limiter denies the request a 429 is returned with
|
||||
// retry_after_seconds. Other upstream errors are surfaced as 502.
|
||||
func HandleCheck(svc *Service) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
resp, err := svc.Check(c.Request.Context())
|
||||
if errors.Is(err, ErrRateLimited) {
|
||||
retry := svc.RetryAfter()
|
||||
seconds := int64(math.Ceil(retry.Seconds()))
|
||||
if seconds < 1 {
|
||||
seconds = 1
|
||||
}
|
||||
c.JSON(http.StatusTooManyRequests, gin.H{
|
||||
"error": ErrRateLimited.Error(),
|
||||
"retry_after_seconds": seconds,
|
||||
})
|
||||
writeRateLimited(c, svc)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
|
||||
c.JSON(http.StatusBadGateway, gin.H{errorResponseKey: err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
}
|
||||
|
||||
func writeRateLimited(c *gin.Context, svc *Service) {
|
||||
retry := svc.RetryAfter()
|
||||
seconds := int64(math.Ceil(retry.Seconds()))
|
||||
if seconds < 1 {
|
||||
seconds = 1
|
||||
}
|
||||
c.JSON(http.StatusTooManyRequests, gin.H{
|
||||
errorResponseKey: ErrRateLimited.Error(),
|
||||
"retry_after_seconds": seconds,
|
||||
})
|
||||
}
|
||||
|
||||
func decodeSingleJSON(reader io.Reader, target any) error {
|
||||
decoder := json.NewDecoder(reader)
|
||||
if err := decoder.Decode(target); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
|
||||
if err == nil {
|
||||
return errors.New("request body contains multiple JSON values")
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// HandleApply queues a service-managed self-update. It is deliberately gated
|
||||
// behind service metadata and a browser same-origin check because the helper
|
||||
// mutates the local Kandev installation and restarts the service.
|
||||
func HandleApply(svc *Service) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if !sameOriginOrNoOrigin(c.Request) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "cross-origin update apply is not allowed"})
|
||||
c.JSON(http.StatusForbidden, gin.H{errorResponseKey: "cross-origin update apply is not allowed"})
|
||||
return
|
||||
}
|
||||
var req applyRequestBody
|
||||
_ = c.ShouldBindJSON(&req)
|
||||
jobID, err := svc.Apply(context.Background(), req.Confirm)
|
||||
if errors.Is(err, ErrApplyConfirm) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
if err := decodeSingleJSON(c.Request.Body, &req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{errorResponseKey: "invalid update request"})
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ErrNoUpdateAvailable) || errors.Is(err, ErrApplyUnsupported) ||
|
||||
jobID, err := svc.Apply(context.Background(), req.Confirm, req.TargetVersion)
|
||||
if errors.Is(err, ErrApplyConfirm) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{errorResponseKey: err.Error()})
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ErrNoUpdateAvailable) || errors.Is(err, ErrUpdateTargetChanged) ||
|
||||
errors.Is(err, ErrApplyUnsupported) ||
|
||||
errors.Is(err, ErrApplyInProgress) {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": err.Error()})
|
||||
c.JSON(http.StatusConflict, gin.H{errorResponseKey: err.Error()})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
c.JSON(http.StatusInternalServerError, gin.H{errorResponseKey: err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusAccepted, ApplyResponse{JobID: jobID})
|
||||
|
||||
@@ -2,14 +2,21 @@ package updates
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"github.com/kandev/kandev/internal/persistence"
|
||||
"github.com/kandev/kandev/internal/system/jobs"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -21,6 +28,7 @@ func newRouter(svc *Service) *gin.Engine {
|
||||
api := r.Group("/api/v1/system")
|
||||
api.GET("/updates", HandleGet(svc))
|
||||
api.POST("/updates/check", HandleCheck(svc))
|
||||
api.PATCH("/updates/channel", HandleSetChannel(svc))
|
||||
api.POST("/updates/apply", HandleApply(svc))
|
||||
return r
|
||||
}
|
||||
@@ -75,6 +83,54 @@ func TestHandleGet_IncludesNonServiceInstallState(t *testing.T) {
|
||||
if got := body["apply_supported"]; got != false {
|
||||
t.Errorf("apply_supported=%v want false", got)
|
||||
}
|
||||
if got := body["channel"]; got != "stable" {
|
||||
t.Errorf("channel=%v want stable", got)
|
||||
}
|
||||
if got := body["channel_editable"]; got != false {
|
||||
t.Errorf("channel_editable=%v want false", got)
|
||||
}
|
||||
if got, ok := body["channel_unsupported_reason"].(string); !ok || got == "" {
|
||||
t.Errorf("channel_unsupported_reason=%v want non-empty string", body["channel_unsupported_reason"])
|
||||
}
|
||||
}
|
||||
|
||||
type requestContextSettingsStore struct{}
|
||||
|
||||
func (requestContextSettingsStore) Get(ctx context.Context, _ string) ([]byte, bool, error) {
|
||||
return nil, false, ctx.Err()
|
||||
}
|
||||
|
||||
func (requestContextSettingsStore) Save(context.Context, string, []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestHandleGetPropagatesRequestContext(t *testing.T) {
|
||||
homeDir := configureManagedNPMInstall(t)
|
||||
pool := newTestPool(t)
|
||||
svc := NewService(
|
||||
pool,
|
||||
"v1.0.0",
|
||||
nil,
|
||||
logger.Default(),
|
||||
WithHomeDir(homeDir),
|
||||
WithSettingsStore(requestContextSettingsStore{}),
|
||||
)
|
||||
r := newRouter(svc)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/system/updates", nil).WithContext(ctx)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status=%d body=%s want 500", w.Code, w.Body.String())
|
||||
}
|
||||
if strings.Contains(w.Body.String(), context.Canceled.Error()) {
|
||||
t.Fatalf("response exposed settings read details: %s", w.Body.String())
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), "failed to load updates") {
|
||||
t.Fatalf("response=%s want generic error", w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCheck_FirstCall200(t *testing.T) {
|
||||
@@ -159,6 +215,306 @@ func TestHandleCheck_GitHubFailureReturns502(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func newManagedNPMServiceForHandler(t *testing.T) (*Service, *memorySettingsStore) {
|
||||
t.Helper()
|
||||
homeDir := configureManagedNPMInstall(t)
|
||||
store := &memorySettingsStore{}
|
||||
svc := NewService(
|
||||
newTestPool(t),
|
||||
"v1.2.3",
|
||||
nil,
|
||||
logger.Default(),
|
||||
WithHomeDir(homeDir),
|
||||
WithSettingsStore(store),
|
||||
)
|
||||
return svc, store
|
||||
}
|
||||
|
||||
func readMemorySetting(t *testing.T, store *memorySettingsStore) ([]byte, bool) {
|
||||
t.Helper()
|
||||
value, present, err := store.Get(context.Background(), updatesChannelSettingKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return value, present
|
||||
}
|
||||
|
||||
func TestHandleSetChannelPersistsSupportedNightlyAndReturnsResolvedTarget(t *testing.T) {
|
||||
svc, store := newManagedNPMServiceForHandler(t)
|
||||
svc.SetNightlyFetcher(func(context.Context) (string, string, error) {
|
||||
return "1.2.4-nightly.shaabc123def456", "https://example/nightly", nil
|
||||
})
|
||||
r := newRouter(svc)
|
||||
req := httptest.NewRequest(
|
||||
http.MethodPatch,
|
||||
"/api/v1/system/updates/channel",
|
||||
bytes.NewBufferString(`{"channel":"nightly"}`),
|
||||
)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp UpdatesResponse
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.Channel != ChannelNightly || !resp.ChannelEditable {
|
||||
t.Fatalf("channel response=%+v", resp)
|
||||
}
|
||||
if resp.Latest != "1.2.4-nightly.shaabc123def456" || !resp.UpdateAvailable {
|
||||
t.Fatalf("resolved response=%+v", resp)
|
||||
}
|
||||
selected, err := svc.selectedChannel(context.Background())
|
||||
raw, present := readMemorySetting(t, store)
|
||||
if err != nil || selected != ChannelNightly || !present || string(raw) != string(ChannelNightly) {
|
||||
t.Fatalf("persisted channel=%q raw=%q present=%v err=%v", selected, raw, present, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleSetChannelRejectsTrailingJSON(t *testing.T) {
|
||||
svc, store := newManagedNPMServiceForHandler(t)
|
||||
svc.SetNightlyFetcher(func(context.Context) (string, string, error) {
|
||||
return "1.2.4-nightly.shaabc123def456", "https://example/nightly", nil
|
||||
})
|
||||
r := newRouter(svc)
|
||||
req := httptest.NewRequest(
|
||||
http.MethodPatch,
|
||||
"/api/v1/system/updates/channel",
|
||||
bytes.NewBufferString(`{"channel":"nightly"} {}`),
|
||||
)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status=%d body=%s want 400", w.Code, w.Body.String())
|
||||
}
|
||||
_, present := readMemorySetting(t, store)
|
||||
if present {
|
||||
t.Fatal("channel selection with trailing JSON was persisted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleSetChannelRejectsInvalidAndUnsupportedNightly(t *testing.T) {
|
||||
t.Run("invalid", func(t *testing.T) {
|
||||
svc, _ := newManagedNPMServiceForHandler(t)
|
||||
r := newRouter(svc)
|
||||
req := httptest.NewRequest(http.MethodPatch, "/api/v1/system/updates/channel", bytes.NewBufferString(`{"channel":"preview"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("unsupported install", func(t *testing.T) {
|
||||
store := &memorySettingsStore{}
|
||||
svc := NewService(newTestPool(t), "v1.2.3", nil, logger.Default(), WithSettingsStore(store))
|
||||
r := newRouter(svc)
|
||||
req := httptest.NewRequest(http.MethodPatch, "/api/v1/system/updates/channel", bytes.NewBufferString(`{"channel":"nightly"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
_, present := readMemorySetting(t, store)
|
||||
if present {
|
||||
t.Fatal("unsupported channel selection was persisted")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestHandleSetChannelResolverFailureReturns502WithoutPersisting(t *testing.T) {
|
||||
svc, store := newManagedNPMServiceForHandler(t)
|
||||
svc.SetNightlyFetcher(func(context.Context) (string, string, error) {
|
||||
return "", "", errors.New("registry down")
|
||||
})
|
||||
r := newRouter(svc)
|
||||
req := httptest.NewRequest(http.MethodPatch, "/api/v1/system/updates/channel", bytes.NewBufferString(`{"channel":"nightly"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusBadGateway {
|
||||
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
_, present := readMemorySetting(t, store)
|
||||
if present {
|
||||
t.Fatal("failed resolver selection was persisted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleSetChannelPersistenceFailureDoesNotExposeStorageDetails(t *testing.T) {
|
||||
svc, store := newManagedNPMServiceForHandler(t)
|
||||
store.saveErr = errors.New("sqlite: secret storage detail")
|
||||
svc.SetNightlyFetcher(func(context.Context) (string, string, error) {
|
||||
return "1.2.4-nightly.shaabc123def456", "https://example/nightly", nil
|
||||
})
|
||||
r := newRouter(svc)
|
||||
req := httptest.NewRequest(
|
||||
http.MethodPatch,
|
||||
"/api/v1/system/updates/channel",
|
||||
bytes.NewBufferString(`{"channel":"nightly"}`),
|
||||
)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status=%d body=%s want 500", w.Code, w.Body.String())
|
||||
}
|
||||
if strings.Contains(w.Body.String(), "secret storage detail") {
|
||||
t.Fatalf("response exposed storage details: %s", w.Body.String())
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), "failed to set update channel") {
|
||||
t.Fatalf("response=%s want generic error", w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleSetChannelRejectsCrossOrigin(t *testing.T) {
|
||||
svc, store := newManagedNPMServiceForHandler(t)
|
||||
svc.SetNightlyFetcher(func(context.Context) (string, string, error) {
|
||||
return "1.2.4-nightly.shaabc123def456", "https://example/nightly", nil
|
||||
})
|
||||
r := newRouter(svc)
|
||||
req := httptest.NewRequest(
|
||||
http.MethodPatch,
|
||||
"/api/v1/system/updates/channel",
|
||||
bytes.NewBufferString(`{"channel":"nightly"}`),
|
||||
)
|
||||
req.Host = "kandev.local"
|
||||
req.Header.Set("Origin", "https://evil.example")
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("status=%d body=%s want 403", w.Code, w.Body.String())
|
||||
}
|
||||
_, present := readMemorySetting(t, store)
|
||||
if present {
|
||||
t.Fatal("cross-origin channel selection was persisted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleSetChannelRejectsCrossPortOrigin(t *testing.T) {
|
||||
svc, store := newManagedNPMServiceForHandler(t)
|
||||
svc.SetNightlyFetcher(func(context.Context) (string, string, error) {
|
||||
return "1.2.4-nightly.shaabc123def456", "https://example/nightly", nil
|
||||
})
|
||||
r := newRouter(svc)
|
||||
req := httptest.NewRequest(
|
||||
http.MethodPatch,
|
||||
"/api/v1/system/updates/channel",
|
||||
bytes.NewBufferString(`{"channel":"nightly"}`),
|
||||
)
|
||||
req.Host = "localhost:38429"
|
||||
req.Header.Set("Origin", "http://localhost:5173")
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("status=%d body=%s want 403", w.Code, w.Body.String())
|
||||
}
|
||||
_, present := readMemorySetting(t, store)
|
||||
if present {
|
||||
t.Fatal("cross-port channel selection was persisted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleApplyRejectsChangedNightlyTarget(t *testing.T) {
|
||||
svc, store := newManagedNPMServiceForHandler(t)
|
||||
if err := store.Save(context.Background(), updatesChannelSettingKey, []byte(ChannelNightly)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := persistence.WriteLatestNightlyVersion(
|
||||
svc.pool.Writer(),
|
||||
"v1.2.5-nightly.shafedcba654321",
|
||||
"https://example/new-nightly",
|
||||
time.Now().UTC(),
|
||||
); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
svc.jobs = jobs.NewTracker(nil, logger.Default())
|
||||
r := newRouter(svc)
|
||||
req := httptest.NewRequest(
|
||||
http.MethodPost,
|
||||
"/api/v1/system/updates/apply",
|
||||
bytes.NewBufferString(`{"confirm":"UPDATE","target_version":"v1.2.4-nightly.shaabc123def456"}`),
|
||||
)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("status=%d body=%s want 409", w.Code, w.Body.String())
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), "update target changed") {
|
||||
t.Fatalf("body=%s want target-changed error", w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleApplyRejectsInvalidJSONBeforeApplying(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
body string
|
||||
}{
|
||||
{
|
||||
name: "type mismatch after valid target",
|
||||
body: `{"confirm":"UPDATE","target_version":"v1.2.4","target_version":123}`,
|
||||
},
|
||||
{
|
||||
name: "truncated object after valid fields",
|
||||
body: `{"confirm":"UPDATE","target_version":"v1.2.4","broken":`,
|
||||
},
|
||||
{
|
||||
name: "trailing JSON value",
|
||||
body: `{"confirm":"UPDATE","target_version":"v1.2.4"} {}`,
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
svc, _ := newManagedNPMServiceForHandler(t)
|
||||
if err := persistence.WriteLatestVersion(
|
||||
svc.pool.Writer(),
|
||||
"v1.2.4",
|
||||
"https://example/v1.2.4",
|
||||
time.Now().UTC(),
|
||||
); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
svc.jobs = jobs.NewTracker(nil, logger.Default())
|
||||
var runnerCalls atomic.Int32
|
||||
svc.applyRun = func(context.Context, applyRequest) (map[string]interface{}, error) {
|
||||
runnerCalls.Add(1)
|
||||
return map[string]interface{}{"status": "started"}, nil
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(
|
||||
http.MethodPost,
|
||||
"/api/v1/system/updates/apply",
|
||||
bytes.NewBufferString(tc.body),
|
||||
)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
newRouter(svc).ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("status=%d body=%s want 400", w.Code, w.Body.String())
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), "invalid update request") {
|
||||
t.Errorf("body=%s want generic invalid-request error", w.Body.String())
|
||||
}
|
||||
if got := runnerCalls.Load(); got != 0 {
|
||||
t.Errorf("apply runner calls=%d want 0", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleApply_RejectsCrossOrigin(t *testing.T) {
|
||||
pool := newTestPool(t)
|
||||
svc := NewService(pool, "v1.0.0", nil, logger.Default())
|
||||
|
||||
@@ -49,6 +49,16 @@ type serviceInstallMetadata struct {
|
||||
InstalledAt string `json:"installed_at"`
|
||||
}
|
||||
|
||||
type managedUserServiceProblem uint8
|
||||
|
||||
const (
|
||||
managedUserServiceSupported managedUserServiceProblem = iota
|
||||
managedUserServiceNotRunning
|
||||
managedUserServiceUnmanaged
|
||||
managedUserServiceWrongMode
|
||||
managedUserServiceUnsupportedManager
|
||||
)
|
||||
|
||||
func (s *Service) detectInstallState() (InstallStateResponse, *serviceInstallMetadata) {
|
||||
if s.getenv(envRunningAsService) != "true" {
|
||||
return InstallStateResponse{}, nil
|
||||
@@ -141,17 +151,8 @@ func (s *Service) metadataMatchesService(state InstallStateResponse, metadata *s
|
||||
}
|
||||
|
||||
func (s InstallStateResponse) applySupport() (bool, string) {
|
||||
if !s.RunningAsService {
|
||||
return false, "Kandev is not running as a managed service."
|
||||
}
|
||||
if !s.ManagedService {
|
||||
return false, "Kandev service metadata is missing or invalid."
|
||||
}
|
||||
if s.Mode != installModeUser {
|
||||
return false, "Self-update is only available for user services."
|
||||
}
|
||||
if s.Manager != serviceManagerSystemd && s.Manager != serviceManagerLaunchd {
|
||||
return false, "This service manager does not support UI self-update."
|
||||
if problem := s.managedUserServiceProblem(); problem != managedUserServiceSupported {
|
||||
return false, problem.reason(false)
|
||||
}
|
||||
if s.Kind != installKindHomebrew && s.Kind != installKindNPM && s.Kind != installKindNPX {
|
||||
return false, "This installation method does not support UI self-update."
|
||||
@@ -159,6 +160,58 @@ func (s InstallStateResponse) applySupport() (bool, string) {
|
||||
return true, ""
|
||||
}
|
||||
|
||||
func (s InstallStateResponse) nightlySupport() (bool, string) {
|
||||
if problem := s.managedUserServiceProblem(); problem != managedUserServiceSupported {
|
||||
return false, problem.reason(true)
|
||||
}
|
||||
if s.Kind != installKindNPM && s.Kind != installKindNPX {
|
||||
return false, "Nightly updates are only available for npm or npx installations."
|
||||
}
|
||||
return true, ""
|
||||
}
|
||||
|
||||
func (s InstallStateResponse) managedUserServiceProblem() managedUserServiceProblem {
|
||||
if !s.RunningAsService {
|
||||
return managedUserServiceNotRunning
|
||||
}
|
||||
if !s.ManagedService {
|
||||
return managedUserServiceUnmanaged
|
||||
}
|
||||
if s.Mode != installModeUser {
|
||||
return managedUserServiceWrongMode
|
||||
}
|
||||
if s.Manager != serviceManagerSystemd && s.Manager != serviceManagerLaunchd {
|
||||
return managedUserServiceUnsupportedManager
|
||||
}
|
||||
return managedUserServiceSupported
|
||||
}
|
||||
|
||||
func (p managedUserServiceProblem) reason(nightly bool) string {
|
||||
if nightly {
|
||||
switch p {
|
||||
case managedUserServiceNotRunning:
|
||||
return "Nightly updates require a Kandev-managed npm or npx user service."
|
||||
case managedUserServiceUnmanaged:
|
||||
return "Nightly updates require valid Kandev service metadata."
|
||||
case managedUserServiceWrongMode:
|
||||
return "Nightly updates are only available for user services."
|
||||
case managedUserServiceUnsupportedManager:
|
||||
return "This service manager does not support nightly updates."
|
||||
}
|
||||
}
|
||||
switch p {
|
||||
case managedUserServiceNotRunning:
|
||||
return "Kandev is not running as a managed service."
|
||||
case managedUserServiceUnmanaged:
|
||||
return "Kandev service metadata is missing or invalid."
|
||||
case managedUserServiceWrongMode:
|
||||
return "Self-update is only available for user services."
|
||||
case managedUserServiceUnsupportedManager:
|
||||
return "This service manager does not support UI self-update."
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func manualCommands(install InstallStateResponse, latest string) []string {
|
||||
target := strings.TrimPrefix(latest, "v")
|
||||
if target == "" {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package updates
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -28,8 +29,15 @@ func TestService_GetManagedUserServiceSupportsApply(t *testing.T) {
|
||||
t.Setenv(envInstallKind, "npm")
|
||||
t.Setenv(envServiceMetadata, metadataPath)
|
||||
|
||||
svc := NewService(newTestPool(t), "v1.0.0", nil, logger.Default(), WithHomeDir(homeDir))
|
||||
resp, err := svc.Get()
|
||||
svc := NewService(
|
||||
newTestPool(t),
|
||||
"v1.0.0",
|
||||
nil,
|
||||
logger.Default(),
|
||||
WithHomeDir(homeDir),
|
||||
WithSettingsStore(&memorySettingsStore{}),
|
||||
)
|
||||
resp, err := svc.Get(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Get: %v", err)
|
||||
}
|
||||
@@ -39,6 +47,9 @@ func TestService_GetManagedUserServiceSupportsApply(t *testing.T) {
|
||||
if !resp.ApplySupported {
|
||||
t.Fatalf("ApplySupported=false reason=%q", resp.ApplyUnsupportedReason)
|
||||
}
|
||||
if !resp.ChannelEditable || resp.ChannelUnsupportedReason != "" {
|
||||
t.Fatalf("nightly capability editable=%v reason=%q", resp.ChannelEditable, resp.ChannelUnsupportedReason)
|
||||
}
|
||||
}
|
||||
|
||||
func TestService_GetManagedNativeServiceSupportsApply(t *testing.T) {
|
||||
@@ -80,13 +91,16 @@ func TestService_GetManagedNativeServiceSupportsApply(t *testing.T) {
|
||||
t.Setenv(envServiceMetadata, metadataPath)
|
||||
|
||||
svc := NewService(newTestPool(t), "v1.0.0", nil, logger.Default(), WithHomeDir(homeDir))
|
||||
resp, err := svc.Get()
|
||||
resp, err := svc.Get(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Get: %v", err)
|
||||
}
|
||||
if !resp.Install.ManagedService || !resp.ApplySupported {
|
||||
t.Fatalf("native install state = %+v apply_supported=%v reason=%q", resp.Install, resp.ApplySupported, resp.ApplyUnsupportedReason)
|
||||
}
|
||||
if resp.ChannelEditable || resp.ChannelUnsupportedReason == "" {
|
||||
t.Fatalf("Homebrew nightly capability editable=%v reason=%q", resp.ChannelEditable, resp.ChannelUnsupportedReason)
|
||||
}
|
||||
}
|
||||
|
||||
func TestService_GetManagedSystemdServiceSupportsApplyWithPercentInMetadataPath(t *testing.T) {
|
||||
@@ -112,7 +126,7 @@ func TestService_GetManagedSystemdServiceSupportsApplyWithPercentInMetadataPath(
|
||||
t.Setenv(envServiceMetadata, metadataPath)
|
||||
|
||||
svc := NewService(newTestPool(t), "v1.0.0", nil, logger.Default(), WithHomeDir(homeDir))
|
||||
resp, err := svc.Get()
|
||||
resp, err := svc.Get(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Get: %v", err)
|
||||
}
|
||||
@@ -141,7 +155,7 @@ func TestService_GetSystemServiceDisablesApply(t *testing.T) {
|
||||
t.Setenv(envServiceMetadata, metadataPath)
|
||||
|
||||
svc := NewService(newTestPool(t), "v1.0.0", nil, logger.Default(), WithHomeDir(homeDir))
|
||||
resp, err := svc.Get()
|
||||
resp, err := svc.Get(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Get: %v", err)
|
||||
}
|
||||
@@ -184,7 +198,7 @@ func TestService_GetForeignServiceDisablesApply(t *testing.T) {
|
||||
t.Setenv(envServiceMetadata, metadataPath)
|
||||
|
||||
svc := NewService(newTestPool(t), "v1.0.0", nil, logger.Default(), WithHomeDir(homeDir))
|
||||
resp, err := svc.Get()
|
||||
resp, err := svc.Get(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Get: %v", err)
|
||||
}
|
||||
@@ -216,7 +230,7 @@ func TestService_GetLocalBundleServiceDisablesApply(t *testing.T) {
|
||||
t.Setenv(envServiceMetadata, metadataPath)
|
||||
|
||||
svc := NewService(newTestPool(t), "v1.0.0", nil, logger.Default(), WithHomeDir(homeDir))
|
||||
resp, err := svc.Get()
|
||||
resp, err := svc.Get(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Get: %v", err)
|
||||
}
|
||||
@@ -247,6 +261,60 @@ func TestManualCommandsNPXHasNoDuplicateBinaryName(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestManagedUserServiceCapabilitiesShareBaseEligibility(t *testing.T) {
|
||||
for name, state := range map[string]InstallStateResponse{
|
||||
"not running": {
|
||||
ManagedService: true,
|
||||
Mode: installModeUser,
|
||||
Manager: serviceManagerSystemd,
|
||||
Kind: installKindNPM,
|
||||
},
|
||||
"unmanaged": {
|
||||
RunningAsService: true,
|
||||
Mode: installModeUser,
|
||||
Manager: serviceManagerSystemd,
|
||||
Kind: installKindNPM,
|
||||
},
|
||||
"system mode": {
|
||||
RunningAsService: true,
|
||||
ManagedService: true,
|
||||
Mode: installModeSystem,
|
||||
Manager: serviceManagerSystemd,
|
||||
Kind: installKindNPM,
|
||||
},
|
||||
"unsupported manager": {
|
||||
RunningAsService: true,
|
||||
ManagedService: true,
|
||||
Mode: installModeUser,
|
||||
Manager: "other",
|
||||
Kind: installKindNPM,
|
||||
},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
if supported, _ := state.applySupport(); supported {
|
||||
t.Fatal("apply unexpectedly supported")
|
||||
}
|
||||
if supported, _ := state.nightlySupport(); supported {
|
||||
t.Fatal("Nightly unexpectedly supported")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
homebrew := InstallStateResponse{
|
||||
RunningAsService: true,
|
||||
ManagedService: true,
|
||||
Mode: installModeUser,
|
||||
Manager: serviceManagerLaunchd,
|
||||
Kind: installKindHomebrew,
|
||||
}
|
||||
if supported, _ := homebrew.applySupport(); !supported {
|
||||
t.Fatal("managed Homebrew user service should support Stable apply")
|
||||
}
|
||||
if supported, _ := homebrew.nightlySupport(); supported {
|
||||
t.Fatal("managed Homebrew user service should not support Nightly")
|
||||
}
|
||||
}
|
||||
|
||||
func writeServiceInstallForTest(t *testing.T, homeDir string, metadata serviceInstallMetadata) (string, string) {
|
||||
t.Helper()
|
||||
metadata.Version = serviceMetadataVersion
|
||||
|
||||
@@ -2,6 +2,8 @@ package updates
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -24,6 +26,23 @@ type updateNotification struct {
|
||||
url string
|
||||
}
|
||||
|
||||
type firstCallBlockingNotifier struct {
|
||||
calls atomic.Int32
|
||||
entered chan struct{}
|
||||
release chan struct{}
|
||||
}
|
||||
|
||||
func (n *firstCallBlockingNotifier) HandleUpdateAvailable(ctx context.Context, _, _ string) {
|
||||
if n.calls.Add(1) != 1 {
|
||||
return
|
||||
}
|
||||
close(n.entered)
|
||||
select {
|
||||
case <-n.release:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
}
|
||||
|
||||
func (n *capturingNotifier) HandleUpdateAvailable(_ context.Context, version, releaseURL string) {
|
||||
n.calls = append(n.calls, updateNotification{version: version, url: releaseURL})
|
||||
}
|
||||
@@ -69,6 +88,160 @@ func TestService_FetchAndPersist_NotifiesCanonicalServiceForNewerRelease(t *test
|
||||
}
|
||||
}
|
||||
|
||||
func TestService_ReplayNightlyNotifiesForUnequalAuthoritativeSHA(t *testing.T) {
|
||||
homeDir := configureManagedNPMInstall(t)
|
||||
pool := newTestPool(t)
|
||||
store := &memorySettingsStore{value: []byte(ChannelNightly), present: true}
|
||||
if err := persistence.WriteLatestNightlyVersion(
|
||||
pool.Writer(),
|
||||
"1.2.4-nightly.sha000000000000",
|
||||
"https://example.test/nightly",
|
||||
time.Now(),
|
||||
); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
svc := NewService(
|
||||
pool,
|
||||
"v1.2.4-nightly.shaffffffffffff",
|
||||
nil,
|
||||
logger.Default(),
|
||||
WithHomeDir(homeDir),
|
||||
WithSettingsStore(store),
|
||||
)
|
||||
notifier := &capturingNotifier{}
|
||||
svc.SetNotifier(notifier)
|
||||
if err := svc.ReplayCachedUpdate(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(notifier.calls) != 1 {
|
||||
t.Fatalf("notifier calls=%d want 1", len(notifier.calls))
|
||||
}
|
||||
if got := notifier.calls[0]; got.version != "1.2.4-nightly.sha000000000000" || got.url != "https://example.test/nightly" {
|
||||
t.Errorf("notifier call = %+v, want cached nightly", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestService_ReplayCachedUpdateSerializesWithChannelSelection(t *testing.T) {
|
||||
homeDir := configureManagedNPMInstall(t)
|
||||
pool := newTestPool(t)
|
||||
store := &memorySettingsStore{value: []byte(ChannelStable), present: true}
|
||||
if err := persistence.WriteLatestVersion(
|
||||
pool.Writer(),
|
||||
"v1.2.4",
|
||||
"https://example.test/stable",
|
||||
time.Now(),
|
||||
); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
svc := NewService(
|
||||
pool,
|
||||
"v1.2.3",
|
||||
nil,
|
||||
logger.Default(),
|
||||
WithHomeDir(homeDir),
|
||||
WithSettingsStore(store),
|
||||
)
|
||||
notifier := &firstCallBlockingNotifier{
|
||||
entered: make(chan struct{}),
|
||||
release: make(chan struct{}),
|
||||
}
|
||||
releaseReplay := sync.OnceFunc(func() { close(notifier.release) })
|
||||
t.Cleanup(releaseReplay)
|
||||
svc.SetNotifier(notifier)
|
||||
nightlyFetchEntered := make(chan struct{})
|
||||
svc.SetNightlyFetcher(func(context.Context) (string, string, error) {
|
||||
close(nightlyFetchEntered)
|
||||
return "v1.2.5-nightly.shaabcdef123456", "https://example.test/nightly", nil
|
||||
})
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
replayDone := make(chan error, 1)
|
||||
go func() { replayDone <- svc.ReplayCachedUpdate(ctx) }()
|
||||
select {
|
||||
case <-notifier.entered:
|
||||
case err := <-replayDone:
|
||||
t.Fatalf("cached replay returned before notifier: %v", err)
|
||||
case <-ctx.Done():
|
||||
t.Fatal("cached replay did not reach notifier")
|
||||
}
|
||||
if svc.updateMu.TryLock() {
|
||||
svc.updateMu.Unlock()
|
||||
t.Fatal("update lock was not held while cached replay notified")
|
||||
}
|
||||
|
||||
selectDone := make(chan error, 1)
|
||||
selectStarted := make(chan struct{})
|
||||
go func() {
|
||||
close(selectStarted)
|
||||
_, err := svc.SelectChannel(ctx, string(ChannelNightly))
|
||||
selectDone <- err
|
||||
}()
|
||||
select {
|
||||
case <-selectStarted:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("channel selection did not start")
|
||||
}
|
||||
|
||||
releaseReplay()
|
||||
select {
|
||||
case err := <-replayDone:
|
||||
if err != nil {
|
||||
t.Fatalf("cached replay: %v", err)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal("cached replay did not finish")
|
||||
}
|
||||
select {
|
||||
case <-nightlyFetchEntered:
|
||||
case err := <-selectDone:
|
||||
t.Fatalf("channel selection returned before resolving Nightly: %v", err)
|
||||
case <-ctx.Done():
|
||||
t.Fatal("channel selection did not resolve Nightly")
|
||||
}
|
||||
select {
|
||||
case err := <-selectDone:
|
||||
if err != nil {
|
||||
t.Fatalf("channel selection: %v", err)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal("channel selection did not finish")
|
||||
}
|
||||
}
|
||||
|
||||
func TestService_ReturnToOlderStableIsAvailableWithoutUpgradeNotification(t *testing.T) {
|
||||
homeDir := configureManagedNPMInstall(t)
|
||||
pool := newTestPool(t)
|
||||
store := &memorySettingsStore{value: []byte(ChannelStable), present: true}
|
||||
if err := persistence.WriteLatestVersion(pool.Writer(), "v1.2.3", "https://example.test/stable", time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
svc := NewService(
|
||||
pool,
|
||||
"v1.2.4-nightly.shaabc123def456",
|
||||
nil,
|
||||
logger.Default(),
|
||||
WithHomeDir(homeDir),
|
||||
WithSettingsStore(store),
|
||||
)
|
||||
notifier := &capturingNotifier{}
|
||||
svc.SetNotifier(notifier)
|
||||
|
||||
resp, err := svc.Get(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !resp.UpdateAvailable {
|
||||
t.Fatal("explicit stable return should be available")
|
||||
}
|
||||
if err := svc.ReplayCachedUpdate(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(notifier.calls) != 0 {
|
||||
t.Fatalf("downgrade-like stable return sent %d notification(s)", len(notifier.calls))
|
||||
}
|
||||
}
|
||||
|
||||
func TestService_PollBeforeLocalSubscription_ReplaysCachedUpdateExactlyOnce(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
t.Setenv("KANDEV_DESKTOP_NATIVE_NOTIFICATIONS", "true")
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
package updates
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const DefaultNPMRegistryURL = "https://registry.npmjs.org/kandev"
|
||||
const maxNPMPackageResponseBytes = 8 << 20
|
||||
|
||||
type npmPackagePayload struct {
|
||||
DistTags map[string]string `json:"dist-tags"`
|
||||
Versions map[string]json.RawMessage `json:"versions"`
|
||||
}
|
||||
|
||||
type npmVersionRecord struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
|
||||
func FetchLatestNightlyFrom(ctx context.Context, client *http.Client, registryURL string) (string, string, error) {
|
||||
if client == nil {
|
||||
client = &http.Client{Timeout: defaultClientTimeout}
|
||||
}
|
||||
if registryURL == "" {
|
||||
registryURL = DefaultNPMRegistryURL
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, registryURL, nil)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("build npm request: %w", err)
|
||||
}
|
||||
req.Header.Set("Accept", "application/vnd.npm.install-v1+json")
|
||||
req.Header.Set("User-Agent", "kandev-updates-poller")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("npm request: %w", err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
|
||||
return "", "", fmt.Errorf("npm registry returned status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
payload, err := decodeNPMPackagePayload(resp.Body)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
version := payload.DistTags[string(ChannelNightly)]
|
||||
if version == "" {
|
||||
return "", "", errors.New("npm response missing nightly dist-tag")
|
||||
}
|
||||
// npm package versions and dist-tag targets use canonical bare SemVer.
|
||||
// Internal update tags add v only after this registry integrity check.
|
||||
if !isCanonicalNPMNightlyVersion(version) {
|
||||
return "", "", fmt.Errorf("npm response has invalid nightly version %q", version)
|
||||
}
|
||||
record, ok := payload.Versions[version]
|
||||
if !ok || len(record) == 0 || string(record) == "null" {
|
||||
return "", "", fmt.Errorf("npm response missing exact version %q", version)
|
||||
}
|
||||
if !isExactNPMVersionRecord(record, version) {
|
||||
return "", "", fmt.Errorf("npm response has invalid exact version record %q", version)
|
||||
}
|
||||
|
||||
return "v" + version, "https://www.npmjs.com/package/kandev/v/" + url.PathEscape(version), nil
|
||||
}
|
||||
|
||||
func isExactNPMVersionRecord(record json.RawMessage, version string) bool {
|
||||
var exact npmVersionRecord
|
||||
return json.Unmarshal(record, &exact) == nil &&
|
||||
exact.Name == "kandev" && exact.Version == version
|
||||
}
|
||||
|
||||
func isCanonicalNPMNightlyVersion(version string) bool {
|
||||
return !strings.HasPrefix(version, "v") && isNightlyVersion(version)
|
||||
}
|
||||
|
||||
func decodeNPMPackagePayload(reader io.Reader) (npmPackagePayload, error) {
|
||||
body, err := io.ReadAll(io.LimitReader(reader, maxNPMPackageResponseBytes+1))
|
||||
if err != nil {
|
||||
return npmPackagePayload{}, fmt.Errorf("read npm response: %w", err)
|
||||
}
|
||||
if len(body) > maxNPMPackageResponseBytes {
|
||||
return npmPackagePayload{}, fmt.Errorf("npm response exceeds %d bytes", maxNPMPackageResponseBytes)
|
||||
}
|
||||
var payload npmPackagePayload
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
return npmPackagePayload{}, fmt.Errorf("decode npm response: %w", err)
|
||||
}
|
||||
return payload, nil
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package updates
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFetchLatestNightlyFromAcceptsCanonicalUnprefixedVersion(t *testing.T) {
|
||||
const version = "1.2.4-nightly.shaabc123def456"
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if got := r.Header.Get("Accept"); got != "application/vnd.npm.install-v1+json" {
|
||||
t.Errorf("Accept=%q", got)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"dist-tags":{"nightly":"` + version + `"},"versions":{"` + version + `":{"name":"kandev","version":"` + version + `"}}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
got, packageURL, err := FetchLatestNightlyFrom(context.Background(), server.Client(), server.URL)
|
||||
if err != nil {
|
||||
t.Fatalf("FetchLatestNightlyFrom: %v", err)
|
||||
}
|
||||
if got != "v"+version {
|
||||
t.Fatalf("version=%q want %q", got, "v"+version)
|
||||
}
|
||||
if packageURL != "https://www.npmjs.com/package/kandev/v/"+version {
|
||||
t.Fatalf("packageURL=%q", packageURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchLatestNightlyFromRejectsInvalidRegistryDocuments(t *testing.T) {
|
||||
const valid = "1.2.4-nightly.shaabc123def456"
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
want string
|
||||
}{
|
||||
{name: "missing tag", body: `{"dist-tags":{},"versions":{}}`, want: "missing nightly dist-tag"},
|
||||
{name: "invalid version", body: `{"dist-tags":{"nightly":"1.2.4-nightly.shaBAD"},"versions":{}}`, want: "invalid nightly version"},
|
||||
{
|
||||
name: "prefixed npm version",
|
||||
body: `{"dist-tags":{"nightly":"v` + valid + `"},"versions":{"v` + valid + `":{"name":"kandev"}}}`,
|
||||
want: "invalid nightly version",
|
||||
},
|
||||
{name: "missing exact record", body: `{"dist-tags":{"nightly":"` + valid + `"},"versions":{}}`, want: "missing exact version"},
|
||||
{name: "null exact record", body: `{"dist-tags":{"nightly":"` + valid + `"},"versions":{"` + valid + `":null}}`, want: "missing exact version"},
|
||||
{name: "empty string exact record", body: `{"dist-tags":{"nightly":"` + valid + `"},"versions":{"` + valid + `":""}}`, want: "invalid exact version record"},
|
||||
{name: "empty exact record", body: `{"dist-tags":{"nightly":"` + valid + `"},"versions":{"` + valid + `":{}}}`, want: "invalid exact version record"},
|
||||
{name: "wrong package name", body: `{"dist-tags":{"nightly":"` + valid + `"},"versions":{"` + valid + `":{"name":"other","version":"` + valid + `"}}}`, want: "invalid exact version record"},
|
||||
{name: "wrong package version", body: `{"dist-tags":{"nightly":"` + valid + `"},"versions":{"` + valid + `":{"name":"kandev","version":"0.0.0"}}}`, want: "invalid exact version record"},
|
||||
{name: "malformed json", body: `{`, want: "decode npm response"},
|
||||
{
|
||||
name: "trailing json value",
|
||||
body: `{"dist-tags":{"nightly":"` + valid + `"},"versions":{"` + valid + `":{"name":"kandev","version":"` + valid + `"}}} {}`,
|
||||
want: "decode npm response",
|
||||
},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(tc.body))
|
||||
}))
|
||||
defer server.Close()
|
||||
_, _, err := FetchLatestNightlyFrom(context.Background(), server.Client(), server.URL)
|
||||
if err == nil || !strings.Contains(err.Error(), tc.want) {
|
||||
t.Fatalf("error=%v want substring %q", err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchLatestNightlyFromReturnsHTTPFailure(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
http.Error(w, "registry down: upstream-secret", http.StatusServiceUnavailable)
|
||||
}))
|
||||
defer server.Close()
|
||||
_, _, err := FetchLatestNightlyFrom(context.Background(), server.Client(), server.URL)
|
||||
if err == nil || !strings.Contains(err.Error(), "npm registry returned status 503") {
|
||||
t.Fatalf("error=%v", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), "upstream-secret") {
|
||||
t.Fatalf("error exposes registry response body: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchLatestNightlyFromRejectsOversizedResponse(t *testing.T) {
|
||||
const version = "1.2.4-nightly.shaabc123def456"
|
||||
body := strings.Repeat(" ", (8<<20)+1) +
|
||||
`{"dist-tags":{"nightly":"` + version + `"},"versions":{"` + version + `":{"name":"kandev"}}}`
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(body))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
_, _, err := FetchLatestNightlyFrom(context.Background(), server.Client(), server.URL)
|
||||
if err == nil || !strings.Contains(err.Error(), "npm response exceeds") {
|
||||
t.Fatalf("error=%v", err)
|
||||
}
|
||||
}
|
||||
@@ -71,7 +71,7 @@ func (s *Service) pollerLoop(ctx context.Context, interval time.Duration) {
|
||||
|
||||
// tickOnce performs a single poll iteration. Intentionally package-internal
|
||||
// so deterministic tests can drive the loop without spinning up synctest.
|
||||
// GitHub rate-limit responses are logged at info; everything else at warn.
|
||||
// GitHub rate-limit responses are logged at info; other source errors at warn.
|
||||
func (s *Service) tickOnce(ctx context.Context) {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
|
||||
@@ -58,6 +58,26 @@ func compareSemver(a, b string) int {
|
||||
return strings.Compare(ap, bp)
|
||||
}
|
||||
|
||||
// compareSemverCore compares only major.minor.patch and ignores prerelease
|
||||
// identifiers. Callers use it when different nightly SHAs at the same numeric
|
||||
// version are both valid targets, while a lower numeric target is a rollback.
|
||||
func compareSemverCore(a, b string) int {
|
||||
an, _, _, aok := parseSemver(a)
|
||||
bn, _, _, bok := parseSemver(b)
|
||||
if !aok || !bok {
|
||||
return compareSemver(a, b)
|
||||
}
|
||||
for i := range an {
|
||||
if an[i] < bn[i] {
|
||||
return -1
|
||||
}
|
||||
if an[i] > bn[i] {
|
||||
return 1
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// parseSemver returns the three numeric segments, the pre-release suffix (or
|
||||
// ""), the git-describe "commits ahead" count (0 when not a git-describe
|
||||
// build), and ok=false when the input is not a recognisable major.minor.patch
|
||||
|
||||
@@ -43,6 +43,25 @@ func TestCompareSemver(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompareSemverCoreFallsBackForInvalidInputs(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
a string
|
||||
b string
|
||||
}{
|
||||
{name: "invalid below valid", a: "not-a-version", b: "v1.2.3"},
|
||||
{name: "valid above invalid", a: "v1.2.3", b: "not-a-version"},
|
||||
{name: "both invalid", a: "invalid-b", b: "invalid-a"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
want := compareSemver(tc.a, tc.b)
|
||||
if got := compareSemverCore(tc.a, tc.b); got != want {
|
||||
t.Fatalf("compareSemverCore(%q, %q)=%d want fallback %d", tc.a, tc.b, got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGitDescribeCommits(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Package updates implements the kandev background updates poller and the
|
||||
// HTTP surface for the System -> Updates page. It polls GitHub Releases every
|
||||
// 6 hours, persists the latest tag in the kandev_meta key/value table, and
|
||||
// HTTP surface for the System -> Updates page. It resolves stable releases
|
||||
// from GitHub or nightlies from npm, persists isolated channel caches, and
|
||||
// exposes a 30s rate-limited "check now" handler.
|
||||
package updates
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
@@ -22,7 +23,8 @@ import (
|
||||
"github.com/kandev/kandev/internal/system/jobs"
|
||||
)
|
||||
|
||||
// PollInterval is the cadence at which the background goroutine polls GitHub.
|
||||
// PollInterval is the cadence at which the background goroutine polls the
|
||||
// selected update source.
|
||||
const PollInterval = 6 * time.Hour
|
||||
|
||||
// ManualCheckWindow is the minimum gap between two manual /check calls.
|
||||
@@ -60,15 +62,18 @@ const devVersion = "dev"
|
||||
|
||||
// UpdatesResponse is the JSON shape returned by both Get() and Check().
|
||||
type UpdatesResponse struct {
|
||||
Current string `json:"current"`
|
||||
Latest string `json:"latest"`
|
||||
LatestURL string `json:"latest_url"`
|
||||
LatestCheckedAt time.Time `json:"latest_checked_at"`
|
||||
UpdateAvailable bool `json:"update_available"`
|
||||
Install InstallStateResponse `json:"install"`
|
||||
ApplySupported bool `json:"apply_supported"`
|
||||
ApplyUnsupportedReason string `json:"apply_unsupported_reason,omitempty"`
|
||||
ManualCommands []string `json:"manual_commands,omitempty"`
|
||||
Current string `json:"current"`
|
||||
Latest string `json:"latest"`
|
||||
LatestURL string `json:"latest_url"`
|
||||
LatestCheckedAt time.Time `json:"latest_checked_at"`
|
||||
UpdateAvailable bool `json:"update_available"`
|
||||
Channel Channel `json:"channel"`
|
||||
ChannelEditable bool `json:"channel_editable"`
|
||||
ChannelUnsupportedReason string `json:"channel_unsupported_reason"`
|
||||
Install InstallStateResponse `json:"install"`
|
||||
ApplySupported bool `json:"apply_supported"`
|
||||
ApplyUnsupportedReason string `json:"apply_unsupported_reason,omitempty"`
|
||||
ManualCommands []string `json:"manual_commands,omitempty"`
|
||||
}
|
||||
|
||||
// ApplyResponse is the 202 payload returned when a self-update helper has
|
||||
@@ -89,9 +94,6 @@ type InstallStateResponse struct {
|
||||
MetadataPath string `json:"metadata_path,omitempty"`
|
||||
}
|
||||
|
||||
// releaseURL is the GitHub endpoint the service polls. Tests override it via
|
||||
// SetReleaseURL.
|
||||
//
|
||||
// Service holds the wiring needed to drive the poller and serve the two
|
||||
// HTTP endpoints.
|
||||
type Service struct {
|
||||
@@ -105,6 +107,7 @@ type Service struct {
|
||||
getenv func(string) string
|
||||
now func() time.Time
|
||||
applyRun applyRunner
|
||||
settings settingsStore
|
||||
|
||||
// notifier routes update availability through the canonical notification
|
||||
// service. It is nil-safe for isolated updates tests and minimal startup.
|
||||
@@ -117,16 +120,23 @@ type Service struct {
|
||||
// the backend cannot wedge apply behind a permanent 409.
|
||||
applyStartedAt atomic.Int64
|
||||
|
||||
// updateMu serializes source resolution and cache persistence across the
|
||||
// poller, manual checks, channel changes, and apply preflight. A slower,
|
||||
// older resolution therefore cannot overwrite a newer operation's cache.
|
||||
updateMu sync.Mutex
|
||||
|
||||
// releaseURL is the GitHub endpoint hit by Check + the poller; defaults
|
||||
// to DefaultReleaseURL and can be overridden by SetReleaseURL for tests.
|
||||
releaseURL string
|
||||
nightlyURL string
|
||||
|
||||
// fetcher is the function used to retrieve the latest release. Defaults
|
||||
// to FetchLatestReleaseFrom(httpClient). Tests inject a deterministic
|
||||
// stub via SetFetcher so the synctest poller test does not block on
|
||||
// real network I/O (which sits outside the fake-time bubble and prevents
|
||||
// synctest.Wait from settling).
|
||||
fetcher Fetcher
|
||||
fetcher Fetcher
|
||||
nightlyFetcher Fetcher
|
||||
|
||||
// mu protects pollerStarted/cancel/wg under concurrent Start calls.
|
||||
mu sync.Mutex
|
||||
@@ -136,8 +146,8 @@ type Service struct {
|
||||
pollerInterval time.Duration
|
||||
}
|
||||
|
||||
// Fetcher abstracts the GitHub release call so tests can drive
|
||||
// the poller and Check() without spinning up an httptest server.
|
||||
// Fetcher abstracts update-source resolution so tests can drive the poller
|
||||
// and Check() without spinning up an httptest server.
|
||||
type Fetcher func(ctx context.Context) (tag, url string, err error)
|
||||
|
||||
// UpdateNotifier is the narrow canonical notification-service boundary used
|
||||
@@ -207,12 +217,14 @@ func NewService(pool *db.Pool, current string, httpClient *http.Client, log *log
|
||||
log: log,
|
||||
limiter: NewLimiter(ManualCheckWindow),
|
||||
releaseURL: DefaultReleaseURL,
|
||||
nightlyURL: DefaultNPMRegistryURL,
|
||||
pollerInterval: PollInterval,
|
||||
homeDir: homeDir,
|
||||
getenv: os.Getenv,
|
||||
now: time.Now,
|
||||
}
|
||||
s.fetcher = s.defaultFetcher
|
||||
s.nightlyFetcher = s.defaultNightlyFetcher
|
||||
s.applyRun = s.defaultApplyRunner
|
||||
for _, opt := range opts {
|
||||
opt(s)
|
||||
@@ -230,6 +242,13 @@ func (s *Service) defaultFetcher(ctx context.Context) (string, string, error) {
|
||||
return FetchLatestReleaseFrom(ctx, s.httpClient, url)
|
||||
}
|
||||
|
||||
func (s *Service) defaultNightlyFetcher(ctx context.Context) (string, string, error) {
|
||||
s.mu.Lock()
|
||||
url := s.nightlyURL
|
||||
s.mu.Unlock()
|
||||
return FetchLatestNightlyFrom(ctx, s.httpClient, url)
|
||||
}
|
||||
|
||||
// SetFetcher overrides the GitHub fetch implementation. Intended for tests
|
||||
// that need deterministic behaviour inside testing/synctest.
|
||||
func (s *Service) SetFetcher(f Fetcher) {
|
||||
@@ -242,6 +261,17 @@ func (s *Service) SetFetcher(f Fetcher) {
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
// SetNightlyFetcher overrides npm nightly resolution. Intended for tests.
|
||||
func (s *Service) SetNightlyFetcher(f Fetcher) {
|
||||
s.mu.Lock()
|
||||
if f == nil {
|
||||
s.nightlyFetcher = s.defaultNightlyFetcher
|
||||
} else {
|
||||
s.nightlyFetcher = f
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
// SetReleaseURL overrides the GitHub endpoint used by the poller and Check().
|
||||
// Intended for tests that point at a httptest stub server.
|
||||
func (s *Service) SetReleaseURL(url string) {
|
||||
@@ -250,6 +280,13 @@ func (s *Service) SetReleaseURL(url string) {
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
// SetNightlyURL overrides the npm registry endpoint used by Check + poller.
|
||||
func (s *Service) SetNightlyURL(url string) {
|
||||
s.mu.Lock()
|
||||
s.nightlyURL = url
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
// SetNotifier wires the canonical notifier after gateway composition.
|
||||
func (s *Service) SetNotifier(notifier UpdateNotifier) {
|
||||
s.mu.Lock()
|
||||
@@ -257,19 +294,24 @@ func (s *Service) SetNotifier(notifier UpdateNotifier) {
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
// Get returns the last-known state from kandev_meta without contacting
|
||||
// GitHub. Safe to call on every page load.
|
||||
func (s *Service) Get() (UpdatesResponse, error) {
|
||||
version, url, checkedAt, err := persistence.ReadLatestVersion(s.pool.Reader())
|
||||
// Get returns the selected channel's last-known state without contacting its
|
||||
// upstream. Safe to call on every page load.
|
||||
func (s *Service) Get(ctx context.Context) (UpdatesResponse, error) {
|
||||
install, _ := s.detectInstallState()
|
||||
channel, err := s.effectiveChannel(ctx, install)
|
||||
if err != nil {
|
||||
return UpdatesResponse{}, err
|
||||
}
|
||||
return s.buildResponse(version, url, checkedAt), nil
|
||||
version, url, checkedAt, err := s.readLatestVersion(channel)
|
||||
if err != nil {
|
||||
return UpdatesResponse{}, err
|
||||
}
|
||||
return s.buildResponseFromChannel(channel, install, version, url, checkedAt), nil
|
||||
}
|
||||
|
||||
// Check forces a synchronous poll against GitHub. Rate-limited per process by
|
||||
// the 30s Limiter. On success the result is persisted and returned. On
|
||||
// failure the previously persisted values are returned unchanged.
|
||||
// Check forces a synchronous poll against the effective channel's source.
|
||||
// It is rate-limited per process by the 30s Limiter. On failure the selected
|
||||
// channel's previously persisted values remain unchanged.
|
||||
func (s *Service) Check(ctx context.Context) (UpdatesResponse, error) {
|
||||
if ok, _ := s.limiter.Allow(); !ok {
|
||||
return UpdatesResponse{}, ErrRateLimited
|
||||
@@ -277,20 +319,16 @@ func (s *Service) Check(ctx context.Context) (UpdatesResponse, error) {
|
||||
return s.fetchAndPersist(ctx)
|
||||
}
|
||||
|
||||
// Apply validates the cached update and current service install, writes an
|
||||
// intent file, and queues the OS-manager helper that performs the actual
|
||||
// package upgrade + service reinstall.
|
||||
func (s *Service) Apply(ctx context.Context, confirm string) (string, error) {
|
||||
// Apply validates that the expected target still matches the cached update and
|
||||
// current service install, writes an exact-version intent, and queues the
|
||||
// OS-manager helper that performs the package upgrade + service reinstall.
|
||||
func (s *Service) Apply(ctx context.Context, confirm, expectedTarget string) (string, error) {
|
||||
if confirm != "UPDATE" {
|
||||
return "", ErrApplyConfirm
|
||||
}
|
||||
if s.jobs == nil {
|
||||
return "", ErrApplyUnsupported
|
||||
}
|
||||
resp, metadata, err := s.applyPreflight()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// Claim the in-flight guard across the launch. A successful launch keeps it
|
||||
// held because the helper restarts the backend shortly (which clears it by
|
||||
// replacing the process); a launch error releases it for an immediate retry.
|
||||
@@ -299,6 +337,11 @@ func (s *Service) Apply(ctx context.Context, confirm string) (string, error) {
|
||||
if !s.claimApplyGuard() {
|
||||
return "", ErrApplyInProgress
|
||||
}
|
||||
resp, metadata, err := s.applyPreflight(ctx, expectedTarget)
|
||||
if err != nil {
|
||||
s.applyStartedAt.Store(0)
|
||||
return "", err
|
||||
}
|
||||
intentPath, intent, err := s.writeApplyIntent(resp, metadata)
|
||||
if err != nil {
|
||||
s.applyStartedAt.Store(0)
|
||||
@@ -357,43 +400,69 @@ func (s *Service) peekLimiter() (bool, time.Duration) {
|
||||
return false, retry
|
||||
}
|
||||
|
||||
// fetchAndPersist hits GitHub, persists the result on success, and always
|
||||
// returns the now-current view of kandev_meta. A fetch failure preserves the
|
||||
// previously persisted state and returns the underlying error.
|
||||
// fetchAndPersist resolves the effective channel and persists its isolated
|
||||
// cache on success. A fetch failure preserves both caches.
|
||||
func (s *Service) fetchAndPersist(ctx context.Context) (UpdatesResponse, error) {
|
||||
s.mu.Lock()
|
||||
fetch := s.fetcher
|
||||
s.mu.Unlock()
|
||||
s.updateMu.Lock()
|
||||
defer s.updateMu.Unlock()
|
||||
|
||||
tag, releaseURL, err := fetch(ctx)
|
||||
install, _ := s.detectInstallState()
|
||||
channel, err := s.effectiveChannel(ctx, install)
|
||||
if err != nil {
|
||||
// Preserve persisted state; surface the error to caller.
|
||||
current, _ := s.Get()
|
||||
return current, err
|
||||
return UpdatesResponse{}, err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
if werr := persistence.WriteLatestVersion(s.pool.Writer(), tag, releaseURL, now); werr != nil {
|
||||
tag, releaseURL, err := s.resolveLatest(ctx, channel)
|
||||
if err != nil {
|
||||
// Preserve persisted state without re-reading settings through a context
|
||||
// the failed upstream request may already have canceled.
|
||||
version, url, checkedAt, readErr := s.readLatestVersion(channel)
|
||||
if readErr != nil {
|
||||
s.log.Warn("updates: read cached version after fetch failure", zap.Error(readErr))
|
||||
return UpdatesResponse{}, err
|
||||
}
|
||||
return s.buildResponseFromChannel(channel, install, version, url, checkedAt), err
|
||||
}
|
||||
now := s.now().UTC()
|
||||
if werr := s.writeLatestVersion(channel, tag, releaseURL, now); werr != nil {
|
||||
s.log.Warn("updates: persist latest version failed", zap.Error(werr))
|
||||
return UpdatesResponse{}, werr
|
||||
}
|
||||
s.notifyUpdateAvailable(ctx, tag, releaseURL)
|
||||
return s.buildResponse(tag, releaseURL, now), nil
|
||||
s.notifyUpdateAvailableFor(ctx, channel, tag, releaseURL)
|
||||
return s.buildResponseFromChannel(channel, install, tag, releaseURL, now), nil
|
||||
}
|
||||
|
||||
func (s *Service) resolveLatest(ctx context.Context, channel Channel) (string, string, error) {
|
||||
s.mu.Lock()
|
||||
fetch := s.fetcher
|
||||
if channel == ChannelNightly {
|
||||
fetch = s.nightlyFetcher
|
||||
}
|
||||
s.mu.Unlock()
|
||||
return fetch(ctx)
|
||||
}
|
||||
|
||||
// ReplayCachedUpdate delivers a previously persisted newer release without
|
||||
// contacting GitHub. It is called when the default user becomes eligible for
|
||||
// Local delivery after an early startup poll.
|
||||
// contacting the selected upstream. It is called when the default user becomes
|
||||
// eligible for Local delivery after an early startup poll.
|
||||
func (s *Service) ReplayCachedUpdate(ctx context.Context) error {
|
||||
tag, releaseURL, _, err := persistence.ReadLatestVersion(s.pool.Reader())
|
||||
s.updateMu.Lock()
|
||||
defer s.updateMu.Unlock()
|
||||
|
||||
install, _ := s.detectInstallState()
|
||||
channel, err := s.effectiveChannel(ctx, install)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.notifyUpdateAvailable(ctx, tag, releaseURL)
|
||||
tag, releaseURL, _, err := s.readLatestVersion(channel)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.notifyUpdateAvailableFor(ctx, channel, tag, releaseURL)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) notifyUpdateAvailable(ctx context.Context, tag, releaseURL string) {
|
||||
if !s.updateAvailable(tag) {
|
||||
func (s *Service) notifyUpdateAvailableFor(ctx context.Context, channel Channel, tag, releaseURL string) {
|
||||
if !s.notificationAvailableFor(channel, tag) {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
@@ -405,33 +474,47 @@ func (s *Service) notifyUpdateAvailable(ctx context.Context, tag, releaseURL str
|
||||
notifier.HandleUpdateAvailable(ctx, tag, releaseURL)
|
||||
}
|
||||
|
||||
func (s *Service) buildResponse(latest, url string, checkedAt time.Time) UpdatesResponse {
|
||||
install, _ := s.detectInstallState()
|
||||
return s.buildResponseFrom(install, latest, url, checkedAt)
|
||||
func (s *Service) notificationAvailableFor(channel Channel, latest string) bool {
|
||||
if !s.updateAvailableFor(channel, latest) {
|
||||
return false
|
||||
}
|
||||
// Returning from a nightly to an older stable is an explicit user action,
|
||||
// not a newly available upgrade. Keep it actionable in the UI without
|
||||
// broadcasting an upgrade notification.
|
||||
if channel == ChannelStable && isNightlyVersion(s.current) && compareSemver(latest, s.current) <= 0 {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// buildResponseFrom assembles the response from an already-detected install
|
||||
// state. Apply reuses this so the ApplySupported gate and the intent file are
|
||||
// derived from a single install-state snapshot rather than two independent
|
||||
// reads (closing a narrow TOCTOU window).
|
||||
func (s *Service) buildResponseFrom(install InstallStateResponse, latest, url string, checkedAt time.Time) UpdatesResponse {
|
||||
// buildResponseFromChannel assembles a response from one install-state
|
||||
// snapshot so capability gates and apply intent stay consistent.
|
||||
func (s *Service) buildResponseFromChannel(channel Channel, install InstallStateResponse, latest, url string, checkedAt time.Time) UpdatesResponse {
|
||||
applySupported, reason := install.applySupport()
|
||||
channelEditable, channelReason := s.channelSupport(install)
|
||||
return UpdatesResponse{
|
||||
Current: s.current,
|
||||
Latest: latest,
|
||||
LatestURL: url,
|
||||
LatestCheckedAt: checkedAt,
|
||||
UpdateAvailable: s.updateAvailable(latest),
|
||||
Install: install,
|
||||
ApplySupported: applySupported,
|
||||
ApplyUnsupportedReason: reason,
|
||||
ManualCommands: manualCommands(install, latest),
|
||||
Current: s.current,
|
||||
Latest: latest,
|
||||
LatestURL: url,
|
||||
LatestCheckedAt: checkedAt,
|
||||
UpdateAvailable: s.updateAvailableFor(channel, latest),
|
||||
Channel: channel,
|
||||
ChannelEditable: channelEditable,
|
||||
ChannelUnsupportedReason: channelReason,
|
||||
Install: install,
|
||||
ApplySupported: applySupported,
|
||||
ApplyUnsupportedReason: reason,
|
||||
ManualCommands: manualCommands(install, latest),
|
||||
}
|
||||
}
|
||||
|
||||
// updateAvailable returns true iff latest is a valid semver strictly greater
|
||||
// than current. Current = "dev" or empty disables the flag.
|
||||
func (s *Service) updateAvailable(latest string) bool {
|
||||
return s.updateAvailableFor(ChannelStable, latest)
|
||||
}
|
||||
|
||||
func (s *Service) updateAvailableFor(channel Channel, latest string) bool {
|
||||
if latest == "" || !isValidSemver(latest) {
|
||||
return false
|
||||
}
|
||||
@@ -441,5 +524,30 @@ func (s *Service) updateAvailable(latest string) bool {
|
||||
if !isValidSemver(s.current) {
|
||||
return false
|
||||
}
|
||||
current := strings.TrimPrefix(s.current, "v")
|
||||
target := strings.TrimPrefix(latest, "v")
|
||||
if current == target {
|
||||
return false
|
||||
}
|
||||
if channel == ChannelNightly && isNightlyVersion(s.current) && isNightlyVersion(latest) {
|
||||
return compareSemverCore(latest, s.current) >= 0
|
||||
}
|
||||
if channel == ChannelStable && isNightlyVersion(s.current) && !isNightlyVersion(latest) {
|
||||
return true
|
||||
}
|
||||
return compareSemver(latest, s.current) > 0
|
||||
}
|
||||
|
||||
func (s *Service) readLatestVersion(channel Channel) (string, string, time.Time, error) {
|
||||
if channel == ChannelNightly {
|
||||
return persistence.ReadLatestNightlyVersion(s.pool.Reader())
|
||||
}
|
||||
return persistence.ReadLatestVersion(s.pool.Reader())
|
||||
}
|
||||
|
||||
func (s *Service) writeLatestVersion(channel Channel, version, url string, checkedAt time.Time) error {
|
||||
if channel == ChannelNightly {
|
||||
return persistence.WriteLatestNightlyVersion(s.pool.Writer(), version, url, checkedAt)
|
||||
}
|
||||
return persistence.WriteLatestVersion(s.pool.Writer(), version, url, checkedAt)
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ func TestService_Get_FreshDB_ReturnsZeroValues(t *testing.T) {
|
||||
pool := newTestPool(t)
|
||||
svc := NewService(pool, "v1.0.0", nil, logger.Default())
|
||||
|
||||
resp, err := svc.Get()
|
||||
resp, err := svc.Get(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Get: %v", err)
|
||||
}
|
||||
@@ -100,7 +100,7 @@ func TestService_Check_PersistsToMeta(t *testing.T) {
|
||||
}
|
||||
|
||||
// Persistence side-effect: a fresh Get should return the same values.
|
||||
got, err := svc.Get()
|
||||
got, err := svc.Get(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("Get: %v", err)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,10 @@ function readRepoFile(path: string): string {
|
||||
return readFileSync(resolve(repoRoot, path), "utf8");
|
||||
}
|
||||
|
||||
function runtimePackagesIn(source: string): string[] {
|
||||
return [...new Set(source.match(/@kdlbs\/runtime-[a-z0-9-]+/g) ?? [])].sort();
|
||||
}
|
||||
|
||||
function workflowFiles(): string[] {
|
||||
const workflowDir = resolve(repoRoot, ".github/workflows");
|
||||
return readdirSync(workflowDir)
|
||||
@@ -226,16 +230,79 @@ describe("release runtime tooling configuration", () => {
|
||||
});
|
||||
|
||||
describe("release npm publishing", () => {
|
||||
it("skips packages that are already published on npm", () => {
|
||||
it("accepts either GitHub release assets or local nightly assets", () => {
|
||||
const script = readRepoFile("scripts/release/publish-npm.sh");
|
||||
|
||||
expect(script).toContain('npm view "${pkg}@${VERSION}" version --silent');
|
||||
expect(script).toMatch(
|
||||
/if package_already_published "\$pkg"; then\s+record_already_published "\$pkg"\s+continue\s+fi/,
|
||||
for (const flag of ["--version", "--dist-tag", "--release-tag", "--assets-dir"]) {
|
||||
expect(script).toContain(flag);
|
||||
}
|
||||
expect(script).toContain('DIST_TAG=""');
|
||||
expect(script).toContain('case "$DIST_TAG" in');
|
||||
expect(script).toContain("latest)");
|
||||
expect(script).toContain("nightly)");
|
||||
expect(script).toContain('if [[ -n "$RELEASE_TAG" && -n "$SOURCE_ASSETS_DIR" ]]');
|
||||
expect(script).toContain('elif [[ -z "$RELEASE_TAG" && -z "$SOURCE_ASSETS_DIR" ]]');
|
||||
expect(script).toContain('elif [[ "$DIST_TAG" == "latest" && -z "$RELEASE_TAG" ]]');
|
||||
expect(script).toContain('elif [[ "$DIST_TAG" == "nightly" && -z "$SOURCE_ASSETS_DIR" ]]');
|
||||
expect(script).toContain('ASSETS_DIR="$SOURCE_ASSETS_DIR"');
|
||||
});
|
||||
|
||||
it("publishes all packages under the requested dist-tag and pins the launcher version", () => {
|
||||
const script = readRepoFile("scripts/release/publish-npm.sh");
|
||||
const packages = readRepoFile("scripts/release/npm-packages.sh");
|
||||
|
||||
const loopStart = script.indexOf('for pkg in "${RUNTIME_PACKAGES[@]}"; do');
|
||||
const loopEnd = script.indexOf("\ndone", loopStart);
|
||||
expect(loopStart).toBeGreaterThanOrEqual(0);
|
||||
expect(loopEnd).toBeGreaterThan(loopStart);
|
||||
const runtimePublishLoop = script.slice(loopStart, loopEnd);
|
||||
|
||||
expect(runtimePublishLoop).toContain(
|
||||
'npm publish --access public --provenance --tag "$DIST_TAG"',
|
||||
);
|
||||
expect(script).toMatch(
|
||||
/if package_already_published "kandev"; then\s+record_already_published "kandev"/,
|
||||
const mainPublish = script.slice(script.indexOf("Publishing kandev@$VERSION"));
|
||||
expect(mainPublish).toContain('npm publish --access public --provenance --tag "$DIST_TAG"');
|
||||
expect(script).toContain("pkg.version = version;");
|
||||
expect(script).toContain('CLI_PACKAGE_BACKUP="$WORK_DIR/cli-package.json"');
|
||||
expect(script).toContain('cp "$CLI_PACKAGE_BACKUP" "$CLI_PACKAGE_JSON"');
|
||||
for (const packageName of [
|
||||
"@kdlbs/runtime-linux-x64",
|
||||
"@kdlbs/runtime-linux-arm64",
|
||||
"@kdlbs/runtime-darwin-x64",
|
||||
"@kdlbs/runtime-darwin-arm64",
|
||||
"@kdlbs/runtime-win32-x64",
|
||||
]) {
|
||||
expect(packages).toContain(`"${packageName}"`);
|
||||
}
|
||||
expect(packages).toContain('NIGHTLY_PACKAGES=("kandev" "${RUNTIME_PACKAGES[@]}")');
|
||||
expect(script).toContain('source "$ROOT_DIR/scripts/release/npm-packages.sh"');
|
||||
});
|
||||
|
||||
it("keeps every runtime package consumer aligned with the publishing inventory", () => {
|
||||
const inventory = runtimePackagesIn(readRepoFile("scripts/release/npm-packages.sh"));
|
||||
expect(inventory.length).toBeGreaterThan(0);
|
||||
|
||||
for (const path of [
|
||||
"apps/cli/src/runtime.ts",
|
||||
"apps/cli/bin/native-shim.js",
|
||||
"apps/cli/package.json",
|
||||
]) {
|
||||
expect(runtimePackagesIn(readRepoFile(path)), path).toEqual(inventory);
|
||||
}
|
||||
expect(readRepoFile("scripts/release/package-npm-runtime.sh")).toContain(
|
||||
'source "$ROOT_DIR/scripts/release/npm-packages.sh"',
|
||||
);
|
||||
expect(readRepoFile("scripts/release/publish-npm.test.mjs")).toContain("loadRuntimeInventory");
|
||||
});
|
||||
|
||||
it("only treats an existing nightly version as idempotent when the nightly tag matches", () => {
|
||||
const script = readRepoFile("scripts/release/publish-npm.sh");
|
||||
|
||||
expect(script).toContain('npm_view_version "${pkg}@${VERSION}"');
|
||||
expect(script).toContain('npm_view_version "${pkg}@${DIST_TAG}"');
|
||||
expect(script).toContain('if [[ "$DIST_TAG" == "nightly" ]]');
|
||||
expect(script).toContain('if [[ "$tagged_version" != "$VERSION" ]]');
|
||||
expect(script).toContain("refusing idempotent success");
|
||||
expect(script).toContain("EPUBLISHCONFLICT");
|
||||
expect(script).toContain("treated as idempotent success");
|
||||
});
|
||||
@@ -390,7 +457,9 @@ describe("release desktop artifacts", () => {
|
||||
expect(workflow).toContain("persist-credentials: false");
|
||||
expect(workflow).toContain("Desktop validation summary");
|
||||
expect(workflow).toContain("No release PR, tag, GitHub release, public container tags");
|
||||
expect(workflow).toContain("if: ${{ !inputs.dry_run && !inputs.desktop_validation_only }}");
|
||||
expect(workflow).toContain(
|
||||
"if: ${{ github.event_name == 'workflow_dispatch' && !inputs.dry_run && !inputs.desktop_validation_only }}",
|
||||
);
|
||||
expect(workflow).toContain('if [ "$DESKTOP_VALIDATION_ONLY" = "true" ]; then');
|
||||
expect(workflow).toContain("scripts/release/desktop-signing-ready.sh macos");
|
||||
expect(workflow).toContain("scripts/release/desktop-signing-ready.sh windows");
|
||||
|
||||
@@ -48,6 +48,17 @@ describe("planSelfUpdate", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("installs an exact npm nightly prerelease target", () => {
|
||||
const nightly = intent("npm");
|
||||
nightly.target_tag = "v0.82.1-nightly.shaabc123def456";
|
||||
nightly.target_version = "0.82.1-nightly.shaabc123def456";
|
||||
|
||||
expect(planSelfUpdate(nightly, { platform: "linux" })[0]).toEqual({
|
||||
command: "npm",
|
||||
args: ["install", "-g", "--prefix", "/usr", "kandev@0.82.1-nightly.shaabc123def456"],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps npm updates inside the original global prefix", () => {
|
||||
const npm = intent("npm");
|
||||
npm.install.cli_entry = "/tmp/kandev-test/npm-global/lib/node_modules/kandev/bin/cli.js";
|
||||
@@ -103,6 +114,26 @@ describe("planSelfUpdate", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("reinstalls an exact npx nightly prerelease target", () => {
|
||||
const nightly = intent("npx");
|
||||
nightly.target_tag = "v0.82.1-nightly.shaabc123def456";
|
||||
nightly.target_version = "0.82.1-nightly.shaabc123def456";
|
||||
|
||||
expect(planSelfUpdate(nightly, { platform: "linux" })[0]).toEqual({
|
||||
command: "npx",
|
||||
args: [
|
||||
"-y",
|
||||
"kandev@0.82.1-nightly.shaabc123def456",
|
||||
"service",
|
||||
"install",
|
||||
"--home-dir",
|
||||
"/home/alice/.kandev",
|
||||
"--port",
|
||||
"38429",
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("plans launchd restart on macOS", () => {
|
||||
const mac = intent("homebrew");
|
||||
mac.install.manager = "launchd";
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { useState } from "react";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
|
||||
import type { UpdatesChannel, UpdatesResponse } from "@/lib/types/system";
|
||||
import { SettingsSaveProvider, useSettingsSaveContributor } from "../settings-save-provider";
|
||||
import { useUpdateChannelDraft } from "./update-channel-control";
|
||||
|
||||
type Deferred = {
|
||||
promise: Promise<void>;
|
||||
resolve: () => void;
|
||||
};
|
||||
|
||||
function deferred(): Deferred {
|
||||
let resolve: () => void = () => undefined;
|
||||
const promise = new Promise<void>((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
function BlockingContributor({
|
||||
pending,
|
||||
onSaveStarted,
|
||||
}: {
|
||||
pending: Deferred;
|
||||
onSaveStarted: () => void;
|
||||
}) {
|
||||
const [isDirty, setIsDirty] = useState(true);
|
||||
useSettingsSaveContributor({
|
||||
id: "blocking-save",
|
||||
order: 0,
|
||||
revision: 1,
|
||||
isDirty,
|
||||
save: async () => {
|
||||
onSaveStarted();
|
||||
await pending.promise;
|
||||
setIsDirty(false);
|
||||
},
|
||||
discard: () => setIsDirty(false),
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
function ChannelDraft({
|
||||
saveChannel,
|
||||
}: {
|
||||
saveChannel: (channel: UpdatesChannel) => Promise<UpdatesResponse>;
|
||||
}) {
|
||||
const { draft, isDirty, setDraft } = useUpdateChannelDraft(
|
||||
{
|
||||
current: "v1.0.0",
|
||||
latest: "v1.0.1",
|
||||
latest_url: "https://example.test/v1.0.1",
|
||||
latest_checked_at: "2026-08-01T00:00:00Z",
|
||||
update_available: true,
|
||||
channel: "stable",
|
||||
channel_editable: true,
|
||||
channel_unsupported_reason: "",
|
||||
install: { running_as_service: true, managed_service: true },
|
||||
apply_supported: true,
|
||||
},
|
||||
saveChannel,
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<button type="button" onClick={() => setDraft("nightly")}>
|
||||
Nightly
|
||||
</button>
|
||||
<button type="button" onClick={() => setDraft("stable")}>
|
||||
Stable
|
||||
</button>
|
||||
<output data-testid="channel-draft" data-dirty={isDirty}>
|
||||
{draft}
|
||||
</output>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
it("preserves an edit made before its queued contributor starts saving", async () => {
|
||||
const pending = deferred();
|
||||
const onSaveStarted = vi.fn();
|
||||
const saveChannel = vi.fn().mockResolvedValue({
|
||||
channel: "nightly",
|
||||
} as UpdatesResponse);
|
||||
render(
|
||||
<SettingsSaveProvider>
|
||||
<BlockingContributor pending={pending} onSaveStarted={onSaveStarted} />
|
||||
<ChannelDraft saveChannel={saveChannel} />
|
||||
</SettingsSaveProvider>,
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Nightly" }));
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Save changes" }));
|
||||
await waitFor(() => expect(onSaveStarted).toHaveBeenCalledOnce());
|
||||
expect(saveChannel).not.toHaveBeenCalled();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Stable" }));
|
||||
await act(async () => pending.resolve());
|
||||
await waitFor(() => expect(saveChannel).toHaveBeenCalledWith("nightly"));
|
||||
|
||||
expect(screen.getByTestId("channel-draft").textContent).toBe("stable");
|
||||
expect(screen.getByTestId("channel-draft").getAttribute("data-dirty")).toBe("true");
|
||||
});
|
||||
@@ -0,0 +1,198 @@
|
||||
"use client";
|
||||
|
||||
import { useLayoutEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Label } from "@kandev/ui/label";
|
||||
import { RadioGroup, RadioGroupItem } from "@kandev/ui/radio-group";
|
||||
import type { UpdatesChannel, UpdatesResponse } from "@/lib/types/system";
|
||||
import { useSettingsSaveContributor } from "../settings-save-provider";
|
||||
import { updateChannelUnsupportedReasonKey } from "./update-channel-reasons";
|
||||
|
||||
export function useUpdateChannelDraft(
|
||||
updates: UpdatesResponse | null | undefined,
|
||||
saveChannel: (channel: UpdatesChannel) => Promise<UpdatesResponse>,
|
||||
) {
|
||||
const authoritative = updates?.channel ?? "stable";
|
||||
const editable = updates?.channel_editable === true;
|
||||
const [saved, setSaved] = useState<UpdatesChannel>(authoritative);
|
||||
const savedRef = useRef(saved);
|
||||
const [draft, setDraftState] = useState<UpdatesChannel>(authoritative);
|
||||
const draftRef = useRef(draft);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
// A newer edit can circle back to the old saved value, so value equality
|
||||
// alone cannot decide whether an in-flight save response may rebase it.
|
||||
const draftRevisionRef = useRef(0);
|
||||
const pendingSaveRevisionRef = useRef<number | null>(null);
|
||||
draftRef.current = draft;
|
||||
const isDirty = editable && draft !== saved;
|
||||
|
||||
const setDraft = (channel: UpdatesChannel) => {
|
||||
draftRevisionRef.current += 1;
|
||||
draftRef.current = channel;
|
||||
setDraftState(channel);
|
||||
};
|
||||
|
||||
// The settings coordinator snapshots this contributor before it begins
|
||||
// saving earlier contributors. Capture the edit token in that snapshot; the
|
||||
// matching save callback closes over this render's draft value.
|
||||
const contributorRevision = draftRevisionRef.current;
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const previous = savedRef.current;
|
||||
savedRef.current = authoritative;
|
||||
setSaved(authoritative);
|
||||
const pendingRevision = pendingSaveRevisionRef.current;
|
||||
const hasNewerDraft = pendingRevision !== null && draftRevisionRef.current !== pendingRevision;
|
||||
if (!editable || (draftRef.current === previous && !hasNewerDraft)) {
|
||||
draftRef.current = authoritative;
|
||||
setDraftState(authoritative);
|
||||
}
|
||||
}, [authoritative, editable]);
|
||||
|
||||
useSettingsSaveContributor({
|
||||
id: "system-updates-channel",
|
||||
order: 10,
|
||||
revision: contributorRevision,
|
||||
// Keep the navigation guard active for the full save. A user can edit the
|
||||
// draft back to the previously saved value while the submitted channel is
|
||||
// still in flight, but leaving then would abandon an unresolved mutation.
|
||||
isDirty: isDirty || isSaving,
|
||||
save: async (revision) => {
|
||||
const submitted = draft;
|
||||
const submittedRevision = revision as number;
|
||||
pendingSaveRevisionRef.current = submittedRevision;
|
||||
setIsSaving(true);
|
||||
try {
|
||||
const response = await saveChannel(submitted);
|
||||
savedRef.current = response.channel;
|
||||
setSaved(response.channel);
|
||||
if (draftRevisionRef.current === submittedRevision) {
|
||||
draftRef.current = response.channel;
|
||||
setDraftState(response.channel);
|
||||
}
|
||||
} finally {
|
||||
if (pendingSaveRevisionRef.current === submittedRevision) {
|
||||
pendingSaveRevisionRef.current = null;
|
||||
}
|
||||
setIsSaving(false);
|
||||
}
|
||||
},
|
||||
discard: () => setDraft(savedRef.current),
|
||||
});
|
||||
|
||||
return {
|
||||
draft,
|
||||
editable,
|
||||
isDirty,
|
||||
isSaving,
|
||||
unsupportedReason: updates?.channel_unsupported_reason ?? "",
|
||||
setDraft,
|
||||
};
|
||||
}
|
||||
|
||||
type UpdateChannelControlProps = ReturnType<typeof useUpdateChannelDraft>;
|
||||
|
||||
export function UpdateChannelControl({
|
||||
draft,
|
||||
editable,
|
||||
isDirty,
|
||||
unsupportedReason,
|
||||
setDraft,
|
||||
}: UpdateChannelControlProps) {
|
||||
const { t } = useTranslation();
|
||||
const reasonId = "system-updates-channel-reason";
|
||||
const reason = unsupportedReason ? t(updateChannelUnsupportedReasonKey(unsupportedReason)) : "";
|
||||
return (
|
||||
<div
|
||||
className="min-w-0 space-y-2"
|
||||
data-testid="system-updates-channel"
|
||||
data-settings-dirty={isDirty}
|
||||
>
|
||||
<div>
|
||||
<div className="text-sm font-medium">{t("settings:updateChannel")}</div>
|
||||
<p className="text-xs text-muted-foreground">{t("settings:updateChannelDescription")}</p>
|
||||
</div>
|
||||
<RadioGroup
|
||||
aria-label={t("settings:updateChannel")}
|
||||
value={draft}
|
||||
onValueChange={(value) => {
|
||||
if (editable && (value === "stable" || value === "nightly")) setDraft(value);
|
||||
}}
|
||||
className="gap-2"
|
||||
data-settings-dirty={isDirty}
|
||||
>
|
||||
<UpdateChannelOption
|
||||
channel="stable"
|
||||
label={t("settings:updateChannelStable")}
|
||||
description={t("settings:updateChannelStableDescription")}
|
||||
disabled={!editable}
|
||||
reasonId={!editable && reason ? reasonId : undefined}
|
||||
/>
|
||||
<UpdateChannelOption
|
||||
channel="nightly"
|
||||
label={t("settings:updateChannelNightly")}
|
||||
description={t("settings:updateChannelNightlyDescription")}
|
||||
disabled={!editable}
|
||||
reasonId={!editable && reason ? reasonId : undefined}
|
||||
/>
|
||||
</RadioGroup>
|
||||
{!editable && reason && (
|
||||
<p
|
||||
id={reasonId}
|
||||
className="break-words text-xs text-muted-foreground"
|
||||
data-testid="system-updates-channel-reason"
|
||||
>
|
||||
{reason}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function UpdateChannelOption({
|
||||
channel,
|
||||
label,
|
||||
description,
|
||||
disabled,
|
||||
reasonId,
|
||||
}: {
|
||||
channel: UpdatesChannel;
|
||||
label: string;
|
||||
description: string;
|
||||
disabled: boolean;
|
||||
reasonId?: string;
|
||||
}) {
|
||||
const inputId = `system-updates-channel-${channel}-input`;
|
||||
const labelId = `system-updates-channel-${channel}-label`;
|
||||
const descriptionId = `system-updates-channel-${channel}-description`;
|
||||
const describedBy = reasonId ? `${descriptionId} ${reasonId}` : descriptionId;
|
||||
return (
|
||||
<Label
|
||||
htmlFor={inputId}
|
||||
className={`flex min-h-11 w-full min-w-0 items-start gap-3 rounded-md border p-3 ${
|
||||
disabled ? "cursor-not-allowed opacity-60" : "cursor-pointer hover:bg-muted/30"
|
||||
}`}
|
||||
data-testid={`system-updates-channel-${channel}`}
|
||||
>
|
||||
<RadioGroupItem
|
||||
id={inputId}
|
||||
value={channel}
|
||||
disabled={disabled}
|
||||
aria-labelledby={labelId}
|
||||
aria-describedby={describedBy}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<span className="min-w-0 space-y-1">
|
||||
<span id={labelId} className="block text-sm font-medium">
|
||||
{label}
|
||||
</span>
|
||||
<span
|
||||
id={descriptionId}
|
||||
className="block whitespace-normal break-words text-xs text-muted-foreground"
|
||||
>
|
||||
{description}
|
||||
</span>
|
||||
</span>
|
||||
</Label>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { cleanup, render, screen } from "@testing-library/react";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { activateLocale } from "@/lib/i18n";
|
||||
import { UpdateChannelControl } from "./update-channel-control";
|
||||
|
||||
describe("UpdateChannelControl reasons under the pseudo-locale", () => {
|
||||
beforeAll(async () => activateLocale("pseudo"));
|
||||
afterAll(async () => activateLocale("en"));
|
||||
afterEach(cleanup);
|
||||
|
||||
it.each([
|
||||
"Nightly updates require a Kandev-managed npm or npx user service.",
|
||||
"Nightly updates require valid Kandev service metadata.",
|
||||
"Nightly updates are only available for user services.",
|
||||
"This service manager does not support nightly updates.",
|
||||
"Nightly updates are only available for npm or npx installations.",
|
||||
"Update channel settings are unavailable.",
|
||||
"An unknown server capability reason.",
|
||||
])("localizes the server reason: %s", (unsupportedReason) => {
|
||||
render(
|
||||
<UpdateChannelControl
|
||||
draft="stable"
|
||||
editable={false}
|
||||
isDirty={false}
|
||||
isSaving={false}
|
||||
unsupportedReason={unsupportedReason}
|
||||
setDraft={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
const reason = screen.getByTestId("system-updates-channel-reason").textContent ?? "";
|
||||
expect(reason).not.toContain(unsupportedReason);
|
||||
expect(reason).toMatch(/[À-ɏ]/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
const FALLBACK_REASON_KEY = "settings:updateChannelUnavailable";
|
||||
|
||||
const REASON_KEYS: Readonly<Record<string, string>> = {
|
||||
"Nightly updates require a Kandev-managed npm or npx user service.":
|
||||
"settings:updateChannelRequiresManagedService",
|
||||
"Nightly updates require valid Kandev service metadata.":
|
||||
"settings:updateChannelRequiresServiceMetadata",
|
||||
"Nightly updates are only available for user services.":
|
||||
"settings:updateChannelRequiresUserService",
|
||||
"This service manager does not support nightly updates.":
|
||||
"settings:updateChannelUnsupportedServiceManager",
|
||||
"Nightly updates are only available for npm or npx installations.":
|
||||
"settings:updateChannelRequiresNpmInstallation",
|
||||
"Update channel settings are unavailable.": "settings:updateChannelSettingsUnavailable",
|
||||
};
|
||||
|
||||
export function updateChannelUnsupportedReasonKey(reason: string): string {
|
||||
return REASON_KEYS[reason] ?? FALLBACK_REASON_KEY;
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import type { ComponentProps } from "react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { UpdatesResponse } from "@/lib/types/system";
|
||||
import type { SelfUpdateController } from "@/hooks/domains/system/use-self-update";
|
||||
import type { DesktopUpdaterController } from "@/hooks/domains/system/use-desktop-updater";
|
||||
import { requestNavigation } from "@/lib/routing/navigation-guard";
|
||||
import { SettingsSaveProvider } from "../settings-save-provider";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useUpdates: vi.fn(),
|
||||
@@ -32,6 +35,13 @@ vi.mock("@kandev/ui/spinner", () => ({
|
||||
import { UpdatesCard } from "./updates-card";
|
||||
|
||||
const APPLY_TESTID = "system-updates-apply";
|
||||
const ARIA_CHECKED = "aria-checked";
|
||||
const CHECK_TESTID = "system-updates-check";
|
||||
const CHANNEL_TESTID = "system-updates-channel";
|
||||
const ERROR_TESTID = "system-updates-error";
|
||||
const LATEST_TESTID = "system-updates-latest";
|
||||
const SETTINGS_DIRTY_ATTRIBUTE = "data-settings-dirty";
|
||||
const SAVE_CHANGES_NAME = "Save changes";
|
||||
|
||||
function updates(overrides: Partial<UpdatesResponse> = {}): UpdatesResponse {
|
||||
return {
|
||||
@@ -40,6 +50,9 @@ function updates(overrides: Partial<UpdatesResponse> = {}): UpdatesResponse {
|
||||
latest_url: "https://example/v1.0.1",
|
||||
latest_checked_at: "2026-05-29T00:00:00.000Z",
|
||||
update_available: true,
|
||||
channel: "stable",
|
||||
channel_editable: true,
|
||||
channel_unsupported_reason: "",
|
||||
install: {
|
||||
running_as_service: true,
|
||||
managed_service: true,
|
||||
@@ -52,6 +65,18 @@ function updates(overrides: Partial<UpdatesResponse> = {}): UpdatesResponse {
|
||||
};
|
||||
}
|
||||
|
||||
function updatesCard(props: ComponentProps<typeof UpdatesCard> = {}) {
|
||||
return (
|
||||
<SettingsSaveProvider>
|
||||
<UpdatesCard {...props} />
|
||||
</SettingsSaveProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function renderUpdatesCard(props: ComponentProps<typeof UpdatesCard> = {}) {
|
||||
return render(updatesCard(props));
|
||||
}
|
||||
|
||||
function selfUpdate(overrides: Partial<SelfUpdateController> = {}): SelfUpdateController {
|
||||
return {
|
||||
phase: "idle",
|
||||
@@ -92,6 +117,21 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("UpdatesCard self-update", () => {
|
||||
it("uses hook-owned checking state to hide Apply update", () => {
|
||||
mocks.useUpdates.mockReturnValue({
|
||||
updates: updates(),
|
||||
check: vi.fn(),
|
||||
reload: vi.fn(),
|
||||
saveChannel: vi.fn(),
|
||||
isChecking: true,
|
||||
error: null,
|
||||
});
|
||||
|
||||
renderUpdatesCard();
|
||||
expect(screen.queryByTestId(APPLY_TESTID)).toBeNull();
|
||||
expect(screen.getByTestId(CHECK_TESTID).hasAttribute("disabled")).toBe(true);
|
||||
});
|
||||
|
||||
it("passes a stable document reload instead of the update-metadata refetch", () => {
|
||||
const reloadDocument = vi.fn();
|
||||
const reloadMetadataFirst = vi.fn();
|
||||
@@ -108,10 +148,10 @@ describe("UpdatesCard self-update", () => {
|
||||
reload: reloadMetadataSecond,
|
||||
});
|
||||
|
||||
const { rerender } = render(<UpdatesCard reloadDocument={reloadDocument} />);
|
||||
const { rerender } = renderUpdatesCard({ reloadDocument });
|
||||
const firstCompletion = mocks.useSelfUpdate.mock.calls.at(-1)?.[0]?.onComplete;
|
||||
|
||||
rerender(<UpdatesCard reloadDocument={reloadDocument} />);
|
||||
rerender(updatesCard({ reloadDocument }));
|
||||
const secondCompletion = mocks.useSelfUpdate.mock.calls.at(-1)?.[0]?.onComplete;
|
||||
|
||||
expect(firstCompletion).toBe(reloadDocument);
|
||||
@@ -134,7 +174,7 @@ describe("UpdatesCard self-update", () => {
|
||||
reload: vi.fn(),
|
||||
});
|
||||
|
||||
render(<UpdatesCard />);
|
||||
renderUpdatesCard();
|
||||
|
||||
expect(screen.queryByTestId(APPLY_TESTID)).toBeNull();
|
||||
expect(screen.getByTestId("system-updates-manual").textContent).toContain(
|
||||
@@ -147,7 +187,7 @@ describe("UpdatesCard self-update", () => {
|
||||
mocks.useUpdates.mockReturnValue({ updates: updates(), check: vi.fn(), reload: vi.fn() });
|
||||
mocks.useSelfUpdate.mockReturnValue(selfUpdate({ start }));
|
||||
|
||||
render(<UpdatesCard />);
|
||||
renderUpdatesCard();
|
||||
fireEvent.click(screen.getByTestId(APPLY_TESTID));
|
||||
fireEvent.click(await screen.findByTestId("system-updates-apply-confirm"));
|
||||
|
||||
@@ -160,7 +200,7 @@ describe("UpdatesCard self-update", () => {
|
||||
selfUpdate({ phase: "restarting", targetVersion: "v1.0.1", isUpdating: true }),
|
||||
);
|
||||
|
||||
render(<UpdatesCard />);
|
||||
renderUpdatesCard();
|
||||
|
||||
expect(screen.queryByTestId(APPLY_TESTID)).toBeNull();
|
||||
const progress = screen.getByTestId("system-updates-progress");
|
||||
@@ -174,7 +214,7 @@ describe("UpdatesCard self-update", () => {
|
||||
selfUpdate({ phase: "done", targetVersion: "v1.0.1", isUpdating: false }),
|
||||
);
|
||||
|
||||
render(<UpdatesCard />);
|
||||
renderUpdatesCard();
|
||||
|
||||
expect(screen.queryByTestId(APPLY_TESTID)).toBeNull();
|
||||
expect(screen.getByTestId("system-updates-progress").textContent).toContain(
|
||||
@@ -206,9 +246,9 @@ describe("UpdatesCard desktop package updates", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
render(<UpdatesCard />);
|
||||
renderUpdatesCard();
|
||||
|
||||
expect(screen.getByTestId("system-updates-latest").textContent).toBe("1.1.0");
|
||||
expect(screen.getByTestId(LATEST_TESTID).textContent).toBe("1.1.0");
|
||||
expect(screen.queryByTestId(APPLY_TESTID)).toBeNull();
|
||||
expect(screen.getByTestId("system-updates-manual").textContent).toContain("package manager");
|
||||
});
|
||||
@@ -240,10 +280,10 @@ describe("UpdatesCard desktop updater", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
render(<UpdatesCard />);
|
||||
renderUpdatesCard();
|
||||
|
||||
expect(screen.getByTestId("system-updates-current").textContent).toBe("1.0.0");
|
||||
expect(screen.getByTestId("system-updates-latest").textContent).toBe("1.1.0");
|
||||
expect(screen.getByTestId(LATEST_TESTID).textContent).toBe("1.1.0");
|
||||
expect(screen.getByTestId(APPLY_TESTID)).toBeTruthy();
|
||||
expect(screen.queryByTestId("system-updates-manual")).toBeNull();
|
||||
expect(screen.getByTestId("system-updates-actions").className).toContain("flex-col");
|
||||
@@ -272,7 +312,7 @@ describe("UpdatesCard desktop updater", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
render(<UpdatesCard />);
|
||||
renderUpdatesCard();
|
||||
fireEvent.click(screen.getByTestId(APPLY_TESTID));
|
||||
expect(install).not.toHaveBeenCalled();
|
||||
fireEvent.click(await screen.findByTestId("system-updates-apply-confirm"));
|
||||
@@ -303,12 +343,339 @@ describe("UpdatesCard desktop updater", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
render(<UpdatesCard />);
|
||||
renderUpdatesCard();
|
||||
|
||||
expect(screen.getByTestId("system-updates-progress").textContent).toContain("25 of 100 bytes");
|
||||
expect(screen.getByTestId("system-updates-error").textContent).toContain(
|
||||
"Signature verification failed",
|
||||
);
|
||||
expect(screen.getByTestId(ERROR_TESTID).textContent).toContain("Signature verification failed");
|
||||
expect(screen.queryByTestId(APPLY_TESTID)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("UpdatesCard channel setting", () => {
|
||||
it("keeps Nightly local until the shared settings action saves it", async () => {
|
||||
const saveChannel = vi.fn().mockResolvedValue(
|
||||
updates({
|
||||
channel: "nightly",
|
||||
latest: "1.0.1-nightly.shaabcdef123456",
|
||||
latest_url: "https://www.npmjs.com/package/kandev/v/1.0.1-nightly.shaabcdef123456",
|
||||
}),
|
||||
);
|
||||
mocks.useUpdates.mockReturnValue({
|
||||
updates: updates(),
|
||||
check: vi.fn(),
|
||||
reload: vi.fn(),
|
||||
saveChannel,
|
||||
error: null,
|
||||
});
|
||||
|
||||
renderUpdatesCard();
|
||||
const stable = screen.getByRole("radio", { name: /^Stable/ });
|
||||
const nightly = screen.getByRole("radio", { name: /^Nightly/ });
|
||||
|
||||
expect(stable.getAttribute(ARIA_CHECKED)).toBe("true");
|
||||
expect(nightly.getAttribute(ARIA_CHECKED)).toBe("false");
|
||||
fireEvent.click(nightly);
|
||||
|
||||
expect(nightly.getAttribute(ARIA_CHECKED)).toBe("true");
|
||||
expect(saveChannel).not.toHaveBeenCalled();
|
||||
expect(screen.getByTestId(CHANNEL_TESTID).getAttribute(SETTINGS_DIRTY_ATTRIBUTE)).toBe("true");
|
||||
expect(screen.getByTestId(LATEST_TESTID).textContent).toBe("-");
|
||||
expect(screen.getByTestId("system-updates-checked-at").textContent).toBe("Last checked never");
|
||||
expect(screen.getByTestId("system-updates-channel-nightly").textContent).toContain(
|
||||
"Install-wide",
|
||||
);
|
||||
expect(screen.getByTestId("system-updates-channel-nightly").textContent).toContain(
|
||||
"exact version shown",
|
||||
);
|
||||
expect(screen.getByTestId(CHECK_TESTID).hasAttribute("disabled")).toBe(true);
|
||||
expect(screen.queryByTestId(APPLY_TESTID)).toBeNull();
|
||||
expect(screen.queryByTestId("system-updates-release-link")).toBeNull();
|
||||
expect(screen.getByTestId("system-updates-channel-pending").textContent).toContain(
|
||||
"Save channel changes",
|
||||
);
|
||||
|
||||
fireEvent.click(await screen.findByRole("button", { name: SAVE_CHANGES_NAME }));
|
||||
|
||||
await waitFor(() => expect(saveChannel).toHaveBeenCalledWith("nightly"));
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId(CHANNEL_TESTID).getAttribute(SETTINGS_DIRTY_ATTRIBUTE)).toBe(
|
||||
"false",
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("UpdatesCard channel save errors", () => {
|
||||
it("clears a previous check error after a channel save succeeds", async () => {
|
||||
let updatesError: string | null = null;
|
||||
const check = vi.fn(async () => {
|
||||
updatesError = "npm registry unavailable";
|
||||
throw new Error(updatesError);
|
||||
});
|
||||
const saveChannel = vi.fn(async () => {
|
||||
updatesError = null;
|
||||
return updates({ channel: "nightly" });
|
||||
});
|
||||
mocks.useUpdates.mockImplementation(() => ({
|
||||
updates: updates(),
|
||||
check,
|
||||
reload: vi.fn(),
|
||||
saveChannel,
|
||||
isChecking: false,
|
||||
error: updatesError,
|
||||
}));
|
||||
|
||||
const { rerender } = renderUpdatesCard();
|
||||
fireEvent.click(screen.getByTestId(CHECK_TESTID));
|
||||
await waitFor(() => expect(check).toHaveBeenCalledOnce());
|
||||
rerender(updatesCard());
|
||||
expect(screen.getByTestId(ERROR_TESTID).textContent).toContain("npm registry unavailable");
|
||||
|
||||
fireEvent.click(screen.getByRole("radio", { name: /^Nightly/ }));
|
||||
fireEvent.click(await screen.findByRole("button", { name: SAVE_CHANGES_NAME }));
|
||||
|
||||
await waitFor(() => expect(saveChannel).toHaveBeenCalledWith("nightly"));
|
||||
rerender(updatesCard());
|
||||
expect(screen.queryByTestId(ERROR_TESTID)).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps a failed channel save dirty and retryable", async () => {
|
||||
const saveChannel = vi
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new Error("npm registry unavailable"))
|
||||
.mockResolvedValueOnce(updates({ channel: "nightly" }));
|
||||
mocks.useUpdates.mockReturnValue({
|
||||
updates: updates(),
|
||||
check: vi.fn(),
|
||||
reload: vi.fn(),
|
||||
saveChannel,
|
||||
error: null,
|
||||
});
|
||||
|
||||
renderUpdatesCard();
|
||||
const nightly = screen.getByRole("radio", { name: /^Nightly/ });
|
||||
fireEvent.click(nightly);
|
||||
fireEvent.click(await screen.findByRole("button", { name: SAVE_CHANGES_NAME }));
|
||||
|
||||
await waitFor(() => expect(screen.getByText("Couldn't save")).toBeTruthy());
|
||||
expect(nightly.getAttribute(ARIA_CHECKED)).toBe("true");
|
||||
expect(screen.getByTestId(CHANNEL_TESTID).getAttribute(SETTINGS_DIRTY_ATTRIBUTE)).toBe("true");
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Retry save" }));
|
||||
|
||||
await waitFor(() => expect(saveChannel).toHaveBeenCalledTimes(2));
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId(CHANNEL_TESTID).getAttribute(SETTINGS_DIRTY_ATTRIBUTE)).toBe(
|
||||
"false",
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it("replaces a previous check error with the channel save failure", async () => {
|
||||
let updatesError: string | null = null;
|
||||
const check = vi.fn(async () => {
|
||||
updatesError = "retry after 27 seconds";
|
||||
throw new Error(updatesError);
|
||||
});
|
||||
const saveChannel = vi.fn(async () => {
|
||||
updatesError = "channel save failed";
|
||||
throw new Error(updatesError);
|
||||
});
|
||||
mocks.useUpdates.mockImplementation(() => ({
|
||||
updates: updates(),
|
||||
check,
|
||||
reload: vi.fn(),
|
||||
saveChannel,
|
||||
isChecking: false,
|
||||
error: updatesError,
|
||||
}));
|
||||
|
||||
const { rerender } = renderUpdatesCard();
|
||||
fireEvent.click(screen.getByTestId(CHECK_TESTID));
|
||||
await waitFor(() => expect(check).toHaveBeenCalledOnce());
|
||||
rerender(updatesCard());
|
||||
expect(screen.getByTestId(ERROR_TESTID).textContent).toContain("27s");
|
||||
|
||||
fireEvent.click(screen.getByRole("radio", { name: /^Nightly/ }));
|
||||
fireEvent.click(await screen.findByRole("button", { name: SAVE_CHANGES_NAME }));
|
||||
|
||||
await waitFor(() => expect(screen.getByText("Couldn't save")).toBeTruthy());
|
||||
expect(screen.getByTestId(ERROR_TESTID).textContent).toContain("channel save failed");
|
||||
expect(screen.getByTestId(ERROR_TESTID).textContent).not.toContain("27s");
|
||||
});
|
||||
});
|
||||
|
||||
describe("UpdatesCard concurrent channel edits", () => {
|
||||
it("keeps update actions blocked when the draft reverts during a save", async () => {
|
||||
let resolveSave!: (value: UpdatesResponse) => void;
|
||||
const saveChannel = vi.fn(
|
||||
() =>
|
||||
new Promise<UpdatesResponse>((resolve) => {
|
||||
resolveSave = resolve;
|
||||
}),
|
||||
);
|
||||
mocks.useUpdates.mockReturnValue({
|
||||
updates: updates(),
|
||||
check: vi.fn(),
|
||||
reload: vi.fn(),
|
||||
saveChannel,
|
||||
error: null,
|
||||
});
|
||||
|
||||
renderUpdatesCard();
|
||||
const stable = screen.getByRole("radio", { name: /^Stable/ });
|
||||
fireEvent.click(screen.getByRole("radio", { name: /^Nightly/ }));
|
||||
fireEvent.click(await screen.findByRole("button", { name: SAVE_CHANGES_NAME }));
|
||||
await waitFor(() => expect(saveChannel).toHaveBeenCalledWith("nightly"));
|
||||
|
||||
fireEvent.click(stable);
|
||||
|
||||
expect(screen.getByTestId(CHANNEL_TESTID).getAttribute(SETTINGS_DIRTY_ATTRIBUTE)).toBe("false");
|
||||
expect(screen.getByTestId("system-updates-card").getAttribute(SETTINGS_DIRTY_ATTRIBUTE)).toBe(
|
||||
"true",
|
||||
);
|
||||
expect(screen.getByTestId(CHECK_TESTID).hasAttribute("disabled")).toBe(true);
|
||||
expect(screen.queryByTestId(APPLY_TESTID)).toBeNull();
|
||||
expect(screen.getByTestId("system-updates-channel-pending").textContent).toContain("Saving");
|
||||
|
||||
const proceed = vi.fn();
|
||||
act(() => requestNavigation(proceed));
|
||||
expect(proceed).not.toHaveBeenCalled();
|
||||
expect(await screen.findByRole("alertdialog")).toBeTruthy();
|
||||
expect(screen.getByRole("button", { name: "Discard and leave" }).hasAttribute("disabled")).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
resolveSave(updates({ channel: "nightly" }));
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId(CHANNEL_TESTID).getAttribute(SETTINGS_DIRTY_ATTRIBUTE)).toBe(
|
||||
"true",
|
||||
),
|
||||
);
|
||||
expect(proceed).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Continue editing" }));
|
||||
});
|
||||
|
||||
it("preserves a newer channel choice while an earlier save is pending", async () => {
|
||||
let resolveSave!: (value: UpdatesResponse) => void;
|
||||
const saveChannel = vi.fn(
|
||||
() =>
|
||||
new Promise<UpdatesResponse>((resolve) => {
|
||||
resolveSave = resolve;
|
||||
}),
|
||||
);
|
||||
let authoritative = updates();
|
||||
mocks.useUpdates.mockImplementation(() => ({
|
||||
updates: authoritative,
|
||||
check: vi.fn(),
|
||||
reload: vi.fn(),
|
||||
saveChannel,
|
||||
error: null,
|
||||
}));
|
||||
|
||||
const { rerender } = renderUpdatesCard();
|
||||
const stable = screen.getByRole("radio", { name: /^Stable/ });
|
||||
const nightly = screen.getByRole("radio", { name: /^Nightly/ });
|
||||
fireEvent.click(nightly);
|
||||
fireEvent.click(await screen.findByRole("button", { name: SAVE_CHANGES_NAME }));
|
||||
await waitFor(() => expect(saveChannel).toHaveBeenCalledWith("nightly"));
|
||||
|
||||
fireEvent.click(stable);
|
||||
authoritative = updates({ channel: "nightly" });
|
||||
rerender(updatesCard());
|
||||
expect(stable.getAttribute(ARIA_CHECKED)).toBe("true");
|
||||
|
||||
await act(async () => {
|
||||
resolveSave(authoritative);
|
||||
});
|
||||
|
||||
expect(stable.getAttribute(ARIA_CHECKED)).toBe("true");
|
||||
expect(screen.getByTestId(CHANNEL_TESTID).getAttribute(SETTINGS_DIRTY_ATTRIBUTE)).toBe("true");
|
||||
});
|
||||
});
|
||||
|
||||
describe("UpdatesCard channel navigation", () => {
|
||||
it("discards an unsaved Nightly choice through the shared navigation guard", async () => {
|
||||
const saveChannel = vi.fn();
|
||||
const proceed = vi.fn();
|
||||
mocks.useUpdates.mockReturnValue({
|
||||
updates: updates(),
|
||||
check: vi.fn(),
|
||||
reload: vi.fn(),
|
||||
saveChannel,
|
||||
error: null,
|
||||
});
|
||||
|
||||
renderUpdatesCard();
|
||||
const stable = screen.getByRole("radio", { name: /^Stable/ });
|
||||
const nightly = screen.getByRole("radio", { name: /^Nightly/ });
|
||||
fireEvent.click(nightly);
|
||||
await screen.findByRole("button", { name: SAVE_CHANGES_NAME });
|
||||
|
||||
act(() => requestNavigation(proceed));
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Discard and leave" }));
|
||||
|
||||
await waitFor(() => expect(stable.getAttribute(ARIA_CHECKED)).toBe("true"));
|
||||
expect(saveChannel).not.toHaveBeenCalled();
|
||||
expect(proceed).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
describe("UpdatesCard channel availability", () => {
|
||||
it("disables Nightly and renders the server capability reason", () => {
|
||||
mocks.useUpdates.mockReturnValue({
|
||||
updates: updates({
|
||||
channel_editable: false,
|
||||
channel_unsupported_reason:
|
||||
"Nightly updates require a Kandev-managed npm or npx user service.",
|
||||
}),
|
||||
check: vi.fn(),
|
||||
reload: vi.fn(),
|
||||
saveChannel: vi.fn(),
|
||||
error: null,
|
||||
});
|
||||
|
||||
renderUpdatesCard();
|
||||
|
||||
const stable = screen.getByRole("radio", { name: /^Stable/ });
|
||||
const nightly = screen.getByRole("radio", { name: /^Nightly/ });
|
||||
const reasonId = screen.getByTestId("system-updates-channel-reason").id;
|
||||
expect(stable.getAttribute(ARIA_CHECKED)).toBe("true");
|
||||
expect(stable.hasAttribute("disabled")).toBe(true);
|
||||
expect(nightly.hasAttribute("disabled")).toBe(true);
|
||||
expect(stable.getAttribute("aria-describedby")).toContain(reasonId);
|
||||
expect(nightly.getAttribute("aria-describedby")).toContain(reasonId);
|
||||
expect(screen.getByTestId("system-updates-channel-reason").textContent).toContain(
|
||||
"Kandev-managed npm or npx user service",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not expose an npm channel selector in the Desktop updater", () => {
|
||||
mocks.useDesktopUpdater.mockReturnValue(
|
||||
desktopUpdater({
|
||||
available: true,
|
||||
state: {
|
||||
phase: "up-to-date",
|
||||
currentVersion: "1.0.0",
|
||||
latestVersion: "1.0.0",
|
||||
releaseNotes: null,
|
||||
releaseUrl: null,
|
||||
checkedAtEpochMs: 42,
|
||||
downloadedBytes: null,
|
||||
totalBytes: null,
|
||||
installSupported: true,
|
||||
installUnsupportedReason: null,
|
||||
error: null,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
renderUpdatesCard();
|
||||
|
||||
expect(screen.queryByTestId(CHANNEL_TESTID)).toBeNull();
|
||||
expect(mocks.useUpdates).not.toHaveBeenCalled();
|
||||
expect(mocks.useSelfUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import type { TFunction } from "i18next";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
@@ -27,7 +26,9 @@ import {
|
||||
import { useUpdates } from "@/hooks/domains/system/use-updates";
|
||||
import { formatDateTime } from "@/lib/i18n/formats";
|
||||
import type { UpdatesResponse } from "@/lib/types/system";
|
||||
import { SettingsCard } from "../settings-card";
|
||||
import { SelfUpdateProgress } from "./self-update-progress";
|
||||
import { UpdateChannelControl, useUpdateChannelDraft } from "./update-channel-control";
|
||||
|
||||
interface ApplyGate {
|
||||
canApply: boolean;
|
||||
@@ -50,10 +51,6 @@ function formatChecked(value: string | number | null | undefined, t: TFunction):
|
||||
return formatDateTime(d);
|
||||
}
|
||||
|
||||
function errorMessage(err: unknown, fallback: string): string {
|
||||
return err instanceof Error ? err.message : fallback;
|
||||
}
|
||||
|
||||
function retryAfterSeconds(message: string): number | null {
|
||||
const match = /retry.*?(\d+)/i.exec(message);
|
||||
return match ? Number(match[1]) : null;
|
||||
@@ -91,54 +88,61 @@ function serviceCardView(
|
||||
};
|
||||
}
|
||||
|
||||
export function UpdatesCard({ reloadDocument = reloadCurrentDocument }: UpdatesCardProps = {}) {
|
||||
function ChannelPendingNotice({ pending, saving }: { pending: boolean; saving: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const { updates, check } = useUpdates();
|
||||
const selfUpdate = useSelfUpdate({ latestVersion: updates?.latest, onComplete: reloadDocument });
|
||||
const desktopUpdater = useDesktopUpdater();
|
||||
const [checking, setChecking] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [retryAfter, setRetryAfter] = useState<number | null>(null);
|
||||
if (!pending) return null;
|
||||
return (
|
||||
<p className="text-xs text-muted-foreground" data-testid="system-updates-channel-pending">
|
||||
{saving ? t("settings:updateChannelSavingNotice") : t("settings:updateChannelUnsavedNotice")}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
export function UpdatesCard({ reloadDocument = reloadCurrentDocument }: UpdatesCardProps = {}) {
|
||||
const desktopUpdater = useDesktopUpdater();
|
||||
if (desktopUpdater.available) {
|
||||
return <DesktopUpdatesCard updater={desktopUpdater} />;
|
||||
}
|
||||
return <ServiceUpdatesCard reloadDocument={reloadDocument} />;
|
||||
}
|
||||
|
||||
const onCheck = async () => {
|
||||
setChecking(true);
|
||||
setError(null);
|
||||
setRetryAfter(null);
|
||||
try {
|
||||
await check();
|
||||
} catch (err) {
|
||||
const message = errorMessage(err, t("system:updatesCheckFailed"));
|
||||
setError(message);
|
||||
setRetryAfter(retryAfterSeconds(message));
|
||||
} finally {
|
||||
setChecking(false);
|
||||
}
|
||||
};
|
||||
|
||||
function ServiceUpdatesCard({ reloadDocument }: { reloadDocument: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const { updates, check, saveChannel, isChecking, error } = useUpdates();
|
||||
const selfUpdate = useSelfUpdate({ latestVersion: updates?.latest, onComplete: reloadDocument });
|
||||
const channel = useUpdateChannelDraft(updates, saveChannel);
|
||||
const view = serviceCardView(updates, selfUpdate);
|
||||
const channelPending = channel.isDirty || channel.isSaving;
|
||||
|
||||
return (
|
||||
<Card data-testid="system-updates-card">
|
||||
<SettingsCard isDirty={channelPending} data-testid="system-updates-card">
|
||||
<CardHeader>
|
||||
<UpdatesHeader available={view.available} />
|
||||
<UpdatesHeader available={view.available && !channelPending} />
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<VersionGrid current={view.current} latest={view.latest} />
|
||||
<LastChecked checkedAt={updates?.latest_checked_at} />
|
||||
<UpdateChannelControl {...channel} />
|
||||
<ChannelPendingNotice pending={channelPending} saving={channel.isSaving} />
|
||||
<VersionGrid
|
||||
current={view.current}
|
||||
latest={channelPending ? "-" : view.latest}
|
||||
latestLabel={
|
||||
channel.draft === "nightly"
|
||||
? t("settings:updateChannelLatestNightly")
|
||||
: t("settings:updateChannelLatestRelease")
|
||||
}
|
||||
/>
|
||||
<LastChecked checkedAt={channelPending ? undefined : updates?.latest_checked_at} />
|
||||
<UpdateActions
|
||||
checking={checking}
|
||||
showApply={view.showApply}
|
||||
checking={isChecking}
|
||||
disabled={channelPending}
|
||||
showApply={view.showApply && !channelPending && !isChecking}
|
||||
latest={view.latest}
|
||||
url={updates?.latest_url}
|
||||
onCheck={onCheck}
|
||||
url={channelPending ? undefined : updates?.latest_url}
|
||||
onCheck={() => ignoreFailure(check())}
|
||||
onApply={selfUpdate.start}
|
||||
/>
|
||||
<ManualUpdateInstructions
|
||||
show={view.showManual}
|
||||
show={view.showManual && !channelPending}
|
||||
reason={view.cannotApplyReason}
|
||||
commands={view.manualCommands}
|
||||
/>
|
||||
@@ -148,9 +152,9 @@ export function UpdatesCard({ reloadDocument = reloadCurrentDocument }: UpdatesC
|
||||
errorMessage={selfUpdate.errorMessage}
|
||||
onDismiss={selfUpdate.dismiss}
|
||||
/>
|
||||
<UpdateError error={error} retryAfter={retryAfter} />
|
||||
<UpdateError error={error} retryAfter={error ? retryAfterSeconds(error) : null} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</SettingsCard>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -222,7 +226,7 @@ function DesktopCurrentStatus({ phase }: { phase: string | undefined }) {
|
||||
);
|
||||
}
|
||||
|
||||
async function ignoreFailure(operation: Promise<void>): Promise<void> {
|
||||
async function ignoreFailure(operation: Promise<unknown>): Promise<void> {
|
||||
await operation.catch(() => undefined);
|
||||
}
|
||||
|
||||
@@ -268,17 +272,28 @@ function UpdatesHeader({ available }: { available: boolean }) {
|
||||
);
|
||||
}
|
||||
|
||||
function VersionGrid({ current, latest }: { current: string; latest: string }) {
|
||||
function VersionGrid({
|
||||
current,
|
||||
latest,
|
||||
latestLabel,
|
||||
}: {
|
||||
current: string;
|
||||
latest: string;
|
||||
latestLabel?: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-3 text-sm">
|
||||
<div
|
||||
className="grid min-w-0 grid-cols-1 gap-3 text-sm sm:grid-cols-2"
|
||||
data-testid="system-updates-versions"
|
||||
>
|
||||
<VersionValue
|
||||
label={t("system:updatesCurrentVersion")}
|
||||
value={current}
|
||||
testId="system-updates-current"
|
||||
/>
|
||||
<VersionValue
|
||||
label={t("system:updatesLatestRelease")}
|
||||
label={latestLabel ?? t("system:updatesLatestRelease")}
|
||||
value={latest}
|
||||
testId="system-updates-latest"
|
||||
/>
|
||||
@@ -288,9 +303,9 @@ function VersionGrid({ current, latest }: { current: string; latest: string }) {
|
||||
|
||||
function VersionValue({ label, value, testId }: { label: string; value: string; testId: string }) {
|
||||
return (
|
||||
<div>
|
||||
<div className="min-w-0">
|
||||
<div className="text-xs text-muted-foreground">{label}</div>
|
||||
<div className="font-mono text-sm" data-testid={testId}>
|
||||
<div className="break-all font-mono text-sm" data-testid={testId}>
|
||||
{value}
|
||||
</div>
|
||||
</div>
|
||||
@@ -308,6 +323,7 @@ function LastChecked({ checkedAt }: { checkedAt?: string | number | null }) {
|
||||
|
||||
interface UpdateActionsProps {
|
||||
checking: boolean;
|
||||
disabled?: boolean;
|
||||
showApply: boolean;
|
||||
latest: string;
|
||||
url?: string;
|
||||
@@ -322,7 +338,7 @@ function UpdateActions(props: UpdateActionsProps) {
|
||||
className="flex flex-col gap-2 sm:flex-row sm:flex-wrap sm:items-center"
|
||||
data-testid="system-updates-actions"
|
||||
>
|
||||
<CheckNowButton checking={props.checking} onCheck={props.onCheck} />
|
||||
<CheckNowButton checking={props.checking} disabled={props.disabled} onCheck={props.onCheck} />
|
||||
<ReleaseNotesLink url={props.url} />
|
||||
<ApplyUpdateDialog
|
||||
showApply={props.showApply}
|
||||
@@ -336,9 +352,11 @@ function UpdateActions(props: UpdateActionsProps) {
|
||||
|
||||
function CheckNowButton({
|
||||
checking,
|
||||
disabled,
|
||||
onCheck,
|
||||
}: {
|
||||
checking: boolean;
|
||||
disabled?: boolean;
|
||||
onCheck: () => Promise<void>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
@@ -346,7 +364,7 @@ function CheckNowButton({
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={checking}
|
||||
disabled={checking || disabled}
|
||||
onClick={() => void onCheck()}
|
||||
className="cursor-pointer"
|
||||
data-testid="system-updates-check"
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import { test, expect } from "../../fixtures/test-base";
|
||||
import { assertNoDocumentHorizontalOverflow } from "../../helpers/layout-assertions";
|
||||
import { PrAssetCapture } from "../../helpers/pr-asset-capture";
|
||||
import { useManagedNPMUpdates } from "./updates-channel-helpers";
|
||||
|
||||
const LONG_NIGHTLY_VERSION = "999999999.999999999.999999999-nightly.shaabcdef123456";
|
||||
const LONG_NIGHTLY_TAG = `v${LONG_NIGHTLY_VERSION}`;
|
||||
|
||||
test.describe("System update channel on mobile", () => {
|
||||
test("selects, saves, and reloads Nightly with touch-safe rows", async ({
|
||||
backend,
|
||||
testPage,
|
||||
}, testInfo) => {
|
||||
test.setTimeout(60_000);
|
||||
const capture = new PrAssetCapture(testPage, testInfo.file);
|
||||
const fixture = await useManagedNPMUpdates(backend, LONG_NIGHTLY_VERSION);
|
||||
try {
|
||||
await testPage.goto("/settings/system/updates");
|
||||
const nightly = testPage.getByRole("radio", { name: /^Nightly/ });
|
||||
const nightlyRow = testPage.getByTestId("system-updates-channel-nightly");
|
||||
const rowBox = await nightlyRow.boundingBox();
|
||||
expect(rowBox).not.toBeNull();
|
||||
expect(rowBox!.height).toBeGreaterThanOrEqual(44);
|
||||
await assertNoDocumentHorizontalOverflow(testPage, "Updates before channel selection");
|
||||
|
||||
await nightlyRow.tap();
|
||||
await expect(nightly).toBeChecked();
|
||||
const saved = testPage.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "PATCH" &&
|
||||
new URL(response.url()).pathname === "/api/v1/system/updates/channel",
|
||||
);
|
||||
await testPage
|
||||
.getByTestId("settings-floating-save")
|
||||
.getByRole("button", { name: "Save changes" })
|
||||
.tap();
|
||||
expect((await saved).status()).toBe(200);
|
||||
await expect(testPage.getByTestId("system-updates-latest")).toHaveText(LONG_NIGHTLY_TAG);
|
||||
expect(fixture.registryRequests()).toBeGreaterThanOrEqual(1);
|
||||
|
||||
await testPage.reload();
|
||||
await expect(nightly).toBeChecked();
|
||||
await expect(testPage.getByTestId("system-updates-latest")).toHaveText(LONG_NIGHTLY_TAG);
|
||||
await assertNoDocumentHorizontalOverflow(testPage, "Updates after Nightly reload");
|
||||
await capture.screenshot("mobile-nightly-update-channel", {
|
||||
caption: "Mobile: saved Nightly channel and exact target",
|
||||
});
|
||||
} finally {
|
||||
try {
|
||||
capture.flush();
|
||||
} finally {
|
||||
await fixture.release();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("explains an unsupported Nightly channel without horizontal overflow", async ({
|
||||
testPage,
|
||||
}) => {
|
||||
let channelMutations = 0;
|
||||
testPage.on("request", (request) => {
|
||||
if (
|
||||
request.method() === "PATCH" &&
|
||||
new URL(request.url()).pathname === "/api/v1/system/updates/channel"
|
||||
) {
|
||||
channelMutations += 1;
|
||||
}
|
||||
});
|
||||
|
||||
await testPage.goto("/settings/system/updates");
|
||||
|
||||
await expect(testPage.getByRole("radio", { name: /^Stable/ })).toBeChecked();
|
||||
await expect(testPage.getByRole("radio", { name: /^Nightly/ })).toBeDisabled();
|
||||
await expect(testPage.getByTestId("system-updates-channel-reason")).toContainText(
|
||||
/managed npm or npx user service/i,
|
||||
);
|
||||
await expect(testPage.getByTestId("settings-floating-save")).toHaveCount(0);
|
||||
await testPage.waitForLoadState("networkidle");
|
||||
expect(channelMutations).toBe(0);
|
||||
await assertNoDocumentHorizontalOverflow(testPage, "Unsupported Updates channel");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import fs from "node:fs";
|
||||
import { createServer, type Server } from "node:http";
|
||||
import path from "node:path";
|
||||
|
||||
import type { BackendContext } from "../../fixtures/backend";
|
||||
|
||||
export const NIGHTLY_VERSION = "1.0.1-nightly.shaabcdef123456";
|
||||
export const NIGHTLY_TAG = `v${NIGHTLY_VERSION}`;
|
||||
|
||||
type ManagedNPMUpdatesFixture = {
|
||||
registryRequests: () => number;
|
||||
release: () => Promise<void>;
|
||||
};
|
||||
|
||||
export async function useManagedNPMUpdates(
|
||||
backend: BackendContext,
|
||||
version = NIGHTLY_VERSION,
|
||||
): Promise<ManagedNPMUpdatesFixture> {
|
||||
const registry = await startRegistry(version);
|
||||
let releaseEnv: (() => Promise<void>) | undefined;
|
||||
try {
|
||||
const metadataPath = writeManagedServiceMetadata(backend);
|
||||
releaseEnv = await backend.useEnv({
|
||||
KANDEV_RUNNING_AS_SERVICE: "true",
|
||||
KANDEV_SERVICE_MODE: "user",
|
||||
KANDEV_SERVICE_MANAGER: "systemd",
|
||||
KANDEV_INSTALL_KIND: "npm",
|
||||
KANDEV_SERVICE_METADATA: metadataPath,
|
||||
KANDEV_E2E_NPM_REGISTRY_URL: registry.url,
|
||||
});
|
||||
} catch (error) {
|
||||
await closeServer(registry.server);
|
||||
throw error;
|
||||
}
|
||||
|
||||
return {
|
||||
registryRequests: () => registry.requests(),
|
||||
release: async () => {
|
||||
try {
|
||||
await releaseEnv?.();
|
||||
} finally {
|
||||
await closeServer(registry.server);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function writeManagedServiceMetadata(backend: BackendContext): string {
|
||||
const fixtureDir = path.join(backend.tmpDir, "nightly-service");
|
||||
const metadataPath = path.join(fixtureDir, "install.json");
|
||||
const servicePath = path.join(fixtureDir, "kandev.service");
|
||||
fs.mkdirSync(fixtureDir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
servicePath,
|
||||
[
|
||||
"# managed by kandev",
|
||||
"[Service]",
|
||||
"Environment=KANDEV_RUNNING_AS_SERVICE=true",
|
||||
`Environment=KANDEV_SERVICE_METADATA=${metadataPath}`,
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
fs.writeFileSync(
|
||||
metadataPath,
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
manager: "systemd",
|
||||
mode: "user",
|
||||
kind: "npm",
|
||||
home_dir: backend.tmpDir,
|
||||
log_dir: path.join(backend.tmpDir, "logs"),
|
||||
service_path: servicePath,
|
||||
launcher_path: path.join(fixtureDir, "kandev"),
|
||||
installed_at: "2026-07-31T12:00:00Z",
|
||||
}),
|
||||
);
|
||||
return metadataPath;
|
||||
}
|
||||
|
||||
async function startRegistry(version: string): Promise<{
|
||||
server: Server;
|
||||
url: string;
|
||||
requests: () => number;
|
||||
}> {
|
||||
let requestCount = 0;
|
||||
const server = createServer((_request, response) => {
|
||||
requestCount += 1;
|
||||
response.writeHead(200, { "Content-Type": "application/json" });
|
||||
response.end(
|
||||
JSON.stringify({
|
||||
"dist-tags": { nightly: version },
|
||||
versions: { [version]: { name: "kandev", version } },
|
||||
}),
|
||||
);
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", resolve);
|
||||
});
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") {
|
||||
await closeServer(server);
|
||||
throw new Error("nightly registry fixture did not bind a TCP port");
|
||||
}
|
||||
return {
|
||||
server,
|
||||
url: `http://127.0.0.1:${address.port}/kandev`,
|
||||
requests: () => requestCount,
|
||||
};
|
||||
}
|
||||
|
||||
function closeServer(server: Server): Promise<void> {
|
||||
if (!server.listening) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
server.close((error) => (error ? reject(error) : resolve()));
|
||||
server.closeAllConnections();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import { test, expect } from "../../fixtures/test-base";
|
||||
import type { Page } from "@playwright/test";
|
||||
import { PrAssetCapture } from "../../helpers/pr-asset-capture";
|
||||
import { NIGHTLY_TAG, NIGHTLY_VERSION, useManagedNPMUpdates } from "./updates-channel-helpers";
|
||||
|
||||
test.describe("System update channel", () => {
|
||||
test("selects and persists Nightly before offering the exact target", async ({
|
||||
backend,
|
||||
testPage,
|
||||
}, testInfo) => {
|
||||
test.setTimeout(60_000);
|
||||
const capture = new PrAssetCapture(testPage, testInfo.file);
|
||||
const fixture = await useManagedNPMUpdates(backend);
|
||||
try {
|
||||
await testPage.goto("/settings/system/updates");
|
||||
const stable = testPage.getByRole("radio", { name: /^Stable/ });
|
||||
const nightly = testPage.getByRole("radio", { name: /^Nightly/ });
|
||||
await expect(stable).toBeChecked();
|
||||
await expect(nightly).toBeEnabled();
|
||||
|
||||
const saved = testPage.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "PATCH" &&
|
||||
new URL(response.url()).pathname === "/api/v1/system/updates/channel",
|
||||
);
|
||||
await nightly.click();
|
||||
await testPage
|
||||
.getByTestId("settings-floating-save")
|
||||
.getByRole("button", { name: "Save changes" })
|
||||
.click();
|
||||
expect((await saved).status()).toBe(200);
|
||||
|
||||
await expect(nightly).toBeChecked();
|
||||
await expect(testPage.getByTestId("system-updates-latest")).toHaveText(NIGHTLY_TAG);
|
||||
expect(fixture.registryRequests()).toBeGreaterThanOrEqual(1);
|
||||
|
||||
await testPage.reload();
|
||||
await expect(nightly).toBeChecked();
|
||||
await expect(testPage.getByTestId("system-updates-latest")).toHaveText(NIGHTLY_TAG);
|
||||
|
||||
await capture.screenshot("desktop-nightly-update-channel", {
|
||||
caption: "Desktop: managed npm service following the Nightly channel",
|
||||
});
|
||||
|
||||
await makeExactNightlyAvailable(testPage);
|
||||
let reportTargetVersion = false;
|
||||
let applyBody: unknown;
|
||||
await testPage.route("**/api/v1/system/updates/apply", async (route) => {
|
||||
applyBody = route.request().postDataJSON();
|
||||
reportTargetVersion = true;
|
||||
await route.fulfill({
|
||||
status: 202,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({ job_id: "nightly-update-1" }),
|
||||
});
|
||||
});
|
||||
let jobRequests = 0;
|
||||
await testPage.route("**/api/v1/system/jobs/nightly-update-1", async (route) => {
|
||||
jobRequests += 1;
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({
|
||||
id: "nightly-update-1",
|
||||
kind: "self-update",
|
||||
state: "succeeded",
|
||||
started_at: new Date().toISOString(),
|
||||
}),
|
||||
});
|
||||
});
|
||||
await testPage.route("**/api/v1/system/info", async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({
|
||||
version: reportTargetVersion ? NIGHTLY_TAG : "v1.0.0",
|
||||
commit: "abcdef123456",
|
||||
build_time: new Date().toISOString(),
|
||||
go_version: "go1.26",
|
||||
os: "linux",
|
||||
arch: "amd64",
|
||||
}),
|
||||
});
|
||||
});
|
||||
const completedReload = testPage.waitForRequest(
|
||||
(request) =>
|
||||
request.isNavigationRequest() &&
|
||||
request.frame() === testPage.mainFrame() &&
|
||||
new URL(request.url()).pathname === "/settings/system/updates",
|
||||
);
|
||||
await testPage.getByTestId("system-updates-apply").click();
|
||||
await expect(testPage.getByRole("alertdialog")).toContainText(NIGHTLY_TAG);
|
||||
await testPage.getByTestId("system-updates-apply-confirm").click();
|
||||
await expect
|
||||
.poll(() => applyBody)
|
||||
.toEqual({
|
||||
confirm: "UPDATE",
|
||||
target_version: NIGHTLY_TAG,
|
||||
});
|
||||
await expect.poll(() => jobRequests).toBeGreaterThan(0);
|
||||
await completedReload;
|
||||
await testPage.waitForLoadState("domcontentloaded");
|
||||
await expect(testPage.getByTestId("system-page-title")).toHaveText("Updates");
|
||||
await expect(testPage.getByTestId("system-updates-latest")).toHaveText(NIGHTLY_TAG);
|
||||
await expect(testPage.getByTestId("system-updates-progress")).toHaveCount(0);
|
||||
} finally {
|
||||
try {
|
||||
capture.flush();
|
||||
} finally {
|
||||
await fixture.release();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps unsupported installs on Stable with no Nightly mutation path", async ({
|
||||
testPage,
|
||||
}) => {
|
||||
let channelMutations = 0;
|
||||
testPage.on("request", (request) => {
|
||||
if (
|
||||
request.method() === "PATCH" &&
|
||||
new URL(request.url()).pathname === "/api/v1/system/updates/channel"
|
||||
) {
|
||||
channelMutations += 1;
|
||||
}
|
||||
});
|
||||
|
||||
await testPage.goto("/settings/system/updates");
|
||||
|
||||
await expect(testPage.getByRole("radio", { name: /^Stable/ })).toBeChecked();
|
||||
await expect(testPage.getByRole("radio", { name: /^Nightly/ })).toBeDisabled();
|
||||
await expect(testPage.getByTestId("system-updates-channel-reason")).toContainText(
|
||||
/managed npm or npx user service/i,
|
||||
);
|
||||
await expect(testPage.getByTestId("settings-floating-save")).toHaveCount(0);
|
||||
await testPage.waitForLoadState("networkidle");
|
||||
expect(channelMutations).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
async function makeExactNightlyAvailable(testPage: Page): Promise<void> {
|
||||
await testPage.route("**/api/v1/system/updates/check", async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({
|
||||
current: "v1.0.0",
|
||||
latest: NIGHTLY_TAG,
|
||||
latest_url: `https://www.npmjs.com/package/kandev/v/${NIGHTLY_VERSION}`,
|
||||
latest_checked_at: new Date().toISOString(),
|
||||
update_available: true,
|
||||
channel: "nightly",
|
||||
channel_editable: true,
|
||||
channel_unsupported_reason: "",
|
||||
install: {
|
||||
running_as_service: true,
|
||||
managed_service: true,
|
||||
mode: "user",
|
||||
manager: "systemd",
|
||||
kind: "npm",
|
||||
},
|
||||
apply_supported: true,
|
||||
}),
|
||||
});
|
||||
});
|
||||
await testPage.getByTestId("system-updates-check").click();
|
||||
await expect(testPage.getByTestId("system-updates-apply")).toBeVisible();
|
||||
}
|
||||
@@ -17,6 +17,10 @@ test.describe("System Updates — rate-limited check", () => {
|
||||
latest_url: "",
|
||||
latest_checked_at: new Date().toISOString(),
|
||||
update_available: false,
|
||||
channel: "stable",
|
||||
channel_editable: false,
|
||||
channel_unsupported_reason:
|
||||
"Nightly updates require a Kandev-managed npm or npx user service.",
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -20,6 +20,10 @@ test.describe("System Updates page", () => {
|
||||
latest_url: "https://example.com/r/v1.0.1",
|
||||
latest_checked_at: new Date().toISOString(),
|
||||
update_available: true,
|
||||
channel: "stable",
|
||||
channel_editable: false,
|
||||
channel_unsupported_reason:
|
||||
"Nightly updates require a Kandev-managed npm or npx user service.",
|
||||
}),
|
||||
});
|
||||
});
|
||||
@@ -35,6 +39,11 @@ test.describe("System Updates page", () => {
|
||||
|
||||
await expect(testPage.getByTestId("system-updates-current")).toHaveText("v1.0.0");
|
||||
await expect(testPage.getByTestId("system-updates-latest")).toHaveText("v1.0.1");
|
||||
await expect(testPage.getByRole("radio", { name: /^Stable/ })).toBeChecked();
|
||||
await expect(testPage.getByRole("radio", { name: /^Nightly/ })).toBeDisabled();
|
||||
await expect(testPage.getByTestId("system-updates-channel-reason")).toContainText(
|
||||
/managed npm or npx user service/i,
|
||||
);
|
||||
await expect(testPage.getByTestId("system-updates-apply")).toHaveCount(0);
|
||||
});
|
||||
|
||||
@@ -51,6 +60,9 @@ test.describe("System Updates page", () => {
|
||||
latest_url: "https://example.com/r/v1.0.1",
|
||||
latest_checked_at: new Date().toISOString(),
|
||||
update_available: true,
|
||||
channel: "stable",
|
||||
channel_editable: true,
|
||||
channel_unsupported_reason: "",
|
||||
install: {
|
||||
running_as_service: true,
|
||||
managed_service: true,
|
||||
@@ -106,6 +118,9 @@ test.describe("System Updates page", () => {
|
||||
latest_url: "https://example.com/r/v1.0.1",
|
||||
latest_checked_at: new Date().toISOString(),
|
||||
update_available: true,
|
||||
channel: "stable",
|
||||
channel_editable: true,
|
||||
channel_unsupported_reason: "",
|
||||
install: {
|
||||
running_as_service: true,
|
||||
managed_service: true,
|
||||
@@ -208,6 +223,10 @@ test.describe("System Updates page", () => {
|
||||
latest_url: "https://example.com/r/v1.0.1",
|
||||
latest_checked_at: new Date().toISOString(),
|
||||
update_available: true,
|
||||
channel: "stable",
|
||||
channel_editable: false,
|
||||
channel_unsupported_reason:
|
||||
"Nightly updates require a Kandev-managed npm or npx user service.",
|
||||
install: { running_as_service: false, managed_service: false },
|
||||
apply_supported: false,
|
||||
apply_unsupported_reason: "Kandev is not running as a managed service.",
|
||||
|
||||
@@ -47,7 +47,7 @@ function registerUpdateLifecycleTests() {
|
||||
await act(async () => {
|
||||
await result.current.start();
|
||||
});
|
||||
expect(mocks.applyUpdate).toHaveBeenCalledWith("UPDATE");
|
||||
expect(mocks.applyUpdate).toHaveBeenCalledWith("UPDATE", "v1.0.1");
|
||||
expect(result.current.phase).toBe("installing");
|
||||
expect(result.current.isUpdating).toBe(true);
|
||||
expect(JSON.parse(localStorage.getItem(STORAGE_KEY) as string).target).toBe("v1.0.1");
|
||||
|
||||
@@ -109,7 +109,7 @@ export function useSelfUpdate({
|
||||
setPhase("starting");
|
||||
writePersisted({ target: latestVersion, startedAt: Date.now() });
|
||||
try {
|
||||
const res = await applyUpdate("UPDATE");
|
||||
const res = await applyUpdate("UPDATE", latestVersion);
|
||||
setJobId(res.job_id);
|
||||
setPhase("installing");
|
||||
} catch (e) {
|
||||
|
||||
@@ -46,6 +46,9 @@ function makeUpdates(updateAvailable: boolean): UpdatesResponse {
|
||||
latest_url: "",
|
||||
latest_checked_at: "2026-05-18T00:00:00Z",
|
||||
update_available: updateAvailable,
|
||||
channel: "stable",
|
||||
channel_editable: true,
|
||||
channel_unsupported_reason: "",
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,450 @@
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { UpdatesResponse } from "@/lib/types/system";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
checkUpdates: vi.fn(),
|
||||
fetchUpdates: vi.fn(),
|
||||
saveUpdatesChannel: vi.fn(),
|
||||
setSystemUpdates: vi.fn(),
|
||||
currentUpdates: null as UpdatesResponse | null,
|
||||
store: {} as object,
|
||||
}));
|
||||
|
||||
vi.mock("@/components/state-provider", () => ({
|
||||
useAppStoreApi: () => mocks.store,
|
||||
useAppStore: (
|
||||
selector: (state: {
|
||||
system: { updates: UpdatesResponse | null };
|
||||
setSystemUpdates: typeof mocks.setSystemUpdates;
|
||||
}) => unknown,
|
||||
) =>
|
||||
selector({
|
||||
system: { updates: mocks.currentUpdates },
|
||||
setSystemUpdates: mocks.setSystemUpdates,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/api/domains/system-api", () => ({
|
||||
checkUpdates: mocks.checkUpdates,
|
||||
fetchUpdates: mocks.fetchUpdates,
|
||||
saveUpdatesChannel: mocks.saveUpdatesChannel,
|
||||
}));
|
||||
|
||||
import { useUpdates } from "./use-updates";
|
||||
|
||||
const SAVE_FAILURE_MESSAGE = "save failed";
|
||||
const CHECK_FAILURE_MESSAGE = "check failed";
|
||||
const CHANNEL_SAVE_FAILURE_COPY = "Could not save the update channel. Try again.";
|
||||
|
||||
function updates(channel: UpdatesResponse["channel"]): UpdatesResponse {
|
||||
const nightly = channel === "nightly";
|
||||
return {
|
||||
current: "v1.0.0",
|
||||
latest: nightly ? "v1.0.1-nightly.shaabcdef123456" : "v1.0.1",
|
||||
latest_url: "https://example.test/update",
|
||||
latest_checked_at: "2026-08-01T00:00:00Z",
|
||||
update_available: true,
|
||||
channel,
|
||||
channel_editable: true,
|
||||
channel_unsupported_reason: "",
|
||||
};
|
||||
}
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (reason?: unknown) => void;
|
||||
const promise = new Promise<T>((done, fail) => {
|
||||
resolve = done;
|
||||
reject = fail;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.checkUpdates.mockReset();
|
||||
mocks.fetchUpdates.mockReset();
|
||||
mocks.saveUpdatesChannel.mockReset();
|
||||
mocks.setSystemUpdates.mockReset();
|
||||
mocks.currentUpdates = updates("stable");
|
||||
mocks.setSystemUpdates.mockImplementation((next: UpdatesResponse) => {
|
||||
mocks.currentUpdates = next;
|
||||
});
|
||||
mocks.store = {
|
||||
getState: () => ({ system: { updates: mocks.currentUpdates } }),
|
||||
};
|
||||
});
|
||||
|
||||
describe("useUpdates", () => {
|
||||
it("keeps checking active until the newest overlapping check settles", async () => {
|
||||
const first = deferred<UpdatesResponse>();
|
||||
const second = deferred<UpdatesResponse>();
|
||||
mocks.checkUpdates.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
|
||||
const { result } = renderHook(() => useUpdates());
|
||||
|
||||
let firstPromise!: Promise<UpdatesResponse | undefined>;
|
||||
let secondPromise!: Promise<UpdatesResponse | undefined>;
|
||||
act(() => {
|
||||
firstPromise = result.current.check();
|
||||
secondPromise = result.current.check();
|
||||
});
|
||||
expect(result.current.isChecking).toBe(true);
|
||||
|
||||
await act(async () => {
|
||||
first.resolve(updates("stable"));
|
||||
await firstPromise;
|
||||
});
|
||||
expect(result.current.isChecking).toBe(true);
|
||||
|
||||
await act(async () => {
|
||||
second.resolve(updates("nightly"));
|
||||
await secondPromise;
|
||||
});
|
||||
expect(result.current.isChecking).toBe(false);
|
||||
});
|
||||
|
||||
it("deduplicates overlapping reloads and publishes their shared result once", async () => {
|
||||
const pending = deferred<UpdatesResponse>();
|
||||
mocks.fetchUpdates.mockReturnValue(pending.promise);
|
||||
const { result } = renderHook(() => useUpdates());
|
||||
|
||||
let firstPromise!: Promise<void>;
|
||||
let secondPromise!: Promise<void>;
|
||||
act(() => {
|
||||
firstPromise = result.current.reload();
|
||||
secondPromise = result.current.reload();
|
||||
});
|
||||
expect(mocks.fetchUpdates).toHaveBeenCalledOnce();
|
||||
|
||||
const nightly = updates("nightly");
|
||||
await act(async () => {
|
||||
pending.resolve(nightly);
|
||||
await Promise.all([firstPromise, secondPromise]);
|
||||
});
|
||||
expect(mocks.setSystemUpdates).toHaveBeenCalledOnce();
|
||||
expect(mocks.setSystemUpdates).toHaveBeenCalledWith(nightly);
|
||||
});
|
||||
});
|
||||
|
||||
describe("useUpdates request ordering", () => {
|
||||
it("starts a fresh reload when a newer failed check makes the shared flight stale", async () => {
|
||||
const staleReload = deferred<UpdatesResponse>();
|
||||
const recoveryReload = deferred<UpdatesResponse>();
|
||||
const checkFailure = new Error(CHECK_FAILURE_MESSAGE);
|
||||
mocks.fetchUpdates
|
||||
.mockReturnValueOnce(staleReload.promise)
|
||||
.mockReturnValueOnce(recoveryReload.promise);
|
||||
mocks.checkUpdates.mockRejectedValue(checkFailure);
|
||||
const { result } = renderHook(() => useUpdates());
|
||||
|
||||
let stalePromise!: Promise<void>;
|
||||
act(() => {
|
||||
stalePromise = result.current.reload();
|
||||
});
|
||||
await act(async () => {
|
||||
await expect(result.current.check()).rejects.toBe(checkFailure);
|
||||
});
|
||||
|
||||
let recoveryPromise!: Promise<void>;
|
||||
act(() => {
|
||||
recoveryPromise = result.current.reload();
|
||||
});
|
||||
expect(mocks.fetchUpdates).toHaveBeenCalledTimes(2);
|
||||
|
||||
const nightly = updates("nightly");
|
||||
await act(async () => {
|
||||
recoveryReload.resolve(nightly);
|
||||
await recoveryPromise;
|
||||
});
|
||||
await act(async () => {
|
||||
staleReload.resolve(updates("stable"));
|
||||
await stalePromise;
|
||||
});
|
||||
|
||||
expect(mocks.setSystemUpdates).toHaveBeenCalledOnce();
|
||||
expect(mocks.setSystemUpdates).toHaveBeenCalledWith(nightly);
|
||||
expect(result.current.error).toBeNull();
|
||||
});
|
||||
|
||||
it("suppresses an obsolete check failure after a newer channel save", async () => {
|
||||
const pendingCheck = deferred<UpdatesResponse>();
|
||||
const nightly = updates("nightly");
|
||||
mocks.checkUpdates.mockReturnValue(pendingCheck.promise);
|
||||
mocks.saveUpdatesChannel.mockResolvedValue(nightly);
|
||||
const { result } = renderHook(() => useUpdates());
|
||||
|
||||
let checkPromise!: Promise<UpdatesResponse | undefined>;
|
||||
await act(async () => {
|
||||
checkPromise = result.current.check();
|
||||
await result.current.saveChannel("nightly");
|
||||
});
|
||||
await act(async () => {
|
||||
pendingCheck.reject(new Error("obsolete check failed"));
|
||||
await expect(checkPromise).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
expect(result.current.error).toBeNull();
|
||||
expect(mocks.setSystemUpdates).toHaveBeenCalledOnce();
|
||||
expect(mocks.setSystemUpdates).toHaveBeenCalledWith(nightly);
|
||||
});
|
||||
|
||||
it("keeps a save authoritative over an older reload from another hook instance", async () => {
|
||||
const pendingReload = deferred<UpdatesResponse>();
|
||||
const nightly = updates("nightly");
|
||||
mocks.fetchUpdates.mockReturnValue(pendingReload.promise);
|
||||
mocks.saveUpdatesChannel.mockResolvedValue(nightly);
|
||||
const reader = renderHook(() => useUpdates());
|
||||
const writer = renderHook(() => useUpdates());
|
||||
|
||||
let reloadPromise!: Promise<void>;
|
||||
await act(async () => {
|
||||
reloadPromise = reader.result.current.reload();
|
||||
await writer.result.current.saveChannel("nightly");
|
||||
});
|
||||
await act(async () => {
|
||||
pendingReload.resolve(updates("stable"));
|
||||
await reloadPromise;
|
||||
});
|
||||
|
||||
expect(mocks.setSystemUpdates).toHaveBeenCalledOnce();
|
||||
expect(mocks.setSystemUpdates).toHaveBeenCalledWith(nightly);
|
||||
});
|
||||
});
|
||||
|
||||
describe("useUpdates initial load recovery", () => {
|
||||
it("does not revalidate when another hook populated the live store", async () => {
|
||||
const initialReload = deferred<UpdatesResponse>();
|
||||
const pendingCheck = deferred<UpdatesResponse>();
|
||||
const checkFailure = new Error(CHECK_FAILURE_MESSAGE);
|
||||
mocks.currentUpdates = null;
|
||||
mocks.fetchUpdates.mockReturnValue(initialReload.promise);
|
||||
mocks.checkUpdates.mockReturnValue(pendingCheck.promise);
|
||||
const { result } = renderHook(() => useUpdates());
|
||||
|
||||
let checkPromise!: Promise<UpdatesResponse | undefined>;
|
||||
act(() => {
|
||||
checkPromise = result.current.check();
|
||||
});
|
||||
mocks.currentUpdates = updates("stable");
|
||||
await act(async () => {
|
||||
pendingCheck.reject(checkFailure);
|
||||
await expect(checkPromise).rejects.toBe(checkFailure);
|
||||
});
|
||||
|
||||
expect(mocks.fetchUpdates).toHaveBeenCalledOnce();
|
||||
await act(async () => {
|
||||
initialReload.resolve(updates("stable"));
|
||||
await initialReload.promise;
|
||||
});
|
||||
});
|
||||
|
||||
it("revalidates an empty store after a check invalidates the initial reload and fails", async () => {
|
||||
const initialReload = deferred<UpdatesResponse>();
|
||||
const recoveryReload = deferred<UpdatesResponse>();
|
||||
const checkFailure = new Error(CHECK_FAILURE_MESSAGE);
|
||||
mocks.currentUpdates = null;
|
||||
mocks.fetchUpdates
|
||||
.mockReturnValueOnce(initialReload.promise)
|
||||
.mockReturnValueOnce(recoveryReload.promise);
|
||||
mocks.checkUpdates.mockRejectedValue(checkFailure);
|
||||
const { result } = renderHook(() => useUpdates());
|
||||
|
||||
expect(mocks.fetchUpdates).toHaveBeenCalledOnce();
|
||||
await act(async () => {
|
||||
await expect(result.current.check()).rejects.toBe(checkFailure);
|
||||
});
|
||||
expect(mocks.fetchUpdates).toHaveBeenCalledTimes(2);
|
||||
|
||||
const stable = updates("stable");
|
||||
await act(async () => {
|
||||
initialReload.resolve(updates("nightly"));
|
||||
recoveryReload.resolve(stable);
|
||||
await Promise.all([initialReload.promise, recoveryReload.promise]);
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
expect(mocks.setSystemUpdates).toHaveBeenCalledOnce();
|
||||
expect(mocks.setSystemUpdates).toHaveBeenCalledWith(stable);
|
||||
expect(result.current.error).toBe(CHECK_FAILURE_MESSAGE);
|
||||
});
|
||||
});
|
||||
|
||||
describe("useUpdates channel saving", () => {
|
||||
it("saves a channel and publishes the returned state", async () => {
|
||||
const nightly = updates("nightly");
|
||||
mocks.saveUpdatesChannel.mockResolvedValue(nightly);
|
||||
const { result, rerender } = renderHook(() => useUpdates());
|
||||
|
||||
let response!: UpdatesResponse;
|
||||
await act(async () => {
|
||||
response = await result.current.saveChannel("nightly");
|
||||
});
|
||||
|
||||
expect(mocks.saveUpdatesChannel).toHaveBeenCalledWith("nightly");
|
||||
expect(mocks.setSystemUpdates).toHaveBeenCalledWith(nightly);
|
||||
expect(response).toBe(nightly);
|
||||
rerender();
|
||||
expect(result.current.updates).toBe(nightly);
|
||||
expect(result.current.error).toBeNull();
|
||||
});
|
||||
|
||||
it("surfaces a channel save failure while revalidating the current state", async () => {
|
||||
const errorLog = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
const failure = new Error(SAVE_FAILURE_MESSAGE);
|
||||
const stable = updates("stable");
|
||||
mocks.saveUpdatesChannel.mockRejectedValue(failure);
|
||||
mocks.fetchUpdates.mockResolvedValue(stable);
|
||||
const { result } = renderHook(() => useUpdates());
|
||||
|
||||
await act(async () => {
|
||||
await expect(result.current.saveChannel("nightly")).rejects.toBe(failure);
|
||||
});
|
||||
|
||||
expect(result.current.error).toBe(CHANNEL_SAVE_FAILURE_COPY);
|
||||
expect(errorLog).toHaveBeenCalledWith("[updates] Failed to save update channel", failure);
|
||||
expect(mocks.fetchUpdates).toHaveBeenCalledOnce();
|
||||
expect(mocks.setSystemUpdates).toHaveBeenCalledWith(stable);
|
||||
errorLog.mockRestore();
|
||||
});
|
||||
|
||||
it("revalidates after a failed save suppresses a concurrent reload", async () => {
|
||||
const errorLog = vi.spyOn(console, "error").mockImplementation(() => undefined);
|
||||
const pendingSave = deferred<UpdatesResponse>();
|
||||
const suppressedReload = deferred<UpdatesResponse>();
|
||||
const recoveryReload = deferred<UpdatesResponse>();
|
||||
const failure = new Error(SAVE_FAILURE_MESSAGE);
|
||||
mocks.saveUpdatesChannel.mockReturnValue(pendingSave.promise);
|
||||
mocks.fetchUpdates
|
||||
.mockReturnValueOnce(suppressedReload.promise)
|
||||
.mockReturnValueOnce(recoveryReload.promise);
|
||||
const { result } = renderHook(() => useUpdates());
|
||||
|
||||
let savePromise!: Promise<UpdatesResponse>;
|
||||
let reloadPromise!: Promise<void>;
|
||||
act(() => {
|
||||
savePromise = result.current.saveChannel("nightly");
|
||||
reloadPromise = result.current.reload();
|
||||
});
|
||||
await act(async () => {
|
||||
suppressedReload.resolve(updates("stable"));
|
||||
await reloadPromise;
|
||||
});
|
||||
expect(mocks.setSystemUpdates).not.toHaveBeenCalled();
|
||||
|
||||
await act(async () => {
|
||||
pendingSave.reject(failure);
|
||||
await expect(savePromise).rejects.toBe(failure);
|
||||
});
|
||||
expect(mocks.fetchUpdates).toHaveBeenCalledTimes(2);
|
||||
|
||||
const stable = updates("stable");
|
||||
await act(async () => {
|
||||
recoveryReload.resolve(stable);
|
||||
await recoveryReload.promise;
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(mocks.setSystemUpdates).toHaveBeenCalledOnce();
|
||||
expect(mocks.setSystemUpdates).toHaveBeenCalledWith(stable);
|
||||
expect(result.current.error).toBe(CHANNEL_SAVE_FAILURE_COPY);
|
||||
errorLog.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe("useUpdates save/read ordering", () => {
|
||||
it("ignores an older check response after a channel save starts", async () => {
|
||||
const pendingCheck = deferred<UpdatesResponse>();
|
||||
const pendingSave = deferred<UpdatesResponse>();
|
||||
mocks.checkUpdates.mockReturnValue(pendingCheck.promise);
|
||||
mocks.saveUpdatesChannel.mockReturnValue(pendingSave.promise);
|
||||
const { result } = renderHook(() => useUpdates());
|
||||
|
||||
let checkPromise!: Promise<UpdatesResponse | undefined>;
|
||||
let savePromise!: Promise<UpdatesResponse>;
|
||||
act(() => {
|
||||
checkPromise = result.current.check();
|
||||
savePromise = result.current.saveChannel("nightly");
|
||||
});
|
||||
|
||||
const nightly = updates("nightly");
|
||||
await act(async () => {
|
||||
pendingSave.resolve(nightly);
|
||||
await savePromise;
|
||||
});
|
||||
await act(async () => {
|
||||
pendingCheck.resolve(updates("stable"));
|
||||
await checkPromise;
|
||||
});
|
||||
|
||||
expect(mocks.setSystemUpdates).toHaveBeenCalledOnce();
|
||||
expect(mocks.setSystemUpdates).toHaveBeenLastCalledWith(nightly);
|
||||
});
|
||||
|
||||
it("keeps a channel save authoritative over a check started while it is pending", async () => {
|
||||
const pendingSave = deferred<UpdatesResponse>();
|
||||
const pendingCheck = deferred<UpdatesResponse>();
|
||||
mocks.saveUpdatesChannel.mockReturnValue(pendingSave.promise);
|
||||
mocks.checkUpdates.mockReturnValue(pendingCheck.promise);
|
||||
const { result } = renderHook(() => useUpdates());
|
||||
|
||||
let savePromise!: Promise<UpdatesResponse>;
|
||||
let checkPromise!: Promise<UpdatesResponse | undefined>;
|
||||
act(() => {
|
||||
savePromise = result.current.saveChannel("nightly");
|
||||
checkPromise = result.current.check();
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
pendingCheck.resolve(updates("stable"));
|
||||
await checkPromise;
|
||||
});
|
||||
expect(mocks.setSystemUpdates).not.toHaveBeenCalled();
|
||||
|
||||
const nightly = updates("nightly");
|
||||
await act(async () => {
|
||||
pendingSave.resolve(nightly);
|
||||
await savePromise;
|
||||
});
|
||||
|
||||
expect(mocks.setSystemUpdates).toHaveBeenCalledOnce();
|
||||
expect(mocks.setSystemUpdates).toHaveBeenCalledWith(nightly);
|
||||
});
|
||||
});
|
||||
|
||||
describe("useUpdates save serialization", () => {
|
||||
it("keeps the newest save authoritative across hook instances", async () => {
|
||||
const firstSave = deferred<UpdatesResponse>();
|
||||
const secondSave = deferred<UpdatesResponse>();
|
||||
mocks.saveUpdatesChannel
|
||||
.mockReturnValueOnce(firstSave.promise)
|
||||
.mockReturnValueOnce(secondSave.promise);
|
||||
const first = renderHook(() => useUpdates());
|
||||
const second = renderHook(() => useUpdates());
|
||||
|
||||
let firstPromise!: Promise<UpdatesResponse>;
|
||||
let secondPromise!: Promise<UpdatesResponse>;
|
||||
await act(async () => {
|
||||
firstPromise = first.result.current.saveChannel("nightly");
|
||||
secondPromise = second.result.current.saveChannel("stable");
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(mocks.saveUpdatesChannel).toHaveBeenCalledOnce();
|
||||
expect(mocks.saveUpdatesChannel).toHaveBeenCalledWith("nightly");
|
||||
|
||||
await act(async () => {
|
||||
firstSave.resolve(updates("nightly"));
|
||||
await firstPromise;
|
||||
});
|
||||
expect(mocks.saveUpdatesChannel).toHaveBeenCalledTimes(2);
|
||||
expect(mocks.saveUpdatesChannel).toHaveBeenLastCalledWith("stable");
|
||||
|
||||
const stable = updates("stable");
|
||||
await act(async () => {
|
||||
secondSave.resolve(stable);
|
||||
await secondPromise;
|
||||
});
|
||||
|
||||
expect(mocks.setSystemUpdates).toHaveBeenCalledOnce();
|
||||
expect(mocks.setSystemUpdates).toHaveBeenCalledWith(stable);
|
||||
});
|
||||
});
|
||||
@@ -1,53 +1,184 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
import { checkUpdates, fetchUpdates } from "@/lib/api/domains/system-api";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
|
||||
import { checkUpdates, fetchUpdates, saveUpdatesChannel } from "@/lib/api/domains/system-api";
|
||||
import type { UpdatesChannel, UpdatesResponse } from "@/lib/types/system";
|
||||
|
||||
type UpdatesRequestCoordinator = {
|
||||
readRevision: number;
|
||||
saveRevision: number;
|
||||
activeSaves: number;
|
||||
saveTail: Promise<void>;
|
||||
reloadFlight: {
|
||||
request: number;
|
||||
promise: Promise<UpdatesResponse>;
|
||||
published: boolean;
|
||||
} | null;
|
||||
};
|
||||
|
||||
// Hooks own their loading/error UI, but every instance writes the same Zustand
|
||||
// store. Coordinate response authority per store so one mounted reader cannot
|
||||
// overwrite a newer channel save performed by another instance.
|
||||
const coordinators = new WeakMap<object, UpdatesRequestCoordinator>();
|
||||
|
||||
function coordinatorFor(store: object): UpdatesRequestCoordinator {
|
||||
let coordinator = coordinators.get(store);
|
||||
if (!coordinator) {
|
||||
coordinator = {
|
||||
readRevision: 0,
|
||||
saveRevision: 0,
|
||||
activeSaves: 0,
|
||||
saveTail: Promise.resolve(),
|
||||
reloadFlight: null,
|
||||
};
|
||||
coordinators.set(store, coordinator);
|
||||
}
|
||||
return coordinator;
|
||||
}
|
||||
|
||||
function revalidateWithoutReplacingError(
|
||||
coordinator: UpdatesRequestCoordinator,
|
||||
setSystemUpdates: (updates: UpdatesResponse) => void,
|
||||
): void {
|
||||
const request = ++coordinator.readRevision;
|
||||
void fetchUpdates({ cache: "no-store" })
|
||||
.then((response) => {
|
||||
if (request === coordinator.readRevision && coordinator.activeSaves === 0) {
|
||||
setSystemUpdates(response);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
// Keep the triggering error authoritative; a later manual reload can retry.
|
||||
});
|
||||
}
|
||||
|
||||
function queueChannelSave(
|
||||
coordinator: UpdatesRequestCoordinator,
|
||||
channel: UpdatesChannel,
|
||||
setSystemUpdates: (updates: UpdatesResponse) => void,
|
||||
setError: (error: string | null) => void,
|
||||
saveErrorMessage: string,
|
||||
): Promise<UpdatesResponse> {
|
||||
const request = ++coordinator.saveRevision;
|
||||
coordinator.activeSaves += 1;
|
||||
coordinator.readRevision += 1;
|
||||
setError(null);
|
||||
const previousSave = coordinator.saveTail;
|
||||
const operation = (async () => {
|
||||
let saved = false;
|
||||
await previousSave;
|
||||
try {
|
||||
const response = await saveUpdatesChannel(channel);
|
||||
saved = true;
|
||||
if (request === coordinator.saveRevision) setSystemUpdates(response);
|
||||
return response;
|
||||
} catch (error) {
|
||||
if (request === coordinator.saveRevision) {
|
||||
console.error("[updates] Failed to save update channel", error);
|
||||
setError(saveErrorMessage);
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
coordinator.activeSaves -= 1;
|
||||
coordinator.readRevision += 1;
|
||||
if (!saved && request === coordinator.saveRevision && coordinator.activeSaves === 0) {
|
||||
revalidateWithoutReplacingError(coordinator, setSystemUpdates);
|
||||
}
|
||||
}
|
||||
})();
|
||||
coordinator.saveTail = operation.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
);
|
||||
return operation;
|
||||
}
|
||||
|
||||
export function useUpdates() {
|
||||
const { t } = useTranslation();
|
||||
const store = useAppStoreApi();
|
||||
const coordinator = coordinatorFor(store);
|
||||
const updates = useAppStore((s) => s.system.updates);
|
||||
const setSystemUpdates = useAppStore((s) => s.setSystemUpdates);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isChecking, setIsChecking] = useState(false);
|
||||
const latestCheck = useRef(0);
|
||||
|
||||
const reload = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await fetchUpdates({ cache: "no-store" });
|
||||
setSystemUpdates(res);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
let flight = coordinator.reloadFlight;
|
||||
if (!flight || flight.request !== coordinator.readRevision) {
|
||||
flight = {
|
||||
request: ++coordinator.readRevision,
|
||||
promise: fetchUpdates({ cache: "no-store" }),
|
||||
published: false,
|
||||
};
|
||||
coordinator.reloadFlight = flight;
|
||||
}
|
||||
}, [setSystemUpdates]);
|
||||
try {
|
||||
const res = await flight.promise;
|
||||
if (
|
||||
!flight.published &&
|
||||
flight.request === coordinator.readRevision &&
|
||||
coordinator.activeSaves === 0
|
||||
) {
|
||||
flight.published = true;
|
||||
setSystemUpdates(res);
|
||||
}
|
||||
} catch (e) {
|
||||
if (flight.request === coordinator.readRevision && coordinator.activeSaves === 0) {
|
||||
setError(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
} finally {
|
||||
if (coordinator.reloadFlight === flight) coordinator.reloadFlight = null;
|
||||
}
|
||||
}, [coordinator, setSystemUpdates]);
|
||||
|
||||
/**
|
||||
* Triggers a server-side re-poll of the GitHub releases endpoint. The
|
||||
* Triggers a server-side re-poll of the selected update channel. The
|
||||
* backend rate-limits this per-process to one call per 30s and replies
|
||||
* with the fresh row (or 429 — surfaced via the returned promise).
|
||||
*/
|
||||
const check = useCallback(async () => {
|
||||
const request = ++coordinator.readRevision;
|
||||
const checkRequest = ++latestCheck.current;
|
||||
setIsChecking(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await checkUpdates();
|
||||
setSystemUpdates(res);
|
||||
if (request === coordinator.readRevision && coordinator.activeSaves === 0) {
|
||||
setSystemUpdates(res);
|
||||
}
|
||||
return res;
|
||||
} catch (e) {
|
||||
if (request !== coordinator.readRevision || coordinator.activeSaves > 0) return undefined;
|
||||
setError(e instanceof Error ? e.message : String(e));
|
||||
if (!store.getState().system.updates) {
|
||||
revalidateWithoutReplacingError(coordinator, setSystemUpdates);
|
||||
}
|
||||
throw e;
|
||||
} finally {
|
||||
setIsChecking(false);
|
||||
if (checkRequest === latestCheck.current) setIsChecking(false);
|
||||
}
|
||||
}, [setSystemUpdates]);
|
||||
}, [coordinator, setSystemUpdates, store]);
|
||||
|
||||
const saveChannel = useCallback(
|
||||
(channel: UpdatesChannel) =>
|
||||
queueChannelSave(
|
||||
coordinator,
|
||||
channel,
|
||||
setSystemUpdates,
|
||||
setError,
|
||||
t("settings:updateChannelSaveFailed"),
|
||||
),
|
||||
[coordinator, setSystemUpdates, t],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (updates) return;
|
||||
void reload();
|
||||
}, [updates, reload]);
|
||||
|
||||
return { updates, isLoading, isChecking, error, reload, check };
|
||||
return { updates, isChecking, error, reload, check, saveChannel };
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
uploadFrontendBundleChunk,
|
||||
fetchUpdates,
|
||||
checkUpdates,
|
||||
saveUpdatesChannel,
|
||||
applyUpdate,
|
||||
fetchSystemJob,
|
||||
fetchRestartCapability,
|
||||
@@ -44,6 +45,7 @@ import {
|
||||
} from "./system-api";
|
||||
|
||||
const BASE = "http://api.test/api/v1/system";
|
||||
const ISO_CHECKED_AT = "2026-05-18T00:00:00Z";
|
||||
|
||||
type FetchInput = Parameters<typeof fetch>[0];
|
||||
type FetchInit = Parameters<typeof fetch>[1];
|
||||
@@ -282,7 +284,7 @@ describe("fetchSystemJob", () => {
|
||||
kind: "vacuum",
|
||||
state: "succeeded",
|
||||
message: "done",
|
||||
started_at: "2026-05-18T00:00:00Z",
|
||||
started_at: ISO_CHECKED_AT,
|
||||
}),
|
||||
);
|
||||
const job = await fetchSystemJob("job-abc");
|
||||
@@ -300,7 +302,7 @@ describe("updates", () => {
|
||||
current: "1.0.0",
|
||||
latest: "1.0.1",
|
||||
latest_url: "https://gh/r",
|
||||
latest_checked_at: "2026-05-18T00:00:00Z",
|
||||
latest_checked_at: ISO_CHECKED_AT,
|
||||
update_available: true,
|
||||
}),
|
||||
);
|
||||
@@ -316,7 +318,7 @@ describe("updates", () => {
|
||||
current: "1.0.0",
|
||||
latest: "1.0.0",
|
||||
latest_url: "",
|
||||
latest_checked_at: "2026-05-18T00:00:00Z",
|
||||
latest_checked_at: ISO_CHECKED_AT,
|
||||
update_available: false,
|
||||
}),
|
||||
);
|
||||
@@ -325,13 +327,38 @@ describe("updates", () => {
|
||||
expect(method()).toBe("POST");
|
||||
});
|
||||
|
||||
it("applyUpdate POSTs /updates/apply with confirmation", async () => {
|
||||
it("saveUpdatesChannel PATCHes the typed channel without allowing init overrides", async () => {
|
||||
fetchSpy.mockResolvedValueOnce(
|
||||
jsonResponse({
|
||||
current: "1.0.0",
|
||||
latest: "1.0.1-nightly.shaabcdef123456",
|
||||
latest_url: "https://www.npmjs.com/package/kandev/v/1.0.1-nightly.shaabcdef123456",
|
||||
latest_checked_at: ISO_CHECKED_AT,
|
||||
update_available: true,
|
||||
channel: "nightly",
|
||||
channel_editable: true,
|
||||
channel_unsupported_reason: "",
|
||||
}),
|
||||
);
|
||||
|
||||
const res = await saveUpdatesChannel("nightly", {
|
||||
init: { method: "GET", body: "caller override" },
|
||||
});
|
||||
const { url, init } = lastCall();
|
||||
|
||||
expect(url).toBe(`${BASE}/updates/channel`);
|
||||
expect((init?.method ?? "").toUpperCase()).toBe("PATCH");
|
||||
expect(init?.body).toBe(JSON.stringify({ channel: "nightly" }));
|
||||
expect(res.channel).toBe("nightly");
|
||||
});
|
||||
|
||||
it("applyUpdate POSTs /updates/apply with confirmation and the displayed target", async () => {
|
||||
fetchSpy.mockResolvedValueOnce(jsonResponse({ job_id: "self-update-1" }));
|
||||
const res = await applyUpdate("UPDATE");
|
||||
const res = await applyUpdate("UPDATE", "v1.0.1");
|
||||
const { url, init } = lastCall();
|
||||
expect(url).toBe(`${BASE}/updates/apply`);
|
||||
expect((init?.method ?? "").toUpperCase()).toBe("POST");
|
||||
expect(init?.body).toBe(JSON.stringify({ confirm: "UPDATE" }));
|
||||
expect(init?.body).toBe(JSON.stringify({ confirm: "UPDATE", target_version: "v1.0.1" }));
|
||||
expect(res.job_id).toBe("self-update-1");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -22,6 +22,7 @@ import type {
|
||||
StorageQuarantineEntry,
|
||||
StorageQuarantinePurgeScope,
|
||||
StorageSettingsResponse,
|
||||
UpdatesChannel,
|
||||
} from "@/lib/types/system";
|
||||
|
||||
const SYSTEM_BASE = "/api/v1/system";
|
||||
@@ -217,14 +218,33 @@ export function checkUpdates(options?: ApiRequestOptions): Promise<UpdatesRespon
|
||||
});
|
||||
}
|
||||
|
||||
export function saveUpdatesChannel(
|
||||
channel: UpdatesChannel,
|
||||
options?: ApiRequestOptions,
|
||||
): Promise<UpdatesResponse> {
|
||||
return fetchJson<UpdatesResponse>(`${SYSTEM_BASE}/updates/channel`, {
|
||||
...options,
|
||||
init: {
|
||||
...(options?.init ?? {}),
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ channel }),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function applyUpdate(
|
||||
confirm = "UPDATE",
|
||||
confirm: string,
|
||||
targetVersion: string,
|
||||
options?: ApiRequestOptions,
|
||||
): Promise<JobAcceptResponse> {
|
||||
return fetchJson<JobAcceptResponse>(`${SYSTEM_BASE}/updates/apply`, {
|
||||
...options,
|
||||
// Spread caller init first so the required method/body can't be overridden.
|
||||
init: { ...(options?.init ?? {}), method: "POST", body: JSON.stringify({ confirm }) },
|
||||
init: {
|
||||
...(options?.init ?? {}),
|
||||
method: "POST",
|
||||
body: JSON.stringify({ confirm, target_version: targetVersion }),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -73,6 +73,9 @@ const UPDATES: UpdatesResponse = {
|
||||
latest_url: "https://github.com/kdlbs/kandev/releases/1.2.4",
|
||||
latest_checked_at: TS,
|
||||
update_available: true,
|
||||
channel: "stable",
|
||||
channel_editable: true,
|
||||
channel_unsupported_reason: "",
|
||||
};
|
||||
|
||||
const JOB: SystemJob = {
|
||||
|
||||
@@ -122,12 +122,17 @@ export interface UpdatesResponse {
|
||||
/** ISO timestamp. */
|
||||
latest_checked_at: string;
|
||||
update_available: boolean;
|
||||
channel: UpdatesChannel;
|
||||
channel_editable: boolean;
|
||||
channel_unsupported_reason: string;
|
||||
install?: InstallState;
|
||||
apply_supported?: boolean;
|
||||
apply_unsupported_reason?: string;
|
||||
manual_commands?: string[];
|
||||
}
|
||||
|
||||
export type UpdatesChannel = "stable" | "nightly";
|
||||
|
||||
export interface InstallState {
|
||||
running_as_service: boolean;
|
||||
managed_service: boolean;
|
||||
|
||||
@@ -37,6 +37,16 @@ function mergeBase(ref, cwd) {
|
||||
return git(["merge-base", ref, "HEAD"], { quiet: true, cwd }).trim();
|
||||
}
|
||||
|
||||
function inProgressBaseMerge(cwd) {
|
||||
try {
|
||||
const mergeHead = git(["rev-parse", "--verify", "MERGE_HEAD"], { quiet: true, cwd }).trim();
|
||||
const baseTip = git(["rev-parse", "--verify", BASE_BRANCH], { quiet: true, cwd }).trim();
|
||||
return mergeHead === baseTip ? mergeHead : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function isAncestor(maybeAncestor, descendant, cwd) {
|
||||
try {
|
||||
git(["merge-base", "--is-ancestor", maybeAncestor, descendant], { quiet: true, cwd });
|
||||
@@ -103,6 +113,17 @@ function forkPointFloor(base, cwd) {
|
||||
export function resolveBase(argv = process.argv, cwd = REPO_ROOT) {
|
||||
const flag = argv.indexOf("--base");
|
||||
const explicit = flag !== -1 && argv[flag + 1] ? argv[flag + 1] : null;
|
||||
|
||||
// During `git merge origin/main`, HEAD is still the PR-side parent until the
|
||||
// merge commit exists. Its normal merge base therefore sits behind main and
|
||||
// misattributes every incoming base-branch change to the PR. Use MERGE_HEAD
|
||||
// only when it exactly matches the fetched base tip; merging another branch
|
||||
// must keep judging that branch's incoming changes.
|
||||
if (!explicit) {
|
||||
const mergeHead = inProgressBaseMerge(cwd);
|
||||
if (mergeHead) return { base: mergeHead };
|
||||
}
|
||||
|
||||
const requested = explicit ?? BASE_BRANCH;
|
||||
|
||||
let base;
|
||||
|
||||
@@ -170,6 +170,25 @@ describe("resolveBase on a pull_request merge ref", () => {
|
||||
});
|
||||
|
||||
describe("resolveBase on other checkout shapes", () => {
|
||||
it("uses the base tip while merging origin/main into a PR branch", () => {
|
||||
const { dir, root } = initRepo();
|
||||
|
||||
git(dir, ["checkout", "-q", "-b", "pr"]);
|
||||
write(dir, OWNED, CLEAN_SOURCE);
|
||||
const prHead = commit(dir, "feat: pr work");
|
||||
|
||||
git(dir, ["checkout", "-q", "main"]);
|
||||
const mainTip = landOnMain(dir);
|
||||
setOriginMain(dir, mainTip);
|
||||
|
||||
git(dir, ["checkout", "-q", prHead]);
|
||||
git(dir, ["merge", "-q", "--no-ff", "--no-commit", mainTip]);
|
||||
|
||||
expect(baseOf(dir, [])).toBe(mainTip);
|
||||
expect(changedFiles(baseOf(dir, []), "A", dir)).toEqual([OWNED]);
|
||||
expect(changedFiles(root, "A", dir)).toContain(FOREIGN);
|
||||
});
|
||||
|
||||
it("floors a rebased branch, which has no merge commit but the same defect", () => {
|
||||
const { dir, root } = initRepo();
|
||||
const mainTip = landOnMain(dir);
|
||||
|
||||
@@ -423,6 +423,24 @@
|
||||
"diagnosticZipDownloading": "Your diagnostic ZIP is downloading.",
|
||||
"diagnosticPartialZipDownloading": "A partial ZIP is downloading: {{warnings}}",
|
||||
"diagnosticPartialZipUnavailable": "A partial diagnostic ZIP is downloading; some frontend logs were unavailable.",
|
||||
"updateChannel": "Update channel",
|
||||
"updateChannelDescription": "Choose which releases this managed service checks and applies.",
|
||||
"updateChannelRequiresManagedService": "Nightly updates require a Kandev-managed npm or npx user service.",
|
||||
"updateChannelRequiresNpmInstallation": "Nightly updates are only available for npm or npx installations.",
|
||||
"updateChannelRequiresServiceMetadata": "Nightly updates require valid Kandev service metadata.",
|
||||
"updateChannelRequiresUserService": "Nightly updates are only available for user services.",
|
||||
"updateChannelSettingsUnavailable": "Update channel settings are unavailable.",
|
||||
"updateChannelStable": "Stable",
|
||||
"updateChannelStableDescription": "Signed GitHub releases. Recommended for most users.",
|
||||
"updateChannelNightly": "Nightly",
|
||||
"updateChannelNightlyDescription": "Install-wide prerelease builds from main via npm. Apply uses the exact version shown.",
|
||||
"updateChannelSaveFailed": "Could not save the update channel. Try again.",
|
||||
"updateChannelSavingNotice": "Saving channel change before checking or applying an update.",
|
||||
"updateChannelUnsavedNotice": "Save channel changes before checking or applying an update.",
|
||||
"updateChannelUnavailable": "The Nightly update channel is unavailable for this installation.",
|
||||
"updateChannelUnsupportedServiceManager": "This service manager does not support nightly updates.",
|
||||
"updateChannelLatestNightly": "Latest nightly",
|
||||
"updateChannelLatestRelease": "Latest release",
|
||||
"externalMcpIntro": "Use this if you want to manage Kandev from coding agents that run <2>outside</2> Kandev (e.g. Claude Code, Cursor, or Codex on your host), or from <4>passthrough agents</4> running inside Kandev.",
|
||||
"externalMcpIntroPassthrough": "Agents launched inside Kandev in their normal mode already have the Kandev MCP wired in automatically, no setup needed.",
|
||||
"externalMcpEndpoints": "Endpoints",
|
||||
|
||||
@@ -383,7 +383,6 @@
|
||||
"updatesApplyConfirmDesktop": "Kandev will install {{version}} and restart the desktop app.",
|
||||
"updatesApplyConfirmService": "Kandev will update to {{version}}, reinstall the user service, and restart it.",
|
||||
"updatesApplyConfirmTitle": "Apply update?",
|
||||
"updatesCheckFailed": "Update check failed",
|
||||
"updatesCheckNow": "Check now",
|
||||
"updatesCurrentVersion": "Current version",
|
||||
"updatesDownloading": "Downloading update ({{downloaded}} bytes)...",
|
||||
|
||||
@@ -423,6 +423,24 @@
|
||||
"diagnosticZipDownloading": "Ŷōũŕ ďĩàĝńōśţĩć ŹĨƤ ĩś ďōŵńĺōàďĩńĝ.",
|
||||
"diagnosticPartialZipDownloading": "À ƥàŕţĩàĺ ŹĨƤ ĩś ďōŵńĺōàďĩńĝ: {{warnings}}",
|
||||
"diagnosticPartialZipUnavailable": "À ƥàŕţĩàĺ ďĩàĝńōśţĩć ŹĨƤ ĩś ďōŵńĺōàďĩńĝ; śōḿē ƒŕōńţēńď ĺōĝś ŵēŕē ũńàvàĩĺàƀĺē.",
|
||||
"updateChannel": "Ũƥďàţē ćĥàńńēĺ",
|
||||
"updateChannelDescription": "Ćĥōōśē ŵĥĩćĥ ŕēĺēàśēś ţĥĩś ḿàńàĝēď śēŕvĩćē ćĥēćķś àńď àƥƥĺĩēś.",
|
||||
"updateChannelRequiresManagedService": "Ńĩĝĥţĺŷ ũƥďàţēś ŕēqũĩŕē à Ķàńďēv-ḿàńàĝēď ńƥḿ ōŕ ńƥx ũśēŕ śēŕvĩćē.",
|
||||
"updateChannelRequiresNpmInstallation": "Ńĩĝĥţĺŷ ũƥďàţēś àŕē ōńĺŷ àvàĩĺàƀĺē ƒōŕ ńƥḿ ōŕ ńƥx ĩńśţàĺĺàţĩōńś.",
|
||||
"updateChannelRequiresServiceMetadata": "Ńĩĝĥţĺŷ ũƥďàţēś ŕēqũĩŕē vàĺĩď Ķàńďēv śēŕvĩćē ḿēţàďàţà.",
|
||||
"updateChannelRequiresUserService": "Ńĩĝĥţĺŷ ũƥďàţēś àŕē ōńĺŷ àvàĩĺàƀĺē ƒōŕ ũśēŕ śēŕvĩćēś.",
|
||||
"updateChannelSettingsUnavailable": "Ũƥďàţē ćĥàńńēĺ śēţţĩńĝś àŕē ũńàvàĩĺàƀĺē.",
|
||||
"updateChannelStable": "Śţàƀĺē",
|
||||
"updateChannelStableDescription": "Śĩĝńēď ĜĩţĤũƀ ŕēĺēàśēś. Ŕēćōḿḿēńďēď ƒōŕ ḿōśţ ũśēŕś.",
|
||||
"updateChannelNightly": "Ńĩĝĥţĺŷ",
|
||||
"updateChannelNightlyDescription": "Ĩńśţàĺĺ-ŵĩďē ƥŕēŕēĺēàśē ƀũĩĺďś ƒŕōḿ ḿàĩń vĩà ńƥḿ. Àƥƥĺŷ ũśēś ţĥē ēxàćţ vēŕśĩōń śĥōŵń.",
|
||||
"updateChannelSaveFailed": "Ćōũĺď ńōţ śàvē ţĥē ũƥďàţē ćĥàńńēĺ. Ţŕŷ àĝàĩń.",
|
||||
"updateChannelSavingNotice": "Śàvĩńĝ ćĥàńńēĺ ćĥàńĝē ƀēƒōŕē ćĥēćķĩńĝ ōŕ àƥƥĺŷĩńĝ àń ũƥďàţē.",
|
||||
"updateChannelUnsavedNotice": "Śàvē ćĥàńńēĺ ćĥàńĝēś ƀēƒōŕē ćĥēćķĩńĝ ōŕ àƥƥĺŷĩńĝ àń ũƥďàţē.",
|
||||
"updateChannelUnavailable": "Ţĥē Ńĩĝĥţĺŷ ũƥďàţē ćĥàńńēĺ ĩś ũńàvàĩĺàƀĺē ƒōŕ ţĥĩś ĩńśţàĺĺàţĩōń.",
|
||||
"updateChannelUnsupportedServiceManager": "Ţĥĩś śēŕvĩćē ḿàńàĝēŕ ďōēś ńōţ śũƥƥōŕţ ńĩĝĥţĺŷ ũƥďàţēś.",
|
||||
"updateChannelLatestNightly": "Ĺàţēśţ ńĩĝĥţĺŷ",
|
||||
"updateChannelLatestRelease": "Ĺàţēśţ ŕēĺēàśē",
|
||||
"externalMcpIntro": "Ũśē ţĥĩś ĩƒ ŷōũ ŵàńţ ţō ḿàńàĝē Ķàńďēv ƒŕōḿ ćōďĩńĝ àĝēńţś ţĥàţ ŕũń <2>ōũţśĩďē</2> Ķàńďēv (ē.ĝ. Ćĺàũďē Ćōďē, Ćũŕśōŕ, ōŕ Ćōďēx ōń ŷōũŕ ĥōśţ), ōŕ ƒŕōḿ <4>ƥàśśţĥŕōũĝĥ àĝēńţś</4> ŕũńńĩńĝ ĩńśĩďē Ķàńďēv.",
|
||||
"externalMcpIntroPassthrough": "Àĝēńţś ĺàũńćĥēď ĩńśĩďē Ķàńďēv ĩń ţĥēĩŕ ńōŕḿàĺ ḿōďē àĺŕēàďŷ ĥàvē ţĥē Ķàńďēv ḾĆƤ ŵĩŕēď ĩń àũţōḿàţĩćàĺĺŷ, ńō śēţũƥ ńēēďēď.",
|
||||
"externalMcpEndpoints": "Ēńďƥōĩńţś",
|
||||
|
||||
@@ -383,7 +383,6 @@
|
||||
"updatesApplyConfirmDesktop": "Ķàńďēv ŵĩĺĺ ĩńśţàĺĺ {{version}} àńď ŕēśţàŕţ ţĥē ďēśķţōƥ àƥƥ.",
|
||||
"updatesApplyConfirmService": "Ķàńďēv ŵĩĺĺ ũƥďàţē ţō {{version}}, ŕēĩńśţàĺĺ ţĥē ũśēŕ śēŕvĩćē, àńď ŕēśţàŕţ ĩţ.",
|
||||
"updatesApplyConfirmTitle": "Àƥƥĺŷ ũƥďàţē?",
|
||||
"updatesCheckFailed": "Ũƥďàţē ćĥēćķ ƒàĩĺēď",
|
||||
"updatesCheckNow": "Ćĥēćķ ńōŵ",
|
||||
"updatesCurrentVersion": "Ćũŕŕēńţ vēŕśĩōń",
|
||||
"updatesDownloading": "Ďōŵńĺōàďĩńĝ ũƥďàţē ({{downloaded}} ƀŷţēś)...",
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
# ADR-2026-07-31-npm-nightly-release-channel: Publish deterministic npm-only nightlies
|
||||
|
||||
**Status:** accepted (amended 2026-08-03)
|
||||
**Date:** 2026-07-31
|
||||
**Area:** workflow, backend, frontend, cli
|
||||
|
||||
## Context
|
||||
|
||||
Kandev's stable release workflow intentionally gives npm, Homebrew, GitHub Releases, Desktop, and
|
||||
containers one shared `X.Y.Z`. Users also need prerelease access to current `main`, but Homebrew
|
||||
and Desktop require separate mutable-feed and signing designs. npm already has six coordinated
|
||||
packages, trusted publishing bound to `.github/workflows/release.yml`, and native dist-tags.
|
||||
|
||||
A commit-derived prerelease must be deterministic for retries and valid even when the abbreviated
|
||||
SHA is digits-only or begins with zero. Update discovery must not sort SHA text as time.
|
||||
|
||||
## Decision
|
||||
|
||||
Kandev has an npm-only `nightly` channel. A stable baseline `X.Y.Z` and current `main` SHA produce
|
||||
`X.Y.(Z+1)-nightly.sha{first-12-lowercase-hex}`. Time and git-describe's `g` marker are excluded:
|
||||
the commit is the identity, and the `sha` prefix makes the SemVer identifier unambiguously
|
||||
nonnumeric.
|
||||
|
||||
The 12-hex abbreviation is an accepted compactness trade-off. Before an already-published version
|
||||
can skip a run, the workflow resolves the abbreviation against full `main` history and requires the
|
||||
resolved commit to equal the scheduled SHA. Git rejects an ambiguous abbreviation, so a prefix
|
||||
collision fails closed for maintainer resolution rather than silently treating a different commit
|
||||
as published.
|
||||
|
||||
The existing release workflow owns both stable and nightly npm publication because npm allows one
|
||||
trusted publisher per package and validates the workflow filename. Its manual dispatch defaults to
|
||||
Stable but also permits a Nightly run from `main`; the scheduled and manual Nightly paths use the
|
||||
same metadata, build, and publish jobs. Manual Nightly dry runs execute the real metadata and
|
||||
registry preflight, then stop before builds or npm writes. The workflow's required Stable bump
|
||||
selector is ignored for Nightly, while Stable-only desktop validation and backfill inputs are
|
||||
rejected instead of silently changing the requested operation.
|
||||
|
||||
Nightlies publish all five runtime packages before the launcher with
|
||||
`npm publish --tag nightly`; stable `latest` tags remain untouched. The publisher and Nightly
|
||||
preflight load one shared package inventory. Nightly jobs do not enter the Git tag, GitHub Release,
|
||||
Desktop, container, or Homebrew graph. Stable and Nightly workflow runs share one non-cancelling
|
||||
concurrency group from start through publication.
|
||||
This release-wide lock is required because Stable pushes its Git tag before its npm publish job is
|
||||
ready; locking only the two npm jobs leaves a window where Nightly can derive from the previous npm
|
||||
baseline. Before building and again before publishing, Nightly requires the highest stable Git tag
|
||||
to match npm `latest`. A scheduled commit superseded by that Stable tag exits successfully.
|
||||
|
||||
A Nightly target must be newer in `main` ancestry than the published Nightly unless the current
|
||||
target is incomplete and needs repair. An older partial runtime publication is recoverable only
|
||||
when its embedded commit is an ancestor of current `main`. Divergent or newer partial tags fail
|
||||
closed. Before publishing, both the Stable baseline and previously observed Nightly tag must still
|
||||
match.
|
||||
|
||||
The backend owns an install-wide Stable/Nightly preference. Stable remains the default and resolves
|
||||
GitHub Releases. Nightly resolves npm's `kandev@nightly` target and is selectable only for verified
|
||||
managed npm/npx user services. Update intents always contain an exact version. Nightly-to-nightly
|
||||
availability follows dist-tag inequality, not SemVer ordering of SHA text. Apply requests bind to
|
||||
the exact cached version shown to the user; if discovery has since changed that cache, the backend
|
||||
rejects the stale target instead of re-resolving or installing a different artifact.
|
||||
|
||||
## Consequences
|
||||
|
||||
Users get one documented prerelease path without weakening stable channels or Desktop signing.
|
||||
One full commit deterministically maps to one immutable version, making scheduled retries safe and
|
||||
observable. A collision in the accepted 12-hex namespace blocks automatic publication and needs
|
||||
maintainer resolution. Publishing six packages can still fail partially, so
|
||||
runtime-first/main-last order and tag-consistency checks are required.
|
||||
|
||||
npm accumulates immutable nightly versions. Homebrew and Desktop users do not receive channel
|
||||
parity in this iteration. The release workflow must explicitly gate every stable-only job when
|
||||
handling Nightly events. The shared dispatch form still displays Stable-only inputs for a manual
|
||||
Nightly, so validation and input descriptions must keep their meaning explicit. A manual Stable
|
||||
release can wait for an in-flight Nightly workflow; Nightlies also wait behind a Stable run,
|
||||
including any release-environment approval. Queued Nightlies whose selected commit was superseded
|
||||
by the completed Stable release skip.
|
||||
|
||||
## Alternatives Considered
|
||||
|
||||
- **Timestamp plus SHA:** gives chronological SemVer ordering but creates different immutable
|
||||
versions for the same commit and complicates retries.
|
||||
- **Raw abbreviated SHA:** can become a numeric SemVer identifier with an illegal leading zero;
|
||||
`sha` is a small explicit validity guard.
|
||||
- **Full 40-hex SHA:** eliminates abbreviation collisions but makes every user-visible package
|
||||
version substantially longer; the shorter identity plus fail-closed ambiguity check is preferred.
|
||||
- **Separate scheduled or manual Nightly workflow:** cleaner YAML isolation, but it conflicts with
|
||||
npm's single trusted publisher configuration for the existing six packages and would duplicate
|
||||
the Nightly safety state machine.
|
||||
- **Serialize only npm publish jobs:** permits more build overlap, but Stable creates its tag before
|
||||
its npm job enters that lock, allowing Nightly to derive from a stale npm baseline.
|
||||
- **GitHub prereleases:** would duplicate stable release artifacts and feeds when npm is the only
|
||||
requested consumer.
|
||||
- **Homebrew `HEAD` or a nightly formula:** viable future designs, but they need source builds or a
|
||||
separate mutable formula/tap and do not match the current immutable-asset formula.
|
||||
@@ -93,6 +93,7 @@ Read individual ADRs for full context. Create new ones via `/record decision` or
|
||||
| 2026-07-30-session-owned-mcp-observability | [Keep MCP Attachment Evidence Session Owned](2026-07-30-session-owned-mcp-observability.md) | accepted | backend, frontend, protocol, security | 2026-07-30 |
|
||||
| 2026-07-30-file-backed-diagnostic-bundles | [File-backed diagnostic bundles](2026-07-30-file-backed-diagnostic-bundles.md) | accepted | backend, frontend, infra, protocol, workflow | 2026-07-30 |
|
||||
| 2026-07-30-runtime-task-state-before-running-event | [Publish Task State Before Running Session State](2026-07-30-runtime-task-state-before-running-event.md) | accepted | backend, frontend, protocol, workflow | 2026-07-30 |
|
||||
| 2026-07-31-npm-nightly-release-channel | [Publish deterministic npm-only nightlies](2026-07-31-npm-nightly-release-channel.md) | accepted (amended 2026-08-03) | workflow, backend, frontend, cli | 2026-07-31 |
|
||||
| 2026-07-31-isolate-manual-pr-review-content | [Isolate Manual PR Review Content](2026-07-31-isolate-manual-pr-review-content.md) | accepted | infra, workflow, security | 2026-07-31 |
|
||||
| 2026-07-31-agent-generated-task-titles | [Bind Agent Title Generation to Pending Tasks](2026-07-31-agent-generated-task-titles.md) | accepted | backend, frontend, protocol | 2026-07-31 |
|
||||
| 2026-07-31-system-service-user-continuity | [Preserve System Service Identity Across Reinstallation](2026-07-31-system-service-user-continuity.md) | accepted | backend, cli, security, operations | 2026-07-31 |
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
---
|
||||
spec: docs/specs/npm-nightly-channel/spec.md
|
||||
created: 2026-07-31
|
||||
status: implemented
|
||||
---
|
||||
|
||||
# Implementation Plan: npm nightly channel
|
||||
|
||||
## Overview
|
||||
|
||||
First make versioning and npm publication deterministic and testable, then add the scheduled branch
|
||||
without allowing it into stable release jobs. Next add channel-aware backend discovery and exact
|
||||
apply semantics, then the responsive setting, E2E proof, and public operating docs.
|
||||
|
||||
## Release automation
|
||||
|
||||
### Version and publisher
|
||||
|
||||
`scripts/release/nightly-version.mjs` validates a stable baseline plus full SHA and emits the next
|
||||
patch prerelease. `scripts/release/publish-npm.sh` accepts explicit version, dist-tag, and either a
|
||||
GitHub release tag or local assets. It sets the runner checkout's launcher version, pins all five
|
||||
optional dependencies, publishes runtimes first, and publishes the launcher last.
|
||||
|
||||
### Workflow
|
||||
|
||||
`.github/workflows/release.yml` gains cron `0 12 * * *`, a Stable/Nightly manual channel selector,
|
||||
a read-only nightly metadata job, shared web/runtime builds, and an OIDC npm publish job. Manual
|
||||
Nightly runs are limited to `main`; their dry-run mode performs preflight without building or
|
||||
publishing. All stable-only jobs require the Stable channel. Non-cancelling concurrency serializes
|
||||
complete Stable and Nightly runs so a pending Stable tag cannot race npm, and Nightly rechecks the
|
||||
stable Git/npm baseline plus the starting `nightly` tag before publication.
|
||||
|
||||
## Backend
|
||||
|
||||
`apps/backend/internal/system/updates/channel.go` owns typed channel validation, the install-wide
|
||||
`updates_channel` setting, and capability checks. `npm.go` resolves and validates the public npm
|
||||
metadata. `Service` selects a resolver and isolated cache for `Get`, `Check`, poller, notification,
|
||||
and apply paths. `PATCH /updates/channel` is mounted on the existing admin group.
|
||||
|
||||
`apps/backend/internal/persistence/meta.go` retains stable keys and adds explicit nightly keys.
|
||||
Channel-aware availability treats npm's dist-tag as authoritative between nightlies while keeping
|
||||
ordinary stable comparisons and avoiding downgrade notifications.
|
||||
|
||||
## Frontend
|
||||
|
||||
`apps/web/lib/types/system.ts`, `system-api.ts`, and `use-updates.ts` carry the channel contract and
|
||||
save mutation. `updates-card.tsx` registers a settings-save contributor and renders full-row Stable
|
||||
and Nightly choices with server-owned capability reasons.
|
||||
|
||||
### Mobile design contract
|
||||
|
||||
The entry point remains the direct Settings > System > Updates route. The selector is a short,
|
||||
one-dimensional setting, so both desktop and phone use an inline card rather than a drawer. The
|
||||
page remains the single scroll owner. Rows follow
|
||||
`mcp-task-agent-profile-default-settings.tsx`, use at least 44px height, wrap the immutable version,
|
||||
and expose no hover-only action. Shared hook/state logic owns both viewports. A `mobile-chrome`
|
||||
Pixel 5 test proves select, save, reload, and zero horizontal overflow.
|
||||
|
||||
## Tests
|
||||
|
||||
- **Version identity:** valid/invalid baselines, numeric SHA prefixes, and deterministic repeat.
|
||||
**File:** `scripts/release/nightly-version.test.mjs`. **How:** Node unit tests.
|
||||
- **Publisher/workflow contract:** source exclusivity, exact package order, dist-tags, schedule,
|
||||
event gates, and no stable side effects. **File:** `apps/cli/src/release-config.test.ts` and
|
||||
`.github/scripts/release-workflow-contract_test.py`. **How:** fixture/static contract tests.
|
||||
- **Registry resolver:** valid tag, missing tag/version, malformed SemVer, HTTP failures.
|
||||
**File:** `apps/backend/internal/system/updates/npm_test.go`. **How:** `httptest.Server`.
|
||||
- **Persistence and service:** default/invalid channel, isolated cache, restart, comparisons,
|
||||
polling, notification, and apply exactness. **Files:** update and persistence `*_test.go`.
|
||||
**How:** real in-memory SQLite plus injected resolvers.
|
||||
- **HTTP:** admin PATCH success, invalid `400`, unsupported `409`, and resolver failure.
|
||||
**File:** `apps/backend/internal/system/updates/handler_test.go`. **How:** Gin integration tests.
|
||||
- **Frontend contract:** request shape, draft/save/discard, disabled reason, and exact target.
|
||||
**Files:** `system-api.test.ts`, `updates-card.test.tsx`. **How:** Vitest with complete response
|
||||
fixtures.
|
||||
|
||||
## E2E Tests
|
||||
|
||||
- **Scenario:** a managed npm service selects Nightly, saves, reloads, and applies the resolved exact
|
||||
version. **File:** `apps/web/e2e/tests/system/updates-channel.spec.ts`.
|
||||
- **Scenario:** the same selection and persistence work at Pixel 5 width with 44px rows and no
|
||||
horizontal overflow. **File:** `apps/web/e2e/tests/system/mobile-updates-page.spec.ts`.
|
||||
- **Scenario:** an unsupported install stays Stable and explains why. **Files:** both specs where
|
||||
the fixture can expose the install kind.
|
||||
|
||||
## Implementation waves
|
||||
|
||||
Wave 1:
|
||||
|
||||
- [x] [Task 01 — Version and npm publisher](task-01-version-and-publisher.md)
|
||||
|
||||
Wave 2:
|
||||
|
||||
- [x] [Task 02 — Scheduled release workflow](task-02-release-workflow.md)
|
||||
- [x] [Task 03 — Backend channel foundation](task-03-backend-channel-foundation.md)
|
||||
|
||||
Wave 3:
|
||||
|
||||
- [x] [Task 04 — Backend API and apply semantics](task-04-backend-api-apply.md)
|
||||
|
||||
Wave 4:
|
||||
|
||||
- [x] [Task 05 — Responsive Updates setting](task-05-updates-channel-ui.md)
|
||||
|
||||
Wave 5:
|
||||
|
||||
- [x] [Task 06 — Desktop and mobile E2E](task-06-updates-channel-e2e.md)
|
||||
|
||||
Wave 6:
|
||||
|
||||
- [x] [Task 07 — Public docs and final records](task-07-docs-and-records.md)
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
id: "01-version-and-publisher"
|
||||
title: "Version and npm publisher"
|
||||
status: completed
|
||||
wave: 1
|
||||
depends_on: []
|
||||
plan: "plan.md"
|
||||
spec: "../../specs/npm-nightly-channel/spec.md"
|
||||
---
|
||||
|
||||
# Task 01: Version and npm publisher
|
||||
|
||||
- **Acceptance:** The helper deterministically emits `X.Y.(Z+1)-nightly.sha{12-hex}` and rejects
|
||||
malformed inputs.
|
||||
- **Acceptance:** The publisher accepts stable release assets or local nightly assets, publishes
|
||||
all five exact runtime packages before `kandev`, and applies the requested dist-tag.
|
||||
- **Acceptance:** Nightly retries accept only already-published versions whose `nightly` tags match.
|
||||
- **Acceptance:** Scheduled preflight and publishing share one package inventory; an older partial
|
||||
publication is recoverable only when its embedded commit is an ancestor of current `main`.
|
||||
- **Verification:** `node --test scripts/release/nightly-version.test.mjs`
|
||||
- **Verification:** `node --test scripts/release/publish-npm.test.mjs`
|
||||
- **Verification:** `cd apps && pnpm --filter kandev exec vitest run src/release-config.test.ts src/service/self_update.test.ts`
|
||||
- **Files likely touched:** `scripts/release/nightly-version.mjs`, its test,
|
||||
`scripts/release/npm-packages.sh`,
|
||||
`scripts/release/publish-npm.sh`, `apps/cli/src/release-config.test.ts`,
|
||||
`apps/cli/src/service/self_update.test.ts`.
|
||||
- **Dependencies:** None.
|
||||
- **Parallelism:** sequential.
|
||||
- **Inputs:** spec publication scenarios; current `publish-npm.sh` and
|
||||
`package-npm-runtime.sh` behavior.
|
||||
- **Risks:** npm trusted-publisher OIDC cannot repair dist-tags outside `npm publish`.
|
||||
|
||||
## Verification results
|
||||
|
||||
- `node --test scripts/release/nightly-version.test.mjs` — passed, 6 tests.
|
||||
- `node --test scripts/release/publish-npm.test.mjs` — passed, 8 tests.
|
||||
- `cd apps && pnpm --filter kandev exec vitest run src/release-config.test.ts src/service/self_update.test.ts`
|
||||
— passed, 24 tests.
|
||||
- `bash -n scripts/release/publish-npm.sh` — passed.
|
||||
@@ -0,0 +1,50 @@
|
||||
---
|
||||
id: "02-release-workflow"
|
||||
title: "Scheduled and manual Nightly release workflow"
|
||||
status: completed
|
||||
wave: 2
|
||||
depends_on: ["01-version-and-publisher"]
|
||||
plan: "plan.md"
|
||||
spec: "../../specs/npm-nightly-channel/spec.md"
|
||||
---
|
||||
|
||||
# Task 02: Scheduled and manual Nightly release workflow
|
||||
|
||||
- **Acceptance:** `release.yml` schedules exact noon UTC and skips unchanged/already-published
|
||||
commits before building.
|
||||
- **Acceptance:** Maintainers can select the Nightly channel on a manual `main` dispatch; it follows
|
||||
the same metadata, build, and publication path as the schedule.
|
||||
- **Acceptance:** Manual Nightly dry-run executes metadata/registry preflight but no builds or npm
|
||||
writes; desktop validation and backfill are rejected, and the Stable bump selector is ignored.
|
||||
- **Acceptance:** Nightly reaches only web/runtime builds and nightly npm publication; every Stable
|
||||
GitHub/Desktop/GHCR/Homebrew mutation requires the Stable channel.
|
||||
- **Acceptance:** Publication uses the exact checked-out SHA; complete Stable and Nightly workflow
|
||||
runs are serialized so a pending Stable tag cannot race npm publication.
|
||||
- **Acceptance:** Preflight and publish skip when the stable Git/npm baseline disagrees or the
|
||||
observed Nightly tag moved, preventing stale or backward tag movement.
|
||||
- **Acceptance:** An older scheduled rerun is skipped before building when a complete Nightly from
|
||||
a newer commit exists; an incomplete current target and ancestor-tagged older partial publishes
|
||||
are repaired, while unresolvable, divergent, or newer partial tag history fails closed.
|
||||
- **Acceptance:** Workflow preflight and the npm publisher consume one shared package inventory.
|
||||
- **Acceptance:** Registry verification remains fail-closed after three bounded attempts so one
|
||||
transient lookup failure does not abort the scheduled publish.
|
||||
- **Verification:** `python3 .github/scripts/release-workflow-contract_test.py`
|
||||
- **Verification:** `node --test scripts/release/npm-view-version.test.mjs`
|
||||
- **Verification:** `cd apps && pnpm --filter kandev exec vitest run src/release-config.test.ts`
|
||||
- **Verification:** `make test-scripts`
|
||||
- **Files likely touched:** `.github/workflows/release.yml`,
|
||||
`.github/scripts/release-workflow-contract_test.py`, `apps/cli/src/release-config.test.ts`,
|
||||
`scripts/release/npm-packages.sh`, `scripts/release/npm-view-version.sh`,
|
||||
`scripts/release/npm-view-version.test.mjs`, `Makefile`.
|
||||
- **Dependencies:** Task 01.
|
||||
- **Parallelism:** sequential because the workflow consumes Task 01's interface.
|
||||
- **Inputs:** spec schedule/publication scenarios; existing `prepare`, `build-web`,
|
||||
`build-bundles`, and `publish-npm` jobs.
|
||||
- **Risks:** an incomplete event gate could trigger stable side effects from cron.
|
||||
|
||||
## Verification results
|
||||
|
||||
- `python3 .github/scripts/release-workflow-contract_test.py` — passed, 22 tests.
|
||||
- `node --test scripts/release/npm-view-version.test.mjs` — passed, 5 tests.
|
||||
- `cd apps && pnpm --filter kandev exec vitest run src/release-config.test.ts` — passed, 13 tests.
|
||||
- `make test-scripts` — passed, including both release workflow suites.
|
||||
@@ -0,0 +1,33 @@
|
||||
---
|
||||
id: "03-backend-channel-foundation"
|
||||
title: "Backend channel foundation"
|
||||
status: completed
|
||||
wave: 2
|
||||
depends_on: ["01-version-and-publisher"]
|
||||
plan: "plan.md"
|
||||
spec: "../../specs/npm-nightly-channel/spec.md"
|
||||
---
|
||||
|
||||
# Task 03: Backend channel foundation
|
||||
|
||||
- **Acceptance:** Stable is the durable default, Nightly persists install-wide, and stable/nightly
|
||||
caches never leak across channels.
|
||||
- **Acceptance:** npm metadata resolution validates `dist-tags.nightly`, its exact version record,
|
||||
and SemVer before returning a target.
|
||||
- **Acceptance:** availability handles unequal nightly SHAs without lexical ordering and preserves
|
||||
normal stable comparisons.
|
||||
- **Verification:** `cd apps/backend && go test -v ./internal/persistence ./internal/system/updates`
|
||||
- **Files likely touched:** `apps/backend/internal/persistence/meta.go`,
|
||||
`apps/backend/internal/system/updates/channel.go`, `npm.go`, `service.go`, `poller.go`, and
|
||||
colocated tests.
|
||||
- **Dependencies:** Task 01 defines the recognized nightly version.
|
||||
- **Parallelism:** sequential in the primary conversation.
|
||||
- **Inputs:** spec data model, failure modes, persistence guarantees, and channel scenarios.
|
||||
- **Risks:** stale registry data and SHA prerelease ordering must fail safely.
|
||||
|
||||
## Verification results
|
||||
|
||||
- `cd apps/backend && go test -v ./internal/persistence ./internal/system/updates` — passed;
|
||||
the local PostgreSQL cases skipped because `KANDEV_TEST_POSTGRES_DSN` was unset.
|
||||
- `Backend Postgres` CI — exercises stable/nightly cache isolation with
|
||||
`KANDEV_TEST_POSTGRES_DSN` through `internal/persistence/postgres_meta_test.go`.
|
||||
@@ -0,0 +1,37 @@
|
||||
---
|
||||
id: "04-backend-api-apply"
|
||||
title: "Backend API and apply semantics"
|
||||
status: completed
|
||||
wave: 3
|
||||
depends_on: ["03-backend-channel-foundation"]
|
||||
plan: "plan.md"
|
||||
spec: "../../specs/npm-nightly-channel/spec.md"
|
||||
---
|
||||
|
||||
# Task 04: Backend API and apply semantics
|
||||
|
||||
- **Acceptance:** Updates responses expose effective channel capability, and admin PATCH persists a
|
||||
valid supported selection while returning `400`/`409` for invalid/unsupported requests.
|
||||
- **Acceptance:** `Get`, `Check`, poller, notifications, and manual commands use the selected
|
||||
channel; apply binds to the submitted cached target, returns 409 if stale, and installs the exact
|
||||
immutable version; downgrade-like channel returns are not sent as normal upgrade notifications.
|
||||
- **Acceptance:** verified npm/npx user services can use Nightly; all other install kinds remain
|
||||
Stable.
|
||||
- **Acceptance:** update-status read failures are logged with their internal detail while the API
|
||||
returns a generic error body.
|
||||
- **Verification:** `cd apps/backend && go test -v ./internal/system/...`
|
||||
- **Verification:** `cd apps && pnpm --filter kandev exec vitest run src/service/self_update.test.ts`
|
||||
- **Files likely touched:** `apps/backend/internal/system/system.go`, updates `handler.go`,
|
||||
`install_state.go`, `apply.go`, service/poller tests, and `apps/cli/src/service/self_update.test.ts`.
|
||||
- **Dependencies:** Task 03.
|
||||
- **Parallelism:** sequential.
|
||||
- **Inputs:** spec API, permissions, supported-install, and exact-apply scenarios.
|
||||
- **Risks:** persisted preference, effective capability, apply preflight, and notification policy
|
||||
must agree from one install snapshot.
|
||||
|
||||
## Verification results
|
||||
|
||||
- `cd apps/backend && go test -v ./internal/system/...` — passed; environment-specific tests for
|
||||
`xdg-open` and PostgreSQL skipped with their documented prerequisites absent.
|
||||
- `cd apps && pnpm --filter kandev exec vitest run src/service/self_update.test.ts` — passed,
|
||||
11 tests.
|
||||
@@ -0,0 +1,41 @@
|
||||
---
|
||||
id: "05-updates-channel-ui"
|
||||
title: "Responsive Updates setting"
|
||||
status: completed
|
||||
wave: 4
|
||||
depends_on: ["04-backend-api-apply"]
|
||||
plan: "plan.md"
|
||||
spec: "../../specs/npm-nightly-channel/spec.md"
|
||||
---
|
||||
|
||||
# Task 05: Responsive Updates setting
|
||||
|
||||
- **Acceptance:** Stable/Nightly uses the shared settings Save/Revert coordinator and persists via
|
||||
the typed PATCH API.
|
||||
- **Acceptance:** server capability reasons disable Nightly for unsupported installs while Desktop
|
||||
keeps its signed stable updater.
|
||||
- **Acceptance:** inline rows are keyboard accessible, at least 44px high on phone, and long target
|
||||
versions cannot create document overflow.
|
||||
- **Acceptance:** a save response cannot overwrite a newer channel draft, and save failures replace
|
||||
stale manual-check errors while leaving the draft retryable.
|
||||
- **Acceptance:** all `useUpdates` instances sharing one Zustand store coordinate read/save
|
||||
authority so an older response cannot overwrite a newer saved channel.
|
||||
- **Acceptance:** channel PATCH requests are serialized in invocation order, and update actions
|
||||
remain blocked for the full save even when a newer draft temporarily matches the old baseline.
|
||||
- **Verification:** `cd apps && pnpm --filter @kandev/web exec vitest run lib/api/domains/system-api.test.ts hooks/domains/system/use-updates.test.ts components/settings/system/updates-card.test.tsx`
|
||||
- **Verification:** `cd apps/web && pnpm run typecheck`
|
||||
- **Files likely touched:** `apps/web/lib/types/system.ts`, `lib/api/domains/system-api.ts`,
|
||||
`hooks/domains/system/use-updates.ts`, `components/settings/system/updates-card.tsx`, an extracted
|
||||
channel control if needed, and focused tests.
|
||||
- **Dependencies:** Task 04 response/API contract.
|
||||
- **Parallelism:** sequential.
|
||||
- **Inputs:** plan mobile design contract and spec UI scenarios.
|
||||
- **Risks:** conditional Desktop composition must not conditionally invoke hooks; failed saves must
|
||||
reject and preserve a discardable authoritative baseline.
|
||||
|
||||
## Verification results
|
||||
|
||||
- `cd apps && pnpm --filter @kandev/web exec vitest run lib/api/domains/system-api.test.ts hooks/domains/system/use-updates.test.ts components/settings/system/updates-card.test.tsx`
|
||||
— passed, 56 tests, including cross-instance stale-read, serialized-save, and save-gating races.
|
||||
- `cd apps/web && pnpm run typecheck` — passed.
|
||||
- Focused ESLint for the changed frontend unit/API files — passed with no warnings.
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
id: "06-updates-channel-e2e"
|
||||
title: "Desktop and mobile E2E"
|
||||
status: completed
|
||||
wave: 5
|
||||
depends_on: ["05-updates-channel-ui"]
|
||||
plan: "plan.md"
|
||||
spec: "../../specs/npm-nightly-channel/spec.md"
|
||||
---
|
||||
|
||||
# Task 06: Desktop and mobile E2E
|
||||
|
||||
- **Acceptance:** Desktop UI selects Nightly, saves, reloads, and applies the registry-resolved exact
|
||||
target through a managed npm fixture.
|
||||
- **Acceptance:** Pixel 5 completes selection/save/reload with 44px rows and no horizontal overflow.
|
||||
- **Acceptance:** an unsupported install renders Stable plus the server reason without a Nightly
|
||||
mutation path.
|
||||
- **Verification:** `cd apps/web && pnpm e2e:run --project chromium tests/system/updates-channel.spec.ts`
|
||||
- **Verification:** `cd apps/web && pnpm e2e:run --project mobile-chrome tests/system/mobile-updates-page.spec.ts`
|
||||
- **Files likely touched:** `apps/web/e2e/tests/system/updates-channel.spec.ts`,
|
||||
`mobile-updates-page.spec.ts`, fixture/API helpers only if the real UI precondition cannot be
|
||||
expressed today.
|
||||
- **Dependencies:** Task 05 and production build from Tasks 03–05.
|
||||
- **Parallelism:** sequential.
|
||||
- **Inputs:** `/e2e` fixture rules and the plan mobile design contract.
|
||||
- **Risks:** E2E must use production Go-served assets and worker-scoped backend URLs.
|
||||
|
||||
## Verification results
|
||||
|
||||
- `cd apps/web && pnpm e2e:run --project chromium tests/system/updates-channel.spec.ts` — passed,
|
||||
2 tests, including exact target confirmation, target-version observation, automatic completion
|
||||
reload, and cleared progress state.
|
||||
- `cd apps/web && pnpm e2e:run --no-build --project mobile-chrome
|
||||
tests/system/mobile-updates-page.spec.ts` — passed, 2 tests on the Pixel 5 project against the
|
||||
desktop run's production assets, including a long canonical Nightly target and the
|
||||
unsupported-channel reason copy.
|
||||
- The production Go-served E2E build used a loopback npm metadata fixture behind the strict
|
||||
`KANDEV_E2E_MOCK=true` gate; selection, real PATCH persistence, reload, unsupported capability,
|
||||
exact target display, 44px rows, and document overflow were exercised.
|
||||
@@ -0,0 +1,33 @@
|
||||
---
|
||||
id: "07-docs-and-records"
|
||||
title: "Public docs and final records"
|
||||
status: completed
|
||||
wave: 6
|
||||
depends_on: ["02-release-workflow", "04-backend-api-apply", "06-updates-channel-e2e"]
|
||||
plan: "plan.md"
|
||||
spec: "../../specs/npm-nightly-channel/spec.md"
|
||||
---
|
||||
|
||||
# Task 07: Public docs and final records
|
||||
|
||||
- **Acceptance:** install, service, operations, and release docs describe `@nightly`, Stable default,
|
||||
supported channel switching, exact noon best-effort cadence, recovery, and exclusions.
|
||||
- **Acceptance:** spec, ADR, plan, and task statuses match the implemented behavior and recorded
|
||||
command results.
|
||||
- **Acceptance:** public documentation validation and diff whitespace checks pass.
|
||||
- **Verification:** `node --test scripts/validate-public-docs.test.mjs`
|
||||
- **Verification:** `node scripts/validate-public-docs.mjs`
|
||||
- **Verification:** `git diff --check`
|
||||
- **Files likely touched:** `README.md`, `docs/public/cli.md`, `use-kandev.md`, `operations.md`,
|
||||
`run-as-a-service.md`, `release-process.md`, `AGENTS.md`, `.agents/skills/release/SKILL.md`, and
|
||||
this feature's durable records.
|
||||
- **Dependencies:** Tasks 02, 04, and 06.
|
||||
- **Parallelism:** sequential.
|
||||
- **Inputs:** landed behavior and `/docs-maintainer` task-oriented documentation rules.
|
||||
- **Risks:** docs must not imply Homebrew/Desktop/GHCR nightly support or exact GitHub cron start.
|
||||
|
||||
## Verification results
|
||||
|
||||
- `node --test scripts/validate-public-docs.test.mjs` — passed, 58 tests.
|
||||
- `node scripts/validate-public-docs.mjs` — passed, 41 published pages validated.
|
||||
- `git diff --check` — passed.
|
||||
+29
-2
@@ -54,6 +54,28 @@ npx -y kandev@latest
|
||||
|
||||
If an npm policy such as `--omit=optional` prevents optional dependencies from being installed, Kandev cannot find its native runtime.
|
||||
|
||||
### npm nightly
|
||||
|
||||
Stable remains npm's default `latest` tag. To opt into the current prerelease from `main`, install
|
||||
or run the `nightly` tag explicitly:
|
||||
|
||||
```bash
|
||||
npm install -g kandev@nightly
|
||||
kandev --version
|
||||
|
||||
# One-off launch
|
||||
npx -y kandev@nightly
|
||||
```
|
||||
|
||||
A nightly version has the form `X.Y.(Z+1)-nightly.sha<12-hex-character SHA prefix>`, based on the latest
|
||||
stable `X.Y.Z`. The launcher and all five platform runtime packages use that same immutable
|
||||
version. Nightlies are best-effort daily snapshots. A new one appears only when `main` has changed
|
||||
since the latest Stable release, so some days may have no new Nightly.
|
||||
|
||||
Nightly does not move `latest` and does not publish a Homebrew formula, Desktop updater feed,
|
||||
container tag, Git tag, or GitHub Release. Use it for prerelease testing, not unattended production
|
||||
rollout.
|
||||
|
||||
## Start and stop
|
||||
|
||||
`run` is the default command. These are equivalent:
|
||||
@@ -205,14 +227,19 @@ Uninstalling the package does not remove `<home>`. Before removing that director
|
||||
|
||||
## Update
|
||||
|
||||
The installer owns CLI updates:
|
||||
The installer owns CLI updates. Update persistent Stable installs with:
|
||||
|
||||
```bash
|
||||
brew upgrade kandev
|
||||
npm install -g kandev@latest
|
||||
npx -y kandev@latest
|
||||
```
|
||||
|
||||
Use `npm install -g kandev@nightly` for a persistent npm Nightly install. `npx -y kandev@latest`
|
||||
and `npx -y kandev@nightly` launch one-off copies from the requested channel; they do not update a
|
||||
global package. A verified managed npm/npx user service can also select **Nightly** under
|
||||
**Settings > System > Updates**. Stable is selected by default; Desktop, Homebrew, system-service,
|
||||
unmanaged, local-checkout, and unknown installs cannot change this setting.
|
||||
|
||||
Release packages pin the shim and native runtime packages to the same SemVer. Do not copy only one binary from a different release into a bundle. A service unit contains installation-specific executable and bundle paths; after the package upgrade, reinstall it with the same service flags and restart it as described above.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
@@ -22,7 +22,7 @@ Kandev does not currently provide a user-login boundary for the web application,
|
||||
| --- | --- | --- | --- |
|
||||
| Desktop | Launch or quit Kandev | `~/.kandev` by default | **Settings > System > Updates** uses the signed desktop updater when supported |
|
||||
| Interactive CLI | `kandev`, then `Ctrl-C` | `~/.kandev` by default | Upgrade the Homebrew or npm package, then restart |
|
||||
| Managed service | `kandev service {start,stop,restart,status}` | `~/.kandev` for a user service, `/var/lib/kandev` for a system service, or the install-time `--home-dir` | Use guarded in-app apply for a managed user service; otherwise upgrade the package, reinstall with the same flags, and restart |
|
||||
| Managed service | `kandev service {start,stop,restart,status}` | `~/.kandev` for a user service, `/var/lib/kandev` for a system service, or the install-time `--home-dir` | A verified npm/npx user service can select and apply Stable or Nightly; other services use Stable and may require a package upgrade, reinstall, and restart |
|
||||
| Docker or Kubernetes | Container or workload manager | Mounted Kandev home plus any external database/provider state | Replace the image and recreate the container or pod |
|
||||
|
||||
See [Desktop app](desktop-app.md), [CLI](cli.md), [Run as a service](run-as-a-service.md), [Docker](docker.md), and [Kubernetes](k8s.md) for mode-specific prerequisites and commands.
|
||||
@@ -298,14 +298,41 @@ Never delete a managed task directory merely because its database row looks term
|
||||
|
||||
## Updates
|
||||
|
||||
The backend contacts the public GitHub Releases API once at startup and every six hours, with a 30-second HTTP timeout, and persists the last successful result. **Check now** performs a synchronous request and permits one manual check per process every 30 seconds. Offline or rate-limited installations continue to show cached state.
|
||||
Stable is the default update channel. It resolves signed releases from the public GitHub Releases
|
||||
API. A verified Kandev-managed npm or npx user service can select **Nightly** in
|
||||
**Settings > System > Updates**, then use the shared **Save changes** action. Nightly resolves the
|
||||
public npm `kandev@nightly` dist-tag. The install-wide selection survives restart. Desktop,
|
||||
Homebrew, system-service, unmanaged, local-checkout, unknown, and invalid-metadata installs stay on
|
||||
Stable and the page explains why Nightly is unavailable.
|
||||
|
||||
Configure update alerts in **Settings > General > Notifications > Notification Events**. Select **Kandev update available** for each notification provider that should receive it: Local delivers the in-app update indication and can use an already-granted browser or native desktop notification; System and Apprise use their configured provider transports. There is no separate update-only channel selector. New Local and System providers include this event by default; existing Local and System providers receive it once on upgrade, while existing Apprise providers remain unchanged. Disabling the event for a provider stops that provider's delivery without disabling release checks. Each provider receives a release version at most once; a later version is a new occurrence.
|
||||
The backend checks the selected source once at startup and every six hours, with a 30-second HTTP
|
||||
timeout, and persists the last successful Stable and Nightly results separately. **Check now**
|
||||
performs a synchronous request and permits one manual check per process every 30 seconds. Offline,
|
||||
rate-limited, or registry-failing installations continue to show that channel's cached state.
|
||||
|
||||
Nightlies are best-effort daily snapshots. A new version appears only when `main` contains commits
|
||||
after the latest Stable release and that exact commit has not already been published. Nightlies do
|
||||
not move npm `latest` and do not create Homebrew, Desktop, GHCR, Git tag, or GitHub Release
|
||||
artifacts.
|
||||
|
||||
Configure update alerts in **Settings > General > Notifications > Notification Events**. Select **Kandev update available** for each notification provider that should receive it: Local delivers the in-app update indication and can use an already-granted browser or native desktop notification; System and Apprise use their configured provider transports. Notification routing is independent of the Stable/Nightly release selector. New Local and System providers include this event by default; existing Local and System providers receive it once on upgrade, while existing Apprise providers remain unchanged. Disabling the event for a provider stops that provider's delivery without disabling release checks. Each provider receives a release version at most once; a later version is a new occurrence. Returning from Nightly to a Stable version is an explicit action and does not produce a normal upgrade notification.
|
||||
|
||||
Before any update, finish or stop active sessions, create and export a database backup plus its master key, preserve unpushed Git work, and read release notes.
|
||||
|
||||
- Desktop: use **Settings > System > Updates** when signed updater assets are available; otherwise install the new desktop package.
|
||||
- Managed user service: use **Settings > System > Updates > Apply update**. Kandev enables it only after verifying the managed unit or plist and `<home>/service/install.json`. If the guarded update is unavailable or fails, run `brew upgrade kandev` or `npm install -g kandev@latest`, rerun `kandev service install` with the same install flags, then `kandev service restart`. System services always use that terminal flow with the required privileges.
|
||||
- Managed npm/npx user service: choose Stable or Nightly, save, check the resolved exact version,
|
||||
then use **Apply update**. Apply submits the exact immutable version shown; if a newer channel
|
||||
target was cached meanwhile, the backend rejects the stale request so the page can refresh. To
|
||||
recover from Nightly, select Stable and apply the shown release. For terminal recovery, an
|
||||
npm-managed service runs `npm install -g kandev@latest` and then `kandev service install` with the
|
||||
same flags; an npx-managed service runs
|
||||
`npx -y kandev@latest service install` with the same flags. Restart afterward. An npx-managed
|
||||
service points into npm's transient `_npx` cache and stops working if that cache is pruned; prefer
|
||||
`npm install -g` for a durable service.
|
||||
- Managed Homebrew user service: Stable only. Use **Apply update** when available; otherwise run
|
||||
`brew upgrade kandev`, reinstall the service with the same flags, and restart.
|
||||
- System service: Stable only. Upgrade with the required privileges, reinstall with the same
|
||||
service flags, and restart; the UI never applies it.
|
||||
- Unmanaged CLI: run `brew upgrade kandev` or `npm install -g kandev@latest`, then restart the process.
|
||||
- Transient npx: start the desired release with `npx -y kandev@latest`; this does not update a persistent package.
|
||||
- Docker/Kubernetes: replace the image and recreate the workload. Do not treat an in-container package install as a durable update.
|
||||
@@ -353,6 +380,8 @@ drawer mirrors it as the saved left sequence followed by the saved right sequenc
|
||||
| Diagnostic bundle is partial | `manifest.json` warnings, source status, and loss counters | Keep a Kandev browser open for frontend capture; use backend-only when browser evidence is unnecessary |
|
||||
| Update check returns HTTP 429 | Time since last **Check now** | Wait at least 30 seconds; background checks retry every six hours |
|
||||
| **Apply update** is absent | Install mode/method and `<home>/service/install.json` | Expected for system, unmanaged, local-checkout, or invalid-metadata installs. A managed npm, npx, or Homebrew user service should offer Apply; reinstall it with the same flags to refresh its identity and metadata, or use the manual package-manager flow. |
|
||||
| **Nightly** is disabled | Install mode/method and `<home>/service/install.json` | Expected unless this is a verified managed npm/npx user service. Homebrew, Desktop, system-service, unmanaged, local-checkout, invalid-metadata, and unknown installs are Stable-only. |
|
||||
| Nightly check or save fails | npm access and cached checked time | Verify access to `https://registry.npmjs.org/kandev`, retry after connectivity returns, or keep/select Stable. A malformed or missing npm `nightly` tag fails closed. |
|
||||
| Metrics show unavailable | OS support, disk path, executor connectivity | Select supported metrics and verify permissions/network; the collector reports errors per sample |
|
||||
| Disk total exceeds filesystem expectation | Separate `data` and `backups` rows | Backups are counted twice in the UI total; use volume metrics for capacity decisions |
|
||||
| Legacy `/tmp/kandev-agent/*` uses disk | Process inventory and open-file references for the exact directory | This is data from older Kandev versions, not a current Storage resource. Stop Kandev, confirm no live process references the target, then remove only the confirmed-inactive legacy directory through host administration. |
|
||||
|
||||
@@ -71,6 +71,20 @@ GHCR images are built before the GitHub Release. npm and Homebrew start only aft
|
||||
|
||||
Base image tags include `X.Y.Z`, `vX.Y.Z`, `sha-*`, and `latest`. Universal tags include `X.Y.Z-universal`, `vX.Y.Z-universal`, and the floating `universal`. The weekly universal rebuild updates only floating/dated weekly tags, never a version-specific release tag.
|
||||
|
||||
## npm Nightly channel
|
||||
|
||||
npm also offers an opt-in `nightly` prerelease for users who want to test recent changes from
|
||||
`main`. Stable remains the default `latest` channel.
|
||||
|
||||
For stable `X.Y.Z` and commit `abcdef123456...`, the corresponding Nightly version is
|
||||
`X.Y.(Z+1)-nightly.shaabcdef123456`. The `kandev` launcher and all five platform runtime packages
|
||||
share that immutable version, so an installed build identifies its source commit.
|
||||
|
||||
Nightlies are best-effort daily snapshots. A new one appears only when `main` has changed since the
|
||||
latest Stable release, so some days may have no new Nightly. A Nightly never moves npm's `latest`
|
||||
tag and does not publish a Git tag, GitHub Release, Homebrew formula, Desktop updater build or feed,
|
||||
or container tag. See [CLI installation](cli.md#npm-nightly) to try Nightly or return to Stable.
|
||||
|
||||
<details>
|
||||
<summary>Signing, verification, and partial-release recovery</summary>
|
||||
|
||||
|
||||
@@ -7,7 +7,11 @@ description: "Install Kandev under systemd or launchd and operate it safely."
|
||||
|
||||
The native Kandev launcher can install itself as a systemd service on Linux or a launchd service on macOS. Use this for a persistent workstation or server. Windows Service Control Manager, OpenRC, and SysV init are not supported.
|
||||
|
||||
Install Kandev first using a persistent [CLI installation](cli.md#install). Do not install a long-lived service from an ephemeral `npx` invocation: the generated unit records the absolute native executable and release-bundle paths.
|
||||
For the simplest path, install Kandev persistently before creating the service; see [CLI installation](cli.md#install). A plain `npx -y kandev@...` launch is ephemeral, but `npx -y kandev@latest service install` can create a managed npx user service. That service depends on the cached npx package remaining present: reinstall it after upgrades, and expect npm cache cleanup to invalidate its recorded absolute paths. Prefer global npm for a durable service. Do not hand-write a long-lived service around an npx command.
|
||||
|
||||
Stable is the default release channel. A verified Kandev-managed npm/npx user service can opt into
|
||||
the npm Nightly channel from **Settings → System → Updates**. Desktop, Homebrew, and system services
|
||||
remain Stable-only.
|
||||
|
||||
> **Network security:** the backend listens on `0.0.0.0` by default and ships with authentication **disabled**. Before allowing remote access, enable [opt-in authentication](authentication.md) (the **Authentication & users** feature toggle, or `KANDEV_FEATURES_AUTH=true`) and terminate TLS in a reverse proxy — authentication does not replace HTTPS. A server bound to non-loopback interfaces without authentication logs a startup warning. See [server configuration](configuration.md#root-and-server).
|
||||
|
||||
@@ -185,16 +189,48 @@ sudo journalctl -u kandev.service -n 200 --no-pager
|
||||
|
||||
For a user service installed by `kandev service install`, use **Settings → System → Updates → Apply update** when a newer release is available. Kandev verifies the managed unit or plist and its owner-only `<home>/service/install.json` metadata before enabling this action. System services still require a terminal update because they need elevated privileges.
|
||||
|
||||
If the Apply action is unavailable or fails, upgrade the package manually, reinstall with the same mode and home flags so absolute paths and bundle metadata are refreshed, then restart explicitly:
|
||||
For a verified global npm user service, or an existing managed npx user service, the same page also
|
||||
provides an install-wide **Stable** or **Nightly** choice. A global npm install is the recommended
|
||||
durable service path. An npx-managed service is a recoverable but fragile fallback because its
|
||||
executable lives in npm's transient cache. Stable reads signed GitHub Releases and remains selected
|
||||
by default. Nightly reads npm's `kandev@nightly` tag and may contain unstable code from `main`. Select the row, use
|
||||
**Save changes**, inspect the exact version, and then apply it separately. Apply submits that exact
|
||||
immutable version; it does not re-resolve either mutable channel source. The backend accepts it
|
||||
only while it still matches the selected channel's cached target. If that cache changes, Apply
|
||||
returns a conflict and the page must refresh before you retry with the newly displayed target.
|
||||
|
||||
To leave Nightly, select Stable, save, and apply the displayed stable release. If the UI cannot do
|
||||
that, use the manual stable recovery below. Homebrew, Desktop, system-service, unmanaged,
|
||||
local-checkout, unknown, and invalid-metadata installs cannot select Nightly.
|
||||
|
||||
If the Apply action is unavailable or fails, use the recovery command that matches the original install. Repeat custom `--home-dir`, `--port`, and `--no-boot-start` values only on `service install`; `service restart` and `service status` accept `--system` but not those install-time flags.
|
||||
|
||||
```bash
|
||||
# npm example; use `brew upgrade kandev` for Homebrew
|
||||
# Global npm service
|
||||
npm install --global kandev@latest
|
||||
kandev service install --home-dir "$HOME/.kandev"
|
||||
# Append original install-time flags here when used.
|
||||
kandev service install
|
||||
kandev service restart
|
||||
kandev service status
|
||||
|
||||
# Existing managed npx service recovery only (run each service command through npx)
|
||||
# This service points into npm's cache. Reinstall after upgrades; npm cache cleanup invalidates it.
|
||||
# Prefer a global npm installation for a durable service.
|
||||
# Append original install-time flags to service install when used.
|
||||
npx -y kandev@latest service install
|
||||
npx -y kandev@latest service restart
|
||||
npx -y kandev@latest service status
|
||||
|
||||
# Homebrew service (Stable only)
|
||||
brew upgrade kandev
|
||||
# Append original install-time flags here when used.
|
||||
kandev service install
|
||||
kandev service restart
|
||||
```
|
||||
|
||||
To remain on Nightly during a manual npm or npx recovery, use `kandev@nightly` in the matching command.
|
||||
Do not use a Homebrew `HEAD` build as an equivalent channel; no Homebrew Nightly is published.
|
||||
|
||||
For system mode:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -40,6 +40,28 @@ npm install -g kandev@latest
|
||||
kandev
|
||||
```
|
||||
|
||||
Stable is the default and is selected by npm's `latest` tag. To test the current prerelease from
|
||||
`main` without changing a global installation, launch the package once from the npm-only `nightly`
|
||||
tag:
|
||||
|
||||
```bash
|
||||
npx -y kandev@nightly
|
||||
```
|
||||
|
||||
To replace a global Stable installation with Nightly, use:
|
||||
|
||||
```bash
|
||||
npm install -g kandev@nightly
|
||||
kandev
|
||||
```
|
||||
|
||||
The global command replaces the installed `kandev` channel. Return to Stable with
|
||||
`npm install -g kandev@latest`.
|
||||
|
||||
Nightly builds may be unstable. They are best-effort daily snapshots, and a new version appears
|
||||
only when `main` has commits after the latest Stable release. Homebrew, Desktop, and container
|
||||
installs have no Nightly channel.
|
||||
|
||||
The launcher selects the platform runtime, starts the Go backend and agent runtime, serves the web app, and opens its local URL. The preferred backend port is `38429`; if it is unavailable, the launcher chooses another free port and prints the actual URL. Use `kandev --headless` (or `KANDEV_NO_BROWSER=1`) when a browser must not open.
|
||||
|
||||
By default, persistent state is under `~/.kandev`, including the SQLite database, repository materializations, sessions, logs, and backups. `KANDEV_HOME_DIR` relocates that root; `KANDEV_DATABASE_PATH` overrides only the database. Kandev creates its data directory with owner-only permissions and rejects symlinked components in that path, but file permissions do not replace host access controls.
|
||||
|
||||
+46
-20
@@ -1,6 +1,12 @@
|
||||
# Run Kandev as a Service
|
||||
|
||||
Install Kandev as an OS-managed service (systemd on Linux, launchd on macOS) so it auto-starts and stays running. User-mode services installed by `kandev service install` can self-update from the System → Updates page. Non-service installs and `--system` services still update manually: `npm i -g kandev@latest` or `brew upgrade kandev`, then re-run `kandev service install`.
|
||||
Install Kandev as an OS-managed service (systemd on Linux, launchd on macOS) so it auto-starts and stays running. User-mode services installed by `kandev service install` can self-update from the System → Updates page. A verified managed global-npm user service can select Stable (the default) or the npm Nightly channel there. An npx-launched service has the same controls, but its executable lives in npm's disposable cache; use it only as a temporary or recovery path, and prefer global npm for persistent services. Homebrew, non-service, local-checkout, and `--system` installs remain Stable-only.
|
||||
|
||||
Manual updates must preserve the install type and selected channel: global npm uses `kandev@latest`
|
||||
for Stable or `kandev@nightly` for Nightly; the temporary npx recovery path accepts the same tags;
|
||||
Homebrew uses `brew upgrade kandev`; and a local checkout is rebuilt with `make service-install`.
|
||||
Reuse custom `--port`, `--home-dir`, and `--no-boot-start` (Linux user mode only) values on
|
||||
`service install`; `service restart` carries only `--system` when applicable.
|
||||
|
||||
This guide assumes you've already installed kandev via [Homebrew or npm](../apps/cli/README.md#quick-start) and that `kandev` works when run interactively.
|
||||
|
||||
@@ -96,18 +102,40 @@ kandev service config [--system]
|
||||
|
||||
If Kandev is running as a user-mode service installed by `kandev service install`, open **Settings → System → Updates** and use **Apply update** when it appears. The button is shown only when the backend can prove it is running from a kandev-managed service unit/plist with valid service metadata.
|
||||
|
||||
Both npm runtime packages and Homebrew install kandev under versioned package-manager paths. Manual upgrades replace those paths, so the unit file must be refreshed afterward.
|
||||
Package-manager installs use versioned paths. Manual upgrades replace those paths, so a service unit must be refreshed afterward.
|
||||
|
||||
**Manual fix:** re-run install. It's idempotent.
|
||||
Use the commands for the original install type:
|
||||
|
||||
```bash
|
||||
npm i -g kandev@latest # or: brew upgrade kandev
|
||||
kandev service install # rewrites the unit with the new paths
|
||||
# Reuse these install-time options only if the original service used them:
|
||||
# --home-dir /path/to/kandev-home --port 38429
|
||||
# --no-boot-start # Linux user mode only
|
||||
# Keep latest for Stable; change to nightly when the saved channel is Nightly.
|
||||
CHANNEL_TAG=latest
|
||||
|
||||
# Global npm user service
|
||||
npm i -g "kandev@$CHANNEL_TAG"
|
||||
kandev service install # append original install-time options here
|
||||
kandev service restart
|
||||
|
||||
# Temporary npx recovery path. This points into npm's disposable cache; do not
|
||||
# rely on it for a persistent service. Move to global npm when recovery is complete.
|
||||
npx -y "kandev@$CHANNEL_TAG" service install # append original install-time options here
|
||||
npx -y "kandev@$CHANNEL_TAG" service restart
|
||||
|
||||
# Homebrew user service (Stable only)
|
||||
brew upgrade kandev
|
||||
kandev service install # append original install-time options here
|
||||
kandev service restart
|
||||
|
||||
# Local checkout service
|
||||
make service-install HOME_DIR=/path/to/kandev-home PORT=38429 NO_BOOT_START=1 # preserve values when used
|
||||
make service-restart
|
||||
```
|
||||
|
||||
If you launch `kandev` interactively after an upgrade, it will detect a stale unit and print a one-line reminder. You can also check with `kandev service config` to see the paths that would be baked in by the next install.
|
||||
|
||||
System services (`kandev service install --system`) do not expose UI self-update. Update them from a privileged shell, then re-run `sudo kandev service install --system`.
|
||||
System services (`kandev service install --system`) do not expose UI self-update. Update them with their original package manager from a privileged shell, then rerun the matching executable. Preserve custom install-time flags on `service install --system`; use only `--system` on `service restart --system`.
|
||||
|
||||
## Linux Boot-Start (`loginctl enable-linger`)
|
||||
|
||||
@@ -193,22 +221,20 @@ This happens with `--system` if `SUDO_USER` isn't set (e.g. you logged in as roo
|
||||
|
||||
The OS service manager keeps running whatever `ExecStart` it has — it doesn't know about npm/brew upgrades. For managed user services, use **Apply update** on the Updates page. Otherwise, **always re-run `kandev service install` after an upgrade** so the unit picks up the new paths, then `kandev service restart` to pick up new code.
|
||||
|
||||
On a managed global-npm user service (or a temporary cache-backed npx service), **Settings → System
|
||||
→ Updates** also owns the install-wide Stable/Nightly choice. Nightly follows npm's
|
||||
`kandev@nightly` tag; save the choice before applying the exact version shown. To recover, select
|
||||
Stable and apply, or manually install `kandev@latest`, reinstall the service, and restart it. There
|
||||
is no Homebrew or Desktop Nightly channel.
|
||||
|
||||
## Updating: TL;DR
|
||||
|
||||
```bash
|
||||
# Option A: managed user service
|
||||
# Use Settings -> System -> Updates -> Apply update
|
||||
|
||||
# Option B: manual / system service
|
||||
# 1. Update the binary
|
||||
npm i -g kandev@latest # or: brew upgrade kandev
|
||||
|
||||
# 2. Refresh the unit file (rewrites paths to point at the new version)
|
||||
kandev service install # add --system if that's what you used originally
|
||||
|
||||
# 3. (install does this automatically) Verify it came back up
|
||||
kandev service status
|
||||
```
|
||||
- Managed global-npm user service: use **Settings → System → Updates → Apply update**. Eligible services can first save Stable or Nightly.
|
||||
- Manual global npm service: install `kandev@latest` for Stable or `kandev@nightly` for Nightly, then run `kandev service install` with the original install-time options and plain `kandev service restart`.
|
||||
- Temporary npx recovery: run `npx -y kandev@latest service install` for Stable or replace `latest` with `nightly`, then rerun the matching npx `service restart`. The unit points into `~/.npm/_npx`; migrate to global npm rather than relying on this cache-backed path for a persistent service.
|
||||
- Manual Homebrew service: run `brew upgrade kandev`, then `kandev service install` with the original install-time options and plain `kandev service restart`.
|
||||
- Local checkout service: preserve `HOME_DIR`, `PORT`, and `NO_BOOT_START` values on `make service-install`; then run `make service-restart` without them.
|
||||
- System service: use the matching manual path through a privileged shell; retain `--system` on both service commands and put other original options only on `service install`.
|
||||
|
||||
## Uninstalling
|
||||
|
||||
|
||||
@@ -187,6 +187,7 @@ System pages (Radarr/Sonarr-style) for status, disk usage, database maintenance,
|
||||
|
||||
| Spec | Status |
|
||||
|---|---|
|
||||
| [npm-nightly-channel](npm-nightly-channel/spec.md) | shipped |
|
||||
| [agent-resume-runtime-recovery](agent-resume-runtime-recovery/spec.md) | shipped |
|
||||
| [agent-stall-recovery](agent-stall-recovery/spec.md) | approved |
|
||||
| [mcp-session-observability](mcp-session-observability/spec.md) | approved |
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
---
|
||||
status: shipped
|
||||
created: 2026-07-31
|
||||
owner: kandev
|
||||
---
|
||||
|
||||
# npm nightly channel
|
||||
|
||||
## Why
|
||||
|
||||
Users who want fixes from `main` currently have to build Kandev themselves or wait for the next
|
||||
stable release. Maintainers also lack one supported prerelease path that exercises the same npm
|
||||
launcher and native runtime packages users install in production.
|
||||
|
||||
## What
|
||||
|
||||
- Kandev publishes an npm nightly from `main` at 12:00 UTC when `main` contains commits after the
|
||||
latest stable release and that exact commit has not already been published.
|
||||
- Maintainers can run the same Nightly path manually from `main`. A manual Nightly dry run performs
|
||||
metadata and registry preflight only, with no platform builds or npm writes.
|
||||
- A nightly for stable `X.Y.Z` and commit `abcdef123456...` has version
|
||||
`X.Y.(Z+1)-nightly.shaabcdef123456`.
|
||||
- The 12-hex abbreviation is an accepted compactness trade-off. Before an existing version can
|
||||
skip publication, Git must resolve that abbreviation to the exact scheduled commit; an ambiguous
|
||||
prefix or identity mismatch fails closed for maintainer resolution.
|
||||
- Every nightly publishes `kandev` and all five `@kdlbs/runtime-*` packages at the same immutable
|
||||
version under the npm `nightly` dist-tag. The stable `latest` dist-tag does not move.
|
||||
- Users persistently install the channel with `npm install -g kandev@nightly`. The command
|
||||
`npx -y kandev@nightly` runs a transient Nightly copy without changing a global installation.
|
||||
- Settings > System > Updates exposes Stable and Nightly for a verified, Kandev-managed npm or
|
||||
npx user service. Stable is the default and the setting is install-wide.
|
||||
- An npx run is managed only after it installs the service (for example,
|
||||
`npx -y kandev@nightly service install`); a transient `npx -y kandev@nightly` run alone neither
|
||||
creates a managed service nor persists an update-channel selection.
|
||||
- Desktop, Homebrew, local-checkout, unknown, unmanaged, and system-service installations remain
|
||||
on the Stable channel.
|
||||
- Stable update discovery continues to use GitHub Releases. Nightly discovery follows npm's
|
||||
`kandev@nightly` dist-tag.
|
||||
- Applying an npm/npx update submits the exact version shown in the Updates page. The backend
|
||||
accepts it only while it still matches the selected channel's cached target, then installs that
|
||||
immutable version; a changed cache returns `409 Conflict` and requires a refresh.
|
||||
- Nightly publication creates no Git tag, GitHub Release, changelog commit, desktop update,
|
||||
container tag, or Homebrew update.
|
||||
|
||||
Decision: [ADR-2026-07-31-npm-nightly-release-channel](../../decisions/2026-07-31-npm-nightly-release-channel.md).
|
||||
|
||||
Implementation plan: [npm nightly channel](../../plans/npm-nightly-channel/plan.md).
|
||||
|
||||
## Data model
|
||||
|
||||
The install-wide `settings` table contains key `updates_channel`. Its value is the UTF-8 string
|
||||
`stable` or `nightly`; a missing or invalid value reads as `stable`.
|
||||
|
||||
The existing stable target cache remains in these `kandev_meta` keys:
|
||||
|
||||
- `latest_version`
|
||||
- `latest_version_url`
|
||||
- `latest_version_checked_at`
|
||||
|
||||
Nightly uses an isolated cache:
|
||||
|
||||
- `latest_version_nightly`
|
||||
- `latest_version_nightly_url`
|
||||
- `latest_version_nightly_checked_at`
|
||||
|
||||
Changing channel never reinterprets cached data from the other source.
|
||||
|
||||
## API surface
|
||||
|
||||
`GET /api/v1/system/updates` and `POST /api/v1/system/updates/check` retain their current fields
|
||||
and add:
|
||||
|
||||
```json
|
||||
{
|
||||
"channel": "stable",
|
||||
"channel_editable": true,
|
||||
"channel_unsupported_reason": ""
|
||||
}
|
||||
```
|
||||
|
||||
`PATCH /api/v1/system/updates/channel` accepts:
|
||||
|
||||
```json
|
||||
{ "channel": "nightly" }
|
||||
```
|
||||
|
||||
It returns the complete updates response for the selected channel. Invalid channel names return
|
||||
`400`. Selecting Nightly for an unsupported installation returns `409`. Persistence or resolver
|
||||
failures return `500` or `502` using the existing System handler error conventions.
|
||||
|
||||
The npm registry contract is the public metadata document for package `kandev`. The resolver reads
|
||||
`dist-tags.nightly`, requires a valid SemVer, and requires the same version to exist in `versions`.
|
||||
|
||||
## Permissions
|
||||
|
||||
Anyone allowed to view System settings may read update status. The existing admin guard applies to
|
||||
manual checks, channel changes, and update application. Channel choice is shared by all users of
|
||||
the installation.
|
||||
|
||||
## Failure modes
|
||||
|
||||
- A GitHub or npm discovery failure preserves that channel's previous cache and surfaces the stale
|
||||
checked time plus the request error.
|
||||
- Apply never re-resolves a moving channel tag. It locks the selected-channel cache, rejects a
|
||||
submitted `target_version` that no longer matches, and writes the matching exact version into the
|
||||
update intent.
|
||||
- A malformed or missing npm `nightly` tag fails closed; it is never offered or installed.
|
||||
- A failed channel save keeps the draft dirty and surfaces that save failure instead of retaining a
|
||||
stale manual-check error or retry countdown.
|
||||
- A scheduled run with no commits after the stable tag exits successfully without building.
|
||||
- A manual Nightly dispatch from a ref other than `main` fails before resolving metadata.
|
||||
- Manual Nightly rejects the Stable-only desktop-validation and backfill modes. The workflow's
|
||||
required bump selector is ignored for Nightly, while `dry_run` remains supported.
|
||||
- A scheduled retry for an already-published commit exits successfully only when the main package
|
||||
and `nightly` tag agree.
|
||||
- Before building, the workflow resolves the commit prefix in the current `nightly` tag. A rerun
|
||||
behind a newer published commit is superseded and exits without building. The same commit skips
|
||||
only when every package exists and its `nightly` tag matches; an incomplete current target
|
||||
proceeds to repair. Divergent or unresolvable history fails closed.
|
||||
- A 12-hex collision makes Git abbreviation resolution ambiguous, so the run fails closed instead
|
||||
of treating the colliding commit as already published.
|
||||
- Stable and Nightly workflow runs share one non-cancelling release-wide concurrency group. This
|
||||
covers Stable tag creation through npm publication, so Nightly cannot derive a version while a
|
||||
newly tagged Stable release is still pending on npm.
|
||||
- Before building and again before publishing, Nightly requires the highest stable Git tag to match
|
||||
`kandev@latest`. A pending Stable tag or a scheduled commit superseded by the current Stable tag
|
||||
exits successfully without publishing.
|
||||
- Before publishing, a Nightly run rechecks `kandev@latest`. If the baseline moved while Nightly
|
||||
was building, the stale run exits without publishing.
|
||||
- The same locked preflight requires `kandev@nightly` to equal the value observed before building;
|
||||
an overlapping run that already moved the tag supersedes the stale run.
|
||||
- Runtime packages publish before `kandev`. If any runtime fails, the main launcher is not
|
||||
published, so no visible launcher references missing exact dependencies.
|
||||
- Trusted-publisher OIDC is used only by `npm publish --tag nightly`. An existing version whose
|
||||
`nightly` tag does not match fails with recovery guidance because OIDC cannot run
|
||||
`npm dist-tag add`.
|
||||
- GitHub's scheduled start may be later than 12:00 UTC; delayed execution does not change the
|
||||
deterministic version.
|
||||
|
||||
## Persistence guarantees
|
||||
|
||||
- Channel choice and both target caches survive backend restarts.
|
||||
- One source failure never overwrites the other source's cache.
|
||||
- Each full commit deterministically maps to one npm version, so a retry never creates a second
|
||||
version for the same source state. The accepted 12-hex collision case halts automatic
|
||||
publication rather than mapping a second commit to the existing package.
|
||||
- npm nightly versions are immutable and retained; this feature performs no automated deletion.
|
||||
|
||||
## Scenarios
|
||||
|
||||
- **GIVEN** stable `0.82.0` and `main` commit `abc123def456...`, **WHEN** the nightly schedule runs,
|
||||
**THEN** all six packages publish as `0.82.1-nightly.shaabc123def456` under `nightly` and
|
||||
`kandev@latest` is unchanged.
|
||||
- **GIVEN** an eligible `main` commit, **WHEN** a maintainer manually dispatches the Nightly
|
||||
channel, **THEN** the same metadata, shared builds, safeguards, and npm publication run as the
|
||||
schedule.
|
||||
- **GIVEN** a manual Nightly with `dry_run=true`, **WHEN** its preflight resolves an eligible
|
||||
target, **THEN** the run reports that exact version and commit without building bundles or
|
||||
changing npm.
|
||||
- **GIVEN** a manual Nightly dispatched from a non-`main` ref or combined with desktop validation
|
||||
or backfill, **WHEN** validation runs, **THEN** it fails with an actionable input error.
|
||||
- **GIVEN** `main` points at the latest stable tag's commit, **WHEN** the nightly schedule runs,
|
||||
**THEN** it exits successfully without a platform build or npm publication.
|
||||
- **GIVEN** the highest Stable Git tag is newer than npm `latest`, **WHEN** Nightly prepares or
|
||||
publishes, **THEN** it exits successfully rather than deriving from the stale npm baseline.
|
||||
- **GIVEN** a Nightly schedule was queued before a Stable release superseded its commit, **WHEN**
|
||||
that Nightly starts after Stable completes, **THEN** it exits successfully without building.
|
||||
- **GIVEN** the current `main` nightly already exists and `kandev@nightly` points to it, **WHEN**
|
||||
the schedule runs again, **THEN** it exits successfully without rebuilding.
|
||||
- **GIVEN** a previous run published only some runtime packages, **WHEN** the same commit retries,
|
||||
**THEN** matching packages are accepted, missing packages publish, and `kandev` publishes last.
|
||||
- **GIVEN** an older run left only some runtime tags advanced, **WHEN** a later `main` commit runs,
|
||||
**THEN** ancestor-tagged partial packages are repaired by the later publish without manual tag
|
||||
edits.
|
||||
- **GIVEN** no channel setting, **WHEN** a user opens Updates, **THEN** Stable is selected and the
|
||||
target comes from GitHub Releases.
|
||||
- **GIVEN** a verified npm managed user service, **WHEN** an admin selects and saves Nightly,
|
||||
**THEN** the setting survives reload and the target resolves from `kandev@nightly`.
|
||||
- **GIVEN** a Nightly save is pending, **WHEN** the admin changes the draft back to Stable before
|
||||
the response arrives, **THEN** the returned Nightly state becomes the saved baseline while the
|
||||
newer Stable draft remains selected, dirty, and available for a follow-up save.
|
||||
- **GIVEN** a Homebrew, Desktop, unmanaged, system-service, local, or unknown installation,
|
||||
**WHEN** Updates renders, **THEN** Nightly is unavailable with a visible reason and Stable stays
|
||||
effective.
|
||||
- **GIVEN** an installed nightly whose SHA sorts lexically after the new target SHA, **WHEN** npm's
|
||||
`nightly` tag changes, **THEN** the new unequal target is offered; SHA text is not treated as a
|
||||
chronological counter.
|
||||
- **GIVEN** a user running a nightly selects Stable, **WHEN** a valid stable target differs,
|
||||
**THEN** the UI offers an explicit return to that exact stable version without announcing it as
|
||||
a normal upgrade notification.
|
||||
- **GIVEN** the Updates page shows target A and discovery changes the selected-channel cache to B,
|
||||
**WHEN** the user submits Apply for A, **THEN** the backend returns `409 Conflict` and installs
|
||||
neither target.
|
||||
- **GIVEN** a Pixel 5 viewport, **WHEN** the user selects Nightly and saves, **THEN** the same
|
||||
persisted outcome is reachable through 44px rows with no horizontal document overflow.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Homebrew `HEAD`, a nightly formula, or a second tap
|
||||
- Desktop nightly updater feeds
|
||||
- GHCR nightly tags
|
||||
- Nightly GitHub Releases or Git tags
|
||||
- Automatic update application
|
||||
- Per-user channels
|
||||
- Additional beta/canary channels
|
||||
- Timestamped versions
|
||||
@@ -53,6 +53,9 @@ A new **System** group is added to the existing settings sidebar (`apps/web/comp
|
||||
6. **Updates** — `/settings/system/updates`
|
||||
- Shows running version, latest available version, and a "new version available" badge if newer.
|
||||
- **Check now** button — forces a re-poll (rate-limited 30s per process).
|
||||
- **Update channel** — Stable is the install-wide default. A verified managed npm/npx user
|
||||
service can select Nightly through the shared Settings save flow. Desktop, Homebrew,
|
||||
unmanaged, system-service, local, and unknown installs remain Stable with a visible reason.
|
||||
- A service update keeps its progress surface while the backend restarts. Once `/system/info` confirms the target version, the page reloads the document so the tab runs the new frontend bundle.
|
||||
- Update alerts are configured with the existing provider/event matrix under
|
||||
**Settings > General > Notifications**. The Updates page does not own a
|
||||
@@ -77,7 +80,10 @@ The **System** group header (and the **Status** child entry) show a numeric badg
|
||||
|
||||
### Backend surface
|
||||
|
||||
A new package `apps/backend/internal/system/` owns these endpoints. It absorbs the existing `internal/health/` package as a sub-component. Endpoints use the same auth model as the rest of `/api/v1/settings/*` (no separate admin tier); see [Permissions](#permissions) for the destructive-action confirmation pattern.
|
||||
A new package `apps/backend/internal/system/` owns these endpoints. It absorbs the existing
|
||||
`internal/health/` package as a sub-component. Read routes use the normal authenticated install
|
||||
identity; selected mutation routes use the existing admin guard. See [Permissions](#permissions)
|
||||
for the exact split and destructive-action confirmation pattern.
|
||||
|
||||
```
|
||||
GET /api/v1/system/health (existing; unchanged)
|
||||
@@ -99,26 +105,48 @@ POST /api/v1/system/logs/bundles/:id/frontend - bounded frontend capture chu
|
||||
GET /api/v1/system/logs/bundles/:id/download - stream ready/partial ZIP
|
||||
POST /api/v1/system/logs/frontend-errors - bounded/rate-limited error-toast report
|
||||
POST /api/v1/system/improve-kandev/bundle/lease - owner-verified 24h task-context copy
|
||||
GET /api/v1/system/updates - { current, latest, latestCheckedAt, releaseUrl, install, applySupported }
|
||||
POST /api/v1/system/updates/check - force GitHub re-poll; rate-limited 30s
|
||||
POST /api/v1/system/updates/apply - queue service-only self-update; body { confirm: "UPDATE" }
|
||||
GET /api/v1/system/updates - { current, latest, latest_url, latest_checked_at, update_available, channel, channel_editable, channel_unsupported_reason, install: { running_as_service, managed_service, mode?, manager?, kind?, metadata_path? }, apply_supported, apply_unsupported_reason?, manual_commands? }
|
||||
POST /api/v1/system/updates/check - force selected-source re-poll; rate-limited 30s
|
||||
PATCH /api/v1/system/updates/channel - persist Stable/Nightly for a verified managed npm/npx user service; body { channel }
|
||||
POST /api/v1/system/updates/apply - queue service-only self-update; body { confirm: "UPDATE", target_version }
|
||||
```
|
||||
|
||||
The System API has no global casing convention. Updates and Info use the snake_case JSON fields
|
||||
shown above, while endpoints such as Disk Usage and Database use their documented camelCase
|
||||
fields. Earlier camelCase Updates names in this draft (`latestCheckedAt`, `releaseUrl`, and
|
||||
`applySupported`) were documentation errors, corrected here without renaming any wire field.
|
||||
|
||||
Storage endpoints are defined separately in [Storage Maintenance](storage-maintenance.md).
|
||||
|
||||
Long-running operations (vacuum, optimize, reset, restore, snapshot create, disk walk) return `202 Accepted` with a `jobId` and publish progress on the existing event bus. The frontend subscribes via WS (`system.job.update` event) to render progress and final result. On success/failure the operation flips a corresponding entry in the existing health surface (e.g., a "VACUUM completed: reclaimed X MB" info issue that auto-expires).
|
||||
|
||||
### Updates poller
|
||||
|
||||
A background goroutine in `internal/system/updates/poller.go` starts on backend boot and polls GitHub releases for `kdlbs/kandev` every 6 hours (unauthenticated; well under the 60 req/hr/IP unauth limit). It compares `tag_name` to the running version (semver) and persists the result to `kandev_meta`:
|
||||
A background goroutine in `internal/system/updates/poller.go` starts on backend boot and polls the
|
||||
selected channel every 6 hours. Stable reads GitHub Releases for `kdlbs/kandev`; Nightly reads the
|
||||
public npm `kandev@nightly` dist-tag. It persists isolated channel targets in `kandev_meta`:
|
||||
|
||||
- `latest_version TEXT` — highest published semver tag (e.g., `1.2.4`)
|
||||
- `latest_version_url TEXT` — URL to that GitHub release
|
||||
- `latest_version_checked_at INTEGER` — unix timestamp of last successful poll
|
||||
- `latest_version_nightly`, `latest_version_nightly_url`,
|
||||
`latest_version_nightly_checked_at` — equivalent npm Nightly cache keys
|
||||
|
||||
The `GET /api/v1/system/updates` handler reads from `kandev_meta` only; it never calls GitHub synchronously. It also reports the current service install state (`running_as_service`, `managed_service`, `mode`, `manager`, `kind`) so the UI can decide whether one-click apply is allowed. `POST /api/v1/system/updates/check` triggers an out-of-band refresh, rate-limited per-process to one call per 30 seconds. If the GitHub call fails (offline, rate limited, 5xx), the handler returns the last-known value and the `latestCheckedAt` exposes the staleness.
|
||||
The `GET /api/v1/system/updates` handler reads from `kandev_meta` only; it never contacts an
|
||||
upstream synchronously. Its nested `install` object reports the current service install state
|
||||
(`running_as_service`, `managed_service`, `mode`, `manager`, `kind`, and `metadata_path`) so the UI
|
||||
can decide whether one-click apply is allowed. The response's `channel` is the effective selected
|
||||
source for this install. Only a
|
||||
verified managed npm/npx user service can persist and expose Nightly; unsupported installs report
|
||||
Stable even if an old Nightly preference remains stored, set `channel_editable=false`, and include
|
||||
`channel_unsupported_reason`. The PATCH write path repeats the managed-service verification before
|
||||
resolving or persisting either channel and returns `409 Conflict` for an unsupported install.
|
||||
`channel_unsupported_reason` remains present with an empty string when channel editing is supported.
|
||||
`POST /api/v1/system/updates/check` triggers a selected-source refresh, rate-limited
|
||||
per-process to one call per 30 seconds. If the GitHub or npm call fails (offline, rate limited,
|
||||
5xx), the channel's last-known value remains cached and `latest_checked_at` exposes the staleness.
|
||||
|
||||
`POST /api/v1/system/updates/apply` is available only when Kandev is running as a kandev-managed user service (`systemd --user` or launchd user agent) and the latest release is newer than the current binary. It writes an update intent under `<KANDEV_HOME_DIR>/service/update-intents/`, starts a manager-owned helper (`systemd-run --user` on Linux, or a one-shot transient LaunchAgent plist bootstrapped via `launchctl bootstrap` on macOS), and returns a `self-update` system job id. Under `KANDEV_E2E_MOCK=true`, the helper path is fake so UI and backend tests can exercise the flow without mutating npm/Homebrew or restarting the service.
|
||||
`POST /api/v1/system/updates/apply` is available only when Kandev is running as a kandev-managed user service (`systemd --user` or launchd user agent) and the selected channel exposes an applicable target. The request includes the exact `target_version` shown to the user. While holding the update-cache lock, the backend rejects a stale target with `409 Conflict`; otherwise it writes that version to an update intent under `<KANDEV_HOME_DIR>/service/update-intents/`, starts a manager-owned helper (`systemd-run --user` on Linux, or a one-shot transient LaunchAgent plist bootstrapped via `launchctl bootstrap` on macOS), and returns a `self-update` system job id. Under `KANDEV_E2E_MOCK=true`, the helper path is fake so UI and backend tests can exercise the flow without mutating npm/Homebrew or restarting the service.
|
||||
|
||||
### Disk-usage cache
|
||||
|
||||
@@ -156,6 +184,11 @@ The page reads the JSON statically; no backend endpoint is needed.
|
||||
Notifications provider/event settings instead of rendering a separate
|
||||
update-notification channel control.
|
||||
- **GIVEN** the user is running a kandev-managed user service and a newer release exists, **WHEN** they open `/settings/system/updates`, **THEN** the page shows **Apply update** and the confirmation queues a `self-update` job.
|
||||
- **GIVEN** the user runs a verified managed npm/npx user service, **WHEN** they select and save
|
||||
Nightly, **THEN** the choice survives reload and update discovery follows `kandev@nightly`.
|
||||
- **GIVEN** the install is Desktop, Homebrew, unmanaged, system-service, local, or unknown,
|
||||
**WHEN** Updates renders, **THEN** Stable remains effective and Nightly shows a visible
|
||||
unsupported reason.
|
||||
- **GIVEN** a service update is in progress, **WHEN** `/system/info` first reports the requested target version, **THEN** the tab reloads exactly once and renders from the confirmed backend's frontend assets; an older version or temporary outage does not trigger the reload.
|
||||
- **GIVEN** the user is not running as a kandev-managed service or is running a `--system` service, **WHEN** they open `/settings/system/updates`, **THEN** the page does not render an update-apply control and instead shows the manual update commands.
|
||||
- **GIVEN** the user clicks **VACUUM** on the Database page, **WHEN** the operation completes, **THEN** the DB size delta is shown ("Reclaimed 12.3 MB"), the page Database stats refresh, and a transient info issue appears on the Status page.
|
||||
@@ -168,15 +201,12 @@ The page reads the JSON statically; no backend endpoint is needed.
|
||||
|
||||
## Data model
|
||||
|
||||
Two new columns on the existing `kandev_meta` table (key/value or pivoted to columns — match the existing schema). One new in-memory cache in the system package. No new SQLite tables.
|
||||
|
||||
```
|
||||
ALTER TABLE kandev_meta ADD COLUMN latest_version TEXT;
|
||||
ALTER TABLE kandev_meta ADD COLUMN latest_version_url TEXT;
|
||||
ALTER TABLE kandev_meta ADD COLUMN latest_version_checked_at INTEGER;
|
||||
```
|
||||
|
||||
(If `kandev_meta` is key/value-shaped, write three rows with these keys instead.)
|
||||
The existing key/value `kandev_meta` table stores stable target keys `latest_version`,
|
||||
`latest_version_url`, and `latest_version_checked_at`. Nightly uses the isolated keys
|
||||
`latest_version_nightly`, `latest_version_nightly_url`, and
|
||||
`latest_version_nightly_checked_at`. The install-wide `settings` table contains
|
||||
`updates_channel` with value `stable` or `nightly`; missing or invalid values read as Stable.
|
||||
No new SQLite table is required.
|
||||
|
||||
## State machine — long-running jobs
|
||||
|
||||
@@ -191,11 +221,17 @@ Each transition publishes `system.job.update` with `{ jobId, kind, state, messag
|
||||
|
||||
## Permissions
|
||||
|
||||
All System endpoints require the same "logged-in install user" check as the existing `/api/v1/settings/*` endpoints — there is no admin tier in v1. Factory reset and restore endpoints additionally validate the `confirm` body field server-side as a defence-in-depth check against accidental fetches.
|
||||
System read endpoints use the normal authenticated/synthetic install identity. The existing admin
|
||||
guard covers database vacuum/optimize/reset, manual update checks, update-channel changes, and
|
||||
update apply. Backup create/restore/delete and disk-usage
|
||||
refresh currently remain on the base authenticated group. Reset and restore additionally validate
|
||||
their confirmation bodies server-side as defence in depth.
|
||||
|
||||
## Failure modes
|
||||
|
||||
- **GitHub poll failure** — log + keep the previous `kandev_meta` row; `/api/v1/system/updates` returns the stale value.
|
||||
- **npm Nightly poll failure** — log + keep the previous Nightly cache; malformed or missing
|
||||
`dist-tags.nightly` fails closed and is never offered.
|
||||
- **Disk walk failure** (permission error on a subdir) — return the partial result with a `warnings: [...]` array per subdir; the page renders a per-row warning icon.
|
||||
- **VACUUM failure** — DB is unaffected (VACUUM is atomic); the job ends `failed` with the SQLite error string. Status page shows a recoverable error issue.
|
||||
- **Non-SQLite maintenance call** — `vacuum`, `optimize`, and `reset` jobs fail with `not supported for <driver> driver` before running SQLite-only SQL; factory reset also rejects before stopping active executions.
|
||||
@@ -218,8 +254,6 @@ All System endpoints require the same "logged-in install user" check as the exis
|
||||
## Out of scope (v1)
|
||||
|
||||
- Live log tail (WS streaming of new lines as they're written).
|
||||
- Channel-aware upgrade hints (npm vs homebrew vs binary install path).
|
||||
- Admin/role gating of destructive actions; everyone who can sign in can VACUUM/Reset.
|
||||
- Importing or analyzing logs outside the diagnostic bundle's retained
|
||||
three-day and byte/profile limits.
|
||||
- Inline editing of `kandev_meta` or other system tables.
|
||||
@@ -230,7 +264,6 @@ All System endpoints require the same "logged-in install user" check as the exis
|
||||
## Future scope
|
||||
|
||||
- Live log tail via WS subscription.
|
||||
- Channel-aware update flow (detect install method, surface the right upgrade command, optionally invoke `kandev upgrade` from the UI for binary installs).
|
||||
- Selective reset (drop only tasks, only sessions, etc.) — only if users actually need finer-grained recovery than Restore-from-snapshot.
|
||||
- Backup scheduling (e.g., daily snapshot) beyond the existing pre-migration trigger.
|
||||
- Health-issue → action wiring (e.g., a "VACUUM" CTA inline on the "Database is XYZ MB" health issue).
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
|
||||
usage() {
|
||||
cat >&2 <<EOF
|
||||
Usage:
|
||||
$0 prepare --scheduled-sha <sha> --output <path>
|
||||
$0 publish --stable-at-start <version> --nightly-at-start <version> \\
|
||||
--tags-at-start <snapshot> --version <version> --assets-dir <path>
|
||||
EOF
|
||||
exit 2
|
||||
}
|
||||
|
||||
npm_version() {
|
||||
bash "$ROOT_DIR/scripts/release/npm-view-version.sh" "$1"
|
||||
}
|
||||
|
||||
latest_stable_tag() {
|
||||
local tag
|
||||
while IFS= read -r tag; do
|
||||
if [[ "$tag" =~ ^v[0-9]+\.[0-9]+(\.[0-9]+)?$ ]]; then
|
||||
printf '%s\n' "$tag"
|
||||
return 0
|
||||
fi
|
||||
done < <(git tag --list 'v*' --sort=-version:refname)
|
||||
return 0
|
||||
}
|
||||
|
||||
normalize_stable_tag() {
|
||||
local tag="$1"
|
||||
if [[ "$tag" =~ ^v([0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
|
||||
printf '%s\n' "${BASH_REMATCH[1]}"
|
||||
elif [[ "$tag" =~ ^v([0-9]+\.[0-9]+)$ ]]; then
|
||||
printf '%s.0\n' "${BASH_REMATCH[1]}"
|
||||
fi
|
||||
}
|
||||
|
||||
MATCHED_STABLE_TAG=""
|
||||
|
||||
stable_tag_matches_npm() {
|
||||
local npm_latest="$1"
|
||||
local tagged_stable
|
||||
MATCHED_STABLE_TAG="$(latest_stable_tag)"
|
||||
if [[ -z "$MATCHED_STABLE_TAG" ]]; then
|
||||
echo "No stable Git tag is available; skipping this best-effort Nightly run."
|
||||
return 1
|
||||
fi
|
||||
tagged_stable="$(normalize_stable_tag "$MATCHED_STABLE_TAG")"
|
||||
if [[ "$tagged_stable" != "$npm_latest" ]]; then
|
||||
echo "Highest stable Git tag $MATCHED_STABLE_TAG does not match npm @latest $npm_latest; skipping Nightly."
|
||||
return 1
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
write_output() {
|
||||
printf '%s=%s\n' "$1" "$2" >> "$OUTPUT_PATH"
|
||||
}
|
||||
|
||||
resolve_nightly_commit() {
|
||||
local version="$1"
|
||||
local label="$2"
|
||||
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+-nightly\.sha([0-9a-f]{12})$ ]]; then
|
||||
echo "$label has unsupported version '$version'; refusing to infer publication order." >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
local sha="${BASH_REMATCH[1]}"
|
||||
local commit
|
||||
if ! commit="$(git rev-parse --verify "${sha}^{commit}" 2>/dev/null)"; then
|
||||
echo "Cannot resolve $label commit prefix $sha in main history." >&2
|
||||
return 1
|
||||
fi
|
||||
printf '%s\n' "$commit"
|
||||
}
|
||||
|
||||
prepare() {
|
||||
local scheduled_sha=""
|
||||
OUTPUT_PATH=""
|
||||
while [[ "$#" -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--scheduled-sha)
|
||||
[[ "$#" -ge 2 ]] || usage
|
||||
scheduled_sha="$2"
|
||||
shift 2
|
||||
;;
|
||||
--output)
|
||||
[[ "$#" -ge 2 ]] || usage
|
||||
OUTPUT_PATH="$2"
|
||||
shift 2
|
||||
;;
|
||||
*) usage ;;
|
||||
esac
|
||||
done
|
||||
[[ -n "$scheduled_sha" && -n "$OUTPUT_PATH" ]] || usage
|
||||
|
||||
write_output should_publish false
|
||||
|
||||
local main_sha
|
||||
main_sha="$(git rev-parse HEAD)"
|
||||
if [[ "$main_sha" != "$scheduled_sha" ]]; then
|
||||
echo "Checked out $main_sha instead of scheduled SHA $scheduled_sha." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
local latest_stable
|
||||
if ! latest_stable="$(npm_version kandev@latest)"; then
|
||||
echo "Could not resolve npm @latest; skipping this best-effort Nightly run."
|
||||
return
|
||||
fi
|
||||
if [[ -z "$latest_stable" ]]; then
|
||||
echo "npm @latest is missing; skipping this best-effort Nightly run."
|
||||
return
|
||||
fi
|
||||
if ! stable_tag_matches_npm "$latest_stable"; then
|
||||
return
|
||||
fi
|
||||
write_output stable_version "$latest_stable"
|
||||
|
||||
local stable_commit
|
||||
stable_commit="$(git rev-parse "${MATCHED_STABLE_TAG}^{commit}")"
|
||||
if ! git merge-base --is-ancestor "$stable_commit" "$main_sha"; then
|
||||
if git merge-base --is-ancestor "$main_sha" "$stable_commit"; then
|
||||
echo "Scheduled commit $main_sha was superseded by stable v$latest_stable; skipping Nightly."
|
||||
return
|
||||
fi
|
||||
echo "Latest stable v$latest_stable is not an ancestor of scheduled main $main_sha." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$main_sha" == "$stable_commit" ]]; then
|
||||
echo "No commits on main since stable v$latest_stable; skipping nightly."
|
||||
return
|
||||
fi
|
||||
|
||||
local nightly_version
|
||||
nightly_version="$(node "$ROOT_DIR/scripts/release/nightly-version.mjs" "$latest_stable" "$main_sha")"
|
||||
write_output version "$nightly_version"
|
||||
write_output tag "v$nightly_version"
|
||||
write_output ref "$main_sha"
|
||||
|
||||
local published_nightly
|
||||
if ! published_nightly="$(npm_version kandev@nightly)"; then
|
||||
echo "Could not resolve npm @nightly; skipping this best-effort Nightly run."
|
||||
return
|
||||
fi
|
||||
write_output nightly_version_at_start "$published_nightly"
|
||||
|
||||
# shellcheck source=npm-packages.sh
|
||||
source "$ROOT_DIR/scripts/release/npm-packages.sh"
|
||||
|
||||
local published_commit=""
|
||||
if [[ -n "$published_nightly" ]]; then
|
||||
if ! published_commit="$(resolve_nightly_commit "$published_nightly" "kandev@nightly")"; then
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$published_commit" != "$main_sha" ]] &&
|
||||
git merge-base --is-ancestor "$main_sha" "$published_commit"; then
|
||||
echo "A Nightly from a newer main commit is already published; skipping superseded commit $main_sha."
|
||||
return
|
||||
fi
|
||||
if ! git merge-base --is-ancestor "$published_commit" "$main_sha"; then
|
||||
echo "Published Nightly commit $published_commit is not an ancestor of scheduled main $main_sha." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
local all_packages_published=true
|
||||
local nightly_tags_at_start=""
|
||||
local package published_version tagged_version tagged_commit
|
||||
for package in "${NIGHTLY_PACKAGES[@]}"; do
|
||||
if ! published_version="$(npm_version "${package}@$nightly_version")"; then
|
||||
echo "Could not verify ${package}@$nightly_version; skipping this best-effort Nightly run."
|
||||
return
|
||||
fi
|
||||
if ! tagged_version="$(npm_version "${package}@nightly")"; then
|
||||
echo "Could not verify ${package}@nightly; skipping this best-effort Nightly run."
|
||||
return
|
||||
fi
|
||||
nightly_tags_at_start+="${package}=${tagged_version};"
|
||||
|
||||
if [[ -n "$published_version" ]]; then
|
||||
if [[ "$tagged_version" != "$nightly_version" ]]; then
|
||||
echo "${package}@$nightly_version exists but @nightly resolves to '${tagged_version:-nothing}'." >&2
|
||||
exit 1
|
||||
fi
|
||||
continue
|
||||
fi
|
||||
|
||||
all_packages_published=false
|
||||
if [[ -n "$tagged_version" && "$tagged_version" != "$published_nightly" ]]; then
|
||||
if ! tagged_commit="$(resolve_nightly_commit "$tagged_version" "${package}@nightly")"; then
|
||||
exit 1
|
||||
fi
|
||||
if ! git merge-base --is-ancestor "$tagged_commit" "$main_sha"; then
|
||||
echo "${package}@nightly commit $tagged_commit is not an ancestor of scheduled main $main_sha." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "${package}@nightly is an older partial publication; the current publish will repair it."
|
||||
fi
|
||||
done
|
||||
write_output nightly_tags_at_start "$nightly_tags_at_start"
|
||||
|
||||
if [[ -n "$published_nightly" && "$all_packages_published" == "true" ]]; then
|
||||
if [[ "$published_commit" != "$main_sha" ]]; then
|
||||
echo "Nightly version identity does not resolve to scheduled commit $main_sha." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "All Nightly packages are already published under @nightly; skipping."
|
||||
return
|
||||
fi
|
||||
|
||||
write_output should_publish true
|
||||
}
|
||||
|
||||
publish() {
|
||||
local stable_at_start=""
|
||||
local nightly_at_start=""
|
||||
local tags_at_start=""
|
||||
local version=""
|
||||
local assets_dir=""
|
||||
local nightly_set=false
|
||||
local tags_set=false
|
||||
while [[ "$#" -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--stable-at-start)
|
||||
[[ "$#" -ge 2 ]] || usage
|
||||
stable_at_start="$2"
|
||||
shift 2
|
||||
;;
|
||||
--nightly-at-start)
|
||||
[[ "$#" -ge 2 ]] || usage
|
||||
nightly_at_start="$2"
|
||||
nightly_set=true
|
||||
shift 2
|
||||
;;
|
||||
--tags-at-start)
|
||||
[[ "$#" -ge 2 ]] || usage
|
||||
tags_at_start="$2"
|
||||
tags_set=true
|
||||
shift 2
|
||||
;;
|
||||
--version)
|
||||
[[ "$#" -ge 2 ]] || usage
|
||||
version="$2"
|
||||
shift 2
|
||||
;;
|
||||
--assets-dir)
|
||||
[[ "$#" -ge 2 ]] || usage
|
||||
assets_dir="$2"
|
||||
shift 2
|
||||
;;
|
||||
*) usage ;;
|
||||
esac
|
||||
done
|
||||
if [[ -z "$stable_at_start" || -z "$version" || -z "$assets_dir" ||
|
||||
"$nightly_set" != "true" || "$tags_set" != "true" ]]; then
|
||||
usage
|
||||
fi
|
||||
|
||||
local current_latest
|
||||
if ! current_latest="$(npm_version kandev@latest)"; then
|
||||
echo "Could not revalidate npm @latest; skipping Nightly publication."
|
||||
return
|
||||
fi
|
||||
if [[ -z "$current_latest" ]]; then
|
||||
echo "npm @latest is missing; skipping Nightly publication."
|
||||
return
|
||||
fi
|
||||
if ! stable_tag_matches_npm "$current_latest"; then
|
||||
return
|
||||
fi
|
||||
if [[ "$current_latest" != "$stable_at_start" ]]; then
|
||||
echo "Stable npm baseline moved from $stable_at_start to $current_latest while this run was building; skipping stale Nightly publication."
|
||||
return
|
||||
fi
|
||||
|
||||
local current_nightly
|
||||
if ! current_nightly="$(npm_version kandev@nightly)"; then
|
||||
echo "Could not revalidate npm @nightly; skipping Nightly publication."
|
||||
return
|
||||
fi
|
||||
if [[ "$current_nightly" != "$nightly_at_start" ]]; then
|
||||
echo "npm @nightly moved from ${nightly_at_start:-nothing} to ${current_nightly:-nothing} while this run was building; skipping superseded publication."
|
||||
return
|
||||
fi
|
||||
|
||||
# shellcheck source=npm-packages.sh
|
||||
source "$ROOT_DIR/scripts/release/npm-packages.sh"
|
||||
local current_nightly_tags=""
|
||||
local package tagged_version
|
||||
for package in "${NIGHTLY_PACKAGES[@]}"; do
|
||||
if ! tagged_version="$(npm_version "${package}@nightly")"; then
|
||||
echo "Could not revalidate ${package}@nightly; skipping Nightly publication."
|
||||
return
|
||||
fi
|
||||
current_nightly_tags+="${package}=${tagged_version};"
|
||||
done
|
||||
if [[ "$current_nightly_tags" != "$tags_at_start" ]]; then
|
||||
echo "One or more npm @nightly tags moved while this run was building; skipping superseded publication."
|
||||
return
|
||||
fi
|
||||
|
||||
bash "$ROOT_DIR/scripts/release/publish-npm.sh" \
|
||||
--version "$version" \
|
||||
--dist-tag nightly \
|
||||
--assets-dir "$assets_dir"
|
||||
}
|
||||
|
||||
cd "$ROOT_DIR"
|
||||
command="${1:-}"
|
||||
[[ -n "$command" ]] || usage
|
||||
shift
|
||||
case "$command" in
|
||||
prepare) prepare "$@" ;;
|
||||
publish) publish "$@" ;;
|
||||
*) usage ;;
|
||||
esac
|
||||
@@ -0,0 +1,546 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import {
|
||||
chmod,
|
||||
copyFile,
|
||||
mkdir,
|
||||
mkdtemp,
|
||||
readFile,
|
||||
rm,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
|
||||
const sourceRoot = path.resolve(import.meta.dirname, "../..");
|
||||
const packages = [
|
||||
"kandev",
|
||||
"@kdlbs/runtime-linux-x64",
|
||||
"@kdlbs/runtime-linux-arm64",
|
||||
"@kdlbs/runtime-darwin-x64",
|
||||
"@kdlbs/runtime-darwin-arm64",
|
||||
"@kdlbs/runtime-win32-x64",
|
||||
];
|
||||
|
||||
async function writeExecutable(file, content) {
|
||||
await writeFile(file, content);
|
||||
await chmod(file, 0o755);
|
||||
}
|
||||
|
||||
function git(root, ...args) {
|
||||
return execFileSync("git", args, { cwd: root, encoding: "utf8" }).trim();
|
||||
}
|
||||
|
||||
async function createFixture() {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "kandev-nightly-release-"));
|
||||
const releaseDir = path.join(root, "scripts/release");
|
||||
const binDir = path.join(root, "bin");
|
||||
const assetsDir = path.join(root, "assets");
|
||||
const stateFile = path.join(root, "npm-state.tsv");
|
||||
const outputFile = path.join(root, "github-output");
|
||||
const publishLog = path.join(root, "publish.log");
|
||||
await Promise.all([
|
||||
mkdir(releaseDir, { recursive: true }),
|
||||
mkdir(binDir, { recursive: true }),
|
||||
mkdir(assetsDir, { recursive: true }),
|
||||
writeFile(stateFile, ""),
|
||||
writeFile(outputFile, ""),
|
||||
writeFile(publishLog, ""),
|
||||
]);
|
||||
await Promise.all(
|
||||
[
|
||||
"nightly-release.sh",
|
||||
"nightly-version.mjs",
|
||||
"npm-packages.sh",
|
||||
"npm-view-version.sh",
|
||||
].map((name) =>
|
||||
copyFile(
|
||||
path.join(sourceRoot, "scripts/release", name),
|
||||
path.join(releaseDir, name),
|
||||
),
|
||||
),
|
||||
);
|
||||
await writeExecutable(
|
||||
path.join(releaseDir, "publish-npm.sh"),
|
||||
`#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
printf '%s\n' "$@" >> "$MOCK_PUBLISH_LOG"
|
||||
`,
|
||||
);
|
||||
await writeExecutable(
|
||||
path.join(binDir, "npm"),
|
||||
`#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
if [[ "$1" != "view" || "$3" != "version" ]]; then
|
||||
printf 'unexpected npm command: %s\n' "$*" >&2
|
||||
exit 2
|
||||
fi
|
||||
spec="$2"
|
||||
while IFS=$'\t' read -r key value; do
|
||||
if [[ "$key" != "$spec" ]]; then
|
||||
continue
|
||||
fi
|
||||
if [[ "$value" == "!ERROR!" ]]; then
|
||||
printf '%s\n' 'npm error code EAI_AGAIN' >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "$value"
|
||||
exit 0
|
||||
done < "$MOCK_NPM_STATE"
|
||||
printf '%s\n' 'npm error code E404' >&2
|
||||
exit 1
|
||||
`,
|
||||
);
|
||||
await writeExecutable(
|
||||
path.join(binDir, "sleep"),
|
||||
"#!/usr/bin/env bash\nexit 0\n",
|
||||
);
|
||||
|
||||
git(root, "init", "-q");
|
||||
git(root, "config", "user.name", "Nightly Test");
|
||||
git(root, "config", "user.email", "nightly@example.test");
|
||||
await writeFile(path.join(root, "history.txt"), "stable\n");
|
||||
git(root, "add", "history.txt");
|
||||
git(root, "commit", "-q", "-m", "stable");
|
||||
const stableSha = git(root, "rev-parse", "HEAD");
|
||||
git(root, "tag", "v1.2.3");
|
||||
await writeFile(path.join(root, "history.txt"), "stable\nmain\n");
|
||||
git(root, "add", "history.txt");
|
||||
git(root, "commit", "-q", "-m", "main");
|
||||
const mainSha = git(root, "rev-parse", "HEAD");
|
||||
await writeFile(path.join(root, "history.txt"), "stable\nmain\nnewer\n");
|
||||
git(root, "add", "history.txt");
|
||||
git(root, "commit", "-q", "-m", "newer");
|
||||
const newerSha = git(root, "rev-parse", "HEAD");
|
||||
git(root, "checkout", "-q", "--detach", stableSha);
|
||||
await writeFile(path.join(root, "history.txt"), "stable\ndivergent\n");
|
||||
git(root, "add", "history.txt");
|
||||
git(root, "commit", "-q", "-m", "divergent");
|
||||
const divergentSha = git(root, "rev-parse", "HEAD");
|
||||
git(root, "checkout", "-q", "--detach", mainSha);
|
||||
|
||||
return {
|
||||
root,
|
||||
releaseDir,
|
||||
binDir,
|
||||
assetsDir,
|
||||
stateFile,
|
||||
outputFile,
|
||||
publishLog,
|
||||
stableSha,
|
||||
mainSha,
|
||||
newerSha,
|
||||
divergentSha,
|
||||
version: `1.2.4-nightly.sha${mainSha.slice(0, 12)}`,
|
||||
};
|
||||
}
|
||||
|
||||
async function setRegistry(fixture, entries) {
|
||||
const lines = [...entries].map(([spec, value]) => `${spec}\t${value}`);
|
||||
await writeFile(
|
||||
fixture.stateFile,
|
||||
lines.length === 0 ? "" : `${lines.join("\n")}\n`,
|
||||
);
|
||||
}
|
||||
|
||||
function runScript(fixture, ...args) {
|
||||
return spawnSync(
|
||||
"bash",
|
||||
[path.join(fixture.releaseDir, "nightly-release.sh"), ...args],
|
||||
{
|
||||
cwd: fixture.root,
|
||||
encoding: "utf8",
|
||||
env: {
|
||||
...process.env,
|
||||
MOCK_NPM_STATE: fixture.stateFile,
|
||||
MOCK_PUBLISH_LOG: fixture.publishLog,
|
||||
PATH: `${fixture.binDir}${path.delimiter}${process.env.PATH ?? ""}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function runPrepare(fixture, scheduledSha = fixture.mainSha) {
|
||||
await writeFile(fixture.outputFile, "");
|
||||
const result = runScript(
|
||||
fixture,
|
||||
"prepare",
|
||||
"--scheduled-sha",
|
||||
scheduledSha,
|
||||
"--output",
|
||||
fixture.outputFile,
|
||||
);
|
||||
const output = Object.fromEntries(
|
||||
(await readFile(fixture.outputFile, "utf8"))
|
||||
.trim()
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.map((line) => {
|
||||
const separator = line.indexOf("=");
|
||||
return [line.slice(0, separator), line.slice(separator + 1)];
|
||||
}),
|
||||
);
|
||||
return { ...result, output };
|
||||
}
|
||||
|
||||
function registryFor(version, nightly = "") {
|
||||
const entries = new Map([["kandev@latest", "1.2.3"]]);
|
||||
if (nightly) entries.set("kandev@nightly", nightly);
|
||||
for (const packageName of packages) {
|
||||
entries.set(`${packageName}@${version}`, version);
|
||||
entries.set(`${packageName}@nightly`, version);
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
function tagsSnapshot(version) {
|
||||
return packages.map((packageName) => `${packageName}=${version};`).join("");
|
||||
}
|
||||
|
||||
test("prepare publishes a changed main commit and snapshots empty tags", async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
await setRegistry(fixture, new Map([["kandev@latest", "1.2.3"]]));
|
||||
const result = await runPrepare(fixture);
|
||||
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(result.output.should_publish, "true");
|
||||
assert.equal(result.output.stable_version, "1.2.3");
|
||||
assert.equal(result.output.version, fixture.version);
|
||||
assert.equal(result.output.tag, `v${fixture.version}`);
|
||||
assert.equal(result.output.ref, fixture.mainSha);
|
||||
assert.equal(result.output.nightly_version_at_start, "");
|
||||
assert.equal(result.output.nightly_tags_at_start, tagsSnapshot(""));
|
||||
} finally {
|
||||
await rm(fixture.root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("prepare normalizes a legacy two-part stable tag", async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
git(fixture.root, "tag", "-d", "v1.2.3");
|
||||
git(fixture.root, "tag", "v1.2", fixture.stableSha);
|
||||
await setRegistry(fixture, new Map([["kandev@latest", "1.2.0"]]));
|
||||
const result = await runPrepare(fixture);
|
||||
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(result.output.should_publish, "true");
|
||||
assert.equal(result.output.stable_version, "1.2.0");
|
||||
assert.equal(
|
||||
result.output.version,
|
||||
`1.2.1-nightly.sha${fixture.mainSha.slice(0, 12)}`,
|
||||
);
|
||||
} finally {
|
||||
await rm(fixture.root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("prepare skips when main has no commit after stable", async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
git(fixture.root, "checkout", "-q", "--detach", fixture.stableSha);
|
||||
await setRegistry(fixture, new Map([["kandev@latest", "1.2.3"]]));
|
||||
const result = await runPrepare(fixture, fixture.stableSha);
|
||||
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(result.output.should_publish, "false");
|
||||
assert.match(result.stdout, /No commits on main since stable/);
|
||||
} finally {
|
||||
await rm(fixture.root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("prepare skips while a stable Git tag is ahead of npm latest", async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
git(fixture.root, "tag", "v1.3.0", fixture.mainSha);
|
||||
await setRegistry(fixture, new Map([["kandev@latest", "1.2.3"]]));
|
||||
const result = await runPrepare(fixture);
|
||||
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(result.output.should_publish, "false");
|
||||
assert.match(result.stdout, /stable Git tag v1\.3\.0.*npm @latest 1\.2\.3/);
|
||||
} finally {
|
||||
await rm(fixture.root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("prepare skips a scheduled commit superseded by the current stable", async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
git(fixture.root, "tag", "v1.3.0", fixture.newerSha);
|
||||
await setRegistry(fixture, new Map([["kandev@latest", "1.3.0"]]));
|
||||
const result = await runPrepare(fixture);
|
||||
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(result.output.should_publish, "false");
|
||||
assert.match(result.stdout, /superseded by stable v1\.3\.0/);
|
||||
} finally {
|
||||
await rm(fixture.root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("prepare skips a complete publication and repairs a partial one", async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
const complete = registryFor(fixture.version, fixture.version);
|
||||
await setRegistry(fixture, complete);
|
||||
const completeResult = await runPrepare(fixture);
|
||||
assert.equal(completeResult.status, 0, completeResult.stderr);
|
||||
assert.equal(completeResult.output.should_publish, "false");
|
||||
|
||||
complete.delete(`${packages.at(-1)}@${fixture.version}`);
|
||||
await setRegistry(fixture, complete);
|
||||
const partialResult = await runPrepare(fixture);
|
||||
assert.equal(partialResult.status, 0, partialResult.stderr);
|
||||
assert.equal(partialResult.output.should_publish, "true");
|
||||
} finally {
|
||||
await rm(fixture.root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("prepare skips a scheduled commit superseded by a newer main Nightly", async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
const newerVersion = `1.2.4-nightly.sha${fixture.newerSha.slice(0, 12)}`;
|
||||
await setRegistry(
|
||||
fixture,
|
||||
new Map([
|
||||
["kandev@latest", "1.2.3"],
|
||||
["kandev@nightly", newerVersion],
|
||||
]),
|
||||
);
|
||||
const result = await runPrepare(fixture);
|
||||
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(result.output.should_publish, "false");
|
||||
assert.match(result.stdout, /newer main commit is already published/);
|
||||
} finally {
|
||||
await rm(fixture.root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("prepare rejects a Nightly version that cannot identify a commit", async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
await setRegistry(
|
||||
fixture,
|
||||
new Map([
|
||||
["kandev@latest", "1.2.3"],
|
||||
["kandev@nightly", "1.2.4-nightly.bad"],
|
||||
]),
|
||||
);
|
||||
const result = await runPrepare(fixture);
|
||||
|
||||
assert.notEqual(result.status, 0);
|
||||
assert.match(result.stderr, /unsupported version/);
|
||||
} finally {
|
||||
await rm(fixture.root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("prepare rejects registry commits outside scheduled main history", async () => {
|
||||
const cases = [
|
||||
{
|
||||
name: "stable baseline",
|
||||
configure(fixture, registry) {
|
||||
git(fixture.root, "tag", "-f", "v1.2.3", fixture.divergentSha);
|
||||
return registry;
|
||||
},
|
||||
error: /Latest stable .* is not an ancestor/,
|
||||
},
|
||||
{
|
||||
name: "top-level Nightly",
|
||||
configure(fixture, registry) {
|
||||
registry.set(
|
||||
"kandev@nightly",
|
||||
`1.2.4-nightly.sha${fixture.divergentSha.slice(0, 12)}`,
|
||||
);
|
||||
return registry;
|
||||
},
|
||||
error: /Published Nightly commit .* is not an ancestor/,
|
||||
},
|
||||
{
|
||||
name: "partial runtime tag",
|
||||
configure(fixture, registry) {
|
||||
const packageName = packages.at(-1);
|
||||
registry.set("kandev@nightly", fixture.version);
|
||||
registry.delete(`${packageName}@${fixture.version}`);
|
||||
registry.set(
|
||||
`${packageName}@nightly`,
|
||||
`1.2.4-nightly.sha${fixture.divergentSha.slice(0, 12)}`,
|
||||
);
|
||||
return registry;
|
||||
},
|
||||
error: /@nightly commit .* is not an ancestor/,
|
||||
},
|
||||
];
|
||||
|
||||
for (const scenario of cases) {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
const registry = scenario.configure(
|
||||
fixture,
|
||||
registryFor(fixture.version, fixture.version),
|
||||
);
|
||||
await setRegistry(fixture, registry);
|
||||
const result = await runPrepare(fixture);
|
||||
|
||||
assert.notEqual(result.status, 0, scenario.name);
|
||||
assert.match(result.stderr, scenario.error, scenario.name);
|
||||
} finally {
|
||||
await rm(fixture.root, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("prepare rejects an exact package whose Nightly tag points elsewhere", async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
const registry = registryFor(fixture.version, fixture.version);
|
||||
registry.set(
|
||||
`${packages.at(-1)}@nightly`,
|
||||
`1.2.4-nightly.sha${fixture.stableSha.slice(0, 12)}`,
|
||||
);
|
||||
await setRegistry(fixture, registry);
|
||||
const result = await runPrepare(fixture);
|
||||
|
||||
assert.notEqual(result.status, 0);
|
||||
assert.match(result.stderr, /exists but @nightly resolves/);
|
||||
} finally {
|
||||
await rm(fixture.root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("prepare safely skips registry failures", async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
await setRegistry(fixture, new Map([["kandev@latest", "!ERROR!"]]));
|
||||
const result = await runPrepare(fixture);
|
||||
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(result.output.should_publish, "false");
|
||||
assert.match(result.stdout, /Could not resolve npm @latest/);
|
||||
} finally {
|
||||
await rm(fixture.root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("prepare safely skips a package registry failure", async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
const registry = new Map([
|
||||
["kandev@latest", "1.2.3"],
|
||||
[`${packages[1]}@${fixture.version}`, "!ERROR!"],
|
||||
]);
|
||||
await setRegistry(fixture, registry);
|
||||
const result = await runPrepare(fixture);
|
||||
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(result.output.should_publish, "false");
|
||||
assert.match(result.stdout, /Could not verify/);
|
||||
} finally {
|
||||
await rm(fixture.root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("publish revalidates the registry snapshot before delegating", async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
await setRegistry(fixture, registryFor(fixture.version, fixture.version));
|
||||
const result = runScript(
|
||||
fixture,
|
||||
"publish",
|
||||
"--stable-at-start",
|
||||
"1.2.3",
|
||||
"--nightly-at-start",
|
||||
fixture.version,
|
||||
"--tags-at-start",
|
||||
tagsSnapshot(fixture.version),
|
||||
"--version",
|
||||
fixture.version,
|
||||
"--assets-dir",
|
||||
fixture.assetsDir,
|
||||
);
|
||||
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.deepEqual(
|
||||
(await readFile(fixture.publishLog, "utf8")).trim().split("\n"),
|
||||
[
|
||||
"--version",
|
||||
fixture.version,
|
||||
"--dist-tag",
|
||||
"nightly",
|
||||
"--assets-dir",
|
||||
fixture.assetsDir,
|
||||
],
|
||||
);
|
||||
} finally {
|
||||
await rm(fixture.root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("publish skips when any locked registry value moves", async () => {
|
||||
const cases = [
|
||||
["stable baseline", "kandev@latest", "1.2.4"],
|
||||
["top-level Nightly", "kandev@nightly", "1.2.4-nightly.sha000000000000"],
|
||||
["runtime tag", `${packages[1]}@nightly`, "1.2.4-nightly.sha000000000000"],
|
||||
];
|
||||
for (const [name, spec, movedValue] of cases) {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
const registry = registryFor(fixture.version, fixture.version);
|
||||
registry.set(spec, movedValue);
|
||||
await setRegistry(fixture, registry);
|
||||
const result = runScript(
|
||||
fixture,
|
||||
"publish",
|
||||
"--stable-at-start",
|
||||
"1.2.3",
|
||||
"--nightly-at-start",
|
||||
fixture.version,
|
||||
"--tags-at-start",
|
||||
tagsSnapshot(fixture.version),
|
||||
"--version",
|
||||
fixture.version,
|
||||
"--assets-dir",
|
||||
fixture.assetsDir,
|
||||
);
|
||||
|
||||
assert.equal(result.status, 0, `${name}: ${result.stderr}`);
|
||||
assert.equal(await readFile(fixture.publishLog, "utf8"), "", name);
|
||||
} finally {
|
||||
await rm(fixture.root, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("publish skips while a stable Git tag is ahead of npm latest", async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
git(fixture.root, "tag", "v1.3.0", fixture.mainSha);
|
||||
await setRegistry(fixture, registryFor(fixture.version, fixture.version));
|
||||
const result = runScript(
|
||||
fixture,
|
||||
"publish",
|
||||
"--stable-at-start",
|
||||
"1.2.3",
|
||||
"--nightly-at-start",
|
||||
fixture.version,
|
||||
"--tags-at-start",
|
||||
tagsSnapshot(fixture.version),
|
||||
"--version",
|
||||
fixture.version,
|
||||
"--assets-dir",
|
||||
fixture.assetsDir,
|
||||
);
|
||||
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(await readFile(fixture.publishLog, "utf8"), "");
|
||||
assert.match(result.stdout, /stable Git tag v1\.3\.0.*npm @latest 1\.2\.3/);
|
||||
} finally {
|
||||
await rm(fixture.root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
const STABLE_SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
|
||||
const FULL_GIT_SHA = /^[0-9a-f]{40}$/;
|
||||
|
||||
export function nightlyVersion(stableVersion, commitSha) {
|
||||
const match = STABLE_SEMVER.exec(stableVersion);
|
||||
if (match === null) {
|
||||
throw new Error(`Expected a stable SemVer X.Y.Z, received: ${stableVersion}`);
|
||||
}
|
||||
if (!FULL_GIT_SHA.test(commitSha)) {
|
||||
throw new Error("Expected a 40-character lowercase hexadecimal Git commit SHA");
|
||||
}
|
||||
|
||||
const [, major, minor, patch] = match;
|
||||
return `${major}.${minor}.${BigInt(patch) + 1n}-nightly.sha${commitSha.slice(0, 12)}`;
|
||||
}
|
||||
|
||||
function main(args) {
|
||||
if (args.length !== 2) {
|
||||
throw new Error("Usage: nightly-version.mjs <stable-version> <40-character-commit-sha>");
|
||||
}
|
||||
process.stdout.write(`${nightlyVersion(args[0], args[1])}\n`);
|
||||
}
|
||||
|
||||
if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
try {
|
||||
main(process.argv.slice(2));
|
||||
} catch (error) {
|
||||
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import test from "node:test";
|
||||
|
||||
import { nightlyVersion } from "./nightly-version.mjs";
|
||||
|
||||
const fullSha = "abc123def4567890abc123def4567890abc123de";
|
||||
|
||||
test("builds the next patch nightly version from a stable version and commit SHA", () => {
|
||||
assert.equal(
|
||||
nightlyVersion("0.82.0", fullSha),
|
||||
"0.82.1-nightly.shaabc123def456",
|
||||
);
|
||||
});
|
||||
|
||||
test("keeps leading zeroes in the hexadecimal SHA prefix", () => {
|
||||
assert.equal(
|
||||
nightlyVersion("12.34.56", "0000000000017890abc123def4567890abc123de"),
|
||||
"12.34.57-nightly.sha000000000001",
|
||||
);
|
||||
});
|
||||
|
||||
test("rejects non-stable or non-canonical base versions", () => {
|
||||
for (const version of [
|
||||
"v0.82.0",
|
||||
"0.82",
|
||||
"0.82.0-beta.1",
|
||||
"01.2.3",
|
||||
"1.02.3",
|
||||
"1.2.03",
|
||||
]) {
|
||||
assert.throws(() => nightlyVersion(version, fullSha), /stable SemVer/);
|
||||
}
|
||||
});
|
||||
|
||||
test("rejects anything except a full lowercase Git commit SHA", () => {
|
||||
for (const sha of [
|
||||
"abc123def456",
|
||||
fullSha.toUpperCase(),
|
||||
`${fullSha}0`,
|
||||
"not-a-sha",
|
||||
]) {
|
||||
assert.throws(
|
||||
() => nightlyVersion("0.82.0", sha),
|
||||
/40-character lowercase hexadecimal/,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("prints the nightly version when invoked as a CLI", () => {
|
||||
const output = execFileSync(process.execPath, [
|
||||
fileURLToPath(new URL("./nightly-version.mjs", import.meta.url)),
|
||||
"0.82.0",
|
||||
fullSha,
|
||||
]);
|
||||
assert.equal(output.toString(), "0.82.1-nightly.shaabc123def456\n");
|
||||
});
|
||||
|
||||
test("exits non-zero with usage when invoked without arguments", () => {
|
||||
const result = spawnSync(
|
||||
process.execPath,
|
||||
[fileURLToPath(new URL("./nightly-version.mjs", import.meta.url))],
|
||||
{ encoding: "utf8" },
|
||||
);
|
||||
|
||||
assert.notEqual(result.status, 0);
|
||||
assert.match(result.stderr, /Usage:/);
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env bash
|
||||
# Shared platform and package inventory for npm packaging, tests, preflight,
|
||||
# and publication. Launcher mappings and package metadata remain independently
|
||||
# checked against this inventory by release-config.test.ts.
|
||||
|
||||
RUNTIME_PLATFORMS=(
|
||||
"linux-x64"
|
||||
"linux-arm64"
|
||||
"macos-x64"
|
||||
"macos-arm64"
|
||||
"windows-x64"
|
||||
)
|
||||
declare -A RUNTIME_PACKAGE_BY_PLATFORM=(
|
||||
["linux-x64"]="@kdlbs/runtime-linux-x64"
|
||||
["linux-arm64"]="@kdlbs/runtime-linux-arm64"
|
||||
["macos-x64"]="@kdlbs/runtime-darwin-x64"
|
||||
["macos-arm64"]="@kdlbs/runtime-darwin-arm64"
|
||||
["windows-x64"]="@kdlbs/runtime-win32-x64"
|
||||
)
|
||||
RUNTIME_PACKAGES=()
|
||||
for runtime_platform in "${RUNTIME_PLATFORMS[@]}"; do
|
||||
RUNTIME_PACKAGES+=("${RUNTIME_PACKAGE_BY_PLATFORM[$runtime_platform]}")
|
||||
done
|
||||
unset runtime_platform
|
||||
NIGHTLY_PACKAGES=("kandev" "${RUNTIME_PACKAGES[@]}")
|
||||
|
||||
readonly -a RUNTIME_PLATFORMS RUNTIME_PACKAGES NIGHTLY_PACKAGES
|
||||
readonly -A RUNTIME_PACKAGE_BY_PLATFORM
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env bash
|
||||
# Resolve one npm package/version spec. A missing package, version, or dist-tag
|
||||
# is a successful empty result; registry and network failures are errors.
|
||||
set -euo pipefail
|
||||
|
||||
if [[ "$#" -ne 1 || -z "$1" ]]; then
|
||||
echo "Usage: $0 <package-spec>" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
SPEC="$1"
|
||||
ERROR_FILE="$(mktemp)"
|
||||
trap 'rm -f "$ERROR_FILE"' EXIT
|
||||
MAX_ATTEMPTS=3
|
||||
RETRY_DELAY_SECONDS=2
|
||||
|
||||
for ((attempt = 1; attempt <= MAX_ATTEMPTS; attempt++)); do
|
||||
if VERSION="$(npm view "$SPEC" version --loglevel=error 2>"$ERROR_FILE")"; then
|
||||
printf '%s\n' "$VERSION"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if grep -qiE '^npm (error|ERR!) (code E404|404([[:space:]]|$)|No match found for version|[^[:space:]]+ is not in this registry)' "$ERROR_FILE"; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if ((attempt < MAX_ATTEMPTS)); then
|
||||
echo "npm view attempt $attempt/$MAX_ATTEMPTS failed for $SPEC; retrying" >&2
|
||||
sleep "$RETRY_DELAY_SECONDS"
|
||||
fi
|
||||
done
|
||||
|
||||
echo "npm view failed for $SPEC" >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,107 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import test from "node:test";
|
||||
|
||||
const repoRoot = path.resolve(import.meta.dirname, "../..");
|
||||
const script = path.join(repoRoot, "scripts/release/npm-view-version.sh");
|
||||
|
||||
async function runView(mode) {
|
||||
const fixtureDir = await mkdtemp(path.join(tmpdir(), "kandev-npm-view-"));
|
||||
const npm = path.join(fixtureDir, "npm");
|
||||
const sleep = path.join(fixtureDir, "sleep");
|
||||
const countFile = path.join(fixtureDir, "attempts");
|
||||
const sleepFile = path.join(fixtureDir, "sleeps");
|
||||
await writeFile(
|
||||
npm,
|
||||
`#!/usr/bin/env bash
|
||||
count=0
|
||||
if [[ -f "$MOCK_NPM_COUNT_FILE" ]]; then read -r count < "$MOCK_NPM_COUNT_FILE"; fi
|
||||
count=$((count + 1))
|
||||
printf '%s\n' "$count" > "$MOCK_NPM_COUNT_FILE"
|
||||
case "$MOCK_NPM_MODE" in
|
||||
found) printf '%s\\n' '1.2.4-nightly.shaabc123def456' ;;
|
||||
missing) printf '%s\\n' 'npm error code E404' 'npm error No match found for version nightly' >&2; exit 1 ;;
|
||||
transient)
|
||||
if (( count < 3 )); then
|
||||
printf '%s\\n' 'npm error code EAI_AGAIN' >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\\n' '1.2.4-nightly.shaabc123def456'
|
||||
;;
|
||||
failure) printf '%s\\n' 'npm error code EAI_AGAIN' 'registry-secret-detail' >&2; exit 1 ;;
|
||||
misleading) printf '%s\\n' 'npm error code EAI_AGAIN' 'npm error request to https://registry.test/e404/404-Not-Found/is-not-in-this-registry failed' >&2; exit 1 ;;
|
||||
esac
|
||||
`,
|
||||
);
|
||||
await writeFile(sleepFile, "");
|
||||
await writeFile(
|
||||
sleep,
|
||||
'#!/usr/bin/env bash\nprintf \'%s\\n\' "$1" >> "$MOCK_SLEEP_FILE"\n',
|
||||
);
|
||||
await chmod(npm, 0o755);
|
||||
await chmod(sleep, 0o755);
|
||||
try {
|
||||
const result = spawnSync("bash", [script, "kandev@nightly"], {
|
||||
encoding: "utf8",
|
||||
env: {
|
||||
...process.env,
|
||||
MOCK_NPM_COUNT_FILE: countFile,
|
||||
MOCK_NPM_MODE: mode,
|
||||
MOCK_SLEEP_FILE: sleepFile,
|
||||
PATH: `${fixtureDir}${path.delimiter}${process.env.PATH ?? ""}`,
|
||||
},
|
||||
});
|
||||
result.attempts = Number(await readFile(countFile, "utf8"));
|
||||
result.sleeps = (await readFile(sleepFile, "utf8"))
|
||||
.trim()
|
||||
.split("\n")
|
||||
.filter(Boolean);
|
||||
return result;
|
||||
} finally {
|
||||
await rm(fixtureDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
test("prints a resolved npm version", async () => {
|
||||
const result = await runView("found");
|
||||
assert.equal(result.status, 0);
|
||||
assert.equal(result.stdout.trim(), "1.2.4-nightly.shaabc123def456");
|
||||
assert.deepEqual(result.sleeps, []);
|
||||
});
|
||||
|
||||
test("treats a missing version or dist-tag as an empty result", async () => {
|
||||
const result = await runView("missing");
|
||||
assert.equal(result.status, 0);
|
||||
assert.equal(result.stdout, "");
|
||||
assert.equal(result.stderr, "");
|
||||
assert.equal(result.attempts, 1);
|
||||
assert.deepEqual(result.sleeps, []);
|
||||
});
|
||||
|
||||
test("retries transient registry failures before succeeding", async () => {
|
||||
const result = await runView("transient");
|
||||
assert.equal(result.status, 0);
|
||||
assert.equal(result.stdout.trim(), "1.2.4-nightly.shaabc123def456");
|
||||
assert.equal(result.attempts, 3);
|
||||
assert.deepEqual(result.sleeps, ["2", "2"]);
|
||||
});
|
||||
|
||||
test("fails closed on registry and network errors", async () => {
|
||||
const result = await runView("failure");
|
||||
assert.notEqual(result.status, 0);
|
||||
assert.match(result.stderr, /npm view failed for kandev@nightly/);
|
||||
assert.doesNotMatch(result.stderr, /registry-secret-detail/);
|
||||
assert.equal(result.attempts, 3);
|
||||
assert.deepEqual(result.sleeps, ["2", "2"]);
|
||||
});
|
||||
|
||||
test("does not mistake missing-looking request URLs for npm E404 diagnostics", async () => {
|
||||
const result = await runView("misleading");
|
||||
assert.notEqual(result.status, 0);
|
||||
assert.match(result.stderr, /npm view failed for kandev@nightly/);
|
||||
assert.equal(result.attempts, 3);
|
||||
assert.deepEqual(result.sleeps, ["2", "2"]);
|
||||
});
|
||||
@@ -13,55 +13,29 @@
|
||||
# release-assets-dir Directory containing kandev-*.tar.gz files
|
||||
# output-dir Directory where per-platform npm packages are written
|
||||
#
|
||||
# Output (one directory per platform ready for npm publish):
|
||||
# <output-dir>/@kdlbs/runtime-linux-x64/
|
||||
# <output-dir>/@kdlbs/runtime-linux-arm64/
|
||||
# <output-dir>/@kdlbs/runtime-darwin-x64/
|
||||
# <output-dir>/@kdlbs/runtime-darwin-arm64/
|
||||
# <output-dir>/@kdlbs/runtime-win32-x64/
|
||||
# Output: one scoped directory per package in npm-packages.sh.
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
# shellcheck source=scripts/release/npm-packages.sh
|
||||
source "$ROOT_DIR/scripts/release/npm-packages.sh"
|
||||
|
||||
VERSION="${1:?Usage: $0 <version> <release-assets-dir> <output-dir>}"
|
||||
ASSETS_DIR="${2:?Usage: $0 <version> <release-assets-dir> <output-dir>}"
|
||||
OUT_DIR="${3:?Usage: $0 <version> <release-assets-dir> <output-dir>}"
|
||||
|
||||
# Maps platform dir name → npm package name + npm os/cpu fields
|
||||
declare -A PLATFORM_TO_PACKAGE=(
|
||||
["linux-x64"]="@kdlbs/runtime-linux-x64"
|
||||
["linux-arm64"]="@kdlbs/runtime-linux-arm64"
|
||||
["macos-x64"]="@kdlbs/runtime-darwin-x64"
|
||||
["macos-arm64"]="@kdlbs/runtime-darwin-arm64"
|
||||
["windows-x64"]="@kdlbs/runtime-win32-x64"
|
||||
)
|
||||
|
||||
declare -A PLATFORM_TO_OS=(
|
||||
["linux-x64"]='["linux"]'
|
||||
["linux-arm64"]='["linux"]'
|
||||
["macos-x64"]='["darwin"]'
|
||||
["macos-arm64"]='["darwin"]'
|
||||
["windows-x64"]='["win32"]'
|
||||
)
|
||||
|
||||
declare -A PLATFORM_TO_CPU=(
|
||||
["linux-x64"]='["x64"]'
|
||||
["linux-arm64"]='["arm64"]'
|
||||
["macos-x64"]='["x64"]'
|
||||
["macos-arm64"]='["arm64"]'
|
||||
["windows-x64"]='["x64"]'
|
||||
)
|
||||
|
||||
echo "Packaging npm runtime packages for version $VERSION..."
|
||||
echo " assets dir: $ASSETS_DIR"
|
||||
echo " output dir: $OUT_DIR"
|
||||
|
||||
for platform in linux-x64 linux-arm64 macos-x64 macos-arm64 windows-x64; do
|
||||
for platform in "${RUNTIME_PLATFORMS[@]}"; do
|
||||
archive="$ASSETS_DIR/kandev-${platform}.tar.gz"
|
||||
if [[ ! -f "$archive" ]]; then
|
||||
echo "Error: missing archive $archive" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
package_name="${PLATFORM_TO_PACKAGE[$platform]}"
|
||||
package_name="${RUNTIME_PACKAGE_BY_PLATFORM[$platform]}"
|
||||
# @kdlbs/runtime-linux-x64 → scope=@kdlbs, name=runtime-linux-x64
|
||||
scope_dir="${package_name%%/*}" # @kdlbs
|
||||
pkg_dir="${package_name##*/}" # runtime-linux-x64
|
||||
@@ -85,8 +59,17 @@ for platform in linux-x64 linux-arm64 macos-x64 macos-arm64 windows-x64; do
|
||||
cp -R "$bundle_root/bin" "$pkg_out/bin"
|
||||
rm -rf "$local_tmp"
|
||||
|
||||
os_field="${PLATFORM_TO_OS[$platform]}"
|
||||
cpu_field="${PLATFORM_TO_CPU[$platform]}"
|
||||
case "$platform" in
|
||||
linux-*) os_field='["linux"]' ;;
|
||||
macos-*) os_field='["darwin"]' ;;
|
||||
windows-*) os_field='["win32"]' ;;
|
||||
*) echo "Error: unsupported runtime platform $platform" >&2; exit 1 ;;
|
||||
esac
|
||||
case "$platform" in
|
||||
*-x64) cpu_field='["x64"]' ;;
|
||||
*-arm64) cpu_field='["arm64"]' ;;
|
||||
*) echo "Error: unsupported runtime architecture $platform" >&2; exit 1 ;;
|
||||
esac
|
||||
|
||||
# Note: `repository` is required when publishing with `npm publish --provenance`.
|
||||
# npm's sigstore attestation embeds repo info from the OIDC token and refuses
|
||||
|
||||
+137
-55
@@ -7,23 +7,19 @@
|
||||
# short-lived publish token. No NPM_TOKEN secret is needed.
|
||||
#
|
||||
# Prerequisites:
|
||||
# - GitHub release assets for <tag> must already exist (verified before publishing).
|
||||
# - Five runtime archives from either a GitHub release or a local directory.
|
||||
# - Running inside GitHub Actions with `id-token: write` permission set on
|
||||
# the publish-npm job. (npm publish from a local shell will fall back to
|
||||
# classic auth — but tokens are not the recommended path going forward.)
|
||||
#
|
||||
# Usage:
|
||||
# publish-npm.sh <version> <tag>
|
||||
#
|
||||
# Arguments:
|
||||
# version SemVer string (e.g. 0.17.0)
|
||||
# tag Git tag (e.g. v0.17.0) — used to verify GitHub release assets exist
|
||||
# publish-npm.sh --version <semver> --dist-tag <latest|nightly> \
|
||||
# (--release-tag <git-tag> | --assets-dir <path>)
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
|
||||
VERSION="${1:?Usage: $0 <version> <tag>}"
|
||||
TAG="${2:?Usage: $0 <version> <tag>}"
|
||||
# shellcheck source=scripts/release/npm-packages.sh
|
||||
source "$ROOT_DIR/scripts/release/npm-packages.sh"
|
||||
|
||||
bold() { printf '\033[1m%s\033[0m' "$*"; }
|
||||
green() { printf '\033[32m%s\033[0m' "$*"; }
|
||||
@@ -33,15 +29,8 @@ yellow(){ printf '\033[33m%s\033[0m' "$*"; }
|
||||
log() { echo " >> $*"; }
|
||||
log_ok() { echo " $(green "ok") $*"; }
|
||||
|
||||
package_already_published() {
|
||||
local pkg="$1"
|
||||
npm view "${pkg}@${VERSION}" version --silent >/dev/null 2>&1
|
||||
}
|
||||
|
||||
record_already_published() {
|
||||
local pkg="$1"
|
||||
echo " $(yellow "skip") $pkg@$VERSION already published (treated as idempotent success)" >&2
|
||||
ALREADY_PUBLISHED+=("$pkg")
|
||||
usage() {
|
||||
echo "Usage: $0 --version <semver> --dist-tag <latest|nightly> (--release-tag <git-tag> | --assets-dir <path>)" >&2
|
||||
}
|
||||
|
||||
die() {
|
||||
@@ -49,33 +38,133 @@ die() {
|
||||
exit 1
|
||||
}
|
||||
|
||||
# -- Verify GitHub release assets exist before publishing ---------------------
|
||||
npm_view_version() {
|
||||
bash "$ROOT_DIR/scripts/release/npm-view-version.sh" "$1"
|
||||
}
|
||||
|
||||
REQUIRED_PLATFORMS=(linux-x64 linux-arm64 macos-x64 macos-arm64 windows-x64)
|
||||
VERSION=""
|
||||
DIST_TAG=""
|
||||
RELEASE_TAG=""
|
||||
SOURCE_ASSETS_DIR=""
|
||||
|
||||
log "Verifying GitHub release assets exist for $TAG..."
|
||||
for platform in "${REQUIRED_PLATFORMS[@]}"; do
|
||||
asset="kandev-${platform}.tar.gz"
|
||||
if ! gh release view "$TAG" --json assets --jq ".assets[].name" 2>/dev/null | grep -q "^${asset}$"; then
|
||||
die "GitHub release asset missing: $asset in release $TAG. Run release workflow first."
|
||||
fi
|
||||
while [[ "$#" -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--version)
|
||||
[[ "$#" -ge 2 ]] || die "--version requires a value"
|
||||
VERSION="$2"
|
||||
shift 2
|
||||
;;
|
||||
--dist-tag)
|
||||
[[ "$#" -ge 2 ]] || die "--dist-tag requires a value"
|
||||
DIST_TAG="$2"
|
||||
shift 2
|
||||
;;
|
||||
--release-tag)
|
||||
[[ "$#" -ge 2 ]] || die "--release-tag requires a value"
|
||||
RELEASE_TAG="$2"
|
||||
shift 2
|
||||
;;
|
||||
--assets-dir)
|
||||
[[ "$#" -ge 2 ]] || die "--assets-dir requires a value"
|
||||
SOURCE_ASSETS_DIR="$2"
|
||||
shift 2
|
||||
;;
|
||||
-h|--help)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
usage
|
||||
die "unknown argument: $1"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
log_ok "All 5 platform assets present in GitHub release $TAG"
|
||||
|
||||
# -- Download release assets for packaging ------------------------------------
|
||||
[[ -n "$VERSION" ]] || die "--version is required"
|
||||
[[ -n "$DIST_TAG" ]] || die "--dist-tag is required"
|
||||
case "$DIST_TAG" in
|
||||
latest)
|
||||
[[ "$VERSION" =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]] || \
|
||||
die "--version must be stable X.Y.Z for --dist-tag latest"
|
||||
;;
|
||||
nightly)
|
||||
[[ "$VERSION" =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)-nightly\.sha[0-9a-f]{12}$ ]] || \
|
||||
die "--version must be X.Y.Z-nightly.sha<12-hex> for --dist-tag nightly"
|
||||
;;
|
||||
*)
|
||||
die "--dist-tag must be latest or nightly"
|
||||
;;
|
||||
esac
|
||||
|
||||
if [[ -n "$RELEASE_TAG" && -n "$SOURCE_ASSETS_DIR" ]]; then
|
||||
die "provide exactly one asset source: --release-tag or --assets-dir"
|
||||
elif [[ -z "$RELEASE_TAG" && -z "$SOURCE_ASSETS_DIR" ]]; then
|
||||
die "provide exactly one asset source: --release-tag or --assets-dir"
|
||||
elif [[ "$DIST_TAG" == "latest" && -z "$RELEASE_TAG" ]]; then
|
||||
die "--dist-tag latest requires --release-tag"
|
||||
elif [[ "$DIST_TAG" == "nightly" && -z "$SOURCE_ASSETS_DIR" ]]; then
|
||||
die "--dist-tag nightly requires --assets-dir"
|
||||
fi
|
||||
|
||||
package_already_published() {
|
||||
local pkg="$1"
|
||||
local published_version
|
||||
if ! published_version="$(npm_view_version "${pkg}@${VERSION}")"; then
|
||||
die "could not verify whether $pkg@$VERSION is already published"
|
||||
fi
|
||||
[[ -n "$published_version" ]]
|
||||
}
|
||||
|
||||
record_already_published() {
|
||||
local pkg="$1"
|
||||
if [[ "$DIST_TAG" == "nightly" ]]; then
|
||||
local tagged_version
|
||||
if ! tagged_version="$(npm_view_version "${pkg}@${DIST_TAG}")"; then
|
||||
die "could not verify $pkg@$DIST_TAG for idempotent publication"
|
||||
fi
|
||||
if [[ "$tagged_version" != "$VERSION" ]]; then
|
||||
die "$pkg@$VERSION exists, but $pkg@$DIST_TAG resolves to '${tagged_version:-nothing}'; refusing idempotent success"
|
||||
fi
|
||||
fi
|
||||
echo " $(yellow "skip") $pkg@$VERSION already published (treated as idempotent success)" >&2
|
||||
ALREADY_PUBLISHED+=("$pkg")
|
||||
}
|
||||
|
||||
WORK_DIR="$(mktemp -d)"
|
||||
trap 'rm -rf "$WORK_DIR"' EXIT
|
||||
ASSETS_DIR="$WORK_DIR/assets"
|
||||
mkdir -p "$ASSETS_DIR"
|
||||
CLI_PACKAGE_JSON="$ROOT_DIR/apps/cli/package.json"
|
||||
CLI_PACKAGE_BACKUP="$WORK_DIR/cli-package.json"
|
||||
cp "$CLI_PACKAGE_JSON" "$CLI_PACKAGE_BACKUP"
|
||||
cleanup() {
|
||||
if [[ -f "$CLI_PACKAGE_BACKUP" ]]; then
|
||||
cp "$CLI_PACKAGE_BACKUP" "$CLI_PACKAGE_JSON"
|
||||
fi
|
||||
rm -rf "$WORK_DIR"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
log "Downloading release assets for $TAG..."
|
||||
for platform in "${REQUIRED_PLATFORMS[@]}"; do
|
||||
# -- Resolve and verify release assets ----------------------------------------
|
||||
|
||||
if [[ -n "$RELEASE_TAG" ]]; then
|
||||
ASSETS_DIR="$WORK_DIR/assets"
|
||||
mkdir -p "$ASSETS_DIR"
|
||||
log "Downloading release assets for $RELEASE_TAG..."
|
||||
for platform in "${RUNTIME_PLATFORMS[@]}"; do
|
||||
asset="kandev-${platform}.tar.gz"
|
||||
log " downloading $asset..."
|
||||
gh release download "$RELEASE_TAG" --pattern "$asset" --dir "$ASSETS_DIR" || \
|
||||
die "GitHub release asset missing: $asset in release $RELEASE_TAG"
|
||||
done
|
||||
else
|
||||
ASSETS_DIR="$SOURCE_ASSETS_DIR"
|
||||
[[ -d "$ASSETS_DIR" ]] || die "asset directory does not exist: $ASSETS_DIR"
|
||||
log "Using release assets from $ASSETS_DIR..."
|
||||
fi
|
||||
|
||||
for platform in "${RUNTIME_PLATFORMS[@]}"; do
|
||||
asset="kandev-${platform}.tar.gz"
|
||||
log " downloading $asset..."
|
||||
gh release download "$TAG" --pattern "$asset" --dir "$ASSETS_DIR"
|
||||
[[ -f "$ASSETS_DIR/$asset" ]] || die "release asset missing: $ASSETS_DIR/$asset"
|
||||
done
|
||||
log_ok "Assets downloaded to $ASSETS_DIR"
|
||||
log_ok "All 5 platform assets present"
|
||||
|
||||
# -- Generate npm runtime packages --------------------------------------------
|
||||
|
||||
@@ -84,14 +173,6 @@ bash "$ROOT_DIR/scripts/release/package-npm-runtime.sh" "$VERSION" "$ASSETS_DIR"
|
||||
|
||||
# -- Publish @kdlbs/runtime-* packages first ---------------------------------
|
||||
|
||||
RUNTIME_PACKAGES=(
|
||||
"@kdlbs/runtime-linux-x64"
|
||||
"@kdlbs/runtime-linux-arm64"
|
||||
"@kdlbs/runtime-darwin-x64"
|
||||
"@kdlbs/runtime-darwin-arm64"
|
||||
"@kdlbs/runtime-win32-x64"
|
||||
)
|
||||
|
||||
echo
|
||||
echo "$(bold "Publishing @kdlbs/runtime-* packages...")"
|
||||
FAILED_PACKAGES=()
|
||||
@@ -117,7 +198,7 @@ for pkg in "${RUNTIME_PACKAGES[@]}"; do
|
||||
# Capture full npm output so we can show the real error on failure rather
|
||||
# than just a generic warning. Distinguish "already published" (idempotent
|
||||
# case — fine) from real failures (must abort).
|
||||
if output="$(cd "$pkg_dir" && npm publish --access public --provenance 2>&1)"; then
|
||||
if output="$(cd "$pkg_dir" && npm publish --access public --provenance --tag "$DIST_TAG" 2>&1)"; then
|
||||
log_ok "$pkg@$VERSION published"
|
||||
elif echo "$output" | grep -qE "EPUBLISHCONFLICT|cannot publish over the previously published versions|You cannot publish over"; then
|
||||
record_already_published "$pkg"
|
||||
@@ -151,19 +232,20 @@ fi
|
||||
# package, we want optionalDependencies to point at @kdlbs/runtime-*@VERSION
|
||||
# so users get matching runtime bundles. The runtime packages were just
|
||||
# published above, so this version exists on npm now.
|
||||
log "Pinning optionalDependencies to $VERSION before publishing main package..."
|
||||
node -e "
|
||||
const fs = require('fs');
|
||||
const path = '$ROOT_DIR/apps/cli/package.json';
|
||||
const pkg = JSON.parse(fs.readFileSync(path, 'utf8'));
|
||||
log "Setting the launcher version and optionalDependencies to $VERSION..."
|
||||
node - "$CLI_PACKAGE_JSON" "$VERSION" <<'NODE'
|
||||
const fs = require("fs");
|
||||
const [path, version] = process.argv.slice(2);
|
||||
const pkg = JSON.parse(fs.readFileSync(path, "utf8"));
|
||||
pkg.version = version;
|
||||
if (pkg.optionalDependencies) {
|
||||
for (const k of Object.keys(pkg.optionalDependencies)) {
|
||||
pkg.optionalDependencies[k] = '$VERSION';
|
||||
pkg.optionalDependencies[k] = version;
|
||||
}
|
||||
}
|
||||
fs.writeFileSync(path, JSON.stringify(pkg, null, 2) + '\n');
|
||||
"
|
||||
log_ok "optionalDependencies pinned to $VERSION"
|
||||
fs.writeFileSync(path, JSON.stringify(pkg, null, 2) + "\n");
|
||||
NODE
|
||||
log_ok "Launcher metadata pinned to $VERSION"
|
||||
|
||||
# -- Publish main kandev package ----------------------------------------------
|
||||
|
||||
@@ -174,7 +256,7 @@ echo "$(bold "Publishing kandev@$VERSION...")"
|
||||
# `prepublishOnly` (in package.json) runs `pnpm build` automatically.
|
||||
if package_already_published "kandev"; then
|
||||
record_already_published "kandev"
|
||||
elif main_output="$(cd "$ROOT_DIR/apps/cli" && npm publish --access public --provenance 2>&1)"; then
|
||||
elif main_output="$(cd "$ROOT_DIR/apps/cli" && npm publish --access public --provenance --tag "$DIST_TAG" 2>&1)"; then
|
||||
log_ok "kandev@$VERSION published"
|
||||
elif echo "$main_output" | grep -qE "EPUBLISHCONFLICT|cannot publish over the previously published versions|You cannot publish over"; then
|
||||
record_already_published "kandev"
|
||||
|
||||
@@ -0,0 +1,356 @@
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
chmod,
|
||||
copyFile,
|
||||
mkdir,
|
||||
mkdtemp,
|
||||
readFile,
|
||||
rm,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import test from "node:test";
|
||||
|
||||
const sourceRoot = path.resolve(import.meta.dirname, "../..");
|
||||
|
||||
async function loadRuntimeInventory() {
|
||||
const inventoryPath = path.join(
|
||||
sourceRoot,
|
||||
"scripts/release/npm-packages.sh",
|
||||
);
|
||||
const source = await readFile(inventoryPath, "utf8");
|
||||
const platformBlock = source.match(/RUNTIME_PLATFORMS=\(([\s\S]*?)\n\)/);
|
||||
assert.ok(platformBlock, "runtime platform inventory is missing");
|
||||
const platforms = [...platformBlock[1].matchAll(/"([^"]+)"/g)].map(
|
||||
(match) => match[1],
|
||||
);
|
||||
const packageByPlatform = new Map(
|
||||
[...source.matchAll(/^\s*\["([^"]+)"\]="([^"]+)"$/gm)].map((match) => [
|
||||
match[1],
|
||||
match[2],
|
||||
]),
|
||||
);
|
||||
return platforms.map((platform) => {
|
||||
const packageName = packageByPlatform.get(platform);
|
||||
assert.ok(packageName, `runtime package is missing for ${platform}`);
|
||||
return { platform, packageName };
|
||||
});
|
||||
}
|
||||
|
||||
const runtimeInventory = await loadRuntimeInventory();
|
||||
const runtimePackages = runtimeInventory.map(({ packageName }) => packageName);
|
||||
const assets = runtimeInventory.map(
|
||||
({ platform }) => `kandev-${platform}.tar.gz`,
|
||||
);
|
||||
const releases = [
|
||||
{ name: "Stable", version: "1.2.3", distTag: "latest" },
|
||||
{
|
||||
name: "Nightly",
|
||||
version: "1.2.4-nightly.shaabcdef123456",
|
||||
distTag: "nightly",
|
||||
},
|
||||
];
|
||||
|
||||
async function createFixture() {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "kandev-publish-npm-"));
|
||||
const releaseDir = path.join(root, "scripts/release");
|
||||
const cliDir = path.join(root, "apps/cli");
|
||||
const assetsDir = path.join(root, "assets");
|
||||
const binDir = path.join(root, "bin");
|
||||
const publishLog = path.join(root, "publish.log");
|
||||
const publishedMetadata = path.join(root, "published-package.json");
|
||||
await Promise.all([
|
||||
mkdir(releaseDir, { recursive: true }),
|
||||
mkdir(cliDir, { recursive: true }),
|
||||
mkdir(assetsDir, { recursive: true }),
|
||||
mkdir(binDir, { recursive: true }),
|
||||
]);
|
||||
await Promise.all(
|
||||
["publish-npm.sh", "npm-packages.sh", "npm-view-version.sh"].map((name) =>
|
||||
copyFile(
|
||||
path.join(sourceRoot, "scripts/release", name),
|
||||
path.join(releaseDir, name),
|
||||
),
|
||||
),
|
||||
);
|
||||
await Promise.all(
|
||||
assets.map((name) => writeFile(path.join(assetsDir, name), "fixture")),
|
||||
);
|
||||
await Promise.all([
|
||||
writeFile(publishLog, ""),
|
||||
writeFile(publishedMetadata, ""),
|
||||
]);
|
||||
|
||||
const originalPackageJSON = `${JSON.stringify(
|
||||
{
|
||||
name: "kandev",
|
||||
version: "0.0.0-bootstrap",
|
||||
optionalDependencies: Object.fromEntries(
|
||||
runtimePackages.map((name) => [name, "0.0.0-bootstrap"]),
|
||||
),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`;
|
||||
await writeFile(path.join(cliDir, "package.json"), originalPackageJSON);
|
||||
|
||||
const runtimePackageLines = runtimePackages
|
||||
.map((name) => `${name} ${name.slice("@kdlbs/".length)}`)
|
||||
.join("\n");
|
||||
await writeExecutable(
|
||||
path.join(releaseDir, "package-npm-runtime.sh"),
|
||||
`#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
version="$1"
|
||||
out="$3"
|
||||
while read -r package name; do
|
||||
dir="$out/@kdlbs/$name"
|
||||
mkdir -p "$dir"
|
||||
printf '{"name":"%s","version":"%s"}\n' "$package" "$version" > "$dir/package.json"
|
||||
done <<'PACKAGES'
|
||||
${runtimePackageLines}
|
||||
PACKAGES
|
||||
`,
|
||||
);
|
||||
await writeExecutable(
|
||||
path.join(binDir, "npm"),
|
||||
`#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
case "$1" in
|
||||
view)
|
||||
spec="$2"
|
||||
if [[ "$MOCK_NPM_MODE" == "registry-failure" ]]; then
|
||||
printf '%s\n' 'npm error code EAI_AGAIN' >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$MOCK_NPM_MODE" == "fresh" || "$MOCK_NPM_MODE" == "runtime-publish-failure" ]]; then
|
||||
printf '%s\n' 'npm error code E404' >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$MOCK_NPM_MODE" == main-conflict* && "$spec" == "kandev@$MOCK_NPM_VERSION" ]]; then
|
||||
printf '%s\n' 'npm error code E404' >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$MOCK_NPM_MODE" == "main-conflict" && "$spec" == "kandev@nightly" ]]; then
|
||||
printf '%s\n' '1.2.3-nightly.sha000000000000'
|
||||
exit 0
|
||||
fi
|
||||
printf '%s\n' "$MOCK_NPM_VERSION"
|
||||
;;
|
||||
publish)
|
||||
package="$(node -p "require('./package.json').name")"
|
||||
printf '%s\n' "$package" >> "$MOCK_NPM_PUBLISH_LOG"
|
||||
if [[ "$package" == "kandev" ]]; then
|
||||
cp package.json "$MOCK_NPM_PUBLISHED_METADATA"
|
||||
fi
|
||||
if [[ "$MOCK_NPM_MODE" == "runtime-publish-failure" && "$package" == "$MOCK_RUNTIME_FAILURE_PACKAGE" ]]; then
|
||||
printf '%s\n' 'npm error code E500' >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$MOCK_NPM_MODE" == main-conflict* && "$package" == "kandev" ]]; then
|
||||
printf '%s\n' 'npm error code EPUBLISHCONFLICT' >&2
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
*)
|
||||
printf 'unexpected npm command: %s\n' "$*" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
`,
|
||||
);
|
||||
await writeExecutable(
|
||||
path.join(binDir, "sleep"),
|
||||
"#!/usr/bin/env bash\nexit 0\n",
|
||||
);
|
||||
await writeExecutable(
|
||||
path.join(binDir, "gh"),
|
||||
`#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
pattern=""
|
||||
directory=""
|
||||
while [[ "$#" -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--pattern) pattern="$2"; shift 2 ;;
|
||||
--dir) directory="$2"; shift 2 ;;
|
||||
*) shift ;;
|
||||
esac
|
||||
done
|
||||
mkdir -p "$directory"
|
||||
: > "$directory/$pattern"
|
||||
`,
|
||||
);
|
||||
|
||||
return {
|
||||
root,
|
||||
releaseDir,
|
||||
cliDir,
|
||||
assetsDir,
|
||||
binDir,
|
||||
publishLog,
|
||||
publishedMetadata,
|
||||
originalPackageJSON,
|
||||
};
|
||||
}
|
||||
|
||||
async function writeExecutable(file, content) {
|
||||
await writeFile(file, content);
|
||||
await chmod(file, 0o755);
|
||||
}
|
||||
|
||||
async function runPublish(fixture, { version, distTag, mode }) {
|
||||
const args = [
|
||||
path.join(fixture.releaseDir, "publish-npm.sh"),
|
||||
"--version",
|
||||
version,
|
||||
"--dist-tag",
|
||||
distTag,
|
||||
];
|
||||
if (distTag === "latest") {
|
||||
args.push("--release-tag", `v${version}`);
|
||||
} else {
|
||||
args.push("--assets-dir", fixture.assetsDir);
|
||||
}
|
||||
const result = spawnSync("bash", args, {
|
||||
encoding: "utf8",
|
||||
cwd: fixture.root,
|
||||
env: {
|
||||
...process.env,
|
||||
MOCK_NPM_MODE: mode,
|
||||
MOCK_NPM_PUBLISH_LOG: fixture.publishLog,
|
||||
MOCK_NPM_PUBLISHED_METADATA: fixture.publishedMetadata,
|
||||
MOCK_RUNTIME_FAILURE_PACKAGE: runtimePackages[1],
|
||||
MOCK_NPM_VERSION: version,
|
||||
PATH: `${fixture.binDir}${path.delimiter}${process.env.PATH ?? ""}`,
|
||||
},
|
||||
});
|
||||
return {
|
||||
...result,
|
||||
packageJSON: await readFile(
|
||||
path.join(fixture.cliDir, "package.json"),
|
||||
"utf8",
|
||||
),
|
||||
publishedMetadata: await readFile(fixture.publishedMetadata, "utf8"),
|
||||
published: (await readFile(fixture.publishLog, "utf8"))
|
||||
.trim()
|
||||
.split("\n")
|
||||
.filter(Boolean),
|
||||
};
|
||||
}
|
||||
|
||||
for (const release of releases) {
|
||||
test(`${release.name} publication is idempotent when every exact package already exists`, async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
const result = await runPublish(fixture, {
|
||||
...release,
|
||||
mode: "all-published",
|
||||
});
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.deepEqual(result.published, []);
|
||||
assert.equal(result.packageJSON, fixture.originalPackageJSON);
|
||||
} finally {
|
||||
await rm(fixture.root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
for (const release of releases) {
|
||||
test(`a fresh ${release.name} publishes every package with pinned launcher metadata`, async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
const result = await runPublish(fixture, { ...release, mode: "fresh" });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.deepEqual(result.published, [...runtimePackages, "kandev"]);
|
||||
const metadata = JSON.parse(result.publishedMetadata);
|
||||
assert.equal(metadata.version, release.version);
|
||||
assert.deepEqual(
|
||||
metadata.optionalDependencies,
|
||||
Object.fromEntries(
|
||||
runtimePackages.map((name) => [name, release.version]),
|
||||
),
|
||||
);
|
||||
assert.equal(result.packageJSON, fixture.originalPackageJSON);
|
||||
} finally {
|
||||
await rm(fixture.root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test("a conflicting Nightly launcher publish fails closed and restores package metadata", async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
const result = await runPublish(fixture, {
|
||||
version: "1.2.4-nightly.shaabcdef123456",
|
||||
distTag: "nightly",
|
||||
mode: "main-conflict",
|
||||
});
|
||||
assert.notEqual(result.status, 0);
|
||||
assert.match(
|
||||
result.stderr,
|
||||
/kandev@nightly resolves to '1\.2\.3-nightly\.sha000000000000'/,
|
||||
);
|
||||
assert.deepEqual(result.published, ["kandev"]);
|
||||
assert.equal(result.packageJSON, fixture.originalPackageJSON);
|
||||
} finally {
|
||||
await rm(fixture.root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a matching Nightly conflict converges as an idempotent success", async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
const result = await runPublish(fixture, {
|
||||
version: "1.2.4-nightly.shaabcdef123456",
|
||||
distTag: "nightly",
|
||||
mode: "main-conflict-matching",
|
||||
});
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.deepEqual(result.published, ["kandev"]);
|
||||
assert.equal(result.packageJSON, fixture.originalPackageJSON);
|
||||
} finally {
|
||||
await rm(fixture.root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a transient registry failure aborts before publishing and preserves metadata", async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
const result = await runPublish(fixture, {
|
||||
version: "1.2.4-nightly.shaabcdef123456",
|
||||
distTag: "nightly",
|
||||
mode: "registry-failure",
|
||||
});
|
||||
assert.notEqual(result.status, 0);
|
||||
assert.match(
|
||||
result.stderr,
|
||||
/could not verify whether @kdlbs\/runtime-linux-x64/,
|
||||
);
|
||||
assert.deepEqual(result.published, []);
|
||||
assert.equal(result.packageJSON, fixture.originalPackageJSON);
|
||||
} finally {
|
||||
await rm(fixture.root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a runtime publish failure withholds the launcher", async () => {
|
||||
const fixture = await createFixture();
|
||||
try {
|
||||
const result = await runPublish(fixture, {
|
||||
version: "1.2.4-nightly.shaabcdef123456",
|
||||
distTag: "nightly",
|
||||
mode: "runtime-publish-failure",
|
||||
});
|
||||
assert.notEqual(result.status, 0);
|
||||
assert.deepEqual(result.published, runtimePackages);
|
||||
assert.ok(
|
||||
result.stderr.includes(`Failed to publish ${runtimePackages[1]}`),
|
||||
);
|
||||
assert.match(result.stderr, /Refusing to publish main kandev/);
|
||||
assert.equal(result.packageJSON, fixture.originalPackageJSON);
|
||||
} finally {
|
||||
await rm(fixture.root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user