diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml new file mode 100644 index 0000000..6eb1acd --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,216 @@ +name: Nightly + +# Builds, signs and notarizes main once a night and publishes it as the +# rolling `nightly` pre-release, for anyone who picks Settings → Actions → +# Update channel → Nightly. A night when main hasn't moved is skipped, and +# "Run workflow" builds one on demand. +# +# Nothing here reaches anyone else. The Stable channel, and every app from +# before channels existed, reads /releases/latest, which never returns a +# pre-release. +# +# A build is named -nightly., a semver pre-release of the release it +# leads up to: next is the version release-please's open release PR proposes +# (a patch bump of the last release when there's none), and n is main's commit +# count, so a later build always has the larger number (UpdateOffer compares +# them). +# +# The build, sign and notarize steps mirror release.yml's. Keep them in step. + +on: + schedule: + # 02:00 UTC: 2am in UK winter, 3am in summer. GitHub's cron has no zones. + - cron: '0 2 * * *' + workflow_dispatch: + +# A build already running finishes; a second request waits for it. +concurrency: + group: nightly + cancel-in-progress: false + +jobs: + prepare: + name: Point the nightly release at this commit + runs-on: ubuntu-latest + permissions: + contents: write + outputs: + base: ${{ steps.version.outputs.base }} + build: ${{ steps.version.outputs.build }} + changed: ${{ steps.changed.outputs.changed }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 + with: + fetch-depth: 0 # the commit count is the build number + persist-credentials: false + + # Nothing to build when the nightly tag is already this commit, unless + # someone asked for one by hand. + - name: Check main has moved + id: changed + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + built=$(gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/nightly" --jq .object.sha 2>/dev/null || true) + if [[ "$built" == "$GITHUB_SHA" && "$GITHUB_EVENT_NAME" == "schedule" ]]; then + echo "changed=false" >> "$GITHUB_OUTPUT" + echo "main is still ${GITHUB_SHA}, already built" + else + echo "changed=true" >> "$GITHUB_OUTPUT" + fi + + - name: Work out the version + if: steps.changed.outputs.changed == 'true' + id: version + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + last=$(jq -r '."."' .release-please-manifest.json) + # release-please recomputes its release PR from the commits on every + # push to main, so its title is the next version. + base=$(gh pr list --repo "$GITHUB_REPOSITORY" --state open --label "autorelease: pending" \ + --json title --jq '.[0].title // ""' \ + | sed -n 's/^chore(main): release \([0-9.]*\)$/\1/p') + if [[ -z "$base" ]]; then + base=$(awk -F. '{ printf "%d.%d.%d", $1, $2, $3 + 1 }' <<<"$last") + fi + build=$(git rev-list --count HEAD) + echo "base=$base" >> "$GITHUB_OUTPUT" + echo "build=$build" >> "$GITHUB_OUTPUT" + echo "Nightly ${base}-nightly.${build} from ${GITHUB_SHA}" + + # The tag moves with every build, and the release is made on the first + # run. Never marked latest, so /releases/latest keeps returning the last + # stable release. + - name: Move the tag and update the release + if: steps.changed.outputs.changed == 'true' + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ steps.version.outputs.base }}-nightly.${{ steps.version.outputs.build }} + run: | + set -euo pipefail + repo="$GITHUB_REPOSITORY" + gh api -X PATCH "repos/$repo/git/refs/tags/nightly" -f sha="$GITHUB_SHA" -F force=true >/dev/null \ + || gh api -X POST "repos/$repo/git/refs" -f ref=refs/tags/nightly -f sha="$GITHUB_SHA" >/dev/null + notes="Built from ${GITHUB_SHA} on main. Not a release: this is what Settings → Actions → Update channel → Nightly installs, rebuilt each night main has moved. Changes since the last release: https://github.com/${repo}/compare/v$(jq -r '."."' .release-please-manifest.json)...${GITHUB_SHA}" + if gh release view nightly --repo "$repo" >/dev/null 2>&1; then + gh release edit nightly --repo "$repo" --prerelease --latest=false \ + --title "Nightly ${VERSION}" --notes "$notes" + else + gh release create nightly --repo "$repo" --verify-tag --prerelease --latest=false \ + --title "Nightly ${VERSION}" --notes "$notes" + fi + + build: + name: Build, sign, notarize (${{ matrix.arch }}) + needs: prepare + if: needs.prepare.outputs.changed == 'true' + runs-on: macos-15 + permissions: + contents: write + strategy: + matrix: + arch: [arm64, x86_64] + fail-fast: false + + env: + STACKNUDGE_BUNDLE_VENV: "1" + KEYCHAIN: build-stack-nudge.keychain + BASE: ${{ needs.prepare.outputs.base }} + BUILD: ${{ needs.prepare.outputs.build }} + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v6 + with: + ref: ${{ github.sha }} + persist-credentials: false + + # The release it leads up to, plus the build number the app compares + # (BuildVersion.current reads StackNudgeNightlyBuild). + - name: Stamp the nightly version + run: | + /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $BASE" panel/Info.plist + /usr/libexec/PlistBuddy -c "Set :CFBundleVersion $BUILD" panel/Info.plist + /usr/libexec/PlistBuddy -c "Add :StackNudgeNightlyBuild string $BUILD" panel/Info.plist + + - name: Set up signing identity + env: + MACOS_CERTIFICATE: ${{ secrets.MACOS_CERTIFICATE }} + MACOS_CERTIFICATE_PWD: ${{ secrets.MACOS_CERTIFICATE_PWD }} + MACOS_KEYCHAIN_PWD: ${{ secrets.MACOS_KEYCHAIN_PWD }} + run: | + set -euo pipefail + echo "$MACOS_CERTIFICATE" | base64 --decode > /tmp/cert.p12 + security create-keychain -p "$MACOS_KEYCHAIN_PWD" "$KEYCHAIN" + security default-keychain -s "$KEYCHAIN" + security unlock-keychain -p "$MACOS_KEYCHAIN_PWD" "$KEYCHAIN" + security set-keychain-settings -lut 7200 "$KEYCHAIN" + security import /tmp/cert.p12 -k "$KEYCHAIN" \ + -P "$MACOS_CERTIFICATE_PWD" \ + -T /usr/bin/codesign \ + -T /usr/bin/security + security set-key-partition-list \ + -S apple-tool:,apple:,codesign: \ + -s -k "$MACOS_KEYCHAIN_PWD" "$KEYCHAIN" + IDENTITY=$( + security find-identity -v -p codesigning "$KEYCHAIN" \ + | awk -F'"' '/"Developer ID Application/ {print $2; exit}' + ) + if [[ -z "$IDENTITY" ]]; then + echo "::error::No Developer ID Application identity found in keychain after import" + exit 1 + fi + echo "STACKNUDGE_SIGN_IDENTITY=$IDENTITY" >> "$GITHUB_ENV" + rm -f /tmp/cert.p12 + + - name: Build ${{ matrix.arch }} + run: bash build.sh ${{ matrix.arch }} + + - name: Notarize ${{ matrix.arch }} + env: + MACOS_NOTARY_API_KEY: ${{ secrets.MACOS_NOTARY_API_KEY }} + MACOS_NOTARY_API_KEY_ID: ${{ secrets.MACOS_NOTARY_API_KEY_ID }} + MACOS_NOTARY_API_ISSUER_ID: ${{ secrets.MACOS_NOTARY_API_ISSUER_ID }} + run: | + set -euo pipefail + echo "$MACOS_NOTARY_API_KEY" | base64 --decode > /tmp/notary-key.p8 + ditto -c -k --keepParent build/StackNudge.app /tmp/notarize.zip + xcrun notarytool submit /tmp/notarize.zip \ + --key /tmp/notary-key.p8 \ + --key-id "$MACOS_NOTARY_API_KEY_ID" \ + --issuer "$MACOS_NOTARY_API_ISSUER_ID" \ + --wait + xcrun stapler staple build/StackNudge.app + spctl -a -vv build/StackNudge.app || true + rm -f /tmp/notary-key.p8 /tmp/notarize.zip + + - name: Package ${{ matrix.arch }} + run: | + set -euo pipefail + ARTIFACT="stack-nudge-${BASE}-nightly.${BUILD}-macos-${{ matrix.arch }}.tar.gz" + tar czf "$ARTIFACT" -C build StackNudge.app + shasum -a 256 "$ARTIFACT" | awk -v name="$ARTIFACT" '{print $1 " " name}' \ + > "$ARTIFACT.sha256" + echo "ARTIFACT=$ARTIFACT" >> "$GITHUB_ENV" + ls -la "$ARTIFACT" "$ARTIFACT.sha256" + + # Upload first, then drop this arch's older build, so the release is + # never without one. The app reads its version from the artifact's name. + - name: Publish ${{ matrix.arch }} + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + repo="$GITHUB_REPOSITORY" + gh release upload nightly --repo "$repo" --clobber "$ARTIFACT" "$ARTIFACT.sha256" + gh release view nightly --repo "$repo" --json assets --jq '.assets[].name' \ + | grep -E -- "-macos-${{ matrix.arch }}\.tar\.gz(\.sha256)?$" \ + | grep -v -F -x -e "$ARTIFACT" -e "$ARTIFACT.sha256" \ + | while read -r old; do gh release delete-asset nightly "$old" --repo "$repo" --yes; done + + - name: Cleanup keychain + if: always() + run: | + security delete-keychain "$KEYCHAIN" || true diff --git a/Tests/StackNudgePanelCoreTests/ExtensionInstallerTests.swift b/Tests/StackNudgePanelCoreTests/ExtensionInstallerTests.swift index 82d507a..68ca1e9 100644 --- a/Tests/StackNudgePanelCoreTests/ExtensionInstallerTests.swift +++ b/Tests/StackNudgePanelCoreTests/ExtensionInstallerTests.swift @@ -281,7 +281,7 @@ final class ExtensionInstallerTests: XCTestCase { _ = ExtensionInstaller.releaseJSON(http: { asked = $0; return Data("{}".utf8) }, gh: { _ in nil }) XCTAssertEqual(asked?.absoluteString, "https://api.github.com/repos/StackOneHQ/stack-nudge-extensions-marketplace/releases/latest") - XCTAssertNotEqual(asked, UpdateChecker.latestReleaseURL) + XCTAssertNotEqual(asked, UpdateChannel.stable.releaseURL) } // The CLI is the fallback, not the first choice — it spawns a process. diff --git a/Tests/StackNudgePanelCoreTests/UpdateChannelTests.swift b/Tests/StackNudgePanelCoreTests/UpdateChannelTests.swift new file mode 100644 index 0000000..a5b9696 --- /dev/null +++ b/Tests/StackNudgePanelCoreTests/UpdateChannelTests.swift @@ -0,0 +1,107 @@ +import XCTest + +@testable import StackNudgePanelCore + +// Stable follows tagged releases; Nightly follows the rolling `nightly` +// pre-release that nightly.yml rebuilds from main each night. +@MainActor +final class UpdateChannelTests: XCTestCase { + + // MARK: - Versions + + func testAVersionReadsAsAReleaseOrANightly() { + XCTAssertEqual(BuildVersion("2.10.1"), BuildVersion(base: "2.10.1")) + XCTAssertEqual(BuildVersion("2.10.0-nightly.812"), BuildVersion(base: "2.10.0", nightly: 812)) + XCTAssertEqual(BuildVersion("2.10.0-nightly.x"), BuildVersion(base: "2.10.0-nightly.x"), + "a nightly needs a number") + XCTAssertEqual(BuildVersion(base: "2.10.0", nightly: 812).string, "2.10.0-nightly.812") + XCTAssertEqual(BuildVersion(base: "2.10.0", nightly: 812).display, "2.10.0 (nightly 812)") + XCTAssertEqual(BuildVersion(base: "2.10.0").display, "2.10.0") + } + + func testTheVersionComesFromThisArchsArtifact() { + XCTAssertEqual(BuildVersion.fromArtifact("stack-nudge-2.10.0-nightly.812-macos-arm64.tar.gz", arch: "arm64"), + BuildVersion(base: "2.10.0", nightly: 812)) + XCTAssertNil(BuildVersion.fromArtifact("stack-nudge-2.10.0-nightly.812-macos-x86_64.tar.gz", arch: "arm64")) + XCTAssertNil(BuildVersion.fromArtifact("stack-nudge-2.10.0-nightly.812-macos-arm64.tar.gz.sha256", arch: "arm64")) + XCTAssertNil(BuildVersion.fromArtifact("extension-away-1.1.1.tar.gz", arch: "arm64")) + } + + private func release(tag: String, assets: [String]) -> [String: Any] { + ["tag_name": tag, "assets": assets.map { ["name": $0] }] + } + + // A nightly's tag is just "nightly", and each arch's upload replaces its + // own files, so the arm64 and x86_64 builds can briefly differ. + func testANightlyIsReadFromItsArtifactNotItsTag() { + let json = release(tag: "nightly", assets: [ + "stack-nudge-2.10.0-nightly.813-macos-arm64.tar.gz", + "stack-nudge-2.10.0-nightly.813-macos-arm64.tar.gz.sha256", + "stack-nudge-2.10.0-nightly.812-macos-x86_64.tar.gz", + ]) + XCTAssertEqual(BuildVersion.offered(by: json, channel: .nightly, arch: "arm64"), + BuildVersion(base: "2.10.0", nightly: 813)) + XCTAssertEqual(BuildVersion.offered(by: json, channel: .nightly, arch: "x86_64"), + BuildVersion(base: "2.10.0", nightly: 812)) + XCTAssertNil(BuildVersion.offered(by: release(tag: "nightly", assets: []), channel: .nightly, arch: "arm64")) + XCTAssertEqual(BuildVersion.offered(by: release(tag: "v2.11.0", assets: []), channel: .stable, arch: "arm64"), + BuildVersion(base: "2.11.0")) + } + + // MARK: - What each channel offers + + // Semver: 2.10.1-nightly.812 comes before 2.10.1. + func testStableOffersANewerReleaseIncludingTheOneANightlyLedUpTo() { + let offer = { UpdateOffer.shouldOffer(BuildVersion($0), to: BuildVersion($1), on: .stable) } + XCTAssertTrue(offer("2.11.0", "2.10.0")) + XCTAssertFalse(offer("2.10.0", "2.10.0")) + // Back on Stable, a nightly waits for the release it was heading for + // rather than stepping back to the one before it. + XCTAssertFalse(offer("2.10.0", "2.10.1-nightly.812")) + XCTAssertTrue(offer("2.10.1", "2.10.1-nightly.812")) + XCTAssertTrue(offer("2.11.0", "2.10.1-nightly.812")) + XCTAssertFalse(offer("2.10.1-nightly.900", "2.10.0"), "the stable channel offers releases only") + } + + func testNightlyOffersALaterBuildOrMovesAReleaseOnToTheNextVersion() { + let offer = { UpdateOffer.shouldOffer(BuildVersion($0), to: BuildVersion($1), on: .nightly) } + XCTAssertTrue(offer("2.10.1-nightly.813", "2.10.1-nightly.812")) + XCTAssertFalse(offer("2.10.1-nightly.812", "2.10.1-nightly.812")) + XCTAssertFalse(offer("2.10.1-nightly.811", "2.10.1-nightly.812")) + // A feat landing moves the next version from a patch to a minor. + XCTAssertTrue(offer("2.11.0-nightly.815", "2.10.1-nightly.812")) + // After 2.10.0 the nightlies lead up to 2.10.1, which is ahead of it. + XCTAssertTrue(offer("2.10.1-nightly.812", "2.10.0")) + // A nightly of the release that's running comes before it. + XCTAssertFalse(offer("2.10.1-nightly.812", "2.10.1")) + XCTAssertFalse(offer("2.11.0", "2.10.0"), "the nightly channel offers nightlies only") + } + + // MARK: - The setting + + func testAnythingButNightlyIsStable() { + XCTAssertEqual(UpdateChannel.from(config: nil), .stable) + XCTAssertEqual(UpdateChannel.from(config: " Nightly "), .nightly) + XCTAssertEqual(UpdateChannel.from(config: "beta"), .stable) + } + + func testTheChannelIsAValueRowUnderActions() { + let nav = PanelNav() + XCTAssertTrue(nav.rows(in: .actions).contains(.updateChannel)) + nav.settingsCategory = .actions + nav.settingsDetailFocused = true + nav.selectedSettingIndex = nav.index(of: .updateChannel) + XCTAssertTrue(nav.selectedRowIsPicker) + nav.cycleForward() + XCTAssertEqual(nav.updateChannel, .stable, "arrows do nothing until a pick starts") + } + + // An offer from the other channel no longer applies, so switching drops + // it and asks again. setUpdateChannel writes the real config, so this + // stops short of calling it and checks the pieces it relies on. + func testTheChannelsReleasesAreDifferentEndpoints() { + XCTAssertTrue(UpdateChannel.stable.releaseURL.path.hasSuffix("/releases/latest")) + XCTAssertTrue(UpdateChannel.nightly.releaseURL.path.hasSuffix("/releases/tags/nightly")) + XCTAssertEqual(UpdateChannel.nightly.releaseGHPath, "repos/StackOneHQ/stack-nudge/releases/tags/nightly") + } +} diff --git a/docs/panel.md b/docs/panel.md index 6959afd..59fb5b8 100644 --- a/docs/panel.md +++ b/docs/panel.md @@ -160,7 +160,7 @@ Reachable from the tab strip, `Cmd+,`, or the last `Cmd`-number. A sidebar of ca | **Extensions** | What's installed, then **Browse extensions** (see [Extensions](#extensions)) | | **Panel** | Hotkey, Pin panel, Keep open when empty, Launch at login, Name from tab titles | | **Events** | History per session, Event history, Clear event history | -| **Actions** | Edit phrases, Check permissions, Open config file, View release notes, Check for updates, Uninstall, Quit | +| **Actions** | Edit phrases, Check permissions, Open config file, View release notes, Update channel (Stable or Nightly, see [Nightly builds](setup.md#nightly-builds)), Check for updates, Uninstall, Quit | | **About** | The version and hook-script status, and a link to this repo | An extension that asks for a Settings page gets one under Extensions. A pending update, an extension update, a missing permission, or an agent whose hooks aren't wired yet shows as a row above every category. An app or extension update also puts a dot on the Settings tab. diff --git a/docs/setup.md b/docs/setup.md index efcba46..fa73c39 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -46,6 +46,12 @@ Because the swap replaces only the bundle, the hook script the agents invoke (`~ No source clone, no swiftc rebuild on the user's machine — the new bundle is the already-signed-and-notarized artifact from CI. Updates are fast and don't disturb the user's Xcode CLT or Python install (or lack thereof). +### Nightly builds + +**Settings → Actions → Update channel** picks which builds the updater offers. **Stable**, the default, is the tagged releases above. **Nightly** follows `main`: at 02:00 UTC each night `main` has moved, it's built, signed and notarized like a release (`.github/workflows/nightly.yml`, which can also be run by hand from Actions) and published as the rolling [`nightly` pre-release](https://github.com/StackOneHQ/stack-nudge/releases/tag/nightly), so the update row offers it within a couple of hours (or straight away from **Check for updates…**). A nightly is a semver pre-release of the release `main` is heading for, `-nightly.`: the version release-please's open release PR proposes (a patch bump when there isn't one) and `main`'s commit count, so Settings → About shows `2.10.1 (nightly 812)`. Switching back to Stable doesn't step back: the release your nightly was leading up to is offered when it ships. The channel is `STACKNUDGE_UPDATE_CHANNEL` (`stable` or `nightly`) in `~/.stack-nudge/config`. Nightlies are pre-releases, which GitHub's latest-release endpoint never returns, so nobody on Stable, and no app from before channels existed, is offered one. + +To grab one by hand: `gh release download nightly --repo StackOneHQ/stack-nudge --pattern "stack-nudge-*-macos-$(uname -m).tar.gz*"`. + ## Uninstall ### macOS — in-app diff --git a/notify.conf.example b/notify.conf.example index 86af838..ac126db 100644 --- a/notify.conf.example +++ b/notify.conf.example @@ -114,6 +114,12 @@ STACKNUDGE_FLOATING_WIDGET=companion # Default: true #STACKNUDGE_GITHUB_USE_GH=false +# Which builds the in-app updater offers: stable (tagged releases) or nightly +# (main, rebuilt each night it has moved, as the rolling `nightly` +# pre-release). Also Settings → Actions → Update channel. +# Default: stable +#STACKNUDGE_UPDATE_CHANNEL=nightly + # Fair-usage budget for pi, in tokens per day, per lane. pi enforces no quota # of its own — API models bill per token against your keys, local models are # free — so these are your own allowances and nothing cuts you off at them. The diff --git a/panel/Panel.swift b/panel/Panel.swift index bfa6fad..652c6ec 100644 --- a/panel/Panel.swift +++ b/panel/Panel.swift @@ -1777,6 +1777,7 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, updateChecker = UpdateChecker(nav: nav) updateChecker?.start() + nav.onUpdateChannelChanged = { [weak self] in self?.updateChecker?.check() } startExtensionUpdateChecks() updater = Updater(nav: nav) diff --git a/panel/PanelNav.swift b/panel/PanelNav.swift index 04e80c8..928e678 100644 --- a/panel/PanelNav.swift +++ b/panel/PanelNav.swift @@ -216,7 +216,7 @@ enum SettingsRow: Hashable { case awayLock case githubLinks, githubActivity, hideShipped, connectGithub, disconnectGithub case historyPerSession - case editPhrases, checkPermissions, openConfig, releaseNotes, checkUpdates, uninstall, quit + case editPhrases, checkPermissions, openConfig, releaseNotes, updateChannel, checkUpdates, uninstall, quit case browseExtensions, extensionSources case openRepo // One per built-in integration on the Integrations list, drawn as a card @@ -272,7 +272,7 @@ extension SettingsRow: CaseIterable { .githubLinks, .githubActivity, .hideShipped, .connectGithub, .disconnectGithub, .historyPerSession, .editPhrases, .checkPermissions, .openConfig, .releaseNotes, - .checkUpdates, .uninstall, .quit, + .updateChannel, .checkUpdates, .uninstall, .quit, .browseExtensions, .extensionSources, .openRepo, ] + Integration.allCases.map { .integration($0) } } @@ -1139,6 +1139,11 @@ final class PanelNav: ObservableObject { // back to .idle a few seconds after a terminal result so the // row reads "Check for updates…" again on subsequent visits. @Published var updateCheckStatus: UpdateCheckStatus = .idle + // Which releases the updater follows (STACKNUDGE_UPDATE_CHANNEL); see + // UpdateChannel. Changing it re-asks, since an offer from the other + // channel no longer applies. + @Published var updateChannel: UpdateChannel = .stable + var onUpdateChannelChanged: (() -> Void)? // Threshold-crossing notifications. quotaAlertsEnabled is the master // switch; quotaAlertThreshold is the single percent value used across // all tiers — banner fires once per period when any tier reaches it. @@ -1712,7 +1717,7 @@ final class PanelNav: ObservableObject { return [.historyPerSession, .eventHistory, .clearHistory] case .actions: return [.editPhrases, .checkPermissions, .openConfig, - .releaseNotes, .checkUpdates, .uninstall, .quit] + .releaseNotes, .updateChannel, .checkUpdates, .uninstall, .quit] // Version and hook-script freshness render above this row as a plain // note, not as rows: they are readouts with nothing to activate, and a // keyboard-selectable row that ignores Enter reads as broken. @@ -2002,6 +2007,7 @@ final class PanelNav: ObservableObject { compactMode = chosen == .pill let rawAlpha = Double(config["STACKNUDGE_COMPACT_ALPHA"] ?? "") ?? 1.0 compactAlpha = Self.compactAlphaOptions.min(by: { abs($0 - rawAlpha) < abs($1 - rawAlpha) }) ?? 1.0 + updateChannel = UpdateChannel.from(config: config[UpdateChannel.configKey]) let rawPerSession = Int(config["STACKNUDGE_EVENTS_PER_SESSION"] ?? "") ?? 5 eventsPerSession = Self.eventsPerSessionOptions.min(by: { abs($0 - rawPerSession) < abs($1 - rawPerSession) }) ?? 5 } @@ -2334,7 +2340,7 @@ final class PanelNav: ObservableObject { .alertThreshold, .pollFrequency, .contextAlert, .piApiBudget, .piLocalBudget, .historyPerSession, - .slackIdle: + .slackIdle, .updateChannel: return true } } @@ -2435,6 +2441,15 @@ final class PanelNav: ObservableObject { if githubSignedIn != signedIn { githubSignedIn = signedIn } } + func setUpdateChannel(_ channel: UpdateChannel) { + guard channel != updateChannel else { return } + updateChannel = channel + ConfigFile.write(key: UpdateChannel.configKey, value: channel.rawValue) + updateAvailable = nil + updateReleaseNotes = nil + onUpdateChannelChanged?() + } + func toggleGithubLinking() { githubLinkingEnabled.toggle() ConfigFile.write(key: "STACKNUDGE_GITHUB", @@ -2661,6 +2676,8 @@ final class PanelNav: ObservableObject { let next = forward ? (idx + 1) % list.count : (idx - 1 + list.count) % list.count eventsPerSession = list[next] ConfigFile.write(key: "STACKNUDGE_EVENTS_PER_SESSION", value: String(eventsPerSession)) + case .updateChannel: + setUpdateChannel(updateChannel == .stable ? .nightly : .stable) // Action rows have nothing to cycle, and activate() handles each of // them before it gets here. case .wireAgents, .dismissAgents, .permissions, .update, .extensionUpdates, diff --git a/panel/Settings.swift b/panel/Settings.swift index 10dc431..5bde366 100644 --- a/panel/Settings.swift +++ b/panel/Settings.swift @@ -567,10 +567,16 @@ struct SettingsView: View { return hints } + // The release version, which is what the bundled changelog is keyed by. private var appVersion: String { Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "?" } + // What the build is: the release, or a nightly built after it. + private var buildVersion: String { + BuildVersion.current()?.display ?? appVersion + } + // The head of an extension's own page: what it last reported, as a // readout rather than a row, for the same reason About's version is one: // there's nothing to activate, and a row that ignores ⏎ reads as broken. @@ -680,7 +686,7 @@ struct SettingsView: View { // stepping Actions → About shifts the text and reads as the page twitching. private var aboutHeader: some View { VStack(alignment: .leading, spacing: 6) { - Text("StackNudge v\(appVersion)") + Text("StackNudge v\(buildVersion)") .font(.subheadline.monospacedDigit()) .frame(maxWidth: .infinity, alignment: .leading) .padding(.horizontal, 10) @@ -947,6 +953,7 @@ struct SettingsView: View { case .checkPermissions: row(.checkPermissions, label: "Check permissions…", kind: .action, value: "") case .openConfig: row(.openConfig, label: "Open config file…", kind: .action, value: "") case .releaseNotes: row(.releaseNotes, label: "View release notes…", kind: .action, value: "") + case .updateChannel: row(.updateChannel, label: "Update channel", kind: .cycle, value: nav.updateChannel.label) case .checkUpdates: row(.checkUpdates, label: "Check for updates…", kind: .action, value: checkForUpdatesStatus) case .uninstall: row(.uninstall, label: "Uninstall StackNudge…", kind: .action, value: "") case .quit: row(.quit, label: "Quit panel", kind: .action, value: "") diff --git a/panel/UpdateChannel.swift b/panel/UpdateChannel.swift new file mode 100644 index 0000000..ae97878 --- /dev/null +++ b/panel/UpdateChannel.swift @@ -0,0 +1,127 @@ +import Foundation + +// Which releases the updater follows. Stable is the tagged releases, read +// from GitHub's /releases/latest, which leaves pre-releases out, so nothing +// here can reach someone who never opted in. Nightly is the rolling +// `nightly` pre-release that nightly.yml rebuilds from main each night. +enum UpdateChannel: String, CaseIterable { + case stable, nightly + + static let configKey = "STACKNUDGE_UPDATE_CHANNEL" + + var label: String { + switch self { + case .stable: return "Stable" + case .nightly: return "Nightly" + } + } + + // Anything but "nightly" is stable, so a typo never opts anyone in. + static func from(config value: String?) -> UpdateChannel { + value?.trimmingCharacters(in: .whitespaces).lowercased() == "nightly" ? .nightly : .stable + } + + var releaseURL: URL { + switch self { + case .stable: return URL(string: "https://api.github.com/repos/StackOneHQ/stack-nudge/releases/latest")! + case .nightly: return URL(string: "https://api.github.com/repos/StackOneHQ/stack-nudge/releases/tags/nightly")! + } + } + + var releaseGHPath: String { + switch self { + case .stable: return "repos/StackOneHQ/stack-nudge/releases/latest" + case .nightly: return "repos/StackOneHQ/stack-nudge/releases/tags/nightly" + } + } +} + +// A build's identity. "2.10.1" is a release. "2.10.1-nightly.812" is a +// nightly: a semver pre-release of 2.10.1, the release main is heading for +// (nightly.yml reads it from release-please's open release PR), where 812 is +// main's commit count, so a later build always has a larger number. As in +// semver, it comes before 2.10.1 itself. +struct BuildVersion: Equatable { + let base: String + let nightly: Int? + + static let nightlyMarker = "-nightly." + // Info.plist key nightly.yml adds; a release build has none. + static let nightlyBuildKey = "StackNudgeNightlyBuild" + + init(base: String, nightly: Int? = nil) { + self.base = base + self.nightly = nightly + } + + init(_ version: String) { + let parts = version.components(separatedBy: Self.nightlyMarker) + if parts.count == 2, let build = Int(parts[1]) { + self.init(base: parts[0], nightly: build) + } else { + self.init(base: version) + } + } + + // How it's written in file names, the status file and the update row. + var string: String { nightly.map { "\(base)\(Self.nightlyMarker)\($0)" } ?? base } + + // How Settings shows it. + var display: String { nightly.map { "\(base) (nightly \($0))" } ?? base } + + static func current(bundle: Bundle = .main) -> BuildVersion? { + guard let base = bundle.infoDictionary?["CFBundleShortVersionString"] as? String else { return nil } + let build = (bundle.infoDictionary?[nightlyBuildKey] as? String).flatMap(Int.init) + ?? bundle.infoDictionary?[nightlyBuildKey] as? Int + return BuildVersion(base: base, nightly: build) + } + + // The version in an app artifact's name, stack-nudge--macos-.tar.gz. + static func fromArtifact(_ name: String, arch: String) -> BuildVersion? { + let prefix = "stack-nudge-", suffix = "-macos-\(arch).tar.gz" + guard name.hasPrefix(prefix), name.hasSuffix(suffix), name.count > prefix.count + suffix.count + else { return nil } + return BuildVersion(String(name.dropFirst(prefix.count).dropLast(suffix.count))) + } + + // The version a release offers this Mac. A stable release is its tag. A + // nightly is read from this arch's artifact rather than the release, + // since each arch's upload replaces its own files and the two can briefly + // be different builds. + static func offered(by json: [String: Any]?, channel: UpdateChannel, arch: String) -> BuildVersion? { + switch channel { + case .stable: + guard let tag = json?["tag_name"] as? String else { return nil } + return BuildVersion(UpdateChecker.stripV(tag)) + case .nightly: + let names = (json?["assets"] as? [[String: Any]] ?? []).compactMap { $0["name"] as? String } + return names.lazy.compactMap { fromArtifact($0, arch: arch) }.first { $0.nightly != nil } + } + } +} + +enum UpdateOffer { + + // Whether `available`, from `channel`'s release, is worth offering to + // the build that's running. Semver order throughout: X-nightly.n comes + // before X. + // + // Stable offers a newer release. To a nightly that includes the release + // it was leading up to, so switching back to Stable waits for that + // release rather than stepping back to the one before. + // + // Nightly offers a later nightly, or to a release build, a nightly of a + // later version: one of its own version would be a step back. + static func shouldOffer(_ available: BuildVersion, to current: BuildVersion, on channel: UpdateChannel) -> Bool { + let newerBase = UpdateChecker.isNewer(available.base, than: current.base) + switch channel { + case .stable: + guard available.nightly == nil else { return false } + return newerBase || (current.nightly != nil && available.base == current.base) + case .nightly: + guard let build = available.nightly else { return false } + guard let running = current.nightly else { return newerBase } + return build > running && !UpdateChecker.isNewer(current.base, than: available.base) + } + } +} diff --git a/panel/UpdateChecker.swift b/panel/UpdateChecker.swift index a70ac44..b336d91 100644 --- a/panel/UpdateChecker.swift +++ b/panel/UpdateChecker.swift @@ -1,8 +1,9 @@ import Foundation -// Polls the GitHub Releases API for stack-nudge and surfaces the latest tag -// when it's newer than this bundle's CFBundleShortVersionString. The result -// is published back to PanelNav (on the main thread) so the tab badge and +// Polls the GitHub Releases API for stack-nudge and surfaces what the update +// channel offers this build: the latest release, or on Nightly the rolling +// nightly pre-release (see UpdateChannel and UpdateOffer). The result is +// published back to PanelNav (on the main thread) so the tab badge and // "Update available" row react automatically. // // Checks fire on app launch and then every `interval` seconds while the app @@ -10,13 +11,9 @@ import Foundation // signal, not a critical path. final class UpdateChecker { - static let latestReleaseURL = URL( - string: "https://api.github.com/repos/StackOneHQ/stack-nudge/releases/latest" - )! static let releasesPageURL = URL( string: "https://github.com/StackOneHQ/stack-nudge/releases/latest" )! - static let latestGHPath = "repos/StackOneHQ/stack-nudge/releases/latest" // Build URL + gh CLI API path for a specific tag like "1.4.2". Both // endpoints return the same JSON shape as /latest, so callers can reuse @@ -63,17 +60,21 @@ final class UpdateChecker { // completion fires on the main thread when supplied; background // polls call with no completion and rely on the nav side effect. func check(completion: ((CheckResult) -> Void)? = nil) { - guard let current = Self.currentVersion() else { + guard let current = BuildVersion.current() else { DispatchQueue.main.async { completion?(.failed) } return } - fetchReleaseJSON(url: Self.latestReleaseURL, ghAPIPath: Self.latestGHPath) { [weak self] json in - guard let tag = json?["tag_name"] as? String else { + // Read on the caller's thread, which is main: the timer and the + // Settings actions both run there. + let channel = nav?.updateChannel ?? .stable + fetchReleaseJSON(url: channel.releaseURL, ghAPIPath: channel.releaseGHPath) { [weak self] json in + guard let available = BuildVersion.offered(by: json, channel: channel, arch: Self.currentHostArch()) + else { DispatchQueue.main.async { completion?(.failed) } return } - let latest = Self.stripV(tag) - let newer = Self.isNewer(latest, than: current) + let latest = available.string + let newer = UpdateOffer.shouldOffer(available, to: current, on: channel) let body = json?["body"] as? String // release-please creates the GitHub Release the moment its PR // merges, but release.yml takes 5–15 min more to build, sign, @@ -118,7 +119,7 @@ final class UpdateChecker { } } - private static func currentHostArch() -> String { + static func currentHostArch() -> String { var sysinfo = utsname() uname(&sysinfo) let m = withUnsafePointer(to: &sysinfo.machine) { @@ -132,7 +133,8 @@ final class UpdateChecker { // the user clicks the update row before the background check has cached // notes. Calls completion on the main thread with the body string or nil. func fetchReleaseNotes(completion: @escaping (String?) -> Void) { - fetchReleaseJSON(url: Self.latestReleaseURL, ghAPIPath: Self.latestGHPath) { json in + let channel = nav?.updateChannel ?? .stable + fetchReleaseJSON(url: channel.releaseURL, ghAPIPath: channel.releaseGHPath) { json in DispatchQueue.main.async { completion(json?["body"] as? String) } } } @@ -140,11 +142,13 @@ final class UpdateChecker { // Fetch release notes for a specific version tag — used by the post-update // view to surface exactly what shipped, even if a newer release lands in // between the install and the relaunch. Same gh-fallback path as the - // /latest case. + // /latest case. A nightly has no tag of its own, so its notes are the + // rolling nightly release's. func fetchReleaseNotes(for version: String, completion: @escaping (String?) -> Void) { + let nightly = BuildVersion(version).nightly != nil fetchReleaseJSON( - url: Self.tagReleaseURL(for: version), - ghAPIPath: Self.tagGHPath(for: version) + url: nightly ? UpdateChannel.nightly.releaseURL : Self.tagReleaseURL(for: version), + ghAPIPath: nightly ? UpdateChannel.nightly.releaseGHPath : Self.tagGHPath(for: version) ) { json in DispatchQueue.main.async { completion(json?["body"] as? String) } } @@ -211,10 +215,6 @@ final class UpdateChecker { // MARK: - Helpers - static func currentVersion() -> String? { - Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String - } - static func stripV(_ tag: String) -> String { tag.hasPrefix("v") ? String(tag.dropFirst()) : tag } diff --git a/panel/Updater.swift b/panel/Updater.swift index 9896821..14d61fa 100644 --- a/panel/Updater.swift +++ b/panel/Updater.swift @@ -8,7 +8,7 @@ import SwiftUI // completes — no longer driven by a shell runner's STAGE markers. enum UpdatePhase: String { case idle - case fetching // GET /releases/latest + case fetching // GET the channel's release (UpdateChannel.releaseURL) case downloading // streaming the .tar.gz case verifying // SHA256 check case extracting // tar -xzf @@ -57,10 +57,6 @@ extension UpdatePhase { final class Updater { static let statusPath = "/tmp/stack-nudge-update-status.json" - static let releasesAPI = URL( - string: "https://api.github.com/repos/StackOneHQ/stack-nudge/releases/latest" - )! - static let releasesGHPath = "repos/StackOneHQ/stack-nudge/releases/latest" private weak var nav: PanelNav? private let session: URLSession @@ -82,6 +78,8 @@ final class Updater { // progress flows back via nav.updaterPhase / nav.updaterLog. func run() { guard let nav else { return } + // Read here, on main, before the work moves off it. + let channel = nav.updateChannel DispatchQueue.main.async { nav.updaterPhase = .idle nav.updaterLog = "" @@ -104,7 +102,7 @@ final class Updater { // recycling the tarball and the empty tmpdir shell. defer { self.cleanupTempDir() } do { - try self.performUpdate() + try self.performUpdate(channel: channel) } catch { self.fail(error) } @@ -147,14 +145,14 @@ final class Updater { // MARK: - Pipeline - private func performUpdate() throws { + private func performUpdate(channel: UpdateChannel) throws { // 1. Resolve which artifact to download. setPhase(.fetching) appendLog("Fetching release manifest…") - let release = try fetchRelease() - appendLog("Latest release: v\(release.version)") - let arch = currentArch() + let release = try fetchRelease(channel: channel, arch: arch) + appendLog("Latest \(channel == .nightly ? "nightly" : "release"): v\(release.version)") + // Anchored at both ends. `contains` matched anywhere in the name, and // this release also carries extension packages — so an extension whose // version embedded "-macos-arm64.tar.gz" produced a name that matched, @@ -411,16 +409,20 @@ final class Updater { let downloadURL: URL } - private func fetchRelease() throws -> ReleaseInfo { - if let json = httpFetchJSON(Self.releasesAPI) { - return try parseRelease(json) - } + private func fetchRelease(channel: UpdateChannel, arch: String) throws -> ReleaseInfo { // Fall back to gh CLI for private-repo dev cycles (same pattern as // UpdateChecker's poller). - if let json = ghFetchJSON(Self.releasesGHPath) { - return try parseRelease(json) + guard let json = httpFetchJSON(channel.releaseURL) ?? ghFetchJSON(channel.releaseGHPath) else { + throw UpdateError.releaseFetchFailed + } + let release = try parseRelease(json) + // A nightly's tag is just "nightly": what it is comes from this arch's + // artifact, the same reading UpdateChecker made when it offered it. + guard channel == .nightly else { return release } + guard let build = BuildVersion.offered(by: json, channel: .nightly, arch: arch) else { + throw UpdateError.noArtifactForArch(arch: arch) } - throw UpdateError.releaseFetchFailed + return ReleaseInfo(version: build.string, assets: release.assets) } private func parseRelease(_ json: [String: Any]) throws -> ReleaseInfo {