Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 37 additions & 16 deletions .github/workflows/release-cli.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@ on:
type: string

permissions:
contents: write
contents: read

jobs:
build-cli:
permissions:
contents: read
strategy:
fail-fast: false
matrix:
Expand Down Expand Up @@ -396,31 +398,50 @@ jobs:
echo "out_dir=$OUT_DIR" >> "$GITHUB_OUTPUT"
echo "asset=$ASSET" >> "$GITHUB_OUTPUT"

- name: Upload release assets
if: github.event_name == 'release'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
shell: bash
run: |
set -euo pipefail
TAG="${RELEASE_TAG}"
OUT_DIR="${{ steps.pkg.outputs.out_dir }}"
ASSET="${{ steps.pkg.outputs.asset }}"
gh release upload "$TAG" "$OUT_DIR/$ASSET" "$OUT_DIR/$ASSET.sha256" --clobber

- name: Upload workflow artifact (manual runs)
if: github.event_name == 'workflow_dispatch'
- name: Upload packaged artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: codexbar-cli-${{ matrix.name }}
path: |
${{ steps.pkg.outputs.out_dir }}/${{ steps.pkg.outputs.asset }}
${{ steps.pkg.outputs.out_dir }}/${{ steps.pkg.outputs.asset }}.sha256

update-homebrew-tap:
publish-release-assets:
runs-on: ubuntu-24.04
needs: build-cli
if: github.event_name == 'release'
permissions:
actions: read
contents: write
steps:
- name: Download packaged artifacts
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
with:
pattern: codexbar-cli-*
path: release-assets
merge-multiple: true

- name: Upload release assets
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
RELEASE_TAG: ${{ github.ref_name }}
shell: bash
run: |
set -euo pipefail
mapfile -t assets < <(find release-assets -maxdepth 1 -type f \
\( -name 'CodexBarCLI-*.tar.gz' -o -name 'CodexBarCLI-*.tar.gz.sha256' \) -print | sort)
if [[ "${#assets[@]}" -ne 12 ]]; then
printf 'Expected 12 CLI release files, found %s.\n' "${#assets[@]}" >&2
printf '%s\n' "${assets[@]:-<none>}" >&2
exit 1
fi
gh release upload "$RELEASE_TAG" "${assets[@]}" --clobber --repo "$GITHUB_REPOSITORY"

update-homebrew-tap:
runs-on: ubuntu-24.04
needs: publish-release-assets
if: github.event_name == 'release'
permissions: {}
steps:
- name: Resolve release tag
id: release
Expand Down
6 changes: 6 additions & 0 deletions Scripts/lint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,10 @@ check_documentation_links() {
node "${ROOT_DIR}/Scripts/check-documentation-links.mjs"
}

check_release_cli_permissions() {
"${ROOT_DIR}/Scripts/test_release_cli_permissions.sh"
}

check_llms_index() {
node "${ROOT_DIR}/Scripts/generate-llms.mjs" --check
}
Expand All @@ -93,10 +97,12 @@ run_portable_checks() {
check_sparkle_signing_paths
check_swift_test_sharding
check_ci_path_gate
check_release_cli_permissions
check_repository_size
check_shell_scripts
check_documentation_links
check_llms_index
check_release_cli_permissions
check_site_locales
}

Expand Down
55 changes: 55 additions & 0 deletions Scripts/test_release_cli_permissions.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#!/usr/bin/env bash

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
WORKFLOW="${ROOT_DIR}/.github/workflows/release-cli.yml"

python3 - "$WORKFLOW" <<'PY'
import pathlib
import re
import sys

workflow = pathlib.Path(sys.argv[1]).read_text()

if not re.search(r"(?ms)^permissions:\n contents: read\n", workflow):
raise SystemExit("release workflow must default to read-only repository contents")


def job(name: str) -> str:
match = re.search(rf"(?ms)^ {re.escape(name)}:\n(?P<body>.*?)(?=^ [A-Za-z0-9_-]+:|\Z)", workflow)
if match is None:
raise SystemExit(f"missing {name} job")
return match.group("body")


build = job("build-cli")
if not re.search(r"(?ms)^ permissions:\n contents: read\n", build):
raise SystemExit("build-cli must receive only read access to repository contents")
if "contents: write" in build:
raise SystemExit("build-cli must not receive repository write access")
if "Upload packaged artifact" not in build or "if: github.event_name" in build.split("Upload packaged artifact", 1)[1].split("\n ", 1)[0]:
raise SystemExit("build-cli must upload its packaged artifact for every run")

publisher = job("publish-release-assets")
for required in (
"needs: build-cli",
"if: github.event_name == 'release'",
"actions: read",
"contents: write",
"actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093",
"pattern: codexbar-cli-*",
"merge-multiple: true",
'gh release upload "$RELEASE_TAG" "${assets[@]}" --clobber --repo "$GITHUB_REPOSITORY"',
):
if required not in publisher:
raise SystemExit(f"release publisher is missing: {required}")

tap = job("update-homebrew-tap")
if "needs: publish-release-assets" not in tap:
raise SystemExit("tap updater must wait for release assets to upload")
if "permissions: {}" not in tap:
raise SystemExit("tap updater must not receive the repository token")

print("Release CLI permissions workflow tests passed.")
PY
17 changes: 16 additions & 1 deletion Sources/CodexBar/Localization.swift
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,22 @@ func L(_ key: String, language: String) -> String {
}

func codexBarLocalizedLocale() -> Locale {
let language = resolvedAppLanguage()
codexBarLocale(forLanguage: resolvedAppLanguage())
}

/// Returns the locale of the resource bundle currently selected by `L`.
///
/// This can differ from `Locale.current` when the app falls back to a supported language. Plural
/// formatting must use this locale so it follows the same language as the resolved strings.
func codexBarLocalizedResourceLocale() -> Locale {
let bundleURL = localizedBundle().bundleURL
guard bundleURL.pathExtension == "lproj" else {
return codexBarLocalizedLocale()
}
return codexBarLocale(forLanguage: bundleURL.deletingPathExtension().lastPathComponent)
}

private func codexBarLocale(forLanguage language: String) -> Locale {
guard !language.isEmpty else { return .current }
let normalized = language.lowercased()
if normalized == "ar" || normalized.hasPrefix("ar-") {
Expand Down
16 changes: 9 additions & 7 deletions Sources/CodexBar/UsagePaceText.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,19 +39,21 @@ enum UsagePaceText {

static func sessionEquivalentDetail(forecast: SessionEquivalentForecast) -> SessionEquivalentDetail {
let displayedEstimate = Self.boundedFullWindowCount(forecast.estimatedWindowsToExhaustWeekly)
let numberText = String.localizedStringWithFormat(
L("≈%d full 5h windows of weekly left · %d windows until reset"),
displayedEstimate,
forecast.windowsUntilReset)
let formattingLocale = codexBarLocalizedResourceLocale()
let numberText = String(
format: L("≈%d full 5h windows of weekly left · %d windows until reset"),
locale: formattingLocale,
arguments: [displayedEstimate, forecast.windowsUntilReset])
let verdictText: String
if forecast.estimatedWindowsToExhaustWeekly >= forecast.availableWindowsUntilReset {
verdictText = L("Weekly cannot run out before reset at this pace")
} else {
let windowsEarly = Self.boundedWindowCount(
forecast.availableWindowsUntilReset - forecast.estimatedWindowsToExhaustWeekly)
verdictText = String.localizedStringWithFormat(
L("Weekly can run out ≈%d windows early"),
max(1, windowsEarly))
verdictText = String(
format: L("Weekly can run out ≈%d windows early"),
locale: formattingLocale,
arguments: [max(1, windowsEarly)])
}
return SessionEquivalentDetail(
verdictText: verdictText,
Expand Down
25 changes: 25 additions & 0 deletions Tests/CodexBarTests/LocalizationBundleCacheTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,31 @@ struct LocalizationBundleCacheTests {
#expect(bundle.bundleURL.lastPathComponent == "en.lproj")
}

@Test
func `format locale follows the resolved resource bundle`() {
let english = CodexBarLocalizationOverride.$appLanguage.withValue("en") {
codexBarLocalizedResourceLocale()
}
#expect(english.language.languageCode?.identifier == "en")

let fallback = CodexBarLocalizationOverride.$appLanguage.withValue("zz-unknown") {
codexBarLocalizedResourceLocale()
}
#expect(fallback.language.languageCode?.identifier == "en")
}

@Test
func `resource locale expands English stringsdict singular forms`() {
let rendered = CodexBarLocalizationOverride.$appLanguage.withValue("en") {
String(
format: L("≈%d full 5h windows of weekly left · %d windows until reset"),
locale: codexBarLocalizedResourceLocale(),
arguments: [1, 1])
}

#expect(rendered == "≈1 full 5h window of weekly left · 1 window until reset")
}

@Test
func `resolution survives an explicit cache reset`() {
let first = CodexBarLocalizationOverride.$appLanguage.withValue("uk") {
Expand Down
59 changes: 37 additions & 22 deletions Tests/CodexBarTests/SpendDashboardControllerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Testing
@testable import CodexBar

@MainActor
@Suite(.serialized)
struct SpendDashboardControllerTests {
@Test
func `empty codex history loads as successful inactive source`() async {
Expand Down Expand Up @@ -288,7 +289,7 @@ struct SpendDashboardControllerTests {
let snapshot = Self.input(id: "claude", provider: .claude, cost: 3).snapshot
store._setTokenSnapshotForTesting(snapshot, provider: .claude)
store._test_tokenUsageRefreshOverride = { _, _ in }
let controller = SpendDashboardController(requestBuilder: { mode in
let controller = SpendDashboardController(userDefaults: settings.userDefaults, requestBuilder: { mode in
await SpendDashboardSource.makeRequest(settings: settings, store: store, mode: mode)
})

Expand Down Expand Up @@ -408,9 +409,11 @@ struct SpendDashboardControllerTests {
environmentBase: [:])
store._setTokenSnapshotForTesting(Self.input(provider: .claude, cost: 3).snapshot, provider: .claude)
store._test_tokenUsageRefreshOverride = { _, _ in }
let controller = SpendDashboardController(requestBuilder: { mode in
await SpendDashboardSource.makeRequest(settings: settings, store: store, mode: mode)
})
let controller = SpendDashboardController(
userDefaults: settings.userDefaults,
requestBuilder: { mode in
await SpendDashboardSource.makeRequest(settings: settings, store: store, mode: mode)
})

let firstConfiguration = SpendDashboardSource.configuration(settings: settings, store: store)
controller.update(configuration: firstConfiguration)
Expand All @@ -431,9 +434,11 @@ struct SpendDashboardControllerTests {
#expect(controller.failedSourceCount == 1)
#expect(store.tokenSnapshot(for: .claude)?.last30DaysCostUSD == 3)

let reopenedController = SpendDashboardController(requestBuilder: { mode in
await SpendDashboardSource.makeRequest(settings: settings, store: store, mode: mode)
})
let reopenedController = SpendDashboardController(
userDefaults: settings.userDefaults,
requestBuilder: { mode in
await SpendDashboardSource.makeRequest(settings: settings, store: store, mode: mode)
})
reopenedController.update(configuration: replacementConfiguration)
await Self.waitUntil { !reopenedController.isRefreshing }
#expect(reopenedController.model.groups.isEmpty)
Expand Down Expand Up @@ -487,9 +492,11 @@ struct SpendDashboardControllerTests {

store._setTokenSnapshotForTesting(Self.input(provider: .mistral, cost: 3).snapshot, provider: .mistral)
store._test_providerRefreshOverride = { _ in }
let controller = SpendDashboardController(requestBuilder: { mode in
await SpendDashboardSource.makeRequest(settings: settings, store: store, mode: mode)
})
let controller = SpendDashboardController(
userDefaults: settings.userDefaults,
requestBuilder: { mode in
await SpendDashboardSource.makeRequest(settings: settings, store: store, mode: mode)
})
controller.update(configuration: selectedBackupConfiguration)
await Self.waitUntil { !controller.isRefreshing }
#expect(controller.model.groups.first?.totalCost == 3)
Expand Down Expand Up @@ -527,9 +534,11 @@ struct SpendDashboardControllerTests {
environmentBase: [:])
store._setTokenSnapshotForTesting(Self.input(provider: .claude, cost: 4).snapshot, provider: .claude)
store._test_tokenUsageRefreshOverride = { _, _ in }
let controller = SpendDashboardController(requestBuilder: { mode in
await SpendDashboardSource.makeRequest(settings: settings, store: store, mode: mode)
})
let controller = SpendDashboardController(
userDefaults: settings.userDefaults,
requestBuilder: { mode in
await SpendDashboardSource.makeRequest(settings: settings, store: store, mode: mode)
})
controller.update(configuration: SpendDashboardSource.configuration(settings: settings, store: store))
await Self.waitUntil { !controller.isRefreshing }
#expect(controller.model.groups.first?.totalCost == 4)
Expand Down Expand Up @@ -557,9 +566,11 @@ struct SpendDashboardControllerTests {
environmentBase: [:])
store._setTokenSnapshotForTesting(Self.input(provider: .claude, cost: 5).snapshot, provider: .claude)
store._test_tokenUsageRefreshOverride = { _, _ in }
let controller = SpendDashboardController(requestBuilder: { mode in
await SpendDashboardSource.makeRequest(settings: settings, store: store, mode: mode)
})
let controller = SpendDashboardController(
userDefaults: settings.userDefaults,
requestBuilder: { mode in
await SpendDashboardSource.makeRequest(settings: settings, store: store, mode: mode)
})
let firstConfiguration = SpendDashboardSource.configuration(settings: settings, store: store)
controller.update(configuration: firstConfiguration)
await Self.waitUntil { !controller.isRefreshing }
Expand Down Expand Up @@ -626,9 +637,11 @@ struct SpendDashboardControllerTests {
environmentBase: [:])
store._setTokenSnapshotForTesting(Self.input(provider: .claude, cost: 5).snapshot, provider: .claude)
store._test_tokenUsageRefreshOverride = { _, _ in }
let controller = SpendDashboardController(requestBuilder: { mode in
await SpendDashboardSource.makeRequest(settings: settings, store: store, mode: mode)
})
let controller = SpendDashboardController(
userDefaults: settings.userDefaults,
requestBuilder: { mode in
await SpendDashboardSource.makeRequest(settings: settings, store: store, mode: mode)
})
controller.update(configuration: SpendDashboardSource.configuration(settings: settings, store: store))
await Self.waitUntil { !controller.isRefreshing }
#expect(controller.model.groups.first?.totalCost == 5)
Expand All @@ -644,9 +657,11 @@ struct SpendDashboardControllerTests {
#expect(controller.model.groups.isEmpty)
#expect(controller.failedSourceCount == 1)

let reopenedController = SpendDashboardController(requestBuilder: { mode in
await SpendDashboardSource.makeRequest(settings: settings, store: store, mode: mode)
})
let reopenedController = SpendDashboardController(
userDefaults: settings.userDefaults,
requestBuilder: { mode in
await SpendDashboardSource.makeRequest(settings: settings, store: store, mode: mode)
})
reopenedController.update(configuration: reenabledConfiguration)
await Self.waitUntil { !reopenedController.isRefreshing }
#expect(reopenedController.model.groups.isEmpty)
Expand Down
Loading