diff --git a/.github/ci-qemu/Dockerfile b/.github/ci-qemu/Dockerfile new file mode 100644 index 000000000000..6bcf2b676e96 --- /dev/null +++ b/.github/ci-qemu/Dockerfile @@ -0,0 +1,17 @@ +FROM ghcr.io/archlinux/archlinux:latest + +# Minimal Arch QEMU image for running test/ci-vm with Arch's current QEMU +# instead of pulling and installing packages on every CI run. +RUN set -euo pipefail; \ + if ! grep -qw landlock /sys/kernel/security/lsm 2>/dev/null; then \ + printf '#!/bin/sh\nexec /usr/bin/pacman --disable-sandbox "$@"\n' >/usr/local/bin/pacman; \ + chmod 0755 /usr/local/bin/pacman; \ + fi; \ + sed -i '1i Server = https://mirror.omarchy.org/$repo/os/$arch' /etc/pacman.d/mirrorlist; \ + pacman -Syu --noconfirm --needed \ + qemu-system-x86 \ + qemu-hw-display-virtio-gpu \ + qemu-hw-display-virtio-vga \ + qemu-img \ + openssh; \ + rm -rf /var/cache/pacman/pkg/* /usr/local/bin/pacman diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 000000000000..2fd8311590ea --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,25 @@ + + +## What changes + + + +## Verification + + + +## Screenshots + + diff --git a/.github/workflows/ci-qemu-image.yml b/.github/workflows/ci-qemu-image.yml new file mode 100644 index 000000000000..ec64dcde1076 --- /dev/null +++ b/.github/workflows/ci-qemu-image.yml @@ -0,0 +1,91 @@ +name: Refresh CI QEMU image + +# Keeps ghcr.io/omacom/omarchy-ci-qemu:latest current with Arch's QEMU and +# openssh so .github/workflows/test.yml boots the test VM without running +# pacman -Syu on every pull request. + +on: + push: + branches: [quattro] + paths: + - .github/ci-qemu/** + - .github/workflows/ci-qemu-image.yml + pull_request: + paths: + - .github/ci-qemu/** + - .github/workflows/ci-qemu-image.yml + schedule: + # Weekly refresh on Sundays at 04:17 UTC. + - cron: '17 4 * * 0' + workflow_dispatch: + +concurrency: + group: ci-qemu-image-${{ github.event.pull_request.number || 'quattro' }} + cancel-in-progress: false + +permissions: + contents: read + +jobs: + validate: + if: github.event_name == 'pull_request' + runs-on: ubuntu-26.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Build and smoke-test candidate image + run: | + docker build -t omarchy-ci-qemu:candidate .github/ci-qemu + docker run --rm omarchy-ci-qemu:candidate bash -euo pipefail -c ' + qemu-system-x86_64 --version | head -n 1 + qemu-img --version | head -n 1 + ssh -V + ' + + publish: + if: github.repository == 'omacom/omarchy' && github.ref == 'refs/heads/quattro' && github.event_name != 'pull_request' + runs-on: ubuntu-26.04 + timeout-minutes: 15 + permissions: + contents: read + packages: write + env: + REGISTRY_IMAGE: ghcr.io/omacom/omarchy-ci-qemu + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Build and smoke-test image + run: | + docker build --pull --no-cache -t omarchy-ci-qemu:candidate .github/ci-qemu + docker run --rm omarchy-ci-qemu:candidate bash -euo pipefail -c ' + qemu-system-x86_64 --version | head -n 1 + qemu-img --version | head -n 1 + ssh -V + ' + - name: Publish image to GHCR + env: + GH_TOKEN: ${{ github.token }} + GH_ACTOR: ${{ github.actor }} + DOCKER_CONFIG: ${{ runner.temp }}/ci-qemu-registry-auth + run: | + set -euo pipefail + mkdir -p "$DOCKER_CONFIG" + trap 'rm -rf "$DOCKER_CONFIG"' EXIT + printf '%s' "$GH_TOKEN" | docker login ghcr.io --username "$GH_ACTOR" --password-stdin + version="$REGISTRY_IMAGE:run-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT" + docker tag omarchy-ci-qemu:candidate "$version" + docker push "$version" + # GHCR creates new packages private. Warn loudly until it is flipped + # public so fork PRs can pull it too; test.yml falls back until then. + anonymous_config=$(mktemp -d "$RUNNER_TEMP/ci-qemu-anonymous.XXXXXX") + if ! DOCKER_CONFIG="$anonymous_config" docker manifest inspect "$version" >/dev/null 2>&1; then + echo "::warning::Make the omacom/omarchy-ci-qemu GHCR package public so fork PRs can pull it without falling back to pacman." + fi + rm -rf "$anonymous_config" + docker tag omarchy-ci-qemu:candidate "$REGISTRY_IMAGE:latest" + docker push "$REGISTRY_IMAGE:latest" + digest=$(docker image inspect "$version" --format '{{index .RepoDigests 0}}') + printf '### CI QEMU image\n\nImage: `%s`\n' "$digest" >>"$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/i18n-check.yml b/.github/workflows/i18n-check.yml index 0bf2ade2bce9..217156fdb2be 100644 --- a/.github/workflows/i18n-check.yml +++ b/.github/workflows/i18n-check.yml @@ -3,11 +3,21 @@ name: Check translation structure # The pull-request gate for i18n: individual PRs only add the English side # (code plus English catalog entries), so this validates structure, not # completeness. Missing translations are pending work for the sync workflow. -# The job runs on every PR (and passes trivially when nothing i18n-relevant -# changed) so it can be a required status check without blocking PRs that -# never trigger a path-filtered workflow. +# It runs only for pull requests that touch what it checks. A required status +# check must not be path-filtered, since a PR that skips it waits on it +# forever, so this needs a job-level condition instead if it is ever made one. on: pull_request: + paths: + - 'default/i18n/**' + - 'default/omarchy/omarchy-menu.jsonc' + - 'shell/**' + - 'bin/**' + - 'install/**' + - 'manual/**' + - 'scripts/i18n-sync.py' + - 'test/shell.d/i18n-test.sh' + - '.github/workflows/i18n-*' permissions: contents: read @@ -18,27 +28,10 @@ jobs: timeout-minutes: 10 steps: - uses: actions/checkout@v7 - with: - fetch-depth: 0 - - name: Check whether anything i18n-relevant changed - id: relevant - env: - BASE_REF: ${{ github.base_ref }} - run: | - git fetch origin "$BASE_REF" - if git diff --name-only "origin/$BASE_REF...HEAD" | grep -qE '^(default/i18n/|default/omarchy/omarchy-menu\.jsonc|shell/|bin/|manual/|scripts/i18n-sync\.py|test/shell\.d/i18n-test\.sh|\.github/workflows/i18n-)'; then - echo "relevant=true" >> "$GITHUB_OUTPUT" - else - echo "relevant=false" >> "$GITHUB_OUTPUT" - echo "No i18n-relevant files changed; passing." - fi - uses: actions/setup-node@v7 - if: steps.relevant.outputs.relevant == 'true' with: node-version: 24 - name: Structural i18n test - if: steps.relevant.outputs.relevant == 'true' run: I18N_STRUCTURAL=1 bash test/shell.d/i18n-test.sh - name: No embedded English literals - if: steps.relevant.outputs.relevant == 'true' run: python3 scripts/i18n-sync.py extract-scan --check diff --git a/.github/workflows/i18n-sync.yml b/.github/workflows/i18n-sync.yml index 7e1a7b8055dd..2bf78b0a7ff1 100644 --- a/.github/workflows/i18n-sync.yml +++ b/.github/workflows/i18n-sync.yml @@ -3,18 +3,17 @@ name: Sync translations # Keeps the 49 translations converged with English without blocking it. # Extraction runs without credentials and ships a patch; a trusted job # vets and publishes it to the i18n-sync branch; one credential-less Muse -# runner per pending language translates; a single collect job lands -# everything as one auto-merging pull request. Modeled on omarchy-site's -# translate-news workflow; keep the Muse install pin in step with it. +# runner per pending language translates; a single collect job validates +# everything and land merges it as one pull request. Modeled on +# omarchy-site's translate-news workflow; keep the Muse install pin in step +# with it. # -# Repository settings this needs: the MUSE_API_KEY Actions secret, and an -# I18N_SYNC_TOKEN secret (a fine-grained PAT with contents + pull-requests -# write on this repo) so the bot's pull request triggers checks — PRs -# created with GITHUB_TOKEN do not. Without it, the PR still opens but a -# human must nudge it (close/reopen or push) before auto-merge can pass. -# "Allow auto-merge" must be enabled, with i18n-check as a required status -# check on quattro. Runs where extraction touched executable code never -# auto-merge; they wait for a human review instead. +# Repository settings this needs: the MUSE_API_KEY Actions secret (and an +# optional MUSE_MODEL variable), and an I18N_SYNC_TOKEN secret (a +# fine-grained PAT with contents + pull-requests write on this repo) for +# the bot that opens and merges the pull request. Runs where extraction +# touched executable code are never merged here; they wait for a human +# review instead. on: push: branches: [quattro] @@ -25,6 +24,7 @@ on: - 'manual/*.md' - 'shell/**' - 'bin/**' + - 'install/**' workflow_dispatch: schedule: # Retry unfinished translations without delaying English. @@ -93,7 +93,6 @@ jobs: run: | mkdir -p "$RUNNER_TEMP/muse-bin" curl --fail --silent --show-error --location https://api.meta.ai/muse-launcher.sh --output "$RUNNER_TEMP/muse-bin/muse" - echo "c6db294799a190ca380da274beb3b9c0e160e0da9681a3d364ce8b0e5fa3a4bc $RUNNER_TEMP/muse-bin/muse" | sha256sum --check chmod +x "$RUNNER_TEMP/muse-bin/muse" MUSE_LAUNCHER_INSTALL=1 "$RUNNER_TEMP/muse-bin/muse" echo "MUSE_NO_AUTO_UPDATE=1" >> "$GITHUB_ENV" @@ -124,9 +123,9 @@ jobs: - name: Package extraction as a patch run: | mkdir -p "$RUNNER_TEMP/extraction" - git add -A -- bin shell default/i18n/en default/i18n/extract-allowlist.json + git add -A -- bin install shell default/i18n/en default/i18n/extract-allowlist.json git diff --cached --binary --no-renames > "$RUNNER_TEMP/extraction/extract.patch" - if git diff --cached --name-only | grep -qE '^(bin|shell)/'; then + if git diff --cached --name-only | grep -qE '^(bin|install|shell)/'; then echo true > "$RUNNER_TEMP/extraction/code-touched.txt" else echo false > "$RUNNER_TEMP/extraction/code-touched.txt" @@ -141,7 +140,7 @@ jobs: if-no-files-found: error # Applies the extraction patch and runs every check that loads its code, with - # no credentials: an extraction may change bin/ or shell/, and the i18n test + # no credentials: an extraction may change bin/, install/ or shell/, and the i18n test # require()s shell JavaScript, so nothing that runs here may hold a token. validate-extract: needs: [prepare, extract] @@ -169,7 +168,7 @@ jobs: fi python3 scripts/i18n-sync.py extract-scan --check I18N_STRUCTURAL=1 bash test/shell.d/i18n-test.sh - for f in $(git diff --cached --name-only -- bin/); do bash -n "$f"; done + for f in $(git diff --cached --name-only -- bin/ install/); do bash -n "$f"; done # Publishes the vetted extraction to the i18n-sync branch. This job holds the # write token, so it runs no repository code: only git, and the path check @@ -211,7 +210,7 @@ jobs: from pathlib import Path patch = Path(os.environ['RUNNER_TEMP']) / 'extraction/extract.patch' out = subprocess.run(['git', 'apply', '--numstat', '-z', str(patch)], check=True, capture_output=True).stdout - allowed = ('bin/', 'shell/', 'default/i18n/en/', 'default/i18n/extract-allowlist.json') + allowed = ('bin/', 'install/', 'shell/', 'default/i18n/en/', 'default/i18n/extract-allowlist.json') code = False for record in out.split(b'\0'): if not record: @@ -219,7 +218,7 @@ jobs: path = record.decode().split('\t', 2)[2] if not path.startswith(allowed) or '..' in Path(path).parts: sys.exit(f'extraction patch contains a disallowed path: {path}') - code = code or path.startswith(('bin/', 'shell/')) + code = code or path.startswith(('bin/', 'install/', 'shell/')) print('true' if code else 'false') PY ) @@ -250,7 +249,10 @@ jobs: translate: needs: [prepare, publish-extract] - if: needs.prepare.outputs.locales != '[]' + # Without a status function the implicit success() also fails when an + # upstream job was skipped, and extract is skipped whenever there is + # nothing to extract, which kept every translation pending. + if: ${{ always() && !cancelled() && needs.prepare.result == 'success' && needs.publish-extract.result == 'success' && needs.prepare.outputs.locales != '[]' }} strategy: fail-fast: false matrix: @@ -266,7 +268,6 @@ jobs: run: | mkdir -p "$RUNNER_TEMP/muse-bin" curl --fail --silent --show-error --location https://api.meta.ai/muse-launcher.sh --output "$RUNNER_TEMP/muse-bin/muse" - echo "c6db294799a190ca380da274beb3b9c0e160e0da9681a3d364ce8b0e5fa3a4bc $RUNNER_TEMP/muse-bin/muse" | sha256sum --check chmod +x "$RUNNER_TEMP/muse-bin/muse" MUSE_LAUNCHER_INSTALL=1 "$RUNNER_TEMP/muse-bin/muse" echo "MUSE_NO_AUTO_UPDATE=1" >> "$GITHUB_ENV" @@ -390,7 +391,7 @@ jobs: with: name: collected path: ${{ runner.temp }}/collected - - name: Commit and open the auto-merging pull request + - name: Commit, open and merge the pull request env: GH_TOKEN: ${{ secrets.I18N_SYNC_TOKEN || github.token }} CODE_TOUCHED: ${{ needs.publish-extract.outputs.code_touched }} @@ -424,7 +425,7 @@ jobs: pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls?head=$GITHUB_REPOSITORY_OWNER:i18n-sync&base=quattro&state=open" --jq '.[0].number // empty') if [ -z "$pr" ]; then if [ "$changed" = true ] || [ "$(git rev-list --count origin/quattro..HEAD)" -gt 0 ]; then - pr=$(gh pr create --base quattro --head i18n-sync --title 'Update translations' --body 'Automated translation sync: extracts embedded English into the catalogs and fills pending translations for all 49 languages. Generated by the Sync translations workflow; merges automatically once i18n-check passes.') + pr=$(gh pr create --base quattro --head i18n-sync --title 'Update translations' --body 'Automated translation sync: extracts embedded English into the catalogs and fills pending translations for all 49 languages. Generated by the Sync translations workflow, which validated these files and merges this pull request itself.') pr=$(basename "$pr") fi fi @@ -435,9 +436,16 @@ jobs: if [ "$(gh pr view "$pr" --json autoMergeRequest --jq '.autoMergeRequest != null')" = true ]; then gh pr merge --disable-auto "$pr" fi - gh pr comment "$pr" --body 'This sync includes an automated extraction that changed executable code under `bin/` or `shell/`, so auto-merge is off: please review those hunks before merging.' + gh pr comment "$pr" --body 'This sync includes an automated extraction that changed executable code under `bin/`, `install/` or `shell/`, so auto-merge is off: please review those hunks before merging.' echo "Extraction touched code; PR #$pr waits for human review." else - gh pr merge --auto --squash "$pr" || echo "Auto-merge could not be enabled for #$pr (enable 'Allow auto-merge' in repository settings); the PR is left open for a human." + # Merged here rather than left to auto-merge: collect has already + # run the structural i18n test on these files, and the next run + # rebuilds i18n-sync from quattro, so a pull request still open + # when it starts loses its translations. + if ! gh pr merge --squash "$pr"; then + echo "Could not merge #$pr; its translations stay pending and are redone by the next run." >&2 + exit 1 + fi fi fi diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 000000000000..b5948efe8c97 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,217 @@ +name: Tests + +# Runs ./test/all on a real Omarchy install: the VM image of the current +# release, booted fresh for each shard, with this checkout's code copied in. +# The package recipes are checked out beside it, because some tests hold this +# repository's scripts against them. Same-repo branches and pushes to quattro +# run on Namespace 16x32 runners (inline, avoiding a separate trust job); fork +# pull requests run the same sharded suite on GitHub's ubuntu-26.04 runners. + +on: + pull_request: + push: + branches: [quattro] + +permissions: + contents: read + +concurrency: + group: tests-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + test: + name: test (${{ matrix.shard }}) + runs-on: ${{ (github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository) && 'namespace-profile-linux-amd64-16x32' || 'ubuntu-26.04' }} + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + include: + - shard: noncomp-1 + args: --no-cli --group=noncomp --shard=1/2 + - shard: noncomp-2 + args: --no-cli --group=noncomp --shard=2/2 + - shard: comp + args: --group=comp + - shard: exclusive + args: --no-cli --group=exclusive + env: + SITE: https://nightly.omarchy.org + PREBUILT_QEMU_IMAGE: ghcr.io/omacom/omarchy-ci-qemu:latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + path: src/omarchy + persist-credentials: false + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: omacom/omarchy-pkgs + path: src/omarchy-pkgs + persist-credentials: false + + # Fetch the current release VM image and pull the prebuilt QEMU container + # concurrently. On Namespace runners with a bundled cache volume, the + # release image is reused across runs keyed by its sha256 (~0.2 s hit) + # and the container image stays warm in Namespace's container cache. On + # GitHub-hosted runners, the image lands in /dev/shm (RAM) while the + # container pulls in parallel. + - name: Prepare VM image and QEMU container + run: | + set -euo pipefail + docker pull -q "$PREBUILT_QEMU_IMAGE" >/tmp/qemu-pull.log 2>&1 & + pull_pid=$! + + curl -fsS --retry 3 -o /tmp/latest.json "$SITE/stable/latest.json" + jq -r '"Image: Omarchy \(.omarchy_version), kernel \(.kernel)"' /tmp/latest.json | tee -a "$GITHUB_STEP_SUMMARY" + sha=$(jq -r .vm.sha256 /tmp/latest.json) + unpacked=$(jq -r .vm.unpacked /tmp/latest.json) + url=$(jq -r .vm.url /tmp/latest.json) + + download_image() { + local dest=$1 + local -a curl_pids=() + mkdir -p "$dest" + if ! command -v aria2c >/dev/null 2>&1; then + sudo apt-get update -qq + sudo apt-get install -y -qq --no-install-recommends aria2 + fi + for file in vmlinuz initrd cmdline; do + curl -fsS --retry 3 -o "$dest/$file" "$unpacked$file" & + curl_pids+=("$!") + done + local started=$SECONDS + aria2c --quiet -x 16 -s 16 -d "$dest" -o base.qcow2 "$url" + for pid in "${curl_pids[@]}"; do + wait "$pid" + done + echo "Fetched $(stat -c %s "$dest/base.qcow2") bytes in $(( SECONDS - started )) s" | tee -a "$GITHUB_STEP_SUMMARY" + (cd "$dest" && echo "$sha base.qcow2" | sha256sum -c -) + } + + if [[ -n ${NSC_CACHE_PATH:-} && -d $NSC_CACHE_PATH && -w $NSC_CACHE_PATH ]]; then + cache_root="$NSC_CACHE_PATH/omarchy-vm" + cache_dir="$cache_root/$sha" + if [[ -f $cache_dir/.ready ]]; then + echo "Image cache hit ($sha)" | tee -a "$GITHUB_STEP_SUMMARY" + else + mkdir -p "$cache_root" + stage="$cache_root/.tmp.$$" + trap 'rm -rf "$stage"' EXIT + download_image "$stage" + touch "$stage/.ready" + if [[ ! -d $cache_dir ]]; then + mv "$stage" "$cache_dir" 2>/dev/null || rm -rf "$stage" + else + rm -rf "$stage" + fi + trap - EXIT + # Keep only the current release in the cache volume. + for entry in "$cache_root"/*; do + [[ -d $entry && $(basename "$entry") != $sha ]] && rm -rf "$entry" + done + fi + image_dir="$cache_dir" + else + image_dir="/dev/shm/image" + download_image "$image_dir" + fi + + if wait "$pull_pid"; then + echo "QEMU_IMAGE=$PREBUILT_QEMU_IMAGE" >>"$GITHUB_ENV" + echo "QEMU_PREBUILT=1" >>"$GITHUB_ENV" + else + echo "Prebuilt $PREBUILT_QEMU_IMAGE unavailable; falling back to archlinux + pacman" + echo "QEMU_IMAGE=ghcr.io/archlinux/archlinux:latest" >>"$GITHUB_ENV" + echo "QEMU_PREBUILT=0" >>"$GITHUB_ENV" + fi + echo "IMAGE_DIR=$image_dir" >>"$GITHUB_ENV" + + # QEMU runs in an Arch container on the runner's KVM: Arch's current QEMU + # (11) instead of Ubuntu's older one, sized to the runner's CPUs and RAM, + # with its throwaway overlay in a RAM tmpfs and cache=unsafe. + - name: Run the tests in the VM + env: + SHARD_ARGS: ${{ matrix.args }} + run: | + set -euo pipefail + sudo chmod 0666 /dev/kvm + smp=$(nproc) + ram_kb=$(awk '/^MemTotal:/ { print $2 }' /proc/meminfo) + if (( ram_kb >= 24000000 )); then + mem=16G + tmpfs_size=4g + else + mem=6G + tmpfs_size=2g + fi + if (( smp >= 8 )); then + comp_jobs=4 + else + comp_jobs=2 + fi + + # shellcheck disable=SC2086 # SHARD_ARGS is intentional word-split flags + docker run --rm --device /dev/kvm \ + --tmpfs "/tmp:rw,nosuid,nodev,size=$tmpfs_size" \ + -v "$PWD:/w" -v "$IMAGE_DIR:/image:ro" -w /w \ + -e VM_STATE_DIR=/tmp -e SMP="$smp" -e MEM="$mem" \ + -e CI_VM_TIMEOUT=900 \ + -e OMARCHY_TEST_COMP_JOBS="$comp_jobs" \ + -e QEMU_PREBUILT="$QEMU_PREBUILT" \ + "$QEMU_IMAGE" bash -euo pipefail -c ' + if [[ $QEMU_PREBUILT != "1" ]]; then + # pacman 7 fails every sync on a kernel without Landlock, which + # these runners have; omarchy-iso does the same. + if ! grep -qw landlock /sys/kernel/security/lsm 2>/dev/null; then + printf "#!/bin/sh\nexec /usr/bin/pacman --disable-sandbox \"\$@\"\n" >/usr/local/bin/pacman + chmod 0755 /usr/local/bin/pacman + fi + # Our own Arch mirror first, the public ones after it; a mirror + # that drops one file must not fail the run: try again. + sed -i "1i Server = https://mirror.omarchy.org/\$repo/os/\$arch" /etc/pacman.d/mirrorlist + for attempt in 1 2 3; do + if pacman -Syu --noconfirm --needed qemu-system-x86 qemu-hw-display-virtio-gpu qemu-hw-display-virtio-vga qemu-img openssh >/dev/null; then + break + elif (( attempt < 3 )); then + echo "pacman failed, attempt $attempt of 3; trying again in 15 s" + sleep 15 + else + echo "::error::the test container could not install QEMU" + exit 1 + fi + done + fi + qemu-system-x86_64 --version | head -n 1 + src/omarchy/test/ci-vm /image src out "$@" + ' _ $SHARD_ARGS + + # The container ran as root: its output belongs to root until here. + - name: Hand the results to the runner's user + if: always() + run: sudo chown -R "$(id -u):$(id -g)" out 2>/dev/null || true + + - name: Summary + if: always() + run: | + if [[ -f out/run.log ]]; then + { + echo '```' + sed -n '/^\(Skipped checks in\|All [0-9][0-9]* test files passed\.\|[0-9][0-9]* test files completed without failures\|[0-9][0-9]* of [0-9][0-9]* test files failed:\|Slowest test files:\)/,$p' out/run.log + echo '```' + } >>"$GITHUB_STEP_SUMMARY" + fi + + # Only a failed run's logs are kept, and test/ci-vm has already printed + # the failing files' output into the job log. GitHub's artifact service + # can fail on its own, so the upload never changes the verdict and + # never holds the job for long. + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: failure() + continue-on-error: true + timeout-minutes: 2 + with: + name: tests-${{ matrix.shard }}-${{ github.run_id }}-${{ github.run_attempt }} + path: out/ + if-no-files-found: ignore + retention-days: 14 diff --git a/.github/workflows/visual-evidence.yml b/.github/workflows/visual-evidence.yml new file mode 100644 index 000000000000..8dc211988418 --- /dev/null +++ b/.github/workflows/visual-evidence.yml @@ -0,0 +1,68 @@ +name: Check visual evidence + +# Asks PRs that could change what's on screen to show it: screenshots or a +# recording in the Screenshots section of the PR body, or a +# "No visible change: " line, which is taken at the author's word. +# It's a nudge toward easier reviews, not a gate: it isn't a required check, +# so a red X here doesn't block a merge. The paths are deliberately broad for +# that reason. It reads only the event payload, so a fork's PR runs it the +# same way, and editing the body re-runs it. A required status check must not +# be path-filtered (a PR that skips it waits on it forever), so this needs a +# job-level condition instead if it is ever made one. +on: + pull_request: + types: [opened, edited, synchronize, reopened, ready_for_review] + paths: + - 'shell/**' + - 'config/**' + - 'themes/**' + - 'applications/**' + - 'install/*.packages' + - 'default/themed/**' + - 'default/hypr/**' + - 'default/omarchy/**' + - 'default/applications/**' + - 'default/fonts/**' + - 'default/gtk/**' + - 'default/plymouth/**' + - 'default/sddm/**' + - 'default/limine/**' + - 'default/i18n/**' + +permissions: + contents: read + +concurrency: + group: visual-evidence-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + visual-evidence: + if: ${{ !github.event.pull_request.draft && github.event.pull_request.user.type != 'Bot' }} + runs-on: ubuntu-latest + timeout-minutes: 2 + steps: + - name: Look for screenshots or a recording in the PR body + env: + PR_BODY: ${{ github.event.pull_request.body }} + run: | + python3 - <<'EOF' + import os, re, sys + + body = re.sub(r"", "", os.environ.get("PR_BODY") or "", flags=re.S) + + # Read the Screenshots section when the template is there; without it, + # only embedded media anywhere in the body counts. + section = re.search(r"^#{1,6}\s*(screenshots?|recordings?|demo)\b.*?$(.*?)(?=^#{1,6}\s|\Z)", body, flags=re.S | re.M | re.I) + media = r"!\[[^\]]*\]\(|\" is all it needs. Editing the body re-runs this check.") + sys.exit(1) + EOF diff --git a/.greptile/files.json b/.greptile/files.json new file mode 100644 index 000000000000..d7d91a43ebc6 --- /dev/null +++ b/.greptile/files.json @@ -0,0 +1,212 @@ +{ + "files": [ + { + "path": "AGENTS.md", + "description": "Contributor contract: style, command naming, the runtime environment (OMARCHY_PATH is always set in the session), platform names, helper commands and tests. CLAUDE.md only imports this file." + }, + { + "path": "agents/skills/command-metadata.md", + "description": "Header metadata every bin/ command declares", + "scope": [ + "bin/**" + ] + }, + { + "path": "docs/cli-router.md", + "description": "How bin/omarchy resolves routes and what omarchy commands --check enforces", + "scope": [ + "bin/**", + "test/cli" + ] + }, + { + "path": "agents/skills/install-scripts.md", + "description": "Rules for install/ leaves and the apply/finalize/provision commands", + "scope": [ + "install/**", + "bin/omarchy-apply-*", + "bin/omarchy-provision-*" + ] + }, + { + "path": "agents/skills/migrations.md", + "description": "Migration model, format, ordering and when tests are kept", + "scope": [ + "migrations/**", + "bin/omarchy-migrate*", + "bin/omarchy-upgrade-to-quattro" + ] + }, + { + "path": "docs/update-process.md", + "description": "The omarchy update pipeline, its sudo boundary, the pacman guard and channels", + "scope": [ + "bin/omarchy-update*", + "bin/omarchy-migrate*", + "bin/omarchy-channel-*", + "bin/omarchy-refresh-pacman", + "bin/omarchy-reinstall-pkgs", + "default/libalpm/**", + "default/pacman/**", + "install/helpers/pacman.sh" + ] + }, + { + "path": "docs/lifecycle-dispatch.md", + "description": "Platform lifecycle operations, their callers and the trust rules for root entrypoints", + "scope": [ + "bin/omarchy-lifecycle-dispatch", + "bin/omarchy-provision-*", + "bin/omarchy-system-factory-reset", + "bin/omarchy-update-boot", + "bin/omarchy-drive-password", + "bin/omarchy-install-browser", + "bin/omarchy-install-gaming-steam", + "bin/omarchy-remove-gaming-steam", + "install/provisioning/**", + "install/hardware/platform-setup.sh", + "install/user/platform-setup.sh" + ] + }, + { + "path": "docs/passwordless-sudo.md", + "description": "Grant lifecycle and package ownership for passwordless sudo", + "scope": [ + "bin/omarchy-sudo-*", + "bin/omarchy-security-functions", + "etc/sudoers.d/**" + ] + }, + { + "path": "docs/file-layout.md", + "description": "Where each repo tree is packaged and installed, env bootstrap, first-run and image builds", + "scope": [ + "config/**", + "default/**", + "etc/**", + "applications/**", + "install/**", + "bin/omarchy-provision-*", + "bin/omarchy-reinstall-*", + "bin/omarchy-dev-*" + ] + }, + { + "path": "agents/skills/shell-dev.md", + "description": "Quickshell plugin contract, IPC, event sources instead of polling, palette imports", + "scope": [ + "shell/**", + "bin/omarchy-shell*" + ] + }, + { + "path": "docs/omarchy-shell.md", + "description": "Plugin manifest, third-party facades, shell.json, theme tokens and bar modules", + "scope": [ + "shell/**", + "config/omarchy/shell.json", + "bin/omarchy-plugin*", + "bin/omarchy-bar*" + ] + }, + { + "path": "docs/menu.md", + "description": "Menu schema, guards, providers and select/input modes", + "scope": [ + "default/omarchy/omarchy-menu.jsonc", + "shell/plugins/menu/**", + "bin/omarchy-menu*" + ] + }, + { + "path": "docs/notifications.md", + "description": "Notification daemon, DND rules and the omarchy-notification-send contract", + "scope": [ + "shell/plugins/notifications/**", + "bin/omarchy-notification-*", + "bin/omarchy-reminder*" + ] + }, + { + "path": "docs/theming.md", + "description": "Theme activation, what a cloned theme may not ship, colors.toml and shell.toml", + "scope": [ + "themes/**", + "default/themed/**", + "bin/omarchy-theme-*" + ] + }, + { + "path": "docs/i18n.md", + "description": "Catalogs, plural and number rules, translation sync and the translator brief", + "scope": [ + "default/i18n/**", + "manual/**", + "shell/**", + "bin/**", + "scripts/i18n-sync.py", + ".github/workflows/**" + ] + }, + { + "path": "agents/skills/mise-tools.md", + "description": "Where tools go instead of mise, and what Omarchy still uses mise for", + "scope": [ + "etc/mise/**", + "install/omarchy-base.packages", + "bin/omarchy-install-ai-cli" + ] + }, + { + "path": "docs/testing.md", + "description": "Suite map, base-test.sh contract, compositor gating and performance guards", + "scope": [ + "test/**" + ] + }, + { + "path": "agents/skills/acceptance-tests.md", + "description": "Graphical acceptance suite run in a disposable VM", + "scope": [ + "test/acceptance", + "test/acceptance.d/**" + ] + }, + { + "path": "agents/skills/icon-font.md", + "description": "Adding glyphs to the Omarchy icon font", + "scope": [ + "default/fonts/omarchy/**" + ] + }, + { + "path": "docs/audio-tuning.md", + "description": "Speaker tunings and what a tuning must report", + "scope": [ + "default/audio/**", + "install/hardware/speaker-tuning.sh", + "install/user/first-run/audio-tuning.sh", + "bin/omarchy-audio-*", + "shell/plugins/panels/audio/**" + ] + }, + { + "path": "docs/input-methods.md", + "description": "Input method setup for CJK languages", + "scope": [ + "default/input-methods/**", + "shell/Commons/InputMethodState.qml", + "install/provisioning/setup-form.sh", + "install/user/input-method.sh", + "default/hypr/**" + ] + }, + { + "path": "docs/elsewhen.md", + "description": "The Elsewhen world clock plugin", + "scope": [ + "shell/plugins/panels/elsewhen/**" + ] + } + ] +} diff --git a/.oligarchyrc b/.oligarchyrc new file mode 100644 index 000000000000..65a8c44d58d5 --- /dev/null +++ b/.oligarchyrc @@ -0,0 +1 @@ +{ "tests": "oligarchy-tests" } diff --git a/AGENTS.md b/AGENTS.md index d3984f4c8d0d..0acbf3ff6a80 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,9 +5,12 @@ matching guide before starting: - [`agents/skills/command-metadata.md`](agents/skills/command-metadata.md) - adding or changing commands in `bin/` - [`agents/skills/install-scripts.md`](agents/skills/install-scripts.md) - working under `install/` or on system/user setup commands +- [`agents/skills/mise-tools.md`](agents/skills/mise-tools.md) - adding a tool to Omarchy, and what Omarchy still uses mise for - [`agents/skills/shell-dev.md`](agents/skills/shell-dev.md) - editing the Quickshell desktop under `shell/` - [`agents/skills/icon-font.md`](agents/skills/icon-font.md) - adding branded glyphs to `default/fonts/omarchy/omarchy.ttf` - [`agents/skills/acceptance-tests.md`](agents/skills/acceptance-tests.md) - writing or running graphical acceptance tests under `test/acceptance.d/` +- [`agents/skills/oligarchy-tests.md`](agents/skills/oligarchy-tests.md) - full omarchy tests that run in qemu to validate behavior +- [`agents/skills/motion.md`](agents/skills/motion.md) - adding or changing any animation or transition in `shell/` - [`agents/skills/visual-verification.md`](agents/skills/visual-verification.md) - verifying any change with a visual effect in the running UI - [`agents/skills/migrations.md`](agents/skills/migrations.md) - creating or changing migrations under `migrations/` @@ -86,7 +89,7 @@ Where platform code lives: - Packages: `install/omarchy-base.packages` for everyone, `install/omarchy-aarch64.packages` for every ARM machine, `install/omarchy-.packages` for one family, and base packages with no aarch64 build in `install/omarchy-x86_64-only.packages`. `omarchy-pkg-defaults` composes them. - Pacman templates: `default/pacman/` for x86, `default/pacman//` for each ARM platform. - Hardware setup: `install/hardware//`, gated by a predicate. `install/hardware/apple/` holds Intel Mac quirks; Apple Silicon's own setup ships in the omarchy-mac packages. -- Boot chains Omarchy can't drive generically: a platform package behind `omarchy-lifecycle-dispatch` ([`docs/lifecycle-dispatch.md`](docs/lifecycle-dispatch.md)). Platforms that boot Limine with UKIs like x86 keep the generic path. +- Boot chains Omarchy can't drive generically: a platform package behind `omarchy-lifecycle-dispatch` ([`docs/lifecycle-dispatch.md`](docs/lifecycle-dispatch.md)). Platforms that boot Limine with UKIs like x86 keep the generic path. x86 machines can move to systemd-boot ([`docs/boot.md`](docs/boot.md)): change the kernel command line with `omarchy-boot-cmdline` and rebuild with `omarchy-boot-rebuild`, never with Limine tools directly, so both loaders stay current. The experience should be the same on every platform. When a package or feature is missing or broken on one, the default is to get it fixed upstream (an aarch64 build, a bug report, a patch to the maintainer) and leave the gap visible meanwhile, not to paper over it. When asked for a platform workaround, say so and propose the upstream fix first. Hiding a menu entry or skipping a package is fine only for things that can't exist there (an x86 guest VM, an x86-only proprietary binary). Alternative packages and platform-only replacements are a last resort, used only when upstream can't or won't fix it, with the reason written next to the code. @@ -128,6 +131,10 @@ Exceptions are allowed for migration and package-helper scripts where the helper - Do not add `aliases` to new menu entries. Aliases are reserved for established alternate names users already type, kept for compatibility. +# Keybindings + +- Default hotkeys follow the planes in [`manual/07-hotkeys.md`](manual/07-hotkeys.md#how-hotkeys-are-laid-out). Pick the plane from what the binding does, never move an existing binding to make room for a new one, and use `Alt` only for a variant of the same binding without it. Hold new and changed bindings in review to the same rules. + # Config Structure - `config/` - default configs copied to `~/.config/` @@ -144,6 +151,27 @@ test entry points: - `./test/cli` - CLI routing, command metadata, theme helpers, and safe dispatch coverage - `./test/shell` - all Omarchy shell tests under `test/shell.d/` +How to run them without wasting runs: + +- Run the files for what you changed directly: `bash test/shell.d/-test.sh`. A change inside one plugin or command runs that area's files (and `i18n-test.sh` when catalog strings changed), not `./test/shell`. +- Run `./test/shell` or `./test/all` only when the change reaches shared code (`shell/Commons/`, `base-test.sh`, the runners, a widely used `bin/` helper), and then once, at the end. +- Always write the whole output to a log file and read it from there: `bash test/shell.d/-test.sh >/tmp/.log 2>&1`. Never pipe a test run straight through `grep`, `head` or `tail`: what they drop is gone, and getting it back costs a whole run. `./test/shell` keeps every file's log and prints the directory at the end; read a failure from its log. +- Run a test again only after changing something it covers. Never rerun to see output, to confirm a pass, or in the hope that a failure goes away. +- For a failure in a file you did not touch, run that one file once on the base branch (in a worktree, or with `git stash`). If it fails there too, it was already broken: report it and leave it out of this change. +- Tests that use the live session (`require_compositor`, `shell-idle-spawn-test.sh`) read the real desktop, so the user working at it can fail them. One that fails in a full run and passes alone is session noise: say so; do not loop on it. + +When to add a test. A test earns its place only by catching a regression nothing else would; every one costs a maintainer to read and everyone a slower suite. Before writing one, name the breakage it would catch. If the answer is "someone edits the line I just added", don't write it. + +- No test for a small declarative change: a menu row, a config value, a package-list entry, a string, a rename. Those need no test of their own, and certainly not a new file. +- Don't restate the implementation: grepping the source or config for the string you just added, asserting a value equals itself, or re-reading the file you edited to confirm the edit is there. +- A test must fail without your change. Revert the fix, or reason it through, and check that the test goes red for the reason the change exists. One that stays green guards nothing. +- Don't test your own stub. If a fake binary or fixture the test writes provides the behaviour under test, nothing real is tested. +- No change-detectors: snapshots of large output, file lists, or exact counts that break whenever someone adds an unrelated entry. +- Extend the area's existing test file (`git grep` the command or function under `test/`) rather than adding a new `*-test.sh`, and follow its style. +- Keep tests in proportion to the change. A few lines of change rarely justify more than a few lines of test, and usually none. +- No test for a migration. It runs once and is frozen once it ships; test logic it needs by moving that logic into a `bin/` command. +- Do test real logic: parsing, routing, a guard on hardware without the feature, the edge case a fix handles. A bug fix with logic in it gets the one test that fails on the base branch and passes with the fix. + New Omarchy shell tests should live in `test/shell.d/*-test.sh` so `./test/shell` picks them up automatically. Source `test/shell.d/base-test.sh` for shared root-path discovery, assertions, and Node test helpers. The graphical acceptance suite runs in a disposable VM, not in the active @@ -160,6 +188,4 @@ To copy a default config to user config with automatic backup: omarchy-refresh-config hypr/hyprland.lua ``` -This copies `$OMARCHY_PATH/config/hypr/hyprland.lua` to `~/.config/hypr/hyprland.lua`. The argument -is interpolated into both paths and only checked with `[[ -e ]]`, so pass a plain relative path: a -name containing `..` resolves and copies, landing outside `~/.config` rather than being rejected. +This copies `$OMARCHY_PATH/config/hypr/hyprland.lua` to `~/.config/hypr/hyprland.lua`. The argument must be a plain relative path: an absolute path or any `..` segment is rejected before anything is copied. That check is lexical, so a symlink under `~/.config` is still followed and its target rewritten — which is what keeps symlink-managed dotfiles working. diff --git a/agents/skills/command-metadata.md b/agents/skills/command-metadata.md index 9b90cf5130ba..e6966772663d 100644 --- a/agents/skills/command-metadata.md +++ b/agents/skills/command-metadata.md @@ -12,6 +12,7 @@ Supported metadata keys: - `# omarchy:name=...` - override the command name inferred from the filename - `# omarchy:summary=...` - short help text - `# omarchy:args=...` - usage arguments +- `# omarchy:subcommand= — ` - one line per subcommand, for a command that takes subcommands (`omarchy bar use `, `omarchy bar reset`, ...); listings and help show each on its own row with its own summary, and `args` is derived from them - `# omarchy:examples=...` - examples separated with ` | ` - `# omarchy:alias=...` / `# omarchy:aliases=...` - alternate routes - `# omarchy:hidden=true` - hide from default command listings diff --git a/agents/skills/icon-font.md b/agents/skills/icon-font.md index 15585006844e..14a48e58ce76 100644 --- a/agents/skills/icon-font.md +++ b/agents/skills/icon-font.md @@ -7,7 +7,7 @@ Fonts does not have: the Omarchy logo and the agent and app brand marks. The menu draws one by naming the font on an entry: ```jsonc -"setup.default.agent.grok": {"icon":"","iconFont":"omarchy","label":"Grok", ...} +"install.ai.desktop.grok-bot": {"icon":"","iconFont":"omarchy","label":"Grok Bot", ...} ``` Without `iconFont`, an entry's `icon` is drawn in the menu font, so reach for @@ -49,8 +49,6 @@ Pick a source whose silhouette alone reads. The command prints these, and all of them matter: - Point the menu entry at the new codepoint with `"iconFont":"omarchy"`. -- Bump the charset range asserted in `test/shell.d/menu-test.sh`; that test - pins the font's coverage and fails until it matches. - Check the README line the command added, and give it a proper display name with `--label` if the glyph name is not the brand's name. diff --git a/agents/skills/install-scripts.md b/agents/skills/install-scripts.md index b117b19370f6..0374eb1a51a8 100644 --- a/agents/skills/install-scripts.md +++ b/agents/skills/install-scripts.md @@ -7,7 +7,7 @@ commands and reusable setup leaves: - `bin/omarchy-apply-system` runs root-owned system setup during ISO finalization. - `bin/omarchy-apply-hardware` runs idempotent hardware-specific setup and is called by `omarchy-apply-system`. -- `bin/omarchy-finalize-user` runs the per-user runtime finalization (skill symlinks, xdg-user-dirs, mime defaults, `install/user/all.sh`). Shipped user defaults are seeded by `/etc/skel` from `omarchy-settings`, not by this command. `bin/omarchy-reinstall-configs` is the explicit destructive resync of those defaults into an existing user's `$HOME`. +- `bin/omarchy-provision-user` runs the per-user runtime finalization (skill symlinks, xdg-user-dirs, mime defaults, `install/user/all.sh`). Shipped user defaults are seeded by `/etc/skel` from `omarchy-settings`, not by this command. `bin/omarchy-reinstall-configs` is the explicit destructive resync of those defaults into an existing user's `$HOME`. - leaf scripts under `install/` are sourced by `run_logged $OMARCHY_INSTALL/path/to/script.sh` and intentionally do not have shebangs. - avoid `exit` in sourced setup scripts unless intentionally aborting setup. - use `$OMARCHY_INSTALL` and `$OMARCHY_PATH` instead of hard-coded Omarchy paths. diff --git a/agents/skills/migrations.md b/agents/skills/migrations.md index 5ed1d4890901..a06224a818da 100644 --- a/agents/skills/migrations.md +++ b/agents/skills/migrations.md @@ -127,6 +127,7 @@ New migration format: - Use `$OMARCHY_PATH` to reference the Omarchy directory. - Be idempotent. Check existing state before changing it. - Migrations are strictly ordered and synchronous. A migration that cannot finish must exit non-zero, remain pending, and stop the queue; never mark later migrations complete against state an earlier migration has not established. +- A migration waiting on a package that has not landed yet (a settings package still declaring what it changes, say) exits `75` with a line saying what it waits for. It stays pending and stops the queue like a failure, but `omarchy update` carries on, and the next update or login runs it again. A dev checkout routinely runs ahead of its packages, so a plain failure there would break every update until the package is rebuilt. Any other non-zero exit is a real failure and stops the update. - Use helper commands such as `omarchy-cmd-present`, `omarchy-cmd-missing`, `omarchy-pkg-add`, `omarchy-pkg-drop`, `omarchy-pkg-present`, and `omarchy-pkg-missing` when appropriate. @@ -163,7 +164,7 @@ rm ~/.local/state/omarchy/migrations/.sh omarchy-migrate ``` -Keep a dedicated test while the migration is still being written or bugfixed, if it calls an Omarchy helper whose interface can still change, or if it is a security-sensitive privileged repair (FIDO2, leftover installer artifacts, udev, sshd). Once a one-shot rewrite has shipped in a tagged release and is frozen, drop the test even when that rewrite used sudo, pacman, or limine-mkinitcpio. Keep the migration itself for late-updaters. Tests of `omarchy-migrate`, the login notifier, and `omarchy-upgrade-to-quattro` stay. +Don't add a test for a migration under `test/`. It runs once per machine and is frozen once it ships, so the test stops guarding anything. If a migration needs logic worth testing, put that logic in a `bin/` command the migration calls and test the command. Tests of `omarchy-migrate`, the login notifier, and `omarchy-upgrade-to-quattro` stay. Omarchy 4.0 is upgraded through `bin/omarchy-upgrade-to-quattro`, not through the normal migration runner. Do not add compatibility migrations for old installer diff --git a/agents/skills/mise-tools.md b/agents/skills/mise-tools.md new file mode 100644 index 000000000000..a07cf3994a2a --- /dev/null +++ b/agents/skills/mise-tools.md @@ -0,0 +1,27 @@ +# mise and where tools go + +Read this before adding a tool to Omarchy, or before changing how Omarchy uses mise. + +## Omarchy declares no mise tools + +mise manages the language runtimes a user sets up from _Install > Development_ (`omarchy-install-dev-env`), each one written to the user's own config with `mise use --global`. Omarchy installs nothing through mise on its own, and ships no lazy tools or auto-install stubs: `etc/mise/conf.d/omarchy-tools.toml` declares nothing, and stays only because older migrations wait for it to exist. + +Every other tool is a package in omacom/omarchy-pkgs, updated by `omarchy update` like the rest of the system: + +- A tool everyone gets goes in `install/omarchy-base.packages` (`uv`, `nodejs`, `playwright-cli`). +- A coding agent is a package on the fast ring, which publishes each upstream release to every channel within the hour. It is installed explicitly, from _Install > AI > CLI_ or by picking it in the agents panel, through `omarchy-install-ai-cli`, which maps the agent's command to its package. Add a new agent there, under `install.ai.cli` and `remove.ai.cli` in the menu, in `omarchy-default-agent`, and in `omarchy-agent`. +- Any other optional CLI goes under _Install > CLI_ and _Remove > CLI_ (GitHub, Hunk, Basecamp, Cloudflare, HEY); gh also comes with _Setup > Git_. +- A package turns off the tool's own updater, since pacman owns updates. + +Don't split a kind of tool between mise and packages, and don't add a mise declaration to get a tool installed. + +## What Omarchy still asks of mise + +- `etc/mise/conf.d/omarchy.toml` holds settings, such as keeping the version a running process uses when `mise up` upgrades it. +- `omarchy update` runs `omarchy-update-mise` for the runtimes the user set up. + +Account switching for `claude`, `codex` and `grok` is Omarchy's own, not mise's: `omarchy-agent-account-dispatch` writes a dispatcher into `~/.local/share/omarchy/agent-accounts/bin` for each of them that is installed, running `omarchy-agent-account-exec`, and `default/bash/env-bootstrap` puts that directory first on PATH, so every session, script and editor runs as the selected subscription account. There is no dispatcher for a CLI that isn't installed: installing or removing an agent through Omarchy rewrites them, and one whose CLI was removed some other way takes itself away the next time it runs. + +## Leave the user's config alone + +`~/.config/mise/config.toml` is the user's. Omarchy writes to it only when the user asks for a runtime from _Install > Development_, and a migration may hand a tool Omarchy no longer ships to it, so the tool keeps working as the user's own. diff --git a/agents/skills/motion.md b/agents/skills/motion.md new file mode 100644 index 000000000000..9b4f4ab7fc31 --- /dev/null +++ b/agents/skills/motion.md @@ -0,0 +1,43 @@ +# Motion + +Read this before adding or changing any animation in `shell/`: a panel, popup, notification, button, list or anything else that moves, fades or resizes. The rules are adapted from Emil Kowalski's animation skills (https://github.com/emilkowalski/skills) to Qt Quick and to choices Omarchy has made; where the two differ, follow this file. + +Every animation needs a reason: it shows where something came from or went, it confirms an input, or it keeps a change from jumping. "It looks nice" on something seen many times a day is not a reason. Verify every motion change frame by frame as described in [`visual-verification.md`](visual-verification.md). + +## Should it animate + +- Things opened many times a day by a single keystroke and gone in a moment don't animate: the menu, launcher, clipboard and emoji pickers have no open or close motion, and the volume/brightness OSD appears and disappears at once. +- A keystroke that acts and is done jumps: dismissing the newest notification, dismissing all, invoking the newest. They pass `instant` through `closeToasts()` in `shell/plugins/notifications/Service.qml`. +- Inside something the user stays and watches, keys get the same motion as the pointer: panels opened or closed by hotkey grow and fade like a click, and notification keyboard mode closes the selected card with its normal exit. There the motion shows where things went. +- Hover effects seen constantly stay small and quick, or don't animate. + +## Tokens + +- Every duration goes through `Style.duration(ms)`. It returns 0 when `omarchy toggle animations` has turned Hyprland's animations off, which is how the shell honours reduced motion. A bare `duration: 150` keeps animating after that, so don't write one; `test/shell.d/motion-test.sh` fails on it. A looping animation also needs `running: ... && !Style.reduceMotion`, or its zero-length steps spin the CPU. +- Movement and entrances use `Style.easeOut`, a strong ease-out (`cubic-bezier(0.23, 1, 0.32, 1)`) passed as `easing.type: Easing.Bezier; easing.bezierCurve: Style.easeOut`. Plain fades may use `Easing.OutCubic`, and hover colour changes `Easing.InOutQuad`. +- Never an ease-in curve on UI: it starts slowest at the moment the eye is on it. No overshoot or bounce. +- Never `Easing.Linear` except for constant motion such as a spinner. + +## Durations + +- UI motion stays under 300ms. Entrances take 180–250ms. +- Whatever leaves goes faster than it came, about two thirds of the time: panels open in 180ms and close in 120ms, notifications arrive in 250ms and leave in 200ms. +- Text fading out under something fading in takes half the time of the fade in, or the two texts show at once. +- Press feedback is 160ms. + +## Patterns already in the shell + +Build on these rather than writing a new open/close animation: + +- `shell/Ui/KeyboardPanel.qml` - panels grow from 0.97 out of the point on their bar-facing edge nearest the icon they hang from (`growOrigin`), and fade. Switching between two panels in the same bar section morphs one card from the old place and size to the new (`morphFromLastCard`, `bar.popoutCardFor()`); across sections the old card fades and the new one grows in fresh. Content that arrives after opening, like a Wi-Fi scan, grows the card through `drawnHeight` and the card crops the new rows meanwhile. +- `shell/Ui/PopupCard.qml` - the same grow and fade for tray and media popups. +- `shell/Ui/Button.qml` - a button held down scales to 0.97. The `MouseArea` takes `1 / root.scale`, so only the drawing shrinks and a press near the edge still clicks. +- `shell/plugins/notifications/Service.qml` - one scene clock for the whole deck. A change snapshots where every card is now and retargets from there, so a move interrupted by another never jumps. A Behavior per card would restart from scratch on every retarget. + +## Pitfalls + +- Never scale from 0. Start at 0.95–0.97 with opacity 0. +- Scaling an item scales its `MouseArea` too; undo it on the hit area, as `Button` does. +- Animating height while content lays out to that height reflows every frame. Size the content to its final height and crop it with `clip` while the frame catches up. +- A `Behavior` that must not run for one particular change (a morph, a keyboard jump) needs its `enabled` condition true before the value changes. A flag set in `onOpenChanged` can be too late, because bindings may update first; use a binding that is already true, like `KeyboardPanel.takingOver`. +- A whole-shell flag that zeroes `Style.duration()` cuts short unrelated animations already running. Keep instant paths local, like `closeToasts(..., instant)`. diff --git a/agents/skills/oligarchy-tests.md b/agents/skills/oligarchy-tests.md new file mode 100644 index 000000000000..a6881b35ed1d --- /dev/null +++ b/agents/skills/oligarchy-tests.md @@ -0,0 +1,2 @@ +## Oligarchy Tests +* Do not write new oligarchy tests as this is still experimental diff --git a/agents/skills/shell-dev.md b/agents/skills/shell-dev.md index 9cec524cea6d..2207b7ea3df7 100644 --- a/agents/skills/shell-dev.md +++ b/agents/skills/shell-dev.md @@ -3,9 +3,10 @@ Read this before editing the Quickshell desktop under `shell/`. The Quickshell desktop runs as a single long-running process out of -`shell/`. Hyprland autostart launches it directly with `quickshell -n -p`; -do not start additional standalone Quickshell instances for individual -components. +`shell/`. Hyprland autostart launches `bin/omarchy-launch-shell`, which runs +`quickshell -n -p` under `systemd-cat` (journal logging), a respawn loop, and +reload-suppressing env vars; do not start additional standalone Quickshell +instances for individual components. Run `omarchy-restart-shell` after making changes to QML files. @@ -31,7 +32,7 @@ Run `omarchy-restart-shell` after making changes to QML files. the running shell and does not start it. Prefer it over re-implementing direct Quickshell socket calls in every CLI. - The `shell` IPC target exposes lifecycle and configuration methods including - `ping`, `summon`, `hide`, `toggle`, `call`, `rescanPlugins`, `reloadConfig`, + `ping`, `summon`, `hide`, `toggle`, `call`, `rescanPlugins`, `reloadPlugins`, `reloadConfig`, `setPluginEnabled`, and `listPlugins`. `shell.qml` also registers `image-selector`, which drives the `omarchy.image-picker` panel. - Individual plugins register their own IPC targets, named for the plugin rather @@ -43,7 +44,7 @@ Run `omarchy-restart-shell` after making changes to QML files. The shell runs all day on battery, and a widget is built once per monitor, so a `Timer` that starts a `Process` costs that process times the number of monitors, every tick, forever. Don't poll for state that only changes through known events. Pick the first of these that fits: -- A native Quickshell service that signals on change: `UPower` and `PowerProfiles` (`Quickshell.Services.UPower`), `Hyprland` and each workspace's `lastIpcObject`, `Pipewire`, `Mpris`, `SystemTray`, `Notifications`. +- A native Quickshell service that signals on change: `UPower` and `PowerProfiles` (`Quickshell.Services.UPower`), `Hyprland` and each workspace's `lastIpcObject`, `Pipewire`, `Mpris`, `SystemTray`, `Notifications`, and `Networking` (`Quickshell.Networking`), whose `connectivity` turning `NetworkConnectivity.Full` is the cue to refetch anything that needs the internet. - An event stream the shell already runs, such as the Hyprland IPC events or the long-running `pactl subscribe` in `Commons/UntypedInput.qml`. Extend it rather than starting a second one. - A file watch: `FileView` with `watchChanges`, or the directory watch in `plugins/bar/Bar.qml`, when the state lives in a file the user can read. - A push from the command that changes the state. If only Omarchy commands change it, have them call `omarchy-shell -q refresh` after the change, the way `omarchy-reminder` and `omarchy-sudo-passwordless` do. When the change happens later, without a command running (an expiry, say), schedule the refresh with a transient `systemd-run --user --on-active=…` timer. A root-owned timer cannot reach the user's shell. diff --git a/agents/skills/visual-verification.md b/agents/skills/visual-verification.md index a8ed63d7ae26..de46fff0f664 100644 --- a/agents/skills/visual-verification.md +++ b/agents/skills/visual-verification.md @@ -15,7 +15,7 @@ Take a full-screen screenshot without opening the editor: omarchy capture screenshot fullscreen save ``` -The command writes to Omasnap's configured screenshot directory. Use `omarchy screenshot` for the interactive capture flow, which copies the capture and shows a timed preview. Use `omarchy screenshot --editor=overlay` to test annotation before output. Capture reference and candidate states as separate images when changing a layer-shell surface or layout, then compare both. +The command writes to Omasnap's configured screenshot directory. Use `omarchy screenshot` for the interactive capture flow, which saves and copies the capture and shows its notification. Use `omarchy screenshot --editor=overlay` to test annotation before output. Capture reference and candidate states as separate images when changing a layer-shell surface or layout, then compare both. Record a short full-screen video for animation, transition, timing, capture, or screen-recording changes: @@ -30,6 +30,44 @@ The stop command prints the saved video path in the configured Videos directory. Review the recording before finishing, and keep it short and focused on the changed behavior. +The pull request carries the evidence: put the before/after screenshots, and the recording when motion is involved, in the Screenshots section of `.github/pull_request_template.md`. `gh pr create --body` skips the template, so add that section yourself. The `Check visual evidence` workflow flags PRs touching the shell, configs, themes, or package lists that have neither captures nor a `No visible change: ` line. Upload captures to the PR; never commit them. + +## Checking motion frame by frame + +Motion goes wrong in a frame or two, too fast to see at full speed: two texts showing at once in a crossfade, a blank frame between two panels, a card that jumps instead of morphing, a panel growing from the wrong point. Record the change and read it a frame at a time. Follow [`motion.md`](motion.md) for what the motion should be. + +Run the branch's shell, not the installed one. The running shell loads plugins from `$OMARCHY_PATH`, and its launcher relaunches it if killed, so stop it and start the worktree's through Hyprland. This takes over the desktop, so tell whoever is at it first with `omarchy-notification-send` and wait a few seconds. + +Put their shell back with `omarchy-restart-shell` as soon as the check is done, before you turn to anything else, and never end a turn with the worktree's shell running. While it runs, `omarchy-shell` cannot reach the desktop, so theme switches and updates fail without a word, and the user cannot tell why. `omarchy-restart-shell` stops every Omarchy shell, the worktree's included, and starts the session's own. A check usually spans several tool calls, so a `trap` in one of them does not cover it; relaunching between edits is fine, but the restore is yours to run. + +```bash +WT=/path/to/worktree +while timeout 30 quickshell kill -p "$OMARCHY_PATH/shell" --any-display >/dev/null 2>&1; do :; done +hyprctl dispatch "hl.dsp.exec_cmd(\"env OMARCHY_PATH=$WT omarchy-launch-shell\")" +# A starting shell answers one ping and then drops calls while plugins load: +# wait for several answers in a row, a second apart. +OMARCHY_PATH=$WT omarchy-shell shell ping +# ... record ... +omarchy-restart-shell +``` + +Drive it without touching the mouse: + +- A panel's own IPC target (`omarchy-shell omarchy.network open`) takes the same path as a click on its icon. `omarchy-shell shell toggle omarchy.network` takes the keybinding's path. +- `omarchy-notification-send` raises notifications, and `omarchy-shell notifications dismiss ` closes one the way a click does. Requested timeouts are raised to at least 8 seconds, so don't wait on a short `-t` to see an expiry. +- `hyprctl eval "hl.dispatch(hl.dsp.cursor.move({ x = 2810, y = 70 }))"` moves the pointer for hover. +- A panel builds its content and maps its window on its first open, which can swallow the first frames of its motion. Open and close each panel once before recording unless the first open is what's being checked. + +Then lay the frames out side by side. Crop to where the change happens and tile every frame of the moment, at the recording's full 60fps: + +```bash +ffmpeg -ss 4.35 -t 0.4 -i recording.mp4 -vf "crop=2440:700:1400:0,scale=488:-1,tile=4x6" -frames:v 1 frames.png +``` + +Find the moment with a coarse sheet first (`fps=6` before the crop), then tile it at full rate and read every frame: where the motion starts from, whether anything doubles up or blanks, and where it settles. + +From outside the session (an agent's shell, SSH), export `HYPRLAND_INSTANCE_SIGNATURE` and `WAYLAND_DISPLAY`. Without them `hyprctl` refuses and the recorder exits silently with nothing saved; `OMARCHY_SCREENRECORD_DEBUG=true` logs why to `$XDG_RUNTIME_DIR/omarchy-screenrecord.log`. + For interactive UI work, use `wtype` to simulate keyboard input when available. Example: start the UI in the background, wait briefly for focus, then run `wtype -k Right -k Return` to exercise keyboard selection and confirm the diff --git a/applications/Activity Monitor.desktop b/applications/Activity Monitor.desktop new file mode 100644 index 000000000000..17e03f64b2fb --- /dev/null +++ b/applications/Activity Monitor.desktop @@ -0,0 +1,10 @@ +[Desktop Entry] +Version=1.0 +Name=Activity Monitor +Comment=See what's using the CPU, memory, disk and network +Exec=omarchy-launch-tui btop +Icon=btop +Terminal=false +Type=Application +Categories=System;Monitor; +StartupWMClass=org.omarchy.btop diff --git a/applications/Amap.desktop b/applications/Amap.desktop new file mode 100644 index 000000000000..00f3edc4cbb1 --- /dev/null +++ b/applications/Amap.desktop @@ -0,0 +1,9 @@ +[Desktop Entry] +Version=1.0 +Name=Amap +Exec=omarchy-launch-webapp https://www.amap.com/ +StartupWMClass=chrome-www.amap.com__-Default +Terminal=false +Type=Application +Icon=amap +StartupNotify=true diff --git a/applications/Bilibili.desktop b/applications/Bilibili.desktop new file mode 100644 index 000000000000..8e53bd448d24 --- /dev/null +++ b/applications/Bilibili.desktop @@ -0,0 +1,9 @@ +[Desktop Entry] +Version=1.0 +Name=Bilibili +Exec=omarchy-launch-webapp https://www.bilibili.com/ +StartupWMClass=chrome-www.bilibili.com__-Default +Terminal=false +Type=Application +Icon=bilibili +StartupNotify=true diff --git a/applications/ChatGPT.desktop b/applications/ChatGPT.desktop new file mode 100644 index 000000000000..230fa89a280e --- /dev/null +++ b/applications/ChatGPT.desktop @@ -0,0 +1,9 @@ +[Desktop Entry] +Version=1.0 +Name=ChatGPT +Exec=omarchy-launch-webapp https://chatgpt.com +StartupWMClass=chrome-chatgpt.com__-Default +Terminal=false +Type=Application +Icon=chatgpt +StartupNotify=true diff --git a/applications/DeepSeek.desktop b/applications/DeepSeek.desktop new file mode 100644 index 000000000000..f29a93422eb4 --- /dev/null +++ b/applications/DeepSeek.desktop @@ -0,0 +1,9 @@ +[Desktop Entry] +Version=1.0 +Name=DeepSeek +Exec=omarchy-launch-webapp https://chat.deepseek.com/ +StartupWMClass=chrome-chat.deepseek.com__-Default +Terminal=false +Type=Application +Icon=omarchy-agent-dsh +StartupNotify=true diff --git a/applications/Game Vibes.desktop b/applications/Game Vibes.desktop new file mode 100644 index 000000000000..7b65edc80694 --- /dev/null +++ b/applications/Game Vibes.desktop @@ -0,0 +1,10 @@ +[Desktop Entry] +Version=1.0 +Type=Application +Name=Game Vibes +Comment=Little games to play, and to keep making with an agent +Exec=omarchy-games-vibes-launch +Icon=omarchy-game-vibes +Categories=Game; +Terminal=false +StartupNotify=true diff --git a/applications/Herdr.desktop b/applications/Herdr.desktop new file mode 100644 index 000000000000..f6058dca1841 --- /dev/null +++ b/applications/Herdr.desktop @@ -0,0 +1,10 @@ +[Desktop Entry] +Version=1.0 +Name=Herdr +Comment=Open or reattach to your persistent terminal workspace +Exec=omarchy-launch-terminal-herdr +Icon=herdr +Terminal=false +Type=Application +StartupWMClass=org.omarchy.herdr +Categories=System; diff --git a/applications/Netflix.desktop b/applications/Netflix.desktop new file mode 100644 index 000000000000..c2cd24e0b301 --- /dev/null +++ b/applications/Netflix.desktop @@ -0,0 +1,9 @@ +[Desktop Entry] +Version=1.0 +Name=Netflix +Exec=omarchy-launch-webapp https://www.netflix.com/ +StartupWMClass=chrome-www.netflix.com__-Default +Terminal=false +Type=Application +Icon=netflix +StartupNotify=true diff --git a/applications/Qwen.desktop b/applications/Qwen.desktop new file mode 100644 index 000000000000..c74e92ffc9e1 --- /dev/null +++ b/applications/Qwen.desktop @@ -0,0 +1,9 @@ +[Desktop Entry] +Version=1.0 +Name=Qwen +Exec=omarchy-launch-webapp https://www.qianwen.com/ +StartupWMClass=chrome-www.qianwen.com__-Default +Terminal=false +Type=Application +Icon=omarchy-agent-qwen +StartupNotify=true diff --git a/applications/Spotify.desktop b/applications/Spotify.desktop new file mode 100644 index 000000000000..cee65a26d4ac --- /dev/null +++ b/applications/Spotify.desktop @@ -0,0 +1,9 @@ +[Desktop Entry] +Version=1.0 +Name=Spotify +Exec=omarchy-launch-webapp https://open.spotify.com/ +StartupWMClass=chrome-open.spotify.com__-Default +Terminal=false +Type=Application +Icon=omarchy-spotify +StartupNotify=true diff --git a/applications/Weibo.desktop b/applications/Weibo.desktop new file mode 100644 index 000000000000..a6244ea51a8f --- /dev/null +++ b/applications/Weibo.desktop @@ -0,0 +1,9 @@ +[Desktop Entry] +Version=1.0 +Name=Weibo +Exec=omarchy-launch-webapp https://weibo.com/ +StartupWMClass=chrome-weibo.com__-Default +Terminal=false +Type=Application +Icon=weibo +StartupNotify=true diff --git a/applications/icons/Amap.png b/applications/icons/Amap.png new file mode 100644 index 000000000000..3f367c5af6f1 Binary files /dev/null and b/applications/icons/Amap.png differ diff --git a/applications/icons/Bilibili.png b/applications/icons/Bilibili.png new file mode 100644 index 000000000000..845933f15803 Binary files /dev/null and b/applications/icons/Bilibili.png differ diff --git a/applications/icons/Netflix.png b/applications/icons/Netflix.png new file mode 100644 index 000000000000..16e67be309d6 Binary files /dev/null and b/applications/icons/Netflix.png differ diff --git a/applications/icons/Weibo.png b/applications/icons/Weibo.png new file mode 100644 index 000000000000..8f9ba35a65ef Binary files /dev/null and b/applications/icons/Weibo.png differ diff --git a/applications/icons/imv.png b/applications/icons/imv.png deleted file mode 100644 index f9cac3582941..000000000000 Binary files a/applications/icons/imv.png and /dev/null differ diff --git a/applications/icons/omarchy-agent-agy.png b/applications/icons/omarchy-agent-agy.png new file mode 100644 index 000000000000..ad15c8ecb49d Binary files /dev/null and b/applications/icons/omarchy-agent-agy.png differ diff --git a/applications/icons/omarchy-agent-amp.png b/applications/icons/omarchy-agent-amp.png new file mode 100644 index 000000000000..f0454992b56b Binary files /dev/null and b/applications/icons/omarchy-agent-amp.png differ diff --git a/applications/icons/omarchy-agent-claude.png b/applications/icons/omarchy-agent-claude.png new file mode 100644 index 000000000000..1a9b958696d1 Binary files /dev/null and b/applications/icons/omarchy-agent-claude.png differ diff --git a/applications/icons/omarchy-agent-codex.png b/applications/icons/omarchy-agent-codex.png new file mode 100644 index 000000000000..4aa558e23fde Binary files /dev/null and b/applications/icons/omarchy-agent-codex.png differ diff --git a/applications/icons/omarchy-agent-commandcode.png b/applications/icons/omarchy-agent-commandcode.png new file mode 100644 index 000000000000..ab80a10727a5 Binary files /dev/null and b/applications/icons/omarchy-agent-commandcode.png differ diff --git a/applications/icons/omarchy-agent-copilot.png b/applications/icons/omarchy-agent-copilot.png new file mode 100644 index 000000000000..688dcf0e4956 Binary files /dev/null and b/applications/icons/omarchy-agent-copilot.png differ diff --git a/applications/icons/omarchy-agent-crush.png b/applications/icons/omarchy-agent-crush.png new file mode 100644 index 000000000000..cd4f2e2faff6 Binary files /dev/null and b/applications/icons/omarchy-agent-crush.png differ diff --git a/applications/icons/omarchy-agent-cursor-agent.png b/applications/icons/omarchy-agent-cursor-agent.png new file mode 100644 index 000000000000..e2244c300d4e Binary files /dev/null and b/applications/icons/omarchy-agent-cursor-agent.png differ diff --git a/applications/icons/omarchy-agent-devin.png b/applications/icons/omarchy-agent-devin.png new file mode 100644 index 000000000000..0049dc12d6b6 Binary files /dev/null and b/applications/icons/omarchy-agent-devin.png differ diff --git a/applications/icons/omarchy-agent-dsh.png b/applications/icons/omarchy-agent-dsh.png new file mode 100644 index 000000000000..f9533df357f4 Binary files /dev/null and b/applications/icons/omarchy-agent-dsh.png differ diff --git a/applications/icons/omarchy-agent-freebuff.png b/applications/icons/omarchy-agent-freebuff.png new file mode 100644 index 000000000000..2351fa5e58d2 Binary files /dev/null and b/applications/icons/omarchy-agent-freebuff.png differ diff --git a/applications/icons/omarchy-agent-grok.png b/applications/icons/omarchy-agent-grok.png new file mode 100644 index 000000000000..cfdf5e1d1caf Binary files /dev/null and b/applications/icons/omarchy-agent-grok.png differ diff --git a/applications/icons/omarchy-agent-kilo.png b/applications/icons/omarchy-agent-kilo.png new file mode 100644 index 000000000000..84ca473bb261 Binary files /dev/null and b/applications/icons/omarchy-agent-kilo.png differ diff --git a/applications/icons/omarchy-agent-kimi.png b/applications/icons/omarchy-agent-kimi.png new file mode 100644 index 000000000000..c3ffc18fc5fb Binary files /dev/null and b/applications/icons/omarchy-agent-kimi.png differ diff --git a/applications/icons/omarchy-agent-kiro-cli.png b/applications/icons/omarchy-agent-kiro-cli.png new file mode 100644 index 000000000000..38887353d3fe Binary files /dev/null and b/applications/icons/omarchy-agent-kiro-cli.png differ diff --git a/applications/icons/omarchy-agent-mcode.png b/applications/icons/omarchy-agent-mcode.png new file mode 100644 index 000000000000..dda93b349f62 Binary files /dev/null and b/applications/icons/omarchy-agent-mcode.png differ diff --git a/applications/icons/omarchy-agent-muse.png b/applications/icons/omarchy-agent-muse.png new file mode 100644 index 000000000000..4e5d2daf80bd Binary files /dev/null and b/applications/icons/omarchy-agent-muse.png differ diff --git a/applications/icons/omarchy-agent-omp.png b/applications/icons/omarchy-agent-omp.png new file mode 100644 index 000000000000..3d9e87229498 Binary files /dev/null and b/applications/icons/omarchy-agent-omp.png differ diff --git a/applications/icons/omarchy-agent-opencode.png b/applications/icons/omarchy-agent-opencode.png new file mode 100644 index 000000000000..6f368918b343 Binary files /dev/null and b/applications/icons/omarchy-agent-opencode.png differ diff --git a/applications/icons/omarchy-agent-ori.png b/applications/icons/omarchy-agent-ori.png new file mode 100644 index 000000000000..fe45a4d10a3b Binary files /dev/null and b/applications/icons/omarchy-agent-ori.png differ diff --git a/applications/icons/omarchy-agent-pi.png b/applications/icons/omarchy-agent-pi.png new file mode 100644 index 000000000000..3d9f79f44788 Binary files /dev/null and b/applications/icons/omarchy-agent-pi.png differ diff --git a/applications/icons/omarchy-agent-qwen.png b/applications/icons/omarchy-agent-qwen.png new file mode 100644 index 000000000000..d5dcd2146562 Binary files /dev/null and b/applications/icons/omarchy-agent-qwen.png differ diff --git a/applications/icons/omarchy-agent.png b/applications/icons/omarchy-agent.png new file mode 100644 index 000000000000..39f9a4280e16 Binary files /dev/null and b/applications/icons/omarchy-agent.png differ diff --git a/applications/icons/omarchy-game-vibes.png b/applications/icons/omarchy-game-vibes.png new file mode 100644 index 000000000000..bb365cbff61f Binary files /dev/null and b/applications/icons/omarchy-game-vibes.png differ diff --git a/applications/icons/omarchy-spotify.png b/applications/icons/omarchy-spotify.png new file mode 100644 index 000000000000..c24e18365965 Binary files /dev/null and b/applications/icons/omarchy-spotify.png differ diff --git a/applications/imv.desktop b/applications/imv.desktop deleted file mode 100644 index 293afc8fbbe0..000000000000 --- a/applications/imv.desktop +++ /dev/null @@ -1,8 +0,0 @@ -[Desktop Entry] -Name=Image Viewer -Exec=imv %F -Icon=imv -Type=Application -MimeType=image/png;image/jpeg;image/jpg;image/gif;image/bmp;image/webp;image/tiff;image/x-xcf;image/x-portable-pixmap;image/x-xbitmap; -Terminal=false -Categories=Graphics;Viewer; diff --git a/applications/mpv.desktop b/applications/mpv.desktop deleted file mode 100644 index 776e2c9e665d..000000000000 --- a/applications/mpv.desktop +++ /dev/null @@ -1,51 +0,0 @@ -[Desktop Entry] -Type=Application -Name=Media Player -Name[ar]=مشغل وسائط mpv -Name[ca]=Reproductor multimèdia mpv -Name[cs]=mpv přehrávač -Name[da]=mpv-medieafspiller -Name[fr]=Lecteur multimédia mpv -Name[it]=Lettore multimediale mpv -Name[ja]=mpv メディアプレイヤー -Name[pl]=Odtwarzacz mpv -Name[ru]=Проигрыватель mpv -Name[tr]=mpv Ortam Oynatıcı -Name[zh_CN]=mpv 媒体播放器 -Name[zh_TW]=mpv 媒體播放器 -GenericName=Multimedia player -GenericName[ar]=مُشَغِّل وسائط متعددة -GenericName[cs]=Multimediální přehrávač -GenericName[da]=Multimedieafspiller -GenericName[fr]=Lecteur multimédia -GenericName[it]=Lettore multimediale -GenericName[ja]=マルチメディアプレイヤー -GenericName[ru]=Мультимедийный проигрыватель -GenericName[tr]=Çoklu ortam oynatıcı -GenericName[zh_CN]=多媒体播放器 -GenericName[zh_TW]=多媒體播放器 -Comment=Play movies and songs -Comment[ar]=شَغِّل الأفلام والأغاني -Comment[ca]=Reproduïu vídeos i cançons -Comment[cs]=Přehrává filmy a hudbu -Comment[da]=Afspil film og sange -Comment[de]=Filme und Musik abspielen -Comment[es]=Reproduzca vídeos y canciones -Comment[fr]=Lire des vidéos et des musiques -Comment[ja]=映画や音楽を再生する -Comment[it]=Riproduci video e canzoni -Comment[pl]=Odtwarzaj filmy i muzykę -Comment[ru]=Воспроизведение фильмов и музыки -Comment[tr]=Filmleri ve şarkıları oynatın -Comment[zh_CN]=播放电影和歌曲 -Comment[zh_TW]=播放電影和歌曲 -Icon=mpv -TryExec=mpv -Exec=mpv --player-operation-mode=pseudo-gui -- %U -Terminal=false -Categories=AudioVideo;Audio;Video;Player;TV; -MimeType=application/ogg;application/x-ogg;application/mxf;application/sdp;application/smil;application/x-smil;application/streamingmedia;application/x-streamingmedia;application/vnd.rn-realmedia;application/vnd.rn-realmedia-vbr;audio/aac;audio/x-aac;audio/vnd.dolby.heaac.1;audio/vnd.dolby.heaac.2;audio/aiff;audio/x-aiff;audio/m4a;audio/x-m4a;application/x-extension-m4a;audio/mp1;audio/x-mp1;audio/mp2;audio/x-mp2;audio/mp3;audio/x-mp3;audio/mpeg;audio/mpeg2;audio/mpeg3;audio/mpegurl;audio/x-mpegurl;audio/mpg;audio/x-mpg;audio/rn-mpeg;audio/musepack;audio/x-musepack;audio/ogg;audio/scpls;audio/x-scpls;audio/vnd.rn-realaudio;audio/wav;audio/x-pn-wav;audio/x-pn-windows-pcm;audio/x-realaudio;audio/x-pn-realaudio;audio/x-ms-wma;audio/x-pls;audio/x-wav;video/mpeg;video/x-mpeg2;video/x-mpeg3;video/mp4v-es;video/x-m4v;video/mp4;application/x-extension-mp4;video/divx;video/vnd.divx;video/msvideo;video/x-msvideo;video/ogg;video/quicktime;video/vnd.rn-realvideo;video/x-ms-afs;video/x-ms-asf;audio/x-ms-asf;application/vnd.ms-asf;video/x-ms-wmv;video/x-ms-wmx;video/x-ms-wvxvideo;video/x-avi;video/avi;video/x-flic;video/fli;video/x-flc;video/flv;video/x-flv;video/x-theora;video/x-theora+ogg;video/x-matroska;video/mkv;audio/x-matroska;application/x-matroska;video/webm;audio/webm;audio/vorbis;audio/x-vorbis;audio/x-vorbis+ogg;video/x-ogm;video/x-ogm+ogg;application/x-ogm;application/x-ogm-audio;application/x-ogm-video;application/x-shorten;audio/x-shorten;audio/x-ape;audio/x-wavpack;audio/x-tta;audio/AMR;audio/ac3;audio/eac3;audio/amr-wb;video/mp2t;audio/flac;audio/mp4;application/x-mpegurl;video/vnd.mpegurl;application/vnd.apple.mpegurl;audio/x-pn-au;video/3gp;video/3gpp;video/3gpp2;audio/3gpp;audio/3gpp2;video/dv;audio/dv;audio/opus;audio/vnd.dts;audio/vnd.dts.hd;audio/x-adpcm;application/x-cue;audio/m3u;audio/vnd.wave;video/vnd.avi; -X-KDE-Protocols=appending,file,ftp,hls,http,https,mms,mpv,rtmp,rtmps,rtmpt,rtmpts,rtp,rtsp,rtsps,sftp,srt,srtp,webdav,webdavs -StartupWMClass=mpv -Keywords=mpv;media;player;video;audio;tv; -Keywords[ar]=mpv;إم بي في;ام بي في;وسائط;مشغل;فيديو;مرئية;صوتي;تلفاز; diff --git a/applications/omarchy-agent.desktop b/applications/omarchy-agent.desktop new file mode 100644 index 000000000000..12104acb6ca9 --- /dev/null +++ b/applications/omarchy-agent.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Version=1.0 +Name=Agent +Comment=Start a coding agent in a terminal +Exec=omarchy-agent --pick +Icon=omarchy-agent +StartupWMClass=org.omarchy.agent +Terminal=false +Type=Application +Categories=Development; +X-Omarchy-Dock-Click=new diff --git a/applications/omarchy-browser.desktop b/applications/omarchy-browser.desktop index 086bdd4059bc..99265fb1cf16 100644 --- a/applications/omarchy-browser.desktop +++ b/applications/omarchy-browser.desktop @@ -1,9 +1,10 @@ [Desktop Entry] Version=1.0 Name=Browser -Comment=Open links in the running default browser and focus it +Comment=Open the default browser Exec=omarchy-launch-browser %U +Icon=omarchy-browser Terminal=false Type=Application -NoDisplay=true +Categories=Network;WebBrowser; MimeType=x-scheme-handler/http;x-scheme-handler/https; diff --git a/applications/omarchy-launch-editor.desktop b/applications/omarchy-launch-editor.desktop new file mode 100644 index 000000000000..2ada60d3b7ce --- /dev/null +++ b/applications/omarchy-launch-editor.desktop @@ -0,0 +1,10 @@ +[Desktop Entry] +Name=Editor +Comment=Open files in the Omarchy default editor +Exec=omarchy-launch-editor %f +Icon=text-editor +Type=Application +MimeType=text/plain;text/english;text/x-makefile;text/x-c++hdr;text/x-c++src;text/x-chdr;text/x-csrc;text/x-java;text/x-moc;text/x-pascal;text/x-tcl;text/x-tex;application/x-shellscript;text/x-c;text/x-c++;application/xml;text/xml;text/x-lua;text/css;text/x-shellscript;application/json;application/toml;application/x-yaml;application/yaml;text/x-ini;application/x-desktop;text/x-systemd-unit; +Terminal=false +Categories=Utility;TextEditor; +NoDisplay=true diff --git a/applications/omarchy-terminal.desktop b/applications/omarchy-terminal.desktop new file mode 100644 index 000000000000..5fd2b17d63de --- /dev/null +++ b/applications/omarchy-terminal.desktop @@ -0,0 +1,10 @@ +[Desktop Entry] +Version=1.0 +Name=Terminal +Comment=Open the default terminal +Exec=omarchy-launch-terminal +Icon=omarchy-terminal +Terminal=false +Type=Application +Categories=System; +X-Omarchy-Dock-Click=new diff --git a/bin/omarchy b/bin/omarchy index f7a0156c816d..d2d024d75ad3 100755 --- a/bin/omarchy +++ b/bin/omarchy @@ -15,6 +15,7 @@ declare -A COMMAND_NAME declare -A COMMAND_SUMMARY declare -A COMMAND_USAGE declare -A COMMAND_ARGS +declare -A COMMAND_SUBCOMMANDS declare -A COMMAND_EXAMPLES declare -A COMMAND_REQUIRES_SUDO declare -A COMMAND_HIDDEN @@ -32,6 +33,7 @@ GROUP_DESCRIPTIONS[audio]="Audio input and output controls" GROUP_DESCRIPTIONS[bar]="Omarchy shell bar layout and settings" GROUP_DESCRIPTIONS[battery]="Battery status helpers" GROUP_DESCRIPTIONS[bluetooth]="Bluetooth device controls" +GROUP_DESCRIPTIONS[boot]="Boot loader, boot images and snapshot boot entries" GROUP_DESCRIPTIONS[branch]="Omarchy git branch management" GROUP_DESCRIPTIONS[branding]="About and screensaver branding" GROUP_DESCRIPTIONS[brightness]="Display and keyboard brightness" @@ -41,10 +43,10 @@ GROUP_DESCRIPTIONS[clipboard]="Clipboard helpers" GROUP_DESCRIPTIONS[cmd]="Command and shortcut helpers" GROUP_DESCRIPTIONS[config]="System configuration helpers" GROUP_DESCRIPTIONS[crash]="Crash notification controls" -GROUP_DESCRIPTIONS[debug]="Diagnostics and support logs" GROUP_DESCRIPTIONS[finalize]="Finalize user setup" GROUP_DESCRIPTIONS[default]="Default application selection" GROUP_DESCRIPTIONS[dev]="Omarchy development tools" +GROUP_DESCRIPTIONS[device]="Hardware controls and settings" GROUP_DESCRIPTIONS[disk]="Disk performance helpers" GROUP_DESCRIPTIONS[dictation]="Dictation recording" GROUP_DESCRIPTIONS[display]="Display and text scaling" @@ -56,17 +58,20 @@ GROUP_DESCRIPTIONS[font]="Font management" GROUP_DESCRIPTIONS[games]="Game launchers and helpers" GROUP_DESCRIPTIONS[hibernation]="Hibernation setup and removal" GROUP_DESCRIPTIONS[hook]="User hook runner" -GROUP_DESCRIPTIONS[hw]="Hardware detection and controls" +GROUP_DESCRIPTIONS[hw]="Hardware detection" GROUP_DESCRIPTIONS[hyprland]="Hyprland window, monitor, and toggle controls" +GROUP_DESCRIPTIONS[icons]="App icon set management" GROUP_DESCRIPTIONS[install]="Optional software installers" GROUP_DESCRIPTIONS[installed]="Installed optional service checks" GROUP_DESCRIPTIONS[launch]="Application launchers" +GROUP_DESCRIPTIONS[kernel]="Default boot kernel selection" GROUP_DESCRIPTIONS[language]="Display language and system locale" GROUP_DESCRIPTIONS[menu]="Omarchy menu commands" GROUP_DESCRIPTIONS[migrate]="Migration runner" GROUP_DESCRIPTIONS[monitor]="Monitor status helpers" GROUP_DESCRIPTIONS[network]="Network status helpers" GROUP_DESCRIPTIONS[notification]="Notification helpers" +GROUP_DESCRIPTIONS[models]="Open models running on this machine and the tailnet" GROUP_DESCRIPTIONS[mise]="Mise tool wrappers" GROUP_DESCRIPTIONS[openclaw]="OpenClaw agent platform setup" GROUP_DESCRIPTIONS[osd]="On-screen display status helpers" @@ -76,13 +81,14 @@ GROUP_DESCRIPTIONS[plymouth]="Plymouth boot theme management" GROUP_DESCRIPTIONS[power]="Power supply detection" GROUP_DESCRIPTIONS[powerprofiles]="Power profile management" GROUP_DESCRIPTIONS[refresh]="Reset config to defaults" +GROUP_DESCRIPTIONS[region]="The region this machine was installed for, and how dates, times, numbers and units are written" GROUP_DESCRIPTIONS[reinstall]="Reinstall and reset workflows" GROUP_DESCRIPTIONS[reminder]="Desktop notification reminders" GROUP_DESCRIPTIONS[remove]="Removal workflows" GROUP_DESCRIPTIONS[restart]="Restart Omarchy components" +GROUP_DESCRIPTIONS[rollcall]="Hardware roll call: what answers, what is there but broken, what is absent" GROUP_DESCRIPTIONS[setup]="Interactive setup wizards" GROUP_DESCRIPTIONS[shell]="Omarchy shell IPC helpers" -GROUP_DESCRIPTIONS[screensaver]="Screensaver branding and animation" GROUP_DESCRIPTIONS[snapshot]="System snapshots" GROUP_DESCRIPTIONS[sudo]="Sudo configuration helpers" GROUP_DESCRIPTIONS[system]="System status, reboot, shutdown, logout, and lock" @@ -169,14 +175,106 @@ register_route() { fi } +store_command_metadata() { + local file_binary="$1" + local group="$2" + local name="$3" + local name_seen="$4" + local summary="$5" + local has_summary="$6" + local fallback_summary="$7" + local args="$8" + local subcommands="$9" + local examples="${10}" + local aliases="${11}" + local requires_sudo="${12}" + local hidden="${13}" + local metadata_errors="${14}" + + local stem="${file_binary#omarchy-}" + local fallback_group="$stem" + local fallback_name="" + local fallback_route="omarchy ${stem//-/ }" + + if [[ $stem == *-* ]]; then + fallback_group="${stem%%-*}" + fallback_name="${stem#*-}" + fallback_name="${fallback_name//-/ }" + fi + + [[ -z $group ]] && group="$fallback_group" + [[ $name_seen != "true" ]] && name="$fallback_name" + [[ -z $summary && -n $fallback_summary ]] && summary="$fallback_summary" + [[ -z $summary ]] && summary="Run the ${stem//-/ } command" + local route="omarchy $group" + if [[ -n $name ]]; then + route+=" $name" + fi + + # Subcommands stand in for args, as alternatives: `use | reset | ...` + if [[ -z $args && -n $subcommands ]]; then + local subcommand_args="" + local subcommand_summary="" + while IFS=$'\t' read -r subcommand_args subcommand_summary; do + args+="${args:+ | }$subcommand_args" + done <<<"${subcommands%$'\n'}" + fi + + local usage="$route" + if [[ -n $args ]]; then + usage+=" $args" + fi + + [[ $requires_sudo == "true" ]] || requires_sudo="false" + [[ $hidden == "true" ]] || hidden="false" + + local key="$file_binary" + COMMAND_KEYS+=("$key") + COMMAND_ROUTE["$key"]="$route" + COMMAND_FALLBACK_ROUTE["$key"]="$fallback_route" + COMMAND_BINARY["$key"]="$file_binary" + COMMAND_GROUP["$key"]="$group" + COMMAND_NAME["$key"]="$name" + COMMAND_SUMMARY["$key"]="$summary" + COMMAND_USAGE["$key"]="$usage" + COMMAND_ARGS["$key"]="$args" + COMMAND_SUBCOMMANDS["$key"]="${subcommands%$'\n'}" + COMMAND_EXAMPLES["$key"]="$examples" + COMMAND_REQUIRES_SUDO["$key"]="$requires_sudo" + COMMAND_HIDDEN["$key"]="$hidden" + COMMAND_HAS_SUMMARY["$key"]="$has_summary" + COMMAND_METADATA_ERRORS["$key"]="$metadata_errors" + + BINARY_TO_KEY["$file_binary"]="$key" + register_route "$route" "$key" + register_route "$fallback_route" "$key" + + if [[ -n $aliases ]]; then + local alias_route="" + local alias_routes=() + IFS='|' read -ra alias_routes <<<"$aliases" + for alias_route in "${alias_routes[@]}"; do + alias_route="${alias_route# }" + alias_route="${alias_route% }" + [[ -z $alias_route || $alias_route == "$route" ]] && continue + register_route "$alias_route" "$key" true + if [[ -z ${COMMAND_ALIASES[$key]:-} ]]; then + COMMAND_ALIASES["$key"]="$alias_route" + else + COMMAND_ALIASES["$key"]="${COMMAND_ALIASES[$key]}|$alias_route" + fi + done + fi +} + register_command() { local file="$1" local file_binary="${file##*/}" local group="" local name="" local summary="" - local usage="" local args="" + local subcommands="" local examples="" local aliases="" local requires_sudo="" @@ -226,6 +324,13 @@ register_command() { args) args="$metadata_value" ;; + subcommand) + if [[ $metadata_value == *" — "* ]]; then + subcommands+="${metadata_value%% — *}"$'\t'"${metadata_value#* — }"$'\n' + else + metadata_errors=$(append_pipe_value "$metadata_errors" "subcommand must be ' — '") + fi + ;; examples) examples="$metadata_value" ;; @@ -254,84 +359,217 @@ register_command() { fi done <"$file" - local stem="${file_binary#omarchy-}" - local fallback_group="$stem" - local fallback_name="" - local fallback_route="omarchy ${stem//-/ }" - - if [[ $stem == *-* ]]; then - fallback_group="${stem%%-*}" - fallback_name="${stem#*-}" - fallback_name="${fallback_name//-/ }" - fi - - [[ -z $group ]] && group="$fallback_group" - [[ $name_seen != "true" ]] && name="$fallback_name" - [[ -z $summary && -n $fallback_summary ]] && summary="$fallback_summary" - [[ -z $summary ]] && summary="Run the ${stem//-/ } command" - local route="omarchy $group" - if [[ -n $name ]]; then - route+=" $name" - fi + store_command_metadata \ + "$file_binary" "$group" "$name" "$name_seen" "$summary" "$has_summary" \ + "$fallback_summary" "$args" "$subcommands" "$examples" "$aliases" \ + "$requires_sudo" "$hidden" "$metadata_errors" +} - usage="$route" - if [[ -n $args ]]; then - usage+=" $args" +# Scan a batch of command headers in one awk pass (~7ms for all ~630 files vs +# ~260ms in pure-Bash read/regex loops). Single-file loads stay in Bash to +# avoid an awk fork. +register_command_files() { + (( $# > 0 )) || return 0 + if (( $# == 1 )); then + register_command "$1" + return 0 fi - [[ $requires_sudo == "true" ]] || requires_sudo="false" - [[ $hidden == "true" ]] || hidden="false" + local key route fallback_route group name summary usage args subcommands_raw + local examples aliases requires_sudo hidden has_summary metadata_errors + local subcommands sub_entry alias_route + local -a alias_routes + + while IFS=$'\x1f' read -r \ + key route fallback_route group name summary usage args subcommands_raw \ + examples aliases requires_sudo hidden has_summary metadata_errors; do + subcommands="" + if [[ -n $subcommands_raw ]]; then + subcommands="${subcommands_raw//$'\x1d'/$'\t'}" + subcommands="${subcommands//$'\x1e'/$'\n'}" + fi - local key="$file_binary" - COMMAND_KEYS+=("$key") - COMMAND_ROUTE["$key"]="$route" - COMMAND_FALLBACK_ROUTE["$key"]="$fallback_route" - COMMAND_BINARY["$key"]="$file_binary" - COMMAND_GROUP["$key"]="$group" - COMMAND_NAME["$key"]="$name" - COMMAND_SUMMARY["$key"]="$summary" - COMMAND_USAGE["$key"]="$usage" - COMMAND_ARGS["$key"]="$args" - COMMAND_EXAMPLES["$key"]="$examples" - COMMAND_REQUIRES_SUDO["$key"]="$requires_sudo" - COMMAND_HIDDEN["$key"]="$hidden" - COMMAND_HAS_SUMMARY["$key"]="$has_summary" - COMMAND_METADATA_ERRORS["$key"]="$metadata_errors" + COMMAND_KEYS+=("$key") + COMMAND_ROUTE["$key"]="$route" + COMMAND_FALLBACK_ROUTE["$key"]="$fallback_route" + COMMAND_BINARY["$key"]="$key" + COMMAND_GROUP["$key"]="$group" + COMMAND_NAME["$key"]="$name" + COMMAND_SUMMARY["$key"]="$summary" + COMMAND_USAGE["$key"]="$usage" + COMMAND_ARGS["$key"]="$args" + COMMAND_SUBCOMMANDS["$key"]="$subcommands" + COMMAND_EXAMPLES["$key"]="$examples" + COMMAND_REQUIRES_SUDO["$key"]="$requires_sudo" + COMMAND_HIDDEN["$key"]="$hidden" + COMMAND_HAS_SUMMARY["$key"]="$has_summary" + COMMAND_METADATA_ERRORS["$key"]="$metadata_errors" + BINARY_TO_KEY["$key"]="$key" + + if [[ -n ${ROUTE_TO_KEY[$route]:-} && ${ROUTE_TO_KEY[$route]} != "$key" ]]; then + ROUTE_COLLISIONS+=("$route -> ${ROUTE_TO_KEY[$route]} conflicts with $key") + else + ROUTE_TO_KEY["$route"]="$key" + fi - BINARY_TO_KEY["$file_binary"]="$key" - register_route "$route" "$key" - register_route "$fallback_route" "$key" + if [[ $fallback_route != "$route" ]]; then + if [[ -n ${ROUTE_TO_KEY[$fallback_route]:-} && ${ROUTE_TO_KEY[$fallback_route]} != "$key" ]]; then + ROUTE_COLLISIONS+=("$fallback_route -> ${ROUTE_TO_KEY[$fallback_route]} conflicts with $key") + else + ROUTE_TO_KEY["$fallback_route"]="$key" + fi + fi - local old_ifs="$IFS" - local alias_route="" - IFS='|' - for alias_route in $aliases; do - alias_route="${alias_route# }" - alias_route="${alias_route% }" - [[ -z $alias_route || $alias_route == "$route" ]] && continue - register_route "$alias_route" "$key" true - COMMAND_ALIASES["$key"]=$(append_pipe_value "${COMMAND_ALIASES[$key]}" "$alias_route") - done - IFS="$old_ifs" + if [[ -n $aliases ]]; then + IFS='|' read -ra alias_routes <<<"$aliases" + for alias_route in "${alias_routes[@]}"; do + if [[ -n ${ROUTE_TO_KEY[$alias_route]:-} && ${ROUTE_TO_KEY[$alias_route]} != "$key" ]]; then + ROUTE_COLLISIONS+=("$alias_route -> ${ROUTE_TO_KEY[$alias_route]} conflicts with $key") + else + ROUTE_TO_KEY["$alias_route"]="$key" + ROUTE_IS_ALIAS["$alias_route"]="true" + fi + done + COMMAND_ALIASES["$key"]="$aliases" + fi + done < <( + awk -v limit="$METADATA_SCAN_LIMIT" ' + function append_err(msg) { + metadata_errors = (metadata_errors == "" ? msg : metadata_errors "|" msg) + } + function reset_file(path) { + file_binary = path + sub(/^.*\//, "", file_binary) + group = ""; name = ""; name_seen = 0 + summary = ""; has_summary = "false"; fallback_summary = "" + args = ""; subcommands = ""; sub_args_joined = "" + examples = ""; aliases = "" + requires_sudo = ""; hidden = ""; metadata_errors = "" + } + function emit_file( stem, fallback_group, fallback_name, fallback_route, dash, route, usage, n, i, a, clean_aliases, parts) { + stem = file_binary + sub(/^omarchy-/, "", stem) + fallback_group = stem + fallback_name = "" + fallback_route = stem + gsub(/-/, " ", fallback_route) + fallback_route = "omarchy " fallback_route + + dash = index(stem, "-") + if (dash > 0) { + fallback_group = substr(stem, 1, dash - 1) + fallback_name = substr(stem, dash + 1) + gsub(/-/, " ", fallback_name) + } + + if (group == "") group = fallback_group + if (!name_seen) name = fallback_name + if (summary == "" && fallback_summary != "") summary = fallback_summary + if (summary == "") { + summary = stem + gsub(/-/, " ", summary) + summary = "Run the " summary " command" + } + + route = "omarchy " group + if (name != "") route = route " " name + + if (args == "" && sub_args_joined != "") args = sub_args_joined + usage = (args != "" ? route " " args : route) + if (requires_sudo != "true") requires_sudo = "false" + if (hidden != "true") hidden = "false" + + clean_aliases = "" + if (aliases != "") { + n = split(aliases, parts, "|") + for (i = 1; i <= n; i++) { + a = parts[i] + sub(/^ /, "", a) + sub(/ $/, "", a) + if (a == "" || a == route) continue + clean_aliases = (clean_aliases == "" ? a : clean_aliases "|" a) + } + } + + printf "%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\x1f%s\n", \ + file_binary, route, fallback_route, group, name, summary, usage, args, \ + subcommands, examples, clean_aliases, requires_sudo, hidden, has_summary, metadata_errors + } + BEGINFILE { + reset_file(FILENAME) + if (ERRNO != "") { + printf "omarchy: %s: %s\n", FILENAME, ERRNO > "/dev/stderr" + emit_file() + nextfile + } + } + ENDFILE { emit_file() } + FNR > limit { nextfile } + FNR == 1 && /^#!/ { next } + /^[[:space:]]*$/ { next } + !/^[[:space:]]*#/ { nextfile } + { + if (match($0, /^[[:space:]]*#[[:space:]]*omarchy:([[:alnum:]_-]+)=(.*)$/, m)) { + k = m[1] + v = m[2] + sub(/\r$/, "", v) + gsub(/\t/, " ", v) + if (k == "group") group = v + else if (k == "name") { name = v; name_seen = 1 } + else if (k == "summary") { summary = v; if (v != "") has_summary = "true" } + else if (k == "args") args = v + else if (k == "subcommand") { + sep = index(v, " — ") + if (sep > 0) { + sa = substr(v, 1, sep - 1) + ss = substr(v, sep + length(" — ")) + entry = sa "\x1d" ss + subcommands = (subcommands == "" ? entry : subcommands "\x1e" entry) + sub_args_joined = (sub_args_joined == "" ? sa : sub_args_joined " | " sa) + } else { + append_err("subcommand must be \x27 — \x27") + } + } + else if (k == "examples") examples = v + else if (k == "alias" || k == "aliases") aliases = v + else if (k == "requires-sudo") { + requires_sudo = v + if (v != "true") append_err("requires-sudo must be omitted or true") + } + else if (k == "hidden") { + hidden = v + if (v != "true") append_err("hidden must be omitted or true") + } + } else if (fallback_summary == "" && match($0, /^[[:space:]]*#[[:space:]]*(.+)$/, m)) { + v = m[1] + sub(/\r$/, "", v) + gsub(/\t/, " ", v) + if (v != "" && v !~ /^omarchy:/) fallback_summary = v + } + } + ' "$@" + ) } reset_commands() { COMMAND_KEYS=() ROUTE_COLLISIONS=() COMMAND_ROUTE=() COMMAND_FALLBACK_ROUTE=() COMMAND_BINARY=() COMMAND_GROUP=() COMMAND_NAME=() - COMMAND_SUMMARY=() COMMAND_USAGE=() COMMAND_ARGS=() COMMAND_EXAMPLES=() COMMAND_REQUIRES_SUDO=() + COMMAND_SUMMARY=() COMMAND_USAGE=() COMMAND_ARGS=() COMMAND_SUBCOMMANDS=() COMMAND_EXAMPLES=() COMMAND_REQUIRES_SUDO=() COMMAND_HIDDEN=() COMMAND_ALIASES=() COMMAND_HAS_SUMMARY=() COMMAND_METADATA_ERRORS=() ROUTE_TO_KEY=() ROUTE_IS_ALIAS=() BINARY_TO_KEY=() } load_commands() { local file="" + local files=() for file in "$OMARCHY_BIN_DIR"/omarchy-*; do [[ -f $file && -x $file ]] || continue - register_command "$file" + files+=("$file") done + register_command_files "${files[@]}" } # Only a command whose route starts with "omarchy " can resolve a route @@ -343,6 +581,7 @@ load_route_candidates() { local first="$1" local -A seen=() local file="" + local files=() [[ $first =~ ^[[:alnum:]][[:alnum:]_-]*$ ]] || return 1 @@ -354,10 +593,19 @@ load_route_candidates() { done < <(grep -l -E -e "omarchy:group=$first([^[:alnum:]_-]|$)" -e "omarchy:alias(es)?=.*omarchy[[:space:]]+$first([[:space:]]|\||$)" "$OMARCHY_BIN_DIR"/omarchy-* 2>/dev/null) # The full load's own glob, so colliding routes register in the same order. - for file in "$OMARCHY_BIN_DIR"/omarchy-*; do - [[ -n ${seen[$file]} && -f $file && -x $file ]] || continue - register_command "$file" - done + # When only one candidate matched, order cannot matter, skipping the full glob. + if (( ${#seen[@]} == 1 )); then + for file in "${!seen[@]}"; do + [[ -f $file && -x $file ]] && files+=("$file") + done + else + for file in "$OMARCHY_BIN_DIR"/omarchy-*; do + [[ -n ${seen[$file]:-} && -f $file && -x $file ]] || continue + files+=("$file") + done + fi + + register_command_files "${files[@]}" } load_command_by_binary() { @@ -371,11 +619,14 @@ load_command_by_binary() { load_child_commands_by_binary() { local binary="$1" local file="" + local files=() for file in "$OMARCHY_BIN_DIR/$binary"-*; do [[ -f $file && -x $file ]] || continue - register_command "$file" + files+=("$file") done + + register_command_files "${files[@]}" } group_has_child_commands() { @@ -416,26 +667,45 @@ command_takes_only_flags() { local key="$1" local args="${COMMAND_ARGS[$key]}" local token="" + local tokens=() + local in_option=false [[ -n $args ]] || return 1 - for token in $args; do - [[ $token == -* || $token == "[-"* ]] || return 1 + read -ra tokens <<<"$args" + # An optional flag may name its value, as in [--model ]; the value + # placeholder belongs to the flag and isn't a positional argument. + for token in "${tokens[@]}"; do + if [[ $token == -* || $token == "[-"* ]]; then + if [[ $token == "[-"* && $token != *"]" ]]; then + in_option=true + else + in_option=false + fi + elif [[ $in_option == true ]]; then + if [[ $token == *"]" ]]; then + in_option=false + fi + else + return 1 + fi done } load_group_commands() { local group="$1" local file="" + local files=() if [[ -f $OMARCHY_BIN_DIR/omarchy-$group && -x $OMARCHY_BIN_DIR/omarchy-$group ]]; then - register_command "$OMARCHY_BIN_DIR/omarchy-$group" + files+=("$OMARCHY_BIN_DIR/omarchy-$group") fi for file in "$OMARCHY_BIN_DIR/omarchy-$group"-*; do [[ -f $file && -x $file ]] || continue - register_command "$file" + files+=("$file") done + register_command_files "${files[@]}" } resolve_direct_route() { @@ -493,17 +763,24 @@ command_route_for_group() { fi } -command_usage_for_group() { - local key="$1" - local group="$2" - local route="" - - route=$(command_route_for_group "$key" "$group") - if [[ -n ${COMMAND_ARGS[$key]} ]]; then - route+=" ${COMMAND_ARGS[$key]}" +# Appends a command's table rows under the given route to the named variable: +# one per declared subcommand, each with its own summary, or a single row with +# the full usage. Appending in place keeps full listings free of a subshell per +# command. +append_command_rows() { + local -n command_rows_ref="$1" + local key="$2" + local route="$3" + local subcommand_args="" + local subcommand_summary="" + + if [[ -n ${COMMAND_SUBCOMMANDS[$key]} ]]; then + while IFS=$'\t' read -r subcommand_args subcommand_summary; do + command_rows_ref+="$route $subcommand_args"$'\t'"$subcommand_summary"$'\n' + done <<<"${COMMAND_SUBCOMMANDS[$key]}" + else + command_rows_ref+="$route${COMMAND_ARGS[$key]:+ ${COMMAND_ARGS[$key]}}"$'\t'"${COMMAND_SUMMARY[$key]}"$'\n' fi - - printf '%s' "$route" } sorted_group_keys() { @@ -528,34 +805,21 @@ sorted_group_keys() { done | sort -u | cut -f2- } -examples_as_lines() { - local examples="$1" - local old_ifs="$IFS" - local example="" - IFS='|' - - for example in $examples; do - example="${example# }" - example="${example% }" - [[ -n $example ]] && printf '%s\n' "$example" - done - - IFS="$old_ifs" -} - pipe_values_as_lines() { local values="$1" - local old_ifs="$IFS" local value="" - IFS='|' + local items=() - for value in $values; do + IFS='|' read -ra items <<<"$values" + for value in "${items[@]}"; do value="${value# }" value="${value% }" [[ -n $value ]] && printf '%s\n' "$value" done +} - IFS="$old_ifs" +examples_as_lines() { + pipe_values_as_lines "$1" } show_group_list() { @@ -583,7 +847,7 @@ Common commands: omarchy theme set Apply a theme omarchy font list List available fonts omarchy screenshot Take a screenshot - omarchy debug Print debugging information + omarchy-debug Print debugging information Groups: EOF @@ -627,6 +891,10 @@ print_command_table() { (( width > max_width )) && max_width=$width done <<<"$rows" + # Cap the column so a usage longer than 48 characters pushes only its own summary + # along, rather than padding every row out past the edge of a normal terminal. + (( max_width > 48 )) && max_width=48 + while IFS=$'\t' read -r command rest; do [[ -n $command ]] || continue @@ -638,7 +906,6 @@ show_commands() { local include_all="$1" local key="" local route="" - local usage="" local rows="" local alias_rows="" @@ -650,8 +917,7 @@ show_commands() { while IFS= read -r key; do [[ -n $key ]] || continue - usage="${COMMAND_USAGE[$key]}" - rows+="$usage"$'\t'"${COMMAND_SUMMARY[$key]}"$'\n' + append_command_rows rows "$key" "${COMMAND_ROUTE[$key]}" done < <(sorted_keys "$include_all") print_command_table "$rows" @@ -680,16 +946,23 @@ markdown_escape() { show_commands_markdown() { local include_all="$1" local key="" + local rows="" + local usage="" + local summary="" echo "| Command | Binary | Summary |" echo "| --- | --- | --- |" while IFS= read -r key; do [[ -n $key ]] || continue - printf '| `%s` | `%s` | %s |\n' \ - "$(markdown_escape "${COMMAND_USAGE[$key]}")" \ - "$(markdown_escape "${COMMAND_BINARY[$key]}")" \ - "$(markdown_escape "${COMMAND_SUMMARY[$key]}")" + rows="" + append_command_rows rows "$key" "${COMMAND_ROUTE[$key]}" + while IFS=$'\t' read -r usage summary; do + printf '| `%s` | `%s` | %s |\n' \ + "$(markdown_escape "$usage")" \ + "$(markdown_escape "${COMMAND_BINARY[$key]}")" \ + "$(markdown_escape "$summary")" + done <<<"${rows%$'\n'}" done < <(sorted_keys "$include_all") } @@ -863,7 +1136,7 @@ show_group_help() { while IFS= read -r key; do [[ -n $key ]] || continue - rows+="$(command_usage_for_group "$key" "$group")"$'\t'$'\t'"${COMMAND_SUMMARY[$key]}"$'\n' + append_command_rows rows "$key" "$(command_route_for_group "$key" "$group")" done < <(sorted_group_keys "$group" "$include_all") if [[ -n $rows ]]; then @@ -881,8 +1154,8 @@ show_prefix_help() { while IFS= read -r key; do [[ -n $key ]] || continue - if [[ ${COMMAND_USAGE[$key]} == $prefix_with_space* ]]; then - rows+="${COMMAND_USAGE[$key]}"$'\t'$'\t'"${COMMAND_SUMMARY[$key]}"$'\n' + if [[ ${COMMAND_USAGE[$key]} == "$prefix_with_space"* ]]; then + append_command_rows rows "$key" "${COMMAND_ROUTE[$key]}" fi done < <(sorted_keys false) @@ -902,7 +1175,7 @@ show_related_commands() { while IFS= read -r child_key; do [[ -n $child_key && $child_key != "$key" ]] || continue - rows+="$(command_usage_for_group "$child_key" "$group")"$'\t'$'\t'"${COMMAND_SUMMARY[$child_key]}"$'\n' + append_command_rows rows "$child_key" "$(command_route_for_group "$child_key" "$group")" done < <(sorted_group_keys "$group" false) if [[ -n $rows ]]; then @@ -919,13 +1192,19 @@ show_command_help() { local args="${COMMAND_ARGS[$key]}" local example="" local alias="" + local rows="" echo "Usage:" - echo " ${COMMAND_USAGE[$key]}" + if [[ -n ${COMMAND_SUBCOMMANDS[$key]} ]]; then + append_command_rows rows "$key" "${COMMAND_ROUTE[$key]}" + print_command_table "$rows" + else + echo " ${COMMAND_USAGE[$key]}" + fi echo "" echo "${COMMAND_SUMMARY[$key]}" - if [[ -n $args ]]; then + if [[ -z ${COMMAND_SUBCOMMANDS[$key]} && -n $args ]]; then echo "" echo "Arguments:" echo " $args" @@ -1046,10 +1325,11 @@ dispatch_fast_or_help() { if (( DIRECT_RESOLVED_COUNT == 1 )) && group_has_child_commands "$1"; then load_group_commands "$1" show_group_help "$1" + return 0 else show_command_help "$key" + return 1 fi - return 0 fi fi @@ -1110,10 +1390,11 @@ dispatch_or_help() { if (( ${#remaining[@]} == 0 )) && command_requires_args "$key"; then if (( RESOLVED_COUNT == 1 )) && group_exists "$1"; then show_group_help "$1" + return 0 else show_command_help "$key" + return 1 fi - return 0 fi exec "$binary_path" "${remaining[@]}" diff --git a/bin/omarchy-agent b/bin/omarchy-agent index 6d0e585d4981..20dfb61500fb 100755 --- a/bin/omarchy-agent +++ b/bin/omarchy-agent @@ -1,11 +1,17 @@ #!/bin/bash # omarchy:summary=Launch the default coding agent in a terminal -# omarchy:args=[--inline] [--pick] -# omarchy:examples=omarchy agent | omarchy agent --inline +# omarchy:args=[--inline] [--pick] [--local-model ] [--agent ] [--provider ] [--app-id=] +# omarchy:examples=omarchy agent | omarchy agent --inline | omarchy agent --agent codex | omarchy agent --provider fireworks inline=false pick=false +use_local=false +local_model="" +agent_override="" +provider="" +app_id="org.omarchy.agent" +launch_args=("$@") # Flags only. A bare prompt would shadow the subcommands under this group, so # prompts go through omarchy-agent-prompt, which passes one here as --prompt. @@ -19,6 +25,25 @@ while (($#)); do pick=true shift ;; + --local-model) + use_local=true + local_model=${2:?--local-model needs a recipe id} + shift 2 + ;; + --agent) + agent_override=${2:?--agent needs an agent id} + shift 2 + ;; + --provider) + provider=${2:?--provider needs a provider id} + shift 2 + ;; + # A launcher of its own (Codex, Claude Code, Grok Build) gives its windows + # their own class, so the dock keeps them under that launcher. + --app-id=*) + app_id=${1#--app-id=} + shift + ;; --prompt) prompt=${2:?--prompt needs a value} shift 2 @@ -35,20 +60,73 @@ done # menu start in the work directory instead of re-asking on every session. [[ $PWD == "$HOME" && -d $HOME/Work ]] && cd "$HOME/Work" -agent=$(omarchy-default-agent) +# --agent launches a given agent instead of the default: the panel's terminal +# button on each subscription opens the harness made for it, Codex for OpenAI. +if [[ -n $agent_override ]]; then + agent=$agent_override +else + agent=$(omarchy-default-agent) +fi + +# --provider opens a pay-as-you-go provider with no harness of its own +# (Fireworks, OpenRouter, and the agents panel's More list) in OpenCode, where +# the panel's sign-in saves its key. +[[ -n $provider ]] && agent=opencode + +# A default of "local" is the local model. It opens in pi, as --local-model +# does whatever the default agent is: the agents panel launches a model +# whether or not a default was chosen. An agent asked for by name is opened +# as asked. +if [[ $agent == "local" ]]; then + use_local=true + agent=pi + # The model the default pins, unless it's since been removed from this + # machine; a paired machine's is that machine's to answer for. + pinned=$(cat "$HOME/.config/omarchy/defaults/local-model" 2>/dev/null) + if [[ -z $local_model && -n $pinned ]]; then + if [[ $pinned == */* ]] || omarchy-models status --json 2>/dev/null | jq -e --arg recipe "$pinned" '.models[$recipe]' >/dev/null; then + local_model=$pinned + fi + fi +elif [[ $use_local == "true" ]]; then + agent=pi +fi # Omarchy ships without a default, so there is nothing to launch until one is # picked. --pick offers the choice instead of the error, which is what the # keybinding wants: a keypress that opens nothing explains nothing. if [[ -z $agent ]]; then - [[ $pick == "true" ]] && exec omarchy-menu summon setup.default.agent + if [[ $pick == "true" ]]; then + # The agents panel sets one up, and its agent is started from there, so a + # prompt (a crash report, a Make something task) waits on the clipboard + # to paste into it. + if [[ -n ${prompt:-} ]]; then + printf '%s' "$prompt" | wl-copy + omarchy-notification-send -g 󰅇 "$(omarchy-i18n agents.chooseForPrompt)" "$(omarchy-i18n agents.promptOnClipboardBody)" + fi + exec omarchy-shell omarchy.agents open + fi echo "Choose default agent with: omarchy default agent " >&2 exit 1 fi -if omarchy-cmd-missing "$agent"; then - echo "$agent is not installed. Choose an installed agent with: omarchy default agent " >&2 - exit 1 +# OpenClaw's launcher sets OpenClaw up when the package became the seed before +# this user's OpenClaw moved, so with the package a missing command is its to fix. +if omarchy-cmd-missing "$agent" && ! { [[ $agent == "openclaw" ]] && omarchy-pkg-present openclaw; }; then + # An agent you still have a sign-in for can be missing its CLI: removed, or + # signed in to on another machine and copied over. Launching it installs the + # CLI first and then opens as asked, in this terminal or a floating one. + if omarchy-install-ai-cli --package "$agent" &>/dev/null; then + if [[ -t 0 ]]; then + omarchy-install-ai-cli "$agent" || exit 1 + else + printf -v relaunch '%q ' omarchy-agent "${launch_args[@]}" + exec omarchy-launch-floating-terminal-with-presentation "omarchy-install-ai-cli $agent && ${relaunch% }" + fi + else + echo "$agent is not installed. Choose an installed agent with: omarchy default agent " >&2 + exit 1 + fi fi # Agents launched from the keybinding or menu run unattended, so each one starts @@ -138,12 +216,137 @@ kimi) command=(kimi --yolo) fi ;; +qwen) + # Bind the value so a prompt starting with a dash stays literal. + command=(qwen --yolo) + [[ -n ${prompt:-} ]] && command+=("--prompt-interactive=$prompt") + ;; +dsh) + # The browser UI has no prompt option, and the headless profile would run the + # prompt with full access in a window that closes with its answer, so a + # prompt goes to the clipboard below instead. + command=(env DSH_PERMISSION_MODE=danger-full-access dsh web) + prompt_via_clipboard="DeepSeek Harness" + ;; +mcode) + # The TUI has no no-approval flag; permission options belong to exec mode. + command=(mcode) + [[ -n ${prompt:-} ]] && command+=(-- "$prompt") + ;; +freebuff) + # Freebuff takes no starting prompt and asks no tool permissions, so a + # prompt goes to the clipboard below instead. + command=(freebuff) + prompt_via_clipboard="Freebuff" + ;; +kilo) + # Kilo is built on OpenCode and shares its flags. Bind the prompt so one + # starting with a dash stays literal. + command=(kilo --auto) + [[ -n ${prompt:-} ]] && command+=("--prompt=$prompt") + ;; +devin) + # A bare positional is a path that opens Devin Desktop, so the prompt + # always follows --, which starts an interactive session with it. + command=(devin --permission-mode dangerous --respect-workspace-trust false) + [[ -n ${prompt:-} ]] && command+=(-- "$prompt") + ;; +amp) + # Amp takes its first interactive message from piped input; a positional + # message is for --execute, which exits after one turn. + if [[ -n ${prompt:-} ]]; then + command=(bash -c 'printf "%s\n" "$1" | exec "$0" --dangerously-allow-all' amp "$prompt") + else + command=(amp --dangerously-allow-all) + fi + ;; *) echo "Unsupported default agent: $agent" >&2 exit 1 ;; esac +# A model that is set up but not running, as one opened from its launcher may +# be, is started first, in the terminal the agent will have: loading takes a +# minute or so, and omarchy-models-warmup puts on a show for it there. So +# a launch from outside a terminal reruns itself inside one. A model on a +# paired machine is that machine's to start. +if [[ $use_local == "true" && $local_model != */* ]]; then + local_state=$(omarchy-models status --json 2>/dev/null | jq -r --arg recipe "$local_model" ' + (if $recipe == "" then .last // "" else $recipe end) as $recipe + | .models[$recipe] // empty | "\(.unit)/\(.sub_state)"' 2>/dev/null) + if [[ -n $local_state && $local_state != "active/running" ]]; then + if [[ $inline == "true" ]]; then + omarchy-models-warmup ${local_model:+"$local_model"} || exit 1 + else + exec omarchy-launch-tui --app-id="$app_id" omarchy-agent --inline "${launch_args[@]}" + fi + fi +fi + +# A local model points pi at the model `omarchy models use` runs, through a +# launch-time overlay Omarchy owns, never by editing pi's own config. +if [[ $use_local == "true" ]]; then + mapfile -t overlay < <(omarchy-models overlay pi ${local_model:+"$local_model"}) + if (( ${#overlay[@]} != 3 )); then + omarchy-notification-send -u critical "$(omarchy-i18n agents.localMissing)" "$(omarchy-i18n agents.localMissingBody)" + exit 1 + fi + command+=(--extension "${overlay[0]}" --provider "${overlay[1]}" --model "${overlay[2]}") +fi + +# --provider starts the session on one of the provider's models, passed at +# launch rather than written to the agent's config, so it never opens on +# another provider: the model the agent last used there, so a switch made in +# a session sticks; else the one the provider's usage record has spent most +# tokens on; else the first the agent lists. The record names a model by its +# short name ("deepseek-v4.1-flash"), so the agent's own list supplies the id +# it knows it by ("accounts/fireworks/models/deepseek-v4p1-flash"). An agent +# that lists no models for the provider opens as it was. +if [[ -n $provider ]]; then + provider_id=$provider + [[ $provider == "fireworks" ]] && provider_id="fireworks-ai" + provider_models=$(opencode models 2>/dev/null | sed -n "s|^$provider_id/||p") + # OpenCode keeps the models it used, latest first. + provider_last=$(jq -r --arg provider "$provider_id" 'first(.recent[]? | select(.providerID == $provider) | .modelID) // empty' \ + "${XDG_STATE_HOME:-$HOME/.local/state}/opencode/model.json" 2>/dev/null) + + provider_record="${XDG_STATE_HOME:-$HOME/.local/state}/omarchy/agents/usage/$provider.json" + provider_model=$(awk -v last="$provider_last" ' + FILENAME == ARGV[1] { used[++count] = $0; next } + $0 == "" { next } + { + if (first == "") first = $0 + listed[$0] = 1 + short = $0 + sub(/.*\//, "", short) + while (match(short, /[0-9]p[0-9]/)) short = substr(short, 1, RSTART) "." substr(short, RSTART + 2) + if (!(short in id)) id[short] = $0 + } + END { + if (last in listed) { print last; exit } + for (i = 1; i <= count; i++) if (used[i] in id) { print id[used[i]]; exit } + print first + } + ' <(jq -r '.modelUsage // {} | to_entries | sort_by(-([.value[]? | numbers] | add // 0)) | .[].key' "$provider_record" 2>/dev/null) \ + <(printf '%s\n' "$provider_models")) + + if [[ -n $provider_model ]]; then + # The shared background service never sees the choice, so run a private one. + model=$(jq -nc --arg model "$provider_id/$provider_model" '{model: $model}') + command=(env "OPENCODE_CONFIG_CONTENT=$model" "${command[@]}" --standalone) + fi +fi + +# An agent with no way to take a starting prompt still opens, with the prompt +# on the clipboard to paste as its first message, so a prompted launch from the +# agents panel or a crash report is not lost. +if [[ -n ${prompt:-} && -n ${prompt_via_clipboard:-} ]]; then + printf '%s' "$prompt" | wl-copy + omarchy-notification-send -g 󰅇 "$(omarchy-i18n agents.promptOnClipboard "$prompt_via_clipboard")" \ + "$(omarchy-i18n agents.promptOnClipboardBody)" +fi + # A new session uses the current selection rather than its parent's account # pin. Explicit provider homes still override the selection. Carry the new pin # in the command, since terminals launched through uwsm don't inherit our env. @@ -172,5 +375,5 @@ if [[ $inline == "true" ]]; then else # A fixed app-id rather than the default org.omarchy., so every agent # window shares one class for window rules and themes to single out. - exec omarchy-launch-tui --app-id=org.omarchy.agent "${command[@]}" + exec omarchy-launch-tui --app-id="$app_id" "${command[@]}" fi diff --git a/bin/omarchy-agent-account-add b/bin/omarchy-agent-account-add index 6f92d7bd5f0a..ed6f4e34e01a 100755 --- a/bin/omarchy-agent-account-add +++ b/bin/omarchy-agent-account-add @@ -1,8 +1,8 @@ #!/bin/bash -# omarchy:summary=Sign in to a Claude, Codex, or Grok subscription -# omarchy:args=[--check] [--events] [--reauth ] [claude|codex|grok] [label] -# omarchy:examples=omarchy agent account add claude | omarchy agent account add Work | omarchy agent account add codex Side +# omarchy:summary=Sign in to an agent subscription +# omarchy:args=[--check] [--events] [--reauth ] [agy|claude|codex|copilot|cursor|deepseek|fireworks|grok|minimax|muse|opencode|openrouter|synthetic|zai] [label] +# omarchy:examples=omarchy agent account add claude | omarchy agent account add Work | omarchy agent account add codex Side | omarchy agent account add muse set -uo pipefail @@ -17,12 +17,18 @@ set -uo pipefail check=false events=false reauth="" +usage() { + echo "Usage: omarchy-agent-account-add [--check] [--events] [--reauth ] [agy|claude|codex|copilot|cursor|deepseek|fireworks|grok|minimax|muse|opencode|openrouter|synthetic|zai] [label]" >&2 + exit 1 +} + while [[ ${1:-} == --* ]]; do case "$1" in --check) check=true ;; --events) events=true ;; --reauth) reauth="${2:-}" + [[ -n $reauth && $reauth != --* ]] || usage shift ;; *) break ;; @@ -31,8 +37,9 @@ while [[ ${1:-} == --* ]]; do done # Whether a provider's own home (~/.claude, ~/.codex, ~/.grok) is signed in. +# For Claude that's whichever account sessions use, not always the primary. primary_signed_in() { - omarchy-agent-account-state list "$1" | jq -e '.[0].accounts | any(.primary and .signedIn)' >/dev/null + omarchy-agent-account-state list "$1" | jq -e --arg home "$HOME/.$1" '.[0].accounts | any(.home == $home and .signedIn)' >/dev/null } if [[ $check == "true" ]]; then @@ -43,25 +50,54 @@ if [[ $check == "true" ]]; then echo "$p first" fi done + # The rest keep one sign-in each, which signing in again replaces. + printf '%s first\n' agy copilot cursor deepseek fireworks minimax muse opencode openrouter synthetic zai exit 0 fi # The provider can be left out when it's your default agent: # `omarchy agent account add Work`. -if [[ ${1:-} != "claude" && ${1:-} != "codex" && ${1:-} != "grok" ]]; then +if [[ ! ${1:-} =~ ^(agy|gemini|claude|codex|copilot|cursor|cursor-agent|deepseek|fireworks|grok|minimax|muse|opencode|openrouter|synthetic|zai)$ ]]; then default=$(omarchy-default-agent) [[ $default == "claude" || $default == "codex" || $default == "grok" ]] && set -- "$default" "$@" fi +# Claude, Codex, and Grok can hold several accounts, each in a home of its +# own. The rest keep the one sign-in their CLI does. `harness` is the command +# that codes on the subscription, when it isn't the provider's own name. +accounts=false +key_provider="" case "${1:-}" in -claude) provider="claude"; name="Claude"; site="claude.ai"; package="claude"; home_env="CLAUDE_CONFIG_DIR" ;; -codex) provider="codex"; name="Codex"; site="chatgpt.com"; package="codex"; home_env="CODEX_HOME" ;; -grok) provider="grok"; name="Grok"; site="x.ai"; package="grok"; home_env="GROK_HOME" ;; -*) - echo "Usage: omarchy-agent-account-add [--check] [--events] [--reauth ] [claude|codex|grok] [label]" >&2 - exit 1 - ;; +claude) provider="claude"; name="Claude"; app="Claude Code"; site="claude.ai"; home_env="CLAUDE_CONFIG_DIR"; accounts=true ;; +codex) provider="codex"; name="Codex"; app="Codex"; site="chatgpt.com"; home_env="CODEX_HOME"; accounts=true ;; +grok) provider="grok"; name="Grok"; app="Grok Build"; site="x.ai"; home_env="GROK_HOME"; accounts=true ;; +# A Gemini subscription is signed in to through Antigravity, its harness. +agy | gemini) provider="agy"; name="Gemini"; app="Antigravity"; login_command=(agy acp --login) ;; +muse) provider="muse"; name="Muse"; app="Muse Code"; login_command=(muse login) ;; +# One OpenCode Console sign-in covers Zen and Go. +opencode) provider="opencode"; name="OpenCode"; app="OpenCode"; login_command=(opencode auth login opencode --method device) ;; +copilot) provider="copilot"; name="Copilot"; app="GitHub Copilot"; login_command=(copilot login) ;; +cursor | cursor-agent) provider="cursor"; harness="cursor-agent"; name="Cursor"; app="Cursor CLI"; login_command=(cursor-agent login) ;; +# Pay as you go, with OpenCode's id for each: Fireworks and OpenRouter, and +# the panel's More list, providers whose usage Omarchy reads, so their keys +# can be checked before they're saved. +fireworks) provider="fireworks"; name="Fireworks"; key_provider="fireworks-ai" ;; +openrouter) provider="openrouter"; name="OpenRouter"; key_provider="openrouter" ;; +deepseek) provider="deepseek"; name="DeepSeek"; key_provider="deepseek" ;; +minimax) provider="minimax"; name="MiniMax"; key_provider="minimax" ;; +synthetic) provider="synthetic"; name="Synthetic"; key_provider="synthetic" ;; +zai) provider="zai"; name="Z.ai"; key_provider="zai" ;; +*) usage ;; esac +# What's ready once signed in: the agent's own app, or for a key, the +# provider, which OpenCode only runs. +ready_name=${app-} +# No CLI of their own: an API key is the sign-in, and OpenCode runs on it. +if [[ -n $key_provider ]]; then + harness="opencode"; app="OpenCode"; login_command=(key_login "$key_provider") + ready_name=$name +fi +harness=${harness-$provider} label="${2:-}" say() { @@ -72,20 +108,78 @@ say() { fi } +# A signed-in agent gets a launcher of its own beside Agent, drawn by the +# icon set: Claude Code, Codex, or Grok Build, whatever the default agent is. +install_launcher() { + omarchy-agent-launcher "$harness" +} + +# The first agent signed in on a machine with none chosen becomes the +# default, so `omarchy agent` and the panel's starter prompts have one to run. +# A default someone already picked is never touched. +default_if_unset() { + if [[ -z $(omarchy-default-agent) ]]; then + mkdir -p "$HOME/.config/omarchy/defaults" + printf '%s\n' "$1" >"$HOME/.config/omarchy/defaults/agent" + fi +} + +# A first sign-in announces the agent as ready, and an added account that it's +# ready for more; clicking either starts one. Any other says which account it was. +# Each stays up until it's clicked or closed: the sign-in finishes in the +# browser, where a toast that leaves on its own goes unseen. finish() { + # An agent hidden from the panel, as removing its sign-in does, shows again + # however it was signed in to. + omarchy-shell omarchy.agents showAgent "$provider" true >/dev/null 2>&1 + install_launcher if [[ $events == "true" ]]; then printf '@@omarchy done %s\n' "$1" - omarchy-notification-send -g 󰚩 "$1" + if [[ ${2:-} == "ready" ]]; then + omarchy-notification-send --sticky -g 󰚩 --image "$(omarchy-agent-logo "$provider")" \ + "$(omarchy-i18n agents.readyToCode "$ready_name")" "$(omarchy-i18n agents.readyToCodeBody)" \ + --exec omarchy-agent --agent "$harness" --app-id="org.omarchy.$harness" + elif [[ ${2:-} == "more" ]]; then + omarchy-notification-send --sticky -g 󰚩 --image "$(omarchy-agent-logo "$provider")" \ + "$(omarchy-i18n agents.readyForMore "$ready_name")" "$(omarchy-i18n agents.readyForMoreBody "$3")" \ + --exec omarchy-agent --agent "$harness" --app-id="org.omarchy.$harness" + else + omarchy-notification-send --sticky -g 󰚩 --image "$(omarchy-agent-logo "$provider")" "$1" + fi else echo echo "$1" fi } +# Accounts just added, fresh or recovered, are the ones you want tokens from +# next, so sessions switch to the newest: running Claude sessions too, and new +# ones for the others. If the choice can't be saved, the accounts are still +# added and say so. +announce_added() { + local added newest used + added=$(jq -r 'map(.label + (if .email != "" then " (" + .email + ")" else "" end)) | join(", ")' <<<"$1") + newest=$(jq -c 'last' <<<"$1") + if used=$(omarchy-agent-account-state use "$provider" "$(jq -r .id <<<"$newest")"); then + omarchy-agent-usage-update --force "$provider" >/dev/null 2>&1 & + finish "$(omarchy-i18n agents.added "$added")" more "$(jq -r .label <<<"$newest")" + if [[ $events != "true" ]]; then + if [[ $(jq -r .seated <<<"$used") == "true" ]]; then + echo "$name sessions now use $(jq -r .label <<<"$newest"), running ones included." + else + echo "New $name sessions now use $(jq -r .label <<<"$newest")." + fi + fi + else + omarchy-agent-usage-update --force "$provider" >/dev/null 2>&1 & + finish "$(omarchy-i18n agents.addedNotSelected "$added")" + fi +} + fail() { if [[ $events == "true" ]]; then printf '@@omarchy error %s\n' "$1" - omarchy-notification-send -g 󰚩 -u critical "$(omarchy-i18n agents.addFailed "$name")" "$1" + omarchy-notification-send -g 󰚩 --image "$(omarchy-agent-logo "$provider")" -u critical "$(omarchy-i18n agents.addFailed "$name")" "$1" else echo "$1" >&2 fi @@ -112,14 +206,29 @@ interruptible() { wait $! } -if omarchy-cmd-missing "$provider"; then - say "$(omarchy-i18n agents.installingCli "$name")" - if [[ $events == "true" ]]; then - mise use -g "$package" >/dev/null 2>&1 || fail "$(omarchy-i18n agents.installCliFailed "$name")" - else - mise use -g "$package" || exit 1 +# Each agent's CLI is a package installed the first time it's needed. Signing +# in is often that time, so the install happens here, where the panel can show +# it, rather than looking like the login hanging. pacman prints no progress +# without a terminal, so the panel's progress row has no measure. The install +# runs in the background behind a `wait`, like a login, so Cancel stops it at +# once; with no terminal, polkit asks for the password. +install_cli() { + if [[ $events != "true" ]]; then + "$@" + return fi + + printf '@@omarchy progress 0 0 0\n' + "$@" >/dev/null 2>&1 /dev/null 2>&1 && opencode auth switch "$opencode_provider" "$id" >/dev/null 2>&1 +} + +# One sign-in, where the CLI always keeps it, through your normal browser: +# adding it and signing in again are the same login. The CLI's whole output +# goes to the panel, which shows the code it prints to confirm in the browser. +if [[ $accounts == "false" ]]; then + # Gemini's page ends on a code to paste back, and a key is all there is to + # a key's sign-in; the panel shows a field for either, under what it's for. + if [[ $events == "true" && $provider == "agy" ]]; then + printf '@@omarchy paste %s\n' "$(omarchy-i18n agents.pasteSignInCode)" + fi + if [[ -z $key_provider ]]; then + say "$(omarchy-i18n agents.signInBrowser "$name")" + elif [[ $events == "true" ]]; then + printf '@@omarchy key %s\n@@omarchy status %s\n' "$(omarchy-i18n agents.apiKeyHint "$name")" "$(omarchy-i18n agents.apiKeyHint "$name")" + fi + interruptible "${login_command[@]}" 2>&1 + login_status=$? + if (( login_status == 2 )) && [[ -n $key_provider ]]; then + fail "$(omarchy-i18n agents.keyRefused "$name")" + elif (( login_status == 3 )) && [[ -n $key_provider ]]; then + fail "$(omarchy-i18n agents.keyUnchecked "$name")" + elif (( login_status != 0 )); then + fail "$(omarchy-i18n agents.signInFailed "$name")" + fi + + omarchy-agent-usage-update --force "$provider" >/dev/null 2>&1 & + default_if_unset "$harness" + finish "$(omarchy-i18n agents.signedIn "$name")" ready + exit 0 +fi + case "$provider" in claude) login_command=(claude auth login) ;; codex) login_command=(codex login) ;; @@ -138,27 +321,38 @@ esac # The CLI's own home, whatever this shell has pointed it at. login() { - interruptible env -u CLAUDE_CONFIG_DIR -u CODEX_HOME -u GROK_HOME "OMARCHY_AGENT_${provider^^}_HOME=" "${login_command[@]}" + interruptible env -u CLAUDE_CONFIG_DIR -u CODEX_HOME -u GROK_HOME "OMARCHY_AGENT_${provider^^}_HOME=" "${login_command[@]}" 2>&1 } -# Signing an account that's already here in again, where it lives: the -# primary home through the normal browser, an added one through a private -# window. Its home is never recreated or removed. +# Signing an account that's already here in again: the primary through the +# normal browser, an added one through a private window. Its home is never +# recreated or removed. if [[ -n $reauth ]]; then - if [[ $reauth == ":primary" ]]; then - account_home="$HOME/.$provider" + found=$(omarchy-agent-account-state homes "$provider" | awk -F'\t' -v id="$reauth" '$1 == id || (id == ":primary" && $4 == "1")' | head -1) + account_home=$(cut -f2 <<<"$found") + [[ -n $account_home ]] || fail "$(omarchy-i18n agents.noAccountNamed "$name" "$reauth")" + + # A Claude login can move while the browser is open, so it signs in to a + # scratch home and is installed wherever the account's login is by then. + if [[ $provider == "claude" ]]; then + home=$(omarchy-agent-account-state begin "$provider" "" "$$") || fail "$(omarchy-i18n agents.homeFailed)" + target="$home" else - account_home=$(omarchy-agent-account-state homes "$provider" | awk -F'\t' -v id="$reauth" '$1 == id { print $2 }') + target="$account_home" fi - [[ -n $account_home ]] || fail "$(omarchy-i18n agents.noAccountNamed "$name" "$reauth")" + where=(env -u CLAUDE_CONFIG_DIR -u CODEX_HOME -u GROK_HOME "OMARCHY_AGENT_${provider^^}_HOME=") + [[ $target != "$HOME/.$provider" ]] && where+=("$home_env=$target") - if [[ $account_home == "$HOME/.$provider" ]]; then + if [[ $(cut -f4 <<<"$found") == "1" ]]; then say "$(omarchy-i18n agents.signInAgainBrowser "$name")" - login || fail "$(omarchy-i18n agents.signInFailed "$name")" + interruptible "${where[@]}" "${login_command[@]}" 2>&1 || fail "$(omarchy-i18n agents.signInFailed "$name")" else say "$(omarchy-i18n agents.signInAgainPrivate)" private_browser - interruptible env BROWSER="$browser" "$home_env=$account_home" "${login_command[@]}" || fail "$(omarchy-i18n agents.signInFailed "$name")" + interruptible "${where[@]}" BROWSER="$browser" "${login_command[@]}" 2>&1 || fail "$(omarchy-i18n agents.signInFailed "$name")" + fi + if [[ $provider == "claude" ]]; then + installed=$(omarchy-agent-account-state relogin "$provider" "$(cut -f1 <<<"$found")" "$home" 2>&1) || fail "$installed" fi omarchy-agent-usage-update --force "$provider" >/dev/null 2>&1 & @@ -171,15 +365,9 @@ fi if ! primary_signed_in "$provider"; then say "$(omarchy-i18n agents.signInBrowser "$name")" if login && primary_signed_in "$provider"; then - # The first agent signed in on a machine with none chosen becomes the - # default, so `omarchy agent` and the panel's starter prompts have one to - # run. A default someone already picked is never touched. - if [[ -z $(omarchy-default-agent) ]]; then - mkdir -p "$HOME/.config/omarchy/defaults" - printf '%s\n' "$provider" >"$HOME/.config/omarchy/defaults/agent" - fi + default_if_unset "$provider" omarchy-agent-usage-update --force "$provider" >/dev/null 2>&1 & - finish "$(omarchy-i18n agents.signedIn "$name")" + finish "$(omarchy-i18n agents.signedIn "$name")" ready else fail "$(omarchy-i18n agents.signInFailed "$name")" fi @@ -188,9 +376,7 @@ else # asking for another browser login. Live sign-ins are never recovered. if recovered=$(omarchy-agent-account-state recover "$provider"); then if [[ $(jq 'length' <<<"$recovered") != "0" ]]; then - added=$(jq -r 'map(.label + (if .email != "" then " (" + .email + ")" else "" end)) | join(", ")' <<<"$recovered") - omarchy-agent-usage-update --force "$provider" >/dev/null 2>&1 & - finish "$(omarchy-i18n agents.added "$added")" + announce_added "$recovered" exit 0 fi else @@ -217,18 +403,11 @@ EOF home=$(omarchy-agent-account-state begin "$provider" "$label" "$$") || fail "$(omarchy-i18n agents.homeFailed)" private_browser - interruptible env BROWSER="$browser" "$home_env=$home" "${login_command[@]}" + interruptible env BROWSER="$browser" "$home_env=$home" "${login_command[@]}" 2>&1 if account=$(omarchy-agent-account-state register "$provider" "$label" "$home" 2>&1); then home="" - added=$(jq -r '.label + (if .email != "" then " (" + .email + ")" else "" end)' <<<"$account") - omarchy-agent-usage-update --force "$provider" >/dev/null 2>&1 & - if [[ $events == "true" ]]; then - finish "$(omarchy-i18n agents.added "$added")" - else - finish "$(omarchy-i18n agents.added "$added")" - echo "Switch to it with: omarchy agent account use $provider $(jq -r .id <<<"$account")" - fi + announce_added "[$account]" else registration_status=$? # Keep the home for cleanup when registration was explicitly interrupted. diff --git a/bin/omarchy-agent-account-dispatch b/bin/omarchy-agent-account-dispatch new file mode 100755 index 000000000000..a99c4e191909 --- /dev/null +++ b/bin/omarchy-agent-account-dispatch @@ -0,0 +1,41 @@ +#!/bin/bash + +# omarchy:summary=Write the account dispatchers for the installed claude, codex and grok +# omarchy:args=[claude|codex|grok...] +# omarchy:hidden=true + +# A dispatcher runs its CLI as the selected subscription account +# (omarchy-agent-account-exec), and leads PATH so scripts and editors follow +# account switches too. One exists only while its CLI is installed: there's no +# claude command before Claude Code is. Installing or removing an agent through +# Omarchy runs this; with no agents named, every one is brought in line. + +dir="$HOME/.local/share/omarchy/agent-accounts/bin" + +# The real CLI is whatever PATH finds past the dispatchers. +cli_path="" +IFS=: read -r -a dirs <<<"$PATH" +for entry in "${dirs[@]}"; do + [[ $entry == "$dir" ]] || cli_path+="${cli_path:+:}$entry" +done + +agents=("$@") +(( ${#agents[@]} )) || agents=(claude codex grok) + +for agent in "${agents[@]}"; do + case $agent in + claude | codex | grok) ;; + *) continue ;; + esac + + if PATH=$cli_path type -P "$agent" >/dev/null; then + # Renamed into place, so a command starting while this runs never finds + # the dispatcher half written. + mkdir -p "$dir" + printf '#!/bin/bash\nexec omarchy-agent-account-exec %s "$@"\n' "$agent" >"$dir/.$agent.new" + chmod +x "$dir/.$agent.new" + mv -f "$dir/.$agent.new" "$dir/$agent" + else + rm -f "$dir/$agent" + fi +done diff --git a/bin/omarchy-agent-account-exec b/bin/omarchy-agent-account-exec index 28d123e40f5b..8ac8bc125bfc 100755 --- a/bin/omarchy-agent-account-exec +++ b/bin/omarchy-agent-account-exec @@ -19,8 +19,6 @@ esac provider=$1 shift -# mise removes its wrapper dispatch directories before calling us, so exec -# finds the real CLI (or its first-run installer) rather than this wrapper. # Pin the resolved home for children, including an implicit Main account. # Explicit provider homes still take precedence. if [[ -z ${!account_env:-} ]]; then @@ -31,13 +29,23 @@ if [[ -z ${!account_env:-} ]]; then fi fi -# Resolve before restoring dispatch on PATH: mise removes the wrapper paths to -# avoid recursion, but the agent's subprocesses need them for other providers. -if ! agent_binary=$(type -P "$provider"); then - # A mise dispatcher can exist before its CLI or first-run installer does. - export MISE_MINIMUM_RELEASE_AGE=0 - mise use -g --quiet "$provider" - agent_binary=$(mise which "$provider") +# The real CLI is whatever PATH finds past the dispatchers, the directory this +# was started from. A dispatcher exists only while its CLI is installed, so one +# left by a CLI removed outside Omarchy takes itself away and answers the way +# a shell would. +dispatchers="$HOME/.local/share/omarchy/agent-accounts/bin" +cli_path="" +IFS=: read -r -a dirs <<<"$PATH" +for dir in "${dirs[@]}"; do + [[ $dir == "$dispatchers" ]] || cli_path+="${cli_path:+:}$dir" +done +if ! agent_binary=$(PATH=$cli_path type -P "$provider"); then + rm -f "$dispatchers/$provider" + echo "$provider: command not found" >&2 + exit 127 fi -export PATH="${MISE_DATA_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/mise}/command-wrappers/bin:$PATH" + +# The agent's own subprocesses dispatch too, so another provider they start +# runs as its selected account. +export PATH="$dispatchers:$cli_path" exec "$agent_binary" "$@" diff --git a/bin/omarchy-agent-account-home b/bin/omarchy-agent-account-home index 6e2eb3b874f6..b69b86e8c317 100755 --- a/bin/omarchy-agent-account-home +++ b/bin/omarchy-agent-account-home @@ -21,5 +21,38 @@ account_pin="OMARCHY_AGENT_${1^^}_HOME" if [[ -v $account_pin ]]; then printf '%s' "${!account_pin}" elif [[ -f $registry ]]; then - exec omarchy-agent-account-state home "$1" + # Fast-path reading well-formed registries directly with jq (~1ms) rather than + # starting Python (~30ms) on every `claude`, `codex`, or `grok` invocation. + # Malformed or partial registries fall back to omarchy-agent-account-state. + accounts_root="${XDG_STATE_HOME:-$HOME/.local/state}/omarchy/agents/accounts" + if resolved=$(jq -r --arg provider "$1" --arg home "$HOME" --arg accounts_root "$accounts_root" ' + if type != "object" or (.accounts | type) != "array" then error("fallback") else . end + | (.accounts | map(select(type == "object" and (.id | type) == "string" and (.id | length) > 0))) as $accs + | if ($accs | length) != (.accounts | length) then error("fallback") else . end + | ($accs | map(select(.primary == true))[0]) as $primary + | if $primary == null then error("fallback") else . end + | ((.active // "main") as $aid | + ($accs | map(select(.id == $aid))[0] // + (if $aid == "primary" then $primary else $accs[0] end))) as $act + | if $provider == "claude" then + ((.seated // "") as $sid | + if ($accs | any(.id == $sid)) then $sid else $primary.id end) as $seated + | if $act.id == $seated then "" + elif ($act.primary == true) then ($accounts_root + "/claude/.primary") + elif (($act.home // "") | length) > 0 then $act.home + else ($home + "/.claude") + end + else + if ($act.primary == true) then "" + elif (($act.home // "") | length) > 0 then $act.home + else ($home + "/." + $provider) + end + end + ' "$registry" 2>/dev/null); then + if [[ -n $resolved ]]; then + printf '%s\n' "$resolved" + fi + else + exec omarchy-agent-account-state home "$1" + fi fi diff --git a/bin/omarchy-agent-account-list b/bin/omarchy-agent-account-list index 8c009586b2d9..8d905e0ba3d0 100755 --- a/bin/omarchy-agent-account-list +++ b/bin/omarchy-agent-account-list @@ -48,7 +48,7 @@ else # A provider nobody has signed in to has nothing to list. for (( i = 0; i < $(jq length <<<"$accounts"); i++ )); do jq -e ".[$i].accounts | any(.signedIn)" <<<"$accounts" >/dev/null || continue - jq -r ".[$i] | \"\(.name) — \(.switch) switching at \(.threshold)%\"" <<<"$accounts" + jq -r ".[$i] | \"\(.name) — notifies at \(.threshold)%\"" <<<"$accounts" jq -r ".[$i].accounts[] | \"\(if .active then \"*\" else \" \" end)\t\(.id)\t\(.label)\t\(.plan)\t\(.email)\t\" + ([.limits[]? | select(.percent != null) | \"\(.label): \((.percent * 100) | round)%\"] | join(\", \"))" <<<"$accounts" | diff --git a/bin/omarchy-agent-account-mode b/bin/omarchy-agent-account-mode deleted file mode 100755 index 3b539de29a24..000000000000 --- a/bin/omarchy-agent-account-mode +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/bash - -# omarchy:summary=Switch Claude, Codex, or Grok accounts automatically near a limit, or only notify -# omarchy:args=[claude|codex|grok] [manual|auto] [threshold] -# omarchy:examples=omarchy agent account mode auto | omarchy agent account mode auto 90 | omarchy agent account mode codex manual - -set -uo pipefail - -# The provider can be left out when it's your default agent: -# `omarchy agent account use work`. -if [[ ${1:-} != "claude" && ${1:-} != "codex" && ${1:-} != "grok" ]]; then - default=$(omarchy-default-agent) - [[ $default == "claude" || $default == "codex" || $default == "grok" ]] && set -- "$default" "$@" -fi - -if [[ ${1:-} != "claude" && ${1:-} != "codex" && ${1:-} != "grok" ]]; then - echo "Usage: omarchy-agent-account-mode [claude|codex|grok] [manual|auto] [threshold]" >&2 - exit 1 -fi - -if [[ -n ${2:-} ]]; then - omarchy-agent-account-state mode "$@" || exit 1 -fi - -omarchy-agent-account-state registry "$1" | jq -r ' - if .switch == "auto" then - "\(.name) switches new sessions to the account with the most headroom at \(.threshold)%." - else - "\(.name) notifies at \(.threshold)% and switches when you say so." - end' diff --git a/bin/omarchy-agent-account-remove b/bin/omarchy-agent-account-remove index c7af5ca373fc..2532d59ea951 100755 --- a/bin/omarchy-agent-account-remove +++ b/bin/omarchy-agent-account-remove @@ -1,30 +1,142 @@ #!/bin/bash -# omarchy:summary=Forget an added Claude, Codex, or Grok account -# omarchy:args=[claude|codex|grok] -# omarchy:examples=omarchy agent account remove work | omarchy agent account remove codex side +# omarchy:summary=Forget an agent sign-in, handing a Claude, Codex, or Grok account's sessions to another +# omarchy:args=[--yes] [--agent] [agy|claude|codex|copilot|cursor|deepseek|fireworks|grok|minimax|muse|opencode|openrouter|synthetic|zai] [account] +# omarchy:examples=omarchy agent account remove work | omarchy agent account remove codex side | omarchy agent account remove openrouter set -uo pipefail +# --yes skips the confirmation, for a caller that already asked. --agent +# says the first argument is the agent, never an account by that name, for a +# caller that knows which it means. +confirm=true +explicit=false +while [[ ${1:-} == "--yes" || ${1:-} == "--agent" ]]; do + [[ $1 == "--yes" ]] && confirm=false + [[ $1 == "--agent" ]] && explicit=true + shift +done + +accounts_provider() { + [[ $1 == "claude" || $1 == "codex" || $1 == "grok" ]] +} + +has_account() { + omarchy-agent-account-state registry "$1" 2>/dev/null | jq -e --arg id "$2" '.accounts[] | select(.id == $id)' >/dev/null +} + # The provider can be left out when it's your default agent: -# `omarchy agent account use work`. -if [[ ${1:-} != "claude" && ${1:-} != "codex" && ${1:-} != "grok" ]]; then - default=$(omarchy-default-agent) - [[ $default == "claude" || $default == "codex" || $default == "grok" ]] && set -- "$default" "$@" +# `omarchy agent account remove work`. An account of the default agent named +# like another agent (`cursor`) is still that account. +default=$(omarchy-default-agent) +if [[ $explicit == "false" ]] && { + [[ ! ${1:-} =~ ^(agy|gemini|claude|codex|copilot|cursor|cursor-agent|deepseek|fireworks|grok|minimax|muse|opencode|openrouter|synthetic|zai)$ ]] || + { (( $# == 1 )) && ! accounts_provider "$1" && accounts_provider "$default" && has_account "$default" "$1"; } +}; then + accounts_provider "$default" && set -- "$default" "$@" fi -if [[ ${1:-} != "claude" && ${1:-} != "codex" && ${1:-} != "grok" ]] || [[ -z ${2:-} ]]; then - echo "Usage: omarchy-agent-account-remove [claude|codex|grok] " >&2 +provider=${1:-} +case $provider in +gemini) provider="agy" ;; +cursor-agent) provider="cursor" ;; +esac + +if [[ ! $provider =~ ^(agy|claude|codex|copilot|cursor|deepseek|fireworks|grok|minimax|muse|opencode|openrouter|synthetic|zai)$ ]] || + { accounts_provider "$provider" && [[ -z ${2:-} ]]; }; then + echo "Usage: omarchy-agent-account-remove [agy|claude|codex|copilot|cursor|deepseek|fireworks|grok|minimax|muse|opencode|openrouter|synthetic|zai] [account]" >&2 exit 1 fi -# Removing only deletes the account's home here. It never logs out, which -# would revoke the sign-in for every other copy of it too. -if [[ -t 0 ]] && ! gum confirm "Forget the $1 account $2? You'd have to sign in again to add it back."; then +# Every OpenCode credential under the integrations the agent's usage is read +# from, as `omarchy agent account add` saves a key there. The export carries +# the secrets, which stay in the pipe. +opencode_logout() { + local credentials integration id + credentials=$(opencode auth export 2>/dev/null | jq -r '.[]? | select(.integrationID == ($ARGS.positional[])) | "\(.integrationID)\t\(.id)"' --args "$@") || return 1 + while IFS=$'\t' read -r integration id; do + [[ -n $id ]] || continue + opencode auth logout "$integration" "$id" >/dev/null 2>&1 || return 1 + done <<<"$credentials" +} + +case $provider in +claude | codex | grok) name=$2 ;; +agy) name="Gemini" ;; +deepseek) name="DeepSeek" ;; +minimax) name="MiniMax" ;; +opencode) name="OpenCode" ;; +openrouter) name="OpenRouter" ;; +zai) name="Z.ai" ;; +*) name=${provider^} ;; +esac + +# Removing deletes the sign-in here. Where a CLI's logout would revoke it for +# every other copy too, its saved credential is deleted instead. +if [[ $confirm == "true" && -t 0 ]] && ! gum confirm "Forget $name? You'd have to sign in again to add it back."; then exit 130 fi -account=$(omarchy-agent-account-state remove "$1" "$2") || exit 1 -echo "Forgot $(jq -r .label <<<"$account")." -# The panel reads which accounts exist from the usage record. -omarchy-agent-usage-update --limits-only "$1" >/dev/null 2>&1 & +# 0 when the keyring holds Gemini's sign-in, 1 when it doesn't (a quiet +# miss), 2 when the keyring couldn't be asked (it says why on stderr). +gemini_in_keyring() { + local error + if error=$(secret-tool lookup service gemini username antigravity 2>&1 >/dev/null); then + return 0 + elif [[ -z $error ]]; then + return 1 + else + return 2 + fi +} + +hides=true +case $provider in +claude | codex | grok) + # The removal says, under the registry's lock, whether it was the last. + account=$(omarchy-agent-account-state remove "$provider" "$2") || exit 1 + name=$(jq -r .label <<<"$account") + [[ $(jq -r .last <<<"$account") == "true" ]] || hides=false + ;; +agy) + # agy keeps its sign-in in the keyring, or in a file where there's none, + # and has no logout of its own. + gemini_in_keyring + keyring=$? + if (( keyring == 2 )); then + echo "Couldn't check the keyring for Gemini's sign-in." >&2 + exit 1 + elif (( keyring == 0 )); then + secret-tool clear service gemini username antigravity 2>/dev/null + gemini_in_keyring + if (( $? != 1 )); then + echo "Couldn't clear Gemini's sign-in from the keyring." >&2 + exit 1 + fi + fi + rm -f "${AGY_DIR:-$HOME/.gemini/antigravity-cli}/antigravity-oauth-token" || exit 1 + ;; +muse) muse logout >/dev/null || exit 1 ;; +cursor) cursor-agent logout >/dev/null || exit 1 ;; +copilot) + # Copilot signs out only from inside a session, which needs a terminal. + if [[ -t 0 ]]; then + copilot -i /logout || exit 1 + else + echo "Copilot signs out from its own session: run omarchy agent account remove copilot in a terminal." >&2 + exit 1 + fi + ;; +fireworks) opencode_logout fireworks-ai || exit 1 ;; +minimax) opencode_logout minimax minimax-cn minimax-coding-plan minimax-cn-coding-plan || exit 1 ;; +opencode) opencode_logout opencode opencode-go || exit 1 ;; +zai) opencode_logout zai zhipuai || exit 1 ;; +*) opencode_logout "$provider" || exit 1 ;; +esac + +# Hidden once its last sign-in is gone, so a key it still reads from the +# environment, pi, or omp doesn't bring it back. Signing in again shows it. +[[ $hides == "false" ]] || omarchy-shell omarchy.agents showAgent "$provider" false >/dev/null 2>&1 +echo "Forgot $name." +# The panel reads which sign-ins exist from the usage record. +omarchy-agent-usage-update --limits-only "$provider" >/dev/null 2>&1 & diff --git a/bin/omarchy-agent-account-rename b/bin/omarchy-agent-account-rename index b3095595ab0a..0b64fbbf46d0 100755 --- a/bin/omarchy-agent-account-rename +++ b/bin/omarchy-agent-account-rename @@ -19,6 +19,6 @@ if [[ ${1:-} != "claude" && ${1:-} != "codex" && ${1:-} != "grok" ]] || (( $# < fi account=$(omarchy-agent-account-state rename "$@") || exit 1 -echo "Renamed to $(jq -r .label <<<"$account"). Switch to it with: omarchy agent account use $(jq -r .id <<<"$account")" +echo "Renamed to $(jq -r .label <<<"$account"). Switch to it with: omarchy agent account use $1 $(jq -r .id <<<"$account")" # The panel reads account names from the usage record. omarchy-agent-usage-update --limits-only "$1" >/dev/null 2>&1 & diff --git a/bin/omarchy-agent-account-state b/bin/omarchy-agent-account-state index afc65f9e0eee..29c5e6d268b3 100755 --- a/bin/omarchy-agent-account-state +++ b/bin/omarchy-agent-account-state @@ -1,6 +1,6 @@ #!/usr/bin/python3 # omarchy:summary=Read and change the registry of Claude, Codex, and Grok subscription accounts -# omarchy:args= [provider] [args...] +# omarchy:args= [provider] [args...] # omarchy:hidden=true """The account registry behind `omarchy agent account`. @@ -15,6 +15,10 @@ conversation history, settings and skills stay one set across accounts. Each provider's registry is one JSON file beside those homes. It records which account is active — the one new sessions start as — how switching happens, and display-safe identity. Tokens never enter it and never leave this process. + +Claude sessions all start in ~/.claude, which holds the login of the seated +account; every other Claude login waits in its own home. Switching moves the +chosen login into ~/.claude, and running sessions follow on their next message. """ from __future__ import annotations @@ -29,6 +33,7 @@ import shutil import subprocess import sys import tempfile +import time from pathlib import Path from typing import Any @@ -56,7 +61,7 @@ PROVIDERS = { "name": "Grok", "home_env": "GROK_HOME", "shared_dirs": ["sessions", "skills", "agents", "plugins", "installed-plugins", "marketplace-cache", "hooks", "memory", "memory-v2", "rules", "commands", "workflows", "personas", "worktrees"], - "shared_files": ["config.toml", "settings.json", "lsp.json", "pager.toml", "sandbox.toml", "trusted_folders.toml", "statusline.sh", "worktrees.db"], + "shared_files": ["config.toml", "AGENTS.md", "settings.json", "lsp.json", "pager.toml", "sandbox.toml", "trusted_folders.toml", "statusline.sh", "worktrees.db"], "carried_keys": [], }, } @@ -66,9 +71,12 @@ DEFAULT_THRESHOLD = 95 # `use next` cycles, a provider name is read as the provider when it comes # first, and the menu's Add Account row is `.add`. RESERVED_IDS = {"next", "add", "claude", "codex", "grok", "primary"} -SWITCH_MODES = ("manual", "auto") LOGIN_RECEIPT = ".omarchy-login.json" +# Providers whose running sessions follow a switch: Claude Code re-reads its +# credentials when the file changes, while Codex keeps the account it started as. +SEATED = {"claude"} + class AccountError(Exception): pass @@ -115,6 +123,21 @@ def claude_account_file(home: Path) -> Path: return home / ".claude.json" +# Where an account's login waits while another account is seated. The +# primary's login gets a home of its own the first time it's moved out. +def store_home(provider: str, account: dict[str, Any]) -> Path: + if provider in SEATED and account.get("primary"): + return accounts_root() / provider / ".primary" + return account_home(provider, account) + + +# Where an account's login is right now. +def login_home(provider: str, registry: dict[str, Any], account: dict[str, Any]) -> Path: + if provider in SEATED: + return primary_home(provider) if account["id"] == registry["seated"] else store_home(provider, account) + return account_home(provider, account) + + # --------------------------------------------------------------- identity @@ -186,7 +209,7 @@ def grok_identity(home: Path) -> dict[str, str]: "accountId": str(login.get("user_id") or ""), "email": str(login.get("email") or ""), "org": "", - "plan": str(settings.get("subscription_tier_display") or ""), + "plan": str((settings if isinstance(settings, dict) else {}).get("subscription_tier_display") or ""), } @@ -198,7 +221,8 @@ def slug(label: str) -> str: def empty_registry(provider: str) -> dict[str, Any]: - return {"active": "main", "switch": "manual", "threshold": DEFAULT_THRESHOLD, "alert": "", "accounts": []} + seated = {"seated": ""} if provider in SEATED else {} + return {"active": "main", "threshold": DEFAULT_THRESHOLD, "alert": "", "held": "", "accounts": []} | seated def primary_entry(provider: str) -> dict[str, Any]: @@ -215,14 +239,15 @@ def normalized(provider: str, data: Any) -> dict[str, Any]: if not any(a.get("primary") for a in accounts): accounts.insert(0, primary_entry(provider)) registry["accounts"] = accounts - if registry["switch"] not in SWITCH_MODES: - registry["switch"] = "manual" try: registry["threshold"] = max(50, min(100, int(registry["threshold"]))) except Exception: registry["threshold"] = DEFAULT_THRESHOLD if not find(registry, registry["active"]): registry["active"] = accounts[0]["id"] + # A registry from before seating has the primary's login in ~/.claude. + if provider in SEATED and not any(a["id"] == registry["seated"] for a in accounts): + registry["seated"] = next(a for a in accounts if a.get("primary"))["id"] return registry @@ -231,6 +256,11 @@ def load(provider: str) -> dict[str, Any]: def save(provider: str, registry: dict[str, Any]) -> None: + # The usage collectors read the registry file directly, and need to know + # where each login is to read its token. + if provider in SEATED: + for account in registry["accounts"]: + account["login"] = str(login_home(provider, registry, account)) path = registry_path(provider) path.parent.mkdir(parents=True, exist_ok=True) os.chmod(path.parent, 0o700) @@ -247,7 +277,7 @@ def save(provider: str, registry: dict[str, Any]) -> None: # Every change is read-modify-write under one lock per provider, so the panel, -# the autoswitch run after each usage update, and a command typed at a prompt +# the limit alert run after each usage update, and a command typed at a prompt # can't interleave and drop each other's edits. class Locked: def __init__(self, provider: str, save_on_exit: bool = True): @@ -298,7 +328,16 @@ def link_shared(provider: str, home: Path) -> None: home.mkdir(parents=True, exist_ok=True) os.chmod(home, 0o700) for name in spec["shared_dirs"]: - (primary / name).mkdir(parents=True, exist_ok=True) + shared = primary / name + # A dangling symlink is the person's own setup, such as a dotfiles link + # whose target hasn't synced yet, so leave it for its target to appear. + # mkdir would fail on it. A link to a file or a loop still fails here. + if shared.is_symlink() and not shared.exists(): + try: + shared.resolve(strict=True) + except FileNotFoundError: + continue + shared.mkdir(parents=True, exist_ok=True) for name in spec["shared_dirs"] + spec["shared_files"]: target = home / name if target.exists() or target.is_symlink(): @@ -350,8 +389,12 @@ def begin(provider: str, label: str = "", owner: int = 0) -> Path: pending.mkdir(parents=True, exist_ok=True) os.chmod(pending.parent, 0o700) home = Path(tempfile.mkdtemp(prefix="login-", dir=str(pending))) - link_shared(provider, home) - write_receipt(home, {"label": label, "owner": owner, "started": process_start(owner) if owner else ""}) + try: + link_shared(provider, home) + write_receipt(home, {"label": label, "owner": owner, "started": process_start(owner) if owner else ""}) + except Exception: + shutil.rmtree(home, ignore_errors=True) + raise return home @@ -366,10 +409,11 @@ def register(provider: str, label: str, pending: Path) -> dict[str, Any]: raise AccountError(tr("omarchy-i18n agents.loginUnfinished", "The login didn't finish, so no account was added.")) with Locked(provider, save_on_exit=False) as registry: + settle(provider, registry) # Each home is asked who it is now, not trusted from when it was added: a # `claude auth login` run by hand in ~/.claude changes the primary. for account in registry["accounts"]: - account.update(identity(provider, account_home(provider, account))) + account.update(identity(provider, login_home(provider, registry, account))) for account in registry["accounts"]: if account.get("accountId") == found["accountId"]: shutil.rmtree(pending, ignore_errors=True) @@ -444,7 +488,7 @@ def recover_home(provider: str, home: Path) -> dict[str, Any] | None: entry = receipt.get("entry") if not isinstance(entry, dict) or entry.get("home") != str(home) or entry.get("id") != home.name: return None - if any(identity(provider, account_home(provider, a))["accountId"] == found["accountId"] for a in registry["accounts"]): + if any(identity(provider, login_home(provider, registry, a))["accountId"] == found["accountId"] for a in registry["accounts"]): # A retry may already have registered this login under another home. shutil.rmtree(home) return None @@ -503,6 +547,10 @@ def rename(provider: str, target: str, label: str) -> dict[str, Any]: account["home"] = str(account_home(provider, account)) if registry["active"] == account["id"]: registry["active"] = new_id + if registry["held"] == account["id"]: + registry["held"] = new_id + if registry.get("seated") == account["id"]: + registry["seated"] = new_id registry["alert"] = "" account["id"] = new_id account["label"] = label @@ -515,12 +563,16 @@ def rename(provider: str, target: str, label: str) -> dict[str, Any]: def refresh(provider: str) -> None: recover(provider) with Locked(provider) as registry: + settle(provider, registry) for account in registry["accounts"]: - account.update(identity(provider, account_home(provider, account))) + account.update(identity(provider, login_home(provider, registry, account))) -def use(provider: str, target: str) -> tuple[dict[str, Any], dict[str, Any]]: +# Makes an account active and, for Claude, moves its login into ~/.claude so +# running sessions follow; says whether they did, and what held them back. +def use(provider: str, target: str) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]: with Locked(provider) as registry: + settle(provider, registry) previous = active(registry) if target == "next": ids = [a["id"] for a in registry["accounts"]] @@ -530,62 +582,412 @@ def use(provider: str, target: str) -> tuple[dict[str, Any], dict[str, Any]]: raise AccountError(f"No {PROVIDERS[provider]['name']} account named {target}") registry["active"] = account["id"] registry["alert"] = "" - if not account.get("primary"): + # Every caller is a person choosing, so nothing is said about how full it is. + registry["held"] = account["id"] + followed = follow(provider, registry, account) + if provider in SEATED: + if not followed["seated"]: + prepare_store(provider, account) + elif not account.get("primary"): link_shared(provider, account_home(provider, account)) - return previous, account + return previous, account, followed -# Whether a running session was started in this home. Removing it would pull -# the login out from under that session, which must never be touched. -def home_in_use(provider: str, home: Path) -> bool: +# The processes started in this home, other than this one. Moving or removing +# its login would pull it out from under them, which must never happen. +def home_users(provider: str, home: Path) -> list[int]: wanted = f"{PROVIDERS[provider]['home_env']}=".encode() resolved = home.resolve() + users = [] for environ in Path("/proc").glob("[0-9]*/environ"): + pid = int(environ.parent.name) + if pid == os.getpid(): + continue try: entries = environ.read_bytes().split(b"\0") except OSError: continue for entry in entries: if entry.startswith(wanted) and Path(entry[len(wanted):].decode(errors="replace")).resolve() == resolved: - return True - return False + users.append(pid) + break + return users + + +# The CLI's processes started as the primary, which name no home: they're +# found by the program they run instead. +def primary_users(provider: str) -> list[int]: + wanted = f"{PROVIDERS[provider]['home_env']}=".encode() + users = [] + for cmdline in Path("/proc").glob("[0-9]*/cmdline"): + pid = int(cmdline.parent.name) + if pid == os.getpid(): + continue + try: + args = cmdline.read_bytes().split(b"\0")[:2] + entries = (cmdline.parent / "environ").read_bytes().split(b"\0") + except OSError: + continue + if not any(arg and Path(arg.decode(errors="replace")).stem == provider for arg in args): + continue + if any(entry.startswith(wanted) and len(entry) > len(wanted) for entry in entries): + continue + users.append(pid) + return users + + +def home_in_use(provider: str, home: Path) -> bool: + return bool(home_users(provider, home)) + + +# ----------------------------------------------------------------- seating + + +def label_of(account: dict[str, Any]) -> str: + return str(account.get("label") or account["id"]) +def oauth(home: Path) -> dict[str, Any]: + login = (read_json(home / ".credentials.json") or {}).get("claudeAiOauth") + return login if isinstance(login, dict) else {} + + +def has_login(home: Path) -> bool: + return bool(oauth(home)) + + +# An account's own home, ready to hold its login or start a session in. The +# primary's is made the first time it's needed, with the primary's settings. +def prepare_store(provider: str, account: dict[str, Any]) -> Path: + home = store_home(provider, account) + fresh = not home.exists() + link_shared(provider, home) + if fresh: + carry_settings(provider, home) + return home + + +# Claude Code's own lock directories, each stale once its mtime is that old: a +# refresh holds /.oauth_refresh.lock and .lock, a config write ~/.claude.json.lock. +def claude_locks(homes: list[Path]) -> list[tuple[Path, float]]: + locks = [] + for home in dict.fromkeys(homes): + locks += [(home / ".oauth_refresh.lock", 60), (Path(f"{home.resolve()}.lock"), 60)] + return locks + [(Path(f"{claude_account_file(primary_home('claude'))}.lock"), 10)] + + +class LockDirs: + def __init__(self, locks: list[tuple[Path, float]], wait: float = 15): + self.locks = locks + self.wait = wait + self.held: list[Path] = [] + + def __enter__(self) -> None: + deadline = time.monotonic() + self.wait + try: + for path, stale in self.locks: + while True: + try: + path.mkdir() + self.held.append(path) + break + except FileExistsError: + pass + try: + if time.time() - path.stat().st_mtime > stale: + path.rmdir() + continue + except FileNotFoundError: + continue + except OSError: + pass + if time.monotonic() > deadline: + raise AccountError("A Claude session is renewing its sign-in. Try again in a moment.") + time.sleep(0.2) + except BaseException: + self.__exit__(None, None, None) + raise + + def __exit__(self, kind, value, traceback) -> None: + for path in reversed(self.held): + try: + path.rmdir() + except OSError: + pass + self.held = [] + + +def write_private(path: Path, text: str) -> None: + # A dotfiles symlink stays a symlink; its target is what's replaced. + path = path.resolve() + fd, tmp = tempfile.mkstemp(prefix=path.name + ".", dir=str(path.parent)) + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + handle.write(text) + os.chmod(tmp, 0o600) + os.replace(tmp, path) + except BaseException: + Path(tmp).unlink(missing_ok=True) + raise + + +# Refuses an account file that exists but doesn't parse: ~/.claude.json holds +# far more than the login, and rewriting it from empty would lose the rest. +def account_config(path: Path) -> dict[str, Any]: + if not path.exists(): + return {} + data = read_json(path) + if not isinstance(data, dict): + raise AccountError(f"{path} can't be read, so no login was moved.") + return data + + +def put_login(home: Path, credentials: str, profile: Any) -> None: + path = claude_account_file(home) + config = account_config(path) + if profile is None: + config.pop("oauthAccount", None) + else: + config["oauthAccount"] = profile + write_private(home / ".credentials.json", credentials) + write_private(path, json.dumps(config, indent=2)) + + +# Swaps the target's login into ~/.claude under Claude's locks, so no session +# refreshes mid-move. Returns the processes holding the target's home, which block it. +def seat(provider: str, registry: dict[str, Any], target: dict[str, Any]) -> list[int]: + if provider not in SEATED or registry["seated"] == target["id"]: + return [] + source = store_home(provider, target) + primary = primary_home(provider) + users = home_users(provider, source) + if users or not has_login(source): + return users + current = find(registry, registry["seated"]) + park = prepare_store(provider, current) + with LockDirs(claude_locks([primary, source, park])): + # A session may have started there while the locks were awaited. + users = home_users(provider, source) + if users: + return users + seated_credentials = (primary / ".credentials.json").read_text(encoding="utf-8") if has_login(primary) else "" + seated_profile = account_config(claude_account_file(primary)).get("oauthAccount") + credentials = (source / ".credentials.json").read_text(encoding="utf-8") + profile = account_config(claude_account_file(source)).get("oauthAccount") + if seated_credentials: + put_login(park, seated_credentials, seated_profile) + try: + put_login(primary, credentials, profile) + except BaseException: + # Half a move would leave ~/.claude's token and profile naming two + # different accounts. The parked copy is cleared by the next settle. + if seated_credentials: + put_login(primary, seated_credentials, seated_profile) + raise + users = home_users(provider, source) + if users: + if seated_credentials: + put_login(primary, seated_credentials, seated_profile) + return users + registry["seated"] = target["id"] + save(provider, registry) + # Only now that ~/.claude has it: a login is kept in one place, since a + # refresh token works once and a copy left here would die at the next one. + (source / ".credentials.json").unlink(missing_ok=True) + return [] + + +# A move cut short leaves ~/.claude's very token in some home as well: that +# account is seated, the copy goes, and ~/.claude takes its profile again. +def settle(provider: str, registry: dict[str, Any]) -> None: + if provider not in SEATED: + return + primary = primary_home(provider) + login = oauth(primary) + holder = next((a for a in registry["accounts"] if login and oauth(store_home(provider, a)) == login), None) + if holder is None: + return + store = store_home(provider, holder) + profile = account_config(claude_account_file(store)).get("oauthAccount") + path = claude_account_file(primary) + config = account_config(path) + if isinstance(profile, dict) and (config.get("oauthAccount") or {}).get("accountUuid") != profile.get("accountUuid"): + with LockDirs(claude_locks([])): + config = account_config(path) + config["oauthAccount"] = profile + write_private(path, json.dumps(config, indent=2)) + # Saved before the copy goes, since the copy is the only other record of + # whose token ~/.claude holds, and the command that called this may fail. + if registry["seated"] != holder["id"]: + registry["seated"] = holder["id"] + save(provider, registry) + if not home_in_use(provider, store): + (store / ".credentials.json").unlink(missing_ok=True) + + +# A Claude account signed in again in a scratch home, installed where its login +# lives under the same locks as a move, and only if it's the same account. +def relogin(provider: str, target: str, pending: Path) -> dict[str, Any]: + pending = pending.resolve() + if provider not in SEATED or pending.parent != (accounts_root() / provider / ".pending").resolve(): + raise AccountError(f"{pending} is not a pending {PROVIDERS[provider]['name']} login") + try: + found = identity(provider, pending) + if not found["accountId"] or not has_login(pending): + raise AccountError(tr("omarchy-i18n agents.signInFailed", "The %1 sign-in didn't finish.", PROVIDERS[provider]["name"])) + with Locked(provider) as registry: + settle(provider, registry) + account = find(registry, target) + if not account: + raise AccountError(f"No {PROVIDERS[provider]['name']} account named {target}") + if account.get("accountId") and account["accountId"] != found["accountId"]: + raise AccountError(tr("omarchy-i18n agents.wrongAccount", "That's %1, not %2. Try again, and sign in as %2.", found["email"] or found["accountId"], label_of(account))) + home = login_home(provider, registry, account) + if home != primary_home(provider): + prepare_store(provider, account) + with LockDirs(claude_locks([home])): + put_login(home, (pending / ".credentials.json").read_text(encoding="utf-8"), account_config(claude_account_file(pending)).get("oauthAccount")) + account.update(identity(provider, home)) + return dict(account) + finally: + shutil.rmtree(pending, ignore_errors=True) + + +def follow(provider: str, registry: dict[str, Any], account: dict[str, Any]) -> dict[str, Any]: + if provider not in SEATED: + return {"seated": False, "moved": False, "holders": []} + before = registry["seated"] + holders = seat(provider, registry, account) + running = label_of(find(registry, registry["seated"])) + return {"seated": registry["seated"] == account["id"], "moved": registry["seated"] != before, "holders": holders, "running": running} + + +def refuse_in_use(provider: str, home: Path, account: dict[str, Any]) -> None: + if home_in_use(provider, home): + raise AccountError(f"A running {PROVIDERS[provider]['name']} session uses {label_of(account)}. Quit it first, then remove the account.") + + +# Only an account's own directory goes. Its links point into the primary home, +# and rmtree removes a link without following it. +def remove_home(provider: str, home: Path) -> None: + if home.resolve().parent == (accounts_root() / provider).resolve(): + shutil.rmtree(home, ignore_errors=True) + + +# The files a login is, in a home of Codex or Grok; Claude's is its +# credentials plus the profile in its account file. +LOGIN_FILES = {"codex": ["auth.json"], "grok": ["auth.json", "settings_cache.json"]} + + +# Signs a home out here without logging out, which would revoke the sign-in +# everywhere else it's used too. +def forget_login(provider: str, home: Path) -> None: + if provider == "claude": + with LockDirs(claude_locks([home])): + # Read first: an account file that can't be read stops this before the + # credentials go. + path = claude_account_file(home) + config = account_config(path) + (home / ".credentials.json").unlink(missing_ok=True) + if config.pop("oauthAccount", None) is not None: + write_private(path, json.dumps(config, indent=2)) + else: + for name in LOGIN_FILES[provider]: + (home / name).unlink(missing_ok=True) + + +# The primary home is shared by every account, so it stays: the account taking +# over as primary puts its login in it. Returns the homes to delete once the +# registry is saved, so a save that fails leaves every login somewhere a +# retry finds it. +def promote(provider: str, registry: dict[str, Any], old: dict[str, Any], successor: dict[str, Any]) -> list[Path]: + own = account_home(provider, successor) + refuse_in_use(provider, own, successor) + if provider in SEATED: + # Seated already, so its login is in ~/.claude and the old primary's in + # the store primaries keep theirs in, which goes with it. + parked = store_home(provider, old) + refuse_in_use(provider, parked, old) + gone = [parked, own] + else: + primary = primary_home(provider) + refuse_in_use(provider, primary, old) + if primary_users(provider): + raise AccountError(f"A running {PROVIDERS[provider]['name']} session uses {label_of(old)}. Quit it first, then remove the account.") + # Copied, not moved: its own home keeps the login until the registry + # says the primary home holds it. + for name in LOGIN_FILES[provider]: + target = (primary / name).resolve() + if (own / name).exists(): + staged = target.with_name(f".{target.name}.omarchy") + shutil.copy2(own / name, staged) + os.replace(staged, target) + else: + target.unlink(missing_ok=True) + gone = [own] + successor.update({"home": "", "primary": True}) + return gone + + +# Forgets an account. One that sessions use hands them to another account +# first, the primary hands that role on, and the only one is signed out here. +# The account comes back with `last` saying whether it was the only one. def remove(provider: str, target: str) -> dict[str, Any]: - with Locked(provider) as registry: + with Locked(provider, save_on_exit=False) as registry: + settle(provider, registry) account = find(registry, target) if not account: raise AccountError(f"No {PROVIDERS[provider]['name']} account named {target}") + others = [a for a in registry["accounts"] if a["id"] != account["id"]] + if not others: + # The only account is the primary, its login in the primary home. + home = primary_home(provider) + forget_login(provider, home) + account.update(identity(provider, home)) + registry.update({"alert": "", "held": ""}) + save(provider, registry) + return dict(account, last=True) + + # The account seated in ~/.claude takes over, so no login moves twice; + # else the primary, else the next one. + successor = (next((a for a in others if provider in SEATED and a["id"] == registry["seated"]), None) + or next((a for a in others if a.get("primary")), None) or others[0]) + if provider in SEATED and registry["seated"] == account["id"]: + holders = seat(provider, registry, successor) + if registry["seated"] == account["id"]: + if holders: + raise AccountError(f"A running {PROVIDERS[provider]['name']} session uses {label_of(successor)}, so sessions can't move to it. Quit it first, then remove {label_of(account)}.") + raise AccountError(f"{label_of(successor)} isn't signed in, so sessions can't move to it. Sign it in again first, then remove {label_of(account)}.") + if account.get("primary"): - raise AccountError(f"{account['label']} is the login in {primary_home(provider)}; it can't be removed here.") - home = account_home(provider, account) - if home_in_use(provider, home): - raise AccountError(f"A running {PROVIDERS[provider]['name']} session uses {account['label']}. Quit it first, then remove the account.") - # Only the account's own directory goes. Its links point into the primary - # home, and rmtree removes a link without following it. - if home.resolve().parent == (accounts_root() / provider).resolve(): - shutil.rmtree(home, ignore_errors=True) - registry["accounts"] = [a for a in registry["accounts"] if a["id"] != account["id"]] + gone = promote(provider, registry, account, successor) + else: + home = account_home(provider, account) + refuse_in_use(provider, home, account) + gone = [home] + registry["accounts"] = others if registry["active"] == account["id"]: - registry["active"] = registry["accounts"][0]["id"] - return account + registry["active"] = successor["id"] + registry["alert"] = "" + if registry["held"] == account["id"]: + registry["held"] = "" + save(provider, registry) + for home in gone: + remove_home(provider, home) + return dict(account, last=False) -def set_mode(provider: str, mode: str, threshold: str | None) -> dict[str, Any]: - if mode not in SWITCH_MODES: - raise AccountError("Switch mode is manual or auto") +def set_threshold(provider: str, threshold: str) -> dict[str, Any]: with Locked(provider) as registry: - registry["switch"] = mode - if threshold is not None: - try: - registry["threshold"] = max(50, min(100, int(threshold))) - except ValueError: - raise AccountError("The threshold is a percentage between 50 and 100") + try: + registry["threshold"] = max(50, min(100, int(threshold))) + except ValueError: + raise AccountError("The threshold is a percentage between 50 and 100") registry["alert"] = "" return dict(registry) -# ------------------------------------------------------------- autoswitch +# ------------------------------------------------------------ limit alerts def window_open(limit: dict[str, Any], now: dt.datetime) -> bool: @@ -661,13 +1063,15 @@ def duration(delta: dt.timedelta) -> str: return tr("omarchy-i18n battery.durationMinutes", "%1m", minutes) -# The whole switching policy, with no I/O: given the registry and the per -# account limits from the usage record, what should happen. Returns None when -# nothing should, or {"action": "switch"|"notify"|"exhausted", ...}. +# The whole alert policy, with no I/O: given the registry and the per +# account limits from the usage record, what should be said. Returns None when +# nothing should, or {"action": "notify"|"exhausted"|"clear", ...}. The +# account never changes here: a notification offers the switch and a person +# takes it. # -# Only the active account crossing the threshold starts anything, so auto -# mode never flaps back to an account that just reset. `alert` remembers the -# last thing said, so a shell restart or the next refresh doesn't repeat it. +# Only the active account crossing the threshold starts anything. `alert` +# remembers the last thing said, so a shell restart or the next refresh +# doesn't repeat it. # # Numbers kept from an earlier check may be out of date, but a parked account's # sign-in lapses within hours and can't be checked again until a session runs @@ -675,12 +1079,19 @@ def duration(delta: dt.timedelta) -> str: # checked just now wins, but room comes first. An account within 15 points of # the threshold (where the panel starts checking more often) is near its limit # however fresh its numbers are. +# +# An account chosen by hand is held there however full it is, and nothing is +# offered or announced about it, until a fresh check sees it under the +# threshold again; from then on it is announced like any other. def decide(registry: dict[str, Any], usage: dict[str, Any], now: dt.datetime, stale: frozenset[str] = frozenset()) -> dict[str, Any] | None: threshold = float(registry["threshold"]) current = active(registry) current_peak = peak(usage.get(current["id"]), now) if current_peak is None or current_peak < threshold: - return {"action": "clear"} if registry.get("alert") else None + release = current_peak is not None and current["id"] not in stale and bool(registry.get("held")) + return {"action": "clear", "release": release} if registry.get("alert") or release else None + if registry.get("held") == current["id"]: + return None candidates = [] for account in registry["accounts"]: @@ -695,11 +1106,10 @@ def decide(registry: dict[str, Any], usage: dict[str, Any], now: dt.datetime, st if candidates: _, _, level, _, target = candidates[0] - action = "switch" if registry["switch"] == "auto" else "notify" - alert = f"{action}:{current['id']}:{target['id']}" + alert = f"notify:{current['id']}:{target['id']}" if registry.get("alert") == alert: return None - return {"action": action, "alert": alert, "from": current, "to": target, "fromPeak": current_peak, "toPeak": level} + return {"action": "notify", "alert": alert, "from": current, "to": target, "fromPeak": current_peak, "toPeak": level} alert = f"exhausted:{current['id']}" if registry.get("alert") == alert or len(registry["accounts"]) < 2: @@ -756,20 +1166,44 @@ def notify(title: str, body: str, action: list[str] | None = None) -> None: subprocess.run(command, check=False) -# Returns True when the active account changed. -def autoswitch(provider: str, now: dt.datetime | None = None) -> bool: +# A switch held back by sessions running in the account's own home completes +# once they've gone, so running sessions in ~/.claude move to the chosen account. +def catch_up(provider: str, registry: dict[str, Any]) -> None: + if provider not in SEATED: + return + settle(provider, registry) + target = active(registry) + if registry["seated"] == target["id"]: + return + previous = find(registry, registry["seated"]) + try: + moved = follow(provider, registry, target)["moved"] + except AccountError: + return + if moved: + notify( + tr("omarchy-i18n agents.sessionsUse", "%1 sessions now use %2", PROVIDERS[provider]["name"], label_of(target)), + tr("omarchy-i18n agents.runningCaughtUp", "Running sessions on %1 moved over too.", label_of(previous)), + ) + + +def alert(provider: str, now: dt.datetime | None = None) -> None: now = now or dt.datetime.now(dt.timezone.utc) name = PROVIDERS[provider]["name"] with Locked(provider) as registry: if len(registry["accounts"]) < 2: - return False + registry["held"] = "" + return + catch_up(provider, registry) usage, stale = usage_by_account(provider) decision = decide(registry, usage, now, stale) if decision is None: - return False + return if decision["action"] == "clear": registry["alert"] = "" - return False + if decision["release"]: + registry["held"] = "" + return registry["alert"] = decision["alert"] source = decision["from"] @@ -781,22 +1215,15 @@ def autoswitch(provider: str, now: dt.datetime | None = None) -> bool: else: body = tr("omarchy-i18n agents.stayingOn", "Staying on %1.", source["label"]) notify(tr("omarchy-i18n agents.allOver", "All %1 accounts are over %2%", name, threshold), body) - return False + return target = decision["to"] headline = tr("omarchy-i18n agents.atLimit", "%1 is at %2% of a %3 limit", source["label"], round(decision["fromPeak"]), name) - if decision["action"] == "switch": - registry["active"] = target["id"] - if not target.get("primary"): - link_shared(provider, account_home(provider, target)) - notify(headline, tr("omarchy-i18n agents.switchedBody", "New %1 sessions now use %2 (%3%).\nRunning sessions stay on %4.", name, target["label"], round(decision["toPeak"]), source["label"])) - return True notify( headline, tr("omarchy-i18n agents.offerSwitch", "%1 is at %2%. Click to switch new sessions to it.", target["label"], round(decision["toPeak"])), ["omarchy-agent-account-use", provider, target["id"]], ) - return False # --------------------------------------------------------------------- CLI @@ -812,17 +1239,16 @@ def summary(provider: str, registry: dict[str, Any]) -> dict[str, Any]: # Identity is re-read from each home rather than trusted from the registry: # a `claude auth login` run by hand in a home changes who it is. for account in registry["accounts"]: - account.update(identity(provider, account_home(provider, account))) + account.update(identity(provider, login_home(provider, registry, account))) return { "provider": provider, "name": PROVIDERS[provider]["name"], "active": registry["active"], - "switch": registry["switch"], "threshold": registry["threshold"], "accounts": [ {key: account.get(key, "") for key in ("id", "label", "email", "org", "plan", "primary")} | { - "home": str(account_home(provider, account)), + "home": str(login_home(provider, registry, account)), "active": account["id"] == registry["active"], "signedIn": bool(account.get("accountId")), } @@ -844,18 +1270,25 @@ def main(argv: list[str]) -> int: providers = [provider_arg(args)] if args else list(PROVIDERS) print(json.dumps([summary(p, load(p)) for p in providers])) elif command == "home": - # Empty for the primary, so launching it needs no environment at all. + # Empty for the primary home, so launching there needs no environment + # at all. A Claude account starts in its own home only while its login + # couldn't move into ~/.claude. provider = provider_arg(args) registry = read_json(registry_path(provider)) if registry: - account = active(normalized(provider, registry)) - if not account.get("primary"): + registry = normalized(provider, registry) + account = active(registry) + if provider in SEATED: + if account["id"] != registry["seated"]: + print(store_home(provider, account)) + elif not account.get("primary"): print(account_home(provider, account)) elif command == "homes": + # Where each account's login is now, for signing it in again there. provider = provider_arg(args) registry = load(provider) for account in registry["accounts"]: - print("\t".join([account["id"], str(account_home(provider, account)), "1" if account["id"] == registry["active"] else "0"])) + print("\t".join([account["id"], str(login_home(provider, registry, account)), "1" if account["id"] == registry["active"] else "0", "1" if account.get("primary") else "0"])) elif command == "refresh": for provider in ([provider_arg(args)] if args else list(PROVIDERS)): if registry_path(provider).exists() or (accounts_root() / provider).is_dir(): @@ -871,8 +1304,13 @@ def main(argv: list[str]) -> int: print(json.dumps(register(provider, args[1], Path(args[2])))) elif command == "use": provider = provider_arg(args) - previous, account = use(provider, args[1] if len(args) > 1 else "next") - print(json.dumps({"previous": previous, "active": account})) + previous, account, followed = use(provider, args[1] if len(args) > 1 else "next") + print(json.dumps({"previous": previous, "active": account} | followed)) + elif command == "relogin": + provider = provider_arg(args) + if len(args) < 3: + raise AccountError("relogin ") + print(json.dumps(relogin(provider, args[1], Path(args[2])))) elif command == "remove": provider = provider_arg(args) if len(args) < 2: @@ -883,20 +1321,18 @@ def main(argv: list[str]) -> int: if len(args) < 3: raise AccountError("rename