diff --git a/.github/workflows/app-ffi-release.yml b/.github/workflows/app-ffi-release.yml index d336d269a9e6..c2c6aec56c3a 100644 --- a/.github/workflows/app-ffi-release.yml +++ b/.github/workflows/app-ffi-release.yml @@ -13,17 +13,20 @@ # ever points at an FFI tag. scripts/cmux-next/check-app-ffi-pin.sh fails CI # when the FFI sources change without a new pin. # -# UNPROVEN (2026-10-05): GITHUB_TOKEN got HTTP 403 creating the first tag -# (run 37272232472). The publish job therefore does not try when workflow -# files changed since the last FFI tag, and a person publishes from the -# artifact. Whether the token can create the tag after a source-only change -# has not been seen yet; the first real FFI source change proves or disproves it. +# TOKEN: GITHUB_TOKEN may not create a cmux-app-ffi-* tag (run 37272232472, +# HTTP 403): ruleset 24624526 admits only admins and the FFI release App +# (manaflow-cmux-ffi-release, used for nothing else). The publish job runs in +# the `ffi-release` environment (deployment policy: feat-cmux-next only), +# which holds the App's CMUX_FFI_RELEASE_APP_ID and CMUX_FFI_RELEASE_APP_KEY. It mints a token for this +# repository only, with contents:write, plus workflows:write only when workflow +# files changed since the last FFI tag, and only the release create uses it. +# Ruleset 24624527 keeps the tags immutable for everyone, the App included. # # FAIL-LOUD: the publish job never reports success without the release. When -# it cannot create it (workflow files changed, an HTTP 403, or a create that -# publishes nothing, as in run 37556534995), it fails with "Publish by hand" -# and the exact commands (HAND_PUBLISH). Publishing by hand, with its checks, -# is the only other path: docs/ci/app-ffi-release.md is the runbook. +# it cannot create it (no App token, an HTTP 403, or a create that publishes +# nothing, as in run 37556534995), it fails with "Publish by hand" and the +# exact commands (HAND_PUBLISH). Publishing by hand, with its checks, is the +# only other path: docs/ci/app-ffi-release.md is the runbook. # # The push paths are the FFI inputs that scripts/cmux-next/check-app-ffi-pin.sh # derives from the Cargo path dependencies of cmux-app-ffi (--list-inputs); @@ -70,10 +73,9 @@ jobs: persist-credentials: false fetch-depth: 0 - # GITHUB_TOKEN may not create a tag whose commit range carries - # workflow-file changes (run 37272232472: HTTP 403 with contents:write). - # Measure the range from the last published FFI tag; the publish job - # skips with a notice when it touches .github/workflows. + # A tag whose commit range carries workflow-file changes needs a token + # with workflows:write. Measure the range from the last published FFI + # tag; the publish job asks the App for workflows:write only then. - name: Workflow files changed since the last FFI release id: workflow-delta shell: bash @@ -155,8 +157,10 @@ jobs: "$smoke/smoke-arm64" dist="$RUNNER_TEMP/dist" rm -rf "$dist"; mkdir -p "$dist" - # Stable zip bytes for a rerun of the same build. - find "$xcf" -exec touch -t 198001010000 {} + + # Source commit time on every file and directory: stable zip bytes + # for a rerun of the same commit, and new header mtimes after a pin + # change so a warm tree rebuilds the Clang module (cx-vqwl). + bash scripts/cmux-next/stamp-app-ffi-mtimes.sh "$xcf" "$GITHUB_SHA" (cd "$OUT" && ditto -c -k --keepParent CCmuxAppFFI.xcframework "$dist/CCmuxAppFFI.xcframework.zip") archive="$dist/CCmuxAppFFI.xcframework.zip" checksum="$(shasum -a 256 "$archive" | awk '{print $1}')" @@ -300,8 +304,12 @@ jobs: if: github.ref == 'refs/heads/feat-cmux-next' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') runs-on: ${{ github.repository_owner != 'manaflow-ai' && 'ubuntu-24.04' || vars.LINUX_RUNNER || 'blacksmith-4vcpu-ubuntu-2404' }} timeout-minutes: 15 + # Holds the FFI release App credentials; its deployment policy admits only + # feat-cmux-next. GITHUB_TOKEN stays read-only: the release create uses + # the App token below and nothing else does. + environment: ffi-release permissions: - contents: write + contents: read env: # What a maintainer runs when this job cannot publish: download this # run's artifact, check it, create the prerelease (never latest), then @@ -322,19 +330,33 @@ jobs: name: CCmuxAppFFI.xcframework path: assets - - name: Workflow files changed, so publish by hand + # Exactly one of these two runs. The token is for this repository only. + - name: Mint release App token + id: app-token + if: needs.build.outputs.workflow_changed != 'true' + uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 + with: + app-id: ${{ secrets.CMUX_FFI_RELEASE_APP_ID }} + private-key: ${{ secrets.CMUX_FFI_RELEASE_APP_KEY }} + owner: ${{ github.repository_owner }} + repositories: ${{ github.event.repository.name }} + permission-contents: write + + - name: Mint release App token (workflow files changed) + id: app-token-workflows if: needs.build.outputs.workflow_changed == 'true' - env: - TAG: ${{ needs.build.outputs.tag }} - shell: bash - run: | - echo "::error title=Publish by hand::Workflow files changed since the last FFI release, and GITHUB_TOKEN cannot create tag $TAG over them. Publish by hand: $HAND_PUBLISH" - exit 1 + uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 + with: + app-id: ${{ secrets.CMUX_FFI_RELEASE_APP_ID }} + private-key: ${{ secrets.CMUX_FFI_RELEASE_APP_KEY }} + owner: ${{ github.repository_owner }} + repositories: ${{ github.event.repository.name }} + permission-contents: write + permission-workflows: write - name: Create the release (never overwrite) - if: needs.build.outputs.workflow_changed != 'true' env: - GH_TOKEN: ${{ github.token }} + GH_TOKEN: ${{ steps.app-token.outputs.token || steps.app-token-workflows.outputs.token }} GH_REPO: ${{ github.repository }} TAG: ${{ needs.build.outputs.tag }} CHECKSUM: ${{ needs.build.outputs.checksum }} @@ -358,13 +380,12 @@ jobs: assets/CCmuxAppFFI.xcframework.zip.sha256 \ assets/SHA256SUMS assets/SOURCE_SHA \ --target "$GITHUB_SHA" --title "$TAG" --notes "$notes" --prerelease --latest=false; then - echo "::error title=Publish by hand::GITHUB_TOKEN could not create release $TAG (see the gh error above, for example HTTP 403). Publish by hand: $HAND_PUBLISH" + echo "::error title=Publish by hand::the release App token could not create release $TAG (see the gh error above, for example HTTP 403). Publish by hand: $HAND_PUBLISH" exit 1 fi echo "release: https://github.com/$GH_REPO/releases/tag/$TAG" - name: The latest release is not an FFI tag - if: needs.build.outputs.workflow_changed != 'true' env: GH_TOKEN: ${{ github.token }} GH_REPO: ${{ github.repository }} @@ -379,7 +400,6 @@ jobs: fi - name: Anonymous download matches the checksum - if: needs.build.outputs.workflow_changed != 'true' env: GH_REPO: ${{ github.repository }} TAG: ${{ needs.build.outputs.tag }} diff --git a/.github/workflows/backend.yml b/.github/workflows/backend.yml index 804aae469fdc..cc3d78c73138 100644 --- a/.github/workflows/backend.yml +++ b/.github/workflows/backend.yml @@ -94,6 +94,9 @@ jobs: - name: Migration lint (parsed SQL) and lint tests working-directory: backend/db run: bun migrate.ts --lint && bun test test + - name: Release rails migration lint (expand-only, numbering, hash lock) + working-directory: scripts/cmux-next/release + run: bun install --frozen-lockfile && bun lint.ts --tree backend - name: Migrations apply from zero (scratch Postgres) working-directory: backend/db env: @@ -253,6 +256,8 @@ jobs: fi (cd backend && bun install --frozen-lockfile >/dev/null) (cd backend/db && bun migrate.ts --lint) || errors=1 + # Release rails: the hash lock and the previous head's files and lock entries (plans/cmux-next/release-rails.md). + (cd scripts/cmux-next/release && bun install --frozen-lockfile >/dev/null && bun lint.ts --tree backend --base "${BEFORE:-origin/feat-cmux-next}") || errors=1 exit "$errors" deploy-staging: @@ -290,12 +295,29 @@ jobs: exit 1 fi echo "$out" - - name: Deploy API Worker + # deploy-worker.sh records the serving version, deploys, smokes apps/api/release-smoke.json and + # runs `wrangler rollback` on red (plans/cmux-next/release-rails.md). + - name: Deploy API Worker (smoke, rollback on red) + id: deploy-api env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} CMUX_NEXT_PG_MIGRATOR_URL: ${{ secrets.CMUX_NEXT_PG_MIGRATOR_URL }} JWT_PRIVATE_JWK: ${{ secrets.JWT_PRIVATE_JWK }} + CMUX_RELEASE_CHANGED_SINCE: ${{ github.event.before }} + CMUX_RELEASE_VERIFY_STEP: "1" run: bash scripts/deploy-worker.sh staging + # Separate step so it also runs when the deploy step failed, was cancelled or timed out. + - name: Smoke the API Worker; roll back on red + if: ${{ always() && steps.deploy-api.outcome != 'skipped' }} + working-directory: backend/apps/api + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: 0c1675e0def6de1ab3a50a4e17dc5656 + BEFORE: ${{ github.event.before }} + run: >- + bun ../../../scripts/cmux-next/release/worker-release.ts verify --worker cmux-api-staging --url https://cloud-api-staging.cmux.dev + --routes release-smoke.json --previous-file "$RUNNER_TEMP/cmux-api-previous-version" + --changed-since "$BEFORE" --source-dir . --wrangler ./node_modules/.bin/wrangler - name: Deploy dashboard (console-staging.cmux.dev) working-directory: backend/apps/dashboard env: @@ -324,13 +346,28 @@ jobs: with: node-version: "24" - run: bun install --frozen-lockfile - - name: Deploy API Worker (refuses if production lacks a migration) + - name: Deploy API Worker (refuses if production lacks a migration; smoke, rollback on red) + id: deploy-api env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} CMUX_NEXT_PG_MIGRATOR_URL: ${{ secrets.CMUX_NEXT_PG_MIGRATOR_URL }} JWT_PRIVATE_JWK: ${{ secrets.JWT_PRIVATE_JWK }} CMUX_NEXT_DEPLOY_PRODUCTION: "1" + CMUX_RELEASE_CHANGED_SINCE: ${{ github.event.before }} + CMUX_RELEASE_VERIFY_STEP: "1" run: bash scripts/deploy-worker.sh production + # Separate step so it also runs when the deploy step failed, was cancelled or timed out. + - name: Smoke the API Worker; roll back on red + if: ${{ always() && steps.deploy-api.outcome != 'skipped' }} + working-directory: backend/apps/api + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: 0c1675e0def6de1ab3a50a4e17dc5656 + BEFORE: ${{ github.event.before }} + run: >- + bun ../../../scripts/cmux-next/release/worker-release.ts verify --worker cmux-api --url https://cloud-api.cmux.dev + --routes release-smoke.json --previous-file "$RUNNER_TEMP/cmux-api-previous-version" + --changed-since "$BEFORE" --source-dir . --wrangler ./node_modules/.bin/wrangler - name: Deploy dashboard (console.cmux.dev) working-directory: backend/apps/dashboard env: diff --git a/.github/workflows/cmux-next.yml b/.github/workflows/cmux-next.yml index f660698581f5..ab935d1a84c4 100644 --- a/.github/workflows/cmux-next.yml +++ b/.github/workflows/cmux-next.yml @@ -92,6 +92,7 @@ on: - Resources/Localizable.xcstrings - web/** - Resources/InfoPlist.xcstrings + - Resources/bin/** - scripts/cmux-next/check-*.sh - scripts/cmux-next/lib/** - scripts/cmux-next/clear-stale-scheme-build-state.sh @@ -105,6 +106,7 @@ on: - scripts/cmux-next/pin-cmux-tui.sh - scripts/cmux-next/request-nightly-next.sh - scripts/cmux-next/tests/** + - scripts/cmux-next/herdr-sync.py - scripts/cmux-next/bundle-ghostty-resources.sh - Resources/ghostty/** - Resources/terminfo-overlay/** @@ -202,6 +204,7 @@ on: - Resources/Localizable.xcstrings - web/** - Resources/InfoPlist.xcstrings + - Resources/bin/** - scripts/cmux-next/check-*.sh - scripts/cmux-next/lib/** - scripts/cmux-next/clear-stale-scheme-build-state.sh @@ -215,6 +218,7 @@ on: - scripts/cmux-next/pin-cmux-tui.sh - scripts/cmux-next/request-nightly-next.sh - scripts/cmux-next/tests/** + - scripts/cmux-next/herdr-sync.py - scripts/cmux-next/bundle-ghostty-resources.sh - Resources/ghostty/** - Resources/terminfo-overlay/** @@ -722,6 +726,7 @@ jobs: bash scripts/cmux-next/tests/embed-cef.test.sh bash scripts/cmux-next/tests/check-app-ffi-pin.test.sh bash scripts/cmux-next/tests/app-ffi-release-paths.test.sh + bash scripts/cmux-next/tests/stamp-app-ffi-mtimes.test.sh bash scripts/cmux-next/tests/daemon-capabilities-fresh.test.sh bash scripts/cmux-next/tests/crash-ratchet-tracked.test.sh bash scripts/cmux-next/tests/crash-ratchet-v2.test.sh @@ -743,6 +748,9 @@ jobs: bash scripts/cmux-next/tests/rust-daemon-miss-builds.test.sh bash scripts/cmux-next/tests/build-cmux-tui-client.test.sh bash scripts/cmux-next/tests/cef-manifest-r2.test.sh + # The herdr-derived agent plugin's vendored manifests match their pin. + python3 -I scripts/cmux-next/herdr-sync.py check + python3 -I scripts/cmux-next/tests/test_herdr_sync.py bash scripts/cef/tests/test-embedder-step.test.sh # The app's Ghostty shell integration comes from ghostty-next (the diff --git a/.github/workflows/cmux-vm.yml b/.github/workflows/cmux-vm.yml index f3d8edca851e..b8ce33e3f017 100644 --- a/.github/workflows/cmux-vm.yml +++ b/.github/workflows/cmux-vm.yml @@ -15,6 +15,11 @@ # feat-cmux-next deploys staging while cmux VM lands there first (Lawrence, # 2026-10-07: "into feat-cmux-next is all we want rn, no main"). # +# deploy-staging refuses a commit whose migrations staging lacks (db-release.ts +# gate reads the database), records the serving version, deploys, smokes +# health and changed routes (release-smoke.json) and runs `wrangler rollback` +# to the recorded version on red (plans/cmux-next/release-rails.md). +# # smoke-staging runs scripts/smoke.ts against the staging Worker after each # staging deploy: create, exec, pause and delete by exact id on the test # tenant. It needs the cmux-vm-staging environment variable @@ -100,6 +105,21 @@ jobs: - id: install run: bun install --frozen-lockfile # Every check below runs whenever install succeeded, so one run reports all failures. + - name: Migration lint (expand-only, schema cmux_vm only, numbering, hash lock) + if: ${{ !cancelled() }} + working-directory: scripts/cmux-next/release + env: + BASE: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }} + run: | + bun install --frozen-lockfile + # A new branch (all-zero BEFORE) lints against origin/feat-cmux-next; a base that cannot be fetched fails. + if [ -z "$BASE" ] || [[ "$BASE" =~ ^0+$ ]]; then + git fetch --quiet --no-tags --depth=1 origin feat-cmux-next || { echo "::error title=Migration lint::cannot fetch origin/feat-cmux-next"; exit 1; } + BASE="$(git rev-parse FETCH_HEAD)" + else + git fetch --quiet --no-tags --depth=1 origin "$BASE" || { echo "::error title=Migration lint::cannot fetch the base $BASE; refusing to lint without it"; exit 1; } + fi + bun lint.ts --tree cmux-vm --base "$BASE" - name: Typecheck (includes compile-time proof misuse cases) if: ${{ !cancelled() && steps.install.outcome == 'success' }} run: bun run typecheck @@ -274,7 +294,7 @@ jobs: (github.event_name == 'workflow_dispatch' && inputs.action == 'deploy-staging') needs: check runs-on: ${{ github.repository_owner != 'manaflow-ai' && 'ubuntu-24.04' || github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && 'blacksmith-4vcpu-ubuntu-2404' || vars.LINUX_RUNNER || 'blacksmith-4vcpu-ubuntu-2404' }} - timeout-minutes: 10 + timeout-minutes: 25 environment: cmux-vm-staging concurrency: group: cmux-vm-deploy-staging @@ -310,7 +330,27 @@ jobs: node-version: "24" - run: bun install --frozen-lockfile if: steps.gate.outputs.enabled == 'true' + - name: Install the release rails + if: steps.gate.outputs.enabled == 'true' + working-directory: scripts/cmux-next/release + run: bun install --frozen-lockfile + # Deploy ordering (plans/cmux-next/release-rails.md): read the staging database and refuse a + # commit whose migrations are not applied there, before anything ships. On 2026-10-07 a push + # ran ahead of 0008 and every Stack webhook answered 503. + - name: Deploy ordering gate (staging has every migration this commit needs) + if: steps.gate.outputs.enabled == 'true' + working-directory: scripts/cmux-next/release + env: + CMUX_VM_DATABASE_URL: ${{ secrets.CMUX_VM_DATABASE_URL }} + run: bun db-release.ts gate --tree cmux-vm --target staging --url-env CMUX_VM_DATABASE_URL + - name: Record the serving version (the rollback target) + if: steps.gate.outputs.enabled == 'true' + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + run: bun ../../scripts/cmux-next/release/worker-release.ts previous --worker cmux-vm-staging --wrangler node_modules/.bin/wrangler --out "$RUNNER_TEMP/cmux-vm-previous-version" - name: Deploy and set secrets + id: deploy if: steps.gate.outputs.enabled == 'true' env: TARGET: staging @@ -321,6 +361,21 @@ jobs: CMUX_VM_STACK_SECRET_SERVER_KEY: ${{ secrets.CMUX_VM_STACK_SECRET_SERVER_KEY }} CMUX_VM_DATABASE_URL: ${{ secrets.CMUX_VM_DATABASE_URL }} run: bash scripts/deploy.sh + # Runs whenever the deploy step started, also when it failed half way (deploy.sh deploys, then + # sets secrets: a failed `secret bulk` leaves a version that answers 503 "not configured"), and + # on a cancel or timeout (always()). + - name: Smoke health and changed routes; roll back on red + if: ${{ always() && steps.gate.outputs.enabled == 'true' && steps.deploy.outcome != 'skipped' }} + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + URL: ${{ vars.CMUX_VM_STAGING_URL }} + BEFORE: ${{ github.event.before }} + run: >- + bun ../../scripts/cmux-next/release/worker-release.ts verify --worker cmux-vm-staging + --url "${URL:-https://vm-staging.cmux.dev}" --routes release-smoke.json + --previous-file "$RUNNER_TEMP/cmux-vm-previous-version" --changed-since "$BEFORE" --source-dir . + --wrangler node_modules/.bin/wrangler smoke-staging: if: >- diff --git a/.github/workflows/herdr-upstream-drift.yml b/.github/workflows/herdr-upstream-drift.yml new file mode 100644 index 000000000000..554790c97250 --- /dev/null +++ b/.github/workflows/herdr-upstream-drift.yml @@ -0,0 +1,75 @@ +# Reports when upstream herdr (https://github.com/ogulcancelik/herdr, Apache-2.0) +# changes the agent-detection manifests or the detector engine sources that the +# cmux agent screen-detection plugin vendors and adapts +# (cmux-tui/bindings/examples/rust-agent-screen-detection, pin HERDR_UPSTREAM.toml). +# +# It checks out feat-cmux-next explicitly, shallow-clones the herdr tip from +# public sources (no token), and runs `herdr-sync.py drift`. On drift it opens +# or updates ONE issue titled "herdr upstream drift" with the summary. It never +# opens a pull request: taking the change means running `herdr-sync.py sync`, +# porting engine changes by hand and updating the attribution notes. +# +# Scheduled workflows run only from the default branch (main). Until this file +# is on main, the schedule does not fire; run it with workflow_dispatch. + +name: herdr upstream drift + +on: + schedule: + - cron: "41 7 * * *" + workflow_dispatch: + +concurrency: + group: herdr-upstream-drift + cancel-in-progress: false + +permissions: + contents: read + +jobs: + drift: + if: github.repository_owner == 'manaflow-ai' + runs-on: ${{ github.repository_owner != 'manaflow-ai' && 'ubuntu-24.04' || 'blacksmith-2vcpu-ubuntu-2404' }} + timeout-minutes: 10 + permissions: + contents: read + issues: write + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + ref: feat-cmux-next + persist-credentials: false + - name: Clone the herdr tip + run: | + set -euo pipefail + git clone --filter=blob:none https://github.com/ogulcancelik/herdr.git "$RUNNER_TEMP/herdr" + git -C "$RUNNER_TEMP/herdr" log -1 --format='herdr tip %H %cs %s' + - name: Compare with the pin + id: drift + run: | + set -uo pipefail + python3 -I scripts/cmux-next/herdr-sync.py drift \ + --herdr "$RUNNER_TEMP/herdr" --rev HEAD \ + --summary-out "$RUNNER_TEMP/herdr-drift.md" + status=$? + case "$status" in + 0) echo "result=clean" >> "$GITHUB_OUTPUT" ;; + 1) echo "result=drift" >> "$GITHUB_OUTPUT" ;; + *) exit "$status" ;; + esac + - name: Open or update the drift issue + if: steps.drift.outputs.result == 'drift' + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + run: | + set -euo pipefail + title="herdr upstream drift" + number="$(gh issue list --state open --search "\"$title\" in:title" --json number,title \ + --jq "map(select(.title == \"$title\")) | first | .number // empty")" + if [ -n "$number" ]; then + gh issue edit "$number" --body-file "$RUNNER_TEMP/herdr-drift.md" + echo "updated issue #$number" + else + gh issue create --title "$title" --body-file "$RUNNER_TEMP/herdr-drift.md" + fi diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 4846d5deef21..5c11d3eb7c0e 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -2451,13 +2451,14 @@ jobs: - name: Notarize app ticket through final DMG id: notarize-nightly if: needs.decide.outputs.fast_build != 'true' && needs.decide.outputs.notary_paused != 'true' - # Published nightly-next waits at most 20m (usually a few minutes): + # Every track waits at most 40m (usually a few minutes; three + # nightly-next builds in a row outlasted 20m). On published nightly-next # an Accepted build is stapled and published by this run, and one still - # in Apple's queue is handed to the next nightly-next run through the - # recovery artifact below. Private nightly/RC paths keep the 40m wait. + # in Apple's queue is handed to a later nightly-next run through the + # recovery artifact below. timeout-minutes: 50 env: - CMUX_NOTARY_WAIT_TIMEOUT: ${{ needs.decide.outputs.track == 'nightly-next' && '20m' || '40m' }} + CMUX_NOTARY_WAIT_TIMEOUT: 40m ASC_API_KEY_ID: ${{ secrets.ASC_API_KEY_ID }} ASC_API_ISSUER_ID: ${{ secrets.ASC_API_ISSUER_ID }} ASC_API_KEY_P8_BASE64: ${{ secrets.ASC_API_KEY_P8_BASE64 }} @@ -2713,7 +2714,7 @@ jobs: else echo "found=true" >> "$GITHUB_OUTPUT" echo "### Pending nightly-next notarizations" >> "$GITHUB_STEP_SUMMARY" - echo "$candidates" | python3 -c 'import json, sys; [print(f"- run {c[\"run_id\"]} build {c[\"build\"]}") for c in json.load(sys.stdin)]' >> "$GITHUB_STEP_SUMMARY" + echo "$candidates" | python3 -c 'import json, sys; [print("- run %s build %s" % (c["run_id"], c["build"])) for c in json.load(sys.stdin)]' >> "$GITHUB_STEP_SUMMARY" fi recover-nightly-next-notarization: @@ -2817,7 +2818,7 @@ jobs: echo "### Continued nightly-next run $run_id (build $BUILD, $BUILD_SHA): Apple accepted it" >> "$GITHUB_STEP_SUMMARY" echo "::endgroup::" exit 0 - done < <(echo "$CANDIDATES" | python3 -c 'import json, sys; [print(f"{c[\"run_id\"]}\t{c[\"artifact\"]}") for c in json.load(sys.stdin)]') + done < <(echo "$CANDIDATES" | python3 -c 'import json, sys; [print("%s\t%s" % (c["run_id"], c["artifact"])) for c in json.load(sys.stdin)]') echo "accepted=false" >> "$GITHUB_OUTPUT" echo "No pending nightly-next notarization was accepted; nothing to continue." >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/release-rails.yml b/.github/workflows/release-rails.yml new file mode 100644 index 000000000000..5399cc0e246e --- /dev/null +++ b/.github/workflows/release-rails.yml @@ -0,0 +1,113 @@ +# Tests for the cmux-next release rails (scripts/cmux-next/release, +# plans/cmux-next/release-rails.md): the migration linter on both trees, the +# rehearse/apply runner and the deploy ordering gate on a scratch Postgres with +# a fake PlanetScale, the post-deploy rollback rail with a fake wrangler and a +# fake Worker, and image promotion with a fake provider. No secrets, no +# database or Cloudflare access, no deploys: it runs on every branch that +# touches these paths, side branches included. + +name: release rails + +on: + pull_request: + paths: + - scripts/cmux-next/release/** + - workers/cmux-vm/migrations/** + - workers/cmux-vm/src/db/schema-*.ts + - workers/cmux-vm/release-smoke.json + - backend/db/migrations/** + - backend/apps/api/release-smoke.json + - backend/apps/api/wrangler.jsonc + - images/cmux-vm/channels/** + - images/cmux-vm/promote.ts + - .github/workflows/release-rails.yml + push: + paths: + - scripts/cmux-next/release/** + - workers/cmux-vm/migrations/** + - workers/cmux-vm/src/db/schema-*.ts + - workers/cmux-vm/release-smoke.json + - backend/db/migrations/** + - backend/apps/api/release-smoke.json + - backend/apps/api/wrangler.jsonc + - images/cmux-vm/channels/** + - images/cmux-vm/promote.ts + - .github/workflows/release-rails.yml + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + rails: + runs-on: ${{ github.repository_owner != 'manaflow-ai' && 'ubuntu-24.04' || github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && 'blacksmith-4vcpu-ubuntu-2404' || vars.LINUX_RUNNER || 'blacksmith-4vcpu-ubuntu-2404' }} + timeout-minutes: 15 + services: + postgres: + image: postgres:17 + env: + POSTGRES_PASSWORD: postgres + ports: ["5432:5432"] + options: --health-cmd pg_isready --health-interval 5s --health-timeout 5s --health-retries 10 + defaults: + run: + working-directory: scripts/cmux-next/release + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 0 + persist-credentials: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + bun-version: "1.4.2" + - id: install + run: bun install --frozen-lockfile + - name: Typecheck + if: ${{ !cancelled() && steps.install.outcome == 'success' }} + run: bun run typecheck + - name: Migration lint, both trees, against the previous head + if: ${{ !cancelled() && steps.install.outcome == 'success' }} + env: + BASE: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }} + run: | + # A new branch (all-zero BEFORE) lints against origin/feat-cmux-next; a base that cannot be resolved fails. + if [ -z "$BASE" ] || [[ "$BASE" =~ ^0+$ ]]; then BASE=origin/feat-cmux-next; fi + git cat-file -e "${BASE}^{commit}" 2>/dev/null || git fetch --quiet --no-tags origin "$BASE" || { echo "::error title=Migration lint::cannot resolve the base $BASE; refusing to lint without it"; exit 1; } + bun lint.ts --base "$BASE" + - name: Rails tests (scratch Postgres, fake PlanetScale, fake wrangler, fake image provider) + if: ${{ !cancelled() && steps.install.outcome == 'success' }} + env: + SCRATCH_URL: postgres://postgres:postgres@localhost:5432/postgres + run: bun test --timeout 60000 test + + # The Worker's schema gate now reads src/db/schema-requirements.ts (shared with the deploy gate). + cmux-vm-schema-gate: + runs-on: ${{ github.repository_owner != 'manaflow-ai' && 'ubuntu-24.04' || github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && 'blacksmith-4vcpu-ubuntu-2404' || vars.LINUX_RUNNER || 'blacksmith-4vcpu-ubuntu-2404' }} + timeout-minutes: 15 + defaults: + run: + working-directory: workers/cmux-vm + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + bun-version: "1.4.2" + - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + with: + node-version: "24" + - id: install + run: bun install --frozen-lockfile + - name: Typecheck + if: ${{ !cancelled() && steps.install.outcome == 'success' }} + run: bun run typecheck + - name: Oxlint with the gdp-ts preset + if: ${{ !cancelled() && steps.install.outcome == 'success' }} + run: bun run lint + - name: Store and schema check tests on PGlite + if: ${{ !cancelled() && steps.install.outcome == 'success' }} + run: bun run test:pg diff --git a/Native/OptChat/optchat-chief/README.md b/Native/OptChat/optchat-chief/README.md index 9d8d64c19068..758d49fd9cb1 100644 --- a/Native/OptChat/optchat-chief/README.md +++ b/Native/OptChat/optchat-chief/README.md @@ -150,15 +150,11 @@ Claude harness, `chief spawn|tell|zoom|date` on any other). Deviation: `tell` reaches a running subagent after its current turn (acpmux queues the prompt; claude-sr has no steering), not between its tool calls. -A Claude spawn of several subagents is single-flight on the shared view: the -first subagent starts alone, its first message marked at the view's last whole -block with the turns' TTL (`Brain::turn_cache_ttl`, 1 hour by default; none once -a route refused our marks), and its session told the same TTL -(`CLAUDE_CODE_PROMPT_CACHE_TTL=1h`, or `FORCE_PROMPT_CACHING_5M=1`), so the API -never sees a 1h mark after a 5m one. The rest start when its response began -streaming (the view's cache entry then exists), at most `WARM_WAIT` (20 s) -later, and read that entry. The trace's `spawn.warm` says whether the first -spoke and how long the wait took. +A subagent's first message carries no cache mark of ours, and all of a +spawn's subagents start at once: Claude Code marks its two system blocks and +the last two messages of every later request in a session, the API takes at +most 4 marks, and a subagent's long tool loop needs Claude Code's own rolling +marks (decision 2026-10-08; see Cache marks and TTL). ## Engine: harness, model and effort per turn @@ -642,7 +638,9 @@ through it. Two rules keep that true: than 16 blocks (`MARK_REACH`) past the last turn's mark: the API looks back only 20 blocks from a mark, so a turn that added more than 80 view lines (a long tool run) would otherwise write the whole view again. Such a turn - writes the new lines once and the next turns catch up. + writes the new lines once and the next turns catch up. The last turn's + marked prefix (its size and hash) is saved in the host state with that + turn's messages, so a restart keeps the rule. - Every mark of one request has one TTL, since the API refuses a 1h mark after a 5m one. On the Claude Code path our mark is 1 hour by default (a human reply 5 to 60 minutes later still reads the view), and each turn @@ -663,6 +661,19 @@ through it. Two rules keep that true: is not reused. 1h and 5m entries are one cache (measured), so a node reads what a turn wrote either way. +**At most 4 marks.** Claude Code 2.1.287 marks its two system blocks and +the last message of a session's first request, and the last TWO messages of +every later request in the session (a tool step, a size-loop follow-up, a +steered message), on the subscription login and through `sr` alike +(measured 2026-10-08). Our view mark stays in the first message's history, +so it would make 5 on the session's second request, which the API refuses. +So a turn or a compactor node that carries our mark runs with +`DISABLE_PROMPT_CACHING=1` in its directory's settings env: Claude Code +places none, every request of the session reads up to our mark, and a +turn's tool steps send their own tail uncached. A turn or node too small +for a mark keeps Claude Code's own. Subagents never carry our mark: their +sessions are long, and Claude Code's own marks cache them step by step. + `turn.start` records the marked piece and the TTL (`layout.mark`, `layout.ttl`) and the inspector lays the prompt out from them. `optchat-core/tests/cache_replay_long.rs` replays 10,000 messages (batch diff --git a/Native/OptChat/optchat-chief/src/acpmux.rs b/Native/OptChat/optchat-chief/src/acpmux.rs index 3e80b1f6c0cb..48f016d08a3f 100644 --- a/Native/OptChat/optchat-chief/src/acpmux.rs +++ b/Native/OptChat/optchat-chief/src/acpmux.rs @@ -323,6 +323,22 @@ impl Acpmux { let Some(map) = set.as_object_mut() else { break result; }; + // A daemon older than the isolation args: keep the args it + // knows (`--tools ""` and the rest), drop only those. + // First the --tools list alone (an acpmux that knows the + // setting source keeps it), then every isolation word. + if key == "args" + && let Some(args) = map.get_mut("args").and_then(Value::as_array_mut) + && let Some(kept) = + without_tools_list(args).or_else(|| without_isolation_args(args)) + { + *args = kept; + log(&format!( + "acpmux refused the isolation args of preset {} ({text}); trying them without the newest (a --tools list, then --setting-sources and --disable-slash-commands; the project settings' denied tools still apply)", + preset.name + )); + continue; + } if map.remove(key).is_none() { break result; } @@ -478,6 +494,55 @@ impl Acpmux { } } +/// `args` without the newer preset allowlist words: `--setting-sources +/// `, `--disable-slash-commands` and `--tools ` (`--tools ""` +/// stays, an older acpmux takes it); None when it has none of them. +pub fn without_isolation_args(args: &[Value]) -> Option> { + let mut kept = Vec::new(); + let mut dropped = false; + let mut words = args.iter(); + while let Some(word) = words.next() { + match word.as_str() { + Some("--setting-sources") => { + words.next(); + dropped = true; + } + Some("--disable-slash-commands") => dropped = true, + Some("--tools") => match words.next() { + Some(value) if value.as_str() == Some("") => { + kept.push(word.clone()); + kept.push(value.clone()); + } + _ => dropped = true, + }, + _ => kept.push(word.clone()), + } + } + dropped.then_some(kept) +} + +/// `args` without a `--tools ` list (`--tools ""` stays); None when +/// it has none. +pub fn without_tools_list(args: &[Value]) -> Option> { + let mut kept = Vec::new(); + let mut dropped = false; + let mut words = args.iter(); + while let Some(word) = words.next() { + if word.as_str() == Some("--tools") { + match words.next() { + Some(value) if value.as_str() == Some("") => { + kept.push(word.clone()); + kept.push(value.clone()); + } + _ => dropped = true, + } + } else { + kept.push(word.clone()); + } + } + dropped.then_some(kept) +} + /// Sends a notification to the turn that owns its session, or to the brain. /// A running prompt's signals. struct TurnRoute { diff --git a/Native/OptChat/optchat-chief/src/brain/mod.rs b/Native/OptChat/optchat-chief/src/brain/mod.rs index 0f274011aa57..48392c9a7322 100644 --- a/Native/OptChat/optchat-chief/src/brain/mod.rs +++ b/Native/OptChat/optchat-chief/src/brain/mod.rs @@ -392,12 +392,12 @@ pub struct Brain { /// The TTL the session settings held when the pool was last hinted: a /// pooled session runs Claude Code with it. prewarm_ttl: Option, + /// Whether the pool was last hinted for a turn with our mark (Claude + /// Code's own marks off, `session_dir::set_session_cache`). + prewarm_ours: Option, /// This turn's TTL differs from `prewarm_ttl` (cache.ttl changed). ttl_stale: Arc, - /// The view up to and including the last turn's marked block - /// (`optchat_core::mark_piece`): the next turn keeps its mark within the - /// API's lookback of it. - last_mark: Option, + /// The monitoring trace (`trace.rs`). pub(crate) trace: crate::trace::Trace, /// Where subagents' workspaces are renamed when they finish. @@ -492,8 +492,8 @@ impl Brain { marker_refused: crate::prompt::MarkLatch::default(), ttl_refused: Arc::new(std::sync::atomic::AtomicBool::new(false)), prewarm_ttl: None, + prewarm_ours: None, ttl_stale: Arc::new(std::sync::atomic::AtomicBool::new(false)), - last_mark: None, chief, turn_remote: false, turn_ask: false, diff --git a/Native/OptChat/optchat-chief/src/brain/prewarm.rs b/Native/OptChat/optchat-chief/src/brain/prewarm.rs index 097ac9f38351..008c263f9a9d 100644 --- a/Native/OptChat/optchat-chief/src/brain/prewarm.rs +++ b/Native/OptChat/optchat-chief/src/brain/prewarm.rs @@ -57,12 +57,24 @@ impl Brain { let (engine, _) = self.next_engine(); let (cached, plain) = self.session_presets(self.family_of(&engine.harness)); if cached.is_some() { - // The pooled Claude Code reads promptCacheTtl when it starts: - // the next turn's TTL, so its own marks match ours. + // The pooled Claude Code reads its cache settings when it + // starts: the next turn's TTL, and whether that turn carries our + // mark (the view has a whole block now, so the next one will). let ttl = self.turn_cache_ttl(); - match crate::session_dir::set_prompt_cache_ttl(&self.settings.session_dir, ttl) { - Ok(()) => self.prewarm_ttl = Some(ttl), - Err(e) => (self.log)(&format!("updating the session's promptCacheTtl: {e}")), + let view = self.chat.render_view(); + let prev = self + .state + .last_mark + .as_ref() + .and_then(|m| m.prefix_of(&view.text)); + let ours = !self.marker_refused.is_off() + && optchat_core::mark_piece(&view.text, prev).is_some(); + match crate::session_dir::set_session_cache(&self.settings.session_dir, ttl, ours) { + Ok(()) => { + self.prewarm_ttl = Some(ttl); + self.prewarm_ours = Some(ours); + } + Err(e) => (self.log)(&format!("updating the session's cache settings: {e}")), } } let preset = cached.or(plain); diff --git a/Native/OptChat/optchat-chief/src/brain/spawns.rs b/Native/OptChat/optchat-chief/src/brain/spawns.rs index 4141f5ba7b0c..615637b7aaf4 100644 --- a/Native/OptChat/optchat-chief/src/brain/spawns.rs +++ b/Native/OptChat/optchat-chief/src/brain/spawns.rs @@ -75,14 +75,10 @@ impl Brain { self.state.spawns.insert(spawn.clone(), record); self.save(); (self.log)(&format!("spawn {spawn}: {}", ids.join(", "))); - // The turns' TTL for a Claude subagent's mark; none once a route - // refused our marks. - let ttl = (!self.marker_refused.is_off()).then(|| self.turn_cache_ttl()); Ok(SpawnPlan { spawn, ids, queued, - ttl, engine: self.spawn_engine(), }) } diff --git a/Native/OptChat/optchat-chief/src/brain/turns.rs b/Native/OptChat/optchat-chief/src/brain/turns.rs index 2b260905e9ff..ca9c16e086fc 100644 --- a/Native/OptChat/optchat-chief/src/brain/turns.rs +++ b/Native/OptChat/optchat-chief/src/brain/turns.rs @@ -197,7 +197,7 @@ impl Brain { } )); if let Err(e) = - crate::session_dir::set_prompt_cache_ttl(&session_dir, retry) + crate::session_dir::set_session_cache(&session_dir, retry, true) { log(&format!("updating the session's promptCacheTtl: {e}")); } @@ -219,6 +219,14 @@ impl Brain { start.key, crate::prompt::MARK_RETRY_AFTER )); + // Unmarked: Claude Code's own marks again. + if let Err(e) = crate::session_dir::set_session_cache( + &session_dir, + ours.unwrap_or(CacheTtl::OneHour), + false, + ) { + log(&format!("updating the session's cache settings: {e}")); + } let mut again = start.clone(); for block in &mut again.blocks { if let Some(b) = block.as_object_mut() { @@ -305,7 +313,42 @@ impl Brain { let session = format!("{}-{first_id}", self.settings.turn_prefix); let conversation = side.clone().or_else(|| self.state.conversation.clone()); let opening: Vec = items.iter().map(item).collect(); + // The engine of this turn, read now (engine.rs): a change applies + // from this turn on and is logged as a note after its messages. + let engine = self.turn_engine_choice(); + let family = self.family_of(&engine.harness); + // The cached layout on a Claude harness whose acpmux takes a preset + // system prompt; else the view and the messages as blocks. + let (cached, plain_preset) = self.session_presets(family); + let marker = self.marker_refused.take(); + let ttl = self.turn_cache_ttl(); + // Our one mark: the last whole block of the view, held within the + // API's lookback of the last turn's mark (optchat_core::mark_piece), + // which is saved with the messages so a restart keeps it. + let mark = cached + .as_ref() + .filter(|_| marker) + .and_then(|_| { + let prev = self + .state + .last_mark + .as_ref() + .and_then(|m| m.prefix_of(&view.text)); + optchat_core::mark_piece(&view.text, prev) + }) + .map(|piece| Mark { piece, ttl }) + // A session the pool started for an unmarked turn runs Claude + // Code with its own marks: ours on top would make 5. + .filter(|_| self.prewarm_ours != Some(false)); + let mark_record = mark.map(|m| { + crate::state::MarkRecord::of( + &optchat_core::block_pieces(&view.text)[..=m.piece].concat(), + ) + }); let done = self.log_items(&items, move |next, done| { + if let Some(record) = mark_record { + next.last_mark = Some(record); + } let first = done.ids.first().copied().unwrap_or(first_id); let stamp = done.stamps.first().map(String::as_str).unwrap_or(""); next.turn = Some(PendingTurn { @@ -371,36 +414,20 @@ impl Brain { // the new messages. Never logged. let at_work = self.at_work_line(); let prompt_texts: Vec = at_work.iter().chain(texts.iter()).cloned().collect(); - // The engine of this turn, read now (engine.rs): a change applies - // from this turn on and is logged as a note after its messages. - let engine = self.turn_engine_choice(); - let family = self.family_of(&engine.harness); self.note_engine(&engine); - // The cached layout on a Claude harness whose acpmux takes a preset - // system prompt; else the view and the messages as blocks. - let (cached, plain_preset) = self.session_presets(family); let cached = cached.as_deref(); - let marker = self.marker_refused.take(); - let ttl = self.turn_cache_ttl(); - // Our one mark: the last whole block of the view, held within the - // API's lookback of the last turn's mark (optchat_core::mark_piece). - let mut mark = None; let (blocks, system_prompt, preset) = match cached { Some(preset) => { - mark = marker - .then(|| optchat_core::mark_piece(&view.text, self.last_mark.as_deref())) - .flatten() - .map(|piece| Mark { piece, ttl }); - self.last_mark = - mark.map(|m| optchat_core::block_pieces(&view.text)[..=m.piece].concat()); // Claude Code's own marks take the same TTL: the API refuses // a 1h mark after a 5m one. A session the pool started // before a cache.ttl change still has the old one. self.ttl_stale .store(self.prewarm_ttl.is_some_and(|p| p != ttl), Ordering::SeqCst); - if let Err(e) = - crate::session_dir::set_prompt_cache_ttl(&self.settings.session_dir, ttl) - { + if let Err(e) = crate::session_dir::set_session_cache( + &self.settings.session_dir, + ttl, + mark.is_some(), + ) { (self.log)(&format!("updating the session's promptCacheTtl: {e}")); } let layout = cached_layout_marked( diff --git a/Native/OptChat/optchat-chief/src/compactor.rs b/Native/OptChat/optchat-chief/src/compactor.rs index 0e6b8dedefcc..7d74b6437682 100644 --- a/Native/OptChat/optchat-chief/src/compactor.rs +++ b/Native/OptChat/optchat-chief/src/compactor.rs @@ -147,6 +147,9 @@ pub struct CompactorSpec { pub timeout: Duration, /// This Chief's home id: the `cmux.chief` tag on every compactor session. pub chief: String, + /// The `env` of the user's Claude Code settings: the slots load no user + /// setting source, so their project settings carry it. + pub user_env: BTreeMap, } /// Compactor sessions that live at once across the main and fallback @@ -312,6 +315,8 @@ struct Live { /// The slot's preset, and the system prompt this node set in it. preset: String, system: Option, + /// The node's first message carries our mark (Claude Code's own off). + ours: bool, opened: Instant, prompts: u32, /// Token use the harness reported, summed over the node's prompts. @@ -348,6 +353,9 @@ pub struct AcpmuxCompactor { /// Warm sessions kept for the next nodes (`with_warm`; 0: none). warm: usize, reaped: AtomicBool, + /// This compactor, when shared (`shared`): a warm session then starts on + /// its own thread after the node returns. + me: std::sync::Weak, log: Option, trace: crate::trace::Trace, } @@ -375,6 +383,7 @@ impl AcpmuxCompactor { model_fallback: None, warm: 0, reaped: AtomicBool::new(false), + me: std::sync::Weak::new(), log: None, trace: crate::trace::Trace::off(), } @@ -437,6 +446,16 @@ impl AcpmuxCompactor { true } + /// The compactor shared, as the host holds it: a node's slot then warms + /// up on its own thread, after the node's line is returned. + pub fn shared(self) -> Arc { + let mut compactor = self; + Arc::new_cyclic(|me| { + compactor.me = me.clone(); + compactor + }) + } + /// Keeps up to `n` warm sessions (`WARM_SESSIONS` in the host). pub fn with_warm(mut self, n: usize) -> AcpmuxCompactor { self.warm = n; @@ -490,7 +509,7 @@ impl AcpmuxCompactor { /// harness shares one directory across slots: codex names the cwd in /// its environment context, ahead of the prompt, so one cwd keeps the /// request prefix identical from node to node. - fn slot_dir(&self, slot: usize, ttl: CacheTtl) -> io::Result { + fn slot_dir(&self, slot: usize, ttl: CacheTtl, ours: bool) -> io::Result { private_dir(&self.spec.work)?; let dir = if self.claude() { self.spec.work.join(format!("slot-{slot}")) @@ -502,17 +521,24 @@ impl AcpmuxCompactor { // (sr resets CLAUDE_CONFIG_DIR, so the preset's user settings are // not), and the ones that take denied tools off the model's list. std::fs::create_dir_all(dir.join(".claude"))?; - write_settings_for(&dir.join(".claude").join("settings.json"), ttl)?; + write_settings_for( + &dir.join(".claude").join("settings.json"), + ttl, + ours, + &self.spec.user_env, + )?; std::fs::canonicalize(&dir) } /// What a warm session must match for a node: its system prompt and the /// model sessions start with now. - fn warm_key(&self, system: Option<&str>, ttl: CacheTtl) -> u64 { + fn warm_key(&self, system: Option<&str>, ttl: CacheTtl, ours: bool) -> u64 { let mut h = std::collections::hash_map::DefaultHasher::new(); std::hash::Hash::hash(&system, &mut h); // A warm session's Claude Code read its slot's TTL when it started. std::hash::Hash::hash(ttl.as_str(), &mut h); + // ...and whether Claude Code's own marks were off (DISABLE). + std::hash::Hash::hash(&ours, &mut h); std::hash::Hash::hash(&self.model(), &mut h); std::hash::Hasher::finish(&h) } @@ -526,12 +552,13 @@ impl AcpmuxCompactor { node: NodeId, system: Option<&str>, ttl: CacheTtl, + ours: bool, ) -> Result { // Claude only through acpmux's own Claude Code adapter // (harness_gate), checked before a slot is taken. let admitted = self.admit(node)?; self.reap_warm(); - let key = self.warm_key(system, ttl); + let key = self.warm_key(system, ttl, ours); let (id, slot, cwd, preset) = match self.slots.acquire((self.warm > 0).then_some(key)) { Acquired::Warm(w) => (w.id, w.slot, w.cwd, w.preset), other => { @@ -544,7 +571,7 @@ impl AcpmuxCompactor { Acquired::Warm(_) => unreachable!(), }; let name = self.session_name(node); - match self.start(slot, &name, system, &admitted, ttl) { + match self.start(slot, &name, system, &admitted, ttl, ours) { Ok((id, cwd, preset)) => (id, slot, cwd, preset), Err(e) => { self.slots.give(slot); @@ -565,6 +592,7 @@ impl AcpmuxCompactor { cwd, preset, system: system.map(str::to_owned), + ours, opened: Instant::now(), prompts: 0, usage: None, @@ -598,8 +626,9 @@ impl AcpmuxCompactor { system: Option<&str>, admitted: &crate::harness_gate::Admitted, ttl: CacheTtl, + ours: bool, ) -> Result<(String, PathBuf, String), ModelError> { - let cwd = self.slot_dir(slot, ttl).map_err(|e| { + let cwd = self.slot_dir(slot, ttl, ours).map_err(|e| { ModelError::new(format!("creating the compactor's working directory: {e}")) })?; let preset = slot_preset(&self.spec.preset, slot); @@ -660,8 +689,11 @@ impl AcpmuxCompactor { /// Starts a warm session in `slot` (counted as warming by /// `Slots::rewarm`) with `system`; gives the slot back when it cannot. - fn warm_up(&self, slot: usize, system: Option) { + fn warm_up(&self, slot: usize, system: Option, ours: bool) { let ttl = self.cache_ttl.get(); + // The next node likely carries our mark as the last one did (a + // context of the same size): its key says so, and a node that does + // not match it starts a fresh session. let started = self.admit(PROBE_NODE).and_then(|admitted| { self.start( slot, @@ -669,6 +701,7 @@ impl AcpmuxCompactor { system.as_deref(), &admitted, ttl, + ours, ) }); match started { @@ -677,7 +710,7 @@ impl AcpmuxCompactor { slot, cwd, preset, - key: self.warm_key(system.as_deref(), ttl), + key: self.warm_key(system.as_deref(), ttl, ours), system, }), Err(e) => { @@ -833,7 +866,7 @@ impl AcpmuxCompactor { started(); } Ok(Reply::text(strip_preamble( - fold.final_text().unwrap_or_default(), + &fold.final_text().unwrap_or_default(), ))) } @@ -876,7 +909,11 @@ impl AcpmuxCompactor { // Claude Code settings and the warm session key agree. let ttl = self.cache_ttl.get(); let layout = cached_prompt_with(request, marker, ttl); - let session = self.open(node, Some(&layout.system), ttl)?; + let ours = layout + .blocks + .iter() + .any(|b| b.get("cache_control").is_some()); + let session = self.open(node, Some(&layout.system), ttl, ours)?; let has_marker = layout .blocks .iter() @@ -893,7 +930,7 @@ impl AcpmuxCompactor { // A fresh session: the refused prompt may sit in the old one's history. self.end(request); let layout = cached_prompt_with(request, false, ttl); - let session = self.open(node, Some(&layout.system), ttl)?; + let session = self.open(node, Some(&layout.system), ttl, false)?; self.prompt(node, &session, layout.blocks, started) } other => other, @@ -917,7 +954,7 @@ impl AcpmuxCompactor { return self.first_cached(request, started); } ( - self.open(node, None, self.cache_ttl.get())?, + self.open(node, None, self.cache_ttl.get(), false)?, request_blocks(request), ) } @@ -1015,7 +1052,21 @@ impl AcpmuxCompactor { // The next node's session starts now, in this slot, so it does not // wait for one; else the slot goes back. if self.warm > 0 && !is_describe(node) && self.slots.rewarm(self.warm) { - self.warm_up(live.slot, live.system.clone()); + // Off the node's path: starting Claude Code takes seconds, and + // the node's line (and any turn waiting for it) must not wait. + let (slot, system, ours) = (live.slot, live.system.clone(), live.ours); + match self.me.upgrade() { + Some(me) => { + let spawned = std::thread::Builder::new() + .name("optchat-compact-warm".into()) + .spawn(move || me.warm_up(slot, system, ours)); + if let Err(e) = spawned { + self.say(&format!("starting a warm compactor session: {e}")); + self.slots.give_slot(slot, true); + } + } + None => self.warm_up(slot, system, ours), + } } else { if live.system.is_some() { let _ = self.port.set_system_prompt(&live.preset, ""); @@ -1064,7 +1115,7 @@ impl crate::brain::images::Describe for AcpmuxCompactor { let n = self.describes.fetch_add(1, Ordering::SeqCst); let node = NodeId::new(0, u64::MAX - n); let session = self - .open(node, None, self.cache_ttl.get()) + .open(node, None, self.cache_ttl.get(), false) .map_err(|e| e.message)?; let reply = self.prompt(node, &session, blocks, &|| {}); self.end_node(node); @@ -1102,13 +1153,17 @@ pub fn request_blocks(request: &CompactRequest) -> Vec { /// The compactor presets' harness arguments on a Claude harness: acpmux's /// allowlist of preset args, every one of which takes a capability away: no -/// tools, no MCP servers, no transcript. The system prompt is the preset's +/// tools, no MCP servers, no transcript, no user or local settings, no +/// skills or slash commands. The system prompt is the preset's /// `systemPrompt` text (acpmux writes and checks the file), never a path. -pub const COMPACTOR_ARGS: [&str; 4] = [ +pub const COMPACTOR_ARGS: [&str; 7] = [ "--tools", "", "--strict-mcp-config", "--no-session-persistence", + "--setting-sources", + "project", + "--disable-slash-commands", ]; /// The slot presets' system prompt at install, before any node sets its @@ -1279,6 +1334,14 @@ pub fn compactor_settings() -> Value { /// `promptCacheTtl`, and at 5 minutes FORCE_PROMPT_CACHING_5M, which wins /// over a subscription login's 1 hour. pub fn compactor_settings_for(ttl: CacheTtl) -> Value { + compactor_settings_with(ttl, false) +} + +/// `compactor_settings_for`, and with `ours` (the node's first message +/// carries our mark) DISABLE_PROMPT_CACHING=1: Claude Code marks its two +/// system blocks and the last two messages of every later request in a +/// session (a size-loop follow-up), and the API takes at most 4 marks. +pub fn compactor_settings_with(ttl: CacheTtl, ours: bool) -> Value { let mut value = json!({ "permissions": {"deny": DENIED_TOOLS.as_slice()}, "autoMemoryEnabled": false, @@ -1289,8 +1352,15 @@ pub fn compactor_settings_for(ttl: CacheTtl) -> Value { "enableAllProjectMcpServers": false, "cleanupPeriodDays": TRANSCRIPT_DAYS, }); + let mut env = serde_json::Map::new(); if ttl == CacheTtl::FiveMinutes { - value["env"] = json!({"FORCE_PROMPT_CACHING_5M": "1"}); + env.insert("FORCE_PROMPT_CACHING_5M".into(), json!("1")); + } + if ours { + env.insert("DISABLE_PROMPT_CACHING".into(), json!("1")); + } + if !env.is_empty() { + value["env"] = Value::Object(env); } value } @@ -1302,15 +1372,35 @@ pub fn prepare_config(dir: &Path) -> io::Result<()> { } fn write_settings(path: &Path) -> io::Result<()> { - write_settings_for(path, CacheTtl::OneHour) + write_settings_for(path, CacheTtl::OneHour, false, &BTreeMap::new()) } -fn write_settings_for(path: &Path, ttl: CacheTtl) -> io::Result<()> { - crate::session_dir::write_if_changed( +/// The slot settings at `ttl`, with `user_env` (the user's Claude Code +/// settings env: the slot loads no user setting source) under the slot's +/// own env. +fn write_settings_for( + path: &Path, + ttl: CacheTtl, + ours: bool, + user_env: &BTreeMap, +) -> io::Result<()> { + let mut settings = compactor_settings_with(ttl, ours); + if !user_env.is_empty() { + let mut env: serde_json::Map = user_env + .iter() + .map(|(k, v)| (k.clone(), Value::String(v.clone()))) + .collect(); + if let Some(own) = settings.get("env").and_then(Value::as_object) { + env.extend(own.clone()); + } + settings["env"] = Value::Object(env); + } + // It may hold the user's settings env (an API token): the user's alone. + crate::session_dir::write_private( path, format!( "{}\n", - serde_json::to_string_pretty(&compactor_settings_for(ttl)).map_err(io::Error::other)? + serde_json::to_string_pretty(&settings).map_err(io::Error::other)? ) .as_bytes(), ) @@ -1437,6 +1527,19 @@ pub fn compactor_effort(family: Family) -> Option { } } +/// The compactor model a Claude Code harness is asked for: the `haiku` +/// alias, which Claude Code maps to its current Haiku. Claude Code 2.1.287 +/// does not know the full id `claude-haiku-5-5` ("[claude-code: +/// unrecognized_model]"); the Messages API route keeps it +/// (`optchat_host::DEFAULT_MODEL`). +pub const CLAUDE_CODE_COMPACTOR_MODEL: &str = "haiku"; + +/// The default compactor model of `family`'s harness (None: the harness's +/// own default model). +pub fn compactor_model_for(family: Family) -> Option { + (family == Family::Claude).then(|| CLAUDE_CODE_COMPACTOR_MODEL.to_owned()) +} + /// Whether a failed compactor turn says the account cannot use the model: /// Claude Code's "There's an issue with the selected model (...). It may /// not exist or you may not have access to it", or the API's @@ -1444,6 +1547,7 @@ pub fn compactor_effort(family: Family) -> Option { pub fn is_model_unavailable(message: &str) -> bool { let lower = message.to_ascii_lowercase(); lower.contains("issue with the selected model") + || lower.contains("unrecognized_model") || lower.contains("may not exist or you may not have access") || (lower.contains("not_found_error") && lower.contains("model")) } @@ -1469,6 +1573,7 @@ pub fn compactor_spec( effort: compactor_effort(family), timeout: CALL_TIMEOUT, chief: home_id(home), + user_env: crate::session_dir::host_user_env(), } } diff --git a/Native/OptChat/optchat-chief/src/fold.rs b/Native/OptChat/optchat-chief/src/fold.rs index f3111dcb4291..d3d069deb5dc 100644 --- a/Native/OptChat/optchat-chief/src/fold.rs +++ b/Native/OptChat/optchat-chief/src/fold.rs @@ -141,6 +141,9 @@ pub struct TurnFold { tools: HashMap, /// The last finished reply: what the turn posts. last_talk: Option, + /// Answers Claude Code finished (`result`) before a steered message + /// made it go on in the same prompt: the post holds them first. + answered: Vec, ended: Option, /// The last raw Claude Code line came from one of its own subagents /// (Task/Agent): the translated updates that follow it are that @@ -207,8 +210,14 @@ impl TurnFold { } /// The turn's final assistant text: its last finished reply. - pub fn final_text(&self) -> Option<&str> { - self.last_talk.as_deref() + pub fn final_text(&self) -> Option { + let parts: Vec<&str> = self + .answered + .iter() + .map(String::as_str) + .chain(self.last_talk.as_deref()) + .collect(); + (!parts.is_empty()).then(|| parts.join("\n\n")) } /// Folds one event; events at or below the last seq are replays. @@ -241,6 +250,16 @@ impl TurnFold { if !self.in_subagent && event.dir != "out" { self.time_request(event); } + // Claude Code finished an answer; with a steered message it goes + // on in this prompt, and the next answer is posted after it. + if !self.in_subagent && event.kind.starts_with("claude.result") { + let mut out = Vec::new(); + self.finish_talk(&mut out); + if let Some(text) = self.last_talk.take() { + self.answered.push(text); + } + return out; + } if event.kind == "claude.assistant" && !self.in_subagent { let message = event.msg.get("message"); let usage = message.and_then(|m| m.get("usage")).and_then(Usage::parse); @@ -630,7 +649,7 @@ mod tests { (Kind::Talk, "It is empty."), ] ); - assert_eq!(fold.final_text(), Some("It is empty.")); + assert_eq!(fold.final_text().as_deref(), Some("It is empty.")); assert_eq!(fold.ended(), Some(&Ended { error: None })); // A replay of the same events changes nothing. for e in &events { @@ -765,7 +784,7 @@ mod tests { (Kind::Talk, "Found it."), ] ); - assert_eq!(fold.final_text(), Some("Found it.")); + assert_eq!(fold.final_text().as_deref(), Some("Found it.")); } /// Audit round 2: a turn that stops early (refusal, max_tokens, diff --git a/Native/OptChat/optchat-chief/src/host.rs b/Native/OptChat/optchat-chief/src/host.rs index 44274829adfd..cd33ed4306af 100644 --- a/Native/OptChat/optchat-chief/src/host.rs +++ b/Native/OptChat/optchat-chief/src/host.rs @@ -119,10 +119,7 @@ pub fn turn_preset( if family == Family::Claude && isolate { // The preset's system prompt carries the instructions: no CLAUDE.md // file reaches a turn (the user's own ~/.claude/CLAUDE.md included). - env.insert( - "CLAUDE_CODE_DISABLE_CLAUDE_MDS".to_owned(), - "1".to_owned(), - ); + env.insert("CLAUDE_CODE_DISABLE_CLAUDE_MDS".to_owned(), "1".to_owned()); } if family == Family::Claude { // claude-sr (when chosen): every turn of this Chief on one sticky @@ -132,15 +129,89 @@ pub fn turn_preset( codex_cache_key(home, "turn"), ); } + // The reference's Claude Code path: no user settings (user MCP servers, + // hooks, plugins), no skills or slash commands, only TURN_TOOLS of the + // built-ins; the session directory's own settings and .mcp.json stay, + // and the user's login still signs in. + let args = if family == Family::Claude && isolate { + turn_isolation_args() + } else { + Vec::new() + }; (isolate || family != Family::Other).then(|| Preset { name: turn_preset_name(home, family), harness: harness.to_owned(), env, - args: Vec::new(), + args, system_prompt: (family == Family::Claude).then(|| system_text.to_owned()), }) } +/// The built-in tools a turn is offered (an allowlist: a built-in a later +/// Claude Code adds is not offered); the Chief's MCP tools come on top. +pub const TURN_TOOLS: [&str; 7] = [ + "Bash", + "Read", + "Edit", + "Write", + "WebFetch", + "WebSearch", + "ToolSearch", +]; + +/// The Claude Code args of an isolated turn: no user or local setting +/// source, no skills or slash commands, only `TURN_TOOLS` of the built-ins +/// (acpmux's preset allowlist). +pub fn turn_isolation_args() -> Vec { + vec![ + "--setting-sources".to_owned(), + "project".to_owned(), + "--disable-slash-commands".to_owned(), + "--tools".to_owned(), + TURN_TOOLS.join(","), + ] +} + +/// A subagent preset `name`: the user's own environment (subagents do real +/// work in the user's repositories), the pinned cmux env, its cache key, +/// and on a Claude harness its system prompt `text`. +#[allow(clippy::too_many_arguments)] +pub fn subagent_preset( + paths: &Paths, + home: &std::path::Path, + name: String, + profile: &str, + family: Family, + isolate: bool, + text: &str, + pinned: &BTreeMap, +) -> Preset { + let mut env = if isolate { + session_dir::isolation_env(paths) + } else { + BTreeMap::new() + }; + env.insert(session_dir::SUBAGENT_ENV.to_owned(), "1".to_owned()); + // Subagents' cmux calls reach the same app daemon as the Chief's. + env.extend(pinned.clone()); + if family == Family::Codex { + env.insert(CODEX_CACHE_KEY_ENV.to_owned(), codex_cache_key(home, "sub")); + } + if family == Family::Claude { + env.insert( + crate::compactor::SUBROUTER_SESSION_KEY_ENV.to_owned(), + codex_cache_key(home, "sub"), + ); + } + Preset { + name, + harness: profile.to_owned(), + env, + args: Vec::new(), + system_prompt: (family == Family::Claude).then(|| text.to_owned()), + } +} + /// The turn preset's name: `optchat-chief-`, and /// `optchat-chief-codex-` for codex, so both can be installed and /// a turn can swap harness families (engine.rs). @@ -486,6 +557,7 @@ fn start( env: session_env, instructions: instructions.clone(), tools, + user_env: session_dir::host_user_env(), }; session_dir::write(paths, &setup).map_err(|e| format!("writing the session directory: {e}"))?; // Section 9: every subagent's directory and system prompt. @@ -561,30 +633,7 @@ fn start( // turn preset (whose system prompt is the Chief's view). let sub_preset_name = format!("optchat-sub-{}", crate::paths::home_id(home)); let sub_preset = |name: String, profile: &str, family: Family, text: &str| { - let mut env = if isolate { - session_dir::isolation_env(paths) - } else { - BTreeMap::new() - }; - env.insert(session_dir::SUBAGENT_ENV.to_owned(), "1".to_owned()); - // Subagents' cmux calls reach the same app daemon as the Chief's. - env.extend(pinned.clone()); - if family == Family::Codex { - env.insert(CODEX_CACHE_KEY_ENV.to_owned(), codex_cache_key(home, "sub")); - } - if family == Family::Claude { - env.insert( - crate::compactor::SUBROUTER_SESSION_KEY_ENV.to_owned(), - codex_cache_key(home, "sub"), - ); - } - Preset { - name, - harness: profile.to_owned(), - env, - args: Vec::new(), - system_prompt: (family == Family::Claude).then(|| text.to_owned()), - } + subagent_preset(paths, home, name, profile, family, isolate, text, &pinned) }; if uses_acpmux { required.push(sub_preset( @@ -676,7 +725,7 @@ fn start( let compactor_claude = compactor_family == Family::Claude; let compactor_model = env("OPTCHAT_COMPACTOR_MODEL") .or_else(|| engine_choice_file.compactor_model.clone()) - .or_else(|| compactor_claude.then(|| config.model.clone())); + .or_else(|| crate::compactor::compactor_model_for(compactor_family)); let compactor_effort = env("OPTCHAT_COMPACTOR_EFFORT"); let port: Arc = agents.clone(); // One gate: at most COMPACTOR_SESSIONS sessions across both models. @@ -711,11 +760,10 @@ fn start( .map(|m| Arc::new(build(Some(m))) as Arc); // An account without the compactor model (Haiku on some // subscriptions) builds with the turn model instead, logged once. - let main = Arc::new( - build(compactor_model.as_deref()) - .with_model_fallback(env("OPTCHAT_CHIEF_MODEL")) - .with_warm(crate::compactor::WARM_SESSIONS), - ); + let main = build(compactor_model.as_deref()) + .with_model_fallback(env("OPTCHAT_CHIEF_MODEL")) + .with_warm(crate::compactor::WARM_SESSIONS) + .shared(); let describer = main.clone() as Arc; ( main as Arc, diff --git a/Native/OptChat/optchat-chief/src/session_dir.rs b/Native/OptChat/optchat-chief/src/session_dir.rs index d827702c7d85..9622f9f3d77a 100644 --- a/Native/OptChat/optchat-chief/src/session_dir.rs +++ b/Native/OptChat/optchat-chief/src/session_dir.rs @@ -41,6 +41,51 @@ pub struct SessionSetup { pub instructions: Option, /// How the turn reaches its memory tools (the harness family). pub tools: crate::prompt::Tools, + /// The `env` of the user's Claude Code settings (`user_settings_env`): + /// a session that loads no user setting source still gets it (the + /// user's API route, for one), under the session's own env. + pub user_env: BTreeMap, +} + +/// Whether this host copies the user's Claude Code settings env into its +/// sessions' settings (`OPTCHAT_COPY_USER_ENV`, `0` turns it off). +/// Only on a macOS host, the user's own Mac: a Chief in a Linux VM or a +/// dev backend image never copies a settings env into its files. +pub fn copy_user_env_allowed(setting: Option<&str>) -> bool { + cfg!(target_os = "macos") && setting.map(str::trim) != Some("0") +} + +/// The user's settings env for this host's sessions (`user_settings_env` +/// of the user's Claude home) when `copy_user_env_allowed`, else empty. +/// Its values are never logged. +pub fn host_user_env() -> BTreeMap { + if copy_user_env_allowed(crate::cli::env("OPTCHAT_COPY_USER_ENV").as_deref()) { + user_settings_env(&crate::compactor::user_claude_home()) + } else { + BTreeMap::new() + } +} + +/// The `env` block of the user's Claude Code settings file +/// (`/settings.json`), string values only; empty when the +/// file is missing or unreadable. +pub fn user_settings_env(claude_home: &Path) -> BTreeMap { + use std::os::unix::fs::MetadataExt; + let file = claude_home.join("settings.json"); + // Only a file this user owns: another user's settings are not ours to copy. + // SAFETY: getuid has no preconditions and cannot fail. + let uid = unsafe { libc::getuid() }; + if std::fs::metadata(&file).map_or(true, |m| m.uid() != uid) { + return BTreeMap::new(); + } + std::fs::read(&file) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + .and_then(|v| v.get("env").and_then(Value::as_object).cloned()) + .into_iter() + .flatten() + .filter_map(|(k, v)| v.as_str().map(|v| (k, v.to_owned()))) + .collect() } pub fn shell_quote(value: &str) -> String { @@ -93,9 +138,12 @@ pub fn settings_json(setup: &SessionSetup, paths: &Paths, deny: &[&str]) -> Valu if setup.cmux_mcp.is_some() { names.push("cmux"); } + // The user's settings env first (a session that loads no user setting + // source keeps the user's API route), the session's own over it. let mut env: serde_json::Map = setup - .env + .user_env .iter() + .chain(setup.env.iter()) .map(|(k, v)| (k.clone(), Value::String(v.clone()))) .collect(); let path = setup @@ -143,8 +191,10 @@ pub const SUBAGENT_DENIED_TOOLS: [&str; 5] = [ /// so the turn's prefix stays small (measured 2026-10-08: 20.7k to 12.1k /// tokens bare). A turn keeps Bash, Read, Edit, Write, WebFetch, WebSearch, /// and ToolSearch (it loads the MCP tools on demand); work beyond those goes -/// to subagents. A tool a later Claude Code adds is offered until it is -/// listed here. +/// to subagents. The turn preset's `--tools` allowlist (`host::TURN_TOOLS`) +/// is the main guard: a tool a later Claude Code adds is not offered. This +/// list stays as the second guard, for an acpmux older than that preset +/// arg (the preset is then installed without it). pub const TURN_DENIED_TOOLS: [&str; 25] = [ "Task", "Agent", @@ -240,14 +290,15 @@ pub fn write(paths: &Paths, setup: &SessionSetup) -> io::Result<()> { &paths.session.join(".mcp.json"), pretty(&mcp_json(setup, paths))?.as_bytes(), )?; + // Private: they may hold the user's settings env (an API token). let settings = pretty(&settings_json(setup, paths, &TURN_DENIED_TOOLS))?; - write_if_changed( + write_private( &paths.session.join(".claude").join("settings.json"), settings.as_bytes(), )?; // The same switches in the local project settings, which some harness // versions read for MCP approval instead of the shared file. - write_if_changed( + write_private( &paths.session.join(".claude").join("settings.local.json"), settings.as_bytes(), )?; @@ -283,6 +334,8 @@ pub fn write_subagent(paths: &Paths, setup: &SessionSetup, text: &str) -> io::Re )?; let mut sub = setup.clone(); sub.env.insert(SUBAGENT_ENV.to_owned(), "1".to_owned()); + // Subagents load the user's own settings; no copy of its env here. + sub.user_env.clear(); let settings = pretty(&settings_json(&sub, paths, &SUBAGENT_DENIED_TOOLS))?; write_if_changed( &dir.join(".claude").join("settings.json"), @@ -326,6 +379,20 @@ pub fn set_claude_md(session: &Path, text: Option<&str>) -> io::Result<()> { /// Claude Code's own cache marks then take the TTL of ours, since the API /// refuses a 1h mark after a 5m one. Claude Code reads it at session start. pub fn set_prompt_cache_ttl(session: &Path, ttl: crate::prompt::CacheTtl) -> io::Result<()> { + set_session_cache(session, ttl, false) +} + +/// `set_prompt_cache_ttl`, and with `ours` (the session's first message +/// carries our mark) DISABLE_PROMPT_CACHING=1: Claude Code then places none +/// of its own. It marks its two system blocks and the last two messages of +/// every request after a session's first (Claude Code 2.1.287, measured), +/// and the API takes at most 4, so our mark in the history makes 5 on the +/// session's second request. Without our mark, Claude Code's own stay. +pub fn set_session_cache( + session: &Path, + ttl: crate::prompt::CacheTtl, + ours: bool, +) -> io::Result<()> { let dir = session.join(".claude"); std::fs::create_dir_all(&dir)?; for name in ["settings.json", "settings.local.json"] { @@ -351,6 +418,11 @@ pub fn set_prompt_cache_ttl(session: &Path, ttl: crate::prompt::CacheTtl) -> io: } } } + if ours { + value["env"]["DISABLE_PROMPT_CACHING"] = json!("1"); + } else if let Some(env) = value["env"].as_object_mut() { + env.remove("DISABLE_PROMPT_CACHING"); + } let text = format!( "{}\n", serde_json::to_string_pretty(&value).map_err(io::Error::other)? @@ -368,6 +440,32 @@ fn remove_if_present(path: &Path) -> io::Result<()> { } /// Replaces `path` through a temporary file, so a reader never sees half a file. +/// `write_if_changed` for a file that may hold a secret: written 0600 from +/// its first byte, and kept 0600. +pub fn write_private(path: &Path, bytes: &[u8]) -> io::Result<()> { + use std::io::Write; + use std::os::unix::fs::OpenOptionsExt; + if std::fs::read(path).is_ok_and(|old| old == bytes) { + return std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)); + } + static WRITES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = WRITES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let tmp = path.with_extension(format!("tmp.{}.{n}", std::process::id())); + let written = (|| { + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&tmp)?; + file.write_all(bytes)?; + std::fs::rename(&tmp, path) + })(); + if written.is_err() { + let _ = std::fs::remove_file(&tmp); + } + written +} + pub fn write_if_changed(path: &Path, bytes: &[u8]) -> io::Result<()> { if std::fs::read(path).is_ok_and(|old| old == bytes) { return Ok(()); @@ -390,6 +488,7 @@ mod tests { env.insert("MUX_HOME".to_string(), "/h".to_string()); env.insert("PATH".to_string(), "/usr/bin".to_string()); SessionSetup { + user_env: Default::default(), exe: "/x/optchat-chief".into(), cmux_mcp: Some("/x/cmux".into()), env, diff --git a/Native/OptChat/optchat-chief/src/state.rs b/Native/OptChat/optchat-chief/src/state.rs index 580cf6d7356f..a781b0ef71ad 100644 --- a/Native/OptChat/optchat-chief/src/state.rs +++ b/Native/OptChat/optchat-chief/src/state.rs @@ -83,6 +83,12 @@ pub struct HostState { /// next connect reads them from the owner again and describes them. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub undescribed: Vec, + /// The view up to and including the last turn's marked block, by size + /// and hash (`optchat_core::mark_piece`): saved with that turn's + /// messages, so the first turn after a restart still marks within the + /// API's lookback of it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_mark: Option, /// G9: the floor of each side conversation (not the main one) the /// chief's wake queue woke, by conversation id. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] @@ -649,3 +655,25 @@ mod tests { assert_eq!(file.load(), HostState::default()); } } + +/// A turn's marked view prefix: its byte length and `trace::hash`. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct MarkRecord { + pub bytes: usize, + pub hash: String, +} + +impl MarkRecord { + pub fn of(prefix: &str) -> MarkRecord { + MarkRecord { + bytes: prefix.len(), + hash: crate::trace::hash(prefix), + } + } + + /// The same prefix of `view`, when `view` still starts with it. + pub fn prefix_of<'a>(&self, view: &'a str) -> Option<&'a str> { + let prefix = view.get(..self.bytes)?; + (crate::trace::hash(prefix) == self.hash).then_some(prefix) + } +} diff --git a/Native/OptChat/optchat-chief/src/subagents.rs b/Native/OptChat/optchat-chief/src/subagents.rs index 437c73b763c3..41d2fc15550d 100644 --- a/Native/OptChat/optchat-chief/src/subagents.rs +++ b/Native/OptChat/optchat-chief/src/subagents.rs @@ -52,9 +52,6 @@ pub const MAX_TASKS: usize = 8; /// Most subagents at work at once; a spawn over it queues the rest, which /// start as others finish. pub const MAX_LIVE: usize = 16; -/// Longest a Claude spawn waits for its first subagent's response to start -/// (the shared view's cache entry then exists) before it starts the rest. -pub const WARM_WAIT: Duration = Duration::from_secs(20); /// Longest `spawn` waits for the view to settle (section 6). pub const SETTLE_LIMIT: Duration = Duration::from_secs(240); /// Prompt ids of the host's own prompts to a subagent start with this; any @@ -68,10 +65,6 @@ pub struct SpawnPlan { pub ids: Vec, /// The ids over `MAX_LIVE`: they wait for a free slot. pub queued: Vec, - /// The TTL of the turns' cache marks (`Brain::turn_cache_ttl`), None - /// once a route refused our marks: a Claude subagent's first message - /// is marked at the view's end with it. - pub ttl: Option, /// The engine of the turn that called spawn (engine.json); None before /// any turn. pub engine: Option, @@ -132,7 +125,6 @@ struct Waiting { task: String, floor: Option, launch: SubagentSettings, - ttl: Option, } /// Serves `spawn` and `tell` (tools.rs `Orchestrator`). @@ -152,8 +144,6 @@ pub struct Spawner { /// Queued subagents' launches, by id, kept until a slot frees (in memory: /// a restarted host reports them as not started). waiting: Mutex>, - /// `WARM_WAIT` (shorter in tests). - warm_wait: Duration, log: crate::brain::Log, } @@ -175,7 +165,6 @@ impl Spawner { no_workspace_reason: "this Chief host has nowhere to make cmux workspaces".to_owned(), pinned: false, waiting: Mutex::new(BTreeMap::new()), - warm_wait: WARM_WAIT, log, } } @@ -233,12 +222,6 @@ impl Spawner { s } - /// How long a Claude spawn waits for its first subagent's response. - pub fn with_warm_wait(mut self, wait: Duration) -> Spawner { - self.warm_wait = wait; - self - } - /// Why there are no workspaces (said in each spawn answer without them). pub fn with_no_workspace_reason(mut self, reason: impl Into) -> Spawner { self.no_workspace_reason = reason.into(); @@ -265,9 +248,7 @@ impl Spawner { view: &str, floor: Option<&str>, s: &SubagentSettings, - ttl: Option, - warm: Option>, - ) -> Result<(String, bool), String> { + ) -> Result { let began = Instant::now(); // Claude only through acpmux's own Claude Code adapter (harness_gate). let admitted = @@ -275,18 +256,12 @@ impl Spawner { crate::harness_gate::trace_refusal(&self.trace, "subagent", &s.harness, &reason); crate::harness_gate::refusal(&reason) })?; - // A Claude session on a preset with a system prompt takes the cached - // layout: our one mark ends the shared view, with the turns' TTL, and - // Claude Code is told the same TTL (the API refuses a 1h mark after a - // 5m one). - let mark = ttl - .filter(|_| admitted.family == crate::acpmux::Family::Claude) - .filter(|_| { - s.preset - .as_deref() - .is_some_and(|p| self.agents.system_prompt(p)) - }) - .and_then(|ttl| crate::prompt::Mark::last_whole(view, ttl)); + // No mark of ours in a subagent's first message: Claude Code marks + // its two system blocks and the last two messages of every later + // request in the session (each tool step), and the API takes at + // most 4 marks, so ours would fail the subagent's second request + // (Claude Code 2.1.287, measured 2026-10-08). Claude Code's own + // marks cache the long session step by step. // The workspace key is chosen first, so the session starts knowing // its workspace (CMUX_WORKSPACE_ID; acpmux per-session env). let key = self @@ -315,7 +290,6 @@ impl Spawner { env: key .iter() .map(|k| ("CMUX_WORKSPACE_ID".to_owned(), crate::workspaces::env_id(k))) - .chain(mark.map(|m| ttl_env(m.ttl))) .collect(), }; let session = self.agents.new_session(&spec)?; @@ -335,22 +309,11 @@ impl Spawner { let prompt_id = format!("{PROMPT_PREFIX}sub:{id}:{}", now_ms()); self.agents.start_prompt( &session, - match mark { - Some(mark) => { - crate::prompt::cached_layout_marked( - "", - view, - &format!("Your task:\n\n{task}"), - Some(mark), - ) - .blocks - } - None => crate::prompt::subagent_blocks(view, task), - }, + crate::prompt::subagent_blocks(view, task), &prompt_id, tx, )?; - self.forward_answer(id, rx, warm.map(|w| (session.clone(), w))); + self.forward_answer(id, rx); self.trace.emit( "subagent.start", json!({"id": id, "spawn": spawn, "session": session, "harness": s.harness, "harness_profile": admitted.profile, "harness_kind": admitted.kind, "harness_argv0": admitted.argv0, "ms": began.elapsed().as_millis() as u64}), @@ -362,10 +325,7 @@ impl Spawner { "subagent.workspace", json!({"id": id, "spawn": spawn, "error": self.trace.text(&self.no_workspace_reason)}), ); - return Ok(( - format!("no cmux workspace ({})", self.no_workspace_reason), - mark.is_some(), - )); + return Ok(format!("no cmux workspace ({})", self.no_workspace_reason)); }; let name = crate::workspaces::name(id, task); let key = key.unwrap_or_else(crate::workspaces::new_key); @@ -382,7 +342,7 @@ impl Spawner { key, name, }); - Ok((note, mark.is_some())) + Ok(note) } Err(e) => { (self.log)(&format!("subagent {id}: opening its workspace: {e}")); @@ -390,10 +350,7 @@ impl Spawner { "subagent.workspace", json!({"id": id, "spawn": spawn, "error": self.trace.text(&e)}), ); - Ok(( - format!("no cmux workspace (opening it failed: {e})"), - mark.is_some(), - )) + Ok(format!("no cmux workspace (opening it failed: {e})")) } } } @@ -449,37 +406,18 @@ impl Spawner { } } - /// Sends the prompt's answer (token use, cost) to the brain; with - /// `warm`, also says once when the response started streaming (the - /// request's cache entry exists), as the compactor's single-flight does. - fn forward_answer( - &self, - id: &str, - rx: std::sync::mpsc::Receiver, - warm: Option<(String, Sender<()>)>, - ) { + /// Sends the prompt's answer (token use, cost) to the brain. + fn forward_answer(&self, id: &str, rx: std::sync::mpsc::Receiver) { let tx = self .tx .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .clone(); let id = id.to_owned(); - let agents = self.agents.clone(); - let mut warm = warm; std::thread::spawn(move || { while let Ok(signal) = rx.recv() { match signal { - TurnSignal::Changed => { - let spoke = warm.as_ref().is_some_and(|(session, _)| { - agents.events(session, 0).is_ok_and(|events| { - events.iter().any(|e| crate::acpmux::is_output(&e.kind)) - }) - }); - if spoke && let Some((_, started)) = warm.take() { - let _ = started.send(()); - } - } - TurnSignal::Streamed => {} + TurnSignal::Changed | TurnSignal::Streamed => {} TurnSignal::Done(answer) => { let _ = tx.send(Input::SubagentAnswer { id, answer }); return; @@ -528,17 +466,8 @@ impl Spawner { return fail("the memory was still summarizing when its slot freed"); } let view = self.chat.render_view().text; - match self.start_one( - &w.spawn, - id, - &w.task, - &view, - w.floor.as_deref(), - &w.launch, - w.ttl, - None, - ) { - Ok((note, _)) => (self.log)(&format!("subagent {id} started from the queue: {note}")), + match self.start_one(&w.spawn, id, &w.task, &view, w.floor.as_deref(), &w.launch) { + Ok(note) => (self.log)(&format!("subagent {id} started from the queue: {note}")), Err(e) => fail(&e), } } @@ -560,18 +489,6 @@ impl Spawner { } } -/// The session env that gives Claude Code the TTL of our mark. -fn ttl_env(ttl: crate::prompt::CacheTtl) -> (String, String) { - match ttl { - crate::prompt::CacheTtl::OneHour => { - ("CLAUDE_CODE_PROMPT_CACHE_TTL".to_owned(), "1h".to_owned()) - } - crate::prompt::CacheTtl::FiveMinutes => { - ("FORCE_PROMPT_CACHING_5M".to_owned(), "1".to_owned()) - } - } -} - /// `asked` as a directory on this host: `~` and `~/...` are `home`; it must /// be absolute and exist. pub fn resolve_cwd(asked: &str, home: &Path) -> Result { @@ -657,7 +574,6 @@ impl Orchestrator for Spawner { task: task.clone(), floor: floor.clone(), launch: launch.clone(), - ttl: plan.ttl, }, ); lines.push(format!( @@ -665,34 +581,10 @@ impl Orchestrator for Spawner { )); continue; } - // Single flight on the shared view: the first subagent starts - // alone; the rest once its response began, so they read the - // view's cache entry instead of each writing it. - let first = started.is_empty(); - let rest = plan.ids.iter().filter(|i| !plan.queued.contains(i)).count() > 1; - let (warm_tx, warm_rx) = channel(); - let warm = (first && rest).then_some(warm_tx); - match self.start_one( - &plan.spawn, - id, - task, - &view, - floor.as_deref(), - &launch, - plan.ttl, - warm, - ) { - Ok((note, marked)) => { + match self.start_one(&plan.spawn, id, task, &view, floor.as_deref(), &launch) { + Ok(note) => { started.push(id.clone()); lines.push(format!("- {id}: {note}")); - if first && rest && marked { - let wait = Instant::now(); - let spoke = warm_rx.recv_timeout(self.warm_wait).is_ok(); - self.trace.emit( - "spawn.warm", - json!({"spawn": plan.spawn, "first": id, "started": spoke, "ms": wait.elapsed().as_millis() as u64}), - ); - } } Err(e) => { (self.log)(&format!("subagent {id} did not start: {e}")); diff --git a/Native/OptChat/optchat-chief/src/turn.rs b/Native/OptChat/optchat-chief/src/turn.rs index 5e26487db8e5..5f13ebcf5244 100644 --- a/Native/OptChat/optchat-chief/src/turn.rs +++ b/Native/OptChat/optchat-chief/src/turn.rs @@ -506,7 +506,7 @@ pub fn run_with_drafts( (e, m) => e.or(m), }; TurnOutcome { - reply: fold.final_text().map(str::to_owned), + reply: fold.final_text(), done_draft, cancelled, error, diff --git a/Native/OptChat/optchat-chief/src/workspaces.rs b/Native/OptChat/optchat-chief/src/workspaces.rs index 2fde1fc1fc15..f8afb1c70013 100644 --- a/Native/OptChat/optchat-chief/src/workspaces.rs +++ b/Native/OptChat/optchat-chief/src/workspaces.rs @@ -96,11 +96,19 @@ pub struct AppWorkspaces { impl AppWorkspaces { /// From the host's env: `CMUX_SOCKET_PATH` (None without it) and the - /// daemon socket. + /// app's daemon, where the app makes the workspaces. pub fn from_env(daemon: &str) -> Option { - crate::cli::env("CMUX_SOCKET_PATH").map(|control| AppWorkspaces { + AppWorkspaces::resolve(daemon, &crate::cli::env) + } + + /// `CMUX_SOCKET_PATH` from `env`, and the daemon that holds the app's + /// workspaces: `CMUX_APP_DAEMON_SOCKET` when the app sets it (the host's + /// `--daemon-socket` is then the Chief's conversation owner), else + /// `daemon` (cmux_env::app_daemon_socket). + pub fn resolve(daemon: &str, env: &dyn Fn(&str) -> Option) -> Option { + env("CMUX_SOCKET_PATH").map(|control| AppWorkspaces { control: control.into(), - daemon: daemon.into(), + daemon: crate::cmux_env::app_daemon_socket(daemon, env).into(), }) } } @@ -370,6 +378,23 @@ fn rename_by_key(daemon: &Path, key: &str, name: &str) -> Result<(), String> { #[cfg(test)] mod tests { + /// Live proof subp3: every done mark failed with "unknown workspace key": + /// the renames went to the Chief's conversation owner (--daemon-socket), + /// while the app makes the workspaces in its own daemon. + #[test] + fn app_workspaces_rename_in_the_apps_daemon() { + let env = |k: &str| match k { + "CMUX_SOCKET_PATH" => Some("/tmp/control.sock".to_owned()), + "CMUX_APP_DAEMON_SOCKET" => Some("/tmp/app-daemon.sock".to_owned()), + _ => None, + }; + let app = AppWorkspaces::resolve("/tmp/chief-owner.sock", &env).unwrap(); + assert_eq!(app.daemon, std::path::PathBuf::from("/tmp/app-daemon.sock")); + let without = |k: &str| (k == "CMUX_SOCKET_PATH").then(|| "/tmp/control.sock".to_owned()); + let app = AppWorkspaces::resolve("/tmp/own.sock", &without).unwrap(); + assert_eq!(app.daemon, std::path::PathBuf::from("/tmp/own.sock")); + } + use super::*; #[test] diff --git a/Native/OptChat/optchat-chief/tests/claude_stdio_only.rs b/Native/OptChat/optchat-chief/tests/claude_stdio_only.rs index f1259b724eb0..a313ad58506b 100644 --- a/Native/OptChat/optchat-chief/tests/claude_stdio_only.rs +++ b/Native/OptChat/optchat-chief/tests/claude_stdio_only.rs @@ -209,6 +209,7 @@ fn compactor_spec(dir: &std::path::Path) -> CompactorSpec { effort: None, timeout: Duration::from_secs(30), chief: "h0me".into(), + user_env: Default::default(), } } diff --git a/Native/OptChat/optchat-chief/tests/cmux_routing.rs b/Native/OptChat/optchat-chief/tests/cmux_routing.rs index 464e91fe726d..41b1386fec82 100644 --- a/Native/OptChat/optchat-chief/tests/cmux_routing.rs +++ b/Native/OptChat/optchat-chief/tests/cmux_routing.rs @@ -103,6 +103,7 @@ fn claude_settings_and_the_launcher_carry_the_pinned_socket() { env, instructions: None, tools: Tools::Mcp, + user_env: Default::default(), }; let paths = Paths::new(Path::new("/h")); let settings = settings_json( diff --git a/Native/OptChat/optchat-chief/tests/common/mod.rs b/Native/OptChat/optchat-chief/tests/common/mod.rs index 8a38eb313524..f46f7faa239f 100644 --- a/Native/OptChat/optchat-chief/tests/common/mod.rs +++ b/Native/OptChat/optchat-chief/tests/common/mod.rs @@ -443,6 +443,9 @@ pub struct Agents { /// The prompt's answer comes this long after its events (acpmux records /// `turn_end` before it answers the prompt). pub answer_delay: Option, + /// `new_session` of a session whose name contains the text takes this + /// long (a Claude Code process that starts slowly). + pub slow_session: Option<(String, Duration)>, /// Each session's turn signals, for `push_events`. pub signals: BTreeMap>, /// The `_acpmux/harnesses` answer; None: `catalog()` (claude-sr and @@ -581,6 +584,18 @@ impl FakeAgents { impl AgentPort for FakeAgents { fn new_session(&self, spec: &SessionSpec) -> Result { + let slow = self.inner.lock().unwrap().slow_session.clone(); + if let Some((part, delay)) = slow + && spec.name.contains(&part) + { + std::thread::sleep(delay); + } + // acpmux refuses any other session env key (acpmux session_env.rs ALLOWED_KEYS). + if let Some(key) = spec.env.keys().find(|k| k.as_str() != "CMUX_WORKSPACE_ID") { + return Err(format!( + "session/new: env key {key} is not one a session may set (allowed: CMUX_WORKSPACE_ID)" + )); + } let mut inner = self.inner.lock().unwrap(); let system = spec .preset diff --git a/Native/OptChat/optchat-chief/tests/compactor.rs b/Native/OptChat/optchat-chief/tests/compactor.rs index ed63f5e51bb0..141ba7246f66 100644 --- a/Native/OptChat/optchat-chief/tests/compactor.rs +++ b/Native/OptChat/optchat-chief/tests/compactor.rs @@ -57,6 +57,7 @@ fn spec(dir: &std::path::Path) -> CompactorSpec { effort: None, timeout: Duration::from_secs(30), chief: "h0me".into(), + user_env: Default::default(), } } @@ -856,15 +857,19 @@ fn the_compactor_presets_are_one_per_slot_with_allowlisted_args_and_a_system_pro let id = optchat_chief::paths::home_id(&home); for (k, p) in presets.iter().enumerate() { assert_eq!(p.name, format!("optchat-compact-{id}-slot-{k}")); - // acpmux's allowlist: no tools, no MCP servers, no transcript; the - // system prompt is the preset's text, never a path in the cwd. + // acpmux's allowlist: no tools, no MCP servers, no transcript, no + // user settings, no skills; the system prompt is the preset's text, + // never a path in the cwd. assert_eq!( p.args, vec![ "--tools", "", "--strict-mcp-config", - "--no-session-persistence" + "--no-session-persistence", + "--setting-sources", + "project", + "--disable-slash-commands" ] ); assert!(p.system_prompt.is_some(), "installed with a system prompt"); @@ -1468,9 +1473,7 @@ fn the_compactor_notice_is_posted_once_across_restarts_and_retracted_when_it_wor let posted = owner .messages .iter() - .find(|m| { - matches!(&m.parts[0], cmux_conversation::Part::Text { text: t, .. } if t == text) - }) + .find(|m| matches!(&m.parts[0], cmux_conversation::Part::Text { text: t, .. } if t == text)) .map(|m| m.id.clone()) .unwrap(); assert!( @@ -1604,5 +1607,178 @@ fn a_refused_marker_comes_back_after_ten_nodes() { for k in 1..=11 { assert!(markers(&inner.prompts[k]).is_empty(), "prompt {k}"); } - assert_eq!(markers(&inner.prompts[12]).len(), 1, "the 12th node tries the mark again"); + assert_eq!( + markers(&inner.prompts[12]).len(), + 1, + "the 12th node tries the mark again" + ); +} + +/// Claude Code without the model in its own table answers a failed call +/// with "[claude-code:unrecognized_model]" (2.1.287 on claude-haiku-5-5): +/// the compactor falls back to the turn model then too. +#[test] +fn an_unrecognized_model_counts_as_unavailable() { + assert!(optchat_chief::compactor::is_model_unavailable( + r#"[claude-code:unrecognized_model] {"model":"claude-haiku-5-5","query_source":"sdk"}"# + )); + assert!(!optchat_chief::compactor::is_model_unavailable( + "API Error: 529 overloaded" + )); +} + +/// An acpmux older than the isolation args refuses them: the preset is +/// installed with the args it knows (`--tools ""` and the rest) kept. +#[test] +fn an_older_acpmux_keeps_the_args_it_knows() { + use optchat_chief::acpmux::without_isolation_args; + let args: Vec = optchat_chief::compactor::COMPACTOR_ARGS + .iter() + .map(|a| json!(a)) + .collect(); + assert_eq!( + without_isolation_args(&args).unwrap(), + vec![ + json!("--tools"), + json!(""), + json!("--strict-mcp-config"), + json!("--no-session-persistence") + ] + ); + assert_eq!(without_isolation_args(&[json!("--tools"), json!("")]), None); + // A turn's built-in list goes too (its denied tools still apply). + let turn: Vec = optchat_chief::host::turn_isolation_args() + .into_iter() + .map(Value::String) + .collect(); + assert_eq!(without_isolation_args(&turn), Some(Vec::new())); + // An acpmux that knows the setting source but not a --tools list loses + // only the list: the turn keeps its setting-source isolation. + use optchat_chief::acpmux::without_tools_list; + assert_eq!( + without_tools_list(&turn), + Some(vec![ + json!("--setting-sources"), + json!("project"), + json!("--disable-slash-commands") + ]) + ); + assert_eq!(without_tools_list(&args), None, "--tools \"\" stays"); +} + +/// A compactor slot loads no user setting source, so its project settings +/// carry the env of the user's Claude Code settings (the user's API route). +#[test] +fn a_compactor_slot_carries_the_users_settings_env() { + let dir = tempfile::tempdir().unwrap(); + let agents = FakeAgents::new(Box::new(|_, _| answer("user: pasted a deploy log"))); + let spec = CompactorSpec { + user_env: [( + "ANTHROPIC_BASE_URL".to_owned(), + "http://router:31415".to_owned(), + )] + .into(), + ..spec(dir.path()) + }; + let compactor = AcpmuxCompactor::new(agents.clone(), spec, Slots::new(COMPACTOR_SESSIONS)); + run_node(&compactor, &request(1)).unwrap(); + let work = std::fs::canonicalize(dir.path().join("work")).unwrap(); + let settings: Value = serde_json::from_slice( + &std::fs::read(work.join("slot-0").join(".claude").join("settings.json")).unwrap(), + ) + .unwrap(); + assert_eq!(settings["env"]["ANTHROPIC_BASE_URL"], "http://router:31415"); +} + +/// Claude Code 2.1.287 does not know `claude-haiku-5-5` +/// ("[claude-code:unrecognized_model]") but takes the `haiku` alias, which +/// it maps to its current Haiku. A Claude Code compactor asks for the +/// alias; the Messages API route keeps the full id; another harness keeps +/// its own default. +#[test] +fn the_compactor_model_resolves_per_harness() { + use optchat_chief::compactor::compactor_model_for; + assert_eq!( + compactor_model_for(Family::Claude).as_deref(), + Some("haiku") + ); + assert_eq!(compactor_model_for(Family::Codex), None); + assert_eq!(compactor_model_for(Family::Other), None); + assert_eq!(Config::default().model, "claude-haiku-5-5"); +} + +/// The slot settings may hold the user's settings env (an API token among +/// it): the file is the user's alone (0600). +#[test] +fn a_compactor_slots_settings_file_is_private() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let agents = FakeAgents::new(Box::new(|_, _| answer("user: pasted a deploy log"))); + let spec = CompactorSpec { + user_env: [("ANTHROPIC_AUTH_TOKEN".to_owned(), "t".to_owned())].into(), + ..spec(dir.path()) + }; + let compactor = AcpmuxCompactor::new(agents.clone(), spec, Slots::new(COMPACTOR_SESSIONS)); + run_node(&compactor, &request(1)).unwrap(); + let work = std::fs::canonicalize(dir.path().join("work")).unwrap(); + let file = work.join("slot-0").join(".claude").join("settings.json"); + let mode = std::fs::metadata(&file).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600, "{mode:o}"); +} + +/// The API takes at most 4 marks per request, and Claude Code marks its two +/// system blocks plus the last two messages of every request after a +/// session's first (a size-loop follow-up): a node that carries our mark +/// runs Claude Code without its own; a node too short for one keeps them. +#[test] +fn a_marked_node_runs_claude_code_without_its_own_cache_marks() { + let dir = tempfile::tempdir().unwrap(); + let agents = FakeAgents::new(Box::new(|_, _| answer("user: a line"))); + agents.inner.lock().unwrap().system_prompts = true; + let compactor = compactor(&agents, dir.path()); + let settings = |k: usize| -> Value { + let cwd = agents.inner.lock().unwrap().specs[k].cwd.clone(); + serde_json::from_slice(&std::fs::read(cwd.join(".claude").join("settings.json")).unwrap()) + .unwrap() + }; + let marked = CompactRequest { + context: chat_of(150), + ..request(0) + }; + run_node(&compactor, &marked).unwrap(); + assert_eq!(markers(&agents.inner.lock().unwrap().prompts[0]).len(), 1); + assert_eq!(settings(0)["env"]["DISABLE_PROMPT_CACHING"], "1"); + run_node(&compactor, &request(1)).unwrap(); + assert!(markers(&agents.inner.lock().unwrap().prompts[1]).is_empty()); + let s = settings(1); + assert!(s["env"].get("DISABLE_PROMPT_CACHING").is_none(), "{s}"); +} + +/// hq-6d dogfood (fb211f1670ad): a node's line was stored only after its +/// slot's warm session had started (about 2.3 s of Claude Code start), so +/// every node, and the turn waiting for it, took that much longer. The warm +/// session now starts after the node returns. +#[test] +fn a_node_returns_before_its_slots_warm_session_starts() { + let dir = tempfile::tempdir().unwrap(); + let agents = FakeAgents::new(Box::new(|_, _| answer("user: pasted a deploy log"))); + agents.inner.lock().unwrap().system_prompts = true; + agents.inner.lock().unwrap().slow_session = Some(("warm".into(), Duration::from_secs(3))); + let compactor = compactor(&agents, dir.path()).with_warm(2).shared(); + let started = std::time::Instant::now(); + assert_eq!( + run_node(&*compactor, &request(1)).unwrap(), + "user: pasted a deploy log" + ); + assert!( + started.elapsed() < Duration::from_secs(2), + "the node waited for its slot's warm session: {:?}", + started.elapsed() + ); + // The warm session still starts, after the node. + let deadline = std::time::Instant::now() + WAIT; + while agents.inner.lock().unwrap().specs.len() < 2 { + assert!(std::time::Instant::now() < deadline, "no warm session"); + std::thread::sleep(Duration::from_millis(20)); + } } diff --git a/Native/OptChat/optchat-chief/tests/harness.rs b/Native/OptChat/optchat-chief/tests/harness.rs index 1da0a420f26a..597a73b22c3c 100644 --- a/Native/OptChat/optchat-chief/tests/harness.rs +++ b/Native/OptChat/optchat-chief/tests/harness.rs @@ -350,6 +350,7 @@ fn a_non_claude_harness_reads_its_instructions_from_agents_md_with_cli_memory_to env: Default::default(), instructions: None, tools: Tools::Cli(paths.bin.join("chief").display().to_string()), + user_env: Default::default(), }; optchat_chief::session_dir::write(&paths, &setup).unwrap(); let agents_md = std::fs::read_to_string(paths.session.join("AGENTS.md")).unwrap(); @@ -651,7 +652,140 @@ fn an_isolated_claude_turn_keeps_the_users_login() { assert_eq!(preset.system_prompt.as_deref(), Some("SYS")); } let codex = turn_preset(&paths, &home, "codex", Family::Codex, true, "SYS").unwrap(); - assert!(!codex.env.contains_key("CLAUDE_CONFIG_DIR"), "{:?}", codex.env); + assert!( + !codex.env.contains_key("CLAUDE_CONFIG_DIR"), + "{:?}", + codex.env + ); +} + +/// The reference's Claude Code path: Chief turns and compactor nodes load +/// no user settings, user MCP servers, user skills or slash commands +/// (`--setting-sources project --disable-slash-commands`; checked on Claude +/// Code 2.1.287: a user MCP server and a user skill leave the session's +/// init, the session directory's .mcp.json and denied tools stay). +/// Subagents keep the user's environment: they do real work. +#[test] +fn turns_and_the_compactor_load_no_user_settings_but_subagents_do() { + use optchat_chief::acpmux::Family; + use optchat_chief::host::{subagent_preset, turn_preset}; + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("mux"); + let paths = optchat_chief::paths::Paths::new(&home); + let isolated = ["--setting-sources", "project", "--disable-slash-commands"]; + for harness in ["claude", "claude-sr"] { + let turn = turn_preset(&paths, &home, harness, Family::Claude, true, "SYS").unwrap(); + // An allowlist of built-ins (checked on Claude Code 2.1.287: the + // session's init lists exactly these and the Chief's MCP tools), so + // a built-in a later Claude Code adds is not offered to a turn. + assert_eq!( + turn.args, + [ + "--setting-sources", + "project", + "--disable-slash-commands", + "--tools", + "Bash,Read,Edit,Write,WebFetch,WebSearch,ToolSearch" + ], + "{harness}" + ); + } + for preset in + optchat_chief::compactor::compactor_presets(&paths, &home, "claude", Family::Claude) + { + for word in isolated { + assert!( + preset.args.iter().any(|a| a == word), + "{}: {:?}", + preset.name, + preset.args + ); + } + } + let sub = subagent_preset( + &paths, + &home, + "optchat-sub-x".into(), + "claude", + Family::Claude, + true, + "SUB", + &Default::default(), + ); + assert!(sub.args.is_empty(), "{:?}", sub.args); + assert!(!sub.env.contains_key("CLAUDE_CODE_DISABLE_CLAUDE_MDS")); +} + +/// A turn that loads no user setting source still gets the env of the +/// user's Claude Code settings (the user's API route, for one: a Mac whose +/// subrouter route lives only in ~/.claude/settings.json). The session's own +/// env wins over it. +#[test] +fn the_session_settings_carry_the_users_settings_env() { + use optchat_chief::prompt::Tools; + use optchat_chief::session_dir::{SessionSetup, settings_json, user_settings_env}; + let dir = tempfile::tempdir().unwrap(); + let claude_home = dir.path().join("claude-home"); + std::fs::create_dir_all(&claude_home).unwrap(); + std::fs::write( + claude_home.join("settings.json"), + r#"{"env": {"ANTHROPIC_BASE_URL": "http://router:31415", "PATH": "/user/bin", "N": 3}, "hooks": {}}"#, + ) + .unwrap(); + let user_env = user_settings_env(&claude_home); + assert_eq!( + user_env.get("ANTHROPIC_BASE_URL").map(String::as_str), + Some("http://router:31415") + ); + assert!(!user_env.contains_key("N"), "string values only"); + assert!(user_settings_env(&dir.path().join("none")).is_empty()); + let paths = optchat_chief::paths::Paths::new(&dir.path().join("mux")); + let setup = SessionSetup { + exe: "/x/optchat-chief".into(), + cmux_mcp: None, + env: [("PATH".to_owned(), "/ours".to_owned())].into(), + instructions: None, + tools: Tools::Mcp, + user_env, + }; + let settings = settings_json(&setup, &paths, &[]); + assert_eq!(settings["env"]["ANTHROPIC_BASE_URL"], "http://router:31415"); + assert_eq!( + settings["env"]["PATH"], + format!("{}:/ours", paths.bin.display()), + "the session's own env wins" + ); +} + +/// The session's project settings may hold the user's settings env (an +/// API token among it): both settings files are the user's alone (0600); +/// the copy happens only on a macOS host (the user's own Mac, never a Linux +/// VM or dev backend image) and `OPTCHAT_COPY_USER_ENV=0` turns it off. +#[test] +fn the_session_settings_files_are_private_and_the_copy_is_gated() { + use optchat_chief::prompt::Tools; + use optchat_chief::session_dir::{SessionSetup, copy_user_env_allowed, write}; + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let paths = optchat_chief::paths::Paths::new(&dir.path().join("mux")); + paths.create().unwrap(); + let setup = SessionSetup { + exe: "/x/optchat-chief".into(), + cmux_mcp: None, + env: Default::default(), + instructions: None, + tools: Tools::Mcp, + user_env: [("ANTHROPIC_AUTH_TOKEN".to_owned(), "t".to_owned())].into(), + }; + write(&paths, &setup).unwrap(); + for name in ["settings.json", "settings.local.json"] { + let file = paths.session.join(".claude").join(name); + let mode = std::fs::metadata(&file).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600, "{name}: {mode:o}"); + } + assert!(!copy_user_env_allowed(Some("0"))); + assert_eq!(copy_user_env_allowed(None), cfg!(target_os = "macos")); + assert_eq!(copy_user_env_allowed(Some("1")), cfg!(target_os = "macos")); } /// Taelin: "opus 5.5 medium is the one I use, it scores better". Turns run diff --git a/Native/OptChat/optchat-chief/tests/live.rs b/Native/OptChat/optchat-chief/tests/live.rs index cd204c7429ca..7bdfd63e9808 100644 --- a/Native/OptChat/optchat-chief/tests/live.rs +++ b/Native/OptChat/optchat-chief/tests/live.rs @@ -363,6 +363,7 @@ fn two_turns_and_two_nodes_through_local_acp() { env, instructions: None, tools: tools.clone(), + user_env: Default::default(), }; session_dir::write(&paths, &setup).unwrap(); let system = system_text(None, &tools); diff --git a/Native/OptChat/optchat-chief/tests/steer.rs b/Native/OptChat/optchat-chief/tests/steer.rs index 9a8449227693..e35c853ac36e 100644 --- a/Native/OptChat/optchat-chief/tests/steer.rs +++ b/Native/OptChat/optchat-chief/tests/steer.rs @@ -84,3 +84,49 @@ fn a_message_during_a_turn_is_steered_in_not_a_stop() { assert_eq!(sends.len(), 1, "{sends:?}"); assert_eq!(sends[0].1, "Built, and the tests pass."); } + +/// Dogfood 2026-10-08 (subagent reports): a report that arrives while the +/// turn writes its reply, with no tool call left, is steered too. Claude +/// Code ends that answer (`result`) and answers the steered message as one +/// more turn of the same prompt; the posted reply holds both answers. +#[test] +fn a_report_steered_after_the_last_tool_call_keeps_both_answers() { + let mut h = Harness::new(Box::new(|turn, _| { + assert_eq!(turn, 0, "one turn answers both"); + vec![ + json!({"dir": "mux", "kind": "turn_started", "msg": {}}), + update( + "agent_message_chunk", + json!({"content": {"type": "text", "text": "a1 and a2 are done."}}), + ), + ] + })); + h.agents.inner.lock().unwrap().steering = true; + h.agents.hold(true); + h.connect(); + h.say("user_local", "[a1] done\n\n[a2] done"); + h.step(); // settled: the turn starts + h.step(); // the turn's session exists + h.agents.wait_prompts(1); + h.say("user_local", "[a3] done"); + h.agents.wait_steers(1); + h.agents.push_events( + "s1", + vec![ + json!({"dir": "in", "kind": "claude.result.success", "msg": {"type": "result", "subtype": "success", "result": "a1 and a2 are done."}}), + json!({"dir": "in", "kind": "claude.user", "msg": {"type": "user", "isReplay": true, "message": {"content": "[a3] done"}}}), + update( + "agent_message_chunk", + json!({"content": {"type": "text", "text": "a3 is done too."}}), + ), + json!({"dir": "mux", "kind": "turn_end", "msg": {"stopReason": "end_turn"}}), + ], + ); + h.agents.hold(false); + h.agents.release(); + h.settle(); + assert!(h.agents.inner.lock().unwrap().cancels.is_empty()); + let sends = h.owner.lock().unwrap().sends(); + assert_eq!(sends.len(), 1, "{sends:?}"); + assert_eq!(sends[0].1, "a1 and a2 are done.\n\na3 is done too."); +} diff --git a/Native/OptChat/optchat-chief/tests/subagents.rs b/Native/OptChat/optchat-chief/tests/subagents.rs index d2e0fc0a88d7..4d828bc3e29f 100644 --- a/Native/OptChat/optchat-chief/tests/subagents.rs +++ b/Native/OptChat/optchat-chief/tests/subagents.rs @@ -725,12 +725,15 @@ fn the_close_setting_closes_a_finished_subagents_workspace() { ); } -/// A Claude spawn of many subagents: the first starts alone and warms the -/// cache of the shared view; the rest start once its response began, each -/// first message marked at the view's end with the turns' TTL (1 hour by -/// default), and Claude Code told the same TTL. +/// A Claude spawn of many subagents takes no mark of ours: Claude Code +/// marks its two system blocks and the last two messages of every later +/// request in a session (each tool step), and the API takes at most 4 +/// marks, so a mark of ours would fail the subagent's second request +/// (measured on Claude Code 2.1.287, 2026-10-08). Claude Code's own marks +/// cache the subagent's session step by step; with no shared mark there is +/// nothing to warm, so all start at once. #[test] -fn a_claude_spawn_warms_the_shared_view_once_then_starts_the_rest_marked() { +fn a_claude_spawn_starts_its_subagents_without_a_mark_of_ours() { let mut s = setup(); s.h.agents.inner.lock().unwrap().system_prompts = true; for k in 0..12 { @@ -748,55 +751,26 @@ fn a_claude_spawn_warms_the_shared_view_once_then_starts_the_rest_marked() { .collect(); assert_eq!(subs.len(), 3); for k in &subs { - let marks: Vec<&Value> = agents.prompts[*k] - .iter() - .filter_map(|b| b.get("cache_control")) - .collect(); - assert_eq!( - marks, - vec![&json!({"type": "ephemeral", "ttl": "1h"})], - "one 1h mark on the shared view: {:?}", + assert!( + agents.prompts[*k] + .iter() + .all(|b| b.get("cache_control").is_none()), + "no mark of ours in a subagent's first message: {:?}", agents.prompts[*k] - ); - } - // The same view blocks up to the mark in every first message. - let upto = |k: usize| { - let p = &agents.prompts[k]; - let m = p - .iter() - .position(|b| b.get("cache_control").is_some()) - .unwrap(); - p[..=m].to_vec() - }; - assert_eq!(upto(subs[0]), upto(subs[1])); - assert_eq!(upto(subs[0]), upto(subs[2])); - let sub_specs: Vec<_> = agents - .specs - .iter() - .filter(|sp| sp.name.starts_with("optchat-sub-h0me-")) - .collect(); - for spec in &sub_specs { - assert_eq!( - spec.env - .get("CLAUDE_CODE_PROMPT_CACHE_TTL") - .map(String::as_str), - Some("1h"), - "Claude Code marks with the same TTL" ); } drop(agents); let events = trace_events(&s.traces); - let warm = events - .iter() - .find(|e| e["ev"] == "spawn.warm") - .expect("the trace says the shared view was warmed"); - assert_eq!(warm["first"], "a1"); - assert_eq!(warm["started"], true, "{warm}"); + assert!( + events.iter().all(|e| e["ev"] != "spawn.warm"), + "nothing to warm without a shared mark" + ); } +/// With no shared mark, no subagent waits for the first one to speak. #[test] -fn the_rest_start_after_the_warm_wait_when_the_first_never_speaks() { - let mut s = setup_with(|sp| sp.with_warm_wait(std::time::Duration::from_millis(300))); +fn no_subagent_waits_for_a_silent_first_one() { + let mut s = setup(); s.h.agents.inner.lock().unwrap().system_prompts = true; for k in 0..12 { s.h.say("user_local", &format!("line {k}")); @@ -806,13 +780,44 @@ fn the_rest_start_after_the_warm_wait_when_the_first_never_speaks() { s.h.agents.hold(true); let began = std::time::Instant::now(); spawn(&mut s, &["silent", "two"]).unwrap(); - assert!(began.elapsed() >= std::time::Duration::from_millis(300)); + assert!(began.elapsed() < std::time::Duration::from_millis(300)); s.h.agents.hold(false); s.h.agents.release(); - assert_eq!(sub_names(&s).len(), 2, "the second still starts"); - let warm = trace_events(&s.traces) - .into_iter() - .find(|e| e["ev"] == "spawn.warm") - .unwrap(); - assert_eq!(warm["started"], false, "{warm}"); + assert_eq!(sub_names(&s).len(), 2, "the second starts at once"); +} + +/// A spawn in a directory of the user's gets no mark: the TTL Claude Code +/// marks with there is not ours to set, and nothing is written into it. +#[test] +fn a_claude_spawn_in_the_users_directory_takes_no_mark() { + let mut s = setup(); + s.h.agents.inner.lock().unwrap().system_prompts = true; + for k in 0..12 { + s.h.say("user_local", &format!("line {k}")); + s.h.settle(); + } + let theirs = tempfile::tempdir().unwrap(); + let dir = theirs.path().display().to_string(); + call(&mut s, move |sp| { + sp.spawn(vec!["one".into(), "two".into()], Some(dir)) + }) + .unwrap(); + let agents = s.h.agents.inner.lock().unwrap(); + let subs: Vec<&Vec> = agents + .prompt_ids + .iter() + .zip(&agents.prompts) + .filter(|(id, _)| id.starts_with("optchat-sub:")) + .map(|(_, p)| p) + .collect(); + assert_eq!(subs.len(), 2); + assert!( + subs.iter() + .all(|p| p.iter().all(|b| b.get("cache_control").is_none())), + "no mark" + ); + assert!( + !theirs.path().join(".claude").exists(), + "nothing written there" + ); } diff --git a/Native/OptChat/optchat-chief/tests/turn_cache.rs b/Native/OptChat/optchat-chief/tests/turn_cache.rs index fa0a16c716b9..4e22cecf8ce4 100644 --- a/Native/OptChat/optchat-chief/tests/turn_cache.rs +++ b/Native/OptChat/optchat-chief/tests/turn_cache.rs @@ -462,3 +462,93 @@ fn a_refused_marker_comes_back_after_ten_turns() { "turn 11 tries the mark again" ); } + +/// The last turn's mark survives a host restart (it is saved with the +/// turn's messages): the first turn after the restart still marks within +/// the API's lookback of it, after a long tool run. +#[test] +fn the_last_turns_mark_survives_a_restart() { + let mut h = claude_harness(None); + fill(&h.chat, 0, 1_200); + h.connect(); + h.say("user_local", "one"); + h.settle(); + let before = h.agents.inner.lock().unwrap().prompts[0].clone(); + let Harness { + dir, + chat, + owner, + brain, + .. + } = h; + drop(brain); + chat.shutdown(); + drop(chat); + let mut h = Harness::in_dir(dir, default_script(), owner); + h.agents.inner.lock().unwrap().system_prompts = true; + fill(&h.chat, 1_200, 160); + h.connect(); + h.say("user_local", "two"); + h.settle(); + let inner = h.agents.inner.lock().unwrap(); + let after = inner.prompts.last().unwrap(); + let (ma, mb) = (markers(&before)[0], markers(after)[0]); + assert_eq!(texts(&before)[..=ma], texts(after)[..=ma]); + assert!( + mb >= ma && mb - ma <= 20, + "marks {ma} then {mb} across the restart" + ); +} + +/// Claude Code's own cache marks per request, measured on 2.1.287 through +/// a capture proxy on both the subscription login and the subrouter +/// (2026-10-08): its two system blocks, then the last message on a +/// session's first request, and the last TWO messages on every later +/// request (a tool step, a follow-up prompt, a steered message). None with +/// DISABLE_PROMPT_CACHING=1 in the session's settings env. +fn claude_code_marks(settings: &Value, later: bool) -> usize { + if settings["env"]["DISABLE_PROMPT_CACHING"] == "1" { + 0 + } else if later { + 4 + } else { + 3 + } +} + +/// The API takes at most 4 marks per request. A turn that carries our view +/// mark runs Claude Code without its own (its mark stays in the history of +/// every later request of the session); a turn too short to carry ours +/// keeps Claude Code's. +#[test] +fn every_turn_request_shape_stays_within_four_cache_marks() { + use optchat_chief::prompt::CacheTtl; + for (lines, marked) in [(0, false), (1_200, true)] { + let mut h = claude_harness(None); + fill(&h.chat, 0, lines); + h.connect(); + h.say("user_local", "one"); + h.settle(); + let ours = { + let inner = h.agents.inner.lock().unwrap(); + markers(&inner.prompts[0]).len() + }; + assert_eq!(ours, usize::from(marked), "view of {lines} lines"); + let settings = session_settings(&h, "settings.json"); + for later in [false, true] { + let total = ours + claude_code_marks(&settings, later); + assert!( + total <= 4, + "view of {lines} lines, {} request: {total} marks", + if later { "a later" } else { "the first" } + ); + } + } + // A session without our mark keeps Claude Code's own cache marks. + let dir = tempfile::tempdir().unwrap(); + optchat_chief::session_dir::set_session_cache(dir.path(), CacheTtl::OneHour, true).unwrap(); + optchat_chief::session_dir::set_session_cache(dir.path(), CacheTtl::OneHour, false).unwrap(); + let path = dir.path().join(".claude").join("settings.json"); + let s: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); + assert!(s["env"].get("DISABLE_PROMPT_CACHING").is_none(), "{s}"); +} diff --git a/Native/OptChat/optchat-chief/tests/turn_tools.rs b/Native/OptChat/optchat-chief/tests/turn_tools.rs index 1301076984a6..4499f096df27 100644 --- a/Native/OptChat/optchat-chief/tests/turn_tools.rs +++ b/Native/OptChat/optchat-chief/tests/turn_tools.rs @@ -56,6 +56,7 @@ fn setup() -> SessionSetup { env: BTreeMap::from([("MUX_HOME".into(), "/h".into())]), instructions: None, tools: optchat_chief::prompt::Tools::Mcp, + user_env: Default::default(), } } diff --git a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGrid.swift b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGrid.swift index 14893bfaf8f4..43a0633ccb13 100644 --- a/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGrid.swift +++ b/Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGrid.swift @@ -3,6 +3,9 @@ import Foundation public enum MobileTerminalRenderGridError: Error, Equatable, Sendable { case invalidFormat(String) case invalidDimensions(columns: Int, rows: Int) + /// Past the replay's bounds (`maximumDimension`, `maximumScrollbackRows`, + /// `maximumReplayCells`), or more rows scrolled than the frame holds. + case invalidSize(columns: Int, rows: Int, scrollbackRows: Int, scrolledRows: Int) case invalidRow(Int) case invalidColumn(Int) case invalidCursor(row: Int, column: Int) @@ -12,6 +15,17 @@ public enum MobileTerminalRenderGridError: Error, Equatable, Sendable { public struct MobileTerminalRenderGridFrame: Codable, Equatable, Sendable { public static let currentFormat = "cmux.render-grid.v1" + /// Largest column or row count a frame may carry: the Mac producer clamps + /// to the same 4096 (`DaemonRenderGridState.maxDimension`). + public static let maximumDimension = 4_096 + /// Largest scrollback row count a frame may carry: Macs clamp requested + /// scrollback to `MobileTerminalScrollbackPreference.maximumRows`, and a + /// burst delta carries at most 2000 rows. + public static let maximumScrollbackRows = MobileTerminalScrollbackPreference.maximumRows + /// Largest `columns * (rows + scrollbackRows)` a frame may carry. A full + /// replay pads every line to `columns`, so this bounds the bytes a frame + /// makes the phone build (about 32 MB of cells). + public static let maximumReplayCells = 32 * 1_024 * 1_024 public var format: String public var surfaceID: String @@ -148,6 +162,17 @@ public struct MobileTerminalRenderGridFrame: Codable, Equatable, Sendable { guard columns > 0, rows > 0 else { throw MobileTerminalRenderGridError.invalidDimensions(columns: columns, rows: rows) } + // A frame past what any Mac sends would make the phone's replay build + // an unbounded byte stream (crash program phase 3, + // MobileProtocolFuzzTests): reject it as malformed. Every product + // below is of values already bounded, so nothing overflows. + guard columns <= Self.maximumDimension, rows <= Self.maximumDimension, + scrollbackRows <= Self.maximumScrollbackRows, + columns * (rows + max(0, scrollbackRows)) <= Self.maximumReplayCells, + scrolledRows <= rows + max(0, scrollbackRows) else { + throw MobileTerminalRenderGridError.invalidSize( + columns: columns, rows: rows, scrollbackRows: scrollbackRows, scrolledRows: scrolledRows) + } if let cursor, !(0.. 0, span.column + width <= columns else { + guard width > 0, width <= columns - span.column else { throw MobileTerminalRenderGridError.invalidSpanWidth( row: span.row, column: span.column, @@ -191,7 +216,7 @@ public struct MobileTerminalRenderGridFrame: Codable, Equatable, Sendable { throw MobileTerminalRenderGridError.invalidStyleID(span.styleID) } let width = span.gridCellWidth - guard width > 0, span.column + width <= columns else { + guard width > 0, width <= columns - span.column else { throw MobileTerminalRenderGridError.invalidSpanWidth( row: span.row, column: span.column, diff --git a/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileProtocolFuzzTests.swift b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileProtocolFuzzTests.swift new file mode 100644 index 000000000000..8d7789dfbfb7 --- /dev/null +++ b/Packages/Shared/CMUXMobileCore/Tests/CMUXMobileCoreTests/MobileProtocolFuzzTests.swift @@ -0,0 +1,147 @@ +import Foundation +import Testing +@testable import CMUXMobileCore + +/// Crash program phase 3 (plans/cmux-next/crash-elimination.md section 7): +/// every decoder that reads bytes from the network (a paired Mac or phone, +/// a relay) returns a value or a typed error for any input and never traps. +/// Seeded mutation of valid encodings plus random bytes; a trap fails the run. +@Suite struct MobileProtocolFuzzTests { + struct Rng { + var state: UInt64 + mutating func next() -> UInt64 { + state ^= state << 13; state ^= state >> 7; state ^= state << 17 + return state + } + mutating func below(_ n: Int) -> Int { Int(next() % UInt64(max(n, 1))) } + } + + static func mutate(_ data: Data, _ rng: inout Rng) -> Data { + var bytes = [UInt8](data) + for _ in 0..<(1 + rng.below(4)) { + switch rng.below(5) { + case 0 where !bytes.isEmpty: bytes[rng.below(bytes.count)] = UInt8(truncatingIfNeeded: rng.next()) + case 1 where !bytes.isEmpty: bytes.removeSubrange(rng.below(bytes.count)...) + case 2: bytes.insert(UInt8(truncatingIfNeeded: rng.next()), at: rng.below(bytes.count + 1)) + case 3 where bytes.count > 1: bytes.swapAt(rng.below(bytes.count), rng.below(bytes.count)) + default: bytes += bytes.prefix(rng.below(bytes.count + 1)) + } + } + return Data(bytes) + } + + static func random(_ rng: inout Rng, _ limit: Int = 64) -> Data { + Data((0.. 100, "the mutations must also produce frames that decode") + } + + @Test func renderGridSizeLimitsAcceptTheMaximumAndRefuseOnePast() throws { + func frame(_ fields: String) -> Data { + Data(#"{"format":"cmux.render-grid.v1","surface_id":"l","state_seq":1,"full":true,"row_spans":[],\#(fields)}"#.utf8) + } + let max = MobileTerminalRenderGridFrame.maximumDimension + _ = try MobileTerminalRenderGridFrame.decode(frame(#""columns":\#(max),"rows":2"#)) + #expect(throws: MobileTerminalRenderGridError.self) { + try MobileTerminalRenderGridFrame.decode(frame(#""columns":\#(max + 1),"rows":2"#)) + } + let scrollback = MobileTerminalRenderGridFrame.maximumScrollbackRows + _ = try MobileTerminalRenderGridFrame.decode(frame(#""columns":80,"rows":24,"scrollback_rows":\#(scrollback)"#)) + #expect(throws: MobileTerminalRenderGridError.self) { + try MobileTerminalRenderGridFrame.decode(frame(#""columns":80,"rows":24,"scrollback_rows":\#(scrollback + 1)"#)) + } + // Wide and tall within each limit, but past the replay's cell budget. + #expect(throws: MobileTerminalRenderGridError.self) { + try MobileTerminalRenderGridFrame.decode(frame(#""columns":\#(max),"rows":\#(max),"scrollback_rows":\#(scrollback)"#)) + } + let delta = #"{"format":"cmux.render-grid.v1","surface_id":"l","state_seq":1,"full":false,"anchor":"screen","columns":4,"rows":2,"row_spans":[],"scrollback_rows":1,"scrolled_rows":"# + _ = try MobileTerminalRenderGridFrame.decode(Data((delta + "3}").utf8)) + #expect(throws: MobileTerminalRenderGridError.self) { + try MobileTerminalRenderGridFrame.decode(Data((delta + "\(Int.max)}").utf8)) + } + } + + @Test func attachTicketsDecodeOrThrowForAnyBytes() { + var rng = Rng(state: 0x54) + let coder = CmxAttachTicketCompactCoder() + for _ in 0..<2_000 { + _ = try? coder.decode(Self.random(&rng, 200)) + _ = try? coder.decode(Self.mutate(Data(#"{"v":1,"h":"x","p":1}"#.utf8), &rng)) + } + } +} diff --git a/Packages/Shared/CmuxAgentBrands/Sources/CmuxAgentBrands/AgentBrandCatalog+Generated.swift b/Packages/Shared/CmuxAgentBrands/Sources/CmuxAgentBrands/AgentBrandCatalog+Generated.swift index 2e9a90e9ed53..ac518114d5d1 100644 --- a/Packages/Shared/CmuxAgentBrands/Sources/CmuxAgentBrands/AgentBrandCatalog+Generated.swift +++ b/Packages/Shared/CmuxAgentBrands/Sources/CmuxAgentBrands/AgentBrandCatalog+Generated.swift @@ -415,6 +415,7 @@ extension AgentBrandCatalog { "gemini": .gemini, "gemini-cli": .gemini, "github-copilot": .copilot, + "github-copilot-cli": .copilot, "goose": .goose, "grok": .grok, "grok-cli": .grok, @@ -499,6 +500,13 @@ extension AgentBrandCatalog { ("dsh", .deepseek), ("gemini cli", .gemini), ("xai", .grok), + ("github-copilot-cli", .copilot), + ("grok-build", .grok), + ("factory-droid", .factory), + ("qwen-code", .qwen), + ("antigravity-acp", .antigravity), + ("amp-acp", .amp), + ("codebuddy-code", .codebuddy), ("prime-agent", nil), ("campfire", nil), ("piper", nil), diff --git a/Packages/Shared/CmuxHomeRender/Sources/CmuxHomeRender/Media/VideoPlayback.swift b/Packages/Shared/CmuxHomeRender/Sources/CmuxHomeRender/Media/VideoPlayback.swift index 020f149bc784..1472dfc00ffe 100644 --- a/Packages/Shared/CmuxHomeRender/Sources/CmuxHomeRender/Media/VideoPlayback.swift +++ b/Packages/Shared/CmuxHomeRender/Sources/CmuxHomeRender/Media/VideoPlayback.swift @@ -126,10 +126,12 @@ public final class VideoPlayback { let center = NotificationCenter.default entry.observers = [ center.addObserver(forName: AVPlayerItem.didPlayToEndTimeNotification, object: item, queue: .main) { [weak self] _ in + // main-proof: addObserver(queue: .main) runs this block on the main queue. MainActor.assumeIsolated { self?.ended(key) } }, center.addObserver(forName: AVPlayerItem.failedToPlayToEndTimeNotification, object: item, queue: .main) { [weak self, weak media] _ in + // main-proof: addObserver(queue: .main) runs this block on the main queue. MainActor.assumeIsolated { guard let media else { return } self?.failed(key, media: media) diff --git a/Packages/Shared/CmuxHomeRender/Sources/CmuxHomeRender/Public/HomeStoreBinding.swift b/Packages/Shared/CmuxHomeRender/Sources/CmuxHomeRender/Public/HomeStoreBinding.swift index e4321c544fc0..2f8aa1047f8a 100644 --- a/Packages/Shared/CmuxHomeRender/Sources/CmuxHomeRender/Public/HomeStoreBinding.swift +++ b/Packages/Shared/CmuxHomeRender/Sources/CmuxHomeRender/Public/HomeStoreBinding.swift @@ -139,6 +139,7 @@ public final class HomeStoreBinding { let id = conversation if Thread.isMainThread { let hooks = hooks + // main-proof: this branch runs only when Thread.isMainThread is true (checked above). MainActor.assumeIsolated { store.close(id) store.unregister(hooks) diff --git a/Packages/Shared/CmuxHomeRender/Tests/CmuxHomeRenderTests/VideoMainDeliveryTests.swift b/Packages/Shared/CmuxHomeRender/Tests/CmuxHomeRenderTests/VideoMainDeliveryTests.swift new file mode 100644 index 000000000000..5c3b13d6396d --- /dev/null +++ b/Packages/Shared/CmuxHomeRender/Tests/CmuxHomeRenderTests/VideoMainDeliveryTests.swift @@ -0,0 +1,38 @@ +import AVFoundation +import CmuxHomeCore +import Foundation +import Testing +@testable import CmuxHomeRender + +/// AVPlayerItem posts its end and failure notifications on its own threads; +/// VideoPlayback observes them on the main queue, so its handler runs on the +/// main actor (`// main-proof:`), never on the posting thread. +@MainActor @Suite struct VideoMainDeliveryTests { + final class FileSource: HomeVideoSource { + let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("video-main-delivery.mov") + func originalURL(for ref: AttachmentRef) async throws -> URL { url } + } + + @Test func anEndPostedOffMainIsHandledOnMain() async throws { + let playback = VideoPlayback() + let source = FileSource() + let key = "row-1" + var changedOnMain: [Bool] = [] + playback.onChange = { _ in changedOnMain.append(Thread.isMainThread) } + playback.toggle(key, ref: AttachmentFixtures.video, media: source) + for _ in 0..<200 where playback.state(key) != .playing { try await Task.sleep(for: .milliseconds(5)) } + #expect(playback.state(key) == .playing) + let item = try #require(playback.layer(key)?.player?.currentItem) + let postedOffMain = await withCheckedContinuation { (done: CheckedContinuation) in + DispatchQueue.global().async { + let offMain = !Thread.isMainThread + NotificationCenter.default.post(name: AVPlayerItem.didPlayToEndTimeNotification, object: item) + done.resume(returning: offMain) + } + } + #expect(postedOffMain, "the notification was posted off main") + for _ in 0..<200 where playback.state(key) != .paused { try await Task.sleep(for: .milliseconds(5)) } + #expect(playback.state(key) == .paused, "the end returned the video to the start, paused") + #expect(changedOnMain.allSatisfy { $0 }, "every change ran on main") + } +} diff --git a/Packages/Shared/CmuxMessagesLab/Patches/Sources__MessagesLabSidebar__Vendor__appkit-native__SidebarDrawing.swift.patch b/Packages/Shared/CmuxMessagesLab/Patches/Sources__MessagesLabSidebar__Vendor__appkit-native__SidebarDrawing.swift.patch new file mode 100644 index 000000000000..51329d18d044 --- /dev/null +++ b/Packages/Shared/CmuxMessagesLab/Patches/Sources__MessagesLabSidebar__Vendor__appkit-native__SidebarDrawing.swift.patch @@ -0,0 +1,94 @@ +--- a/Sources/MessagesLabSidebar/Vendor/appkit-native/SidebarDrawing.swift ++++ b/Sources/MessagesLabSidebar/Vendor/appkit-native/SidebarDrawing.swift +@@ -1,3 +1,4 @@ ++import os // cmux: OSAllocatedUnfairLock for the monogram font cache + import AppKit + import CoreText + +@@ -94,7 +95,7 @@ + + /// The drawing: pure functions of a summary and a render context (any thread). + enum SidebarDraw { +- static let p3 = CGColorSpace(name: CGColorSpace.displayP3)! ++ static let p3 = CGColorSpace(name: CGColorSpace.displayP3) ?? CGColorSpaceCreateDeviceRGB() // cmux: no force unwrap + /// Where `AvatarSpec.image` paths resolve (the host sets it; default: the app bundle's + /// "assets" folder). + static var assetDirectory: URL? = Bundle.main.resourceURL?.appendingPathComponent("assets") +@@ -104,11 +105,31 @@ + guard !images.isEmpty else { return } + DispatchQueue.main.async { DispatchQueue.global(qos: .utility).async { withExtendedLifetime(images) {} } } + } +- static let nameFont = CTFontCreateUIFontForLanguage(.emphasizedSystem, SidebarMetrics.nameSize, nil)! +- static let previewFont = CTFontCreateUIFontForLanguage(.system, SidebarMetrics.previewSize, nil)! +- static let timeFont = CTFontCreateUIFontForLanguage(.system, SidebarMetrics.timeSize, nil)! +- static let pinNameFont = CTFontCreateUIFontForLanguage(.system, SidebarMetrics.pinNameSize, nil)! +- static let bubbleFont = CTFontCreateUIFontForLanguage(.system, 11, nil)! ++ // cmux: no force unwrap: Core Text's UI font lookup returns an optional (crash program, cx-qpqs class). ++ static let nameFont = uiFont(.emphasizedSystem, SidebarMetrics.nameSize) ++ static let previewFont = uiFont(.system, SidebarMetrics.previewSize) ++ static let timeFont = uiFont(.system, SidebarMetrics.timeSize) ++ static let pinNameFont = uiFont(.system, SidebarMetrics.pinNameSize) ++ static let bubbleFont = uiFont(.system, 11) ++ ++ // cmux: the UI font, or Helvetica at that size when Core Text returns none. ++ static func uiFont(_ type: CTFontUIFontType, _ size: CGFloat) -> CTFont { ++ CTFontCreateUIFontForLanguage(type, size, nil) ?? CTFontCreateWithName("Helvetica" as CFString, size, nil) ++ } ++ ++ // cmux: monogram fonts held per half point for the process: avatars draw on ++ // concurrentPerform threads, and a font made and dropped per draw can come ++ // back nil there (cx-qpqs). ++ private static let monogramFonts = OSAllocatedUnfairLock<[CGFloat: CTFont]>(initialState: [:]) ++ static func monogramFont(_ size: CGFloat) -> CTFont { ++ let key = (size * 2).rounded() / 2 ++ return monogramFonts.withLock { fonts in ++ if let held = fonts[key] { return held } ++ let font = uiFont(.emphasizedSystem, key) ++ fonts[key] = font ++ return font ++ } ++ } + + /// A flipped (top-left origin) bitmap in the context's color space at its scale. + static func bitmap(size: CGSize, ctx: SidebarRenderContext, _ draw: (CGContext) -> Void) -> CGImage { +@@ -170,10 +191,11 @@ + case let .monogram(m): + g.saveGState() + g.addEllipse(in: r); g.clip() +- let grad = CGGradient(colorsSpace: nil, colors: [p.monogramTop, p.monogramBottom] as CFArray, locations: [0, 1])! ++ // cmux: an optional gradient draws nothing when it fails (SidebarCrashSafe). ++ let grad = CGGradient(colorsSpace: nil, colors: [p.monogramTop, p.monogramBottom] as CFArray, locations: [0, 1]) + g.drawLinearGradient(grad, start: CGPoint(x: r.midX, y: r.minY), end: CGPoint(x: r.midX, y: r.maxY), options: []) + g.restoreGState() +- let font = CTFontCreateUIFontForLanguage(.emphasizedSystem, (r.width * 0.42).rounded(), nil)! ++ let font = monogramFont((r.width * 0.42).rounded()) // cmux: held, no force unwrap (cx-qpqs) + let white = CGColor(gray: 1, alpha: 1) + let l = line(m.uppercased(), font, white) + let lw = width(l) +@@ -230,7 +252,7 @@ + /// the visible rows' text at the exact width in every frame. + static func rowTime(_ c: ConversationSummary, emphasized: Bool, ctx: SidebarRenderContext, time: ConversationTimeFormatter) -> CGImage { + let p = ctx.palette +- let secondary = emphasized ? p.selectedText.copy(alpha: 0.82)! : p.secondary ++ let secondary = emphasized ? p.selectedText.copy(alpha: 0.82) ?? p.selectedText : p.secondary // cmux: no force unwrap + // `.distantPast`: a row without a time (the host's extra search results). + let tl = line(c.lastAt == .distantPast ? "" : time.string(c.lastAt, now: ctx.now), timeFont, secondary) + let bell = c.muted ? (emphasized ? ctx.bellSelected : ctx.bellSecondary) : nil +@@ -295,7 +317,7 @@ + /// The title of the host's extra search section: 11 pt semibold, secondary, at the row + /// text's x, baseline 20 pt in a 28 pt band (to verify against Messages' search sections). + static func sectionHeader(_ title: String, width: CGFloat, ctx: SidebarRenderContext) -> CGImage { +- let font = CTFontCreateUIFontForLanguage(.emphasizedSystem, 11, nil)! ++ let font = uiFont(.emphasizedSystem, 11) // cmux: no force unwrap (cx-qpqs) + let l = truncated(line(title, font, ctx.palette.secondary), width - 2 * SidebarMetrics.selectionInsetX - 10, font, ctx.palette.secondary) + return bitmap(size: CGSize(width: max(1, width), height: 28), ctx: ctx) { g in + draw(l, x: SidebarMetrics.selectionInsetX + 10, baseline: 20, g) +@@ -469,7 +491,7 @@ + if let m = map[k] { lock.unlock(); return m } + lock.unlock() + let nameColor = emphasized ? p.selectedText : p.name +- let secondary = emphasized ? p.selectedText.copy(alpha: 0.82)! : p.secondary ++ let secondary = emphasized ? p.selectedText.copy(alpha: 0.82) ?? p.selectedText : p.secondary // cmux: no force unwrap + let text = (c.lastReaction.map(SidebarStrings.reaction) ?? c.preview).replacingOccurrences(of: "\n", with: " ") + let attr = NSAttributedString(string: text, attributes: [ + NSAttributedString.Key(kCTFontAttributeName as String): SidebarDraw.previewFont, diff --git a/Packages/Shared/CmuxMessagesLab/Patches/Sources__MessagesLabSidebar__Vendor__appkit-native__SidebarModel.swift.patch b/Packages/Shared/CmuxMessagesLab/Patches/Sources__MessagesLabSidebar__Vendor__appkit-native__SidebarModel.swift.patch new file mode 100644 index 000000000000..35a6a02af4be --- /dev/null +++ b/Packages/Shared/CmuxMessagesLab/Patches/Sources__MessagesLabSidebar__Vendor__appkit-native__SidebarModel.swift.patch @@ -0,0 +1,32 @@ +--- a/Sources/MessagesLabSidebar/Vendor/appkit-native/SidebarModel.swift ++++ b/Sources/MessagesLabSidebar/Vendor/appkit-native/SidebarModel.swift +@@ -301,13 +301,16 @@ + /// taken only as a CGColor resolved in `appearance` (no component of an NSColor is read, so + /// catalog, pattern and gray colors are safe). + static func resolve(_ appearance: NSAppearance, unreadColor: NSColor? = nil, selectionColor: NSColor? = nil) -> SidebarPalette { +- var p: SidebarPalette! +- appearance.performAsCurrentDrawingAppearance { ++ // cmux: no IUO (crash program). The block runs synchronously, so `palette` is set; ++ // without it the palette resolves in the current appearance. ++ var palette: SidebarPalette? ++ func build() -> SidebarPalette { + let dark = appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua + func p3(_ r: CGFloat, _ g: CGFloat, _ b: CGFloat, _ a: CGFloat = 1) -> CGColor { +- CGColor(colorSpace: SidebarDraw.p3, components: [r / 255, g / 255, b / 255, a])! ++ CGColor(colorSpace: SidebarDraw.p3, components: [r / 255, g / 255, b / 255, a]) ++ ?? CGColor(red: r / 255, green: g / 255, blue: b / 255, alpha: a) // cmux: no force unwrap + } +- p = SidebarPalette( ++ return SidebarPalette( + dark: dark, + name: NSColor.labelColor.cgColor, + secondary: NSColor.secondaryLabelColor.cgColor, +@@ -328,6 +331,7 @@ + bubbleText: dark ? p3(255, 255, 255) : p3(0, 0, 0), + typingDot: dark ? p3(150, 150, 154) : p3(142, 142, 147)) + } +- return p ++ appearance.performAsCurrentDrawingAppearance { palette = build() } ++ return palette ?? build() + } + } diff --git a/Packages/Shared/CmuxMessagesLab/Patches/Sources__MessagesLabSidebar__Vendor__appkit-native__SidebarView.swift.patch b/Packages/Shared/CmuxMessagesLab/Patches/Sources__MessagesLabSidebar__Vendor__appkit-native__SidebarView.swift.patch index 7f60da0b9d84..3fbfc9c3fe1a 100644 --- a/Packages/Shared/CmuxMessagesLab/Patches/Sources__MessagesLabSidebar__Vendor__appkit-native__SidebarView.swift.patch +++ b/Packages/Shared/CmuxMessagesLab/Patches/Sources__MessagesLabSidebar__Vendor__appkit-native__SidebarView.swift.patch @@ -1,5 +1,23 @@ --- a/Sources/MessagesLabSidebar/Vendor/appkit-native/SidebarView.swift +++ b/Sources/MessagesLabSidebar/Vendor/appkit-native/SidebarView.swift +@@ -70,7 +70,7 @@ + /// width it is designed for (to verify against Messages' default). + var minimumWidth: CGFloat { SidebarMetrics.minimumWidth } + var preferredWidth: CGFloat? { SidebarMetrics.preferredWidth } +- private var palette = SidebarPalette.resolve(NSAppearance(named: .darkAqua)!) ++ private var palette = SidebarPalette.resolve(NSAppearance(named: .darkAqua) ?? NSAppearance.currentDrawing()) // cmux: no force unwrap + private var generation = 0 + private var scale: CGFloat { document.window?.backingScaleFactor ?? 2 } + private let cache = SidebarBitmapCache() +@@ -922,7 +922,7 @@ + case #selector(NSResponder.moveDown(_:)): moveSelection(1); return true + case #selector(NSResponder.moveUp(_:)): moveSelection(-1); return true + case #selector(NSResponder.insertNewline(_:)): +- if highlightID == nil || position(of: highlightID!) == nil { moveSelection(1) } ++ if highlightID.map({ position(of: $0) == nil }) ?? true { moveSelection(1) } // cmux: no force unwrap + view.window?.makeFirstResponder(document) + return true + case #selector(NSResponder.cancelOperation(_:)): @@ -935,6 +935,9 @@ } diff --git a/Packages/Shared/CmuxMessagesLab/Patches/appkit-native__Compose.swift.patch b/Packages/Shared/CmuxMessagesLab/Patches/appkit-native__Compose.swift.patch index a3c87977414e..ecfc12b0dff8 100644 --- a/Packages/Shared/CmuxMessagesLab/Patches/appkit-native__Compose.swift.patch +++ b/Packages/Shared/CmuxMessagesLab/Patches/appkit-native__Compose.swift.patch @@ -10,11 +10,10 @@ /// Marked (IME) text changed. UITextView reports marked text through /// `textViewDidChange`, so the draft (and the field height) follows the /// composition; NSTextView does not post a text change for it. -@@ -17,6 +20,15 @@ - /// container origin to whole points, which put the text 0.24 pt higher +@@ -18,6 +21,15 @@ /// than Catalyst's (measured by the text probe's first baseline). override var textContainerOrigin: NSPoint { NSPoint(x: textContainerInset.width, y: textContainerInset.height) } -+ + + /// cmux: the caret's NSTextInsertionIndicator shows no effects view. Its + /// glass bubble (input source, dictation, caps lock) sits just left of the + /// caret, which is 7 pt into the field, so it covered the "+" glass. The @@ -23,9 +22,10 @@ + super.didAddSubview(subview) + (subview as? NSTextInsertionIndicator)?.automaticModeOptions.remove(.showEffectsView) + } - ++ override func setMarkedText(_ string: Any, selectedRange: NSRange, replacementRange: NSRange) { super.setMarkedText(string, selectedRange: selectedRange, replacementRange: replacementRange) + onMarkedTextChange() @@ -166,6 +178,7 @@ override func paste(_ sender: Any?) { @@ -34,7 +34,17 @@ if pb.string(forType: .string) == nil, let img = NSImage(pasteboard: pb) { onPasteImage(img); return } super.paste(sender) } -@@ -253,7 +266,8 @@ +@@ -180,7 +193,8 @@ + /// layer (the shared code removes animations from it). + final class ComposeTextView { + let view: FieldTextView +- var layer: CALayer { view.layer! } ++ // cmux: init sets wantsLayer, so the layer exists; a detached layer stands in otherwise (crash program). ++ var layer: CALayer { view.layer ?? CALayer() } + var onSend: () -> Void { get { view.onSend } set { view.onSend = newValue } } + var onEscape: () -> Void { get { view.onEscape } set { view.onEscape = newValue } } + var text: String { view.string } +@@ -253,7 +267,8 @@ var onSendPulse: ((CFTimeInterval) -> Void)? static func height(lines: Int, chips: Bool) -> CGFloat { ComposeMetrics.height(lines: lines, chips: chips) } @@ -44,7 +54,7 @@ static func fieldWidth(_ windowWidth: CGFloat) -> CGFloat { 526 + windowWidth - Fixture.windowWidth } static let font = Fixture.bodyFont static let maxLines = 8 -@@ -266,19 +280,20 @@ +@@ -266,19 +281,20 @@ default: return .limited } }() @@ -69,7 +79,7 @@ /// The placeholders, localized once (each `Strings` read is a bundle table lookup; every /// commit asked for one). private static let placeholders = (field: Strings.placeholder, reply: Strings.replyPlaceholder) -@@ -305,7 +320,8 @@ +@@ -305,7 +321,8 @@ l.actions = none; l.contentsScale = DisplayScale.current } buttons.isUserInteractionEnabled = false @@ -79,7 +89,18 @@ addSubview(buttons) glass.anchorPoint = CGPoint(x: 0.5, y: 1) layer.addSublayer(glass) -@@ -485,11 +501,11 @@ +@@ -470,8 +487,9 @@ + let grey = NSColor(white: 55 / 255, alpha: 1) + let space = CGColorSpace(name: CGColorSpace.sRGB) + for (stops, fromTop) in [(top, true), (bottom, false)] { ++ // cmux: an optional gradient draws nothing when it fails (CrashSafeGraphics). + let g = CGGradient(colorsSpace: space, colors: stops.map { grey.withAlphaComponent($0.1).cgColor } as CFArray, +- locations: stops.map { $0.0 / cap })! ++ locations: stops.map { $0.0 / cap }) + c.drawLinearGradient(g, start: CGPoint(x: 0, y: fromTop ? 0 : h), end: CGPoint(x: 0, y: fromTop ? cap : h - cap), options: []) + } + c.restoreGState() +@@ -485,11 +503,11 @@ fmt.opaque = false let ph = placeholder placeholderLayer.contents = UIGraphicsImageRenderer(size: CGSize(width: 300, height: 30), format: fmt).image { ctx in @@ -93,7 +114,7 @@ // Messages' glyph is ChatKit's AudioMessageEntryViewButton waveform at 20 pt // (fitted to the lossless stills): 5 capsules 1.818 pt wide, 3.636 pt apart, // 3.613 / 7.25 / 14.522 pt tall; centre 557.5 pt from the left of a 628 pt window. -@@ -550,7 +566,7 @@ +@@ -550,7 +568,7 @@ placeholderLayer.opacity = text.isEmpty && chips.isEmpty ? 1 : 0 waveLayer.opacity = text.isEmpty && chips.isEmpty ? 1 : 0 CATransaction.commit() @@ -102,7 +123,7 @@ let old = fieldHeight fieldHeight = h if attachmentsChanged || placed.map({ $0.0 != h || $0.1 != text.isEmpty || $0.2 != strip.height || $0.3 != bounds.size }) ?? true { -@@ -630,7 +646,7 @@ +@@ -630,7 +648,7 @@ alpha = p < 0.6 ? 1 : p < 0.65 ? 1 - (p - 0.6) / 0.05 : p < 0.95 ? 0 : (p - 0.95) / 0.05 } let f = fieldRect diff --git a/Packages/Shared/CmuxMessagesLab/Patches/appkit-native__FlightRecorder.swift.patch b/Packages/Shared/CmuxMessagesLab/Patches/appkit-native__FlightRecorder.swift.patch index f833132fcad4..59379ed8a2b9 100644 --- a/Packages/Shared/CmuxMessagesLab/Patches/appkit-native__FlightRecorder.swift.patch +++ b/Packages/Shared/CmuxMessagesLab/Patches/appkit-native__FlightRecorder.swift.patch @@ -75,7 +75,8 @@ + "frame": c.window.map { NSStringFromRect($0.frame) } ?? ""], + "load": HomeFlightRecorder.loadAverage, "build": Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") ?? ""], dir + "/meta.json") - FileHandle.standardError.write("MessagesLab flight recorder: \(reason) -> \(dir)\n".data(using: .utf8)!) +- FileHandle.standardError.write("MessagesLab flight recorder: \(reason) -> \(dir)\n".data(using: .utf8)!) ++ FileHandle.standardError.write(Data("MessagesLab flight recorder: \(reason) -> \(dir)\n".utf8)) // cmux: no force unwrap dumps.append(dir) - burst(dir, c, count: 30) + // cmux: window captures only with their own opt-in (HomeFlightRecorder.capturesWindow). diff --git a/Packages/Shared/CmuxMessagesLab/Patches/appkit-native__HeaderBar.swift.patch b/Packages/Shared/CmuxMessagesLab/Patches/appkit-native__HeaderBar.swift.patch new file mode 100644 index 000000000000..10452a94dfc5 --- /dev/null +++ b/Packages/Shared/CmuxMessagesLab/Patches/appkit-native__HeaderBar.swift.patch @@ -0,0 +1,23 @@ +--- a/Sources/MessagesLabHome/Vendor/appkit-native/HeaderBar.swift ++++ b/Sources/MessagesLabHome/Vendor/appkit-native/HeaderBar.swift +@@ -26,7 +26,9 @@ + avatarHolder?.shift = contentLeading / 2 + } + } +- private var pillCenter: NSLayoutConstraint! ++ // cmux: built on first use in init, never an IUO (crash program). ++ private let pillHolder = PassThroughView() ++ private lazy var pillCenter: NSLayoutConstraint = pill.centerXAnchor.constraint(equalTo: pillHolder.centerXAnchor) + /// The accessory spans the window, or (macOS 26 with a sidebar item) only the detail + /// pane: the pill moves from the accessory's center to the transcript's. + func centerPill() { +@@ -64,8 +66,7 @@ + pill.font = .systemFont(ofSize: 13, weight: .bold) + pill.target = self + pill.action = #selector(contactClicked) +- let holder = PassThroughView() +- pillCenter = pill.centerXAnchor.constraint(equalTo: holder.centerXAnchor) ++ let holder = pillHolder + holder.translatesAutoresizingMaskIntoConstraints = false + pill.translatesAutoresizingMaskIntoConstraints = false + holder.addSubview(pill) diff --git a/Packages/Shared/CmuxMessagesLab/Patches/appkit-native__SwipeReply.swift.patch b/Packages/Shared/CmuxMessagesLab/Patches/appkit-native__SwipeReply.swift.patch index 6ab5cb374d11..92dc433e1039 100644 --- a/Packages/Shared/CmuxMessagesLab/Patches/appkit-native__SwipeReply.swift.patch +++ b/Packages/Shared/CmuxMessagesLab/Patches/appkit-native__SwipeReply.swift.patch @@ -27,3 +27,69 @@ cell.layer.addSublayer(arrow) move(by: dx) return true +@@ -181,7 +183,7 @@ + guard let sym = NSImage(systemSymbolName: "arrowshape.turn.up.left.fill", accessibilityDescription: nil)?.withSymbolConfiguration(cfg) else { return nil } + let px = Int(Tuning.arrowSize * scale) + guard let ctx = CGContext(data: nil, width: px, height: px, bitsPerComponent: 8, bytesPerRow: 0, +- space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil } ++ space: LabColorSpace.sRGB, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil } // cmux: no force unwrap + NSGraphicsContext.saveGraphicsState() + NSGraphicsContext.current = NSGraphicsContext(cgContext: ctx, flipped: false) + let sz = sym.size, r = CGFloat(px) +@@ -204,39 +206,44 @@ + guard let i = a.firstIndex(of: "--swipe-check"), i + 1 < a.count else { return nil } + return a[i + 1] + } +- static func event(dx: CGFloat, dy: CGFloat, phase: Int64) -> NSEvent { +- let cg = CGEvent(scrollWheelEvent2Source: nil, units: .pixel, wheelCount: 2, wheel1: Int32(dy), wheel2: Int32(dx), wheel3: 0)! ++ // cmux: optional, no force unwraps (crash program); `run` records a FAIL for a nil event. ++ static func event(dx: CGFloat, dy: CGFloat, phase: Int64) -> NSEvent? { ++ guard let cg = CGEvent(scrollWheelEvent2Source: nil, units: .pixel, wheelCount: 2, wheel1: Int32(dy), wheel2: Int32(dx), wheel3: 0) else { return nil } + cg.setIntegerValueField(.scrollWheelEventIsContinuous, value: 1) + cg.setDoubleValueField(.scrollWheelEventFixedPtDeltaAxis1, value: dy) + cg.setDoubleValueField(.scrollWheelEventFixedPtDeltaAxis2, value: dx) + cg.setIntegerValueField(.scrollWheelEventPointDeltaAxis1, value: Int64(dy)) + cg.setIntegerValueField(.scrollWheelEventPointDeltaAxis2, value: Int64(dx)) + cg.setIntegerValueField(.scrollWheelEventScrollPhase, value: phase) +- return NSEvent(cgEvent: cg)! ++ return NSEvent(cgEvent: cg) + } + static func run(_ c: ChatController, out: String) { + var lines: [String] = [] + func check(_ name: String, _ ok: Bool, _ detail: String) { lines.append("\(ok ? "PASS" : "FAIL") \(name): \(detail)") } +- guard let hit = c.demo.lastTextRow(mine: false) else { lines.append("FAIL no incoming text row"); finish(lines, out); return } ++ guard let hit = c.demo?.lastTextRow(mine: false) else { lines.append("FAIL no incoming text row"); finish(lines, out); return } + let p = CGPoint(x: hit.body.midX, y: hit.body.midY) ++ @discardableResult func handle(_ e: NSEvent?) -> NSEvent? { // cmux: a nil event is a FAIL, not a trap ++ guard let e else { lines.append("FAIL could not make a scroll event"); return nil } ++ return c.swipe.handle(e, at: p) ++ } + func stream(_ dx: CGFloat, _ dy: CGFloat, steps: Int) -> [CGFloat] { + var offsets: [CGFloat] = [] +- c.swipe.handle(event(dx: dx / CGFloat(steps), dy: dy / CGFloat(steps), phase: 1), at: p) +- for _ in 1.. UIImage? { + guard let cg = cgImage else { return self } + guard let ctx = CGContext(data: nil, width: cg.width, height: cg.height, bitsPerComponent: 8, bytesPerRow: 0, +- space: CGColorSpace(name: CGColorSpace.sRGB)!, ++ space: LabColorSpace.sRGB, // cmux: no force unwrap + bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue) else { return self } + ctx.draw(cg, in: CGRect(x: 0, y: 0, width: cg.width, height: cg.height)) + return UIImage(cgImage: ctx.makeImage(), scale: scale) diff --git a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Engine.swift.patch b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Engine.swift.patch index 3a7083bb954b..06088b45b17a 100644 --- a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Engine.swift.patch +++ b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Engine.swift.patch @@ -35,3 +35,29 @@ } return nil } +@@ -190,13 +204,14 @@ + /// grey placeholder square, 137.5 x 103.5 pt) until LinkPreviews fills it or, + /// without metadata, the domain card (title = site = host) replaces it. + enum TextParts { +- private static let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) ++ // cmux: optional, no try! (crash program); without it no link is detected. ++ static let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) + static func host(_ url: URL) -> String { + url.host.map { $0.hasPrefix("www.") ? String($0.dropFirst(4)) : $0 } ?? url.absoluteString + } + static func linkRuns(_ text: String) -> [TextRun] { + let ns = text as NSString +- return detector.matches(in: text, range: NSRange(location: 0, length: ns.length)).compactMap { m in ++ return (detector?.matches(in: text, range: NSRange(location: 0, length: ns.length)) ?? []).compactMap { m in + guard let url = m.url else { return nil } + return TextRun(start: m.range.location, length: m.range.length, style: nil, link: url.absoluteString, mention: nil, detected: nil) + } +@@ -205,7 +220,7 @@ + static func soleURL(_ line: String) -> URL? { + let t = line.trimmingCharacters(in: .whitespaces) + let ns = t as NSString +- guard ns.length > 0, let m = detector.firstMatch(in: t, range: NSRange(location: 0, length: ns.length)), ++ guard ns.length > 0, let m = detector?.firstMatch(in: t, range: NSRange(location: 0, length: ns.length)), + m.range.location == 0, m.range.length == ns.length, let url = m.url, + url.scheme == "http" || url.scheme == "https" else { return nil } + return url diff --git a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Fixture.swift.patch b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Fixture.swift.patch index 967a1e41f03b..6cbd2a2161e8 100644 --- a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Fixture.swift.patch +++ b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Fixture.swift.patch @@ -35,15 +35,17 @@ /// Outgoing bubbles shade with their position in the window (measured: /// lighter near the top, deeper blue near the compose field). /// (window y in 2x px, red, green), Display P3. -@@ -88,13 +98,42 @@ +@@ -88,13 +98,43 @@ (1500, 68.8, 145.8), (1800, 65.2, 144.1), (2082, 62.8, 142)] /// A gradient colour (red, green from the stops) in Display P3. static func gradientColor(_ r: CGFloat, _ g: CGFloat) -> UIColor { p3(r, g, gradientBlue) } - static let outgoingGradient: CGGradient = CGGradient( -+ private static let measuredGradient: CGGradient = CGGradient( ++ // cmux: optional, no force unwrap (crash program); a nil gradient draws nothing. ++ private static let measuredGradient: CGGradient? = CGGradient( colorsSpace: CGColorSpace(name: CGColorSpace.displayP3), colors: gradientStops.map { gradientColor($0.1, $0.2).cgColor } as CFArray, - locations: gradientStops.map { $0.0 / 2082 })! +- locations: gradientStops.map { $0.0 / 2082 })! ++ locations: gradientStops.map { $0.0 / 2082 }) + /// cmux: the themed outgoing gradient as (2x px window y, colour) stops; + /// nil keeps the measured stops (`gradientStops`, `gradientBlue`). + static var themedGradient: [(CGFloat, UIColor)]? { themedAccent ? theme.map { (inactive ? $0.inactive : $0.active).gradientStops } : nil } @@ -60,7 +62,7 @@ + green: ca.greenComponent + (cb.greenComponent - ca.greenComponent) * f, + blue: ca.blueComponent + (cb.blueComponent - ca.blueComponent) * f, alpha: 1) + } -+ static var outgoingGradient: CGGradient { ++ static var outgoingGradient: CGGradient? { + if let t = theme, themedAccent { return (inactive ? t.inactive : t.active).outgoingGradient } + return measuredGradient + } diff --git a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Header.swift.patch b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Header.swift.patch index 052a57c90be6..ab20c017de7c 100644 --- a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Header.swift.patch +++ b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Header.swift.patch @@ -1,6 +1,18 @@ --- a/Sources/MessagesLabHome/Vendor/catalyst/Header.swift +++ b/Sources/MessagesLabHome/Vendor/catalyst/Header.swift -@@ -167,7 +167,9 @@ +@@ -15,8 +15,9 @@ + private let overlay: CanvasView + // Display P3: the same transfer curve as sRGB (the fitted blur is unchanged for + // greys) without clipping the P3 blues under the header. +- private static let ci = CIContext(options: [.workingColorSpace: CGColorSpace(name: CGColorSpace.displayP3)!, +- .outputColorSpace: CGColorSpace(name: CGColorSpace.displayP3)!]) ++ // cmux: LabColorSpace (no force unwrap; crash program). ++ private static let ci = CIContext(options: [.workingColorSpace: LabColorSpace.displayP3, ++ .outputColorSpace: LabColorSpace.displayP3]) + // Fitted to the reference header (least squares over three frames): + // out = base + gain * (w * blur(s1) + (1 - w) * blur(s2)), sigmas in 2x px. + static let blurSigma1: Double = 5.3 +@@ -167,7 +168,9 @@ super.init(frame: frame) isUserInteractionEnabled = false addSubview(canvas) @@ -11,3 +23,13 @@ if self.drawsTrafficLights { // Measured top/bottom colours of each glassy light, plus a light rim. let colors: [((CGFloat, CGFloat, CGFloat), (CGFloat, CGFloat, CGFloat))] = [ +@@ -183,7 +186,8 @@ + } + ctx.saveGState() + UIBezierPath(ovalIn: r).addClip() +- let g = CGGradient(colorsSpace: space, colors: [col(c.0), col(c.1)] as CFArray, locations: [0.15, 0.85])! ++ // cmux: an optional gradient draws nothing when it fails (CrashSafeGraphics). ++ let g = CGGradient(colorsSpace: space, colors: [col(c.0), col(c.1)] as CFArray, locations: [0.15, 0.85]) + ctx.drawLinearGradient(g, start: CGPoint(x: 0, y: r.minY), end: CGPoint(x: 0, y: r.maxY), options: []) + ctx.restoreGState() + UIColor(white: 1, alpha: 0.35).setStroke() diff --git a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Layout.swift.patch b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Layout.swift.patch index ec2d54ff4486..ebdade6d287a 100644 --- a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Layout.swift.patch +++ b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Layout.swift.patch @@ -12,9 +12,27 @@ let ts = CTTypesetterCreateWithAttributedString(attr) let len = (text as NSString).length var lines: [Line] = [] -@@ -56,6 +59,11 @@ - if !traits.isEmpty, let d = Fixture.bodyFont.fontDescriptor.withSymbolicTraits(traits) { - a.addAttribute(.font, value: UIFont(descriptor: d, size: Fixture.bodyFont.pointSize), range: range) +@@ -40,8 +43,9 @@ + func attributed(color: UIColor, linkColor: UIColor, kern: CGFloat = Fixture.bodyKern) -> NSAttributedString { + let a = NSMutableAttributedString(string: text, attributes: [.font: Fixture.bodyFont, .foregroundColor: color, .kern: kern]) + for r in runs { +- let range = NSRange(location: r.start, length: r.length) +- guard NSMaxRange(range) <= a.length else { continue } ++ // cmux: a run that does not fit this text is skipped: negative, or past the end ++ // without overflowing (NSMaxRange of Int.max traps; addAttribute raises NSRangeException). ++ guard let range = Self.range(r.start, r.length, in: a.length) else { continue } + var traits: UIFontDescriptor.SymbolicTraits = [] + for s in r.style ?? [] { + switch s { +@@ -53,9 +57,15 @@ + } + } + if r.mention != nil { traits.insert(.traitBold) } +- if !traits.isEmpty, let d = Fixture.bodyFont.fontDescriptor.withSymbolicTraits(traits) { +- a.addAttribute(.font, value: UIFont(descriptor: d, size: Fixture.bodyFont.pointSize), range: range) ++ // cmux: the bold/italic face held for the process (HomeFonts, cx-qpqs); no font attribute when there is none. ++ if !traits.isEmpty, let f = HomeFonts.font(Fixture.bodyFont, adding: traits) { ++ a.addAttribute(.font, value: f, range: range) } + // cmux: inline code and code blocks (HomeMarkdown) in the monospaced system font, one point smaller like Messages' body. + // One font for the process (HomeFonts.code): one made per run on RowBitmaps' threads came back nil. @@ -24,7 +42,30 @@ if r.link != nil { a.addAttributes([.foregroundColor: linkColor, .underlineStyle: NSUnderlineStyle.single.rawValue], range: range) } -@@ -113,7 +121,13 @@ +@@ -64,6 +74,13 @@ + return a + } + ++ /// cmux: `start.. NSRange? { ++ guard start >= 0, length >= 0, start <= count, length <= count - start else { return nil } ++ return NSRange(location: start, length: length) ++ } ++ + /// A line after a hard newline advances as far as a wrapped line, on both + /// sides (measured: a received 19-line bubble with 13 newlines is 19 x 16 pt; + /// the recording's sent 3-line bubble is 14 + 3 x 16 = 62 pt). +@@ -89,6 +106,8 @@ + let i = Int(floor(p.y / Fixture.lineHeight)) + guard i >= 0, i < lines.count else { return nil } + let attr = attributed(color: .white, linkColor: .white) ++ // cmux: lines measured for another text (stale during an edit or a streamed reply) are not read past the end. ++ guard Self.range(lines[i].range.location, lines[i].range.length, in: attr.length) != nil else { return nil } + let line = CTLineCreateWithAttributedString(attr.attributedSubstring(from: lines[i].range)) + let idx = CTLineGetStringIndexForPosition(line, CGPoint(x: p.x, y: 0)) + lines[i].range.location + return runs.first { $0.link != nil && idx >= $0.start && idx < $0.start + $0.length }?.link +@@ -113,7 +132,13 @@ /// references/real-messages/recordings/stills/widths; line breaks bound it per width to /// [226,232), [260,273), [287.5,294), [304.5,319.5), >= 338; 0.654 is inside all five). The old rule, proportional to /// the width (0.5707 W), wrapped later than Messages below 600 pt. @@ -39,7 +80,28 @@ var maxLinkWidth: CGFloat { min(Fixture.maxLinkWidth, maxTextWidth + 2 * Fixture.bubblePadX) } var mediaWidth: CGFloat { min(Fixture.mediaWidth, maxTextWidth + 2 * Fixture.bubblePadX) } } -@@ -683,7 +697,8 @@ +@@ -606,7 +631,7 @@ + let outgoing = m.senderId == me + var gap: CGFloat + var connector: String? +- if prev == nil || m.date.timeIntervalSince(prev!.date) > separatorGap { ++ if prev.map({ m.date.timeIntervalSince($0.date) > separatorGap }) ?? true { // cmux: no force unwrap + rows.append(RowSpec(key: "sep:\(m.id)", kind: .separator(bold: Format.day(m.date, now: now), rest: Format.time(m.date)), + gap: prev == nil ? 12 : 0, height: 35.5)) + gap = 0 +@@ -651,8 +676,9 @@ + if m.retractedAt != nil { + rows.append(RowSpec(key: "unsent:\(m.id)", kind: .unsent(outgoing: outgoing), gap: max(gap, 8), height: 16)) + } else { +- let lastOfGroup = next == nil || next!.senderId != m.senderId || next!.date.timeIntervalSince(m.date) >= groupGap +- || next!.retractedAt != nil || next!.replyTo != m.replyTo ++ // cmux: no force unwrap (crash program) ++ let lastOfGroup = next.map { next in next.senderId != m.senderId || next.date.timeIntervalSince(m.date) >= groupGap ++ || next.retractedAt != nil || next.replyTo != m.replyTo } ?? true + for (pi, part) in m.parts.enumerated() { + let measured = MeasureCache.shared.size(m, pi, width: width, estimate: exact.map { !$0.contains(idx) } ?? false) + let (size, tl) = (measured.size, measured.text) +@@ -683,7 +709,8 @@ gap: 1, height: 14)) } if case .failed = m.status { @@ -49,18 +111,18 @@ gap: 1, height: 14)) } if !threadMode, let n = replyCount[m.id], n >= 2, m.replyTo == nil { -@@ -695,6 +710,10 @@ - } +@@ -696,6 +723,10 @@ } prev = m -+ } + } + // cmux: the host's notice, centered like the date row, under the newest message. + if !threadMode, span.upperBound == messages.count, s.atNewest, let notice = s.ui.notice { + rows.append(RowSpec(key: "notice", kind: .separator(bold: "", rest: notice), gap: 0, height: 35.5)) - } ++ } if !threadMode, span.upperBound == messages.count, s.atNewest, s.ui.typing.contains(where: { $0 != me }) { rows.append(RowSpec(key: "typing", kind: .typing, gap: 0, height: 35)) -@@ -747,7 +766,7 @@ + } +@@ -747,7 +778,7 @@ enum Format { private static let timeFormatter: DateFormatter = { let f = DateFormatter() @@ -69,7 +131,7 @@ f.timeZone = Instant.zone f.dateFormat = "h:mm\u{202F}a" return f -@@ -766,7 +785,7 @@ +@@ -766,7 +797,7 @@ private static let calendar: Calendar = { var c = Calendar(identifier: .gregorian); c.timeZone = Instant.zone; return c }() private static func formatter(_ f: String) -> DateFormatter { let d = DateFormatter() @@ -78,7 +140,7 @@ d.timeZone = Instant.zone d.dateFormat = f return d -@@ -785,56 +804,58 @@ +@@ -785,56 +816,58 @@ static func duration(_ s: Double) -> String { String(format: "%d:%02d", Int(s) / 60, Int(s) % 60) } } @@ -92,6 +154,8 @@ - static var notDelivered: String { String(localized: "label.notDelivered", defaultValue: "Not Delivered") } - static var unsentMine: String { String(localized: "row.unsent.mine", defaultValue: "You unsent a message") } - static var unsentTheirs: String { String(localized: "row.unsent.theirs", defaultValue: "A message was unsent") } +- static func replies(_ n: Int) -> String { +- String(format: String(localized: "label.replies", defaultValue: "%lld Replies"), n) + static var today: String { String(localized: "separator.today", defaultValue: "Today", bundle: .module) } + static var yesterday: String { String(localized: "separator.yesterday", defaultValue: "Yesterday", bundle: .module) } + static var read: String { String(localized: "receipt.read", defaultValue: "Read", bundle: .module) } @@ -100,8 +164,7 @@ + static var notDelivered: String { String(localized: "label.notDelivered", defaultValue: "Not Delivered", bundle: .module) } + static var unsentMine: String { String(localized: "row.unsent.mine", defaultValue: "You unsent a message", bundle: .module) } + static var unsentTheirs: String { String(localized: "row.unsent.theirs", defaultValue: "A message was unsent", bundle: .module) } - static func replies(_ n: Int) -> String { -- String(format: String(localized: "label.replies", defaultValue: "%lld Replies"), n) ++ static func replies(_ n: Int) -> String { + String(format: String(localized: "label.replies", defaultValue: "%lld Replies", bundle: .module), n) } - static var location: String { String(localized: "preview.location", defaultValue: "Location") } diff --git a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__LinkPreviews.swift.patch b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__LinkPreviews.swift.patch index 5c6694d98715..5bb9298cb291 100644 --- a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__LinkPreviews.swift.patch +++ b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__LinkPreviews.swift.patch @@ -23,3 +23,27 @@ func fetch(_ url: String, done: @escaping (LinkMetadata?) -> Void) { dispatchPrecondition(condition: .onQueue(.main)) if let hit = cache[url] { +@@ -55,7 +62,7 @@ + if hit?.title == nil { enqueueFallback(url) } + return + } +- if waiting[url] != nil { waiting[url]!.append(done); return } ++ if waiting[url] != nil { waiting[url]?.append(done); return } // cmux: no force unwrap + guard let u = URL(string: url), u.scheme == "https" || u.scheme == "http" else { done(nil); return } + waiting[url] = [done] + let file = dir.appendingPathComponent(String(format: "%016llx.png", LinkPreviews.fnv1a(url))) +@@ -100,9 +107,11 @@ + /// `` (either attribute order), entities decoded. + static func metaTags(_ html: String) -> [String: String] { + var out: [String: String] = [:] +- let re = try! NSRegularExpression(pattern: "]*>", options: [.caseInsensitive]) +- let key = try! NSRegularExpression(pattern: "(?:property|name)\\s*=\\s*[\"']([^\"']+)[\"']", options: [.caseInsensitive]) +- let val = try! NSRegularExpression(pattern: "content\\s*=\\s*(\"([^\"]*)\"|'([^']*)')", options: [.caseInsensitive]) ++ // cmux: no try! (crash program); a pattern that fails to compile reads no tags. ++ guard let re = try? NSRegularExpression(pattern: "]*>", options: [.caseInsensitive]), ++ let key = try? NSRegularExpression(pattern: "(?:property|name)\\s*=\\s*[\"']([^\"']+)[\"']", options: [.caseInsensitive]), ++ let val = try? NSRegularExpression(pattern: "content\\s*=\\s*(\"([^\"]*)\"|'([^']*)')", options: [.caseInsensitive]) ++ else { return out } + let ns = html as NSString + for m in re.matches(in: html, range: NSRange(location: 0, length: min(ns.length, 400_000))) { + let tag = ns.substring(with: m.range) as NSString diff --git a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__LongText.swift.patch b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__LongText.swift.patch index 49d9545b8648..fffb27f34073 100644 --- a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__LongText.swift.patch +++ b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__LongText.swift.patch @@ -1,12 +1,68 @@ --- a/Sources/MessagesLabHome/Vendor/catalyst/LongText.swift +++ b/Sources/MessagesLabHome/Vendor/catalyst/LongText.swift -@@ -819,7 +819,8 @@ +@@ -218,7 +218,8 @@ + func blockString(_ b: Int) -> NSString { + let a = starts[b], e = starts[b + 1] + return withBytes { p in +- NSString(bytes: p.baseAddress! + a, length: e - a, encoding: String.Encoding.utf8.rawValue) ?? "" ++ guard let base = p.baseAddress else { return "" } // cmux: no force unwrap ++ return NSString(bytes: base + a, length: e - a, encoding: String.Encoding.utf8.rawValue) ?? "" + } + } + +@@ -248,8 +249,10 @@ + guard !n.isEmpty, from < count else { return nil } + return withBytes { p in + n.withUnsafeBufferPointer { q in +- guard let r = memmem(p.baseAddress! + from, count - from, q.baseAddress!, q.count) else { return nil } +- let o = UnsafeRawPointer(r) - UnsafeRawPointer(p.baseAddress!) ++ // cmux: no force unwraps (crash program) ++ guard let base = p.baseAddress, let needle = q.baseAddress, ++ let r = memmem(base + from, count - from, needle, q.count) else { return nil } ++ let o = UnsafeRawPointer(r) - UnsafeRawPointer(base) + return o..<(o + q.count) + } + } +@@ -337,14 +340,15 @@ + let a = NSMutableAttributedString(string: string as String, + attributes: [.font: Fixture.bodyFont, .foregroundColor: color, .kern: Fixture.bodyKern]) + if string.range(of: "http").location != NSNotFound || string.range(of: "www.").location != NSNotFound { +- for m in BlockLayout.detector.matches(in: string as String, range: NSRange(location: 0, length: string.length)) { ++ for m in BlockLayout.detector?.matches(in: string as String, range: NSRange(location: 0, length: string.length)) ?? [] { + a.addAttributes([.foregroundColor: link, .underlineStyle: NSUnderlineStyle.single.rawValue], range: m.range) + } + } + drawAttr[outgoing] = a + return a + } +- static let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) ++ // cmux: optional, no try! (crash program); without it no link is underlined. ++ static let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) + } + + /// Block layouts by (lineage, byte range, column): LRU, 256 blocks. +@@ -818,8 +822,10 @@ + /// The layout of a long text at a width. `message`: a message shown as source /// (MarkdownStore.showsSource) lays its markdown text out as plain text. func layout(_ text: String, width: CGFloat, message: ID? = nil) -> LongTextLayout { - let idx = index(for: text)! +- let idx = index(for: text)! - let md = idx.markdown && !(message.map { MarkdownStore.shared.showsSource($0) } ?? false) ++ // cmux: index(for:) builds one when asked to; an unregistered index stands in (crash program). ++ let idx = index(for: text) ?? LongTextIndex.build(text, lineage: 0) + // cmux: a plain message (MarkdownStore.isPlain) is laid out as plain text too. + let md = idx.markdown && !(message.map { MarkdownStore.shared.showsSource($0) || MarkdownStore.shared.isPlain($0) } ?? false) let wk = md || !idx.markdown ? width : -width lock.lock() let id = ObjectIdentifier(idx) +@@ -873,7 +879,10 @@ + prev.markdown || !LongTextIndex.isMarkdown(String(decoding: UnsafeBufferPointer(rebasing: p[prev.starts[prev.blockCount - 1]...]), as: UTF8.self)) { + let keep = prev.blockCount - 1 + let from = max(0, prev.starts[keep] - 256) +- let same = prev.withBytes { q in memcmp(q.baseAddress! + from, p.baseAddress! + from, prev.count - from) == 0 } ++ let same = prev.withBytes { q in // cmux: no force unwraps ++ guard let qb = q.baseAddress, let pb = p.baseAddress else { return false } ++ return memcmp(qb + from, pb + from, prev.count - from) == 0 ++ } + if same { + let i = LongTextIndex.build(t, lineage: prev.lineage, prefix: prev, keep: keep) + LongTextStats.streamExtends += 1 diff --git a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__MarkdownLayout.swift.patch b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__MarkdownLayout.swift.patch new file mode 100644 index 000000000000..935c41d7248a --- /dev/null +++ b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__MarkdownLayout.swift.patch @@ -0,0 +1,39 @@ +--- a/Sources/MessagesLabHome/Vendor/catalyst/MarkdownLayout.swift ++++ b/Sources/MessagesLabHome/Vendor/catalyst/MarkdownLayout.swift +@@ -102,11 +102,11 @@ + /// Body text baseline below a line top (13 pt SF in a 16 pt line; Fixture.textBaseline - bubblePadY). + static let bodyBaseline: CGFloat = 13 + static let codeBaseline: CGFloat = 12.5 +- static let codeFont = UIFont.monospacedSystemFont(ofSize: 12, weight: .regular) +- static let codeBoldFont = UIFont.monospacedSystemFont(ofSize: 12, weight: .semibold) +- static let inlineCodeFont = UIFont.monospacedSystemFont(ofSize: 12, weight: .regular) ++ static let codeFont = HomeFonts.monospaced(ofSize: 12, weight: .regular) // cmux: nil-checked (HomeFonts, cx-qpqs) ++ static let codeBoldFont = HomeFonts.monospaced(ofSize: 12, weight: .semibold) // cmux: nil-checked (HomeFonts, cx-qpqs) ++ static let inlineCodeFont = HomeFonts.monospaced(ofSize: 12, weight: .regular) // cmux: nil-checked (HomeFonts, cx-qpqs) + /// Headings are body size (Lawrence, 2026-10-06): weight only, one step. +- static func headingFont(_ level: Int) -> UIFont { .systemFont(ofSize: Fixture.bodyFont.pointSize, weight: level <= 2 ? .bold : .semibold) } ++ static func headingFont(_ level: Int) -> UIFont { HomeFonts.system(ofSize: Fixture.bodyFont.pointSize, weight: level <= 2 ? .bold : .semibold) } // cmux: held for the process (HomeFonts, cx-qpqs) + static let codePadX: CGFloat = 8 + /// Space under a scrollable block's content for its scroll indicator. + static let indicatorRoom: CGFloat = 5 +@@ -480,7 +480,7 @@ + let rid = out.regions.count + let cols = max(1, t.columns) + let pad = Markdown.cellPadX +- let headFont = UIFont.systemFont(ofSize: Fixture.bodyFont.pointSize, weight: .semibold) ++ let headFont = HomeFonts.system(ofSize: Fixture.bodyFont.pointSize, weight: .semibold) // cmux: held for the process (HomeFonts, cx-qpqs) + let all: [[MDText]] = [t.header] + t.rows + // Column widths: min = widest unbreakable word (capped), max = widest one-line cell. + var minW = [CGFloat](repeating: 16, count: cols), maxW = [CGFloat](repeating: 16, count: cols) +@@ -613,8 +613,9 @@ + var traits: UIFontDescriptor.SymbolicTraits = [] + if s.style.contains(.strong) { traits.insert(.traitBold) } + if s.style.contains(.emphasis) { traits.insert(.traitItalic) } +- if !traits.isEmpty, let d = font.fontDescriptor.withSymbolicTraits(font.fontDescriptor.symbolicTraits.union(traits)) { +- a.addAttribute(.font, value: UIFont(descriptor: d, size: font.pointSize), range: r) ++ // cmux: the bold/italic face held for the process (HomeFonts, cx-qpqs); no font attribute when there is none. ++ if !traits.isEmpty, let f = HomeFonts.font(font, adding: traits) { ++ a.addAttribute(.font, value: f, range: r) + } + } + if let l = s.link { a.addAttribute(.link, value: l, range: r) } diff --git a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__MarkdownParser.swift.patch b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__MarkdownParser.swift.patch index 5be2e3707e3a..fe3702ffec98 100644 --- a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__MarkdownParser.swift.patch +++ b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__MarkdownParser.swift.patch @@ -1,9 +1,10 @@ --- a/Sources/MessagesLabHome/Vendor/catalyst/MarkdownParser.swift +++ b/Sources/MessagesLabHome/Vendor/catalyst/MarkdownParser.swift -@@ -12,6 +12,33 @@ +@@ -11,6 +11,33 @@ + // The parser is pure (Foundation only, no UIKit), thread safe and runs off main. // Top-level blocks carry their source line range, so a stream re-parses only // from the start of its last top-level block (MarkdownStore). - ++ +/// cmux (interim, until MessagesLab ships the same API): the destinations that become links. +/// Only http, https and mailto (plus a host's `extraSchemes`); any other scheme, an obfuscated +/// scheme and a relative URL stay plain text, and a click re-checks with `url(_:)`. @@ -30,10 +31,9 @@ + + static func allows(_ dest: String) -> Bool { url(dest) != nil } +} -+ + /// Inline styles of a run of display text. struct MDStyle: OptionSet, Hashable { - let rawValue: UInt16 @@ -883,16 +910,22 @@ func set(_ s: MDStyle, _ l: String?) { if s != runStyle || l != runLink { cut(); runStyle = s; runLink = l } } func emit(_ s: String) { for u in s.unicodeScalars { out.append(u); len16 += u.utf16.count } } @@ -60,3 +60,31 @@ case .br: set(style, linkNow); emit("\n") } } +@@ -991,7 +1024,8 @@ + let hex = body.hasPrefix("#x") || body.hasPrefix("#X") + let digits = body.dropFirst(hex ? 2 : 1) + guard !digits.isEmpty, digits.count <= (hex ? 6 : 7), let v = UInt32(digits, radix: hex ? 16 : 10) else { return nil } +- let scalar = (v == 0 || v > 0x10FFFF) ? Unicode.Scalar(0xFFFD)! : (Unicode.Scalar(v) ?? Unicode.Scalar(0xFFFD)!) ++ let replacement: Unicode.Scalar = "\u{FFFD}" // cmux: a literal, no force unwrap ++ let scalar = (v == 0 || v > 0x10FFFF) ? replacement : (Unicode.Scalar(v) ?? replacement) + return (String(scalar), semi - i + 1) + } + guard let r = entities[body] else { return nil } +@@ -1004,7 +1038,7 @@ + guard !body.isEmpty, !body.contains(where: { $0 == " " || $0 == "<" || $0 == "\n" }) else { return nil } + if let colon = body.firstIndex(of: ":") { + let scheme = body[.. Bool { lock.lock(); defer { lock.unlock() }; return source.contains(id) } func setShowsSource(_ id: ID, _ on: Bool) { lock.lock(); if on { source.insert(id) } else { source.remove(id) }; lock.unlock() } -+ /// cmux: messages whose text is never Markdown (a person's text shows as typed; only an -+ /// agent's is Markdown). The host marks them before they are measured. -+ private var plain = Set() -+ func isPlain(_ id: ID) -> Bool { lock.lock(); defer { lock.unlock() }; return plain.contains(id) } -+ func setPlain(_ id: ID, _ on: Bool) { lock.lock(); if on { plain.insert(id) } else { plain.remove(id) }; lock.unlock() } ++ /// cmux: a message's text is plain unless the host marks it Markdown (only an agent's ++ /// text is Markdown; a person's shows as typed). Plain is the default, so a message the ++ /// host has not seen (the reducer's local send, measured before the owner's echo) never ++ /// takes the Markdown engine. The host marks a message before it is measured. ++ private var markdownIDs = Set() ++ func isPlain(_ id: ID) -> Bool { lock.lock(); defer { lock.unlock() }; return !markdownIDs.contains(id) } ++ func setPlain(_ id: ID, _ on: Bool) { lock.lock(); if on { markdownIDs.remove(id) } else { markdownIDs.insert(id) }; lock.unlock() } func document(_ text: String) -> MDDocument { lock.lock() -@@ -70,7 +75,7 @@ +@@ -70,7 +77,7 @@ /// message shown as source. static func layout(_ text: String, message: ID?, width: CGFloat) -> MarkdownLayout? { guard enabled, mightContain(text), !LongText.isLong(text) else { return nil } diff --git a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Model.swift.patch b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Model.swift.patch index 3f1510e7aaa7..6d24f77092d8 100644 --- a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Model.swift.patch +++ b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Model.swift.patch @@ -10,7 +10,7 @@ + /// Unset (fixtures, the differential harness), the conversation's -07:00. + static var liveZone: TimeZone? + static var liveLocale: Locale? -+ static let zone = liveZone ?? TimeZone(secondsFromGMT: -7 * 3600)! ++ static let zone = liveZone ?? TimeZone(secondsFromGMT: -7 * 3600) ?? .gmt // cmux: no force unwrap + static let locale = liveLocale ?? Locale(identifier: "en_US") private static let writer: ISO8601DateFormatter = { let f = ISO8601DateFormatter() @@ -22,7 +22,28 @@ - static var sharedDirectory: URL { Bundle.main.resourceURL! } + /// cmux: fixtures are not in the app bundle; the harness sets `root`. + static var root: URL? -+ static var sharedDirectory: URL { root ?? Bundle.main.resourceURL! } ++ static var sharedDirectory: URL { root ?? Bundle.main.resourceURL ?? Bundle.main.bundleURL } // cmux: no force unwrap /// The repo's shared/ directory, for the large generated stores that are /// not bundled. static var repoShared: URL { +@@ -314,12 +322,17 @@ + } + static func loadConversation() -> Conversation { + let url = sharedDirectory.appendingPathComponent("conversation.json") +- let data = try! Data(contentsOf: url) +- return try! JSONDecoder().decode(Conversation.self, from: data) ++ // cmux: no try! (crash program); a missing or unreadable fixture is an empty conversation. ++ guard let data = try? Data(contentsOf: url), ++ let conversation = try? JSONDecoder().decode(Conversation.self, from: data) else { ++ return Conversation(id: "", title: "", participants: [], messages: []) ++ } ++ return conversation + } + /// Resolve an AssetRef: a path relative to shared/assets or a file URL. + static func assetURL(_ ref: String) -> URL { +- if ref.hasPrefix("file:") { return URL(string: ref)! } ++ // cmux: no force unwrap; a file: ref that does not parse resolves like any other ref. ++ if ref.hasPrefix("file:"), let url = URL(string: ref) { return url } + // Catalyst fixture assets (Fixtures/real, bundled as `real/`). + if ref.hasPrefix("real/") { return sharedDirectory.appendingPathComponent(ref) } + return sharedDirectory.appendingPathComponent("assets").appendingPathComponent(ref) diff --git a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__RowDrawing.swift.patch b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__RowDrawing.swift.patch index 13b9d1fa17a1..deb1f00b0e65 100644 --- a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__RowDrawing.swift.patch +++ b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__RowDrawing.swift.patch @@ -1,6 +1,66 @@ --- a/Sources/MessagesLabHome/Vendor/catalyst/RowDrawing.swift +++ b/Sources/MessagesLabHome/Vendor/catalyst/RowDrawing.swift -@@ -252,10 +252,11 @@ +@@ -13,8 +13,9 @@ + static let margin: CGFloat = 24 + + static func receiptParts(_ bold: String, _ rest: String) -> [(String, UIFont, UIColor)] { +- [(bold, .systemFont(ofSize: Fixture.captionSize, weight: .semibold), Fixture.secondaryText), +- (rest, .systemFont(ofSize: Fixture.captionSize), Fixture.secondaryText)] ++ // cmux: fonts held for the process (HomeFonts, cx-qpqs); receipts draw on RowBitmaps' threads. ++ [(bold, HomeFonts.system(ofSize: Fixture.captionSize, weight: .semibold), Fixture.secondaryText), ++ (rest, HomeFonts.system(ofSize: Fixture.captionSize), Fixture.secondaryText)] + } + static let captionKern: CGFloat = -0.03 + +@@ -65,17 +66,17 @@ + } + case let .unsent(outgoing): + let s = outgoing ? Strings.unsentMine : Strings.unsentTheirs +- let f = UIFont.systemFont(ofSize: 11) ++ let f = HomeFonts.system(ofSize: 11) // cmux: HomeFonts (cx-qpqs) + let w = TextDraw.width(s, font: f) + TextDraw.line(s, font: f, color: Fixture.secondaryText, x: m.centerX + 0.1 - w / 2, baseline: top + 12, in: ctx) + case let .label(text, outgoing, color): +- let f = UIFont.systemFont(ofSize: 10, weight: .medium) ++ let f = HomeFonts.system(ofSize: 10, weight: .medium) // cmux: HomeFonts (cx-qpqs) + let c: UIColor = color == .failure ? UIColor(red: 1, green: 0.27, blue: 0.23, alpha: 1) + : color == .link ? UIColor(red: 0.2, green: 0.55, blue: 1, alpha: 1) : Fixture.secondaryText + let w = TextDraw.width(text, font: f) + TextDraw.line(text, font: f, color: c, x: outgoing ? m.receiptRight - w : Fixture.labelLeft, baseline: top + 11, in: ctx) + case let .replies(count, _, outgoing): +- let f = UIFont.systemFont(ofSize: 10, weight: .semibold) ++ let f = HomeFonts.system(ofSize: 10, weight: .semibold) // cmux: HomeFonts (cx-qpqs) + let s = Strings.replies(count) + let w = TextDraw.width(s, font: f, kern: captionKern) + TextDraw.line(s, font: f, color: PreviewStyle.repliesBlue, +@@ -151,7 +152,7 @@ + UIColor(white: light ? 0 : 1, alpha: 0.25 + 0.6 * CGFloat(k) / 7).setStroke(); p.stroke() + } + let host = URL(string: url).map(TextParts.host) ?? url +- let f = UIFont.systemFont(ofSize: 10) ++ let f = HomeFonts.system(ofSize: 10) // cmux: HomeFonts (cx-qpqs) + TextDraw.line(host, font: f, color: Fixture.secondaryText, x: body.midX - TextDraw.width(host, font: f) / 2, baseline: c.y + 24, in: ctx) + case let .link(_, title, site, image, theme): + // A light appearance draws every card light; a dark one keeps the card's +@@ -178,7 +179,7 @@ + let c = CGPoint(x: body.minX - 14, y: body.midY) + UIColor(red: 1, green: 0.27, blue: 0.23, alpha: 1).setFill() + UIBezierPath(ovalIn: CGRect(x: c.x - 8, y: c.y - 8, width: 16, height: 16)).fill() +- let f = UIFont.systemFont(ofSize: 12, weight: .bold) ++ let f = HomeFonts.system(ofSize: 12, weight: .bold) // cmux: HomeFonts (cx-qpqs) + TextDraw.line("!", font: f, color: .white, x: c.x - TextDraw.width("!", font: f) / 2, baseline: c.y + 4.5, in: ctx) + } + drawReactions(ctx, p.reactions, body: body, outgoing: p.outgoing, windowY: windowY) +@@ -223,7 +224,7 @@ + TextDraw.line(s, font: Sizing.linkTitleFont, color: titleColor, x: card.minX + 10, baseline: y, in: ctx, kern: -0.005) + y += 12 + } +- TextDraw.line(site, font: .systemFont(ofSize: 10), color: siteColor, x: card.minX + 10.25, baseline: y + 2.8, in: ctx, kern: -0.03) ++ TextDraw.line(site, font: HomeFonts.system(ofSize: 10), color: siteColor, x: card.minX + 10.25, baseline: y + 2.8, in: ctx, kern: -0.03) // cmux: HomeFonts (cx-qpqs) + } + + static func drawAttachment(_ ctx: CGContext, _ a: Attachment, body: CGRect, row p: PartRow, windowY: CGFloat) { +@@ -252,10 +253,11 @@ UIColor(white: 1, alpha: 0.85).setFill() tri.fill() } @@ -14,7 +74,12 @@ fg.setFill() UIBezierPath(ovalIn: CGRect(x: body.minX + 8, y: body.midY - 11, width: 22, height: 22)).fill() let tri = UIBezierPath() -@@ -277,7 +278,7 @@ +@@ -273,21 +275,21 @@ + cornerRadius: 1).fill() + } + let d = Format.duration(a.durationSeconds ?? 0) +- TextDraw.line(d, font: .monospacedDigitSystemFont(ofSize: 11, weight: .regular), color: fg, x: body.maxX - 36, ++ TextDraw.line(d, font: HomeFonts.monospacedDigit(ofSize: 11, weight: .regular), color: fg, x: body.maxX - 36, // cmux: HomeFonts (cx-qpqs) baseline: body.midY + 4, in: ctx) default: fillBubble(ctx, shape, outgoing: p.outgoing, windowY: windowY) @@ -23,3 +88,83 @@ let icon = CGRect(x: body.minX + 10, y: body.minY + 10, width: 28, height: 36) if a.kind == "contact" { UIColor(white: 0.55, alpha: 1).setFill() + UIBezierPath(ovalIn: CGRect(x: body.minX + 9, y: body.minY + 10, width: 36, height: 36)).fill() + let initial = String(a.fileName.prefix(1)).uppercased() +- let f = UIFont.systemFont(ofSize: 17, weight: .semibold) ++ let f = HomeFonts.system(ofSize: 17, weight: .semibold) // cmux: HomeFonts (cx-qpqs) + TextDraw.line(initial, font: f, color: .white, x: body.minX + 27 - TextDraw.width(initial, font: f) / 2, + baseline: body.minY + 34, in: ctx) + let name = (a.fileName as NSString).deletingPathExtension +- TextDraw.line(name, font: .systemFont(ofSize: 13, weight: .semibold), color: fg, x: body.minX + 54, baseline: body.minY + 33, in: ctx) ++ TextDraw.line(name, font: HomeFonts.system(ofSize: 13, weight: .semibold), color: fg, x: body.minX + 54, baseline: body.minY + 33, in: ctx) // cmux: HomeFonts (cx-qpqs) + let chev = UIBezierPath() + chev.move(to: CGPoint(x: body.maxX - 18, y: body.midY - 5)) + chev.addLine(to: CGPoint(x: body.maxX - 13, y: body.midY)) +@@ -347,11 +349,11 @@ + } + } + let label = ext.uppercased() +- let f = UIFont.systemFont(ofSize: 7, weight: .regular) ++ let f = HomeFonts.system(ofSize: 7, weight: .regular) // cmux: HomeFonts (cx-qpqs) + TextDraw.line(label, font: f, color: UIColor(white: 0.6, alpha: 1), x: icon.midX - TextDraw.width(label, font: f) / 2, + baseline: icon.maxY - 5, in: ctx) + } +- let nameFont = UIFont.systemFont(ofSize: 13, weight: .semibold) ++ let nameFont = HomeFonts.system(ofSize: 13, weight: .semibold) // cmux: HomeFonts (cx-qpqs) + var name = a.fileName + while TextDraw.width(name, font: nameFont) > body.width - 100, name.count > 4 { name = String(name.dropLast(5)) + "…" } + let x = body.minX + 84.5 +@@ -365,7 +367,7 @@ + fg.setFill() + UIBezierPath(roundedRect: CGRect(x: bar.minX, y: bar.minY, width: bar.width * CGFloat(pr), height: 4), cornerRadius: 2).fill() + } +- TextDraw.line(sub, font: .systemFont(ofSize: 11), color: fg.withAlphaComponent(0.6), x: x, baseline: body.minY + 58.5, in: ctx) ++ TextDraw.line(sub, font: HomeFonts.system(ofSize: 11), color: fg.withAlphaComponent(0.6), x: x, baseline: body.minY + 58.5, in: ctx) // cmux: HomeFonts (cx-qpqs) + } + + /// The round save button beside a photo or video (measured: 28 pt, 14 pt +@@ -433,7 +435,7 @@ + Fixture.connector.setFill() + UIBezierPath(roundedRect: CGRect(x: 32.5, y: stubTop, width: 2.5, height: stubH), cornerRadius: 1.25).fill() + if pv.count >= 2 { +- let f = UIFont.systemFont(ofSize: 10, weight: .semibold) ++ let f = HomeFonts.system(ofSize: 10, weight: .semibold) // cmux: HomeFonts (cx-qpqs) + TextDraw.line(Strings.replies(pv.count), font: f, color: PreviewStyle.repliesBlue, x: 44.5, baseline: box.maxY + (pv.isText ? 12.5 : 11.5), in: ctx, + kern: RowDraw.captionKern) + } +@@ -462,7 +464,7 @@ + BubblePath.make(body: full, outgoing: outgoing, tail: tail).addClip() + img.draw(in: full) + ctx.restoreGState() +- TextDraw.line(caption, font: .systemFont(ofSize: 12), color: .white, x: full.minX + 13, baseline: full.maxY - 14, in: ctx) ++ TextDraw.line(caption, font: HomeFonts.system(ofSize: 12), color: .white, x: full.minX + 13, baseline: full.maxY - 14, in: ctx) // cmux: HomeFonts (cx-qpqs) + } + + static func drawLocation(_ ctx: CGContext, body: CGRect, title: String, subtitle: String, tail: Bool, outgoing: Bool) { +@@ -500,7 +502,7 @@ + UIBezierPath(ovalIn: CGRect(x: pin.x - 2, y: pin.y - 2, width: 4, height: 4)).fill() + ctx.restoreGState() + TextDraw.line(title, font: Sizing.linkTitleFont, color: UIColor(white: 0.93, alpha: 1), x: body.minX + 10, baseline: map.maxY + 18, in: ctx) +- TextDraw.line(subtitle, font: .systemFont(ofSize: 10), color: UIColor(white: 0.68, alpha: 1), x: body.minX + 10, baseline: map.maxY + 32, in: ctx) ++ TextDraw.line(subtitle, font: HomeFonts.system(ofSize: 10), color: UIColor(white: 0.68, alpha: 1), x: body.minX + 10, baseline: map.maxY + 32, in: ctx) // cmux: HomeFonts (cx-qpqs) + } + + /// The person whose tapbacks draw blue (the conversation's own participant). +@@ -567,7 +569,7 @@ + } + + static func drawEmoji(_ e: String, in rect: CGRect, ctx: CGContext) { +- let f = UIFont.systemFont(ofSize: 15) ++ let f = HomeFonts.system(ofSize: 15) // cmux: HomeFonts (cx-qpqs) + let w = TextDraw.width(e, font: f) + TextDraw.line(e, font: f, color: .white, x: rect.midX - w / 2, baseline: rect.midY + 5.5, in: ctx) + } +@@ -630,7 +632,7 @@ + let s = img.size + img.draw(in: CGRect(x: r.midX - s.width / 2, y: r.midY - s.height / 2, width: s.width, height: s.height)) + } else { +- let f = UIFont.systemFont(ofSize: r.height * 0.42, weight: .heavy) ++ let f = HomeFonts.system(ofSize: r.height * 0.42, weight: .heavy) // cmux: HomeFonts (cx-qpqs) + let lines = Strings.laughGlyph.components(separatedBy: "\n") + for (i, l) in lines.enumerated() { + TextDraw.line(l, font: f, color: color, x: r.midX - TextDraw.width(l, font: f) / 2, diff --git a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Shapes.swift.patch b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Shapes.swift.patch new file mode 100644 index 000000000000..c18164e2defb --- /dev/null +++ b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Shapes.swift.patch @@ -0,0 +1,15 @@ +--- a/Sources/MessagesLabHome/Vendor/catalyst/Shapes.swift ++++ b/Sources/MessagesLabHome/Vendor/catalyst/Shapes.swift +@@ -130,9 +130,10 @@ + let white = UIColor.white + let space = CGColorSpace(name: CGColorSpace.sRGB) + for (stops, fromTop) in [(rim.top, true), (rim.bottom, false)] { +- let span = stops.last!.0 ++ // cmux: no force unwraps (crash program); an empty rim or a failed gradient draws nothing. ++ guard let span = stops.last?.0 else { continue } + let g = CGGradient(colorsSpace: space, colors: stops.map { white.withAlphaComponent($0.1).cgColor } as CFArray, +- locations: stops.map { $0.0 / span })! ++ locations: stops.map { $0.0 / span }) + let y0 = fromTop ? rect.minY : rect.maxY + let y1 = fromTop ? rect.minY + span : rect.maxY - span + ctx.drawLinearGradient(g, start: CGPoint(x: 0, y: y0), end: CGPoint(x: 0, y: y1), options: []) diff --git a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Springs.swift.patch b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Springs.swift.patch index 58b330622612..79aae34d3aa7 100644 --- a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Springs.swift.patch +++ b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Springs.swift.patch @@ -10,3 +10,21 @@ let data = try? Data(contentsOf: url), let obj = try? JSONSerialization.jsonObject(with: data) as? [String: [String: Any]] else { return [:] } var out: [String: SpringElement] = [:] +@@ -149,7 +150,7 @@ + spring: Spring(duration: duration, bounce: c["bounce"] as? Double ?? 0, + initialVelocity: c["initialVelocity"] as? Double ?? 0), + delta: c["delta"] as? Double ?? 0, +- curve: cp?.count == 4 ? Curve(x1: cp![0], y1: cp![1], x2: cp![2], y2: cp![3], duration: duration) : nil) ++ curve: cp.flatMap { $0.count == 4 ? Curve(x1: $0[0], y1: $0[1], x2: $0[2], y2: $0[3], duration: duration) : nil }) // cmux: no force unwrap + } + out[name] = SpringElement(name: name, from: e["from"] as? Double ?? 0, to: e["to"] as? Double ?? 0, components: comps) + } +@@ -486,7 +487,7 @@ + tau = 0 + } + let total = k.duration * Double(max(1, k.repeatCount)) +- if k.repeatCount < .infinity, tau >= total { return k.isRemovedOnCompletion ? nil : (kp, values.last!.doubleValue) } ++ if k.repeatCount < .infinity, tau >= total { return k.isRemovedOnCompletion ? nil : values.last.map { (kp, $0.doubleValue) } } // cmux: no force unwrap + // Wrap only repeating animations (a one-shot at exactly its end + // must not wrap to its first value). + if k.repeatCount > 1 { tau = tau.truncatingRemainder(dividingBy: k.duration) } diff --git a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Transcript.swift.patch b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Transcript.swift.patch index 00ab3e6cfe86..1e54acfb56ac 100644 --- a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Transcript.swift.patch +++ b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__Transcript.swift.patch @@ -1,5 +1,14 @@ --- a/Sources/MessagesLabHome/Vendor/catalyst/Transcript.swift +++ b/Sources/MessagesLabHome/Vendor/catalyst/Transcript.swift +@@ -519,7 +519,7 @@ + deinit { + RowCell.destroyed += 1 + if ProcessInfo.processInfo.environment["ML_CELLS"] != nil, RowCell.destroyed % 500 == 7 { +- FileHandle.standardError.write(("deinit stack:\n" + Thread.callStackSymbols.prefix(14).joined(separator: "\n") + "\n").data(using: .utf8)!) ++ FileHandle.standardError.write(Data(("deinit stack:\n" + Thread.callStackSymbols.prefix(14).joined(separator: "\n") + "\n").utf8)) // cmux: no force unwrap + } + } + @@ -541,8 +541,7 @@ connector.strokeColor = Fixture.connector.cgColor connector.lineWidth = 2.6 @@ -46,12 +55,10 @@ CATransaction.commit() self.spec = nil } -@@ -963,6 +966,16 @@ - RowCell.placeFill(badgeFill, windowTop: windowY + badgeTop, width: badgeFill.bounds.width, span: fillSpan, reachBelow: fillReachBelow) - } +@@ -965,6 +968,16 @@ CATransaction.commit() -+ } -+ + } + + /// cmux: the outgoing gradient's colours and their locations from one + /// stop list. A palette change that set only the colours left a cell + /// made under the measured palette (8 stops) with 11 themed colours. @@ -60,6 +67,8 @@ + ?? Fixture.gradientStops.map { ($0.0, Fixture.gradientColor($0.1, $0.2).cgColor) } + fillGradient.colors = stops.map(\.1) + fillGradient.locations = stops.map { NSNumber(value: Double($0.0 / (Fixture.gradientHeight * 2))) } - } - ++ } ++ /// Window y of the cell's top: the outgoing fill shades with it. + var windowY: CGFloat = 0 { + didSet { diff --git a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__WindowView.swift.patch b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__WindowView.swift.patch index 5adaaf5a6026..6da0774d779f 100644 --- a/Packages/Shared/CmuxMessagesLab/Patches/catalyst__WindowView.swift.patch +++ b/Packages/Shared/CmuxMessagesLab/Patches/catalyst__WindowView.swift.patch @@ -50,6 +50,15 @@ // Rows configured in this transaction draw now (RowCell.transitionDepth). RowCell.transitionDepth += 1 defer { RowCell.transitionDepth -= 1 } +@@ -406,7 +414,7 @@ + MessagesWindowView.createdInCommits += RowCell.created - created0 + MessagesWindowView.destroyedInCommits += RowCell.destroyed - destroyed0 + if MessagesWindowView.logCells, RowCell.destroyed - destroyed0 > 0 { +- FileHandle.standardError.write("commit \(String(describing: action).prefix(30)) destroyed \(RowCell.destroyed - destroyed0)\n".data(using: .utf8)!) ++ FileHandle.standardError.write(Data("commit \(String(describing: action).prefix(30)) destroyed \(RowCell.destroyed - destroyed0)\n".utf8)) // cmux: no force unwrap + } + } + let t0 = CACurrentMediaTime() @@ -567,13 +575,13 @@ let msgs = state.conversation.messages let now = store.date(at: t) @@ -119,7 +128,17 @@ return (top > 0 ? countHead(headIDs) : 0, head, dropTail, tail) default: return nil -@@ -1051,7 +1060,8 @@ +@@ -758,7 +767,8 @@ + for i in band { + let key = model.rows[i].spec.key + let newWin = layout.contentTop(i) - newOffset +- if let ot = oldSnap.contentTop(key), oldSnap.row(oldSnap.index(key)!).ghost == model.rows[i].ghost || model.rows[i].ghost { ++ // cmux: no force unwrap; contentTop(key) found the key, so index(key) does too. ++ if let ot = oldSnap.contentTop(key), let oi = oldSnap.index(key), oldSnap.row(oi).ghost == model.rows[i].ghost || model.rows[i].ghost { + let d = (ot + oldRowsTop - oldOffset) - newWin + deltas[key] = d + for j in pendingNew { deltas[model.rows[j].spec.key] = d } +@@ -1051,7 +1061,8 @@ func collectionView(_ cv: UICollectionView, numberOfItemsInSection section: Int) -> Int { model.count } func collectionView(_ cv: UICollectionView, cellForItemAt ip: IndexPath) -> UICollectionViewCell { @@ -129,7 +148,7 @@ decorate(cell, ip.item) return cell } -@@ -1304,7 +1314,7 @@ +@@ -1304,7 +1315,7 @@ return } let msgs = [rm] + s.conversation.messages.filter { $0.replyTo == root } diff --git a/Packages/Shared/CmuxMessagesLab/README.md b/Packages/Shared/CmuxMessagesLab/README.md index 3a50da6f428e..5db7bd61018b 100644 --- a/Packages/Shared/CmuxMessagesLab/README.md +++ b/Packages/Shared/CmuxMessagesLab/README.md @@ -74,9 +74,10 @@ and render-server field animation, blurred header and native scrolling. | ComposeAttachments | the image placeholder and file tile fill use the theme's chip fill on a light theme (a dark theme keeps the measured white) | | Fixture | the gradient mix falls back to the measured blue when a colour cannot convert (never reads components of an unconverted colour; the Markdown getWhite fix is upstream as 40b9869) | | FlightRecorder | the app's policy and log folder (`HomeFlightRecorder`), window captures behind their own opt-in, the pane's optional window (attached from `ChatController.windowChanged`, observers replaced), FlashCheck/LiveProbes/Bench/LiveRecord helpers from `HomeFlightRecorder` | -| MarkdownStore, LongText | `isPlain`/`setPlain`: a message HomeMapping marks plain (a person's text, or a part with mentions) never takes the Markdown engine; only an agent's text is Markdown | +| MarkdownStore, LongText | `isPlain`/`setPlain`: a message is plain unless HomeMapping marks it Markdown (an agent's text without mentions), so a person's text never takes the Markdown engine, also before HomeStore has it (the reducer's local send at the press) | | MarkdownParser, MarkdownHost | `MarkdownLinkPolicy` (interim, same API as MessagesLab's coming rule): only http, https and mailto (plus `extraSchemes`, empty) become links; other, obfuscated and relative destinations are plain text; a click re-checks (`Cmux/PaneLinks.swift` for Home) | | ComposeAttachments, WindowView, TiledBubble | checked casts instead of `as!` (crash ratchet, cx-6so) | +| Compose, FlightRecorder, SwipeReply, HeaderBar, UIKitNames, ComposeAttachments, Engine, Fixture, Header, Layout, LinkPreviews, LongText, MarkdownParser, Model, Shapes, Springs, TiledBubble, Transcript, WindowView, Sidebar{Drawing,Model,View} | crash program (plans/cmux-next/crash-elimination.md): no force unwraps, `try!`, `as!` or IUOs; named color spaces and UI fonts through `CrashSafeGraphics`/`SidebarCrashSafe` with stated fallbacks, an optional gradient draws nothing, a fixture that cannot load is an empty conversation | ## Updating diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/CrashSafeGraphics.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/CrashSafeGraphics.swift new file mode 100644 index 000000000000..fe767a7fd995 --- /dev/null +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/CrashSafeGraphics.swift @@ -0,0 +1,30 @@ +import AppKit +import CoreText + +// cmux (crash program, plans/cmux-next/crash-elimination.md): Core Graphics and Core +// Text constructors MessagesLab force-unwrapped. Each returns a working value or a +// stated fallback instead of trapping; Tests/MessagesLabHomeTests/CrashSafeGraphicsTests +// pins that every named literal resolves, so the fallbacks never run in practice. + +/// The named color spaces MessagesLab draws in. +enum LabColorSpace { + /// sRGB (device RGB if the name does not resolve). + static let sRGB: CGColorSpace = CGColorSpace(name: CGColorSpace.sRGB) ?? CGColorSpaceCreateDeviceRGB() + /// Display P3 (device RGB if the name does not resolve). + static let displayP3: CGColorSpace = CGColorSpace(name: CGColorSpace.displayP3) ?? CGColorSpaceCreateDeviceRGB() +} + +/// The system UI font of a kind and size; the system font by name if Core Text +/// returns none for the kind. +func labUIFont(_ type: CTFontUIFontType, _ size: CGFloat) -> CTFont { + CTFontCreateUIFontForLanguage(type, size, nil) ?? CTFontCreateWithName(".AppleSystemUIFont" as CFString, size, nil) +} + +extension CGContext { + /// Draws `gradient`, or nothing when it could not be built (a `CGGradient` + /// initializer returned nil for its colors or locations). + func drawLinearGradient(_ gradient: CGGradient?, start: CGPoint, end: CGPoint, options: CGGradientDrawingOptions) { + guard let gradient else { return } + drawLinearGradient(gradient, start: start, end: end, options: options) + } +} diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/FixtureTheme.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/FixtureTheme.swift index 436b97d3590f..9e3f18213108 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/FixtureTheme.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/FixtureTheme.swift @@ -19,7 +19,8 @@ struct FixtureTheme: Equatable { let secondaryText: NSColor /// (2x px window y, colour), over the gradient's 1041 pt. let gradientStops: [(CGFloat, NSColor)] - let outgoingGradient: CGGradient + /// nil when Core Graphics refuses the stops (bubbles then draw no gradient). + let outgoingGradient: CGGradient? /// A light theme (background luminance above one half). MessagesLab /// measured a dark window only: on a dark theme the field and typing /// colours below keep its measured values; a light theme takes the @@ -48,7 +49,7 @@ struct FixtureTheme: Equatable { gradientStops = stops.map { (span * $0.location, c($0.color)) } outgoingGradient = CGGradient(colorsSpace: CGColorSpace(name: CGColorSpace.sRGB), colors: stops.map { $0.color.cgColor } as CFArray, - locations: stops.map(\.location))! + locations: stops.map(\.location)) let bg = p.background let light = 0.2126 * bg.red + 0.7152 * bg.green + 0.0722 * bg.blue > 0.5 isLight = light diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/HomeFonts.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/HomeFonts.swift index de14bd63cca9..45bd91f5a5f3 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/HomeFonts.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/HomeFonts.swift @@ -1,4 +1,5 @@ import AppKit +import os /// Fonts the off-main row renderers share for the life of the process. /// @@ -21,4 +22,89 @@ enum HomeFonts { if let d = Fixture.bodyFont.fontDescriptor.withDesign(.monospaced), let f = NSFont(descriptor: d, size: size) { return f } return NSFont.userFixedPitchFont(ofSize: size) ?? Fixture.bodyFont }() + + /// `systemFont(ofSize:weight:)` for the off-main row renderers (RowDrawing, + /// MarkdownLayout): made once per size and weight and held for the life of + /// the process, so no lookup races the release of the last instance. The + /// nonnull annotation is not trusted: a nil from AppKit falls back to the + /// body font with the weight through `NSFont(descriptor:size:)`, which + /// returns an optional, and then to the body font itself. + static func system(ofSize size: CGFloat, weight: NSFont.Weight = .regular) -> NSFont { + let key = Key(size: quantized(size), weight: weight.rawValue, traits: 0, monospaced: false) + return cached(key) { makeSystem(key.size, weight) } + } + + /// Not cached: `cached` calls it under the store's lock (not reentrant). + private static func makeSystem(_ size: CGFloat, _ weight: NSFont.Weight) -> NSFont { + if let font = unannotated(NSFont.systemFont(ofSize: size, weight: weight)) { return font } + let d = Fixture.bodyFont.fontDescriptor.addingAttributes([.traits: [NSFontDescriptor.TraitKey.weight: weight.rawValue]]) + return NSFont(descriptor: d, size: size) ?? Fixture.bodyFont + } + + /// `monospacedSystemFont(ofSize:weight:)`, held like `system(ofSize:weight:)`. + static func monospaced(ofSize size: CGFloat, weight: NSFont.Weight = .regular) -> NSFont { + let key = Key(size: quantized(size), weight: weight.rawValue, traits: 0, monospaced: true) + return cached(key) { + if let font = unannotated(NSFont.monospacedSystemFont(ofSize: key.size, weight: weight)) { return font } + if let d = Fixture.bodyFont.fontDescriptor.withDesign(.monospaced), let f = NSFont(descriptor: d, size: key.size) { return f } + return NSFont.userFixedPitchFont(ofSize: key.size) ?? Fixture.bodyFont + } + } + + /// `monospacedDigitSystemFont(ofSize:weight:)`, held like `system(ofSize:weight:)`. + static func monospacedDigit(ofSize size: CGFloat, weight: NSFont.Weight = .regular) -> NSFont { + let key = Key(size: quantized(size), weight: weight.rawValue, traits: 0, monospaced: false, name: "digits") + return cached(key) { + unannotated(NSFont.monospacedDigitSystemFont(ofSize: key.size, weight: weight)) ?? makeSystem(key.size, weight) + } + } + + /// `base` with `traits` added (bold, italic for a Markdown run), held per + /// base font, size and traits; nil when the font has no such face, so a + /// caller adds no font attribute instead of a nil (`addAttribute` would + /// store NSNull for an optional and throw for a nil). + static func font(_ base: NSFont, adding traits: NSFontDescriptor.SymbolicTraits) -> NSFont? { + let all = base.fontDescriptor.symbolicTraits.union(traits) + let key = Key(size: quantized(base.pointSize), weight: 0, traits: all.rawValue, monospaced: false, name: base.fontName) + if let hit = store.withLock({ $0[key] }) { return hit } + guard let d = base.fontDescriptor.withSymbolicTraits(all), let font = NSFont(descriptor: d, size: key.size) else { return nil } + return store.withLock { fonts in + if let held = fonts[key] { return held } + fonts[key] = font + return font + } + } + + private struct Key: Hashable { + var size: CGFloat + var weight: CGFloat + var traits: UInt32 + var monospaced: Bool + var name = "" + } + + private static let store = OSAllocatedUnfairLock<[Key: NSFont]>(initialState: [:]) + + /// Sizes to the half point, so a size computed from a frame (a reaction + /// glyph at 42% of its circle) does not grow the store without bound. + private static func quantized(_ size: CGFloat) -> CGFloat { (size * 2).rounded() / 2 } + + private static func cached(_ key: Key, make: () -> NSFont) -> NSFont { + // Made under the lock: one creation per key, and no thread drops it. + // `make` must not call back into the store (the lock is not reentrant). + store.withLock { fonts in + if let held = fonts[key] { return held } + let font = make() + fonts[key] = font + return font + } + } + + /// The reference an AppKit factory annotated nonnull returned, read as an + /// optional: under concurrency these factories can return nil (cx-qpqs), + /// and Swift would trust the annotation. + private static func unannotated(_ font: NSFont) -> NSFont? { + unsafeBitCast(font, to: NSFont?.self) + } } + diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/HomeProjection.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/HomeProjection.swift index 9243363bd47d..7961180a6b3b 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/HomeProjection.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/HomeProjection.swift @@ -128,12 +128,12 @@ final class HomeProjection: @preconcurrency ChatIntents { /// The whole current value; unchanged values return before any work. func apply(items: [TranscriptItem], summary: ConversationSummary?, typing: Set, hasOlder newHasOlder: Bool) { - if controller.store == nil { + guard let store = controller.store else { install(items: items, summary: summary, typing: typing, hasOlder: newHasOlder) restoreDraft() return } - let typingChanged = Set(controller.store.state.ui.typing) != Set(typing.filter { $0 != me }.map(\.rawValue)) + let typingChanged = Set(store.state.ui.typing) != Set(typing.filter { $0 != me }.map(\.rawValue)) guard items != shown || summary != shownSummary || typingChanged || newHasOlder != hasOlder else { return } appliedUpdates += 1 if newHasOlder != hasOlder { olderRequested = false } @@ -144,17 +144,17 @@ final class HomeProjection: @preconcurrency ChatIntents { // MessagesLab bd65bbf: a keystroke goes first. Statuses and typing that arrive in a // keystroke frame are committed at the start of the next display frame; anything // else (a message, a tapback, a page) is committed now, in order. - let typingActions = core.typing(controller.store.state, wanted: typing) + let typingActions = core.typing(store.state, wanted: typing) let ambient = !diff.rebuild && (diff.actions + typingActions).allSatisfy { switch $0 { case .status, .typing: return true; default: return false } } if ambient, controller.inKeystrokeFrame, !(diff.actions + typingActions).isEmpty { let held = diff.actions controller.nextFrame { [weak self] in - guard let self, !self.stopped, self.controller.store != nil else { return } + guard let self, !self.stopped, let store = self.controller.store else { return } for a in held { self.controller.dispatch(a) } // Typing against the projection then (a receive in between may have ended it). - for a in self.core.typing(self.controller.store.state, wanted: typing) { self.controller.dispatch(a) } + for a in self.core.typing(store.state, wanted: typing) { self.controller.dispatch(a) } self.onRowsChange() } } else { @@ -166,7 +166,7 @@ final class HomeProjection: @preconcurrency ChatIntents { controller.dispatch(a) } } - for a in core.typing(controller.store.state, wanted: typing) { controller.dispatch(a) } + for a in core.typing(store.state, wanted: typing) { controller.dispatch(a) } } if titleChanged { applyHeader() } refreshAttachments() @@ -180,8 +180,8 @@ final class HomeProjection: @preconcurrency ChatIntents { private func install(items: [TranscriptItem], summary: ConversationSummary?, typing: Set, hasOlder: Bool) { let (conv, w) = core.install(conversation, items: items, summary: summary) self.hasOlder = hasOlder - controller.install(conv, windowStart: w.start, total: w.total) - controller.store.linkPreviews = linkPreviews + let store = controller.install(conv, windowStart: w.start, total: w.total) + store.linkPreviews = linkPreviews if let previews = linkPreviews?.previews { // MessagesLab 85684b4: the LinkPresentation fallback runs only for an OUTGOING card on // screen (a link I sent); a late answer fills the card. @@ -192,7 +192,7 @@ final class HomeProjection: @preconcurrency ChatIntents { } } applyHeader() - for a in core.typing(controller.store.state, wanted: typing) { controller.dispatch(a) } + for a in core.typing(store.state, wanted: typing) { controller.dispatch(a) } if notice != nil { controller.dispatch(.cmuxNotice(notice)) } refreshAttachments() onSummaryChange(summary) @@ -203,12 +203,12 @@ final class HomeProjection: @preconcurrency ChatIntents { /// for it): `.replaceWindow`, then the pin or the first visible row's /// window position is restored. private func rebuild() { - guard let demo = controller.demo else { return } + guard let demo = controller.demo, let store = controller.store else { return } rebuilds += 1 - let pinned = controller.store.state.ui.scroll.pinnedToBottom + let pinned = store.state.ui.scroll.pinnedToBottom let anchor = demo.anchorProbe let msgs = shown.map { HomeMapping.message($0, aliases: aliases, me: me, summary: shownSummary, media: core.media, links: core.links) } - let pendingLocal = controller.store.state.conversation.messages.filter { m in + let pendingLocal = store.state.conversation.messages.filter { m in aliases.contains { $0.value == m.id } && !msgs.contains { $0.id == m.id } } controller.dispatch(.replaceWindow(msgs + pendingLocal, start: HomeMapping.window(shown, summary: shownSummary).start)) @@ -246,7 +246,7 @@ final class HomeProjection: @preconcurrency ChatIntents { linkPreviews?.allowSend(text) controller.dispatch(.send) homeStore.setDraft("", for: conversation) - guard core.recordSend(key, in: controller.store.state) else { return } + guard core.recordSend(key, in: store.state) else { return } for a in attachments { media.useLocal(a.files, for: a.ref.hash) drafts[a.ref.hash] = nil @@ -280,7 +280,7 @@ final class HomeProjection: @preconcurrency ChatIntents { guard !stopped, !homeStore.transcript(for: conversation).contains(where: { $0.key == key }) else { return } core.forget(key) rebuild() - if controller.store.state.ui.draft.text.isEmpty, !text.isEmpty { controller.dispatch(.setDraft(text)) } + if controller.store?.state.ui.draft.text.isEmpty == true, !text.isEmpty { controller.dispatch(.setDraft(text)) } for a in attachments { restoreDraft(a) } if let notice { onAttachmentRefusal(notice) } } diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/PaneHost.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/PaneHost.swift index bec24b0dc00f..599f5319d922 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/PaneHost.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/PaneHost.swift @@ -255,8 +255,11 @@ extension TranscriptDocumentView { final class ChatController: NSObject, NSTextViewDelegate { var window: NSWindow? { host.window } let host: HostView - private(set) var store: Store! - private(set) var demo: MessagesWindowView! + /// The projection, nil until `install` (crash program: no longer an IUO that trapped + /// when read early). + private(set) var store: Store? + /// The window view over `store`, nil until `install`. + private(set) var demo: MessagesWindowView? /// cmux: where the user's changes go (the HomeStore adapter). weak var intents: ChatIntents? /// cmux: one-shot wake-ups on the host's timer (CmuxNext: DemandTimer). @@ -315,11 +318,14 @@ final class ChatController: NSObject, NSTextViewDelegate { /// cmux: install the window view over the adapter's projection (the /// loaded HomeStore window), in place of `load()` over a source. - func install(_ conv: Conversation, windowStart lo: Int, total: Int) { - store = Store(conversation: conv, baseDate: Date(), windowStart: lo, total: total) + @discardableResult + func install(_ conv: Conversation, windowStart lo: Int, total: Int) -> Store { + let store = Store(conversation: conv, baseDate: Date(), windowStart: lo, total: total) + self.store = store store.responder = nil start = CACurrentMediaTime() - demo = MessagesWindowView(store: store) + let demo = MessagesWindowView(store: store) + self.demo = demo demo.clock = { [weak self] in self?.clock ?? 0 } demo.requestWake = { [weak self] t in self?.requestViewWake(t) } demo.drawsChrome = false @@ -365,9 +371,9 @@ final class ChatController: NSObject, NSTextViewDelegate { tv.view.onPastePasteboard = { [weak self] pb in self?.intents?.takeAttachments(from: pb) ?? false } tv.view.onPasteImage = { _ in } tv.view.onMarkedTextChange = { [weak self] in - guard let self else { return } - let s = self.demo.compose.textView.view.string - if s != self.store.state.ui.draft.text { self.dispatch(.setDraft(s)) } + guard let self, let demo = self.demo, let store = self.store else { return } + let s = demo.compose.textView.view.string + if s != store.state.ui.draft.text { self.dispatch(.setDraft(s)) } } demo.onScrollPosition = { [weak self] in ScaleKeeper.shared.setNeedsApply() @@ -378,6 +384,7 @@ final class ChatController: NSObject, NSTextViewDelegate { if intents?.canReply == true { swipe.install() } host.needsLayout = true onInstalled.forEach { $0(self) } + return store } /// cmux: the host moved to a window (or left one): key-state palette and @@ -391,8 +398,8 @@ final class ChatController: NSObject, NSTextViewDelegate { guard let window, let demo else { return } let nc = NotificationCenter.default if !Self.noFocus { - observers.append(nc.addObserver(forName: NSWindow.didBecomeKeyNotification, object: window, queue: .main) { [weak self] _ in self?.demo.setInactive(false) }) - observers.append(nc.addObserver(forName: NSWindow.didResignKeyNotification, object: window, queue: .main) { [weak self] _ in self?.demo.setInactive(true) }) + observers.append(nc.addObserver(forName: NSWindow.didBecomeKeyNotification, object: window, queue: .main) { [weak self] _ in self?.demo?.setInactive(false) }) + observers.append(nc.addObserver(forName: NSWindow.didResignKeyNotification, object: window, queue: .main) { [weak self] _ in self?.demo?.setInactive(true) }) demo.setInactive(!window.isKeyWindow) } else { demo.setInactive(!Self.args.contains("--active")) @@ -461,7 +468,7 @@ final class ChatController: NSObject, NSTextViewDelegate { ScaleKeeper.shared.setNeedsApply() host.scrollView.syncFromModel() if !selection.isEmpty { selection.refresh() } - host.fieldChrome.follow(field: demo.compose.fieldRect) + if let demo { host.fieldChrome.follow(field: demo.compose.fieldRect) } scheduleWake() } @@ -501,10 +508,10 @@ final class ChatController: NSObject, NSTextViewDelegate { private func wakeFired() { wakeAt = .infinity let now = clock - store.advance(to: now) + store?.advance(to: now) if viewWakeAt <= now { viewWakeAt = .infinity - demo.settle(at: now) + demo?.settle(at: now) } afterEngine() } @@ -522,6 +529,7 @@ final class ChatController: NSObject, NSTextViewDelegate { } func textDidChange(_ notification: Notification) { + guard let demo else { return } dispatch(.setDraft(demo.compose.textView.view.string)) intents?.draftChanged() } @@ -610,7 +618,7 @@ final class ChatController: NSObject, NSTextViewDelegate { func showPicker(for hit: MessagesWindowView.Hit) { closePicker() - let mine = hit.row.reactions.first { $0.senderId == store.state.me }?.kind + let mine = hit.row.reactions.first { $0.senderId == store?.state.me }?.kind let p = TapbackPickerView(ref: hit.row.ref, selected: mine) { [weak self] kind in guard let self, let picker = self.picker else { return } self.intents?.react(picker.ref, kind) diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/PaneMenu.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/PaneMenu.swift index c30852782b22..579696c1958b 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/PaneMenu.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Cmux/PaneMenu.swift @@ -12,7 +12,7 @@ extension ChatController { func menu(at p: CGPoint) -> NSMenu? { guard let hit = demo?.hit(p) else { return nil } let ref = hit.row.ref - let current = hit.row.reactions.first { $0.senderId == store.state.me }?.kind + let current = hit.row.reactions.first { $0.senderId == store?.state.me }?.kind let menu = NSMenu() // The pressed bubble is highlighted while the menu is open (real Messages, macOS 27: // incoming 59 -> 91, outgoing (72,147,247) -> (45,89,192), in about 0.22 s after @@ -74,7 +74,7 @@ extension ChatController { /// Tapback Details…: who reacted, with what (a popover at the bubble). /// cmux: names from the HomeStore conversation's participants. func showTapbackDetails(_ hit: MessagesWindowView.Hit) { - let st = store.state + guard let st = store?.state else { return } let lines = hit.row.reactions.map { r -> String in let who = st.conversation.participants.first { $0.id == r.senderId }?.displayName ?? r.senderId let what: String diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/appkit-native/Compose.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/appkit-native/Compose.swift index 2701226a6a93..821727b7fb05 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/appkit-native/Compose.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/appkit-native/Compose.swift @@ -193,7 +193,8 @@ final class CaretView: NSView { /// layer (the shared code removes animations from it). final class ComposeTextView { let view: FieldTextView - var layer: CALayer { view.layer! } + // cmux: init sets wantsLayer, so the layer exists; a detached layer stands in otherwise (crash program). + var layer: CALayer { view.layer ?? CALayer() } var onSend: () -> Void { get { view.onSend } set { view.onSend = newValue } } var onEscape: () -> Void { get { view.onEscape } set { view.onEscape = newValue } } var text: String { view.string } @@ -486,8 +487,9 @@ final class ComposeView: UIView { let grey = NSColor(white: 55 / 255, alpha: 1) let space = CGColorSpace(name: CGColorSpace.sRGB) for (stops, fromTop) in [(top, true), (bottom, false)] { + // cmux: an optional gradient draws nothing when it fails (CrashSafeGraphics). let g = CGGradient(colorsSpace: space, colors: stops.map { grey.withAlphaComponent($0.1).cgColor } as CFArray, - locations: stops.map { $0.0 / cap })! + locations: stops.map { $0.0 / cap }) c.drawLinearGradient(g, start: CGPoint(x: 0, y: fromTop ? 0 : h), end: CGPoint(x: 0, y: fromTop ? cap : h - cap), options: []) } c.restoreGState() diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/appkit-native/FlightRecorder.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/appkit-native/FlightRecorder.swift index 9661d41d027f..c46e00e2b142 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/appkit-native/FlightRecorder.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/appkit-native/FlightRecorder.swift @@ -473,7 +473,7 @@ final class FlightRecorder: NSObject { "frame": c.window.map { NSStringFromRect($0.frame) } ?? ""], "load": HomeFlightRecorder.loadAverage, "build": Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") ?? ""], dir + "/meta.json") - FileHandle.standardError.write("MessagesLab flight recorder: \(reason) -> \(dir)\n".data(using: .utf8)!) + FileHandle.standardError.write(Data("MessagesLab flight recorder: \(reason) -> \(dir)\n".utf8)) // cmux: no force unwrap dumps.append(dir) // cmux: window captures only with their own opt-in (HomeFlightRecorder.capturesWindow). if HomeFlightRecorder.capturesWindow() { burst(dir, c, count: 30) } diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/appkit-native/HeaderBar.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/appkit-native/HeaderBar.swift index 56d2e0dda829..a32807782235 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/appkit-native/HeaderBar.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/appkit-native/HeaderBar.swift @@ -26,7 +26,9 @@ final class HeaderBar: NSObject, NSToolbarDelegate { avatarHolder?.shift = contentLeading / 2 } } - private var pillCenter: NSLayoutConstraint! + // cmux: built on first use in init, never an IUO (crash program). + private let pillHolder = PassThroughView() + private lazy var pillCenter: NSLayoutConstraint = pill.centerXAnchor.constraint(equalTo: pillHolder.centerXAnchor) /// The accessory spans the window, or (macOS 26 with a sidebar item) only the detail /// pane: the pill moves from the accessory's center to the transcript's. func centerPill() { @@ -64,8 +66,7 @@ final class HeaderBar: NSObject, NSToolbarDelegate { pill.font = .systemFont(ofSize: 13, weight: .bold) pill.target = self pill.action = #selector(contactClicked) - let holder = PassThroughView() - pillCenter = pill.centerXAnchor.constraint(equalTo: holder.centerXAnchor) + let holder = pillHolder holder.translatesAutoresizingMaskIntoConstraints = false pill.translatesAutoresizingMaskIntoConstraints = false holder.addSubview(pill) diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/appkit-native/SwipeReply.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/appkit-native/SwipeReply.swift index e6552c48a3ac..556f5ac09a14 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/appkit-native/SwipeReply.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/appkit-native/SwipeReply.swift @@ -183,7 +183,7 @@ final class SwipeReply { guard let sym = NSImage(systemSymbolName: "arrowshape.turn.up.left.fill", accessibilityDescription: nil)?.withSymbolConfiguration(cfg) else { return nil } let px = Int(Tuning.arrowSize * scale) guard let ctx = CGContext(data: nil, width: px, height: px, bitsPerComponent: 8, bytesPerRow: 0, - space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil } + space: LabColorSpace.sRGB, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil } // cmux: no force unwrap NSGraphicsContext.saveGraphicsState() NSGraphicsContext.current = NSGraphicsContext(cgContext: ctx, flipped: false) let sz = sym.size, r = CGFloat(px) @@ -206,39 +206,44 @@ enum SwipeCheck { guard let i = a.firstIndex(of: "--swipe-check"), i + 1 < a.count else { return nil } return a[i + 1] } - static func event(dx: CGFloat, dy: CGFloat, phase: Int64) -> NSEvent { - let cg = CGEvent(scrollWheelEvent2Source: nil, units: .pixel, wheelCount: 2, wheel1: Int32(dy), wheel2: Int32(dx), wheel3: 0)! + // cmux: optional, no force unwraps (crash program); `run` records a FAIL for a nil event. + static func event(dx: CGFloat, dy: CGFloat, phase: Int64) -> NSEvent? { + guard let cg = CGEvent(scrollWheelEvent2Source: nil, units: .pixel, wheelCount: 2, wheel1: Int32(dy), wheel2: Int32(dx), wheel3: 0) else { return nil } cg.setIntegerValueField(.scrollWheelEventIsContinuous, value: 1) cg.setDoubleValueField(.scrollWheelEventFixedPtDeltaAxis1, value: dy) cg.setDoubleValueField(.scrollWheelEventFixedPtDeltaAxis2, value: dx) cg.setIntegerValueField(.scrollWheelEventPointDeltaAxis1, value: Int64(dy)) cg.setIntegerValueField(.scrollWheelEventPointDeltaAxis2, value: Int64(dx)) cg.setIntegerValueField(.scrollWheelEventScrollPhase, value: phase) - return NSEvent(cgEvent: cg)! + return NSEvent(cgEvent: cg) } static func run(_ c: ChatController, out: String) { var lines: [String] = [] func check(_ name: String, _ ok: Bool, _ detail: String) { lines.append("\(ok ? "PASS" : "FAIL") \(name): \(detail)") } - guard let hit = c.demo.lastTextRow(mine: false) else { lines.append("FAIL no incoming text row"); finish(lines, out); return } + guard let hit = c.demo?.lastTextRow(mine: false) else { lines.append("FAIL no incoming text row"); finish(lines, out); return } let p = CGPoint(x: hit.body.midX, y: hit.body.midY) + @discardableResult func handle(_ e: NSEvent?) -> NSEvent? { // cmux: a nil event is a FAIL, not a trap + guard let e else { lines.append("FAIL could not make a scroll event"); return nil } + return c.swipe.handle(e, at: p) + } func stream(_ dx: CGFloat, _ dy: CGFloat, steps: Int) -> [CGFloat] { var offsets: [CGFloat] = [] - c.swipe.handle(event(dx: dx / CGFloat(steps), dy: dy / CGFloat(steps), phase: 1), at: p) - for _ in 1.. UIImage? { guard let cg = cgImage else { return self } guard let ctx = CGContext(data: nil, width: cg.width, height: cg.height, bitsPerComponent: 8, bytesPerRow: 0, - space: CGColorSpace(name: CGColorSpace.sRGB)!, + space: LabColorSpace.sRGB, // cmux: no force unwrap bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue) else { return self } ctx.draw(cg, in: CGRect(x: 0, y: 0, width: cg.width, height: cg.height)) return UIImage(cgImage: ctx.makeImage(), scale: scale) diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Engine.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Engine.swift index 33ccf0663b43..9b2a52ce41b8 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Engine.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Engine.swift @@ -204,13 +204,14 @@ enum Reducer { /// grey placeholder square, 137.5 x 103.5 pt) until LinkPreviews fills it or, /// without metadata, the domain card (title = site = host) replaces it. enum TextParts { - private static let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) + // cmux: optional, no try! (crash program); without it no link is detected. + static let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) static func host(_ url: URL) -> String { url.host.map { $0.hasPrefix("www.") ? String($0.dropFirst(4)) : $0 } ?? url.absoluteString } static func linkRuns(_ text: String) -> [TextRun] { let ns = text as NSString - return detector.matches(in: text, range: NSRange(location: 0, length: ns.length)).compactMap { m in + return (detector?.matches(in: text, range: NSRange(location: 0, length: ns.length)) ?? []).compactMap { m in guard let url = m.url else { return nil } return TextRun(start: m.range.location, length: m.range.length, style: nil, link: url.absoluteString, mention: nil, detected: nil) } @@ -219,7 +220,7 @@ enum TextParts { static func soleURL(_ line: String) -> URL? { let t = line.trimmingCharacters(in: .whitespaces) let ns = t as NSString - guard ns.length > 0, let m = detector.firstMatch(in: t, range: NSRange(location: 0, length: ns.length)), + guard ns.length > 0, let m = detector?.firstMatch(in: t, range: NSRange(location: 0, length: ns.length)), m.range.location == 0, m.range.length == ns.length, let url = m.url, url.scheme == "http" || url.scheme == "https" else { return nil } return url diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Fixture.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Fixture.swift index 2e3d3efaf8aa..c1e895ebbe01 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Fixture.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Fixture.swift @@ -98,10 +98,11 @@ enum Fixture { (1500, 68.8, 145.8), (1800, 65.2, 144.1), (2082, 62.8, 142)] /// A gradient colour (red, green from the stops) in Display P3. static func gradientColor(_ r: CGFloat, _ g: CGFloat) -> UIColor { p3(r, g, gradientBlue) } - private static let measuredGradient: CGGradient = CGGradient( + // cmux: optional, no force unwrap (crash program); a nil gradient draws nothing. + private static let measuredGradient: CGGradient? = CGGradient( colorsSpace: CGColorSpace(name: CGColorSpace.displayP3), colors: gradientStops.map { gradientColor($0.1, $0.2).cgColor } as CFArray, - locations: gradientStops.map { $0.0 / 2082 })! + locations: gradientStops.map { $0.0 / 2082 }) /// cmux: the themed outgoing gradient as (2x px window y, colour) stops; /// nil keeps the measured stops (`gradientStops`, `gradientBlue`). static var themedGradient: [(CGFloat, UIColor)]? { themedAccent ? theme.map { (inactive ? $0.inactive : $0.active).gradientStops } : nil } @@ -118,7 +119,7 @@ enum Fixture { green: ca.greenComponent + (cb.greenComponent - ca.greenComponent) * f, blue: ca.blueComponent + (cb.blueComponent - ca.blueComponent) * f, alpha: 1) } - static var outgoingGradient: CGGradient { + static var outgoingGradient: CGGradient? { if let t = theme, themedAccent { return (inactive ? t.inactive : t.active).outgoingGradient } return measuredGradient } diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Header.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Header.swift index a9587493d171..60d3318c95fc 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Header.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Header.swift @@ -15,8 +15,9 @@ final class HeaderView: UIView { private let overlay: CanvasView // Display P3: the same transfer curve as sRGB (the fitted blur is unchanged for // greys) without clipping the P3 blues under the header. - private static let ci = CIContext(options: [.workingColorSpace: CGColorSpace(name: CGColorSpace.displayP3)!, - .outputColorSpace: CGColorSpace(name: CGColorSpace.displayP3)!]) + // cmux: LabColorSpace (no force unwrap; crash program). + private static let ci = CIContext(options: [.workingColorSpace: LabColorSpace.displayP3, + .outputColorSpace: LabColorSpace.displayP3]) // Fitted to the reference header (least squares over three frames): // out = base + gain * (w * blur(s1) + (1 - w) * blur(s2)), sigmas in 2x px. static let blurSigma1: Double = 5.3 @@ -185,7 +186,8 @@ final class ChromeView: UIView { } ctx.saveGState() UIBezierPath(ovalIn: r).addClip() - let g = CGGradient(colorsSpace: space, colors: [col(c.0), col(c.1)] as CFArray, locations: [0.15, 0.85])! + // cmux: an optional gradient draws nothing when it fails (CrashSafeGraphics). + let g = CGGradient(colorsSpace: space, colors: [col(c.0), col(c.1)] as CFArray, locations: [0.15, 0.85]) ctx.drawLinearGradient(g, start: CGPoint(x: 0, y: r.minY), end: CGPoint(x: 0, y: r.maxY), options: []) ctx.restoreGState() UIColor(white: 1, alpha: 0.35).setStroke() diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Layout.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Layout.swift index 02aad4ee109a..cc5a8459ee5a 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Layout.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Layout.swift @@ -43,8 +43,9 @@ struct TextLayout: Hashable { func attributed(color: UIColor, linkColor: UIColor, kern: CGFloat = Fixture.bodyKern) -> NSAttributedString { let a = NSMutableAttributedString(string: text, attributes: [.font: Fixture.bodyFont, .foregroundColor: color, .kern: kern]) for r in runs { - let range = NSRange(location: r.start, length: r.length) - guard NSMaxRange(range) <= a.length else { continue } + // cmux: a run that does not fit this text is skipped: negative, or past the end + // without overflowing (NSMaxRange of Int.max traps; addAttribute raises NSRangeException). + guard let range = Self.range(r.start, r.length, in: a.length) else { continue } var traits: UIFontDescriptor.SymbolicTraits = [] for s in r.style ?? [] { switch s { @@ -56,8 +57,9 @@ struct TextLayout: Hashable { } } if r.mention != nil { traits.insert(.traitBold) } - if !traits.isEmpty, let d = Fixture.bodyFont.fontDescriptor.withSymbolicTraits(traits) { - a.addAttribute(.font, value: UIFont(descriptor: d, size: Fixture.bodyFont.pointSize), range: range) + // cmux: the bold/italic face held for the process (HomeFonts, cx-qpqs); no font attribute when there is none. + if !traits.isEmpty, let f = HomeFonts.font(Fixture.bodyFont, adding: traits) { + a.addAttribute(.font, value: f, range: range) } // cmux: inline code and code blocks (HomeMarkdown) in the monospaced system font, one point smaller like Messages' body. // One font for the process (HomeFonts.code): one made per run on RowBitmaps' threads came back nil. @@ -72,6 +74,13 @@ struct TextLayout: Hashable { return a } + /// cmux: `start.. NSRange? { + guard start >= 0, length >= 0, start <= count, length <= count - start else { return nil } + return NSRange(location: start, length: length) + } + /// A line after a hard newline advances as far as a wrapped line, on both /// sides (measured: a received 19-line bubble with 13 newlines is 19 x 16 pt; /// the recording's sent 3-line bubble is 14 + 3 x 16 = 62 pt). @@ -97,6 +106,8 @@ struct TextLayout: Hashable { let i = Int(floor(p.y / Fixture.lineHeight)) guard i >= 0, i < lines.count else { return nil } let attr = attributed(color: .white, linkColor: .white) + // cmux: lines measured for another text (stale during an edit or a streamed reply) are not read past the end. + guard Self.range(lines[i].range.location, lines[i].range.length, in: attr.length) != nil else { return nil } let line = CTLineCreateWithAttributedString(attr.attributedSubstring(from: lines[i].range)) let idx = CTLineGetStringIndexForPosition(line, CGPoint(x: p.x, y: 0)) + lines[i].range.location return runs.first { $0.link != nil && idx >= $0.start && idx < $0.start + $0.length }?.link @@ -620,7 +631,7 @@ enum RowBuilder { let outgoing = m.senderId == me var gap: CGFloat var connector: String? - if prev == nil || m.date.timeIntervalSince(prev!.date) > separatorGap { + if prev.map({ m.date.timeIntervalSince($0.date) > separatorGap }) ?? true { // cmux: no force unwrap rows.append(RowSpec(key: "sep:\(m.id)", kind: .separator(bold: Format.day(m.date, now: now), rest: Format.time(m.date)), gap: prev == nil ? 12 : 0, height: 35.5)) gap = 0 @@ -665,8 +676,9 @@ enum RowBuilder { if m.retractedAt != nil { rows.append(RowSpec(key: "unsent:\(m.id)", kind: .unsent(outgoing: outgoing), gap: max(gap, 8), height: 16)) } else { - let lastOfGroup = next == nil || next!.senderId != m.senderId || next!.date.timeIntervalSince(m.date) >= groupGap - || next!.retractedAt != nil || next!.replyTo != m.replyTo + // cmux: no force unwrap (crash program) + let lastOfGroup = next.map { next in next.senderId != m.senderId || next.date.timeIntervalSince(m.date) >= groupGap + || next.retractedAt != nil || next.replyTo != m.replyTo } ?? true for (pi, part) in m.parts.enumerated() { let measured = MeasureCache.shared.size(m, pi, width: width, estimate: exact.map { !$0.contains(idx) } ?? false) let (size, tl) = (measured.size, measured.text) diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/LinkPreviews.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/LinkPreviews.swift index a8be03990617..dd7a32646166 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/LinkPreviews.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/LinkPreviews.swift @@ -62,7 +62,7 @@ final class LinkPreviews: LinkPreviewFetching { if hit?.title == nil { enqueueFallback(url) } return } - if waiting[url] != nil { waiting[url]!.append(done); return } + if waiting[url] != nil { waiting[url]?.append(done); return } // cmux: no force unwrap guard let u = URL(string: url), u.scheme == "https" || u.scheme == "http" else { done(nil); return } waiting[url] = [done] let file = dir.appendingPathComponent(String(format: "%016llx.png", LinkPreviews.fnv1a(url))) @@ -107,9 +107,11 @@ final class LinkPreviews: LinkPreviewFetching { /// `` (either attribute order), entities decoded. static func metaTags(_ html: String) -> [String: String] { var out: [String: String] = [:] - let re = try! NSRegularExpression(pattern: "]*>", options: [.caseInsensitive]) - let key = try! NSRegularExpression(pattern: "(?:property|name)\\s*=\\s*[\"']([^\"']+)[\"']", options: [.caseInsensitive]) - let val = try! NSRegularExpression(pattern: "content\\s*=\\s*(\"([^\"]*)\"|'([^']*)')", options: [.caseInsensitive]) + // cmux: no try! (crash program); a pattern that fails to compile reads no tags. + guard let re = try? NSRegularExpression(pattern: "]*>", options: [.caseInsensitive]), + let key = try? NSRegularExpression(pattern: "(?:property|name)\\s*=\\s*[\"']([^\"']+)[\"']", options: [.caseInsensitive]), + let val = try? NSRegularExpression(pattern: "content\\s*=\\s*(\"([^\"]*)\"|'([^']*)')", options: [.caseInsensitive]) + else { return out } let ns = html as NSString for m in re.matches(in: html, range: NSRange(location: 0, length: min(ns.length, 400_000))) { let tag = ns.substring(with: m.range) as NSString diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/LongText.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/LongText.swift index 8c950990b42c..4e5c13b4ff45 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/LongText.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/LongText.swift @@ -218,7 +218,8 @@ final class LongTextIndex: @unchecked Sendable { func blockString(_ b: Int) -> NSString { let a = starts[b], e = starts[b + 1] return withBytes { p in - NSString(bytes: p.baseAddress! + a, length: e - a, encoding: String.Encoding.utf8.rawValue) ?? "" + guard let base = p.baseAddress else { return "" } // cmux: no force unwrap + return NSString(bytes: base + a, length: e - a, encoding: String.Encoding.utf8.rawValue) ?? "" } } @@ -248,8 +249,10 @@ final class LongTextIndex: @unchecked Sendable { guard !n.isEmpty, from < count else { return nil } return withBytes { p in n.withUnsafeBufferPointer { q in - guard let r = memmem(p.baseAddress! + from, count - from, q.baseAddress!, q.count) else { return nil } - let o = UnsafeRawPointer(r) - UnsafeRawPointer(p.baseAddress!) + // cmux: no force unwraps (crash program) + guard let base = p.baseAddress, let needle = q.baseAddress, + let r = memmem(base + from, count - from, needle, q.count) else { return nil } + let o = UnsafeRawPointer(r) - UnsafeRawPointer(base) return o..<(o + q.count) } } @@ -337,14 +340,15 @@ final class BlockLayout: @unchecked Sendable { let a = NSMutableAttributedString(string: string as String, attributes: [.font: Fixture.bodyFont, .foregroundColor: color, .kern: Fixture.bodyKern]) if string.range(of: "http").location != NSNotFound || string.range(of: "www.").location != NSNotFound { - for m in BlockLayout.detector.matches(in: string as String, range: NSRange(location: 0, length: string.length)) { + for m in BlockLayout.detector?.matches(in: string as String, range: NSRange(location: 0, length: string.length)) ?? [] { a.addAttributes([.foregroundColor: link, .underlineStyle: NSUnderlineStyle.single.rawValue], range: m.range) } } drawAttr[outgoing] = a return a } - static let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) + // cmux: optional, no try! (crash program); without it no link is underlined. + static let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) } /// Block layouts by (lineage, byte range, column): LRU, 256 blocks. @@ -818,7 +822,8 @@ final class LongTextStore: @unchecked Sendable { /// The layout of a long text at a width. `message`: a message shown as source /// (MarkdownStore.showsSource) lays its markdown text out as plain text. func layout(_ text: String, width: CGFloat, message: ID? = nil) -> LongTextLayout { - let idx = index(for: text)! + // cmux: index(for:) builds one when asked to; an unregistered index stands in (crash program). + let idx = index(for: text) ?? LongTextIndex.build(text, lineage: 0) // cmux: a plain message (MarkdownStore.isPlain) is laid out as plain text too. let md = idx.markdown && !(message.map { MarkdownStore.shared.showsSource($0) || MarkdownStore.shared.isPlain($0) } ?? false) let wk = md || !idx.markdown ? width : -width @@ -874,7 +879,10 @@ final class LongTextStore: @unchecked Sendable { prev.markdown || !LongTextIndex.isMarkdown(String(decoding: UnsafeBufferPointer(rebasing: p[prev.starts[prev.blockCount - 1]...]), as: UTF8.self)) { let keep = prev.blockCount - 1 let from = max(0, prev.starts[keep] - 256) - let same = prev.withBytes { q in memcmp(q.baseAddress! + from, p.baseAddress! + from, prev.count - from) == 0 } + let same = prev.withBytes { q in // cmux: no force unwraps + guard let qb = q.baseAddress, let pb = p.baseAddress else { return false } + return memcmp(qb + from, pb + from, prev.count - from) == 0 + } if same { let i = LongTextIndex.build(t, lineage: prev.lineage, prefix: prev, keep: keep) LongTextStats.streamExtends += 1 diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/MarkdownLayout.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/MarkdownLayout.swift index e44d8c8354e4..98b918a53d0a 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/MarkdownLayout.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/MarkdownLayout.swift @@ -102,11 +102,11 @@ extension Markdown { /// Body text baseline below a line top (13 pt SF in a 16 pt line; Fixture.textBaseline - bubblePadY). static let bodyBaseline: CGFloat = 13 static let codeBaseline: CGFloat = 12.5 - static let codeFont = UIFont.monospacedSystemFont(ofSize: 12, weight: .regular) - static let codeBoldFont = UIFont.monospacedSystemFont(ofSize: 12, weight: .semibold) - static let inlineCodeFont = UIFont.monospacedSystemFont(ofSize: 12, weight: .regular) + static let codeFont = HomeFonts.monospaced(ofSize: 12, weight: .regular) // cmux: nil-checked (HomeFonts, cx-qpqs) + static let codeBoldFont = HomeFonts.monospaced(ofSize: 12, weight: .semibold) // cmux: nil-checked (HomeFonts, cx-qpqs) + static let inlineCodeFont = HomeFonts.monospaced(ofSize: 12, weight: .regular) // cmux: nil-checked (HomeFonts, cx-qpqs) /// Headings are body size (Lawrence, 2026-10-06): weight only, one step. - static func headingFont(_ level: Int) -> UIFont { .systemFont(ofSize: Fixture.bodyFont.pointSize, weight: level <= 2 ? .bold : .semibold) } + static func headingFont(_ level: Int) -> UIFont { HomeFonts.system(ofSize: Fixture.bodyFont.pointSize, weight: level <= 2 ? .bold : .semibold) } // cmux: held for the process (HomeFonts, cx-qpqs) static let codePadX: CGFloat = 8 /// Space under a scrollable block's content for its scroll indicator. static let indicatorRoom: CGFloat = 5 @@ -480,7 +480,7 @@ enum MarkdownLayoutEngine { let rid = out.regions.count let cols = max(1, t.columns) let pad = Markdown.cellPadX - let headFont = UIFont.systemFont(ofSize: Fixture.bodyFont.pointSize, weight: .semibold) + let headFont = HomeFonts.system(ofSize: Fixture.bodyFont.pointSize, weight: .semibold) // cmux: held for the process (HomeFonts, cx-qpqs) let all: [[MDText]] = [t.header] + t.rows // Column widths: min = widest unbreakable word (capped), max = widest one-line cell. var minW = [CGFloat](repeating: 16, count: cols), maxW = [CGFloat](repeating: 16, count: cols) @@ -613,8 +613,9 @@ enum MarkdownLayoutEngine { var traits: UIFontDescriptor.SymbolicTraits = [] if s.style.contains(.strong) { traits.insert(.traitBold) } if s.style.contains(.emphasis) { traits.insert(.traitItalic) } - if !traits.isEmpty, let d = font.fontDescriptor.withSymbolicTraits(font.fontDescriptor.symbolicTraits.union(traits)) { - a.addAttribute(.font, value: UIFont(descriptor: d, size: font.pointSize), range: r) + // cmux: the bold/italic face held for the process (HomeFonts, cx-qpqs); no font attribute when there is none. + if !traits.isEmpty, let f = HomeFonts.font(font, adding: traits) { + a.addAttribute(.font, value: f, range: r) } } if let l = s.link { a.addAttribute(.link, value: l, range: r) } diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/MarkdownParser.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/MarkdownParser.swift index 188bd9955933..f66e76726ac7 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/MarkdownParser.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/MarkdownParser.swift @@ -1024,7 +1024,8 @@ enum MDInlineParser { let hex = body.hasPrefix("#x") || body.hasPrefix("#X") let digits = body.dropFirst(hex ? 2 : 1) guard !digits.isEmpty, digits.count <= (hex ? 6 : 7), let v = UInt32(digits, radix: hex ? 16 : 10) else { return nil } - let scalar = (v == 0 || v > 0x10FFFF) ? Unicode.Scalar(0xFFFD)! : (Unicode.Scalar(v) ?? Unicode.Scalar(0xFFFD)!) + let replacement: Unicode.Scalar = "\u{FFFD}" // cmux: a literal, no force unwrap + let scalar = (v == 0 || v > 0x10FFFF) ? replacement : (Unicode.Scalar(v) ?? replacement) return (String(scalar), semi - i + 1) } guard let r = entities[body] else { return nil } @@ -1037,7 +1038,7 @@ enum MDInlineParser { guard !body.isEmpty, !body.contains(where: { $0 == " " || $0 == "<" || $0 == "\n" }) else { return nil } if let colon = body.firstIndex(of: ":") { let scheme = body[.. Bool { lock.lock(); defer { lock.unlock() }; return source.contains(id) } func setShowsSource(_ id: ID, _ on: Bool) { lock.lock(); if on { source.insert(id) } else { source.remove(id) }; lock.unlock() } - /// cmux: messages whose text is never Markdown (a person's text shows as typed; only an - /// agent's is Markdown). The host marks them before they are measured. - private var plain = Set() - func isPlain(_ id: ID) -> Bool { lock.lock(); defer { lock.unlock() }; return plain.contains(id) } - func setPlain(_ id: ID, _ on: Bool) { lock.lock(); if on { plain.insert(id) } else { plain.remove(id) }; lock.unlock() } + /// cmux: a message's text is plain unless the host marks it Markdown (only an agent's + /// text is Markdown; a person's shows as typed). Plain is the default, so a message the + /// host has not seen (the reducer's local send, measured before the owner's echo) never + /// takes the Markdown engine. The host marks a message before it is measured. + private var markdownIDs = Set() + func isPlain(_ id: ID) -> Bool { lock.lock(); defer { lock.unlock() }; return !markdownIDs.contains(id) } + func setPlain(_ id: ID, _ on: Bool) { lock.lock(); if on { markdownIDs.remove(id) } else { markdownIDs.insert(id) }; lock.unlock() } func document(_ text: String) -> MDDocument { lock.lock() diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Model.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Model.swift index 18311f3480a6..e87d41e936d1 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Model.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Model.swift @@ -226,7 +226,7 @@ enum Instant { /// Unset (fixtures, the differential harness), the conversation's -07:00. static var liveZone: TimeZone? static var liveLocale: Locale? - static let zone = liveZone ?? TimeZone(secondsFromGMT: -7 * 3600)! + static let zone = liveZone ?? TimeZone(secondsFromGMT: -7 * 3600) ?? .gmt // cmux: no force unwrap static let locale = liveLocale ?? Locale(identifier: "en_US") private static let writer: ISO8601DateFormatter = { let f = ISO8601DateFormatter() @@ -313,7 +313,7 @@ enum Fixtures { /// into this variant's sources). /// cmux: fixtures are not in the app bundle; the harness sets `root`. static var root: URL? - static var sharedDirectory: URL { root ?? Bundle.main.resourceURL! } + static var sharedDirectory: URL { root ?? Bundle.main.resourceURL ?? Bundle.main.bundleURL } // cmux: no force unwrap /// The repo's shared/ directory, for the large generated stores that are /// not bundled. static var repoShared: URL { @@ -322,12 +322,17 @@ enum Fixtures { } static func loadConversation() -> Conversation { let url = sharedDirectory.appendingPathComponent("conversation.json") - let data = try! Data(contentsOf: url) - return try! JSONDecoder().decode(Conversation.self, from: data) + // cmux: no try! (crash program); a missing or unreadable fixture is an empty conversation. + guard let data = try? Data(contentsOf: url), + let conversation = try? JSONDecoder().decode(Conversation.self, from: data) else { + return Conversation(id: "", title: "", participants: [], messages: []) + } + return conversation } /// Resolve an AssetRef: a path relative to shared/assets or a file URL. static func assetURL(_ ref: String) -> URL { - if ref.hasPrefix("file:") { return URL(string: ref)! } + // cmux: no force unwrap; a file: ref that does not parse resolves like any other ref. + if ref.hasPrefix("file:"), let url = URL(string: ref) { return url } // Catalyst fixture assets (Fixtures/real, bundled as `real/`). if ref.hasPrefix("real/") { return sharedDirectory.appendingPathComponent(ref) } return sharedDirectory.appendingPathComponent("assets").appendingPathComponent(ref) diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/RowDrawing.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/RowDrawing.swift index 34f2d2e2b825..b6dc8972ca35 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/RowDrawing.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/RowDrawing.swift @@ -13,8 +13,9 @@ enum RowDraw { static let margin: CGFloat = 24 static func receiptParts(_ bold: String, _ rest: String) -> [(String, UIFont, UIColor)] { - [(bold, .systemFont(ofSize: Fixture.captionSize, weight: .semibold), Fixture.secondaryText), - (rest, .systemFont(ofSize: Fixture.captionSize), Fixture.secondaryText)] + // cmux: fonts held for the process (HomeFonts, cx-qpqs); receipts draw on RowBitmaps' threads. + [(bold, HomeFonts.system(ofSize: Fixture.captionSize, weight: .semibold), Fixture.secondaryText), + (rest, HomeFonts.system(ofSize: Fixture.captionSize), Fixture.secondaryText)] } static let captionKern: CGFloat = -0.03 @@ -65,17 +66,17 @@ enum RowDraw { } case let .unsent(outgoing): let s = outgoing ? Strings.unsentMine : Strings.unsentTheirs - let f = UIFont.systemFont(ofSize: 11) + let f = HomeFonts.system(ofSize: 11) // cmux: HomeFonts (cx-qpqs) let w = TextDraw.width(s, font: f) TextDraw.line(s, font: f, color: Fixture.secondaryText, x: m.centerX + 0.1 - w / 2, baseline: top + 12, in: ctx) case let .label(text, outgoing, color): - let f = UIFont.systemFont(ofSize: 10, weight: .medium) + let f = HomeFonts.system(ofSize: 10, weight: .medium) // cmux: HomeFonts (cx-qpqs) let c: UIColor = color == .failure ? UIColor(red: 1, green: 0.27, blue: 0.23, alpha: 1) : color == .link ? UIColor(red: 0.2, green: 0.55, blue: 1, alpha: 1) : Fixture.secondaryText let w = TextDraw.width(text, font: f) TextDraw.line(text, font: f, color: c, x: outgoing ? m.receiptRight - w : Fixture.labelLeft, baseline: top + 11, in: ctx) case let .replies(count, _, outgoing): - let f = UIFont.systemFont(ofSize: 10, weight: .semibold) + let f = HomeFonts.system(ofSize: 10, weight: .semibold) // cmux: HomeFonts (cx-qpqs) let s = Strings.replies(count) let w = TextDraw.width(s, font: f, kern: captionKern) TextDraw.line(s, font: f, color: PreviewStyle.repliesBlue, @@ -151,7 +152,7 @@ enum PartRenderer { UIColor(white: light ? 0 : 1, alpha: 0.25 + 0.6 * CGFloat(k) / 7).setStroke(); p.stroke() } let host = URL(string: url).map(TextParts.host) ?? url - let f = UIFont.systemFont(ofSize: 10) + let f = HomeFonts.system(ofSize: 10) // cmux: HomeFonts (cx-qpqs) TextDraw.line(host, font: f, color: Fixture.secondaryText, x: body.midX - TextDraw.width(host, font: f) / 2, baseline: c.y + 24, in: ctx) case let .link(_, title, site, image, theme): // A light appearance draws every card light; a dark one keeps the card's @@ -178,7 +179,7 @@ enum PartRenderer { let c = CGPoint(x: body.minX - 14, y: body.midY) UIColor(red: 1, green: 0.27, blue: 0.23, alpha: 1).setFill() UIBezierPath(ovalIn: CGRect(x: c.x - 8, y: c.y - 8, width: 16, height: 16)).fill() - let f = UIFont.systemFont(ofSize: 12, weight: .bold) + let f = HomeFonts.system(ofSize: 12, weight: .bold) // cmux: HomeFonts (cx-qpqs) TextDraw.line("!", font: f, color: .white, x: c.x - TextDraw.width("!", font: f) / 2, baseline: c.y + 4.5, in: ctx) } drawReactions(ctx, p.reactions, body: body, outgoing: p.outgoing, windowY: windowY) @@ -223,7 +224,7 @@ enum PartRenderer { TextDraw.line(s, font: Sizing.linkTitleFont, color: titleColor, x: card.minX + 10, baseline: y, in: ctx, kern: -0.005) y += 12 } - TextDraw.line(site, font: .systemFont(ofSize: 10), color: siteColor, x: card.minX + 10.25, baseline: y + 2.8, in: ctx, kern: -0.03) + TextDraw.line(site, font: HomeFonts.system(ofSize: 10), color: siteColor, x: card.minX + 10.25, baseline: y + 2.8, in: ctx, kern: -0.03) // cmux: HomeFonts (cx-qpqs) } static func drawAttachment(_ ctx: CGContext, _ a: Attachment, body: CGRect, row p: PartRow, windowY: CGFloat) { @@ -274,7 +275,7 @@ enum PartRenderer { cornerRadius: 1).fill() } let d = Format.duration(a.durationSeconds ?? 0) - TextDraw.line(d, font: .monospacedDigitSystemFont(ofSize: 11, weight: .regular), color: fg, x: body.maxX - 36, + TextDraw.line(d, font: HomeFonts.monospacedDigit(ofSize: 11, weight: .regular), color: fg, x: body.maxX - 36, // cmux: HomeFonts (cx-qpqs) baseline: body.midY + 4, in: ctx) default: fillBubble(ctx, shape, outgoing: p.outgoing, windowY: windowY) @@ -284,11 +285,11 @@ enum PartRenderer { UIColor(white: 0.55, alpha: 1).setFill() UIBezierPath(ovalIn: CGRect(x: body.minX + 9, y: body.minY + 10, width: 36, height: 36)).fill() let initial = String(a.fileName.prefix(1)).uppercased() - let f = UIFont.systemFont(ofSize: 17, weight: .semibold) + let f = HomeFonts.system(ofSize: 17, weight: .semibold) // cmux: HomeFonts (cx-qpqs) TextDraw.line(initial, font: f, color: .white, x: body.minX + 27 - TextDraw.width(initial, font: f) / 2, baseline: body.minY + 34, in: ctx) let name = (a.fileName as NSString).deletingPathExtension - TextDraw.line(name, font: .systemFont(ofSize: 13, weight: .semibold), color: fg, x: body.minX + 54, baseline: body.minY + 33, in: ctx) + TextDraw.line(name, font: HomeFonts.system(ofSize: 13, weight: .semibold), color: fg, x: body.minX + 54, baseline: body.minY + 33, in: ctx) // cmux: HomeFonts (cx-qpqs) let chev = UIBezierPath() chev.move(to: CGPoint(x: body.maxX - 18, y: body.midY - 5)) chev.addLine(to: CGPoint(x: body.maxX - 13, y: body.midY)) @@ -348,11 +349,11 @@ enum PartRenderer { } } let label = ext.uppercased() - let f = UIFont.systemFont(ofSize: 7, weight: .regular) + let f = HomeFonts.system(ofSize: 7, weight: .regular) // cmux: HomeFonts (cx-qpqs) TextDraw.line(label, font: f, color: UIColor(white: 0.6, alpha: 1), x: icon.midX - TextDraw.width(label, font: f) / 2, baseline: icon.maxY - 5, in: ctx) } - let nameFont = UIFont.systemFont(ofSize: 13, weight: .semibold) + let nameFont = HomeFonts.system(ofSize: 13, weight: .semibold) // cmux: HomeFonts (cx-qpqs) var name = a.fileName while TextDraw.width(name, font: nameFont) > body.width - 100, name.count > 4 { name = String(name.dropLast(5)) + "…" } let x = body.minX + 84.5 @@ -366,7 +367,7 @@ enum PartRenderer { fg.setFill() UIBezierPath(roundedRect: CGRect(x: bar.minX, y: bar.minY, width: bar.width * CGFloat(pr), height: 4), cornerRadius: 2).fill() } - TextDraw.line(sub, font: .systemFont(ofSize: 11), color: fg.withAlphaComponent(0.6), x: x, baseline: body.minY + 58.5, in: ctx) + TextDraw.line(sub, font: HomeFonts.system(ofSize: 11), color: fg.withAlphaComponent(0.6), x: x, baseline: body.minY + 58.5, in: ctx) // cmux: HomeFonts (cx-qpqs) } /// The round save button beside a photo or video (measured: 28 pt, 14 pt @@ -434,7 +435,7 @@ enum PartRenderer { Fixture.connector.setFill() UIBezierPath(roundedRect: CGRect(x: 32.5, y: stubTop, width: 2.5, height: stubH), cornerRadius: 1.25).fill() if pv.count >= 2 { - let f = UIFont.systemFont(ofSize: 10, weight: .semibold) + let f = HomeFonts.system(ofSize: 10, weight: .semibold) // cmux: HomeFonts (cx-qpqs) TextDraw.line(Strings.replies(pv.count), font: f, color: PreviewStyle.repliesBlue, x: 44.5, baseline: box.maxY + (pv.isText ? 12.5 : 11.5), in: ctx, kern: RowDraw.captionKern) } @@ -463,7 +464,7 @@ enum PartRenderer { BubblePath.make(body: full, outgoing: outgoing, tail: tail).addClip() img.draw(in: full) ctx.restoreGState() - TextDraw.line(caption, font: .systemFont(ofSize: 12), color: .white, x: full.minX + 13, baseline: full.maxY - 14, in: ctx) + TextDraw.line(caption, font: HomeFonts.system(ofSize: 12), color: .white, x: full.minX + 13, baseline: full.maxY - 14, in: ctx) // cmux: HomeFonts (cx-qpqs) } static func drawLocation(_ ctx: CGContext, body: CGRect, title: String, subtitle: String, tail: Bool, outgoing: Bool) { @@ -501,7 +502,7 @@ enum PartRenderer { UIBezierPath(ovalIn: CGRect(x: pin.x - 2, y: pin.y - 2, width: 4, height: 4)).fill() ctx.restoreGState() TextDraw.line(title, font: Sizing.linkTitleFont, color: UIColor(white: 0.93, alpha: 1), x: body.minX + 10, baseline: map.maxY + 18, in: ctx) - TextDraw.line(subtitle, font: .systemFont(ofSize: 10), color: UIColor(white: 0.68, alpha: 1), x: body.minX + 10, baseline: map.maxY + 32, in: ctx) + TextDraw.line(subtitle, font: HomeFonts.system(ofSize: 10), color: UIColor(white: 0.68, alpha: 1), x: body.minX + 10, baseline: map.maxY + 32, in: ctx) // cmux: HomeFonts (cx-qpqs) } /// The person whose tapbacks draw blue (the conversation's own participant). @@ -568,7 +569,7 @@ enum PartRenderer { } static func drawEmoji(_ e: String, in rect: CGRect, ctx: CGContext) { - let f = UIFont.systemFont(ofSize: 15) + let f = HomeFonts.system(ofSize: 15) // cmux: HomeFonts (cx-qpqs) let w = TextDraw.width(e, font: f) TextDraw.line(e, font: f, color: .white, x: rect.midX - w / 2, baseline: rect.midY + 5.5, in: ctx) } @@ -631,7 +632,7 @@ enum TapbackGlyph { let s = img.size img.draw(in: CGRect(x: r.midX - s.width / 2, y: r.midY - s.height / 2, width: s.width, height: s.height)) } else { - let f = UIFont.systemFont(ofSize: r.height * 0.42, weight: .heavy) + let f = HomeFonts.system(ofSize: r.height * 0.42, weight: .heavy) // cmux: HomeFonts (cx-qpqs) let lines = Strings.laughGlyph.components(separatedBy: "\n") for (i, l) in lines.enumerated() { TextDraw.line(l, font: f, color: color, x: r.midX - TextDraw.width(l, font: f) / 2, diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Shapes.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Shapes.swift index f6c2466050d2..dc9cbd6a8b84 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Shapes.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Shapes.swift @@ -130,9 +130,10 @@ enum Glass { let white = UIColor.white let space = CGColorSpace(name: CGColorSpace.sRGB) for (stops, fromTop) in [(rim.top, true), (rim.bottom, false)] { - let span = stops.last!.0 + // cmux: no force unwraps (crash program); an empty rim or a failed gradient draws nothing. + guard let span = stops.last?.0 else { continue } let g = CGGradient(colorsSpace: space, colors: stops.map { white.withAlphaComponent($0.1).cgColor } as CFArray, - locations: stops.map { $0.0 / span })! + locations: stops.map { $0.0 / span }) let y0 = fromTop ? rect.minY : rect.maxY let y1 = fromTop ? rect.minY + span : rect.maxY - span ctx.drawLinearGradient(g, start: CGPoint(x: 0, y: y0), end: CGPoint(x: 0, y: y1), options: []) diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Springs.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Springs.swift index a78e1d135568..4832eb049636 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Springs.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Springs.swift @@ -150,7 +150,7 @@ enum Springs { spring: Spring(duration: duration, bounce: c["bounce"] as? Double ?? 0, initialVelocity: c["initialVelocity"] as? Double ?? 0), delta: c["delta"] as? Double ?? 0, - curve: cp?.count == 4 ? Curve(x1: cp![0], y1: cp![1], x2: cp![2], y2: cp![3], duration: duration) : nil) + curve: cp.flatMap { $0.count == 4 ? Curve(x1: $0[0], y1: $0[1], x2: $0[2], y2: $0[3], duration: duration) : nil }) // cmux: no force unwrap } out[name] = SpringElement(name: name, from: e["from"] as? Double ?? 0, to: e["to"] as? Double ?? 0, components: comps) } @@ -487,7 +487,7 @@ enum Presenter { tau = 0 } let total = k.duration * Double(max(1, k.repeatCount)) - if k.repeatCount < .infinity, tau >= total { return k.isRemovedOnCompletion ? nil : (kp, values.last!.doubleValue) } + if k.repeatCount < .infinity, tau >= total { return k.isRemovedOnCompletion ? nil : values.last.map { (kp, $0.doubleValue) } } // cmux: no force unwrap // Wrap only repeating animations (a one-shot at exactly its end // must not wrap to its first value). if k.repeatCount > 1 { tau = tau.truncatingRemainder(dividingBy: k.duration) } diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Transcript.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Transcript.swift index 13dfff00ca48..890739264f70 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Transcript.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/Transcript.swift @@ -519,7 +519,7 @@ final class RowCell: UICollectionViewCell { deinit { RowCell.destroyed += 1 if ProcessInfo.processInfo.environment["ML_CELLS"] != nil, RowCell.destroyed % 500 == 7 { - FileHandle.standardError.write(("deinit stack:\n" + Thread.callStackSymbols.prefix(14).joined(separator: "\n") + "\n").data(using: .utf8)!) + FileHandle.standardError.write(Data(("deinit stack:\n" + Thread.callStackSymbols.prefix(14).joined(separator: "\n") + "\n").utf8)) // cmux: no force unwrap } } diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/WindowView.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/WindowView.swift index 4196b8c10ed2..c2010fc09588 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/WindowView.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabHome/Vendor/catalyst/WindowView.swift @@ -414,7 +414,7 @@ final class MessagesWindowView: UIView, UICollectionViewDataSource, UICollection MessagesWindowView.createdInCommits += RowCell.created - created0 MessagesWindowView.destroyedInCommits += RowCell.destroyed - destroyed0 if MessagesWindowView.logCells, RowCell.destroyed - destroyed0 > 0 { - FileHandle.standardError.write("commit \(String(describing: action).prefix(30)) destroyed \(RowCell.destroyed - destroyed0)\n".data(using: .utf8)!) + FileHandle.standardError.write(Data("commit \(String(describing: action).prefix(30)) destroyed \(RowCell.destroyed - destroyed0)\n".utf8)) // cmux: no force unwrap } } let t0 = CACurrentMediaTime() @@ -767,7 +767,8 @@ final class MessagesWindowView: UIView, UICollectionViewDataSource, UICollection for i in band { let key = model.rows[i].spec.key let newWin = layout.contentTop(i) - newOffset - if let ot = oldSnap.contentTop(key), oldSnap.row(oldSnap.index(key)!).ghost == model.rows[i].ghost || model.rows[i].ghost { + // cmux: no force unwrap; contentTop(key) found the key, so index(key) does too. + if let ot = oldSnap.contentTop(key), let oi = oldSnap.index(key), oldSnap.row(oi).ghost == model.rows[i].ghost || model.rows[i].ghost { let d = (ot + oldRowsTop - oldOffset) - newWin deltas[key] = d for j in pendingNew { deltas[model.rows[j].spec.key] = d } diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabSidebar/Cmux/SidebarCrashSafe.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabSidebar/Cmux/SidebarCrashSafe.swift new file mode 100644 index 000000000000..edbd17c1f50c --- /dev/null +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabSidebar/Cmux/SidebarCrashSafe.swift @@ -0,0 +1,14 @@ +import AppKit +import CoreText + +// cmux (crash program, plans/cmux-next/crash-elimination.md): constructors the vendored +// sidebar force-unwrapped (gradients; fonts are SidebarDraw.uiFont). Each returns a working value or a stated fallback instead of +// trapping; Tests/MessagesLabSidebarTests/SidebarCrashSafeTests pins that the literals resolve. + +extension CGContext { + /// Draws `gradient`, or nothing when it could not be built. + func drawLinearGradient(_ gradient: CGGradient?, start: CGPoint, end: CGPoint, options: CGGradientDrawingOptions) { + guard let gradient else { return } + drawLinearGradient(gradient, start: start, end: end, options: options) + } +} diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabSidebar/Vendor/appkit-native/SidebarDrawing.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabSidebar/Vendor/appkit-native/SidebarDrawing.swift index 3d93acda2cd4..07cc276c64b4 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabSidebar/Vendor/appkit-native/SidebarDrawing.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabSidebar/Vendor/appkit-native/SidebarDrawing.swift @@ -1,3 +1,4 @@ +import os // cmux: OSAllocatedUnfairLock for the monogram font cache import AppKit import CoreText @@ -94,7 +95,7 @@ final class SidebarAvatarCache { /// The drawing: pure functions of a summary and a render context (any thread). enum SidebarDraw { - static let p3 = CGColorSpace(name: CGColorSpace.displayP3)! + static let p3 = CGColorSpace(name: CGColorSpace.displayP3) ?? CGColorSpaceCreateDeviceRGB() // cmux: no force unwrap /// Where `AvatarSpec.image` paths resolve (the host sets it; default: the app bundle's /// "assets" folder). static var assetDirectory: URL? = Bundle.main.resourceURL?.appendingPathComponent("assets") @@ -104,11 +105,31 @@ enum SidebarDraw { guard !images.isEmpty else { return } DispatchQueue.main.async { DispatchQueue.global(qos: .utility).async { withExtendedLifetime(images) {} } } } - static let nameFont = CTFontCreateUIFontForLanguage(.emphasizedSystem, SidebarMetrics.nameSize, nil)! - static let previewFont = CTFontCreateUIFontForLanguage(.system, SidebarMetrics.previewSize, nil)! - static let timeFont = CTFontCreateUIFontForLanguage(.system, SidebarMetrics.timeSize, nil)! - static let pinNameFont = CTFontCreateUIFontForLanguage(.system, SidebarMetrics.pinNameSize, nil)! - static let bubbleFont = CTFontCreateUIFontForLanguage(.system, 11, nil)! + // cmux: no force unwrap: Core Text's UI font lookup returns an optional (crash program, cx-qpqs class). + static let nameFont = uiFont(.emphasizedSystem, SidebarMetrics.nameSize) + static let previewFont = uiFont(.system, SidebarMetrics.previewSize) + static let timeFont = uiFont(.system, SidebarMetrics.timeSize) + static let pinNameFont = uiFont(.system, SidebarMetrics.pinNameSize) + static let bubbleFont = uiFont(.system, 11) + + // cmux: the UI font, or Helvetica at that size when Core Text returns none. + static func uiFont(_ type: CTFontUIFontType, _ size: CGFloat) -> CTFont { + CTFontCreateUIFontForLanguage(type, size, nil) ?? CTFontCreateWithName("Helvetica" as CFString, size, nil) + } + + // cmux: monogram fonts held per half point for the process: avatars draw on + // concurrentPerform threads, and a font made and dropped per draw can come + // back nil there (cx-qpqs). + private static let monogramFonts = OSAllocatedUnfairLock<[CGFloat: CTFont]>(initialState: [:]) + static func monogramFont(_ size: CGFloat) -> CTFont { + let key = (size * 2).rounded() / 2 + return monogramFonts.withLock { fonts in + if let held = fonts[key] { return held } + let font = uiFont(.emphasizedSystem, key) + fonts[key] = font + return font + } + } /// A flipped (top-left origin) bitmap in the context's color space at its scale. static func bitmap(size: CGSize, ctx: SidebarRenderContext, _ draw: (CGContext) -> Void) -> CGImage { @@ -170,10 +191,11 @@ enum SidebarDraw { case let .monogram(m): g.saveGState() g.addEllipse(in: r); g.clip() - let grad = CGGradient(colorsSpace: nil, colors: [p.monogramTop, p.monogramBottom] as CFArray, locations: [0, 1])! + // cmux: an optional gradient draws nothing when it fails (SidebarCrashSafe). + let grad = CGGradient(colorsSpace: nil, colors: [p.monogramTop, p.monogramBottom] as CFArray, locations: [0, 1]) g.drawLinearGradient(grad, start: CGPoint(x: r.midX, y: r.minY), end: CGPoint(x: r.midX, y: r.maxY), options: []) g.restoreGState() - let font = CTFontCreateUIFontForLanguage(.emphasizedSystem, (r.width * 0.42).rounded(), nil)! + let font = monogramFont((r.width * 0.42).rounded()) // cmux: held, no force unwrap (cx-qpqs) let white = CGColor(gray: 1, alpha: 1) let l = line(m.uppercased(), font, white) let lw = width(l) @@ -230,7 +252,7 @@ enum SidebarDraw { /// the visible rows' text at the exact width in every frame. static func rowTime(_ c: ConversationSummary, emphasized: Bool, ctx: SidebarRenderContext, time: ConversationTimeFormatter) -> CGImage { let p = ctx.palette - let secondary = emphasized ? p.selectedText.copy(alpha: 0.82)! : p.secondary + let secondary = emphasized ? p.selectedText.copy(alpha: 0.82) ?? p.selectedText : p.secondary // cmux: no force unwrap // `.distantPast`: a row without a time (the host's extra search results). let tl = line(c.lastAt == .distantPast ? "" : time.string(c.lastAt, now: ctx.now), timeFont, secondary) let bell = c.muted ? (emphasized ? ctx.bellSelected : ctx.bellSecondary) : nil @@ -295,7 +317,7 @@ enum SidebarDraw { /// The title of the host's extra search section: 11 pt semibold, secondary, at the row /// text's x, baseline 20 pt in a 28 pt band (to verify against Messages' search sections). static func sectionHeader(_ title: String, width: CGFloat, ctx: SidebarRenderContext) -> CGImage { - let font = CTFontCreateUIFontForLanguage(.emphasizedSystem, 11, nil)! + let font = uiFont(.emphasizedSystem, 11) // cmux: no force unwrap (cx-qpqs) let l = truncated(line(title, font, ctx.palette.secondary), width - 2 * SidebarMetrics.selectionInsetX - 10, font, ctx.palette.secondary) return bitmap(size: CGSize(width: max(1, width), height: 28), ctx: ctx) { g in draw(l, x: SidebarMetrics.selectionInsetX + 10, baseline: 20, g) @@ -469,7 +491,7 @@ final class SidebarTextCache { if let m = map[k] { lock.unlock(); return m } lock.unlock() let nameColor = emphasized ? p.selectedText : p.name - let secondary = emphasized ? p.selectedText.copy(alpha: 0.82)! : p.secondary + let secondary = emphasized ? p.selectedText.copy(alpha: 0.82) ?? p.selectedText : p.secondary // cmux: no force unwrap let text = (c.lastReaction.map(SidebarStrings.reaction) ?? c.preview).replacingOccurrences(of: "\n", with: " ") let attr = NSAttributedString(string: text, attributes: [ NSAttributedString.Key(kCTFontAttributeName as String): SidebarDraw.previewFont, diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabSidebar/Vendor/appkit-native/SidebarModel.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabSidebar/Vendor/appkit-native/SidebarModel.swift index 6acd74f8dafd..bf9a1c8ef9cc 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabSidebar/Vendor/appkit-native/SidebarModel.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabSidebar/Vendor/appkit-native/SidebarModel.swift @@ -301,13 +301,16 @@ struct SidebarPalette: Equatable { /// taken only as a CGColor resolved in `appearance` (no component of an NSColor is read, so /// catalog, pattern and gray colors are safe). static func resolve(_ appearance: NSAppearance, unreadColor: NSColor? = nil, selectionColor: NSColor? = nil) -> SidebarPalette { - var p: SidebarPalette! - appearance.performAsCurrentDrawingAppearance { + // cmux: no IUO (crash program). The block runs synchronously, so `palette` is set; + // without it the palette resolves in the current appearance. + var palette: SidebarPalette? + func build() -> SidebarPalette { let dark = appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua func p3(_ r: CGFloat, _ g: CGFloat, _ b: CGFloat, _ a: CGFloat = 1) -> CGColor { - CGColor(colorSpace: SidebarDraw.p3, components: [r / 255, g / 255, b / 255, a])! + CGColor(colorSpace: SidebarDraw.p3, components: [r / 255, g / 255, b / 255, a]) + ?? CGColor(red: r / 255, green: g / 255, blue: b / 255, alpha: a) // cmux: no force unwrap } - p = SidebarPalette( + return SidebarPalette( dark: dark, name: NSColor.labelColor.cgColor, secondary: NSColor.secondaryLabelColor.cgColor, @@ -328,6 +331,7 @@ struct SidebarPalette: Equatable { bubbleText: dark ? p3(255, 255, 255) : p3(0, 0, 0), typingDot: dark ? p3(150, 150, 154) : p3(142, 142, 147)) } - return p + appearance.performAsCurrentDrawingAppearance { palette = build() } + return palette ?? build() } } diff --git a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabSidebar/Vendor/appkit-native/SidebarView.swift b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabSidebar/Vendor/appkit-native/SidebarView.swift index efe04f6d4435..92a95ae20bf6 100644 --- a/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabSidebar/Vendor/appkit-native/SidebarView.swift +++ b/Packages/Shared/CmuxMessagesLab/Sources/MessagesLabSidebar/Vendor/appkit-native/SidebarView.swift @@ -70,7 +70,7 @@ final class SidebarController: NSViewController, NSSearchFieldDelegate, NSMenuDe /// width it is designed for (to verify against Messages' default). var minimumWidth: CGFloat { SidebarMetrics.minimumWidth } var preferredWidth: CGFloat? { SidebarMetrics.preferredWidth } - private var palette = SidebarPalette.resolve(NSAppearance(named: .darkAqua)!) + private var palette = SidebarPalette.resolve(NSAppearance(named: .darkAqua) ?? NSAppearance.currentDrawing()) // cmux: no force unwrap private var generation = 0 private var scale: CGFloat { document.window?.backingScaleFactor ?? 2 } private let cache = SidebarBitmapCache() @@ -922,7 +922,7 @@ final class SidebarController: NSViewController, NSSearchFieldDelegate, NSMenuDe case #selector(NSResponder.moveDown(_:)): moveSelection(1); return true case #selector(NSResponder.moveUp(_:)): moveSelection(-1); return true case #selector(NSResponder.insertNewline(_:)): - if highlightID == nil || position(of: highlightID!) == nil { moveSelection(1) } + if highlightID.map({ position(of: $0) == nil }) ?? true { moveSelection(1) } // cmux: no force unwrap view.window?.makeFirstResponder(document) return true case #selector(NSResponder.cancelOperation(_:)): diff --git a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/AttachmentProjectionTests.swift b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/AttachmentProjectionTests.swift index 3dc438b58041..c67d6b08f811 100644 --- a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/AttachmentProjectionTests.swift +++ b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/AttachmentProjectionTests.swift @@ -53,27 +53,27 @@ import UniformTypeIdentifiers defer { p.stop() } let photo = try await store.prepareAttachment(fileURL: try Self.png("photo.png")) await p.addDraft(photo) - let chip = try #require(c.store.state.ui.draft.attachments.first) + let chip = try #require(c.store!.state.ui.draft.attachments.first) #expect(chip.id == photo.ref.hash) #expect(chip.kind == "image") #expect(chip.asset != nil, "the picture is made before the chip shows, so the bubble has it from the first frame") - #expect(c.demo.compose.chips.map(\.id) == [photo.ref.hash], "MessagesLab's compose chips") + #expect(c.demo!.compose.chips.map(\.id) == [photo.ref.hash], "MessagesLab's compose chips") c.dispatch(.setDraft("Here")) - let before = c.store.state.conversation.messages.count + let before = c.store!.state.conversation.messages.count p.send() - let local = try #require(c.store.state.conversation.messages.last) - #expect(c.store.state.conversation.messages.count == before + 1) + let local = try #require(c.store!.state.conversation.messages.last) + #expect(c.store!.state.conversation.messages.count == before + 1) guard case .attachment(let a)? = local.parts.first else { Issue.record("attachment first: \(local.parts)"); return } #expect(a.id == photo.ref.hash) #expect(local.parts.last?.plainText == "Here") - #expect(c.store.state.ui.draft.attachments.isEmpty && c.store.state.ui.draft.text.isEmpty) + #expect(c.store!.state.ui.draft.attachments.isEmpty && c.store!.state.ui.draft.text.isEmpty) let key = try #require(p.aliases.first { $0.value == local.id }?.key) await waitUntil { store.transcript(for: id).contains { $0.key == key && $0.seq != nil } } let item = try #require(store.transcript(for: id).first { $0.key == key }) #expect(item.attachmentHashes == [photo.ref.hash] && item.parts.count == 2 && item.parts.last == .text("Here"), "one message: the attachment, then the text") await waitUntil { p.shown.contains { $0.key == key && $0.seq != nil } } - #expect(c.store.state.conversation.messages.filter { $0.id == local.id }.count == 1, "the echo only changes the status") + #expect(c.store!.state.conversation.messages.filter { $0.id == local.id }.count == 1, "the echo only changes the status") } @Test func aBubbleGetsItsPictureFromTheStoreWithoutAReflow() async throws { @@ -88,12 +88,12 @@ import UniformTypeIdentifiers let incoming = TranscriptItem(key: IdempotencyKey("img"), seq: 4, author: them, parts: [.attachment(ref)], createdAt: Fixture2.start.addingTimeInterval(200), delivery: .committed, messageID: MessageID("m4")) p.apply(items: Fixture2.history(3) + [incoming], summary: Fixture2.summary(lastSeq: 4), typing: [], hasOlder: false) - let row0 = try #require(c.demo.model.rows.first { RowBuilder.owner($0.spec.key) == "img" }) + let row0 = try #require(c.demo!.model.rows.first { RowBuilder.owner($0.spec.key) == "img" }) await p.media.settled() await waitUntil { p.media.asset("h-remote") != nil } - guard case .attachment(let a)? = c.store.state.message("img")?.parts.first else { Issue.record("no attachment"); return } + guard case .attachment(let a)? = c.store!.state.message("img")?.parts.first else { Issue.record("no attachment"); return } #expect(a.asset != nil, "the picture reached MessagesLab's part") - let row1 = try #require(c.demo.model.rows.first { RowBuilder.owner($0.spec.key) == "img" }) + let row1 = try #require(c.demo!.model.rows.first { RowBuilder.owner($0.spec.key) == "img" }) #expect(row0.spec.height == row1.spec.height && row0.spec.gap == row1.spec.gap, "no reflow when the bytes arrive") #expect(await asked.values == ["h-remote thumbnail(maxPixel: 1024)"], "an image asks for a thumbnail, once") } @@ -112,7 +112,7 @@ import UniformTypeIdentifiers createdAt: Fixture2.start.addingTimeInterval(200), delivery: .committed, messageID: MessageID("m4")) p.apply(items: Fixture2.history(3) + [item], summary: Fixture2.summary(lastSeq: 4), typing: [], hasOlder: false) await waitUntil { p.media.asset("h-video") != nil } - guard case .attachment(let a)? = c.store.state.message("vid")?.parts.first else { Issue.record("no attachment"); return } + guard case .attachment(let a)? = c.store!.state.message("vid")?.parts.first else { Issue.record("no attachment"); return } #expect(a.kind == "video" && a.poster != nil && a.asset == nil, "MessagesLab draws poster ?? asset: the poster, never the movie") #expect(a.durationSeconds == 2) #expect(await asked.values == ["poster"]) @@ -127,7 +127,7 @@ import UniformTypeIdentifiers let waiting = TranscriptItem(key: IdempotencyKey("wait"), seq: nil, author: me, parts: [.text("queued")], createdAt: Fixture2.start.addingTimeInterval(301), delivery: .sending) p.apply(items: Fixture2.history(2) + [uploading, waiting], summary: Fixture2.summary(lastSeq: 2), typing: [], hasOlder: false) - guard case .attachment(let a)? = c.store.state.message("up")?.parts.first, case .uploading(let shown) = a.transfer else { + guard case .attachment(let a)? = c.store!.state.message("up")?.parts.first, case .uploading(let shown) = a.transfer else { Issue.record("a file row shows MessagesLab's upload bar"); return } #expect(shown == 0.42, "2% steps") @@ -141,7 +141,7 @@ import UniformTypeIdentifiers uploading.attachmentProgress = [:] uploading.delivery = .notDelivered(.ownerUnreachable) p.apply(items: Fixture2.history(2) + [uploading, waiting], summary: Fixture2.summary(lastSeq: 2), typing: [], hasOlder: false) - guard case .attachment(let done)? = c.store.state.message("up")?.parts.first else { Issue.record("no attachment"); return } + guard case .attachment(let done)? = c.store!.state.message("up")?.parts.first else { Issue.record("no attachment"); return } #expect(done.transfer == .done) #expect(p.canCancelSend("up"), "a failed send can be cancelled") } @@ -158,14 +158,14 @@ import UniformTypeIdentifiers fileURL: try Self.png("huge.png", width: 10, height: 10)) await p.addDraft(big) c.dispatch(.setDraft("Too big")) - let before = c.store.state.conversation.messages.count + let before = c.store!.state.conversation.messages.count p.send() await waitUntil { !refusals.isEmpty } #expect(refusals.count == 1) if case .tooLarge? = refusals.first {} else { Issue.record("tooLarge, got \(refusals)") } - #expect(c.store.state.conversation.messages.count == before, "the local message goes") - #expect(c.store.state.ui.draft.text == "Too big") - #expect(c.store.state.ui.draft.attachments.map(\.id) == ["h-big"], "the chip is back") + #expect(c.store!.state.conversation.messages.count == before, "the local message goes") + #expect(c.store!.state.ui.draft.text == "Too big") + #expect(c.store!.state.ui.draft.attachments.map(\.id) == ["h-big"], "the chip is back") #expect(p.draftAttachments.map(\.ref.hash) == ["h-big"]) } } diff --git a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/ChatControllerBeforeInstallTests.swift b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/ChatControllerBeforeInstallTests.swift new file mode 100644 index 000000000000..b79135dda282 --- /dev/null +++ b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/ChatControllerBeforeInstallTests.swift @@ -0,0 +1,15 @@ +import AppKit +import Testing +@testable import MessagesLabHome + +/// Crash program (plans/cmux-next/crash-elimination.md): the pane controller's store and +/// window view were implicitly unwrapped and trapped when read before `install`. Read +/// early, they are nil, and the controller's queries answer as for an empty pane. +@MainActor @Suite struct ChatControllerBeforeInstallTests { + @Test func storeAndWindowViewReadBeforeInstallAreEmpty() { + let controller = ChatController(host: HostView(frame: NSRect(x: 0, y: 0, width: 628, height: 900)), wake: NoWake()) + #expect(controller.store == nil) + #expect(controller.demo == nil) + #expect(controller.isIdle) + } +} diff --git a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/CrashSafeGraphicsTests.swift b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/CrashSafeGraphicsTests.swift new file mode 100644 index 000000000000..31e6b9e67449 --- /dev/null +++ b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/CrashSafeGraphicsTests.swift @@ -0,0 +1,28 @@ +import AppKit +import Testing +@testable import MessagesLabHome + +/// Crash program: the literals MessagesLab used to force-unwrap now go through non-trapping +/// constructors (CrashSafeGraphics). These pin that every literal still resolves, so the +/// fallbacks never run. +@Suite struct CrashSafeGraphicsTests { + @Test func namedColorSpacesResolve() { + #expect(CGColorSpace(name: CGColorSpace.sRGB) != nil) + #expect(CGColorSpace(name: CGColorSpace.displayP3) != nil) + #expect(LabColorSpace.displayP3.name == CGColorSpace.displayP3) + } + + @Test func systemUIFontsResolve() { + #expect(CTFontCreateUIFontForLanguage(.system, 13, nil) != nil) + #expect(CTFontCreateUIFontForLanguage(.emphasizedSystem, 11, nil) != nil) + #expect(CTFontGetSize(labUIFont(.system, 13)) == 13) + } + + @Test func linkDetectorsAndMetaPatternsCompile() { + #expect(TextParts.detector != nil) + #expect(BlockLayout.detector != nil) + #expect(TextParts.linkRuns("see https://cmux.com now").count == 1) + let tags = LinkPreviews.metaTags(#""#) + #expect(tags["og:title"] == "cmux") + } +} diff --git a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/FailedReceiptTests.swift b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/FailedReceiptTests.swift index c5762c41f521..70d4ce263be6 100644 --- a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/FailedReceiptTests.swift +++ b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/FailedReceiptTests.swift @@ -19,7 +19,7 @@ import Testing unanswered.mayHaveBeenDelivered = true p.apply(items: Fixture2.history(3) + [refused, unanswered], summary: Fixture2.summary(lastSeq: 3), typing: [], hasOlder: false) func label(_ key: String) -> String? { - guard let row = c.demo.model.rows.first(where: { $0.spec.key == "failed:\(key)" }), + guard let row = c.demo!.model.rows.first(where: { $0.spec.key == "failed:\(key)" }), case let .label(text, outgoing, color) = row.spec.kind, outgoing, color == .failure else { return nil } return text } @@ -34,7 +34,7 @@ import Testing p.apply(items: Fixture2.history(2) + [item], summary: Fixture2.summary(lastSeq: 2), typing: [], hasOlder: false) item.mayHaveBeenDelivered = true p.apply(items: Fixture2.history(2) + [item], summary: Fixture2.summary(lastSeq: 2), typing: [], hasOlder: false) - let row = c.demo.model.rows.first { $0.spec.key == "failed:send" } + let row = c.demo!.model.rows.first { $0.spec.key == "failed:send" } guard case let .label(text, _, _)? = row?.spec.kind else { Issue.record("no failed label"); return } #expect(text == "May Not Have Been Delivered") } diff --git a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/FlightRecorderTests.swift b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/FlightRecorderTests.swift index 761c1f44e30b..cba96a765606 100644 --- a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/FlightRecorderTests.swift +++ b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/FlightRecorderTests.swift @@ -41,10 +41,10 @@ import Testing let (window, _, c) = pane() defer { window.close() } c.host.layoutSubtreeIfNeeded() - c.demo.layoutIfNeeded() - c.demo.collection.layoutIfNeeded() - #expect(!c.demo.collection.visibleCells.isEmpty) - #expect(HomeFlightRecorder.coverageGaps(c.demo).isEmpty, "\(HomeFlightRecorder.coverageGaps(c.demo))") + c.demo!.layoutIfNeeded() + c.demo!.collection.layoutIfNeeded() + #expect(!c.demo!.collection.visibleCells.isEmpty) + #expect(HomeFlightRecorder.coverageGaps(c.demo!).isEmpty, "\(HomeFlightRecorder.coverageGaps(c.demo!))") } @Test func saveLastSecondsWritesTheRingUnderTheAppsLogFolder() throws { diff --git a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/HomeBehaviorPinTests.swift b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/HomeBehaviorPinTests.swift index f5c5cd972ea5..8d51002048ce 100644 --- a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/HomeBehaviorPinTests.swift +++ b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/HomeBehaviorPinTests.swift @@ -11,13 +11,13 @@ import Testing private func pane(_ items: [TranscriptItem]) -> ChatController { let (p, c) = Fixture2.projection() p.apply(items: items, summary: Fixture2.summary(lastSeq: Seq(items.count)), typing: [], hasOlder: false) - c.host.layoutSubtreeIfNeeded(); c.demo.layoutIfNeeded(); c.demo.collection.layoutIfNeeded() + c.host.layoutSubtreeIfNeeded(); c.demo!.layoutIfNeeded(); c.demo!.collection.layoutIfNeeded() return c } /// The text each part row shows, in transcript order. private func shown(_ c: ChatController) -> [String] { - c.demo.model.rows.compactMap { + c.demo!.model.rows.compactMap { guard case let .part(row) = $0.spec.kind else { return nil } return row.markdown?.plain ?? row.text?.text } @@ -58,7 +58,7 @@ import Testing @Test func aDragAcrossTwoMessagesCopiesBothTexts() throws { let c = pane([Fixture2.item(1, Fixture2.them, "First reply here"), Fixture2.item(2, Fixture2.me, "Second one mine")]) - let a = try #require(c.demo.lastTextRow(mine: false)), b = try #require(c.demo.lastTextRow(mine: true)) + let a = try #require(c.demo!.lastTextRow(mine: false)), b = try #require(c.demo!.lastTextRow(mine: true)) let from = CGPoint(x: a.body.minX + Fixture.bubblePadX + 1, y: a.body.minY + Fixture.bubblePadY + Fixture.lineHeight / 2) let to = CGPoint(x: b.body.maxX - Fixture.bubblePadX - 1, y: b.body.minY + Fixture.bubblePadY + Fixture.lineHeight / 2) c.mouseDown(at: from, event(.leftMouseDown)) @@ -70,7 +70,7 @@ import Testing @Test func aDoubleClickSelectsTheWord() throws { let c = pane([Fixture2.item(1, Fixture2.them, "alpha bravo charlie")]) - let a = try #require(c.demo.lastTextRow(mine: false)) + let a = try #require(c.demo!.lastTextRow(mine: false)) let tl = try #require(a.row.text) let x = CTLineGetOffsetForStringIndex(CTLineCreateWithAttributedString(tl.attributed(color: .white, linkColor: .white)), 8, nil) c.doubleClicked(CGPoint(x: a.body.minX + Fixture.bubblePadX + x, y: a.body.minY + Fixture.bubblePadY + Fixture.lineHeight / 2)) diff --git a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/HomeFontsTests.swift b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/HomeFontsTests.swift new file mode 100644 index 000000000000..efef8012ff77 --- /dev/null +++ b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/HomeFontsTests.swift @@ -0,0 +1,44 @@ +import AppKit +import Dispatch +import Testing +@testable import MessagesLabHome + +/// Crash program class (cx-qpqs): AppKit font factories annotated nonnull +/// return nil when threads make and drop the last instance at once, and the +/// row renderers run on several threads. HomeFonts holds one font per size +/// and weight for the process; a Markdown run's bold or italic face is held +/// too, and a run with no such face gets no font attribute (never a nil). +@Suite struct HomeFontsTests { + @Test func aSystemFontIsHeldOncePerSizeAndWeight() { + let a = HomeFonts.system(ofSize: 10, weight: .semibold) + let b = HomeFonts.system(ofSize: 10, weight: .semibold) + #expect(a === b) + #expect(a.pointSize == 10) + #expect(HomeFonts.system(ofSize: 10) !== a) + // A size computed from a frame lands on the half point. + #expect(HomeFonts.system(ofSize: 10.2, weight: .heavy) === HomeFonts.system(ofSize: 10.1, weight: .heavy)) + #expect(HomeFonts.monospaced(ofSize: 12).isFixedPitch) + } + + @Test func boldAndItalicRunsDrawTheirFaceOnManyRenderThreadsAtOnce() throws { + let (shown, runs) = HomeMarkdown.render("Run **bold** and *slanted* now") + let tl = TextLayout(text: shown, runs: runs, lines: [], width: 0) + let bold = try #require(tl.runs.first { $0.style?.contains("bold") == true }) + let italic = try #require(tl.runs.first { $0.style?.contains("italic") == true }) + let lock = NSLock() + var wrong = 0 + DispatchQueue.concurrentPerform(iterations: 8) { _ in + for _ in 0..<20000 { + autoreleasepool { + let text = tl.attributed(color: .white, linkColor: .white) + let b = text.attribute(.font, at: bold.start, effectiveRange: nil) as? NSFont + let i = text.attribute(.font, at: italic.start, effectiveRange: nil) as? NSFont + let ok = b?.fontDescriptor.symbolicTraits.contains(.bold) == true + && i?.fontDescriptor.symbolicTraits.contains(.italic) == true + if !ok { lock.lock(); wrong += 1; lock.unlock() } + } + } + } + #expect(wrong == 0) + } +} diff --git a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/HomeProjectionTests.swift b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/HomeProjectionTests.swift index 983a53943e96..8d51f7d472bf 100644 --- a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/HomeProjectionTests.swift +++ b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/HomeProjectionTests.swift @@ -12,12 +12,12 @@ import Testing let (p, c) = Fixture2.projection() let items = Fixture2.history(20) p.apply(items: items, summary: Fixture2.summary(lastSeq: 20), typing: [], hasOlder: false) - #expect(c.store.state.conversation.messages.count == 20) + #expect(c.store!.state.conversation.messages.count == 20) p.apply(items: items, summary: Fixture2.summary(lastSeq: 20), typing: [], hasOlder: false) #expect(p.appliedUpdates == 0) p.apply(items: items + [Fixture2.item(21, them, "New")], summary: Fixture2.summary(lastSeq: 21), typing: [], hasOlder: false) #expect(p.appliedUpdates == 1) - #expect(c.store.state.conversation.messages.last?.id == "k21") + #expect(c.store!.state.conversation.messages.last?.id == "k21") } @Test func typingShowsMessagesLabsIndicator() { @@ -25,10 +25,10 @@ import Testing let items = Fixture2.history(5) p.apply(items: items, summary: Fixture2.summary(lastSeq: 5), typing: [], hasOlder: false) p.apply(items: items, summary: Fixture2.summary(lastSeq: 5), typing: [them], hasOlder: false) - #expect(c.store.state.ui.typing == ["agent_chief"]) - #expect(c.demo.model.rows.last?.spec.key == "typing") + #expect(c.store!.state.ui.typing == ["agent_chief"]) + #expect(c.demo!.model.rows.last?.spec.key == "typing") p.apply(items: items + [Fixture2.item(6, them, "Done")], summary: Fixture2.summary(lastSeq: 6), typing: [], hasOlder: false) - #expect(c.store.state.ui.typing.isEmpty) + #expect(c.store!.state.ui.typing.isEmpty) } /// A host notice (Home's "quit older builds to merge Chief history") is a @@ -40,7 +40,7 @@ import Testing p.apply(items: items, summary: Fixture2.summary(lastSeq: 3), typing: [], hasOlder: false) let text = "Quit older cmux DEV builds to merge Chief history" p.notice = text - let row = try #require(c.demo.model.rows.last, "a row under the newest message") + let row = try #require(c.demo!.model.rows.last, "a row under the newest message") #expect(row.spec.key == "notice") guard case let .separator(bold, rest) = row.spec.kind else { Issue.record("the notice is MessagesLab's system row, not \(row.spec.kind)") @@ -49,10 +49,10 @@ import Testing #expect(bold.isEmpty && rest == text) // A new message keeps the notice at the end; clearing it removes the row. p.apply(items: items + [Fixture2.item(4, them, "Later")], summary: Fixture2.summary(lastSeq: 4), typing: [], hasOlder: false) - #expect(c.demo.model.rows.last?.spec.key == "notice") + #expect(c.demo!.model.rows.last?.spec.key == "notice") // A removed row may stay a moment as a leaving (ghost) row; the live rows lose it. p.notice = nil - #expect(!c.demo.model.rows.contains { !$0.ghost && $0.spec.key == "notice" }) + #expect(!c.demo!.model.rows.contains { !$0.ghost && $0.spec.key == "notice" }) } private func onlineStore(_ items: [CmuxHomeCore.Message] = []) async -> (HomeStore, ScriptedSource) { @@ -68,14 +68,14 @@ import Testing let (store, source) = await onlineStore((1...4).map { Fixture2.message(Seq($0), $0 % 2 == 0 ? me : them, "Line \($0)") }) let (p, c) = Fixture2.projection(store: store) p.start() - #expect(c.store.state.conversation.messages.count == 4) + #expect(c.store!.state.conversation.messages.count == 4) c.dispatch(.setDraft("Hello there")) p.send() - let local = try #require(c.store.state.conversation.messages.last) + let local = try #require(c.store!.state.conversation.messages.last) #expect(local.parts.first?.plainText == "Hello there") #expect(local.status == .sending) - #expect(c.demo.morphs.count == 1, "MessagesLab's send morph") - #expect(c.store.state.ui.draft.text.isEmpty) + #expect(c.demo!.morphs.count == 1, "MessagesLab's send morph") + #expect(c.store!.state.ui.draft.text.isEmpty) let key = try #require(p.aliases.first(where: { $0.value == local.id })?.key) await waitUntil { store.transcript(for: Fixture2.id).contains { $0.key == key } } let sent = await source.submitted @@ -84,13 +84,13 @@ import Testing #expect(sent.first?.op == .sendMessage(conversation: Fixture2.id, parts: [.text("Hello there")])) // The pending item and the owner's echo only move the local message's status. await waitUntil { p.shown.contains { $0.key == key } } - #expect(c.store.state.conversation.messages.filter { $0.parts.first?.plainText == "Hello there" }.count == 1) + #expect(c.store!.state.conversation.messages.filter { $0.parts.first?.plainText == "Hello there" }.count == 1) await source.publish(.message(Fixture2.message(5, me, "Hello there", key: key.rawValue), rev: 11)) await waitUntil { p.shown.last?.seq == 5 } - if case .delivered = c.store.state.conversation.messages.last?.status {} else { - Issue.record("committed echo shows Delivered, got \(String(describing: c.store.state.conversation.messages.last?.status))") + if case .delivered = c.store!.state.conversation.messages.last?.status {} else { + Issue.record("committed echo shows Delivered, got \(String(describing: c.store!.state.conversation.messages.last?.status))") } - #expect(c.store.state.conversation.messages.last?.id == local.id, "no remove and insert") + #expect(c.store!.state.conversation.messages.last?.id == local.id, "no remove and insert") p.stop() store.stop() } @@ -100,8 +100,8 @@ import Testing p.apply(items: Fixture2.history(3), summary: Fixture2.summary(lastSeq: 3), typing: [], hasOlder: false) c.dispatch(.setDraft("Not yet")) p.send() - #expect(c.store.state.ui.draft.text == "Not yet") - #expect(c.store.state.conversation.messages.count == 3) + #expect(c.store!.state.ui.draft.text == "Not yet") + #expect(c.store!.state.conversation.messages.count == 3) } @Test func aSendRefusedBeforeTheLogReturnsItsText() { @@ -111,12 +111,12 @@ import Testing // logging it (it never reached HomeStore's transcript). c.dispatch(.setDraft("Refused")) c.dispatch(.send) - let local = c.store.state.conversation.messages.last!.id + let local = c.store!.state.conversation.messages.last!.id let key = IdempotencyKey("cmk_never_logged") p.rememberAlias(key, local) p.sendRefused(key, text: "Refused", .ownerUnreachable) - #expect(!c.store.state.conversation.messages.contains { $0.id == local }) - #expect(c.store.state.ui.draft.text == "Refused") + #expect(!c.store!.state.conversation.messages.contains { $0.id == local }) + #expect(c.store!.state.ui.draft.text == "Refused") #expect(p.aliases[key] == nil) } @@ -145,7 +145,7 @@ import Testing let demo = try #require(c.demo) demo.collection.contentOffset.y = demo.pinnedOffset - 900 demo.userScrolled() - #expect(!c.store.state.ui.scroll.pinnedToBottom) + #expect(!c.store!.state.ui.scroll.pinnedToBottom) let before = try #require(demo.anchorProbe) p.apply(items: items + [Fixture2.item(81, them, "While you read")], summary: Fixture2.summary(lastSeq: 81), typing: [], hasOlder: true) let after = try #require(demo.anchorProbe) diff --git a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/HomeRenderTests.swift b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/HomeRenderTests.swift index 688ef8a9df2d..7bc3d7f34d57 100644 --- a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/HomeRenderTests.swift +++ b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/HomeRenderTests.swift @@ -31,9 +31,9 @@ import Testing for (i, t) in Self.agent.enumerated() { items.append(Fixture2.item(Seq(i + 2), Fixture2.them, t)) } items.append(Fixture2.item(5, Fixture2.me, "Thanks, **looks good** (mine stays as typed).")) p.apply(items: items, summary: Fixture2.summary(lastSeq: 5), typing: [], hasOlder: false) - c.demo.backgroundColor = Fixture.background - c.host.layoutSubtreeIfNeeded(); c.demo.layoutIfNeeded(); c.demo.collection.layoutIfNeeded() - let hit = try #require(c.demo.lastTextRow(mine: false)) + c.demo!.backgroundColor = Fixture.background + c.host.layoutSubtreeIfNeeded(); c.demo!.layoutIfNeeded(); c.demo!.collection.layoutIfNeeded() + let hit = try #require(c.demo!.lastTextRow(mine: false)) let from = CGPoint(x: hit.body.minX + 16, y: hit.body.minY + 14), to = CGPoint(x: hit.body.maxX - 30, y: hit.body.maxY - 12) c.mouseDown(at: from, event(.leftMouseDown)) c.mouseDragged(at: to, event(.leftMouseDragged)) @@ -42,7 +42,7 @@ import Testing // Row bitmaps draw asynchronously: let them land. for _ in 0..<30 { try await Task.sleep(for: .milliseconds(40)) - c.host.layoutSubtreeIfNeeded(); c.demo.collection.layoutIfNeeded(); CATransaction.flush() + c.host.layoutSubtreeIfNeeded(); c.demo!.collection.layoutIfNeeded(); CATransaction.flush() } let b = c.host.bounds let ctx = try #require(CGContext(data: nil, width: Int(b.width * 2), height: Int(b.height * 2), bitsPerComponent: 8, bytesPerRow: 0, diff --git a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/KeystrokeAheadTests.swift b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/KeystrokeAheadTests.swift index 875fc2c67349..10a6a4f55c38 100644 --- a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/KeystrokeAheadTests.swift +++ b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/KeystrokeAheadTests.swift @@ -24,12 +24,12 @@ import Testing let keystrokeFrames = frames.count // the keystroke frame's own end // The Chief reads my message in the same frame: only a status change. p.apply(items: [Fixture2.item(1, them, "Hi"), mine], summary: Fixture2.summary(lastSeq: 2, read: 2), typing: [them], hasOlder: false) - #expect(c.store.state.ui.typing.isEmpty, "typing waits for the next frame") - if case .read = c.store.state.message("k2")?.status { Issue.record("the read status waited for the next frame") } + #expect(c.store!.state.ui.typing.isEmpty, "typing waits for the next frame") + if case .read = c.store!.state.message("k2")?.status { Issue.record("the read status waited for the next frame") } #expect(frames.count == keystrokeFrames + 1, "one held commit") frames.forEach { $0() } - #expect(c.store.state.ui.typing == [them.rawValue]) - if case .read = c.store.state.message("k2")?.status {} else { Issue.record("read after the frame, got \(String(describing: c.store.state.message("k2")?.status))") } + #expect(c.store!.state.ui.typing == [them.rawValue]) + if case .read = c.store!.state.message("k2")?.status {} else { Issue.record("read after the frame, got \(String(describing: c.store!.state.message("k2")?.status))") } } @Test func aReceivedMessageIsNeverHeld() { @@ -41,7 +41,7 @@ import Testing c.dispatch(.setDraft("H")) let keystrokeFrames = frames.count p.apply(items: [Fixture2.item(1, them, "Hi"), Fixture2.item(2, them, "There")], summary: Fixture2.summary(lastSeq: 2), typing: [], hasOlder: false) - #expect(c.store.state.conversation.messages.count == 2) + #expect(c.store!.state.conversation.messages.count == 2) #expect(frames.count == keystrokeFrames, "nothing held") } } diff --git a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/LinkPreviewPolicyTests.swift b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/LinkPreviewPolicyTests.swift index baab9259627e..23cf6022a2a3 100644 --- a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/LinkPreviewPolicyTests.swift +++ b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/LinkPreviewPolicyTests.swift @@ -24,7 +24,7 @@ import Testing p.apply(items: first + [Fixture2.item(2, them, "https://example.com/report\nhere it is", key: "turn:s1:2")], summary: Fixture2.summary(lastSeq: 2), typing: [], hasOlder: false) #expect(previews.requested.isEmpty, "a received card fetched: \(previews.requested)") - let card = try #require(c.store.state.message(HomeMapping.rowSafe("turn:s1:2"))?.parts.first) + let card = try #require(c.store!.state.message(HomeMapping.rowSafe("turn:s1:2"))?.parts.first) guard case let .link(_, title, site, image, _) = card else { Issue.record("not a card: \(card)"); return } #expect(title == "example.com" && site == "example.com" && image == nil, "the domain-only card") } diff --git a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/LinkRuleTests.swift b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/LinkRuleTests.swift index bd9ffcc25f54..1adf8c9a8855 100644 --- a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/LinkRuleTests.swift +++ b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/LinkRuleTests.swift @@ -60,7 +60,7 @@ import Testing + "the first one-word text would cut it off after its first line and draw the rest outside the bubble." p.apply(items: [Fixture2.item(1, them, "Hi"), Fixture2.item(2, me, long, key: "k2")], summary: Fixture2.summary(lastSeq: 2), typing: [], hasOlder: false) - let row = try #require(c.demo.model.rows.first { $0.spec.key == "part:k2:0" }) + let row = try #require(c.demo!.model.rows.first { $0.spec.key == "part:k2:0" }) let lines = TextLayout.make(long, runs: [], maxWidth: row.spec.metrics.maxTextWidth).lines.count #expect(lines >= 3) #expect(row.spec.height >= CGFloat(lines) * Fixture.lineHeight, "row \(row.spec.height) pt for \(lines) lines") @@ -74,11 +74,11 @@ import Testing summary: Fixture2.summary(lastSeq: 2), typing: [], hasOlder: false) p.apply(items: [Fixture2.item(1, them, "Hi"), Fixture2.item(2, me, Self.urlAndText, key: "k2")], summary: Fixture2.summary(lastSeq: 2), typing: [], hasOlder: false) - let message = try #require(c.store.state.message("k2")) + let message = try #require(c.store!.state.message("k2")) try #require(message.parts.count == 2, "card + text bubble, got \(message.parts)") - let keys = c.demo.model.rows.map(\.spec.key).filter { $0.hasPrefix("part:k2:") } + let keys = c.demo!.model.rows.map(\.spec.key).filter { $0.hasPrefix("part:k2:") } #expect(keys == ["part:k2:0", "part:k2:1"]) - let text = try #require(c.demo.model.rows.first { $0.spec.key == "part:k2:1" }) + let text = try #require(c.demo!.model.rows.first { $0.spec.key == "part:k2:1" }) #expect(text.spec.height >= Fixture.lineHeight) } diff --git a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/OutgoingFillTests.swift b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/OutgoingFillTests.swift index 7e5bafb695ff..d9ed1a3221b7 100644 --- a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/OutgoingFillTests.swift +++ b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/OutgoingFillTests.swift @@ -20,24 +20,24 @@ import Testing createdAt: Fixture2.start.addingTimeInterval(400), delivery: .notDelivered(.invalid("x"))) p.apply(items: Fixture2.history(4) + [failed], summary: Fixture2.summary(lastSeq: 4), typing: [], hasOlder: false) c.host.layoutSubtreeIfNeeded() - c.demo.collection.layoutIfNeeded() + c.demo!.collection.layoutIfNeeded() return (p, c) } @Test func aFailedSendLowInATallPaneKeepsItsBubbleFill() throws { let (_, c) = tallPane(height: 1300) - let cell = try #require(c.demo.collection.visibleCells.compactMap { $0 as? RowCell }.first { $0.spec?.key == "part:failed:0" }) + let cell = try #require(c.demo!.collection.visibleCells.compactMap { $0 as? RowCell }.first { $0.spec?.key == "part:failed:0" }) let spec = try #require(cell.spec) - let body = cell.layer.convert(RowDraw.bodyRect(spec), to: c.demo.layer) + let body = cell.layer.convert(RowDraw.bodyRect(spec), to: c.demo!.layer) #expect(body.minY > Fixture.gradientHeight, "the row sits below the measured window (\(body.minY))") #expect(!cell.fillContainer.isHidden) - #expect(HomeFlightRecorder.unfilledOutgoing(c.demo).isEmpty, "\(HomeFlightRecorder.unfilledOutgoing(c.demo))") + #expect(HomeFlightRecorder.unfilledOutgoing(c.demo!).isEmpty, "\(HomeFlightRecorder.unfilledOutgoing(c.demo!))") } @Test func aPaletteChangeKeepsOneLocationPerColour() throws { let (_, c) = tallPane(height: 900) defer { Fixture.theme = nil } - let cell = try #require(c.demo.collection.visibleCells.compactMap { $0 as? RowCell }.first { $0.spec?.key == "part:failed:0" }) + let cell = try #require(c.demo!.collection.visibleCells.compactMap { $0 as? RowCell }.first { $0.spec?.key == "part:failed:0" }) let spec = try #require(cell.spec) // Measured (8 stops) to a chosen accent (11 stops) on a live cell. let theme = HomePalette.Theme(background: .gray255(30), foreground: .gray255(230), accent: .rgb255(200, 30, 30), @@ -62,7 +62,7 @@ import Testing let failed = TranscriptItem(key: IdempotencyKey("shot"), seq: nil, author: me, parts: [.attachment(ref)], createdAt: Fixture2.start.addingTimeInterval(400), delivery: .notDelivered(.invalid("x"))) p.apply(items: Fixture2.history(2) + [failed], summary: Fixture2.summary(lastSeq: 2), typing: [], hasOlder: false) - let spec = try #require(c.demo.model.rows.first { $0.spec.key == "part:shot:0" }?.spec) + let spec = try #require(c.demo!.model.rows.first { $0.spec.key == "part:shot:0" }?.spec) // The row bitmap the cell shows, at 1x, redrawn into a known RGBA layout. let scale = Fixture.renderScale Fixture.renderScale = 1 diff --git a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/PaneLinkClickTests.swift b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/PaneLinkClickTests.swift index b6ccbbf59eed..de2a4e0de7f1 100644 --- a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/PaneLinkClickTests.swift +++ b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/PaneLinkClickTests.swift @@ -21,7 +21,7 @@ import Testing Fixture2.item(3, Fixture2.them, "Image: ![chart](https://example.com/chart.png)"), ] p.apply(items: items, summary: Fixture2.summary(lastSeq: 3), typing: [], hasOlder: false) - c.host.layoutSubtreeIfNeeded(); c.demo.layoutIfNeeded(); c.demo.collection.layoutIfNeeded() + c.host.layoutSubtreeIfNeeded(); c.demo!.layoutIfNeeded(); c.demo!.collection.layoutIfNeeded() var opened = Set() let b = c.host.bounds for y in stride(from: b.minY, to: b.maxY, by: 3) { diff --git a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/PaneMenuTests.swift b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/PaneMenuTests.swift index 827396dc019a..e81aa4f81772 100644 --- a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/PaneMenuTests.swift +++ b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/PaneMenuTests.swift @@ -15,9 +15,9 @@ import Testing if let i = items.lastIndex(where: { $0.author == Fixture2.them }) { items[i].reactions = reactions } p.apply(items: items, summary: Fixture2.summary(lastSeq: 6), typing: [], hasOlder: false) c.host.layoutSubtreeIfNeeded() - c.demo.layoutIfNeeded() - c.demo.collection.layoutIfNeeded() - guard let hit = c.demo.lastTextRow(mine: false) else { return (nil, c) } + c.demo!.layoutIfNeeded() + c.demo!.collection.layoutIfNeeded() + guard let hit = c.demo!.lastTextRow(mine: false) else { return (nil, c) } return (c.menu(at: CGPoint(x: hit.body.midX, y: hit.body.midY)), c) } @@ -43,8 +43,8 @@ import Testing @Test func tapbackDetailsListsWhoReactedFromHomeStore() throws { let (_, c) = menu(reactions: [CmuxHomeCore.Reaction(author: Fixture2.me, partIndex: 0, kind: .tapback(.love))]) - let hit = try #require(c.demo.lastTextRow(mine: false)) + let hit = try #require(c.demo!.lastTextRow(mine: false)) #expect(hit.row.reactions.map(\.senderId) == [Fixture2.me.rawValue]) - #expect(c.store.state.conversation.participants.first { $0.id == Fixture2.me.rawValue }?.displayName != nil) + #expect(c.store!.state.conversation.participants.first { $0.id == Fixture2.me.rawValue }?.displayName != nil) } } diff --git a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/PersonTextPlainTests.swift b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/PersonTextPlainTests.swift index d76dd0e4d588..ad4f74af321a 100644 --- a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/PersonTextPlainTests.swift +++ b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/PersonTextPlainTests.swift @@ -13,12 +13,56 @@ import Testing Fixture2.item(2, Fixture2.me, "Thanks, **looks good** and `done`.")] p.apply(items: items, summary: Fixture2.summary(lastSeq: 2), typing: [], hasOlder: false) c.host.layoutSubtreeIfNeeded() - c.demo.layoutIfNeeded() - c.demo.collection.layoutIfNeeded() - let mine = try #require(c.demo.lastTextRow(mine: true)) + c.demo!.layoutIfNeeded() + c.demo!.collection.layoutIfNeeded() + let mine = try #require(c.demo!.lastTextRow(mine: true)) #expect(mine.row.markdown == nil, "a person's text takes the plain path") #expect(mine.row.text?.text == "Thanks, **looks good** and `done`.") - let agent = try #require(c.demo.lastTextRow(mine: false)) + let agent = try #require(c.demo!.lastTextRow(mine: false)) #expect(agent.row.text?.text == "Plan: ship it after verify-clean.", "an agent's text stays Markdown") } + + private func laidOut(_ c: ChatController) { + c.host.layoutSubtreeIfNeeded(); c.demo!.layoutIfNeeded(); c.demo!.collection.layoutIfNeeded() + } + + /// My own send never went through HomeMapping before MessagesLab's reducer made and + /// measured its local message (`.send`), so it showed as Markdown at once and, measured + /// under the same id, after the owner's echo too. A person's text shows as typed on every + /// path: the local message at the press, the committed echo, and a later open. + @Test func mySendShowsAsTypedAtThePressAfterTheEchoAndAfterAReopen() async throws { + let typed = "**bold** and _x_" + let source = ScriptedSource(me: Fixture2.people[0], summary: Fixture2.summary(lastSeq: 1), + messages: [Fixture2.message(1, Fixture2.them, "Hi")]) + let store = HomeStore(source: source) + store.start() + defer { store.stop() } + await waitUntil { store.isOnline && store.me != nil } + await store.open(Fixture2.id) + let (p, c) = Fixture2.projection(store: store) + p.start() + c.dispatch(.setDraft(typed)) + p.send() + laidOut(c) + let atPress = try #require(c.demo!.lastTextRow(mine: true)) + #expect(atPress.row.markdown == nil, "the local message at the press takes the plain path") + #expect(atPress.row.text?.text == typed) + let local = try #require(c.store!.state.conversation.messages.last) + let key = try #require(p.aliases.first(where: { $0.value == local.id })?.key) + await waitUntil { store.transcript(for: Fixture2.id).contains { $0.key == key } } + await source.publish(.message(Fixture2.message(2, Fixture2.me, typed, key: key.rawValue), rev: 11)) + await waitUntil { p.shown.last?.seq == 2 } + laidOut(c) + let echoed = try #require(c.demo!.lastTextRow(mine: true)) + #expect(echoed.row.markdown == nil, "the committed echo takes the plain path") + #expect(echoed.row.text?.text == typed) + p.stop() + let (p2, c2) = Fixture2.projection(store: store) + p2.start() + laidOut(c2) + let reopened = try #require(c2.demo!.lastTextRow(mine: true)) + #expect(reopened.row.markdown == nil, "a later open takes the plain path") + #expect(reopened.row.text?.text == typed) + p2.stop() + } } diff --git a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/ProjectionIDTests.swift b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/ProjectionIDTests.swift index 14184d94fb35..c4d07d8d1c04 100644 --- a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/ProjectionIDTests.swift +++ b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/ProjectionIDTests.swift @@ -21,11 +21,11 @@ import Testing items.append(Fixture2.item(Seq(seq), seq % 2 == 0 ? them : me, "Message \(seq)", key: seq % 2 == 0 ? "turn:s1:\(seq)" : "preflight-\(seq)")) p.apply(items: items, summary: Fixture2.summary(lastSeq: Seq(seq)), typing: [], hasOlder: false) } - let keys = c.demo.model.rows.map(\.spec.key) + let keys = c.demo!.model.rows.map(\.spec.key) #expect(keys.count == Set(keys).count, "duplicate rows: \(keys)") #expect(keys.filter { $0.hasPrefix("part:") }.count == 5, "one part row per message: \(keys)") // Ids still round-trip: a tapback on a Chief message finds its item. - let chief = try #require(c.store.state.conversation.messages.first { $0.senderId == them.rawValue }) + let chief = try #require(c.store!.state.conversation.messages.first { $0.senderId == them.rawValue }) #expect(RowBuilder.owner("part:\(chief.id):0") == Substring(chief.id)) } } diff --git a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/TextLayoutFuzzTests.swift b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/TextLayoutFuzzTests.swift new file mode 100644 index 000000000000..80501c05b35d --- /dev/null +++ b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabHomeTests/TextLayoutFuzzTests.swift @@ -0,0 +1,79 @@ +import AppKit +import Testing +@testable import MessagesLabHome + +/// Crash program phase 3 (plans/cmux-next/crash-elimination.md section 7): +/// property tests for the Home transcript's text layout. An Objective-C range +/// exception ends the test process, so every property is "never throws" plus +/// the invariant that a range is valid for the string it is used on. +/// Seeded, so a failure reproduces from its seed. +@Suite struct TextLayoutFuzzTests { + struct Rng { + var state: UInt64 + mutating func next() -> UInt64 { + state ^= state << 13; state ^= state >> 7; state ^= state << 17 + return state + } + mutating func below(_ n: Int) -> Int { Int(next() % UInt64(max(n, 1))) } + mutating func pick(_ items: [T]) -> T { items[below(items.count)] } + } + + /// Markdown tokens plus the text that breaks UTF-16 arithmetic: surrogate + /// pairs, ZWJ emoji, combining marks, CRLF, right-to-left text. + static let tokens = [ + "**", "*", "_", "`", "```", "```swift\n", "\n", "\r\n", " ", "# ", "## ", "- ", "1. ", "> ", "| a | b |\n|---|---|\n", + "[link](https://example.com)", "", "word", "longer words here", "👩‍👩‍👧‍👦", "🇯🇵", "e\u{301}", "𝒳", "\u{200D}", + "שלום", "日本語", "\t", "\\", "~~", "@mention", String(repeating: "x", count: 300), + ] + + static func document(_ rng: inout Rng) -> String { + (0..= 0 && run.length >= 0 && run.start + run.length <= length, "run \(run) outside \(length)") + } + let layout = TextLayout.make(text, runs: runs, maxWidth: CGFloat(20 + rng.below(600))) + _ = layout.attributed(color: .white, linkColor: .white) + _ = layout.link(at: CGPoint(x: CGFloat(rng.below(600)), y: CGFloat(rng.below(400)))) + } + } + + @Test func runsThatDoNotFitTheTextAreSkipped() { + var rng = Rng(state: 7) + let extremes = [-1, 0, 1, 5, Int.max, Int.min, Int.max - 1] + for _ in 0..<3_000 { + let text = Self.document(&rng) + let length = (text as NSString).length + let runs = (0.. (RowCell, CGPoint) { - let cell = try #require(c.demo.collection.visibleCells.compactMap { $0 as? RowCell }.first { + let cell = try #require(c.demo!.collection.visibleCells.compactMap { $0 as? RowCell }.first { if let spec = $0.spec, case let .part(p) = spec.kind { return p.ref == ref } return false }) @@ -51,7 +51,7 @@ import Testing let (window, p, c, ref, asked) = try host() defer { window.close() } let (cell, point) = try cell(c, ref) - #expect(c.demo.hit(point)?.row.ref == ref, "the click lands on the video bubble") + #expect(c.demo!.hit(point)?.row.ref == ref, "the click lands on the video bubble") c.clicked(point) #expect(p.videoState(ref) == .loading, "a click starts playback (fetching the URL)") await p.video.playback.settled() diff --git a/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabSidebarTests/SidebarCrashSafeTests.swift b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabSidebarTests/SidebarCrashSafeTests.swift new file mode 100644 index 000000000000..49dec953f3e9 --- /dev/null +++ b/Packages/Shared/CmuxMessagesLab/Tests/MessagesLabSidebarTests/SidebarCrashSafeTests.swift @@ -0,0 +1,21 @@ +import AppKit +import Testing +@testable import MessagesLabSidebar + +/// Crash program: the sidebar's fonts, color space and palette no longer force-unwrap. +/// These pin that the literals resolve, so the fallbacks never run. +@MainActor @Suite struct SidebarCrashSafeTests { + @Test func fontsAndColorSpaceResolve() { + #expect(CTFontCreateUIFontForLanguage(.emphasizedSystem, 13, nil) != nil) + #expect(CTFontGetSize(SidebarDraw.uiFont(.system, 12)) == 12) + #expect(SidebarDraw.p3.name == CGColorSpace.displayP3) + } + + @Test func paletteResolvesInBothAppearances() throws { + let dark = try #require(NSAppearance(named: .darkAqua)) + let light = try #require(NSAppearance(named: .aqua)) + #expect(SidebarPalette.resolve(dark).dark) + #expect(!SidebarPalette.resolve(light).dark) + #expect(SidebarPalette.resolve(dark).monogramTop.colorSpace?.name == CGColorSpace.displayP3) + } +} diff --git a/Packages/macOS/CmuxNext/Package.swift b/Packages/macOS/CmuxNext/Package.swift index 0fd30a0fb954..41d4b5917271 100644 --- a/Packages/macOS/CmuxNext/Package.swift +++ b/Packages/macOS/CmuxNext/Package.swift @@ -101,8 +101,8 @@ let daemonSwiftSettings: [SwiftSetting] = [ /// when the FFI sources differ from the pinned source sha. let appFFI: Target = .binaryTarget( name: "CCmuxAppFFI", - url: "https://github.com/manaflow-ai/cmux/releases/download/cmux-app-ffi-eee4e4fffe22964457034c3fd2a8fb22388dec2b/CCmuxAppFFI.xcframework.zip", - checksum: "29b59f4c85596393ab656ac27edb7b55bde9036f3c73450e361bdb1ecd649de1" + url: "https://github.com/manaflow-ai/cmux/releases/download/cmux-app-ffi-a10946c9823b7074033c1a3b302e807994d09301/CCmuxAppFFI.xcframework.zip", + checksum: "759521e45a8a063a88c13f083ad4943e645b1dc8e087897e695815bcf3e8ca06" ) let package = Package( @@ -117,6 +117,7 @@ let package = Package( dependencies: [ .package(path: "../../Shared/CmuxGhosttyKit"), .package(path: "../../Shared/CMUXAuthCore"), + .package(path: "../../Shared/CmuxInstallAuthCore"), .package(path: "../../Shared/CmuxAuthRuntime"), .package(path: "../../Shared/CMUXMobileCore"), .package(path: "../../Shared/CmuxTheme"), @@ -640,13 +641,14 @@ let package = Package( dependencies: [ "CmuxNextWakeups", .product(name: "CMUXAuthCore", package: "CMUXAuthCore"), + .product(name: "CmuxInstallAuthCore", package: "CmuxInstallAuthCore"), .product(name: "CmuxAuthRuntime", package: "CmuxAuthRuntime"), ], swiftSettings: daemonSwiftSettings ), .testTarget( name: "CmuxNextCloudTests", - dependencies: ["CmuxNextCloud"], + dependencies: ["CmuxNextCloud", .product(name: "CmuxInstallAuthCore", package: "CmuxInstallAuthCore")], swiftSettings: daemonSwiftSettings ), // Machines reached over the user's own OpenSSH: destinations, the diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextActions/ActionCatalog.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextActions/ActionCatalog.swift index 7598fe0c195d..6bdd3ddbea27 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextActions/ActionCatalog.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextActions/ActionCatalog.swift @@ -109,6 +109,7 @@ public nonisolated enum ActionCatalog { AppStoreActionCatalog.self, TasksActionCatalog.self, LinkActionCatalog.self, + ShareActionCatalog.self, ServerActionCatalog.self, MarkdownPageActionCatalog.self, ListActionCatalog.self, diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextActions/ActionCatalog.xcstrings b/Packages/macOS/CmuxNext/Sources/CmuxNextActions/ActionCatalog.xcstrings index aee3fc974e1c..66344ee3ea1b 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextActions/ActionCatalog.xcstrings +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextActions/ActionCatalog.xcstrings @@ -71002,6 +71002,137 @@ } } } + }, + "action.app.shareCmux": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Share cmux…" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux…" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux…" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux…" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux…" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux…" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux…" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux…" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "cmux を共有…" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux…" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux…" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux…" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux…" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux…" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux…" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux…" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux…" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux…" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux…" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux…" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux…" + } + } + } } }, "version": "1.0" diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextActions/ActionRegistry.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextActions/ActionRegistry.swift index 9651a956007c..b99a635980e0 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextActions/ActionRegistry.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextActions/ActionRegistry.swift @@ -331,7 +331,7 @@ public final class ActionRegistry { var best: (id: ActionID, specificity: Int)? for id in ids where canPerform(id) { let specificity = descriptor(for: id)?.requires.rawValue.nonzeroBitCount ?? 0 - if best == nil || specificity > best!.specificity { + if specificity > best?.specificity ?? Int.min { best = (id, specificity) } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextActions/Catalog/ShareActionCatalog.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextActions/Catalog/ShareActionCatalog.swift new file mode 100644 index 000000000000..f98fddd0c1d3 --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextActions/Catalog/ShareActionCatalog.swift @@ -0,0 +1,18 @@ +// "Share cmux…" (cx-7py7): the Share cmux modal with a message and the +// public download link. The palette, the Help menu and the "cmux Updated!" +// card's Share cmux row run this one action. + +nonisolated enum ShareActionCatalog: ActionCatalogGroup { + static func descriptors() -> [ActionDescriptor] { + [ + ActionDescriptor( + id: "app.shareCmux", + title: String(localized: "action.app.shareCmux", defaultValue: "Share cmux…", bundle: .module), + keywords: ["share", "invite", "friend", "recommend", "download link", "copy link", "tell a friend"], + category: .settings, symbol: "square.and.arrow.up", surfaces: [.palette, .menu], mainMenu: .help, + // A modal for a person to edit and copy; scripts have nothing to read back. + surfacePlan: ActionSurfacePlan(cli: .exempt(.guiOnly), contextMenuExemption: .noObject) + ), + ] + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextActions/KeyBindingDefaults.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextActions/KeyBindingDefaults.swift index 5db74dcb3e81..bb5af28c846f 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextActions/KeyBindingDefaults.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextActions/KeyBindingDefaults.swift @@ -21,12 +21,12 @@ public import AppKit /// Unbinding `nextSurface` or `prevSurface` in cmux.json removes its entries. public nonisolated struct KeyBindingDefaults { public nonisolated init() {} - static let right = String(Character(UnicodeScalar(UInt32(NSRightArrowFunctionKey))!)) - static let left = String(Character(UnicodeScalar(UInt32(NSLeftArrowFunctionKey))!)) + static let right = String(Character(UnicodeScalar(UInt32(NSRightArrowFunctionKey)) ?? UnicodeScalar(0))) + static let left = String(Character(UnicodeScalar(UInt32(NSLeftArrowFunctionKey)) ?? UnicodeScalar(0))) static let up = String(Character(UnicodeScalar(UInt32(NSUpArrowFunctionKey)) ?? UnicodeScalar(0))) static let down = String(Character(UnicodeScalar(UInt32(NSDownArrowFunctionKey)) ?? UnicodeScalar(0))) - public static let pageUp = String(Character(UnicodeScalar(UInt32(NSPageUpFunctionKey))!)) - public static let pageDown = String(Character(UnicodeScalar(UInt32(NSPageDownFunctionKey))!)) + public static let pageUp = String(Character(UnicodeScalar(UInt32(NSPageUpFunctionKey)) ?? UnicodeScalar(0))) + public static let pageDown = String(Character(UnicodeScalar(UInt32(NSPageDownFunctionKey)) ?? UnicodeScalar(0))) public static let home = String(Character(UnicodeScalar(UInt32(NSHomeFunctionKey)) ?? UnicodeScalar(0))) public static let end = String(Character(UnicodeScalar(UInt32(NSEndFunctionKey)) ?? UnicodeScalar(0))) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextActions/Shortcut+Display.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextActions/Shortcut+Display.swift index 9d1ce728f9af..e76129e804b9 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextActions/Shortcut+Display.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextActions/Shortcut+Display.swift @@ -2,10 +2,10 @@ import AppKit extension Shortcut { // Key-equivalent characters for non-printing keys (NSMenuItem semantics). - public nonisolated static let upArrowKey = String(Character(UnicodeScalar(UInt32(NSUpArrowFunctionKey))!)) - public nonisolated static let downArrowKey = String(Character(UnicodeScalar(UInt32(NSDownArrowFunctionKey))!)) - public nonisolated static let leftArrowKey = String(Character(UnicodeScalar(UInt32(NSLeftArrowFunctionKey))!)) - public nonisolated static let rightArrowKey = String(Character(UnicodeScalar(UInt32(NSRightArrowFunctionKey))!)) + public nonisolated static let upArrowKey = String(Character(UnicodeScalar(UInt32(NSUpArrowFunctionKey)) ?? UnicodeScalar(0))) + public nonisolated static let downArrowKey = String(Character(UnicodeScalar(UInt32(NSDownArrowFunctionKey)) ?? UnicodeScalar(0))) + public nonisolated static let leftArrowKey = String(Character(UnicodeScalar(UInt32(NSLeftArrowFunctionKey)) ?? UnicodeScalar(0))) + public nonisolated static let rightArrowKey = String(Character(UnicodeScalar(UInt32(NSRightArrowFunctionKey)) ?? UnicodeScalar(0))) public nonisolated static let returnKey = "\r" public nonisolated static let tabKey = "\t" public nonisolated static let escapeKey = "\u{1B}" diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentActivity/AgentActivityPageAddress.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentActivity/AgentActivityPageAddress.swift index e6571f72f491..0e98bb8c5076 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentActivity/AgentActivityPageAddress.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentActivity/AgentActivityPageAddress.swift @@ -5,7 +5,8 @@ public import Foundation /// tab kind the workspace store already persists and restores. public nonisolated enum AgentActivityPageAddress { public static let string = "cmux://agent-activity" - public static var url: URL { URL(string: string)! } + /// The page address (a literal a test parses; /dev/null stands in rather than a trap). + public static let url: URL = URL(string: string) ?? URL(fileURLWithPath: "/dev/null") /// `cmux://agent-activity`, with or without a trailing slash, query or fragment. public static func matches(_ url: URL?) -> Bool { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/AcpmuxPaneMethods+Answers.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/AcpmuxPaneMethods+Answers.swift index 403a51cb6dfe..ce0d78620a38 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/AcpmuxPaneMethods+Answers.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/AcpmuxPaneMethods+Answers.swift @@ -16,7 +16,7 @@ nonisolated extension AcpmuxPaneMethods { /// tool permission. They are an object of 1 to ``maximumAnswerItems`` of the question's own /// items (an item id or prompt), and each value is a string, a list of at most /// ``maximumAnswerListStrings`` strings, or Codex's `{answers: [string]}` with that one key. Each key and each string is at most - /// ``maximumAnswerBytes`` UTF-8 bytes. + /// ``maximumAnswerBytes`` UTF-8 bytes; strings in a list are bounded together by the same limit. static func breaksAnswersRule(_ object: [String: Any]?, options: AcpmuxPermissionOptions) -> Bool { guard let object, object["method"] as? String == "_acpmux/permission_respond", let params = object["params"] as? [String: Any], let rawAnswers = params["answers"] else { return false } @@ -40,7 +40,8 @@ nonisolated extension AcpmuxPaneMethods { private static func fitsAnswerList(_ value: Any) -> Bool { guard let list = value as? [Any], list.count <= maximumAnswerListStrings else { return false } - return list.allSatisfy(fitsAnswerString) + guard list.allSatisfy(fitsAnswerString) else { return false } + return list.compactMap { ($0 as? String)?.utf8.count }.reduce(0, +) <= maximumAnswerBytes } private static func fitsAnswerString(_ value: Any) -> Bool { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/AgentPaneNavigation.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/AgentPaneNavigation.swift index a240f0e8b222..ac809ca7a99e 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/AgentPaneNavigation.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/AgentPaneNavigation.swift @@ -27,7 +27,7 @@ final class AgentPaneNavigation: NSObject, WKNavigationDelegate { } } - func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { + func webView(_ webView: WKWebView, didFinish navigation: WKNavigation?) { AgentPaneLaunchTimings.shared.mark("agent_pane.page_loaded") view?.applyTheme() view?.applyShortcuts() diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/AgentPaneSource.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/AgentPaneSource.swift index 900191578cf9..4e72faf1f73f 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/AgentPaneSource.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/AgentPaneSource.swift @@ -41,7 +41,10 @@ public nonisolated enum AgentPaneSource: Equatable, Sendable { public var pageURL: URL { switch self { case .bundled(let page): - URL(string: "\(Self.bundledOrigin)/\(page.lastPathComponent)")! + // A file name under a literal origin; the escaped form covers names URL(string:) refuses. + URL(string: "\(Self.bundledOrigin)/\(page.lastPathComponent)") + ?? URL(string: "\(Self.bundledOrigin)/\(page.lastPathComponent.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "")") + ?? URL(fileURLWithPath: "/dev/null") case .devServer(let url): url } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Accounts/AccountsService.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Accounts/AccountsService.swift index 13eb830a4305..ca49811f200b 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Accounts/AccountsService.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Accounts/AccountsService.swift @@ -81,7 +81,7 @@ final class AccountsService: AccountsServices { } var client: CodeRouterClient? { - guard let cloud = services.cloud else { return nil } + let cloud = services.cloud let auth = cloud.auth, labels = labels return CodeRouterClient(baseURL: cloud.configuration.apiBaseURL, tokens: { try await auth.tokens() }, teamID: { await auth.teamID }, labeler: { await labels.labeler() }) @@ -94,11 +94,11 @@ final class AccountsService: AccountsServices { return await Task.detached { await ProviderDetector(environment: environment).detectAll() }.value } - var isSignedInToCmux: Bool { showcaseMock?.isSignedInToCmux ?? (services.cloud?.isSignedIn ?? false) } + var isSignedInToCmux: Bool { showcaseMock?.isSignedInToCmux ?? services.cloud.isSignedIn } func signInToCmux() { if let showcaseMock { showcaseMock.signInToCmux(); model.refresh(); return } - guard let cloud = services.cloud else { return } + let cloud = services.cloud // task-owner: one hosted sign-in; ends when the browser flow returns Task { [weak self] in _ = await cloud.auth.signIn() diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/AppActions+Workspaces.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/AppActions+Workspaces.swift index 6becf1f9584e..31f446aada68 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/AppActions+Workspaces.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/AppActions+Workspaces.swift @@ -82,7 +82,7 @@ extension AppActions { let focus = NewWorkspaceFocus(invocation) let show = focus.shows - let windows = services.windows! + let windows = services.windows // Shown: the active window, or a new one when none is open. Not // shown (the CLI default): the most recent window lists it, or a new // window when none is open (a workspace never lives in no window). diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/AppDelegate.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/AppDelegate.swift index 05afa22b9d81..573931038b85 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/AppDelegate.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/AppDelegate.swift @@ -18,7 +18,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate { private let launchSettle = LaunchSettle() /// Cleanup deferred until the launch settles (injected; tests pass their own). private let launchCleanup: LaunchCleanup - private var services: AppServices! + /// Set in applicationDidFinishLaunching; nil before it (no IUO). + private var services: AppServices? private var settings: SettingsController? private let control = AppControl() private var cloudContext: Task? @@ -91,7 +92,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // App-scoped Ghostty actions (quit, toggle_visibility, ...) arrive with no surface. TerminalHooks(services: services).install() DebugTimings.markLaunch("dfl.bind") - startSettingsAndControl(registry: services.registry, launch: settingsRead) + startSettingsAndControl(services: services, launch: settingsRead) DebugTimings.markLaunch("dfl.settings") NSApp.mainMenu = MainMenu.make(registry: services.registry) DebugTimings.markLaunch("dfl.menu") @@ -192,7 +193,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate { /// cmux-next.json settings (density, shortcut overrides) and the tagged /// control socket (`action.list/describe/run`) over the same registry. - private func startSettingsAndControl(registry: ActionRegistry, launch: SettingsController.LaunchRead) { + private func startSettingsAndControl(services: AppServices, launch: SettingsController.LaunchRead) { + let registry = services.registry let settings = SettingsController(registry: registry, fileURL: launch.fileURL, launch: launch) settings.applyManagedFeaturesNow() ManagedPolicyBridge(settings: settings, updater: services.updater, auth: services.cloud.auth).start() diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/AppServices.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/AppServices.swift index d448bf572ee1..0cbf5b127936 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/AppServices.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/AppServices.swift @@ -34,38 +34,38 @@ final class AppServices { var showJumpWindow: @MainActor (NSWindow, WindowActivation.Intent) -> Void = { WindowActivation.show($0, $1) } /// The app's key window. Tests and `debug.key` replace it: a window only becomes key in a running, active app. var keyWindowSource: @MainActor () -> NSWindow? = { NSApp.keyWindow } - private(set) var cloud: CloudService! + private(set) lazy var cloud: CloudService = CloudService(machines: machines, isDebugBuild: ControlService.isDebugBuild) // first read in init (no IUO) /// The feed mirror (`FeedDO`), started once the cmux account is signed in. - private(set) var feed: FeedService! + private(set) lazy var feed: FeedService = FeedService(auth: cloud.auth, showcase: environment.showcase) // first read in init (no IUO) var showcase = ShowcaseState() /// The wide Inbox page, backed by `feed.model`. private(set) lazy var feedPage = FeedPageService(services: self) /// SSH machines (Connect to Machine…); `serverReach`: paired servers' Chief sessions in the sidebar. - private(set) var ssh: SSHService! + private(set) lazy var ssh: SSHService = SSHService(machines: machines, bundleID: environment.launch.bundleID) // first read in init (no IUO) private(set) lazy var serverReach = ServerReachService.app(services: self) /// Phone access; started by the account layer once signed in. let mobile = MobileHostService() let registry = ActionRegistry.standard() /// Sparkle updates (release builds) or read-only feed probes (DEV). let updater = UpdaterService() - private(set) var updateSheet: UpdateSheetController! + private(set) lazy var updateSheet: UpdateSheetController = UpdateSheetController(source: UpdateSheetModel(service: updater)) // first read in init (no IUO) /// cmux.json controller; set by `AppDelegate` once it starts. var settings: SettingsController? /// Writes the palette shortcut recorder's edits (the recorder holds it weakly). var paletteShortcutEditor: PaletteShortcutEditor? - private(set) var cache: TabContentCache! - private(set) var windows: WindowManager! - private(set) var dragSession: TabDragSession! - private(set) var palette: PaletteController! - private(set) var previews: TabPreviewSource! + private(set) lazy var cache: TabContentCache = TabContentCache(daemon: daemon, cef: CEFEngine(lifecycleTrace: .shared, contextMenus: self.contextMenus)) // first read in init (no IUO) + private(set) lazy var windows: WindowManager = WindowManager(services: self) // first read in init (no IUO) + private(set) lazy var dragSession: TabDragSession = TabDragSession(services: self) // first read in init (no IUO) + private(set) lazy var palette: PaletteController = PaletteController(registry: registry, sources: PaletteSourcesBridge.make(services: self)) // first read in init (no IUO) + private(set) lazy var previews: TabPreviewSource = TabPreviewSource(cache: cache) // first read in init (no IUO) /// CPU and memory for the hover cards and `resources` (sampled on demand). - private(set) var resources: AppResourceSource! + private(set) lazy var resources: AppResourceSource = AppResourceSource(services: self) // first read in init (no IUO) let presentation = ContentPresentationScheduler() /// Blank-pane invariant, checked after each presentation settle. let surfaceInvariant = SurfaceInvariantMonitor() /// Input invariants, desync reports, focus journaling and the no-activate keyboard guard. let input = InputVerificationService() - private(set) var emptyWorkspaces: EmptyWorkspaceRepair! + private(set) lazy var emptyWorkspaces: EmptyWorkspaceRepair = EmptyWorkspaceRepair(daemon: daemon) // first read in init (no IUO) /// Reopen Closed Tab history; set when the tab handlers bind. var closedTabs: ClosedTabTracker? /// The app-wide "where was I" trail (plans/cmux-next/history.md 4.2). @@ -118,15 +118,15 @@ final class AppServices { /// The one icon picker (R94): Set Icon of workspaces, screens, spaces, browser profiles. private(set) lazy var iconPicker = IconPickerService(services: self) /// cmux.json command `actions`, registered as `cmuxConfig.`. - private(set) var configActions: ConfigActionsController! + private(set) lazy var configActions: ConfigActionsController = ConfigActionsController(context: AppActionContext(services: self)) // first read in init (no IUO) /// System-wide hot keys for catalog actions marked `isGlobalHotKey`. private(set) lazy var globalHotKeys = GlobalHotKeyService.app(self) let terminalDelegate = TerminalHostDelegate() /// Attention rings, banners, sounds and dismissal (plans/cmux-next/notifications.md). let notifications = NotificationCenterService() /// The one keyboard router (plans/cmux-next/focus.md section 5). - private(set) var keyRouter: KeyRouter! - private(set) var chromiumWarmup: ChromiumWarmup! + private(set) lazy var keyRouter: KeyRouter = KeyRouter(registry: registry) // first read in init (no IUO) + private(set) lazy var chromiumWarmup: ChromiumWarmup = ChromiumWarmup(engine: cache.cef) // first read in init (no IUO) /// The Settings window (Settings…, Cmd-,). private(set) lazy var settingsWindow = SettingsWindowService(services: self) /// Debug Settings: tunable overrides and their window (DEV and NIGHTLY). @@ -141,9 +141,9 @@ final class AppServices { private(set) lazy var externalOpen = ExternalOpenController(services: self) let terminalTheme = TerminalThemeSetting(backdropScope: .app) /// Room, workspace and terminal themes. - private(set) var themes: ThemeCoordinator! + private(set) lazy var themes: ThemeCoordinator = ThemeCoordinator(services: self, terminalThemes: .forApplication(bundleIdentifier: environment.launch.bundleID)) // first read in init (no IUO) /// Browser tabs of remote machines reach that machine's localhost. - private(set) var remoteLocalhost: RemoteLocalhostService! + private(set) lazy var remoteLocalhost: RemoteLocalhostService = RemoteLocalhostService(machines: machines) // first read in init (no IUO) var chromiumLikelyObservations: [Task] = [] /// Repaints on `appearance.borders` changes (`observeBorders`). var borderObservation: Task? @@ -179,7 +179,7 @@ final class AppServices { /// The browser host's engine provider (idle until the daemon offers the endpoint). private(set) var browserHost: AppBrowserHost? /// Remote-terminal tabs: mount, placeholder, snapshot, moves. - private(set) var remoteTerminals: RemoteTerminalService! + private(set) lazy var remoteTerminals: RemoteTerminalService = RemoteTerminalService(services: self) // first read in init (no IUO) /// - Parameter launchReveal: The launch load-in the windows' sidebars /// hold for; the app-wide one by default. init(environment: AppEnvironment, launchReveal: LaunchReveal = .shared) { @@ -192,15 +192,15 @@ final class AppServices { crashRecovery = CrashRecoveryService(bundleID: environment.launch.bundleID, marksRun: environment.marksRun) machines = MachineRegistry(local: daemon) machines.isFeatureDisabled = { [registry] in registry.disabledFeatures.contains($0) } - cloud = CloudService(machines: machines, isDebugBuild: ControlService.isDebugBuild) - feed = FeedService(auth: cloud.auth, showcase: environment.showcase) - ssh = SSHService(machines: machines, bundleID: environment.launch.bundleID) + _ = cloud // built here, as before + _ = feed // built here, as before + _ = ssh // built here, as before BrowserLifecycleTrace.shared.configure { tab, event in InputJournal.shared.append(window: nil, .content(tab: tab, event: event)) } - cache = TabContentCache(daemon: daemon, cef: CEFEngine(lifecycleTrace: .shared, contextMenus: contextMenus)) - themes = ThemeCoordinator(services: self, terminalThemes: .forApplication(bundleIdentifier: environment.launch.bundleID)) - remoteLocalhost = RemoteLocalhostService(machines: machines) + _ = cache // built here, as before + _ = themes // built here, as before + _ = remoteLocalhost // built here, as before cache.configureBrowser = { [weak self] tab, url, base in // a Cloud proxied tab's store first (ProxiedBrowserTabs) await self?.cache.pageRequests.proxiedTabs.configuration(for: tab.id, url: url, base: base) { await self?.remoteLocalhost.configuration(for: tab, url: url, base: base) ?? base } ?? base } @@ -232,11 +232,11 @@ final class AppServices { } cache.cef.openOffTheRecord = { [weak self] url, source in self?.openOffTheRecord(url, source: source) } cache.browserTabs.isIncognitoTab = { [weak self] key in - guard let self, let windows, let workspace = workspaceID(ofTab: key) else { return false } + guard let self, let workspace = workspaceID(ofTab: key) else { return false } return windows.isIncognito(workspace: workspace) } cache.browserTabs.isIncognitoPane = { [weak self] pane in - guard let self, let windows, let workspace = daemon.store.workspace(containing: pane)?.id else { return false } + guard let self, let workspace = daemon.store.workspace(containing: pane)?.id else { return false } return windows.isIncognito(workspace: workspace) } cache.browserProfile = { [weak self] key in self?.browserProfiles.engineProfile(forTab: key) } @@ -250,10 +250,10 @@ final class AppServices { guard let self else { return explicit } return browserProfiles.profileForNewTab(in: pane, on: daemon, explicit: explicit) } - emptyWorkspaces = EmptyWorkspaceRepair(daemon: daemon) + _ = emptyWorkspaces // built here, as before cache.sessionDelegate = terminalDelegate cache.pageRequests.services = self - keyRouter = KeyRouter(registry: registry) + _ = keyRouter // built here, as before keyRouter.services = self keyRouter.whichKey = WhichKeyController() cache.keyRouter = keyRouter @@ -281,24 +281,23 @@ final class AppServices { surfaceInvariant.observeWindowOcclusion() cache.presentationChanges.subscribe("surface-invariant") { [weak self] in self?.surfaceInvariant.noteChange() } cache.presentationChanges.subscribe("browser-host") { [weak self] in self?.browserHost?.provider.refreshTabs() } - resources = AppResourceSource(services: self) - windows = WindowManager(services: self) + _ = resources // built here, as before + _ = windows // built here, as before windows.incognitoHistoryReset = { [weak cache, weak self] in cache?.resetIncognitoHistory() self?.locationTrail.forgetIncognito() } - dragSession = TabDragSession(services: self) - previews = TabPreviewSource(cache: cache) - remoteTerminals = RemoteTerminalService(services: self) + _ = dragSession // built here, as before + _ = previews // built here, as before + _ = remoteTerminals // built here, as before remoteTerminals.start() WorkspaceClose.willClose = { [weak self] workspace in self?.remoteTerminals.workspaceClosing(workspace) } let registry = registry daemon.workTracker = { registry.track($0) } - palette = PaletteController(registry: registry, sources: PaletteSourcesBridge.make(services: self)) + _ = palette // built here, as before terminalDelegate.services = self - configActions = ConfigActionsController(context: AppActionContext(services: self)) - let updateSheet = UpdateSheetController(source: UpdateSheetModel(service: updater)) - self.updateSheet = updateSheet + _ = configActions // built here, as before + let updateSheet = self.updateSheet // built here, as before updater.attach(sheet: updateSheet, services: self) cache.onBrowserReady = { [weak self] key in for controller in self?.windows.controllers ?? [] { @@ -307,7 +306,7 @@ final class AppServices { } observePaletteForFocus() input.start(services: self) - chromiumWarmup = ChromiumWarmup(engine: cache.cef) + _ = chromiumWarmup // built here, as before browserHost = AppBrowserHost(services: self) browserHost?.start() notifications.start(services: self) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Apps/AppsService.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Apps/AppsService.swift index da6842565e37..5835d1859c3f 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Apps/AppsService.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Apps/AppsService.swift @@ -104,7 +104,7 @@ final class AppsService { return } waitingStore = (appID, installed, focus) - if let windows = services.windows, windows.restored, windows.controllers.isEmpty { windows.reopenOrCreateWindow() } + if case let windows = services.windows, windows.restored, windows.controllers.isEmpty { windows.reopenOrCreateWindow() } } /// The first window opened or a window mounted a pane: a request that diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserHits/BrowserHitHandlers.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserHits/BrowserHitHandlers.swift index 6d4d2da0451b..c436fcbdbc85 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserHits/BrowserHitHandlers.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserHits/BrowserHitHandlers.swift @@ -114,7 +114,7 @@ enum BrowserHitHandlers { guard daemon.supports(DaemonCapabilities.shared.frontendBrowserTabs) else { throw ActionFailure(message: daemon.missingCapabilityMessage(DaemonCapabilities.shared.frontendBrowserTabs)) } - guard let browserTabs = services.cache.browserTabs, case .open(let choice) = browserTabs.resolve(requested: nil) else { return } + guard case let browserTabs = services.cache.browserTabs, case .open(let choice) = browserTabs.resolve(requested: nil) else { return } let address = url.absoluteString WorkspaceHandlers.createAndShow(services: services, newWindow: newWindow, window: window, room: room) { connection, terminal in guard let pane = terminal.pane else { return } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserHost/AppBrowserHostTabs.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserHost/AppBrowserHostTabs.swift index 69893970c726..8f233669ae52 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserHost/AppBrowserHostTabs.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserHost/AppBrowserHostTabs.swift @@ -136,7 +136,7 @@ final class AppBrowserHostTabs: ProviderTabSource, ProviderAccessSource, Automat /// selection or focus changes. The session owns the tab: its end closes it /// (``endSessionTab(_:)``) unless it was kept. The driver navigates it. func openAutomationTab(url: URL?) async throws -> WebKitTab { - guard let services, let browserTabs = services.cache.browserTabs, browserTabs.isAvailable() else { + guard let services, case let browserTabs = services.cache.browserTabs, browserTabs.isAvailable() else { throw AutomationTabError.unavailable } guard let pane = services.windows.active?.focusedPane, !browserTabs.isIncognitoPane(pane.pane.handle) else { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserPageRequests.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserPageRequests.swift index fab0eb475037..ef130faff35a 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserPageRequests.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserPageRequests.swift @@ -198,7 +198,7 @@ final class BrowserPageRequests: BrowserTabDelegate { child?.close() return } - let browserTabs = services.cache.browserTabs! + let browserTabs = services.cache.browserTabs let daemon = services.machines.daemon(forTab: tab) guard browserTabs.isAvailable(), daemon === services.activeDaemon, !browserTabs.isIncognitoTab(key) else { if let child { return browserTab(page, didRequest: .adoptTab(child, .foregroundTab)) } @@ -238,7 +238,7 @@ final class BrowserPageRequests: BrowserTabDelegate { return } // The opener's pane is not on screen (its page is kept alive). - let browserTabs = services.cache.browserTabs! + let browserTabs = services.cache.browserTabs guard browserTabs.isAvailable() else { child?.close(); return } let choice = Self.choice(adopting: child, inherited: engine, browserTabs: browserTabs) let handle = pane.handle, address = url?.absoluteString ?? "about:blank", openers = openers diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserProfiles/BrowserProfileService+Defaults.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserProfiles/BrowserProfileService+Defaults.swift index 8d865773e5fe..3f03b7b3e641 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserProfiles/BrowserProfileService+Defaults.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserProfiles/BrowserProfileService+Defaults.swift @@ -37,7 +37,7 @@ extension BrowserProfileService { /// The room a new tab of `workspaceID` takes its default from: the room /// of the window that shows it, else the active window's. func roomDefault(_ workspaceID: String?) -> String? { - guard let windows = services.windows else { return nil } + let windows = services.windows let owner = workspaceID.flatMap { windows.registry.value.owner(of: $0) } let room = owner.flatMap { windows.states[$0]?.profileID } ?? windows.active?.state.profileID ?? .defaultProfile return services.machines.local.store.profile(room)?.browserProfileID?.rawValue diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserProfiles/BrowserProfileService+Presentation.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserProfiles/BrowserProfileService+Presentation.swift index 23934be44a55..ac8cdf79afbe 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserProfiles/BrowserProfileService+Presentation.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserProfiles/BrowserProfileService+Presentation.swift @@ -32,7 +32,7 @@ extension BrowserProfileService { /// Re-renders every tab strip and omnibar after a profile or a default /// changed (names, colors, which tabs differ from their workspace). func refreshPresentation() { - for controller in services.windows?.controllers ?? [] { + for controller in services.windows.controllers { for pane in controller.content?.panes.values.map({ $0 }) ?? [] { pane.resyncStrip() } } for (key, entry) in services.cache.browsers { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserProfiles/BrowserProfileService+Tabs.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserProfiles/BrowserProfileService+Tabs.swift index fbe1cf9ae65a..75d229cd3e71 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserProfiles/BrowserProfileService+Tabs.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserProfiles/BrowserProfileService+Tabs.swift @@ -24,7 +24,7 @@ extension BrowserProfileService { return } // The pane is not on screen: create the tab there directly. - let browserTabs = services.cache.browserTabs! + let browserTabs = services.cache.browserTabs guard case .open(let choice) = browserTabs.resolve(requested: nil, inherited: tab.browserEngine) else { return } let handle = pane.handle services.registry.track(Task { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserProfiles/BrowserProfileService.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserProfiles/BrowserProfileService.swift index 9ab6bdbbeb80..355c9296d5c8 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserProfiles/BrowserProfileService.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/BrowserProfiles/BrowserProfileService.swift @@ -117,7 +117,7 @@ final class BrowserProfileService { /// The engine store of a tab: an incognito window's session, else the /// profile its record names (fixed at creation), else the default one. func engineProfile(forTab key: String) -> BrowserProfileID { - if let windows = services.windows, let incognito = windows.browserProfile(forWorkspace: services.workspaceID(ofTab: key)) { + if case let windows = services.windows, let incognito = windows.browserProfile(forWorkspace: services.workspaceID(ofTab: key)) { return incognito } return book.engineProfile(for: services.cache.tabModel(key)?.snapshot.browserProfileID) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Cloud/AppServices+Cloud.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Cloud/AppServices+Cloud.swift index 44027bee9fe9..e5a1a3f74aba 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Cloud/AppServices+Cloud.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Cloud/AppServices+Cloud.swift @@ -8,7 +8,7 @@ extension AppServices { /// window's machine (the local daemon, or its Cloud machine). var activeDaemon: DaemonService { if let routedDaemon { return routedDaemon } - guard let machine = windows?.active?.state.machineID else { return daemon } + guard let machine = windows.active?.state.machineID else { return daemon } // A window of a machine turned off by policy (DisabledFeatures) keeps // its blocked daemon: commands fail there, never land on this Mac. return machines.daemon(machine: machine) ?? machines.anyDaemon(machine: machine) ?? daemon @@ -25,7 +25,7 @@ extension AppServices { let signedIn = cloud.isSignedIn context.remove([.signedIn, .signedOut, .cloudWorkspace]) context.insert(signedIn ? .signedIn : .signedOut) - if signedIn, let machine = windows?.active?.state.machineID, machines.session(machine) != nil { + if signedIn, let machine = windows.active?.state.machineID, machines.session(machine) != nil { context.insert(.cloudWorkspace) } if registry.context != context { registry.context = context } @@ -34,7 +34,7 @@ extension AppServices { /// Starts Cloud and keeps the registry context current. func startCloud() -> Task { cloud.start() - let cloud = cloud!, machines = machines + let cloud = cloud, machines = machines return Task { [weak self] in var account: String? for await state in Observations({ (cloud.isSignedIn, machines.cloud.count, cloud.auth.user?.id, cloud.auth.teamID) }) { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Cloud/CloudMachineSession.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Cloud/CloudMachineSession.swift index 686959f40e5e..4338d61484a0 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Cloud/CloudMachineSession.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Cloud/CloudMachineSession.swift @@ -38,7 +38,7 @@ final class CloudMachineSession { @ObservationIgnored private var connectHop: Task? @ObservationIgnored private var disconnected = false /// Repairs an empty workspace on this machine (never on another). - @ObservationIgnored private(set) var emptyWorkspaces: EmptyWorkspaceRepair! + @ObservationIgnored let emptyWorkspaces: EmptyWorkspaceRepair convenience init(machine: CloudMachine, link: CloudMachineLink) { self.init(machine: machine, link: link, appLink: nil, localIdentity: { nil }) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Cloud/CloudService.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Cloud/CloudService.swift index f1ec2807891f..98a4cb182503 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Cloud/CloudService.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Cloud/CloudService.swift @@ -17,6 +17,9 @@ final class CloudService { @ObservationIgnored let api: CloudAPIClient @ObservationIgnored let paths: CloudPaths @ObservationIgnored private(set) var hub: CloudTunnelHub? + /// This Mac's Cloud install principal (cx-wb5.64): install tokens for the + /// credential relay; registered at sign-in, revoked at sign-out. + @ObservationIgnored let installIdentity: MacInstallIdentity @ObservationIgnored private let machines: MachineRegistry @ObservationIgnored private let binary: URL? @ObservationIgnored private var lastRefresh: ContinuousClock.Instant? @@ -41,6 +44,14 @@ final class CloudService { tokens: { try await auth.tokens() }, teamID: { await auth.teamID } ) + installIdentity = MacInstallIdentity( + store: .forApp(directory: paths.root.appendingPathComponent("install", isDirectory: true), + service: "\(configuration.bundleID ?? "cmux").install-key.\(configuration.ownerAPIBaseURL().host ?? "unknown")", + team: CodeSigningTeam.current(), isDebugBuild: configuration.isDebugBuild), + transport: InstallHTTPTransport(baseURL: configuration.ownerAPIBaseURL()), + deviceName: Self.deviceName, + clientVersion: Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String + ) binary = try? DaemonLauncher.resolveBinary(bundle: .main, environment: ProcessInfo.processInfo.environment) if let binary { hub = CloudTunnelHub(api: api, paths: paths, binary: binary, deviceName: Self.deviceName) @@ -71,6 +82,16 @@ final class CloudService { return nil } + /// Whether a Cloud API request may go out: not turned off by the + /// organization, the managed team present (P17-3), not a local-only + /// backend. (A missing cmux-tui client blocks machines, not the API.) + var mayCallCloud: Bool { + if policyDisabled { return false } + if auth.managedTeamID != nil, auth.teamID == nil { return false } + if case .localOnly = configuration.backend { return false } + return true + } + func start() { auth.start() if configuration.linkSource == .appServer, linkEvents == nil { @@ -97,8 +118,10 @@ final class CloudService { // Sign-out revoked the WireGuard peer and parked the hub. await self.hub?.resume() await self.refresh() + await self.installSignedIn() } else { self.dropAllMachines() + await self.installIdentity.unbind() } } }) @@ -134,6 +157,7 @@ final class CloudService { guard let self, auth.isSignedIn else { return } await hub?.resume() await refresh() + await installSignedIn() } } } @@ -256,6 +280,24 @@ final class CloudService { func signOut() async { dropAllMachines() if let hub { await hub.revoke() } + // Revoke the install while the Stack session still exists. + if let stackUser = auth.user?.id { + let auth = auth + await installIdentity.signOut(stackUser: stackUser, session: { try await auth.tokens().access }) + } await auth.signOut() } + + /// Registers (or reuses) this Mac's install for the signed-in user and + /// mints one token. A failure is logged: the relay mints again when it + /// needs a token, and the hub path does not depend on it. + private func installSignedIn() async { + guard let stackUser = auth.user?.id, mayCallCloud else { return } + let auth = auth + do { + try await installIdentity.signedIn(stackUser: stackUser, session: { try await auth.tokens().access }) + } catch { + logger.error("install registration failed: \(String(describing: error), privacy: .public)") + } + } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/AppControl+Cloud.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/AppControl+Cloud.swift index 72ead52aa780..83cecb9b6efd 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/AppControl+Cloud.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/AppControl+Cloud.swift @@ -9,7 +9,7 @@ extension AppControl { func registerCloudMethods(_ services: AppServices) { service?.router.register([ .mainActor("auth.status") { _ in - let cloud = services.cloud! + let cloud = services.cloud let user = cloud.auth.user return .value(.object([ "signed_in": .bool(cloud.isSignedIn), @@ -34,7 +34,7 @@ extension AppControl { case .failed(let reason): "failed: \(reason)" } let compat = services.machines.compatibility(of: session.daemon) - return .object([ + let fields: [String: JSONValue] = [ "id": .string(session.machineID), "title": .string(session.machine.title), "status": .string(session.machine.status.rawValue), @@ -49,7 +49,8 @@ extension AppControl { "missing_required": .array((compat?.missingRequired ?? []).map(JSONValue.string)), "missing_features": .array((compat?.missingOptional ?? []).map(JSONValue.string)), "workspaces": .array(store.workspaces.map { .object(["id": .string($0.id), "name": .string($0.displayName)]) }), - ]) + ] + return .object(fields) } return .value(.object(["machines": .array(rows), "last_error": services.cloud.lastError.map(JSONValue.string) ?? .null])) }, diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/AppControl.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/AppControl.swift index 3537db7397a3..fe9cac7ebae5 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/AppControl.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/AppControl.swift @@ -97,11 +97,11 @@ final class AppControl { // Window membership and the window invariants (no window // without a workspace). .mainActor("debug.windows") { [weak services] _ in - guard let services, let windows = services.windows else { return .value(.null) } + guard let services, case let windows = services.windows else { return .value(.null) } guard case .object(var report) = WindowInvariants.report(windows) else { return .value(.null) } // Every workspace the app closed or kept after it lost its // last pane, with the cause (EmptyWorkspaceRepair). - report["emptied_workspaces"] = .array((services.emptyWorkspaces?.decisions ?? []).map { + report["emptied_workspaces"] = .array(services.emptyWorkspaces.decisions.map { .object(["key": .string($0.key.rawValue), "cause": .string(String(describing: $0.cause))]) }) return .value(.object(report)) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugCEF.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugCEF.swift index cb2c4b1231e6..b2e20f7b75fa 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugCEF.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugCEF.swift @@ -19,7 +19,7 @@ enum DebugCEF { "trigger": report.trigger.map { .string($0) } ?? .null, "footprint_mb": .number(footprintMegabytes()), ] - if let browserTabs = services.cache.browserTabs { + if case let browserTabs = services.cache.browserTabs { object["default_engine"] = .string(browserTabs.preference.defaultEngine.rawValue) object["unavailable"] = unavailable(browserTabs.cefUnavailable()) let fallbacks = browserTabs.fallbacks diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugThemes.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugThemes.swift index 30e03fd909bb..4d8b9cc8076b 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugThemes.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugThemes.swift @@ -10,7 +10,7 @@ import CmuxNextTerminal /// resolved window and content backgrounds as `#RRGGBB`. enum DebugThemes { static func report(services: AppServices) -> JSONValue { - let windows = (services.windows?.controllers ?? []).map { controller -> JSONValue in + let windows = services.windows.controllers.map { controller -> JSONValue in var object = scope(controller.themeScope) object["window_number"] = .number(Double(controller.window?.windowNumber ?? 0)) object["room"] = .string(controller.state.profileID.rawValue) @@ -24,7 +24,7 @@ enum DebugThemes { }) return .object(object) } - let terminals = (services.cache?.terminals ?? [:]).sorted { $0.key < $1.key }.map { key, entry -> JSONValue in + let terminals = services.cache.terminals.sorted { $0.key < $1.key }.map { key, entry -> JSONValue in var object = scope(entry.themeScope) object["tab"] = .string(key) object["surface_theme"] = entry.session.theme.map { .string($0.themeName) } ?? .null diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugUpdater.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugUpdater.swift index bf65506ffc15..8a39005dbfcc 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugUpdater.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugUpdater.swift @@ -10,6 +10,10 @@ import CmuxNextUpdater /// release notes (UPDATE-CARD screenshots; nothing downloads or installs); /// `{action: "unstage"}` follows the real updater again. `{action: "tip", /// id?}` shows a "Did you know" tip; `{action: "untip"}` hides it. +/// `{action: "updated", previous?}` records `previous` (default "0.0.1") +/// as the last seen version, so this launch +/// shows the "cmux Updated!" card (cx-7py7); `{action: "share"}` opens the +/// Share cmux modal and `{action: "share-copy"}` presses its Copy Link. @MainActor enum DebugUpdater { static func run(_ params: [String: JSONValue], _ services: AppServices, @@ -32,11 +36,24 @@ enum DebugUpdater { case "untip": services.updater.debugShowTip(nil) return .object(["tip": .null]) + case "updated": + let previous = params["previous"]?.stringValue ?? "0.0.1" + guard services.updater.whatsNew.debugPretendUpdated(from: previous) else { + throw ControlError.invalidParams("debug.updater updated: previous must be a version older than \(services.updater.identity.shortVersion)") + } + return .object(["updatedCard": .bool(services.updater.whatsNew.showsUpdatedCard)]) + case "share": + ShareCmuxPresenter.present(services) + return .object(["shown": .bool(ShareCmuxPresenter.shown != nil)]) + case "share-copy": + guard let view = ShareCmuxPresenter.shown else { throw ControlError.invalidParams("debug.updater share-copy: the Share cmux modal is not open") } + view.copyMessage() + return .object(["copied": .string(view.messageText)]) case "unstage": services.updater.debugStage(version: nil, notes: nil) return .object(["staged": .null]) default: - throw ControlError.invalidParams("debug.updater: action must be \"relaunch\", \"stage\", \"unstage\", \"tip\" or \"untip\"") + throw ControlError.invalidParams("debug.updater: action must be \"relaunch\", \"stage\", \"unstage\", \"tip\", \"untip\", \"updated\", \"share\" or \"share-copy\"") } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Drag/TabDragSession+Commit.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Drag/TabDragSession+Commit.swift index 1a53044a8b35..58a9c9e1e648 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Drag/TabDragSession+Commit.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Drag/TabDragSession+Commit.swift @@ -35,7 +35,7 @@ extension TabDragSession { let end: @MainActor () -> Void = { [weak self] in lifecycle.settle(transaction, ok: ok) self?.commitsInFlight.remove(transaction) - self?.services.input.monitor.noteChange() + self?.services.input.monitor?.noteChange() // The view change of a landed user drop, after the echo. if ok { self?.revealLanded(drag, outcome: outcome, dropWindow: dropWindow) } } @@ -91,7 +91,7 @@ extension TabDragSession { // Made unplaced, then put at the gap by the sidebar's own path // (personal order, or move-workspace-to-group at the slot). let slot = gapSlot(drag) - Task { + Task { [services] in let key = await TabMoves.toNewWorkspace(tab, services: services, transaction: transaction) drag.landedWorkspaceID = key?.rawValue if let key, let state = dropWindow?.state { claimAndPlace(key, in: state, at: slot, select: !drag.filesAway) } @@ -103,7 +103,7 @@ extension TabDragSession { TabMoves.toWorkspace(tab, workspace: workspace, services: services, transaction: transaction, completion: settle) case .tearOff(let point): let frame = tearOffFrame(drag, at: point, size: drag.source.windowSize) - Task { + Task { [services] in let key = await TabMoves.toNewWorkspace(tab, services: services, transaction: transaction) drag.landedWorkspaceID = key?.rawValue if let key { focusTornOff(openTornOff(workspace: key, frame: frame, drag: drag), drag: drag) } @@ -137,7 +137,7 @@ extension TabDragSession { settle(false) case .newWorkspace: let slot = gapSlot(drag) - Task { + Task { [services] in let key = await TabGroupMoves.toNewWorkspace(group, workspaceGroup: nil, index: nil, services: services, transaction: transaction) drag.landedWorkspaceID = key?.rawValue if let key, let state = dropWindow?.state { claimAndPlace(key, in: state, at: slot, select: !drag.filesAway) } @@ -150,7 +150,7 @@ extension TabDragSession { TabGroupMoves.move(group, to: pane, index: pane.tabs.count, services: services, transaction: transaction, completion: settle) case .tearOff(let point): let frame = tearOffFrame(drag, at: point, size: drag.source.windowSize) - Task { + Task { [services] in let key = await TabGroupMoves.toNewWorkspace(group, workspaceGroup: nil, index: nil, services: services, transaction: transaction) drag.landedWorkspaceID = key?.rawValue if let key { focusTornOff(openTornOff(workspace: key, frame: frame, drag: drag), drag: drag) } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Drag/TabDragSession.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Drag/TabDragSession.swift index 0a7da2401a3b..c9cb0ad3dd58 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Drag/TabDragSession.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Drag/TabDragSession.swift @@ -67,7 +67,7 @@ final class TabDragSession: NSObject { let window = sourceWindow ?? services.windows.controllers.first { $0.content === pane?.workspace } var context = pane.map { Self.context(of: $0, item: item, draggedCount: draggedCount) } ?? .workspaces(count: draggedCount) if let window { context.sourceWindowWorkspaceCount = max(1, services.windows.registry.members(of: window.state.id).count) } - let content = pane?.view.bounds ?? window?.content?.layoutView?.bounds ?? .zero + let content = pane?.view.bounds ?? window?.content?.layoutView.bounds ?? .zero let aspect = content.width > 0 ? (content.height - Metrics.tabStripHeight) / content.width : nil let scale = window?.window?.backingScaleFactor ?? 2 let ghost = TabDragGhostPanel(tabImage: image, tabSize: frame.size, grabOffset: grabOffset, aspect: aspect, scale: scale) @@ -118,7 +118,7 @@ final class TabDragSession: NSObject { guard let tab else { return } let cache = services.cache Task { [weak drag] in - let image = await cache?.previewImage(for: tab, maxPixelSize: TabPreviewFitting.cachedPixelSize, captureIfMissing: true) + let image = await cache.previewImage(for: tab, maxPixelSize: TabPreviewFitting.cachedPixelSize, captureIfMissing: true) guard let drag, let image else { return } drag.ghost.setThumbnail(image) drag.motion.hasPreview = true diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Drag/TabDropTargets.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Drag/TabDropTargets.swift index 38bbc0d7a42d..52e551305a8f 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Drag/TabDropTargets.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Drag/TabDropTargets.swift @@ -116,7 +116,7 @@ final class LayoutTabDropTarget: TabDropTargetProviding { /// `ownGroup` is the group a center drop on `controller` keeps. private func proposal(screenPoint: CGPoint, dragKey: String, ownGroup: (PaneController) -> String?) -> TabDropProposal? { - guard let content = window?.content, let layout = content.layoutView, let nsWindow = layout.window, + guard let content = window?.content, case let layout = content.layoutView, let nsWindow = layout.window, !layout.bounds.isEmpty else { return nil } let local = layout.convert(nsWindow.convertPoint(fromScreen: screenPoint), from: nil) let inside = layout.bounds.insetBy(dx: 0.5, dy: 0.5) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Drag/TabMoves.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Drag/TabMoves.swift index 454a36758a78..adc62ed775a4 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Drag/TabMoves.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Drag/TabMoves.swift @@ -49,7 +49,7 @@ enum TabMoves { case .pty: return .terminal(SpawnOptions(cwd: tab.cwd, workspace: services.workspaceKey(of: pane))) case .browser: - guard tab.isFrontendOwned, let browserTabs = services.cache.browserTabs, !browserTabs.isIncognitoTab(tab.id), + guard tab.isFrontendOwned, case let browserTabs = services.cache.browserTabs, !browserTabs.isIncognitoTab(tab.id), case .open(let choice) = browserTabs.resolve(requested: nil, inherited: tab.browserEngine) else { return nil } return .browser(url: services.newTabAddress(for: choice), engine: choice.engine, profileID: tab.snapshot.browserProfileID) @@ -223,7 +223,7 @@ enum TabMoves { // A conversation or a kind this app does not know: its title still names it. case .conversation, .other: .terminal } - let offTheRecord = tab.kind == .browser && services.cache.browserTabs?.isIncognitoTab(tab.id) == true + let offTheRecord = tab.kind == .browser && services.cache.browserTabs.isIncognitoTab(tab.id) == true let pageTitle = tab.kind == .browser && !offTheRecord ? services.cache.existingBrowser(tab.id)?.tab.state.title : nil return NewWorkspaceName.Tab(kind: kind, userName: tab.name, title: tab.title, pageTitle: pageTitle, url: tab.url, cwd: tab.cwd) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Feed/FeedPageService.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Feed/FeedPageService.swift index 919ee7a0bcbc..951018040218 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Feed/FeedPageService.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Feed/FeedPageService.swift @@ -35,7 +35,7 @@ final class FeedPageService: InternalPageProvider { var icon: IconName? { .inbox } func makeView(for key: String, in window: WindowController?) -> NSView { - guard let feed = services.feed else { return NSView() } + let feed = services.feed FeedGitHubActions.install(on: feed.model, services: services) return FeedHostView(model: feed.model, layoutOverride: .inbox) } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Feed/FeedPanelController.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Feed/FeedPanelController.swift index 75f4d919df29..16ffcc4bdbae 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Feed/FeedPanelController.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Feed/FeedPanelController.swift @@ -24,7 +24,7 @@ final class FeedPanelController { } private func show() { - guard let window = context.services.windows.active?.window, let feed = context.services.feed else { return } + guard let window = context.services.windows.active?.window, case let feed = context.services.feed else { return } feed.startIfSignedIn() let panel = panel ?? makePanel(model: feed.model) self.panel = panel diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Feed/FeedService.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Feed/FeedService.swift index 32613d3456b1..5cc6200c3ada 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Feed/FeedService.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Feed/FeedService.swift @@ -32,9 +32,7 @@ final class FeedService { /// The API Worker for this build: `CMUX_NEXT_FEED_API_URL`, else staging /// for development auth and production for production auth. static func apiBaseURL(auth: CloudAuth, environment: [String: String] = ProcessInfo.processInfo.environment) -> URL { - // The override is for development only: a release build never sends its token to another origin. - if auth.configuration.isDebugBuild, let raw = environment["CMUX_NEXT_FEED_API_URL"], let url = URL(string: raw) { return url } - return URL(string: auth.configuration.isProductionAuth ? "https://cloud-api.cmux.dev" : "https://cloud-api-staging.cmux.dev")! + auth.configuration.ownerAPIBaseURL(environment: environment) } init(auth: CloudAuth, showcase: Bool = false) { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/BrowserChordTable.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/BrowserChordTable.swift index 93913bbae36d..a9c6f88c06c7 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/BrowserChordTable.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/BrowserChordTable.swift @@ -16,9 +16,9 @@ import CmuxNextActions /// consulted, so cmux keeps them. enum BrowserChordTable { private static let left = Shortcut.leftArrowKey - private static let right = String(Character(UnicodeScalar(UInt32(NSRightArrowFunctionKey))!)) - private static let pageUp = String(Character(UnicodeScalar(UInt32(NSPageUpFunctionKey))!)) - private static let pageDown = String(Character(UnicodeScalar(UInt32(NSPageDownFunctionKey))!)) + private static let right = Shortcut.rightArrowKey + private static let pageUp = FunctionKeyCharacter.string(NSPageUpFunctionKey) + private static let pageDown = FunctionKeyCharacter.string(NSPageDownFunctionKey) /// The standard browser shortcuts on macOS, limited to Command and /// Control chords. diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/DebugKey.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/DebugKey.swift index 1b6943ac6177..9357cf12b70d 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/DebugKey.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/DebugKey.swift @@ -21,11 +21,11 @@ enum DebugKey { private static let named: [String: (characters: String, keyCode: UInt16)] = [ "return": ("\r", 36), "escape": ("\u{1b}", 53), "tab": ("\t", 48), "d": ("d", 2), "c": ("c", 8), "v": ("v", 9), "l": ("l", 37), "w": ("w", 13), "t": ("t", 17), "h": ("h", 4), "j": ("j", 38), "k": ("k", 40), - "left": (String(UnicodeScalar(NSLeftArrowFunctionKey)!), 123), "right": (String(UnicodeScalar(NSRightArrowFunctionKey)!), 124), - "down": (String(UnicodeScalar(NSDownArrowFunctionKey)!), 125), "up": (String(UnicodeScalar(NSUpArrowFunctionKey)!), 126), - "pageup": (String(UnicodeScalar(NSPageUpFunctionKey)!), 116), "pagedown": (String(UnicodeScalar(NSPageDownFunctionKey)!), 121), - "home": (String(UnicodeScalar(NSHomeFunctionKey)!), 115), "end": (String(UnicodeScalar(NSEndFunctionKey)!), 119), - "delete": ("\u{7f}", 51), "forwarddelete": (String(UnicodeScalar(NSDeleteFunctionKey)!), 117), "a": ("a", 0), "n": ("n", 45), "b": ("b", 11), + "left": (Shortcut.leftArrowKey, 123), "right": (Shortcut.rightArrowKey, 124), + "down": (Shortcut.downArrowKey, 125), "up": (Shortcut.upArrowKey, 126), + "pageup": (FunctionKeyCharacter.string(NSPageUpFunctionKey), 116), "pagedown": (FunctionKeyCharacter.string(NSPageDownFunctionKey), 121), + "home": (FunctionKeyCharacter.string(NSHomeFunctionKey), 115), "end": (FunctionKeyCharacter.string(NSEndFunctionKey), 119), + "delete": ("\u{7f}", 51), "forwarddelete": (FunctionKeyCharacter.string(NSDeleteFunctionKey), 117), "a": ("a", 0), "n": ("n", 45), "b": ("b", 11), ] /// ANSI virtual key codes, so Chromium accelerators (extension commands @@ -116,7 +116,7 @@ enum DebugKey { if params["target"]?.stringValue == "palette" { // The palette's own report: open or closed, its page, a refusal // notice, and key-downs that reached the system beep. - let palette = services.palette! + let palette = services.palette return .object([ // With no main window the palette is the dispatch's only window. "handled_by": .string(handledBy == "page" || (controller == nil && ["window", "responder"].contains(handledBy)) ? "palette" : handledBy), diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/DebugPaletteCapture.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/DebugPaletteCapture.swift index 1c39dfd22cc6..41184372605f 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/DebugPaletteCapture.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/DebugPaletteCapture.swift @@ -23,7 +23,7 @@ enum DebugPaletteCapture { let size = view.bounds.size let scale = panel.backingScaleFactor guard let context = CGContext(data: nil, width: Int(size.width * scale), height: Int(size.height * scale), bitsPerComponent: 8, - bytesPerRow: 0, space: CGColorSpace(name: CGColorSpace.sRGB)!, + bytesPerRow: 0, space: CGColorSpace(name: CGColorSpace.sRGB) ?? CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return .object(["error": .string("no bitmap context")]) } context.scaleBy(x: scale, y: scale) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/FocusEffectApplier.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/FocusEffectApplier.swift index 02ab7c23b7c1..4f42d0968aa2 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/FocusEffectApplier.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/FocusEffectApplier.swift @@ -369,7 +369,7 @@ final class FocusEffectApplier: FocusEffectApplying { if context.agent { next.insert(.agentPaneFocused) } if case .addressBar = controller.focus.state.resolved { next.insert(.omnibarFocused) } // The same rule as `KeyRouter.keyContext`: the focused page's id (diff, markdown, code editor). - switch services.keyRouter?.focusedPage(in: controller)?.descriptor.id { + switch services.keyRouter.focusedPage(in: controller)?.descriptor.id { case KeyRouter.diffPageID?: next.insert(.diffViewerFocused) case KeyRouter.markdownPageID?: next.insert(.markdownFocused) case KeyRouter.codeEditorPageID?: next.insert(.codeEditorFocused) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/FunctionKeyCharacter.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/FunctionKeyCharacter.swift new file mode 100644 index 000000000000..28a83c37dd1c --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/FunctionKeyCharacter.swift @@ -0,0 +1,11 @@ +import AppKit + +/// The key-equivalent character of an AppKit function key (`NSPageUpFunctionKey` +/// and the others are Unicode private-use scalars, U+F700 and up). Never traps: +/// a code that is not a scalar gives "" (FunctionKeyCharacterTests checks +/// every code the app uses). +nonisolated enum FunctionKeyCharacter { + static func string(_ code: Int) -> String { + UInt32(exactly: code).flatMap { Unicode.Scalar($0) }.map { String(Character($0)) } ?? "" + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/Keybindings/KeybindingControl.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/Keybindings/KeybindingControl.swift index f2658751976a..cec8b4c94cc0 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/Keybindings/KeybindingControl.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/Keybindings/KeybindingControl.swift @@ -45,7 +45,7 @@ enum KeybindingControl { } else { controller = controllers.first { $0.window?.isKeyWindow == true } ?? controllers.first } - guard let controller, let window = controller.window, let router = services.keyRouter else { + guard let controller, let window = controller.window, case let router = services.keyRouter else { return (KeyContext(bits: services.registry.context), nil) } return (router.keyContext(for: controller.focus.state, facts: router.facts(in: window, controller: controller)), controller.state.id) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/WindowKeyTable.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/WindowKeyTable.swift index 166e47f0eff3..e52323e87215 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/WindowKeyTable.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Focus/WindowKeyTable.swift @@ -106,6 +106,6 @@ extension AppServices { /// The key window's role (`KeyWindowRole.resolve`). var keyWindowRole: KeyWindowRole? { guard let key = keyWindowSource() else { return nil } - return KeyWindowRole.resolve(key, ownedByMain: windows.owner(of: key) != nil, isPalette: palette?.owns(key) == true) + return KeyWindowRole.resolve(key, ownedByMain: windows.owner(of: key) != nil, isPalette: palette.owns(key) == true) } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/FrameBatcher.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/FrameBatcher.swift index e039cab08c66..8df93580ccf8 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/FrameBatcher.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/FrameBatcher.swift @@ -13,13 +13,18 @@ import CmuxNextWakeups @MainActor final class FrameBatcher: FrameBatchScheduler, ControlFrameSource { private var pending: [@MainActor @Sendable () -> Void] = [] - private var client: FrameClient! + private let owner: String + private let scheduler: FrameScheduler + /// Built in init (lazy because its callback captures self; no IUO). + private lazy var client = FrameClient(owner: owner, isAnimation: false, on: scheduler) { [weak self] _ in + self?.drain() ?? false + } /// `owner` names the batcher in the wakeup ledger and debug.wakeups. init(owner: String, scheduler: FrameScheduler = .app) { - client = FrameClient(owner: owner, isAnimation: false, on: scheduler) { [weak self] _ in - self?.drain() ?? false - } + self.owner = owner + self.scheduler = scheduler + _ = client // built here, as before } /// Hops through the main run loop in the common modes, not a main-actor diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/AgentHandlers.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/AgentHandlers.swift index 3f07507fad2d..5d5b4c607cc2 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/AgentHandlers.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/AgentHandlers.swift @@ -235,7 +235,7 @@ enum AgentHandlers { let options = SpawnOptions(cwd: tab.cwd, workspace: context.services.workspaceKey(of: pane.pane)) let line = command + "\n" let logger = context.daemon.logger - let repair = context.services.emptyWorkspaces! + let repair = context.services.emptyWorkspaces Task { do { let surface: SurfaceID? diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/AgentSessionWorkspace.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/AgentSessionWorkspace.swift index ce83083dc2fc..dba9daf3f9bb 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/AgentSessionWorkspace.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/AgentSessionWorkspace.swift @@ -28,7 +28,7 @@ enum AgentSessionWorkspace { guard !session.isEmpty else { throw ActionFailure(message: MiscHandlerStrings.sessionRequired) } guard services.agentTabs.canHostChat else { throw ActionFailure(message: MiscHandlerStrings.quickChatUnavailable) } let daemon = services.daemon - guard let connection = daemon.connection, let repair = services.emptyWorkspaces else { + guard let connection = daemon.connection, case let repair = services.emptyWorkspaces else { throw ActionFailure(message: MiscHandlerStrings.daemonOffline) } let name = invocation["name"]?.stringValue.flatMap { $0.isEmpty ? nil : $0 } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/BrowserHandlers.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/BrowserHandlers.swift index d473f94d45d1..3f87d92455d8 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/BrowserHandlers.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/BrowserHandlers.swift @@ -97,7 +97,7 @@ enum BrowserHandlers { context: AppActionContext) throws { let handle = pane.pane.handle let connection = try context.requireConnection() - let browserTabs = context.services.cache.browserTabs! + let browserTabs = context.services.cache.browserTabs // The default engine (never refused: no engine is requested). guard case .open(let choice) = browserTabs.resolve(requested: nil) else { return } let intent = pane.workspace?.beginFocusIntent() diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/BrowserProfileOpenHandlers.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/BrowserProfileOpenHandlers.swift index 6e1e41c8bed8..eff7b702e58a 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/BrowserProfileOpenHandlers.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/BrowserProfileOpenHandlers.swift @@ -28,7 +28,7 @@ enum BrowserProfileOpenHandlers { } bind("browserProfile.newWindow") { invocation in let record = try context.requiredBrowserProfile(invocation) - let windows = context.services.windows! + let windows = context.services.windows let windowID = UUID().uuidString.lowercased() var spawn = WorkspaceSpawn() spawn.browserProfile = record.id @@ -36,7 +36,7 @@ enum BrowserProfileOpenHandlers { } bind("browserProfile.newWorkspace") { invocation in let record = try context.requiredBrowserProfile(invocation) - let windows = context.services.windows! + let windows = context.services.windows let target = windows.targetWindow(preferring: windows.active?.state.id) var spawn = WorkspaceSpawn() spawn.browserProfile = record.id diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/ChiefInspectorHandlers.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/ChiefInspectorHandlers.swift index d5eb58474837..f9019c5f5f8b 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/ChiefInspectorHandlers.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/ChiefInspectorHandlers.swift @@ -93,7 +93,7 @@ enum ChiefInspectorHandlers { private static func openInNewColumn(_ url: URL, anchor: PaneModel, context: AppActionContext) async throws { let handle = anchor.handle let connection = try context.requireConnection() - guard let browserTabs = context.services.cache.browserTabs, + guard case let browserTabs = context.services.cache.browserTabs, case .open(let choice) = browserTabs.resolve(requested: nil) else { throw ActionWorkFailure(MiscHandlerStrings.noBrowser) } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/CloudHandlers+Account.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/CloudHandlers+Account.swift index 1fdc6f076cd7..d866b87e2c3b 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/CloudHandlers+Account.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/CloudHandlers+Account.swift @@ -7,7 +7,7 @@ import CmuxNextDaemon // and diagnostics. extension CloudHandlers { static func bindCreation(into registry: ActionRegistry, context: AppActionContext, reason: @escaping @MainActor () -> String?) { - let cloud = context.services.cloud! + let cloud = context.services.cloud bind("newCloudMachine", registry, reason: reason) { _ in run("new cloud machine", context) { let session = try await cloud.createMachine(name: nil) @@ -30,7 +30,7 @@ extension CloudHandlers { } static func bindAccount(into registry: ActionRegistry, context: AppActionContext, reason: @escaping @MainActor () -> String?) { - let cloud = context.services.cloud! + let cloud = context.services.cloud bind("palette.auth.signIn", registry, reason: reason) { _ in guard !cloud.isSignedIn else { throw ActionFailure(message: CloudStrings.alreadySignedIn) } run("sign in", context) { _ = await cloud.auth.signIn() } @@ -78,7 +78,7 @@ extension CloudHandlers { /// Account, backend, tunnel, and per-machine link state. No secrets. static func diagnostics(_ context: AppActionContext) async -> String { - let cloud = context.services.cloud! + let cloud = context.services.cloud var lines = [ "backend: \(cloud.configuration.apiBaseURL.absoluteString) (\(cloud.configuration.backend))", "signed in: \(cloud.isSignedIn)" + (cloud.auth.user?.primaryEmail.map { " as \($0)" } ?? ""), diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/CloudHandlers+Domains.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/CloudHandlers+Domains.swift index a62b88fb226a..2633b949429f 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/CloudHandlers+Domains.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/CloudHandlers+Domains.swift @@ -4,7 +4,7 @@ import CmuxNextCloud extension CloudHandlers { static func bindDomainActions(into registry: ActionRegistry, context: AppActionContext, reason: @escaping @MainActor () -> String?) { - guard let cloud = context.services.cloud else { return } + let cloud = context.services.cloud bind("cloudDomainList", registry, reason: reason) { _ in runTracked("list Cloud domains", context) { let domains = try await cloud.api.listDomains() diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/CloudHandlers+Machine.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/CloudHandlers+Machine.swift index 78dbf4fc4a5b..70eef41deefe 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/CloudHandlers+Machine.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/CloudHandlers+Machine.swift @@ -8,7 +8,7 @@ import CmuxNextDaemon // restore, fork, and snapshot deletion. extension CloudHandlers { static func bindMachineActions(into registry: ActionRegistry, context: AppActionContext, reason: @escaping @MainActor () -> String?) { - let cloud = context.services.cloud! + let cloud = context.services.cloud bind("cloudOpenMachine", registry, reason: reason) { invocation in let session = try machine(invocation, context) // An app link waits for the user after it ended: opening the diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/CloudHandlers+Network.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/CloudHandlers+Network.swift index 074af5e5bddf..6494e1225404 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/CloudHandlers+Network.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/CloudHandlers+Network.swift @@ -4,7 +4,7 @@ import CmuxNextCloud extension CloudHandlers { static func bindNetworkActions(into registry: ActionRegistry, context: AppActionContext, reason: @escaping @MainActor () -> String?) { - let cloud = context.services.cloud! + let cloud = context.services.cloud bind("cloudTunnelAttach", registry, reason: reason) { invocation in let networkID = try networkArgument(invocation) runTracked("attach Cloud tunnel network", context) { try await cloud.api.attachTunnelNetwork(deviceFingerprint: cloud.localDeviceID(), networkID: networkID) } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/CloudHandlers.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/CloudHandlers.swift index 06bd20ed4f0c..ac84bbec427c 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/CloudHandlers.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/CloudHandlers.swift @@ -11,7 +11,7 @@ import CmuxNextDaemon /// as a sheet (and in the log), refusals reach the control socket. enum CloudHandlers { static func bind(into registry: ActionRegistry, context: AppActionContext) { - let cloud = context.services.cloud! + let cloud = context.services.cloud let reason: @MainActor () -> String? = { cloud.unavailableReason } let signedInReason: @MainActor () -> String? = { cloud.unavailableReason ?? (cloud.isSignedIn ? nil : CloudStrings.signInFirst) } bindMachineActions(into: registry, context: context, reason: signedInReason) @@ -88,7 +88,7 @@ enum CloudHandlers { /// Shows `workspaceID` in the active window (or a new one). static func show(_ workspaceID: String, _ context: AppActionContext) { - let windows = context.services.windows! + let windows = context.services.windows if let state = windows.active?.state { windows.show(workspaceID: workspaceID, in: state) } else { windows.openWindow(workspaces: [workspaceID]) } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/IconHistory.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/IconHistory.swift index 2c725a71579e..9b81aaa52e0c 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/IconHistory.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/IconHistory.swift @@ -43,7 +43,7 @@ struct IconHistory { /// picker panel, key while it closes, is never a toast's window). static func inActiveWindow(_ ctx: AppActionContext, apply: @escaping @MainActor (String, FieldUpdate) throws -> Bool) -> Self { IconHistory(apply: apply, offerUndo: { message, undo in - guard let window = ctx.services.windows?.active?.window ?? NSApp.mainWindow else { return } + guard let window = ctx.services.windows.active?.window ?? NSApp.mainWindow else { return } let handle = CmuxToastCenter.shared.show(CmuxToast(id: undoToastID, message: message, action: .undo()), in: window) handle.onAction = { undo() } }) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/PageCommandHandlers.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/PageCommandHandlers.swift index 263df80fc863..eb73511e7fcc 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/PageCommandHandlers.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/PageCommandHandlers.swift @@ -11,7 +11,7 @@ enum PageCommandHandlers { let services = context.services for (action, command) in MarkdownPageCommand.forAction { registry.bind(ActionID(rawValue: action), run: { _ in - guard let controller = services.windows.active, let router = services.keyRouter, + guard let controller = services.windows.active, case let router = services.keyRouter, let page = router.focusedPage(in: controller), page.descriptor.commands.contains(command), page.send(command: command) else { throw ActionFailure(message: FilePageStrings.noFilePage) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/RemoteHandlers.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/RemoteHandlers.swift index b025cb00c4be..c647fb3fe62b 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/RemoteHandlers.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/RemoteHandlers.swift @@ -11,7 +11,7 @@ import CmuxNextRemote /// refusal on the control socket. enum RemoteHandlers { static func bind(into registry: ActionRegistry, context: AppActionContext) { - let ssh = context.services.ssh! + let ssh = context.services.ssh let available: @MainActor () -> String? = { ssh.unavailableReason } let hasMachine: @MainActor () -> String? = { ssh.unavailableReason ?? (ssh.sessions.isEmpty ? RemoteStrings.noMachine : nil) } ssh.offerInstall = { [weak registry] session in diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/ResourceHandlers.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/ResourceHandlers.swift index e1335e8ec0e0..2ec8cd8e1283 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/ResourceHandlers.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/ResourceHandlers.swift @@ -17,7 +17,7 @@ enum ResourceHandlers { registry.bind("workspace.showResources", run: { invocation in let (workspace, _) = try ctx.workspace(invocation) // Each window's sidebar lists only its own workspaces. - let manager = ctx.services.windows! + let manager = ctx.services.windows let lists = { (window: WindowController) in manager.registry.members(of: window.state.id).contains(workspace.id) } let window = manager.active.flatMap { lists($0) ? $0 : nil } ?? manager.controllers.first(where: lists) guard let window, window.sidebar.container.sidebarView.showHoverCard(for: SidebarWorkspaceID(workspace.id)) else { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/RoomHandlers.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/RoomHandlers.swift index 90f23bfb0545..6f0515dabcf5 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/RoomHandlers.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/RoomHandlers.swift @@ -19,14 +19,14 @@ enum RoomHandlers { bind("space.new") { try create(invocation: $0, context) } bind("space.newWindow") { invocation in let room = try context.room(invocation) - let windows = context.services.windows! + let windows = context.services.windows let windowID = UUID().uuidString.lowercased() windows.state(for: windowID).enterProfile(room.id) Task { await windows.createWorkspace(into: windowID, newTabPage: invocation.origin == .user) } } bind("space.newWorkspace") { invocation in let room = try context.room(invocation) - let windows = context.services.windows! + let windows = context.services.windows let target = windows.targetWindow(preferring: windows.active?.state.id) var spawn = WorkspaceSpawn(profile: room.id) spawn.opensNewTabPage = invocation.origin == .user @@ -133,8 +133,11 @@ enum RoomHandlers { RoomMoveHandlers.bind(bind, context: context) } - /// A new space with the next free color; the active window enters it - /// (`enter`, else a switch that opens a new terminal workspace there). + /// A new space with the next free color and its own first workspace. + /// One path for the palette, menu, keyboard, CLI, `action.run` and the + /// strip's New Space button: `enter` (Open Link in New Space) or + /// `startNewSpace`, which shows the space only when the + /// run may change the view. static func create(invocation: ActionInvocation, _ context: AppActionContext, action: ActionID = "space.new", enter: (@MainActor @Sendable (ProfileID, WindowState) -> Void)? = nil) throws { let store = context.services.machines.local.store @@ -158,8 +161,10 @@ enum RoomHandlers { // files the new workspace unpinned (so in `default`) and // the window falls back as from a deleted room (cx-d8x5). await services.machines.local.store.mirrored(profile: id) - if let active, let state = services.windows.states[active.id] { - if let enter { enter(id, state) } else { services.windows.switchProfile(id, in: state) } + if let enter, let active, let state = services.windows.states[active.id] { + enter(id, state) + } else { + try await startNewSpace(id, from: active?.id, windows: services.windows) } return nil } catch { @@ -168,6 +173,28 @@ enum RoomHandlers { }) } + /// Gives the new, empty space `profile` its first workspace. A run that + /// may change the view shows the space in window `windowID` + /// (`switchProfile`, which creates the workspace there). Any other run + /// (a script, the CLI without `focus`) files the workspace, pinned to + /// `profile`, into that window without showing it: the window stays in + /// its space, which never lists the new workspace (cx-f8aw). With no + /// open window, a new window opens in the space (behind for a run + /// without view permission). + private static func startNewSpace(_ profile: ProfileID, from windowID: String?, windows: WindowManager) async throws { + if let windowID, let state = windows.states[windowID], windows.registry.value.window(windowID)?.isOpen == true { + if ActionRunScope.viewChangeAllowed() { + windows.switchProfile(profile, in: state) + } else { + _ = try await windows.createWorkspace(WorkspaceSpawn(profile: profile), into: windowID) + } + return + } + let newWindow = UUID().uuidString.lowercased() + windows.state(for: newWindow).enterProfile(profile) + _ = try await windows.createWorkspace(WorkspaceSpawn(profile: profile), into: newWindow) + } + private static func move(invocation: ActionInvocation, by delta: Int, _ context: AppActionContext) throws { let room = try context.room(invocation) let order = context.services.machines.local.store.profileIDs diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/RoomMoveHandlers.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/RoomMoveHandlers.swift index 92f66bb56ab8..a1f5be1fe9af 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/RoomMoveHandlers.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/RoomMoveHandlers.swift @@ -60,7 +60,7 @@ enum RoomMoveHandlers { /// duplicate never shares a running terminal. It is shown in the active /// window, which switches to `room`. private static func duplicate(_ workspace: WorkspaceModel, into room: ProfileID, _ context: AppActionContext) { - let windows = context.services.windows! + let windows = context.services.windows let directories = terminalDirectories(of: workspace) let target = windows.targetWindow(preferring: windows.active?.state.id) let spawn = WorkspaceSpawn(cwd: directories.first ?? nil, name: workspace.displayName, profile: room) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/SettingsHandlers.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/SettingsHandlers.swift index 8ee433b7ba55..05bec580d2d1 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/SettingsHandlers.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/SettingsHandlers.swift @@ -29,9 +29,10 @@ enum SettingsHandlers { registry.bind("palette.toggleSetting", run: { invocation in try toggleSetting(invocation, context) }) registry.bind("browser.defaultEngine.chromium", run: { _ in try setDefaultEngine(.chromium, context) }) registry.bind("browser.defaultEngine.webkit", run: { _ in try setDefaultEngine(.webkit, context) }) - registry.bind("sendFeedback", run: { _ in try context.open(URL(string: "https://github.com/manaflow-ai/cmux/issues/new")!) }) + registry.bind("sendFeedback", run: { _ in try context.open(StaticURL.feedback.url) }) registry.bind("help.showCrashLogs", run: { _ in context.services.crashRecovery.showCrashLogs() }) registry.bind("help.documentation", run: { invocation in try context.open(documentationURL(topic: invocation["topic"]?.stringValue)) }) + registry.bind("app.shareCmux", run: { [weak services = context.services] _ in services.map(ShareCmuxPresenter.present) }) UpdateHandlers.bind(into: registry, updater: context.services.updater, openWhatsNew: { [weak services = context.services] in services.map { WhatsNewPage.open($0) } ?? false }) OnboardingHandlers.bind(into: registry, context: context) @@ -116,7 +117,7 @@ enum SettingsHandlers { /// then writes cmux-next.json; the watcher reapplies the same value. private static func setDefaultEngine(_ engine: BrowserDefaultEngine, _ context: AppActionContext) throws { try AppearanceHandlers.requireUnmanaged(BrowserDefaultEngine.configPath, context) - context.services.cache.browserTabs?.preference.defaultEngine = engine + context.services.cache.browserTabs.preference.defaultEngine = engine if engine == .chromium { context.services.chromiumWarmup.chromiumLikely(.defaultEngine) } guard let settings = context.services.settings else { return } Task { @@ -127,7 +128,7 @@ enum SettingsHandlers { } static func documentationURL(topic: String?) -> URL { - var url = URL(string: "https://cmux.com/docs")! + var url = StaticURL.documentation.url let allowed = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-_/")) if let topic = topic?.trimmingCharacters(in: CharacterSet(charactersIn: "/ ")), !topic.isEmpty, topic.unicodeScalars.allSatisfy(allowed.contains) { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TabGroupHandlers+Moves.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TabGroupHandlers+Moves.swift index efbe900deacd..7d0513af1706 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TabGroupHandlers+Moves.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TabGroupHandlers+Moves.swift @@ -61,7 +61,7 @@ extension TabGroupHandlers { private static func moveToNewWorkspace(_ invocation: ActionInvocation, newWindow: Bool, _ ctx: AppActionContext) { guard let (group, pane) = group(invocation, ctx), connection(for: pane, ctx) != nil else { return } - let windows = ctx.services.windows! + let windows = ctx.services.windows let origin = windows.moveOrigin(of: ctx.services.workspaceID(of: pane)) Task { guard let key = await TabGroupMoves.toNewWorkspace(group, workspaceGroup: nil, index: nil, services: ctx.services, diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TabHandlers+More.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TabHandlers+More.swift index e3faf4c20b9e..a35e0318b3cb 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TabHandlers+More.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TabHandlers+More.swift @@ -39,7 +39,7 @@ extension TabHandlers { }) registry.bind("palette.moveTabToNewWorkspace", invoke: { invocation in guard let (tab, _) = ctx.daemonTab(invocation), ctx.connection() != nil else { return } - let windows = ctx.services.windows! + let windows = ctx.services.windows let origin = windows.moveOrigin(of: ctx.services.workspaceID(ofTab: tab.id)) // Read before the await: whether this run may change the view, // and the window it acts in. @@ -57,7 +57,7 @@ extension TabHandlers { }) registry.bind("tab.moveToNewWindow", invoke: { invocation in guard let (tab, _) = ctx.daemonTab(invocation), ctx.connection() != nil else { return } - let windows = ctx.services.windows! + let windows = ctx.services.windows let origin = windows.moveOrigin(of: ctx.services.workspaceID(ofTab: tab.id)) // Read before the await: a run this client's user did not start // opens the window behind, never key. diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TabHandlers.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TabHandlers.swift index eb24c5e588c3..64de1067b23a 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TabHandlers.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TabHandlers.swift @@ -27,7 +27,7 @@ enum TabHandlers { registry.bind(NewTabPage.focusLocation, invoke: { ctx.paneController($0)?.focusLocation($0) }) registry.bind("openBrowser", invoke: { TabLifecycle.newBrowser(ctx, $0) }) registry.bind("openBrowser.webkit", invoke: { TabLifecycle.newBrowser(ctx, $0, engine: .webkit) }) - let chromiumReason: @MainActor () -> String? = { ctx.services.cache.browserTabs?.cefUnavailableReason() } + let chromiumReason: @MainActor () -> String? = { ctx.services.cache.browserTabs.cefUnavailableReason() } registry.bind("openBrowser.chromium", unavailable: chromiumReason, invoke: { TabLifecycle.newBrowser(ctx, $0, engine: .cef) }) registry.bind("browser.openInChromium", unavailable: chromiumReason, invoke: { TabLifecycle.reopen(ctx, $0, on: .cef) }) registry.bind("browser.openInWebKit", invoke: { TabLifecycle.reopen(ctx, $0, on: .webkit) }) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TabIconHandlers.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TabIconHandlers.swift index 027f9a37607b..7984573e20d2 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TabIconHandlers.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TabIconHandlers.swift @@ -75,7 +75,7 @@ enum TabIconHandlers { return true }, offerUndo: { message, undo in let windows = ctx.services.windows - guard let window = shownIn.window ?? windows?.active?.window ?? NSApp.mainWindow else { return } + guard let window = shownIn.window ?? windows.active?.window ?? NSApp.mainWindow else { return } let handle = CmuxToastCenter.shared.show(CmuxToast(id: undoToastID, message: message, action: .undo()), in: window) handle.onAction = { undo() } }) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TabLifecycle.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TabLifecycle.swift index 4e99c1dc6e6c..c9b4076f26dc 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TabLifecycle.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TabLifecycle.swift @@ -20,7 +20,7 @@ enum TabLifecycle { toggled: invocation["toggleWorkspace"]?.boolValue == true ) noteUserChoice(.terminal, ctx, invocation, pane: focused) - if invocation.origin == .user, opensWorkspace, let windows = ctx.services.windows, + if invocation.origin == .user, opensWorkspace, case let windows = ctx.services.windows, let windowID = ctx.activeWindow?.state.id { let daemon = ctx.services.daemon(for: focused) let start = cwd ?? ctx.services.paneController(for: focused)?.selectedTab?.cwd ?? focused.tabs.first?.cwd @@ -162,7 +162,7 @@ enum TabLifecycle { if engine == .webkit, ctx.services.cache.pageRequests.proxiedTabs.isProxied(tab.id) { return ctx.refuse(RefusalStrings.proxiedTabStaysInChromium) } - if engine == .cef, let reason = ctx.services.cache.browserTabs?.cefUnavailableReason() { + if engine == .cef, let reason = ctx.services.cache.browserTabs.cefUnavailableReason() { return ctx.refuse(reason) } let live = ctx.services.cache.existingBrowser(tab.id)?.tab.state.url @@ -210,7 +210,7 @@ enum TabLifecycle { pane = invoked } // A refused engine is not remembered, or Auto would repeat the refusal on every Cmd-T in the folder. - if case .open? = ctx.services.cache.browserTabs?.resolve(requested: engine) { + if case .open = ctx.services.cache.browserTabs.resolve(requested: engine) { noteUserChoice(.browser(engine: plan.recordedEngine), ctx, invocation, pane: pane) } if docked { return } @@ -253,7 +253,7 @@ enum TabLifecycle { else { controller.newBrowserTab(url: url, engine: engine, then: then) } return } - let browserTabs = ctx.services.cache.browserTabs! + let browserTabs = ctx.services.cache.browserTabs guard browserTabs.isAvailable() else { return ctx.refuse(RefusalStrings.needsDaemonCapability(DaemonCapabilities.shared.frontendBrowserTabs)) } let choice: BrowserEngineChoice switch browserTabs.resolve(requested: engine) { @@ -278,7 +278,7 @@ enum TabLifecycle { /// frontend tab on the resolved engine, else nil (the chat stays). private static func chatRespawn(_ ctx: AppActionContext, url: URL?, engine: String?, profile: AgentBrowserProfile.Request) -> SplitRespawn? { - guard let browserTabs = ctx.services.cache.browserTabs, browserTabs.isAvailable(), + guard case let browserTabs = ctx.services.cache.browserTabs, browserTabs.isAvailable(), case .open(let choice) = browserTabs.resolve(requested: engine) else { return nil } var profileID: String? if case .explicit(let id) = profile { profileID = id } @@ -294,7 +294,7 @@ enum TabLifecycle { controller.newBrowserTab(url: url, engine: engine, profile: profile, then: agentTab) return } - guard let browserTabs = ctx.services.cache.browserTabs, browserTabs.isAvailable() else { + guard case let browserTabs = ctx.services.cache.browserTabs, browserTabs.isAvailable() else { return ctx.refuse(RefusalStrings.needsDaemonCapability(DaemonCapabilities.shared.frontendBrowserTabs)) } let choice: BrowserEngineChoice diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TerminalHandlers+Input.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TerminalHandlers+Input.swift index 7eaf018ad0c4..a94178a64d8d 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TerminalHandlers+Input.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/TerminalHandlers+Input.swift @@ -14,7 +14,7 @@ extension TerminalHandlers { // Keyboard Shortcuts, Passwords) focuses and selects that field. // An untargeted run that may change the view (Cmd-F, the palette); a CLI run names its pane. if invocation.target == nil, invocation.allowsViewChange, let controller = ctx.services.windows.active, - let page = ctx.services.keyRouter?.focusedPage(in: controller), + let page = ctx.services.keyRouter.focusedPage(in: controller), page.descriptor.ownsSearchField, page.send(command: "focusSearch") { return } guard let (pane, content) = ctx.visibleContent(invocation) else { return } if case .page = content, let key = pane.stripModel.selectedID?.rawValue, diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/WorkspaceGroupHandlers.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/WorkspaceGroupHandlers.swift index 6e300138ea1c..20188b616ab6 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/WorkspaceGroupHandlers.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/WorkspaceGroupHandlers.swift @@ -128,7 +128,7 @@ enum WorkspaceGroupHandlers { /// New workspace in the window's room, then into personal group `id`. private static func newPersonalWorkspace(in id: WorkspaceGroupID, newTabPage: Bool, _ context: AppActionContext) { - let windows = context.services.windows! + let windows = context.services.windows let target = windows.targetWindow(preferring: windows.active?.state.id) let local = context.services.machines.local Task { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/WorkspaceHandlers.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/WorkspaceHandlers.swift index 9457faf93857..ceeba7767045 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/WorkspaceHandlers.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/WorkspaceHandlers.swift @@ -59,7 +59,7 @@ enum WorkspaceHandlers { newWindow: Bool = false, window: String? = nil, room: ProfileID? = nil, then configure: (@Sendable (DaemonConnection, CreateTerminalResult) async throws -> Void)? = nil) { let daemon = services.activeDaemon - let windows = services.windows! + let windows = services.windows // Claimed before the create command, so the workspace lands in (or // opens) its window in the step that first mirrors it. let target = windows.targetWindow(preferring: newWindow ? nil : window ?? windows.active?.state.id) @@ -116,7 +116,7 @@ enum WorkspaceHandlers { /// A workspace whose only tab is a blank browser tab. private static func newBrowserWorkspace(_ context: AppActionContext) throws { try context.require(DaemonCapabilities.shared.frontendBrowserTabs) - let browserTabs = context.services.cache.browserTabs! + let browserTabs = context.services.cache.browserTabs guard case .open(let choice) = browserTabs.resolve(requested: nil) else { return } let fallbacks = browserTabs.fallbacks let address = context.services.newTabAddress(for: choice) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/WorkspaceStructureHandlers.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/WorkspaceStructureHandlers.swift index 00c29a711a8f..0c12f9066dba 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/WorkspaceStructureHandlers.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/WorkspaceStructureHandlers.swift @@ -58,14 +58,15 @@ enum WorkspaceStructureHandlers { let withBrowsers = browsers && daemon.supports(DaemonCapabilities.shared.frontendBrowserTabs) var blueprint = WorkspaceBlueprint(workspace) if !withBrowsers { blueprint = blueprint.withoutBrowserTabs(fallbackDirectory: WorkspaceVerbHandlers.directory(of: workspace, context)) } - let windows = context.services.windows! + let windows = context.services.windows let target = windows.targetWindow(preferring: windows.registry.value.owner(of: workspace.id) ?? context.activeWindow?.state.id) var spawn = WorkspaceSpawn(cwd: firstLeafDirectory(blueprint), name: workspace.displayName) spawn.slot = .below(workspace.id) - let engine: BrowserEngine = context.services.cache.browserTabs.map { tabs in - if case .open(let choice) = tabs.resolve(requested: nil) { return choice.engine } - return .webkit - } ?? .webkit + let engine: BrowserEngine = if case .open(let choice) = context.services.cache.browserTabs.resolve(requested: nil) { + choice.engine + } else { + .webkit + } let metadata = daemon.supports(DaemonCapabilities.shared.workspaceMetadata) context.services.registry.track(Task { do { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/WorkspaceVerbHandlers.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/WorkspaceVerbHandlers.swift index 91849d44af9f..1d05ecce059c 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/WorkspaceVerbHandlers.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Handlers/WorkspaceVerbHandlers.swift @@ -95,7 +95,7 @@ enum WorkspaceVerbHandlers { private static func spawn(_ context: AppActionContext, anchor: WorkspaceModel?, cwd: String?, slot: WorkspaceSlot?, newTabPage: Bool, then: (@MainActor @Sendable (String, SidebarBridge) -> Void)? = nil) throws { - let windows = context.services.windows! + let windows = context.services.windows let window = anchor.flatMap { windows.registry.value.owner(of: $0.id) } ?? context.activeWindow?.state.id let target = windows.targetWindow(preferring: window) var spawn = WorkspaceSpawn(cwd: cwd) @@ -130,7 +130,7 @@ enum WorkspaceVerbHandlers { /// The sidebar of the window that lists `workspace`, else the active one. static func sidebar(showing workspace: WorkspaceModel, _ context: AppActionContext) throws -> SidebarBridge { - let windows = context.services.windows! + let windows = context.services.windows if let owner = windows.registry.value.owner(of: workspace.id), let controller = windows.controller(for: owner) { return controller.sidebar } return try context.sidebar() } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/History/AgentHistory.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/History/AgentHistory.swift index 5c9317648255..d5b02fb97ead 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/History/AgentHistory.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/History/AgentHistory.swift @@ -26,7 +26,8 @@ final class AgentHistory { /// session journal. Concurrent calls share one read. func refresh() async { if let refreshing { return await refreshing.value } - let task = Task { await readAll() } + // The owner's daemons are read before the first suspension, so a weak capture is enough. + let task = Task { [weak self] in _ = await self?.readAll() } refreshing = task await task.value refreshing = nil diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/History/ClosedWorkspaceTracker.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/History/ClosedWorkspaceTracker.swift index 07950a555888..3feb52189d95 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/History/ClosedWorkspaceTracker.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/History/ClosedWorkspaceTracker.swift @@ -26,7 +26,7 @@ final class ClosedWorkspaceTracker { let machines = services.machines observation = Task { [weak self, weak services] in for await snapshot in Observations({ - Self.snapshot(of: machines.daemons) { services?.windows?.isIncognito(workspace: $0) ?? false } + Self.snapshot(of: machines.daemons) { services?.windows.isIncognito(workspace: $0) ?? false } }) { self?.apply(snapshot) } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/History/CommandHistory.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/History/CommandHistory.swift index 6821161f5363..cffbd4d40a1e 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/History/CommandHistory.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/History/CommandHistory.swift @@ -77,7 +77,8 @@ final class CommandHistory { /// the capability. Concurrent calls share one read. func refresh() async { if let refreshing { return await refreshing.value } - let task = Task { await readAll() } + // The owner's daemons are read before the first suspension, so a weak capture is enough. + let task = Task { [weak self] in _ = await self?.readAll() } refreshing = task await task.value refreshing = nil diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/History/HistoryService.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/History/HistoryService.swift index f55643fb2172..c3ab5b22f34f 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/History/HistoryService.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/History/HistoryService.swift @@ -32,7 +32,7 @@ final class HistoryService { /// Launch: page history becomes durable in `supportDirectory`. func start(supportDirectory: URL) { self.supportDirectory = supportDirectory - let cache = services.cache! + let cache = services.cache attach(cache.history, profile: .default) for (profile, entry) in cache.profileHistories { attach(entry.history, profile: profile) } cache.onProfileHistoryCreated = { [weak self] profile, history in self?.attach(history, profile: profile) } @@ -99,7 +99,7 @@ final class HistoryService { for (profile, log) in profileLogs { for visit in await log.visits(matching: query.text, since: since, limit: limit) { all.append(HistoryEntry(id: "page:\(profile):\(visit.id)", kind: .page, time: visit.time, - title: visit.title?.isEmpty == false ? visit.title! : visit.url, detail: visit.url, + title: visit.title.flatMap { $0.isEmpty ? nil : $0 } ?? visit.url, detail: visit.url, payload: .page(url: visit.url, profile: profile))) } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Home/DebugHome+Page.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Home/DebugHome+Page.swift index 7cee79d533b1..fef45d064de1 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Home/DebugHome+Page.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Home/DebugHome+Page.swift @@ -44,15 +44,15 @@ extension DebugHome { ]) } } - return .object([ + let fields: [String: JSONValue] = [ "online": .bool(store.isOnline), "me": store.me.map { .string($0.id.rawValue) } ?? .null, "shown": view?.shown.map { .string($0.rawValue) } ?? .null, // The opened transcript as the store holds it, to compare with the row's preview_source. - "shown_transcript": view?.shown.map { id in + "shown_transcript": view?.shown.map { id -> JSONValue in let items = store.transcript(for: id) - return .object(["conversation": .string(id.rawValue), "count": .number(Double(items.count)), - "last_seq": items.compactMap(\.seq).max().map { .number(Double($0)) } ?? .null]) + let lastSeq: JSONValue = items.compactMap(\.seq).max().map { .number(Double($0)) } ?? .null + return .object(["conversation": .string(id.rawValue), "count": .number(Double(items.count)), "last_seq": lastSeq]) } ?? .null, // Teammates with no DM yet (the search's Teammates section draws from these). "teammates_without_dm": .number(Double(Self.teammatesWithoutDM(rows: store.rows, contacts: home.contacts()))), @@ -72,7 +72,7 @@ extension DebugHome { ]) } ?? .null, // Every window's Home sidebar: its width and divider (window points from the top-left). - "sidebar_windows": .array(services.windows.controllers.compactMap { controller in + "sidebar_windows": .array(services.windows.controllers.compactMap { controller -> JSONValue? in guard let page = controller.topPages.views[.home] as? TopHomePageView else { return nil } return .object([ "window": .string(controller.state.id), @@ -80,12 +80,13 @@ extension DebugHome { "divider": page.split.dividerFrameInWindow.map(Self.frame) ?? .null, ]) }), - "chiefs": .array(home.directory.chiefs.map { chief in + "chiefs": .array(home.directory.chiefs.map { chief -> JSONValue in .object(["id": .string(chief.id), "name": .string(chief.name), "default": .bool(chief.isDefault), "main_conversation": chief.mainConversation.map { .string($0) } ?? .null]) }), "archived_chiefs": .array(home.directory.archivedChiefs.sorted().map { .string($0) }), "team_members": .number(Double(home.directory.teamMembers.count)), - ]) + ] + return .object(fields) } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Home/HomeService+Workspace.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Home/HomeService+Workspace.swift index 650327e0e8a5..6a70e2692cf3 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Home/HomeService+Workspace.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Home/HomeService+Workspace.swift @@ -76,7 +76,7 @@ extension HomeService { /// The signed-in user's chief placed on a paired server (G6), or nil: /// signed out, none placed, or the read failed (logged; the local chief stays). func readPlacedChief() async -> CloudChief? { - guard services.cloud.auth.isSignedIn, let feed = services.feed else { return nil } + guard services.cloud.auth.isSignedIn, case let feed = services.feed else { return nil } do { return try await HomeChiefSource.readPlaced { path, body in try await feed.call(path, body) } } catch { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/IconPicker/IconPickerService.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/IconPicker/IconPickerService.swift index 6b31846446f3..e9c0c20e9152 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/IconPicker/IconPickerService.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/IconPicker/IconPickerService.swift @@ -127,7 +127,7 @@ final class IconPickerService { /// An anchor at personal group `id`'s header in the active window, else /// the middle of the active window's content. func anchor(group id: String) -> Anchor? { - guard let controller = services?.windows?.active, let content = controller.window?.contentView else { return nil } + guard let controller = services?.windows.active, let content = controller.window?.contentView else { return nil } if let screen = controller.sidebar.container.sidebarView.groupRowFrameOnScreen(for: CmuxNextSidebar.GroupID(id)), let window = content.window { return Anchor(view: content, rect: content.convert(window.convertFromScreen(screen), from: nil)) @@ -137,7 +137,7 @@ final class IconPickerService { /// An anchor at the top middle of the active window (objects with no row on screen). func activeWindowAnchor() -> Anchor? { - services?.windows?.active?.window?.contentView.map { centerAnchor(in: $0) } + services?.windows.active?.window?.contentView.map { centerAnchor(in: $0) } } private func centerAnchor(in content: NSView) -> Anchor { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/InputVerification/AppControl+Input.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/InputVerification/AppControl+Input.swift index f4d28d17020c..0a72a3267db8 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/InputVerification/AppControl+Input.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/InputVerification/AppControl+Input.swift @@ -18,7 +18,7 @@ extension AppControl { let source = call.params["source"]?.stringValue ?? "journal" let entries: [InputJournalEntry] if source == "report" { - guard let report = services?.input.monitor.reports.last else { return .value(["error": "no desync report"]) } + guard let report = services?.input.monitor?.reports.last else { return .value(["error": "no desync report"]) } entries = report.journal } else { entries = InputJournal.shared.entries() diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/InputVerification/DebugTabDrag.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/InputVerification/DebugTabDrag.swift index d318b0cb5ba1..d1e5f8b7100a 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/InputVerification/DebugTabDrag.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/InputVerification/DebugTabDrag.swift @@ -12,7 +12,7 @@ import CmuxNextSettings /// winning drop target and the outcome a release would commit. enum DebugTabDrag { static func report(services: AppServices) -> JSONValue { - let session = services.dragSession! + let session = services.dragSession guard let drag = session.drag ?? session.landing else { return .object(["dragging": .bool(false), "strips": strips(services)]) } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/InputVerification/InputVerificationService.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/InputVerification/InputVerificationService.swift index 8f2817704465..05ed2e493a25 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/InputVerification/InputVerificationService.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/InputVerification/InputVerificationService.swift @@ -8,8 +8,8 @@ import CmuxNextDaemon /// keyboard guard (`InputVerificationService+NoActivateGuard.swift`). One per /// app, owned by `AppServices.input`; observers live as long as the app. final class InputVerificationService { - /// Input invariants and desync reports; set by `start`. - private(set) var monitor: InputInvariantMonitor! + /// Input invariants and desync reports; set by `start` (nil before it). + private(set) var monitor: InputInvariantMonitor? private var geometryObservers: [any NSObjectProtocol] = [] /// No-activate mode only: gives back a keyboard the user did not give. var keyboardGuard: NoActivateKeyboardGuard? diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/MainMenu.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/MainMenu.swift index b66fc6eede02..5b054fe79619 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/MainMenu.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/MainMenu.swift @@ -50,7 +50,7 @@ enum MainMenu { NSApp.windowsMenu = windowMenu.submenu // Debug (DEV and NIGHTLY, `DevTools`): debug-only actions placed there. var debug = DevTools.isEnabled ? registry.makeMainMenuItems(for: .debug) : [] - if DevTools.isEnabled { debug += [.separator(), SidebarToggleIconMenu.shared.makeItem()] } + if DevTools.isEnabled { debug += [.separator(), SidebarToggleIconMenu.shared.makeItem(), StatusIconSetMenu.shared.makeItem()] } if !debug.isEmpty { mainMenu.addItem(submenu(Strings.menuDebug, items: debug)) } return mainMenu } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/NewTabPage.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/NewTabPage.swift index 22063e5cc52f..c13ccc4c10ea 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/NewTabPage.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/NewTabPage.swift @@ -346,7 +346,7 @@ extension NewTabPage { : ChromiumInternalURL(typed: text)?.url ?? resolver.commitTypoFix(for: text) ?? resolver.destination(for: request.text)?.url let engine = BrowserEngineTag.engine(for: url) // A session-local browser tab is made and selected right away. - if services.cache.browserTabs?.isAvailable() == true { + if services.cache.browserTabs.isAvailable() == true { pane.newBrowserTab(url: url, engine: engine, then: closePage) } else { // A refused tab (a Chromium page without Chromium) keeps the page. diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Notifications/DebugNotifications.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Notifications/DebugNotifications.swift index a2925c27a3b7..5bd62b63dcb2 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Notifications/DebugNotifications.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Notifications/DebugNotifications.swift @@ -43,11 +43,7 @@ enum DebugNotifications { return [ "unread": .array(unread), "windows": .array(windows), - "banners": .array(center.desktop.posted.map { banner in - ["id": .string(banner.id), "title": .string(banner.title), - "subtitle": banner.subtitle.map(JSONValue.string) ?? .null, "body": .string(banner.body), - "surface": banner.surface.map { .number(Double($0)) } ?? .null] - }), + "banners": .array(center.desktop.posted.map(banner)), "authorization": .string(center.desktop.authorization), "log": .array(center.log.map(JSONValue.string)), "feed_log": .array((center.feedBridge?.log ?? []).map(JSONValue.string)), @@ -60,4 +56,17 @@ enum DebugNotifications { ], ] } + + /// One banner the app asked for, with its status badge (`attachment`: + /// byte count and the PNG as base64, null when the banner had none). + static func banner(_ banner: DesktopNotifier.Posted) -> JSONValue { + [ + "id": .string(banner.id), "title": .string(banner.title), + "subtitle": banner.subtitle.map(JSONValue.string) ?? .null, "body": .string(banner.body), + "surface": banner.surface.map { .number(Double($0)) } ?? .null, + "attachment": banner.attachment.map { data in + ["bytes": .number(Double(data.count)), "png_base64": .string(data.base64EncodedString())] + } ?? .null, + ] + } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Notifications/DesktopNotifier.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Notifications/DesktopNotifier.swift index 5a97ed3d2c6b..c237fe07b125 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Notifications/DesktopNotifier.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Notifications/DesktopNotifier.swift @@ -18,6 +18,8 @@ final class DesktopNotifier: NSObject { var body: String var surface: UInt64? var sound: String? + /// The status badge PNG the banner carries (OSC 7501 alerts), else nil. + var attachment: Data? } /// Banner clicked: the notification id and its tab's surface handle. @@ -39,7 +41,7 @@ final class DesktopNotifier: NSObject { func post(id: String, title: String, subtitle: String? = nil, body: String, surface: UInt64?, workspace: String?, defaultSound: Bool, attachment: Data? = nil) { posted.append(Posted(id: id, title: title, subtitle: subtitle, body: body, surface: surface, - sound: defaultSound ? "default" : nil)) + sound: defaultSound ? "default" : nil, attachment: attachment)) if posted.count > Self.postedLimit { posted.removeFirst(posted.count - Self.postedLimit) } guard let center = resolvedCenter() else { return } let content = UNMutableNotificationContent() diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Notifications/NotificationCenterService+ProgramStatus.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Notifications/NotificationCenterService+ProgramStatus.swift index f954ef0ed82d..1346be6127f6 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Notifications/NotificationCenterService+ProgramStatus.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Notifications/NotificationCenterService+ProgramStatus.swift @@ -3,6 +3,7 @@ import CmuxNextBridge import CmuxNextDaemon import CmuxNextDesign import CmuxNextSettings +import CmuxNextWakeups /// OSC 7501 notifications (cx-kxa2): the daemon posts them; here the app /// finds the record behind one, drops a `done` the user can already see, and @@ -16,6 +17,36 @@ extension NotificationCenterService { level: notification.level, records: located.tab.programStatus) } + /// How long an alert waits for its record before it shows without one. + static let programAlertWait: Duration = .milliseconds(1500) + + /// Holds an alert-shaped `terminal` notification until the tab's OSC 7501 + /// records contain its record (observed, no poll), then calls `deliver` + /// once with the match; after `programAlertWait` it delivers without one. + func holdUntilRecord(_ notification: DaemonNotification, located: LocatedTab, + deliver: @escaping @MainActor @Sendable (ProgramStatusNotification?) -> Void) { + let id = notification.notification.rawValue + let tab = located.tab + let hold = HeldProgramAlert(timer: DemandTimer(owner: "notifications.programAlert", clock: clock)) + let finish: @MainActor @Sendable (ProgramStatusNotification?) -> Void = { [weak self] found in + guard !hold.delivered else { return } + hold.delivered = true + hold.timer.cancel() + self?.heldProgramAlerts.removeValue(forKey: id)?.cancel() + deliver(found) + } + hold.timer.schedule(after: Self.programAlertWait) { @MainActor in finish(nil) } + heldProgramAlerts[id] = Task { @MainActor in // task-owner: heldProgramAlerts, cancelled by finish + for await records in Observations({ tab.programStatus }) { + if let found = ProgramStatusNotification.match(title: notification.title, body: notification.body, + level: notification.level, records: records) { + finish(found) + return + } + } + } + } + /// Where the tab is for the user now (status-indicators.md visibility /// rule): the selected tab of its pane, in the workspace a visible window /// shows, while cmux is active. A pane of the shown workspace counts as on @@ -42,6 +73,14 @@ extension NotificationCenterService { } } +/// One held OSC 7501 alert: delivered once, by its record or its deadline. +@MainActor +final class HeldProgramAlert { + let timer: DemandTimer + var delivered = false + init(timer: DemandTimer) { self.timer = timer } +} + /// The badge image a status notification attaches: the status glyph the /// sidebar draws for the reason, on the theme's surface, as a PNG file /// `UNNotificationAttachment` can take (the center moves the file, so each @@ -50,19 +89,23 @@ extension NotificationCenterService { enum StatusNotificationImage { static let side: CGFloat = 64 - /// PNG data per reason (six images; drawn once per theme). + /// PNG data per reason, icon set and theme. private static var cache: [String: Data] = [:] - /// The badge PNG for `reason`, cached per reason and theme. + /// The badge PNG for `reason` in the chosen status icon set + /// (`StatusIconSet`), cached per reason, set and theme. static func data(_ reason: ProgramStatusNotification.Reason) -> Data? { - let key = "\(reason.rawValue)-\(ThemeScope.app.tokens.surfaceBackground)" + let set = StatusIndicatorAppearance.shared.config.iconSet + let key = "\(reason.rawValue)-\(set.rawValue)-\(ThemeScope.app.tokens.surfaceBackground)" if let cached = cache[key] { return cached } - let drawn = png(reason) + let drawn = png(reason, set: set) cache[key] = drawn return drawn } - static func png(_ reason: ProgramStatusNotification.Reason) -> Data? { + /// The badge for `reason` drawn with `set`'s mark (the reason's blocked + /// kind included) by `StatusIconSet.image`, the drawing the sidebar uses. + static func png(_ reason: ProgramStatusNotification.Reason, set: StatusIconSet) -> Data? { let tokens = ThemeScope.app.tokens let scale: CGFloat = 2 let pixels = Int(side * scale) @@ -75,17 +118,14 @@ enum StatusNotificationImage { context.addPath(CGPath(roundedRect: tile, cornerWidth: side * 0.22, cornerHeight: side * 0.22, transform: nil)) context.setFillColor(tokens.surfaceBackground.withAlpha(1).nsColor.cgColor) context.fillPath() - let indicator = StatusIndicatorLayer() - indicator.contentsScale = scale - indicator.colors = StatusIndicatorLayer.Colors( - loading: tokens.textSecondary.nsColor.cgColor, attention: tokens.attention.nsColor.cgColor, - danger: tokens.danger.nsColor.cgColor, success: tokens.success.nsColor.cgColor, - accent: tokens.textPrimary.nsColor.cgColor) let glyph = side * 0.5 - indicator.frame = CGRect(x: (side - glyph) / 2, y: (side - glyph) / 2, width: glyph, height: glyph) - indicator.apply(.make(reason.indicator, style: .arc, animates: false), config: StatusIndicatorConfig(animatesLoops: false)) - context.translateBy(x: indicator.frame.minX, y: indicator.frame.minY) - indicator.layer.render(in: context) + let kind = reason.kind.flatMap { StatusBlockedKind(rawValue: $0.rawValue) } + let mark = ThemeScope.app.perform { + set.image(state: reason.indicator, kind: kind, pointSize: glyph, scale: scale, appearance: ThemeScope.app.appearance) + } + if let mark = mark?.cgImage(forProposedRect: nil, context: nil, hints: nil) { + context.draw(mark, in: CGRect(x: (side - glyph) / 2, y: (side - glyph) / 2, width: glyph, height: glyph)) + } guard let image = context.makeImage() else { return nil } return NSBitmapImageRep(cgImage: image).representation(using: .png, properties: [:]) } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Notifications/NotificationCenterService.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Notifications/NotificationCenterService.swift index 6c5e3a1a553e..bb235a22f5b0 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Notifications/NotificationCenterService.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Notifications/NotificationCenterService.swift @@ -22,6 +22,9 @@ final class NotificationCenterService { @ObservationIgnored private var lastKeystroke: [String: ContinuousClock.Instant] = [:] /// `timeout` dismissal deadlines per tab id (one-shot `DemandTimer`s). @ObservationIgnored private var timeouts: [String: DemandTimer] = [:] + /// OSC 7501 alerts held until their record arrives, by notification id + /// (`NotificationCenterService+ProgramStatus`). + @ObservationIgnored var heldProgramAlerts: [UInt64: Task] = [:] /// Banner ids posted per tab id, withdrawn once the tab is read. @ObservationIgnored private var banners: [String: [String]] = [:] @ObservationIgnored private var lastSeen: UInt64 = 0 @@ -195,8 +198,21 @@ final class NotificationCenterService { acknowledge(located.tab) return } - // An OSC 7501 done for a terminal the user can see is read at once. let program = programStatus(of: notification, source: source, located: located) + if program == nil, source == .terminal, + ProgramStatusNotification.looksLikeAlert(title: notification.title, level: notification.level) { + holdUntilRecord(notification, located: located) { [weak self] found in + self?.deliver(notification, source: source, located: located, decision: decision, program: found) + } + return + } + deliver(notification, source: source, located: located, decision: decision, program: program) + } + + /// The rest of an arrival once its OSC 7501 record (if any) is known. + func deliver(_ notification: DaemonNotification, source: NotificationSource, located: LocatedTab, + decision: NotificationPolicy.Decision, program: ProgramStatusNotification?) { + // An OSC 7501 done for a terminal the user can see is read at once. if let program, !program.notifies(visibility: visibility(of: located)) { note("program status \(program.reason.rawValue) visible: read at once") acknowledge(located.tab) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/AppOnboardingServices+Chats.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/AppOnboardingServices+Chats.swift index 45290a777b9e..645266c450bf 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/AppOnboardingServices+Chats.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/AppOnboardingServices+Chats.swift @@ -2,6 +2,7 @@ import CmuxNextAgentPane import CmuxNextOnboarding import Foundation import Observation +import os /// The chats step: resumed chats open as agent tabs in their project's /// workspace, which the projects step may have opened a moment before. @@ -18,15 +19,16 @@ extension AppOnboardingServices { continue } waitingChats[path, default: []] += chats - guard !openingFolders.contains(path), let windows = services.windows else { continue } + guard !openingFolders.contains(path), case let windows = services.windows else { continue } let target = windows.targetWindow(preferring: windows.active?.state.id) let folder = URL(fileURLWithPath: path, isDirectory: true) let spawn = folderSpawn(folder) - Task { + let logger = services.daemon.logger + Task { [weak self] in do { _ = try await windows.createWorkspace(spawn, into: target) } catch { - folderFailed(folder, error) + self?.folderFailed(folder, error, logger: logger) } } } @@ -34,11 +36,13 @@ extension AppOnboardingServices { /// A folder's workspace could not be made: it is no longer opening, and /// its waiting chats are dropped, so a later resume asks again. - func folderFailed(_ folder: URL, _ error: any Error) { + /// `logger` is read before the workspace request, so a failure that lands + /// after the onboarding service is gone does not reach through it. + func folderFailed(_ folder: URL, _ error: any Error, logger: Logger) { let path = folder.standardizedFileURL.path openingFolders.remove(path) let dropped = waitingChats.removeValue(forKey: path)?.count ?? 0 - services.daemon.logger.error( + logger.error( "onboarding workspace for a folder failed (\(dropped) chats dropped): \(String(describing: error), privacy: .public)") } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/AppOnboardingServices+ClassicSessions.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/AppOnboardingServices+ClassicSessions.swift index a4bd650c7a5b..6d83712815e6 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/AppOnboardingServices+ClassicSessions.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/AppOnboardingServices+ClassicSessions.swift @@ -14,8 +14,10 @@ extension AppOnboardingServices { /// Recreates local workspace shells and terminal tabs. Classic commands, /// scrollback, and remote panels are intentionally ignored. func importClassicSessions(_ workspaces: [ClassicSessionWorkspace]) { - guard let windows = services.windows else { return } + let windows = services.windows let target = windows.targetWindow(preferring: windows.active?.state.id) + // Read before the task: after a suspension the onboarding service may be gone. + let machines = services.machines, logger = services.daemon.logger Task { @MainActor [weak self] in guard let self else { return } for saved in workspaces { @@ -26,10 +28,10 @@ extension AppOnboardingServices { var spawn = WorkspaceSpawn(cwd: saved.workingDirectory, name: saved.name) spawn.slot = .bottom(anchor: nil) let id = try await windows.createWorkspace(spawn, into: target) - guard let daemon = services.machines.daemon(forWorkspace: id), let connection = daemon.connection else { continue } + guard let daemon = machines.daemon(forWorkspace: id), let connection = daemon.connection else { continue } try await restoreClassicLayout(saved.layout, workspaceID: id, connection: connection) } - catch { services.daemon.logger.error("classic session import failed: \(String(describing: error), privacy: .public)") } + catch { logger.error("classic session import failed: \(String(describing: error), privacy: .public)") } } } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/AppOnboardingServices.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/AppOnboardingServices.swift index 49be3180449a..da7d6e29a573 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/AppOnboardingServices.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/AppOnboardingServices.swift @@ -98,16 +98,17 @@ final class AppOnboardingServices: OnboardingServices { /// the sidebar keeps the list's order; any macOS privacy prompts for /// Desktop or Documents come now, together, as the step said. func openProjects(_ folders: [URL]) { - guard let windows = services.windows else { return } + let windows = services.windows let target = windows.targetWindow(preferring: windows.active?.state.id) // Every folder counts as opening now, so chats picked meanwhile wait for it. let spawns = folders.map { ($0, folderSpawn($0)) } - Task { + let logger = services.daemon.logger + Task { [weak self] in for (folder, spawn) in spawns { do { _ = try await windows.createWorkspace(spawn, into: target) } catch { - folderFailed(folder, error) + self?.folderFailed(folder, error, logger: logger) } } } @@ -121,7 +122,7 @@ final class AppOnboardingServices: OnboardingServices { } func runImport(_ plan: ImportPlan, progress: @escaping @MainActor (ImportProgress) -> Void) async throws -> ImportSummary { - let cache = services.cache! + let cache = services.cache let destination = AppImportDestination(store: owner.importStore, bookmarks: services.importedBookmarkSink) { id in cache.history(for: BrowserProfileRecord.engineProfile(for: id) ?? .default) } @@ -147,7 +148,7 @@ final class AppOnboardingServices: OnboardingServices { } func canImportPasswords() async -> Bool { - await services.cache?.cef.canImportPasswords() ?? false + await services.cache.cef.canImportPasswords() } /// Touch ID, or the Mac's password where there is none. Only a Mac with diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/ExternalOpenController.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/ExternalOpenController.swift index ead789d14011..7f3a8187a293 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/ExternalOpenController.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/ExternalOpenController.swift @@ -57,7 +57,7 @@ final class ExternalOpenController { /// Workspace services: a new workspace (in the current window, or a new /// one) whose terminal starts in the folder. func newWorkspace(at path: String, newWindow: Bool) { - guard case .terminal(let cwd, _) = router.newTabHere(path), let windows = services.windows else { return } + guard case .terminal(let cwd, _) = router.newTabHere(path), case let windows = services.windows else { return } let target = newWindow ? UUID().uuidString.lowercased() : windows.targetWindow(preferring: windows.active?.state.id) let logger = services.daemon.logger Task { @@ -71,7 +71,7 @@ final class ExternalOpenController { } func perform(_ route: ExternalOpenRoute) { - guard let windows = services.windows else { return pending.append(route) } + let windows = services.windows guard let controller = windows.active else { pending.append(route) if windows.restored, windows.controllers.isEmpty { windows.reopenOrCreateWindow() } @@ -99,7 +99,7 @@ final class ExternalOpenController { private var creatingWorkspace = false private func createWorkspaceForPending(in controller: WindowController) { - guard !creatingWorkspace, let windows = services.windows else { return } + guard !creatingWorkspace, case let windows = services.windows else { return } creatingWorkspace = true let target = windows.targetWindow(preferring: controller.state.id) let logger = services.daemon.logger diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/OnboardingService.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/OnboardingService.swift index 01f4c0a990a5..c7f9de387802 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/OnboardingService.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/OnboardingService.swift @@ -234,7 +234,7 @@ final class OnboardingService { // Only the first run's Skip or Done ends the first run; another // window's (Import and Sync, a single step) leaves it as it is. if controller?.model.isFirstRun ?? true { markDone(completed: completed) } - guard Self.opensNewTab(completed: completed, shown: services.windows?.active?.shownTopPage) else { return } + guard Self.opensNewTab(completed: completed, shown: services.windows.active?.shownTopPage) else { return } services.registry.perform("newTab") } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/PasswordCSVFiles.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/PasswordCSVFiles.swift index fd25099fcef2..fa091d5efa6e 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/PasswordCSVFiles.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Onboarding/PasswordCSVFiles.swift @@ -21,7 +21,7 @@ struct PasswordCSVFiles { /// The guided steps (source, the source's export steps, the open panel), then the import of /// the picked file and the Trash offer for it. func chooseImport(profile: String) throws { - guard let cef = services.cache?.cef else { throw ActionFailure(message: PasswordCSVStrings.unavailable) } + let cef = services.cache.cef let guide = PasswordCSVGuide(presenter: LivePasswordCSVGuidePresenter()) services.registry.track(Task { @MainActor in guard let url = await guide.run() else { return nil } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Pages/PageFactory.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Pages/PageFactory.swift index 6f58ebb61053..acb60e0d0de9 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Pages/PageFactory.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Pages/PageFactory.swift @@ -93,7 +93,7 @@ struct PageFactory { func settingsPage(route: String?) -> PageWebView? { guard let settings = services.settings else { return nil } let provider = SettingsPageProvider(settings: settings, domains: { [weak services] in - ["themes": services?.themes?.catalog.names ?? [], "font_families": SettingsPageDomains.fontFamilies, "sounds": SettingsPageDomains.sounds] + ["themes": services?.themes.catalog.names ?? [], "font_families": SettingsPageDomains.fontFamilies, "sounds": SettingsPageDomains.sounds] }, hostLists: { [weak services] in services?.settingsWindow.pageHostLists() ?? .null }) let accounts = services.accounts.model provider.accountsState = { (try? JSONValue.parse(JSONEncoder().encode(accounts.pageState))) ?? .null } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/PaneBrowserTabOpener.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/PaneBrowserTabOpener.swift index 5590c04d56dc..d94cf7ba87f3 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/PaneBrowserTabOpener.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/PaneBrowserTabOpener.swift @@ -45,7 +45,7 @@ struct PaneBrowserTabOpener { return true } let requested = requested ?? (child == nil && inherited == nil ? url.flatMap(FilePageOpener.tabEngine(for:)) : nil) - let browserTabs = services.cache.browserTabs! + let browserTabs = services.cache.browserTabs if browserTabs.isAvailable() { var choice: BrowserEngineChoice switch browserTabs.resolve(requested: requested, inherited: inherited) { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/PaneController+Intents.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/PaneController+Intents.swift index fa25256c57c1..349ef1ae5222 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/PaneController+Intents.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/PaneController+Intents.swift @@ -102,7 +102,7 @@ extension PaneController { let workspace = services.workspaceKey(of: pane) guard let connection = daemon.connection else { return } let intent = self.workspace?.beginFocusIntent() - services.registry.track(Task { + services.registry.track(Task { [services] in do { var start = cwd if let agent, let agentCwd = await agent.workingContext()?.cwd, WorkingURL.isDirectory(agentCwd) { start = agentCwd } @@ -161,7 +161,7 @@ extension PaneController { let keys = Set(ids.map(\.rawValue)) let runs = daemon.closeRuns(surfaces: surfaces, commands: commands.map { ($0.label, $0.run) }) let userClose = CloseUndoToasts.isUserClose // a refused user close shows RefusedCloseNotice - services.registry.track(Task { + services.registry.track(Task { [services] in let (failed, unknown, codes) = await daemon.runReportingOutcomes(runs) if failed, userClose { RefusedCloseNotice(services: services).show(codes: codes, in: view.window) } // A close that missed its deadline under daemon load usually still @@ -199,13 +199,13 @@ extension PaneController { services.registry.refuse(daemon.missingCapabilityMessage(DaemonCapabilities.shared.tabMetadata)) return } - services.registry.track(Task { + services.registry.track(Task { [services] in let ok = await daemon.intend("set-tab-pinned", .setTabPinned(surface: surface, pinned: pinned)) { connection in if let resource { return try await connection.state.setTabPinned(resource, pinned) } _ = try await connection.setTabPinned(surface, pinned) } if !ok { resyncStrip() } - return ok ? nil : "set-tab-pinned failed (see the app log)" + return withExtendedLifetime(services) { ok ? nil : "set-tab-pinned failed (see the app log)" } }) } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Passwords/PasswordsPage.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Passwords/PasswordsPage.swift index 9913ff9b707f..5008d54b2c46 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Passwords/PasswordsPage.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Passwords/PasswordsPage.swift @@ -37,7 +37,7 @@ final class PasswordsPageService: InternalPageProvider { #if DEBUG if ProcessInfo.processInfo.environment["CMUX_NEXT_PASSWORDS_SAMPLE"] == "1" { return SamplePasswordStore() } #endif - return ChromiumPasswordStore(engine: { [weak services] in services?.cache?.cef }) + return ChromiumPasswordStore(engine: { [weak services] in services?.cache.cef }) } func open(focus: Bool) throws { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Pins/PinCommands.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Pins/PinCommands.swift index 18449c7651dc..d8e504a99bfa 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Pins/PinCommands.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Pins/PinCommands.swift @@ -46,7 +46,7 @@ struct PinCommands { /// Cmd-Z, and an entry on the window would keep the toast from the key.) func registerUndo(title: String, _ inverse: @escaping @MainActor (PinCommands) -> Void) { let windows = context.services.windows - guard let window = windows?.active?.window ?? NSApp.keyWindow ?? NSApp.mainWindow ?? windows?.controllers.last?.window else { return } + guard let window = windows.active?.window ?? NSApp.keyWindow ?? NSApp.mainWindow ?? windows.controllers.last?.window else { return } let handle = CmuxToastCenter.shared.show(CmuxToast(id: Self.undoToastID, message: PinStrings.done(title), action: .undo()), in: window) handle.onAction = { inverse(self) } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Quit/QuitCoordinator.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Quit/QuitCoordinator.swift index e3a37119dbc8..21346643a0c8 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Quit/QuitCoordinator.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Quit/QuitCoordinator.swift @@ -71,7 +71,8 @@ final class QuitCoordinator { let origin = origins.consume(appleEventReason: Self.quitReason()) let behavior = services.settings?.snapshot.quitBehavior ?? QuitBehaviorSetting.fallback logger.info("quit origin=\(String(describing: origin), privacy: .public) behavior=\(behavior.rawValue, privacy: .public)") - Task { @MainActor in + // [services]: the quit task pins the app's services until it ends (cx-6so P1b). + Task { @MainActor [services] in // Unsaved documents come first (R96 quit hook). Answering that // question is the quit's one dialog: the sessions are not asked // about after it (#17501). @@ -117,7 +118,10 @@ final class QuitCoordinator { self.isQuitting = false sender.reply(toApplicationShouldTerminate: false) case .quit(let choice, let remember): - Task { @MainActor in await self.complete(choice, remember: remember, sender) } + Task { @MainActor [services] in + await self.complete(choice, remember: remember, sender) + withExtendedLifetime(services) {} // pins the app's services until the quit ends + } } } self.sheet = sheet diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Quit/QuitFactsReader.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Quit/QuitFactsReader.swift index 113c773a587f..2003a6b6f00a 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Quit/QuitFactsReader.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Quit/QuitFactsReader.swift @@ -12,7 +12,7 @@ enum QuitFactsReader { static func read(_ services: AppServices) async -> QuitFacts { let local = services.machines.local - let windows = services.windows! + let windows = services.windows var kept: [SurfaceID] = [] var incognito: [SurfaceID] = [] var seen = Set() diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Remote/RemoteTerminalService.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Remote/RemoteTerminalService.swift index 07542de23378..cba8646f9528 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Remote/RemoteTerminalService.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Remote/RemoteTerminalService.swift @@ -180,7 +180,7 @@ final class RemoteTerminalService { let machines = services.machines if let ssh = machines.sshSession(daemon.machineID) { let service = services.ssh - return { service?.reconnect(ssh) } + return { service.reconnect(ssh) } } if let cloud = machines.session(daemon.machineID) { return { cloud.connect(origin: .user) } } if let server = machines.server(daemon.machineID) { return { server.connect() } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Remote/SSHMachineSession.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Remote/SSHMachineSession.swift index 1d9608878367..0e5ff3a6e994 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Remote/SSHMachineSession.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Remote/SSHMachineSession.swift @@ -13,7 +13,7 @@ final class SSHMachineSession { let machineID: String let daemon: DaemonService @ObservationIgnored let link: SSHMachineLink - @ObservationIgnored private(set) var emptyWorkspaces: EmptyWorkspaceRepair! + @ObservationIgnored let emptyWorkspaces: EmptyWorkspaceRepair /// The link's gate status (`SSHConnectionMachine`), mirrored from the actor. var linkStatus: SSHConnectionMachine.Status = .offline /// The install step in progress, for the header's detail. diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/RemoteLocalhost/BrowserTabOpen.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/RemoteLocalhost/BrowserTabOpen.swift index ec9721323187..e91d8383cd74 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/RemoteLocalhost/BrowserTabOpen.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/RemoteLocalhost/BrowserTabOpen.swift @@ -99,7 +99,7 @@ extension BrowserTabOpen { /// adopts it. Throws a typed refusal; never opens the URL any other way. @MainActor static func open(_ request: Request, services: AppServices) async throws(Refusal) { - guard let browserTabs = services.cache.browserTabs, browserTabs.cefUnavailable() == nil else { throw .cefUnavailable } + guard case let browserTabs = services.cache.browserTabs, browserTabs.cefUnavailable() == nil else { throw .cefUnavailable } guard let pane = services.windows.active?.focusedPane else { throw .noWindow } let page: any BrowserTab do { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/RemoteView/RemoteBrowserPages.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/RemoteView/RemoteBrowserPages.swift index 4b62ec3bb6d9..9cc37a1f951d 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/RemoteView/RemoteBrowserPages.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/RemoteView/RemoteBrowserPages.swift @@ -196,6 +196,13 @@ enum RemoteBrowserPages { "note": session.lastNote.map(JSONValue.string) ?? .null, "cursor": session.nativeUI.cursorKind.map(JSONValue.string) ?? .null, "surfaces": .array(session.surfaces.surfaceIDs.map { .number(Double($0)) }), + "surface_info": .array(session.surfaces.surfaceIDs.map { id in + let frame = session.surfaces.view(of: id)?.frame ?? .zero + return .object([ + "id": .number(Double(id)), "kind": session.surfaces.kind(of: id).map(JSONValue.string) ?? .null, + "frame": .string("\(Int(frame.minX)),\(Int(frame.minY)) \(Int(frame.width))x\(Int(frame.height))"), + ]) + }), "frame": .string("\(Int(session.pane.view.frame.width))x\(Int(session.pane.view.frame.height))"), ]) } @@ -240,6 +247,41 @@ enum RemoteBrowserPages { tab.handlePointer(event) } return ["clicked": true] + case "surface_click": + // A left click at `x`,`y` (the surface's CSS pixels from its top + // left) on open popup surface `surface`, through the surface + // view's own pointer path. + guard let target, let id = params["surface"]?.intValue, + let view = target.surfaces.view(of: UInt32(clamping: id)) else { return ["error": "no such surface"] } + guard let window = view.window else { return ["error": "the surface is not in a window"] } + let point = view.convert(NSPoint(x: params["x"]?.doubleValue ?? 10, y: params["y"]?.doubleValue ?? 10), to: nil) + for type in [NSEvent.EventType.leftMouseDown, .leftMouseUp] { + guard let event = NSEvent.mouseEvent( + with: type, location: point, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: window.windowNumber, context: nil, eventNumber: 0, clickCount: 1, pressure: 1) else { continue } + view.eventTarget?.handlePointer(event) + } + return ["clicked": true] + case "type": + // Types `text` (lowercase a-z) on the page's key path, a key down + // and up per letter, as the keyboard would. + guard let tab = target?.tab, let window = tab.pane.view.window else { return ["error": "no session"] } + let codes: [Character: UInt16] = [ + "a": 0, "s": 1, "d": 2, "f": 3, "h": 4, "g": 5, "z": 6, "x": 7, "c": 8, "v": 9, "b": 11, "q": 12, "w": 13, + "e": 14, "r": 15, "y": 16, "t": 17, "o": 31, "u": 32, "i": 34, "p": 35, "l": 37, "j": 38, "k": 40, "n": 45, "m": 46, + ] + let text = params["text"]?.stringValue ?? "" + guard text.allSatisfy({ codes[$0] != nil }) else { return ["error": "text is lowercase a-z"] } + for character in text { + for type in [NSEvent.EventType.keyDown, .keyUp] { + guard let event = NSEvent.keyEvent( + with: type, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: window.windowNumber, context: nil, characters: String(character), + charactersIgnoringModifiers: String(character), isARepeat: false, keyCode: codes[character] ?? 0) else { continue } + tab.handleKey(event) + } + } + return ["typed": .number(Double(text.count))] case "history": // `op`: `back`, `forward`, `reload` or `stop`, as the toolbar does. guard let tab = target?.tab else { return ["error": "no session"] } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Resources/Localizable.xcstrings b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Resources/Localizable.xcstrings index dcd274aa9528..9c578edece0c 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Resources/Localizable.xcstrings +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Resources/Localizable.xcstrings @@ -6564,6 +6564,138 @@ } } } + }, + "menu.debug.statusIcons": { + "comment": "Debug menu submenu, DEV and NIGHTLY builds only: choose the icon set for agent and program status marks.", + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Status Icons" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "أيقونات الحالة" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Ikone statusa" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Statusikoner" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Statussymbole" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Iconos de estado" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Icônes d’état" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Icone di stato" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ステータスアイコン" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "រូបតំណាងស្ថានភាព" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "상태 아이콘" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Statusikoner" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Ikony stanu" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Ícones de status" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Значки статуса" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "ไอคอนสถานะ" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Durum Simgeleri" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Значки стану" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Biểu tượng trạng thái" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "状态图标" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "狀態圖示" + } + } + } } }, "version": "1.0" diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Screens/ScreenEmojiIcon.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Screens/ScreenEmojiIcon.swift index 0651832bdb3d..2a0d4eae7868 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Screens/ScreenEmojiIcon.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Screens/ScreenEmojiIcon.swift @@ -22,7 +22,7 @@ enum ScreenEmojiIcon { let side = TabStripMetrics.standard.iconSize let pixels = Int((side * scale).rounded()) guard pixels > 0, let context = CGContext(data: nil, width: pixels, height: pixels, bitsPerComponent: 8, bytesPerRow: 0, - space: CGColorSpace(name: CGColorSpace.sRGB)!, + space: CGColorSpace(name: CGColorSpace.sRGB) ?? CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil } context.scaleBy(x: scale, y: scale) NSGraphicsContext.saveGraphicsState() diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Server/ServerReachControl.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Server/ServerReachControl.swift index 6e58cdeff587..6cb71d075194 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Server/ServerReachControl.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Server/ServerReachControl.swift @@ -65,7 +65,7 @@ enum ServerReachControl { /// The chief's current revision, or nil when `chief.list` does not list it. @MainActor private static func chiefRevision(_ services: AppServices, _ chief: String) async throws -> Int? { - guard let feed = services.feed else { throw FeedServiceError.signedOut } + let feed = services.feed return try await CloudChiefs.list { path, body in try await feed.call(path, body) }.first { $0.id == chief }?.rev } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Settings/SettingsWindowService.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Settings/SettingsWindowService.swift index d32c4f767a73..9258153089f9 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Settings/SettingsWindowService.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Settings/SettingsWindowService.swift @@ -62,18 +62,18 @@ final class SettingsWindowService: InternalPageProvider { let route = Self.route(section: target, setting: setting) // The window's one Settings tab comes back when another workspace of the window holds it // (nxdog77: Cmd-, in a second workspace opened a second Settings tab). - if focus, let window = services.windows?.active { revealSettingsTab(of: window) } + if focus, let window = services.windows.active { revealSettingsTab(of: window) } // A user run in a window whose workspace has no pane to hold a tab (an empty workspace, // or Home standing for the home workspace) shows Settings as the window's top page // (nxdog70: Cmd-, on Home with an empty workspace showed nothing). - if focus, let window = services.windows?.active, !Self.holdsTab(window, services) { + if focus, let window = services.windows.active, !Self.holdsTab(window, services) { waiting = nil showTopPage(in: window, route: route) return } - guard let windows = services.windows, let window = windows.active, Self.hasPane(window) else { + guard case let windows = services.windows, let window = windows.active, Self.hasPane(window) else { waiting = (target, setting, focus) - if let windows = services.windows, windows.restored, windows.controllers.isEmpty { windows.reopenOrCreateWindow() } + if case let windows = services.windows, windows.restored, windows.controllers.isEmpty { windows.reopenOrCreateWindow() } return } waiting = nil @@ -85,7 +85,7 @@ final class SettingsWindowService: InternalPageProvider { /// A window installed its workspace content or mounted a pane: a show that waited for a window /// with a pane runs now. func windowDidShowContent() { - guard let request = waiting, let window = services.windows?.active, Self.hasPane(window) else { return } + guard let request = waiting, let window = services.windows.active, Self.hasPane(window) else { return } waiting = nil try? show(section: request.section, setting: request.setting, focus: request.focus) } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Share/ShareCmuxPresenter.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Share/ShareCmuxPresenter.swift new file mode 100644 index 000000000000..645816f5309a --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Share/ShareCmuxPresenter.swift @@ -0,0 +1,28 @@ +import AppKit +import CmuxNextActions +import CmuxNextDesign +import CmuxNextUpdater + +/// `app.shareCmux` (palette, Help menu, the "cmux Updated!" card's Share +/// cmux row; cx-7py7): the Share cmux modal, centered over the active +/// window with a scrim (the app host without a window). One at a time; +/// the x and Escape close it. +@MainActor +enum ShareCmuxPresenter { + /// The modal on screen, if any (`debug.updater {action: "share-copy"}`). + private(set) static weak var shown: ShareCmuxView? + + /// Shows the modal. A run that may not change the view (automation + /// without `focus`) shows nothing: the modal takes the keyboard. + static func present(_ services: AppServices) { + guard ActionRunScope.viewChangeAllowed(), shown == nil else { return } + let host = services.windows.active?.window.map(WindowOverlayHost.host(for:)) ?? WindowOverlayHost.appHost() + let view = ShareCmuxView() + let handle = host.present(view, options: .dialog()) + view.onClose = { [weak handle] in handle?.dismiss() } + handle.onDismiss = { shown = nil } + shown = view + // The overlay's focus trap starts on its first control in view order (the x); Copy Link goes first. + view.focusCopyLink() + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarBridge+Cards.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarBridge+Cards.swift index 82c24a8cfd19..da242f7d4686 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarBridge+Cards.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarBridge+Cards.swift @@ -44,11 +44,12 @@ enum SidebarCardFeed { handle(id, action, updater: updater) } return Task { - for await (cards, card, tip) in Observations({ () -> ([SidebarCard], SidebarUpdateCard?, SidebarTipCard?) in - (cards(updater), updateCard(updater), tipCard(updater, registry: registry)) + for await (cards, card, updated, tip) in Observations({ () -> ([SidebarCard], SidebarUpdateCard?, SidebarUpdatedCard?, SidebarTipCard?) in + (cards(updater), updateCard(updater), updatedCard(updater), tipCard(updater, registry: registry)) }) { if model.cards != cards { model.cards = cards } if model.updateCard != card { model.updateCard = card } + if model.updatedCard != updated { model.updatedCard = updated } if model.tipCard != tip { model.tipCard = tip } } } @@ -65,10 +66,32 @@ enum SidebarCardFeed { case .openUpdateLink(let url): openUpdateLink(url, services: services) case .tryTip(let id): services.updater.tryTip(id) case .dismissTip(let id): services.updater.dismissTip(id) + case .openWhatsNew, .shareCmux, .dismissUpdated: route(intent, registry: services.registry, updater: services.updater) default: break } } + /// The "cmux Updated!" card (cx-7py7): its rows run the palette's own + /// actions as the user's (`updates.whatsNew` opens the page and marks + /// this version seen; `app.shareCmux` opens the modal); its x marks this + /// version seen, so the card and the What's New dot go together. + static func route(_ intent: SidebarIntent, registry: ActionRegistry, updater: UpdaterService) { + switch intent { + case .openWhatsNew: _ = registry.perform("updates.whatsNew", invocation: ActionInvocation(origin: .user)) + case .shareCmux: _ = registry.perform("app.shareCmux", invocation: ActionInvocation(origin: .user)) + case .dismissUpdated: updater.whatsNew.dismissUpdated() + default: break + } + } + + /// The "cmux Updated!" card while it shows (nil while an update is staged: + /// the update card has the slot). + static func updatedCard(_ updater: UpdaterService) -> SidebarUpdatedCard? { + guard updater.readyCard == nil, updater.whatsNew.showsUpdatedCard else { return nil } + return SidebarUpdatedCard(title: UpdaterService.updatedCardTitle, whatsNewTitle: UpdaterService.updatedCardWhatsNewTitle, + shareTitle: UpdaterService.updatedCardShareTitle, dismissLabel: UpdaterService.updatedCardDismissLabel) + } + /// A link in the update card's popover (a pull request, the release /// notes): a browser tab in the active window's focused pane, like a /// Cmd-click on a terminal link; with no window it waits for one. @@ -93,9 +116,10 @@ enum SidebarCardFeed { } /// The "Did you know" card (BOTTOM-LEFT-CARDS K1): today's tip with its - /// action's shortcut; nil while the update card shows (one card at a time). + /// action's shortcut; nil while the update card or the "cmux Updated!" + /// card shows (one card at a time; the tip waits). static func tipCard(_ updater: UpdaterService, registry: ActionRegistry?) -> SidebarTipCard? { - guard updater.readyCard == nil, let tip = updater.tip else { return nil } + guard updater.readyCard == nil, !updater.whatsNew.showsUpdatedCard, let tip = updater.tip else { return nil } return SidebarTipCard(id: tip.id, eyebrow: UpdaterService.tipEyebrow, title: tip.title, benefit: tip.benefit, shortcut: registry?.shortcutDisplay(for: ActionID(rawValue: tip.action)), tryTitle: UpdaterService.announcementActionTitle, dismissLabel: UpdaterService.tipDismissLabel) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarBridge+Intents.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarBridge+Intents.swift index 4ead4506123c..f841c403acbe 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarBridge+Intents.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarBridge+Intents.swift @@ -107,7 +107,7 @@ extension SidebarBridge { sendPinned(ids, pinned) case .activateItem(let id, let opensWorkspace): activateLayoutItem(id, opensWorkspace: opensWorkspace) - case .installUpdate, .setAutomaticUpdates, .openUpdateLink, .tryTip, .dismissTip: + case .installUpdate, .setAutomaticUpdates, .openUpdateLink, .tryTip, .dismissTip, .openWhatsNew, .shareCmux, .dismissUpdated: SidebarCardFeed.handle(intent, services: services) case .layout(let op): applyLayoutOp(op) @@ -165,7 +165,9 @@ extension SidebarBridge { private func run(_ commands: [WorkspaceMovePlan.Command], on daemon: DaemonService) { let keys = Dictionary(daemon.store.workspaces.compactMap { model in model.key.map { (model.id, $0) } }, uniquingKeysWith: { first, _ in first }) - Task { + // [services] pins the app's services while the commands run, so a + // re-sync after a rejection never reads a freed owner (cx-6so P1b). + Task { [weak self, services] in for command in commands { let ok: Bool switch command { @@ -179,7 +181,7 @@ extension SidebarBridge { ok = false } if !ok { - resync() + withExtendedLifetime(services) { self?.resync() } return } } @@ -207,9 +209,9 @@ extension SidebarBridge { /// it has an `intent`; a failure re-syncs the sidebar. private func command(_ label: String, on daemon: DaemonService, intent: Intent? = nil, _ body: @escaping @Sendable (DaemonConnection) async throws -> Void) { - Task { + Task { [weak self, services] in let ok = if let intent { await daemon.intend(label, intent, body) } else { await daemon.request(label, body) != nil } - if !ok { resync() } + if !ok { withExtendedLifetime(services) { self?.resync() } } } } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarBridge+Personal.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarBridge+Personal.swift index 9829b0b3bed3..ccbf772f771d 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarBridge+Personal.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarBridge+Personal.swift @@ -29,19 +29,9 @@ extension SidebarBridge { case .groupEditorEnded(let group): groupFlow.editorEnded(WorkspaceGroupID(rawValue: group.rawValue)) case .renameGroup(let group, let name): - model.apply(intent) - let v2 = statePersonal - personal("update-personal-group") { - if v2 { return try await $0.state.updateWorkspaceGroup(group.rawValue, name: name) } - try await $0.updatePersonalGroup(WorkspaceGroupID(rawValue: group.rawValue), name: name) - } + groupFlow.edit(group, name: name, intent) case .setGroupColor(let group, let color): - model.apply(intent) - let v2 = statePersonal - personal("update-personal-group") { - if v2 { return try await $0.state.updateWorkspaceGroup(group.rawValue, color: .set(color.rawValue)) } - try await $0.updatePersonalGroup(WorkspaceGroupID(rawValue: group.rawValue), color: .set(color.rawValue)) - } + groupFlow.edit(group, color: color, intent) case .toggleCollapse(.group(let group)): model.apply(intent) guard let collapsed = model.group(group)?.isCollapsed else { return true } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarBridge+PinnedItems.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarBridge+PinnedItems.swift index e7ec7c05cac8..458d2670de79 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarBridge+PinnedItems.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarBridge+PinnedItems.swift @@ -96,7 +96,7 @@ extension SidebarBridge { /// when its pane is on screen, else through that window's selection /// memory and focus. Showing the workspace switches space if needed. private func reveal(_ tab: TabModel, in pane: PaneModel, workspace: String, state: WindowState) { - let windows = services.windows! + let windows = services.windows let value = windows.registry.value let owner = value.owner(of: workspace).flatMap { $0 != state.id && value.window($0)?.isOpen == true ? windows.controller(for: $0) : nil } let target = owner?.state ?? state diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarBridge.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarBridge.swift index 46ea8fcea9a9..0e86cd9e4dbc 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarBridge.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarBridge.swift @@ -57,6 +57,7 @@ final class SidebarBridge { state?.focus.send(.sidebarVisibility(hidden: presentation == .hidden)) } container.sidebarView.contextMenuProvider = { [weak self] target in self?.contextMenu(for: target) } + groupFlow.wireEditor() container.sidebarView.resourceSource = services.resources container.sidebarView.hoverCards = services.hoverCards container.sidebarView.appSections = chatsMount.makeSections(services: services) @@ -155,7 +156,7 @@ final class SidebarBridge { /// window ids, the most recently used window's. Loading sections with /// nothing saved show placeholder rows. private func seedFromSnapshot(_ state: WindowState) { - let windows = services.windows! + let windows = services.windows let isLaunchWindow = windows.controllers.isEmpty && windows.registry.isLaunching let saved = services.sidebarSnapshots.launchDocument.snapshot(for: state.id, fallback: isLaunchWindow) seed = SidebarSeed(sections: saved?.sidebarSections ?? []) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarGroupFlow.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarGroupFlow.swift index 60e8310cc5f6..f90b92560bdc 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarGroupFlow.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarGroupFlow.swift @@ -1,3 +1,4 @@ +import CmuxNextActions import CmuxNextBridge import CmuxNextDaemon import CmuxNextDesign @@ -44,9 +45,14 @@ struct SidebarGroupFlow { /// asks without a name: that group's name editor opens (repeated New /// Group, cx-rcby). Automation, and a person who names the group, get /// the group they asked for; the group it empties goes. + /// A person's new group gets the next palette color and its editor + /// opens on it (the Chrome flow). func newGroup(of ids: [SidebarWorkspaceID], name: String, byUser: Bool) { if byUser, name.isEmpty, bridge.usesPersonalOrganization, let whole = bridge.life.whole(bridge.placements(ids)) { return editGroup(whole) } - bridge.handle(.createGroup(CmuxNextSidebar.GroupID.make(), name: name, color: .grey, workspaces: ids)) + let id = CmuxNextSidebar.GroupID.make() + let used = Set(bridge.services.machines.local.store.personal.groups.compactMap(\.color)) + bridge.handle(.createGroup(id, name: name, color: byUser ? GroupColor.automatic(used: used) ?? .grey : .grey, workspaces: ids)) + if byUser, name.isEmpty, bridge.model.group(id) != nil { editGroup(WorkspaceGroupID(rawValue: id.rawValue)) } } /// Opens `group`'s name editor now, or once the sidebar shows it. @@ -102,14 +108,25 @@ struct SidebarGroupFlow { room: ProfileID, _ intent: SidebarIntent) { let id = WorkspaceGroupID(rawValue: group.rawValue), members = bridge.placements(ids), v2 = bridge.statePersonal let life = bridge.life, ending = life.emptied(by: members, into: nil) - bridge.model.apply(intent) + // A pending edit until the store holds the new group (cx-odqn): the + // create, place and delete echoes never show the group empty or the + // member snapping back; the header view carries on under the daemon's id. + let (settleFailed, applied) = bridge.rows.outcome(bridge.rows.add(intent), resync: { bridge.resync() }) + let editor = editor + let failed: @MainActor () -> Void = { + // Edits made meanwhile go with the group that was not made. + for edit in editor.creating.removeValue(forKey: id) ?? [] { bridge.rows.settle(edit.token) } + settleFailed() + } // Mixed order: the new group's place where the model formed it, // set before members join so it never shows at the end first. let place = bridge.usesMixedOrder && v2 ? PersonalSidebarPlanner(machines: bridge.services.machines).groupPlacement(of: group, in: bridge.model.sections) : PersonalSidebar.GroupPlacement() - let move = place.move, top = place.topIndex - life.commit("create-personal-group", ending: ending, recheck: { life.emptied(by: members, into: nil) }, failed: { bridge.resync() }) { connection in + let move = place.move, top = place.topIndex, flow = self + editor.creating[id] = [] + life.commit("create-personal-group", ending: ending, recheck: { life.emptied(by: members, into: nil) }, failed: failed, + applied: applied, landed: { created in flow.landed(id, as: created) }) { connection -> WorkspaceGroupID in // The v2 operation names the group itself. let created = v2 ? WorkspaceGroupID(rawValue: try await connection.state.createWorkspaceGroup( name: SidebarGroup.named(name), room: room.rawValue, color: color.rawValue, index: move).id) @@ -119,6 +136,80 @@ struct SidebarGroupFlow { try await connection.state.placePersonalWorkspace(session: workspace.session, key: workspace.key, resource: workspace.resource, group: .set(created)) } + return created + } + } + + /// The daemon made the group under `created`: edits made meanwhile go to it. + private func landed(_ local: WorkspaceGroupID, as created: WorkspaceGroupID) { + editor.created[local] = created + guard let pending = editor.creating.removeValue(forKey: local) else { return } + for edit in pending { send(created, name: edit.name, color: edit.color, edit: edit.token) } + } + + /// `.renameGroup` / `.setGroupColor`. The editor opens on a new group at + /// once, under the sidebar's own id: an edit before the daemon made the + /// group waits for it, and later ones go to the daemon's id. + func edit(_ group: CmuxNextSidebar.GroupID, name: String? = nil, color: GroupColor? = nil, _ intent: SidebarIntent) { + // A pending edit until the store holds it, so a recompute (or the + // pending new group's own edit) never shows the old name or color. + let token = bridge.rows.add(intent) + let id = WorkspaceGroupID(rawValue: group.rawValue) + if editor.creating[id] != nil { + editor.creating[id]?.append(PersonalGroupEditorState.Edit(name: name, color: color, token: token)) + return + } + send(editor.created[id] ?? id, name: name, color: color, edit: token) + } + + private func send(_ id: WorkspaceGroupID, name: String?, color: GroupColor?, edit: SidebarPendingEdits.Token) { + let v2 = bridge.statePersonal, bridge = bridge, colorUpdate: FieldUpdate = color.map { .set($0.rawValue) } ?? .unchanged + bridge.rows.send("update-personal-group", edit: edit, on: bridge.services.machines.local, resync: { bridge.resync() }) { connection in + if v2 { return try await connection.state.updateWorkspaceGroup(id.rawValue, name: name, color: colorUpdate) } + try await connection.updatePersonalGroup(id, name: name, color: colorUpdate) + } + } + + // MARK: The group editor's rows + + /// The editor's action rows run through the action registry with the + /// group as their target, the same path as the palette, menus and CLI. + func wireEditor() { + let container = bridge.container + container.groupEditorItems = { [weak bridge = self.bridge] _ in + bridge.map { SidebarGroupFlow(bridge: $0).editorItems() } ?? SidebarContainerView.standardGroupEditorItems() + } + container.onGroupEditorItem = { [weak bridge = self.bridge] group, item in + guard let bridge else { return } + SidebarGroupFlow(bridge: bridge).performEditorItem(group, item) + } + } + + /// The standard rows with each action's current shortcut. + private func editorItems() -> [[SidebarGroupEditorItem]] { + let registry = bridge.services.registry + return SidebarContainerView.standardGroupEditorItems().map { section in + section.map { item in + var item = item + item.shortcut = registry.shortcutDisplay(for: ActionID(rawValue: item.id)) + return item + } + } + } + + private func performEditorItem(_ group: CmuxNextSidebar.GroupID, _ item: String) { + // A group made empty that is about to get a member (New Workspace in + // Group, or an action from its full menu) does not go when the editor closes. + // Delete, Ungroup and Close end the group themselves (no second delete). + let local = WorkspaceGroupID(rawValue: group.rawValue) + if ["workspaceGroup.newWorkspace", SidebarContainerView.moreActionsItem, "workspaceGroup.delete", "workspaceGroup.ungroup", + "workspaceGroup.closeWorkspaces"].contains(item) { + editor.explicit.remove(local) } + guard item != SidebarContainerView.moreActionsItem else { return } + // The daemon's id for a group the sidebar made under its own. + let target = editor.created[local] ?? local + let invocation = ActionInvocation(target: ActionTargetRef(kind: .workspaceGroup, id: target.rawValue), origin: .user) + _ = bridge.services.registry.perform(ActionID(rawValue: item), invocation: invocation) } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarProfileControl.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarProfileControl.swift index 006107f42adb..d9c7fb920757 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarProfileControl.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/SidebarProfileControl.swift @@ -42,8 +42,8 @@ import Observation /// The signed-in user, starting their picture's fetch. private var account: SidebarAccount? { - AccountAvatarImages.shared.load(services.cloud?.auth.user?.profileImageURL) - return SidebarAccount(services.cloud?.auth) + AccountAvatarImages.shared.load(services.cloud.auth.user?.profileImageURL) + return SidebarAccount(services.cloud.auth) } func menu(workspace: String?) -> NSMenu { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/StaticURL.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/StaticURL.swift new file mode 100644 index 000000000000..91dd073cb231 --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/StaticURL.swift @@ -0,0 +1,13 @@ +import Foundation + +/// Fixed URLs the app builds from literals. `URL(string:)` is optional, so a +/// literal goes through `url`, which never traps: a literal that did not +/// parse would become a file URL of the same text. StaticURLTests checks +/// that every case parses, so that fallback is never taken. +nonisolated enum StaticURL: String, CaseIterable { + case feedback = "https://github.com/manaflow-ai/cmux/issues/new" + case documentation = "https://cmux.com/docs" + case blank = "about:blank" + + var url: URL { URL(string: rawValue) ?? URL(fileURLWithPath: rawValue) } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Strings.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Strings.swift index 2b21ae5d8258..531c32cb1a5e 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Strings.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Strings.swift @@ -23,6 +23,9 @@ enum Strings { static var menuSidebarToggleIcon: String { String(localized: "menu.debug.sidebarToggleIcon", defaultValue: "Sidebar Toggle Icon", bundle: .module) } + static var menuStatusIcons: String { + String(localized: "menu.debug.statusIcons", defaultValue: "Status Icons", bundle: .module) + } static var menuServer: String { String(localized: "menu.server", defaultValue: "Server", bundle: .module) } static var menuMinimize: String { String(localized: "menu.window.minimize", defaultValue: "Minimize", bundle: .module) } static var menuZoom: String { String(localized: "menu.window.zoom", defaultValue: "Zoom", bundle: .module) } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/TabAndGroupTargetSource.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/TabAndGroupTargetSource.swift index 4fa7c44713e2..cc2c4433b673 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/TabAndGroupTargetSource.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/TabAndGroupTargetSource.swift @@ -31,7 +31,7 @@ final class TabAndGroupTargetSource: PaletteTargetSource { case .tabGroup: name = panes.flatMap(\.tabGroups).first { $0.id.rawValue == target.id }?.name case .workspaceGroup: - let nodes = (services.windows?.active?.sidebar.model.sections ?? []).flatMap(\.nodes) + let nodes = (services.windows.active?.sidebar.model.sections ?? []).flatMap(\.nodes) name = nodes.compactMap { node -> String? in guard case .group(let group) = node, group.id.rawValue == target.id else { return nil } return group.name diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/TabContentCache+AgentDriven.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/TabContentCache+AgentDriven.swift index da164cb69cb0..9d0df3e53e2e 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/TabContentCache+AgentDriven.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/TabContentCache+AgentDriven.swift @@ -23,7 +23,7 @@ extension TabContentCache { func rebuildForAgent(_ key: String) { guard let page = browsers[key]?.tab else { return } // A page with no URL yet starts over blank. - reroute(key, to: page.state.url ?? URL(string: "about:blank")!) + reroute(key, to: page.state.url ?? StaticURL.blank.url) // `reroute` makes nothing while a page is already being made, or // without a record; the old page goes regardless. if let entry = browsers.removeValue(forKey: key) { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/TabContentCache.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/TabContentCache.swift index 3eef574ed11d..34581bcf9ed0 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/TabContentCache.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/TabContentCache.swift @@ -63,7 +63,7 @@ final class TabContentCache { let pageInstalls = PageInstallCounter() /// Tab `key`'s browser profile: an incognito window's, else nil (default). var browserProfile: ((String) -> BrowserProfileID?)? - private(set) var browserTabs: BrowserTabService! + let browserTabs: BrowserTabService /// Page-originated tab requests (new-tab links, popups, window.close). let pageRequests = BrowserPageRequests() private var pendingBrowsers: Set = [] diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Themes/ThemeCoordinator.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Themes/ThemeCoordinator.swift index a82e8651b0bb..4e37eeca6383 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Themes/ThemeCoordinator.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Themes/ThemeCoordinator.swift @@ -88,12 +88,12 @@ final class ThemeCoordinator { let store = services.machines.local.store let terminalThemes = terminalThemes let local = services.machines.local - Task { + Task { [weak self] in await terminalThemes.load() // Once per launch, after the home daemon's first tree: drop the // themes of its terminals that closed while the app was away. for await loaded in Observations({ local.store.isLoaded }) where loaded { - self.pruneTerminalThemes() + self?.pruneTerminalThemes() return } } @@ -167,11 +167,11 @@ final class ThemeCoordinator { /// Re-reads every theme. `forceSurfaces` re-applies surface configs /// even when unchanged (after a Ghostty config reload reset them). func apply(forceSurfaces: Bool = false) { - for controller in services.windows?.controllers ?? [] { + for controller in services.windows.controllers { windowDidChange(controller) for content in controller.mountedContents { contentDidShow(content) } } - for entry in services.cache?.terminals.values.map({ $0 }) ?? [] { + for entry in services.cache.terminals.values.map({ $0 }) { entry.themeBinding.coordinator = self setTheme(of: entry.themeScope, to: terminalTheme(entry.themeKey)) if forceSurfaces { entry.themeBinding.syncSurface(force: true) } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Usage/AppResourceSource.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Usage/AppResourceSource.swift index 55078f983320..db1b8dd86f80 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Usage/AppResourceSource.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Usage/AppResourceSource.swift @@ -138,8 +138,12 @@ final class AppResourceSource: ResourceSampleSource { resolved.tabs.append(TabResourceSources(tabID: tab.id, title: tab.displayTitle, kind: .terminal, processes: [], estimatedAppBytes: estimate)) let key = ObjectIdentifier(daemon) - if daemonIndex[key] == nil { - daemonIndex[key] = resolved.daemons.count + let index: Int + if let known = daemonIndex[key] { + index = known + } else { + index = resolved.daemons.count + daemonIndex[key] = index resolved.daemons.append(DaemonQuery( host: daemon.isLocal ? ProcessKey.localHost : daemon.machineID, connection: daemon.connection, @@ -147,7 +151,7 @@ final class AppResourceSource: ResourceSampleSource { terminals: [] )) } - resolved.daemons[daemonIndex[key]!].terminals.append(TerminalQuery(tabID: tab.id, surface: tab.surface)) + resolved.daemons[index].terminals.append(TerminalQuery(tabID: tab.id, surface: tab.surface)) case .browser: let page = services.cache.existingBrowser(tab.id)?.tab let kind: TabResourceKind = switch page?.engineKind { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/EphemeralWorkspaces.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/EphemeralWorkspaces.swift index 783aa66b8c30..c4a5c832bf0c 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/EphemeralWorkspaces.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/EphemeralWorkspaces.swift @@ -26,7 +26,7 @@ enum EphemeralWorkspaces { /// the workspace (reconcile gives it the first ephemeral orphan). static func newIncognitoWorkspace(_ manager: WindowManager, window windowID: String, address: String, choice: BrowserEngineChoice) { let daemon = manager.services.daemon - let browserTabs = manager.services.cache.browserTabs! + let browserTabs = manager.services.cache.browserTabs manager.pendingEphemeralWindows.append(windowID) Task { @MainActor in defer { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/PersonalGroupLifecycle.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/PersonalGroupLifecycle.swift index 4c5efd3f2425..af5aa49689e3 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/PersonalGroupLifecycle.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/PersonalGroupLifecycle.swift @@ -1,4 +1,6 @@ import CmuxNextDaemon +import CmuxNextSidebar +import CmuxNextDesign /// When a personal workspace group ends (cx-rcby). The home daemon keeps a /// group until a client deletes it, so the client that moves workspaces @@ -106,19 +108,22 @@ struct PersonalGroupLife { /// `failed` runs when a command fails (the caller re-syncs). /// `applied` runs once the home store holds the command's result /// (read-your-writes): a sidebar pending edit settles there (cx-odqn). - func commit(_ label: String, ending: [WorkspaceGroupID], recheck: @escaping @MainActor () -> [WorkspaceGroupID] = { [] }, - failed: @escaping @MainActor () -> Void, applied: (@MainActor () -> Void)? = nil, - _ body: @escaping @Sendable (DaemonConnection) async throws -> Void) { + /// `landed` gets the command's value as soon as it replied. + func commit(_ label: String, ending: [WorkspaceGroupID], recheck: @escaping @MainActor () -> [WorkspaceGroupID] = { [] }, + failed: @escaping @MainActor () -> Void, applied: (@MainActor () -> Void)? = nil, + landed: @escaping @MainActor (Value) -> Void = { _ in }, + _ body: @escaping @Sendable (DaemonConnection) async throws -> Value) { let home = machines.local, personal = personal, v2 = home.store.servesStateResources let transaction = ClientTransactionID.generate() personal.endingGroups.formUnion(ending) Task { // Shown again before a failure re-syncs, so a kept group never stays hidden. @MainActor func end() { personal.endingGroups.subtract(ending) } - guard await home.request(label, transaction: transaction, { connection, _ in try await body(connection) }) != nil else { + guard let value = await home.request(label, transaction: transaction, { connection, _ in try await body(connection) }) else { end() return failed() } + landed(value) if let applied { home.whenApplied(transaction, applied) } let still = Set(recheck()) let doomed = ending.filter(still.contains) @@ -137,7 +142,7 @@ struct PersonalGroupLife { func deleteIfEmpty(_ group: WorkspaceGroupID, failed: @escaping @MainActor () -> Void) { guard isEmptyUnpinned(group) else { return } let life = self - commit("delete-personal-group", ending: [group], recheck: { life.isEmptyUnpinned(group) ? [group] : [] }, failed: failed) { _ in } + commit("delete-personal-group", ending: [group], recheck: { life.isEmptyUnpinned(group) ? [group] : [] }, failed: failed) { _ -> Void in } } } @@ -148,4 +153,16 @@ struct PersonalGroupLife { final class PersonalGroupEditorState { var pending: WorkspaceGroupID? var explicit: Set = [] + /// Groups the sidebar made that the daemon is still creating: name and + /// color edits made meanwhile (the editor is open on the new group). + var creating: [WorkspaceGroupID: [Edit]] = [:] + + /// A name or color edit waiting for the daemon's id, with its pending row edit. + struct Edit { + var name: String? + var color: GroupColor? + var token: SidebarPendingEdits.Token + } + /// The daemon's id for a group the sidebar made under its own id. + var created: [WorkspaceGroupID: WorkspaceGroupID] = [:] } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/StatusIconSetMenu.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/StatusIconSetMenu.swift new file mode 100644 index 000000000000..259c4bc0a62f --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/StatusIconSetMenu.swift @@ -0,0 +1,56 @@ +import AppKit +import CmuxNextDesign + +/// Debug menu > Status Icons (DEV and NIGHTLY, `DevTools`; cx-kxa2): one +/// item per `StatusIconSet` candidate, with its blocked-question mark and a +/// check on the current one. Choosing writes the Debug Settings tunable, so +/// every indicator restyles at once and the choice persists in the build's +/// debug-tunables.json. Choosing the default removes the override. +final class StatusIconSetMenu: NSObject, NSMenuDelegate { + static let shared = StatusIconSetMenu() + + /// Where the choice is written (tests pass their own store). + var store: TunableStore = .shared + + func makeItem() -> NSMenuItem { + let item = NSMenuItem(title: Strings.menuStatusIcons, action: nil, keyEquivalent: "") + let menu = NSMenu(title: Strings.menuStatusIcons) + menu.delegate = self + for set in StatusIconSet.allCases { + let choice = NSMenuItem(title: set.tunableTitle, action: #selector(choose(_:)), keyEquivalent: "") + choice.target = self + choice.representedObject = set.rawValue + choice.image = set.image(state: .waiting(kind: .question), pointSize: Metrics.smallIconSize) + menu.addItem(choice) + } + item.submenu = menu + updateStates(in: menu) + return item + } + + @objc func choose(_ sender: NSMenuItem) { + guard let raw = sender.representedObject as? String, let set = StatusIconSet(rawValue: raw) else { return } + select(set) + } + + /// Sets the icon set; the default clears the override. + func select(_ set: StatusIconSet) { + let key = StatusIconSet.tunable.key + if set == StatusIconSet.tunable.defaultValue { + store.reset([key]) + } else { + store.set(key, set.tunableValue) + } + } + + func menuNeedsUpdate(_ menu: NSMenu) { + updateStates(in: menu) + } + + private func updateStates(in menu: NSMenu) { + let current = StatusIconSet.tunable.value(in: store).rawValue + for item in menu.items { + item.state = (item.representedObject as? String) == current ? .on : .off + } + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowController.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowController.swift index 79b20d522ea4..84ff877730c3 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowController.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowController.swift @@ -20,7 +20,8 @@ final class WindowController: NSWindowController, NSWindowDelegate { /// This window's focus state machine (plans/cmux-next/focus.md); it /// lives in the window's `WindowState`. var focus: FocusCoordinator { state.focus } - private(set) var focusApplier: FocusEffectApplier! + /// Built in init (lazy because it holds self; no IUO). + private(set) lazy var focusApplier = FocusEffectApplier(controller: self) private(set) var content: WorkspaceContentController? /// Recently shown workspaces kept mounted and paused, oldest first /// (plans/cmux-next/tab-lifecycle.md): switching back to one swaps its @@ -81,7 +82,6 @@ final class WindowController: NSWindowController, NSWindowDelegate { if let frame { window.setFrame(frame, display: false) } else { window.center() } window.delegate = self window.focus = focus - focusApplier = FocusEffectApplier(controller: self) focus.applier = focusApplier focus.send(.appActive(NSApp.isActive)) startShortcutHints() @@ -129,8 +129,8 @@ final class WindowController: NSWindowController, NSWindowDelegate { private func observeWorkspace() { let machines = services.machines - let cloud = services.cloud! - let windows = services.windows! + let cloud = services.cloud + let windows = services.windows let state = state workspaceObservation = Task { [weak self] in for await _ in Observations({ () -> [String] in diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowManager+Creation.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowManager+Creation.swift index 737fa3929379..6f9feacafaf5 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowManager+Creation.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowManager+Creation.swift @@ -30,7 +30,7 @@ extension WindowManager { let target = targetWindow(preferring: state?.id) var spawn = WorkspaceSpawn(newTabPage: true) spawn.slot = slot - Task { + Task { [services] in do { _ = try await createWorkspace(spawn, on: daemon, into: target) } catch { @@ -44,7 +44,7 @@ extension WindowManager { @discardableResult func newWindow(frame: CGRect? = nil) -> String { let windowID = UUID().uuidString.lowercased() - Task { await createWorkspace(into: windowID, frame: frame, newTabPage: true) } + Task { [services] in await createWorkspace(into: windowID, frame: frame, newTabPage: true); withExtendedLifetime(services) {} } return windowID } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowManager+Incognito.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowManager+Incognito.swift index 90ef7597e454..e064242ba883 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowManager+Incognito.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowManager+Incognito.swift @@ -22,7 +22,7 @@ extension WindowManager { // The session begins now, so the window's first page is incognito. _ = incognitoProfile() let daemon = services.daemon - let browserTabs = services.cache.browserTabs! + let browserTabs = services.cache.browserTabs let choice: BrowserEngineChoice = if case .open(let choice) = browserTabs.resolve(requested: nil) { choice } else { @@ -37,7 +37,7 @@ extension WindowManager { // session alive until the window opens. let key = WorkspaceKey.generate() claimNew(workspaceID: key.rawValue, window: windowID) - Task { + Task { [services] in guard let connection = daemon.connection else { pendingClaims[key.rawValue] = nil return endIncognitoSessionIfUnused() diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowManager+Membership.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowManager+Membership.swift index 5611c6876e54..5eccb0189daf 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowManager+Membership.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowManager+Membership.swift @@ -262,7 +262,7 @@ extension WindowManager { /// load state, or the Cloud machine list changes. func observeMembership() { let machines = services.machines - let cloud = services.cloud! + let cloud = services.cloud membershipObservation?.cancel() membershipObservation = Task { [weak self] in for await _ in Observations({ () -> [String] in @@ -350,7 +350,7 @@ extension WindowManager { /// Every Cloud machine that could still report workspaces has loaded. private var cloudSettled: Bool { - guard let cloud = services.cloud, cloud.isSignedIn || cloud.auth.isRestoring else { return true } + guard case let cloud = services.cloud, cloud.isSignedIn || cloud.auth.isRestoring else { return true } guard cloud.hasLoadedMachines else { return false } return services.machines.cloud.allSatisfy { !$0.machine.status.isLive || $0.daemon.store.isLoaded } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowManager+Profiles.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowManager+Profiles.swift index 406f4a11b5cc..bbd94072c57d 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowManager+Profiles.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowManager+Profiles.swift @@ -32,7 +32,7 @@ extension WindowManager { // soon as the daemon mirrors it. state.enterProfile(profile) recordSaver.stateDidChange(state) - Task { await createWorkspace(into: state.id) } + Task { [services] in await createWorkspace(into: state.id); withExtendedLifetime(services) {} } return } let remembered = state.profileWorkspaces[profile].flatMap { visible.contains($0) ? $0 : nil } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowMembershipHandlers.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowMembershipHandlers.swift index d69905b83ac3..986aa9d6cb9f 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowMembershipHandlers.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowMembershipHandlers.swift @@ -31,7 +31,7 @@ enum WindowMembershipHandlers { /// when it is part of a multi-selection there. static func workspaces(_ invocation: ActionInvocation, _ context: AppActionContext) throws -> [String] { let id = try context.workspace(invocation).model.id - let windows = context.services.windows! + let windows = context.services.windows guard let owner = windows.registry.value.owner(of: id), let controller = windows.controller(for: owner) else { return [id] } let selection = controller.sidebar.model.orderedSelection.map(\.rawValue) return selection.count > 1 && selection.contains(id) ? selection : [id] @@ -59,7 +59,7 @@ enum WindowMembershipHandlers { /// every workspace of that window, the window itself moves there (like /// dragging them out): no second window opens and none closes. static func toNewWindow(_ ids: [String], _ context: AppActionContext) { - let windows = context.services.windows! + let windows = context.services.windows let source = ids.first.flatMap { windows.registry.value.owner(of: $0) }.flatMap(windows.controller(for:)) let frame = source?.window?.frame.offsetBy(dx: 28, dy: -28) if let source, let frame, Set(ids) == Set(windows.registry.members(of: source.state.id)) { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowTargetSource.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowTargetSource.swift index 930d65967ca3..61df6a3bf304 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowTargetSource.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Windows/WindowTargetSource.swift @@ -45,7 +45,7 @@ final class WindowTargetSource: PaletteTargetSource { } private func windows() -> [PaletteTargetOption] { - let windows = services.windows! + let windows = services.windows let active = windows.active?.state.id let options = windows.controllers.enumerated().map { index, controller in let name = controller.state.workspaceID.flatMap { services.workspace(id: $0)?.displayName } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/WorkspaceContentController+Intents.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/WorkspaceContentController+Intents.swift index 148d04a3899b..0099210f1322 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/WorkspaceContentController+Intents.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/WorkspaceContentController+Intents.swift @@ -98,13 +98,15 @@ extension WorkspaceContentController { _ body: @escaping @Sendable (DaemonConnection) async throws -> SurfaceCreated) { guard let connection = daemon.connection else { return } let intent = beginFocusIntent() - Task { + // [services, state]: the task pins this controller's owners until it ends (cx-6so P1b). + Task { [services, state] in do { expectFocus(on: try await body(connection).surface, generation: intent) then?() } catch { daemon.logger.error("\(label, privacy: .public) failed: \(String(describing: error), privacy: .public)") } + withExtendedLifetime((services, state)) {} } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/WorkspaceContentController.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/WorkspaceContentController.swift index 3ddbe4513da7..c1d229aeb667 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/WorkspaceContentController.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/WorkspaceContentController.swift @@ -13,11 +13,12 @@ final class WorkspaceContentController: LayoutPaneContentProvider { /// The machine daemon that owns `workspace`; every command goes there. let daemon: DaemonService let layoutModel = LayoutModel() - private(set) var layoutView: LayoutRootView! + // Built in init in this order (lazy because they hold self; no IUOs). + private(set) lazy var layoutView = LayoutRootView(model: layoutModel, contentProvider: self) /// Layout plus the bottom screen bar; what the window shows. - private(set) var contentView: WorkspaceContentView! + private(set) lazy var contentView = WorkspaceContentView(layoutView: layoutView, bar: screenBar.view) private(set) var emptyView: EmptyWorkspaceView? - private(set) var screenBar: ScreenBarController! + private(set) lazy var screenBar = ScreenBarController(content: self) /// The workspace theme: only this content area, under the window's /// room theme. let themeScope = ThemeScope(level: .workspace) @@ -61,9 +62,9 @@ final class WorkspaceContentController: LayoutPaneContentProvider { self.state = state focus = state.focus layoutModel.intentHandler = { [weak self] intent in self?.handle(intent) } - layoutView = LayoutRootView(model: layoutModel, contentProvider: self) - screenBar = ScreenBarController(content: self) - contentView = WorkspaceContentView(layoutView: layoutView, bar: screenBar.view) + _ = layoutView // built here, then the bar and the content view, as before + _ = screenBar + _ = contentView let fallbackCreate = emptyWorkspaceRepair.create emptyWorkspaceRepair.createFirst = { [weak services, weak daemon] key in guard let services, let daemon, let workspace = daemon.store.workspaces.first(where: { $0.key == key }) else { throw DaemonError.notConnected } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApps/Store/AppStoreCatalog.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApps/Store/AppStoreCatalog.swift index 21c6de3c8d41..1683281387f0 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApps/Store/AppStoreCatalog.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApps/Store/AppStoreCatalog.swift @@ -19,7 +19,7 @@ public nonisolated struct BundledAppStoreCatalog: AppStoreCatalog { public func search(query: String, category: String?) async throws -> [AppStoreListing] { listings.filter { listing in - (category == nil || listing.categories.contains(category!)) && listing.matches(query) + (category.map { listing.categories.contains($0) } ?? true) && listing.matches(query) } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBookmarks/Codec/TagScanner.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBookmarks/Codec/TagScanner.swift index 74f2db9618dc..d9f0da87d1ec 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBookmarks/Codec/TagScanner.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBookmarks/Codec/TagScanner.swift @@ -149,6 +149,6 @@ nonisolated struct TagScanner { } private static func lower(_ scalar: Unicode.Scalar) -> Unicode.Scalar { - ("A"..."Z").contains(scalar) ? Unicode.Scalar(scalar.value + 32)! : scalar + ("A"..."Z").contains(scalar) ? Unicode.Scalar(scalar.value + 32) ?? scalar : scalar } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBookmarks/UI/BookmarkEditorState.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBookmarks/UI/BookmarkEditorState.swift index 7e2d241938a6..ec001ad83506 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBookmarks/UI/BookmarkEditorState.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBookmarks/UI/BookmarkEditorState.swift @@ -26,7 +26,8 @@ public struct BookmarkEditorState: Identifiable, Equatable, Sendable { /// `cmux://bookmarks`, the manager page's address. public nonisolated enum BookmarkPageAddress { public static let string = "cmux://bookmarks" - public static var url: URL { URL(string: string)! } + /// The page address (a literal a test parses; /dev/null stands in rather than a trap). + public static let url: URL = URL(string: string) ?? URL(fileURLWithPath: "/dev/null") /// `cmux://bookmarks`, with or without a trailing slash, query or fragment. public static func matches(_ url: URL?) -> Bool { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBridge/ProgramStatusNotification.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBridge/ProgramStatusNotification.swift index 97fb015a196d..3ddef424ae94 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBridge/ProgramStatusNotification.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBridge/ProgramStatusNotification.swift @@ -56,6 +56,17 @@ public struct ProgramStatusNotification: Hashable, Sendable { .flatMap { record in reason(record).map { ProgramStatusNotification(record: record, reason: $0) } } } + /// Whether a `terminal` notification reads like an OSC 7501 alert (" + /// " at the verb's level) whose record may not have arrived yet: + /// the session events stream can deliver the record after the + /// notification, so the app waits briefly for it before the banner. + public static func looksLikeAlert(title: String, level: NotificationLevel) -> Bool { + Reason.allCases.contains { reason in + let suffix = " " + verb(reason) + return Self.level(reason) == level && title.hasSuffix(suffix) && title.count > suffix.count + } + } + /// The daemon's notification text limits (terminal_metadata.rs). static let titleLimit = 256 static let bodyLimit = 1024 diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBridge/StatusMapping.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBridge/StatusMapping.swift index de2cc4e5f5b3..ad0a41811bd7 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBridge/StatusMapping.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBridge/StatusMapping.swift @@ -63,6 +63,14 @@ public struct StatusMapping { turn(tab) == .needsInput || ProgramStatusRecord.strongest(tab.programStatus)?.state == .blocked } + /// What the tab's strongest blocked OSC 7501 record waits for + /// (permission, question, auth), for the tab's needs-input badge; nil + /// when nothing blocks or the program named no kind. + public func blockedKind(_ tab: TabModel) -> StatusBlockedKind? { + guard let record = ProgramStatusRecord.strongest(tab.programStatus), record.state == .blocked else { return nil } + return record.kind.flatMap { StatusBlockedKind(rawValue: $0.rawValue) } + } + /// An unseen OSC 7501 outcome for the tab's badge: `error` is a failure, /// `done` a success, until the user looks at the terminal. Nil while a /// stronger record (blocked, working) is live or nothing is unseen. @@ -127,7 +135,7 @@ public struct StatusMapping { func state(_ record: ProgramStatusRecord) -> StatusIndicatorState? { switch record.state { case .working: .working(progress: record.progress.map { Double($0) / 100 }) - case .blocked: .waiting + case .blocked: .waiting(kind: record.kind.flatMap { StatusBlockedKind(rawValue: $0.rawValue) }) case .error: .error case .done: .success case .idle: nil diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBridge/TabItemMapping.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBridge/TabItemMapping.swift index 189ed4332064..03679a8d9ee5 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBridge/TabItemMapping.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBridge/TabItemMapping.swift @@ -37,6 +37,7 @@ public struct TabItemMapping { ) if busy.state.replacesTabIcon { item.indicator = busy.state } item.busyStyle = busy.style + if item.status == .needsInput { item.blockedKind = StatusMapping.shared.blockedKind(tab) } applyUserIcon(tab, to: &item) return item } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/CEF/BrowserExtensionInfo.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/CEF/BrowserExtensionInfo.swift index f89a8a5b13da..4e242bb86c6c 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/CEF/BrowserExtensionInfo.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/CEF/BrowserExtensionInfo.swift @@ -118,6 +118,8 @@ public nonisolated struct BrowserExtensionInfo: Hashable, Sendable, Identifiable /// Chrome Web Store pages for extensions. extension URL { - public static let browserExtensionWebStore = URL(string: "https://chromewebstore.google.com/category/extensions")! - public static let browserExtensionManagement = URL(string: "chrome://extensions")! + // Literals a test parses; /dev/null stands in rather than a trap. + public static let browserExtensionWebStore = URL(string: "https://chromewebstore.google.com/category/extensions") + ?? URL(fileURLWithPath: "/dev/null") + public static let browserExtensionManagement = URL(string: "chrome://extensions") ?? URL(fileURLWithPath: "/dev/null") } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/CEF/CEFDevToolsController.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/CEF/CEFDevToolsController.swift index 9d86a8b5a4e9..e35a9b0f4f8a 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/CEF/CEFDevToolsController.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/CEF/CEFDevToolsController.swift @@ -81,7 +81,7 @@ final class CEFDevToolsController { // Between dock sides: the same DevTools window, a new frame. tab.devTools.dock = dock views?.divider.needsDisplay = true - views?.divider.window?.invalidateCursorRects(for: views!.divider) + if let divider = views?.divider { divider.window?.invalidateCursorRects(for: divider) } tab.container.layoutContent() return } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/CEF/CEFRuntime.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/CEF/CEFRuntime.swift index 5687d0a290b1..ccb8a1d6fab4 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/CEF/CEFRuntime.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/CEF/CEFRuntime.swift @@ -330,14 +330,14 @@ final class CEFRuntime { // Chromium never opens a window (fork API 8) nor focuses a page of its own. shim.setWindowRequestHandler(cefWindowRequestCallback) shim.setFocusRequestHandler(cefFocusRequestCallback) - let ok = switchStorage.withUnsafeBufferPointer { buffer in - buffer.baseAddress!.withMemoryRebound(to: UnsafePointer?.self, capacity: buffer.count) { list in + let ok = switchStorage.withUnsafeBufferPointer { buffer in // never empty (ends with nil); no base: 0, a failed init + buffer.baseAddress?.withMemoryRebound(to: UnsafePointer?.self, capacity: buffer.count) { list in shim.initialize( layout.frameworkDirectory.path, layout.mainBundle.path, layout.helperExecutable.path, storage.root.path, storage.logFile.path, 0, locale.locale, locale.acceptLanguages, list, context, cefScheduleCallback, cefEventCallback, cefKeyCallback ) - } + } ?? 0 } guard ok == 1 else { pump.stop() diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/CEF/CEFTab.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/CEF/CEFTab.swift index c48dcfddec35..33fe95f3ae37 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/CEF/CEFTab.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/CEF/CEFTab.swift @@ -363,7 +363,7 @@ public final class CEFTab: BrowserTab, BrowserOcclusionHosting, BrowserExtension public func exitContentFullscreen() { guard state.isContentFullscreen else { return } - Task { _ = try? await evaluate("document.exitFullscreen && document.exitFullscreen()") } + Task { [runtime] in _ = try? await evaluate("document.exitFullscreen && document.exitFullscreen()"); withExtendedLifetime(runtime) {} } } public func showDevTools() { performDevTools(.show) } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/Core/Identifiers.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/Core/Identifiers.swift index 7e2b0ac26730..bc8dfda4dd60 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/Core/Identifiers.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/Core/Identifiers.swift @@ -30,7 +30,8 @@ public nonisolated struct BrowserProfileID: RawRepresentable, Hashable, Sendable /// The built-in profile. It has its own fixed UUID so that its storage is /// a normal identified store, never the engine's shared default store. public static let `default` = BrowserProfileID( - rawValue: UUID(uuidString: "8E5C0D1F-2B7A-4F3C-9A61-5D2E7B0C4A11")! + // 8E5C0D1F-2B7A-4F3C-9A61-5D2E7B0C4A11 as bytes (non-optional by construction). + rawValue: UUID(uuid: (0x8E, 0x5C, 0x0D, 0x1F, 0x2B, 0x7A, 0x4F, 0x3C, 0x9A, 0x61, 0x5D, 0x2E, 0x7B, 0x0C, 0x4A, 0x11)) ) public var description: String { rawValue.uuidString } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/Engine/MockBrowserEngine.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/Engine/MockBrowserEngine.swift index c9292fab7c34..ebc26edf34cb 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/Engine/MockBrowserEngine.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/Engine/MockBrowserEngine.swift @@ -149,12 +149,13 @@ public final class MockBrowserTab: BrowserTab { @discardableResult public func presentPrompt(_ kind: BrowserPromptKind, origin: String) async -> BrowserPromptResponse { await withCheckedContinuation { continuation in - var prompt: BrowserPrompt! - prompt = BrowserPrompt(kind: kind, origin: origin) { [weak self] response in + var prompt: BrowserPrompt? + let made = BrowserPrompt(kind: kind, origin: origin) { [weak self] response in self?.pendingPrompts.removeAll { $0 === prompt } continuation.resume(returning: response) } - pendingPrompts.append(prompt) + prompt = made + pendingPrompts.append(made) } } @@ -210,7 +211,7 @@ public final class MockBrowserTab: BrowserTab { let size = 4 let context = CGContext( data: nil, width: size, height: size, bitsPerComponent: 8, bytesPerRow: 0, - space: CGColorSpace(name: CGColorSpace.sRGB)!, + space: CGColorSpace(name: CGColorSpace.sRGB) ?? CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue ) context?.setFillColor(gray: 0.5, alpha: 1) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/Favicon/FaviconLoader.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/Favicon/FaviconLoader.swift index 55fdf8babd8f..9ab90232acec 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/Favicon/FaviconLoader.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/Favicon/FaviconLoader.swift @@ -95,7 +95,7 @@ public final class BrowserFaviconLoader: BrowserFaviconLoading { let width = max(1, Int((CGFloat(best.width) * scale).rounded())) let height = max(1, Int((CGFloat(best.height) * scale).rounded())) guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, - space: CGColorSpace(name: CGColorSpace.sRGB)!, + space: CGColorSpace(name: CGColorSpace.sRGB) ?? CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil } context.interpolationQuality = .high context.draw(best, in: CGRect(x: 0, y: 0, width: width, height: height)) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/Omnibox/BrowserURLResolver.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/Omnibox/BrowserURLResolver.swift index aba47917d16b..a6064b5b16d7 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/Omnibox/BrowserURLResolver.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/Omnibox/BrowserURLResolver.swift @@ -95,7 +95,7 @@ public nonisolated struct BrowserURLResolver: Sendable { let port = afterColon.prefix { $0.isNumber } if !port.isEmpty, !afterColon.hasPrefix("//") { let rest = afterColon.dropFirst(port.count) - if rest.isEmpty || "/?#".contains(rest.first!) { + if rest.first.map({ "/?#".contains($0) }) ?? true { return nil } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/Omnibox/OmnibarKeyword.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/Omnibox/OmnibarKeyword.swift index d5d90b16cf5e..274e2cf6fc4d 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/Omnibox/OmnibarKeyword.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/Omnibox/OmnibarKeyword.swift @@ -45,7 +45,7 @@ public nonisolated struct OmnibarKeyword: Hashable, Sendable { components.scheme = "cmux-omnibox" components.host = extensionID.isEmpty ? "extension" : extensionID components.path = "/" + content - let url = components.url ?? URL(string: "cmux-omnibox://extension/")! + let url = components.url ?? URL(string: "cmux-omnibox://extension/") ?? URL(fileURLWithPath: "/dev/null") var row = BrowserSuggestion(kind: .keyword, title: description.isEmpty ? content : description, detail: description.isEmpty || description == content ? "" : content, url: url, score: Double(1000 - rank)) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/PageInfo/UI/CertificateViewerWindow.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/PageInfo/UI/CertificateViewerWindow.swift index 74ca0964a6ce..77c8d902a04e 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/PageInfo/UI/CertificateViewerWindow.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/PageInfo/UI/CertificateViewerWindow.swift @@ -77,7 +77,7 @@ final class CertificateViewerWindow: PageInfoWindow { private func generalView(_ certificate: PageInfoCertificate) -> NSView { let missing = PageInfoStrings.notPartOfCertificate - func value(_ text: String?) -> String { text?.isEmpty == false ? text! : missing } + func value(_ text: String?) -> String { text.flatMap { $0.isEmpty ? nil : $0 } ?? missing } let dates = DateFormatter() dates.dateStyle = .full dates.timeStyle = .long diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/UI/AddressBarView.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/UI/AddressBarView.swift index 2ad814da8103..c65c4a3ced1b 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/UI/AddressBarView.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/UI/AddressBarView.swift @@ -37,8 +37,9 @@ public final class AddressBarView: NSView { let starButton = BookmarkStarButton() /// The trailing badges (browser profile, machine, bookmark star); hidden ones take no room. private lazy var badges = NSStackView(views: [profileBadgeView, machineBadgeView, starButton]) - private var fieldToEdge: NSLayoutConstraint! - private var fieldToBadge: NSLayoutConstraint! + // Built on first use in init (no IUO). + private lazy var fieldToEdge = field.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -OmnibarStyle.trailingPadding) + private lazy var fieldToBadge = field.trailingAnchor.constraint(equalTo: badges.leadingAnchor, constant: -OmnibarStyle.textLeading) let panel = OmniboxSuggestionPanel() let density = DensityBinding() @@ -48,7 +49,20 @@ public final class AddressBarView: NSView { /// Set by `focus()` for the responder change it causes. var pendingFocusSource: OmnibarInput.FocusSource? private var security: BrowserSecurityState = .none - private(set) var controller: OmnibarController! + /// Built in init, where `onEffect` is set (no IUO; lazy because its closures capture self). + private(set) lazy var controller = OmnibarController( + field: field, + popup: self, + // Once the view is gone (a controller that outlives it): the engine's plain + // resolver, as `suggest` answers `finished`. + resolver: { [weak self, suggestionEngine] in self?.resolver ?? suggestionEngine.resolver }, + suggest: { [weak self] request in + guard let self else { return OmniboxDelivery.finished } + var request = request + request.tabKey = tabKey + return suggestionEngine.deliveries(for: request) + } + ) /// Chromium tabs also load `chrome://` and `chrome-extension://` pages /// (Chromium's own WebUI and extension pages, which WebKit cannot show). @@ -82,19 +96,6 @@ public final class AddressBarView: NSView { self.suggestionEngine = suggestionEngine super.init(frame: .zero) translatesAutoresizingMaskIntoConstraints = false - controller = OmnibarController( - field: field, - popup: self, - // Once the view is gone (a controller that outlives it): the engine's plain - // resolver, as `suggest` answers `finished`. - resolver: { [weak self, suggestionEngine] in self?.resolver ?? suggestionEngine.resolver }, - suggest: { [weak self] request in - guard let self else { return OmniboxDelivery.finished } - var request = request - request.tabKey = tabKey - return suggestionEngine.deliveries(for: request) - } - ) controller.onEffect = { [weak self] effect in self?.perform(effect) } controller.onStep = { [weak self] in self?.updateChrome() } @@ -125,8 +126,6 @@ public final class AddressBarView: NSView { badges.spacing = 4 badges.translatesAutoresizingMaskIntoConstraints = false addSubview(badges) - fieldToEdge = field.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -OmnibarStyle.trailingPadding) - fieldToBadge = field.trailingAnchor.constraint(equalTo: badges.leadingAnchor, constant: -OmnibarStyle.textLeading) NSLayoutConstraint.activate([ density.bind(heightAnchor.constraint(equalToConstant: 0)) { OmnibarStyle.barHeight }, pill.leadingAnchor.constraint(equalTo: leadingAnchor), diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/UI/BrowserChromeView.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/UI/BrowserChromeView.swift index 76dcba4157e6..59def4c5bc78 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/UI/BrowserChromeView.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/UI/BrowserChromeView.swift @@ -63,7 +63,12 @@ public final class BrowserChromeView: NSView { private let promptBar = PromptBarView() private let promptDialogs = BrowserPromptDialogs() let pageStatus = PageStatusViews() - var toolbarHeight: NSLayoutConstraint! + /// Bound in setup (first read there), never an IUO. + lazy var toolbarHeight: NSLayoutConstraint = density.bind(toolbar.heightAnchor.constraint(equalToConstant: 0)) { [weak self] in + // A deallocated chrome view's constraint is never laid out again. + guard let self else { return 0 } + return isToolbarHidden ? 0 : currentToolbarHeight + } private var observation: ObservationLoop? private var showsStop = false var isToolbarHidden = false @@ -197,11 +202,7 @@ public final class BrowserChromeView: NSView { addSubview(promptBar) addSubview(findBar) - toolbarHeight = density.bind(toolbar.heightAnchor.constraint(equalToConstant: 0)) { [weak self] in - // A deallocated chrome view's constraint is never laid out again. - guard let self else { return 0 } - return isToolbarHidden ? 0 : currentToolbarHeight - } + _ = toolbarHeight // binds it here, in the same order as before density.update { [extensionSlot, toolbarButtons] in extensionSlot.spacing = BrowserMetrics.buttonSpacing toolbarButtons.spacing = BrowserMetrics.buttonSpacing diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/UI/BrowserDebugWindow.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/UI/BrowserDebugWindow.swift index 774532d6ae33..a13aa80373e1 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/UI/BrowserDebugWindow.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/UI/BrowserDebugWindow.swift @@ -32,7 +32,7 @@ public final class BrowserDebugWindow: NSObject, BrowserTabDelegate { @discardableResult public static func showIfRequested(environment: [String: String] = ProcessInfo.processInfo.environment) -> String? { guard let engineName = environment["CMUX_NEXT_DEBUG_BROWSER"], !engineName.isEmpty else { return nil } - let url = environment["CMUX_NEXT_DEBUG_BROWSER_URL"].flatMap(URL.init(string:)) ?? URL(string: "https://example.com")! + let url = environment["CMUX_NEXT_DEBUG_BROWSER_URL"].flatMap(URL.init(string:)) ?? URL(string: "https://example.com") ?? URL(fileURLWithPath: "/dev/null") let report = environment["CMUX_NEXT_DEBUG_BROWSER_REPORT"].map { URL(filePath: $0) } let configuration = BrowserTabConfiguration(initialURL: url, pane: BrowserPaneID(rawValue: "debug-window")) do { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/UI/LoadErrorView.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/UI/LoadErrorView.swift index b0aaa6e06209..66543c1d7a4d 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/UI/LoadErrorView.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/UI/LoadErrorView.swift @@ -11,9 +11,10 @@ final class LoadErrorView: NSView { var onProceed: (() -> Void)? private let titleLabel = NSTextField(labelWithString: Strings.loadFailedTitle) private let messageLabel = NSTextField(wrappingLabelWithString: "") - private(set) var retryButton: ChromeTextButton! - private(set) var backButton: ChromeTextButton! - private(set) var proceedButton: ChromeTextButton! + // Targets are set in init (no IUOs). + let retryButton = ChromeTextButton(title: Strings.tryAgain, prominent: true, action: #selector(LoadErrorView.retry), target: nil) + let backButton = ChromeTextButton(title: Strings.certificateBackToSafety, prominent: true, action: #selector(LoadErrorView.goBack), target: nil) + let proceedButton = ChromeTextButton(title: "", prominent: false, action: #selector(LoadErrorView.proceed), target: nil) let detailsButton = ChromeTextButton(title: Strings.certificateShowDetails, prominent: false, action: nil, target: nil) let detailsLabel = NSTextField(wrappingLabelWithString: "") private(set) var showsDetails = false @@ -24,12 +25,8 @@ final class LoadErrorView: NSView { super.init(frame: frame) wantsLayer = true messageLabel.alignment = .center - let retry = ChromeTextButton(title: Strings.tryAgain, prominent: true, action: #selector(retry), target: self) - let back = ChromeTextButton(title: Strings.certificateBackToSafety, prominent: true, action: #selector(goBack), target: self) - let proceed = ChromeTextButton(title: "", prominent: false, action: #selector(proceed), target: self) - retryButton = retry - backButton = back - proceedButton = proceed + let retry = retryButton, back = backButton, proceed = proceedButton + for button in [retry, back, proceed] { button.target = self } detailsButton.action = #selector(toggleDetails) detailsButton.target = self detailsLabel.alignment = .center diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/WebKit/WebKitTab+Delegates.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/WebKit/WebKitTab+Delegates.swift index 405804862529..d5aa5c4e744c 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/WebKit/WebKitTab+Delegates.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/WebKit/WebKitTab+Delegates.swift @@ -74,17 +74,17 @@ extension WebKitTab: WKNavigationDelegate { downloads.register(download, source: navigationResponse.response.url) } - public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { + public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation?) { guard let id = navigationID(for: navigation, creating: true) else { return } apply(.started(id, url: webView.url)) } - public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) { + public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation?) { guard let id = navigationID(for: navigation, creating: false) else { return } apply(.redirected(id, url: webView.url)) } - public func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { + public func webView(_ webView: WKWebView, didCommit navigation: WKNavigation?) { guard let id = navigationID(for: navigation, creating: false) else { return } apply(.committed(id, url: webView.url)) pageInfoActivity.documentCommitted(origin: webView.url.flatMap(PageInfoSite.origin(of:))) @@ -95,7 +95,7 @@ extension WebKitTab: WKNavigationDelegate { syncSecurity() } - public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { + public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation?) { guard let id = navigationID(for: navigation, creating: false) else { return } forgetNavigation(navigation) apply(.finished(id)) @@ -104,13 +104,13 @@ extension WebKitTab: WKNavigationDelegate { refreshFavicon() } - public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: any Error) { + public func webView(_ webView: WKWebView, didFail navigation: WKNavigation?, withError error: any Error) { guard let id = navigationID(for: navigation, creating: false) else { return } forgetNavigation(navigation) apply(.failed(id, BrowserLoadError(error))) } - public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: any Error) { + public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation?, withError error: any Error) { guard let id = navigationID(for: navigation, creating: false) else { return } forgetNavigation(navigation) apply(.failed(id, BrowserLoadError(error))) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowserAutomation/DOMKeyCodes.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowserAutomation/DOMKeyCodes.swift index 2f8d32fda1a9..21a8f75403b1 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowserAutomation/DOMKeyCodes.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowserAutomation/DOMKeyCodes.swift @@ -38,7 +38,7 @@ nonisolated enum DOMKeyCodes { "AltLeft": .option, "AltRight": .option, "MetaLeft": .command, "MetaRight": .command, "CapsLock": .capsLock, ] - private static func function(_ value: Int) -> String { String(Character(UnicodeScalar(UInt32(value))!)) } + private static func function(_ value: Int) -> String { String(Character(UnicodeScalar(UInt32(value)) ?? UnicodeScalar(0))) } /// Characters AppKit puts on named keys (NSEvent function-key range). static let namedCharacters: [String: String] = { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowserImport/Parsers/FirefoxSessionReader.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowserImport/Parsers/FirefoxSessionReader.swift index ddca0e9e8e4a..6d76e55f80f3 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowserImport/Parsers/FirefoxSessionReader.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowserImport/Parsers/FirefoxSessionReader.swift @@ -30,8 +30,10 @@ public struct FirefoxSessionReader { guard size > 0, size <= maximumSize else { return nil } var output = [UInt8](repeating: 0, count: size) let written = bytes.withUnsafeBufferPointer { source in - output.withUnsafeMutableBufferPointer { destination in - compression_decode_buffer(destination.baseAddress!, size, source.baseAddress! + 12, bytes.count - 12, nil, COMPRESSION_LZ4_RAW) + output.withUnsafeMutableBufferPointer { destination -> Int in + // Both buffers are non-empty (checked above); without a base address nothing decodes. + guard let target = destination.baseAddress, let input = source.baseAddress else { return 0 } + return compression_decode_buffer(target, size, input + 12, bytes.count - 12, nil, COMPRESSION_LZ4_RAW) } } return written == size ? Data(output) : nil diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowserImport/Passwords/PasswordCSVImporter.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowserImport/Passwords/PasswordCSVImporter.swift index cc08e409410f..26f4c0b7e8ec 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowserImport/Passwords/PasswordCSVImporter.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowserImport/Passwords/PasswordCSVImporter.swift @@ -40,10 +40,11 @@ public struct PasswordCSVImporter: Sendable { guard size <= maximumSize else { throw .unreadable } var failed = false let bytes = SecretBytes(capacity: size) { out in + guard let base = out.baseAddress else { return 0 } // an empty buffer reads nothing var done = 0 // Each read returns at least one byte until the end, so this ends within size + 1 steps. for _ in 0...size where done < size && !failed { - let count = Darwin.read(descriptor, out.baseAddress! + done, size - done) // concurrency-allow: called only from Task.detached in run(file:intoProfile:) + let count = Darwin.read(descriptor, base + done, size - done) // concurrency-allow: called only from Task.detached in run(file:intoProfile:) if count > 0 { done += count } else if count == 0 || errno != EINTR { failed = count < 0; break } } return done diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowserImport/Sources/ImportedExtension.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowserImport/Sources/ImportedExtension.swift index 3f74a416c3df..bce98e26014d 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowserImport/Sources/ImportedExtension.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowserImport/Sources/ImportedExtension.swift @@ -20,8 +20,9 @@ public struct ImportedExtension: Sendable, Codable, Hashable, Identifiable { } /// The extension's Chrome Web Store page, where Chromium installs it. - public var webStoreURL: URL { - URL(string: "https://chromewebstore.google.com/detail/\(id)")! + /// nil for an id that does not form a URL (ids come from the imported profile's files). + public var webStoreURL: URL? { + URL(string: "https://chromewebstore.google.com/detail/\(id)") } /// Chrome extension ids are 32 letters from a to p. diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextCloud/Config/CloudConfiguration.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextCloud/Config/CloudConfiguration.swift index 71000a56c5c2..2399351d5b10 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextCloud/Config/CloudConfiguration.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextCloud/Config/CloudConfiguration.swift @@ -57,9 +57,15 @@ public struct CloudConfiguration: Sendable, Equatable { .appendingPathComponent(bundleID ?? "cmux", isDirectory: true) } - public var callbackURL: URL { URL(string: "\(callbackScheme)://auth-callback")! } + /// `://auth-callback`. `resolve` accepts only a scheme that forms this URL; + /// /dev/null stands in for a hand-built configuration with one that does not. + public var callbackURL: URL { URL(string: "\(callbackScheme)://auth-callback") ?? Self.inertURL } - static let productionOrigin = URL(string: "https://cmux.com")! + /// Stands in where a literal URL failed to parse (tests parse every literal). + static let inertURL = URL(fileURLWithPath: "/dev/null") + static let productionOrigin = URL(string: "https://cmux.com") ?? inertURL + static let stackOrigin = URL(string: "https://api.stack-auth.com") ?? inertURL + static let localDevelopmentOrigin = URL(string: "http://localhost:3777") ?? inertURL static let developmentProjectID = "454ecd03-1db2-4050-845e-4ce5b0cd9895" static let developmentClientKey = "pck_xb63160bwe9699vtxfzfj6emmxpafg5mkjrtp6ehzxv5g" static let productionProjectID = "9790718f-14cd-4f7e-824d-eaf527a82b82" @@ -79,9 +85,10 @@ public struct CloudConfiguration: Sendable, Equatable { } let production = !isDebugBuild || value("CMUX_AUTH_ENVIRONMENT")?.lowercased() == "production" let tag = value("CMUX_TAG").flatMap(sanitizedSchemeTag) - let scheme = value("CMUX_AUTH_CALLBACK_SCHEME") + // A scheme that cannot form `://auth-callback` is ignored (it trapped at sign-in). + let scheme = value("CMUX_AUTH_CALLBACK_SCHEME").flatMap { URL(string: "\($0)://auth-callback") == nil ? nil : $0 } ?? (isDebugBuild ? (tag.map { "cmux-dev-\($0)" } ?? "cmux-dev") : defaultScheme(bundleID)) - let stackBase = value("CMUX_STACK_BASE_URL").flatMap(URL.init(string:)) ?? URL(string: "https://api.stack-auth.com")! + let stackBase = value("CMUX_STACK_BASE_URL").flatMap(URL.init(string:)) ?? stackOrigin if production { return CloudConfiguration( backend: .production, apiBaseURL: productionOrigin, authWebOrigin: productionOrigin, @@ -92,7 +99,8 @@ public struct CloudConfiguration: Sendable, Equatable { let api = value("CMUX_VM_API_BASE_URL").flatMap(URL.init(string:)) ?? value("CMUX_API_BASE_URL").flatMap(URL.init(string:)) ?? devBackend - ?? URL(string: "http://localhost:\(value("CMUX_PORT") ?? "3777")")! + ?? URL(string: "http://localhost:\(value("CMUX_PORT") ?? "3777")") + ?? localDevelopmentOrigin let web = value("CMUX_AUTH_WWW_ORIGIN").flatMap(URL.init(string:)) ?? devBackend ?? api let backend: Backend = isLoopback(api) && devBackend == nil ? .localOnly(api) : .development(api) return CloudConfiguration( @@ -104,6 +112,16 @@ public struct CloudConfiguration: Sendable, Equatable { } /// This process's configuration. + /// The API Worker (`/v1/read`, `/v1/ops`, `/v1/auth/*`): production + /// auth uses cloud-api.cmux.dev, everything else the staging Worker. The + /// `CMUX_NEXT_FEED_API_URL` override is honored in debug builds only, so + /// a release build never sends a credential to another origin. + public func ownerAPIBaseURL(environment: [String: String] = ProcessInfo.processInfo.environment) -> URL { + if isDebugBuild, let raw = environment["CMUX_NEXT_FEED_API_URL"], let url = URL(string: raw) { return url } + // crash-allow: both operands are constant, valid https URL literals, so the parse cannot fail + return URL(string: isProductionAuth ? "https://cloud-api.cmux.dev" : "https://cloud-api-staging.cmux.dev")! + } + public static func current(bundle: Bundle = .main, isDebugBuild: Bool) -> CloudConfiguration { let bundled = bundle.object(forInfoDictionaryKey: "LSEnvironment") as? [String: String] ?? [:] return resolve(bundleID: bundle.bundleIdentifier, bundled: bundled, @@ -143,12 +161,14 @@ public struct CloudConfiguration: Sendable, Equatable { /// Hosted sign-in entry: `handler/native-sign-in` wraps Stack sign-in and /// returns to `://auth-callback` through `handler/after-sign-in`. public func signInURL(callbackState: String?) -> URL { - var callback = URLComponents(url: callbackURL, resolvingAgainstBaseURL: false)! - if let callbackState { callback.queryItems = [URLQueryItem(name: "cmux_auth_state", value: callbackState)] } - var after = URLComponents(url: authWebOrigin.appendingPathComponent("handler/after-sign-in"), resolvingAgainstBaseURL: false)! - after.queryItems = [URLQueryItem(name: "native_app_return_to", value: callback.url!.absoluteString)] - var entry = URLComponents(url: authWebOrigin.appendingPathComponent("handler/native-sign-in"), resolvingAgainstBaseURL: false)! - entry.queryItems = [URLQueryItem(name: "after_auth_return_to", value: after.url!.absoluteString)] - return entry.url! + // URLComponents of a parsed URL always forms a URL again; without one, the bare entry page. + let entryPage = authWebOrigin.appendingPathComponent("handler/native-sign-in") + var callback = URLComponents(url: callbackURL, resolvingAgainstBaseURL: false) + if let callbackState { callback?.queryItems = [URLQueryItem(name: "cmux_auth_state", value: callbackState)] } + var after = URLComponents(url: authWebOrigin.appendingPathComponent("handler/after-sign-in"), resolvingAgainstBaseURL: false) + after?.queryItems = callback?.url.map { [URLQueryItem(name: "native_app_return_to", value: $0.absoluteString)] } + var entry = URLComponents(url: entryPage, resolvingAgainstBaseURL: false) + entry?.queryItems = after?.url.map { [URLQueryItem(name: "after_auth_return_to", value: $0.absoluteString)] } + return entry?.url ?? entryPage } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextCloud/Identity/InstallHTTPTransport.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextCloud/Identity/InstallHTTPTransport.swift new file mode 100644 index 000000000000..cb005862ba2f --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextCloud/Identity/InstallHTTPTransport.swift @@ -0,0 +1,39 @@ +public import CmuxInstallAuthCore +public import Foundation + +/// POSTs install-auth JSON to the API Worker at `baseURL`. Redirects are +/// refused (a bearer or a signed challenge never follows one), and nothing +/// is cached. +public struct InstallHTTPTransport: InstallAuthTransport { + private let baseURL: URL + private let session: URLSession + + public init(baseURL: URL) { + self.baseURL = baseURL + let configuration = URLSessionConfiguration.ephemeral + configuration.urlCache = nil + configuration.httpShouldSetCookies = false + configuration.timeoutIntervalForRequest = 15 + session = URLSession(configuration: configuration, delegate: RefuseRedirects(), delegateQueue: nil) + } + + public func post(_ path: String, json: Data, bearer: String?, headers: [String: String]) async throws -> (status: Int, body: Data) { + var request = URLRequest(url: baseURL.appendingPathComponent(path)) + request.httpMethod = "POST" + request.httpBody = json + request.setValue("application/json", forHTTPHeaderField: "content-type") + if let bearer { request.setValue("Bearer \(bearer)", forHTTPHeaderField: "authorization") } + for (name, value) in headers { request.setValue(value, forHTTPHeaderField: name) } + let (data, response) = try await session.data(for: request) + return ((response as? HTTPURLResponse)?.statusCode ?? 0, data) + } +} + +/// Answers every redirect with "do not follow" (the completion-handler form: +/// the async delegate form crashes swift 6.4 SILGen in this module). +private final class RefuseRedirects: NSObject, URLSessionTaskDelegate, Sendable { + func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) { + completionHandler(nil) + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextCloud/Identity/InstallSigners.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextCloud/Identity/InstallSigners.swift new file mode 100644 index 000000000000..6f7f0984a679 --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextCloud/Identity/InstallSigners.swift @@ -0,0 +1,79 @@ +public import CmuxInstallAuthCore +import CryptoKit +public import Foundation +import Security + +/// A software P-256 install key in a 0600 file (development builds only). +struct FileInstallSigner: InstallSigner { + let file: URL + + func publicKeyX963() async throws -> Data { try key().publicKey.x963Representation } + + func sign(_ message: Data) async throws -> Data { try key().signature(for: message).rawRepresentation } + + func rotate() async throws { + guard unlink(file.path) == 0 || errno == ENOENT else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + } + + private func key() throws -> P256.Signing.PrivateKey { + if let raw = try? Data(contentsOf: file), let key = try? P256.Signing.PrivateKey(rawRepresentation: raw) { return key } + let made = P256.Signing.PrivateKey() + try OwnerOnlyFile.write(made.rawRepresentation, to: file) + return made + } +} + +/// The install key in the Secure Enclave (signed builds). Only the enclave's +/// encrypted key blob is stored, in the Keychain for this device only; the +/// private key never leaves the enclave. No user-presence prompt. +struct EnclaveInstallSigner: InstallSigner { + enum Failure: Error { case secureEnclaveUnavailable, keychain(OSStatus) } + + let service: String + let account: String + + func publicKeyX963() async throws -> Data { try key().publicKey.x963Representation } + + func sign(_ message: Data) async throws -> Data { try key().signature(for: message).rawRepresentation } + + func rotate() async throws { + let status = SecItemDelete(query() as CFDictionary) + guard status == errSecSuccess || status == errSecItemNotFound else { throw Failure.keychain(status) } + } + + private func key() throws -> SecureEnclave.P256.Signing.PrivateKey { + guard SecureEnclave.isAvailable else { throw Failure.secureEnclaveUnavailable } + if let blob = try read() { return try SecureEnclave.P256.Signing.PrivateKey(dataRepresentation: blob) } + var error: Unmanaged? + guard let access = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly, + .privateKeyUsage, &error) else { + throw Failure.keychain(errSecParam) + } + let made = try SecureEnclave.P256.Signing.PrivateKey(accessControl: access) + try write(made.dataRepresentation) + return made + } + + private func query() -> [String: Any] { + [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, + kSecAttrAccount as String: account] + } + + private func read() throws -> Data? { + var query = query() + query[kSecReturnData as String] = true + var out: CFTypeRef? + let status = SecItemCopyMatching(query as CFDictionary, &out) + if status == errSecItemNotFound { return nil } + guard status == errSecSuccess else { throw Failure.keychain(status) } + return out as? Data + } + + private func write(_ data: Data) throws { + var query = query() + query[kSecValueData as String] = data + query[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly + let status = SecItemAdd(query as CFDictionary, nil) + guard status == errSecSuccess else { throw Failure.keychain(status) } + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextCloud/Identity/MacInstallIdentity.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextCloud/Identity/MacInstallIdentity.swift new file mode 100644 index 000000000000..c48287736aac --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextCloud/Identity/MacInstallIdentity.swift @@ -0,0 +1,119 @@ +public import CmuxInstallAuthCore +public import Foundation +import os + +/// The Mac app's Cloud install principal (bead cx-wb5.64; identity spec D5): +/// an install key and a record per Stack user, registered as kind `mac` with +/// the mac grant (read, mutate-own, mutate-shared, cloud-link; never execute; +/// the server caps it) when the user signs in, then short-lived install +/// tokens minted from the key without the Stack session. Sign-out revokes the +/// install and forgets its key and record, so the next sign-in registers a +/// new install. The credential relay (cx-wb5.63) sends Cloud ops with these +/// tokens; a Stack bearer never leaves the app. +/// +/// Every bind has a generation: a registration that is still in flight when +/// the user signs out (or another user signs in) never writes its record, so +/// nothing on disk can mint for it afterwards. Its install may stay on the +/// server, unusable (its key is rotated away). +public actor MacInstallIdentity { + public enum Failure: Error, Equatable { + /// No user is signed in. + case signedOut + } + + private let store: MacInstallStore + private let transport: any InstallAuthTransport + private let deviceName: String + private let clientVersion: String? + private var client: InstallAuthClient? + private var user: String? + private var generation: UInt64 = 0 + /// Set by ``signOut(stackUser:session:)`` until the session ends + /// (``unbind()``): a late sign-in callback registers nothing. + private var signingOut = false + private let logger = Logger(subsystem: "com.cmuxterm.app.next", category: "cloud.install") + + public init(store: MacInstallStore, transport: any InstallAuthTransport, deviceName: String, clientVersion: String?) { + self.store = store + self.transport = transport + self.deviceName = deviceName + self.clientVersion = clientVersion + } + + /// The user signed in: binds them and registers (or reuses) the install + /// at once by minting one token, so a later relay call does not wait. + public func signedIn(stackUser: String, session: @escaping InstallAuthClient.SessionToken) async throws { + guard !signingOut else { throw Failure.signedOut } + if user != stackUser || client == nil { bind(stackUser: stackUser, session: session) } + _ = try await installToken() + } + + /// A valid install token for the signed-in user. + public func installToken() async throws -> String { + guard let client else { throw Failure.signedOut } + return try await client.installToken() + } + + /// The owner refused the current token (401): the next call mints again. + public func invalidate() async { await client?.invalidate() } + + /// The session ended without a sign-out here (expired, or signed out + /// elsewhere): stop minting. The key and record stay, so a sign-in of the + /// same user reuses the install and a later sign-out can still revoke it. + public func unbind() async { + signingOut = false + await drop() + } + + /// Stops the bound client: no record write, no token from a mint in flight. + private func drop() async { + generation &+= 1 + let dropped = client + client = nil + user = nil + await dropped?.reset() + } + + /// Sign-out of `stackUser` (needs the Stack session still): revokes the + /// install on the server, also one stored by an earlier launch that this + /// one never bound, then always rotates the user's key and forgets the + /// record, so this Mac never mints for that install again, also when the + /// revoke failed or a registration was still in flight. Until the session + /// ends (``unbind()``) no sign-in registers. + public func signOut(stackUser signedOutUser: String, session: @escaping InstallAuthClient.SessionToken) async { + signingOut = true + await drop() + let client = InstallAuthClient( + transport: transport, signer: store.signer(for: signedOutUser), sessionToken: session, stackUser: signedOutUser, + deviceName: deviceName, clientVersion: clientVersion, record: store.record(for: signedOutUser), profile: .mac + ) + do { + try await client.revoke() + } catch { + logger.error("install revoke failed: \(String(describing: error), privacy: .public)") + } + await client.reset() + store.saveRecord(nil, for: signedOutUser) + do { + try await store.signer(for: signedOutUser).rotate() + } catch { + logger.error("install key rotation failed: \(String(describing: error), privacy: .public)") + } + } + + private func bind(stackUser: String, session: InstallAuthClient.SessionToken?) { + generation &+= 1 + let bound = generation + user = stackUser + client = InstallAuthClient( + transport: transport, signer: store.signer(for: stackUser), sessionToken: session, stackUser: stackUser, + deviceName: deviceName, clientVersion: clientVersion, record: store.record(for: stackUser), + profile: .mac, onRecord: { [weak self] record in await self?.recordChanged(record, for: stackUser, generation: bound) } + ) + } + + private func recordChanged(_ record: InstallRecord?, for stackUser: String, generation bound: UInt64) { + guard bound == generation else { return } + store.saveRecord(record, for: stackUser) + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextCloud/Identity/MacInstallStore.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextCloud/Identity/MacInstallStore.swift new file mode 100644 index 000000000000..1fe4e785afc8 --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextCloud/Identity/MacInstallStore.swift @@ -0,0 +1,77 @@ +public import CmuxInstallAuthCore +import CryptoKit +public import Foundation + +/// Where the Mac app keeps its install keys and records (cx-wb5.64), one +/// key per Stack user (two users on one Mac never share or rotate each +/// other's key). +/// - ``files(directory:)``: a debug build without a Team ID: software P-256 +/// keys and the records in 0600 files in a 0700 directory, so a rebuild +/// never raises a Keychain prompt (the same known DEV gap as the P8 +/// frontend key, identity.md). +/// - ``enclave(service:directory:)``: every other build: keys in the Secure +/// Enclave (only the encrypted blob is stored, in the Keychain); records +/// (user and install ids, not secrets) in the 0600 file. +public struct MacInstallStore: Sendable { + private let makeSigner: @Sendable (String) -> any InstallSigner + private let records: URL + /// Whether keys live in the Secure Enclave. + public let usesSecureEnclave: Bool + + public static func files(directory: URL) -> MacInstallStore { + MacInstallStore(makeSigner: { account in FileInstallSigner(file: directory.appendingPathComponent(account)) }, + records: directory.appendingPathComponent("install-records.json"), usesSecureEnclave: false) + } + + public static func enclave(service: String, directory: URL) -> MacInstallStore { + MacInstallStore(makeSigner: { account in EnclaveInstallSigner(service: service, account: account) }, + records: directory.appendingPathComponent("install-records.json"), usesSecureEnclave: true) + } + + /// The store for this process. Only a debug build with no Team ID uses + /// files; a release build, or a build whose Team ID could not be read, + /// uses the Secure Enclave (fails closed). + public static func forApp(directory: URL, service: String, team: String?, isDebugBuild: Bool) -> MacInstallStore { + isDebugBuild && team == nil ? .files(directory: directory) : .enclave(service: service, directory: directory) + } + + /// The key of `user`: `install-key-`. + func signer(for user: String) -> any InstallSigner { + let digest = SHA256.hash(data: Data(user.utf8)).prefix(8).map { String(format: "%02x", $0) }.joined() + return makeSigner("install-key-\(digest)") + } + + func record(for user: String) -> InstallRecord? { + guard let data = try? Data(contentsOf: records), + let all = try? JSONDecoder().decode([String: InstallRecord].self, from: data) else { return nil } + return all[user] + } + + func saveRecord(_ record: InstallRecord?, for user: String) { + var all = (try? Data(contentsOf: records)).flatMap { try? JSONDecoder().decode([String: InstallRecord].self, from: $0) } ?? [:] + all[user] = record + guard let data = try? JSONEncoder().encode(all) else { return } + try? OwnerOnlyFile.write(data, to: records) + } +} + +/// 0600 files in a 0700 directory: written to a unique temporary file +/// (created exclusively, never through a symlink), synced, then renamed. +enum OwnerOnlyFile { + static func write(_ data: Data, to url: URL) throws { + let directory = url.deletingLastPathComponent() + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, + attributes: [.posixPermissions: 0o700]) + guard chmod(directory.path, 0o700) == 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EPERM) } + let temporary = directory.appendingPathComponent(".\(url.lastPathComponent).\(UUID().uuidString).tmp") + let fd = open(temporary.path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600) + guard fd >= 0 else { throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) } + let written = data.withUnsafeBytes { buffer in buffer.baseAddress.map { Darwin.write(fd, $0, buffer.count) } ?? 0 } + let synced = fsync(fd) == 0 + close(fd) + guard written == data.count, synced, rename(temporary.path, url.path) == 0 else { + unlink(temporary.path) + throw CocoaError(.fileWriteUnknown, userInfo: [NSFilePathErrorKey: url.path]) + } + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextCodeRouter/Detection/ProviderDetector.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextCodeRouter/Detection/ProviderDetector.swift index de8abccb9ecf..2bc3ba8c5715 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextCodeRouter/Detection/ProviderDetector.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextCodeRouter/Detection/ProviderDetector.swift @@ -50,14 +50,18 @@ public struct ProviderDetector: Sendable { // MARK: Local servers func detectOllama() async -> ProviderDetection { - let host = environment.value("OLLAMA_HOST").map(Self.ollamaBase) ?? URL(string: "http://127.0.0.1:11434")! + let host = environment.value("OLLAMA_HOST").map(Self.ollamaBase) ?? Self.ollamaDefault return await probe(.ollama, base: host, path: "api/tags") } func detectLMStudio() async -> ProviderDetection { - await probe(.lmStudio, base: URL(string: "http://127.0.0.1:1234")!, path: "v1/models") + await probe(.lmStudio, base: Self.lmStudioDefault, path: "v1/models") } + // Literals a test parses; /dev/null stands in rather than a trap. + static let ollamaDefault = URL(string: "http://127.0.0.1:11434") ?? URL(fileURLWithPath: "/dev/null") + static let lmStudioDefault = URL(string: "http://127.0.0.1:1234") ?? URL(fileURLWithPath: "/dev/null") + private func probe(_ provider: AIProvider, base: URL, path: String) async -> ProviderDetection { let address = [base.host, base.port.map(String.init)].compactMap { $0 }.joined(separator: ":") let reachable = await environment.servers.isReachable(base.appendingPathComponent(path)) @@ -75,11 +79,11 @@ public struct ProviderDetector: Sendable { static func ollamaBase(_ raw: String) -> URL { let withScheme = raw.contains("://") ? raw : "http://" + raw guard var components = URLComponents(string: withScheme), components.host?.isEmpty == false else { - return URL(string: "http://127.0.0.1:11434")! + return ollamaDefault } if components.host == "0.0.0.0" { components.host = "127.0.0.1" } if components.port == nil { components.port = 11434 } components.path = "" - return components.url ?? URL(string: "http://127.0.0.1:11434")! + return components.url ?? ollamaDefault } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextCodeRouter/Keychain/ProviderKeyStore.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextCodeRouter/Keychain/ProviderKeyStore.swift index 3af7173d1997..895a04ceb015 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextCodeRouter/Keychain/ProviderKeyStore.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextCodeRouter/Keychain/ProviderKeyStore.swift @@ -28,7 +28,7 @@ public struct KeychainProviderKeyStore: ProviderKeyStoring { } public static func service(bundleID: String?) -> String { - "\(bundleID?.isEmpty == false ? bundleID! : "com.cmuxterm.app").ai-provider-keys" + "\(bundleID.flatMap { $0.isEmpty ? nil : $0 } ?? "com.cmuxterm.app").ai-provider-keys" } private func base(_ provider: AIProvider?) -> [String: Any] { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/BackdropArt.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/BackdropArt.swift index 2540b823d1bc..060d8e165b3b 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/BackdropArt.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/BackdropArt.swift @@ -102,7 +102,8 @@ public nonisolated enum BackdropArt: String, CaseIterable, Sendable { case .womenPickingOlives: id = "436536" case .sunflowers: id = "436524" } - return URL(string: "https://www.metmuseum.org/art/collection/search/\(id)")! + // A literal per case (a test parses each); /dev/null stands in rather than a trap. + return URL(string: "https://www.metmuseum.org/art/collection/search/\(id)") ?? URL(fileURLWithPath: "/dev/null") } /// Loads the packaged image. A missing resource safely paints no art. diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/Dialog/CmuxDialogButtonView.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/Dialog/CmuxDialogButtonView.swift index 997b3a711b94..c33026377e45 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/Dialog/CmuxDialogButtonView.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/Dialog/CmuxDialogButtonView.swift @@ -5,12 +5,12 @@ public import AppKit /// draws a focus ring in `Palette.focusRing` while it has keyboard focus. @MainActor public final class CmuxDialogButtonView: NSButton { - public let button: CmuxDialogButton + public private(set) var button: CmuxDialogButton private var isHovering = false { didSet { refresh() } } private var tracking: NSTrackingArea? private var hasFocus = false { didSet { refresh() } } - init(_ button: CmuxDialogButton, target: AnyObject?, action: Selector) { + public init(_ button: CmuxDialogButton, target: AnyObject?, action: Selector) { self.button = button super.init(frame: .zero) translatesAutoresizingMaskIntoConstraints = false @@ -29,6 +29,14 @@ public final class CmuxDialogButtonView: NSButton { @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") } + /// Shows a new title in place (Copy Link turning into "Copied"). + public func retitle(_ title: String) { + guard title != button.title else { return } + button.title = title + setAccessibilityLabel(title) + refresh() + } + public override var acceptsFirstResponder: Bool { true } public override var canBecomeKeyView: Bool { true } public override var isHighlighted: Bool { didSet { refresh() } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/GroupColor+Theme.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/GroupColor+Theme.swift new file mode 100644 index 000000000000..fa11ddf50f26 --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/GroupColor+Theme.swift @@ -0,0 +1,58 @@ +public import AppKit +public import CmuxTheme + +/// Workspace group colors from the active Ghostty theme (cx-rcby, Lawrence +/// 2026-10-08: "make groups like this", the Chrome tab group chip): each +/// token is one of the theme's ANSI colors, so groups follow the palette +/// the terminal draws with; grey is "none". The color is kept readable over +/// the sidebar (`ThemeTokens.readable`), like the status colors. +extension GroupColor { + /// The order the group editor offers: none, then the palette. + public static let editorOrder: [GroupColor] = [.grey, .red, .orange, .yellow, .green, .cyan, .blue, .purple, .pink] + + /// The token's color in `tokens`' ANSI palette; nil for grey (none). + nonisolated public func themeRGB(_ tokens: ThemeTokens) -> ThemeRGB? { + let p = tokens.ansi + guard p.count >= 8 else { return nil } + let rgb: ThemeRGB? = switch self { + case .grey: nil + case .red: p[1] + case .green: p[2] + case .yellow: p[3] + case .blue: p[4] + case .purple: p[5] + case .cyan: p[6] + // Bright magenta when the theme names 16 colors. + case .pink: p.count > 13 ? p[13] : p[5].mixed(toward: p[1], 0.35) + case .orange: p[1].mixed(toward: p[3], 0.5) + } + return rgb.map { ThemeTokens.readable($0.withAlpha(1), over: tokens.sidebarBackground, minimum: ThemeTokens.minimumMarkContrast) } + } + + /// The token's color in the active theme scope (the app theme outside + /// one): the member bar and the editor's dot. Nil for grey (none). + public var themed: NSColor? { themeRGB(ThemeContext.active ?? ThemeScope.app.tokens)?.nsColor } + + /// The group chip's fill in the active theme scope: the color washed + /// into the sidebar so the name stays primary text; none draws the + /// neutral badge fill. + public var themedChipFill: NSColor { + let tokens = ThemeContext.active ?? ThemeScope.app.tokens + guard let rgb = themeRGB(tokens) else { return Palette.badgeFill } + return tokens.sidebarBackground.withAlpha(1).mixed(toward: rgb, tokens.isDark ? 0.34 : 0.26).nsColor + } + + /// The group header bar's fill and the members' bar (the Chrome tab + /// group look): the theme's palette color lightened to a pastel so dark + /// text reads on it; none is Chrome's light gray. + public var headerFill: NSColor { + let tokens = ThemeContext.active ?? ThemeScope.app.tokens + guard let rgb = themeRGB(tokens) else { + return (tokens.isDark ? ThemeRGB(hex: 0xDCDDE1) : ThemeRGB(hex: 0xDADCE0)).nsColor + } + return rgb.withAlpha(1).mixed(toward: ThemeRGB(hex: 0xFFFFFF), 0.35).nsColor + } + + /// Text and glyphs on `headerFill`: near black, as on Chrome's group headers. + public static var headerInk: NSColor { ThemeRGB(hex: 0x1F1F1F).nsColor } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/Resources/Localizable.xcstrings b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/Resources/Localizable.xcstrings index a5106c51c953..c788bb81b595 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/Resources/Localizable.xcstrings +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/Resources/Localizable.xcstrings @@ -2620,6 +2620,1326 @@ } } } + }, + "statusIconSet.current": { + "comment": "Status icon set candidate (Debug menu, Debug Settings): today's marks: working dots, a still dot for blocked, a check for done.", + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Dots (original)" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "نقاط (الحالي)" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Tačke (trenutno)" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Prikker (nuværende)" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Punkte (aktuell)" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Puntos (actual)" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Points (actuel)" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Punti (attuale)" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ドット(元のデザイン)" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "ចំណុច (បច្ចុប្បន្ន)" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "점 (현재)" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Prikker (nåværende)" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Kropki (obecne)" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Pontos (atual)" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Точки (текущие)" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "จุด (ปัจจุบัน)" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Noktalar (geçerli)" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Крапки (поточні)" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Chấm (hiện tại)" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "圆点(当前)" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "圓點(目前)" + } + } + } + }, + "statusIconSet.shapes": { + "comment": "Status icon set candidate (Debug menu, Debug Settings): pictures: a raised hand, a speech bubble with a question mark, a key.", + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Shapes" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "أشكال" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Oblici" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Former" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Formen" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Formas" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Formes" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Forme" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "図形" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "រាង" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "도형" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Former" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Kształty" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Formas" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Фигуры" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "รูปทรง" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Şekiller" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Фігури" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Hình dạng" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "形状" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "形狀" + } + } + } + }, + "statusIconSet.rings": { + "comment": "Status icon set candidate (Debug menu, Debug Settings): outlined rings with a small mark inside.", + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Rings" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "حلقات" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Prstenovi" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Ringe" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Ringe" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Anillos" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Anneaux" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Anelli" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "リング" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "រង្វង់" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "링" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Ringer" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Pierścienie" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Anéis" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Кольца" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "วงแหวน" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Halkalar" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Кільця" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Vòng" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "圆环" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "圓環" + } + } + } + }, + "statusIconSet.badges": { + "comment": "Status icon set candidate (Debug menu, Debug Settings): filled discs with a mark cut out.", + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Badges" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "شارات" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Značke" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Mærker" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Plaketten" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Insignias" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Pastilles" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Badge" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "バッジ" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "ផ្លាកសញ្ញា" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "배지" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Merker" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Plakietki" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Selos" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Значки" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "ป้าย" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Rozetler" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Бейджі" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Huy hiệu" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "徽章" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "徽章" + } + } + } + }, + "statusIconSet.bars": { + "comment": "Status icon set candidate (Debug menu, Debug Settings): waving bars while an agent works.", + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Pulse Bars" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "أشرطة نابضة" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Pulsirajuće trake" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Pulserende bjælker" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Pulsbalken" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Barras pulsantes" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Barres pulsées" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Barre pulsanti" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "パルスバー" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "របារលោត" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "펄스 막대" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Pulserende stolper" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Pulsujące paski" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Barras pulsantes" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Пульсирующие полосы" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "แถบกะพริบ" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Nabız Çubukları" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Пульсуючі смуги" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Thanh nhịp" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "脉冲条" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "脈衝條" + } + } + } + }, + "statusIconSet.pips": { + "comment": "Status icon set candidate (Debug menu, Debug Settings): very small colored dots.", + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Minimal Pips" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "نقاط صغيرة" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Minimalne tačke" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Minimale prikker" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Minimale Punkte" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Puntos mínimos" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Points minimaux" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Punti minimi" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ミニマルな点" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "ចំណុចតូចៗ" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "최소 점" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Minimale prikker" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Minimalne kropki" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Pontos mínimos" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Минимальные точки" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "จุดเล็ก" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Minimal Noktalar" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Мінімальні крапки" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Chấm tối giản" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "极简圆点" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "極簡圓點" + } + } + } + }, + "statusIconSet.signs": { + "comment": "Status icon set candidate (Debug menu, Debug Settings): warning triangles and a stop octagon, like road signs.", + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Signs" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "إشارات" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Znakovi" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Skilte" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Schilder" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Señales" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Panneaux" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Segnali" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "標識" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "ផ្លាកសញ្ញាចរាចរណ៍" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "표지판" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Skilt" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Znaki" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Sinais" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Знаки" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "ป้ายเตือน" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "İşaretler" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Знаки" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Biển báo" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "标志" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "標誌" + } + } + } + }, + "statusIconSet.letters": { + "comment": "Status icon set candidate (Debug menu, Debug Settings): single letters P, Q, A in rounded squares.", + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Letters" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "أحرف" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Slova" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Bogstaver" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Buchstaben" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Letras" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Lettres" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Lettere" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "文字" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "អក្សរ" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "문자" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Bokstaver" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Litery" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Letras" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Буквы" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "ตัวอักษร" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Harfler" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Літери" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Chữ cái" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "字母" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "字母" + } + } + } + }, + "statusIconSet.symbols": { + "comment": "Status icon set candidate (Debug menu, Debug Settings): filled system symbols.", + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Symbols" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "رموز" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Simboli" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Symboler" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Symbole" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Símbolos" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Symboles" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Simboli" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "シンボル" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "និមិត្តសញ្ញា" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "기호" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Symboler" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Symbole" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Símbolos" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Символы" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "สัญลักษณ์" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Semboller" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Символи" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Ký hiệu" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "符号" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "符號" + } + } + } + }, + "statusIconSet.symbolsOutline": { + "comment": "Status icon set candidate (Debug menu, Debug Settings): outlined system symbols.", + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Outlined Symbols" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "رموز مفرغة" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Obrisani simboli" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Konturerede symboler" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Umrissene Symbole" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Símbolos con contorno" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Symboles en contour" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Simboli con contorno" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "アウトラインのシンボル" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "និមិត្តសញ្ញាបន្ទាត់" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "윤곽선 기호" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Konturerte symboler" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Symbole konturowe" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Símbolos contornados" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Контурные символы" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "สัญลักษณ์แบบเส้น" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Çerçeveli Semboller" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Контурні символи" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Ký hiệu viền" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "轮廓符号" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "輪廓符號" + } + } + } } }, "version": "1.0" diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusBlockedKind.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusBlockedKind.swift new file mode 100644 index 000000000000..40bc9f71d361 --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusBlockedKind.swift @@ -0,0 +1,10 @@ +/// What a blocked program waits for (OSC 7501 `kind`): a status icon set +/// can mark each apart (`StatusIconSet`). +public nonisolated enum StatusBlockedKind: String, Hashable, Sendable, CaseIterable { + /// The program asks to run something (a tool, a command). + case permission + /// The program asks a question. + case question + /// The program needs a sign-in. + case auth +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusGlyphGeometry.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusGlyphGeometry.swift new file mode 100644 index 000000000000..16b2e8cbe01b --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusGlyphGeometry.swift @@ -0,0 +1,61 @@ +import CoreGraphics + +/// Paths the indicator layer and the image export share, so an exported +/// status image (`StatusIconSet.image`) has the live glyph's geometry. All +/// in unflipped (bottom-left) space. +nonisolated enum StatusGlyphGeometry { + /// A ring that starts at 12 o'clock and runs clockwise, so `strokeEnd` + /// reads as progress. + static func ringPath(in rect: CGRect, thickness: CGFloat) -> CGPath { + let radius = max(0, min(rect.width, rect.height) / 2 - thickness / 2) + let path = CGMutablePath() + path.addArc(center: CGPoint(x: rect.midX, y: rect.midY), radius: radius, + startAngle: .pi / 2, endAngle: .pi / 2 - 2 * .pi, clockwise: true) + return path + } + + static func checkPath(in rect: CGRect) -> CGPath { + let path = CGMutablePath() + path.move(to: CGPoint(x: rect.minX, y: rect.minY + rect.height * 0.5)) + path.addLine(to: CGPoint(x: rect.minX + rect.width * 0.38, y: rect.minY + rect.height * 0.12)) + path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) + return path + } + + /// The check's box inside the glyph square. + static func checkRect(in rect: CGRect) -> CGRect { + rect.insetBy(dx: rect.width * 0.16, dy: rect.height * 0.2) + } + + /// The still dot (waiting, error, busy dot) at `scale` of the square. + static func dotRect(in rect: CGRect, scale: CGFloat) -> CGRect { + let side = rect.width * scale + return CGRect(x: rect.midX - side / 2, y: rect.midY - side / 2, width: side, height: side) + } + + /// Dot diameter as a share of the glyph square: three dots and two gaps + /// of half a dot fill the width (3 + 2 * 0.5 = 4 dots wide). + static let dotsDiameterShare: CGFloat = 0.25 + + /// The working dots or bars: one element's frame in the square's own + /// coordinates, and the step between copies. + static func repeatedElement(in size: CGSize, bars: Bool) -> (frame: CGRect, step: CGFloat) { + if bars { + let width = size.width * 0.18 + let step = width * 1.7 + let height = size.height * 0.7 + let total = width * 3 + (step - width) * 2 + return (CGRect(x: (size.width - total) / 2, y: (size.height - height) / 2, width: width, height: height), step) + } + let side = size.width * dotsDiameterShare + return (CGRect(x: 0, y: (size.height - side) / 2, width: side, height: side), side * 1.5) + } + + /// The path of one working element in its own frame. + static func repeatedElementPath(_ frame: CGRect, bars: Bool) -> CGPath { + let bounds = CGRect(origin: .zero, size: frame.size) + guard bars else { return CGPath(ellipseIn: bounds, transform: nil) } + let radius = bounds.width / 2 + return CGPath(roundedRect: bounds, cornerWidth: radius, cornerHeight: radius, transform: nil) + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIconSet+Image.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIconSet+Image.swift new file mode 100644 index 000000000000..9222f9c5089f --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIconSet+Image.swift @@ -0,0 +1,101 @@ +public import AppKit + +/// A set's mark for one state as a still image, from the same geometry and +/// mark drawing the indicator layer uses, so a notification attachment +/// (cx-kxa2 notification landing) shows the icon the sidebar shows. +extension StatusIconSet { + /// The still image of `state` (with `kind` for a waiting state) at + /// `pointSize`, tinted with the theme roles resolved under `appearance` + /// (nil: the current drawing appearance; inside a `ThemeScope.perform` + /// the scope's colors). Nil for idle. + @MainActor + public func image(state: StatusIndicatorState, kind: StatusBlockedKind? = nil, pointSize: CGFloat, scale: CGFloat = 2, + appearance: NSAppearance? = nil) -> NSImage? { + var state = state + if let kind, case .waiting = state { state = .waiting(kind: kind) } + let config = StatusIndicatorConfig(iconSet: self) + let plan = StatusIndicatorPlan.make(state, style: config.settings.style, animates: false, set: self) + let pixels = Int((pointSize * scale).rounded()) + guard plan.glyph != .none, pixels > 0, + let mask = StatusGlyphArt.mask(plan, pixels: pixels, scale: scale, config: config) else { return nil } + var colors: StatusIndicatorLayer.Colors? + (appearance ?? NSAppearance.currentDrawing()).performAsCurrentDrawingAppearance { + colors = .current(loading: config.settings.color) + } + guard let color = colors?.color(for: plan.tint), let space = CGColorSpace(name: CGColorSpace.sRGB), + let context = CGContext(data: nil, width: pixels, height: pixels, bitsPerComponent: 8, bytesPerRow: pixels * 4, + space: space, + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil } + let rect = CGRect(x: 0, y: 0, width: pixels, height: pixels) + context.clip(to: rect, mask: mask) + context.setFillColor(color) + context.fill(rect) + guard let image = context.makeImage() else { return nil } + let result = NSImage(cgImage: image, size: NSSize(width: pointSize, height: pointSize)) + result.accessibilityDescription = tunableTitle + return result + } +} + +/// Every plan glyph drawn still as an alpha mask (the first frame of an +/// animated one), with the layer's geometry. +@MainActor +enum StatusGlyphArt { + static func mask(_ plan: StatusIndicatorPlan, pixels: Int, scale: CGFloat, config: StatusIndicatorConfig) -> CGImage? { + guard let context = CGContext(data: nil, width: pixels, height: pixels, bitsPerComponent: 8, bytesPerRow: pixels, + space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.alphaOnly.rawValue) else { return nil } + let rect = CGRect(x: 0, y: 0, width: pixels, height: pixels) + let thickness = config.settings.thickness * scale + context.setFillColor(gray: 0, alpha: 1) + context.setStrokeColor(gray: 0, alpha: 1) + context.setLineCap(.round) + context.setLineJoin(.round) + switch plan.glyph { + case .none: + return nil + case .arc: + let radius = rect.width / 2 - thickness / 2 + context.addArc(center: CGPoint(x: rect.midX, y: rect.midY), radius: radius, startAngle: 0, + endAngle: 2 * .pi * config.arcLength, clockwise: false) + context.setLineWidth(thickness) + context.strokePath() + case .ring(let progress): + context.setLineWidth(thickness) + context.setAlpha(config.trackOpacity) + context.addPath(StatusGlyphGeometry.ringPath(in: rect, thickness: thickness)) + context.strokePath() + context.setAlpha(1) + let radius = max(0, rect.width / 2 - thickness / 2) + context.addArc(center: CGPoint(x: rect.midX, y: rect.midY), radius: radius, startAngle: .pi / 2, + endAngle: .pi / 2 - 2 * .pi * progress, clockwise: true) + context.strokePath() + case .native: + guard let image = NativeSpinnerImage.image(side: CGFloat(pixels) / scale, scale: scale) else { return nil } + context.draw(image, in: rect) + case .braille: + guard let image = BrailleSpinnerImage.images(side: CGFloat(pixels) / scale, scale: scale, family: config.terminalFontFamily).first + else { return nil } + context.draw(image, in: rect) + case .dot: + context.fillEllipse(in: StatusGlyphGeometry.dotRect(in: rect, scale: config.dotScale)) + case .check: + context.addPath(StatusGlyphGeometry.checkPath(in: StatusGlyphGeometry.checkRect(in: rect))) + context.setLineWidth(max(thickness, 1.25 * scale)) + context.strokePath() + case .dots, .bars: + let bars = plan.glyph == .bars + let element = StatusGlyphGeometry.repeatedElement(in: rect.size, bars: bars) + for index in 0...choice( + "status.iconSet", .status, "Status icons", + help: "The marks for agent working, blocked (permission, question, auth), done and error everywhere. Symbols is the default; Dots is the original drawing.", + default: .symbols, code: "StatusIconSet.tunable") + + public var tunableTitle: String { + switch self { + case .current: String(localized: "statusIconSet.current", defaultValue: "Dots (original)", bundle: .module) + case .shapes: String(localized: "statusIconSet.shapes", defaultValue: "Shapes", bundle: .module) + case .rings: String(localized: "statusIconSet.rings", defaultValue: "Rings", bundle: .module) + case .badges: String(localized: "statusIconSet.badges", defaultValue: "Badges", bundle: .module) + case .bars: String(localized: "statusIconSet.bars", defaultValue: "Pulse Bars", bundle: .module) + case .pips: String(localized: "statusIconSet.pips", defaultValue: "Minimal Pips", bundle: .module) + case .signs: String(localized: "statusIconSet.signs", defaultValue: "Signs", bundle: .module) + case .letters: String(localized: "statusIconSet.letters", defaultValue: "Letters", bundle: .module) + case .symbols: String(localized: "statusIconSet.symbols", defaultValue: "Symbols", bundle: .module) + case .symbolsOutline: String(localized: "statusIconSet.symbolsOutline", defaultValue: "Outlined Symbols", bundle: .module) + } + } + + /// One line for review sheets (not shown in the app). + public var summary: String { + switch self { + case .current: "Working dots, still attention dot for every blocked kind, danger dot, check." + case .shapes: "Sparkle, raised hand, ? bubble, key, ! for plain blocked, check, x in a ring." + case .rings: "Outlined rings with !, ?, key inside; empty ring for plain blocked; filled disc for done." + case .badges: "Filled discs with !, ?, key, check, x cut out; a pulsing sparkle disc for work." + case .bars: "Three waving bars for work; bare !, ?, key, dot, check, x." + case .pips: "Small pips: filled for permission, hollow for question, a diamond for auth." + case .signs: "Warning triangles with !, ?, key; outlined for plain blocked; an x octagon for error." + case .letters: "P, Q, A and ! cut out of rounded squares; check and x squares." + case .symbols: "SF Symbols, filled: hand.raised, questionmark.bubble, key, exclamationmark.circle, checkmark.circle, xmark.octagon." + case .symbolsOutline: "SF Symbols, outlined, and a pulsing sparkle for work." + } + } + + /// The set's plan for `state` before animation is applied, or nil where + /// the set keeps the default drawing (`current`, loading, known progress). + func plan(for state: StatusIndicatorState) -> StatusIndicatorPlan? { + guard self != .current else { return nil } + switch state { + case .working where state.progress == nil: + if self == .bars { return StatusIndicatorPlan(glyph: .bars, animation: .wave, tint: .accent) } + if self == .signs { return StatusIndicatorPlan(glyph: .dots, animation: .wave, tint: .accent) } + return StatusIndicatorPlan(glyph: .mark(workingMark), animation: .pulse, tint: .accent) + case .waiting(let kind): + if self == .bars, kind == nil { return StatusIndicatorPlan(glyph: .dot, animation: nil, tint: .attention) } + return StatusIndicatorPlan(glyph: .mark(blockedMark(kind)), animation: nil, tint: .attention) + case .success: + if self == .bars || self == .signs { return StatusIndicatorPlan(glyph: .check, animation: nil, tint: .success) } + return StatusIndicatorPlan(glyph: .mark(doneMark), animation: nil, tint: .success) + case .error: + return StatusIndicatorPlan(glyph: .mark(errorMark), animation: nil, tint: .danger) + case .idle, .busy, .paused, .working: + return nil + } + } + + private var workingMark: StatusMark { + switch self { + case .current, .bars, .signs, .shapes: .glyph(.sparkle) + case .rings: .outline(.circle, .dot) + case .badges: .badge(.circle, .sparkle) + case .pips: .glyph(.pip) + case .letters: .outline(.roundedSquare, .dot) + case .symbols: .symbol("ellipsis.circle.fill") + case .symbolsOutline: .symbol("sparkle") + } + } + + private func blockedMark(_ kind: StatusBlockedKind?) -> StatusMark { + switch self { + case .current, .shapes: + switch kind { + case .permission?: .glyph(.hand) + case .question?: .glyph(.bubbleQuestion) + case .auth?: .glyph(.key) + case nil: .glyph(.exclamation) + } + case .rings: .outline(.circle, Self.figure(kind)) + case .badges: .badge(.circle, Self.figure(kind) ?? .dot) + case .bars: .glyph(Self.figure(kind) ?? .dot) + case .pips: + switch kind { + case .permission?, nil: .glyph(.pip) + case .question?: .glyph(.hollowPip) + case .auth?: .glyph(.diamond) + } + case .signs: kind == nil ? .outline(.triangle, .exclamation) : .badge(.triangle, Self.figure(kind)) + case .letters: + switch kind { + case .permission?: .letter("P") + case .question?: .letter("Q") + case .auth?: .letter("A") + case nil: .letter("!") + } + case .symbols: + switch kind { + case .permission?: .symbol("hand.raised.fill") + case .question?: .symbol("questionmark.bubble.fill") + case .auth?: .symbol("key.fill") + case nil: .symbol("exclamationmark.circle.fill") + } + case .symbolsOutline: + switch kind { + case .permission?: .symbol("hand.raised") + case .question?: .symbol("questionmark.bubble") + case .auth?: .symbol("key") + case nil: .symbol("exclamationmark.circle") + } + } + } + + /// The small figure for a kind: ! permission, ? question, key auth. + private static func figure(_ kind: StatusBlockedKind?) -> StatusMark.Figure? { + switch kind { + case .permission?: .exclamation + case .question?: .question + case .auth?: .key + case nil: nil + } + } + + private var doneMark: StatusMark { + switch self { + case .current, .shapes, .bars, .signs: .glyph(.check) + case .rings: .badge(.circle, nil) + case .badges: .badge(.circle, .check) + case .pips: .glyph(.pip) + case .letters: .badge(.roundedSquare, .check) + case .symbols: .symbol("checkmark.circle.fill") + case .symbolsOutline: .symbol("checkmark.circle") + } + } + + private var errorMark: StatusMark { + switch self { + case .current, .shapes, .rings: .outline(.circle, .cross) + case .badges: .badge(.circle, .cross) + case .bars: .glyph(.cross) + case .pips: .glyph(.pip) + case .signs: .badge(.octagon, .cross) + case .letters: .badge(.roundedSquare, .cross) + case .symbols: .symbol("xmark.octagon.fill") + case .symbolsOutline: .symbol("xmark.octagon") + } + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorAppearance.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorAppearance.swift index b7a74d32c4ed..f664baf3d2ab 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorAppearance.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorAppearance.swift @@ -24,11 +24,13 @@ public nonisolated struct StatusIndicatorConfig: Hashable, Sendable { public var pulsePeriod: Double? /// The terminal font the braille style draws in (`terminal.fontFamily`). public var terminalFontFamily: String? + /// The status icon set (Debug Settings `status.iconSet`, cx-kxa2). + public var iconSet: StatusIconSet public init(settings: StatusIndicatorSettings = StatusIndicatorSettings(), styleOverride: StatusIndicatorStyle? = nil, arcLength: Double = 0.72, trackOpacity: Double = 0.22, dotScale: Double = 0.5, pulseLow: Double = 0.35, nativeSteps: Int = 8, animatesLoops: Bool = true, spinnerPeriod: Double? = nil, pulsePeriod: Double? = nil, - terminalFontFamily: String? = nil) { + terminalFontFamily: String? = nil, iconSet: StatusIconSet = .current) { self.settings = settings self.styleOverride = styleOverride self.arcLength = arcLength @@ -40,6 +42,7 @@ public nonisolated struct StatusIndicatorConfig: Hashable, Sendable { self.spinnerPeriod = spinnerPeriod self.pulsePeriod = pulsePeriod self.terminalFontFamily = terminalFontFamily + self.iconSet = iconSet } /// The style for a report that asked for `hint`: the Debug Settings @@ -61,7 +64,8 @@ public nonisolated struct StatusIndicatorConfig: Hashable, Sendable { animatesLoops: Motion.animatesLoops, spinnerPeriod: Motion.period(.spinner), pulsePeriod: Motion.period(.pulse), - terminalFontFamily: DesignSettings.shared.terminalFontFamily) + terminalFontFamily: DesignSettings.shared.terminalFontFamily, + iconSet: StatusIconSet.tunable.value) } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorLayer+Dots.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorLayer+Dots.swift index 2090e4e7cedf..1226a8de4670 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorLayer+Dots.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorLayer+Dots.swift @@ -6,13 +6,12 @@ import QuartzCore /// dot; the replicator delays each copy by a third of the cycle, so the /// render server runs the whole wave with no timer and no wakeup. Still /// (Reduce Motion, hidden, occluded), the three dots stay at full strength. +/// The `bars` glyph (a status icon set's working mark) is the same +/// replicator around one short rounded bar. extension StatusIndicatorLayer { - /// Dot diameter as a share of the glyph square: three dots and two gaps - /// of half a dot fill the width (3 + 2 * 0.5 = 4 dots wide). - static let dotsDiameterShare: CGFloat = 0.25 static let dotsCount = 3 - func buildDots(in rect: CGRect) { + func buildDots(in rect: CGRect, bars: Bool = false) { let replicator = dotsLayer ?? { let replicator = CAReplicatorLayer() replicator.actions = Self.noActions @@ -25,14 +24,13 @@ extension StatusIndicatorLayer { return replicator }() if replicator.frame != rect { replicator.frame = rect } - let side = rect.width * Self.dotsDiameterShare - let step = side * 1.5 + let element = StatusGlyphGeometry.repeatedElement(in: rect.size, bars: bars) replicator.instanceCount = Self.dotsCount - replicator.instanceTransform = CATransform3DMakeTranslation(step, 0, 0) + replicator.instanceTransform = CATransform3DMakeTranslation(element.step, 0, 0) guard let dot = replicator.sublayers?.first as? CAShapeLayer else { return } dot.contentsScale = contentsScale - dot.frame = CGRect(x: 0, y: (rect.height - side) / 2, width: side, height: side) - dot.path = CGPath(ellipseIn: dot.bounds, transform: nil) + dot.frame = element.frame + dot.path = StatusGlyphGeometry.repeatedElementPath(element.frame, bars: bars) } func removeDots() { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorLayer+Mark.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorLayer+Mark.swift new file mode 100644 index 000000000000..67c0b1fcbfdb --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorLayer+Mark.swift @@ -0,0 +1,45 @@ +import QuartzCore + +/// What a mark's mask was drawn for: redrawn only when the mark or the +/// pixel size changes, never per color change (the tint is the layer's +/// background color). +struct StatusMarkKey: Hashable { + var mark: StatusMark + var pixels: Int +} + +/// A status icon set's mark (`StatusIndicatorPlan.Glyph.mark`): one tinted layer +/// masked by the mark drawn as alpha (`StatusMarkArt`), like the native and +/// braille styles, so it costs one sublayer and recolors for free. Pulse +/// and spin animate the layer itself. +extension StatusIndicatorLayer { + func buildMark(_ mark: StatusMark, in rect: CGRect) { + let tinted = markLayer ?? { + let tinted = CALayer() + tinted.actions = Self.noActions + let mask = CALayer() + mask.actions = Self.noActions + mask.contentsGravity = .resizeAspect + tinted.mask = mask + layer.addSublayer(tinted) + markLayer = tinted + return tinted + }() + if tinted.frame != rect { + tinted.frame = rect + tinted.mask?.frame = tinted.bounds + } + tinted.mask?.contentsScale = contentsScale + let key = StatusMarkKey(mark: mark, pixels: Int((rect.width * contentsScale).rounded())) + if key != markKey { + markKey = key + tinted.mask?.contents = StatusMarkArt.mask(mark, pixels: key.pixels) + } + } + + func removeMark() { + markLayer?.removeFromSuperlayer() + markLayer = nil + markKey = nil + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorLayer.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorLayer.swift index 029897b4cf5c..236da6684597 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorLayer.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorLayer.swift @@ -40,6 +40,17 @@ public final class StatusIndicatorLayer { success: Palette.success.cgColor, accent: Palette.textPrimary.cgColor) } + + /// The color a plan's tint draws in. + public func color(for tint: StatusIndicatorPlan.Tint) -> CGColor { + switch tint { + case .loading: loading + case .attention: attention + case .danger: danger + case .success: success + case .accent: accent ?? loading + } + } } public private(set) var plan: StatusIndicatorPlan = .hidden @@ -58,6 +69,10 @@ public final class StatusIndicatorLayer { private var brailleFrames: [CGImage] = [] /// The working dots: a replicator of one dot (`StatusIndicatorLayer+Dots`). var dotsLayer: CAReplicatorLayer? + /// A status icon set's mark: a tinted layer masked by `StatusMarkArt` + /// (`StatusIndicatorLayer+Mark`), and what its mask was drawn for. + var markLayer: CALayer? + var markKey: StatusMarkKey? public init() { layer.actions = Self.noActions @@ -98,7 +113,7 @@ public final class StatusIndicatorLayer { /// The animation running now (tests, diagnostics). public var runningAnimation: StatusIndicatorPlan.Animation? { - for (sublayer, key) in [(glyphLayer as CALayer?, "spin"), (nativeLayer, "step"), (glyphLayer, "pulse"), (brailleLayer?.mask, "frames"), (dotsLayer?.sublayers?.first, "wave")] { + for (sublayer, key) in [(glyphLayer as CALayer?, "spin"), (nativeLayer, "step"), (glyphLayer, "pulse"), (markLayer, "pulse"), (brailleLayer?.mask, "frames"), (dotsLayer?.sublayers?.first, "wave")] { if let sublayer, sublayer.animation(forKey: key) != nil { return StatusIndicatorPlan.Animation(key: key) } @@ -147,6 +162,7 @@ public final class StatusIndicatorLayer { private func rebuild() { let rect = glyphRect let thickness = config.settings.thickness + if case .mark = plan.glyph {} else { removeMark() } switch plan.glyph { case .none: removeGlyph(); removeTrack(); removeNative(); removeBraille(); removeDots() @@ -161,11 +177,11 @@ public final class StatusIndicatorLayer { case .ring(let progress): removeNative(); removeBraille(); removeDots() let track = makeTrack(frame: rect) - track.path = ringPath(in: track.bounds, thickness: thickness) + track.path = StatusGlyphGeometry.ringPath(in: track.bounds, thickness: thickness) track.lineWidth = thickness track.opacity = Float(config.trackOpacity) let shape = makeGlyph(frame: rect) - shape.path = ringPath(in: shape.bounds, thickness: thickness) + shape.path = StatusGlyphGeometry.ringPath(in: shape.bounds, thickness: thickness) shape.fillColor = nil shape.lineWidth = thickness shape.strokeStart = 0 @@ -188,7 +204,7 @@ public final class StatusIndicatorLayer { case .check: removeTrack(); removeNative(); removeBraille(); removeDots() let shape = makeGlyph(frame: rect) - shape.path = checkPath(in: shape.bounds.insetBy(dx: rect.width * 0.16, dy: rect.height * 0.2)) + shape.path = StatusGlyphGeometry.checkPath(in: StatusGlyphGeometry.checkRect(in: shape.bounds)) shape.fillColor = nil shape.lineWidth = max(thickness, 1.25) shape.lineJoin = .round @@ -206,27 +222,15 @@ public final class StatusIndicatorLayer { case .dots: removeGlyph(); removeTrack(); removeNative(); removeBraille() buildDots(in: rect) + case .bars: + removeGlyph(); removeTrack(); removeNative(); removeBraille() + buildDots(in: rect, bars: true) + case .mark(let mark): + removeGlyph(); removeTrack(); removeNative(); removeBraille(); removeDots() + buildMark(mark, in: rect) } } - /// A ring that starts at 12 o'clock and runs clockwise, so `strokeEnd` - /// reads as progress. - private func ringPath(in rect: CGRect, thickness: CGFloat) -> CGPath { - let radius = max(0, min(rect.width, rect.height) / 2 - thickness / 2) - let path = CGMutablePath() - path.addArc(center: CGPoint(x: rect.midX, y: rect.midY), radius: radius, - startAngle: .pi / 2, endAngle: .pi / 2 - 2 * .pi, clockwise: true) - return path - } - - private func checkPath(in rect: CGRect) -> CGPath { - let path = CGMutablePath() - path.move(to: CGPoint(x: rect.minX, y: rect.minY + rect.height * 0.5)) - path.addLine(to: CGPoint(x: rect.minX + rect.width * 0.38, y: rect.minY + rect.height * 0.12)) - path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) - return path - } - // MARK: Sublayers private func makeGlyph(frame: CGRect) -> CAShapeLayer { @@ -321,6 +325,7 @@ public final class StatusIndicatorLayer { private func removeAllAnimations() { glyphLayer?.removeAllAnimations() + markLayer?.removeAllAnimations() nativeLayer?.removeAllAnimations() brailleLayer?.mask?.removeAllAnimations() dotsLayer?.sublayers?.first?.removeAllAnimations() @@ -330,13 +335,8 @@ public final class StatusIndicatorLayer { private func applyColors() { guard let colors else { return } - let color: CGColor = switch plan.tint { - case .loading: colors.loading - case .attention: colors.attention - case .danger: colors.danger - case .success: colors.success - case .accent: colors.accent ?? colors.loading - } + let color = colors.color(for: plan.tint) + markLayer?.backgroundColor = color switch plan.glyph { case .dot: glyphLayer?.fillColor = color @@ -370,7 +370,7 @@ public final class StatusIndicatorLayer { switch animation { case .step?: nativeLayer case .frames?: brailleLayer?.mask - case .spin?, .pulse?: glyphLayer + case .spin?, .pulse?: markLayer ?? glyphLayer case .wave?: dotsLayer?.sublayers?.first case nil: nil } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorPlan.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorPlan.swift index 298b2f97ee15..0d09c94d37b9 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorPlan.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorPlan.swift @@ -20,6 +20,11 @@ public nonisolated struct StatusIndicatorPlan: Hashable, Sendable { /// (WORKING-AND-LOADING-INDICATORS). No loading style draws it, so /// agent work never looks like a page or a command loading. case dots + /// Three short bars side by side, waving like `dots` (a status icon + /// set's working mark). + case bars + /// A status icon set's drawn mark (`StatusMark`, `StatusIconSet`). + case mark(StatusMark) } public enum Animation: Hashable, Sendable { @@ -64,8 +69,11 @@ public nonisolated struct StatusIndicatorPlan: Hashable, Sendable { /// is off screen or occluded, and under Reduce Motion or loops off /// (`Motion.animatesLoops`): then nothing animates and the static glyph /// stays, so an indicator never costs a frame it cannot be seen in. - public static func make(_ state: StatusIndicatorState, style: StatusIndicatorStyle, animates: Bool) -> StatusIndicatorPlan { - var plan = staticPlan(state, style: style) + /// `set` restyles the attention and working marks (`StatusIconSet`); + /// the default `current` is the drawing above, unchanged. + public static func make(_ state: StatusIndicatorState, style: StatusIndicatorStyle, animates: Bool, + set: StatusIconSet = .current) -> StatusIndicatorPlan { + var plan = set.plan(for: state) ?? staticPlan(state, style: style) if !animates { plan.animation = nil } return plan } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorState.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorState.swift index 387cd92ed2ae..354150b37236 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorState.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorState.swift @@ -17,8 +17,9 @@ public nonisolated enum StatusIndicatorState: Hashable, Sendable { /// (WORKING-AND-LOADING-INDICATORS). `progress` in 0...1 when the /// program reports one. case working(progress: Double?) - /// Waiting for the user (an agent asks for approval). - case waiting + /// Waiting for the user (an agent asks for approval). `kind` says what + /// for when the reporter names it (OSC 7501 `kind`); nil is plain blocked. + case waiting(kind: StatusBlockedKind?) case error /// A finished run, shown until its owner clears it (`status run` badge). case success @@ -27,6 +28,14 @@ public nonisolated enum StatusIndicatorState: Hashable, Sendable { public static let busy = StatusIndicatorState.busy(progress: nil) /// An agent working with no known progress, the common case. public static let working = StatusIndicatorState.working(progress: nil) + /// Waiting for the user with no known reason, the common case. + public static let waiting = StatusIndicatorState.waiting(kind: nil) + + /// What a waiting state waits for; nil for every other state. + public var blockedKind: StatusBlockedKind? { + if case .waiting(let kind) = self { return kind } + return nil + } public var isVisible: Bool { self != .idle } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorTunables.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorTunables.swift index 59a1bbbd7589..880999e1eacd 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorTunables.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorTunables.swift @@ -25,6 +25,7 @@ public nonisolated enum StatusIndicatorTunables { default: 8, range: 4...24, step: 1, unit: .count, code: "StatusIndicatorTunables.nativeSteps") public static var all: [TunableDescriptor] { - [style.descriptor, arcLength.descriptor, trackOpacity.descriptor, dotScale.descriptor, pulseLow.descriptor, nativeSteps.descriptor] + [style.descriptor, arcLength.descriptor, trackOpacity.descriptor, dotScale.descriptor, pulseLow.descriptor, nativeSteps.descriptor, + StatusIconSet.tunable.descriptor] } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorView.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorView.swift index 31ecca03c944..d6a487fab054 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorView.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusIndicatorView.swift @@ -52,7 +52,7 @@ public final class StatusIndicatorView: NSView, StatusIndicatorConfigClient { private func refresh() { let config = StatusIndicatorAppearance.shared.config let animates = window != nil && isWindowVisible && config.animatesLoops - let plan = StatusIndicatorPlan.make(state, style: config.style(hint: styleHint), animates: animates) + let plan = StatusIndicatorPlan.make(state, style: config.style(hint: styleHint), animates: animates, set: config.iconSet) let showed = showsGlyph indicator.apply(plan, config: config) isHidden = plan.glyph == .none diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusMark.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusMark.swift new file mode 100644 index 000000000000..cba495014dfa --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusMark.swift @@ -0,0 +1,25 @@ +/// One drawn mark of a status icon set (`StatusIconSet`), as a value: a +/// figure alone, a figure knocked out of a filled container (a badge), a +/// figure inside a stroked container, a monogram, or an SF Symbol. +/// `StatusMarkArt` draws it as an alpha mask the indicator tints with a theme +/// role, so every mark takes the theme's colors in light and dark. +public nonisolated enum StatusMark: Hashable, Sendable { + /// The figure alone, filling the slot. + case glyph(Figure) + /// A filled container with the figure cut out (nil: solid). + case badge(Container, Figure?) + /// A stroked container with the figure inside (nil: empty). + case outline(Container, Figure?) + /// A letter cut out of a filled rounded square. + case letter(String) + /// An SF Symbol, drawn as a template. + case symbol(String) + + public enum Container: Hashable, Sendable { + case circle, roundedSquare, triangle, octagon + } + + public enum Figure: Hashable, Sendable { + case exclamation, question, key, check, cross, hand, shield, bubble, bubbleQuestion, sparkle, dot, pip, hollowPip, diamond + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusMarkArt.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusMarkArt.swift new file mode 100644 index 000000000000..a325f5db9326 --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/StatusIndicator/StatusMarkArt.swift @@ -0,0 +1,241 @@ +import AppKit +import CoreText + +/// Draws a `StatusMark` as an alpha mask (opaque where the mark is), the one +/// drawing the live indicator layer and the image export both use. Vector +/// paths in unflipped space, sized from the slot so they stay crisp from +/// 10 to 32 points; badges cut their figure out of the container. +@MainActor +enum StatusMarkArt { + /// The mark in a square of `pixels`, as an alpha-only image. + static func mask(_ mark: StatusMark, pixels: Int) -> CGImage? { + guard pixels > 0, let context = CGContext(data: nil, width: pixels, height: pixels, bitsPerComponent: 8, bytesPerRow: pixels, + space: CGColorSpaceCreateDeviceGray(), + bitmapInfo: CGImageAlphaInfo.alphaOnly.rawValue) else { return nil } + context.setShouldAntialias(true) + draw(mark, in: context, rect: CGRect(x: 0, y: 0, width: pixels, height: pixels)) + return context.makeImage() + } + + /// Draws `mark` opaque into `rect` of `context` (the caller tints). + static func draw(_ mark: StatusMark, in context: CGContext, rect: CGRect) { + context.saveGState() + defer { context.restoreGState() } + context.setFillColor(gray: 0, alpha: 1) + context.setStrokeColor(gray: 0, alpha: 1) + context.setLineCap(.round) + context.setLineJoin(.round) + switch mark { + case .glyph(let figure): + drawFigure(figure, in: context, box: rect.insetBy(dx: rect.width * 0.06, dy: rect.height * 0.06), large: true) + case .badge(let container, let figure): + fillContainer(container, in: context, rect: rect) + if let figure { + context.setBlendMode(.clear) + drawFigure(figure, in: context, box: innerBox(container, rect), large: false) + context.setBlendMode(.normal) + } + case .outline(let container, let figure): + strokeContainer(container, in: context, rect: rect) + if let figure { drawFigure(figure, in: context, box: innerBox(container, rect), large: false) } + case .letter(let letter): + fillContainer(.roundedSquare, in: context, rect: rect) + context.setBlendMode(.clear) + drawLetter(letter, in: context, rect: rect) + context.setBlendMode(.normal) + case .symbol(let name): + drawSymbol(name, in: context, rect: rect) + } + } + + // MARK: Containers + + private static func containerPath(_ container: StatusMark.Container, _ rect: CGRect) -> CGPath { + let w = rect.width + switch container { + case .circle: + return CGPath(ellipseIn: rect.insetBy(dx: w * 0.04, dy: w * 0.04), transform: nil) + case .roundedSquare: + let r = rect.insetBy(dx: w * 0.06, dy: w * 0.06) + return CGPath(roundedRect: r, cornerWidth: w * 0.22, cornerHeight: w * 0.22, transform: nil) + case .triangle: + let path = CGMutablePath() + path.addLines(between: [point(rect, 0.5, 0.92), point(rect, 0.06, 0.12), point(rect, 0.94, 0.12)]) + path.closeSubpath() + return path + case .octagon: + let path = CGMutablePath() + let center = CGPoint(x: rect.midX, y: rect.midY), radius = w * 0.47 + for index in 0..<8 { + let angle = CGFloat.pi / 8 + CGFloat(index) * .pi / 4 + let p = CGPoint(x: center.x + radius * cos(angle), y: center.y + radius * sin(angle)) + if index == 0 { path.move(to: p) } else { path.addLine(to: p) } + } + path.closeSubpath() + return path + } + } + + private static func fillContainer(_ container: StatusMark.Container, in context: CGContext, rect: CGRect) { + let path = containerPath(container, rect) + context.addPath(path) + context.fillPath() + if container == .triangle { + // Round the triangle's corners: stroke its outline wide. + context.addPath(path) + context.setLineWidth(rect.width * 0.1) + context.strokePath() + } + } + + private static func strokeContainer(_ container: StatusMark.Container, in context: CGContext, rect: CGRect) { + let line = max(1, rect.width * 0.1) + context.setLineWidth(line) + context.addPath(containerPath(container, rect.insetBy(dx: line / 2, dy: line / 2))) + context.strokePath() + } + + /// The figure's box inside a container. + private static func innerBox(_ container: StatusMark.Container, _ rect: CGRect) -> CGRect { + switch container { + case .circle, .octagon: rect.insetBy(dx: rect.width * 0.26, dy: rect.height * 0.26) + case .roundedSquare: rect.insetBy(dx: rect.width * 0.25, dy: rect.height * 0.25) + case .triangle: CGRect(x: rect.minX + rect.width * 0.3, y: rect.minY + rect.height * 0.2, width: rect.width * 0.4, height: rect.height * 0.46) + } + } + + // MARK: Figures + + static func point(_ box: CGRect, _ x: CGFloat, _ y: CGFloat) -> CGPoint { + CGPoint(x: box.minX + x * box.width, y: box.minY + y * box.height) + } + + /// `large` figures fill the slot alone (thinner strokes relative to size). + private static func drawFigure(_ figure: StatusMark.Figure, in context: CGContext, box: CGRect, large: Bool) { + let w = min(box.width, box.height) + let line = max(1, w * (large ? 0.14 : 0.18)) + context.setLineWidth(line) + func dot(_ x: CGFloat, _ y: CGFloat, _ r: CGFloat) { + let c = point(box, x, y) + context.fillEllipse(in: CGRect(x: c.x - r * w, y: c.y - r * w, width: 2 * r * w, height: 2 * r * w)) + } + switch figure { + case .exclamation: + context.move(to: point(box, 0.5, 0.92)) + context.addLine(to: point(box, 0.5, 0.42)) + context.setLineWidth(max(1, w * 0.2)) + context.strokePath() + dot(0.5, 0.1, 0.11) + case .question: + let radius = w * 0.24 + let center = point(box, 0.5, 0.7) + context.addArc(center: center, radius: radius, startAngle: .pi * 0.95, endAngle: -.pi * 0.25, clockwise: true) + context.addLine(to: point(box, 0.5, 0.36)) + context.setLineWidth(max(1, w * 0.17)) + context.strokePath() + dot(0.5, 0.1, 0.1) + case .key: + let head = point(box, 0.3, 0.5) + let r = w * 0.2 + context.setLineWidth(max(1, w * 0.14)) + context.strokeEllipse(in: CGRect(x: head.x - r, y: head.y - r, width: 2 * r, height: 2 * r)) + context.move(to: point(box, 0.5, 0.5)) + context.addLine(to: point(box, 0.95, 0.5)) + context.move(to: point(box, 0.8, 0.5)) + context.addLine(to: point(box, 0.8, 0.3)) + context.move(to: point(box, 0.93, 0.5)) + context.addLine(to: point(box, 0.93, 0.34)) + context.strokePath() + case .check: + context.addPath(StatusGlyphGeometry.checkPath(in: box.insetBy(dx: w * 0.08, dy: w * 0.14))) + context.strokePath() + case .cross: + context.move(to: point(box, 0.18, 0.18)) + context.addLine(to: point(box, 0.82, 0.82)) + context.move(to: point(box, 0.82, 0.18)) + context.addLine(to: point(box, 0.18, 0.82)) + context.strokePath() + case .hand: + let palm = CGRect(x: box.minX + w * 0.2, y: box.minY + w * 0.04, width: w * 0.6, height: w * 0.52) + context.addPath(CGPath(roundedRect: palm, cornerWidth: w * 0.2, cornerHeight: w * 0.2, transform: nil)) + context.fillPath() + let finger = w * 0.13 + context.setLineWidth(finger) + for (x, top) in [(0.28, 0.78), (0.42, 0.92), (0.57, 0.9), (0.71, 0.76)] as [(CGFloat, CGFloat)] { + context.move(to: point(box, x, 0.4)) + context.addLine(to: point(box, x, top)) + } + context.move(to: point(box, 0.26, 0.24)) + context.addLine(to: point(box, 0.08, 0.5)) + context.strokePath() + case .shield: + let path = CGMutablePath() + path.move(to: point(box, 0.5, 0.96)) + path.addLine(to: point(box, 0.88, 0.82)) + path.addCurve(to: point(box, 0.5, 0.02), control1: point(box, 0.88, 0.4), control2: point(box, 0.72, 0.16)) + path.addCurve(to: point(box, 0.12, 0.82), control1: point(box, 0.28, 0.16), control2: point(box, 0.12, 0.4)) + path.closeSubpath() + context.addPath(path) + context.fillPath() + case .bubble, .bubbleQuestion: + let body = CGRect(x: box.minX, y: box.minY + w * 0.22, width: w, height: w * 0.74) + context.addPath(CGPath(roundedRect: body, cornerWidth: w * 0.26, cornerHeight: w * 0.26, transform: nil)) + context.addLines(between: [point(box, 0.22, 0.3), point(box, 0.14, 0.0), point(box, 0.5, 0.3)]) + context.fillPath() + if figure == .bubbleQuestion { + context.setBlendMode(.clear) + drawFigure(.question, in: context, box: body.insetBy(dx: body.width * 0.28, dy: body.height * 0.16), large: false) + context.setBlendMode(.normal) + } + case .sparkle: + let path = CGMutablePath() + let c = point(box, 0.5, 0.5) + let tips = [point(box, 0.5, 1), point(box, 1, 0.5), point(box, 0.5, 0), point(box, 0, 0.5)] + path.move(to: tips[0]) + for index in 1...4 { + let tip = tips[index % 4] + let previous = tips[index - 1] + let control = CGPoint(x: c.x + (previous.x + tip.x - 2 * c.x) * 0.12, y: c.y + (previous.y + tip.y - 2 * c.y) * 0.12) + path.addQuadCurve(to: tip, control: control) + } + path.closeSubpath() + context.addPath(path) + context.fillPath() + case .dot: + dot(0.5, 0.5, 0.26) + case .pip: + dot(0.5, 0.5, 0.17) + case .hollowPip: + let r = w * 0.17 + let c = point(box, 0.5, 0.5) + context.setLineWidth(max(1, w * 0.09)) + context.strokeEllipse(in: CGRect(x: c.x - r, y: c.y - r, width: 2 * r, height: 2 * r)) + case .diamond: + let s: CGFloat = 0.2 + context.addLines(between: [point(box, 0.5, 0.5 + s), point(box, 0.5 + s, 0.5), point(box, 0.5, 0.5 - s), point(box, 0.5 - s, 0.5)]) + context.closePath() + context.fillPath() + } + } + + // MARK: Text and symbols + + private static func drawLetter(_ letter: String, in context: CGContext, rect: CGRect) { + let font = NSFont.systemFont(ofSize: rect.height * 0.62, weight: .heavy) + let line = CTLineCreateWithAttributedString(NSAttributedString(string: letter, attributes: [.font: font, .foregroundColor: NSColor.black])) + let bounds = CTLineGetImageBounds(line, context) + context.textPosition = CGPoint(x: rect.midX - bounds.width / 2 - bounds.minX, y: rect.midY - bounds.height / 2 - bounds.minY) + CTLineDraw(line, context) + } + + private static func drawSymbol(_ name: String, in context: CGContext, rect: CGRect) { + let configuration = NSImage.SymbolConfiguration(pointSize: rect.height * 0.8, weight: .semibold) + guard let image = NSImage(systemSymbolName: name, accessibilityDescription: nil)?.withSymbolConfiguration(configuration) else { return } + let fit = min(rect.width / image.size.width, rect.height / image.size.height) + let size = CGSize(width: image.size.width * fit, height: image.size.height * fit) + let target = CGRect(x: rect.midX - size.width / 2, y: rect.midY - size.height / 2, width: size.width, height: size.height) + guard let cg = image.cgImage(forProposedRect: nil, context: nil, hints: nil) else { return } + // The template's alpha is the mark. + context.draw(cg, in: target) + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/ThemeScope+Views.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/ThemeScope+Views.swift index 35930407c6e4..2eb1d6c43222 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/ThemeScope+Views.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/ThemeScope+Views.swift @@ -86,7 +86,8 @@ extension NSView { defer { ThemeContext.pop() } var result: T? effectiveAppearance.performAsCurrentDrawingAppearance { result = body() } - return result! + // The block runs synchronously, so `result` is set; otherwise run `body` without the appearance. + return result ?? body() } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/ThemeScope.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/ThemeScope.swift index ba385b387a86..a20c49305142 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/ThemeScope.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/ThemeScope.swift @@ -282,7 +282,8 @@ public final class ThemeScope { defer { ThemeContext.pop() } var result: T? appearance.performAsCurrentDrawingAppearance { result = body() } - return result! + // The block runs synchronously, so `result` is set; otherwise run `body` without the appearance. + return result ?? body() } /// A root view takes an explicit appearance only where its scope's diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/Toast/CmuxToastAvoidance.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/Toast/CmuxToastAvoidance.swift new file mode 100644 index 000000000000..c9ac16877cef --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/Toast/CmuxToastAvoidance.swift @@ -0,0 +1,41 @@ +public import AppKit + +/// A view a toast must never cover (the Home composer and its buttons). +/// The toast host lifts each toast above every such view in its window +/// whose rect lies under the toast, and moves shown toasts when one posts +/// `cmuxToastAvoidanceDidChange`. +@MainActor +public protocol CmuxToastAvoiding: NSView { + /// The rect toasts stay clear of, in the view's own coordinates. + var toastAvoidanceRect: NSRect { get } +} + +extension Notification.Name { + /// Posted (object: the view) when a `CmuxToastAvoiding` view's rect + /// changes, so shown toasts move clear of it. + public static let cmuxToastAvoidanceDidChange = Notification.Name("CmuxNextDesign.toastAvoidanceDidChange") +} + +extension CmuxToastOverlayHost { + /// The gap between a toast and the view it avoids. + static let avoidanceGap: CGFloat = 8 + + /// The lowest bottom edge (window coordinates) a toast of `width`, + /// centered in `bounds`, may take in `window`: above every avoided rect + /// under it, else `bounds.minY`. + static func floor(width: CGFloat, in bounds: NSRect, window: NSWindow) -> CGFloat { + let band = NSRect(x: bounds.midX - width / 2 - avoidanceGap, y: bounds.minY, + width: width + 2 * avoidanceGap, height: bounds.height) + var floor = bounds.minY + func visit(_ view: NSView) { + guard !view.isHidden, view.alphaValue > 0.01 else { return } + if let avoiding = view as? any CmuxToastAvoiding { + let rect = avoiding.convert(avoiding.toastAvoidanceRect, to: nil) + if !rect.isEmpty, rect.intersects(band) { floor = max(floor, rect.maxY + avoidanceGap) } + } + view.subviews.forEach(visit) + } + if let content = window.contentView { visit(content) } + return floor + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/Toast/CmuxToastHost.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/Toast/CmuxToastHost.swift index 6e891e9fc0b3..3fe1e681ac5e 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/Toast/CmuxToastHost.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextDesign/Toast/CmuxToastHost.swift @@ -13,14 +13,42 @@ public protocol CmuxToastHosting: AnyObject { /// taking clicks only on the toast itself. @MainActor public final class CmuxToastOverlayHost: CmuxToastHosting { - private var handles: [ObjectIdentifier: (handle: OverlayHandle, window: NSWindow)] = [:] + private var handles: [ObjectIdentifier: (handle: OverlayHandle, window: NSWindow, view: CmuxToastView, slot: Int)] = [:] + private var avoidanceObserver: (any NSObjectProtocol)? - public init() {} + public init() { + avoidanceObserver = NotificationCenter.default.addObserver(forName: .cmuxToastAvoidanceDidChange, object: nil, + queue: .main) { [weak self] _ in + // task-owner: one hop to the main actor; moves this host's toasts once + Task { @MainActor in self?.reanchor(in: nil) } + } + } + + isolated deinit { + if let avoidanceObserver { NotificationCenter.default.removeObserver(avoidanceObserver) } + } + + /// The overlay places a toast 24 pt above the anchor's bottom, centered. + static let overlayLift: CGFloat = 24 - /// The anchor of `slot` in window coordinates: the overlay places a - /// toast 24 pt above the anchor's bottom, centered. - static func anchor(slot: Int, height: CGFloat, in bounds: NSRect) -> NSRect { - NSRect(x: bounds.minX, y: bounds.minY + CGFloat(slot) * (height + 8), width: bounds.width, height: height) + /// The anchor of `slot` in window coordinates, its toast's bottom at + /// `floor` or higher (clear of the views toasts avoid). + static func anchor(slot: Int, height: CGFloat, in bounds: NSRect, floor: CGFloat? = nil) -> NSRect { + let base = max(bounds.minY, (floor ?? bounds.minY) - overlayLift) + return NSRect(x: bounds.minX, y: base + CGFloat(slot) * (height + 8), width: bounds.width, height: height) + } + + private func anchor(for toast: CmuxToastView, slot: Int, in window: NSWindow) -> NSRect { + let bounds = window.contentView?.bounds ?? .zero + return Self.anchor(slot: slot, height: toast.frame.height, in: bounds, + floor: Self.floor(width: toast.frame.width, in: bounds, window: window)) + } + + /// Moves every toast in `window` (all windows when nil) clear of the avoided views. + private func reanchor(in window: NSWindow?) { + for entry in handles.values where window == nil || entry.window === window { + entry.handle.update(anchor: anchor(for: entry.view, slot: entry.slot, in: entry.window)) + } } public func show(_ toast: CmuxToastView, in window: NSWindow, slot: Int, windowGone: @escaping () -> Void) { @@ -28,21 +56,22 @@ public final class CmuxToastOverlayHost: CmuxToastHosting { let size = toast.fittingSize toast.translatesAutoresizingMaskIntoConstraints = true toast.frame = NSRect(origin: .zero, size: size) - let bounds = window.contentView?.bounds ?? .zero - let options = OverlayOptions(kind: .toast, anchor: Self.anchor(slot: slot, height: size.height, in: bounds), + let options = OverlayOptions(kind: .toast, anchor: anchor(for: toast, slot: slot, in: window), passesThroughClicks: false) let handle = WindowOverlayHost.host(for: window).present(toast, options: options) handle.onDismiss = windowGone - handles[ObjectIdentifier(toast)] = (handle, window) + handles[ObjectIdentifier(toast)] = (handle, window, toast, slot) } public func move(_ toast: CmuxToastView, to slot: Int) { - guard let (handle, window) = handles[ObjectIdentifier(toast)] else { return } - handle.update(anchor: Self.anchor(slot: slot, height: toast.frame.height, in: window.contentView?.bounds ?? .zero)) + guard var entry = handles[ObjectIdentifier(toast)] else { return } + entry.slot = slot + handles[ObjectIdentifier(toast)] = entry + entry.handle.update(anchor: anchor(for: toast, slot: slot, in: entry.window)) } public func hide(_ toast: CmuxToastView) { - guard let (handle, _) = handles.removeValue(forKey: ObjectIdentifier(toast)) else { return } + guard let (handle, _, _, _) = handles.removeValue(forKey: ObjectIdentifier(toast)) else { return } handle.onDismiss = nil handle.dismiss() } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextFeed/GitHubFeedSource.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextFeed/GitHubFeedSource.swift index 01db8e06fc2c..72e800cb4b3a 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextFeed/GitHubFeedSource.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextFeed/GitHubFeedSource.swift @@ -125,9 +125,8 @@ public final class GitHubFeedSource: GitHubFeedDetailProviding { let url = notificationURL(repository: notification.repository, subject: notification.subject) let isReview = notification.reason == "review_requested" let number = githubNumber(from: notification.subject.url) - let dedupe = isReview && number != nil - ? "github:review:\(notification.repository.fullName):\(number!)" - : "github:notification:\(notification.id)" + let dedupe = (isReview ? number : nil).map { "github:review:\(notification.repository.fullName):\($0)" } + ?? "github:notification:\(notification.id)" let prompt: FeedPrompt = isReview ? .review(.init(subject: .pr, ref: url?.absoluteString ?? notification.subject.title)) : .notice diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextHistory/HistoryPageModel.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextHistory/HistoryPageModel.swift index e23c2c348d08..638bd72593ca 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextHistory/HistoryPageModel.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextHistory/HistoryPageModel.swift @@ -110,7 +110,8 @@ public final class HistoryPageModel { /// The page's address. public nonisolated enum HistoryPageAddress { public static let string = "cmux://history" - public static var url: URL { URL(string: string)! } + /// The page address (a literal a test parses; /dev/null stands in rather than a trap). + public static let url: URL = URL(string: string) ?? URL(fileURLWithPath: "/dev/null") /// `cmux://history`, with or without a trailing slash, query or fragment. public static func matches(_ url: URL?) -> Bool { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextHome/NativeTranscript/HomeNativeTranscriptView.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextHome/NativeTranscript/HomeNativeTranscriptView.swift index c29b66ef3c67..66095876c4dd 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextHome/NativeTranscript/HomeNativeTranscriptView.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextHome/NativeTranscript/HomeNativeTranscriptView.swift @@ -1,7 +1,7 @@ public import AppKit public import CmuxHomeCore public import CmuxHomeRender -import CmuxNextDesign +public import CmuxNextDesign import MessagesLabHome /// The Home transcript (plans/cmux-next/home-mac.md): MessagesLabAppKitNative's @@ -38,6 +38,8 @@ public final class HomeNativeTranscriptView: NSView { // task-owner: replaced by the next intake; awaited by attachmentsReady var intake: Task? private var stopped = false + /// The composer rect toasts last moved clear of (posted on change). + private var lastToastAvoidance = NSRect.zero /// False while the owner is unreachable (H17: offline Send is off; the /// text stays a draft). The wiring sets it from `HomeStore.connection`. public var isSendEnabled = true { @@ -161,6 +163,11 @@ public final class HomeNativeTranscriptView: NSView { noticeLabel.preferredMaxLayoutWidth = width let height = ceil(noticeLabel.intrinsicContentSize.height) noticeLabel.frame = CGRect(x: 16, y: transcript.fieldTop - height - 8, width: width, height: height) + let avoided = toastAvoidanceRect + if avoided != lastToastAvoidance { + lastToastAvoidance = avoided + NotificationCenter.default.post(name: .cmuxToastAvoidanceDidChange, object: self) + } } /// A notice about the conversation itself (Home's merge notice): a row of @@ -245,3 +252,13 @@ public final class HomeNativeTranscriptView: NSView { } } } + +/// Toasts stay clear of the composer and its buttons (the area below the +/// field's top edge). +extension HomeNativeTranscriptView: CmuxToastAvoiding { + public var toastAvoidanceRect: NSRect { + let top = transcript.fieldTop + return NSRect(x: 0, y: top, width: bounds.width, height: max(0, bounds.height - top)) + } +} + diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextLayout/Demo/LayoutDemo.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextLayout/Demo/LayoutDemo.swift index 3aa2897b8cc0..91bd69a1ca6e 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextLayout/Demo/LayoutDemo.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextLayout/Demo/LayoutDemo.swift @@ -86,7 +86,7 @@ public final class LayoutDemoController: NSObject { let modes = CenterFocusedColumn.allCases model.centerFocusedColumnOverride = modes[((modes.firstIndex(of: model.centerFocusedColumn) ?? 0) + 1) % modes.count] case let digit? where Int(digit).map({ (1...9).contains($0) }) == true: - let index = Int(digit)! - 1 + let index = (Int(digit) ?? 0) - 1 if model.screens.indices.contains(index) { model.selectScreen(model.screens[index].id) } default: return false } @@ -129,7 +129,8 @@ private final class DemoTabChip: NSView, NSDraggingSource { let dragItem = NSDraggingItem(pasteboardWriter: item) let image = NSImage(size: bounds.size, flipped: false) { [weak self] rect in guard let self else { return false } - self.layer?.render(in: NSGraphicsContext.current!.cgContext) + guard let context = NSGraphicsContext.current?.cgContext else { return false } + self.layer?.render(in: context) return true } dragItem.setDraggingFrame(bounds, contents: image) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextLayout/Views/LayoutRootView.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextLayout/Views/LayoutRootView.swift index 5fec3673ae6e..d7dfb93c1190 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextLayout/Views/LayoutRootView.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextLayout/Views/LayoutRootView.swift @@ -255,7 +255,7 @@ public final class LayoutRootView: NSView { if view.step(dt) { moving = true } } for id in Array(screenFrames.keys) { - if screenFrames[id]!.advance(dt, parameters: Motion.spring(.screen)) { moving = true } + if screenFrames[id]?.advance(dt, parameters: Motion.spring(.screen)) == true { moving = true } } applyScreenFrames() if highlight.step(dt) { moving = true } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextLayout/Views/ScreenContentView+Rows.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextLayout/Views/ScreenContentView+Rows.swift index 288e33b65f51..738e107cc0ab 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextLayout/Views/ScreenContentView+Rows.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextLayout/Views/ScreenContentView+Rows.swift @@ -51,7 +51,7 @@ extension ScreenContentView { func stepRows(_ dt: Double) -> Bool { var moving = false for id in Array(rowScrolls.keys) where rowScrolls[id]?.state.isGestureActive == false { - if rowScrolls[id]!.state.spring.advance(dt, parameters: Motion.spring(.scroll), epsilon: 0.25) { moving = true } + if rowScrolls[id]?.state.spring.advance(dt, parameters: Motion.spring(.scroll), epsilon: 0.25) == true { moving = true } } if !rowScrolls.isEmpty { refreshRowShift() } return moving diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextLayout/Views/ScreenContentView.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextLayout/Views/ScreenContentView.swift index e14f0bf6ab39..1c6374208681 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextLayout/Views/ScreenContentView.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextLayout/Views/ScreenContentView.swift @@ -194,10 +194,10 @@ final class ScreenContentView: NSView { func step(_ dt: Double) -> Bool { var moving = false for key in Array(paneFrames.keys) { - if paneFrames[key]!.advance(dt, parameters: Motion.spring(.move)) { moving = true } + if paneFrames[key]?.advance(dt, parameters: Motion.spring(.move)) == true { moving = true } } for key in Array(dividerFrames.keys) { - if dividerFrames[key]!.advance(dt, parameters: Motion.spring(.move)) { moving = true } + if dividerFrames[key]?.advance(dt, parameters: Motion.spring(.move)) == true { moving = true } } if stepRows(dt) { moving = true } if !isUserScrolling { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Gallery/GalleryWindow.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Gallery/GalleryWindow.swift index 40b72dbb5c68..529dc6b543a9 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Gallery/GalleryWindow.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Gallery/GalleryWindow.swift @@ -55,7 +55,7 @@ final class GalleryWindow: NSWindow { switch event.charactersIgnoringModifiers?.lowercased() { case "p": return .pick case "t": return .appearance - case let digit? where digit.count == 1 && "123456789".contains(digit): return .jump(Int(digit)! - 1) + case let digit? where digit.count == 1 && "123456789".contains(digit): return .jump((Int(digit) ?? 1) - 1) default: return nil } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Gallery/OnboardingGalleryController.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Gallery/OnboardingGalleryController.swift index e70efeaf66e0..523b90c774a4 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Gallery/OnboardingGalleryController.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Gallery/OnboardingGalleryController.swift @@ -15,7 +15,9 @@ public final class OnboardingGalleryController: NSWindowController, NSWindowDele private let previewAppearance: (Bool?) -> Void let sidebarView = GallerySidebar() let stageView = GalleryStage() - var barView: GalleryBottomBar! + /// Built in init where `onNote` is set (no IUO; lazy because its targets are self). + lazy var barView = GalleryBottomBar(target: self, pick: #selector(pickPressed), compare: #selector(comparePressed), + copy: #selector(copyPressed), run: #selector(runPressed)) private(set) var isComparing = false private var runningFlow = false { didSet { (window as? GalleryWindow)?.flowRunning = runningFlow } @@ -36,8 +38,6 @@ public final class OnboardingGalleryController: NSWindowController, NSWindowDele window.identifier = NSUserInterfaceItemIdentifier("cmux.onboarding.gallery") super.init(window: window) window.delegate = self - barView = GalleryBottomBar(target: self, pick: #selector(pickPressed), compare: #selector(comparePressed), - copy: #selector(copyPressed), run: #selector(runPressed)) barView.onNote = { [weak self] text in self?.setNote(text) } sidebarView.onSelect = { [weak self] step in self?.go(step: step, index: 0) } window.install(kind: .onboardingGallery, content: makeContent(), scope: .app) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Model/OnboardingServices.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Model/OnboardingServices.swift index d56477b1e389..901800afbcd2 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Model/OnboardingServices.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Model/OnboardingServices.swift @@ -131,7 +131,10 @@ public extension OnboardingServices { /// System Settings deep links. public extension URL { /// Privacy & Security > Full Disk Access. - static let systemSettingsFullDiskAccess = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles")! + /// (Literals a test parses; /dev/null stands in rather than a trap.) + static let systemSettingsFullDiskAccess = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles") + ?? URL(fileURLWithPath: "/dev/null") /// Desktop & Dock (the default web browser menu). - static let systemSettingsDefaultBrowser = URL(string: "x-apple.systempreferences:com.apple.Desktop-Settings.extension")! + static let systemSettingsDefaultBrowser = URL(string: "x-apple.systempreferences:com.apple.Desktop-Settings.extension") + ?? URL(fileURLWithPath: "/dev/null") } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Steps/DefaultBrowserStepView.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Steps/DefaultBrowserStepView.swift index 907163ac592f..2b6c24970c77 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Steps/DefaultBrowserStepView.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Steps/DefaultBrowserStepView.swift @@ -6,13 +6,12 @@ import CmuxNextDesign final class DefaultBrowserStepView: NSView { private let model: DefaultAppsStepModel private let status = OnboardingLabel.make(color: Palette.textSecondary, lines: 2) - private var button: NSButton! + private lazy var button: NSButton = OnboardingControl.button(OnboardingStrings.makeDefaultBrowser, target: self, action: #selector(press)) // no IUO (crash program) private var loop: RenderLoop? init(model: DefaultAppsStepModel) { self.model = model super.init(frame: .zero) - button = OnboardingControl.button(OnboardingStrings.makeDefaultBrowser, target: self, action: #selector(press)) let stack = NSStackView(views: [status, button]) stack.orientation = .vertical stack.alignment = .leading diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/System/AgentApp.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/System/AgentApp.swift index a12dbb347208..c0fcff895639 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/System/AgentApp.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/System/AgentApp.swift @@ -15,6 +15,7 @@ public nonisolated enum AgentApp: String, CaseIterable, Sendable, Comparable { } public static func < (lhs: AgentApp, rhs: AgentApp) -> Bool { - allCases.firstIndex(of: lhs)! < allCases.firstIndex(of: rhs)! + // Every case is in allCases; the declaration order is the order. + (allCases.firstIndex(of: lhs) ?? 0) < (allCases.firstIndex(of: rhs) ?? 0) } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/BottomBarBrowserVariant.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/BottomBarBrowserVariant.swift index 7679f2359df2..6262c487a8d8 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/BottomBarBrowserVariant.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/BottomBarBrowserVariant.swift @@ -37,11 +37,10 @@ struct BottomBarBrowser: OnboardingScreenVariant { final class BottomBarBrowserBar: BrowserClaimView { private let status = OnboardingLabel.make(lines: 2) - private var button: NSButton! + private lazy var button: NSButton = OnboardingControl.button(OnboardingStrings.makeDefaultBrowser, target: self, action: #selector(requestClaim)) // no IUO (crash program) override init(model: DefaultAppsStepModel) { super.init(model: model) - button = OnboardingControl.button(OnboardingStrings.makeDefaultBrowser, target: self, action: #selector(requestClaim)) button.setContentCompressionResistancePriority(.required, for: .horizontal) addSubview(status) addSubview(button) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/CenteredHeroBrowserVariant.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/CenteredHeroBrowserVariant.swift index 573a4201bdff..799e2546f3e4 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/CenteredHeroBrowserVariant.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/CenteredHeroBrowserVariant.swift @@ -28,11 +28,11 @@ struct CenteredHeroBrowser: OnboardingScreenVariant { final class CenteredHeroBrowserBody: BrowserClaimView { private let title = OnboardingLabel.make(BrowserVariantStrings.openLinks, font: .systemFont(ofSize: 34, weight: .bold), lines: 2) private let status = OnboardingLabel.make(font: .systemFont(ofSize: 13), color: Palette.textSecondary, lines: 2) - private var button: NSButton! + private lazy var button: NSButton = .browserHeroButton(OnboardingStrings.makeDefaultBrowser, target: self, action: #selector(requestClaim)) // no IUO (crash program) override init(model: DefaultAppsStepModel) { super.init(model: model) - button = .browserHeroButton(OnboardingStrings.makeDefaultBrowser, target: self, action: #selector(requestClaim)) + _ = button // built here, as before title.alignment = .center status.alignment = .center let stack = NSStackView(views: [title, button, status]) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/CheckboxRowBrowserVariant.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/CheckboxRowBrowserVariant.swift index baa5acbb7f39..e93309825a16 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/CheckboxRowBrowserVariant.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/CheckboxRowBrowserVariant.swift @@ -24,11 +24,10 @@ struct CheckboxRowBrowser: OnboardingScreenVariant { final class CheckboxRowBrowserBody: BrowserClaimView { private let row = FlippedView() private let state = OnboardingLabel.make(font: OnboardingMetrics.captionFont, color: Palette.textSecondary, lines: 2) - private var box: NSButton! + private lazy var box: NSButton = OnboardingControl.checkbox(BrowserVariantStrings.openLinks, target: self, action: #selector(toggled)) // no IUO (crash program) override init(model: DefaultAppsStepModel) { super.init(model: model) - box = OnboardingControl.checkbox(BrowserVariantStrings.openLinks, target: self, action: #selector(toggled)) box.setContentCompressionResistancePriority(.required, for: .horizontal) state.alignment = .right row.addSubview(box) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/EditorialSplitBrowserVariant.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/EditorialSplitBrowserVariant.swift index 0caa2470c09d..f190a84827e7 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/EditorialSplitBrowserVariant.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/EditorialSplitBrowserVariant.swift @@ -33,11 +33,10 @@ final class EditorialSplitBrowserBody: BrowserClaimView { private let wellCaption = OnboardingLabel.make(BrowserVariantStrings.opensLinksNow, font: OnboardingMetrics.captionFont, color: Palette.textTertiary) private let wellName = OnboardingLabel.make(font: .systemFont(ofSize: 22, weight: .semibold)) - private var button: NSButton! + private lazy var button: NSButton = OnboardingControl.button(OnboardingStrings.makeDefaultBrowser, target: self, action: #selector(requestClaim)) // no IUO (crash program) override init(model: DefaultAppsStepModel) { super.init(model: model) - button = OnboardingControl.button(OnboardingStrings.makeDefaultBrowser, target: self, action: #selector(requestClaim)) let column = NSStackView(views: [title, sentence, button, note]) column.orientation = .vertical column.alignment = .leading diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/FloatingCardBrowserVariant.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/FloatingCardBrowserVariant.swift index 7ee2c2015d5c..47a2e40d19e4 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/FloatingCardBrowserVariant.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/FloatingCardBrowserVariant.swift @@ -24,11 +24,10 @@ struct FloatingCardBrowser: OnboardingScreenVariant { final class FloatingCardBrowserBody: BrowserClaimView { private let status = OnboardingLabel.make(color: Palette.textSecondary, lines: 2) - private var button: NSButton! + private lazy var button: NSButton = OnboardingControl.button(OnboardingStrings.makeDefaultBrowser, prominent: true, target: self, action: #selector(requestClaim)) // no IUO (crash program) override init(model: DefaultAppsStepModel) { super.init(model: model) - button = OnboardingControl.button(OnboardingStrings.makeDefaultBrowser, prominent: true, target: self, action: #selector(requestClaim)) button.setContentCompressionResistancePriority(.required, for: .horizontal) let row = NSStackView(views: [button, status]) row.orientation = .horizontal diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/FooterActionBrowserVariant.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/FooterActionBrowserVariant.swift index 64d7882e2bd4..50274a91a105 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/FooterActionBrowserVariant.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/FooterActionBrowserVariant.swift @@ -54,7 +54,7 @@ final class FooterActionBrowserStatus: BrowserClaimView { /// "2 of 4" on the left; Skip, Make Default and Continue on the right. final class FooterActionBrowserFooter: BrowserClaimView { private let context: OnboardingStepContext - private var make: NSButton! + private lazy var make: NSButton = OnboardingControl.button(BrowserVariantStrings.makeDefault, target: self, action: #selector(requestClaim)) // no IUO (crash program) init(context: OnboardingStepContext) { self.context = context @@ -63,7 +63,7 @@ final class FooterActionBrowserFooter: BrowserClaimView { font: OnboardingMetrics.captionFont, color: Palette.textTertiary) counter.isHidden = !OnboardingFooter.showsCounter(count: context.count) let skip = OnboardingControl.plainButton(OnboardingStrings.skip, target: self, action: #selector(skipPressed)) - make = OnboardingControl.button(BrowserVariantStrings.makeDefault, target: self, action: #selector(requestClaim)) + _ = make // built here, as before let next = OnboardingControl.button(context.isLast ? OnboardingStrings.done : OnboardingStrings.continueButton, prominent: true, target: self, action: #selector(nextPressed)) let actions = NSStackView(views: [skip, make, next]) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/StatusFirstBrowserVariant.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/StatusFirstBrowserVariant.swift index c53adc477b3c..b062d4b0ce6a 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/StatusFirstBrowserVariant.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/StatusFirstBrowserVariant.swift @@ -36,15 +36,14 @@ struct StatusFirstBrowser: OnboardingScreenVariant { final class StatusFirstBrowserBody: BrowserClaimView { private let headline = OnboardingLabel.make(font: .systemFont(ofSize: 28, weight: .regular), lines: 2) private let note = OnboardingLabel.make(color: Palette.textSecondary, lines: 2) - private var button: NSButton! - private var stack: NSStackView! + private lazy var button: NSButton = OnboardingControl.button(BrowserVariantStrings.useCmux, prominent: true, target: self, action: #selector(requestClaim)) // no IUO (crash program) + private lazy var stack: NSStackView = NSStackView(views: [headline, note, button]) // no IUO (crash program) override init(model: DefaultAppsStepModel) { super.init(model: model) - button = OnboardingControl.button(BrowserVariantStrings.useCmux, prominent: true, target: self, action: #selector(requestClaim)) + _ = button // built here, as before headline.alignment = .center note.alignment = .center - stack = NSStackView(views: [headline, note, button]) stack.orientation = .vertical stack.alignment = .centerX stack.spacing = 12 diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/TopBarBrowserVariant.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/TopBarBrowserVariant.swift index 2b13a8591dd2..ca86ddeeb55e 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/TopBarBrowserVariant.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/DefaultBrowser/TopBarBrowserVariant.swift @@ -42,11 +42,11 @@ struct TopBarBrowser: OnboardingScreenVariant { final class TopBarBrowserBody: BrowserClaimView { private let status = OnboardingLabel.make(font: OnboardingMetrics.captionFont, color: Palette.textSecondary, lines: 2) - private var button: NSButton! + private lazy var button: NSButton = OnboardingControl.button(OnboardingStrings.makeDefaultBrowser, prominent: true, target: self, action: #selector(requestClaim)) // no IUO (crash program) override init(model: DefaultAppsStepModel) { super.init(model: model) - button = OnboardingControl.button(OnboardingStrings.makeDefaultBrowser, prominent: true, target: self, action: #selector(requestClaim)) + _ = button // built here, as before status.alignment = .center let stack = NSStackView(views: [button, status]) stack.orientation = .vertical diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/Import/ImportEverything.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/Import/ImportEverything.swift index c8edf9b47acb..c50c431f792e 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/Import/ImportEverything.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/Import/ImportEverything.swift @@ -27,8 +27,8 @@ struct ImportEverything: OnboardingScreenVariant { /// the hidden list, in a narrow centered column. final class ImportEverythingBody: NSView { private let model: ImportStepModel - private var master: NSButton! - private var disclosure: NSButton! + private lazy var master: NSButton = OnboardingControl.checkbox(ImportVariantStrings.everything, target: self, action: #selector(masterToggled)) // no IUO (crash program) + private lazy var disclosure: NSButton = NSButton(title: "", target: self, action: #selector(disclose)) // no IUO (crash program) private var disclosureRow: NSView? private let list: ImportProfileList private var loop: RenderLoop? @@ -37,13 +37,11 @@ final class ImportEverythingBody: NSView { self.model = model list = ImportProfileList(model: model, style: .checkboxes, spacing: 10, emptyAlignment: .center) super.init(frame: .zero) - master = OnboardingControl.checkbox(ImportVariantStrings.everything, target: self, action: #selector(masterToggled)) master.controlSize = .large master.allowsMixedState = true master.attributedTitle = NSAttributedString(string: ImportVariantStrings.everything, attributes: [ .font: NSFont.systemFont(ofSize: 15, weight: .medium), .foregroundColor: Palette.textPrimary, ]) - disclosure = NSButton(title: "", target: self, action: #selector(disclose)) disclosure.bezelStyle = .disclosure disclosure.setButtonType(.pushOnPushOff) disclosure.contentTintColor = Palette.textSecondary diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/Import/ImportProfileList.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/Import/ImportProfileList.swift index 1fab6a079068..a822cb5ab301 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/Import/ImportProfileList.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/Import/ImportProfileList.swift @@ -13,7 +13,7 @@ final class ImportProfileList: NSView { private let style: Style private let font: NSFont private let stack = NSStackView() - private var scroll: NSScrollView! + private lazy var scroll: NSScrollView = VariantLayout.scroller(stack) // no IUO (crash program) private let empty: NSTextField private var boxes: [String: NSButton] = [:] private var shown: [BrowserSourceProfile]? @@ -31,7 +31,6 @@ final class ImportProfileList: NSView { stack.orientation = .vertical stack.alignment = .leading stack.spacing = style == .checkboxes ? spacing : 0 - scroll = VariantLayout.scroller(stack) addSubview(scroll) addSubview(empty) let hug = bottomAnchor.constraint(equalTo: scroll.bottomAnchor) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/Import/ImportSummaryLine.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/Import/ImportSummaryLine.swift index b01cf18a9167..362109216a3e 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/Import/ImportSummaryLine.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/Import/ImportSummaryLine.swift @@ -29,8 +29,8 @@ final class ImportSummaryBody: NSView { private let model: ImportStepModel private let headline = OnboardingLabel.make(font: .systemFont(ofSize: 17, weight: .medium)) private let detail = OnboardingLabel.make(color: Palette.textSecondary) - private var disclosure: NSButton! - private var edit: NSButton! + private lazy var disclosure: NSButton = NSButton(title: "", target: self, action: #selector(disclose)) // no IUO (crash program) + private lazy var edit: NSButton = OnboardingControl.plainButton(ImportVariantStrings.edit, target: self, action: #selector(discloseFromLabel)) // no IUO (crash program) private let editors: NSView private var loop: RenderLoop? @@ -40,12 +40,10 @@ final class ImportSummaryBody: NSView { let kinds = ImportKindPicker(model: model, style: .inline) editors = VariantLayout.column([list, VariantLayout.hairline(), kinds], spacing: 16, fill: [list]) super.init(frame: .zero) - disclosure = NSButton(title: "", target: self, action: #selector(disclose)) disclosure.bezelStyle = .disclosure disclosure.setButtonType(.pushOnPushOff) disclosure.contentTintColor = Palette.textSecondary disclosure.setAccessibilityLabel(ImportVariantStrings.edit) - edit = OnboardingControl.plainButton(ImportVariantStrings.edit, target: self, action: #selector(discloseFromLabel)) let editRow = NSStackView(views: [disclosure, edit]) editRow.spacing = 4 editors.isHidden = true diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/Theme/ThemeRow.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/Theme/ThemeRow.swift index 228c50825ce2..5ee5798e7434 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/Theme/ThemeRow.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextOnboarding/Variants/Theme/ThemeRow.swift @@ -142,12 +142,11 @@ final class ThemeSwatchDot: ThemePressable, ThemeChoiceItem { /// A system radio button as a theme choice. final class ThemeRadioItem: NSView, ThemeChoiceItem { var onPress: (() -> Void)? - private var radio: NSButton! + private lazy var radio: NSButton = OnboardingControl.radio("", target: self, action: #selector(pressed)) // no IUO (crash program) init() { super.init(frame: .zero) translatesAutoresizingMaskIntoConstraints = false - radio = OnboardingControl.radio("", target: self, action: #selector(pressed)) addSubview(radio) NSLayoutConstraint.activate([ radio.leadingAnchor.constraint(equalTo: leadingAnchor), radio.trailingAnchor.constraint(lessThanOrEqualTo: trailingAnchor), diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextPages/PageWebView.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextPages/PageWebView.swift index 5f50a9b3b70b..03cea0c21c66 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextPages/PageWebView.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextPages/PageWebView.swift @@ -377,7 +377,7 @@ public final class PageWebView: NSView, PageSurface, WKNavigationDelegate { } } - public func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) { + public func webView(_ webView: WKWebView, didCommit navigation: WKNavigation?) { // A new document: the old one's subscriptions and host calls end with it, and it has not // painted yet. router.reset() @@ -388,7 +388,7 @@ public final class PageWebView: NSView, PageSurface, WKNavigationDelegate { router.send = { envelope in bridge.evaluate(PageRouter.receiveScript(envelope)) } } - public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { + public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation?) { loaded = true applyUIScale() applyTheme(force: true) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextRemote/Install/RemoteInstall.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextRemote/Install/RemoteInstall.swift index c72bf01efffe..e9f51ffe15cd 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextRemote/Install/RemoteInstall.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextRemote/Install/RemoteInstall.swift @@ -68,7 +68,7 @@ public enum RemoteInstallError: Error, Hashable, Sendable { /// Either way the machine checks the digest again and runs the staged /// binary's `remote-probe` before renaming it over the old one. public struct RemoteInstallPlan: Hashable, Sendable { - public static let base = URL(string: "https://files.cmux.com/cmux-tui")! + public static let base = URL(string: "https://files.cmux.com/cmux-tui") ?? URL(fileURLWithPath: "/dev/null") // a test parses it public let commit: String public let artifact: String public let sha256: String diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextRemote/Policy/RemoteRelayPolicy.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextRemote/Policy/RemoteRelayPolicy.swift index e3ca0aa4a724..2076913470be 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextRemote/Policy/RemoteRelayPolicy.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextRemote/Policy/RemoteRelayPolicy.swift @@ -80,14 +80,14 @@ public struct RemoteRelayPolicy: Sendable { for key in params.keys.sorted() where Self.commandParams.contains(key) { return .deny(.commandParam(key)) } - for key in params.keys.sorted() { + for (key, value) in params.sorted(by: { $0.key < $1.key }) { guard let kind = Self.idKind(key) else { continue } let owners: Set = switch kind { case .workspace: owned.workspaces case .surface: owned.surfaces case .tab: owned.tabs } - for id in Self.strings(params[key]!) where !owners.contains(id) { + for id in Self.strings(value) where !owners.contains(id) { return .deny(.unownedTarget(key, id)) } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextRemoteBrowser/Pane/RemoteBrowserSurfaces.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextRemoteBrowser/Pane/RemoteBrowserSurfaces.swift index fa8277e83e8e..fbd9d0856c3c 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextRemoteBrowser/Pane/RemoteBrowserSurfaces.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextRemoteBrowser/Pane/RemoteBrowserSurfaces.swift @@ -34,7 +34,7 @@ public final class RemoteBrowserSurfaces { public func apply(_ message: RbSurfaceMessage) { switch message { - case let .show(surface, stream, _, anchor, _, _): + case let .show(surface, stream, kind, anchor, _, _): // A show of an open surface (a new size) replaces it: its stream changed. remove(surface) let pane = RemoteBrowserPane(source: source(stream)) @@ -43,7 +43,7 @@ public final class RemoteBrowserSurfaces { pane.view.eventTarget = input pane.view.frame = anchor page.addSubview(pane.view) - open[surface] = Surface(pane: pane, input: input) + open[surface] = Surface(pane: pane, input: input, kind: kind) pane.start() case let .update(surface, anchor, _, _): if let view = open[surface]?.pane.view { view.frame = anchor } @@ -61,6 +61,12 @@ public final class RemoteBrowserSurfaces { open[surface]?.pane.view } + /// The host's kind string of an open surface (`page_popup`, `autofill`, + /// `extension_popup`, `bubble`). + package func kind(of surface: UInt32) -> String? { + open[surface]?.kind + } + /// Sends a pointer event at `point` (the surface's CSS pixels) to /// `surface`; dropped once the surface is gone. public func sendPointer(_ event: NSEvent, at point: CGPoint, surface: UInt32) { @@ -80,6 +86,7 @@ public final class RemoteBrowserSurfaces { private struct Surface { let pane: RemoteBrowserPane let input: SurfaceInput + let kind: String } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextRemoteView/Tab/RemoteViewTabRecord.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextRemoteView/Tab/RemoteViewTabRecord.swift index 58df3b76e4de..7943ea667c3e 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextRemoteView/Tab/RemoteViewTabRecord.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextRemoteView/Tab/RemoteViewTabRecord.swift @@ -118,7 +118,8 @@ public nonisolated struct RemoteViewTabRecord: Sendable, Hashable { URLQueryItem(name: "target", value: target.rawValue), URLQueryItem(name: "mode", value: mode.rawValue), ] - return components.url! + // A scheme, a host, no path and query items always form a URL; /dev/null stands in otherwise. + return components.url ?? URL(fileURLWithPath: "/dev/null") } /// True for `cmux://remote-view` with any query (valid or not): the App diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextResources/SharedProcess.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextResources/SharedProcess.swift index 36b5bedff19e..5f1de0f23bc4 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextResources/SharedProcess.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextResources/SharedProcess.swift @@ -15,7 +15,8 @@ public enum SharedRole: String, Sendable, Hashable, CaseIterable, Comparable { case extensions public static func < (lhs: SharedRole, rhs: SharedRole) -> Bool { - allCases.firstIndex(of: lhs)! < allCases.firstIndex(of: rhs)! + // Every case is in allCases; the declaration order is the order. + (allCases.firstIndex(of: lhs) ?? 0) < (allCases.firstIndex(of: rhs) ?? 0) } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSettings/JSONC.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSettings/JSONC.swift index 4ebdabedf795..9c68bc2c9a5e 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSettings/JSONC.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSettings/JSONC.swift @@ -196,7 +196,7 @@ public struct JSONC { } private static func setting(_ value: JSONValue, at path: ArraySlice, in object: ObjectNode, bytes: [UInt8], edits: inout [Edit]) { - let key = path.first! + guard let key = path.first else { return } // the public entry refuses an empty path let rest = path.dropFirst() if let member = object.members.first(where: { $0.key == key }) { if rest.isEmpty { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSettings/JSONValue.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSettings/JSONValue.swift index 8d7a8a7019e4..2eea1ba114c0 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSettings/JSONValue.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSettings/JSONValue.swift @@ -144,13 +144,13 @@ public enum JSONValue: Sendable, Hashable { return "[\n" + body.joined(separator: ",\n") + "\n" + outer + "]" case .object(let members): guard !members.isEmpty else { return "{}" } - let keys = members.keys.sorted() + let sorted = members.sorted { $0.key < $1.key } guard let indent else { - return "{" + keys.map { Self.quote($0) + ":" + members[$0]!.render(indent: nil, level: 0) }.joined(separator: ",") + "}" + return "{" + sorted.map { Self.quote($0.key) + ":" + $0.value.render(indent: nil, level: 0) }.joined(separator: ",") + "}" } let inner = base + String(repeating: indent, count: level + 1) let outer = base + String(repeating: indent, count: level) - let body = keys.map { inner + Self.quote($0) + ": " + members[$0]!.render(indent: indent, level: level + 1, base: base) } + let body = sorted.map { inner + Self.quote($0.key) + ": " + $0.value.render(indent: indent, level: level + 1, base: base) } return "{\n" + body.joined(separator: ",\n") + "\n" + outer + "}" } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSettings/Managed/ManagedStatusReport.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSettings/Managed/ManagedStatusReport.swift index 0ce1a4e242a6..6e789bede014 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSettings/Managed/ManagedStatusReport.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSettings/Managed/ManagedStatusReport.swift @@ -23,9 +23,9 @@ public nonisolated enum ManagedStatusReport { /// The report without its timestamp, so a load that changes nothing writes nothing. public static func body(context: Context, managed: ManagedPreferences, team: TeamPolicyLayer, effective: EffectiveSettings) -> JSONValue { - let applied = effective.managedKeys.keys.sorted().map { key -> JSONValue in + let applied = effective.managedKeys.sorted { $0.key < $1.key }.map { key, layer -> JSONValue in let source: String - switch effective.managedKeys[key]! { + switch layer { case .device: source = "mdm" case .team: source = "team" } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSettings/ShortcutBinding.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSettings/ShortcutBinding.swift index fab47127ae91..cbb1300e6648 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSettings/ShortcutBinding.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSettings/ShortcutBinding.swift @@ -185,6 +185,7 @@ public struct ShortcutBindingFormat { } private static func functionKey(_ code: Int) -> String { - String(Character(UnicodeScalar(UInt32(code))!)) + // Function-key codes are valid private-use scalars; NUL stands in otherwise (no trap). + String(Character(UnicodeScalar(UInt32(code)) ?? UnicodeScalar(0))) } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSettings/SurfaceTabBarParser.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSettings/SurfaceTabBarParser.swift index d8f50ac36e6c..d2076103a2fb 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSettings/SurfaceTabBarParser.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSettings/SurfaceTabBarParser.swift @@ -88,8 +88,7 @@ public struct SurfaceTabBarParser { return nil } button = reference(identifier, id: explicitID, path: path, actions: actions, diagnostics: &diagnostics) - case "command", "agent": - let type = forms.first! + case let type? where type == "command" || type == "agent": guard let command = ConfigActionParser.commandText(type: type, fields: fields, path: path, diagnostics: &diagnostics) else { return nil } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarEdits.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarEdits.swift index b01a0f1cf621..5355a500e401 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarEdits.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Logic/SidebarEdits.swift @@ -18,7 +18,8 @@ public nonisolated enum SidebarEdits { public static func apply(_ intent: SidebarIntent, to sections: inout [SidebarSection]) -> Bool { switch intent { case .select, .selectTab, .moveTab, .newWorkspace, .openGroup, .switchProfile, .newProfile, .reorderProfile, .activateItem, .installUpdate, .setAutomaticUpdates, - .openUpdateLink, .tryTip, .dismissTip, .layout, .toggleLayoutSection, .dropOnLayoutSection, .groupEditorEnded: + .openUpdateLink, .tryTip, .dismissTip, .openWhatsNew, .shareCmux, .dismissUpdated, .layout, .toggleLayoutSection, + .dropOnLayoutSection, .groupEditorEnded: return false case let .setGroupPinned(id, pinned): return mutateGroup(id, in: §ions) { $0.isPinned = pinned } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarGroupEditorItem.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarGroupEditorItem.swift new file mode 100644 index 000000000000..28b46d289441 --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarGroupEditorItem.swift @@ -0,0 +1,18 @@ +import Foundation + +/// One action row of the group editor, filled by the App from the action +/// registry (the editor never runs an action itself). +public nonisolated struct SidebarGroupEditorItem: Hashable, Sendable { + public var id: String + public var title: String + public var symbol: String? + /// The shortcut's display text, if the action has one. + public var shortcut: String? + + public init(id: String, title: String, symbol: String? = nil, shortcut: String? = nil) { + self.id = id + self.title = title + self.symbol = symbol + self.shortcut = shortcut + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarIntent.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarIntent.swift index 13c865ab2055..0933c3aaead9 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarIntent.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarIntent.swift @@ -71,6 +71,12 @@ public nonisolated enum SidebarIntent: Hashable, Sendable { case tryTip(String) /// The tip card's x: never show this tip again. case dismissTip(String) + /// The "cmux Updated!" card's "See What's New" row (`updates.whatsNew`). + case openWhatsNew + /// The "cmux Updated!" card's "Share cmux" row (`app.shareCmux`). + case shareCmux + /// The "cmux Updated!" card's x: this version is seen. + case dismissUpdated /// Change the section layout; the App sends it to the workspace store. case layout(SidebarLayoutOp) /// Workspace rows dropped on a top section (the pinned tiles or the top diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarModel.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarModel.swift index 28392e6220cc..ed22ee0d173b 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarModel.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarModel.swift @@ -80,8 +80,10 @@ public final class SidebarModel { /// Back in the footer: return to where the window was. @ObservationIgnored public var onBack: (() -> Void)? /// The "Did you know" card (BOTTOM-LEFT-CARDS K1), shown only while - /// ``updateCard`` is nil. + /// ``updateCard`` and ``updatedCard`` are nil. public var tipCard: SidebarTipCard? + /// The "cmux Updated!" card (cx-7py7), shown only while ``updateCard`` is nil. + public var updatedCard: SidebarUpdatedCard? /// A card's click, button or dismiss. @ObservationIgnored public var onCardAction: ((String, SidebarCardAction) -> Void)? /// Whether each workspace expands to show its intra-workspace tabs. @@ -191,7 +193,8 @@ public final class SidebarModel { dropClosed(Set(ids)) case let .switchProfile(id): activeProfileID = id - case .activateItem, .installUpdate, .setAutomaticUpdates, .openUpdateLink, .dropOnLayoutSection, .tryTip, .dismissTip: + case .activateItem, .installUpdate, .setAutomaticUpdates, .openUpdateLink, .dropOnLayoutSection, .tryTip, .dismissTip, + .openWhatsNew, .shareCmux, .dismissUpdated: break case let .layout(op): if case .success(let next) = SidebarLayoutReducer.reduce(layout, op) { layout = next } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarUpdatedCard.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarUpdatedCard.swift new file mode 100644 index 000000000000..8e538e0ab8e2 --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Model/SidebarUpdatedCard.swift @@ -0,0 +1,22 @@ +import Foundation + +/// The "cmux Updated!" card above the footer (cx-7py7): after the app +/// updated to a new version, a title with an x and two rows, "See What's +/// New" (`SidebarIntent.openWhatsNew`) and "Share cmux" (`.shareCmux`). +/// The x sends `.dismissUpdated`. It takes the bottom card slot before the +/// tip card (the tip waits); a staged update card wins over it. Text +/// arrives localized. +public nonisolated struct SidebarUpdatedCard: Hashable, Sendable { + public var title: String + public var whatsNewTitle: String + public var shareTitle: String + /// The x's tooltip and VoiceOver label. + public var dismissLabel: String + + public init(title: String, whatsNewTitle: String, shareTitle: String, dismissLabel: String) { + self.title = title + self.whatsNewTitle = whatsNewTitle + self.shareTitle = shareTitle + self.dismissLabel = dismissLabel + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Resources/Localizable.xcstrings b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Resources/Localizable.xcstrings index 2cff776cb57e..9a0dd0bf925c 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Resources/Localizable.xcstrings +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Resources/Localizable.xcstrings @@ -9956,6 +9956,1840 @@ } } } + }, + "sidebar.groupEditor.ax": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Edit Workspace Group" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ワークスペースグループを編集" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "تعديل مجموعة مساحات العمل" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Uredi grupu radnih prostora" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Rediger arbejdsområdegruppe" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Arbeitsbereichsgruppe bearbeiten" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Editar grupo de espacios de trabajo" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Modifier le groupe d’espaces de travail" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Modifica gruppo di spazi di lavoro" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "កែក្រុមកន្លែងធ្វើការ" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "워크스페이스 그룹 편집" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Rediger arbeidsområdegruppe" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Edytuj grupę obszarów roboczych" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Editar grupo de espaços de trabalho" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Изменить группу рабочих пространств" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "แก้ไขกลุ่มพื้นที่ทำงาน" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Çalışma alanı grubunu düzenle" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Редагувати групу робочих просторів" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Sửa nhóm không gian làm việc" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "编辑工作区组" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "編輯工作區群組" + } + } + } + }, + "sidebar.groupEditor.name": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Group name" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "グループ名" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "اسم المجموعة" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Naziv grupe" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Gruppenavn" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Gruppenname" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Nombre del grupo" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Nom du groupe" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Nome del gruppo" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "ឈ្មោះក្រុម" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "그룹 이름" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Gruppenavn" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Nazwa grupy" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Nome do grupo" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Название группы" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "ชื่อกลุ่ม" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Grup adı" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Назва групи" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Tên nhóm" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "组名称" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "群組名稱" + } + } + } + }, + "sidebar.groupEditor.namePlaceholder": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Name this group" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "グループに名前を付ける" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "سمِّ هذه المجموعة" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Imenuj ovu grupu" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Navngiv denne gruppe" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Gruppe benennen" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Ponle nombre a este grupo" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Nommer ce groupe" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Assegna un nome al gruppo" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "ដាក់ឈ្មោះក្រុមនេះ" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "그룹 이름 지정" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Gi gruppen et navn" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Nazwij tę grupę" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Dê um nome a este grupo" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Назовите группу" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "ตั้งชื่อกลุ่มนี้" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Bu gruba ad verin" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Назвіть цю групу" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Đặt tên cho nhóm này" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "为此组命名" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "為此群組命名" + } + } + } + }, + "sidebar.groupEditor.newWorkspace": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "New Workspace in Group" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "グループに新規ワークスペース" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "مساحة عمل جديدة في المجموعة" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Novi radni prostor u grupi" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Nyt arbejdsområde i gruppe" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Neuer Arbeitsbereich in Gruppe" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Nuevo espacio de trabajo en el grupo" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Nouvel espace de travail dans le groupe" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Nuovo spazio di lavoro nel gruppo" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "កន្លែងធ្វើការថ្មីក្នុងក្រុម" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "그룹에 새 워크스페이스" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Nytt arbeidsområde i gruppen" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Nowy obszar roboczy w grupie" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Novo espaço de trabalho no grupo" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Новое рабочее пространство в группе" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "พื้นที่ทำงานใหม่ในกลุ่ม" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Grupta yeni çalışma alanı" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Новий робочий простір у групі" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Không gian làm việc mới trong nhóm" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "在组中新建工作区" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "在群組中新增工作區" + } + } + } + }, + "sidebar.groupEditor.moveToNewWindow": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Move Group to New Window" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "グループを新規ウインドウに移動" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "نقل المجموعة إلى نافذة جديدة" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Premjesti grupu u novi prozor" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Flyt gruppe til nyt vindue" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Gruppe in neues Fenster bewegen" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Mover el grupo a una ventana nueva" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Déplacer le groupe dans une nouvelle fenêtre" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Sposta il gruppo in una nuova finestra" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "ផ្លាស់ទីក្រុមទៅបង្អួចថ្មី" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "그룹을 새 윈도우로 이동" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Flytt gruppen til nytt vindu" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Przenieś grupę do nowego okna" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Mover grupo para nova janela" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Переместить группу в новое окно" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "ย้ายกลุ่มไปยังหน้าต่างใหม่" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Grubu yeni pencereye taşı" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Перемістити групу в нове вікно" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Chuyển nhóm sang cửa sổ mới" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "将组移到新窗口" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "將群組移到新視窗" + } + } + } + }, + "sidebar.groupEditor.close": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Close Group" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "グループを閉じる" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "إغلاق المجموعة" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Zatvori grupu" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Luk gruppe" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Gruppe schließen" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Cerrar grupo" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Fermer le groupe" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Chiudi gruppo" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "បិទក្រុម" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "그룹 닫기" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Lukk gruppen" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Zamknij grupę" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Fechar grupo" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Закрыть группу" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "ปิดกลุ่ม" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Grubu kapat" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Закрити групу" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Đóng nhóm" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "关闭组" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "關閉群組" + } + } + } + }, + "sidebar.groupEditor.ungroup": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Ungroup" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "グループ解除" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "فك التجميع" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Razgrupiši" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Opløs gruppe" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Gruppierung aufheben" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Desagrupar" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Dissocier" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Separa" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "បំបែកក្រុម" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "그룹 해제" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Opphev gruppe" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Rozgrupuj" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Desagrupar" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Разгруппировать" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "เลิกจัดกลุ่ม" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Grubu çöz" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Розгрупувати" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Bỏ nhóm" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "取消分组" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "取消群組" + } + } + } + }, + "sidebar.groupEditor.delete": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Delete Group" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "グループを削除" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "حذف المجموعة" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Izbriši grupu" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Slet gruppe" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Gruppe löschen" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Eliminar grupo" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Supprimer le groupe" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Elimina gruppo" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "លុបក្រុម" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "그룹 삭제" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Slett gruppen" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Usuń grupę" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Excluir grupo" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Удалить группу" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "ลบกลุ่ม" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Grubu sil" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Видалити групу" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Xóa nhóm" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "删除组" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "刪除群組" + } + } + } + }, + "sidebar.groupEditor.moreActions": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "More Group Actions…" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "その他のグループ操作…" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "مزيد من إجراءات المجموعة…" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Više radnji za grupu…" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Flere gruppehandlinger…" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Weitere Gruppenaktionen…" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Más acciones del grupo…" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Autres actions du groupe…" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Altre azioni del gruppo…" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "សកម្មភាពក្រុមបន្ថែម…" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "그룹 작업 더 보기…" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Flere gruppehandlinger…" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Więcej działań grupy…" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Mais ações do grupo…" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Другие действия с группой…" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "การทำงานกับกลุ่มเพิ่มเติม…" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Diğer grup işlemleri…" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Інші дії з групою…" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Thao tác nhóm khác…" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "更多组操作…" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "更多群組操作…" + } + } + } + }, + "sidebar.group.more": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Group options" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "グループのオプション" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "خيارات المجموعة" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Opcije grupe" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Gruppeindstillinger" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Gruppenoptionen" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Opciones del grupo" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Options du groupe" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Opzioni gruppo" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "ជម្រើសក្រុម" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "그룹 옵션" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Gruppealternativer" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Opcje grupy" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Opções do grupo" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Параметры группы" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "ตัวเลือกกลุ่ม" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Grup seçenekleri" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Параметри групи" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Tùy chọn nhóm" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "组选项" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "群組選項" + } + } + } + }, + "sidebar.group.collapse": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Collapse group" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "グループを折りたたむ" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "طي المجموعة" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Skupi grupu" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Fold gruppe sammen" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Gruppe einklappen" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Contraer grupo" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Réduire le groupe" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Comprimi gruppo" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "បង្រួមក្រុម" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "그룹 접기" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Skjul gruppen" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Zwiń grupę" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Recolher grupo" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Свернуть группу" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "ยุบกลุ่ม" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Grubu daralt" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Згорнути групу" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Thu gọn nhóm" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "折叠组" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "收合群組" + } + } + } + }, + "sidebar.group.expand": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Expand group" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "グループを展開" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "توسيع المجموعة" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Proširi grupu" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Fold gruppe ud" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Gruppe ausklappen" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Expandir grupo" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Développer le groupe" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Espandi gruppo" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "ពង្រីកក្រុម" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "그룹 펼치기" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Vis gruppen" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Rozwiń grupę" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Expandir grupo" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Развернуть группу" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "ขยายกลุ่ม" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Grubu genişlet" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Розгорнути групу" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Mở rộng nhóm" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "展开组" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "展開群組" + } + } + } + }, + "sidebar.groupColor.none": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No color" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "色なし" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "بلا لون" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Bez boje" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Ingen farve" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Keine Farbe" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Sin color" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Aucune couleur" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Nessun colore" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "គ្មានពណ៌" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "색상 없음" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Ingen farge" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Bez koloru" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Sem cor" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Без цвета" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "ไม่มีสี" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Renk yok" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Без кольору" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Không màu" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "无颜色" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "無顏色" + } + } + } + }, + "sidebar.groupColor.slot": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Theme color %d" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "テーマの色 %d" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "لون السمة %d" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Boja teme %d" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Temafarve %d" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Designfarbe %d" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Color del tema %d" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Couleur du thème %d" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Colore del tema %d" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "ពណ៌រចនាប័ទ្ម %d" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "테마 색상 %d" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Temafarge %d" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Kolor motywu %d" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Cor do tema %d" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Цвет темы %d" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "สีธีม %d" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Tema rengi %d" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Колір теми %d" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Màu chủ đề %d" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "主题颜色 %d" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "主題顏色 %d" + } + } + } } }, "version": "1.0" diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Sections/SidebarLayoutReducer.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Sections/SidebarLayoutReducer.swift index 6be5db260e64..8d265b6463bd 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Sections/SidebarLayoutReducer.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Sections/SidebarLayoutReducer.swift @@ -14,7 +14,7 @@ public nonisolated enum SidebarLayoutReducer { /// a no-op returns the document unchanged. public static func reduce(_ document: SidebarLayoutDocument, _ op: SidebarLayoutOp) -> Result { var sections = document.sections - do { + do throws(SidebarLayoutReject) { switch op { case let .sectionAdd(section, index): try add(section, at: index, to: §ions) @@ -42,10 +42,9 @@ public nonisolated enum SidebarLayoutReducer { case .reset: sections = SidebarLayoutDocument.defaults.sections } - } catch let reject as SidebarLayoutReject { - return .failure(reject) } catch { - preconditionFailure("SidebarLayoutReducer throws only SidebarLayoutReject") + // Typed throws: the compiler proves every error here is a SidebarLayoutReject. + return .failure(error) } guard sections != document.sections else { return .success(document) } return .success(SidebarLayoutDocument(revision: document.revision + 1, sections: sections)) @@ -53,7 +52,7 @@ public nonisolated enum SidebarLayoutReducer { // MARK: Sections - private static func add(_ section: LayoutSection, at index: Int, to sections: inout [LayoutSection]) throws { + private static func add(_ section: LayoutSection, at index: Int, to sections: inout [LayoutSection]) throws(SidebarLayoutReject) { guard sections.count < maxSections else { throw SidebarLayoutReject.tooMany } // L2: ids are unique across sections and items. let sectionIDs = Set(sections.map(\.id.rawValue)) @@ -81,7 +80,7 @@ public nonisolated enum SidebarLayoutReducer { sections.insert(section, at: insertionIndex(region: section.region, index: index, in: sections)) } - private static func update(_ id: LayoutSectionID, _ patch: SectionPatch, in sections: inout [LayoutSection]) throws { + private static func update(_ id: LayoutSectionID, _ patch: SectionPatch, in sections: inout [LayoutSection]) throws(SidebarLayoutReject) { guard let s = sections.firstIndex(where: { $0.id == id }) else { throw SidebarLayoutReject.unknownSection } if let title = patch.title { try validate(title: title.value) @@ -107,7 +106,7 @@ public nonisolated enum SidebarLayoutReducer { } } - private static func moveSection(_ id: LayoutSectionID, to region: SidebarRegion, at index: Int, in sections: inout [LayoutSection]) throws { + private static func moveSection(_ id: LayoutSectionID, to region: SidebarRegion, at index: Int, in sections: inout [LayoutSection]) throws(SidebarLayoutReject) { guard let s = sections.firstIndex(where: { $0.id == id }) else { throw SidebarLayoutReject.unknownSection } var section = sections.remove(at: s) section.region = region @@ -131,7 +130,7 @@ public nonisolated enum SidebarLayoutReducer { // MARK: Items - private static func addItem(_ item: LayoutItem, to id: LayoutSectionID, at index: Int, in sections: inout [LayoutSection]) throws { + private static func addItem(_ item: LayoutItem, to id: LayoutSectionID, at index: Int, in sections: inout [LayoutSection]) throws(SidebarLayoutReject) { guard let s = sections.firstIndex(where: { $0.id == id }) else { throw SidebarLayoutReject.unknownSection } try ensureItems(sections[s]) try validate(span: item.span) @@ -144,7 +143,7 @@ public nonisolated enum SidebarLayoutReducer { sections[s].items.insert(item, at: slot) } - private static func moveItem(_ id: LayoutItemID, to target: LayoutSectionID, at index: Int, in sections: inout [LayoutSection]) throws { + private static func moveItem(_ id: LayoutItemID, to target: LayoutSectionID, at index: Int, in sections: inout [LayoutSection]) throws(SidebarLayoutReject) { guard let (s, i) = locate(id, in: sections) else { throw SidebarLayoutReject.unknownItem } guard let t = sections.firstIndex(where: { $0.id == target }) else { throw SidebarLayoutReject.unknownSection } try ensureItems(sections[t]) @@ -164,7 +163,7 @@ public nonisolated enum SidebarLayoutReducer { // MARK: Validation - private static func ensureItems(_ section: LayoutSection) throws { + private static func ensureItems(_ section: LayoutSection) throws(SidebarLayoutReject) { switch section.content { case .items: return case .workspaces: throw SidebarLayoutReject.workspacesRequired @@ -172,19 +171,19 @@ public nonisolated enum SidebarLayoutReducer { } } - private static func validate(title: String?) throws { + private static func validate(title: String?) throws(SidebarLayoutReject) { guard let title else { return } // Unicode scalars, like the store's reducer (Rust `chars().count()`). guard !title.isEmpty, title.unicodeScalars.count <= maxTitleLength else { throw SidebarLayoutReject.invalidTitle } } /// L4: an item's grid span is 1...12, like the arrangement's columns. - private static func validate(span: Int?) throws { + private static func validate(span: Int?) throws(SidebarLayoutReject) { guard let span else { return } guard SectionArrangement.columnsRange.contains(span) else { throw SidebarLayoutReject.invalidArrangement } } - private static func validate(maxRows: Int?) throws { + private static func validate(maxRows: Int?) throws(SidebarLayoutReject) { guard let maxRows else { return } guard maxRowsRange.contains(maxRows) else { throw SidebarLayoutReject.invalidMaxRows } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Sections/SidebarRegionDrop.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Sections/SidebarRegionDrop.swift index ebd130daeebf..067a970705a8 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Sections/SidebarRegionDrop.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Sections/SidebarRegionDrop.swift @@ -4,8 +4,9 @@ import Foundation /// Drop-to-pin (PINNED-ITEMS-END-TO-END P2): where a workspace row dragged /// from the list lands in the band above it. The items section under the /// point (its header, its rows or tiles, half a section gap around them) -/// takes it, at the index of the first item the point is not past; past -/// every item, it goes last. Pure, read from the band's layout. +/// takes it, at the index of the first item the point is not past (never +/// before the section's leading built-in rows); past every item, it goes +/// last. Pure, read from the band's layout. nonisolated struct SidebarRegionDrop: Hashable, Sendable { var section: LayoutSectionID var index: Int @@ -22,7 +23,10 @@ nonisolated struct SidebarRegionDrop: Hashable, Sendable { guard point.y >= frame.minY, point.y < frame.maxY else { continue } let next = rows.first { row in Self.item(of: row) != nil && !Self.isPast(point, row) } let index = next.flatMap(Self.item).flatMap { id in section.items.firstIndex { $0.id == id } } ?? section.items.count - return SidebarRegionDrop(section: section.id, index: index, frame: frame) + // The built-in rows (Home, App Store) stay at the top of their + // section: a pin goes after them (cx-odqn, coordinator 2026-10-08). + let builtIns = section.items.prefix { $0.ref.kind != LayoutItemRef.workspaceKind }.count + return SidebarRegionDrop(section: section.id, index: max(index, builtIns), frame: frame) } return nil } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/GroupEditor/SidebarGroupEditor.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/GroupEditor/SidebarGroupEditor.swift new file mode 100644 index 000000000000..b6adb111f14a --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/GroupEditor/SidebarGroupEditor.swift @@ -0,0 +1,323 @@ +import AppKit +import CmuxNextDesign +import QuartzCore + +/// The workspace group editor (cx-rcby, Lawrence 2026-10-08: the Chrome tab +/// group bubble): a name field that opens focused with the name selected, +/// a row of color dots (none, then the theme's palette) and the group's +/// actions in sections. Opened from the group chip, its more button or a +/// right-click. Every edit goes out through the callbacks; the editor +/// never edits sidebar state. +@MainActor +final class SidebarGroupEditor { + var onRename: ((GroupID, String) -> Void)? + var onColor: ((GroupID, GroupColor) -> Void)? + var onItem: ((GroupID, String) -> Void)? + /// The editor closed, after any rename it committed. + var onClose: ((GroupID) -> Void)? + private var panel: SidebarGroupEditorPanel? + private(set) var shownGroup: GroupID? + /// A member of the shown group: the store may give a group the sidebar + /// made another id, and the editor follows it. + private var member: WorkspaceID? + /// The groups the last update showed (`follow`). + private var known: Set = [] + /// The group whose editor closed last, and the event time it closed at. + private var lastClosed: (group: GroupID, time: TimeInterval)? + + var isVisible: Bool { shownGroup != nil } + /// False in tests: the bubble is laid out but never put on screen. + var ordersFront = true + + func show(_ group: SidebarGroup, items: [[SidebarGroupEditorItem]], anchor: CGRect, parent: NSWindow, themeAnchor: NSView) { + if let shownGroup, shownGroup != group.id { hide() } + let panel = panel ?? SidebarGroupEditorPanel() + self.panel = panel + panel.onRename = { [weak self] name in + guard let self, let id = self.shownGroup else { return } + self.onRename?(id, name) + } + panel.onColor = { [weak self] color in + guard let self, let id = self.shownGroup else { return } + self.onColor?(id, color) + } + panel.onItem = { [weak self] item in + guard let self, let id = self.shownGroup else { return } + self.onItem?(id, item) + } + panel.onClose = { [weak self] in + guard let self, let id = self.shownGroup else { return } + self.shownGroup = nil + self.member = nil + self.lastClosed = (id, NSApp.currentEvent?.timestamp ?? ProcessInfo.processInfo.systemUptime) + self.onClose?(id) + } + shownGroup = group.id + member = group.workspaces.first?.id + panel.configure(group, items: items) + panel.adoptThemeScope(of: themeAnchor) + // A window off screen (tests, a hidden window) gets no bubble on screen. + panel.present(below: anchor, parent: parent, ordersFront: ordersFront && parent.isVisible) + } + + /// Keeps the open editor on its group after a sidebar update: the same + /// group refreshes its color; a group the store re-identified is found + /// by its member; a group that is gone closes the editor. + func follow(_ groups: [GroupID: SidebarGroup]) { + defer { known = Set(groups.keys) } + guard let shown = shownGroup else { return } + if let group = groups[shown] { + panel?.refresh(group) + if member == nil { member = group.workspaces.first?.id } + return + } + // Only a group that just appeared can be the shown one under a new + // id; a member dragged into another group ends the editor. + if let member, let moved = groups.values.first(where: { !known.contains($0.id) && $0.workspaces.contains { $0.id == member } }) { + shownGroup = moved.id + panel?.refresh(moved) + return + } + hide() + } + + /// Whether the editor of `group` closed during the click that is + /// happening now (the click made the sidebar's window key, which closes + /// the bubble first): that click toggles it closed, it does not reopen it. + func closedByThisClick(_ group: GroupID, at timestamp: TimeInterval?) -> Bool { + guard let closed = lastClosed, closed.group == group, let timestamp else { return false } + return timestamp - closed.time <= NSEvent.doubleClickInterval + } + + func hide() { + panel?.dismiss() + } + + /// The editor's bubble, for tests and the real-app proof. + var bubble: SidebarGroupEditorPanel? { panel } +} + +/// The editor bubble: Liquid Glass (opaque under Reduce Transparency), in +/// the sidebar's theme scope. +final class SidebarGroupEditorPanel: ActiveAppKeyPanel, NSTextFieldDelegate { + var onRename: ((String) -> Void)? + var onColor: ((GroupColor) -> Void)? + var onItem: ((String) -> Void)? + var onClose: (() -> Void)? + + let nameField = NSTextField() + private let field = NSView() + private(set) var swatches: [SidebarGroupSwatchView] = [] + private let stack = NSStackView() + private var name = "" + private var fieldWidth: NSLayoutConstraint? + private var dismissing = false + /// Shown (on screen, or laid out in a test) and not yet dismissed. + private(set) var isPresented = false + + init() { + super.init(contentRect: .zero, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: true) + isOpaque = false + backgroundColor = .clear + hasShadow = true + isReleasedWhenClosed = false + hidesOnDeactivate = true + animationBehavior = .none + collectionBehavior = [.transient, .ignoresCycle, .fullScreenAuxiliary] + let content = ThemeChangeView() + let glass = Glass.makeOverlayPanel(content: content, cornerRadius: Metrics.panelCornerRadius) + glass.translatesAutoresizingMaskIntoConstraints = true + contentView = glass + content.onThemeChange = { [weak self, weak glass] in + glass?.applyTheme() + self?.applyColors() + } + build(in: content) + setAccessibilityLabel(GroupEditorStrings.editor) + onKeyElsewhere = { [weak self] in self?.dismiss() } + } + + override var canBecomeMain: Bool { false } + + /// About the Chrome bubble's width at the sidebar's type size. + static var width: CGFloat { Metrics.space6 * 15 } + + private func build(in content: NSView) { + nameField.placeholderString = GroupEditorStrings.namePlaceholder + nameField.font = Typography.body + nameField.isBezeled = false + nameField.drawsBackground = false + nameField.focusRingType = .none + nameField.delegate = self + nameField.lineBreakMode = .byTruncatingTail + nameField.setAccessibilityLabel(GroupEditorStrings.nameLabel) + field.wantsLayer = true + field.layer?.cornerRadius = Metrics.itemCornerRadius + field.layer?.cornerCurve = .continuous + nameField.translatesAutoresizingMaskIntoConstraints = false + field.addSubview(nameField) + + swatches = GroupColor.editorOrder.map { color in + let swatch = SidebarGroupSwatchView(color: color) + swatch.onPick = { [weak self] picked in self?.pick(picked) } + return swatch + } + stack.orientation = .vertical + stack.alignment = .leading + stack.spacing = Metrics.space1 + stack.translatesAutoresizingMaskIntoConstraints = false + content.addSubview(stack) + let p = Metrics.space4 + NSLayoutConstraint.activate([ + stack.topAnchor.constraint(equalTo: content.topAnchor, constant: p), + stack.leadingAnchor.constraint(equalTo: content.leadingAnchor, constant: p), + stack.trailingAnchor.constraint(equalTo: content.trailingAnchor, constant: -p), + stack.bottomAnchor.constraint(equalTo: content.bottomAnchor, constant: -p), + field.heightAnchor.constraint(equalToConstant: Metrics.tabHeight), + stack.widthAnchor.constraint(greaterThanOrEqualToConstant: Self.width - 2 * p), + nameField.leadingAnchor.constraint(equalTo: field.leadingAnchor, constant: Metrics.space3), + nameField.trailingAnchor.constraint(equalTo: field.trailingAnchor, constant: -Metrics.space3), + nameField.centerYAnchor.constraint(equalTo: field.centerYAnchor), + ]) + } + + /// Lays out the name, the dots and the item sections for `group`. + func configure(_ group: SidebarGroup, items: [[SidebarGroupEditorItem]]) { + name = group.name + nameField.stringValue = group.name + for swatch in swatches { swatch.isChosen = swatch.color == group.color } + stack.arrangedSubviews.forEach { $0.removeFromSuperview() } + let dots = NSStackView(views: swatches) + dots.spacing = Metrics.space1 + dots.distribution = .equalSpacing + var views: [NSView] = [dots] + stack.addArrangedSubview(field) + stack.addArrangedSubview(dots) + stack.setCustomSpacing(Metrics.space3, after: field) + var last: NSView = dots + for section in items where !section.isEmpty { + let separator = HairlineView() + separator.heightAnchor.constraint(equalToConstant: 1).isActive = true + stack.setCustomSpacing(Metrics.space3, after: last) + stack.addArrangedSubview(separator) + stack.setCustomSpacing(Metrics.space2, after: separator) + views.append(separator) + for item in section { + let row = SidebarGroupEditorRow(item) + row.onPress = { [weak self] in self?.press(item.id) } + stack.addArrangedSubview(row) + views.append(row) + last = row + } + } + for view in views { view.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true } + if fieldWidth == nil { + fieldWidth = field.widthAnchor.constraint(equalTo: stack.widthAnchor) + fieldWidth?.isActive = true + } + applyColors() + } + + /// The group changed while the editor is open: its color; its name only + /// when the field is not being edited. + func refresh(_ group: SidebarGroup) { + for swatch in swatches { swatch.isChosen = swatch.color == group.color } + // A name the person typed is kept; an untouched field follows the group. + if nameField.stringValue == name { + nameField.stringValue = group.name + } + name = group.name + } + + private func applyColors() { + guard let content = (contentView as? OverlaySurfaceView) else { return } + content.performWithTheme { + nameField.textColor = Palette.textPrimary + field.layer?.backgroundColor = Palette.hoverFill.cgColor + field.layer?.borderColor = Palette.focusRing.cgColor + field.layer?.borderWidth = Metrics.dividerThickness + } + styleFieldEditor() + } + + func pick(_ color: GroupColor) { + for swatch in swatches { swatch.isChosen = swatch.color == color } + onColor?(color) + } + + func press(_ item: String) { + commitName() + onItem?(item) + dismiss() + } + + private func commitName() { + let text = nameField.stringValue.trimmingCharacters(in: .whitespacesAndNewlines) + guard !text.isEmpty, text != name else { return } + name = text + onRename?(text) + } + + func present(below anchor: CGRect, parent: NSWindow, ordersFront: Bool = true) { + dismissing = false + isPresented = true + if ordersFront, self.parent !== parent { + self.parent?.removeChildWindow(self) + parent.addChildWindow(self, ordered: .above) + } + contentView?.layoutSubtreeIfNeeded() + let size = contentView?.fittingSize ?? .zero + var origin = CGPoint(x: anchor.minX, y: anchor.minY - Metrics.space1 - size.height) + if let screen = parent.screen ?? NSScreen.main { + let visible = screen.visibleFrame + origin.x = min(max(origin.x, visible.minX + Metrics.space2), visible.maxX - size.width - Metrics.space2) + // No room below: open above the chip. + if origin.y < visible.minY + Metrics.space2 { origin.y = anchor.maxY + Metrics.space1 } + } + setFrame(CGRect(origin: origin, size: size), display: ordersFront) + guard ordersFront else { return } + alphaValue = 0 + makeKeyAndOrderFront(nil) + makeFirstResponder(nameField) + nameField.currentEditor()?.selectAll(nil) + styleFieldEditor() + Motion.animateTimed(.fadeIn, in: contentView) { animator().alphaValue = 1 } + } + + /// Gray selection and caret: the system accent (blue) never shows in chrome. + private func styleFieldEditor() { + guard let editor = nameField.currentEditor() as? NSTextView else { return } + nameField.performWithTheme { + editor.selectedTextAttributes = [.backgroundColor: Palette.textSelection] + editor.insertionPointColor = Palette.textPrimary + } + } + + func dismiss() { + guard !dismissing, isPresented else { return } + dismissing = true + isPresented = false + commitName() + parent?.removeChildWindow(self) + orderOut(nil) + onClose?() + } + + override func resignKey() { + super.resignKey() + dismiss() + } + + override func cancelOperation(_ sender: Any?) { + dismiss() + } + + /// Return commits the name and closes; Escape closes (a typed name is kept, like Chrome). + func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool { + if selector == #selector(NSResponder.insertNewline(_:)) || selector == #selector(NSResponder.cancelOperation(_:)) { + dismiss() + return true + } + return false + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/GroupEditor/SidebarGroupEditorControls.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/GroupEditor/SidebarGroupEditorControls.swift new file mode 100644 index 000000000000..91da1d899a27 --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/GroupEditor/SidebarGroupEditorControls.swift @@ -0,0 +1,181 @@ +import AppKit +import CmuxNextDesign +import QuartzCore + +/// One color dot in the group editor: the theme's palette color, or for +/// none (grey) the neutral fill with a hairline edge. The chosen dot gets a +/// ring in the primary text color. +final class SidebarGroupSwatchView: NSView { + let color: GroupColor + var isChosen = false { didSet { if oldValue != isChosen { updateColors() } } } + var onPick: ((GroupColor) -> Void)? + private let fill = CALayer() + private let ring = CALayer() + private var isHovered = false { didSet { if oldValue != isHovered { updateColors() } } } + + init(color: GroupColor) { + self.color = color + super.init(frame: .zero) + wantsLayer = true + layerContentsRedrawPolicy = .never + ring.borderWidth = Metrics.space1 * 0.75 + for sublayer in [ring, fill] { + sublayer.actions = ["bounds": NSNull(), "position": NSNull(), "cornerRadius": NSNull(), "backgroundColor": NSNull(), "borderColor": NSNull()] + layer?.addSublayer(sublayer) + } + setAccessibilityElement(true) + setAccessibilityRole(.radioButton) + setAccessibilityLabel(GroupEditorStrings.colorName(color)) + addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self, userInfo: nil)) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { nil } + + override var intrinsicContentSize: NSSize { + let side = Metrics.iconSize + Metrics.space2 + return NSSize(width: side, height: side) + } + + override func layout() { + super.layout() + let side = min(bounds.width, bounds.height) + let outer = CGRect(x: (bounds.width - side) / 2, y: (bounds.height - side) / 2, width: side, height: side) + ring.frame = outer + ring.cornerRadius = side / 2 + let inner = outer.insetBy(dx: Metrics.space1 + 1, dy: Metrics.space1 + 1) + fill.frame = inner + fill.cornerRadius = inner.width / 2 + updateColors() + } + + override func viewDidChangeEffectiveAppearance() { + super.viewDidChangeEffectiveAppearance() + updateColors() + } + + private func updateColors() { + performWithTheme { + // The same color the group's header bar takes; none draws an edge too. + fill.backgroundColor = color.headerFill.cgColor + fill.borderColor = Palette.textTertiary.cgColor + fill.borderWidth = color == .grey ? Metrics.dividerThickness : 0 + ring.borderColor = (isChosen ? Palette.textPrimary : (isHovered ? Palette.separator : NSColor.clear)).cgColor + } + setAccessibilityValue(isChosen ? 1 : 0) + } + + override func mouseEntered(with event: NSEvent) { isHovered = true } + override func mouseExited(with event: NSEvent) { isHovered = false } + override func mouseDown(with event: NSEvent) {} + override func mouseUp(with event: NSEvent) { + if bounds.contains(convert(event.locationInWindow, from: nil)) { onPick?(color) } + } + + override func accessibilityPerformPress() -> Bool { + onPick?(color) + return true + } +} + +/// A menu-like row of the group editor: an icon, the title and the +/// action's shortcut, like a menu item. +final class SidebarGroupEditorRow: NSView { + var onPress: (() -> Void)? + let item: SidebarGroupEditorItem + private let icon = NSImageView() + private let label = NSTextField(labelWithString: "") + private let shortcut = NSTextField(labelWithString: "") + private var isHovered = false { didSet { if oldValue != isHovered { updateColors() } } } + + init(_ item: SidebarGroupEditorItem) { + self.item = item + super.init(frame: .zero) + wantsLayer = true + layer?.cornerRadius = Metrics.itemCornerRadius + layer?.cornerCurve = .continuous + label.font = Typography.body + label.stringValue = item.title + label.lineBreakMode = .byTruncatingTail + shortcut.font = Typography.body + shortcut.stringValue = item.shortcut ?? "" + shortcut.alignment = .right + icon.image = item.symbol.flatMap { NSImage(systemSymbolName: $0, accessibilityDescription: nil) } + icon.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: Typography.body.pointSize, weight: .regular) + for view in [icon, label, shortcut] { + view.translatesAutoresizingMaskIntoConstraints = false + addSubview(view) + } + label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + NSLayoutConstraint.activate([ + heightAnchor.constraint(equalToConstant: Metrics.sidebarRowHeight), + icon.leadingAnchor.constraint(equalTo: leadingAnchor, constant: Metrics.space3), + icon.centerYAnchor.constraint(equalTo: centerYAnchor), + icon.widthAnchor.constraint(equalToConstant: Metrics.iconSize), + label.leadingAnchor.constraint(equalTo: icon.trailingAnchor, constant: Metrics.space3), + label.centerYAnchor.constraint(equalTo: centerYAnchor), + shortcut.leadingAnchor.constraint(greaterThanOrEqualTo: label.trailingAnchor, constant: Metrics.space4), + shortcut.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -Metrics.space3), + shortcut.centerYAnchor.constraint(equalTo: centerYAnchor), + ]) + setAccessibilityElement(true) + setAccessibilityRole(.button) + setAccessibilityLabel(item.title) + addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self, userInfo: nil)) + updateColors() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { nil } + + override func viewDidChangeEffectiveAppearance() { + super.viewDidChangeEffectiveAppearance() + updateColors() + } + + private func updateColors() { + performWithTheme { + layer?.backgroundColor = isHovered ? Palette.hoverFill.cgColor : nil + label.textColor = Palette.textPrimary + icon.contentTintColor = Palette.textSecondary + shortcut.textColor = Palette.textTertiary + } + } + + override func mouseEntered(with event: NSEvent) { isHovered = true } + override func mouseExited(with event: NSEvent) { isHovered = false } + override func mouseDown(with event: NSEvent) {} + override func mouseUp(with event: NSEvent) { + if bounds.contains(convert(event.locationInWindow, from: nil)) { onPress?() } + } + + override func accessibilityPerformPress() -> Bool { + onPress?() + return true + } +} + +/// The group editor's and the group chip's strings (Resources/Localizable.xcstrings, en and ja). +enum GroupEditorStrings { + static var editor: String { String(localized: "sidebar.groupEditor.ax", defaultValue: "Edit Workspace Group", bundle: .module) } + static var nameLabel: String { String(localized: "sidebar.groupEditor.name", defaultValue: "Group name", bundle: .module) } + static var namePlaceholder: String { String(localized: "sidebar.groupEditor.namePlaceholder", defaultValue: "Name this group", bundle: .module) } + static var newWorkspace: String { String(localized: "sidebar.groupEditor.newWorkspace", defaultValue: "New Workspace in Group", bundle: .module) } + static var moveToNewWindow: String { String(localized: "sidebar.groupEditor.moveToNewWindow", defaultValue: "Move Group to New Window", bundle: .module) } + static var close: String { String(localized: "sidebar.groupEditor.close", defaultValue: "Close Group", bundle: .module) } + static var ungroup: String { String(localized: "sidebar.groupEditor.ungroup", defaultValue: "Ungroup", bundle: .module) } + static var delete: String { String(localized: "sidebar.groupEditor.delete", defaultValue: "Delete Group", bundle: .module) } + static var moreActions: String { String(localized: "sidebar.groupEditor.moreActions", defaultValue: "More Group Actions…", bundle: .module) } + static var more: String { String(localized: "sidebar.group.more", defaultValue: "Group options", bundle: .module) } + static var collapse: String { String(localized: "sidebar.group.collapse", defaultValue: "Collapse group", bundle: .module) } + static var expand: String { String(localized: "sidebar.group.expand", defaultValue: "Expand group", bundle: .module) } + + /// A dot's spoken name: none, or its slot in the theme's palette (the + /// color itself follows the theme, so no fixed color word is used). + static func colorName(_ color: GroupColor) -> String { + guard color != .grey, let slot = GroupColor.editorOrder.firstIndex(of: color) else { + return String(localized: "sidebar.groupColor.none", defaultValue: "No color", bundle: .module) + } + return String(format: String(localized: "sidebar.groupColor.slot", defaultValue: "Theme color %d", bundle: .module), slot) + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/GroupHeaderRowView.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/GroupHeaderRowView.swift index 3f068db21c76..8b3218a4c7eb 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/GroupHeaderRowView.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/GroupHeaderRowView.swift @@ -3,58 +3,67 @@ import CmuxNextDesign import CmuxNextIcons import QuartzCore -/// Group header, option B "Color label and band" (Lawrence 2026-10-07; spec -/// WORKSPACE-GROUPS-OPTION-A amendment 1): the disclosure caret leads at the -/// leading inset (S1, Dia-style hover fill on the whole row), then the name -/// in a colored label, the tab-group chip (GroupColor.fill; a neutral chip -/// without a color). The member count shows at rest and gives its slot to -/// the + / pencil buttons on hover. A group icon (emoji or SF Symbol) leads -/// inside the label. A collapsed group also surfaces its -/// children's activity and unread total. +/// Group header as the Chrome tab group header bar (cx-rcby, Lawrence +/// 2026-10-08: "make sure for groups we pixel match this", "but with our +/// smaller height"): one full-width rounded bar filled with the group's +/// color (light gray for none) with the name in dark regular type, a more +/// (⋮) button on hover and the collapse chevron at the right edge. Radius, +/// padding, type and glyphs scale with the row height (the sidebar density +/// setting). No member count: a collapsed group shows its members' activity +/// and unread total in the bar. The name, the more button and a right-click +/// open the group editor; the chevron and the rest of the bar collapse. final class GroupHeaderRowView: SidebarRowView { - private let dot = CAShapeLayer() private let name = SidebarRowView.label(font: SidebarStyle.headerFont) - private let count = SidebarRowView.label(font: SidebarStyle.subtitleFont) private let chevron = NSImageView() private let activity = StatusIndicatorView() private let badge = UnreadBadgeView() private let pin = NSImageView() - /// The group's icon inside its label, before the name (`workspace-group-icon-v1`). + /// The group's icon inside its chip, before the name (`workspace-group-icon-v1`). let glyph = SidebarIconView() private let pill = CALayer() - let addButton = SidebarIconButton(symbol: "plus", pointSize: { Metrics.smallIconSize - Metrics.space1 }, weight: .semibold, label: Strings.newWorkspace) - let editButton = SidebarIconButton(symbol: "pencil", pointSize: { Metrics.smallIconSize - Metrics.space1 }, weight: .semibold, label: Strings.rename) + /// The members' bar starts under the chip (the members' rows continue it). + private let connector = CALayer() + /// The more button (⋮): the group editor. Shows on hover and while the editor is open. + let moreButton = SidebarIconButton(symbol: "ellipsis", pointSize: { Metrics.smallIconSize - Metrics.space1 }, weight: .bold, + label: GroupEditorStrings.more) private var pinned = false private var hasIcon = false private var color: GroupColor = .grey private var collapsed = false + private var hasMembers = false private var chevronFrame: CGRect = .zero var isDropTarget = false { didSet { if isDropTarget != oldValue { needsDisplay = true } } } /// Arrow keys stopped here (`SidebarListView+GroupKeys`): a focus ring, not a selection. var isKeyboardFocused = false { didSet { if isKeyboardFocused != oldValue { needsDisplay = true } } } - var onAdd: (() -> Void)? - var onEdit: (() -> Void)? + /// The group editor is open for this group: the chip stays in its hover look. + var isEditing = false { didSet { if isEditing != oldValue { needsLayout = true; needsDisplay = true } } } + var onMore: (() -> Void)? - override var interactiveSubviews: [NSView] { [addButton, editButton] } + override var interactiveSubviews: [NSView] { [moreButton] } required init(key: SidebarRowKey) { super.init(key: key) + layer?.addSublayer(connector) layer?.addSublayer(pill) - layer?.addSublayer(dot) - count.alignment = .right + for sublayer in [pill, connector] { sublayer.actions = ["bounds": NSNull(), "position": NSNull(), "backgroundColor": NSNull()] } glyph.drawsUncoloredSymbolAsText = true - [glyph, name, pin, count, chevron, activity, badge, addButton, editButton].forEach(addSubview) - addButton.onPress = { [weak self] in self?.onAdd?() } - editButton.onPress = { [weak self] in self?.onEdit?() } + // The more glyph stands upright (⋮), like the Chrome chip's. + moreButton.image = Self.verticalEllipsis() + [glyph, name, pin, chevron, activity, badge, moreButton].forEach(addSubview) + moreButton.onPress = { [weak self] in self?.onMore?() } + setAccessibilityCustomActions([NSAccessibilityCustomAction(name: GroupEditorStrings.editor) { [weak self] in + self?.onMore?() + return self?.onMore != nil + }]) } override func prepareForReuse(key: SidebarRowKey) { super.prepareForReuse(key: key) isDropTarget = false isKeyboardFocused = false + isEditing = false collapsed = false - onAdd = nil - onEdit = nil + onMore = nil } private struct Content: Hashable { @@ -62,101 +71,106 @@ final class GroupHeaderRowView: SidebarRowView { var childCount: Int var collapsed: Bool var fontSize: CGFloat - var dotSize: CGFloat } func configure(_ group: SidebarGroup, row: SidebarRow, animated: Bool) { - let content = Content( - group: group, childCount: row.childCount, collapsed: row.isCollapsed, - fontSize: SidebarStyle.headerFont.pointSize, dotSize: SidebarStyle.dotSize - ) + let content = Content(group: group, childCount: row.childCount, collapsed: row.isCollapsed, fontSize: SidebarStyle.headerFont.pointSize) guard needsConfigure(content) else { return } color = group.color name.stringValue = group.name - name.font = SidebarStyle.headerFont - count.font = SidebarStyle.subtitleFont - count.stringValue = "\(row.childCount)" pinned = group.isPinned hasIcon = group.icon != nil glyph.configure(icon: group.icon) pin.image = pinned ? NSImage.icon(.statePinned, size: Metrics.smallIconSize) : nil collapsed = row.isCollapsed - chevron.image = SidebarStyle.chevron(collapsed: collapsed) + hasMembers = row.childCount > 0 + chevron.image = Self.chevronImage(collapsed: collapsed) + moreButton.image = Self.verticalEllipsis() activity.configure(collapsed ? group.aggregateActivity : .idle) let unread = group.unreadTotal badge.configure(collapsed && unread > 0 ? .count(unread) : .none) setAccessibilityElement(true) setAccessibilityRole(.disclosureTriangle) setAccessibilityLabel("\(group.name), \(Strings.groupCount(row.childCount))") + setAccessibilityHelp(collapsed ? GroupEditorStrings.expand : GroupEditorStrings.collapse) setAccessibilityExpanded(!collapsed) needsLayout = true needsDisplay = true } + /// Three dots stacked, the Chrome chip's more glyph, as a template image. + private static func verticalEllipsis() -> NSImage { + let side = Metrics.smallIconSize, dot = max(2, side / 6) + let image = NSImage(size: NSSize(width: side, height: side), flipped: false) { rect in + for i in 0..<3 { + let y = rect.midY + CGFloat(i - 1) * dot * 2.2 - dot / 2 + NSBezierPath(ovalIn: NSRect(x: rect.midX - dot / 2, y: y, width: dot, height: dot)).fill() + } + return true + } + image.isTemplate = true + return image + } + + private static func chevronImage(collapsed: Bool) -> NSImage? { + let config = NSImage.SymbolConfiguration(pointSize: Metrics.smallIconSize - Metrics.space2, weight: .bold) + return NSImage(systemSymbolName: collapsed ? "chevron.down" : "chevron.up", accessibilityDescription: nil)? + .withSymbolConfiguration(config) + } + override var titleFrame: NSRect { name.frame } - /// The name's colored label (`GroupLabelBandTests`). + /// The group chip (`GroupLabelBandTests`): a click here opens the editor. var labelFrame: NSRect { pill.frame } /// The width the name needs to draw whole (`GroupLabelBandTests`). var titleIntrinsicWidth: CGFloat { - // The label's own measure plus the cell's text inset on both sides, - // measured with the header font it draws in (the live capture cut - // "Frontend" to "Fronte…" at the bare measured width). let font = name.font ?? SidebarStyle.headerFont let text = ceil((name.stringValue as NSString).size(withAttributes: [.font: font]).width) return max(ceil(name.intrinsicContentSize.width), text + 2 * Metrics.space2) } + /// The group's name and icon: a click here opens the editor; the rest + /// of the bar and the chevron collapse (the Chrome header toggles). + var nameHitFrame: NSRect { + let start = hasIcon ? glyph.frame.minX : name.frame.minX + return NSRect(x: start - Metrics.space2, y: 0, width: name.frame.maxX - start + 2 * Metrics.space2, height: bounds.height) + } var labelFill: CGColor? { pill.isHidden ? nil : pill.backgroundColor } - override var titleFont: NSFont { SidebarStyle.headerFont } + override var titleFont: NSFont { name.font ?? SidebarStyle.headerFont } private var renaming = false override func setTitleHidden(_ hidden: Bool) { renaming = hidden name.isHidden = hidden } + /// Whether the more button shows: on hover, and while the editor is open. + private var showsMore: Bool { isHovered || isEditing } + override func updateLayer() { performWithTheme { - name.textColor = Palette.textPrimary - count.textColor = Palette.textTertiary - pin.contentTintColor = Palette.textTertiary - chevron.contentTintColor = isHovered ? Palette.textSecondary : Palette.textTertiary - let tint = SidebarStyle.color(color) - // The label: the tab-group chip fill, a neutral chip without a - // color; hover darkens it like a tab-group chip. - var fill = color == .grey ? Palette.badgeFill : color.fill - if isHovered { fill = fill.blended(withFraction: 0.08, of: Palette.textPrimary) ?? fill } - if isDropTarget { fill = fill.blended(withFraction: 0.16, of: Palette.textPrimary) ?? fill } + // Dark text and glyphs on the light or colored bar (the Chrome tab group header). + let ink = GroupColor.headerInk + name.textColor = ink + pin.contentTintColor = ink.withAlphaComponent(0.7) + chevron.contentTintColor = ink + moreButton.contentTintColor = ink + var fill = color.headerFill + if isHovered || isEditing { fill = fill.blended(withFraction: 0.08, of: .black) ?? fill } + if isDropTarget { fill = fill.blended(withFraction: 0.16, of: .black) ?? fill } pill.backgroundColor = fill.cgColor - // Fills only: a drop onto the group tints the row in its color; a - // selected group (or the collapsed group that holds the selected - // workspace) paints the selection fill. - if isDropTarget { - paintFill(color == .grey ? Palette.selectionFill : tint.withAlphaComponent(0.16)) - pill.borderColor = (color == .grey ? Palette.focusRing : tint).cgColor - pill.borderWidth = Metrics.dividerThickness * 1.5 - } else if isSelected { - pill.borderWidth = 0 - paintFill(Palette.selectionFill) - } else { - pill.borderWidth = 0 - paintFill(isHovered ? Palette.hoverFill : nil) - } + pill.borderWidth = isDropTarget ? Metrics.dividerThickness * 1.5 : 0 + pill.borderColor = ink.withAlphaComponent(0.5).cgColor + // A collapsed group that holds the selected workspace paints the selection fill around its bar. + paintFill(isSelected ? Palette.selectionFill : nil) CATransaction.begin() CATransaction.setDisableActions(true) layer?.borderColor = Palette.focusRing.cgColor layer?.borderWidth = isKeyboardFocused ? Metrics.dividerThickness * 1.5 : 0 layer?.cornerRadius = SidebarStyle.rowCornerRadius - // The label carries the color; the dot layer stays for reuse. - dot.isHidden = true - dot.fillColor = collapsed ? nil : tint.cgColor - dot.strokeColor = tint.cgColor - dot.lineWidth = collapsed ? Metrics.dividerThickness * 1.5 : 0 CATransaction.commit() } } - /// The disclosure caret and the inset before it: a click here toggles - /// immediately (a click on the name waits for a double click). - var disclosureFrame: NSRect { NSRect(x: 0, y: 0, width: chevronFrame.maxX + Metrics.space1 / 2, height: bounds.height) } + /// The chevron and the space around it: a click here collapses or expands. + var disclosureFrame: NSRect { chevronFrame.insetBy(dx: -Metrics.space1, dy: -Metrics.space2) } override func layout() { super.layout() @@ -164,27 +178,28 @@ final class GroupHeaderRowView: SidebarRowView { CATransaction.begin() CATransaction.setDisableActions(true) defer { CATransaction.commit() } - let inset = Metrics.dividerThickness - let chevronSide = Metrics.smallIconSize + // One full-width rounded bar (the Chrome tab group header) whose + // radius, padding, type and glyphs scale with the row height + // (the sidebar density: compact 24, comfortable 32 pt). + let barHeight = SidebarStyle.groupHeaderBarHeight(rowHeight: b.height) + let pad = (barHeight * 0.62).rounded() name.isHidden = renaming - - var trailing = b.width - Metrics.space3 - let control = SidebarStyle.controlSize - // Hover controls keep their slots, so the name never re-truncates on hover. - addButton.isHidden = !isHovered - editButton.isHidden = !isHovered - editButton.frame = NSRect(x: trailing - control, y: (b.height - control) / 2, width: control, height: control) - trailing -= control + Metrics.space1 - addButton.frame = NSRect(x: trailing - control, y: (b.height - control) / 2, width: control, height: control) - trailing -= control + Metrics.space2 - chevronFrame = CGRect(x: SidebarStyle.titleLeading, y: (b.height - chevronSide) / 2, width: chevronSide, height: chevronSide) + name.font = SidebarStyle.groupHeaderFont(barHeight: barHeight) + let chevronSide = max(Metrics.smallIconSize - Metrics.space1, (barHeight * 0.46).rounded()) + chevronFrame = CGRect(x: b.width - pad * 0.75 - chevronSide, y: (b.height - chevronSide) / 2, width: chevronSide, height: chevronSide) chevron.frame = chevronFrame - chevron.isHidden = false + let control = barHeight - Metrics.space1 + // The more button fades in left of the chevron on hover; its slot is kept. + moreButton.frame = NSRect(x: max(pad, chevronFrame.minX - Metrics.space1 - control), y: (b.height - control) / 2, width: control, height: control) + moreButton.isHidden = false + moreButton.alphaValue = showsMore ? 1 : 0 + // Shown to VoiceOver only when it shows; the header's custom action edits the group always. + moreButton.setAccessibilityElement(showsMore) + var trailing = moreButton.frame.minX - Metrics.space2 if badge.state.isUnread { badge.isHidden = false - let w = badge.preferredWidth - let h = SidebarStyle.badgeHeight + let w = badge.preferredWidth, h = SidebarStyle.badgeHeight badge.frame = NSRect(x: trailing - w, y: (b.height - h) / 2, width: w, height: h) trailing = badge.frame.minX - Metrics.space2 } else { @@ -195,41 +210,21 @@ final class GroupHeaderRowView: SidebarRowView { activity.frame = NSRect(x: trailing - ind, y: (b.height - ind) / 2, width: ind, height: ind) trailing -= ind + Metrics.space2 } - let cw = ceil(count.attributedStringValue.size().width) + Metrics.space2 - let ch = ceil(count.intrinsicContentSize.height) - count.isHidden = isHovered || badge.state.isUnread - if !badge.state.isUnread { - count.frame = NSRect(x: trailing - cw, y: (b.height - ch) / 2, width: cw, height: ch) - trailing -= cw + Metrics.space2 - } - // Caret, then the name inside its label (FlatSidebarTests, GroupLabelBandTests). - let pad = Metrics.space3 - let chipX = chevronFrame.maxX + Metrics.space1 - let chipHeight = min(b.height, max(Metrics.space6, b.height - 2 * Metrics.space3)) - // The icon leads inside the label at the workspace-row icon size (the - // label's height at most); without one the name does. - let glyphSide = min(SidebarStyle.iconBox, chipHeight) - let glyphRoom = hasIcon ? glyphSide + Metrics.space1 : 0 + let glyphSide = min(SidebarStyle.iconBox, barHeight) glyph.isHidden = !hasIcon - glyph.frame = NSRect(x: chipX + pad - Metrics.space1, y: (b.height - glyphSide) / 2, width: glyphSide, height: glyphSide) - let nx = chipX + pad + glyphRoom - (hasIcon ? Metrics.space1 : 0) - let nh = ceil(name.intrinsicContentSize.height) - let dotSide = SidebarStyle.dotSize - let dotRoom: CGFloat = 0 + glyph.frame = NSRect(x: pad - Metrics.space1, y: (b.height - glyphSide) / 2, width: glyphSide, height: glyphSide) + let nx = pad + (hasIcon ? glyphSide : 0) let pinSide = Metrics.smallIconSize let pinRoom = pinned ? pinSide + Metrics.space2 : 0 - let nameWidth = min(titleIntrinsicWidth, max(0, trailing - nx - pad - pinRoom)) + let nameWidth = min(titleIntrinsicWidth, max(0, trailing - pinRoom - nx)) + let nh = ceil(name.intrinsicContentSize.height) name.frame = NSRect(x: nx, y: (b.height - nh) / 2, width: nameWidth, height: nh) - pill.isHidden = renaming - pill.frame = NSRect(x: chipX, y: (b.height - chipHeight) / 2, width: nx - chipX + nameWidth + pad, height: chipHeight) - pill.cornerRadius = max(0, SidebarStyle.rowCornerRadius - Metrics.space1) - var x = pill.frame.maxX + Metrics.space2 - let dotFrame = CGRect(x: x, y: (b.height - dotSide) / 2, width: dotSide, height: dotSide) - dot.frame = dotFrame - dot.path = CGPath(ellipseIn: CGRect(origin: .zero, size: dotFrame.size).insetBy(dx: inset, dy: inset), transform: nil) - x += dotRoom pin.isHidden = !pinned - pin.frame = NSRect(x: x, y: (b.height - pinSide) / 2, width: pinSide, height: pinSide) + pin.frame = NSRect(x: name.frame.maxX + Metrics.space2, y: (b.height - pinSide) / 2, width: pinSide, height: pinSide) + pill.isHidden = renaming + pill.frame = NSRect(x: 0, y: (b.height - barHeight) / 2, width: b.width, height: barHeight) + pill.cornerRadius = (barHeight * 0.23).rounded() + connector.isHidden = true needsDisplay = true } @@ -237,4 +232,16 @@ final class GroupHeaderRowView: SidebarRowView { super.hoverChanged() needsLayout = true } + + /// A new group's chip arrives once: it fades and scales up from the + /// chip's leading edge (Reduce Motion: no scale, the row's fade only). + func playAppear() { + guard Motion.animatesMovement else { return } + let scale = CABasicAnimation(keyPath: "transform.scale") + scale.fromValue = 0.86 + scale.toValue = 1 + scale.duration = Motion.duration(MotionSpring.appear) + scale.timingFunction = CAMediaTimingFunction(name: .easeOut) + pill.add(scale, forKey: "cmux.groupAppear") + } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarBottomCardSlot.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarBottomCardSlot.swift index 9b7639e99c88..b9eb9262d681 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarBottomCardSlot.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarBottomCardSlot.swift @@ -1,58 +1,76 @@ import AppKit import CmuxNextDesign -/// UPDATE-CARD + BOTTOM-LEFT-CARDS K1: one card slot directly above the -/// footer (the spaces dots and the account row below it), under the R114 -/// card stack: the staged update card first, else the "Did you know" tip -/// card, never both. They are the sidebar's own views, not band items, so -/// minimal mode's band fade never hides them. Without a card the slot takes -/// no room; the footer controls never move (Lawrence: controls fixed, the -/// card space above them may appear and disappear). +/// UPDATE-CARD + BOTTOM-LEFT-CARDS K1 + cx-7py7: one card slot directly +/// above the footer (the spaces dots and the account row below it), under +/// the R114 card stack: the staged update card first, else the "cmux +/// Updated!" card, else the "Did you know" tip card, never two. They are +/// the sidebar's own views, not band items, so minimal mode's band fade +/// never hides them. Without a card the slot takes no room; the footer +/// controls never move (Lawrence: controls fixed, the card space above them +/// may appear and disappear). struct SidebarBottomCardSlot { let update: SidebarUpdateCardView + let updated: SidebarUpdatedCardView let tip: SidebarTipCardView - /// Adds both views to `sidebar` and routes their actions to its model. + /// Adds the views to `sidebar` and routes their actions to its model. func install(in sidebar: SidebarView) { update.onInstall = { [weak sidebar] in sidebar?.model.send(.installUpdate) } update.onAutomaticUpdates = { [weak sidebar] on in sidebar?.model.send(.setAutomaticUpdates(on)) } update.onOpenLink = { [weak sidebar] url in sidebar?.model.send(.openUpdateLink(url)) } + updated.whatsNewRow.onPress = { [weak sidebar] in sidebar?.model.send(.openWhatsNew) } + updated.shareRow.onPress = { [weak sidebar] in sidebar?.model.send(.shareCmux) } + updated.closeButton.onPress = { [weak sidebar] in sidebar?.model.send(.dismissUpdated) } tip.onTry = { [weak sidebar] id in sidebar?.model.send(.tryTip(id)) } tip.onDismiss = { [weak sidebar] id in sidebar?.model.send(.dismissTip(id)) } sidebar.addSubview(update) + sidebar.addSubview(updated) sidebar.addSubview(tip) } /// Shows the cards the model holds (the slot picks one). func show(_ cards: SidebarBottomCards) { update.configure(cards.update) + updated.configure(cards.updated) tip.configure(cards.tip) } - /// The tip card shows only while no update card does. - var showsTip: Bool { update.card == nil && tip.tip != nil } + private enum Shown { case update, updated, tip } + + /// The card that has the slot: update, then updated, then tip. + private var shown: Shown? { + if update.card != nil { return .update } + if updated.card != nil { return .updated } + return tip.tip != nil ? .tip : nil + } + + /// The tip card shows only while no other card does. + var showsTip: Bool { shown == .tip } /// The room the slot takes above the footer: its card and a gap above /// and below it; 0 without a card. var height: CGFloat { - if update.card != nil { return SidebarUpdateCardView.height + 2 * Metrics.space2 } - return showsTip ? SidebarTipCardView.height + 2 * Metrics.space2 : 0 + switch shown { + case .update: SidebarUpdateCardView.height + 2 * Metrics.space2 + case .updated: SidebarUpdatedCardView.height + 2 * Metrics.space2 + case .tip: SidebarTipCardView.height + 2 * Metrics.space2 + case nil: 0 + } } /// Lays the card out in the slot, which ends at `bottom`, inset like the /// card stack's cards across a sidebar `width` wide. func place(above bottom: CGFloat, width sidebarWidth: CGFloat, slotHeight: CGFloat) { let inset = Metrics.space3, width = max(0, sidebarWidth - 2 * inset) - let showsUpdate = slotHeight > 0 && update.card != nil - let showsTipCard = slotHeight > 0 && !showsUpdate && showsTip - tip.isHidden = !showsTipCard - update.frame = showsUpdate - ? NSRect(x: inset, y: bottom - Metrics.space2 - SidebarUpdateCardView.height, width: width, - height: SidebarUpdateCardView.height).integral - : .zero - tip.frame = showsTipCard - ? NSRect(x: inset, y: bottom - Metrics.space2 - SidebarTipCardView.height, width: width, - height: SidebarTipCardView.height).integral - : .zero + let shown = slotHeight > 0 ? shown : nil + func frame(_ which: Shown, height: CGFloat) -> NSRect { + shown == which ? NSRect(x: inset, y: bottom - Metrics.space2 - height, width: width, height: height).integral : .zero + } + tip.isHidden = shown != .tip + updated.isHidden = shown != .updated + update.frame = frame(.update, height: SidebarUpdateCardView.height) + updated.frame = frame(.updated, height: SidebarUpdatedCardView.height) + tip.frame = frame(.tip, height: SidebarTipCardView.height) } } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarContainerView+GroupEditor.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarContainerView+GroupEditor.swift new file mode 100644 index 000000000000..c31b79a1c0a8 --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarContainerView+GroupEditor.swift @@ -0,0 +1,29 @@ +import AppKit + +// The group editor's App side (cx-rcby): its action rows and what runs them. +extension SidebarContainerView { + /// The group whose editor is open, if any. + public var editingGroup: GroupID? { sidebarView.list.groupEditor.shownGroup } + + /// The group editor's action rows for a group; nil shows + /// `standardGroupEditorItems()`. A row's id is an action id. + public var groupEditorItems: ((GroupID) -> [[SidebarGroupEditorItem]])? { + get { sidebarView.list.groupEditorItems } + set { sidebarView.list.groupEditorItems = newValue } + } + + /// A group editor row was chosen: the App runs the action on the group. + public var onGroupEditorItem: ((GroupID, String) -> Void)? { + get { sidebarView.list.onGroupEditorItem } + set { sidebarView.list.onGroupEditorItem = newValue } + } + + /// The editor's standard rows: New Workspace in Group, Move Group to New + /// Window, Close Group; Ungroup, Delete Group, More Group Actions. + /// The editor row that shows the group's full menu (the sidebar shows it). + public static var moreActionsItem: String { SidebarGroupEditing.moreActionsItem } + + public static func standardGroupEditorItems() -> [[SidebarGroupEditorItem]] { + SidebarGroupEditing.standardItems() + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarContainerView.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarContainerView.swift index 35a20444c269..26154818c998 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarContainerView.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarContainerView.swift @@ -132,12 +132,6 @@ public final class SidebarContainerView: NSView { sidebarView.beginRename(workspace: id) } - /// The group whose name is being edited, if any (cx-rcby). - public var editingGroup: GroupID? { - if case let .group(id)? = sidebarView.list.inlineRename.session?.key { return id } - return nil - } - /// Starts inline rename of a group, showing the sidebar first when it /// is hidden. public func beginRename(group id: GroupID) { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarGroupKeys.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarGroupKeys.swift index cd2ebb47d49a..cf22c511b0de 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarGroupKeys.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarGroupKeys.swift @@ -60,7 +60,7 @@ import AppKit return true case .carriageReturn?, .enter?: guard let group = list.focusedGroup else { return false } - list.inlineRename.begin(.group(group)) + list.groupEditing.open(group) return true default: return false diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarInlineRename.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarInlineRename.swift index 30c1fc0dcc1a..9da3da858a2d 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarInlineRename.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarInlineRename.swift @@ -27,9 +27,7 @@ final class SidebarInlineRename: NSObject, NSTextFieldDelegate { /// Renames the group `member` belongs to (drag to group). func beginGroup(of member: WorkspaceID) { - guard let group = group(containing: member) else { return } - begin(.group(group)) - if session != nil { groupMember = member } + list.map { SidebarGroupEditing(list: $0).open(containing: member) } } /// After a reload: moves a rename whose group the store replaced to @@ -52,6 +50,8 @@ final class SidebarInlineRename: NSObject, NSTextFieldDelegate { func begin(_ key: SidebarRowKey) { guard let list, list.model.presentation == .shown, list.drag == nil else { return } + // A group's name is edited in the group editor (cx-rcby). + if case let .group(id) = key { return list.groupEditing.open(id) } if session != nil { end(commit: true) } let original: String switch key { @@ -110,7 +110,6 @@ final class SidebarInlineRename: NSObject, NSTextFieldDelegate { } list.reload(animated: false) } - if case let .group(id) = session.key { list?.model.send(.groupEditorEnded(id)) } list?.window?.makeFirstResponder(list) onEnded?(byKeyboard) } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+ContextMenu.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+ContextMenu.swift index 8ddd12e6c8fa..5d5fb54fba94 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+ContextMenu.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+ContextMenu.swift @@ -3,8 +3,14 @@ import AppKit // action registry. extension SidebarListView { override func menu(for event: NSEvent) -> NSMenu? { - guard let contextMenuProvider else { return nil } let point = convert(event.locationInWindow, from: nil) + if case let .group(id)? = displayed.row(at: point.y)?.key { + // A right-click on a group opens its editor (cx-rcby); the + // editor's last row shows the group's full menu. + groupEditing.open(id) + return nil + } + guard let contextMenuProvider else { return nil } let target: SidebarContextTarget switch displayed.row(at: point.y)?.key { case let .workspace(id)?: @@ -13,8 +19,8 @@ extension SidebarListView { reload(animated: true) } target = .workspaces(model.orderedSelection.isEmpty ? [id] : model.orderedSelection) - case let .group(id)?: - target = .group(id) + case .group?: + return nil case let .section(id)?, let .emptySection(id)?: target = .section(id) case let .tab(workspace, _)?: diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+GroupEditor.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+GroupEditor.swift new file mode 100644 index 000000000000..e022b20456bf --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+GroupEditor.swift @@ -0,0 +1,122 @@ +import AppKit +import CmuxNextDesign + +// The group editor (cx-rcby): the chip, its more button, a right-click on +// the header, Return on a focused header, the Rename action and a new group +// all open the one editor bubble under the chip. Name and color edits go out +// as intents; an action row goes to the App (the action registry). +@MainActor +struct SidebarGroupEditing { + let list: SidebarListView + + /// The id of the editor's trailing row that shows the group's full menu. + static let moreActionsItem = "sidebar.group.moreActions" + + /// The editor's rows when the App gives none: the shared group actions. + static func standardItems() -> [[SidebarGroupEditorItem]] { + [ + [ + SidebarGroupEditorItem(id: "workspaceGroup.newWorkspace", title: GroupEditorStrings.newWorkspace, symbol: "plus.square.on.square"), + SidebarGroupEditorItem(id: "workspaceGroup.moveToNewWindow", title: GroupEditorStrings.moveToNewWindow, symbol: "macwindow.badge.plus"), + SidebarGroupEditorItem(id: "workspaceGroup.closeWorkspaces", title: GroupEditorStrings.close, symbol: "xmark.square"), + ], + [ + SidebarGroupEditorItem(id: "workspaceGroup.ungroup", title: GroupEditorStrings.ungroup, symbol: "square.stack.3d.up.slash"), + SidebarGroupEditorItem(id: "workspaceGroup.delete", title: GroupEditorStrings.delete, symbol: "trash"), + SidebarGroupEditorItem(id: moreActionsItem, title: GroupEditorStrings.moreActions, symbol: "ellipsis.circle"), + ], + ] + } + + /// Wires the editor to the model (once, from `init`). + func wire() { + let editor = list.groupEditor + editor.onRename = { [weak list] id, name in list?.model.send(.renameGroup(id, name)) } + editor.onColor = { [weak list] id, color in + list?.model.send(.setGroupColor(id, color)) + list?.reload(animated: true) + } + editor.onItem = { [weak list] id, item in + guard let list else { return } + // The App hears every row, More too (a menu action may add a member). + list.onGroupEditorItem?(id, item) + if item == Self.moreActionsItem { SidebarGroupEditing(list: list).showMenu(id) } + } + // The bubble is its own window: the keys stay where the click put them. + editor.onClose = { [weak list] id in + guard let list else { return } + for case let header as GroupHeaderRowView in list.rowViews.values { header.isEditing = false } + list.model.send(.groupEditorEnded(id)) + list.reload(animated: true) + } + } + + /// Opens the editor under the group's chip. A hidden sidebar, a drag or + /// a group not shown opens nothing. + func open(_ id: GroupID) { + guard list.groups[id] != nil, let window = list.window, list.model.presentation == .shown, list.drag == nil else { return } + // A click whose mouse-down closed this group's editor toggles it closed. + if list.groupEditor.closedByThisClick(id, at: NSApp.currentEvent?.timestamp) { return } + if let row = list.displayed.row(for: .group(id)) { list.scrollToVisible(list.frame(for: row)) } + list.realizeVisibleRows() + guard let group = list.groups[id], let view = list.rowViews[.group(id)] as? GroupHeaderRowView else { return } + view.layoutSubtreeIfNeeded() + // The row's settled frame: a group made a moment ago may still be moving in. + let rowFrame = list.displayed.row(for: .group(id)).map(list.frame(for:)) ?? view.frame + let chip = view.labelFrame.offsetBy(dx: rowFrame.minX, dy: rowFrame.minY) + let anchor = window.convertToScreen(list.convert(chip, to: nil)) + list.hoverCards.dismiss(.click) + list.groupEditor.show(group, items: list.groupEditorItems?(id) ?? Self.standardItems(), anchor: anchor, parent: window, + themeAnchor: list) + view.isEditing = true + } + + /// Opens the editor for the group `member` is in (a group a drop just made). + func open(containing member: WorkspaceID) { + guard let group = list.groups.values.first(where: { $0.workspaces.contains { $0.id == member } }) else { return } + open(group.id) + } + + /// The group's full menu (every group action), under its chip. + private func showMenu(_ id: GroupID) { + guard let menu = list.contextMenuProvider?(.group(id)), let view = list.rowViews[.group(id)] as? GroupHeaderRowView else { return } + _ = menu.popUp(positioning: nil, at: NSPoint(x: view.labelFrame.minX, y: view.labelFrame.maxY + Metrics.space1), in: view) + } + + /// Keeps the open editor with its chip: a chip scrolled out of view closes it. + func followScroll() { + guard let shown = list.groupEditor.shownGroup else { return } + let visible = list.enclosingScrollView?.contentView.bounds ?? list.bounds + guard let row = list.displayed.row(for: .group(shown)), visible.intersects(list.frame(for: row)) else { return list.groupEditor.hide() } + } + + /// Whether `point` (list coordinates) is on the group's name, off its chevron. + func isOnChip(_ point: NSPoint, group: GroupID) -> Bool { + guard let view = list.rowViews[.group(group)] as? GroupHeaderRowView else { return false } + let local = list.convert(point, to: view) + return view.nameHitFrame.contains(local) && !view.disclosureFrame.contains(local) + } + + /// A group the store gave a new id (the home daemon names a group the + /// sidebar made) keeps its header view: the new key takes the old view, + /// so the group moves once instead of leaving and arriving again. + func adoptReidentified(from old: SidebarLayout, to new: SidebarLayout) { + for row in new.rows { + guard case let .group(id) = row.key, old.row(for: row.key) == nil, list.rowViews[row.key] == nil, + let members = list.groups[id].map({ Set($0.workspaces.map(\.id)) }), !members.isEmpty else { continue } + let previous = old.rows.first { candidate in + guard case let .group(oldID) = candidate.key, new.row(for: candidate.key) == nil, list.rowViews[candidate.key] != nil else { return false } + return old.rows.contains { member in + guard member.group == oldID, case let .workspace(workspace) = member.key else { return false } + return members.contains(workspace) + } + } + guard let previous, let view = list.rowViews.removeValue(forKey: previous.key) else { continue } + if case let .group(oldID) = previous.key, list.focusedGroup == oldID { list.focusedGroup = id } + view.key = row.key + view.configuredContent = nil + list.rowViews[row.key] = view + list.wire(view, key: row.key) + } + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Mouse.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Mouse.swift index fc528d7ac708..086057866a9c 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Mouse.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Mouse.swift @@ -9,6 +9,8 @@ extension SidebarListView { override func mouseDown(with event: NSEvent) { hoverCards.dismiss(.click) if inlineRename.isActive { inlineRename.end(commit: true) } + // A click in the list closes the group editor, like a click outside it. + if groupEditor.isVisible { groupEditor.hide() } window?.makeFirstResponder(self) let point = convert(event.locationInWindow, from: nil) guard let row = displayed.row(at: point.y) else { @@ -92,9 +94,11 @@ extension SidebarListView { // An empty saved group reopens; any other group toggles. if let g = model.group(group), g.isPinned, g.workspaces.isEmpty { model.send(.openGroup(group)) + } else if groupEditing.isOnChip(point, group: group) { + // The chip opens the group editor (cx-rcby); its chevron and + // the rest of the row toggle at once. + return groupEditing.open(group) } else { - // A click anywhere on the header toggles at once; rename is - // Return on the focused header or the menu. model.send(.toggleCollapse(.group(group))) } case let .section(section): diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Reuse.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Reuse.swift index 7223baabad55..1d0f0c4f863c 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Reuse.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView+Reuse.swift @@ -13,7 +13,7 @@ extension SidebarListView { } /// Per-key callbacks, set on every dequeue so recycled views never keep /// a previous row's target. - private func wire(_ view: SidebarRowView, key: SidebarRowKey) { + func wire(_ view: SidebarRowView, key: SidebarRowKey) { switch (key, view) { case let (.workspace(id), view as WorkspaceRowView): view.onClose = { [weak self] in self?.model.send(.close([id])) } @@ -24,12 +24,8 @@ extension SidebarListView { self?.model.send(.selectTab(workspace: workspaceID, tab: tabID)) } case let (.group(id), view as GroupHeaderRowView): - guard let row = displayed.row(for: .group(id)) else { return } - view.onAdd = { [weak self] in - guard let self, case let .machine(machine) = self.sections[row.section]?.kind else { return } - self.model.send(.newWorkspace(machine: machine.id, group: id)) - } - view.onEdit = { [weak self] in self?.inlineRename.begin(.group(id)) } + view.onMore = { [weak self] in self?.groupEditing.open(id) } + view.isEditing = groupEditor.shownGroup == id case let (.section(sectionID), view as SectionHeaderRowView): if case let .machine(machine) = sectionID { view.allowsAdd = true diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView.swift index bfea15c08543..75816860e4ff 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarListView.swift @@ -34,8 +34,13 @@ final class SidebarListView: NSView { var suppressed: Set = [] /// Workspaces a pin drop took to the band: out of the list until its card lands (cx-odqn). var leaving: Set = [] - /// Inline rename of a workspace or group row. + /// Inline rename of a workspace row (a group's name is edited in `groupEditor`). let inlineRename = SidebarInlineRename() + /// The group editor bubble (SidebarListView+GroupEditor) and its App-filled rows. + let groupEditor = SidebarGroupEditor() + var groupEditorItems: ((GroupID) -> [[SidebarGroupEditorItem]])? + var onGroupEditorItem: ((GroupID, String) -> Void)? + var groupEditing: SidebarGroupEditing { SidebarGroupEditing(list: self) } /// Drag autoscroll frames from the window's FrameScheduler. lazy var autoscroll = SidebarDragAutoscroll(list: self) var external: ExternalDrag? @@ -69,6 +74,7 @@ final class SidebarListView: NSView { setAccessibilityLabel(Strings.sidebarLabel) hoverCard.list = self inlineRename.list = self + groupEditing.wire() } @available(*, unavailable) required init?(coder: NSCoder) { fatalError() } @@ -130,6 +136,8 @@ final class SidebarListView: NSView { if let shown = hoverCard.shownID { hoverCards.contentChanged(WorkspaceHoverCardController.targetID(shown)) } applyKeepingViewport(displayLayout(), animated: animated) inlineRename.follow() + groupEditor.follow(groups) + if let shown = groupEditor.shownGroup { (rowViews[.group(shown)] as? GroupHeaderRowView)?.isEditing = true } } func options(includeGap: Bool) -> SidebarLayoutOptions { var o = model.listOptions() @@ -167,6 +175,7 @@ final class SidebarListView: NSView { defer { updateHover() } let old = displayed displayed = layout + groupEditing.adoptReidentified(from: old, to: layout) selectedRowKey = layout.selectedRowKey(for: model.selectedItem, in: model.sections) updateDocumentHeight() let realize = realizationRect() @@ -201,6 +210,7 @@ final class SidebarListView: NSView { view.alphaValue = 0 } else if animate, existing == nil, old.row(for: row.key) == nil { appearing.append((view, target)) + (view as? GroupHeaderRowView)?.playAppear() } else { targets.append((view, target)) } @@ -316,6 +326,7 @@ final class SidebarListView: NSView { /// Adds views for rows scrolled into range and drops far-away ones. func realizeVisibleRows() { guard !isShiftingViewport else { return } + groupEditing.followScroll() let realize = realizationRect() for row in displayed.rows where rowViews[row.key] == nil { let target = frame(for: row) @@ -335,7 +346,7 @@ final class SidebarListView: NSView { let keepRect = realizationRect().insetBy(dx: 0, dy: -SidebarStyle.overscan) for row in displayed.rows { guard let view = rowViews[row.key], !frame(for: row).intersects(keepRect), - inlineRename.session?.key != row.key else { continue } + inlineRename.session?.key != row.key, row.key != groupEditor.shownGroup.map(SidebarRowKey.group) else { continue } recycle(view) rowViews[row.key] = nil } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarStyle.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarStyle.swift index 70c6db65342d..1f41460fe673 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarStyle.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarStyle.swift @@ -55,9 +55,20 @@ enum SidebarStyle { /// default icon (WORKSPACE-ROWS-NO-DEFAULT-ICON). Group headers start /// their name here too. static var titleLeading: CGFloat { horizontalInset } - /// How far a group member's content moves in: past the header's caret - /// and its band (option B, Lawrence 2026-10-07). - static var groupMemberIndent: CGFloat { Metrics.smallIconSize + Metrics.space1 } + /// How far a group member's content moves in: half a row (16 pt at + /// the comfortable 32 pt row, the Chrome tab group sidebar). + static var groupMemberIndent: CGFloat { (Metrics.sidebarRowHeight * 0.5).rounded() } + /// Where a group header's bar starts: the row's leading edge (full width). + static var groupChipLeading: CGFloat { 0 } + /// The header bar inside its row: 26 of 32 pt, scaled with the row height. + static func groupHeaderBarHeight(rowHeight: CGFloat) -> CGFloat { rowHeight - 2 * (rowHeight * 0.09).rounded() } + /// The header's name: regular weight, 14 pt on a 26 pt bar, scaled. + static func groupHeaderFont(barHeight: CGFloat) -> NSFont { + NSFont.systemFont(ofSize: min(15, max(11, (barHeight * 0.54).rounded())), weight: .regular) + } + /// The members' bar: 3 pt at the 32 pt row, scaled; at the members' leading edge. + static var groupBarWidth: CGFloat { max(2, (Metrics.sidebarRowHeight * 0.1).rounded()) } + static var groupBarX: CGFloat { (Metrics.sidebarRowHeight * 0.12).rounded() } static var headerFont: NSFont { Typography.header } static var badgeFont: NSFont { Typography.shortcut } /// A user-chosen SF Symbol at the title's point size, where symbols match the text beside them. diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarUpdatedCardView.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarUpdatedCardView.swift new file mode 100644 index 000000000000..1fa6c74d47ba --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarUpdatedCardView.swift @@ -0,0 +1,219 @@ +import AppKit +import CmuxNextDesign + +/// The "cmux Updated!" card above the footer (cx-7py7), in the tip card's +/// slot and on its material: the title centered with an x, a hairline, then +/// two rows, "See What's New" and "Share cmux". Liquid Glass with the +/// theme's glass tint (opaque under Reduce Transparency), the lines in a +/// sibling above the material like the tip card (cx-367y). Hidden without +/// a card. +final class SidebarUpdatedCardView: NSView { + private(set) var card: SidebarUpdatedCard? + private let titleLabel = NSTextField(labelWithString: "") + private let divider = NSView() + let whatsNewRow = SidebarUpdatedCardRow(symbol: "sparkles") + let shareRow = SidebarUpdatedCardRow(symbol: "square.and.arrow.up") + let closeButton = SidebarIconButton(symbol: "xmark", pointSize: { 9 }, label: "") + /// The card's material: Liquid Glass, or opaque under Reduce Transparency. + let surface: OverlaySurfaceView + /// The lines and rows, flipped, over the surface. + private let content = SidebarUpdatedCardContent() + + init(frame: NSRect = .zero, reduceTransparency: ReduceTransparency = .shared) { + surface = OverlaySurfaceView(interactive: true, cornerRadius: Metrics.space3, reduceTransparency: reduceTransparency) + super.init(frame: frame) + surface.translatesAutoresizingMaskIntoConstraints = true + addSubview(surface) + addSubview(content) + content.material = { [weak surface] in surface?.material ?? .liquidGlass } + titleLabel.alignment = .center + titleLabel.lineBreakMode = .byTruncatingTail + titleLabel.maximumNumberOfLines = 1 + divider.wantsLayer = true + [titleLabel, divider, whatsNewRow, shareRow, closeButton].forEach(content.addSubview) + setAccessibilityElement(false) + isHidden = true + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError() } + + override var isFlipped: Bool { true } + override var mouseDownCanMoveWindow: Bool { false } + + /// Shows `card`, or hides the view for nil. + func configure(_ card: SidebarUpdatedCard?) { + guard card != self.card else { return } + self.card = card + isHidden = card == nil + guard let card else { return } + titleLabel.stringValue = card.title + whatsNewRow.text = card.whatsNewTitle + shareRow.text = card.shareTitle + closeButton.label = card.dismissLabel + needsLayout = true + applyColors() + } + + // MARK: Geometry + + private static var padding: CGFloat { Metrics.space2 } + private static var titleHeight: CGFloat { ceil(Typography.bodyEmphasized.boundingRectForFont.height) + 2 * Metrics.space2 } + static var rowHeight: CGFloat { ceil(Typography.body.boundingRectForFont.height) + 2 * Metrics.space2 } + + /// Fixed: the title band, the hairline, two rows. + static var height: CGFloat { ceil(titleHeight + 1 + Metrics.space1 + 2 * rowHeight + padding) } + + override func layout() { + super.layout() + let b = bounds, pad = Self.padding + surface.frame = b + surface.cornerRadius = Metrics.space3 + content.layer?.cornerRadius = Metrics.space3 + content.layer?.cornerCurve = .continuous + content.frame = b + titleLabel.font = Typography.bodyEmphasized + let close: CGFloat = 16, titleHeight = Self.titleHeight + closeButton.frame = NSRect(x: b.width - pad - close, y: (titleHeight - close) / 2, width: close, height: close) + let lineHeight = ceil(Typography.bodyEmphasized.boundingRectForFont.height) + titleLabel.frame = NSRect(x: pad + close, y: (titleHeight - lineHeight) / 2, width: max(0, b.width - 2 * (pad + close)), + height: lineHeight) + divider.frame = NSRect(x: 0, y: titleHeight, width: b.width, height: 1) + let rowWidth = max(0, b.width - 2 * pad) + whatsNewRow.frame = NSRect(x: pad, y: divider.frame.maxY + Metrics.space1, width: rowWidth, height: Self.rowHeight) + shareRow.frame = NSRect(x: pad, y: whatsNewRow.frame.maxY, width: rowWidth, height: Self.rowHeight) + } + + private func applyColors() { + performWithTheme { + titleLabel.textColor = Palette.textPrimary + divider.layer?.backgroundColor = Palette.separator.cgColor + } + whatsNewRow.refresh() + shareRow.refresh() + } + + override func viewDidChangeEffectiveAppearance() { + super.viewDidChangeEffectiveAppearance() + applyColors() + surface.applyTheme() + } + + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + applyColors() + } + + // MARK: Tests + + /// Every line as shown, top to bottom. + var shownText: [String] { [titleLabel.stringValue, whatsNewRow.text, shareRow.text] } +} + +/// One row of the "cmux Updated!" card: a symbol and a title, the hover +/// fill of the sidebar's other controls, pressed by a click (VoiceOver: +/// a button named by its title). +final class SidebarUpdatedCardRow: NSButton { + private(set) lazy var hover = ChromeHover(self, behindContent: true) + var onPress: (() -> Void)? + private let symbol: String + /// The row's title as shown. + var text = "" { + didSet { + guard text != oldValue else { return } + setAccessibilityLabel(text) + refresh() + } + } + + init(symbol: String) { + self.symbol = symbol + super.init(frame: .zero) + isBordered = false + imagePosition = .imageLeading + imageHugsTitle = true + alignment = .natural + wantsLayer = true + target = self + action = #selector(pressed) + refusesFirstResponder = true + setAccessibilityRole(.button) + hover.followPointer(onChange: { [weak self] in self?.refresh() }) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError() } + + @objc private func pressed() { onPress?() } + + /// Symbol and title in the hover state's color. + func refresh() { + performWithTheme { + let color = hover.state.hovering || hover.state.pressed ? Palette.textPrimary : Palette.textSecondary + let config = NSImage.SymbolConfiguration(pointSize: Metrics.smallIconSize, weight: .regular) + image = NSImage(systemSymbolName: symbol, accessibilityDescription: nil)?.withSymbolConfiguration(config) + contentTintColor = color + // A leading space separates the title from the symbol (imageHugsTitle). + attributedTitle = NSAttributedString(string: " " + text, attributes: [.font: Typography.body, .foregroundColor: color]) + } + needsDisplay = true + } + + override var wantsUpdateLayer: Bool { true } + + override func updateLayer() { + layer?.cornerRadius = Metrics.itemCornerRadius + hover.refresh(animated: false) + } + + override func viewDidChangeEffectiveAppearance() { + super.viewDidChangeEffectiveAppearance() + refresh() + } + + /// NSButton tracks the click inside `super.mouseDown` and returns on release. + override func mouseDown(with event: NSEvent) { + hover.state.pressed = true + refresh() + super.mouseDown(with: event) + hover.state.pressed = false + refresh() + } + + /// A row hidden under the pointer (the card going away) gets no exit event. + override func viewDidHide() { + super.viewDidHide() + hover.state.pressed = false + hover.pointer?.refresh() + } + + override func viewDidUnhide() { + super.viewDidUnhide() + hover.pointer?.refresh() + } +} + +/// The card's lines, flipped, over the glass: the tip card's light theme +/// veil keeps them legible over a bright backdrop; the opaque fill needs none. +private final class SidebarUpdatedCardContent: NSView { + var material: () -> OverlayMaterial = { .liquidGlass } + + override init(frame: NSRect) { + super.init(frame: frame) + wantsLayer = true + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError() } + + override var isFlipped: Bool { true } + override var wantsUpdateLayer: Bool { true } + + override func updateLayer() { + performWithTheme { + layer?.backgroundColor = material() == .opaque + ? NSColor.clear.cgColor + : Palette.elevatedBackground.withAlphaComponent(0.32).cgColor + } + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarView+Rename.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarView+Rename.swift index 42eb0557cb4b..3f133797d760 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarView+Rename.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarView+Rename.swift @@ -1,5 +1,5 @@ extension SidebarView { - /// Starts inline rename of a group. Commit emits `.renameGroup`. + /// Opens the group editor (cx-rcby); a name edit emits `.renameGroup`. public func beginRename(group id: GroupID) { list.inlineRename.begin(.group(id)) } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarView+UpdateCard.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarView+UpdateCard.swift index 313b82b8d2a2..c4315418fdba 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarView+UpdateCard.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarView+UpdateCard.swift @@ -2,12 +2,13 @@ import AppKit extension SidebarView { /// The bottom-left card slot over this sidebar's two card views. - var cardSlot: SidebarBottomCardSlot { SidebarBottomCardSlot(update: updateCardView, tip: tipCardView) } + var cardSlot: SidebarBottomCardSlot { SidebarBottomCardSlot(update: updateCardView, updated: updatedCardView, tip: tipCardView) } } /// The bottom-left cards the sidebar renders (`SidebarModel.updateCard`, -/// `.tipCard`): `updateCardView` and `tipCardView`, one at a time. +/// `.updatedCard`, `.tipCard`): one at a time, in that order. nonisolated struct SidebarBottomCards: Hashable, Sendable { var update: SidebarUpdateCard? + var updated: SidebarUpdatedCard? var tip: SidebarTipCard? } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarView.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarView.swift index f80b189fe3cd..d7b640c08b8f 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarView.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/SidebarView.swift @@ -60,7 +60,7 @@ public final class SidebarView: NSView { var minimalHiddenBands: (top: Bool, bottom: Bool) = (false, false) var accessories: [SidebarAccessorySlot: NSView] = [:] let footer = NSView() - let updateCardView = SidebarUpdateCardView(), tipCardView = SidebarTipCardView() // SidebarBottomCards + let updateCardView = SidebarUpdateCardView(), updatedCardView = SidebarUpdatedCardView(), tipCardView = SidebarTipCardView() /// Back, in the footer band's spot while a destination is open (`SidebarView+Footer`). let backButton = SidebarBackButton() /// Where the spaces dots sit (`sidebar.spacesPosition`, R109). @@ -347,7 +347,7 @@ public final class SidebarView: NSView { fontSize: Typography.body.pointSize, titlebarHeight: Metrics.titlebarHeight, showsBack: model.showsBack, - cards: SidebarBottomCards(update: model.updateCard, tip: model.tipCard) + cards: SidebarBottomCards(update: model.updateCard, updated: model.updatedCard, tip: model.tipCard) ) }) { self?.render(state) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/WorkspaceRowView.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/WorkspaceRowView.swift index 5aa130cad6b4..3a504b8dbbb4 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/WorkspaceRowView.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextSidebar/Views/WorkspaceRowView.swift @@ -47,6 +47,7 @@ final class WorkspaceRowView: SidebarRowView { var groupBandFrame: NSRect { groupRail.frame } var isGroupBandHidden: Bool { groupRail.isHidden } private var groupColor: GroupColor? + private var lastInGroup = false private var iconKind: WorkspaceIcon? /// Selected but not active (the active row paints the selection fill). var isSecondarySelected = false { didSet { if isSecondarySelected != oldValue { needsDisplay = true } } } @@ -123,6 +124,7 @@ final class WorkspaceRowView: SidebarRowView { var ws: SidebarWorkspace var group: GroupID? var groupColor: GroupColor? + var lastInGroup: Bool var fontSize: CGFloat var iconSize: CGFloat var agentMark: SidebarAgentMarkVariant @@ -133,7 +135,7 @@ final class WorkspaceRowView: SidebarRowView { func configure(_ ws: SidebarWorkspace, row: SidebarRow) { lastConfiguration = (ws, row) let content = Content( - ws: ws, group: row.group, groupColor: row.groupColor, + ws: ws, group: row.group, groupColor: row.groupColor, lastInGroup: row.isLastInGroup, fontSize: SidebarStyle.titleFont.pointSize, iconSize: Metrics.smallIconSize, agentMark: observedAgentMarkVariant(), disclosure: row.tabDisclosure, row: row.content @@ -141,6 +143,7 @@ final class WorkspaceRowView: SidebarRowView { guard needsConfigure(content) else { return } grouped = row.group != nil groupColor = row.groupColor + lastInGroup = row.isLastInGroup isShowingPlaceholder = ws.rowState == .placeholder isClosable = ws.isClosable placeholderFraction = SidebarStyle.placeholderFractions[ws.id.rawValue.utf8.reduce(0) { $0 &+ Int($1) } % SidebarStyle.placeholderFractions.count] @@ -243,7 +246,8 @@ final class WorkspaceRowView: SidebarRowView { tabCount.textColor = Palette.textTertiary mutedMark.contentTintColor = Palette.textTertiary prBadge.textColor = Palette.textSecondary - agentMark.contentTintColor = activityState == .waiting ? Palette.attention : Palette.textSecondary + let waits = if case .waiting = activityState { true } else { false } + agentMark.contentTintColor = waits ? Palette.attention : Palette.textSecondary // Fills only, no borders: drop target, selection, multi-selection, hover. paintFill(isDropTarget || isSelected ? Palette.selectionFill : isSecondarySelected ? Palette.secondarySelectionFill @@ -260,23 +264,19 @@ final class WorkspaceRowView: SidebarRowView { CATransaction.setDisableActions(true) defer { CATransaction.commit() } - // Option B band (Lawrence 2026-10-07): a member indents past its - // header's caret, and one band in the group color runs under the - // caret through every member row (full height, so rows join); - // a neutral band for a group without a color. + // The members' bar (cx-rcby, the Chrome tab group line): one thin + // line in the group's theme color under the chip's rounded start, + // through every member row (full height, so rows join) and rounded + // off under the last member; a neutral line for a group without a color. let indent: CGFloat = grouped ? SidebarStyle.groupMemberIndent : 0 - let railWidth = max(Metrics.dividerThickness * 3, 3) - groupRail.frame = NSRect( - x: SidebarStyle.titleLeading + (Metrics.smallIconSize - railWidth) / 2, - y: 0, - width: railWidth, - height: b.height - ) + let barWidth = SidebarStyle.groupBarWidth + let barBottom = lastInGroup ? Metrics.space2 : 0 + groupRail.frame = NSRect(x: SidebarStyle.groupBarX, y: 0, width: barWidth, height: max(0, b.height - barBottom)) groupRail.isHidden = !grouped performWithTheme { - let color = groupColor.map { $0 == .grey ? Palette.badgeFill : $0.swatch } ?? Palette.badgeFill - groupRail.backgroundColor = color.cgColor - groupRail.cornerRadius = 0 + groupRail.backgroundColor = (groupColor ?? .grey).headerFill.cgColor + groupRail.cornerRadius = lastInGroup ? barWidth / 2 : 0 + groupRail.maskedCorners = isFlipped ? [.layerMinXMaxYCorner, .layerMaxXMaxYCorner] : [.layerMinXMinYCorner, .layerMaxXMinYCorner] } // A custom workspace icon takes the leading slot; without one the // title starts at the leading inset (no default kind glyph). diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/Demo/TabStripDemo.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/Demo/TabStripDemo.swift index 28faabe07106..5e780d7f6aa0 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/Demo/TabStripDemo.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/Demo/TabStripDemo.swift @@ -84,7 +84,7 @@ public final class MockTabPreviewProvider: TabPreviewProvider { let height = Int(maxPixelSize.height) guard width > 0, height > 0, let context = CGContext( data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, - space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue + space: CGColorSpace(name: CGColorSpace.sRGB) ?? CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue ) else { return nil } context.setFillColor(CGColor(gray: 0.08, alpha: 1)) context.fill(CGRect(x: 0, y: 0, width: width, height: height)) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabAgentMarkCache.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabAgentMarkCache.swift index 841b014b12b1..ecb26045c039 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabAgentMarkCache.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabAgentMarkCache.swift @@ -17,7 +17,7 @@ final class TabAgentMarkCache { let pixels = Int((size * scale).rounded()) guard pixels > 0, let context = CGContext( data: nil, width: pixels, height: pixels, bitsPerComponent: 8, bytesPerRow: 0, - space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue + space: CGColorSpace(name: CGColorSpace.sRGB) ?? CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue ) else { return nil } let side = CGFloat(pixels) * Self.fill let inset = (CGFloat(pixels) - side) / 2 diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabCell+StatusBadge.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabCell+StatusBadge.swift new file mode 100644 index 000000000000..e5f1a307680d --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabCell+StatusBadge.swift @@ -0,0 +1,63 @@ +import CmuxNextDesign +import QuartzCore + +/// The tab's status badge in a status icon set (cx-kxa2): with a candidate +/// set chosen (`StatusIconSet`, Debug Settings `status.iconSet`), needs +/// input, done and failed draw the set's mark (with the OSC 7501 blocked +/// kind) at the icon's corner in place of the colored dot. The default set +/// keeps the dot, so nothing changes until a set is picked. The unread dot +/// is not a status and stays a dot. +extension TabCell { + /// The state the badge stands for; nil without a status. + var statusBadgeState: StatusIndicatorState? { + switch item.status { + case .needsInput: .waiting(kind: item.blockedKind) + case .success: .success + case .failure: .error + case .none: nil + } + } + + /// The set's mark for the badge, or nil where the dot stays. + func statusBadgePlan(config: StatusIndicatorConfig) -> StatusIndicatorPlan? { + guard config.iconSet != .current, let state = statusBadgeState else { return nil } + let plan = StatusIndicatorPlan.make(state, style: config.settings.style, animates: false, set: config.iconSet) + return plan.glyph == .none ? nil : plan + } + + /// Creates, updates or removes the badge mark for the item and config. + /// A cell with a status follows the shared config, so a set switch + /// restyles it live. + func updateStatusGlyph() { + if item.status != .none { StatusIndicatorAppearance.shared.register(self) } + let config = StatusIndicatorAppearance.shared.config + if let plan = statusBadgePlan(config: config) { + let glyph = statusGlyphLayer ?? { + let glyph = StatusIndicatorLayer() + glyph.hostIsFlipped = true // the strip's tab layers live in a FlippedView + glyph.contentsScale = scale + themeScope.perform { glyph.colors = .current(loading: config.settings.color) } + layer.insertSublayer(glyph.layer, below: titleLayer) + statusGlyphLayer = glyph + return glyph + }() + glyph.apply(plan, config: config) + } else if let statusGlyphLayer { + statusGlyphLayer.layer.removeFromSuperlayer() + self.statusGlyphLayer = nil + } + layoutLayers() + } + + /// Places the badge mark at the icon's top trailing corner, where the dot + /// sits; true when it draws (the dot is then skipped). + func layoutStatusGlyph(iconFrame: CGRect, visible: Bool) -> Bool { + guard let statusGlyphLayer else { return false } + statusGlyphLayer.contentsScale = scale + statusGlyphLayer.layer.opacity = visible ? 1 : 0 + let side = pixel(iconFrame.width * 0.62) + statusGlyphLayer.frame = CGRect(x: pixel(iconFrame.maxX - side + Metrics.space1), y: pixel(iconFrame.minY - Metrics.space1), + width: side, height: side) + return visible + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabCell+StatusIndicator.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabCell+StatusIndicator.swift index 27911a3fcc8d..9b6f094d3068 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabCell+StatusIndicator.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabCell+StatusIndicator.swift @@ -10,7 +10,7 @@ extension TabCell: StatusIndicatorConfigClient { var spinnerPlan: StatusIndicatorPlan { guard item.indicator.replacesTabIcon else { return .hidden } let config = StatusIndicatorAppearance.shared.config - return StatusIndicatorPlan.make(item.indicator, style: config.style(hint: item.busyStyle), animates: config.animatesLoops) + return StatusIndicatorPlan.make(item.indicator, style: config.style(hint: item.busyStyle), animates: config.animatesLoops, set: config.iconSet) } /// Creates, updates or removes the indicator for the current item and @@ -30,6 +30,7 @@ extension TabCell: StatusIndicatorConfigClient { } func statusIndicatorConfigDidChange(_ config: StatusIndicatorConfig) { + if item.status != .none { updateStatusGlyph() } guard item.isBusy else { return } updateSpinner() updateColors(animated: false) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabCell.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabCell.swift index 41b8df679fa1..8300bf9e6e2a 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabCell.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabCell.swift @@ -74,6 +74,7 @@ final class TabCell { // unread or showing status, close button on the selected/hovered tab. var spinnerLayer: StatusIndicatorLayer? var badgeLayer: CALayer? + var statusGlyphLayer: StatusIndicatorLayer? // a status icon set's badge mark (TabCell+StatusBadge) var closeBackgroundLayer: CALayer? var closeGlyphLayer: CAShapeLayer? /// The machine badge, created while the item names a remote machine. @@ -152,6 +153,7 @@ final class TabCell { if previous?.indicator != item.indicator || previous?.busyStyle != item.busyStyle { updateSpinner() } + if previous?.status != item.status || previous?.blockedKind != item.blockedKind { updateStatusGlyph() } if previous?.machineBadge != item.machineBadge { updateMachineBadge() } if previous?.themeBadge != item.themeBadge { updateThemeBadge() } if previous?.profileBadge != item.profileBadge { updateProfileBadge() } @@ -212,7 +214,9 @@ final class TabCell { titleLayer.foregroundColor = text.cgColor machineLayer?.foregroundColor = Palette.textTertiary.cgColor applyProfileDotColors() - spinnerLayer?.colors = .current(loading: StatusIndicatorAppearance.shared.config.settings.color) + let indicatorColors = StatusIndicatorLayer.Colors.current(loading: StatusIndicatorAppearance.shared.config.settings.color) + spinnerLayer?.colors = indicatorColors + statusGlyphLayer?.colors = indicatorColors separatorLayer.backgroundColor = Palette.separator.cgColor iconLayer.contents = iconImage(tint: item.tint?.swatch ?? text) } @@ -301,7 +305,8 @@ final class TabCell { } } - if visibility.showsIcon, badgeColor != nil { + let drawsStatusGlyph = layoutStatusGlyph(iconFrame: iconFrame, visible: visibility.showsIcon) + if visibility.showsIcon, badgeColor != nil, !drawsStatusGlyph { let badgeLayer = makeBadge() let badge = m.badgeSize badgeLayer.frame = CGRect( diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabItem.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabItem.swift index 7084cd3ba838..a3fb89c0be62 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabItem.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabItem.swift @@ -24,6 +24,9 @@ public struct TabItem: Identifiable, Hashable, Sendable { /// `appearance.statusIndicator.style`. public var busyStyle: StatusIndicatorStyle? public var status: TabStatus + /// What a `needsInput` badge waits for (OSC 7501 `kind`), so a status + /// icon set can mark it (`StatusIconSet`); nil for other states. + public var blockedKind: StatusBlockedKind? /// The page hibernated (released to save memory; reloads when /// selected): the icon and title are drawn dimmed. public var isDormant = false diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabStripView+Drag.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabStripView+Drag.swift index 3bbf30f7d3bf..2aaf5570ccf5 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabStripView+Drag.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabStripView+Drag.swift @@ -204,7 +204,7 @@ extension TabStripView { let height = Int((size.height * scale).rounded()) guard width > 0, height > 0, let context = CGContext( data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, - space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue + space: CGColorSpace(name: CGColorSpace.sRGB) ?? CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue ) else { return nil } // Layers are flipped; CoreGraphics is not. context.translateBy(x: 0, y: CGFloat(height)) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabSymbolCache.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabSymbolCache.swift index 30914e7f02cf..c10ecb974561 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabSymbolCache.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextTabs/TabSymbolCache.swift @@ -17,7 +17,7 @@ final class TabSymbolCache { let pixels = Int((size * scale).rounded()) guard let context = CGContext( data: nil, width: pixels, height: pixels, bitsPerComponent: 8, bytesPerRow: 0, - space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue + space: CGColorSpace(name: CGColorSpace.sRGB) ?? CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue ) else { return nil } context.scaleBy(x: scale, y: scale) let graphics = NSGraphicsContext(cgContext: context, flipped: false) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextTerminal/LocalPTYTerminalIO.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextTerminal/LocalPTYTerminalIO.swift index 753ad4abebe6..5b31e51538ea 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextTerminal/LocalPTYTerminalIO.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextTerminal/LocalPTYTerminalIO.swift @@ -210,9 +210,11 @@ private nonisolated final class PendingInput: @unchecked Sendable { func flush(to fd: Int32, source: any DispatchSourceWrite) { while !cancelled, offset < data.count { - let written = data.withUnsafeBytes { raw in + let written = data.withUnsafeBytes { raw -> Int in + // offset < data.count, so the buffer has a base address; without one, drop the data. + guard let base = raw.baseAddress else { return 0 } // concurrency-allow: nonblocking PTY descriptor, on the private write queue. - Darwin.write(fd, raw.baseAddress! + offset, raw.count - offset) + return Darwin.write(fd, base + offset, raw.count - offset) } if written > 0 { offset += written diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextUpdater/Resources/Localizable.xcstrings b/Packages/macOS/CmuxNext/Sources/CmuxNextUpdater/Resources/Localizable.xcstrings index b7c47dc2b1b6..f5eb19449bc5 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextUpdater/Resources/Localizable.xcstrings +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextUpdater/Resources/Localizable.xcstrings @@ -11528,6 +11528,1447 @@ } } } + }, + "updater.updated.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "cmux Updated!" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "cmux Updated!" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "cmux Updated!" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "cmux Updated!" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "cmux Updated!" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "cmux Updated!" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "cmux Updated!" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "cmux Updated!" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "cmux をアップデートしました" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "cmux Updated!" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "cmux Updated!" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "cmux Updated!" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "cmux Updated!" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "cmux Updated!" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "cmux Updated!" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "cmux Updated!" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "cmux Updated!" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "cmux Updated!" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "cmux Updated!" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "cmux Updated!" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "cmux Updated!" + } + } + } + }, + "updater.updated.whatsNew": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "See What's New" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "See What's New" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "See What's New" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "See What's New" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "See What's New" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "See What's New" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "See What's New" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "See What's New" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "新機能を見る" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "See What's New" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "See What's New" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "See What's New" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "See What's New" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "See What's New" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "See What's New" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "See What's New" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "See What's New" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "See What's New" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "See What's New" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "See What's New" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "See What's New" + } + } + } + }, + "updater.updated.share": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Share cmux" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "cmux を共有" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux" + } + } + } + }, + "updater.updated.dismiss": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Hide Until the Next Update" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "Hide Until the Next Update" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Hide Until the Next Update" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Hide Until the Next Update" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Hide Until the Next Update" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Hide Until the Next Update" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Hide Until the Next Update" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Hide Until the Next Update" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "次のアップデートまで非表示" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "Hide Until the Next Update" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "Hide Until the Next Update" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Hide Until the Next Update" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Hide Until the Next Update" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Hide Until the Next Update" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Hide Until the Next Update" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "Hide Until the Next Update" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Hide Until the Next Update" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Hide Until the Next Update" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Hide Until the Next Update" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "Hide Until the Next Update" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "Hide Until the Next Update" + } + } + } + }, + "share.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Share cmux with a Friend" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux with a Friend" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux with a Friend" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux with a Friend" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux with a Friend" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux with a Friend" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux with a Friend" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux with a Friend" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "友だちに cmux を紹介" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux with a Friend" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux with a Friend" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux with a Friend" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux with a Friend" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux with a Friend" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux with a Friend" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux with a Friend" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux with a Friend" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux with a Friend" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux with a Friend" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux with a Friend" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "Share cmux with a Friend" + } + } + } + }, + "share.body": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Send this message with the download link to a friend." + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "Send this message with the download link to a friend." + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Send this message with the download link to a friend." + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Send this message with the download link to a friend." + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Send this message with the download link to a friend." + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Send this message with the download link to a friend." + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Send this message with the download link to a friend." + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Send this message with the download link to a friend." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ダウンロードリンク付きのこのメッセージを友だちに送りましょう。" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "Send this message with the download link to a friend." + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "Send this message with the download link to a friend." + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Send this message with the download link to a friend." + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Send this message with the download link to a friend." + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Send this message with the download link to a friend." + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Send this message with the download link to a friend." + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "Send this message with the download link to a friend." + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Send this message with the download link to a friend." + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Send this message with the download link to a friend." + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Send this message with the download link to a friend." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "Send this message with the download link to a friend." + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "Send this message with the download link to a friend." + } + } + } + }, + "share.message": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Here's a link to download cmux, the terminal I was telling you about:" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "Here's a link to download cmux, the terminal I was telling you about:" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Here's a link to download cmux, the terminal I was telling you about:" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Here's a link to download cmux, the terminal I was telling you about:" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Here's a link to download cmux, the terminal I was telling you about:" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Here's a link to download cmux, the terminal I was telling you about:" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Here's a link to download cmux, the terminal I was telling you about:" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Here's a link to download cmux, the terminal I was telling you about:" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "前に話したターミナル、cmux のダウンロードリンクです:" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "Here's a link to download cmux, the terminal I was telling you about:" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "Here's a link to download cmux, the terminal I was telling you about:" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Here's a link to download cmux, the terminal I was telling you about:" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Here's a link to download cmux, the terminal I was telling you about:" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Here's a link to download cmux, the terminal I was telling you about:" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Here's a link to download cmux, the terminal I was telling you about:" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "Here's a link to download cmux, the terminal I was telling you about:" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Here's a link to download cmux, the terminal I was telling you about:" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Here's a link to download cmux, the terminal I was telling you about:" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Here's a link to download cmux, the terminal I was telling you about:" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "Here's a link to download cmux, the terminal I was telling you about:" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "Here's a link to download cmux, the terminal I was telling you about:" + } + } + } + }, + "share.messageLabel": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Message" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "Message" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Message" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Message" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Message" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Message" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Message" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Message" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "メッセージ" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "Message" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "Message" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Message" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Message" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Message" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Message" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "Message" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Message" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Message" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Message" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "Message" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "Message" + } + } + } + }, + "share.copyLink": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Copy Link" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "Copy Link" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Copy Link" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Copy Link" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Copy Link" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Copy Link" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Copy Link" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Copy Link" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "リンクをコピー" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "Copy Link" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "Copy Link" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Copy Link" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Copy Link" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Copy Link" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Copy Link" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "Copy Link" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Copy Link" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Copy Link" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Copy Link" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "Copy Link" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "Copy Link" + } + } + } + }, + "share.copied": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Copied" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "Copied" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Copied" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Copied" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Copied" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Copied" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Copied" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Copied" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "コピーしました" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "Copied" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "Copied" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Copied" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Copied" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Copied" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Copied" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "Copied" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Copied" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Copied" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Copied" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "Copied" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "Copied" + } + } + } + }, + "share.close": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Close" + } + }, + "ar": { + "stringUnit": { + "state": "needs_review", + "value": "Close" + } + }, + "bs": { + "stringUnit": { + "state": "needs_review", + "value": "Close" + } + }, + "da": { + "stringUnit": { + "state": "needs_review", + "value": "Close" + } + }, + "de": { + "stringUnit": { + "state": "needs_review", + "value": "Close" + } + }, + "es": { + "stringUnit": { + "state": "needs_review", + "value": "Close" + } + }, + "fr": { + "stringUnit": { + "state": "needs_review", + "value": "Close" + } + }, + "it": { + "stringUnit": { + "state": "needs_review", + "value": "Close" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "閉じる" + } + }, + "km": { + "stringUnit": { + "state": "needs_review", + "value": "Close" + } + }, + "ko": { + "stringUnit": { + "state": "needs_review", + "value": "Close" + } + }, + "nb": { + "stringUnit": { + "state": "needs_review", + "value": "Close" + } + }, + "pl": { + "stringUnit": { + "state": "needs_review", + "value": "Close" + } + }, + "pt-BR": { + "stringUnit": { + "state": "needs_review", + "value": "Close" + } + }, + "ru": { + "stringUnit": { + "state": "needs_review", + "value": "Close" + } + }, + "th": { + "stringUnit": { + "state": "needs_review", + "value": "Close" + } + }, + "tr": { + "stringUnit": { + "state": "needs_review", + "value": "Close" + } + }, + "uk": { + "stringUnit": { + "state": "needs_review", + "value": "Close" + } + }, + "vi": { + "stringUnit": { + "state": "needs_review", + "value": "Close" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "needs_review", + "value": "Close" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "needs_review", + "value": "Close" + } + } + } } }, "version": "1.0" diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextUpdater/Share/ShareCmuxStrings.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextUpdater/Share/ShareCmuxStrings.swift new file mode 100644 index 000000000000..12140e029465 --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextUpdater/Share/ShareCmuxStrings.swift @@ -0,0 +1,29 @@ +import Foundation + +/// The "cmux Updated!" card's and the Share cmux modal's strings +/// (Resources/Localizable.xcstrings; cx-7py7). +nonisolated enum ShareCmuxStrings { + static var cardTitle: String { UpdaterStrings.text("updater.updated.title", "cmux Updated!") } + static var cardWhatsNew: String { UpdaterStrings.text("updater.updated.whatsNew", "See What's New") } + static var cardShare: String { UpdaterStrings.text("updater.updated.share", "Share cmux") } + static var cardDismiss: String { UpdaterStrings.text("updater.updated.dismiss", "Hide Until the Next Update") } + + static var title: String { UpdaterStrings.text("share.title", "Share cmux with a Friend") } + static var body: String { UpdaterStrings.text("share.body", "Send this message with the download link to a friend.") } + static var message: String { + UpdaterStrings.text("share.message", "Here's a link to download cmux, the terminal I was telling you about:") + } + static var messageLabel: String { UpdaterStrings.text("share.messageLabel", "Message") } + static var copyLink: String { UpdaterStrings.text("share.copyLink", "Copy Link") } + static var copied: String { UpdaterStrings.text("share.copied", "Copied") } + static var close: String { UpdaterStrings.text("share.close", "Close") } +} + +extension UpdaterService { + /// The "cmux Updated!" card's text (the App fills `SidebarUpdatedCard`). + public static var updatedCardTitle: String { ShareCmuxStrings.cardTitle } + public static var updatedCardWhatsNewTitle: String { ShareCmuxStrings.cardWhatsNew } + public static var updatedCardShareTitle: String { ShareCmuxStrings.cardShare } + /// The x's tooltip and VoiceOver label. + public static var updatedCardDismissLabel: String { ShareCmuxStrings.cardDismiss } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextUpdater/Share/ShareCmuxView.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextUpdater/Share/ShareCmuxView.swift new file mode 100644 index 000000000000..25a5ee9ea5a5 --- /dev/null +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextUpdater/Share/ShareCmuxView.swift @@ -0,0 +1,233 @@ +public import AppKit +import CmuxNextDesign + +/// "Share cmux" (cx-7py7): a centered modal in the cmux dialog style +/// (theme grays, no accent color): a title, one short line, an editable +/// message that carries the plain public download link, a Copy Link button +/// that copies the message as shown and turns into "Copied", and an x. +/// Escape closes it too. No referral or gift tracking: the link is the +/// public download page. The App presents it (`app.shareCmux`). +@MainActor +public final class ShareCmuxView: NSView { + /// The public download page (the same link the team invite email uses). + public static let downloadURL = URL(string: "https://cmux.com/download")! // crash-allow: a constant valid URL + + /// The prefilled message: one localized sentence, a blank line, the link. + public static var defaultMessage: String { "\(ShareCmuxStrings.message)\n\n\(downloadURL.absoluteString)" } + + /// Copy Link's default write: the message as plain text on the general pasteboard. + public static func writeToGeneralPasteboard(_ text: String) { + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(text, forType: .string) + } + + /// The x or Escape (the presenter dismisses the overlay). + public var onClose: (() -> Void)? + let copyButton: CmuxDialogButtonView + let closeButton: NSButton + let messageView = ShareCmuxMessageTextView() + private let titleLabel = NSTextField(wrappingLabelWithString: ShareCmuxStrings.title) + private let bodyLabel = NSTextField(wrappingLabelWithString: ShareCmuxStrings.body) + private let messageScroll = NSScrollView() + private let stack = NSStackView() + /// The modal's material, below the lines (like the tip card, cx-367y). + let surface: OverlaySurfaceView + private let writeToPasteboard: @MainActor (String) -> Void + + /// `writeToPasteboard` puts the copied message on the general pasteboard + /// (tests record it instead). + public init(writeToPasteboard: @escaping @MainActor (String) -> Void = ShareCmuxView.writeToGeneralPasteboard) { + self.writeToPasteboard = writeToPasteboard + surface = OverlaySurfaceView(interactive: true) + copyButton = CmuxDialogButtonView(CmuxDialogButton(id: "copy-link", title: ShareCmuxStrings.copyLink, role: .default), + target: nil, action: #selector(ShareCmuxView.copyMessage)) + closeButton = NSButton(image: NSImage(systemSymbolName: "xmark", accessibilityDescription: ShareCmuxStrings.close) ?? NSImage(), + target: nil, action: nil) + super.init(frame: .zero) + copyButton.target = self + closeButton.target = self + closeButton.action = #selector(closePressed) + build() + setAccessibilityElement(true) + setAccessibilityRole(.group) + setAccessibilitySubrole(.dialog) + setAccessibilityLabel(ShareCmuxStrings.title) + setAccessibilityModal(true) + identifier = NSUserInterfaceItemIdentifier("cmux.shareCmux") + setFrameSize(fittingSize) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") } + + /// The message as shown (edits included). + public var messageText: String { + get { messageView.string } + set { + messageView.string = newValue + copyButton.retitle(ShareCmuxStrings.copyLink) + } + } + + /// Copy Link: the message as shown goes to the pasteboard; the button + /// says "Copied" until the message changes. + @objc public func copyMessage() { + writeToPasteboard(messageText) + copyButton.retitle(ShareCmuxStrings.copied) + } + + @objc private func closePressed() { onClose?() } + + /// Gives the keyboard to Copy Link (the presenter, once the modal shows). + public func focusCopyLink() { + window?.makeFirstResponder(copyButton) + } + + public override func cancelOperation(_ sender: Any?) { onClose?() } + + /// Return copies while Copy Link has the keyboard (Space presses it too); + /// in the message, Return types a line break. + public override func keyDown(with event: NSEvent) { + if [36, 76].contains(event.keyCode), window?.firstResponder === copyButton { + copyMessage() + } else { + super.keyDown(with: event) + } + } + + public override var acceptsFirstResponder: Bool { true } + + // MARK: Layout + + static var width: CGFloat { 380 * Typography.userScale } + + private func build() { + let padding = Metrics.space5, contentWidth = Self.width - 2 * padding + stack.orientation = .vertical + stack.alignment = .leading + stack.spacing = Metrics.space3 + stack.edgeInsets = NSEdgeInsets(top: padding, left: padding, bottom: padding, right: padding) + stack.translatesAutoresizingMaskIntoConstraints = false + + titleLabel.font = Typography.title + titleLabel.preferredMaxLayoutWidth = contentWidth - 20 - 2 * Metrics.space2 + bodyLabel.font = Typography.body + bodyLabel.preferredMaxLayoutWidth = contentWidth + for label in [titleLabel, bodyLabel] { label.isSelectable = false } + bodyLabel.widthAnchor.constraint(equalToConstant: contentWidth).isActive = true + + closeButton.isBordered = false + closeButton.focusRingType = .none + closeButton.bezelStyle = .regularSquare + closeButton.imagePosition = .imageOnly + closeButton.setAccessibilityLabel(ShareCmuxStrings.close) + closeButton.toolTip = ShareCmuxStrings.close + closeButton.identifier = NSUserInterfaceItemIdentifier("cmux.shareCmux.close") + closeButton.translatesAutoresizingMaskIntoConstraints = false + closeButton.widthAnchor.constraint(equalToConstant: 20).isActive = true + closeButton.heightAnchor.constraint(equalToConstant: 20).isActive = true + let header = NSStackView(views: [titleLabel, NSView(), closeButton]) + header.orientation = .horizontal + header.spacing = Metrics.space2 + header.alignment = .top + header.translatesAutoresizingMaskIntoConstraints = false + header.widthAnchor.constraint(equalToConstant: contentWidth).isActive = true + + messageView.isRichText = false + messageView.allowsUndo = true + messageView.font = Typography.body + messageView.drawsBackground = false + messageView.textContainerInset = NSSize(width: Metrics.space2, height: Metrics.space2) + messageView.isVerticallyResizable = true + messageView.isHorizontallyResizable = false + messageView.minSize = NSSize(width: 0, height: 96 * Typography.userScale) + messageView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) + messageView.frame = NSRect(x: 0, y: 0, width: contentWidth, height: 96 * Typography.userScale) + messageView.autoresizingMask = [.width] + messageView.textContainer?.widthTracksTextView = true + messageView.string = Self.defaultMessage + messageView.setAccessibilityLabel(ShareCmuxStrings.messageLabel) + messageView.identifier = NSUserInterfaceItemIdentifier("cmux.shareCmux.message") + messageView.onEdit = { [weak self] in self?.copyButton.retitle(ShareCmuxStrings.copyLink) } + messageView.onCancel = { [weak self] in self?.onClose?() } + messageView.onTab = { [weak self] backward in + guard let self else { return } + self.window?.makeFirstResponder(backward ? self.closeButton : self.copyButton) + } + messageScroll.documentView = messageView + messageScroll.hasVerticalScroller = true + messageScroll.autohidesScrollers = true + messageScroll.drawsBackground = false + messageScroll.borderType = .noBorder + messageScroll.wantsLayer = true + messageScroll.layer?.cornerRadius = 7 + messageScroll.layer?.cornerCurve = .continuous + messageScroll.translatesAutoresizingMaskIntoConstraints = false + messageScroll.widthAnchor.constraint(equalToConstant: contentWidth).isActive = true + messageScroll.heightAnchor.constraint(equalToConstant: 96 * Typography.userScale).isActive = true + + copyButton.identifier = NSUserInterfaceItemIdentifier("cmux.shareCmux.copyLink") + copyButton.widthAnchor.constraint(equalToConstant: contentWidth).isActive = true + + [header, bodyLabel, messageScroll, copyButton].forEach(stack.addArrangedSubview) + // The lines sit in a sibling above the material, not inside the glass's own view (nxdog75). + surface.translatesAutoresizingMaskIntoConstraints = false + addSubview(surface) + addSubview(stack) + NSLayoutConstraint.activate([ + surface.leadingAnchor.constraint(equalTo: leadingAnchor), surface.trailingAnchor.constraint(equalTo: trailingAnchor), + surface.topAnchor.constraint(equalTo: topAnchor), surface.bottomAnchor.constraint(equalTo: bottomAnchor), + stack.leadingAnchor.constraint(equalTo: leadingAnchor), stack.trailingAnchor.constraint(equalTo: trailingAnchor), + stack.topAnchor.constraint(equalTo: topAnchor), stack.bottomAnchor.constraint(equalTo: bottomAnchor), + widthAnchor.constraint(equalToConstant: Self.width), + ]) + applyColors() + } + + private func applyColors() { + performWithTheme { + titleLabel.textColor = Palette.textPrimary + bodyLabel.textColor = Palette.textSecondary + messageView.textColor = Palette.textPrimary + messageView.insertionPointColor = Palette.textPrimary + messageScroll.layer?.backgroundColor = Palette.hoverFill.cgColor + closeButton.contentTintColor = Palette.textSecondary + } + } + + public override func viewDidChangeEffectiveAppearance() { + super.viewDidChangeEffectiveAppearance() + applyColors() + surface.applyTheme() + } + + public override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + applyColors() + } + + // MARK: Tests + + /// The title and the line, as shown. + var shownText: [String] { [titleLabel.stringValue, bodyLabel.stringValue] } +} + +/// The message box: plain text; Escape closes the modal instead of +/// completing a word; Tab and Shift-Tab leave it (the overlay's Tab cycle +/// holds only controls); every edit puts "Copy Link" back. +final class ShareCmuxMessageTextView: NSTextView { + var onEdit: (() -> Void)? + var onCancel: (() -> Void)? + /// Tab (false) or Shift-Tab (true). + var onTab: ((Bool) -> Void)? + + override func insertTab(_ sender: Any?) { onTab?(false) } + override func insertBacktab(_ sender: Any?) { onTab?(true) } + + override func didChangeText() { + super.didChangeText() + onEdit?() + } + + override func cancelOperation(_ sender: Any?) { onCancel?() } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextUpdater/WhatsNew/WhatsNewCenter.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextUpdater/WhatsNew/WhatsNewCenter.swift index 44ce3d1187d6..4320cebfdd4d 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextUpdater/WhatsNew/WhatsNewCenter.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextUpdater/WhatsNew/WhatsNewCenter.swift @@ -23,6 +23,14 @@ public final class WhatsNewCenter { /// Whether the sidebar's What's New item shows (with its unread dot). public var showsItem: Bool { isItemEnabled && !unseen.isEmpty } + /// This launch's stable or RC version is newer than the last seen one, + /// and neither the page nor the "cmux Updated!" card's x has marked it + /// seen (cx-7py7). Nightly versions never set it. + public private(set) var isUpdated = false + /// Whether the sidebar shows the "cmux Updated!" card: after any update, + /// with or without notes, until the page opens or the x; never on a + /// first install. `updates.showWhatsNew` off hides it too. + public var showsUpdatedCard: Bool { isItemEnabled && isUpdated } public let current: WhatsNewVersion? @ObservationIgnored let seen: WhatsNewSeenStore @@ -51,6 +59,7 @@ public final class WhatsNewCenter { } let tracker = seen.tracker(current: current) self.tracker = tracker + isUpdated = Self.announcesUpdate(to: current) && (tracker.lastSeen.map { $0 < current } ?? false) let sources = sources let task = Task { [weak self] in var documents: [WhatsNewDocument] = [] @@ -79,6 +88,36 @@ public final class WhatsNewCenter { presented = unseen.isEmpty ? (tracker?.recent(known) ?? []) : unseen if let current { seen.markSeen(current) } unseen = [] + isUpdated = false return presented } + + /// Whether an update to `version` shows the "cmux Updated!" card: stable + /// and RC versions do; nightly builds update several times a day, so they + /// do not (chief, 2026-10-08). + static func announcesUpdate(to version: WhatsNewVersion) -> Bool { + version.prerelease?.kind != "nightly" + } + + /// The "cmux Updated!" card's x: this version is seen, so the card and + /// the sidebar item's dot go together (one seen state). + public func dismissUpdated() { + if let current { seen.markSeen(current) } + unseen = [] + isUpdated = false + } + + /// DEV/NIGHTLY proof (`debug.updater {action: "updated", previous}`): + /// records `previous` as the last seen version and shows this launch as + /// an update from it. False for an unreadable or not older version. + @discardableResult + public func debugPretendUpdated(from previous: String) -> Bool { + guard let current, let lastSeen = WhatsNewVersion(previous), lastSeen < current else { return false } + seen.defaults.set(lastSeen.description, forKey: WhatsNewSeenStore.lastSeenKey) + let tracker = WhatsNewTracker(current: current, lastSeen: lastSeen) + self.tracker = tracker + unseen = tracker.unseen(known) + isUpdated = true + return true + } } diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextActionsTests/CrashLiteralTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextActionsTests/CrashLiteralTests.swift new file mode 100644 index 000000000000..8368b4bf89da --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextActionsTests/CrashLiteralTests.swift @@ -0,0 +1,18 @@ +import AppKit +import Testing +@testable import CmuxNextActions + +/// Crash program: the function-key characters no longer force-unwrap their scalar; each +/// still resolves to AppKit's private-use character, never the NUL fallback. +@MainActor @Suite struct CrashLiteralTests { + @Test func functionKeyCharactersResolve() { + #expect(Shortcut.upArrowKey == "\u{F700}") + #expect(Shortcut.downArrowKey == "\u{F701}") + #expect(Shortcut.leftArrowKey == "\u{F702}") + #expect(Shortcut.rightArrowKey == "\u{F703}") + #expect(KeyBindingDefaults.left == "\u{F702}") + #expect(KeyBindingDefaults.right == "\u{F703}") + #expect(KeyBindingDefaults.pageUp == "\u{F72C}") + #expect(KeyBindingDefaults.pageDown == "\u{F72D}") + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAgentActivityTests/CrashLiteralTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAgentActivityTests/CrashLiteralTests.swift new file mode 100644 index 000000000000..6aa088b1d99b --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAgentActivityTests/CrashLiteralTests.swift @@ -0,0 +1,10 @@ +import Foundation +import Testing +@testable import CmuxNextAgentActivity + +/// Crash program: the cmux:// page address is a literal that must parse. +@MainActor @Suite struct AgentActivityCrashLiteralTests { + @Test func pageAddressParses() { + #expect(AgentActivityPageAddress.url.absoluteString == AgentActivityPageAddress.string) + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAgentPaneTests/AgentPanePolicyParityTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAgentPaneTests/AgentPanePolicyParityTests.swift index 97414373aa11..1c7a28b42b02 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAgentPaneTests/AgentPanePolicyParityTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAgentPaneTests/AgentPanePolicyParityTests.swift @@ -135,6 +135,33 @@ import Testing "\(c["name"] ?? "?")") } + /// Seed the same pending-question keys described by a case's state. The shared + /// cases keep the question body out of `state`, so construct the minimal daemon + /// pending frame from the answer keys in the request before checking it. + static func seedQuestions(_ c: [String: Any], _ state: [String: Any], _ options: AcpmuxPermissionOptions) { + let params = ((try? JSONSerialization.jsonObject( + with: Data((c["text"] as? String ?? "").utf8), options: [.fragmentsAllowed] + )) as? [String: Any])?["params"] as? [String: Any] + let answers = params?["answers"] as? [String: Any] + let keys = answers.map { Array($0.keys) } ?? ["question"] + let denies = (state["denies"] as? [Any] ?? []).compactMap { $0 as? [String] } + for case let permission as String in state["questions"] as? [Any] ?? [] { + let items = keys.map { ["id": $0] } + var request: [String: Any] = ["toolCall": ["_meta": ["acpmux": [ + "question": ["items": items] + ]]]] + let optionsForPermission = denies.compactMap { deny -> [String: Any]? in + guard deny.count >= 2, deny[0] == permission else { return nil } + return ["optionId": deny[1], "kind": "reject_once"] + } + if !optionsForPermission.isEmpty { request["options"] = optionsForPermission } + options.observe(["method": "_acpmux/permission_pending", + "params": ["permissionId": permission, + "request": request]], + replyTo: nil) + } + } + @Test func frames() throws { for c in try Self.cases("frames.json") { try Self.checkFrame(c) } } @@ -179,18 +206,21 @@ import Testing /// runs against `check_frame`) against ``AgentPaneTransport/checkOne(_:_:)``. @Test func fullCheckOrder() throws { let all = try Self.cases("check.json") - #expect(all.count == 28, "check.json: the full order's 28 cases") + #expect(all.count == 41, "check.json: the full order's 41 cases") for c in all { let name = c["name"] as? String ?? "?" let state = try #require(c["state"] as? [String: Any]) let sessions = AcpmuxPaneSessions() for case let s as String in state["sessions"] as? [Any] ?? [] { sessions.add(s) } let options = AcpmuxPermissionOptions() + let questionPermissions = Set((state["questions"] as? [Any] ?? []).compactMap { $0 as? String }) for case let deny as [String] in state["denies"] as? [Any] ?? [] { + if questionPermissions.contains(deny.first ?? "") { continue } options.observe(["method": "_acpmux/permission_pending", "params": ["permissionId": deny[0], "request": ["options": [["optionId": deny[1], "kind": "reject_once"]]]]], replyTo: nil) } + Self.seedQuestions(c, state, options) let snapshot = AgentPaneTransport.Snapshot( isFirst: state["first"] as? Bool ?? false, localAppToken: state["token"] as? String, modeFields: (state["mode_fields"] as? [String]).map(Set.init), sessions: sessions, options: options) diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAgentPaneTests/AgentPaneQuestionAnswersTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAgentPaneTests/AgentPaneQuestionAnswersTests.swift index 00bd22977fd8..4b1d65c7e2f1 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAgentPaneTests/AgentPaneQuestionAnswersTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAgentPaneTests/AgentPaneQuestionAnswersTests.swift @@ -5,7 +5,8 @@ import Testing /// `answers` on `_acpmux/permission_respond` (plans/cmux-next/agent-questions.md): the relay lets /// page answers through only to a pending question (`request.toolCall._meta.acpmux.question` is an /// object), keyed by that question's items, and bounded: 1 to ``AcpmuxPaneMethods/maximumAnswerItems`` -/// items, each key and each string at most ``AcpmuxPaneMethods/maximumAnswerBytes`` UTF-8 bytes. Anything else is refused as `transport.intent_invalid` and never reaches the +/// items, each key and each string at most ``AcpmuxPaneMethods/maximumAnswerBytes`` UTF-8 bytes, +/// and list strings counted together under that same bound. Anything else is refused as `transport.intent_invalid` and never reaches the /// daemon; the permission stays pending. An answer is still an allow and needs a fresh gesture. @MainActor @Suite(.serialized) struct AgentPaneQuestionAnswersTests { @@ -80,9 +81,9 @@ import Testing #expect(Self.passes(Self.respond(permission: "p-codex", answers: ["db_engine": ["answers": ["SQLite"]], "service_name": ["answers": ["ledger"]]]))) #expect(Self.passes(Self.respond(permission: "p-codex", answers: ["db_engine": ["answers": ["SQLite", "Postgres"]]]))) #expect(Self.passes(Self.respond(permission: "p-codex", answers: ["db_engine": ["SQLite"]]))) - // The limit is per string: exactly 4096 bytes passes, and so do several such strings. + // A scalar may use all 4096 bytes; a list's strings are counted together. #expect(Self.passes(Self.respond(permission: "p-claude", answers: ["Which auth?": String(repeating: "a", count: 4096)]))) - #expect(Self.passes(Self.respond(permission: "p-codex", answers: ["db_engine": ["answers": [String(repeating: "a", count: 4096), String(repeating: "b", count: 4096)]]]))) + #expect(Self.refused(Self.respond(permission: "p-codex", answers: ["db_engine": ["answers": [String(repeating: "a", count: 2048), String(repeating: "b", count: 2049)]]]))) // A list holds at most 64 strings. #expect(Self.passes(Self.respond(permission: "p-codex", answers: ["db_engine": ["answers": Array(repeating: "SQLite", count: 64)]]))) #expect(Self.passes(Self.respond(permission: "p-claude", answers: ["Which auth?": Array(repeating: "OAuth", count: 64)]))) diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/ConfigActionsTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/ConfigActionsTests.swift index 44c8a7f2954e..e10c2c83c108 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/ConfigActionsTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/ConfigActionsTests.swift @@ -13,7 +13,7 @@ import Testing @Test func configCommandActionsAreRegisteredAndReplaced() throws { let services = Coverage.boundServices() - let controller = services.configActions! + let controller = services.configActions let command = ConfigCommandAction(name: "start-claude", title: "Start Claude", command: "claude") controller.apply([command]) #expect(services.registry.isBound("cmuxConfig.start-claude")) @@ -41,7 +41,7 @@ import Testing let settings = SettingsController(registry: services.registry, design: DesignSettings(), fileURL: url) settings.start() defer { settings.stop() } - let controller = services.configActions! + let controller = services.configActions controller.start(settings: settings) defer { controller.stop() } try await eventually(settings) { services.registry.isBound("cmuxConfig.go") } diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/CtrlDigitEverywhereTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/CtrlDigitEverywhereTests.swift index cbe4558d51b5..73cf2a403860 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/CtrlDigitEverywhereTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/CtrlDigitEverywhereTests.swift @@ -18,7 +18,7 @@ struct CtrlDigitEverywhereTests { @Test func controlDigitsRunTheirActionInEverySurface() throws { let services = M.services() - let router = services.keyRouter! + let router = services.keyRouter var failures: [String] = [] for surface in M.surfaces where !["browser focus mode", "palette open"].contains(surface.name) { for digit in "123456789" { diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/DesktopNotifierTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/DesktopNotifierTests.swift index 073dbb511ad9..25946b0a529f 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/DesktopNotifierTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/DesktopNotifierTests.swift @@ -51,4 +51,21 @@ import Testing #expect(notifier.posted.last?.subtitle == "api server") #expect(notifier.posted.last?.title == "terraform needs approval") } + + /// An OSC 7501 alert banner carries a status badge image; the debug + /// report says which banners had one and gives its PNG, so a live check + /// can prove the badge arrived without Notification Center access. + @MainActor @Test func theDebugReportShowsABannersStatusBadge() { + let notifier = DesktopNotifier() + let badge = Data([0x89, 0x50, 0x4E, 0x47, 1, 2, 3]) + notifier.post(id: "n2", title: "terraform failed", subtitle: "api server", body: "", + surface: 7, workspace: "w1", defaultSound: false, attachment: badge) + notifier.post(id: "n3", title: "plain", body: "text", surface: nil, workspace: nil, defaultSound: false) + #expect(notifier.posted.map(\.attachment) == [badge, nil]) + let reports = notifier.posted.map(DebugNotifications.banner) + #expect(reports[0]["attachment"]?["bytes"]?.doubleValue == Double(badge.count)) + #expect(reports[0]["attachment"]?["png_base64"]?.stringValue == badge.base64EncodedString()) + #expect(reports[1]["attachment"] == .null) + #expect(reports[0]["title"]?.stringValue == "terraform failed") + } } diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/DiffPageTabTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/DiffPageTabTests.swift index 83c8027bcc67..186851327cc2 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/DiffPageTabTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/DiffPageTabTests.swift @@ -47,7 +47,7 @@ struct DiffPageTabTests { /// (they are bound for the diff page, not left unavailable). With no diff page they do not. @Test func aBareKeyOnAFocusedDiffPageRunsItsAction() { let services = ActionBindingCoverageTests.boundServices() - let router = services.keyRouter! + let router = services.keyRouter let diffPage = PageKeyOwnershipTests.context(page: PageDescriptor.diff.id) for (chars, code, action) in [("j", UInt16(38), "diffViewerNextLine"), ("k", UInt16(40), "diffViewerPreviousLine"), ("/", UInt16(44), "diffViewerSearch")] { diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/KeyInterceptionTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/KeyInterceptionTests.swift index c3d835a17940..b881137fb7c0 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/KeyInterceptionTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/KeyInterceptionTests.swift @@ -104,7 +104,7 @@ struct KeyInterceptionTests { @Test func ghosttyKeybindBecomesTheRoutedRegistryAction() throws { let services = ActionBindingCoverageTests.boundServices() - let router = services.keyRouter! + let router = services.keyRouter // A chord no cmux default binds (Ctrl-Cmd-H/J/K/L focus panes). let bind = GhosttyHostKeybind(key: .unicode(UInt32(("b" as Unicode.Scalar).value)), modifiers: [.command, .control], action: .gotoSplit(.left)) diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/KeyOwnershipMatrixTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/KeyOwnershipMatrixTests.swift index d4e19316e136..368c39f8371a 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/KeyOwnershipMatrixTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/KeyOwnershipMatrixTests.swift @@ -167,7 +167,7 @@ struct KeyOwnershipMatrixTests { let services = Self.services() let composing = KeyRouter.Facts(hasMarkedText: true) let agent = Self.focused(.agent, tab: "local-agent:1") - let router = services.keyRouter! + let router = services.keyRouter #expect(router.decide(try K.key("\t", keyCode: 48, [.control]), focus: agent, keyWindow: .content, facts: composing) == .deliver) #expect(router.decide(try K.key("k", keyCode: 40, [.control]), focus: agent, keyWindow: .content, facts: composing) == .deliver) guard case .run(let candidate) = router.decide(try K.key("w", keyCode: 13, [.command]), focus: agent, keyWindow: .content, diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/KeyPrimaryInputTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/KeyPrimaryInputTests.swift index 9c56f4356271..dbd06a8e060d 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/KeyPrimaryInputTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/KeyPrimaryInputTests.swift @@ -19,7 +19,7 @@ struct KeyPrimaryInputTests { @Test func typingOnAnOpenScreenGoesToItsPrimaryInput() throws { let services = M.services() - let router = services.keyRouter! + let router = services.keyRouter let letter = try K.key("h", keyCode: 4, []) let screens: [(String, FocusState)] = [ ("Home", M.focused(M.homeKind, tab: "home-1")), @@ -39,7 +39,7 @@ struct KeyPrimaryInputTests { @Test func navigationKeysAndOtherSurfacesKeepTheirKeys() throws { let services = M.services() - let router = services.keyRouter! + let router = services.keyRouter let home = M.focused(M.homeKind, tab: "home-1") let up = String(UnicodeScalar(NSUpArrowFunctionKey)!) for event in [try K.key(up, keyCode: 126, [.function, .numericPad]), try K.key("\r", keyCode: 36, []), diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/KeyRecorderTraceTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/KeyRecorderTraceTests.swift index febbc332794c..32da1b7f096b 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/KeyRecorderTraceTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/KeyRecorderTraceTests.swift @@ -26,7 +26,7 @@ struct KeyRecorderTraceTests { @MainActor struct UndoToastTraceTests { @Test func commandZOnAnUndoToastIsTracedAsTheToasts() throws { - let router = KeyOwnershipMatrixTests.services().keyRouter! + let router = KeyOwnershipMatrixTests.services().keyRouter let toasts = CmuxToastCenter(clock: ManualClock(), host: CmuxToastHeadlessHost()) router.undoToasts = toasts let window = ToastUndoKeyTests.window() diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/ListNavigationKeyTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/ListNavigationKeyTests.swift index 91b54d76d1b8..467d67087a7a 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/ListNavigationKeyTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/ListNavigationKeyTests.swift @@ -21,7 +21,7 @@ struct ListNavigationKeyTests { } @Test func listKeysMoveTheSelectionWhereAListHasFocus() throws { - let router = M.services().keyRouter! + let router = M.services().keyRouter let surfaces: [(String, FocusState, KeyRouter.Facts)] = [ ("new tab agent dropdown (agent page combobox)", M.focused(.agent, tab: "local-agent:1"), Self.list), ("React page menu", M.focused(.page, tab: "local-page:settings:1"), Self.list), @@ -40,7 +40,7 @@ struct ListNavigationKeyTests { } @Test func terminalsAndPlainFieldsKeepTheirControlKeys() throws { - let router = M.services().keyRouter! + let router = M.services().keyRouter for focus in [M.terminal, M.focused(.agent, tab: "local-agent:1"), M.focused(.terminal, tab: "t1", target: .textField)] { for (event, action) in try Self.keys() { if case .run(let candidate) = router.decide(event, focus: focus, keyWindow: .content, facts: KeyRouter.Facts()) { diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/MarkdownPageKeyTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/MarkdownPageKeyTests.swift index 8e64d929417c..ad6780522113 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/MarkdownPageKeyTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/MarkdownPageKeyTests.swift @@ -25,7 +25,7 @@ struct MarkdownPageKeyTests { } @Test func commandSInAMarkdownPageSavesThroughThePageCommand() throws { - let router = M.services().keyRouter! + let router = M.services().keyRouter let save = try K.key("s", keyCode: 1, [.command]) let decision = router.decide(save, focus: Self.markdownPage, keyWindow: .content, facts: KeyRouter.Facts(pageID: PageDescriptor.markdown.id)) @@ -48,7 +48,7 @@ extension MarkdownPageKeyTests { /// a focused markdown page, through its page commands; elsewhere those /// keys keep their owners. @Test func linkBackAndForwardInAMarkdownPage() throws { - let router = M.services().keyRouter! + let router = M.services().keyRouter let markdown = KeyRouter.Facts(pageID: PageDescriptor.markdown.id) let cases: [(NSEvent, ActionID, String)] = [ (try K.key("k", keyCode: 40, [.command, .shift]), "markdownLink", "link"), diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/OmnibarListKeyTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/OmnibarListKeyTests.swift index f8d1c6156c85..7a3cc011ab03 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/OmnibarListKeyTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/OmnibarListKeyTests.swift @@ -13,7 +13,7 @@ struct OmnibarListKeyTests { typealias M = KeyOwnershipMatrixTests @Test func controlKeysMoveTheOpenSuggestionList() throws { - let router = M.services().keyRouter! + let router = M.services().keyRouter let addressBar = M.focused(.browser, tab: "b1", target: .addressBar) for (event, action) in try ListNavigationKeyTests.keys() { guard case .run(let candidate) = router.decide(event, focus: addressBar, keyWindow: .content, @@ -27,7 +27,7 @@ struct OmnibarListKeyTests { } @Test func aClosedListLeavesTheControlKeysToTheField() throws { - let router = M.services().keyRouter! + let router = M.services().keyRouter let addressBar = M.focused(.browser, tab: "b1", target: .addressBar) for (event, action) in try ListNavigationKeyTests.keys() { if case .run(let candidate) = router.decide(event, focus: addressBar, keyWindow: .content, facts: KeyRouter.Facts()) { diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/PageHistoryKeyTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/PageHistoryKeyTests.swift index 7281e5fe7051..3988fe689340 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/PageHistoryKeyTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/PageHistoryKeyTests.swift @@ -14,7 +14,7 @@ struct PageHistoryKeyTests { static let storePage = M.focused(.page, tab: "local-page:app-store:1") @Test func commandBracketsRunGoBackAndForwardOnAPageWithHistory() throws { - let router = M.services().keyRouter! + let router = M.services().keyRouter let cases: [(String, UInt16, ActionID)] = [("[", 33, "focusHistoryBack"), ("]", 30, "focusHistoryForward")] for (key, code, action) in cases { let event = try K.key(key, keyCode: code, [.command]) @@ -29,7 +29,7 @@ struct PageHistoryKeyTests { } @Test func otherChordsKeepTheirOwnersOnAPageWithHistory() throws { - let router = M.services().keyRouter! + let router = M.services().keyRouter let event = try K.key("s", keyCode: 1, [.command, .shift]) let plain = router.decide(event, focus: Self.storePage, keyWindow: .content, facts: KeyRouter.Facts()) #expect(router.decide(event, focus: Self.storePage, keyWindow: .content, facts: KeyRouter.Facts(showsPageHistory: true)) == plain) diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/PageKeyOwnershipTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/PageKeyOwnershipTests.swift index 81de5fd4b59e..043a500ab91b 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/PageKeyOwnershipTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/PageKeyOwnershipTests.swift @@ -33,7 +33,7 @@ struct PageKeyOwnershipTests { @Test func bareKeysRunOnlyInAnOwningPageWithoutATextField() { let services = KeyOwnershipMatrixTests.services() services.registry.bind("diffViewerNextLine") {} - let router = services.keyRouter! + let router = services.keyRouter let j = Self.key("j", code: 38) #expect(router.bareKeyWinner(j, context: Self.context(page: "cmux.diff"))?.command == "diffViewerNextLine") #expect(router.bareKeyWinner(j, context: Self.context(page: "cmux.diff", editing: true)) == nil, "a text field types j") diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/PageTypeAheadTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/PageTypeAheadTests.swift index 46935164d580..0d68cef32478 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/PageTypeAheadTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/PageTypeAheadTests.swift @@ -16,7 +16,7 @@ struct PageTypeAheadTests { static let loading = KeyRouter.Facts(pageInputPending: true) @Test func printableKeysOnALoadingPageAreQueuedAndChordsStillResolve() throws { - let router = M.services().keyRouter! + let router = M.services().keyRouter let letter = try K.key("h", keyCode: 4, []) for focus in [M.focused(.agent, tab: "local-agent:1"), M.focused(.page, tab: "local-page:keybindings:1")] { #expect(router.decide(letter, focus: focus, keyWindow: .content, facts: Self.loading) == .typeAhead) diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/PresentationChangeSubscribersTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/PresentationChangeSubscribersTests.swift index f4a7ac8ba5fa..d18d63a3dbbb 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/PresentationChangeSubscribersTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/PresentationChangeSubscribersTests.swift @@ -16,7 +16,7 @@ import Testing let before = provider.observation services.cache.release("cx-x3t9-no-such-tab") #expect(provider.observation > before, "the browser host re-reads its tabs on a presentation change") - #expect(services.input.monitor.isPending, "the input monitor checks once the change settles") + #expect(services.input.monitor?.isPending == true, "the input monitor checks once the change settles") } /// Each owner has its own subscription: a later owner adds to the list, diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SheetEscapeTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SheetEscapeTests.swift index 49b31919ea40..2ac787facb60 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SheetEscapeTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SheetEscapeTests.swift @@ -18,7 +18,7 @@ struct SheetEscapeTests { /// Headless: only an unmodified Escape asks to end a sheet, and the key /// is consumed only when a sheet ended. @Test func onlyUnmodifiedEscapeEndsASheet() { - let router = KeyOwnershipMatrixTests.services().keyRouter! + let router = KeyOwnershipMatrixTests.services().keyRouter let window = NSWindow(contentRect: CGRect(x: 0, y: 0, width: 200, height: 100), styleMask: [.titled], backing: .buffered, defer: true) var asked: [NSWindow] = [] var hasSheet = true @@ -36,7 +36,7 @@ struct SheetEscapeTests { @Test(.enabled(if: WindowSession.available, WindowSession.reason)) func escapeCancelsASheetOnTheWindowItReaches() async throws { NSApplication.shared.setActivationPolicy(.accessory) - let router = KeyOwnershipMatrixTests.services().keyRouter! + let router = KeyOwnershipMatrixTests.services().keyRouter let window = NSWindow(contentRect: NSRect(x: -30000, y: -30000, width: 400, height: 300), styleMask: [.titled], backing: .buffered, defer: false) window.isReleasedWhenClosed = false diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SpaceNewEntersOwnWorkspaceTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SpaceNewEntersOwnWorkspaceTests.swift index 8889b795ef42..a96cb279c483 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SpaceNewEntersOwnWorkspaceTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/SpaceNewEntersOwnWorkspaceTests.swift @@ -171,4 +171,55 @@ import Testing machines: services.machines) == [Self.firstKey], "the old space keeps only its workspace") } + + /// `action.run space.new` from a script (no `focus`) goes through the + /// same path as the button: the new space starts with its own workspace, + /// pinned there. The run may not change the view, so the window stays in + /// its space on its workspace, and the current space never lists the + /// new workspace (cx-f8aw, nxdog78-v1: workspace-3 showed in the + /// current space). + @Test func scriptedNewSpaceGetsItsOwnWorkspaceWithoutMovingTheView() async throws { + let daemon = try RoomsDaemon() + defer { daemon.stop() } + let services = ActionBindingCoverageTests.boundServices() + services.windows.ordersWindowsIn = false + services.daemon.start(makeConnection: { daemon.connection() }) + defer { + for controller in services.windows.controllers { controller.window?.close() } + services.daemon.shutdownConnection() + } + try await Self.waitUntil("home daemon loaded with rooms") { + services.daemon.store.isLoaded && services.daemon.store.personal.isLoaded && services.daemon.store.workspaces.count == 1 + } + let window = try #require(services.windows.openWindow(workspaces: [Self.firstKey])) + services.windows.didActivate(window) + services.windows.reconcileMembership() + #expect(window.state.profileID == .defaultProfile) + + let run = RegistryControlBridge(registry: services.registry).performActionTracked(ControlActionRequest( + actionID: "space.new", origin: "script", focus: false)) + #expect(run.outcome == .ran, "space.new: \(run.outcome)") + + try await Self.waitUntil("the new space's workspace is created, pinned and mirrored") { + services.daemon.store.workspaces.count == 2 + && daemon.state.value.withLock { $0.rooms.count == 2 && $0.pins.count == 1 } + } + let (room, newKey, pins) = daemon.state.value.withLock { state in + (state.rooms[1].id, state.workspaces[1].key, state.pins.map { "\($0.key)=\($0.room)" }) + } + #expect(pins == ["\(newKey)=\(room)"], "the new workspace must be pinned to the new space, pins: \(pins)") + try await Self.waitUntil("the window lists the new workspace") { + services.windows.registry.members(of: window.state.id).contains(newKey) + } + for task in run.work { #expect(await task.value == nil, "space.new work failed") } + for _ in 0..<50 { await Task.yield() } + #expect(window.state.profileID == .defaultProfile, "a script run must not switch the window's space") + #expect(window.state.workspaceID == Self.firstKey, "a script run must not change the shown workspace") + #expect(WindowProfiles.visible(services.windows.registry.members(of: window.state.id), profile: .defaultProfile, + machines: services.machines) == [Self.firstKey], + "the current space must not list the new space's workspace") + #expect(WindowProfiles.visible(services.windows.registry.members(of: window.state.id), profile: ProfileID(rawValue: room), + machines: services.machines) == [newKey], + "the new space holds its own workspace") + } } diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/StaticLiteralTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/StaticLiteralTests.swift new file mode 100644 index 000000000000..a4aa7d495d03 --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/StaticLiteralTests.swift @@ -0,0 +1,39 @@ +import AppKit +import CmuxNextActions +@testable import CmuxNextApp +import Testing + +/// The literals the app builds without a trap (crash program P1b): each one +/// parses, so the non-trapping fallbacks are never taken. +@MainActor +struct StaticURLTests { + @Test(arguments: StaticURL.allCases) + func everyLiteralParses(_ link: StaticURL) throws { + let parsed = try #require(URL(string: link.rawValue)) + #expect(link.url == parsed) + #expect(link.url.absoluteString == link.rawValue) + } +} + +@MainActor +struct FunctionKeyCharacterTests { + nonisolated static let codes = [NSLeftArrowFunctionKey, NSRightArrowFunctionKey, NSUpArrowFunctionKey, NSDownArrowFunctionKey, + NSPageUpFunctionKey, NSPageDownFunctionKey, NSHomeFunctionKey, NSEndFunctionKey, NSDeleteFunctionKey] + + @Test(arguments: codes) + func everyFunctionKeyIsOneScalar(_ code: Int) { + #expect(FunctionKeyCharacter.string(code).unicodeScalars.map(\.value) == [UInt32(code)]) + } + + @Test func arrowKeysMatchTheShortcutConstants() { + #expect(FunctionKeyCharacter.string(NSLeftArrowFunctionKey) == Shortcut.leftArrowKey) + #expect(FunctionKeyCharacter.string(NSRightArrowFunctionKey) == Shortcut.rightArrowKey) + #expect(FunctionKeyCharacter.string(NSUpArrowFunctionKey) == Shortcut.upArrowKey) + #expect(FunctionKeyCharacter.string(NSDownArrowFunctionKey) == Shortcut.downArrowKey) + } + + @Test func aCodeOutsideUnicodeGivesEmpty() { + #expect(FunctionKeyCharacter.string(-1) == "") + #expect(FunctionKeyCharacter.string(0xD800) == "") + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/StatusIconSetMenuTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/StatusIconSetMenuTests.swift new file mode 100644 index 000000000000..4525de92ec01 --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/StatusIconSetMenuTests.swift @@ -0,0 +1,33 @@ +import AppKit +import CmuxNextDesign +import Testing +@testable import CmuxNextApp + +/// cx-kxa2: Debug menu > Status Icons lists every candidate set with a check +/// on the chosen one and writes the same Debug Settings tunable. +@MainActor @Suite(.serialized) struct StatusIconSetMenuTests { + @Test func theMenuListsEverySetAndWritesTheTunable() throws { + let store = TunableStore() + store.register([StatusIconSet.tunable.descriptor]) + store.activate(file: nil) + let menu = StatusIconSetMenu() + menu.store = store + let item = menu.makeItem() + #expect(item.title == Strings.menuStatusIcons) + let choices = try #require(item.submenu?.items) + #expect(choices.map { $0.representedObject as? String } == StatusIconSet.allCases.map(\.rawValue)) + #expect(choices.map(\.title) == StatusIconSet.allCases.map(\.tunableTitle)) + #expect(choices.first { $0.state == .on }?.representedObject as? String == StatusIconSet.symbols.rawValue) + + menu.select(.badges) + #expect(StatusIconSet.tunable.value(in: store) == .badges) + menu.menuNeedsUpdate(try #require(item.submenu)) + #expect(choices.first { $0.state == .on }?.representedObject as? String == "badges") + + menu.select(.symbols) + #expect(store.override(StatusIconSet.tunable.key) == nil, "choosing the default removes the override") + #expect(StatusIconSet.tunable.value(in: store) == .symbols) + menu.select(.current) + #expect(StatusIconSet.tunable.value(in: store) == .current, "the original dots stay one choice away") + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/StatusNotificationImageIconSetTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/StatusNotificationImageIconSetTests.swift new file mode 100644 index 000000000000..06cd6bce101a --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/StatusNotificationImageIconSetTests.swift @@ -0,0 +1,24 @@ +import AppKit +import CmuxNextBridge +import CmuxNextDesign +import Testing +@testable import CmuxNextApp + +/// cx-kxa2: an OSC 7501 notification's badge image draws the chosen status +/// icon set's mark for the reason, with the blocked kind. +@MainActor @Suite struct StatusNotificationImageIconSetTests { + @Test func theBadgeFollowsTheSetAndTheKind() throws { + let current = try #require(StatusNotificationImage.png(.question, set: .current)) + let badges = try #require(StatusNotificationImage.png(.question, set: .badges)) + #expect(current != badges, "the chosen set draws the badge") + let auth = try #require(StatusNotificationImage.png(.auth, set: .badges)) + #expect(auth != badges, "a candidate set marks question and auth apart") + #expect(StatusNotificationImage.png(.permission, set: .current) == StatusNotificationImage.png(.question, set: .current), + "the default set keeps one mark for every blocked kind") + for reason in ProgramStatusNotification.Reason.allCases { + for set in StatusIconSet.allCases { + #expect(StatusNotificationImage.png(reason, set: set) != nil, "\(reason) \(set)") + } + } + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/TerminalClipboardDialogKeyTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/TerminalClipboardDialogKeyTests.swift index 90219e7a49aa..4aba0dde50b3 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/TerminalClipboardDialogKeyTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/TerminalClipboardDialogKeyTests.swift @@ -26,7 +26,7 @@ import Testing let right = NSView(frame: NSRect(x: 400, y: 0, width: 400, height: 600)) let leftTerminal = Focusable(frame: NSRect(x: 0, y: 0, width: 400, height: 600)) let rightTerminal = Focusable(frame: NSRect(x: 0, y: 0, width: 400, height: 600)) - let router = KeyOwnershipMatrixTests.services().keyRouter! + let router = KeyOwnershipMatrixTests.services().keyRouter var answers: [Bool] = [] private var close: (() -> Void)? diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/ToastUndoKeyTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/ToastUndoKeyTests.swift index 33363665ecbf..8af19ce3e21a 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/ToastUndoKeyTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/ToastUndoKeyTests.swift @@ -22,7 +22,7 @@ struct ToastUndoKeyTests { } @Test func commandZRunsTheNewestUndoToast() { - let router = KeyOwnershipMatrixTests.services().keyRouter! + let router = KeyOwnershipMatrixTests.services().keyRouter let toasts = CmuxToastCenter(clock: ManualClock(), host: CmuxToastHeadlessHost()) router.undoToasts = toasts let window = Self.window() @@ -38,7 +38,7 @@ struct ToastUndoKeyTests { } @Test func withoutAnUndoToastCommandZIsNotTaken() { - let router = KeyOwnershipMatrixTests.services().keyRouter! + let router = KeyOwnershipMatrixTests.services().keyRouter let toasts = CmuxToastCenter(clock: ManualClock(), host: CmuxToastHeadlessHost()) router.undoToasts = toasts let window = Self.window() diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/UpdatedCardFeedTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/UpdatedCardFeedTests.swift new file mode 100644 index 000000000000..610e6f84da82 --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/UpdatedCardFeedTests.swift @@ -0,0 +1,54 @@ +import CmuxNextActions +@testable import CmuxNextApp +import CmuxNextSidebar +@testable import CmuxNextUpdater +import Foundation +import Testing + +/// The "cmux Updated!" card's App side (cx-7py7): the feed fills the card +/// after an update and holds the tip back meanwhile; the rows run the same +/// actions as the palette (`updates.whatsNew`, `app.shareCmux`); the x +/// marks this version seen. +@MainActor @Suite(.serialized) struct UpdatedCardFeedTests { + private func updater(updatedFrom previous: String?) async -> UpdaterService { + let defaults = UserDefaults(suiteName: "updated-card-\(UUID().uuidString)")! // crash-allow: test suite name + let identity = UpdateBuildIdentity(bundleIdentifier: "com.cmuxterm.app.nightly", shortVersion: "0.66.0", build: "100", + minimumSystemVersion: nil, infoFeedURL: nil, hasPublicKey: false) + if let previous { defaults.set(previous, forKey: WhatsNewSeenStore.lastSeenKey) } + let updater = UpdaterService(identity: identity, policy: ManagedUpdatePolicy { false }, defaults: defaults, enableSparkle: false) + await updater.whatsNew.load().value + updater.debugShowTip(TipCatalog.all.first?.id) + return updater + } + + @Test func theCardShowsAfterAnUpdateAndTheTipWaits() async throws { + let updated = await updater(updatedFrom: "0.65.0") + let card = try #require(SidebarCardFeed.updatedCard(updated)) + #expect(card.title == "cmux Updated!") + #expect(card.whatsNewTitle == "See What's New") + #expect(card.shareTitle == "Share cmux") + #expect(SidebarCardFeed.tipCard(updated, registry: nil) == nil, "the tip waits for the Updated card") + updated.whatsNew.dismissUpdated() + #expect(SidebarCardFeed.updatedCard(updated) == nil) + #expect(SidebarCardFeed.tipCard(updated, registry: nil) != nil) + } + + @Test func aFirstInstallShowsNoCard() async { + let fresh = await updater(updatedFrom: nil) + #expect(SidebarCardFeed.updatedCard(fresh) == nil) + } + + @Test func theRowsRunThePaletteActionsAndTheXMarksSeen() async { + let updated = await updater(updatedFrom: "0.65.0") + let registry = ActionRegistry(catalog: ActionCatalog.all) + var ran: [String] = [] + let whatsNewBound = registry.bind("updates.whatsNew", run: { _ in ran.append("updates.whatsNew") }) + let shareBound = registry.bind("app.shareCmux", run: { _ in ran.append("app.shareCmux") }) + #expect(whatsNewBound && shareBound) + SidebarCardFeed.route(.openWhatsNew, registry: registry, updater: updated) + SidebarCardFeed.route(.shareCmux, registry: registry, updater: updated) + #expect(ran == ["updates.whatsNew", "app.shareCmux"]) + SidebarCardFeed.route(.dismissUpdated, registry: registry, updater: updated) + #expect(!updated.whatsNew.showsUpdatedCard) + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/WindowLifecycleTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/WindowLifecycleTests.swift index d9c83d362ed3..08435f480976 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/WindowLifecycleTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextAppTests/WindowLifecycleTests.swift @@ -36,7 +36,7 @@ struct WindowLifecycleTests { } private static func expectConsistent(_ services: AppServices, _ step: String = "") { - let windows = services.windows! + let windows = services.windows #expect(WindowInvariants.problems(windows).isEmpty, "\(step): \(WindowInvariants.problems(windows))") for controller in windows.controllers { #expect(!windows.registry.members(of: controller.state.id).isEmpty, "\(step): \(controller.state.id) shows no workspace") @@ -131,7 +131,7 @@ struct WindowLifecycleTests { // A saved window lists a workspace no machine reports (gone, or its // Cloud machine still connecting): it is kept, but never shown empty. let services = Self.services(workspaces: 1) - let windows = services.windows! + let windows = services.windows windows.transition { registry in registry.openWindow(id: "saved", workspaceIDs: ["00000000-dead-4000-8000-000000000000"]) } @@ -173,7 +173,7 @@ struct WindowLifecycleTests { for seed in UInt64(1)...8 { var rng = WindowRegistryRaceTests.Seeded(state: seed) let services = Self.services(workspaces: 4) - let windows = services.windows! + let windows = services.windows windows.openWindow(workspaces: [Self.id(1), Self.id(2)]) windows.openWindow(workspaces: [Self.id(3), Self.id(4)]) windows.reconcileMembership() diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextBookmarksTests/CrashLiteralTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextBookmarksTests/CrashLiteralTests.swift new file mode 100644 index 000000000000..8bd4b46918a7 --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextBookmarksTests/CrashLiteralTests.swift @@ -0,0 +1,10 @@ +import Foundation +import Testing +@testable import CmuxNextBookmarks + +/// Crash program: the cmux:// page address is a literal that must parse. +@MainActor @Suite struct BookmarksCrashLiteralTests { + @Test func pageAddressParses() { + #expect(BookmarkPageAddress.url.absoluteString == BookmarkPageAddress.string) + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextBridgeTests/AgentTurnIndicatorTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextBridgeTests/AgentTurnIndicatorTests.swift index 0847a5f0d807..33c6fe942855 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextBridgeTests/AgentTurnIndicatorTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextBridgeTests/AgentTurnIndicatorTests.swift @@ -137,9 +137,9 @@ struct AgentTurnIndicatorTests { #expect(working.primary?.label == "Build") #expect(SidebarMapping.shared.row(workspace, machine: .local).activity == .working(progress: 0.4)) tab.programStatus.append(ProgramStatusRecord(id: "deploy", state: .blocked, kind: .permission, updatedSeq: 2)) - #expect(StatusMapping.shared.summary(tab).state == .waiting) + #expect(StatusMapping.shared.summary(tab).state == .waiting(kind: .permission)) #expect(TabItemMapping.shared.item(tab, fallbackTitle: "t").status == .needsInput) - #expect(SidebarMapping.shared.row(workspace, machine: .local).activity == .waiting) + #expect(SidebarMapping.shared.row(workspace, machine: .local).activity == .waiting(kind: .permission)) tab.programStatus = [ProgramStatusRecord(state: .idle, updatedSeq: 3)] #expect(StatusMapping.shared.summary(tab) == .idle) } @@ -178,7 +178,7 @@ struct RowWorkingSlotTests { tabs[0].programStatus = [ProgramStatusRecord(state: .working, updatedSeq: 1)] tabs[1].programStatus = [ProgramStatusRecord(state: .blocked, kind: .question, updatedSeq: 2)] let row = SidebarMapping.shared.row(workspace, machine: .local) - #expect(row.activity == .waiting) + #expect(row.activity == .waiting(kind: .question)) #expect(row.agentWorking) } } diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextBridgeTests/ProgramStatusNotificationTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextBridgeTests/ProgramStatusNotificationTests.swift index f302f8fbf74c..902c3b3ea526 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextBridgeTests/ProgramStatusNotificationTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextBridgeTests/ProgramStatusNotificationTests.swift @@ -66,4 +66,16 @@ struct ProgramStatusNotificationTests { #expect(ProgramStatusNotification.Reason.failed.indicator == .error) #expect(ProgramStatusNotification.Reason.done.indicator == .success) } + + /// The session events stream can deliver a record after its alert (live + /// run 1008-201829-3d11f5: two of twenty banners had no badge), so the app + /// holds an alert-shaped notification until its record arrives. + @Test func alertShapedTextIsRecognizedBeforeItsRecordArrives() { + #expect(ProgramStatusNotification.looksLikeAlert(title: "Login needs sign-in", level: .warning)) + #expect(ProgramStatusNotification.looksLikeAlert(title: "Build failed", level: .error)) + #expect(ProgramStatusNotification.looksLikeAlert(title: "deploy is done", level: .info)) + #expect(!ProgramStatusNotification.looksLikeAlert(title: "Build failed", level: .warning)) + #expect(!ProgramStatusNotification.looksLikeAlert(title: "nine", level: .info)) + #expect(!ProgramStatusNotification.looksLikeAlert(title: "needs approval", level: .warning), "a name comes first") + } } diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextBridgeTests/StatusBlockedKindMappingTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextBridgeTests/StatusBlockedKindMappingTests.swift new file mode 100644 index 000000000000..1055bd108add --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextBridgeTests/StatusBlockedKindMappingTests.swift @@ -0,0 +1,45 @@ +import CmuxNextDesign +import CmuxNextTabs +import Testing +@testable import CmuxNextBridge +@testable import CmuxNextDaemon + +/// cx-kxa2: the OSC 7501 blocked kind (permission, question, auth) reaches the +/// indicator state the sidebar row and the tab badge draw, so a status icon +/// set can mark each kind apart. +@MainActor +struct StatusBlockedKindMappingTests { + @Test func aBlockedQuestionReachesTheRowAndTheTab() throws { + let store = try BridgeFixture.store() + let workspace = try #require(store.sidebarSections.flatMap(\.workspaces).first { $0.displayName == "beta" }) + let tab = try #require(workspace.screens.flatMap(\.panes).flatMap(\.tabs).first) + tab.programStatus = [ProgramStatusRecord(id: "ask", state: .blocked, kind: .question, title: "Which branch?", updatedSeq: 1)] + #expect(StatusMapping.shared.summary(tab).state == .waiting(kind: .question)) + #expect(StatusMapping.shared.blockedKind(tab) == .question) + #expect(SidebarMapping.shared.row(workspace, machine: .local).activity == .waiting(kind: .question)) + let item = TabItemMapping.shared.item(tab, fallbackTitle: "t") + #expect(item.status == .needsInput) + #expect(item.blockedKind == .question) + // The plan of a candidate set sees the kind; the default set does not change. + let state = SidebarMapping.shared.row(workspace, machine: .local).activity + #expect(StatusIndicatorPlan.make(state, style: .arc, animates: true, set: .badges) + != StatusIndicatorPlan.make(.waiting, style: .arc, animates: true, set: .badges)) + #expect(StatusIndicatorPlan.make(state, style: .arc, animates: true) == StatusIndicatorPlan.make(.waiting, style: .arc, animates: true)) + } + + @Test func eachKindMapsAndAnUnknownKindIsPlainBlocked() throws { + let store = try BridgeFixture.store() + let tab = try #require(store.workspaces.flatMap(\.screens).flatMap(\.panes).flatMap(\.tabs).first) + for (kind, expected) in [(ProgramStatusRecord.Kind.permission, StatusBlockedKind.permission), (.question, .question), (.auth, .auth)] { + tab.programStatus = [ProgramStatusRecord(state: .blocked, kind: kind, updatedSeq: 1)] + #expect(StatusMapping.shared.summary(tab).state == .waiting(kind: expected)) + } + tab.programStatus = [ProgramStatusRecord(state: .blocked, updatedSeq: 2)] + #expect(StatusMapping.shared.summary(tab).state == .waiting(kind: nil)) + #expect(TabItemMapping.shared.item(tab, fallbackTitle: "t").blockedKind == nil) + // An agent hook that blocks has no kind. + tab.programStatus = [] + tab.setAgent(AgentStatus(surface: 1, state: .blocked)) + #expect(StatusMapping.shared.summary(tab).state == .waiting) + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextBrowserImportTests/ChromiumParserTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextBrowserImportTests/ChromiumParserTests.swift index e7ee392a7834..a8c227198b8a 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextBrowserImportTests/ChromiumParserTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextBrowserImportTests/ChromiumParserTests.swift @@ -140,6 +140,6 @@ import Testing #expect(extensions.map(\.name) == ["Dark Reader", "uBlock Origin"]) #expect(extensions[1].version == "1.60.0") #expect(extensions[0].enabled == false) - #expect(extensions[1].webStoreURL.absoluteString == "https://chromewebstore.google.com/detail/\(ublock)") + #expect(extensions[1].webStoreURL?.absoluteString == "https://chromewebstore.google.com/detail/\(ublock)") } } diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextBrowserTests/CrashLiteralTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextBrowserTests/CrashLiteralTests.swift new file mode 100644 index 000000000000..cd7771145364 --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextBrowserTests/CrashLiteralTests.swift @@ -0,0 +1,13 @@ +import Foundation +import Testing +@testable import CmuxNextBrowser + +/// Crash program: literal URLs and the default profile id are built without a force +/// unwrap; these pin that every literal parses (the /dev/null stand-in never runs). +@MainActor @Suite struct BrowserCrashLiteralTests { + @Test func literalsParse() { + #expect(URL.browserExtensionWebStore.absoluteString == "https://chromewebstore.google.com/category/extensions") + #expect(URL.browserExtensionManagement.absoluteString == "chrome://extensions") + #expect(BrowserProfileID.default.rawValue.uuidString == "8E5C0D1F-2B7A-4F3C-9A61-5D2E7B0C4A11") + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextCloudTests/CloudLogicTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextCloudTests/CloudLogicTests.swift index 088e2287d417..1ab902d8b72d 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextCloudTests/CloudLogicTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextCloudTests/CloudLogicTests.swift @@ -31,6 +31,16 @@ import Testing #expect(config.backend == .localOnly(URL(string: "http://localhost:3811")!)) } + /// A callback scheme from the environment that cannot form a URL used to trap at sign-in; + /// it is ignored and the default scheme is used. + @Test func unusableCallbackSchemeFallsBackToTheDefault() throws { + let config = CloudConfiguration.resolve(bundleID: "b", bundled: ["CMUX_AUTH_CALLBACK_SCHEME": "bad scheme"], + process: [:], isDebugBuild: true) + #expect(config.callbackScheme == "cmux-dev") + let url = config.signInURL(callbackState: "s1") + #expect(url.path == "/handler/native-sign-in") + } + @Test func signInURLNestsTheNativeCallback() throws { let config = CloudConfiguration.resolve(bundleID: "b", bundled: ["CMUX_AUTH_WWW_ORIGIN": "https://web.test", "CMUX_TAG": "My Tag"], process: [:], isDebugBuild: true) diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextCloudTests/CrashLiteralTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextCloudTests/CrashLiteralTests.swift new file mode 100644 index 000000000000..70b4b11a44d7 --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextCloudTests/CrashLiteralTests.swift @@ -0,0 +1,13 @@ +import Foundation +import Testing +@testable import CmuxNextCloud + +/// Crash program: the backend origins are literals that must parse (the /dev/null +/// stand-in never runs). +@Suite struct CloudCrashLiteralTests { + @Test func originsParse() { + #expect(CloudConfiguration.productionOrigin.absoluteString == "https://cmux.com") + #expect(CloudConfiguration.stackOrigin.absoluteString == "https://api.stack-auth.com") + #expect(CloudConfiguration.localDevelopmentOrigin.absoluteString == "http://localhost:3777") + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextCloudTests/MacInstallIdentityTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextCloudTests/MacInstallIdentityTests.swift new file mode 100644 index 000000000000..398bc6c44edd --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextCloudTests/MacInstallIdentityTests.swift @@ -0,0 +1,230 @@ +import CmuxInstallAuthCore +@testable import CmuxNextCloud +import Foundation +import Testing + +/// cx-wb5.64: the Mac app's Cloud install principal. It registers kind mac +/// with the mac grant at sign-in, mints install tokens without the Stack +/// session afterwards, and revokes the install at sign-out. A development +/// build keeps its key and records in 0600 files (no Keychain prompt per +/// rebuild); a signed build keeps the key in the Secure Enclave. +/// One install.register call, as the fake owner saw it. +private struct Registration: Sendable, Equatable { + var kind: String? + var platform: String? + var opClasses: [String]? + var keyX: String? +} + +private actor FakeOwner: InstallAuthTransport { + var registered: [Registration] = [] + var revoked: [String] = [] + var mints = 0 + var sessionCalls = 0 + /// While set, install.register waits until ``releaseRegister()``. + private var holdRegister: CheckedContinuation? + private var holding = false + private var heldWaiters: [CheckedContinuation] = [] + + func holdRegisters() { holding = true } + func registerHeld() async { + if holdRegister != nil { return } + await withCheckedContinuation { heldWaiters.append($0) } + } + func releaseRegister() { + holding = false + holdRegister?.resume() + holdRegister = nil + } + + nonisolated func post(_ path: String, json: Data, bearer: String?, headers: [String: String]) async throws -> (status: Int, body: Data) { + let body = try JSONSerialization.jsonObject(with: json) as? [String: Any] ?? [:] + if path == "/v1/ops", body["op"] as? String == "install.register" { await waitIfHeld() } + return try await handle(path, json, bearer) + } + + private func waitIfHeld() async { + guard holding else { return } + await withCheckedContinuation { continuation in + holdRegister = continuation + for waiter in heldWaiters { waiter.resume() } + heldWaiters = [] + } + } + + private func reply(_ object: [String: Any], _ status: Int = 200) throws -> (status: Int, body: Data) { + (status, try JSONSerialization.data(withJSONObject: object)) + } + + private func handle(_ path: String, _ json: Data, _ bearer: String?) throws -> (status: Int, body: Data) { + let body = try JSONSerialization.jsonObject(with: json) as? [String: Any] ?? [:] + switch path { + case "/v1/ops": + // A session token names its Stack user: "session" is stack_1, "session-" is . + guard let bearer, bearer.hasPrefix("session") else { return try reply(["code": "auth.unauthenticated"], 401) } + let stackUser = bearer == "session" ? "stack_1" : String(bearer.dropFirst("session-".count)) + sessionCalls += 1 + let params = body["params"] as? [String: Any] ?? [:] + switch body["op"] as? String { + case "user.ensure": return try reply(["ok": true, "value": ["id": "user_\(stackUser)", "stack_user_id": stackUser]]) + case "install.revoke": + revoked.append(params["install"] as? String ?? "") + return try reply(["ok": true, "value": ["id": params["install"] ?? ""]]) + default: + registered.append(Registration(kind: params["kind"] as? String, platform: params["platform"] as? String, + opClasses: params["op_classes"] as? [String], + keyX: (params["public_jwk"] as? [String: String])?["x"])) + return try reply(["ok": true, "value": ["id": "inst_\(registered.count)"]]) + } + case "/v1/auth/challenge": + let install = body["install"] as? String ?? "" + guard !revoked.contains(install) else { return try reply(["code": "auth.forbidden"], 403) } + return try reply(["nonce": String(repeating: "a", count: 32), "message_prefix": "cmux-auth-v1\ndevelopment\n\(install)\n"]) + case "/v1/auth/token": + mints += 1 + let payload = try JSONSerialization.data(withJSONObject: ["iss": "https://cmux-api/development", "n": mints]) + let token = "eyJhbGciOiJFUzI1NiJ9.\(payload.base64EncodedString().replacingOccurrences(of: "=", with: "").replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_")).c2ln" + return try reply(["access_token": token, "expires_at": Date().addingTimeInterval(600).timeIntervalSince1970 * 1000]) + default: + return try reply([:], 404) + } + } +} + +private func temporaryDirectory() -> URL { + let url = FileManager.default.temporaryDirectory.appendingPathComponent("mac-install-\(UUID().uuidString)", isDirectory: true) + return url +} + +private func identity(_ owner: FakeOwner, _ directory: URL) -> MacInstallIdentity { + MacInstallIdentity(store: .files(directory: directory), transport: owner, deviceName: "cmux-test-mac", clientVersion: "1.0.0") +} + +@Suite struct MacInstallIdentityTests { + @Test func signInRegistersAMacInstallWithTheMacGrantAndMintsAToken() async throws { + let owner = FakeOwner(), directory = temporaryDirectory() + let mac = identity(owner, directory) + try await mac.signedIn(stackUser: "stack_1", session: { "session" }) + let registered = await owner.registered + #expect(registered.count == 1) + #expect(registered.first?.kind == "mac") + #expect(registered.first?.platform == "macos") + #expect(registered.first?.opClasses == ["read", "mutate-own", "mutate-shared", "cloud-link"]) + #expect(await owner.mints == 1) + #expect(try await mac.installToken().hasPrefix("eyJ")) + } + + @Test func aRestartedAppMintsWithoutTheSessionAndWithoutRegisteringAgain() async throws { + let owner = FakeOwner(), directory = temporaryDirectory() + try await identity(owner, directory).signedIn(stackUser: "stack_1", session: { "session" }) + let sessionCalls = await owner.sessionCalls + let restarted = identity(owner, directory) + try await restarted.signedIn(stackUser: "stack_1", session: { throw CancellationError() }) + #expect(await owner.registered.count == 1) + #expect(await owner.sessionCalls == sessionCalls) + #expect(await owner.mints == 2) + } + + @Test func signOutRevokesTheInstallAndForgetsItsKeyAndRecord() async throws { + let owner = FakeOwner(), directory = temporaryDirectory() + let mac = identity(owner, directory) + try await mac.signedIn(stackUser: "stack_1", session: { "session" }) + await mac.signOut(stackUser: "stack_1", session: { "session" }) + #expect(await owner.revoked == ["inst_1"]) + await #expect(throws: MacInstallIdentity.Failure.signedOut) { try await mac.installToken() } + // The session ends (the app's observer unbinds); the next sign-in + // registers a new install with a new key. + await mac.unbind() + try await mac.signedIn(stackUser: "stack_1", session: { "session" }) + let keys = await owner.registered.map(\.keyX) + #expect(keys.count == 2 && keys[0] != keys[1]) + } + + @Test func aDevelopmentStoreKeepsItsFilesOwnerOnly() async throws { + let owner = FakeOwner(), directory = temporaryDirectory() + try await identity(owner, directory).signedIn(stackUser: "stack_1", session: { "session" }) + let mode = { (url: URL) in (try? FileManager.default.attributesOfItem(atPath: url.path)[.posixPermissions] as? Int) ?? -1 } + #expect(mode(directory) == 0o700) + let files = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil) + #expect(!files.isEmpty) + for file in files { #expect(mode(file) == 0o600, "\(file.lastPathComponent)") } + } +} + +@Suite struct MacInstallIdentityReviewTests { + /// Release builds call the API Worker (cloud-api.cmux.dev), never the web + /// origin; a development build may override it. + @Test func installCallsGoToTheAPIWorker() { + let release = CloudConfiguration.resolve(bundleID: "com.cmuxterm.app", bundled: [:], process: [:], isDebugBuild: false) + #expect(release.ownerAPIBaseURL(environment: ["CMUX_NEXT_FEED_API_URL": "https://evil.test"]).absoluteString == "https://cloud-api.cmux.dev") + let staging = CloudConfiguration.resolve(bundleID: "test.dev", bundled: ["CMUX_VM_API_BASE_URL": "https://dev.test"], process: [:], isDebugBuild: true) + #expect(staging.ownerAPIBaseURL(environment: [:]).absoluteString == "https://cloud-api-staging.cmux.dev") + #expect(staging.ownerAPIBaseURL(environment: ["CMUX_NEXT_FEED_API_URL": "http://127.0.0.1:8787"]).absoluteString == "http://127.0.0.1:8787") + } + + @Test func aSignOutDuringRegistrationLeavesNothingThatCanMint() async throws { + let owner = FakeOwner(), directory = temporaryDirectory() + let mac = identity(owner, directory) + await owner.holdRegisters() + let signIn = Task { try await mac.signedIn(stackUser: "stack_1", session: { "session" }) } + await owner.registerHeld() + await mac.signOut(stackUser: "stack_1", session: { "session" }) + await owner.releaseRegister() + _ = try? await signIn.value + await #expect(throws: MacInstallIdentity.Failure.signedOut) { try await mac.installToken() } + // Nothing on disk lets a restarted app mint for that install. + let restarted = identity(owner, directory) + let mintsBefore = await owner.mints + await #expect(throws: (any Error).self) { + try await restarted.signedIn(stackUser: "stack_1", session: { throw CancellationError() }) + } + #expect(await owner.mints == mintsBefore) + } + + @Test func twoStackUsersEachKeepTheirOwnKey() async throws { + let owner = FakeOwner(), directory = temporaryDirectory() + let mac = identity(owner, directory) + try await mac.signedIn(stackUser: "ada", session: { "session-ada" }) + try await mac.signedIn(stackUser: "bob", session: { "session-bob" }) + // Ada again, without a session: her key and record still mint. + try await mac.signedIn(stackUser: "ada", session: { throw CancellationError() }) + let registered = await owner.registered + #expect(registered.count == 2) + #expect(registered[0].keyX != registered[1].keyX) + } + + @Test func onlyADebugBuildWithoutATeamUsesTheFileStore() { + let directory = temporaryDirectory() + #expect(!MacInstallStore.forApp(directory: directory, service: "s", team: nil, isDebugBuild: true).usesSecureEnclave) + #expect(MacInstallStore.forApp(directory: directory, service: "s", team: nil, isDebugBuild: false).usesSecureEnclave) + #expect(MacInstallStore.forApp(directory: directory, service: "s", team: "ABCDE12345", isDebugBuild: true).usesSecureEnclave) + } +} + +@Suite struct MacInstallIdentitySignOutTests { + /// A sign-out before this launch bound the user (the record and key come + /// from an earlier launch) still revokes that install. + @Test func aSignOutWithNothingBoundRevokesTheStoredInstall() async throws { + let owner = FakeOwner(), directory = temporaryDirectory() + try await identity(owner, directory).signedIn(stackUser: "stack_1", session: { "session" }) + let relaunched = identity(owner, directory) + await relaunched.signOut(stackUser: "stack_1", session: { "session" }) + #expect(await owner.revoked == ["inst_1"]) + } + + /// Between this sign-out and the session's end, a late sign-in callback + /// registers nothing. + @Test func noRegistrationBetweenSignOutAndTheEndOfTheSession() async throws { + let owner = FakeOwner(), directory = temporaryDirectory() + let mac = identity(owner, directory) + await mac.signOut(stackUser: "stack_1", session: { "session" }) + await #expect(throws: MacInstallIdentity.Failure.signedOut) { + try await mac.signedIn(stackUser: "stack_1", session: { "session" }) + } + #expect(await owner.registered.isEmpty) + // The session ended (unbind); the next sign-in registers again. + await mac.unbind() + try await mac.signedIn(stackUser: "stack_1", session: { "session" }) + #expect(await owner.registered.count == 1) + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextCodeRouterTests/CrashLiteralTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextCodeRouterTests/CrashLiteralTests.swift new file mode 100644 index 000000000000..59a29141cf27 --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextCodeRouterTests/CrashLiteralTests.swift @@ -0,0 +1,12 @@ +import Foundation +import Testing +@testable import CmuxNextCodeRouter + +/// Crash program: the local server defaults are literals that must parse. +@Suite struct CodeRouterCrashLiteralTests { + @Test func localServerDefaultsParse() { + #expect(ProviderDetector.ollamaDefault.absoluteString == "http://127.0.0.1:11434") + #expect(ProviderDetector.lmStudioDefault.absoluteString == "http://127.0.0.1:1234") + #expect(KeychainProviderKeyStore.service(bundleID: "") == "com.cmuxterm.app.ai-provider-keys") + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextDesignTests/CrashLiteralTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextDesignTests/CrashLiteralTests.swift new file mode 100644 index 000000000000..f44536dca97f --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextDesignTests/CrashLiteralTests.swift @@ -0,0 +1,12 @@ +import Foundation +import Testing +@testable import CmuxNextDesign + +/// Crash program: every backdrop's museum page is a literal that must parse. +@MainActor @Suite struct DesignCrashLiteralTests { + @Test func everyBackdropSourceParses() { + for art in BackdropArt.allCases { + #expect(art.sourceURL.host == "www.metmuseum.org", "\(art)") + } + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextDesignTests/StatusIconSetTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextDesignTests/StatusIconSetTests.swift new file mode 100644 index 000000000000..bb5bb8525ce3 --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextDesignTests/StatusIconSetTests.swift @@ -0,0 +1,138 @@ +import AppKit +import Testing +@testable import CmuxNextDesign + +/// cx-kxa2 (Lawrence 2026-10-08: "make sure we have better notif icons for +/// osc 7501 things ... make sure i can try a bunch of different icons so we +/// can search for the best one together"). Status icon candidate sets: the +/// default keeps today's marks exactly, every other set draws every state, +/// and an OSC 7501 blocked kind (permission, question, auth) reaches the plan. +@MainActor @Suite struct StatusIconSetTests { + /// The states a set restyles, with the blocked kinds. + static let states: [StatusIndicatorState] = [ + .working, .waiting(kind: .permission), .waiting(kind: .question), .waiting(kind: .auth), .waiting, .success, .error, .idle, + ] + + static func table(_ set: StatusIconSet) -> [StatusIndicatorPlan] { + states.map { StatusIndicatorPlan.make($0, style: .arc, animates: true, set: set) } + } + + /// Lawrence picked Symbols as the default (2026-10-09); `current` stays + /// the original drawing, byte for byte, and a plain config value keeps it. + @Test func symbolsIsTheDefaultAndCurrentIsTodaysDrawing() { + #expect(StatusIconSet.tunable.defaultValue == .symbols) + #expect(StatusIndicatorConfig().iconSet == .current) + let all: [StatusIndicatorState] = Self.states + [.busy, .busy(progress: 0.3), .paused(progress: nil), .paused(progress: 0.5), + .working(progress: 0.4)] + for state in all { + for style in StatusIndicatorStyle.allCases { + for animates in [true, false] { + #expect(StatusIndicatorPlan.make(state, style: style, animates: animates, set: .current) + == StatusIndicatorPlan.make(state, style: style, animates: animates), "\(state) \(style)") + } + } + } + // Today's marks, whatever the blocked kind. + for kind in StatusBlockedKind.allCases { + #expect(StatusIndicatorPlan.make(.waiting(kind: kind), style: .arc, animates: true) + == StatusIndicatorPlan(glyph: .dot, animation: nil, tint: .attention)) + } + #expect(StatusIndicatorPlan.make(.working, style: .arc, animates: true) == StatusIndicatorPlan(glyph: .dots, animation: .wave, tint: .accent)) + #expect(StatusIndicatorPlan.make(.error, style: .arc, animates: true) == StatusIndicatorPlan(glyph: .dot, animation: nil, tint: .danger)) + #expect(StatusIndicatorPlan.make(.success, style: .arc, animates: true) == StatusIndicatorPlan(glyph: .check, animation: nil, tint: .success)) + } + + @Test func atLeastEightSetsAndNoTwoDrawAlike() { + #expect(StatusIconSet.allCases.count >= 8) + let tables = StatusIconSet.allCases.map(Self.table) + for i in tables.indices { + for j in tables.indices where j > i { + #expect(tables[i] != tables[j], "\(StatusIconSet.allCases[i]) and \(StatusIconSet.allCases[j]) draw the same") + } + } + #expect(Set(StatusIconSet.allCases.map(\.tunableTitle)).count == StatusIconSet.allCases.count) + } + + @Test func everyCandidateSetMarksEachBlockedKindApart() { + for set in StatusIconSet.allCases where set != .current { + let kinds = StatusBlockedKind.allCases.map { StatusIndicatorPlan.make(.waiting(kind: $0), style: .arc, animates: true, set: set) } + #expect(Set(kinds).count == kinds.count, "\(set): permission, question and auth read apart") + for state in Self.states { + let plan = StatusIndicatorPlan.make(state, style: .arc, animates: true, set: set) + #expect((plan.glyph == .none) == (state == .idle), "\(set) \(state)") + // Colors come from the theme roles only. + switch state { + case .waiting: #expect(plan.tint == .attention, "\(set) \(state)") + case .error: #expect(plan.tint == .danger) + case .success: #expect(plan.tint == .success) + case .working: #expect(plan.tint == .accent) + default: break + } + } + // Loading stays the loading style's; known progress stays a ring. + for state: StatusIndicatorState in [.busy, .busy(progress: 0.3), .paused(progress: nil)] { + #expect(StatusIndicatorPlan.make(state, style: .arc, animates: true, set: set) + == StatusIndicatorPlan.make(state, style: .arc, animates: true)) + } + #expect(StatusIndicatorPlan.make(.working(progress: 0.4), style: .arc, animates: true, set: set).glyph == .ring(progress: 0.4)) + // Still hosts (occluded, Reduce Motion) animate nothing. + for state in Self.states { + #expect(StatusIndicatorPlan.make(state, style: .arc, animates: false, set: set).animation == nil) + } + } + } + + @Test func theSetIsADebugSettingsTunable() { + #expect(StatusIndicatorTunables.all.contains { $0.key == StatusIconSet.tunable.key }) + #expect(StatusIndicatorConfig(iconSet: .badges).iconSet == .badges) + } + + /// The exported image comes from the same drawing as the live layer, so + /// notifications can attach it: every set draws every visible state. + @Test func everySetExportsAnImageForEveryState() throws { + for set in StatusIconSet.allCases { + for state in Self.states where state != .idle { + let image = try #require(set.image(state: state, pointSize: 16, appearance: NSAppearance(named: .darkAqua)), "\(set) \(state)") + #expect(image.size == NSSize(width: 16, height: 16)) + let cg = try #require(image.cgImage(forProposedRect: nil, context: nil, hints: nil)) + #expect(Self.inked(cg) > 8, "\(set) \(state) draws ink") + } + #expect(set.image(state: .idle, pointSize: 16) == nil) + } + let kind = try #require(StatusIconSet.badges.image(state: .waiting, kind: .question, pointSize: 16)? + .cgImage(forProposedRect: nil, context: nil, hints: nil)) + let plain = try #require(StatusIconSet.badges.image(state: .waiting, pointSize: 16)? + .cgImage(forProposedRect: nil, context: nil, hints: nil)) + #expect(Self.pixels(kind) != Self.pixels(plain), "the kind argument reaches the drawing") + } + + @Test func aCandidateMarkUsesOneLayerAndPulsesWhileWorking() { + let indicator = StatusIndicatorLayer() + indicator.colors = StatusIndicatorLayer.Colors(loading: CGColor(gray: 0.5, alpha: 1), attention: CGColor(gray: 0.6, alpha: 1), + danger: CGColor(gray: 0.3, alpha: 1), success: CGColor(gray: 0.7, alpha: 1)) + indicator.frame = CGRect(x: 0, y: 0, width: 12, height: 12) + let config = StatusIndicatorConfig(iconSet: .badges) + indicator.apply(.make(.waiting(kind: .auth), style: .arc, animates: true, set: .badges), config: config) + #expect(indicator.liveSublayerCount == 1) + if Motion.animatesLoops { + indicator.apply(.make(.working, style: .arc, animates: true, set: .badges), config: config) + #expect(indicator.runningAnimation != nil) + } + indicator.apply(.hidden, config: config) + #expect(indicator.liveSublayerCount == 0) + } + + static func pixels(_ image: CGImage) -> [UInt8] { + let width = image.width, height = image.height + var bytes = [UInt8](repeating: 0, count: width * height * 4) + let context = CGContext(data: &bytes, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, + space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) + context?.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height)) + return bytes + } + + static func inked(_ image: CGImage) -> Int { + let bytes = pixels(image) + return stride(from: 3, to: bytes.count, by: 4).filter { bytes[$0] > 50 }.count + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextHistoryTests/CrashLiteralTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextHistoryTests/CrashLiteralTests.swift new file mode 100644 index 000000000000..553f697c0bde --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextHistoryTests/CrashLiteralTests.swift @@ -0,0 +1,10 @@ +import Foundation +import Testing +@testable import CmuxNextHistory + +/// Crash program: the cmux:// page addresses are literals that must parse. +@MainActor @Suite struct PageAddressCrashLiteralTests { + @Test func pageAddressesParse() { + #expect(HistoryPageAddress.url.absoluteString == HistoryPageAddress.string) + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextHomeTests/HomeToastPlacementTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextHomeTests/HomeToastPlacementTests.swift new file mode 100644 index 000000000000..218605e4c955 --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextHomeTests/HomeToastPlacementTests.swift @@ -0,0 +1,31 @@ +import AppKit +import CmuxNextDesign +@testable import CmuxNextHome +import Testing + +/// Lawrence (hmdm7 shots, 2026-10-08): a toast ("Recovered unsaved changes +/// in main.ts (src) Open X") sat on the Home composer's "+" button. A toast +/// never covers the composer or its buttons: it goes above the composer, at +/// every Home width, the narrowest too. +@MainActor @Suite(.serialized) struct HomeToastPlacementTests { + @Test(arguments: [628.0, 360.0]) + func aToastNeverCoversTheComposer(width: Double) async throws { + let (window, view, _) = await HomeFirstRunTests.view() + defer { window.close() } + window.setContentSize(NSSize(width: width, height: 700)) + view.frame = window.contentView?.bounds ?? .zero + view.layoutSubtreeIfNeeded() + let toastView = CmuxToastView(toast: CmuxToast(id: "recovered", message: "Recovered unsaved changes in main.ts (src)", + action: .init(title: "Open"))) + let host = CmuxToastOverlayHost() + host.show(toastView, in: window, slot: 0, windowGone: {}) + defer { host.hide(toastView) } + toastView.layoutSubtreeIfNeeded() + // Overlay panel coordinates are the window's own. + let toast = toastView.frame + let fieldTop = view.transcript.fieldTop + let composer = view.convert(NSRect(x: 0, y: fieldTop, width: view.bounds.width, height: view.bounds.height - fieldTop), to: nil) + #expect(toast.height > 0) + #expect(!toast.intersects(composer), "the toast \(toast) covers the composer \(composer) at width \(width)") + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextLayoutTests/LayoutRootClipTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextLayoutTests/LayoutRootClipTests.swift new file mode 100644 index 000000000000..e72d51f3ab1d --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextLayoutTests/LayoutRootClipTests.swift @@ -0,0 +1,71 @@ +import AppKit +import Testing +@testable import CmuxNextLayout + +/// A strip column that scrolls past the layout's leading edge is cut at that +/// edge: nothing of it draws over the window sidebar beside the layout, on +/// screen (the layer mask) and in AppKit's own rendering (`cacheDisplay`, the +/// path of `debug.window_snapshot`). Guard for preflight nxdog71-v2, whose +/// in-process snapshot showed web page content of the scrolled-out column +/// under the sidebar while the screen showed it cut (a capture artifact of +/// web content, not a layout overlap). +@MainActor +struct LayoutRootClipTests { + private let screen = LayoutScreen(id: "s", name: "", layout: .columns([ + LayoutColumn(id: "c1", width: 0.8, root: .leaf("a")), + LayoutColumn(id: "c2", width: 0.8, root: .leaf("b")), + ])) + static let sidebarWidth: CGFloat = 200 + + @Test func aColumnScrolledPastTheLeadingEdgeNeverDrawsOverTheSidebar() async throws { + let model = LayoutModel(screens: [screen], activeScreenID: "s", focusedPane: "a") + let provider = SolidPaneProvider() + let window = NSView(frame: CGRect(x: 0, y: 0, width: 1100, height: 400)) + let root = LayoutRootView(model: model, contentProvider: provider) + root.frame = CGRect(x: Self.sidebarWidth, y: 0, width: 900, height: 400) + window.addSubview(root) + root.layoutSubtreeIfNeeded() + + // Focus the second column: the strip scrolls the first one partly out + // past the leading edge (the sidebar side), as Show Memory does. + model.focus("b") + await waitUntil { (root.frame(of: "a")?.minX ?? 0) < -50 && (root.frame(of: "a")?.maxX ?? 0) > 50 } + let frame = try #require(root.frame(of: "a")) + #expect(frame.minX < 0 && frame.maxX > 0, "the first column must be partly scrolled out (\(frame))") + + let rep = try #require(window.bitmapImageRepForCachingDisplay(in: window.bounds)) + window.cacheDisplay(in: window.bounds, to: rep) + let scale = CGFloat(rep.pixelsWide) / window.bounds.width + func isColumn(atX x: CGFloat) -> Bool { + guard let color = rep.colorAt(x: Int(x * scale), y: rep.pixelsHigh / 2)?.usingColorSpace(.deviceRGB) else { return false } + // sRGB red reads about 1.00/0.15/0.00 in device RGB. + return color.alphaComponent > 0.9 && color.redComponent > 0.9 && color.greenComponent < 0.3 && color.blueComponent < 0.1 + } + // The visible part of the column draws (the probe works) ... + #expect(isColumn(atX: Self.sidebarWidth + 10)) + // ... and none of it draws in the sidebar. + for x in stride(from: CGFloat(5), to: Self.sidebarWidth, by: 15) { + #expect(!isColumn(atX: x), "the scrolled-out column draws over the sidebar at x=\(x)") + } + withExtendedLifetime(provider) {} + } + + private func waitUntil(sourceLocation: SourceLocation = #_sourceLocation, _ condition: () -> Bool) async { + for _ in 0..<1000 where !condition() { await Task.yield() } + if !condition() { Issue.record("the condition never held", sourceLocation: sourceLocation) } + } +} + +/// A pane that paints itself solid red (drawn, so `cacheDisplay` renders it). +private final class SolidPaneView: NSView { + override func draw(_ dirtyRect: NSRect) { + NSColor(srgbRed: 1, green: 0, blue: 0, alpha: 1).setFill() + dirtyRect.fill() + } +} + +private final class SolidPaneProvider: LayoutPaneContentProvider { + func makeContentView(for pane: PaneID) -> NSView { + pane == "a" ? SolidPaneView() : NSView() + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextOnboardingTests/CrashLiteralTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextOnboardingTests/CrashLiteralTests.swift new file mode 100644 index 000000000000..36116131340a --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextOnboardingTests/CrashLiteralTests.swift @@ -0,0 +1,11 @@ +import Foundation +import Testing +@testable import CmuxNextOnboarding + +/// Crash program: the System Settings deep links are literals that must parse. +@MainActor @Suite struct OnboardingCrashLiteralTests { + @Test func systemSettingsLinksParse() { + #expect(URL.systemSettingsFullDiskAccess.scheme == "x-apple.systempreferences") + #expect(URL.systemSettingsDefaultBrowser.scheme == "x-apple.systempreferences") + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextRemoteBrowserTests/RemoteBrowserSurfacesTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextRemoteBrowserTests/RemoteBrowserSurfacesTests.swift index 622fad6286bd..bc8cd53678a2 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextRemoteBrowserTests/RemoteBrowserSurfacesTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextRemoteBrowserTests/RemoteBrowserSurfacesTests.swift @@ -45,6 +45,26 @@ struct RemoteBrowserSurfacesTests { #expect(!page.subviews.contains(view)) } + /// CEF API 21 kinds: a datalist/autofill list and an extension popup are + /// child views over the page like a page popup, each on its own stream. + @Test(arguments: ["autofill", "extension_popup"]) + func viewsSurfaceKindsShowAsChildViewsAtTheirAnchor(kind: String) throws { + let (surfaces, page, streams, _) = Self.make() + let body = RemoteRdJSON.object([ + "t": .string("rb.surface.show"), "surface": .int(11), "stream": .int(4), "kind": .string(kind), + "anchor": .object(["x": .int(8), "y": .int(40), "width": .int(180), "height": .int(90)]), + "width": .int(360), "height": .int(180), + ]) + surfaces.apply(try #require(RbSurfaceMessage(body))) + let view = try #require(surfaces.view(of: 11)) + #expect(view.superview === page) + #expect(view.frame == CGRect(x: 8, y: 40, width: 180, height: 90)) + #expect(streams.requested == [4]) + #expect(surfaces.kind(of: 11) == kind) + surfaces.apply(.hide(surface: 11)) + #expect(surfaces.view(of: 11) == nil) + } + @Test func closingTheSessionRemovesEverySurface() throws { let (surfaces, page, _, _) = Self.make() surfaces.apply(try #require(RbSurfaceMessage(Self.show))) diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextRemoteTests/CrashLiteralTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextRemoteTests/CrashLiteralTests.swift new file mode 100644 index 000000000000..fcab04ca0ea1 --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextRemoteTests/CrashLiteralTests.swift @@ -0,0 +1,10 @@ +import Foundation +import Testing +@testable import CmuxNextRemote + +/// Crash program: the install base is a literal that must parse. +@Suite struct RemoteCrashLiteralTests { + @Test func installBaseParses() { + #expect(RemoteInstallPlan.base.absoluteString == "https://files.cmux.com/cmux-tui") + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/FlatSidebarTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/FlatSidebarTests.swift index 039fd315c6da..67c91e4353db 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/FlatSidebarTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/FlatSidebarTests.swift @@ -52,12 +52,12 @@ import Testing let h = MinimalChromeTests.Harness(sections: fixture()) let header = try #require(h.sidebar.list.rowViews[.group(g1)] as? GroupHeaderRowView) header.layoutSubtreeIfNeeded() - // S1: the caret leads at the workspace titles' inset (a loose row's - // title, both in their row's coordinates) and the name follows it. + // The chip (cx-rcby): it starts near the workspace titles' inset and + // the collapse chevron ends it, after the name. let row = try #require(h.sidebar.list.rowViews[.workspace(id("b"))] as? WorkspaceRowView) row.layoutSubtreeIfNeeded() - #expect(header.titleFrame.minX > row.titleFrame.minX, "header \(header.titleFrame.minX) row \(row.titleFrame.minX)") - #expect(header.disclosureFrame.midX < header.titleFrame.minX) - #expect(header.titleFont == SidebarStyle.headerFont) + #expect(header.labelFrame.minX <= row.titleFrame.minX, "chip \(header.labelFrame.minX) row \(row.titleFrame.minX)") + #expect(header.disclosureFrame.midX > header.titleFrame.maxX) + #expect(header.titleFont.pointSize >= 11, "the name's type scales with the row") } } diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/GroupChipEditorTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/GroupChipEditorTests.swift new file mode 100644 index 000000000000..45c062e4ebd5 --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/GroupChipEditorTests.swift @@ -0,0 +1,197 @@ +import AppKit +import CmuxNextDesign +import Testing +@testable import CmuxNextSidebar + +/// cx-rcby (Lawrence 2026-10-08: "new group is very ugly, the creation +/// animation is very bad too. make groups like this", the Chrome tab group +/// chip and its editor bubble): the header is a chip with no member count, +/// a more button on hover and the chevron; the chip, the more button and a +/// right-click open one editor whose name, color and rows go out as intents +/// and App actions; a group the store gives a new id keeps its header view, +/// so a new group moves in once. +@MainActor @Suite struct GroupChipEditorTests { + final class Harness { + let window: NSWindow + let sidebar: SidebarView + var intents: [SidebarIntent] = [] + var items: [(GroupID, String)] = [] + + init(sections: [SidebarSection] = fixture()) { + let model = SidebarModel(sections: sections, activeWorkspaceID: id("a")) + sidebar = SidebarView(model: model) + window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 260, height: 600), styleMask: [.borderless], backing: .buffered, defer: true) + window.isReleasedWhenClosed = false + sidebar.frame = window.contentView!.bounds + window.contentView!.addSubview(sidebar) + sidebar.layoutSubtreeIfNeeded() + sidebar.list.reload(animated: false) + sidebar.list.groupEditor.ordersFront = false + model.onIntent = { [unowned self] intent in + self.intents.append(intent) + model.apply(intent) + } + sidebar.list.onGroupEditorItem = { [unowned self] group, item in self.items.append((group, item)) } + } + + var list: SidebarListView { sidebar.list } + + func header(_ group: GroupID) throws -> GroupHeaderRowView { + let view = try #require(list.rowViews[.group(group)] as? GroupHeaderRowView) + view.layoutSubtreeIfNeeded() + return view + } + } + + @Test func theHeaderShowsNoMemberCount() throws { + let h = Harness() + let header = try h.header(g1) + let shown = header.allSubviews.compactMap { $0 as? NSTextField }.filter { !$0.isHidden }.map(\.stringValue) + #expect(!shown.contains("3"), "no count on the chip row: \(shown)") + } + + @Test func theMoreButtonShowsOnHoverOnlyAndTheNameKeepsItsWidth() throws { + let h = Harness() + let header = try h.header(g1) + header.isHovered = false + header.layoutSubtreeIfNeeded() + let rest = header.titleFrame, chip = header.labelFrame + #expect(header.moreButton.alphaValue == 0) + header.isHovered = true + header.layoutSubtreeIfNeeded() + #expect(header.moreButton.alphaValue == 1) + #expect(header.titleFrame == rest) + #expect(header.labelFrame == chip, "the chip keeps its width on hover") + #expect(header.labelFrame.contains(NSPoint(x: header.moreButton.frame.midX, y: header.moreButton.frame.midY)), "inside the chip") + } + + @Test func theMoreButtonAndARightClickOpenTheEditor() throws { + let h = Harness() + let header = try h.header(g1) + header.isHovered = true + header.layoutSubtreeIfNeeded() + header.moreButton.performClick(nil) + #expect(h.list.groupEditor.shownGroup == g1) + h.list.groupEditor.hide() + #expect(h.list.groupEditor.shownGroup == nil) + + let row = try #require(h.list.displayed.row(for: .group(g1))) + let point = h.list.convert(NSPoint(x: h.list.frame(for: row).midX, y: h.list.frame(for: row).midY), to: nil) + let event = try #require(NSEvent.mouseEvent(with: .rightMouseDown, location: point, modifierFlags: [], timestamp: 0, + windowNumber: h.window.windowNumber, context: nil, eventNumber: 0, clickCount: 1, pressure: 1)) + #expect(h.list.menu(for: event) == nil, "the editor, not a menu") + #expect(h.list.groupEditor.shownGroup == g1) + } + + @Test func theEditorOpensWithTheNameAndTheChosenColor() throws { + let h = Harness() + h.list.groupEditing.open(g1) + let bubble = try #require(h.list.groupEditor.bubble) + #expect(bubble.nameField.stringValue == "G1") + #expect(bubble.swatches.map(\.color) == GroupColor.editorOrder) + #expect(bubble.swatches.first { $0.isChosen }?.color == .purple) + #expect(try h.header(g1).isEditing) + } + + @Test func nameAndColorGoOutAsIntentsAndClosingEndsTheEditor() throws { + let h = Harness() + h.list.groupEditing.open(g1) + let bubble = try #require(h.list.groupEditor.bubble) + bubble.pick(.red) + #expect(h.intents.contains(.setGroupColor(g1, .red))) + bubble.nameField.stringValue = "Frontend" + bubble.dismiss() + let tail = h.intents.suffix(2) + #expect(Array(tail) == [.renameGroup(g1, "Frontend"), .groupEditorEnded(g1)], "\(h.intents)") + #expect(h.list.groupEditor.shownGroup == nil) + #expect(try h.header(g1).isEditing == false) + } + + @Test func anEmptyOrUnchangedNameSendsNoRename() throws { + let h = Harness() + h.list.groupEditing.open(g1) + let bubble = try #require(h.list.groupEditor.bubble) + bubble.nameField.stringValue = " " + bubble.dismiss() + #expect(!h.intents.contains { if case .renameGroup = $0 { true } else { false } }) + #expect(h.intents.last == .groupEditorEnded(g1)) + } + + @Test func theMoreRowReachesTheAppToo() throws { + let h = Harness() + h.list.groupEditing.open(g1) + let bubble = try #require(h.list.groupEditor.bubble) + bubble.press(SidebarGroupEditing.moreActionsItem) + #expect(h.items.map(\.1) == [SidebarGroupEditing.moreActionsItem], "the App keeps a group made empty for the menu's action") + } + + /// A member dragged into another group that already existed ends the + /// editor; only a group that just appeared can carry the shown one on. + @Test func theEditorDoesNotFollowItsMemberIntoAnotherGroup() throws { + let h = Harness() + h.list.groupEditing.open(g1) + var sections = fixture() + sections[1].nodes.remove(at: 1) + // local is now: a, b, G2, c; G2 takes G1's members. + sections[1].nodes[2] = .group(SidebarGroup(id: g2, name: "G2", color: .green, workspaces: [w("h1"), w("h2"), w("g1"), w("g2"), w("g3")])) + h.list.model.setSections(sections) + h.list.reload(animated: false) + #expect(h.list.groupEditor.shownGroup == nil) + } + + @Test func aRowGoesToTheAppWithTheGroupAndClosesTheEditor() throws { + let h = Harness() + h.list.groupEditing.open(g1) + let bubble = try #require(h.list.groupEditor.bubble) + bubble.press("workspaceGroup.newWorkspace") + #expect(h.items.map(\.0) == [g1]) + #expect(h.items.map(\.1) == ["workspaceGroup.newWorkspace"]) + #expect(h.list.groupEditor.shownGroup == nil) + } + + @Test func theStandardRowsAreTheChromeEditorsActions() { + let ids = SidebarContainerView.standardGroupEditorItems().map { $0.map(\.id) } + #expect(ids == [ + ["workspaceGroup.newWorkspace", "workspaceGroup.moveToNewWindow", "workspaceGroup.closeWorkspaces"], + ["workspaceGroup.ungroup", "workspaceGroup.delete", SidebarGroupEditing.moreActionsItem], + ]) + } + + /// The home daemon names a group the sidebar made: the same header view + /// carries on under the new id, and an open editor follows it. + @Test func aReidentifiedGroupKeepsItsHeaderAndItsEditor() throws { + let h = Harness() + let before = try h.header(g1) + h.list.groupEditing.open(g1) + var sections = fixture() + let renamed = GroupID("G1-daemon") + sections[1].nodes[1] = .group(SidebarGroup(id: renamed, name: "G1", color: .purple, workspaces: [w("g1"), w("g2"), w("g3")])) + h.list.model.setSections(sections) + h.list.reload(animated: true) + #expect(h.list.rowViews[.group(renamed)] === before, "one header view, no leave and arrive") + #expect(h.list.rowViews[.group(g1)] == nil) + #expect(h.list.groupEditor.shownGroup == renamed) + } + + @Test func aClickInTheListClosesTheEditorAndEndsIt() throws { + let h = Harness() + h.list.groupEditing.open(g1) + let row = try #require(h.list.displayed.row(for: .workspace(id("b")))) + let point = h.list.convert(NSPoint(x: h.list.frame(for: row).midX, y: h.list.frame(for: row).midY), to: nil) + let event = try #require(NSEvent.mouseEvent(with: .leftMouseDown, location: point, modifierFlags: [], timestamp: 0, + windowNumber: h.window.windowNumber, context: nil, eventNumber: 0, clickCount: 1, pressure: 1)) + h.list.mouseDown(with: event) + #expect(h.list.groupEditor.shownGroup == nil) + #expect(h.intents.contains(.groupEditorEnded(g1))) + } + + @Test func theEditorClosesWhenItsGroupIsGone() throws { + let h = Harness() + h.list.groupEditing.open(g1) + var sections = fixture() + sections[1].nodes.remove(at: 1) + h.list.model.setSections(sections) + h.list.reload(animated: false) + #expect(h.list.groupEditor.shownGroup == nil) + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/GroupHeaderClickTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/GroupHeaderClickTests.swift index 1adf8ce9c623..968d62ae0ee2 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/GroupHeaderClickTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/GroupHeaderClickTests.swift @@ -1,10 +1,12 @@ import AppKit +import CmuxNextDesign import Testing @testable import CmuxNextSidebar -/// A click on a group header toggles it at once (cx-qno.17: no double-click -/// wait); renaming is Return on the focused header or the menu, so a double -/// click is one toggle, never a collapse and re-expand flicker. +/// A group header is a chip (cx-rcby, Lawrence 2026-10-08, the Chrome tab +/// group chip): a click on the chip opens the group editor; the chevron and +/// the rest of the row toggle at once (cx-qno.17: no double-click wait), so +/// a double click is one toggle, never a collapse and re-expand flicker. @MainActor @Suite struct GroupHeaderClickTests { final class Harness { let window: NSWindow @@ -20,6 +22,7 @@ import Testing window.contentView!.addSubview(sidebar) sidebar.layoutSubtreeIfNeeded() sidebar.list.reload(animated: false) + sidebar.list.groupEditor.ordersFront = false model.onIntent = { [unowned self] intent in self.intents.append(intent) model.apply(intent) @@ -32,11 +35,19 @@ import Testing intents.filter { if case .toggleCollapse = $0 { true } else { false } }.count } - /// A point on the group's name, in window coordinates. - func namePoint(_ group: GroupID) -> NSPoint { + /// A point on the row past the chip, in window coordinates. + func rowPoint(_ group: GroupID) -> NSPoint { let row = list.displayed.row(for: .group(group))! let frame = list.frame(for: row) - return list.convert(NSPoint(x: frame.minX + frame.width * 0.5, y: frame.midY), to: nil) + return list.convert(NSPoint(x: frame.maxX - Metrics.space4, y: frame.midY), to: nil) + } + + /// A point on the group's name inside its chip, in window coordinates. + func namePoint(_ group: GroupID) -> NSPoint { + let view = list.rowViews[.group(group)] as! GroupHeaderRowView + view.layoutSubtreeIfNeeded() + let local = NSPoint(x: view.titleFrame.midX, y: view.bounds.midY) + return list.convert(list.convert(local, from: view), to: nil) } func click(_ point: NSPoint, count: Int) { @@ -49,28 +60,39 @@ import Testing } } - @Test func singleClickOnGroupNameTogglesAtOnce() { + @Test func aClickOnTheChipOpensTheEditorAndDoesNotToggle() { let h = Harness() h.click(h.namePoint(g1), count: 1) + #expect(h.toggles == 0) + #expect(h.list.groupEditor.shownGroup == g1) + #expect(h.list.model.group(g1)?.isCollapsed == false) + } + + @Test func aClickOnTheRowPastTheChipTogglesAtOnce() { + let h = Harness() + h.click(h.rowPoint(g1), count: 1) #expect(h.toggles == 1, "no double-click wait (cx-qno.17)") #expect(h.list.model.group(g1)?.isCollapsed == true) + #expect(h.list.groupEditor.shownGroup == nil) } - @Test func doubleClickOnGroupNameTogglesOnceAndDoesNotRename() { + @Test func aDoubleClickOnTheRowTogglesOnceAndDoesNotRename() { let h = Harness() - let point = h.namePoint(g1) + let point = h.rowPoint(g1) h.click(point, count: 1) h.click(point, count: 2) #expect(h.toggles == 1, "the second click of a double click is not a second toggle") - #expect(h.list.inlineRename.session == nil, "rename is Return or the menu") + #expect(h.list.inlineRename.session == nil) } @Test func clickOnChevronTogglesImmediately() { let h = Harness() let view = h.list.rowViews[.group(g1)] as! GroupHeaderRowView + view.layoutSubtreeIfNeeded() let local = NSPoint(x: view.disclosureFrame.midX, y: view.bounds.midY) let point = h.list.convert(h.list.convert(local, from: view), to: nil) h.click(point, count: 1) #expect(h.toggles == 1) + #expect(h.list.groupEditor.shownGroup == nil) } } diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/GroupHeaderKeyboardTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/GroupHeaderKeyboardTests.swift index d6811354ad39..5b3fdb425040 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/GroupHeaderKeyboardTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/GroupHeaderKeyboardTests.swift @@ -80,11 +80,12 @@ import Testing #expect(h.model.activeWorkspaceID == id("c"), "the hidden members are skipped") } - @Test func returnOnAFocusedHeaderRenamesTheGroup() { + /// cx-rcby: Return on a focused header opens the group editor. + @Test func returnOnAFocusedHeaderOpensTheGroupEditor() { let h = Harness(active: "g1") h.up() h.enter() - #expect(h.list.inlineRename.session?.key == .group(g1)) - h.list.inlineRename.end(commit: false) + #expect(h.list.groupEditor.shownGroup == g1) + h.list.groupEditor.hide() } } diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/GroupLabelBandTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/GroupLabelBandTests.swift index 5f36840623cd..cb7862bfaa17 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/GroupLabelBandTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/GroupLabelBandTests.swift @@ -3,11 +3,11 @@ import CmuxNextDesign import Testing @testable import CmuxNextSidebar -/// Workspace groups, option B "Color label and band" (Lawrence 2026-10-07: -/// "i like Option B"; spec WORKSPACE-GROUPS-OPTION-A amendment 1): the group -/// name sits in a colored label (the tab-group chip: GroupColor.fill, a -/// neutral chip without a color), and the members carry one continuous band -/// in the group color under the header's caret, indented past it. +/// Workspace groups as Chrome tab group chips (cx-rcby, Lawrence 2026-10-08, +/// after option B of 2026-10-07): the group name sits in a pill chip filled +/// with the group's theme color (neutral without one) that ends in the +/// collapse chevron, and the members carry one thin continuous bar in the +/// group color under the chip's start, indented past it. @MainActor @Suite struct GroupLabelBandTests { @Test func theNameSitsInAColoredLabel() throws { let h = MinimalChromeTests.Harness(sections: fixture()) @@ -16,7 +16,7 @@ import Testing header.updateLayer() let chip = header.labelFrame #expect(chip.width > 0 && chip.height > 0) - #expect(chip.minX > header.disclosureFrame.minX, "the caret leads (S1)") + #expect(chip.contains(NSPoint(x: header.disclosureFrame.midX, y: header.disclosureFrame.midY)), "the chevron ends the chip") #expect(chip.contains(NSPoint(x: header.titleFrame.midX, y: header.titleFrame.midY)), "the name is inside the label") #expect(header.labelFill != nil, "a colored group's label is filled") } @@ -40,11 +40,12 @@ import Testing let loose = try #require(h.sidebar.list.rowViews[.workspace(id("b"))] as? WorkspaceRowView) [header, first, second, loose].forEach { $0.layoutSubtreeIfNeeded() } #expect(loose.titleFrame.minX == SidebarStyle.titleLeading, "a loose row keeps the inset") - #expect(first.titleFrame.minX > header.disclosureFrame.maxX, "member \(first.titleFrame.minX) caret \(header.disclosureFrame.maxX)") + #expect(first.titleFrame.minX > first.groupBandFrame.maxX, "member \(first.titleFrame.minX) bar \(first.groupBandFrame.maxX)") + #expect(first.groupBandFrame.minX >= header.labelFrame.minX, "the bar starts under the chip") // The band fills each member row top to bottom, so adjacent rows join. for row in [first, second] { let band = row.groupBandFrame - #expect(band.width >= 2, "a visible band") + #expect(band.width >= 2 && band.width <= 3, "a thin visible bar") #expect(band.minY <= 0 && band.maxY >= row.bounds.height, "full height \(band) in \(row.bounds)") #expect(band.midX < first.titleFrame.minX) } @@ -68,7 +69,7 @@ import Testing #expect(header.glyph.emojiText == "🚀") #expect(header.labelFrame.contains(NSPoint(x: header.glyph.frame.midX, y: header.glyph.frame.midY)), "the icon is inside the label") #expect(header.glyph.frame.maxX <= header.titleFrame.minX, "the icon leads the name") - #expect(header.labelFrame.width > plainHeader.labelFrame.width, "the label grows by the icon") + #expect(header.titleFrame.minX > plainHeader.titleFrame.minX, "the name moves past the icon") #expect(header.titleFrame.width >= header.titleIntrinsicWidth, "the name still draws whole") } diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/MinimalSidebarS1Tests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/MinimalSidebarS1Tests.swift index 552e6cac30b4..bb1c96677466 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/MinimalSidebarS1Tests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/MinimalSidebarS1Tests.swift @@ -53,14 +53,17 @@ import Testing // MARK: Group caret - @Test func theGroupCaretSitsLeftOfTheNameAndShowsAtRest() throws { + /// cx-rcby: the chevron ends the group chip, after the name, like the + /// Chrome tab group chip, and shows without hover. + @Test func theGroupChevronEndsTheChipAndShowsAtRest() throws { let h = MinimalChromeTests.Harness(sections: fixture()) let header = try #require(h.sidebar.list.rowViews[.group(g1)] as? GroupHeaderRowView) header.isHovered = false header.layoutSubtreeIfNeeded() - #expect(header.disclosureFrame.midX < header.titleFrame.minX, "caret \(header.disclosureFrame) name \(header.titleFrame)") - let caret = header.subviews.compactMap { $0 as? NSImageView }.first { !$0.isHidden && $0.frame.maxX <= header.titleFrame.minX } - #expect(caret != nil, "the caret shows on an expanded group without hover") + #expect(header.disclosureFrame.midX > header.titleFrame.maxX, "chevron \(header.disclosureFrame) name \(header.titleFrame)") + #expect(header.labelFrame.contains(NSPoint(x: header.disclosureFrame.midX, y: header.disclosureFrame.midY)), "inside the chip") + let chevron = header.subviews.compactMap { $0 as? NSImageView }.first { !$0.isHidden && $0.frame.minX >= header.titleFrame.maxX } + #expect(chevron != nil, "the chevron shows on an expanded group without hover") } // MARK: Retired items diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/SidebarDropCommitTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/SidebarDropCommitTests.swift index cf79cf9b8153..af98b372339c 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/SidebarDropCommitTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/SidebarDropCommitTests.swift @@ -146,4 +146,28 @@ import Testing full.layoutSubtreeIfNeeded() #expect(full.showsChevron, "a machine with workspaces still folds") } + + /// Coordinator decision 2026-10-08 (cx-odqn): pins go after the built-in + /// rows. Home and App Store stay at the top of their section; a row + /// dropped on either one takes the first index after them. + @Test func aPinDroppedOnHomeGoesAfterTheBuiltInRows() throws { + let rowsSection = LayoutSection(id: LayoutSectionID("sec_top_rows"), region: .top, look: .builtIn, items: [ + LayoutItem(id: LayoutItemID("home"), ref: SidebarLayoutDocument.homeRef), + LayoutItem(id: LayoutItemID("store"), ref: .app("cmux/app-store")), + SidebarPinDropTests.tile("w1"), + ]) + let region = SidebarRegionView(region: .top) + region.update(SidebarRegionView.Content(sections: [rowsSection], infos: [:], collapsed: [], look: .quiet, + metrics: SidebarPinDropTests.metrics, drawsLines: true), width: 240) + func frame(_ id: String) throws -> CGRect { try tileFrame(id, in: region) } + func drop(_ point: CGPoint) -> Int? { + SidebarRegionDrop.target(at: point, layout: region.layoutResult, sections: [rowsSection], + gap: SidebarPinDropTests.metrics.sectionGap)?.index + } + let home = try frame("home"), store = try frame("store"), w1 = try frame("w1") + #expect(drop(CGPoint(x: home.midX, y: home.maxY - 2)) == 2, "the bottom half of Home: after App Store") + #expect(drop(CGPoint(x: home.midX, y: home.minY + 2)) == 2, "the top half of Home: after App Store") + #expect(drop(CGPoint(x: store.midX, y: store.midY + 2)) == 2) + #expect(drop(CGPoint(x: w1.midX, y: w1.maxY - 2)) == 3, "past a pin: after it") + } } diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/SidebarOntoGroupTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/SidebarOntoGroupTests.swift index 17691228f34e..ae12deb14e27 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/SidebarOntoGroupTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/SidebarOntoGroupTests.swift @@ -66,35 +66,33 @@ import Testing #expect(groups[0].workspaces.map(\.id) == [id("x"), id("y")]) #expect(groups[0].name == SidebarGroup.named("")) #expect(groups[0].color != .grey) - #expect(h.list.inlineRename.session?.key == .group(groups[0].id), "the new group renames in place") - let field = try #require(h.list.inlineRename.session?.field) - let header = try h.frame(.group(groups[0].id)), title = try #require(h.list.rowViews[.group(groups[0].id)]).titleFrame - #expect(abs(field.frame.midY - (header.minY + title.midY)) < 1, "the rename field sits on the header's settled title") - - h.list.inlineRename.end(commit: false) + // cx-rcby: the new group's editor opens on it (the Chrome flow). + #expect(h.list.groupEditor.shownGroup == groups[0].id, "the new group's editor opens") + h.list.groupEditor.hide() h.window.undoManager?.undo() #expect(h.groups(cloudSection).isEmpty) #expect(shape(h.model.sections, cloudSection) == "x y") } - /// The home daemon makes the group under its own id: the rename follows - /// the group its row moved to and keeps what was typed. + /// The home daemon makes the group under its own id: the editor follows + /// the group its row moved to and keeps what was typed (cx-rcby). @Test func theRenameFollowsTheGroupTheStoreMadeInItsPlace() throws { let h = Harness() defer { h.window.close() } try h.drag(.workspace(id("y")), over: .workspace(id("x")), at: 0.5) h.list.finishDrag() let made = try #require(h.groups(cloudSection).first) - try #require(h.list.inlineRename.session?.key == .group(made.id)) - h.list.inlineRename.session?.field.stringValue = "Infra" + try #require(h.list.groupEditor.shownGroup == made.id) + let bubble = try #require(h.list.groupEditor.bubble) + bubble.nameField.stringValue = "Infra" let stored = GroupID.make() h.model.send(.ungroup(made.id)) h.model.send(.createGroup(stored, name: made.name, color: made.color, workspaces: [id("x"), id("y")], anchor: id("x"))) h.list.reload(animated: false) - #expect(h.list.inlineRename.session?.key == .group(stored)) - #expect(h.list.inlineRename.session?.field.stringValue == "Infra") - #expect(h.list.subviews.filter { $0 is NSTextField }.count == 1, "no orphaned field") + #expect(h.list.groupEditor.shownGroup == stored) + #expect(bubble.nameField.stringValue == "Infra", "what was typed stays") + h.list.groupEditor.hide() } @Test func theBandsEdgesAreStickyOnceEntered() throws { diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/SidebarUpdatedCardTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/SidebarUpdatedCardTests.swift new file mode 100644 index 000000000000..8491d19391a3 --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/SidebarUpdatedCardTests.swift @@ -0,0 +1,96 @@ +import AppKit +import CmuxNextDesign +import Testing +@testable import CmuxNextSidebar + +/// The "cmux Updated!" card (cx-7py7) in the bottom-left card slot: on the +/// tip card's glass, above the footer. A staged update wins the slot, then +/// the Updated card, then the tip, which waits. +@MainActor @Suite(.serialized) struct SidebarUpdatedCardTests { + static let card = SidebarUpdatedCard(title: "cmux Updated!", whatsNewTitle: "See What's New", shareTitle: "Share cmux", + dismissLabel: "Hide Until the Next Update") + + private func sidebar(intents: ((SidebarIntent) -> Void)? = nil) -> SidebarView { + let model = SidebarModel() + model.onIntent = intents + let view = SidebarView(model: model) + view.frame = NSRect(x: 0, y: 0, width: 260, height: 700) + view.layoutSubtreeIfNeeded() + return view + } + + private func settle(_ view: SidebarView, until done: () -> Bool) async { + for _ in 0..<200 where !done() { await Task.yield() } + view.needsLayout = true + view.layoutSubtreeIfNeeded() + } + + @Test func theCardShowsAboveTheFooterAndTheFooterNeverMoves() async { + let view = sidebar() + let footer = view.footer.frame + #expect(view.updatedCardView.isHidden && view.updatedCardView.frame == .zero) + view.model.updatedCard = Self.card + await settle(view) { view.updatedCardView.card == Self.card } + let card = view.updatedCardView + #expect(!card.isHidden) + #expect(card.frame.height == SidebarUpdatedCardView.height) + #expect(card.frame.maxY <= view.footer.frame.minY) + #expect(view.footer.frame == footer) + #expect(card.shownText == ["cmux Updated!", "See What's New", "Share cmux"]) + view.model.updatedCard = nil + await settle(view) { view.updatedCardView.card == nil } + #expect(card.isHidden && card.frame == .zero) + } + + @Test func theUpdatedCardWinsTheSlotOverTheTip() async { + let view = sidebar() + view.model.tipCard = SidebarTipCardTests.tip + view.model.updatedCard = Self.card + await settle(view) { view.updatedCardView.card != nil && view.tipCardView.tip != nil } + #expect(!view.updatedCardView.isHidden && view.updatedCardView.frame.height > 0) + #expect(view.tipCardView.isHidden && view.tipCardView.frame == .zero, "the tip waits") + view.model.updatedCard = nil + await settle(view) { view.updatedCardView.card == nil } + #expect(!view.tipCardView.isHidden, "the tip comes back once the card goes") + } + + @Test func aStagedUpdateWinsOverTheUpdatedCard() async { + let view = sidebar() + view.model.updatedCard = Self.card + view.model.updateCard = SidebarUpdateCardTests.card + await settle(view) { view.updateCardView.card != nil && view.updatedCardView.card != nil } + #expect(!view.updateCardView.isHidden) + #expect(view.updatedCardView.isHidden && view.updatedCardView.frame == .zero) + } + + @Test func theRowsAndTheXSendTheirIntents() async { + var intents: [SidebarIntent] = [] + let view = sidebar { intents.append($0) } + view.model.updatedCard = Self.card + await settle(view) { view.updatedCardView.card != nil } + view.updatedCardView.whatsNewRow.onPress?() + view.updatedCardView.shareRow.onPress?() + view.updatedCardView.closeButton.onPress?() + #expect(intents == [.openWhatsNew, .shareCmux, .dismissUpdated]) + #expect(view.updatedCardView.closeButton.accessibilityLabel() == "Hide Until the Next Update") + #expect(view.updatedCardView.whatsNewRow.accessibilityLabel() == "See What's New") + #expect(view.updatedCardView.shareRow.accessibilityRole() == .button) + } + + /// Same material as the tip card (cx-367y): glass, the lines above it, + /// opaque under Reduce Transparency. + @Test func theCardIsGlassWithTheLinesAboveIt() { + let reduce = ReduceTransparency(system: { false }, changes: NotificationCenter()) + let card = SidebarUpdatedCardView(reduceTransparency: reduce) + card.configure(Self.card) + card.frame = NSRect(x: 0, y: 0, width: 236, height: SidebarUpdatedCardView.height) + card.layoutSubtreeIfNeeded() + #expect(card.surface.frame == card.bounds) + let surfaceIndex = card.subviews.firstIndex(of: card.surface) ?? .max + let linesIndex = card.subviews.firstIndex { card.shareRow.isDescendant(of: $0) } ?? -1 + #expect(linesIndex > surfaceIndex, "the lines sit above the glass") + reduce.override = true + #expect(card.surface.material == .opaque) + reduce.override = nil + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/StatusIconSetSheetTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/StatusIconSetSheetTests.swift new file mode 100644 index 000000000000..10d129288a2b --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/StatusIconSetSheetTests.swift @@ -0,0 +1,320 @@ +import AppKit +import Foundation +import ImageIO +import Metal +import QuartzCore +import Testing +import UniformTypeIdentifiers +@testable import CmuxNextDesign +@testable import CmuxNextSidebar + +/// The status icon candidate sets side by side (cx-kxa2, Lawrence +/// 2026-10-08: "make sure i can try a bunch of different icons so we can +/// search for the best one together"): rows = sets, columns = states, at +/// 10, 12, 16 and 32 pt, in Ghostty's default dark theme and GitHub Light +/// Default, plus real sidebar rows per set. Frames come from `CARenderer` +/// (the Core Animation compositor), so animations, replicators and masks +/// render as on screen. Writes one self-contained HTML file, +/// `/.build/status-icons/contact-sheet.html` (and +/// `$NX_ARTIFACTS/status-icons-contact-sheet.html`). Renderer helpers follow +/// StatusStatesSheetTests (feat-cmux-next-status-icons). +@MainActor @Suite(.serialized) struct StatusIconSetSheetTests { + struct Look { + let name: String + let tokens: ThemeTokens + let input: ThemeInput + } + + static let dark = ThemeInput.ghosttyDefault + static let light = ThemeInput( + background: ThemeRGB(hex: 0xFFFFFF), foreground: ThemeRGB(hex: 0x1F2328), + palette: [ + 0x24292F, 0xCF222E, 0x116329, 0x4D2D00, 0x0969DA, 0x8250DF, 0x1B7C83, 0x6E7781, + 0x57606A, 0xA40E26, 0x1A7F37, 0x633C01, 0x218BFF, 0xA475F9, 0x3192AA, 0x8C959F, + ].map { ThemeRGB(hex: $0) }) + static let looks = [ + Look(name: "Dark (Ghostty default)", tokens: ThemeTokens.derive(from: dark), input: dark), + Look(name: "Light (GitHub Light Default)", tokens: ThemeTokens.derive(from: light), input: light), + ] + + static let states: [(String, StatusIndicatorState)] = [ + ("working", .working), ("blocked: permission", .waiting(kind: .permission)), ("blocked: question", .waiting(kind: .question)), + ("blocked: auth", .waiting(kind: .auth)), ("blocked", .waiting), ("done", .success), ("error", .error), ("idle", .idle), + ("working 40%", .working(progress: 0.4)), + ] + + static let slots: [CGFloat] = [10, 12, 16, 32] + static let fps = 15.0 + static let seconds = 2.4 + + static func colors(_ tokens: ThemeTokens) -> StatusIndicatorLayer.Colors { + StatusIndicatorLayer.Colors( + loading: tokens.textSecondary.nsColor.cgColor, attention: tokens.attention.nsColor.cgColor, + danger: tokens.danger.nsColor.cgColor, success: tokens.success.nsColor.cgColor, + accent: tokens.textPrimary.nsColor.cgColor) + } + + static func text(_ string: String, _ color: CGColor, size: CGFloat, frame: CGRect) -> CATextLayer { + let layer = CATextLayer() + layer.string = string + layer.font = NSFont.systemFont(ofSize: size, weight: .medium) + layer.fontSize = size + layer.foregroundColor = color + layer.contentsScale = 2 + layer.frame = frame + layer.isWrapped = false + layer.truncationMode = .end + return layer + } + + /// One table: rows = sets, columns = states, one slot size. + static func matrix(_ look: Look, slot: CGFloat) -> CALayer { + let colWidth = max(92, slot + 40) + let rowHeight = max(28, slot + 16) + let labelWidth: CGFloat = 150 + let width = labelWidth + CGFloat(states.count) * colWidth + 12 + let height = 26 + CGFloat(StatusIconSet.allCases.count) * rowHeight + 8 + let root = CALayer() + root.isGeometryFlipped = true + root.frame = CGRect(x: 0, y: 0, width: width, height: height) + root.backgroundColor = look.tokens.surfaceBackground.withAlpha(1).nsColor.cgColor + let label = look.tokens.textSecondary.nsColor.cgColor + for (c, state) in states.enumerated() { + root.addSublayer(text(state.0, label, size: 10, frame: CGRect(x: labelWidth + CGFloat(c) * colWidth, y: 6, width: colWidth - 4, height: 16))) + } + for (r, set) in StatusIconSet.allCases.enumerated() { + let y = 26 + CGFloat(r) * rowHeight + root.addSublayer(text(set.tunableTitle, label, size: 11, frame: CGRect(x: 8, y: y + (rowHeight - 14) / 2, width: labelWidth - 8, height: 16))) + let config = StatusIndicatorConfig(iconSet: set) + for (c, state) in states.enumerated() { + let indicator = StatusIndicatorLayer() + root.addSublayer(indicator.layer) + indicator.contentsScale = 2 + indicator.hostIsFlipped = true + indicator.colors = colors(look.tokens) + indicator.frame = CGRect(x: labelWidth + CGFloat(c) * colWidth + 6, y: y + (rowHeight - slot) / 2, width: slot, height: slot) + indicator.apply(.make(state.1, style: .arc, animates: true, set: set), config: config) + keep.append(indicator) + } + } + return root + } + + /// Real sidebar rows in `look`'s theme, drawn with the shared config's set. + static func sidebar(_ look: Look) -> NSView { + func ws(_ n: Int, _ title: String, _ status: String?, _ activity: StatusIndicatorState, unread: UnreadState = .none) -> SidebarWorkspace { + SidebarWorkspace(id: WorkspaceID("icons-\(n)"), title: title, directory: "~/fun/cmux", status: status, + icon: nil, unread: unread, activity: activity) + } + let machine = SidebarMachine(id: .local, name: "This Mac", kind: .local) + let sections = [SidebarSection(kind: .machine(machine), nodes: [ + .workspace(ws(1, "agent working", "Claude: working", .working)), + .workspace(ws(2, "needs permission", "Codex: run rm -rf build?", .waiting(kind: .permission), unread: .dot)), + .workspace(ws(3, "asks a question", "Which branch?", .waiting(kind: .question))), + .workspace(ws(4, "needs sign-in", "gh auth login", .waiting(kind: .auth))), + .workspace(ws(5, "done, unseen", "zig build done in 2m 14s", .success)), + .workspace(ws(6, "error", "Migration failed (exit 1)", .error, unread: .count(1))), + ])] + let model = SidebarModel(sections: sections, activeWorkspaceID: WorkspaceID("icons-0")) + let scope = ThemeScope(level: .room) + scope.setOverride(nil, input: look.input, animated: false) + let sidebar = SidebarView(model: model) + sidebar.frame = NSRect(x: 0, y: 0, width: 240, height: 250) + sidebar.wantsLayer = true + sidebar.appearance = scope.appearance + // An offscreen window (never ordered front) makes AppKit draw the + // rows' layer contents; detached views leave them empty. + let window = NSWindow(contentRect: sidebar.frame, styleMask: [.borderless], backing: .buffered, defer: false) + window.isReleasedWhenClosed = false + window.contentView = sidebar + scope.root(sidebar) + sidebar.layoutSubtreeIfNeeded() + sidebar.list.reload(animated: false) + sidebar.list.setWindowVisible(true) + sidebar.layoutSubtreeIfNeeded() + window.displayIfNeeded() + sidebar.displayIfNeeded() + CATransaction.flush() + scopes.append(scope) + windows.append(window) + return sidebar + } + + static var keep: [StatusIndicatorLayer] = [] + static var scopes: [ThemeScope] = [] + static var windows: [NSWindow] = [] + + /// Renders `layer` with the Core Animation compositor at `count` times, + /// `1 / fps` apart, starting now. + static func frames(of layer: CALayer, count: Int) throws -> [CGImage] { + guard let device = MTLCreateSystemDefaultDevice(), let queue = device.makeCommandQueue() else { throw SheetError.noMetal } + let scale: CGFloat = 2 + let width = Int(layer.bounds.width * scale), height = Int(layer.bounds.height * scale) + let descriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .bgra8Unorm, width: width, height: height, mipmapped: false) + descriptor.usage = [.renderTarget, .shaderRead] + descriptor.storageMode = .managed + guard let texture = device.makeTexture(descriptor: descriptor) else { throw SheetError.noMetal } + let renderer = CARenderer(mtlTexture: texture, options: [ + kCARendererColorSpace: CGColorSpace(name: CGColorSpace.sRGB)!, + kCARendererMetalCommandQueue: queue, + ]) + let host = CALayer() + host.frame = CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height)) + let holder = CALayer() + // Scale about the bottom-left corner, not the center. + holder.anchorPoint = .zero + holder.frame = host.bounds + holder.sublayerTransform = CATransform3DMakeScale(scale, scale, 1) + host.addSublayer(holder) + layer.removeFromSuperlayer() + layer.frame.origin = .zero + holder.addSublayer(layer) + renderer.layer = host + renderer.bounds = host.bounds + // Animations get their begin time when the transaction commits. + CATransaction.flush() + let start = CACurrentMediaTime() + var images: [CGImage] = [] + for index in 0.. Data { + NSBitmapImageRep(cgImage: image).representation(using: .png, properties: [:]) ?? Data() + } + + static func gif(_ images: [CGImage]) -> Data { + let data = NSMutableData() + guard let destination = CGImageDestinationCreateWithData(data, UTType.gif.identifier as CFString, images.count, nil) else { return Data() } + CGImageDestinationSetProperties(destination, [kCGImagePropertyGIFDictionary: [kCGImagePropertyGIFLoopCount: 0]] as CFDictionary) + for image in images { + CGImageDestinationAddImage(destination, image, [kCGImagePropertyGIFDictionary: [kCGImagePropertyGIFDelayTime: 1 / fps]] as CFDictionary) + } + CGImageDestinationFinalize(destination) + return data as Data + } + + static func img(_ data: Data, _ mime: String, width: Int) -> String { + "" + } + + @Test func writesTheContactSheet() throws { + Motion.reduceMotionOverride = false + let previous = StatusIndicatorAppearance.shared.config + defer { + Motion.reduceMotionOverride = nil + StatusIndicatorAppearance.shared.apply(previous) + Self.keep.removeAll() + Self.scopes.removeAll() + Self.windows.forEach { $0.close() } + Self.windows.removeAll() + } + let count = Int(Self.seconds * Self.fps) + var body = "" + var anyMotion = false + for look in Self.looks { + body += "

\(look.name)

" + for slot in Self.slots { + let layer = Self.matrix(look, slot: slot) + let width = Int(layer.bounds.width) + let images = try Self.frames(of: layer, count: count) + // Any frame: one offset can equal a whole spinner period. + let first = Self.png(images[0]) + anyMotion = anyMotion || images.dropFirst().contains { Self.png($0) != first } + body += "

\(Int(slot)) pt slot

\(Self.img(Self.gif(images), "image/gif", width: width))
animated (\(count) frames, \(Int(Self.fps)) fps)
" + body += "
\(Self.img(Self.png(images[0]), "image/png", width: width))
first frame (the still look under Reduce Motion)
" + } + body += "

Sidebar rows (real SidebarView), one per set

" + for set in StatusIconSet.allCases { + var config = previous + config.iconSet = set + StatusIndicatorAppearance.shared.apply(config) + let sidebar = Self.sidebar(look) + guard let layer = sidebar.layer else { continue } + let images = try Self.frames(of: layer, count: count) + body += "
\(Self.img(Self.gif(images), "image/gif", width: 240))
\(set.tunableTitle) (\(set.rawValue))
" + } + body += "
" + } + // The export path (StatusIconSet.image, for notification attachments): + // the same marks drawn still by Core Graphics, 16 pt, in each look. + body += "

Exported still images (StatusIconSet.image, 16 pt)

" + for look in Self.looks { + let scope = ThemeScope(level: .room) + scope.setOverride(nil, input: look.input, animated: false) + var rows = "" + Self.states.map { "\($0.0)" }.joined() + "" + for set in StatusIconSet.allCases { + rows += "\(set.tunableTitle)" + for state in Self.states { + let image = scope.perform { set.image(state: state.1, pointSize: 16, appearance: scope.appearance) } + let data = image.flatMap { $0.cgImage(forProposedRect: nil, context: nil, hints: nil) }.map(Self.png) ?? Data() + rows += "" + (data.isEmpty ? "" : Self.img(data, "image/png", width: 16)) + "" + } + rows += "" + } + let background = look.tokens.surfaceBackground.withAlpha(1).nsColor.usingColorSpace(.sRGB) ?? .black + let hex = String(format: "#%02x%02x%02x", Int(background.redComponent * 255), Int(background.greenComponent * 255), Int(background.blueComponent * 255)) + body += "

\(look.name)

\(rows)
" + Self.scopes.append(scope) + } + var legend = "" + for set in StatusIconSet.allCases { + legend += "\(set.rawValue)\(set.tunableTitle)\(set.summary)" + } + let html = """ + cmux-next status icon candidates + +

Status icon candidates (cx-kxa2)

+

Rendered by the app's own StatusIndicatorLayer and SidebarView, frames from the Core Animation compositor (CARenderer), 2x pixels shown at real size. + Blocked kinds come from OSC 7501 kind (permission, question, auth). Colors are the theme's attention, danger, success and foreground roles. + Pick one in DEV/NIGHTLY: Debug menu > Status Icons, or Debug Settings > Status Indicators > Status icons. The default stays current until one is picked.

+

Motion captured by the compositor: \(anyMotion ? "yes" : "no (stills only on this host)").

+ \(legend)
+ \(body) + + """ + let package = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + let folder = package.appending(path: ".build/status-icons") + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + try Data(html.utf8).write(to: folder.appending(path: "contact-sheet.html")) + if let artifacts = ProcessInfo.processInfo.environment["NX_ARTIFACTS"] { + try Data(html.utf8).write(to: URL(fileURLWithPath: artifacts).appending(path: "status-icons-contact-sheet.html")) + } + // Motion is reported in the sheet, not asserted: the step returns the + // artifact only when green, and some hosts render stills. + #expect(html.contains("image/gif")) + #expect(html.contains("badges")) + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/StatusStatesSheetTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/StatusStatesSheetTests.swift index 768ec1d7db1d..a0e974054e5a 100644 --- a/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/StatusStatesSheetTests.swift +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextSidebarTests/StatusStatesSheetTests.swift @@ -133,17 +133,26 @@ import UniformTypeIdentifiers sidebar.frame = NSRect(x: 0, y: 0, width: 260, height: 420) sidebar.wantsLayer = true sidebar.appearance = scope.appearance + // An offscreen window (never ordered front) makes AppKit draw the + // rows' layer contents; detached views leave them empty. + let window = NSWindow(contentRect: sidebar.frame, styleMask: [.borderless], backing: .buffered, defer: false) + window.isReleasedWhenClosed = false + window.contentView = sidebar scope.root(sidebar) sidebar.layoutSubtreeIfNeeded() sidebar.list.reload(animated: false) sidebar.list.setWindowVisible(true) sidebar.layoutSubtreeIfNeeded() + window.displayIfNeeded() sidebar.displayIfNeeded() + CATransaction.flush() scopes.append(scope) + windows.append(window) return sidebar } static var keep: [StatusIndicatorLayer] = [] + static var windows: [NSWindow] = [] static var scopes: [ThemeScope] = [] /// Renders `layer` with the Core Animation compositor at `count` times, @@ -288,5 +297,7 @@ import UniformTypeIdentifiers #expect(html.contains("image/gif")) Self.keep.removeAll() Self.scopes.removeAll() + Self.windows.forEach { $0.close() } + Self.windows.removeAll() } } diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextTabsTests/TabStatusBadgeIconSetTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextTabsTests/TabStatusBadgeIconSetTests.swift new file mode 100644 index 000000000000..3300ec6c2ad4 --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextTabsTests/TabStatusBadgeIconSetTests.swift @@ -0,0 +1,32 @@ +import AppKit +import CmuxNextDesign +import Testing +@testable import CmuxNextTabs + +/// cx-kxa2: a tab's status badge (needs input, done, failed) draws the +/// chosen status icon set; the default set keeps today's colored dot. +@MainActor @Suite struct TabStatusBadgeIconSetTests { + func cell(_ status: TabStatus, kind: StatusBlockedKind? = nil) -> TabCell { + var item = TabItem(id: TabID("t"), title: "Agent", status: status) + item.blockedKind = kind + return TabCell(item: item) + } + + @Test func theDefaultSetKeepsTheDot() { + let config = StatusIndicatorConfig() + for status in [TabStatus.needsInput, .success, .failure, .none] { + #expect(cell(status).statusBadgePlan(config: config) == nil, "\(status)") + } + } + + @Test func aCandidateSetDrawsTheBadgeStateWithItsKind() throws { + let config = StatusIndicatorConfig(iconSet: .badges) + let question = try #require(cell(.needsInput, kind: .question).statusBadgePlan(config: config)) + #expect(question == StatusIndicatorPlan.make(.waiting(kind: .question), style: .arc, animates: false, set: .badges)) + let auth = try #require(cell(.needsInput, kind: .auth).statusBadgePlan(config: config)) + #expect(auth != question) + #expect(cell(.success).statusBadgePlan(config: config) == StatusIndicatorPlan.make(.success, style: .arc, animates: false, set: .badges)) + #expect(cell(.failure).statusBadgePlan(config: config) == StatusIndicatorPlan.make(.error, style: .arc, animates: false, set: .badges)) + #expect(cell(.none).statusBadgePlan(config: config) == nil, "an unread dot is not a status") + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextUpdaterTests/ShareCmuxTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextUpdaterTests/ShareCmuxTests.swift new file mode 100644 index 000000000000..d0daebf42c29 --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextUpdaterTests/ShareCmuxTests.swift @@ -0,0 +1,59 @@ +import AppKit +import Testing +@testable import CmuxNextUpdater + +/// "Share cmux" (cx-7py7): a centered modal with a title, one line, an +/// editable message that carries the plain public download link, and Copy +/// Link, which copies the message as shown (edits included) and turns into +/// "Copied". The x and Escape close it. No referral tracking. +@MainActor +@Suite struct ShareCmuxTests { + /// Records what Copy Link writes (a fleet step has no pasteboard server; + /// the real-app proof checks the general pasteboard). + private final class Clipboard { + var text: String? + } + + @Test func theMessageCarriesThePlainDownloadLink() { + let message = ShareCmuxView.defaultMessage + #expect(ShareCmuxView.downloadURL.absoluteString == "https://cmux.com/download") + #expect(message.hasSuffix("\n\nhttps://cmux.com/download")) + #expect(!message.contains("?"), "no referral or tracking query") + } + + @Test func copyLinkWritesTheMessageAndShowsCopied() { + let board = Clipboard() + let view = ShareCmuxView { board.text = $0 } + #expect(view.messageText == ShareCmuxView.defaultMessage) + #expect(view.copyButton.button.title == "Copy Link") + view.copyButton.performClick(nil) + #expect(board.text == ShareCmuxView.defaultMessage) + #expect(view.copyButton.button.title == "Copied") + } + + @Test func copyLinkCopiesTheEditedMessage() { + let board = Clipboard() + let view = ShareCmuxView { board.text = $0 } + view.messageText = "Try this terminal: https://cmux.com/download" + view.copyButton.performClick(nil) + #expect(board.text == "Try this terminal: https://cmux.com/download") + } + + @Test func theCloseButtonAndEscapeClose() { + let view = ShareCmuxView { _ in } + var closed = 0 + view.onClose = { closed += 1 } + view.closeButton.performClick(nil) + view.cancelOperation(nil) + #expect(closed == 2) + #expect(view.closeButton.accessibilityLabel() == "Close") + #expect(view.messageView.accessibilityLabel() == "Message") + } + + @Test func theModalShowsItsTitleAndLine() { + let view = ShareCmuxView { _ in } + view.layoutSubtreeIfNeeded() + #expect(view.shownText == ["Share cmux with a Friend", "Send this message with the download link to a friend."]) + #expect(view.frame.width > 0 && view.frame.height > 0) + } +} diff --git a/Packages/macOS/CmuxNext/Tests/CmuxNextUpdaterTests/UpdatedCardTests.swift b/Packages/macOS/CmuxNext/Tests/CmuxNextUpdaterTests/UpdatedCardTests.swift new file mode 100644 index 000000000000..541afd264356 --- /dev/null +++ b/Packages/macOS/CmuxNext/Tests/CmuxNextUpdaterTests/UpdatedCardTests.swift @@ -0,0 +1,99 @@ +import Foundation +import Testing +@testable import CmuxNextUpdater + +/// The "cmux Updated!" card (cx-7py7): it shows once after the installed +/// version moves past the last seen one, never on a first install, and it +/// shares What's New's one seen state: the card's x, the card's What's New +/// row, the palette and the sidebar item all clear the card and the dot. +@MainActor +@Suite struct UpdatedCardTests { + let documents = ["0.65.0", "0.66.0", "0.67.0"].map { WhatsNewFixtures.document($0) } + + private func center(_ version: String, _ defaults: UserDefaults, sources: [any WhatsNewSource]? = nil) async -> WhatsNewCenter { + let center = WhatsNewCenter(currentVersion: version, defaults: defaults, sources: sources ?? [StubWhatsNewSource(documents)]) + await center.load().value + return center + } + + @Test func aFirstInstallShowsNoCard() async { + let fresh = await center("0.66.0", WhatsNewFixtures.defaults()) + #expect(!fresh.showsUpdatedCard) + } + + @Test func aVersionChangeShowsTheCardOnceAndTheDismissalSurvivesARelaunch() async { + let defaults = WhatsNewFixtures.defaults() + _ = await center("0.65.0", defaults) + let updated = await center("0.66.0", defaults) + #expect(updated.showsUpdatedCard) + updated.dismissUpdated() + #expect(!updated.showsUpdatedCard) + #expect(!updated.showsItem, "one seen state: the x also clears the What's New dot") + let relaunched = await center("0.66.0", defaults) + #expect(!relaunched.showsUpdatedCard, "dismissed for this version") + } + + @Test func theDismissalIsPerVersion() async { + let defaults = WhatsNewFixtures.defaults() + _ = await center("0.65.0", defaults) + await center("0.66.0", defaults).dismissUpdated() + let next = await center("0.67.0", defaults) + #expect(next.showsUpdatedCard, "the next version shows the card again") + } + + @Test func openingWhatsNewClearsTheCard() async { + let defaults = WhatsNewFixtures.defaults() + _ = await center("0.65.0", defaults) + let updated = await center("0.66.0", defaults) + updated.open() + #expect(!updated.showsUpdatedCard) + #expect(!(await center("0.66.0", defaults)).showsUpdatedCard) + } + + @Test func anUpdateWithoutNotesStillShowsTheCard() async { + let defaults = WhatsNewFixtures.defaults() + _ = await center("0.65.0", defaults, sources: []) + let updated = await center("0.66.0", defaults, sources: []) + #expect(updated.showsUpdatedCard) + #expect(!updated.showsItem) + } + + @Test func aRollbackOrTheSettingOffShowsNoCard() async { + let defaults = WhatsNewFixtures.defaults() + _ = await center("0.66.0", defaults) + #expect(!(await center("0.65.0", defaults)).showsUpdatedCard) + let other = WhatsNewFixtures.defaults() + _ = await center("0.65.0", other) + let updated = await center("0.66.0", other) + updated.isItemEnabled = false + #expect(!updated.showsUpdatedCard) + } + + /// Chief 2026-10-08: nightly builds update several times a day, so only + /// stable and RC version changes show the card. The What's New item + /// keeps its own rule (notes the user has not seen). + @Test func onlyStableAndRCUpdatesShowTheCard() async { + let nightly = WhatsNewFixtures.defaults() + _ = await center("0.66.0-nightly.10", nightly, sources: []) + #expect(!(await center("0.66.0-nightly.11", nightly, sources: [])).showsUpdatedCard, "nightly to nightly") + let toNightly = WhatsNewFixtures.defaults() + _ = await center("0.65.0", toNightly, sources: []) + #expect(!(await center("0.66.0-nightly.3", toNightly, sources: [])).showsUpdatedCard, "stable to nightly") + let rc = WhatsNewFixtures.defaults() + _ = await center("0.65.0", rc, sources: []) + #expect((await center("0.66.0-rc.1", rc, sources: [])).showsUpdatedCard, "an RC shows the card") + let stable = WhatsNewFixtures.defaults() + _ = await center("0.66.0-nightly.12", stable, sources: []) + #expect((await center("0.66.0", stable, sources: [])).showsUpdatedCard, "nightly to stable shows the card") + } + + /// DEV/NIGHTLY proof (`debug.updater {action: "updated", previous}`): + /// a fake previous version shows the card on this launch. + @Test func aFakePreviousVersionShowsTheCard() async { + let fresh = await center("0.66.0", WhatsNewFixtures.defaults()) + #expect(fresh.debugPretendUpdated(from: "0.65.0")) + #expect(fresh.showsUpdatedCard) + #expect(fresh.unseen.map(\.version) == ["0.66.0"]) + #expect(!fresh.debugPretendUpdated(from: "0.67.0"), "a newer previous version is refused") + } +} diff --git a/Packages/macOS/CmuxNext/ci-target-graph.json b/Packages/macOS/CmuxNext/ci-target-graph.json index 92283fc51bbf..a61a0f3a6b9b 100644 --- a/Packages/macOS/CmuxNext/ci-target-graph.json +++ b/Packages/macOS/CmuxNext/ci-target-graph.json @@ -10,6 +10,7 @@ "CmuxGhosttyKit": "Packages/Shared/CmuxGhosttyKit", "CmuxHomeCore": "Packages/Shared/CmuxHomeCore", "CmuxHomeRender": "Packages/Shared/CmuxHomeRender", + "CmuxInstallAuthCore": "Packages/Shared/CmuxInstallAuthCore", "CmuxIrxTransport": "Packages/Shared/CmuxIrxTransport", "CmuxMessagesLab": "Packages/Shared/CmuxMessagesLab", "CmuxMobileRPC": "Packages/iOS/CmuxMobileRPC", @@ -440,7 +441,8 @@ ], "packages": [ "CMUXAuthCore", - "CmuxAuthRuntime" + "CmuxAuthRuntime", + "CmuxInstallAuthCore" ] }, "CmuxNextCloudTests": { @@ -449,7 +451,9 @@ "targets": [ "CmuxNextCloud" ], - "packages": [], + "packages": [ + "CmuxInstallAuthCore" + ], "reads": [] }, "CmuxNextCodeRouter": { diff --git a/THIRD_PARTY_LICENSES.md b/THIRD_PARTY_LICENSES.md index 897d065b6852..a67855404413 100644 --- a/THIRD_PARTY_LICENSES.md +++ b/THIRD_PARTY_LICENSES.md @@ -246,29 +246,25 @@ manifests and adapted detector sources live under `cmux-tui/bindings/examples/rust-agent-screen-detection/`. - **Package license:** GPL-3.0-or-later AND Apache-2.0 -- **Herdr-derived material:** Apache License 2.0 -- **Source:** https://github.com/herdrdev/herdr -- **Detector source reference:** commit `7b675f42af35508eab66ac42fe1598628597a893` -- **Pi bundled-launcher correction:** commit `b1ff4582e9688f52ffb943cfa8bee4871ae122e4` -- **Manifest snapshot:** commit `2290257acb2085ce6842ba5c7e3ca50c3ba64f02` -- **Included manifest fixes:** Claude MCP elicitation `f807b697353cfa00aa912c7cde4830e863001cf5`, Claude background-shell state `987b070fbfa187e85009b45cd7e208fc6175ff6a`, Codex weak-blocker scope `f457cff4f2648eee85d176f8a41861241d4e8428`, and Copilot background-agent activity `2290257acb2085ce6842ba5c7e3ca50c3ba64f02` +- **Herdr-derived material:** Apache License 2.0 (upstream ships no NOTICE file) +- **Source:** https://github.com/ogulcancelik/herdr (also https://github.com/herdrdev/herdr, the same repository) +- **Upstream pin:** commit `2563803dca97c040beaf3dc3acdcb5a3221b4238` (herdr 0.9.3, manifest engine version 3), with per-file hashes in `cmux-tui/bindings/examples/rust-agent-screen-detection/HERDR_UPSTREAM.toml` - **License text:** cmux-owned code is covered by `cmux-tui/bindings/examples/rust-agent-screen-detection/LICENSE`; the herdr-derived files use `cmux-tui/bindings/examples/rust-agent-screen-detection/manifests/LICENSE` -- **Latest agent-surface capability audit:** commit `987b070fbfa187e85009b45cd7e208fc6175ff6a`. The herdr repository tip checked on 2026-09-02 is `94f6d9c0d9bb9cf9ffae99d8bbfb09e9bf2fc9e0`; commits after the audit pin change client rendering, terminal reads, graphics ownership, Windows input and worktree handling, or sidebar focus, with no further `src/detect` or manifest changes. The audit includes the exact Pi bundled CLI path correction from `b1ff4582e9688f52ffb943cfa8bee4871ae122e4` and the Claude background-shell state correction from `987b070fbfa187e85009b45cd7e208fc6175ff6a`, both adapted and tested in the userland package. The first-acquisition OSC retention fix from `82e6a80eb3ae39fb3d3ebd4d1fed19389767e605` is adapted in the userland tracker. The foreground group-leader CWD fix from `3a3792622e59c7f2dc20f9c0236167161e4a5035` is already covered by cmux's generic `foreground_cwd` resource. The shell-render refactor in `207be3c771d281baae6e5fa0fb74be9a056e97a2` and independent multi-client tab views in `6c0bb273d5d5405a00985621b17e36f8b4d64609` are application/client architecture and are not copied. The delayed-agent-prompt fix in `8633a398e653eee47b375c963996c78a8a14aa48` changes PTY input sequencing, and `5616196942cbe752cc0659b9bd0fb616b2a6ed5c` hardens malformed Windows process environments in portable-pty. These changes are outside detector behavior and are not copied. SDK endpoint-generation compatibility remains a standalone-release requirement; review the Windows changes before publishing a Windows package. - -Nineteen manifests are unchanged from the manifest snapshot. `claude.toml` is -byte-identical to upstream commit `987b070fbfa187e85009b45cd7e208fc6175ff6a`. -`grok.toml` is based on the snapshot file and contains one documented cmux -precedence correction. `github-copilot.toml` is byte-identical to the snapshot -and uses upstream version `2026.08.29.1`. The manifest engine, process discovery, state detector, and update -logic are adapted for the cmux userland plugin contract. The source paths, -commits, license, and adaptations are recorded in + +All 22 manifests are byte-identical to herdr's `src/detect/manifests/` at the +pin; none is changed by cmux. The manifest engine, process discovery, state +detector, background-agent tracking and update logic are adapted and changed +by cmux for the userland plugin contract; each such file states the upstream +file, the commit and the changes in its header. The source paths, commits, +license, adaptations and the reviewed upstream commits are recorded in `cmux-tui/bindings/examples/rust-agent-screen-detection/ATTRIBUTIONS.md`. -The SHA256SUMS file is a checked-in byte-provenance record verified before the -bundled manifests are compiled. It detects accidental drift, but it is not a -cryptographic release signature for remote updates. +`scripts/cmux-next/herdr-sync.py check` verifies the vendored bytes against +`manifests/SHA256SUMS` and the pin on every push; the record detects +accidental drift, but it is not a cryptographic release signature for remote +updates. --- diff --git a/agent-chat/src/agentBrands.generated.ts b/agent-chat/src/agentBrands.generated.ts index 8fed74c63571..3a9e7f26d9c6 100644 --- a/agent-chat/src/agentBrands.generated.ts +++ b/agent-chat/src/agentBrands.generated.ts @@ -317,6 +317,7 @@ export const AGENT_BRAND_LOOKUP: Readonly> = "gemini": "gemini", "gemini-cli": "gemini", "github-copilot": "copilot", + "github-copilot-cli": "copilot", "goose": "goose", "grok": "grok", "grok-cli": "grok", @@ -401,6 +402,13 @@ export const AGENT_BRAND_RESOLUTION_CASES: readonly (readonly [input: string, br ["dsh", "deepseek"], ["gemini cli", "gemini"], ["xai", "grok"], + ["github-copilot-cli", "copilot"], + ["grok-build", "grok"], + ["factory-droid", "factory"], + ["qwen-code", "qwen"], + ["antigravity-acp", "antigravity"], + ["amp-acp", "amp"], + ["codebuddy-code", "codebuddy"], ["prime-agent", null], ["campfire", null], ["piper", null], diff --git a/backend/apps/api/release-smoke.json b/backend/apps/api/release-smoke.json new file mode 100644 index 000000000000..c024580e03cb --- /dev/null +++ b/backend/apps/api/release-smoke.json @@ -0,0 +1,7 @@ +{ + "_doc": "Post-deploy smoke for scripts/cmux-next/release/worker-release.ts verify (backend.yml deploy jobs). Routes without sources run after every deploy; the others when a matching file under backend/apps/api changed.", + "routes": [ + { "name": "health", "method": "GET", "path": "/v1/health", "expect": [200], "bodyIncludes": "\"ok\":true" }, + { "name": "sso discover", "method": "GET", "path": "/v1/sso/discover?email=release-smoke%40example.com", "expect": [200], "sources": ["src/**sso*", "src/auth.ts"] } + ] +} diff --git a/backend/apps/api/src/domains/common.ts b/backend/apps/api/src/domains/common.ts index 164519c9f485..0b4373c77299 100644 --- a/backend/apps/api/src/domains/common.ts +++ b/backend/apps/api/src/domains/common.ts @@ -352,6 +352,23 @@ export const internalOps: ReadonlyMap = new Map([ mcp: { expose: "never", group: "internal" } } as CloudOpDef ], + [ + "install.mac_execute_narrow", + { + name: "install.mac_execute_narrow", + owner: "cloud:UserDO", + class: "mutation", + risk: "mutate-own", + target: "install", + principals: ["system"], + params: Schema.Struct({}), + result: Schema.Unknown, + errors: [], + docs: "Internal: UserDO drops execute once from the grants of its active mac installs made before the mac grant cap (read, mutate-own, mutate-shared, cloud-link), on bind, then marks the migration done (cx-wb5.64).", + cli: { path: "", visible: false }, + mcp: { expose: "never", group: "internal" } + } as CloudOpDef + ], [ "install.register_server", { diff --git a/backend/apps/api/src/domains/team-vm-taint.ts b/backend/apps/api/src/domains/team-vm-taint.ts index ec2cdf39298f..03225c7c5d12 100644 --- a/backend/apps/api/src/domains/team-vm-taint.ts +++ b/backend/apps/api/src/domains/team-vm-taint.ts @@ -9,7 +9,8 @@ import type { TeamVmState } from "./team-vm.ts" * may have left something running that no certificate revocation ends. A removal of a member who * held a team SSH certificate valid after the current VM was created taints that VM's epoch; an * owner or admin then accepts the risk or rebuilds (a new VM at the next epoch). A rebuilt VM is - * paused and kept in `retired` until an owner deletes it (its files can be copied off first). + * paused with its run budget spent, so no inbound traffic resumes it (cx-009a), and kept in + * `retired` until an owner deletes it (its files can be copied off first). */ export interface TeamVmTaint { readonly epoch: number @@ -30,6 +31,12 @@ export interface TeamVmRetired { /** While `pausing`: failed pause attempts and when the alarm tries again (backoff). */ readonly pause_attempts?: number readonly pause_retry_at?: number + /** + * The provider confirmed the retire: run budget spent, then paused, so no inbound traffic + * resumes it (cx-009a). A `paused` row without it was paused before the fence existed; the + * alarm retires it again. + */ + readonly fenced?: boolean } /** A rebuild keeps at most this many replaced VMs until an owner deletes some. */ @@ -56,9 +63,12 @@ export const pausingRetired = (s: TeamVmState): TeamVmRetired | null => (s.retir /** Installs of epochs below this are revoked: a rebuilt epoch's install goes before its replacement exists. */ export const staleBelow = (s: TeamVmState): number => ((s.retired ?? []).some((r) => r.epoch === s.epoch) ? s.epoch + 1 : s.epoch) +/** A retired VM the alarm still retires: not yet paused, or paused before the fence (cx-009a). */ +export const retireDue = (r: TeamVmRetired): boolean => r.state === "pausing" || r.fenced !== true + /** The next pause retry of a retired VM, for the alarm. */ export const pauseWakeAt = (s: TeamVmState): number | null => { - const times = (s.retired ?? []).filter((r) => r.state === "pausing").map((r) => r.pause_retry_at ?? r.at) + const times = (s.retired ?? []).filter(retireDue).map((r) => r.pause_retry_at ?? r.at) return times.length ? Math.min(...times) : null } @@ -135,14 +145,14 @@ export const reduceRetired = (state: TeamVmState, op: "team_vm.retired_paused" | const row = list.find((r) => r.vm === d.value.vm) if (!row) return op === "team_vm.retired_deleted" ? reject("selector.not_found", "no retired VM with this id") : same(state) if (op === "team_vm.retired_pause_failed") { - if (row.state === "paused") return same(state) + if (!retireDue(row)) return same(state) const attempts = (row.pause_attempts ?? 0) + 1 const retiredList = list.map((r) => (r.vm === row.vm ? { ...r, pause_attempts: attempts, pause_retry_at: ctx.now + pauseDelayMs(attempts) } : r)) return { ok: true, state: { ...state, retired: retiredList, updated_at: ctx.now }, value: { vm: row.vm, attempts } } } if (op === "team_vm.retired_paused") { - if (row.state === "paused") return same(state) - return { ok: true, state: { ...state, retired: list.map((r) => (r.vm === row.vm ? { ...r, state: "paused" as const } : r)), updated_at: ctx.now }, value: { vm: row.vm, state: "paused" } } + if (!retireDue(row)) return same(state) + return { ok: true, state: { ...state, retired: list.map((r) => (r.vm === row.vm ? { ...r, state: "paused" as const, fenced: true } : r)), updated_at: ctx.now }, value: { vm: row.vm, state: "paused" } } } return { ok: true, state: { ...state, retired: list.filter((r) => r.vm !== row.vm), updated_at: ctx.now }, value: { vm: row.vm, deleted: true } } } diff --git a/backend/apps/api/src/domains/team.ts b/backend/apps/api/src/domains/team.ts index 24d33c0ec72e..71ce19969b34 100644 --- a/backend/apps/api/src/domains/team.ts +++ b/backend/apps/api/src/domains/team.ts @@ -43,7 +43,8 @@ const HTTP_ONLY_OPS: ReadonlySet = new Set([ // A tainted team VM's owner actions: role check and audit here, the act in TeamVmDO (cx-q4f3). "team_vm.taint.accept", "team_vm.rebuild", - "team_vm.retired.delete" + "team_vm.retired.delete", + "team_vm.retired.export" ]) export const teamDomain: Domain = { @@ -231,7 +232,7 @@ export const teamDomain: Domain = { // TeamDO's own submit after an owner or admin acted on a tainted team VM (cx-q4f3): audit only. if (p.kind !== "system" || p.identity !== "system:team" || !state.team) return reject("auth.forbidden", "internal op") const t = params as { action?: string; by?: string; epoch?: number; tainted_by?: ReadonlyArray } - const what = { cert_issued_while_tainted: "SSH certificate issued while the team VM is tainted", taint_accepted: "team VM taint accepted", rebuild: "team VM rebuilt", retired_deleted: "retired team VM deleted" }[t.action ?? ""] + const what = { cert_issued_while_tainted: "SSH certificate issued while the team VM is tainted", taint_accepted: "team VM taint accepted", rebuild: "team VM rebuilt", retired_deleted: "retired team VM deleted", retired_exported: "retired team VM files exported" }[t.action ?? ""] if (!what || typeof t.by !== "string") return reject("validation.invalid", "action and by required") return withAudit({ ok: true, state, value: { audited: true }, audit: { summary: `${what} (epoch ${t.epoch}, removed: ${(t.tainted_by ?? []).join(", ") || "none"})`, detail: params } }, state.team.id, ctx, op) } diff --git a/backend/apps/api/src/domains/user.ts b/backend/apps/api/src/domains/user.ts index 116e315112be..3847587ea9b1 100644 --- a/backend/apps/api/src/domains/user.ts +++ b/backend/apps/api/src/domains/user.ts @@ -25,7 +25,7 @@ export interface UserState extends PushTargetsState, ChiefsState { readonly installs: Readonly> readonly grants: Readonly> /** One-time migrations already done on this user (CLOUD-LINK-FOLLOWUPS decision 2). */ - readonly migrations?: { readonly ios_cloud_link?: true } + readonly migrations?: { readonly ios_cloud_link?: true; readonly mac_execute_narrow?: true } /** * Revoked installs whose team SSH certificates still need a KRL entry in each team's TeamDO * (plans/cmux-next/team-vm-plan.md S4). UserDO's alarm delivers them and clears each one. @@ -94,6 +94,29 @@ export const iosGrantsToMigrate = (state: UserState): Array => .filter((g): g is NonNullable => !!g && g.revoked_at === null && !g.op_classes.includes("cloud-link") && g.op_classes.every((c) => OLD_IOS_CLASSES.includes(c))) .map((g) => g.id) +/** + * cx-wb5.64: grants of active mac installs that still carry execute. Before the mac grant cap + * (e9d25623248e) a mac install got the old default (read, mutate-own, mutate-shared, execute); since + * then install.register refuses execute for kind mac and no op widens a grant, so any such grant is + * from before the cap. No created_at cutoff: production gets the cap at its own deploy. Runs once per + * user (the done flag). A later feature that grants execute to a mac install on purpose must set + * migrations.mac_execute_narrow first, or a user without the flag loses it at the next bind. + */ +export const macGrantsToNarrow = (state: UserState): Array => + state.migrations?.mac_execute_narrow + ? [] + : Object.values(state.installs) + .filter((i) => i.kind === "mac" && i.revoked_at === null) + .map((i) => state.grants[i.grant]) + .filter((g): g is NonNullable => !!g && g.revoked_at === null && g.op_classes.includes("execute")) + .map((g) => g.id) + +/** The one-time grant migrations this user still needs, as [internal op, idempotency key prefix] (run on UserDO bind). */ +export const grantMigrationsDue = (state: UserState): Array => [ + ...(iosGrantsToMigrate(state).length ? [["install.ios_cloud_link_migrate", "ios-cloud-link"] as const] : []), + ...(macGrantsToNarrow(state).length ? [["install.mac_execute_narrow", "mac-execute-narrow"] as const] : []) +] + /** * Inbox calls come from this user only, through an active install whose grant covers the op * (the catalog check other owners apply). @@ -176,7 +199,8 @@ const withInstallKind = (state: UserState, p: Principal): Principal => { * machines through the credential relay); never execute. An install with neither execute nor * cloud-link gets no SSH certificate (team-ssh-ca.ts). The kind is self-declared by the session holder * (a cli or web register keeps execute), so this caps a stolen install token, not the session; - * no shipped client registered a mac install before this change, so no grant needs a migration; + * installs registered before this cap (the feat-cmux-next-ios Mac link host, 8fa5131c7964) lose + * execute once through install.mac_execute_narrow; * - vm: vm-self only; every other kind (cli, ...): all install classes. * money and destructive are never install classes (G8 approvals, cx-wb5.65). */ @@ -328,6 +352,15 @@ export const makeUserDomain = (appIdHash: string): Domain => ({ // Done once per user: later iPhone installs keep the grant their client asked for. return { ok: true, state: { ...state, grants, migrations: { ...state.migrations, ios_cloud_link: true } }, value: { migrated: ids.length } } } + case "install.mac_execute_narrow": { + if (p.kind !== "system") return reject("auth.forbidden", "internal op") + if (state.migrations?.mac_execute_narrow) return { ok: true, state, value: { narrowed: 0 }, changed: false } + const ids = macGrantsToNarrow(state) + const grants = { ...state.grants } + // Narrowing only: execute goes, every other class stays, nothing is added. + for (const id of ids) grants[id] = { ...grants[id]!, op_classes: grants[id]!.op_classes.filter((c) => c !== "execute") } + return { ok: true, state: { ...state, grants, migrations: { ...state.migrations, mac_execute_narrow: true } }, value: { narrowed: ids.length } } + } case "install.rename": { const d = decodeParams(InstallRename, params) if (!d.ok) return d diff --git a/backend/apps/api/src/http.ts b/backend/apps/api/src/http.ts index d828f5933bae..8ec200736743 100644 --- a/backend/apps/api/src/http.ts +++ b/backend/apps/api/src/http.ts @@ -251,7 +251,7 @@ const OpsLive = HttpApiBuilder.group(CloudApi, "ops", (handlers) => return yield* Effect.tryPromise({ try: () => rpc(env.TEAM_DO.get(env.TEAM_DO.idFromName(p.team!)).ssoOp(p.team!, p, frame)), catch: unreachable }) } // TeamDO, outside its reducer: the SSH CA (team-ssh-ca.ts; keys never enter params) and a tainted team VM's owner actions (cx-q4f3). - if (["team_vm.ssh_cert", "team_vm.ssh_cert.challenge", "team_vm.ssh_cert.revoke", "team_vm.ssh_ca.rotate", "team_vm.taint.accept", "team_vm.rebuild", "team_vm.retired.delete"].includes(payload.op)) { + if (["team_vm.ssh_cert", "team_vm.ssh_cert.challenge", "team_vm.ssh_cert.revoke", "team_vm.ssh_ca.rotate", "team_vm.taint.accept", "team_vm.rebuild", "team_vm.retired.delete", "team_vm.retired.export"].includes(payload.op)) { const p = yield* principalFor("cloud:TeamDO", principal) const stub = env.TEAM_DO.get(env.TEAM_DO.idFromName(p.team!)) return yield* Effect.tryPromise({ try: () => rpc(payload.op.startsWith("team_vm.ssh_") ? stub.sshOp(p.team!, p, frame) : stub.vmAdminOp(p.team!, p, frame)), catch: unreachable }) diff --git a/backend/apps/api/src/index.ts b/backend/apps/api/src/index.ts index b1830889c96b..315f166fdc7b 100644 --- a/backend/apps/api/src/index.ts +++ b/backend/apps/api/src/index.ts @@ -12,6 +12,7 @@ import { CARD_PATH, handleContactCard, handleSendblueHook } from "./home-text.ts import { handleOutboxReplay } from "./admin-outbox.ts" import { handleCloudAbandonedClear } from "./cloud-admin.ts" import { handleTeamVmAdmin } from "./team-vm-admin.ts" +import { handleTeamVmExport } from "./team-vm-export-route.ts" import { signInRules, ssoGate, versionRefusal } from "./policy-gate.ts" import type { PresenceKeyBody } from "./user-do.ts" import { handlePairBegin, handlePairWait } from "./pair-routes.ts" @@ -152,6 +153,8 @@ export default { if (url.pathname === "/v1/admin/outbox/replay") return handleOutboxReplay(request, env) if (url.pathname === "/v1/admin/cloud/abandoned/clear") return handleCloudAbandonedClear(request, env) if (url.pathname.startsWith("/v1/admin/team-vm/")) return handleTeamVmAdmin(request, env) + const tvmExport = url.pathname.match(/^\/v1\/team-vm\/export\/(team_[A-Za-z0-9_-]{1,64})\/([0-9a-f]{64})$/) + if (tvmExport) return handleTeamVmExport(request, env, tvmExport[1]!, tvmExport[2]!) // Webhook ingress: no bearer; each route verifies its own signature before any DO call. const hook = url.pathname.match(/^\/v1\/hooks\/automation\/([^/]+)\/([^/]+)$/) if (hook) return handleAutomationHook(request, env, hook[1]!, hook[2]!) diff --git a/backend/apps/api/src/tar.ts b/backend/apps/api/src/tar.ts new file mode 100644 index 000000000000..c7aa3c9ab687 --- /dev/null +++ b/backend/apps/api/src/tar.ts @@ -0,0 +1,87 @@ +/** + * A minimal POSIX tar (pax/ustar) writer for streamed archives (team-vm-export.ts). It only + * encodes headers: the caller writes each file's bytes after its header and `padding(size)` zero + * bytes after them, then `TAR_END`. Every size is known before the first byte, so `tarLength` + * gives the exact archive length (a Content-Length the browser can show progress against). + */ +export interface TarEntry { + /** The archive path, relative, `/`-separated; a directory's path has no trailing slash. */ + readonly path: string + readonly kind: "file" | "dir" + readonly size: number + /** Permission bits (for example 0o644). */ + readonly mode: number + /** Modification time, seconds since the epoch. */ + readonly mtime: number + readonly uname?: string + readonly gname?: string +} + +const BLOCK = 512 +const enc = new TextEncoder() + +/** Zero bytes after `size` bytes of data, up to the next 512-byte block. */ +export const padding = (size: number): number => (BLOCK - (size % BLOCK)) % BLOCK + +/** Two zero blocks end the archive. */ +export const TAR_END = new Uint8Array(2 * BLOCK) + +const octal = (n: number, width: number): string => Math.max(0, Math.floor(n)).toString(8).padStart(width - 1, "0") + "\0" + +const ustarName = (e: TarEntry): string => (e.kind === "dir" ? `${e.path}/` : e.path) + +/** Plain ASCII without control characters that fits the 100-byte name field; anything else gets a pax `path` record. */ +const fitsUstar = (name: string): boolean => name.length <= 100 && /^[\x20-\x7e]+$/.test(name) + +const paxRecord = (key: string, value: string): Uint8Array => { + const body = enc.encode(` ${key}=${value}\n`).length + let len = body + 1 + while (String(len).length + body !== len) len = String(len).length + body + return enc.encode(`${len} ${key}=${value}\n`) +} + +const field = (h: Uint8Array, offset: number, width: number, value: string) => { + const bytes = enc.encode(value) + h.set(bytes.subarray(0, width), offset) +} + +const header = (name: string, type: string, size: number, e: Pick): Uint8Array => { + const h = new Uint8Array(BLOCK) + field(h, 0, 100, name) + field(h, 100, 8, octal(e.mode & 0o7777, 8)) + field(h, 108, 8, octal(0, 8)) + field(h, 116, 8, octal(0, 8)) + field(h, 124, 12, octal(size, 12)) + field(h, 136, 12, octal(e.mtime, 12)) + field(h, 148, 8, " ") + field(h, 156, 1, type) + field(h, 257, 6, "ustar\0") + field(h, 263, 2, "00") + const owner = (s: string | undefined) => (s && /^[\x21-\x7e]{1,31}$/.test(s) ? s : "") + field(h, 265, 32, owner(e.uname)) + field(h, 297, 32, owner(e.gname)) + let sum = 0 + for (const b of h) sum += b + field(h, 148, 8, sum.toString(8).padStart(6, "0") + "\0 ") + return h +} + +/** The header block(s) of one entry: a pax extended header first when the path does not fit ustar. */ +export const tarHeader = (e: TarEntry): Uint8Array => { + const name = ustarName(e) + const size = e.kind === "dir" ? 0 : e.size + const type = e.kind === "dir" ? "5" : "0" + if (fitsUstar(name)) return header(name, type, size, e) + const pax = paxRecord("path", name) + const out = new Uint8Array(BLOCK + pax.length + padding(pax.length) + BLOCK) + out.set(header("././@PaxHeader", "x", pax.length, e), 0) + out.set(pax, BLOCK) + // The ustar name is only a fallback for readers without pax: the ASCII part, cut to 100 bytes. + const fallback = name.replace(/[^\x20-\x7e]/g, "_").slice(-100) + out.set(header(fallback, type, size, e), BLOCK + pax.length + padding(pax.length)) + return out +} + +/** The exact length of the archive of `entries`: headers, data, padding and the end blocks. */ +export const tarLength = (entries: ReadonlyArray): number => + entries.reduce((n, e) => n + tarHeader(e).length + (e.kind === "file" ? e.size + padding(e.size) : 0), 0) + TAR_END.length diff --git a/backend/apps/api/src/team-vm-do.ts b/backend/apps/api/src/team-vm-do.ts index f7dbde854869..22083560fe0f 100644 --- a/backend/apps/api/src/team-vm-do.ts +++ b/backend/apps/api/src/team-vm-do.ts @@ -3,15 +3,17 @@ import type { Env } from "./env.ts" import { OwnerDO, type ReadResult, type SubmitResult } from "./owner-do.ts" import { DriverError, FakeDriver, providerRefusal, teamVmDriver } from "./team-vm-driver.ts" import { MAX_ATTEMPTS, teamVmDomain, teamVmSlug, teamVmWakeAt, type TeamVmState } from "./domains/team-vm.ts" -import { fromBase64, isStream, MAX_ENTRY_BYTES, sha256Hex, TeamJournal } from "./team-vm-journal.ts" +import { fromBase64, isStream, journalCaller, MAX_ENTRY_BYTES, sha256Hex, TeamJournal } from "./team-vm-journal.ts" import { TeamVmLedger, type LedgerRow } from "./team-vm-ledger.ts" import { RegistryOutbox } from "./team-vm-registry-outbox.ts" import { prefixReport, TeamVmRegistry, type RegistryCounts, type RegistryEvent, type RegistryEventKind } from "./team-vm-registry.ts" import { TEAM_VM_REGISTRY } from "./team-vm-admin.ts" import { BindRunner } from "./team-vm-bind-run.ts" import { FakeGuest, type FakeGuestMode } from "./team-vm-fake-guest.ts" -import { adminAction, pauseRetired, taintSummary, type AdminReply, type AdminRequest, type TaintRunDeps, type TaintSummary } from "./team-vm-taint-run.ts" +import { adminAction, pauseRetired, taintSummary, type AdminReply, type AdminRequest, type TaintSummary } from "./team-vm-taint-run.ts" import { taintView } from "./domains/team-vm-taint.ts" +import { downloadExport, exportUnknown, type ExportRunDeps } from "./team-vm-export-run.ts" +import { ExportTickets } from "./team-vm-export.ts" import type { DeliverResult, TargetItem } from "./do-outbox.ts" /** Retry of undelivered registry events when the alarm next runs for this object. */ @@ -50,18 +52,6 @@ export class TeamVmDO extends OwnerDO { return this.journalStore } - /** - * The journal is the team's zero-loss tier and holds every person's files: only the VM's own - * install for the current epoch reads or writes it, never a member's session or another install. - */ - private journalCaller(state: TeamVmState, p: Principal, risk: "read" | "mutate-own"): { ok: true } | { ok: false; code: string; message: string } { - if (p.kind !== "install" || p.team === undefined || p.team !== state.team) return { ok: false, code: "auth.forbidden", message: "only the team VM's install uses the journal" } - if (!state.vm_install) return { ok: false, code: "team_vm.not_bound", message: "the team VM has not bound its install yet" } - if (p.install !== state.vm_install) return { ok: false, code: "auth.forbidden", message: "only the team VM's install uses the journal" } - if (!p.grant_classes?.includes(risk)) return { ok: false, code: "auth.forbidden", message: `grant does not cover ${risk}` } - return { ok: true } - } - constructor(ctx: DurableObjectState, env: Env) { super(ctx, env, teamVmDomain as Domain, "team_vm") } @@ -76,7 +66,7 @@ export class TeamVmDO extends OwnerDO { protected read(state: TeamVmState, op: string, params: unknown, principal: Principal): ReadResult { if (op === "team_vm.journal.high_water" || op === "team_vm.journal.read") { - const allowed = this.journalCaller(state, principal, "read") + const allowed = journalCaller(state, principal, "read") if (!allowed.ok) return allowed const p = (params ?? {}) as { stream?: unknown; from_seq?: unknown } if (!isStream(p.stream)) return { ok: false, code: "validation.invalid", message: "unknown journal stream" } @@ -120,9 +110,9 @@ export class TeamVmDO extends OwnerDO { } // Taint after a member removal (cx-q4f3): team-vm-taint-run.ts. - private get taintDeps(): TaintRunDeps { + private get taintDeps(): ExportRunDeps { const driver = () => (providerRefusal(this.env) ? null : teamVmDriver(this.env, this.sqlStore)) - return { state: () => this.boundEngine?.currentState, driver, refusal: () => providerRefusal(this.env), submitSystem: (op, p, k) => this.submitSystem(op, p, k), deleteVm: (id, by) => this.deleteVm(this.boundEngine!.stream.slice("team_vm:".length), id, by), reconcile: () => this.reconcile() } + return { state: () => this.boundEngine?.currentState, driver, refusal: () => providerRefusal(this.env), submitSystem: (op, p, k) => this.submitSystem(op, p, k), deleteVm: (id, by) => this.deleteVm(this.boundEngine!.stream.slice("team_vm:".length), id, by), reconcile: () => this.reconcile(), exportTickets: () => new ExportTickets(this.sqlStore) } } /** RPC from TeamDO's certificate issue: the taint of a team that has a VM record (never creates one). */ @@ -138,6 +128,9 @@ export class TeamVmDO extends OwnerDO { return adminAction(this.taintDeps, req) } + /** The team files download (`GET /v1/team-vm/export//`, cx-lyvg): the ticket the export op minted, single use. */ + async exportDownload(entity: string, ticket: string): Promise { return this.isBound(entity) ? (this.bind(entity), downloadExport(this.taintDeps, ticket)) : exportUnknown() } + /** A member-removal notice for a team that never had a VM creates no record here. */ override async systemDeliver(entity: string, source: string, items: ReadonlyArray): Promise { if (!this.isBound(entity) && items.every((i) => i.op === "team_vm.member_removed")) return { done: items.map((i) => i.id) } @@ -185,7 +178,7 @@ export class TeamVmDO extends OwnerDO { }) const state = this.boundEngine?.currentState if (!state) return reject("owner.unreachable", "team VM record not open") - const allowed = this.journalCaller(state, principal, "mutate-own") + const allowed = journalCaller(state, principal, "mutate-own") if (!allowed.ok) return reject(allowed.code, allowed.message) const p = (frame.params ?? {}) as { stream?: unknown; epoch?: unknown; first_seq?: unknown; last_seq?: unknown; bytes?: unknown; sha256?: unknown } if (!isStream(p.stream) || typeof p.epoch !== "number" || typeof p.first_seq !== "number" || typeof p.last_seq !== "number" || typeof p.bytes !== "string" || typeof p.sha256 !== "string") diff --git a/backend/apps/api/src/team-vm-driver-files.ts b/backend/apps/api/src/team-vm-driver-files.ts new file mode 100644 index 000000000000..ed78b5832bcd --- /dev/null +++ b/backend/apps/api/src/team-vm-driver-files.ts @@ -0,0 +1,158 @@ +import type { SqlStore } from "@cmux/ownership" +import { DriverError, type FsKind, type FsStat, type TeamVmFiles } from "./team-vm-driver.ts" + +/** One metadata call (list or stat); a read gets the caller's signal instead. */ +const META_TIMEOUT_MS = 20_000 + +const kindOf = (v: unknown): FsKind => (v === "file" || v === "directory" || v === "symlink" ? v : "other") + +/** + * Freestyle's file API (`GET /v5/vms/{id}/fs/dir|stat|read?path=`, OpenAPI v5). It works on the + * VM's disk while the VM is paused with its run budget spent (cx-009a: fs/read 200 on a fenced VM). + * A 404 means "no such VM, or no such path"; a second read of the VM tells the two apart. + */ +export class FreestyleFiles implements TeamVmFiles { + constructor( + private readonly apiKey: string, + private readonly baseUrl: string + ) {} + + private url(id: string, verb: string, path: string) { + return `${this.baseUrl.replace(/\/+$/, "")}/v5/vms/${encodeURIComponent(id)}/fs/${verb}?path=${encodeURIComponent(path)}` + } + + private async get(url: string, signal: AbortSignal, headers: Record = {}): Promise { + try { + return await fetch(url, { headers: { authorization: `Bearer ${this.apiKey}`, ...headers }, signal }) + } catch (e) { + throw new DriverError("team_vm.provider_failed", `fs: no answer ${e instanceof Error && e.name === "TimeoutError" ? "TIMEOUT" : "UNREACHABLE"}`, false) + } + } + + /** On a 404: null when the VM exists (the path is missing), else vm_missing. */ + private async missing(id: string): Promise { + const vm = await this.get(`${this.baseUrl.replace(/\/+$/, "")}/v5/vms/${encodeURIComponent(id)}`, AbortSignal.timeout(META_TIMEOUT_MS)) + await vm.body?.cancel() + if (vm.status === 404) throw new DriverError("team_vm.vm_missing", "fs: VM 404", true) + if (vm.status !== 200) throw this.failure(vm.status, "", "fs") + return null + } + + /** Only the step, the status and the provider's code reach the caller, never its message. */ + private failure(status: number, code: string, what: string): DriverError { + const final = status === 400 || status === 401 || status === 403 || status === 422 + return new DriverError(final ? "team_vm.provider_refused" : "team_vm.provider_failed", `${what}: ${status}${code ? ` ${code.slice(0, 40)}` : ""}`, final) + } + + private async json(res: Response, what: string): Promise> { + const body = (await res.json().catch(() => ({}))) as Record + if (res.status !== 200) throw this.failure(res.status, typeof body.code === "string" ? body.code : "", what) + return body + } + + async list(id: string, path: string) { + const res = await this.get(this.url(id, "dir", path), AbortSignal.timeout(META_TIMEOUT_MS)) + if (res.status === 404) return (await res.body?.cancel(), this.missing(id)) + const body = await this.json(res, "fs list") + if (!Array.isArray(body.entries)) throw new DriverError("team_vm.provider_failed", "fs list: answer without entries", false) + return (body.entries as Array>).filter((e) => typeof e.name === "string").map((e) => ({ name: e.name as string, kind: kindOf(e.kind) })) + } + + async stat(id: string, path: string): Promise { + const res = await this.get(this.url(id, "stat", path), AbortSignal.timeout(META_TIMEOUT_MS)) + if (res.status === 404) return (await res.body?.cancel(), this.missing(id)) + const b = await this.json(res, "fs stat") + const kind: FsKind = b.isSymlink === true ? "symlink" : b.isDirectory === true ? "directory" : b.isFile === true ? "file" : "other" + const mode = typeof b.permissions === "string" && /^[0-7]{1,6}$/.test(b.permissions) ? parseInt(b.permissions, 8) & 0o7777 : kind === "directory" ? 0o755 : 0o644 + // Epoch seconds as a string while running, "" on a paused VM's disk (measured cx-lyvg). + const at = typeof b.modified === "string" ? (/^\d{1,12}$/.test(b.modified) ? Number(b.modified) * 1000 : Date.parse(b.modified)) : NaN + const size = typeof b.size === "number" && Number.isSafeInteger(b.size) && b.size >= 0 ? b.size : 0 + return { kind, size, mode, mtime: Number.isFinite(at) ? Math.floor(at / 1000) : 0, owner: typeof b.owner === "string" ? b.owner : "", group: typeof b.group === "string" ? b.group : "" } + } + + async read(id: string, path: string, offset: number, signal: AbortSignal) { + const res = await this.get(this.url(id, "read", path), signal, offset > 0 ? { range: `bytes=${offset}-` } : {}) + const ok = offset > 0 ? res.status === 206 : res.status === 200 + if (!ok || !res.body) { + const body = (await res.json().catch(() => ({}))) as Record + if (res.status === 404) throw new DriverError("team_vm.vm_missing", "fs read: 404", true) + throw this.failure(res.status, typeof body.code === "string" ? body.code : "", "fs read") + } + return res.body + } +} + +/** + * Test files for FakeDriver: one row per path in the DO's SQLite (`fake_fs`). `cut_once` ends the + * next read of that file with an error after that many bytes (a provider stream that broke), and + * `stat_size` makes stat report another size than the stored bytes (a huge file without the bytes). + */ +export class FakeFiles implements TeamVmFiles { + constructor(private readonly sql: SqlStore) { + sql.exec(`CREATE TABLE IF NOT EXISTS fake_fs (vm TEXT NOT NULL, path TEXT NOT NULL, kind TEXT NOT NULL, data BLOB, mode INTEGER NOT NULL, stat_size INTEGER, cut_once INTEGER, PRIMARY KEY (vm, path))`) + sql.exec(`CREATE TABLE IF NOT EXISTS fake_fs_reads (n INTEGER NOT NULL)`) + } + + /** Test only: writes a file or symlink (and its parent directories) into `vm`. */ + put(vm: string, path: string, data: Uint8Array | string, opts: { kind?: "file" | "symlink"; mode?: number; stat_size?: number; cut_once?: number } = {}) { + const parts = path.split("/").filter(Boolean) + for (let i = 1; i < parts.length; i++) this.sql.exec(`INSERT OR IGNORE INTO fake_fs (vm, path, kind, data, mode) VALUES (?, ?, 'directory', NULL, 493)`, vm, `/${parts.slice(0, i).join("/")}`) + const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data + this.sql.exec(`INSERT OR REPLACE INTO fake_fs (vm, path, kind, data, mode, stat_size, cut_once) VALUES (?, ?, ?, ?, ?, ?, ?)`, vm, `/${parts.join("/")}`, opts.kind ?? "file", bytes, opts.mode ?? 0o644, opts.stat_size ?? null, opts.cut_once ?? null) + } + + /** Test only: an empty directory. */ + mkdir(vm: string, path: string) { + this.put(vm, `${path}/.x`, "") + this.sql.exec(`DELETE FROM fake_fs WHERE vm = ? AND path = ?`, vm, `${path}/.x`) + } + + /** Test only: how many reads ran (each is one provider request). */ + reads(): number { + return this.sql.exec<{ n: number }>(`SELECT COUNT(*) AS n FROM fake_fs_reads`)[0]!.n + } + + private vmExists(vm: string) { + if (!this.sql.exec(`SELECT 1 FROM fake_vm WHERE id = ?`, vm)[0]) throw new DriverError("team_vm.vm_missing", "fs: VM 404", true) + } + + async list(vm: string, path: string) { + this.vmExists(vm) + if (!this.sql.exec(`SELECT 1 FROM fake_fs WHERE vm = ? AND path = ? AND kind = 'directory'`, vm, path)[0]) return null + // substr, not LIKE: the DO's SQLite refuses long LIKE patterns. + const prefix = `${path}/` + const rows = this.sql.exec<{ path: string; kind: string }>(`SELECT path, kind FROM fake_fs WHERE vm = ? AND substr(path, 1, ?) = ?`, vm, prefix.length, prefix) + return rows.filter((r) => !r.path.slice(path.length + 1).includes("/")).map((r) => ({ name: r.path.slice(path.length + 1), kind: kindOf(r.kind) })) + } + + async stat(vm: string, path: string): Promise { + this.vmExists(vm) + const r = this.sql.exec<{ kind: string; data: ArrayBuffer | null; mode: number; stat_size: number | null }>(`SELECT kind, data, mode, stat_size FROM fake_fs WHERE vm = ? AND path = ?`, vm, path)[0] + if (!r) return null + return { kind: kindOf(r.kind), size: r.stat_size ?? (r.data ? r.data.byteLength : 0), mode: r.mode, mtime: 1_800_000_000, owner: "cmux", group: "cmux" } + } + + async read(vm: string, path: string, offset: number, _signal: AbortSignal) { + this.vmExists(vm) + this.sql.exec(`INSERT INTO fake_fs_reads (n) VALUES (1)`) + const r = this.sql.exec<{ data: ArrayBuffer | null; cut_once: number | null }>(`SELECT data, cut_once FROM fake_fs WHERE vm = ? AND path = ? AND kind = 'file'`, vm, path)[0] + if (!r) throw new DriverError("team_vm.vm_missing", "fs read: 404", true) + const bytes = new Uint8Array(r.data ?? new ArrayBuffer(0)).slice(offset) + const cut = r.cut_once + if (cut !== null) this.sql.exec(`UPDATE fake_fs SET cut_once = NULL WHERE vm = ? AND path = ?`, vm, path) + return new ReadableStream({ + start(ctl) { + if (cut === null) { + // Two chunks, so a reader sees a stream rather than one buffer. + const mid = Math.floor(bytes.length / 2) + if (mid > 0) ctl.enqueue(bytes.slice(0, mid)) + if (bytes.length > mid) ctl.enqueue(bytes.slice(mid)) + ctl.close() + } else { + if (cut > 0) ctl.enqueue(bytes.slice(0, cut)) + ctl.error(new Error("fake stream cut")) + } + } + }) + } +} diff --git a/backend/apps/api/src/team-vm-driver.ts b/backend/apps/api/src/team-vm-driver.ts index 2fb51c571f8c..c028bfe311fa 100644 --- a/backend/apps/api/src/team-vm-driver.ts +++ b/backend/apps/api/src/team-vm-driver.ts @@ -2,6 +2,7 @@ import type { SqlStore } from "@cmux/ownership" import type { Env } from "./env.ts" import type { ProviderState } from "./domains/team-vm.ts" import { FakeGuest } from "./team-vm-fake-guest.ts" +import { FakeFiles, FreestyleFiles } from "./team-vm-driver-files.ts" /** * The provider behind TeamVmDO (plans/cmux-next/team-vm-plan.md S2). Two calls, both idempotent: @@ -16,8 +17,14 @@ export interface TeamVmDriver { lookup(name: string): Promise<{ readonly id: string; readonly team: string | null } | null> /** Deletes the VM with this provider id; a VM already gone counts as deleted. Callers pass ledger ids only. */ deleteVm(id: string): Promise - /** Pauses the VM with this provider id (memory and disk kept); a VM already paused counts as paused. */ - pauseVm(id: string): Promise + /** + * Retires the VM with this provider id: syncs a running guest's disk (best effort, bounded), spends its lifetime run budget, then pauses it (memory + * and disk kept; a VM already paused counts as paused). The provider resumes a paused VM on any + * inbound traffic (public IPv6, VPC peers, tunnels, its SSH proxy; measured cx-009a); a spent + * budget makes it refuse every later start, those wakes and exec included, while the files stay + * readable and the VM can still be deleted. Nothing in cmux raises the budget again. + */ + retireVm(id: string): Promise /** * Runs one command on this exact VM through the provider API (authenticated by our provider key, * which the guest never sees) and returns its exit code and output. Used only by the bind @@ -26,6 +33,32 @@ export interface TeamVmDriver { exec(id: string, command: string, timeoutMs: number): Promise<{ readonly code: number; readonly stdout: string }> /** One page of the provider account's VMs (report-only callers; never used to adopt or delete). */ listPage(limit: number, offset: number): Promise<{ readonly vms: ReadonlyArray<{ readonly id: string; readonly slug: string | null }>; readonly size: number; readonly total: number | null }> + /** + * The provider's file API on the VM's disk (team-vm-export.ts). It reads a paused VM without + * starting it, also one whose run budget is spent (measured cx-009a). Never used on a running VM. + */ + readonly files: TeamVmFiles +} + +export type FsKind = "file" | "directory" | "symlink" | "other" +export interface FsStat { + readonly kind: FsKind + readonly size: number + /** Permission bits. */ + readonly mode: number + /** Seconds since the epoch, 0 when unknown. */ + readonly mtime: number + readonly owner: string + readonly group: string +} + +export interface TeamVmFiles { + /** The entries of directory `path`, or null when the path does not exist (the VM itself missing is `team_vm.vm_missing`). */ + list(id: string, path: string): Promise | null> + /** Metadata of `path` without following a symlink's target, or null when the path does not exist. */ + stat(id: string, path: string): Promise + /** The bytes of file `path` from byte `offset` on, as the provider streams them. */ + read(id: string, path: string, offset: number, signal: AbortSignal): Promise> } export class DriverError extends Error { @@ -48,14 +81,21 @@ const IDLE_TIMEOUT_SECONDS = 600 const REQUEST_TIMEOUT_MS = 20_000 /** A create can take much longer than a wake (the web driver allows minutes); a lost answer is recovered by slug. */ const CREATE_TIMEOUT_MS = 120_000 +/** The guest `sync` before a retire: long enough to flush a busy disk, short enough that the fence follows promptly. */ +const RETIRE_SYNC_MS = 15_000 +/** A retired VM's lifetime run budget: below the time it has already run, so the provider refuses every start. */ +const RETIRED_RUN_BUDGET_SECONDS = 1 const nonEmpty = (v: unknown): v is string => typeof v === "string" && v.length > 0 export class FreestyleDriver implements TeamVmDriver { + readonly files: FreestyleFiles constructor( private readonly apiKey: string, private readonly baseUrl: string, private readonly snapshot: string - ) {} + ) { + this.files = new FreestyleFiles(apiKey, baseUrl) + } private async call(method: string, path: string, body?: unknown, timeoutMs = REQUEST_TIMEOUT_MS): Promise<{ status: number; json: Record }> { let res: Response @@ -139,7 +179,22 @@ export class FreestyleDriver implements TeamVmDriver { this.fail(gone.status, gone.json, "delete VM") } - async pauseVm(id: string) { + async retireVm(id: string) { + // The file API reads a paused VM's disk image, not the guest page cache (measured cx-lyvg: a + // file written seconds before the pause read back as 0 bytes). So a running VM syncs first, + // as root, bounded; a failure never holds the fence back. A paused VM is never woken for it. + const seen = await this.call("GET", `/v5/vms/${encodeURIComponent(id)}`) + if (seen.status === 404) throw new DriverError("team_vm.vm_missing", "retire VM: 404", true) + if (seen.status === 200 && seen.json.state === "running") { + const synced = await this.call("POST", `/v5/vms/${encodeURIComponent(id)}/exec-await`, { command: "sync", timeoutMs: RETIRE_SYNC_MS, linuxUser: "root" }, RETIRE_SYNC_MS + 5_000) + if (synced.status !== 200 || synced.json.statusCode !== 0) console.warn(JSON.stringify({ msg: "team vm retire sync failed", vm: id, status: synced.status })) + } + // First the budget (1 s is always spent: the VM has run at least that long), so no packet that + // arrives between the pause and a later call can run it again. On a running VM the budget alone + // pauses it within about a second; the pause below then confirms the state. + const capped = await this.call("PATCH", `/v5/vms/${encodeURIComponent(id)}`, { maxRunTotalSeconds: RETIRED_RUN_BUDGET_SECONDS }) + if (capped.status === 404) throw new DriverError("team_vm.vm_missing", "retire VM: 404", true) + if (capped.status < 200 || capped.status >= 300) this.fail(capped.status, capped.json, "retire VM") const r = await this.call("POST", `/v5/vms/${encodeURIComponent(id)}/pause`) if (r.status >= 200 && r.status < 300) return // A VM that is already paused (or stopped) may refuse the call; that is the state asked for. @@ -177,8 +232,10 @@ export class FreestyleDriver implements TeamVmDriver { */ export class FakeDriver implements TeamVmDriver { private readonly guest: FakeGuest + readonly files: FakeFiles constructor(private readonly sql: SqlStore) { this.guest = new FakeGuest(sql) + this.files = new FakeFiles(sql) sql.exec(`CREATE TABLE IF NOT EXISTS fake_vm (slug TEXT PRIMARY KEY, id TEXT NOT NULL UNIQUE, state TEXT NOT NULL, team TEXT)`) sql.exec(`CREATE TABLE IF NOT EXISTS fake_ctl (id INTEGER PRIMARY KEY CHECK (id = 1), fail_next INTEGER NOT NULL DEFAULT 0, creates INTEGER NOT NULL DEFAULT 0, starts INTEGER NOT NULL DEFAULT 0, slug_prefix TEXT, lose_next_create INTEGER NOT NULL DEFAULT 0)`) sql.exec(`INSERT OR IGNORE INTO fake_ctl (id) VALUES (1)`) @@ -233,17 +290,29 @@ export class FakeDriver implements TeamVmDriver { this.sql.exec(`DELETE FROM fake_vm WHERE id = ?`, id) } - async pauseVm(id: string) { + async retireVm(id: string) { this.maybeFail() this.sql.exec(`CREATE TABLE IF NOT EXISTS fake_pause_ctl (id INTEGER PRIMARY KEY CHECK (id = 1), fail INTEGER NOT NULL)`) if ((this.sql.exec<{ fail: number }>(`SELECT fail FROM fake_pause_ctl WHERE id = 1`)[0]?.fail ?? 0) > 0) { this.sql.exec(`UPDATE fake_pause_ctl SET fail = fail - 1 WHERE id = 1`) throw new DriverError("team_vm.provider_failed", "fake pause failure", false) } - if (!this.sql.exec<{ id: string }>(`SELECT id FROM fake_vm WHERE id = ?`, id)[0]) throw new DriverError("team_vm.vm_missing", "pause VM: 404", true) + if (!this.sql.exec<{ id: string }>(`SELECT id FROM fake_vm WHERE id = ?`, id)[0]) throw new DriverError("team_vm.vm_missing", "retire VM: 404", true) + this.sql.exec(`CREATE TABLE IF NOT EXISTS fake_fence (id TEXT PRIMARY KEY)`) + this.sql.exec(`INSERT OR IGNORE INTO fake_fence (id) VALUES (?)`, id) this.sql.exec(`UPDATE fake_vm SET state = 'paused' WHERE id = ?`, id) } + /** + * Test only: one inbound connection to `id` as the provider handles it (measured cx-009a): + * traffic resumes a paused VM unless its run budget is spent (`fake_fence`). + */ + inbound(id: string): void { + this.sql.exec(`CREATE TABLE IF NOT EXISTS fake_fence (id TEXT PRIMARY KEY)`) + if (this.sql.exec<{ id: string }>(`SELECT id FROM fake_fence WHERE id = ?`, id)[0]) return + this.sql.exec(`UPDATE fake_vm SET state = 'running' WHERE id = ? AND state = 'paused'`, id) + } + async exec(id: string, command: string, _timeoutMs: number) { if (!this.sql.exec<{ id: string }>(`SELECT id FROM fake_vm WHERE id = ?`, id)[0]) throw new DriverError("team_vm.vm_missing", "exec: 404", true) return this.guest.run(id, command) diff --git a/backend/apps/api/src/team-vm-export-route.ts b/backend/apps/api/src/team-vm-export-route.ts new file mode 100644 index 000000000000..c25ad59cad0f --- /dev/null +++ b/backend/apps/api/src/team-vm-export-route.ts @@ -0,0 +1,17 @@ +import type { Env } from "./env.ts" + +interface ExportStub { + exportDownload(entity: string, ticket: string): Promise +} + +/** + * `GET /v1/team-vm/export//` (cx-lyvg): the team files of a retired team VM as a tar. + * No bearer: a browser download cannot send one. The ticket (256 random bits, single use, 5 + * minutes) comes from the audited owner/admin op team_vm.retired.export; only that team's + * TeamVmDO knows it (it stores the SHA-256), so a ticket never opens another team's files. + */ +export const handleTeamVmExport = async (request: Request, env: Env, team: string, ticket: string): Promise => { + if (request.method !== "GET") return Response.json({ ok: false, error: { code: "validation.invalid", message: "GET only" } }, { status: 405, headers: { allow: "GET" } }) + const stub = env.TEAM_VM_DO.get(env.TEAM_VM_DO.idFromName(team)) as unknown as ExportStub + return stub.exportDownload(team, ticket) +} diff --git a/backend/apps/api/src/team-vm-export-run.ts b/backend/apps/api/src/team-vm-export-run.ts new file mode 100644 index 000000000000..fea2fdaee5e6 --- /dev/null +++ b/backend/apps/api/src/team-vm-export-run.ts @@ -0,0 +1,54 @@ +import { DriverError } from "./team-vm-driver.ts" +import { EXPORT_LIMITS, exportRefusal, exportResponse, planExport, type ExportTickets } from "./team-vm-export.ts" +import type { AdminReply, TaintRunDeps } from "./team-vm-taint-run.ts" + +/** TeamVmDO's side of team_vm.retired.export (team-vm-export.ts): the op after TeamDO's owner/admin check, and the download. */ +export type ExportRunDeps = TaintRunDeps & { readonly exportTickets: () => ExportTickets } + +/** The download path of a ticket; the dashboard puts the API origin in front. */ +export const exportPath = (team: string, ticket: string) => `/v1/team-vm/export/${team}/${ticket}` + +const provider = (d: TaintRunDeps): { ok: true; driver: NonNullable> } | { ok: false; code: string; message: string } => { + const refused = d.refusal() + const driver = refused ? null : d.driver() + return driver ? { ok: true, driver } : { ok: false, code: refused ?? "team_vm.not_configured", message: "no team VM provider is available on this deployment" } +} + +export const exportRetired = async (d: ExportRunDeps, req: { readonly vm: string; readonly by: string }): Promise => { + const s = d.state() + if (!s?.team) return { ok: false, code: "owner.unreachable", message: "team VM record not open" } + const row = (s.retired ?? []).find((r) => r.vm === req.vm) + const refused = exportRefusal(row) + if (refused) return refused + const p = provider(d) + if (!p.ok) return p + let plan: Awaited> + try { + plan = await planExport(p.driver, row!.vm) + } catch (e) { + if (e instanceof DriverError) return { ok: false, code: e.code, message: e.message } + throw e + } + if (!plan.ok) return plan + const now = Date.now() + const expiresAt = now + EXPORT_LIMITS.ticketMs + const { ticket, total } = await d.exportTickets().mint(row!.vm, req.by, plan.entries, expiresAt, now) + const value = { vm: row!.vm, path: exportPath(s.team, ticket), expires_at: expiresAt, files: plan.files, bytes: plan.bytes, archive_bytes: total, skipped: plan.skipped.slice(0, 50), skipped_count: plan.skipped.length } + return { ok: true, value, tainted_by: row!.tainted_by, epoch: row!.epoch } +} + +const refusal = (status: number, code: string, message: string) => Response.json({ ok: false, error: { code, message } }, { status, headers: { "cache-control": "private, no-store" } }) + +/** The download of one ticket: the ticket ends here; the VM must still be a fenced retired VM of this team. */ +export const downloadExport = async (d: ExportRunDeps, ticket: string): Promise => { + const taken = await d.exportTickets().take(ticket, Date.now()) + if (!taken) return refusal(404, "team_vm.export_ticket_invalid", "this download link expired or was used; start the download again") + const refused = exportRefusal((d.state()?.retired ?? []).find((r) => r.vm === taken.vm)) + if (refused) return refusal(409, refused.code, refused.message) + const p = provider(d) + if (!p.ok) return refusal(503, p.code, p.message) + return exportResponse(p.driver, taken.vm, taken.entries, taken.total) +} + +/** The answer for a ticket of a team without a VM record. */ +export const exportUnknown = () => refusal(404, "team_vm.export_ticket_invalid", "this download link expired or was used; start the download again") diff --git a/backend/apps/api/src/team-vm-export.ts b/backend/apps/api/src/team-vm-export.ts new file mode 100644 index 000000000000..8b24f02a5c20 --- /dev/null +++ b/backend/apps/api/src/team-vm-export.ts @@ -0,0 +1,205 @@ +import type { SqlStore } from "@cmux/ownership" +import { DriverError, type TeamVmDriver } from "./team-vm-driver.ts" +import { padding, TAR_END, tarHeader, tarLength, type TarEntry } from "./tar.ts" +import type { TeamVmRetired } from "./domains/team-vm-taint.ts" + +/** + * team_vm.retired.export (cx-lyvg): the team files (/srv/team) of a VM a rebuild retired, as one tar + * download. A retired VM is fenced (run budget spent, paused; cx-009a), so nothing in it runs and + * its files cannot change; the provider's file API still reads its disk. Nothing here starts, + * resumes or changes the VM: only fs list, stat and read calls. + * + * Two steps. The op (TeamDO role check and audit, then here) walks the tree once with list and + * stat, refuses what is over the limits, and stores the manifest under a single-use ticket. The + * download (`GET /v1/team-vm/export//`, no bearer: a browser download cannot send + * one) takes the ticket and streams the tar from the stored manifest: one provider read per file, + * piped chunk by chunk, so the Worker holds one chunk at a time, never the archive. The tar length + * is known from the manifest, so the response has a Content-Length and a short stream fails + * visibly instead of saving a cut archive. + * + * Why streaming and not R2: the only bucket is the Home attachments bucket (another owner and + * retention), and an R2 copy would need the same streaming plus a second store with its own + * deletion. A frozen VM is the archive's source of truth already. + */ +export const EXPORT_ROOT = "/srv/team" +/** The archive's top directory. */ +export const ARCHIVE_ROOT = "team" + +export const EXPORT_LIMITS = { + /** + * File bytes: 2 GiB. A browser download of that size finishes in minutes, ustar sizes stay far + * under their 8 GiB field, and the stream time limit below holds it at about 1.2 MB/s. + */ + maxBytes: 2 * 1024 ** 3, + /** Files, directories and skipped entries. Each costs one provider request in the walk and one in the download; Workers allow 10,000 per request. */ + maxEntries: 5000, + /** The walk's time limit (the op answers within it). */ + planMs: 60_000, + /** Parallel list/stat requests during the walk. */ + concurrency: 8, + /** The download's time limit: a stream still open after 30 minutes is cut (the browser shows a failed download). */ + streamMs: 30 * 60_000, + /** One read with no new bytes for this long is retried from where it stopped. */ + stallMs: 60_000, + /** Attempts per file (a broken provider stream resumes with a Range request). */ + readAttempts: 3, + /** The ticket is valid this long, for one download. */ + ticketMs: 5 * 60_000 +} as const + +export type ExportLimits = typeof EXPORT_LIMITS + +type Fail = { readonly ok: false; readonly code: string; readonly message: string } +export type Plan = { readonly ok: true; readonly entries: ReadonlyArray; readonly bytes: number; readonly files: number; readonly skipped: ReadonlyArray } | Fail + +const fail = (code: string, message: string): Fail => ({ ok: false, code, message }) +const SAFE_NAME = (n: string) => n.length > 0 && n !== "." && n !== ".." && !n.includes("/") && !n.includes("\0") + +/** Walks EXPORT_ROOT on `vm` (list and stat only) into a sorted manifest, or the refusal. */ +export const planExport = async (driver: TeamVmDriver, vm: string, limits: ExportLimits = EXPORT_LIMITS, now: () => number = Date.now): Promise => { + const deadline = now() + limits.planMs + const entries: Array = [{ path: ARCHIVE_ROOT, kind: "dir", size: 0, mode: 0o755, mtime: Math.floor(now() / 1000) }] + const skipped: Array = [] + let bytes = 0 + let dirs = [""] + while (dirs.length > 0) { + const next: Array = [] + for (let i = 0; i < dirs.length; i += limits.concurrency) { + if (now() > deadline) return fail("team_vm.export_timeout", "listing the team files took too long; try again") + const lists = await Promise.all(dirs.slice(i, i + limits.concurrency).map(async (rel) => ({ rel, items: await driver.files.list(vm, rel ? `${EXPORT_ROOT}/${rel}` : EXPORT_ROOT) }))) + const files: Array = [] + for (const { rel, items } of lists) { + if (items === null) { + if (rel === "") return fail("team_vm.export_no_files", `this VM has no ${EXPORT_ROOT}`) + continue + } + for (const it of items) { + const path = rel ? `${rel}/${it.name}` : it.name + if (!SAFE_NAME(it.name) || `${EXPORT_ROOT}/${path}`.length > 4000) skipped.push(path) + else if (it.kind === "directory") next.push(path) + else if (it.kind === "file") files.push(path) + else skipped.push(path) + } + } + if (entries.length + next.length + files.length + skipped.length > limits.maxEntries) return fail("team_vm.export_too_large", `the team files have more than ${limits.maxEntries} entries`) + for (let j = 0; j < files.length; j += limits.concurrency) { + if (now() > deadline) return fail("team_vm.export_timeout", "listing the team files took too long; try again") + const stats = await Promise.all(files.slice(j, j + limits.concurrency).map(async (path) => ({ path, st: await driver.files.stat(vm, `${EXPORT_ROOT}/${path}`) }))) + for (const { path, st } of stats) { + // A file that vanished between list and stat cannot happen on a fenced VM; skip it anyway. + if (!st || st.kind !== "file") { + skipped.push(path) + continue + } + bytes += st.size + if (bytes > limits.maxBytes) return fail("team_vm.export_too_large", `the team files are larger than ${limits.maxBytes} bytes`) + // A paused VM's disk answers no modification time (measured cx-lyvg): the export time stands in. + entries.push({ path: `${ARCHIVE_ROOT}/${path}`, kind: "file", size: st.size, mode: st.mode, mtime: st.mtime || Math.floor(now() / 1000), uname: st.owner, gname: st.group }) + } + } + } + for (const d of next) entries.push({ path: `${ARCHIVE_ROOT}/${d}`, kind: "dir", size: 0, mode: 0o755, mtime: Math.floor(now() / 1000) }) + dirs = next + } + entries.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)) + return { ok: true, entries, bytes, files: entries.filter((e) => e.kind === "file").length, skipped: skipped.sort() } +} + +const hex = (b: ArrayBuffer) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, "0")).join("") +const TICKET = /^[0-9a-f]{64}$/ +export const isTicket = (t: string) => TICKET.test(t) + +/** Single-use download tickets and their manifests, in TeamVmDO's SQLite. Only the ticket's SHA-256 is stored. */ +export class ExportTickets { + constructor(private readonly sql: SqlStore) { + sql.exec(`CREATE TABLE IF NOT EXISTS team_vm_export (ticket TEXT PRIMARY KEY, vm TEXT NOT NULL, by TEXT NOT NULL, expires_at INTEGER NOT NULL, total INTEGER NOT NULL)`) + sql.exec(`CREATE TABLE IF NOT EXISTS team_vm_export_entry (ticket TEXT NOT NULL, seq INTEGER NOT NULL, entry TEXT NOT NULL, PRIMARY KEY (ticket, seq))`) + } + + private sweep(now: number) { + this.sql.exec(`DELETE FROM team_vm_export_entry WHERE ticket IN (SELECT ticket FROM team_vm_export WHERE expires_at <= ?)`, now) + this.sql.exec(`DELETE FROM team_vm_export WHERE expires_at <= ?`, now) + } + + async mint(vm: string, by: string, entries: ReadonlyArray, expiresAt: number, now: number): Promise<{ ticket: string; total: number }> { + this.sweep(now) + const ticket = hex(crypto.getRandomValues(new Uint8Array(32)).buffer as ArrayBuffer) + const key = hex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(ticket))) + const total = tarLength(entries) + this.sql.exec(`INSERT INTO team_vm_export (ticket, vm, by, expires_at, total) VALUES (?, ?, ?, ?, ?)`, key, vm, by, expiresAt, total) + entries.forEach((e, i) => this.sql.exec(`INSERT INTO team_vm_export_entry (ticket, seq, entry) VALUES (?, ?, ?)`, key, i, JSON.stringify(e))) + return { ticket, total } + } + + /** Takes (and so ends) a valid ticket: its VM, manifest and archive length, or null. */ + async take(ticket: string, now: number): Promise<{ vm: string; entries: Array; total: number } | null> { + if (!isTicket(ticket)) return null + const key = hex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(ticket))) + const row = this.sql.exec<{ vm: string; expires_at: number; total: number }>(`SELECT vm, expires_at, total FROM team_vm_export WHERE ticket = ?`, key)[0] + const entries = row ? this.sql.exec<{ entry: string }>(`SELECT entry FROM team_vm_export_entry WHERE ticket = ? ORDER BY seq`, key).map((r) => JSON.parse(r.entry) as TarEntry) : [] + this.sql.exec(`DELETE FROM team_vm_export_entry WHERE ticket = ?`, key) + this.sql.exec(`DELETE FROM team_vm_export WHERE ticket = ?`, key) + this.sweep(now) + return row && row.expires_at > now ? { vm: row.vm, entries, total: row.total } : null + } +} + +/** Why a retired row may not be read now, or null: only a paused row with the fence confirmed (the VM can never run again). */ +export const exportRefusal = (row: TeamVmRetired | undefined): Fail | null => { + if (!row) return fail("selector.not_found", "no retired team VM with this id") + if (row.state !== "paused" || row.fenced !== true) return fail("team_vm.retired_not_fenced", "the retired VM is not fenced yet (paused with its run budget spent); try again in a few minutes") + return null +} + +/** Reads one file into the writer from `offset`, resuming a broken provider stream with a Range request. */ +const copyFile = async (driver: TeamVmDriver, vm: string, e: TarEntry, w: WritableStreamDefaultWriter, deadline: number, limits: ExportLimits) => { + const source = `${EXPORT_ROOT}/${e.path.slice(ARCHIVE_ROOT.length + 1)}` + let sent = 0 + for (let attempt = 1; sent < e.size; attempt++) { + const ctl = new AbortController() + try { + const body = await driver.files.read(vm, source, sent, AbortSignal.any([ctl.signal, AbortSignal.timeout(Math.max(1, deadline - Date.now()))])) + const reader = body.getReader() + for (;;) { + let stall: ReturnType | undefined + const chunk = await Promise.race([reader.read(), new Promise((_, reject) => (stall = setTimeout(() => reject(new Error("read stalled")), limits.stallMs)))]).finally(() => clearTimeout(stall)) + if (chunk.done) break + if (sent + chunk.value.byteLength > e.size) throw new DriverError("team_vm.export_changed", `fs read: ${e.path} is longer than its stat`, true) + await w.write(chunk.value) + sent += chunk.value.byteLength + } + if (sent < e.size) throw new DriverError("team_vm.export_changed", `fs read: ${e.path} is shorter than its stat`, true) + } catch (err) { + ctl.abort() + const final = err instanceof DriverError && err.final + if (final || attempt >= limits.readAttempts || Date.now() > deadline) throw err + } + } +} + +/** The download: the tar of `entries` streamed from `vm`, bounded by the stream time limit. */ +export const exportResponse = (driver: TeamVmDriver, vm: string, entries: ReadonlyArray, total: number, limits: ExportLimits = EXPORT_LIMITS): Response => { + const { readable, writable } = new FixedLengthStream(total) + const w = writable.getWriter() + const deadline = Date.now() + limits.streamMs + const run = async () => { + for (const e of entries) { + await w.write(tarHeader(e)) + if (e.kind !== "file") continue + if (e.size > 0) await copyFile(driver, vm, e, w, deadline, limits) + const pad = padding(e.size) + if (pad > 0) await w.write(new Uint8Array(pad)) + } + await w.write(TAR_END) + await w.close() + } + run().catch(async (err: unknown) => { + // A cut stream: the length check makes the browser report a failed download, never a short archive saved as complete. + console.warn(JSON.stringify({ msg: "team vm export stream failed", vm, error: err instanceof DriverError ? `${err.code} ${err.message}` : String(err).slice(0, 200) })) + await w.abort(err).catch(() => undefined) + }) + const name = `cmux-team-files-${vm.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 80)}.tar` + return new Response(readable, { + headers: { "content-type": "application/x-tar", "content-disposition": `attachment; filename="${name}"`, "cache-control": "private, no-store", "x-content-type-options": "nosniff", "referrer-policy": "no-referrer" } + }) +} diff --git a/backend/apps/api/src/team-vm-journal.ts b/backend/apps/api/src/team-vm-journal.ts index d90c91e885b6..6d3d9d3bfbc6 100644 --- a/backend/apps/api/src/team-vm-journal.ts +++ b/backend/apps/api/src/team-vm-journal.ts @@ -1,4 +1,5 @@ -import type { SqlStore } from "@cmux/ownership" +import type { Principal, SqlStore } from "@cmux/ownership" +import type { TeamVmState } from "./domains/team-vm.ts" /** * The team journal (plans/cmux-next/team-vm-plan.md 3b, S6): the zero-loss tier for writes the @@ -142,3 +143,15 @@ export class TeamJournal { return { entries, high_water: this.highWater(stream).high_water, more } } } + +/** + * The journal is the team's zero-loss tier and holds every person's files: only the VM's own + * install for the current epoch reads or writes it, never a member's session or another install. + */ +export const journalCaller = (state: TeamVmState, p: Principal, risk: "read" | "mutate-own"): { ok: true } | { ok: false; code: string; message: string } => { + if (p.kind !== "install" || p.team === undefined || p.team !== state.team) return { ok: false, code: "auth.forbidden", message: "only the team VM's install uses the journal" } + if (!state.vm_install) return { ok: false, code: "team_vm.not_bound", message: "the team VM has not bound its install yet" } + if (p.install !== state.vm_install) return { ok: false, code: "auth.forbidden", message: "only the team VM's install uses the journal" } + if (!p.grant_classes?.includes(risk)) return { ok: false, code: "auth.forbidden", message: `grant does not cover ${risk}` } + return { ok: true } +} diff --git a/backend/apps/api/src/team-vm-taint-admin.ts b/backend/apps/api/src/team-vm-taint-admin.ts index 5b628fad60d9..e228f98f0d2a 100644 --- a/backend/apps/api/src/team-vm-taint-admin.ts +++ b/backend/apps/api/src/team-vm-taint-admin.ts @@ -1,5 +1,5 @@ import type { OwnerFrame, Principal, RowReader } from "@cmux/ownership" -import { TeamVmRebuild, TeamVmRetiredDelete, TeamVmTaintAccept } from "@cmux/protocol" +import { TeamVmRebuild, TeamVmRetiredDelete, TeamVmRetiredExport, TeamVmTaintAccept } from "@cmux/protocol" import { decodeParams } from "./domains/common.ts" import { memberOf, roleOf } from "./domains/team-members.ts" import type { TeamState } from "./domains/team.ts" @@ -7,8 +7,8 @@ import type { DomainReply } from "./team-domain-external.ts" import type { AdminReply, AdminRequest } from "./team-vm-taint-run.ts" /** - * The owner actions on a tainted team VM (cx-q4f3): team_vm.taint.accept, team_vm.rebuild and - * team_vm.retired.delete. TeamDO holds the roles and the audit chain, so the request comes here + * The owner actions on a tainted team VM (cx-q4f3): team_vm.taint.accept, team_vm.rebuild, + * team_vm.retired.delete and team_vm.retired.export (cx-lyvg, a read of the retired VM's files, audited). TeamDO holds the roles and the audit chain, so the request comes here * first: an owner or admin in a person's session only, then TeamVmDO acts, then TeamDO audits the * outcome in its chain. */ @@ -21,7 +21,7 @@ export interface VmAdminDeps { readonly teamVm: { adminAction(entity: string, req: AdminRequest): Promise } } -const defs = { "team_vm.taint.accept": TeamVmTaintAccept, "team_vm.rebuild": TeamVmRebuild, "team_vm.retired.delete": TeamVmRetiredDelete } as const +const defs = { "team_vm.taint.accept": TeamVmTaintAccept, "team_vm.rebuild": TeamVmRebuild, "team_vm.retired.delete": TeamVmRetiredDelete, "team_vm.retired.export": TeamVmRetiredExport } as const export const vmAdminExternal = async (deps: VmAdminDeps, p: Principal, frame: { op: string; params: unknown; idempotency_key: string }): Promise => { const base = { op: frame.op, transaction: "", idempotency_key: frame.idempotency_key, stream: deps.stream, sequence: 0, replayed: false } @@ -41,8 +41,8 @@ export const vmAdminExternal = async (deps: VmAdminDeps, p: Principal, frame: { // The caller's identity scopes the key, so two owners' requests never share a replay. const key = `${p.identity}|${frame.idempotency_key}` const req: AdminRequest = - frame.op === "team_vm.retired.delete" - ? { action: "delete", by: p.user, vm: d.value.vm!, key } + frame.op === "team_vm.retired.delete" || frame.op === "team_vm.retired.export" + ? { action: frame.op === "team_vm.retired.delete" ? "delete" : "export", by: p.user, vm: d.value.vm!, key } : frame.op === "team_vm.rebuild" ? { action: "rebuild", by: p.user, epoch: d.value.epoch!, key } : { action: "accept", by: p.user, epoch: d.value.epoch!, users: d.value.users ?? [], key } @@ -53,8 +53,8 @@ export const vmAdminExternal = async (deps: VmAdminDeps, p: Principal, frame: { return fail("owner.unreachable", "the team VM record did not answer; try again", true) } if (!r.ok) return fail(r.code, r.message, r.code === "owner.unreachable") - const action = req.action === "accept" ? "taint_accepted" : req.action === "rebuild" ? "rebuild" : "retired_deleted" - const audit = { action, by: p.user, epoch: r.epoch, tainted_by: r.tainted_by, ...(req.action === "delete" ? { vm: req.vm } : {}) } + const action = ({ accept: "taint_accepted", rebuild: "rebuild", delete: "retired_deleted", export: "retired_exported" } as const)[req.action] + const audit = { action, by: p.user, epoch: r.epoch, tainted_by: r.tainted_by, ...(req.action === "delete" || req.action === "export" ? { vm: req.vm } : {}) } const rej = deps.submitSystem("team_vm.taint_audit", audit, `taint-admin:${action}:${key}`).frames.find((f) => f.t === "reject") // The action happened; a failed audit is logged loudly rather than reported as a failed action. if (rej) console.error(JSON.stringify({ msg: "team vm taint audit refused", team: deps.team, action, code: rej.t === "reject" ? rej.code : "" })) diff --git a/backend/apps/api/src/team-vm-taint-run.ts b/backend/apps/api/src/team-vm-taint-run.ts index 100a787ae55b..6017b14aea30 100644 --- a/backend/apps/api/src/team-vm-taint-run.ts +++ b/backend/apps/api/src/team-vm-taint-run.ts @@ -1,7 +1,8 @@ import type { OwnerFrame } from "@cmux/ownership" -import { currentTaint, pausingRetired, taintBlocks, type TeamVmTaint } from "./domains/team-vm-taint.ts" +import { currentTaint, pausingRetired, retireDue, taintBlocks, type TeamVmTaint } from "./domains/team-vm-taint.ts" import type { TeamVmState } from "./domains/team-vm.ts" import { DriverError, type TeamVmDriver } from "./team-vm-driver.ts" +import { exportRetired, type ExportRunDeps } from "./team-vm-export-run.ts" /** * TeamVmDO's side of the taint (cx-q4f3, domains/team-vm-taint.ts): the owner actions TeamDO @@ -23,6 +24,7 @@ export type AdminRequest = | { readonly action: "accept"; readonly by: string; readonly epoch: number; readonly users: ReadonlyArray; readonly key: string } | { readonly action: "rebuild"; readonly by: string; readonly epoch: number; readonly key: string } | { readonly action: "delete"; readonly by: string; readonly vm: string; readonly key: string } + | { readonly action: "export"; readonly by: string; readonly vm: string; readonly key: string } export type AdminReply = { ok: true; value: Record; tainted_by: ReadonlyArray; epoch: number } | { ok: false; code: string; message: string } @@ -46,7 +48,7 @@ const outcome = (frames: ReadonlyArray): { ok: true; value: Record } } -export const adminAction = async (d: TaintRunDeps, req: AdminRequest): Promise => { +export const adminAction = async (d: ExportRunDeps, req: AdminRequest): Promise => { const s = d.state() if (!s) return { ok: false, code: "owner.unreachable", message: "team VM record not open" } const taintedBy = currentTaint(s)?.users ?? [] @@ -65,6 +67,7 @@ export const adminAction = async (d: TaintRunDeps, req: AdminRequest): Promise x.vm === req.vm) if (!row) return { ok: false, code: "selector.not_found", message: "no retired team VM with this id" } const del = await d.deleteVm(row.vm, req.by) @@ -73,24 +76,25 @@ export const adminAction = async (d: TaintRunDeps, req: AdminRequest): Promise => { - const due = (d.state()?.retired ?? []).filter((r) => r.state === "pausing" && (r.pause_retry_at ?? r.at) <= now) + const due = (d.state()?.retired ?? []).filter((r) => retireDue(r) && (r.pause_retry_at ?? r.at) <= now) if (due.length === 0) return const driver = d.driver() for (const r of due) { const attempt = r.pause_attempts ?? 0 try { if (!driver) throw new DriverError("team_vm.not_configured", "no team VM provider", false) - await driver.pauseVm(r.vm) + await driver.retireVm(r.vm) } catch (e) { // A VM deleted outside cmux is as good as paused: nothing of it runs. if (!(e instanceof DriverError && e.code === "team_vm.vm_missing")) { console.warn(JSON.stringify({ msg: "team vm retired pause failed", vm: r.vm, attempt: attempt + 1, error: e instanceof DriverError ? e.code : String(e) })) - d.submitSystem("team_vm.retired_pause_failed", { vm: r.vm }, `retired-pause-failed:${r.vm}:${attempt}`) + // The keys carry the fence (cx-009a): a row paused before it already used the old keys, and a replay does not reduce again. + d.submitSystem("team_vm.retired_pause_failed", { vm: r.vm }, `retired-fence-failed:${r.vm}:${attempt}`) continue } } - d.submitSystem("team_vm.retired_paused", { vm: r.vm }, `retired-paused:${r.vm}`) + d.submitSystem("team_vm.retired_paused", { vm: r.vm }, `retired-fenced:${r.vm}`) } } diff --git a/backend/apps/api/src/user-do.ts b/backend/apps/api/src/user-do.ts index 67f5d092d6cc..f202d7676295 100644 --- a/backend/apps/api/src/user-do.ts +++ b/backend/apps/api/src/user-do.ts @@ -7,7 +7,7 @@ import { deliverKrlNotices, krlDueAt, type KrlRetry } from "./user-krl.ts" import { emailDomainOf, verifyInstallSignature, type InstallClaims } from "./auth.ts" import { verifyAttestation, type AttestedKey } from "./app-attest.ts" import { admit } from "./domains/common.ts" -import { chiefActive, grantFor, inboxRefusalFor, installActive, iosGrantsToMigrate, userPathAllowed, jwkThumbprint, makeUserDomain, type UserState } from "./domains/user.ts" +import { chiefActive, grantFor, inboxRefusalFor, installActive, grantMigrationsDue, userPathAllowed, jwkThumbprint, makeUserDomain, type UserState } from "./domains/user.ts" import { appIdHashFor, confirmView } from "./domains/user-confirm.ts" import { CHIEF_AGENT_CLASS, chiefList, placedChiefClasses } from "./domains/user-chief.ts" import type { Env } from "./env.ts" @@ -89,10 +89,10 @@ export class UserDO extends OwnerDO { return true } - /** CLOUD-LINK-FOLLOWUPS decision 2: old iPhone grants get cloud-link once (idempotent; nothing to do = no op). */ + /** One-time grant migrations (idempotent; nothing to do = no op): old iPhone grants get cloud-link (CLOUD-LINK-FOLLOWUPS decision 2); old Mac grants lose execute (cx-wb5.64). */ protected override bind(entity: string) { const engine = super.bind(entity) - if (iosGrantsToMigrate(engine.currentState).length) this.submitSystem("install.ios_cloud_link_migrate", {}, `ios-cloud-link:${engine.currentSeq}`) + for (const [op, key] of grantMigrationsDue(engine.currentState)) this.submitSystem(op, {}, `${key}:${engine.currentSeq}`) return engine } diff --git a/backend/apps/api/test/install-mac-execute-narrow.test.ts b/backend/apps/api/test/install-mac-execute-narrow.test.ts new file mode 100644 index 000000000000..763d463678ed --- /dev/null +++ b/backend/apps/api/test/install-mac-execute-narrow.test.ts @@ -0,0 +1,97 @@ +import type { ReduceContext } from "@cmux/ownership" +import { describe, expect, it } from "vitest" +import { macGrantsToNarrow, userDomain, type UserState } from "../src/domains/user.ts" +import { env } from "cloudflare:workers" +import { runInDurableObject } from "cloudflare:test" +import { post, sessionToken } from "./cloud-bind-support.ts" + +/** + * cx-wb5.64: Mac installs registered before the mac grant cap (e9d25623248e) got the old default + * (read, mutate-own, mutate-shared, execute). One idempotent server-side migration (internal + * install.mac_execute_narrow, run on bind) drops execute from their grants and keeps every other + * class. No class is added, and nothing but an active mac install's grant changes. + */ + +const OWNER = "user_00000000000000000001" +const jwk = { kty: "EC", crv: "P-256", x: "x".repeat(43), y: "y".repeat(43) } +const inst = (id: string, kind: string, grant: string, revoked: number | null = null) => ({ + id, device: `dev_${id.slice(5)}`, kind, name: id, device_name: id, platform: kind === "ios" ? "ios" : "macos", public_jwk: jwk, thumbprint: id, grant, created_at: 1, revoked_at: revoked +}) +const grant = (id: string, grantee: string, op_classes: Array, revoked: number | null = null) => ({ id, grantee, op_classes, approval: "none", expires_at: null, revoked_at: revoked, created_from: "install" }) +const OLD_MAC = ["read", "mutate-own", "mutate-shared", "execute"] +const state = { + user: { id: OWNER, stack_user_id: "s", email: null, display_name: "o", personal_team: "team_00000000000000000001" }, + installs: { + inst_mac_old_000000000000: inst("inst_mac_old_000000000000", "mac", "grant_a"), + inst_mac_new_000000000000: inst("inst_mac_new_000000000000", "mac", "grant_b"), + inst_mac_rev_000000000000: inst("inst_mac_rev_000000000000", "mac", "grant_c", 5), + inst_cli_000000000000000: inst("inst_cli_000000000000000", "cli", "grant_d"), + inst_mac_link_00000000000: inst("inst_mac_link_00000000000", "mac", "grant_e") + }, + grants: { + grant_a: grant("grant_a", "inst_mac_old_000000000000", OLD_MAC), + grant_b: grant("grant_b", "inst_mac_new_000000000000", ["read", "mutate-own", "mutate-shared", "cloud-link"]), + grant_c: grant("grant_c", "inst_mac_rev_000000000000", OLD_MAC), + grant_d: grant("grant_d", "inst_cli_000000000000000", OLD_MAC), + grant_e: grant("grant_e", "inst_mac_link_00000000000", ["read", "cloud-link", "execute"]) + } +} as unknown as UserState +const sys: ReduceContext = { principal: { identity: "system:user", kind: "system" }, now: 9, tx: "t", newId: (p) => `${p}_x` } + +describe("old Mac grants lose execute once", () => { + it("finds only active mac grants that still carry execute", () => { + expect(macGrantsToNarrow(state).sort()).toEqual(["grant_a", "grant_e"]) + }) + + it("drops execute and keeps every other class, and a second run changes nothing", () => { + const r = userDomain.reduce(state, "install.mac_execute_narrow", {}, sys) + if (!r.ok) throw new Error(r.message) + const s = r.state as UserState + expect([...s.grants["grant_a"]!.op_classes].sort()).toEqual(["mutate-own", "mutate-shared", "read"]) + expect([...s.grants["grant_e"]!.op_classes].sort()).toEqual(["cloud-link", "read"]) + expect(s.grants["grant_b"]).toEqual(state.grants["grant_b"]) + expect(s.grants["grant_c"]).toEqual(state.grants["grant_c"]) + expect(s.grants["grant_d"]).toEqual(state.grants["grant_d"]) + expect(r.value).toEqual({ narrowed: 2 }) + expect(macGrantsToNarrow(s)).toEqual([]) + const again = userDomain.reduce(s, "install.mac_execute_narrow", {}, sys) + if (!again.ok) throw new Error(again.message) + expect(again.state).toEqual(s) + }) + + it("runs once per user: after the done flag, a mac grant with execute is left alone", () => { + const r = userDomain.reduce(state, "install.mac_execute_narrow", {}, sys) + if (!r.ok) throw new Error(r.message) + const done = r.state as UserState + expect(done.migrations?.mac_execute_narrow).toBe(true) + const later = { ...done, grants: { ...done.grants, grant_a: grant("grant_a", "inst_mac_old_000000000000", OLD_MAC) } } as unknown as UserState + expect(macGrantsToNarrow(later)).toEqual([]) + }) + + it("is refused for a non-system caller", () => { + const session: ReduceContext = { ...sys, principal: { identity: `user:${OWNER}`, user: OWNER, kind: "session" } } + expect(userDomain.reduce(state, "install.mac_execute_narrow", {}, session)).toMatchObject({ ok: false }) + }) + + it("the per-request grant check (installGrant) narrows an old Mac grant first, so execute is gone at once", { timeout: 60_000 }, async () => { + const session = await sessionToken("mac-execute-narrow-grant-path") + const user = (await post("/v1/ops", session, { op: "user.ensure", params: {}, idempotency_key: crypto.randomUUID(), origin: "user" })).body.value.id as string + const pair = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"])) as CryptoKeyPair + const j = (await crypto.subtle.exportKey("jwk", pair.publicKey)) as JsonWebKey + const reg = await post("/v1/ops", session, { op: "install.register", params: { public_jwk: { kty: "EC", crv: "P-256", x: j.x, y: j.y }, kind: "mac", name: "cmux", device_name: "m", platform: "macos" }, idempotency_key: crypto.randomUUID(), origin: "user" }) + expect(reg.body.ok, JSON.stringify(reg.body)).toBe(true) + const install = reg.body.value.id as string + const grantId = reg.body.value.grant as string + const ns = (env as unknown as { USER_DO: DurableObjectNamespace }).USER_DO + const stub = ns.get(ns.idFromName(user)) + // Give the grant the pre-cap default (in memory only) and clear the done flag, as on a user from before the cap. + await (runInDurableObject as unknown as (s: unknown, f: (i: any) => Promise) => Promise)(stub, async (i) => { + const st = i.boundEngine.currentState + st.grants[grantId] = { ...st.grants[grantId], op_classes: OLD_MAC } + if (st.migrations) delete st.migrations.mac_execute_narrow + }) + const r = await (stub as unknown as { installGrant(e: string, i: string, g: string): Promise<{ ok: boolean; op_classes?: ReadonlyArray }> }).installGrant(user, install, grantId) + expect(r.ok).toBe(true) + expect([...(r.op_classes ?? [])].sort()).toEqual(["mutate-own", "mutate-shared", "read"]) + }) +}) diff --git a/backend/apps/api/test/team-vm-export.test.ts b/backend/apps/api/test/team-vm-export.test.ts new file mode 100644 index 000000000000..7a83b06c0986 --- /dev/null +++ b/backend/apps/api/test/team-vm-export.test.ts @@ -0,0 +1,242 @@ +import { env } from "cloudflare:workers" +import type { Principal } from "@cmux/ownership" +import { afterEach, describe, expect, it, vi } from "vitest" +import { FakeDriver, FreestyleDriver } from "../src/team-vm-driver.ts" +import { api, inDO, mutate, setup, sshLine, worker } from "./team-ssh-support.ts" +import { fireAlarm } from "./setup/alarm.ts" + +/** + * cx-lyvg: a rebuild retires the old team VM with its team files on /srv/team, and the fence + * (cx-009a) means it never runs again, so nothing can copy the files off over SSH. Owners and + * admins download them with team_vm.retired.export: the op walks /srv/team through the provider's + * file API (the VM stays paused and fenced) and answers a single-use download path; the download + * streams a tar of exactly those files. + */ +const ns = (env as unknown as { TEAM_VM_DO: DurableObjectNamespace }).TEAM_VM_DO +const vmStub = (team: string) => ns.get(ns.idFromName(team)) as any +const files = (team: string, fn: (f: FakeDriver["files"]) => void) => inDO(vmStub(team), async (instance) => fn(new FakeDriver(instance.sqlStore).files)) +const fakeState = (team: string, vm: string) => + inDO(vmStub(team), async (_i, st) => st.storage.sql.exec<{ state: string }>(`SELECT state FROM fake_vm WHERE id = ?`, vm).toArray()[0]?.state ?? null) +const fenced = (team: string, vm: string) => inDO(vmStub(team), async (_i, st) => st.storage.sql.exec(`SELECT 1 FROM fake_fence WHERE id = ?`, vm).toArray().length === 1) + +/** A tar parser for the test: entry name (pax `path` first), type and bytes. */ +const untar = (buf: Uint8Array) => { + const dec = new TextDecoder() + const str = (b: Uint8Array) => dec.decode(b.subarray(0, b.indexOf(0) < 0 ? b.length : b.indexOf(0))) + const out: Array<{ name: string; type: string; mode: number; data: Uint8Array }> = [] + let pax: string | null = null + let o = 0 + while (o + 512 <= buf.length) { + const h = buf.subarray(o, o + 512) + if (h.every((b) => b === 0)) break + let sum = 0 + for (let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 32 : h[i]! + expect(parseInt(str(h.subarray(148, 156)).trim(), 8)).toBe(sum) + const size = parseInt(str(h.subarray(124, 136)), 8) + const type = String.fromCharCode(h[156]!) + const data = buf.subarray(o + 512, o + 512 + size) + o += 512 + Math.ceil(size / 512) * 512 + if (type === "x") { + pax = /\d+ path=([^\n]*)\n/.exec(dec.decode(data))?.[1] ?? null + continue + } + out.push({ name: pax ?? str(h.subarray(0, 100)), type, mode: parseInt(str(h.subarray(100, 108)), 8), data: new Uint8Array(data) }) + pax = null + } + return out +} + +let n = 0 +/** A team whose VM a rebuild retired (fenced), with team files written on the old VM first. */ +const retired = async (opts: { failPause?: boolean; seed?: (f: FakeDriver["files"], vm: string) => void } = {}) => { + const t = await setup(`stack-export-${String(++n).padStart(4, "0")}${Date.now() % 1_000_000}`) + const admin = (p: Principal, op: string, params: unknown) => (t.stub as any).vmAdminOp(t.team, p, { op, params, idempotency_key: crypto.randomUUID() }) + const status = async () => (await api(t.token, "/v1/read", { op: "team_vm.status", params: {} })).value + const woke = await mutate(t.token, "team_vm.ensure_awake", { reason: "ssh" }) + expect(woke.ok, JSON.stringify(woke)).toBe(true) + const first = woke.value as { vm: string; epoch: number } + await files(t.team, (f) => (opts.seed ?? defaultSeed)(f, first.vm)) + expect((await t.op(t.memberP, "team_vm.ssh_cert", { public_key: await sshLine("ed25519"), class: "agent" })).ok).toBe(true) + const removed = await inDO(t.stub, async (instance) => instance.submitSystem("team.member.remove", { user: t.member }, `remove:${t.member}:${crypto.randomUUID()}`)) + expect(removed.frames.find((f: any) => f.t === "reject")).toBeUndefined() + await fireAlarm(t.stub) + await fireAlarm(t.stub) + if (opts.failPause) await vmStub(t.team).fakeControl({ fail_pause: 1000 }) + expect((await admin(t.ownerP, "team_vm.rebuild", { epoch: first.epoch })).ok).toBe(true) + const download = (path: string) => worker.fetch(`https://api.test${path}`) + const audits = () => + inDO(t.stub, async (_i, st) => + st.storage.sql + .exec<{ payload: string }>(`SELECT payload FROM own_outbox WHERE kind = 'audit.append' ORDER BY id`) + .toArray() + .map((r) => JSON.parse(r.payload) as { op: string; detail: any }) + .filter((a) => a.op === "team_vm.taint_audit" && a.detail?.action === "retired_exported") + ) + return { ...t, first, admin, status, download, audits } +} + +const LONG = `${"deep/".repeat(30)}notes-日本語.md` +const BINARY = Uint8Array.from({ length: 1500 }, (_, i) => (i * 7) % 256) +const defaultSeed = (f: FakeDriver["files"], vm: string) => { + f.put(vm, "/srv/team/README.md", "team readme\n") + f.put(vm, "/srv/team/src/app.ts", "export const x = 1\n", { mode: 0o755 }) + f.put(vm, "/srv/team/bin/blob.dat", BINARY) + f.put(vm, `/srv/team/${LONG}`, "long path\n") + f.put(vm, "/srv/team/link", "/etc/passwd", { kind: "symlink" }) + f.mkdir(vm, "/srv/team/empty") + // Outside /srv/team: never exported. + f.put(vm, "/home/alice/secret.txt", "not team files") +} + +describe("team_vm.retired.export (cx-lyvg)", { timeout: 60_000 }, () => { + it("an owner downloads /srv/team of the fenced retired VM as a tar; the VM stays paused and fenced", async () => { + const t = await retired() + expect((await t.status()).retired).toEqual([expect.objectContaining({ vm: t.first.vm, state: "paused" })]) + const starts = (await vmStub(t.team).fakeControl({})).starts + const r = await t.admin(t.ownerP, "team_vm.retired.export", { vm: t.first.vm }) + expect(r.ok, JSON.stringify(r)).toBe(true) + expect(r.value).toMatchObject({ vm: t.first.vm, files: 4, bytes: 12 + 19 + 1500 + 10, skipped: ["link"], skipped_count: 1 }) + expect(r.value.path).toMatch(new RegExp(`^/v1/team-vm/export/${t.team}/[0-9a-f]{64}$`)) + const res = await t.download(r.value.path) + expect(res.status).toBe(200) + expect(res.headers.get("content-type")).toBe("application/x-tar") + expect(res.headers.get("referrer-policy")).toBe("no-referrer") + expect(res.headers.get("content-disposition")).toMatch(/^attachment; filename="cmux-team-files-.+\.tar"$/) + const body = new Uint8Array(await res.arrayBuffer()) + expect(body.length).toBe(r.value.archive_bytes) + expect(Number(res.headers.get("content-length") ?? body.length)).toBe(body.length) + const entries = untar(body) + const text = (name: string) => new TextDecoder().decode(entries.find((e) => e.name === name)?.data) + expect(entries.map((e) => e.name).sort()).toEqual( + ["team/", "team/README.md", "team/bin/", "team/bin/blob.dat", "team/empty/", "team/src/", "team/src/app.ts", ...LONG.split("/").slice(0, -1).map((_, i, a) => `team/${a.slice(0, i + 1).join("/")}/`), `team/${LONG}`].sort() + ) + expect(text("team/README.md")).toBe("team readme\n") + expect(entries.find((e) => e.name === "team/src/app.ts")?.mode).toBe(0o755) + expect([...entries.find((e) => e.name === "team/bin/blob.dat")!.data]).toEqual([...BINARY]) + expect(text(`team/${LONG}`)).toBe("long path\n") + // Never started, never unfenced: still paused, still with its budget spent. + expect(await fakeState(t.team, t.first.vm)).toBe("paused") + expect(await fenced(t.team, t.first.vm)).toBe(true) + expect((await vmStub(t.team).fakeControl({})).starts).toBe(starts) + // Audited in the team's chain, with the VM. + expect(await t.audits()).toEqual([expect.objectContaining({ detail: expect.objectContaining({ action: "retired_exported", by: t.owner, vm: t.first.vm }) })]) + // The ticket is single use. + const again = await t.download(r.value.path) + expect(again.status).toBe(404) + expect(((await again.json()) as any).error.code).toBe("team_vm.export_ticket_invalid") + }) + + it("members, agents and other teams' owners cannot export; refusals are not audited", async () => { + const t = await retired() + const agent: Principal = { ...t.ownerP, agent: "agent_x" } as Principal + for (const p of [t.memberP, agent, { ...t.ownerP, kind: "install", install: "inst_00000000000000000081" } as Principal]) { + expect((await t.admin(p, "team_vm.retired.export", { vm: t.first.vm })).error?.code).toBe("auth.forbidden") + } + expect((await t.admin(t.ownerP, "team_vm.retired.export", { vm: "vm_not_retired" })).error?.code).toBe("selector.not_found") + expect((await t.admin(t.ownerP, "team_vm.retired.export", {})).error?.code).toBe("validation.invalid") + expect(await t.audits()).toEqual([]) + // A ticket names its team: the same ticket under another team's path opens nothing. + const r = await t.admin(t.ownerP, "team_vm.retired.export", { vm: t.first.vm }) + expect(r.ok, JSON.stringify(r)).toBe(true) + const other = await t.download(r.value.path.replace(t.team, "team_00000000000000000000")) + expect(other.status).toBe(404) + const own = await t.download(r.value.path) + expect(own.status).toBe(200) + expect((await own.arrayBuffer()).byteLength).toBe(r.value.archive_bytes) + }) + + it("a retired VM that is not fenced yet is refused, and its download too; nothing starts it", async () => { + const t = await retired({ failPause: true }) + expect((await t.status()).retired).toEqual([expect.objectContaining({ vm: t.first.vm, state: "pausing" })]) + const r = await t.admin(t.ownerP, "team_vm.retired.export", { vm: t.first.vm }) + expect(r.error?.code, JSON.stringify(r)).toBe("team_vm.retired_not_fenced") + expect(await t.audits()).toEqual([]) + // A ticket minted while fenced is refused at download when the row is no longer a fenced retired VM. + await vmStub(t.team).fakeControl({ fail_pause: 0 }) + await vmStub(t.team).fakeAlarm(10 * 60_000) + const ok = await t.admin(t.ownerP, "team_vm.retired.export", { vm: t.first.vm }) + expect(ok.ok, JSON.stringify(ok)).toBe(true) + expect((await t.admin(t.ownerP, "team_vm.retired.delete", { vm: t.first.vm, files_copied: true })).ok).toBe(true) + const gone = await t.download(ok.value.path) + expect(gone.status).toBe(409) + expect(((await gone.json()) as any).error.code).toBe("selector.not_found") + }) + + it("over the limits (2 GiB of files) or without /srv/team: declared errors, no ticket", async () => { + const big = await retired({ seed: (f, vm) => (f.put(vm, "/srv/team/a.bin", "x", { stat_size: 2 * 1024 ** 3 }), f.put(vm, "/srv/team/b.bin", "y")) }) + expect((await big.admin(big.ownerP, "team_vm.retired.export", { vm: big.first.vm })).error?.code).toBe("team_vm.export_too_large") + const none = await retired({ seed: (f, vm) => f.put(vm, "/home/alice/x", "x") }) + expect((await none.admin(none.ownerP, "team_vm.retired.export", { vm: none.first.vm })).error?.code).toBe("team_vm.export_no_files") + const many = await retired({ seed: (f, vm) => Array.from({ length: 5001 }, (_, i) => f.put(vm, `/srv/team/f${i}`, "")) }) + expect((await many.admin(many.ownerP, "team_vm.retired.export", { vm: many.first.vm })).error?.code).toBe("team_vm.export_too_large") + expect([...(await big.audits()), ...(await none.audits()), ...(await many.audits())]).toEqual([]) + }) + + it("a provider stream that breaks mid-file resumes from the byte it stopped at", async () => { + const t = await retired({ seed: (f, vm) => f.put(vm, "/srv/team/big.dat", BINARY, { cut_once: 700 }) }) + const r = await t.admin(t.ownerP, "team_vm.retired.export", { vm: t.first.vm }) + expect(r.ok, JSON.stringify(r)).toBe(true) + const body = new Uint8Array(await (await t.download(r.value.path)).arrayBuffer()) + expect([...untar(body).find((e) => e.name === "team/big.dat")!.data]).toEqual([...BINARY]) + }) + + it("an expired ticket opens nothing", async () => { + const t = await retired() + const r = await t.admin(t.ownerP, "team_vm.retired.export", { vm: t.first.vm }) + await inDO(vmStub(t.team), async (_i, st) => st.storage.sql.exec(`UPDATE team_vm_export SET expires_at = 1`)) + expect((await t.download(r.value.path)).status).toBe(404) + }) +}) + +describe("FreestyleDriver files (cx-lyvg)", () => { + afterEach(() => vi.unstubAllGlobals()) + const provider = (answers: Array<[number, unknown]>) => { + const calls: Array<{ path: string; range: string | null }> = [] + vi.stubGlobal("fetch", async (url: string, init: RequestInit) => { + const u = new URL(url) + calls.push({ path: `${u.pathname}${u.search}`, range: new Headers(init.headers).get("range") }) + const [status, body] = answers.shift() ?? [500, {}] + return body instanceof Uint8Array ? new Response(body, { status }) : new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }) + }) + return { calls, files: new FreestyleDriver("test-key", "https://provider.test", "snap").files } + } + + it("lists, stats and reads through /v5/vms/{id}/fs (a resumed read sends Range)", async () => { + const p = provider([ + [200, { entries: [{ name: "a.txt", kind: "file" }, { name: "d", kind: "directory" }, { name: "l", kind: "symlink" }] }], + [200, { size: 3, isFile: true, isDirectory: false, isSymlink: false, permissions: "0640", owner: "cmux", group: "cmux", modified: "2026-10-09T00:00:00Z" }], + [206, new Uint8Array([2, 3])] + ]) + expect(await p.files.list("vm-1", "/srv/team")).toEqual([ + { name: "a.txt", kind: "file" }, + { name: "d", kind: "directory" }, + { name: "l", kind: "symlink" } + ]) + expect(await p.files.stat("vm-1", "/srv/team/a.txt")).toEqual({ kind: "file", size: 3, mode: 0o640, mtime: Date.parse("2026-10-09T00:00:00Z") / 1000, owner: "cmux", group: "cmux" }) + const body = await p.files.read("vm-1", "/srv/team/a.txt", 1, AbortSignal.timeout(5000)) + expect([...new Uint8Array(await new Response(body).arrayBuffer())]).toEqual([2, 3]) + expect(p.calls).toEqual([ + { path: "/v5/vms/vm-1/fs/dir?path=%2Fsrv%2Fteam", range: null }, + { path: "/v5/vms/vm-1/fs/stat?path=%2Fsrv%2Fteam%2Fa.txt", range: null }, + { path: "/v5/vms/vm-1/fs/read?path=%2Fsrv%2Fteam%2Fa.txt", range: "bytes=1-" } + ]) + }) + + it("reads the metadata a paused VM's disk answers: modified as epoch seconds or empty, numeric owners", async () => { + // Measured 2026-10-09: running {"permissions":"644","owner":"root","modified":"1791515201"}; paused {"owner":"0","group":"0","modified":""}. + const p = provider([ + [200, { size: 12, isFile: true, isDirectory: false, isSymlink: false, permissions: "644", owner: "root", group: "root", modified: "1791515201" }], + [200, { size: 300000, isFile: true, isDirectory: false, isSymlink: false, permissions: "644", owner: "0", group: "0", modified: "" }] + ]) + expect(await p.files.stat("vm-1", "/srv/team/a.txt")).toEqual({ kind: "file", size: 12, mode: 0o644, mtime: 1791515201, owner: "root", group: "root" }) + expect(await p.files.stat("vm-1", "/srv/team/d/b.bin")).toEqual({ kind: "file", size: 300000, mode: 0o644, mtime: 0, owner: "0", group: "0" }) + }) + + it("a 404 is a missing path when the VM exists, and vm_missing when it does not", async () => { + const path = provider([[404, { code: "NOT_FOUND" }], [200, { id: "vm-1", state: "paused" }]]) + expect(await path.files.list("vm-1", "/srv/team")).toBeNull() + vi.unstubAllGlobals() + const vm = provider([[404, { code: "NOT_FOUND" }], [404, { code: "NOT_FOUND" }]]) + await expect(vm.files.stat("vm-1", "/srv/team")).rejects.toMatchObject({ code: "team_vm.vm_missing" }) + }) +}) diff --git a/backend/apps/api/test/team-vm-retired-fence.test.ts b/backend/apps/api/test/team-vm-retired-fence.test.ts new file mode 100644 index 000000000000..8318f9f4114c --- /dev/null +++ b/backend/apps/api/test/team-vm-retired-fence.test.ts @@ -0,0 +1,148 @@ +import { env } from "cloudflare:workers" +import type { Principal } from "@cmux/ownership" +import { afterEach, describe, expect, it, vi } from "vitest" +import { DriverError, FakeDriver, FreestyleDriver } from "../src/team-vm-driver.ts" +import { api, inDO, mutate, setup, sshLine } from "./team-ssh-support.ts" +import { fireAlarm } from "./setup/alarm.ts" + +/** + * cx-009a: Freestyle resumes a paused VM on inbound traffic (measured 2026-10-09 on the dev + * account: public IPv6 with a rule, a VPC peer, a WireGuard tunnel peer and the SSH proxy each + * took a paused VM to running in under 1 s, and the connection succeeded). A VM that a rebuild + * retired after a member removal is paused, so without a fence anything the removed member left + * that can send it a packet would run it again. The fake provider models that wake. + */ +const ns = (env as unknown as { TEAM_VM_DO: DurableObjectNamespace }).TEAM_VM_DO +const vmStub = (team: string) => ns.get(ns.idFromName(team)) as any + +/** One inbound connection attempt to `vm`, as the provider handles it. */ +const inbound = (team: string, vm: string) => inDO(vmStub(team), async (instance) => new FakeDriver(instance.sqlStore).inbound(vm)) +const fakeState = (team: string, vm: string) => + inDO(vmStub(team), async (_i, st) => st.storage.sql.exec<{ state: string }>(`SELECT state FROM fake_vm WHERE id = ?`, vm).toArray()[0]?.state ?? null) + +let n = 0 +const rebuilt = async (opts: { failPause?: boolean } = {}) => { + const t = await setup(`stack-fence-${String(++n).padStart(4, "0")}${Date.now() % 1_000_000}`) + const admin = (p: Principal, op: string, params: unknown) => (t.stub as any).vmAdminOp(t.team, p, { op, params, idempotency_key: crypto.randomUUID() }) + const status = async () => (await api(t.token, "/v1/read", { op: "team_vm.status", params: {} })).value + const woke = await mutate(t.token, "team_vm.ensure_awake", { reason: "ssh" }) + expect(woke.ok, JSON.stringify(woke)).toBe(true) + const first = woke.value as { vm: string; epoch: number } + expect((await t.op(t.memberP, "team_vm.ssh_cert", { public_key: await sshLine("ed25519"), class: "agent" })).ok).toBe(true) + const removed = await inDO(t.stub, async (instance) => instance.submitSystem("team.member.remove", { user: t.member }, `remove:${t.member}:${crypto.randomUUID()}`)) + expect(removed.frames.find((f: any) => f.t === "reject")).toBeUndefined() + await fireAlarm(t.stub) + await fireAlarm(t.stub) + if (opts.failPause) await vmStub(t.team).fakeControl({ fail_pause: 1000 }) + const r = await admin(t.ownerP, "team_vm.rebuild", { epoch: first.epoch }) + expect(r.ok, JSON.stringify(r)).toBe(true) + return { ...t, first, status } +} + +describe("a retired team VM stays paused on inbound traffic (cx-009a)", { timeout: 60_000 }, () => { + it("inbound traffic to the paused retired VM does not run it again", async () => { + const t = await rebuilt() + expect((await t.status()).retired).toEqual([expect.objectContaining({ vm: t.first.vm, state: "paused" })]) + expect(await fakeState(t.team, t.first.vm)).toBe("paused") + await inbound(t.team, t.first.vm) + expect(await fakeState(t.team, t.first.vm)).toBe("paused") + // Later alarms (the retired VM's pause path included) leave it paused too. + await vmStub(t.team).fakeAlarm(10 * 60_000) + await inbound(t.team, t.first.vm) + expect(await fakeState(t.team, t.first.vm)).toBe("paused") + }) + + it("a retired VM paused before the fence existed gets fenced on the next alarm and then stays paused", async () => { + // The provider refuses the rebuild's retire, so neither the budget nor the new event key is spent. + const t = await rebuilt({ failPause: true }) + // What a pre-fence TeamVmDO left: the row paused (its old reducer set no flag), no budget spent at the provider. + await inDO(vmStub(t.team), async (instance) => { + const engine = instance.boundEngine + engine.state = { ...engine.currentState, retired: engine.currentState.retired.map((r: any) => ({ ...r, state: "paused" })) } + instance.sqlStore.exec(`UPDATE fake_vm SET state = 'paused' WHERE id = ?`, t.first.vm) + }) + await vmStub(t.team).fakeControl({ fail_pause: 0 }) + await vmStub(t.team).fakeAlarm(10 * 60_000) + const row = await inDO(vmStub(t.team), async (instance) => instance.boundEngine.currentState.retired[0]) + expect(row).toMatchObject({ vm: t.first.vm, state: "paused", fenced: true }) + await inbound(t.team, t.first.vm) + expect(await fakeState(t.team, t.first.vm)).toBe("paused") + }) + + it("the fence is only on the retired VM: the team's new VM still wakes on traffic after an idle pause", async () => { + const t = await rebuilt() + const s = await t.status() + expect(s.vm).not.toBe(t.first.vm) + await vmStub(t.team).fakeControl({ pause_all: true }) + await inbound(t.team, s.vm) + expect(await fakeState(t.team, s.vm)).toBe("running") + expect(await fakeState(t.team, t.first.vm)).toBe("paused") + }) +}) + +describe("FreestyleDriver.retireVm (cx-009a)", () => { + afterEach(() => vi.unstubAllGlobals()) + /** Answers each call from `answers` in order and records method, path and body. */ + const provider = (answers: Array<[number, unknown]>) => { + const calls: Array<{ method: string; path: string; body: unknown }> = [] + vi.stubGlobal("fetch", async (url: string, init: RequestInit) => { + calls.push({ method: init.method ?? "GET", path: new URL(url).pathname, body: init.body ? JSON.parse(String(init.body)) : undefined }) + const [status, body] = answers.shift() ?? [500, {}] + return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }) + }) + return { calls, driver: new FreestyleDriver("test-key", "https://provider.test", "snap") } + } + + it("spends the run budget before the pause, so no inbound packet can resume the VM between the two calls", async () => { + const p = provider([[200, { id: "vm-1", state: "paused" }], [200, { state: "paused", maxRunTotalSeconds: 1 }], [200, { state: "paused" }]]) + await p.driver.retireVm("vm-1") + expect(p.calls).toEqual([ + { method: "GET", path: "/v5/vms/vm-1", body: undefined }, + { method: "PATCH", path: "/v5/vms/vm-1", body: { maxRunTotalSeconds: 1 } }, + { method: "POST", path: "/v5/vms/vm-1/pause", body: undefined } + ]) + }) + + /** + * cx-lyvg, measured 2026-10-09 on the dev account: the provider's file API reads a paused VM's + * disk image, not the guest's page cache. A file written seconds before the pause read back as + * 0 bytes (stat size 0); after a `sync` in the guest it read back whole. So a running VM is + * synced before the fence, or team_vm.retired.export would miss the newest team files. + */ + it("a running VM is synced before its run budget is spent, so the retired disk holds every write", async () => { + const p = provider([[200, { id: "vm-1", state: "running" }], [200, { statusCode: 0, stdout: "" }], [200, {}], [200, { state: "paused" }]]) + await p.driver.retireVm("vm-1") + expect(p.calls).toEqual([ + { method: "GET", path: "/v5/vms/vm-1", body: undefined }, + { method: "POST", path: "/v5/vms/vm-1/exec-await", body: { command: "sync", timeoutMs: 15_000, linuxUser: "root" } }, + { method: "PATCH", path: "/v5/vms/vm-1", body: { maxRunTotalSeconds: 1 } }, + { method: "POST", path: "/v5/vms/vm-1/pause", body: undefined } + ]) + }) + + it("a failed sync never holds the fence back, and a paused VM is never woken to sync", async () => { + const failed = provider([[200, { id: "vm-1", state: "running" }], [500, { code: "INTERNAL" }], [200, {}], [200, { state: "paused" }]]) + await failed.driver.retireVm("vm-1") + expect(failed.calls.map((c) => `${c.method} ${c.path}`)).toEqual(["GET /v5/vms/vm-1", "POST /v5/vms/vm-1/exec-await", "PATCH /v5/vms/vm-1", "POST /v5/vms/vm-1/pause"]) + vi.unstubAllGlobals() + const unknown = provider([[500, {}], [200, {}], [200, { state: "paused" }]]) + await unknown.driver.retireVm("vm-1") + expect(unknown.calls.map((c) => c.method)).toEqual(["GET", "PATCH", "POST"]) + }) + + it("a VM the budget already paused counts as retired (the provider refuses a second pause with 409)", async () => { + const p = provider([[200, { id: "vm-1", state: "paused" }], [200, {}], [409, { code: "CONFLICT" }], [200, { id: "vm-1", state: "paused" }]]) + await p.driver.retireVm("vm-1") + expect(p.calls.map((c) => c.method)).toEqual(["GET", "PATCH", "POST", "GET"]) + }) + + it("a VM that is gone answers vm_missing; a refused budget is an error and nothing is paused", async () => { + const gone = provider([[404, { code: "NOT_FOUND" }]]) + await expect(gone.driver.retireVm("vm-1")).rejects.toMatchObject({ code: "team_vm.vm_missing" }) + vi.unstubAllGlobals() + const refused = provider([[200, { id: "vm-1", state: "paused" }], [500, { code: "INTERNAL" }]]) + const err = await refused.driver.retireVm("vm-1").catch((e) => e) + expect(err).toBeInstanceOf(DriverError) + expect(refused.calls.map((c) => c.method)).toEqual(["GET", "PATCH"]) + }) +}) diff --git a/backend/apps/dashboard/src/lib/server.ts b/backend/apps/dashboard/src/lib/server.ts index 132e827d49b2..ff4ffb0221b3 100644 --- a/backend/apps/dashboard/src/lib/server.ts +++ b/backend/apps/dashboard/src/lib/server.ts @@ -146,6 +146,20 @@ export const mutate = createServerFn({ method: "POST" }) return post("/v1/ops", { op: data.op, params: data.params, idempotency_key: data.idempotency_key, origin: "user" }) }) +/** + * team_vm.retired.export (cx-lyvg): sends the op with the session, then answers the absolute + * download URL on the API origin (single use, 5 minutes) for the browser to open; null on failure. + */ +export const exportTeamFiles = createServerFn({ method: "POST" }) + .validator((d: { vm: string; idempotency_key: string }) => d) + .handler(async ({ data }) => { + requireSameOrigin() + const r = await post("/v1/ops", { op: "team_vm.retired.export", params: { vm: data.vm }, idempotency_key: data.idempotency_key, origin: "user" }) + const value = r.body.ok && r.body.value && typeof r.body.value === "object" && !Array.isArray(r.body.value) ? r.body.value : null + const path = value && typeof value.path === "string" && value.path.startsWith("/v1/team-vm/export/") ? value.path : null + return { ...r, url: path ? `${apiUrl()}${path}` : null } + }) + export const read = createServerFn({ method: "POST" }) .validator((d: { op: string; params: Record }) => d) .handler(async ({ data }) => { diff --git a/backend/apps/dashboard/src/lib/team-vm-card.tsx b/backend/apps/dashboard/src/lib/team-vm-card.tsx index 38e059e0b7dd..958439ae79ed 100644 --- a/backend/apps/dashboard/src/lib/team-vm-card.tsx +++ b/backend/apps/dashboard/src/lib/team-vm-card.tsx @@ -13,6 +13,8 @@ export interface TeamVmCardProps { readonly onCancel: () => void readonly onFilesCopied: (value: boolean) => void readonly onConfirm: () => void + /** Export a paused retired VM's /srv/team (team_vm.retired.export) and start the browser download. */ + readonly onDownload: (vm: string) => void } const pill = (color: string): CSSProperties => ({ display: "inline-block", padding: "0 8px", borderRadius: 999, border: `1px solid ${color}`, color, fontSize: 12, lineHeight: "20px", whiteSpace: "nowrap" }) @@ -25,7 +27,7 @@ const accentButton: CSSProperties = { borderColor: "var(--accent)", color: "var( const dim = (disabled: boolean, style?: CSSProperties): CSSProperties | undefined => (disabled ? { ...style, opacity: 0.45, cursor: "not-allowed" } : style) /** The team VM: state, taint badge (every member), owner/admin actions and the retired VMs. */ -export function TeamVmCard({ view, role, locale, state, onOpen, onCancel, onFilesCopied, onConfirm }: TeamVmCardProps) { +export function TeamVmCard({ view, role, locale, state, onOpen, onCancel, onFilesCopied, onConfirm, onDownload }: TeamVmCardProps) { const t = (key: TeamVmTextKey, vars?: Record) => teamVmText(locale, key, vars) const badge = taintBadge(view) const manage = canManageTeamVm(role) @@ -77,15 +79,47 @@ export function TeamVmCard({ view, role, locale, state, onOpen, onCancel, onFile {full ? {t("rebuild.full")} : null} ) : null} - {state.dialog && state.dialog.kind !== "delete" ? : null} - {view.retired.length > 0 ? : null} + {state.dialog && state.dialog.kind !== "delete" ? : null} + {view.retired.length > 0 ? : null} ) } -type ConfirmProps = Pick +type ConfirmProps = Pick + +/** The Download button of one paused retired VM; off while any download is being prepared or an op runs. */ +function DownloadButton({ vm, locale, state, onDownload }: { readonly vm: string } & Pick) { + const off = state.busy || state.download?.phase === "busy" + return ( + + ) +} + +/** What the last download of this VM did: preparing, started (with the skipped count), or the error. */ +function DownloadStatus({ vm, locale, state }: { readonly vm: string } & Pick) { + const d = state.download + if (!d || d.vm !== vm) return null + const t = (key: TeamVmTextKey, vars?: Record) => teamVmText(locale, key, vars) + if (d.phase === "busy") return

{t("download.busy", { vm })}

+ if (d.phase === "failed" && d.error) { + return ( +

+ {t("download.failed", { code: d.error.code, text: teamVmErrorText(locale, d.error.code) })} +

+ ) + } + return ( +

+ {t("download.started")} + {d.skipped > 0 ? ` ${t("download.skipped", { count: String(d.skipped) })}` : null} +

+ ) +} function Retired({ view, manage, locale, state, onOpen, ...confirm }: ConfirmProps & Pick & { readonly manage: boolean }) { + const onDownload = confirm.onDownload const t = (key: TeamVmTextKey, vars?: Record) => teamVmText(locale, key, vars) const deleting = state.dialog?.kind === "delete" ? state.dialog.vm : null return ( @@ -117,10 +151,14 @@ function Retired({ view, manage, locale, state, onOpen, ...confirm }: ConfirmPro {t("retired.by", { who: r.by, when: absoluteTime(locale, r.at) })} {manage && r.state === "paused" ? ( - + + + + ) : null} + {manage && deleting !== r.vm ? : null} ))} @@ -132,7 +170,7 @@ function Retired({ view, manage, locale, state, onOpen, ...confirm }: ConfirmPro } /** The confirm panel of the open dialog: what the op does, and for Delete the required files-copied checkbox. */ -function Confirm({ view, locale, state, onCancel, onFilesCopied, onConfirm }: ConfirmProps) { +function Confirm({ view, locale, state, onCancel, onFilesCopied, onConfirm, onDownload }: ConfirmProps) { const t = (key: TeamVmTextKey, vars?: Record) => teamVmText(locale, key, vars) const dialog = state.dialog if (!dialog) return null @@ -151,6 +189,13 @@ function Confirm({ view, locale, state, onCancel, onFilesCopied, onConfirm }: Co ) : (

{t(`confirm.${dialog.kind}.body`)}

)} + {dialog.kind === "delete" ? ( +
+

{t("confirm.download_first")}

+ + +
+ ) : null} {dialog.kind === "delete" ? (